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 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 Callable, 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 59@dataclass 60class BinaryFile: 61 pass 62 63 64@dataclass 65class MatchPred: 66 pred: Callable[[str], bool] 67 68 69Matcher = Is | Glob | Regex | BinaryFile | MatchPred 70 71 72# predicate functions for Func matcher 73 74 75@dataclass 76class AllowPerm: 77 """Rule checking if scontext has 'perm' to the entity""" 78 tclass: str 79 scontext: set[str] 80 perm: str 81 82 83@dataclass 84class ResolveType: 85 """Rule checking if type can be resolved""" 86 pass 87 88 89@dataclass 90class NotAnyOf: 91 """Rule checking if entity is not labelled as any of the given labels""" 92 labels: set[str] 93 94 95@dataclass 96class HasAttr: 97 """Rule checking if the context has the specified attribute""" 98 attr: str 99 100 101Rule = AllowPerm | ResolveType | NotAnyOf | HasAttr 102 103 104# Helper for 'read' 105def AllowRead(tclass, scontext): 106 return AllowPerm(tclass, scontext, 'read') 107 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) 118 case BinaryFile(): 119 return path.startswith('./bin/') and not path.endswith('/') 120 case MatchPred(pred): 121 return pred(path) 122 case _: 123 sys.exit(f'unknown matcher: {matcher}') 124 125 126def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]: 127 """Returns error message if scontext can't read the target""" 128 errors = [] 129 match rule: 130 case AllowPerm(tclass, scontext, perm): 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}, 136 perms={perm})) 137 if len(te_rules) > 0: 138 continue # no errors 139 140 errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})") 141 case ResolveType(): 142 if tcontext not in pol.GetAllTypes(False): 143 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown") 144 case NotAnyOf(labels): 145 if tcontext in labels: 146 errors.append(f"Error: {path}: can't be labelled as '{tcontext}'") 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}") 150 return errors 151 152 153target_specific_rules = [ 154 (Glob('*'), ResolveType()), 155] 156 157 158generic_rules = [ 159 # binaries should be executable 160 (BinaryFile(), NotAnyOf({'vendor_file'})), 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'})), 171 (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')), 172 # linker.config.pb 173 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})), 174] 175 176 177all_rules = target_specific_rules + generic_rules 178 179 180def 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 189def system_vendor_rule(partition): 190 exceptions = [ 191 "./etc/linker.config.pb" 192 ] 193 def pred(path): 194 return path not in exceptions 195 196 return MatchPred(pred), HasAttr(base_attr_for(partition)) 197 198 199def check_line(pol: policy.Policy, line: str, rules, ignore_unknown_context=False) -> List[str]: 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 215 if ignore_unknown_context and tcontext not in pol.GetAllTypes(False): 216 return [] 217 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 226def 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 236def do_main(work_dir): 237 """Do testing""" 238 parser = argparse.ArgumentParser() 239 parser.add_argument('--all', action='store_true', help='tests ALL aspects') 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') 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 248 # ignore unknown contexts unless --all is specified 249 ignore_unknown_context = True 250 if args.all: 251 ignore_unknown_context = False 252 253 rules = all_rules 254 if args.partition: 255 rules.append(system_vendor_rule(args.partition)) 256 257 errors = [] 258 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts: 259 for line in file_contexts: 260 errors.extend(check_line(pol, line, rules, ignore_unknown_context)) 261 if len(errors) > 0: 262 sys.exit('\n'.join(errors)) 263 264 265if __name__ == '__main__': 266 with tempfile.TemporaryDirectory() as temp_dir: 267 do_main(temp_dir) 268