blob: 3c51b67f3505aafa60f29ac2a6fd6eac801f3306 [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
Jooyung Han92bfb372023-09-08 14:28:40 +090068@dataclass
69class ResolveType:
70 """Rule checking if type can be resolved"""
71 pass
72
73
74Rule = AllowRead | ResolveType
Jooyung Han23d1e622023-04-04 18:03:07 +090075
76
77def match_path(path: str, matcher: Matcher) -> bool:
78 """True if path matches with the given matcher"""
79 match matcher:
80 case Is(target):
81 return path == target
82 case Glob(pattern):
83 return pathlib.PurePath(path).match(pattern)
84 case Regex(pattern):
85 return re.match(pattern, path)
86
87
88def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
89 """Returns error message if scontext can't read the target"""
Jooyung Han3e592f22023-06-05 10:47:20 +090090 errors = []
Jooyung Han23d1e622023-04-04 18:03:07 +090091 match rule:
92 case AllowRead(tclass, scontext):
Jooyung Han61b46b62023-05-31 17:41:28 +090093 # Test every source in scontext(set)
94 for s in scontext:
95 te_rules = list(pol.QueryTERule(scontext={s},
96 tcontext={tcontext},
97 tclass={tclass},
98 perms={'read'}))
99 if len(te_rules) > 0:
Jooyung Han3e592f22023-06-05 10:47:20 +0900100 continue # no errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900101
Jooyung Han3e592f22023-06-05 10:47:20 +0900102 errors.append(f"Error: {path}: {s} can't read. (tcontext={tcontext})")
Jooyung Han92bfb372023-09-08 14:28:40 +0900103 case ResolveType():
104 if tcontext not in pol.GetAllTypes(False):
105 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown")
Jooyung Han3e592f22023-06-05 10:47:20 +0900106 return errors
Jooyung Han23d1e622023-04-04 18:03:07 +0900107
108
Jooyung Han92bfb372023-09-08 14:28:40 +0900109target_specific_rules = [
110 (Glob('*'), ResolveType()),
111]
112
113
114generic_rules = [
Jooyung Han23d1e622023-04-04 18:03:07 +0900115 # permissions
116 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
117 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
118 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
119 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
120 # vintf fragments
121 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
122 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
123 # ./ and apex_manifest.pb
124 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
125 (Is('./'), AllowRead('dir', {'linkerconfig', 'apexd'})),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900126 # linker.config.pb
127 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900128]
129
130
Jooyung Han92bfb372023-09-08 14:28:40 +0900131all_rules = target_specific_rules + generic_rules
132
133
134def check_line(pol: policy.Policy, line: str, rules) -> List[str]:
Jooyung Han23d1e622023-04-04 18:03:07 +0900135 """Parses a file_contexts line and runs checks"""
136 # skip empty/comment line
137 line = line.strip()
138 if line == '' or line[0] == '#':
139 return []
140
141 # parse
142 split = line.split()
143 if len(split) != 2:
144 return [f"Error: invalid file_contexts: {line}"]
145 path, context = split[0], split[1]
146 if len(context.split(':')) != 4:
147 return [f"Error: invalid file_contexts: {line}"]
148 tcontext = context.split(':')[2]
149
150 # check rules
151 errors = []
152 for matcher, rule in rules:
153 if match_path(path, matcher):
154 errors.extend(check_rule(pol, path, tcontext, rule))
155 return errors
156
157
158def extract_data(name, temp_dir):
159 out_path = os.path.join(temp_dir, name)
160 with open(out_path, 'wb') as f:
161 blob = pkgutil.get_data('apex_sepolicy_tests', name)
162 if not blob:
163 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
164 f.write(blob)
165 return out_path
166
167
168def do_main(work_dir):
169 """Do testing"""
170 parser = argparse.ArgumentParser()
Jooyung Han92bfb372023-09-08 14:28:40 +0900171 parser.add_argument('--all', action='store_true', help='tests ALL aspects')
Jooyung Han23d1e622023-04-04 18:03:07 +0900172 parser.add_argument('-f', '--file_contexts', help='output of "deapexer list -Z"')
173 args = parser.parse_args()
174
175 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
176 policy_path = extract_data('precompiled_sepolicy', work_dir)
177 pol = policy.Policy(policy_path, None, lib_path)
178
Jooyung Han92bfb372023-09-08 14:28:40 +0900179 if args.all:
180 rules = all_rules
181 else:
182 rules = generic_rules
183
Jooyung Han23d1e622023-04-04 18:03:07 +0900184 errors = []
185 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
186 for line in file_contexts:
Jooyung Han92bfb372023-09-08 14:28:40 +0900187 errors.extend(check_line(pol, line, rules))
Jooyung Han23d1e622023-04-04 18:03:07 +0900188 if len(errors) > 0:
189 sys.exit('\n'.join(errors))
190
191
192if __name__ == '__main__':
193 with tempfile.TemporaryDirectory() as temp_dir:
194 do_main(temp_dir)