blob: 518ebbc102e64731a024f77f3bd3032a67e609a3 [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
68Rule = AllowRead
69
70
71def match_path(path: str, matcher: Matcher) -> bool:
72 """True if path matches with the given matcher"""
73 match matcher:
74 case Is(target):
75 return path == target
76 case Glob(pattern):
77 return pathlib.PurePath(path).match(pattern)
78 case Regex(pattern):
79 return re.match(pattern, path)
80
81
82def check_rule(pol, path: str, tcontext: str, rule: Rule) -> List[str]:
83 """Returns error message if scontext can't read the target"""
Jooyung Han3e592f22023-06-05 10:47:20 +090084 errors = []
Jooyung Han23d1e622023-04-04 18:03:07 +090085 match rule:
86 case AllowRead(tclass, scontext):
Jooyung Han61b46b62023-05-31 17:41:28 +090087 # Test every source in scontext(set)
88 for s in scontext:
89 te_rules = list(pol.QueryTERule(scontext={s},
90 tcontext={tcontext},
91 tclass={tclass},
92 perms={'read'}))
93 if len(te_rules) > 0:
Jooyung Han3e592f22023-06-05 10:47:20 +090094 continue # no errors
Jooyung Han23d1e622023-04-04 18:03:07 +090095
Jooyung Han3e592f22023-06-05 10:47:20 +090096 errors.append(f"Error: {path}: {s} can't read. (tcontext={tcontext})")
97 return errors
Jooyung Han23d1e622023-04-04 18:03:07 +090098
99
100rules = [
101 # permissions
102 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
103 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
104 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
105 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
106 # vintf fragments
107 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
108 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
109 # ./ and apex_manifest.pb
110 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
111 (Is('./'), AllowRead('dir', {'linkerconfig', 'apexd'})),
Jooyung Hanbabd0602023-04-24 15:34:49 +0900112 # linker.config.pb
113 (Is('./etc/linker.config.pb'), AllowRead('file', {'linkerconfig'})),
Jooyung Han23d1e622023-04-04 18:03:07 +0900114]
115
116
117def check_line(pol: policy.Policy, line: str) -> List[str]:
118 """Parses a file_contexts line and runs checks"""
119 # skip empty/comment line
120 line = line.strip()
121 if line == '' or line[0] == '#':
122 return []
123
124 # parse
125 split = line.split()
126 if len(split) != 2:
127 return [f"Error: invalid file_contexts: {line}"]
128 path, context = split[0], split[1]
129 if len(context.split(':')) != 4:
130 return [f"Error: invalid file_contexts: {line}"]
131 tcontext = context.split(':')[2]
132
133 # check rules
134 errors = []
135 for matcher, rule in rules:
136 if match_path(path, matcher):
137 errors.extend(check_rule(pol, path, tcontext, rule))
138 return errors
139
140
141def extract_data(name, temp_dir):
142 out_path = os.path.join(temp_dir, name)
143 with open(out_path, 'wb') as f:
144 blob = pkgutil.get_data('apex_sepolicy_tests', name)
145 if not blob:
146 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
147 f.write(blob)
148 return out_path
149
150
151def do_main(work_dir):
152 """Do testing"""
153 parser = argparse.ArgumentParser()
154 parser.add_argument('-f', '--file_contexts', help='output of "deapexer list -Z"')
155 args = parser.parse_args()
156
157 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
158 policy_path = extract_data('precompiled_sepolicy', work_dir)
159 pol = policy.Policy(policy_path, None, lib_path)
160
161 errors = []
162 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
163 for line in file_contexts:
164 errors.extend(check_line(pol, line))
165 if len(errors) > 0:
166 sys.exit('\n'.join(errors))
167
168
169if __name__ == '__main__':
170 with tempfile.TemporaryDirectory() as temp_dir:
171 do_main(temp_dir)