blob: 1c5b8e284afc49664f654160ab3af7d93ad2a3ce [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
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070019import policy
Dan Cashman91d398d2017-09-26 12:58:29 -070020from policy import MatchPathPrefix
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070021import re
22import sys
23
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070024DEBUG=False
25
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070026'''
27Use file_contexts and policy to verify Treble requirements
28are not violated.
29'''
Joel Galensonb0d74a12020-07-27 09:30:34 -070030coredomainAllowlist = {
Steven Moreland000ec932020-04-02 16:20:31 -070031 # TODO: how do we make sure vendor_init doesn't have bad coupling with
32 # /vendor? It is the only system process which is not coredomain.
Tom Cherry9c778042018-01-25 11:31:09 -080033 'vendor_init',
Joel Galensonb0d74a12020-07-27 09:30:34 -070034 # TODO(b/152813275): need to avoid allowlist for rootdir
Steven Moreland000ec932020-04-02 16:20:31 -070035 "modprobe",
36 "slideshow",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070037 }
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070038
39class scontext:
40 def __init__(self):
41 self.fromSystem = False
42 self.fromVendor = False
43 self.coredomain = False
44 self.appdomain = False
45 self.attributes = set()
46 self.entrypoints = []
47 self.entrypointpaths = []
Steven Moreland000ec932020-04-02 16:20:31 -070048 self.error = ""
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070049
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070050def PrintScontexts():
51 for d in sorted(alldomains.keys()):
52 sctx = alldomains[d]
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +110053 print(d)
54 print("\tcoredomain="+str(sctx.coredomain))
55 print("\tappdomain="+str(sctx.appdomain))
56 print("\tfromSystem="+str(sctx.fromSystem))
57 print("\tfromVendor="+str(sctx.fromVendor))
58 print("\tattributes="+str(sctx.attributes))
59 print("\tentrypoints="+str(sctx.entrypoints))
60 print("\tentrypointpaths=")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070061 if sctx.entrypointpaths is not None:
62 for path in sctx.entrypointpaths:
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +110063 print("\t\t"+str(path))
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070064
65alldomains = {}
66coredomains = set()
67appdomains = set()
68vendordomains = set()
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080069pol = None
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070070
Dan Cashman91d398d2017-09-26 12:58:29 -070071# compat vars
72alltypes = set()
73oldalltypes = set()
74compatMapping = None
Tri Voe3f4f772018-09-28 17:21:08 -070075pubtypes = set()
Dan Cashman91d398d2017-09-26 12:58:29 -070076
77# Distinguish between PRODUCT_FULL_TREBLE and PRODUCT_FULL_TREBLE_OVERRIDE
78FakeTreble = False
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070079
80def GetAllDomains(pol):
81 global alldomains
82 for result in pol.QueryTypeAttribute("domain", True):
83 alldomains[result] = scontext()
84
85def GetAppDomains():
86 global appdomains
87 global alldomains
88 for d in alldomains:
89 # The application of the "appdomain" attribute is trusted because core
90 # selinux policy contains neverallow rules that enforce that only zygote
91 # and runas spawned processes may transition to processes that have
92 # the appdomain attribute.
93 if "appdomain" in alldomains[d].attributes:
94 alldomains[d].appdomain = True
95 appdomains.add(d)
96
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070097def GetCoreDomains():
98 global alldomains
99 global coredomains
100 for d in alldomains:
Steven Moreland000ec932020-04-02 16:20:31 -0700101 domain = alldomains[d]
Dan Cashman91d398d2017-09-26 12:58:29 -0700102 # TestCoredomainViolations will verify if coredomain was incorrectly
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700103 # applied.
Steven Moreland000ec932020-04-02 16:20:31 -0700104 if "coredomain" in domain.attributes:
105 domain.coredomain = True
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700106 coredomains.add(d)
107 # check whether domains are executed off of /system or /vendor
Joel Galensonb0d74a12020-07-27 09:30:34 -0700108 if d in coredomainAllowlist:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700109 continue
Steven Moreland000ec932020-04-02 16:20:31 -0700110 # TODO(b/153112003): add checks to prevent app domains from being
111 # incorrectly labeled as coredomain. Apps don't have entrypoints as
112 # they're always dynamically transitioned to by zygote.
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700113 if d in appdomains:
114 continue
Steven Moreland000ec932020-04-02 16:20:31 -0700115 # TODO(b/153112747): need to handle cases where there is a dynamic
116 # transition OR there happens to be no context in AOSP files.
117 if not domain.entrypointpaths:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700118 continue
Steven Moreland000ec932020-04-02 16:20:31 -0700119
120 for path in domain.entrypointpaths:
121 vendor = any(MatchPathPrefix(path, prefix) for prefix in
122 ["/vendor", "/odm"])
123 system = any(MatchPathPrefix(path, prefix) for prefix in
124 ["/init", "/system_ext", "/product" ])
125
126 # only mark entrypoint as system if it is not in legacy /system/vendor
127 if MatchPathPrefix(path, "/system/vendor"):
128 vendor = True
129 elif MatchPathPrefix(path, "/system"):
130 system = True
131
132 if not vendor and not system:
133 domain.error += "Unrecognized entrypoint for " + d + " at " + path + "\n"
134
135 domain.fromSystem = domain.fromSystem or system
136 domain.fromVendor = domain.fromVendor or vendor
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700137
138###
139# Add the entrypoint type and path(s) to each domain.
140#
141def GetDomainEntrypoints(pol):
142 global alldomains
Dan Cashman91d398d2017-09-26 12:58:29 -0700143 for x in pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])):
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700144 if not x.sctx in alldomains:
145 continue
146 alldomains[x.sctx].entrypoints.append(str(x.tctx))
147 # postinstall_file represents a special case specific to A/B OTAs.
148 # Update_engine mounts a partition and relabels it postinstall_file.
149 # There is no file_contexts entry associated with postinstall_file
150 # so skip the lookup.
151 if x.tctx == "postinstall_file":
152 continue
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700153 entrypointpath = pol.QueryFc(x.tctx)
154 if not entrypointpath:
155 continue
156 alldomains[x.sctx].entrypointpaths.extend(entrypointpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700157###
158# Get attributes associated with each domain
159#
160def GetAttributes(pol):
161 global alldomains
162 for domain in alldomains:
163 for result in pol.QueryTypeAttribute(domain, False):
164 alldomains[domain].attributes.add(result)
165
Dan Cashman91d398d2017-09-26 12:58:29 -0700166def GetAllTypes(pol, oldpol):
167 global alltypes
168 global oldalltypes
169 alltypes = pol.GetAllTypes(False)
170 oldalltypes = oldpol.GetAllTypes(False)
171
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700172def setup(pol):
173 GetAllDomains(pol)
174 GetAttributes(pol)
175 GetDomainEntrypoints(pol)
176 GetAppDomains()
177 GetCoreDomains()
178
Dan Cashman91d398d2017-09-26 12:58:29 -0700179# setup for the policy compatibility tests
Tri Voe3f4f772018-09-28 17:21:08 -0700180def compatSetup(pol, oldpol, mapping, types):
Dan Cashman91d398d2017-09-26 12:58:29 -0700181 global compatMapping
Tri Voe3f4f772018-09-28 17:21:08 -0700182 global pubtypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700183
184 GetAllTypes(pol, oldpol)
185 compatMapping = mapping
Tri Voe3f4f772018-09-28 17:21:08 -0700186 pubtypes = types
Dan Cashman91d398d2017-09-26 12:58:29 -0700187
188def DomainsWithAttribute(attr):
189 global alldomains
190 domains = []
191 for domain in alldomains:
192 if attr in alldomains[domain].attributes:
193 domains.append(domain)
194 return domains
195
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700196#############################################################
197# Tests
198#############################################################
199def TestCoredomainViolations():
200 global alldomains
201 # verify that all domains launched from /system have the coredomain
202 # attribute
203 ret = ""
Steven Moreland000ec932020-04-02 16:20:31 -0700204
205 for d in alldomains:
206 domain = alldomains[d]
207 if domain.fromSystem and domain.fromVendor:
208 ret += "The following domain is system and vendor: " + d + "\n"
209
210 for domain in alldomains.values():
211 ret += domain.error
212
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700213 violators = []
214 for d in alldomains:
215 domain = alldomains[d]
216 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 = []
227 for d in alldomains:
228 domain = alldomains[d]
229 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.
Dan Cashman91d398d2017-09-26 12:58:29 -0700242def TestNoUnmappedNewTypes():
243 global alltypes
244 global oldalltypes
245 global compatMapping
Tri Voe3f4f772018-09-28 17:21:08 -0700246 global pubtypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700247 newt = alltypes - oldalltypes
248 ret = ""
249 violators = []
250
251 for n in newt:
Tri Voe3f4f772018-09-28 17:21:08 -0700252 if n in pubtypes and compatMapping.rTypeattributesets.get(n) is None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700253 violators.append(n)
254
255 if len(violators) > 0:
Tri Voe3f4f772018-09-28 17:21:08 -0700256 ret += "SELinux: The following public types were found added to the "
257 ret += "policy without an entry into the compatibility mapping file(s) "
Tri Vo438684b2018-09-29 17:47:10 -0700258 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
259 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800260 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
261 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700262 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/781036\n"
263 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/852612\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700264 return ret
265
266###
267# Make sure that any public type removed in the current policy has its
268# declaration added to the mapping file for use in non-platform policy
269def TestNoUnmappedRmTypes():
270 global alltypes
271 global oldalltypes
272 global compatMapping
273 rmt = oldalltypes - alltypes
274 ret = ""
275 violators = []
276
277 for o in rmt:
278 if o in compatMapping.pubtypes and not o in compatMapping.types:
279 violators.append(o)
280
281 if len(violators) > 0:
282 ret += "SELinux: The following formerly public types were removed from "
283 ret += "policy without a declaration in the compatibility mapping "
Tri Vo438684b2018-09-29 17:47:10 -0700284 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
285 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800286 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
287 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700288 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/822743\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700289 return ret
290
291def TestTrebleCompatMapping():
292 ret = TestNoUnmappedNewTypes()
293 ret += TestNoUnmappedRmTypes()
294 return ret
295
296def TestViolatorAttribute(attribute):
297 global FakeTreble
298 ret = ""
299 if FakeTreble:
300 return ret
301
302 violators = DomainsWithAttribute(attribute)
303 if len(violators) > 0:
304 ret += "SELinux: The following domains violate the Treble ban "
305 ret += "against use of the " + attribute + " attribute: "
306 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
307 return ret
308
309def TestViolatorAttributes():
Steven Moreland5c0a0a82019-05-13 17:06:50 -0700310 ret = ""
Dan Cashman91d398d2017-09-26 12:58:29 -0700311 ret += TestViolatorAttribute("socket_between_core_and_vendor_violators")
312 ret += TestViolatorAttribute("vendor_executes_system_violators")
313 return ret
314
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800315# TODO move this to sepolicy_tests
316def TestCoreDataTypeViolations():
317 global pol
318 return pol.AssertPathTypesDoNotHaveAttr(["/data/vendor/", "/data/vendor_ce/",
319 "/data/vendor_de/"], [], "core_data_file_type")
320
Dan Cashman91d398d2017-09-26 12:58:29 -0700321###
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700322# extend OptionParser to allow the same option flag to be used multiple times.
323# This is used to allow multiple file_contexts files and tests to be
324# specified.
325#
326class MultipleOption(Option):
327 ACTIONS = Option.ACTIONS + ("extend",)
328 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
329 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
330 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
331
332 def take_action(self, action, dest, opt, value, values, parser):
333 if action == "extend":
334 values.ensure_value(dest, []).append(value)
335 else:
336 Option.take_action(self, action, dest, opt, value, values, parser)
337
Dan Cashman91d398d2017-09-26 12:58:29 -0700338Tests = {"CoredomainViolations": TestCoredomainViolations,
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800339 "CoreDatatypeViolations": TestCoreDataTypeViolations,
Dan Cashman91d398d2017-09-26 12:58:29 -0700340 "TrebleCompatMapping": TestTrebleCompatMapping,
341 "ViolatorAttributes": TestViolatorAttributes}
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700342
343if __name__ == '__main__':
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700344 usage = "treble_sepolicy_tests -l $(ANDROID_HOST_OUT)/lib64/libsepolwrap.so "
Dan Cashman91d398d2017-09-26 12:58:29 -0700345 usage += "-f nonplat_file_contexts -f plat_file_contexts "
346 usage += "-p curr_policy -b base_policy -o old_policy "
347 usage +="-m mapping file [--test test] [--help]"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700348 parser = OptionParser(option_class=MultipleOption, usage=usage)
Dan Cashman91d398d2017-09-26 12:58:29 -0700349 parser.add_option("-b", "--basepolicy", dest="basepolicy", metavar="FILE")
Tri Voe3f4f772018-09-28 17:21:08 -0700350 parser.add_option("-u", "--base-pub-policy", dest="base_pub_policy",
351 metavar="FILE")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700352 parser.add_option("-f", "--file_contexts", dest="file_contexts",
353 metavar="FILE", action="extend", type="string")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700354 parser.add_option("-l", "--library-path", dest="libpath", metavar="FILE")
Dan Cashman91d398d2017-09-26 12:58:29 -0700355 parser.add_option("-m", "--mapping", dest="mapping", metavar="FILE")
356 parser.add_option("-o", "--oldpolicy", dest="oldpolicy", metavar="FILE")
357 parser.add_option("-p", "--policy", dest="policy", metavar="FILE")
358 parser.add_option("-t", "--test", dest="tests", action="extend",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700359 help="Test options include "+str(Tests))
Dan Cashman91d398d2017-09-26 12:58:29 -0700360 parser.add_option("--fake-treble", action="store_true", dest="faketreble",
361 default=False)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700362
363 (options, args) = parser.parse_args()
364
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700365 if not options.libpath:
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700366 sys.exit("Must specify path to libsepolwrap library\n" + parser.usage)
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700367 if not os.path.exists(options.libpath):
368 sys.exit("Error: library-path " + options.libpath + " does not exist\n"
369 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700370 if not options.policy:
Dan Cashman91d398d2017-09-26 12:58:29 -0700371 sys.exit("Must specify current monolithic policy file\n" + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700372 if not os.path.exists(options.policy):
373 sys.exit("Error: policy file " + options.policy + " does not exist\n"
374 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700375 if not options.file_contexts:
376 sys.exit("Error: Must specify file_contexts file(s)\n" + parser.usage)
377 for f in options.file_contexts:
378 if not os.path.exists(f):
379 sys.exit("Error: File_contexts file " + f + " does not exist\n" +
380 parser.usage)
381
Tri Voe3f4f772018-09-28 17:21:08 -0700382 # Mapping files and public platform policy are only necessary for the
383 # TrebleCompatMapping test.
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100384 if options.tests is None or options.tests == "TrebleCompatMapping":
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800385 if not options.basepolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700386 sys.exit("Must specify the current platform-only policy file\n"
387 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800388 if not options.mapping:
Tri Voe3f4f772018-09-28 17:21:08 -0700389 sys.exit("Must specify a compatibility mapping file\n"
390 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800391 if not options.oldpolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700392 sys.exit("Must specify the previous monolithic policy file\n"
393 + parser.usage)
394 if not options.base_pub_policy:
395 sys.exit("Must specify the current platform-only public policy "
396 + ".cil file\n" + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800397 basepol = policy.Policy(options.basepolicy, None, options.libpath)
398 oldpol = policy.Policy(options.oldpolicy, None, options.libpath)
399 mapping = mini_parser.MiniCilParser(options.mapping)
Tri Voe3f4f772018-09-28 17:21:08 -0700400 pubpol = mini_parser.MiniCilParser(options.base_pub_policy)
401 compatSetup(basepol, oldpol, mapping, pubpol.types)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800402
Dan Cashman91d398d2017-09-26 12:58:29 -0700403 if options.faketreble:
404 FakeTreble = True
405
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700406 pol = policy.Policy(options.policy, options.file_contexts, options.libpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700407 setup(pol)
408
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700409 if DEBUG:
410 PrintScontexts()
411
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700412 results = ""
413 # If an individual test is not specified, run all tests.
Dan Cashman91d398d2017-09-26 12:58:29 -0700414 if options.tests is None:
415 for t in Tests.values():
416 results += t()
417 else:
418 for tn in options.tests:
419 t = Tests.get(tn)
420 if t:
421 results += t()
422 else:
423 err = "Error: unknown test: " + tn + "\n"
424 err += "Available tests:\n"
425 for tn in Tests.keys():
426 err += tn + "\n"
427 sys.exit(err)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700428
429 if len(results) > 0:
430 sys.exit(results)