blob: 27e92b1036ff97323f6a5d61a97cfbd04dbd4ba5 [file] [log] [blame]
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -07001from optparse import OptionParser
2from optparse import Option, OptionValueError
3import os
Dan Cashman91d398d2017-09-26 12:58:29 -07004import mini_parser
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -07005import policy
Dan Cashman91d398d2017-09-26 12:58:29 -07006from policy import MatchPathPrefix
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -07007import re
8import sys
9
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070010DEBUG=False
11
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070012'''
13Use file_contexts and policy to verify Treble requirements
14are not violated.
15'''
Joel Galensonb0d74a12020-07-27 09:30:34 -070016coredomainAllowlist = {
Steven Moreland000ec932020-04-02 16:20:31 -070017 # TODO: how do we make sure vendor_init doesn't have bad coupling with
18 # /vendor? It is the only system process which is not coredomain.
Tom Cherry9c778042018-01-25 11:31:09 -080019 'vendor_init',
Joel Galensonb0d74a12020-07-27 09:30:34 -070020 # TODO(b/152813275): need to avoid allowlist for rootdir
Steven Moreland000ec932020-04-02 16:20:31 -070021 "modprobe",
22 "slideshow",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070023 }
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070024
25class scontext:
26 def __init__(self):
27 self.fromSystem = False
28 self.fromVendor = False
29 self.coredomain = False
30 self.appdomain = False
31 self.attributes = set()
32 self.entrypoints = []
33 self.entrypointpaths = []
Steven Moreland000ec932020-04-02 16:20:31 -070034 self.error = ""
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070035
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070036def PrintScontexts():
37 for d in sorted(alldomains.keys()):
38 sctx = alldomains[d]
39 print d
40 print "\tcoredomain="+str(sctx.coredomain)
41 print "\tappdomain="+str(sctx.appdomain)
42 print "\tfromSystem="+str(sctx.fromSystem)
43 print "\tfromVendor="+str(sctx.fromVendor)
44 print "\tattributes="+str(sctx.attributes)
45 print "\tentrypoints="+str(sctx.entrypoints)
46 print "\tentrypointpaths="
47 if sctx.entrypointpaths is not None:
48 for path in sctx.entrypointpaths:
49 print "\t\t"+str(path)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070050
51alldomains = {}
52coredomains = set()
53appdomains = set()
54vendordomains = set()
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080055pol = None
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070056
Dan Cashman91d398d2017-09-26 12:58:29 -070057# compat vars
58alltypes = set()
59oldalltypes = set()
60compatMapping = None
Tri Voe3f4f772018-09-28 17:21:08 -070061pubtypes = set()
Dan Cashman91d398d2017-09-26 12:58:29 -070062
63# Distinguish between PRODUCT_FULL_TREBLE and PRODUCT_FULL_TREBLE_OVERRIDE
64FakeTreble = False
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070065
66def GetAllDomains(pol):
67 global alldomains
68 for result in pol.QueryTypeAttribute("domain", True):
69 alldomains[result] = scontext()
70
71def GetAppDomains():
72 global appdomains
73 global alldomains
74 for d in alldomains:
75 # The application of the "appdomain" attribute is trusted because core
76 # selinux policy contains neverallow rules that enforce that only zygote
77 # and runas spawned processes may transition to processes that have
78 # the appdomain attribute.
79 if "appdomain" in alldomains[d].attributes:
80 alldomains[d].appdomain = True
81 appdomains.add(d)
82
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070083def GetCoreDomains():
84 global alldomains
85 global coredomains
86 for d in alldomains:
Steven Moreland000ec932020-04-02 16:20:31 -070087 domain = alldomains[d]
Dan Cashman91d398d2017-09-26 12:58:29 -070088 # TestCoredomainViolations will verify if coredomain was incorrectly
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070089 # applied.
Steven Moreland000ec932020-04-02 16:20:31 -070090 if "coredomain" in domain.attributes:
91 domain.coredomain = True
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070092 coredomains.add(d)
93 # check whether domains are executed off of /system or /vendor
Joel Galensonb0d74a12020-07-27 09:30:34 -070094 if d in coredomainAllowlist:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070095 continue
Steven Moreland000ec932020-04-02 16:20:31 -070096 # TODO(b/153112003): add checks to prevent app domains from being
97 # incorrectly labeled as coredomain. Apps don't have entrypoints as
98 # they're always dynamically transitioned to by zygote.
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070099 if d in appdomains:
100 continue
Steven Moreland000ec932020-04-02 16:20:31 -0700101 # TODO(b/153112747): need to handle cases where there is a dynamic
102 # transition OR there happens to be no context in AOSP files.
103 if not domain.entrypointpaths:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700104 continue
Steven Moreland000ec932020-04-02 16:20:31 -0700105
106 for path in domain.entrypointpaths:
107 vendor = any(MatchPathPrefix(path, prefix) for prefix in
108 ["/vendor", "/odm"])
109 system = any(MatchPathPrefix(path, prefix) for prefix in
110 ["/init", "/system_ext", "/product" ])
111
112 # only mark entrypoint as system if it is not in legacy /system/vendor
113 if MatchPathPrefix(path, "/system/vendor"):
114 vendor = True
115 elif MatchPathPrefix(path, "/system"):
116 system = True
117
118 if not vendor and not system:
119 domain.error += "Unrecognized entrypoint for " + d + " at " + path + "\n"
120
121 domain.fromSystem = domain.fromSystem or system
122 domain.fromVendor = domain.fromVendor or vendor
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700123
124###
125# Add the entrypoint type and path(s) to each domain.
126#
127def GetDomainEntrypoints(pol):
128 global alldomains
Dan Cashman91d398d2017-09-26 12:58:29 -0700129 for x in pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])):
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700130 if not x.sctx in alldomains:
131 continue
132 alldomains[x.sctx].entrypoints.append(str(x.tctx))
133 # postinstall_file represents a special case specific to A/B OTAs.
134 # Update_engine mounts a partition and relabels it postinstall_file.
135 # There is no file_contexts entry associated with postinstall_file
136 # so skip the lookup.
137 if x.tctx == "postinstall_file":
138 continue
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700139 entrypointpath = pol.QueryFc(x.tctx)
140 if not entrypointpath:
141 continue
142 alldomains[x.sctx].entrypointpaths.extend(entrypointpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700143###
144# Get attributes associated with each domain
145#
146def GetAttributes(pol):
147 global alldomains
148 for domain in alldomains:
149 for result in pol.QueryTypeAttribute(domain, False):
150 alldomains[domain].attributes.add(result)
151
Dan Cashman91d398d2017-09-26 12:58:29 -0700152def GetAllTypes(pol, oldpol):
153 global alltypes
154 global oldalltypes
155 alltypes = pol.GetAllTypes(False)
156 oldalltypes = oldpol.GetAllTypes(False)
157
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700158def setup(pol):
159 GetAllDomains(pol)
160 GetAttributes(pol)
161 GetDomainEntrypoints(pol)
162 GetAppDomains()
163 GetCoreDomains()
164
Dan Cashman91d398d2017-09-26 12:58:29 -0700165# setup for the policy compatibility tests
Tri Voe3f4f772018-09-28 17:21:08 -0700166def compatSetup(pol, oldpol, mapping, types):
Dan Cashman91d398d2017-09-26 12:58:29 -0700167 global compatMapping
Tri Voe3f4f772018-09-28 17:21:08 -0700168 global pubtypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700169
170 GetAllTypes(pol, oldpol)
171 compatMapping = mapping
Tri Voe3f4f772018-09-28 17:21:08 -0700172 pubtypes = types
Dan Cashman91d398d2017-09-26 12:58:29 -0700173
174def DomainsWithAttribute(attr):
175 global alldomains
176 domains = []
177 for domain in alldomains:
178 if attr in alldomains[domain].attributes:
179 domains.append(domain)
180 return domains
181
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700182#############################################################
183# Tests
184#############################################################
185def TestCoredomainViolations():
186 global alldomains
187 # verify that all domains launched from /system have the coredomain
188 # attribute
189 ret = ""
Steven Moreland000ec932020-04-02 16:20:31 -0700190
191 for d in alldomains:
192 domain = alldomains[d]
193 if domain.fromSystem and domain.fromVendor:
194 ret += "The following domain is system and vendor: " + d + "\n"
195
196 for domain in alldomains.values():
197 ret += domain.error
198
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700199 violators = []
200 for d in alldomains:
201 domain = alldomains[d]
202 if domain.fromSystem and "coredomain" not in domain.attributes:
203 violators.append(d);
204 if len(violators) > 0:
205 ret += "The following domain(s) must be associated with the "
206 ret += "\"coredomain\" attribute because they are executed off of "
207 ret += "/system:\n"
208 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
209
210 # verify that all domains launched form /vendor do not have the coredomain
211 # attribute
212 violators = []
213 for d in alldomains:
214 domain = alldomains[d]
215 if domain.fromVendor and "coredomain" in domain.attributes:
216 violators.append(d)
217 if len(violators) > 0:
218 ret += "The following domains must not be associated with the "
219 ret += "\"coredomain\" attribute because they are executed off of "
220 ret += "/vendor or /system/vendor:\n"
221 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
222
223 return ret
224
225###
Tri Voe3f4f772018-09-28 17:21:08 -0700226# Make sure that any new public type introduced in the new policy that was not
227# present in the old policy has been recorded in the mapping file.
Dan Cashman91d398d2017-09-26 12:58:29 -0700228def TestNoUnmappedNewTypes():
229 global alltypes
230 global oldalltypes
231 global compatMapping
Tri Voe3f4f772018-09-28 17:21:08 -0700232 global pubtypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700233 newt = alltypes - oldalltypes
234 ret = ""
235 violators = []
236
237 for n in newt:
Tri Voe3f4f772018-09-28 17:21:08 -0700238 if n in pubtypes and compatMapping.rTypeattributesets.get(n) is None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700239 violators.append(n)
240
241 if len(violators) > 0:
Tri Voe3f4f772018-09-28 17:21:08 -0700242 ret += "SELinux: The following public types were found added to the "
243 ret += "policy without an entry into the compatibility mapping file(s) "
Tri Vo438684b2018-09-29 17:47:10 -0700244 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
245 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800246 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
247 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700248 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/781036\n"
249 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/852612\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700250 return ret
251
252###
253# Make sure that any public type removed in the current policy has its
254# declaration added to the mapping file for use in non-platform policy
255def TestNoUnmappedRmTypes():
256 global alltypes
257 global oldalltypes
258 global compatMapping
259 rmt = oldalltypes - alltypes
260 ret = ""
261 violators = []
262
263 for o in rmt:
264 if o in compatMapping.pubtypes and not o in compatMapping.types:
265 violators.append(o)
266
267 if len(violators) > 0:
268 ret += "SELinux: The following formerly public types were removed from "
269 ret += "policy without a declaration in the compatibility mapping "
Tri Vo438684b2018-09-29 17:47:10 -0700270 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
271 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800272 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
273 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700274 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/822743\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700275 return ret
276
277def TestTrebleCompatMapping():
278 ret = TestNoUnmappedNewTypes()
279 ret += TestNoUnmappedRmTypes()
280 return ret
281
282def TestViolatorAttribute(attribute):
283 global FakeTreble
284 ret = ""
285 if FakeTreble:
286 return ret
287
288 violators = DomainsWithAttribute(attribute)
289 if len(violators) > 0:
290 ret += "SELinux: The following domains violate the Treble ban "
291 ret += "against use of the " + attribute + " attribute: "
292 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
293 return ret
294
295def TestViolatorAttributes():
Steven Moreland5c0a0a82019-05-13 17:06:50 -0700296 ret = ""
Dan Cashman91d398d2017-09-26 12:58:29 -0700297 ret += TestViolatorAttribute("socket_between_core_and_vendor_violators")
298 ret += TestViolatorAttribute("vendor_executes_system_violators")
299 return ret
300
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800301# TODO move this to sepolicy_tests
302def TestCoreDataTypeViolations():
303 global pol
304 return pol.AssertPathTypesDoNotHaveAttr(["/data/vendor/", "/data/vendor_ce/",
305 "/data/vendor_de/"], [], "core_data_file_type")
306
Dan Cashman91d398d2017-09-26 12:58:29 -0700307###
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700308# extend OptionParser to allow the same option flag to be used multiple times.
309# This is used to allow multiple file_contexts files and tests to be
310# specified.
311#
312class MultipleOption(Option):
313 ACTIONS = Option.ACTIONS + ("extend",)
314 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
315 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
316 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
317
318 def take_action(self, action, dest, opt, value, values, parser):
319 if action == "extend":
320 values.ensure_value(dest, []).append(value)
321 else:
322 Option.take_action(self, action, dest, opt, value, values, parser)
323
Dan Cashman91d398d2017-09-26 12:58:29 -0700324Tests = {"CoredomainViolations": TestCoredomainViolations,
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800325 "CoreDatatypeViolations": TestCoreDataTypeViolations,
Dan Cashman91d398d2017-09-26 12:58:29 -0700326 "TrebleCompatMapping": TestTrebleCompatMapping,
327 "ViolatorAttributes": TestViolatorAttributes}
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700328
329if __name__ == '__main__':
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700330 usage = "treble_sepolicy_tests -l $(ANDROID_HOST_OUT)/lib64/libsepolwrap.so "
Dan Cashman91d398d2017-09-26 12:58:29 -0700331 usage += "-f nonplat_file_contexts -f plat_file_contexts "
332 usage += "-p curr_policy -b base_policy -o old_policy "
333 usage +="-m mapping file [--test test] [--help]"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700334 parser = OptionParser(option_class=MultipleOption, usage=usage)
Dan Cashman91d398d2017-09-26 12:58:29 -0700335 parser.add_option("-b", "--basepolicy", dest="basepolicy", metavar="FILE")
Tri Voe3f4f772018-09-28 17:21:08 -0700336 parser.add_option("-u", "--base-pub-policy", dest="base_pub_policy",
337 metavar="FILE")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700338 parser.add_option("-f", "--file_contexts", dest="file_contexts",
339 metavar="FILE", action="extend", type="string")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700340 parser.add_option("-l", "--library-path", dest="libpath", metavar="FILE")
Dan Cashman91d398d2017-09-26 12:58:29 -0700341 parser.add_option("-m", "--mapping", dest="mapping", metavar="FILE")
342 parser.add_option("-o", "--oldpolicy", dest="oldpolicy", metavar="FILE")
343 parser.add_option("-p", "--policy", dest="policy", metavar="FILE")
344 parser.add_option("-t", "--test", dest="tests", action="extend",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700345 help="Test options include "+str(Tests))
Dan Cashman91d398d2017-09-26 12:58:29 -0700346 parser.add_option("--fake-treble", action="store_true", dest="faketreble",
347 default=False)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700348
349 (options, args) = parser.parse_args()
350
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700351 if not options.libpath:
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700352 sys.exit("Must specify path to libsepolwrap library\n" + parser.usage)
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700353 if not os.path.exists(options.libpath):
354 sys.exit("Error: library-path " + options.libpath + " does not exist\n"
355 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700356 if not options.policy:
Dan Cashman91d398d2017-09-26 12:58:29 -0700357 sys.exit("Must specify current monolithic policy file\n" + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700358 if not os.path.exists(options.policy):
359 sys.exit("Error: policy file " + options.policy + " does not exist\n"
360 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700361 if not options.file_contexts:
362 sys.exit("Error: Must specify file_contexts file(s)\n" + parser.usage)
363 for f in options.file_contexts:
364 if not os.path.exists(f):
365 sys.exit("Error: File_contexts file " + f + " does not exist\n" +
366 parser.usage)
367
Tri Voe3f4f772018-09-28 17:21:08 -0700368 # Mapping files and public platform policy are only necessary for the
369 # TrebleCompatMapping test.
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800370 if options.tests is None or options.tests is "TrebleCompatMapping":
371 if not options.basepolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700372 sys.exit("Must specify the current platform-only policy file\n"
373 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800374 if not options.mapping:
Tri Voe3f4f772018-09-28 17:21:08 -0700375 sys.exit("Must specify a compatibility mapping file\n"
376 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800377 if not options.oldpolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700378 sys.exit("Must specify the previous monolithic policy file\n"
379 + parser.usage)
380 if not options.base_pub_policy:
381 sys.exit("Must specify the current platform-only public policy "
382 + ".cil file\n" + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800383 basepol = policy.Policy(options.basepolicy, None, options.libpath)
384 oldpol = policy.Policy(options.oldpolicy, None, options.libpath)
385 mapping = mini_parser.MiniCilParser(options.mapping)
Tri Voe3f4f772018-09-28 17:21:08 -0700386 pubpol = mini_parser.MiniCilParser(options.base_pub_policy)
387 compatSetup(basepol, oldpol, mapping, pubpol.types)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800388
Dan Cashman91d398d2017-09-26 12:58:29 -0700389 if options.faketreble:
390 FakeTreble = True
391
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700392 pol = policy.Policy(options.policy, options.file_contexts, options.libpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700393 setup(pol)
394
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700395 if DEBUG:
396 PrintScontexts()
397
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700398 results = ""
399 # If an individual test is not specified, run all tests.
Dan Cashman91d398d2017-09-26 12:58:29 -0700400 if options.tests is None:
401 for t in Tests.values():
402 results += t()
403 else:
404 for tn in options.tests:
405 t = Tests.get(tn)
406 if t:
407 results += t()
408 else:
409 err = "Error: unknown test: " + tn + "\n"
410 err += "Available tests:\n"
411 for tn in Tests.keys():
412 err += tn + "\n"
413 sys.exit(err)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700414
415 if len(results) > 0:
416 sys.exit(results)