blob: 2cdde3c72e3f6748f670b05e8262d412ac6405f3 [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"""
84 match rule:
85 case AllowRead(tclass, scontext):
86 te_rules = list(pol.QueryTERule(scontext=scontext,
87 tcontext={tcontext},
88 tclass={tclass},
89 perms={'read'}))
90 if len(te_rules) > 0:
91 return [] # no errors
92
93 return [f"Error: {path}: {scontext} can't read. (tcontext={tcontext})"]
94
95
96rules = [
97 # permissions
98 (Is('./etc/permissions/'), AllowRead('dir', {'system_server'})),
99 (Glob('./etc/permissions/*.xml'), AllowRead('file', {'system_server'})),
100 # init scripts with optional SDK version (e.g. foo.rc, foo.32rc)
101 (Regex('\./etc/.*\.\d*rc'), AllowRead('file', {'init'})),
102 # vintf fragments
103 (Is('./etc/vintf/'), AllowRead('dir', {'servicemanager', 'apexd'})),
104 (Glob('./etc/vintf/*.xml'), AllowRead('file', {'servicemanager', 'apexd'})),
105 # ./ and apex_manifest.pb
106 (Is('./apex_manifest.pb'), AllowRead('file', {'linkerconfig', 'apexd'})),
107 (Is('./'), AllowRead('dir', {'linkerconfig', 'apexd'})),
108]
109
110
111def check_line(pol: policy.Policy, line: str) -> List[str]:
112 """Parses a file_contexts line and runs checks"""
113 # skip empty/comment line
114 line = line.strip()
115 if line == '' or line[0] == '#':
116 return []
117
118 # parse
119 split = line.split()
120 if len(split) != 2:
121 return [f"Error: invalid file_contexts: {line}"]
122 path, context = split[0], split[1]
123 if len(context.split(':')) != 4:
124 return [f"Error: invalid file_contexts: {line}"]
125 tcontext = context.split(':')[2]
126
127 # check rules
128 errors = []
129 for matcher, rule in rules:
130 if match_path(path, matcher):
131 errors.extend(check_rule(pol, path, tcontext, rule))
132 return errors
133
134
135def extract_data(name, temp_dir):
136 out_path = os.path.join(temp_dir, name)
137 with open(out_path, 'wb') as f:
138 blob = pkgutil.get_data('apex_sepolicy_tests', name)
139 if not blob:
140 sys.exit(f"Error: {name} does not exist. Is this binary corrupted?\n")
141 f.write(blob)
142 return out_path
143
144
145def do_main(work_dir):
146 """Do testing"""
147 parser = argparse.ArgumentParser()
148 parser.add_argument('-f', '--file_contexts', help='output of "deapexer list -Z"')
149 args = parser.parse_args()
150
151 lib_path = extract_data(LIBSEPOLWRAP, work_dir)
152 policy_path = extract_data('precompiled_sepolicy', work_dir)
153 pol = policy.Policy(policy_path, None, lib_path)
154
155 errors = []
156 with open(args.file_contexts, 'rt', encoding='utf-8') as file_contexts:
157 for line in file_contexts:
158 errors.extend(check_line(pol, line))
159 if len(errors) > 0:
160 sys.exit('\n'.join(errors))
161
162
163if __name__ == '__main__':
164 with tempfile.TemporaryDirectory() as temp_dir:
165 do_main(temp_dir)