Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 1 | #!/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 | |
| 18 | Usage: |
| 19 | $ deapexer list -Z foo.apex > /tmp/fc |
| 20 | $ apex_sepolicy_tests -f /tmp/fc |
| 21 | """ |
| 22 | |
| 23 | |
| 24 | import argparse |
| 25 | import os |
| 26 | import pathlib |
| 27 | import pkgutil |
| 28 | import re |
| 29 | import sys |
| 30 | import tempfile |
| 31 | from dataclasses import dataclass |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 32 | from typing import Callable, List |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 33 | |
| 34 | import policy |
| 35 | |
| 36 | |
| 37 | SHARED_LIB_EXTENSION = '.dylib' if sys.platform == 'darwin' else '.so' |
| 38 | LIBSEPOLWRAP = "libsepolwrap" + SHARED_LIB_EXTENSION |
| 39 | |
| 40 | |
| 41 | @dataclass |
| 42 | class Is: |
| 43 | """Exact matcher for a path.""" |
| 44 | path: str |
| 45 | |
| 46 | |
| 47 | @dataclass |
| 48 | class Glob: |
| 49 | """Path matcher with pathlib.PurePath.match""" |
| 50 | pattern: str |
| 51 | |
| 52 | |
| 53 | @dataclass |
| 54 | class Regex: |
| 55 | """Path matcher with re.match""" |
| 56 | pattern: str |
| 57 | |
| 58 | |
Jooyung Han | c945a10 | 2024-02-07 15:41:25 +0900 | [diff] [blame] | 59 | @dataclass |
| 60 | class BinaryFile: |
| 61 | pass |
| 62 | |
| 63 | |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 64 | @dataclass |
| 65 | class MatchPred: |
| 66 | pred: Callable[[str], bool] |
| 67 | |
| 68 | |
| 69 | Matcher = Is | Glob | Regex | BinaryFile | MatchPred |
Jooyung Han | c945a10 | 2024-02-07 15:41:25 +0900 | [diff] [blame] | 70 | |
| 71 | |
| 72 | # predicate functions for Func matcher |
| 73 | |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 74 | |
| 75 | @dataclass |
Jooyung Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 76 | class AllowPerm: |
| 77 | """Rule checking if scontext has 'perm' to the entity""" |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 78 | tclass: str |
| 79 | scontext: set[str] |
Jooyung Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 80 | perm: str |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 81 | |
| 82 | |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 83 | @dataclass |
| 84 | class ResolveType: |
| 85 | """Rule checking if type can be resolved""" |
| 86 | pass |
| 87 | |
| 88 | |
Jooyung Han | c945a10 | 2024-02-07 15:41:25 +0900 | [diff] [blame] | 89 | @dataclass |
| 90 | class NotAnyOf: |
| 91 | """Rule checking if entity is not labelled as any of the given labels""" |
| 92 | labels: set[str] |
| 93 | |
| 94 | |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 95 | @dataclass |
| 96 | class HasAttr: |
| 97 | """Rule checking if the context has the specified attribute""" |
| 98 | attr: str |
| 99 | |
| 100 | |
| 101 | Rule = AllowPerm | ResolveType | NotAnyOf | HasAttr |
Jooyung Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 102 | |
| 103 | |
| 104 | # Helper for 'read' |
| 105 | def AllowRead(tclass, scontext): |
| 106 | return AllowPerm(tclass, scontext, 'read') |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 107 | |
| 108 | |
| 109 | def 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 Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 118 | case BinaryFile(): |
Jooyung Han | c945a10 | 2024-02-07 15:41:25 +0900 | [diff] [blame] | 119 | return path.startswith('./bin/') and not path.endswith('/') |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 120 | case MatchPred(pred): |
| 121 | return pred(path) |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 122 | case _: |
| 123 | sys.exit(f'unknown matcher: {matcher}') |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 124 | |
| 125 | |
| 126 | def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]: |
| 127 | """Returns error message if scontext can't read the target""" |
Jooyung Han | 3e592f2 | 2023-06-05 10:47:20 +0900 | [diff] [blame] | 128 | errors = [] |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 129 | match rule: |
Jooyung Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 130 | case AllowPerm(tclass, scontext, perm): |
Jooyung Han | 61b46b6 | 2023-05-31 17:41:28 +0900 | [diff] [blame] | 131 | # 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 Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 136 | perms={perm})) |
Jooyung Han | 61b46b6 | 2023-05-31 17:41:28 +0900 | [diff] [blame] | 137 | if len(te_rules) > 0: |
Jooyung Han | 3e592f2 | 2023-06-05 10:47:20 +0900 | [diff] [blame] | 138 | continue # no errors |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 139 | |
Jooyung Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 140 | errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})") |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 141 | case ResolveType(): |
| 142 | if tcontext not in pol.GetAllTypes(False): |
| 143 | errors.append(f"Error: {path}: tcontext({tcontext}) is unknown") |
Jooyung Han | c945a10 | 2024-02-07 15:41:25 +0900 | [diff] [blame] | 144 | case NotAnyOf(labels): |
| 145 | if tcontext in labels: |
| 146 | errors.append(f"Error: {path}: can't be labelled as '{tcontext}'") |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 147 | 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 Han | 3e592f2 | 2023-06-05 10:47:20 +0900 | [diff] [blame] | 150 | return errors |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 151 | |
| 152 | |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 153 | target_specific_rules = [ |
| 154 | (Glob('*'), ResolveType()), |
| 155 | ] |
| 156 | |
| 157 | |
| 158 | generic_rules = [ |
Jooyung Han | c945a10 | 2024-02-07 15:41:25 +0900 | [diff] [blame] | 159 | # binaries should be executable |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 160 | (BinaryFile(), NotAnyOf({'vendor_file'})), |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 161 | # 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 Han | b951790 | 2023-11-14 13:50:14 +0900 | [diff] [blame] | 171 | (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')), |
Jooyung Han | babd060 | 2023-04-24 15:34:49 +0900 | [diff] [blame] | 172 | # linker.config.pb |
| 173 | (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})), |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 174 | ] |
| 175 | |
| 176 | |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 177 | all_rules = target_specific_rules + generic_rules |
| 178 | |
| 179 | |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 180 | def 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 | |
| 189 | def system_vendor_rule(partition): |
| 190 | exceptions = [ |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 191 | "./etc/linker.config.pb" |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 192 | ] |
| 193 | def pred(path): |
| 194 | return path not in exceptions |
| 195 | |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 196 | return MatchPred(pred), HasAttr(base_attr_for(partition)) |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 197 | |
| 198 | |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 199 | def check_line(pol: policy.Policy, line: str, rules, ignore_unknown_context=False) -> List[str]: |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 200 | """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 Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 215 | if ignore_unknown_context and tcontext not in pol.GetAllTypes(False): |
| 216 | return [] |
| 217 | |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 218 | # 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 | |
| 226 | def 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 | |
| 236 | def do_main(work_dir): |
| 237 | """Do testing""" |
| 238 | parser = argparse.ArgumentParser() |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 239 | parser.add_argument('--all', action='store_true', help='tests ALL aspects') |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 240 | 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 Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 242 | 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 Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 248 | # ignore unknown contexts unless --all is specified |
| 249 | ignore_unknown_context = True |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 250 | if args.all: |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 251 | ignore_unknown_context = False |
Jooyung Han | 92bfb37 | 2023-09-08 14:28:40 +0900 | [diff] [blame] | 252 | |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 253 | rules = all_rules |
Jooyung Han | 20b6352 | 2025-01-03 17:45:25 +0900 | [diff] [blame] | 254 | if args.partition: |
| 255 | rules.append(system_vendor_rule(args.partition)) |
| 256 | |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 257 | errors = [] |
| 258 | with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts: |
| 259 | for line in file_contexts: |
Jooyung Han | 4b966cb | 2025-02-06 23:23:15 -0800 | [diff] [blame^] | 260 | errors.extend(check_line(pol, line, rules, ignore_unknown_context)) |
Jooyung Han | 23d1e62 | 2023-04-04 18:03:07 +0900 | [diff] [blame] | 261 | if len(errors) > 0: |
| 262 | sys.exit('\n'.join(errors)) |
| 263 | |
| 264 | |
| 265 | if __name__ == '__main__': |
| 266 | with tempfile.TemporaryDirectory() as temp_dir: |
| 267 | do_main(temp_dir) |