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 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 64Matcher = Is | Glob | Regex | BinaryFile 65 66 67# predicate functions for Func matcher 68 69 70@dataclass 71class AllowPerm: 72 """Rule checking if scontext has 'perm' to the entity""" 73 tclass: str 74 scontext: set[str] 75 perm: str 76 77 78@dataclass 79class ResolveType: 80 """Rule checking if type can be resolved""" 81 pass 82 83 84@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 91 92 93# Helper for 'read' 94def AllowRead(tclass, scontext): 95 return AllowPerm(tclass, scontext, 'read') 96 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) 107 case BinaryFile: 108 return path.startswith('./bin/') and not path.endswith('/') 109 110 111def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]: 112 """Returns error message if scontext can't read the target""" 113 errors = [] 114 match rule: 115 case AllowPerm(tclass, scontext, perm): 116 # 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}, 121 perms={perm})) 122 if len(te_rules) > 0: 123 continue # no errors 124 125 errors.append(f"Error: {path}: {s} can't {perm}. (tcontext={tcontext})") 126 case ResolveType(): 127 if tcontext not in pol.GetAllTypes(False): 128 errors.append(f"Error: {path}: tcontext({tcontext}) is unknown") 129 case NotAnyOf(labels): 130 if tcontext in labels: 131 errors.append(f"Error: {path}: can't be labelled as '{tcontext}'") 132 return errors 133 134 135target_specific_rules = [ 136 (Glob('*'), ResolveType()), 137] 138 139 140generic_rules = [ 141 # binaries should be executable 142 (BinaryFile, NotAnyOf({'vendor_file'})), 143 # 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'})), 153 (Is('./'), AllowPerm('dir', {'linkerconfig', 'apexd'}, 'search')), 154 # linker.config.pb 155 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})), 156] 157 158 159all_rules = target_specific_rules + generic_rules 160 161 162def check_line(pol: policy.Policy, line: str, rules) -> List[str]: 163 """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() 199 parser.add_argument('--all', action='store_true', help='tests ALL aspects') 200 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 207 if args.all: 208 rules = all_rules 209 else: 210 rules = generic_rules 211 212 errors = [] 213 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts: 214 for line in file_contexts: 215 errors.extend(check_line(pol, line, rules)) 216 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) 223