blob: b1d02a690a37b43930794aff025a244e52a336d9 [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
Jooyung Han20b63522025-01-03 17:45:25 +090032from typing import Callable, List
Jooyung Han23d1e622023-04-04 18:03:07 +090033
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
Jooyung Hanc945a102024-02-07 15:41:25 +090059@dataclass
60class BinaryFile:
61 pass
62
63
Jooyung Han20b63522025-01-03 17:45:25 +090064@dataclass
65class MatchPred:
66 pred: Callable[[str], bool]
67
68
69Matcher = Is | Glob | Regex | BinaryFile | MatchPred
Jooyung Hanc945a102024-02-07 15:41:25 +090070
71
72# predicate functions for Func matcher
73
Jooyung Han23d1e622023-04-04 18:03:07 +090074
75@dataclass
Jooyung Hanb9517902023-11-14 13:50:14 +090076class AllowPerm:
77 """Rule checking if scontext has 'perm' to the entity"""
Jooyung Han23d1e622023-04-04 18:03:07 +090078 tclass: str
79 scontext: set[str]
Jooyung Hanb9517902023-11-14 13:50:14 +090080 perm: str
Jooyung Han23d1e622023-04-04 18:03:07 +090081
82
Jooyung Han92bfb372023-09-08 14:28:40 +090083@dataclass
84class ResolveType:
85 """Rule checking if type can be resolved"""
86 pass
87
88
Jooyung Hanc945a102024-02-07 15:41:25 +090089@dataclass
90class NotAnyOf:
91 """Rule checking if entity is not labelled as any of the given labels"""
92 labels: set[str]
93
94
Jooyung Han20b63522025-01-03 17:45:25 +090095@dataclass
96class HasAttr:
97 """Rule checking if the context has the specified attribute"""
98 attr: str
99
100
101Rule = AllowPerm | ResolveType | NotAnyOf | HasAttr
Jooyung Hanb9517902023-11-14 13:50:14 +0900102
103
104# Helper for 'read'
105def AllowRead(tclass, scontext):
106 return AllowPerm(tclass, scontext, 'read')
Jooyung Han23d1e622023-04-04 18:03:07 +0900107
108
109def match_path(path: str, matcher: Matcher) -> bool:
110 """True if path matches with the given matcher"""
111 match matcher:
112 case Is(target):
113 return path == target
114 case Glob(pattern):
115 return pathlib.PurePath(path).match(pattern)
116 case Regex(pattern):
117 return re.match(pattern, path)
Jooyung Han20b63522025-01-03 17:45:25 +0900118 case BinaryFile():
Jooyung Hanc945a102024-02-07 15:41:25 +0900119 return path.startswith('./bin/') and not path.endswith('/')
Jooyung Han20b63522025-01-03 17:45:25 +0900120 case MatchPred(pred):
121 return pred(path)
Jooyung Han4b966cb2025-02-06 23:23:15 -0800122 case _:
123 sys.exit(f'unknown matcher: {matcher}')
Jooyung Han23d1e622023-04-04 18:03:07 +0900124
125
126def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
127 """Returns error message if scontext can't read the target"""
Jooyung Han3e592f22023-06-05 10:47:20 +0900128 errors = []
Jooyung Han23d1e622023-04-04 18:03:07 +0900129 match rule:
Jooyung Hanb9517902023-11-14 13:50:14 +0900130 case AllowPerm(tclass, scontext, perm):
Jooyung Han61b46b62023-05-31 17:41:28 +0900131 # Test every source in scontext(set)
132 for s in scontext:
133 te_rules = list(pol.QueryTERule(scontext={s},
134 tcontext={tcontext},
135 tclass={tclass},
Jooyung Hanb9517902023-11-14 13:50:14 +0900136 perms={perm}))
Jooyung Han61b46b62023-05-31 17:41:28 +0900137 if len(te_rules) > 0:
Jooyung Han3e592f22023-06-05 10:47:20 +0900138 continue # no errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900139
Jooyung Hanb9517902023-11-14 13:50:14 +0900140 errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})")
Jooyung Han92bfb372023-09-08 14:28:40 +0900141 case ResolveType():
142 if tcontext not in pol.GetAllTypes(False):
143 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown")
Jooyung Hanc945a102024-02-07 15:41:25 +0900144 case NotAnyOf(labels):
145 if tcontext in labels:
146 errors.append(f"Error: {path}: can't be labelled as '{tcontext}'")
Jooyung Han20b63522025-01-03 17:45:25 +0900147 case HasAttr(attr):
148 if tcontext not in pol.QueryTypeAttribute(attr, True):
149 errors.append(f"Error: {path}: tcontext({tcontext}) must be associated with {attr}")
Jooyung Han3e592f22023-06-05 10:47:20 +0900150 return errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900151
152
Jooyung Han92bfb372023-09-08 14:28:40 +0900153target_specific_rules = [
154 (Glob('*'), ResolveType()),
155]
156
157
158generic_rules = [
Jooyung Hanc945a102024-02-07 15:41:25 +0900159 # binaries should be executable
Jooyung Han20b63522025-01-03 17:45:25 +0900160 (BinaryFile(), NotAnyOf({'vendor_file'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900161 # permissions
162 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
163 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
164 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
165 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
166 # vintf fragments
167 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
168 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
169 # ./ and apex_manifest.pb
170 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
Jooyung Hanb9517902023-11-14 13:50:14 +0900171 (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900172 # linker.config.pb
173 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900174]
175
176
Jooyung Han92bfb372023-09-08 14:28:40 +0900177all_rules = target_specific_rules + generic_rules
178
179
Jooyung Han20b63522025-01-03 17:45:25 +0900180def base_attr_for(partition):
181 if partition in ['system', 'system_ext', 'product']:
182 return 'system_file_type'
183 elif partition in ['vendor', 'odm']:
184 return 'vendor_file_type'
185 else:
186 sys.exit(f"Error: invalid partition: {partition}\n")
187
188
189def system_vendor_rule(partition):
190 exceptions = [
Jooyung Han4b966cb2025-02-06 23:23:15 -0800191 "./etc/linker.config.pb"
Jooyung Han20b63522025-01-03 17:45:25 +0900192 ]
193 def pred(path):
194 return path not in exceptions
195
Jooyung Han4b966cb2025-02-06 23:23:15 -0800196 return MatchPred(pred), HasAttr(base_attr_for(partition))
Jooyung Han20b63522025-01-03 17:45:25 +0900197
198
Jooyung Han4b966cb2025-02-06 23:23:15 -0800199def check_line(pol: policy.Policy, line: str, rules, ignore_unknown_context=False) -> List[str]:
Jooyung Han23d1e622023-04-04 18:03:07 +0900200 """Parses a file_contexts line and runs checks"""
201 # skip empty/comment line
202 line = line.strip()
203 if line == '' or line[0] == '#':
204 return []
205
206 # parse
207 split = line.split()
208 if len(split) != 2:
209 return [f"Error: invalid file_contexts: {line}"]
210 path, context = split[0], split[1]
211 if len(context.split(':')) != 4:
212 return [f"Error: invalid file_contexts: {line}"]
213 tcontext = context.split(':')[2]
214
Jooyung Han4b966cb2025-02-06 23:23:15 -0800215 if ignore_unknown_context and tcontext not in pol.GetAllTypes(False):
216 return []
217
Jooyung Han23d1e622023-04-04 18:03:07 +0900218 # check rules
219 errors = []
220 for matcher, rule in rules:
221 if match_path(path, matcher):
222 errors.extend(check_rule(pol, path, tcontext, rule))
223 return errors
224
225
226def extract_data(name, temp_dir):
227 out_path = os.path.join(temp_dir, name)
228 with open(out_path, 'wb') as f:
229 blob = pkgutil.get_data('apex_sepolicy_tests', name)
230 if not blob:
231 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
232 f.write(blob)
233 return out_path
234
235
236def do_main(work_dir):
237 """Do testing"""
238 parser = argparse.ArgumentParser()
Jooyung Han92bfb372023-09-08 14:28:40 +0900239 parser.add_argument('--all', action='store_true', help='tests ALL aspects')
Jooyung Han20b63522025-01-03 17:45:25 +0900240 parser.add_argument('-f', '--file_contexts', required=True, help='output of "deapexer list -Z"')
241 parser.add_argument('-p', '--partition', help='partition to check Treble violations')
Jooyung Han23d1e622023-04-04 18:03:07 +0900242 args = parser.parse_args()
243
244 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
245 policy_path = extract_data('precompiled_sepolicy', work_dir)
246 pol = policy.Policy(policy_path, None, lib_path)
247
Jooyung Han4b966cb2025-02-06 23:23:15 -0800248 # ignore unknown contexts unless --all is specified
249 ignore_unknown_context = True
Jooyung Han92bfb372023-09-08 14:28:40 +0900250 if args.all:
Jooyung Han4b966cb2025-02-06 23:23:15 -0800251 ignore_unknown_context = False
Jooyung Han92bfb372023-09-08 14:28:40 +0900252
Jooyung Han4b966cb2025-02-06 23:23:15 -0800253 rules = all_rules
Jooyung Han20b63522025-01-03 17:45:25 +0900254 if args.partition:
255 rules.append(system_vendor_rule(args.partition))
256
Jooyung Han23d1e622023-04-04 18:03:07 +0900257 errors = []
258 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
259 for line in file_contexts:
Jooyung Han4b966cb2025-02-06 23:23:15 -0800260 errors.extend(check_line(pol, line, rules, ignore_unknown_context))
Jooyung Han23d1e622023-04-04 18:03:07 +0900261 if len(errors) > 0:
262 sys.exit('\n'.join(errors))
263
264
265if __name__ == '__main__':
266 with tempfile.TemporaryDirectory() as temp_dir:
267 do_main(temp_dir)