blob: 26082cbcf7ac0f64610b781e165517cb2b580acd [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
Jooyung Hanc945a102024-02-07 15:41:25 +090059@dataclass
60class BinaryFile:
61 pass
62
63
64Matcher = Is | Glob | Regex | BinaryFile
65
66
67# predicate functions for Func matcher
68
Jooyung Han23d1e622023-04-04 18:03:07 +090069
70@dataclass
Jooyung Hanb9517902023-11-14 13:50:14 +090071class AllowPerm:
72 """Rule checking if scontext has 'perm' to the entity"""
Jooyung Han23d1e622023-04-04 18:03:07 +090073 tclass: str
74 scontext: set[str]
Jooyung Hanb9517902023-11-14 13:50:14 +090075 perm: str
Jooyung Han23d1e622023-04-04 18:03:07 +090076
77
Jooyung Han92bfb372023-09-08 14:28:40 +090078@dataclass
79class ResolveType:
80 """Rule checking if type can be resolved"""
81 pass
82
83
Jooyung Hanc945a102024-02-07 15:41:25 +090084@dataclass
85class NotAnyOf:
86 """Rule checking if entity is not labelled as any of the given labels"""
87 labels: set[str]
88
89
90Rule = AllowPerm | ResolveType | NotAnyOf
Jooyung Hanb9517902023-11-14 13:50:14 +090091
92
93# Helper for 'read'
94def AllowRead(tclass, scontext):
95 return AllowPerm(tclass, scontext, 'read')
Jooyung Han23d1e622023-04-04 18:03:07 +090096
97
98def match_path(path: str, matcher: Matcher) -> bool:
99 """True if path matches with the given matcher"""
100 match matcher:
101 case Is(target):
102 return path == target
103 case Glob(pattern):
104 return pathlib.PurePath(path).match(pattern)
105 case Regex(pattern):
106 return re.match(pattern, path)
Jooyung Hanc945a102024-02-07 15:41:25 +0900107 case BinaryFile:
108 return path.startswith('./bin/') and not path.endswith('/')
Jooyung Han23d1e622023-04-04 18:03:07 +0900109
110
111def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
112 """Returns error message if scontext can't read the target"""
Jooyung Han3e592f22023-06-05 10:47:20 +0900113 errors = []
Jooyung Han23d1e622023-04-04 18:03:07 +0900114 match rule:
Jooyung Hanb9517902023-11-14 13:50:14 +0900115 case AllowPerm(tclass, scontext, perm):
Jooyung Han61b46b62023-05-31 17:41:28 +0900116 # Test every source in scontext(set)
117 for s in scontext:
118 te_rules = list(pol.QueryTERule(scontext={s},
119 tcontext={tcontext},
120 tclass={tclass},
Jooyung Hanb9517902023-11-14 13:50:14 +0900121 perms={perm}))
Jooyung Han61b46b62023-05-31 17:41:28 +0900122 if len(te_rules) > 0:
Jooyung Han3e592f22023-06-05 10:47:20 +0900123 continue # no errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900124
Jooyung Hanb9517902023-11-14 13:50:14 +0900125 errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})")
Jooyung Han92bfb372023-09-08 14:28:40 +0900126 case ResolveType():
127 if tcontext not in pol.GetAllTypes(False):
128 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown")
Jooyung Hanc945a102024-02-07 15:41:25 +0900129 case NotAnyOf(labels):
130 if tcontext in labels:
131 errors.append(f"Error: {path}: can't be labelled as '{tcontext}'")
Jooyung Han3e592f22023-06-05 10:47:20 +0900132 return errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900133
134
Jooyung Han92bfb372023-09-08 14:28:40 +0900135target_specific_rules = [
136 (Glob('*'), ResolveType()),
137]
138
139
140generic_rules = [
Jooyung Hanc945a102024-02-07 15:41:25 +0900141 # binaries should be executable
142 (BinaryFile, NotAnyOf({'vendor_file'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900143 # permissions
144 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
145 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
146 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
147 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
148 # vintf fragments
149 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
150 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
151 # ./ and apex_manifest.pb
152 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
Jooyung Hanb9517902023-11-14 13:50:14 +0900153 (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900154 # linker.config.pb
155 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900156]
157
158
Jooyung Han92bfb372023-09-08 14:28:40 +0900159all_rules = target_specific_rules + generic_rules
160
161
162def check_line(pol: policy.Policy, line: str, rules) -> List[str]:
Jooyung Han23d1e622023-04-04 18:03:07 +0900163 """Parses a file_contexts line and runs checks"""
164 # skip empty/comment line
165 line = line.strip()
166 if line == '' or line[0] == '#':
167 return []
168
169 # parse
170 split = line.split()
171 if len(split) != 2:
172 return [f"Error: invalid file_contexts: {line}"]
173 path, context = split[0], split[1]
174 if len(context.split(':')) != 4:
175 return [f"Error: invalid file_contexts: {line}"]
176 tcontext = context.split(':')[2]
177
178 # check rules
179 errors = []
180 for matcher, rule in rules:
181 if match_path(path, matcher):
182 errors.extend(check_rule(pol, path, tcontext, rule))
183 return errors
184
185
186def extract_data(name, temp_dir):
187 out_path = os.path.join(temp_dir, name)
188 with open(out_path, 'wb') as f:
189 blob = pkgutil.get_data('apex_sepolicy_tests', name)
190 if not blob:
191 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
192 f.write(blob)
193 return out_path
194
195
196def do_main(work_dir):
197 """Do testing"""
198 parser = argparse.ArgumentParser()
Jooyung Han92bfb372023-09-08 14:28:40 +0900199 parser.add_argument('--all', action='store_true', help='tests ALL aspects')
Jooyung Han23d1e622023-04-04 18:03:07 +0900200 parser.add_argument('-f', '--file_contexts', help='output of "deapexer list -Z"')
201 args = parser.parse_args()
202
203 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
204 policy_path = extract_data('precompiled_sepolicy', work_dir)
205 pol = policy.Policy(policy_path, None, lib_path)
206
Jooyung Han92bfb372023-09-08 14:28:40 +0900207 if args.all:
208 rules = all_rules
209 else:
210 rules = generic_rules
211
Jooyung Han23d1e622023-04-04 18:03:07 +0900212 errors = []
213 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
214 for line in file_contexts:
Jooyung Han92bfb372023-09-08 14:28:40 +0900215 errors.extend(check_line(pol, line, rules))
Jooyung Han23d1e622023-04-04 18:03:07 +0900216 if len(errors) > 0:
217 sys.exit('\n'.join(errors))
218
219
220if __name__ == '__main__':
221 with tempfile.TemporaryDirectory() as temp_dir:
222 do_main(temp_dir)