blob: 0bcc9986776c4fff6d17e4a0ae03a30d2c1804d6 [file] [log] [blame]
Jooyung Han23d1e622023-04-04 18:03:07 +09001#!/usr/bin/env python3
2#
3# Copyright 2023 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16""" A tool to test APEX file_contexts
17
18Usage:
19 $ deapexer list -Z foo.apex > /tmp/fc
20 $ apex_sepolicy_tests -f /tmp/fc
21"""
22
23
24import argparse
25import os
26import pathlib
27import pkgutil
28import re
29import sys
30import tempfile
31from dataclasses import dataclass
32from typing import List
33
34import policy
35
36
37SHARED_LIB_EXTENSION = '.dylib' if sys.platform == 'darwin' else '.so'
38LIBSEPOLWRAP = "libsepolwrap" + SHARED_LIB_EXTENSION
39
40
41@dataclass
42class Is:
43 """Exact matcher for a path."""
44 path: str
45
46
47@dataclass
48class Glob:
49 """Path matcher with pathlib.PurePath.match"""
50 pattern: str
51
52
53@dataclass
54class Regex:
55 """Path matcher with re.match"""
56 pattern: str
57
58
59Matcher = Is | Glob | Regex
60
61@dataclass
62class AllowRead:
63 """Rule checking if scontext can read the entity"""
64 tclass: str
65 scontext: set[str]
66
67
68Rule = AllowRead
69
70
71def match_path(path: str, matcher: Matcher) -> bool:
72 """True if path matches with the given matcher"""
73 match matcher:
74 case Is(target):
75 return path == target
76 case Glob(pattern):
77 return pathlib.PurePath(path).match(pattern)
78 case Regex(pattern):
79 return re.match(pattern, path)
80
81
82def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
83 """Returns error message if scontext can't read the target"""
84 match rule:
85 case AllowRead(tclass, scontext):
86 te_rules = list(pol.QueryTERule(scontext=scontext,
87 tcontext={tcontext},
88 tclass={tclass},
89 perms={'read'}))
90 if len(te_rules) > 0:
91 return [] # no errors
92
93 return [f"Error: {path}: {scontext} can't read. (tcontext={tcontext})"]
94
95
96rules = [
97 # permissions
98 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
99 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
100 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
101 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
102 # vintf fragments
103 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
104 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
105 # ./ and apex_manifest.pb
106 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
107 (Is('./'), AllowRead('dir', {'linkerconfig', 'apexd'})),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900108 # linker.config.pb
109 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900110]
111
112
113def check_line(pol: policy.Policy, line: str) -> List[str]:
114 """Parses a file_contexts line and runs checks"""
115 # skip empty/comment line
116 line = line.strip()
117 if line == '' or line[0] == '#':
118 return []
119
120 # parse
121 split = line.split()
122 if len(split) != 2:
123 return [f"Error: invalid file_contexts: {line}"]
124 path, context = split[0], split[1]
125 if len(context.split(':')) != 4:
126 return [f"Error: invalid file_contexts: {line}"]
127 tcontext = context.split(':')[2]
128
129 # check rules
130 errors = []
131 for matcher, rule in rules:
132 if match_path(path, matcher):
133 errors.extend(check_rule(pol, path, tcontext, rule))
134 return errors
135
136
137def extract_data(name, temp_dir):
138 out_path = os.path.join(temp_dir, name)
139 with open(out_path, 'wb') as f:
140 blob = pkgutil.get_data('apex_sepolicy_tests', name)
141 if not blob:
142 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
143 f.write(blob)
144 return out_path
145
146
147def do_main(work_dir):
148 """Do testing"""
149 parser = argparse.ArgumentParser()
150 parser.add_argument('-f', '--file_contexts', help='output of "deapexer list -Z"')
151 args = parser.parse_args()
152
153 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
154 policy_path = extract_data('precompiled_sepolicy', work_dir)
155 pol = policy.Policy(policy_path, None, lib_path)
156
157 errors = []
158 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
159 for line in file_contexts:
160 errors.extend(check_line(pol, line))
161 if len(errors) > 0:
162 sys.exit('\n'.join(errors))
163
164
165if __name__ == '__main__':
166 with tempfile.TemporaryDirectory() as temp_dir:
167 do_main(temp_dir)