blob: ab01745f83eb94b93386d0246b5190550a958a3a [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
Jooyung Hanb9517902023-11-14 13:50:14 +090062class AllowPerm:
63 """Rule checking if scontext has 'perm' to the entity"""
Jooyung Han23d1e622023-04-04 18:03:07 +090064 tclass: str
65 scontext: set[str]
Jooyung Hanb9517902023-11-14 13:50:14 +090066 perm: str
Jooyung Han23d1e622023-04-04 18:03:07 +090067
68
Jooyung Han92bfb372023-09-08 14:28:40 +090069@dataclass
70class ResolveType:
71 """Rule checking if type can be resolved"""
72 pass
73
74
Jooyung Hanb9517902023-11-14 13:50:14 +090075Rule = AllowPerm | ResolveType
76
77
78# Helper for 'read'
79def AllowRead(tclass, scontext):
80 return AllowPerm(tclass, scontext, 'read')
Jooyung Han23d1e622023-04-04 18:03:07 +090081
82
83def match_path(path: str, matcher: Matcher) -> bool:
84 """True if path matches with the given matcher"""
85 match matcher:
86 case Is(target):
87 return path == target
88 case Glob(pattern):
89 return pathlib.PurePath(path).match(pattern)
90 case Regex(pattern):
91 return re.match(pattern, path)
92
93
94def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
95 """Returns error message if scontext can't read the target"""
Jooyung Han3e592f22023-06-05 10:47:20 +090096 errors = []
Jooyung Han23d1e622023-04-04 18:03:07 +090097 match rule:
Jooyung Hanb9517902023-11-14 13:50:14 +090098 case AllowPerm(tclass, scontext, perm):
Jooyung Han61b46b62023-05-31 17:41:28 +090099 # Test every source in scontext(set)
100 for s in scontext:
101 te_rules = list(pol.QueryTERule(scontext={s},
102 tcontext={tcontext},
103 tclass={tclass},
Jooyung Hanb9517902023-11-14 13:50:14 +0900104 perms={perm}))
Jooyung Han61b46b62023-05-31 17:41:28 +0900105 if len(te_rules) > 0:
Jooyung Han3e592f22023-06-05 10:47:20 +0900106 continue # no errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900107
Jooyung Hanb9517902023-11-14 13:50:14 +0900108 errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})")
Jooyung Han92bfb372023-09-08 14:28:40 +0900109 case ResolveType():
110 if tcontext not in pol.GetAllTypes(False):
111 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown")
Jooyung Han3e592f22023-06-05 10:47:20 +0900112 return errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900113
114
Jooyung Han92bfb372023-09-08 14:28:40 +0900115target_specific_rules = [
116 (Glob('*'), ResolveType()),
117]
118
119
120generic_rules = [
Jooyung Han23d1e622023-04-04 18:03:07 +0900121 # permissions
122 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
123 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
124 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
125 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
126 # vintf fragments
127 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
128 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
129 # ./ and apex_manifest.pb
130 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
Jooyung Hanb9517902023-11-14 13:50:14 +0900131 (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900132 # linker.config.pb
133 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900134]
135
136
Jooyung Han92bfb372023-09-08 14:28:40 +0900137all_rules = target_specific_rules + generic_rules
138
139
140def check_line(pol: policy.Policy, line: str, rules) -> List[str]:
Jooyung Han23d1e622023-04-04 18:03:07 +0900141 """Parses a file_contexts line and runs checks"""
142 # skip empty/comment line
143 line = line.strip()
144 if line == '' or line[0] == '#':
145 return []
146
147 # parse
148 split = line.split()
149 if len(split) != 2:
150 return [f"Error: invalid file_contexts: {line}"]
151 path, context = split[0], split[1]
152 if len(context.split(':')) != 4:
153 return [f"Error: invalid file_contexts: {line}"]
154 tcontext = context.split(':')[2]
155
156 # check rules
157 errors = []
158 for matcher, rule in rules:
159 if match_path(path, matcher):
160 errors.extend(check_rule(pol, path, tcontext, rule))
161 return errors
162
163
164def extract_data(name, temp_dir):
165 out_path = os.path.join(temp_dir, name)
166 with open(out_path, 'wb') as f:
167 blob = pkgutil.get_data('apex_sepolicy_tests', name)
168 if not blob:
169 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
170 f.write(blob)
171 return out_path
172
173
174def do_main(work_dir):
175 """Do testing"""
176 parser = argparse.ArgumentParser()
Jooyung Han92bfb372023-09-08 14:28:40 +0900177 parser.add_argument('--all', action='store_true', help='tests ALL aspects')
Jooyung Han23d1e622023-04-04 18:03:07 +0900178 parser.add_argument('-f', '--file_contexts', help='output of "deapexer list -Z"')
179 args = parser.parse_args()
180
181 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
182 policy_path = extract_data('precompiled_sepolicy', work_dir)
183 pol = policy.Policy(policy_path, None, lib_path)
184
Jooyung Han92bfb372023-09-08 14:28:40 +0900185 if args.all:
186 rules = all_rules
187 else:
188 rules = generic_rules
189
Jooyung Han23d1e622023-04-04 18:03:07 +0900190 errors = []
191 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
192 for line in file_contexts:
Jooyung Han92bfb372023-09-08 14:28:40 +0900193 errors.extend(check_line(pol, line, rules))
Jooyung Han23d1e622023-04-04 18:03:07 +0900194 if len(errors) > 0:
195 sys.exit('\n'.join(errors))
196
197
198if __name__ == '__main__':
199 with tempfile.TemporaryDirectory() as temp_dir:
200 do_main(temp_dir)