blob: 1d380abf3f348926e62947d275ce08be15555a6c [file] [log] [blame]
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +11001# Copyright 2021 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070015from optparse import OptionParser
16from optparse import Option, OptionValueError
17import os
Dan Cashman91d398d2017-09-26 12:58:29 -070018import mini_parser
Inseob Kim4912a242022-07-25 11:30:02 +090019import pkgutil
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070020import policy
Dan Cashman91d398d2017-09-26 12:58:29 -070021from policy import MatchPathPrefix
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070022import re
Inseob Kim4912a242022-07-25 11:30:02 +090023import shutil
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070024import sys
Inseob Kim4912a242022-07-25 11:30:02 +090025import tempfile
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070026
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070027DEBUG=False
Inseob Kim3a9ac6f2022-07-19 14:27:36 +090028SHARED_LIB_EXTENSION = '.dylib' if sys.platform == 'darwin' else '.so'
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070029
Charles Chendc184e92023-01-26 03:06:44 +000030# TODO(b/266998144): consider rename this file.
31
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070032'''
33Use file_contexts and policy to verify Treble requirements
34are not violated.
35'''
Joel Galensonb0d74a12020-07-27 09:30:34 -070036coredomainAllowlist = {
Steven Moreland000ec932020-04-02 16:20:31 -070037 # TODO: how do we make sure vendor_init doesn't have bad coupling with
38 # /vendor? It is the only system process which is not coredomain.
Tom Cherry9c778042018-01-25 11:31:09 -080039 'vendor_init',
Joel Galensonb0d74a12020-07-27 09:30:34 -070040 # TODO(b/152813275): need to avoid allowlist for rootdir
Steven Moreland000ec932020-04-02 16:20:31 -070041 "modprobe",
42 "slideshow",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070043 }
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070044
45class scontext:
46 def __init__(self):
47 self.fromSystem = False
48 self.fromVendor = False
49 self.coredomain = False
50 self.appdomain = False
51 self.attributes = set()
52 self.entrypoints = []
53 self.entrypointpaths = []
Steven Moreland000ec932020-04-02 16:20:31 -070054 self.error = ""
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070055
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070056
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110057class TestPolicy:
58 """A policy loaded in memory with its domains easily accessible."""
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070059
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110060 def __init__(self):
61 self.alldomains = {}
62 self.coredomains = set()
63 self.appdomains = set()
64 self.vendordomains = set()
65 self.pol = None
Dan Cashman91d398d2017-09-26 12:58:29 -070066
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110067 # compat vars
68 self.alltypes = set()
69 self.oldalltypes = set()
70 self.compatMapping = None
71 self.pubtypes = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070072
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110073 # Distinguish between PRODUCT_FULL_TREBLE and PRODUCT_FULL_TREBLE_OVERRIDE
74 self.FakeTreble = False
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070075
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110076 def GetAllDomains(self):
77 for result in self.pol.QueryTypeAttribute("domain", True):
78 self.alldomains[result] = scontext()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070079
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110080 def GetAppDomains(self):
81 for d in self.alldomains:
82 # The application of the "appdomain" attribute is trusted because core
83 # selinux policy contains neverallow rules that enforce that only zygote
84 # and runas spawned processes may transition to processes that have
85 # the appdomain attribute.
86 if "appdomain" in self.alldomains[d].attributes:
87 self.alldomains[d].appdomain = True
88 self.appdomains.add(d)
Steven Moreland000ec932020-04-02 16:20:31 -070089
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +110090 def GetCoreDomains(self):
91 for d in self.alldomains:
92 domain = self.alldomains[d]
93 # TestCoredomainViolations will verify if coredomain was incorrectly
94 # applied.
95 if "coredomain" in domain.attributes:
96 domain.coredomain = True
97 self.coredomains.add(d)
98 # check whether domains are executed off of /system or /vendor
99 if d in coredomainAllowlist:
100 continue
101 # TODO(b/153112003): add checks to prevent app domains from being
102 # incorrectly labeled as coredomain. Apps don't have entrypoints as
103 # they're always dynamically transitioned to by zygote.
104 if d in self.appdomains:
105 continue
106 # TODO(b/153112747): need to handle cases where there is a dynamic
107 # transition OR there happens to be no context in AOSP files.
108 if not domain.entrypointpaths:
109 continue
Steven Moreland000ec932020-04-02 16:20:31 -0700110
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100111 for path in domain.entrypointpaths:
112 vendor = any(MatchPathPrefix(path, prefix) for prefix in
113 ["/vendor", "/odm"])
114 system = any(MatchPathPrefix(path, prefix) for prefix in
115 ["/init", "/system_ext", "/product" ])
Steven Moreland000ec932020-04-02 16:20:31 -0700116
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100117 # only mark entrypoint as system if it is not in legacy /system/vendor
118 if MatchPathPrefix(path, "/system/vendor"):
119 vendor = True
120 elif MatchPathPrefix(path, "/system"):
121 system = True
Steven Moreland000ec932020-04-02 16:20:31 -0700122
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100123 if not vendor and not system:
124 domain.error += "Unrecognized entrypoint for " + d + " at " + path + "\n"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700125
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100126 domain.fromSystem = domain.fromSystem or system
127 domain.fromVendor = domain.fromVendor or vendor
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700128
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100129 ###
130 # Add the entrypoint type and path(s) to each domain.
131 #
132 def GetDomainEntrypoints(self):
133 for x in self.pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])):
134 if not x.sctx in self.alldomains:
135 continue
136 self.alldomains[x.sctx].entrypoints.append(str(x.tctx))
137 # postinstall_file represents a special case specific to A/B OTAs.
138 # Update_engine mounts a partition and relabels it postinstall_file.
139 # There is no file_contexts entry associated with postinstall_file
140 # so skip the lookup.
141 if x.tctx == "postinstall_file":
142 continue
143 entrypointpath = self.pol.QueryFc(x.tctx)
144 if not entrypointpath:
145 continue
146 self.alldomains[x.sctx].entrypointpaths.extend(entrypointpath)
Dan Cashman91d398d2017-09-26 12:58:29 -0700147
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100148 ###
149 # Get attributes associated with each domain
150 #
151 def GetAttributes(self):
152 for domain in self.alldomains:
153 for result in self.pol.QueryTypeAttribute(domain, False):
154 self.alldomains[domain].attributes.add(result)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700155
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100156 def setup(self, pol):
157 self.pol = pol
158 self.GetAllDomains()
159 self.GetAttributes()
160 self.GetDomainEntrypoints()
161 self.GetAppDomains()
162 self.GetCoreDomains()
Dan Cashman91d398d2017-09-26 12:58:29 -0700163
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100164 def GetAllTypes(self, basepol, oldpol):
165 self.alltypes = basepol.GetAllTypes(False)
166 self.oldalltypes = oldpol.GetAllTypes(False)
Dan Cashman91d398d2017-09-26 12:58:29 -0700167
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100168 # setup for the policy compatibility tests
169 def compatSetup(self, basepol, oldpol, mapping, types):
170 self.GetAllTypes(basepol, oldpol)
171 self.compatMapping = mapping
172 self.pubtypes = types
173
174 def DomainsWithAttribute(self, attr):
175 domains = []
176 for domain in self.alldomains:
177 if attr in self.alldomains[domain].attributes:
178 domains.append(domain)
179 return domains
180
181 def PrintScontexts(self):
182 for d in sorted(self.alldomains.keys()):
183 sctx = self.alldomains[d]
184 print(d)
185 print("\tcoredomain="+str(sctx.coredomain))
186 print("\tappdomain="+str(sctx.appdomain))
187 print("\tfromSystem="+str(sctx.fromSystem))
188 print("\tfromVendor="+str(sctx.fromVendor))
189 print("\tattributes="+str(sctx.attributes))
190 print("\tentrypoints="+str(sctx.entrypoints))
191 print("\tentrypointpaths=")
192 if sctx.entrypointpaths is not None:
193 for path in sctx.entrypointpaths:
194 print("\t\t"+str(path))
195
Dan Cashman91d398d2017-09-26 12:58:29 -0700196
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700197#############################################################
198# Tests
199#############################################################
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100200def TestCoredomainViolations(test_policy):
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700201 # verify that all domains launched from /system have the coredomain
202 # attribute
203 ret = ""
Steven Moreland000ec932020-04-02 16:20:31 -0700204
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100205 for d in test_policy.alldomains:
206 domain = test_policy.alldomains[d]
Steven Moreland000ec932020-04-02 16:20:31 -0700207 if domain.fromSystem and domain.fromVendor:
208 ret += "The following domain is system and vendor: " + d + "\n"
209
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100210 for domain in test_policy.alldomains.values():
Steven Moreland000ec932020-04-02 16:20:31 -0700211 ret += domain.error
212
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700213 violators = []
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100214 for d in test_policy.alldomains:
215 domain = test_policy.alldomains[d]
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700216 if domain.fromSystem and "coredomain" not in domain.attributes:
217 violators.append(d);
218 if len(violators) > 0:
219 ret += "The following domain(s) must be associated with the "
220 ret += "\"coredomain\" attribute because they are executed off of "
221 ret += "/system:\n"
222 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
223
224 # verify that all domains launched form /vendor do not have the coredomain
225 # attribute
226 violators = []
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100227 for d in test_policy.alldomains:
228 domain = test_policy.alldomains[d]
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700229 if domain.fromVendor and "coredomain" in domain.attributes:
230 violators.append(d)
231 if len(violators) > 0:
232 ret += "The following domains must not be associated with the "
233 ret += "\"coredomain\" attribute because they are executed off of "
234 ret += "/vendor or /system/vendor:\n"
235 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
236
237 return ret
238
239###
Tri Voe3f4f772018-09-28 17:21:08 -0700240# Make sure that any new public type introduced in the new policy that was not
241# present in the old policy has been recorded in the mapping file.
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100242def TestNoUnmappedNewTypes(test_policy):
243 newt = test_policy.alltypes - test_policy.oldalltypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700244 ret = ""
245 violators = []
246
247 for n in newt:
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100248 if n in test_policy.pubtypes and test_policy.compatMapping.rTypeattributesets.get(n) is None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700249 violators.append(n)
250
251 if len(violators) > 0:
Tri Voe3f4f772018-09-28 17:21:08 -0700252 ret += "SELinux: The following public types were found added to the "
253 ret += "policy without an entry into the compatibility mapping file(s) "
Tri Vo438684b2018-09-29 17:47:10 -0700254 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
255 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800256 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
257 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700258 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/781036\n"
259 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/852612\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700260 return ret
261
262###
263# Make sure that any public type removed in the current policy has its
264# declaration added to the mapping file for use in non-platform policy
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100265def TestNoUnmappedRmTypes(test_policy):
266 rmt = test_policy.oldalltypes - test_policy.alltypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700267 ret = ""
268 violators = []
269
270 for o in rmt:
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100271 if o in test_policy.compatMapping.pubtypes and not o in test_policy.compatMapping.types:
Dan Cashman91d398d2017-09-26 12:58:29 -0700272 violators.append(o)
273
274 if len(violators) > 0:
275 ret += "SELinux: The following formerly public types were removed from "
276 ret += "policy without a declaration in the compatibility mapping "
Tri Vo438684b2018-09-29 17:47:10 -0700277 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
278 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800279 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
280 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700281 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/822743\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700282 return ret
283
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100284def TestTrebleCompatMapping(test_policy):
285 ret = TestNoUnmappedNewTypes(test_policy)
286 ret += TestNoUnmappedRmTypes(test_policy)
Dan Cashman91d398d2017-09-26 12:58:29 -0700287 return ret
288
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100289def TestViolatorAttribute(test_policy, attribute):
Dan Cashman91d398d2017-09-26 12:58:29 -0700290 ret = ""
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100291 if test_policy.FakeTreble:
Dan Cashman91d398d2017-09-26 12:58:29 -0700292 return ret
293
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100294 violators = test_policy.DomainsWithAttribute(attribute)
Dan Cashman91d398d2017-09-26 12:58:29 -0700295 if len(violators) > 0:
296 ret += "SELinux: The following domains violate the Treble ban "
297 ret += "against use of the " + attribute + " attribute: "
298 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
299 return ret
300
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100301def TestViolatorAttributes(test_policy):
Steven Moreland5c0a0a82019-05-13 17:06:50 -0700302 ret = ""
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100303 ret += TestViolatorAttribute(test_policy, "socket_between_core_and_vendor_violators")
304 ret += TestViolatorAttribute(test_policy, "vendor_executes_system_violators")
Dan Cashman91d398d2017-09-26 12:58:29 -0700305 return ret
306
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800307# TODO move this to sepolicy_tests
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100308def TestCoreDataTypeViolations(test_policy):
309 return test_policy.pol.AssertPathTypesDoNotHaveAttr(["/data/vendor/", "/data/vendor_ce/",
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800310 "/data/vendor_de/"], [], "core_data_file_type")
311
Charles Chendc184e92023-01-26 03:06:44 +0000312# TODO move this to sepolicy_tests
313def TestIsolatedAttributeConsistency(test_policy):
314 permissionAllowList = {
315 # hardware related
316 "codec2_config_prop" : ["file"],
317 "device_config_nnapi_native_prop":["file"],
318 "dmabuf_system_heap_device":["chr_file"],
319 "hal_allocator_default":["binder", "fd"],
320 "hal_codec2": ["binder", "fd"],
321 "hal_codec2_hwservice":["hwservice_manager"],
322 "hal_graphics_allocator": ["binder", "fd"],
323 "hal_graphics_allocator_service":["service_manager"],
324 "hal_graphics_allocator_hwservice":["hwservice_manager"],
325 "hal_graphics_allocator_server":["binder", "service_manager"],
326 "hal_graphics_mapper_hwservice":["hwservice_manager"],
327 "hal_neuralnetworks": ["binder", "fd"],
328 "hal_neuralnetworks_hwservice":["hwservice_manager"],
329 "hal_omx_hwservice":["hwservice_manager"],
330 "hidl_allocator_hwservice":["hwservice_manager"],
331 "hidl_manager_hwservice":["hwservice_manager"],
332 "hidl_memory_hwservice":["hwservice_manager"],
333 "hidl_token_hwservice":["hwservice_manager"],
334 "hwservicemanager":["binder"],
335 "hwservicemanager_prop":["file"],
336 "hwbinder_device":["chr_file"],
337 "mediacodec":["binder", "fd"],
338 "mediaswcodec":["binder", "fd"],
339 "media_variant_prop":["file"],
340 "nnapi_ext_deny_product_prop":["file"],
341 "ion_device" : ["chr_file"],
342 # system services
343 "audioserver_service":["service_manager"],
344 "cameraserver_service":["service_manager"],
345 "content_capture_service":["service_manager"],
346 "device_state_service":["service_manager"],
347 "hal_neuralnetworks_service":["service_manager"],
348 "servicemanager":["fd"],
349 "speech_recognition_service":["service_manager"],
350 "mediaserver_service" :["service_manager"]
351 }
352
353 def resolveHalServerSubtype(target):
354 # permission given as a client in technical_debt.cil
355 hal_server_attributes = [
356 "hal_codec2_server",
357 "hal_graphics_allocator_server",
358 "hal_neuralnetworks_server"]
359
360 for attr in hal_server_attributes:
361 if target in test_policy.pol.QueryTypeAttribute(Type=attr, IsAttr=True):
362 return attr.rsplit("_", 1)[0]
363 return target
364
365 def checkPermissions(permissions):
366 violated_permissions = []
367 for perm in permissions:
368 tctx, tclass, p = perm.split(":")
369 tctx = resolveHalServerSubtype(tctx)
370 if tctx not in permissionAllowList \
371 or tclass not in permissionAllowList[tctx] \
372 or ( p == "write" and not perm.startswith("hwbinder_device:chr_file") ) \
373 or ( p == "rw_file_perms"):
374 violated_permissions += [perm]
375 return violated_permissions
376
377 ret = ""
378
379 isolatedMemberTypes = test_policy.pol.QueryTypeAttribute(Type="isolated_app_all", IsAttr=True)
380 baseRules = test_policy.pol.QueryExpandedTERule(scontext=["isolated_app"])
381 basePermissionSet = set([":".join([rule.tctx, rule.tclass, perm])
382 for rule in baseRules for perm in rule.perms])
383 for subType in isolatedMemberTypes:
384 if subType == "isolated_app" : continue
385 currentTypeRule = test_policy.pol.QueryExpandedTERule(scontext=[subType])
386 typePermissionSet = set([":".join([rule.tctx, rule.tclass, perm])
387 for rule in currentTypeRule for perm in rule.perms
388 if not rule.tctx in [subType, subType + "_userfaultfd"]])
389 deltaPermissionSet = typePermissionSet.difference(basePermissionSet)
390 violated_permissions = checkPermissions(list(deltaPermissionSet))
391 for perm in violated_permissions:
392 ret += "allow %s %s:%s %s \n" % (subType, *perm.split(":"))
393
394 if ret:
395 ret = ("Found prohibited permission granted for isolated like types. " + \
396 "Please replace your allow statements that involve \"-isolated_app\" with " + \
397 "\"-isolated_app_all\". Violations are shown as the following: \n") + ret
398 return ret
399
Dan Cashman91d398d2017-09-26 12:58:29 -0700400###
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700401# extend OptionParser to allow the same option flag to be used multiple times.
402# This is used to allow multiple file_contexts files and tests to be
403# specified.
404#
405class MultipleOption(Option):
406 ACTIONS = Option.ACTIONS + ("extend",)
407 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
408 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
409 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
410
411 def take_action(self, action, dest, opt, value, values, parser):
412 if action == "extend":
413 values.ensure_value(dest, []).append(value)
414 else:
415 Option.take_action(self, action, dest, opt, value, values, parser)
416
Dan Cashman91d398d2017-09-26 12:58:29 -0700417Tests = {"CoredomainViolations": TestCoredomainViolations,
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800418 "CoreDatatypeViolations": TestCoreDataTypeViolations,
Dan Cashman91d398d2017-09-26 12:58:29 -0700419 "TrebleCompatMapping": TestTrebleCompatMapping,
Charles Chendc184e92023-01-26 03:06:44 +0000420 "ViolatorAttributes": TestViolatorAttributes,
421 "IsolatedAttributeConsistency": TestIsolatedAttributeConsistency}
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700422
Inseob Kim4912a242022-07-25 11:30:02 +0900423def do_main(libpath):
424 """
425 Args:
426 libpath: string, path to libsepolwrap.so
427 """
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100428 test_policy = TestPolicy()
Inseob Kim4912a242022-07-25 11:30:02 +0900429
Inseob Kim6fa8efd2021-12-29 13:56:14 +0900430 usage = "treble_sepolicy_tests "
Dan Cashman91d398d2017-09-26 12:58:29 -0700431 usage += "-f nonplat_file_contexts -f plat_file_contexts "
432 usage += "-p curr_policy -b base_policy -o old_policy "
433 usage +="-m mapping file [--test test] [--help]"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700434 parser = OptionParser(option_class=MultipleOption, usage=usage)
Dan Cashman91d398d2017-09-26 12:58:29 -0700435 parser.add_option("-b", "--basepolicy", dest="basepolicy", metavar="FILE")
Tri Voe3f4f772018-09-28 17:21:08 -0700436 parser.add_option("-u", "--base-pub-policy", dest="base_pub_policy",
437 metavar="FILE")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700438 parser.add_option("-f", "--file_contexts", dest="file_contexts",
439 metavar="FILE", action="extend", type="string")
Dan Cashman91d398d2017-09-26 12:58:29 -0700440 parser.add_option("-m", "--mapping", dest="mapping", metavar="FILE")
441 parser.add_option("-o", "--oldpolicy", dest="oldpolicy", metavar="FILE")
442 parser.add_option("-p", "--policy", dest="policy", metavar="FILE")
443 parser.add_option("-t", "--test", dest="tests", action="extend",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700444 help="Test options include "+str(Tests))
Dan Cashman91d398d2017-09-26 12:58:29 -0700445 parser.add_option("--fake-treble", action="store_true", dest="faketreble",
446 default=False)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700447
448 (options, args) = parser.parse_args()
449
450 if not options.policy:
Dan Cashman91d398d2017-09-26 12:58:29 -0700451 sys.exit("Must specify current monolithic policy file\n" + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700452 if not os.path.exists(options.policy):
453 sys.exit("Error: policy file " + options.policy + " does not exist\n"
454 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700455 if not options.file_contexts:
456 sys.exit("Error: Must specify file_contexts file(s)\n" + parser.usage)
457 for f in options.file_contexts:
458 if not os.path.exists(f):
459 sys.exit("Error: File_contexts file " + f + " does not exist\n" +
460 parser.usage)
461
Tri Voe3f4f772018-09-28 17:21:08 -0700462 # Mapping files and public platform policy are only necessary for the
463 # TrebleCompatMapping test.
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100464 if options.tests is None or options.tests == "TrebleCompatMapping":
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800465 if not options.basepolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700466 sys.exit("Must specify the current platform-only policy file\n"
467 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800468 if not options.mapping:
Tri Voe3f4f772018-09-28 17:21:08 -0700469 sys.exit("Must specify a compatibility mapping file\n"
470 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800471 if not options.oldpolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700472 sys.exit("Must specify the previous monolithic policy file\n"
473 + parser.usage)
474 if not options.base_pub_policy:
475 sys.exit("Must specify the current platform-only public policy "
476 + ".cil file\n" + parser.usage)
Inseob Kim6fa8efd2021-12-29 13:56:14 +0900477 basepol = policy.Policy(options.basepolicy, None, libpath)
478 oldpol = policy.Policy(options.oldpolicy, None, libpath)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800479 mapping = mini_parser.MiniCilParser(options.mapping)
Tri Voe3f4f772018-09-28 17:21:08 -0700480 pubpol = mini_parser.MiniCilParser(options.base_pub_policy)
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100481 test_policy.compatSetup(basepol, oldpol, mapping, pubpol.types)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800482
Dan Cashman91d398d2017-09-26 12:58:29 -0700483 if options.faketreble:
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100484 test_policy.FakeTreble = True
Dan Cashman91d398d2017-09-26 12:58:29 -0700485
Inseob Kim6fa8efd2021-12-29 13:56:14 +0900486 pol = policy.Policy(options.policy, options.file_contexts, libpath)
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100487 test_policy.setup(pol)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700488
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700489 if DEBUG:
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100490 test_policy.PrintScontexts()
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700491
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700492 results = ""
493 # If an individual test is not specified, run all tests.
Dan Cashman91d398d2017-09-26 12:58:29 -0700494 if options.tests is None:
495 for t in Tests.values():
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100496 results += t(test_policy)
Dan Cashman91d398d2017-09-26 12:58:29 -0700497 else:
498 for tn in options.tests:
499 t = Tests.get(tn)
500 if t:
Thiébaud Weksteendab3b1a2023-03-06 13:54:07 +1100501 results += t(test_policy)
Dan Cashman91d398d2017-09-26 12:58:29 -0700502 else:
503 err = "Error: unknown test: " + tn + "\n"
504 err += "Available tests:\n"
505 for tn in Tests.keys():
506 err += tn + "\n"
507 sys.exit(err)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700508
509 if len(results) > 0:
510 sys.exit(results)
Inseob Kim4912a242022-07-25 11:30:02 +0900511
512if __name__ == '__main__':
513 temp_dir = tempfile.mkdtemp()
514 try:
515 libname = "libsepolwrap" + SHARED_LIB_EXTENSION
516 libpath = os.path.join(temp_dir, libname)
517 with open(libpath, "wb") as f:
518 blob = pkgutil.get_data("treble_sepolicy_tests", libname)
519 if not blob:
520 sys.exit("Error: libsepolwrap does not exist. Is this binary corrupted?\n")
521 f.write(blob)
522 do_main(libpath)
523 finally:
524 shutil.rmtree(temp_dir)