blob: d8c5c2b07a5526ffe692606bddc2215076a649a6 [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 Han23d1e622023-04-04 18:03:07 +0900122
123
124def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
125 """Returns error message if scontext can't read the target"""
Jooyung Han3e592f22023-06-05 10:47:20 +0900126 errors = []
Jooyung Han23d1e622023-04-04 18:03:07 +0900127 match rule:
Jooyung Hanb9517902023-11-14 13:50:14 +0900128 case AllowPerm(tclass, scontext, perm):
Jooyung Han61b46b62023-05-31 17:41:28 +0900129 # Test every source in scontext(set)
130 for s in scontext:
131 te_rules = list(pol.QueryTERule(scontext={s},
132 tcontext={tcontext},
133 tclass={tclass},
Jooyung Hanb9517902023-11-14 13:50:14 +0900134 perms={perm}))
Jooyung Han61b46b62023-05-31 17:41:28 +0900135 if len(te_rules) > 0:
Jooyung Han3e592f22023-06-05 10:47:20 +0900136 continue # no errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900137
Jooyung Hanb9517902023-11-14 13:50:14 +0900138 errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})")
Jooyung Han92bfb372023-09-08 14:28:40 +0900139 case ResolveType():
140 if tcontext not in pol.GetAllTypes(False):
141 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown")
Jooyung Hanc945a102024-02-07 15:41:25 +0900142 case NotAnyOf(labels):
143 if tcontext in labels:
144 errors.append(f"Error: {path}: can't be labelled as '{tcontext}'")
Jooyung Han20b63522025-01-03 17:45:25 +0900145 case HasAttr(attr):
146 if tcontext not in pol.QueryTypeAttribute(attr, True):
147 errors.append(f"Error: {path}: tcontext({tcontext}) must be associated with {attr}")
Jooyung Han3e592f22023-06-05 10:47:20 +0900148 return errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900149
150
Jooyung Han92bfb372023-09-08 14:28:40 +0900151target_specific_rules = [
152 (Glob('*'), ResolveType()),
153]
154
155
156generic_rules = [
Jooyung Hanc945a102024-02-07 15:41:25 +0900157 # binaries should be executable
Jooyung Han20b63522025-01-03 17:45:25 +0900158 (BinaryFile(), NotAnyOf({'vendor_file'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900159 # permissions
160 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
161 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
162 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
163 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
164 # vintf fragments
165 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
166 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
167 # ./ and apex_manifest.pb
168 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
Jooyung Hanb9517902023-11-14 13:50:14 +0900169 (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900170 # linker.config.pb
171 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900172]
173
174
Jooyung Han92bfb372023-09-08 14:28:40 +0900175all_rules = target_specific_rules + generic_rules
176
177
Jooyung Han20b63522025-01-03 17:45:25 +0900178def base_attr_for(partition):
179 if partition in ['system', 'system_ext', 'product']:
180 return 'system_file_type'
181 elif partition in ['vendor', 'odm']:
182 return 'vendor_file_type'
183 else:
184 sys.exit(f"Error: invalid partition: {partition}\n")
185
186
187def system_vendor_rule(partition):
188 exceptions = [
189 "./etc/linkerconfig.pb"
190 ]
191 def pred(path):
192 return path not in exceptions
193
194 return pred, HasAttr(base_attr_for(partition))
195
196
Jooyung Han92bfb372023-09-08 14:28:40 +0900197def check_line(pol: policy.Policy, line: str, rules) -> List[str]:
Jooyung Han23d1e622023-04-04 18:03:07 +0900198 """Parses a file_contexts line and runs checks"""
199 # skip empty/comment line
200 line = line.strip()
201 if line == '' or line[0] == '#':
202 return []
203
204 # parse
205 split = line.split()
206 if len(split) != 2:
207 return [f"Error: invalid file_contexts: {line}"]
208 path, context = split[0], split[1]
209 if len(context.split(':')) != 4:
210 return [f"Error: invalid file_contexts: {line}"]
211 tcontext = context.split(':')[2]
212
213 # check rules
214 errors = []
215 for matcher, rule in rules:
216 if match_path(path, matcher):
217 errors.extend(check_rule(pol, path, tcontext, rule))
218 return errors
219
220
221def extract_data(name, temp_dir):
222 out_path = os.path.join(temp_dir, name)
223 with open(out_path, 'wb') as f:
224 blob = pkgutil.get_data('apex_sepolicy_tests', name)
225 if not blob:
226 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
227 f.write(blob)
228 return out_path
229
230
231def do_main(work_dir):
232 """Do testing"""
233 parser = argparse.ArgumentParser()
Jooyung Han92bfb372023-09-08 14:28:40 +0900234 parser.add_argument('--all', action='store_true', help='tests ALL aspects')
Jooyung Han20b63522025-01-03 17:45:25 +0900235 parser.add_argument('-f', '--file_contexts', required=True, help='output of "deapexer list -Z"')
236 parser.add_argument('-p', '--partition', help='partition to check Treble violations')
Jooyung Han23d1e622023-04-04 18:03:07 +0900237 args = parser.parse_args()
238
239 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
240 policy_path = extract_data('precompiled_sepolicy', work_dir)
241 pol = policy.Policy(policy_path, None, lib_path)
242
Jooyung Han92bfb372023-09-08 14:28:40 +0900243 if args.all:
244 rules = all_rules
245 else:
246 rules = generic_rules
247
Jooyung Han20b63522025-01-03 17:45:25 +0900248 if args.partition:
249 rules.append(system_vendor_rule(args.partition))
250
Jooyung Han23d1e622023-04-04 18:03:07 +0900251 errors = []
252 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
253 for line in file_contexts:
Jooyung Han92bfb372023-09-08 14:28:40 +0900254 errors.extend(check_line(pol, line, rules))
Jooyung Han23d1e622023-04-04 18:03:07 +0900255 if len(errors) > 0:
256 sys.exit('\n'.join(errors))
257
258
259if __name__ == '__main__':
260 with tempfile.TemporaryDirectory() as temp_dir:
261 do_main(temp_dir)