blob: f721795432f2af465aa22e0b746e9390a442852b [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'''
16###
Steven Morelanda00530b2020-04-02 16:02:54 -070017# TODO: how do we make sure vendor_init doesn't have bad coupling with /vendor?
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070018coredomainWhitelist = {
Tom Cherry9c778042018-01-25 11:31:09 -080019 'vendor_init',
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070020 }
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070021
22class scontext:
23 def __init__(self):
24 self.fromSystem = False
25 self.fromVendor = False
26 self.coredomain = False
27 self.appdomain = False
28 self.attributes = set()
29 self.entrypoints = []
30 self.entrypointpaths = []
31
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070032def PrintScontexts():
33 for d in sorted(alldomains.keys()):
34 sctx = alldomains[d]
35 print d
36 print "\tcoredomain="+str(sctx.coredomain)
37 print "\tappdomain="+str(sctx.appdomain)
38 print "\tfromSystem="+str(sctx.fromSystem)
39 print "\tfromVendor="+str(sctx.fromVendor)
40 print "\tattributes="+str(sctx.attributes)
41 print "\tentrypoints="+str(sctx.entrypoints)
42 print "\tentrypointpaths="
43 if sctx.entrypointpaths is not None:
44 for path in sctx.entrypointpaths:
45 print "\t\t"+str(path)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070046
47alldomains = {}
48coredomains = set()
49appdomains = set()
50vendordomains = set()
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080051pol = None
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070052
Dan Cashman91d398d2017-09-26 12:58:29 -070053# compat vars
54alltypes = set()
55oldalltypes = set()
56compatMapping = None
Tri Voe3f4f772018-09-28 17:21:08 -070057pubtypes = set()
Dan Cashman91d398d2017-09-26 12:58:29 -070058
59# Distinguish between PRODUCT_FULL_TREBLE and PRODUCT_FULL_TREBLE_OVERRIDE
60FakeTreble = False
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070061
62def GetAllDomains(pol):
63 global alldomains
64 for result in pol.QueryTypeAttribute("domain", True):
65 alldomains[result] = scontext()
66
67def GetAppDomains():
68 global appdomains
69 global alldomains
70 for d in alldomains:
71 # The application of the "appdomain" attribute is trusted because core
72 # selinux policy contains neverallow rules that enforce that only zygote
73 # and runas spawned processes may transition to processes that have
74 # the appdomain attribute.
75 if "appdomain" in alldomains[d].attributes:
76 alldomains[d].appdomain = True
77 appdomains.add(d)
78
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070079def GetCoreDomains():
80 global alldomains
81 global coredomains
82 for d in alldomains:
Dan Cashman91d398d2017-09-26 12:58:29 -070083 # TestCoredomainViolations will verify if coredomain was incorrectly
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070084 # applied.
85 if "coredomain" in alldomains[d].attributes:
86 alldomains[d].coredomain = True
87 coredomains.add(d)
88 # check whether domains are executed off of /system or /vendor
89 if d in coredomainWhitelist:
90 continue
91 # TODO, add checks to prevent app domains from being incorrectly
92 # labeled as coredomain. Apps don't have entrypoints as they're always
93 # dynamically transitioned to by zygote.
94 if d in appdomains:
95 continue
96 if not alldomains[d].entrypointpaths:
97 continue
98 for path in alldomains[d].entrypointpaths:
99 # Processes with entrypoint on /system
100 if ((MatchPathPrefix(path, "/system") and not
101 MatchPathPrefix(path, "/system/vendor")) or
102 MatchPathPrefix(path, "/init") or
103 MatchPathPrefix(path, "/charger")):
104 alldomains[d].fromSystem = True
105 # Processes with entrypoint on /vendor or /system/vendor
106 if (MatchPathPrefix(path, "/vendor") or
107 MatchPathPrefix(path, "/system/vendor")):
108 alldomains[d].fromVendor = True
109
110###
111# Add the entrypoint type and path(s) to each domain.
112#
113def GetDomainEntrypoints(pol):
114 global alldomains
Dan Cashman91d398d2017-09-26 12:58:29 -0700115 for x in pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])):
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700116 if not x.sctx in alldomains:
117 continue
118 alldomains[x.sctx].entrypoints.append(str(x.tctx))
119 # postinstall_file represents a special case specific to A/B OTAs.
120 # Update_engine mounts a partition and relabels it postinstall_file.
121 # There is no file_contexts entry associated with postinstall_file
122 # so skip the lookup.
123 if x.tctx == "postinstall_file":
124 continue
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700125 entrypointpath = pol.QueryFc(x.tctx)
126 if not entrypointpath:
127 continue
128 alldomains[x.sctx].entrypointpaths.extend(entrypointpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700129###
130# Get attributes associated with each domain
131#
132def GetAttributes(pol):
133 global alldomains
134 for domain in alldomains:
135 for result in pol.QueryTypeAttribute(domain, False):
136 alldomains[domain].attributes.add(result)
137
Dan Cashman91d398d2017-09-26 12:58:29 -0700138def GetAllTypes(pol, oldpol):
139 global alltypes
140 global oldalltypes
141 alltypes = pol.GetAllTypes(False)
142 oldalltypes = oldpol.GetAllTypes(False)
143
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700144def setup(pol):
145 GetAllDomains(pol)
146 GetAttributes(pol)
147 GetDomainEntrypoints(pol)
148 GetAppDomains()
149 GetCoreDomains()
150
Dan Cashman91d398d2017-09-26 12:58:29 -0700151# setup for the policy compatibility tests
Tri Voe3f4f772018-09-28 17:21:08 -0700152def compatSetup(pol, oldpol, mapping, types):
Dan Cashman91d398d2017-09-26 12:58:29 -0700153 global compatMapping
Tri Voe3f4f772018-09-28 17:21:08 -0700154 global pubtypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700155
156 GetAllTypes(pol, oldpol)
157 compatMapping = mapping
Tri Voe3f4f772018-09-28 17:21:08 -0700158 pubtypes = types
Dan Cashman91d398d2017-09-26 12:58:29 -0700159
160def DomainsWithAttribute(attr):
161 global alldomains
162 domains = []
163 for domain in alldomains:
164 if attr in alldomains[domain].attributes:
165 domains.append(domain)
166 return domains
167
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700168#############################################################
169# Tests
170#############################################################
171def TestCoredomainViolations():
172 global alldomains
173 # verify that all domains launched from /system have the coredomain
174 # attribute
175 ret = ""
176 violators = []
177 for d in alldomains:
178 domain = alldomains[d]
179 if domain.fromSystem and "coredomain" not in domain.attributes:
180 violators.append(d);
181 if len(violators) > 0:
182 ret += "The following domain(s) must be associated with the "
183 ret += "\"coredomain\" attribute because they are executed off of "
184 ret += "/system:\n"
185 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
186
187 # verify that all domains launched form /vendor do not have the coredomain
188 # attribute
189 violators = []
190 for d in alldomains:
191 domain = alldomains[d]
192 if domain.fromVendor and "coredomain" in domain.attributes:
193 violators.append(d)
194 if len(violators) > 0:
195 ret += "The following domains must not be associated with the "
196 ret += "\"coredomain\" attribute because they are executed off of "
197 ret += "/vendor or /system/vendor:\n"
198 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
199
200 return ret
201
202###
Tri Voe3f4f772018-09-28 17:21:08 -0700203# Make sure that any new public type introduced in the new policy that was not
204# present in the old policy has been recorded in the mapping file.
Dan Cashman91d398d2017-09-26 12:58:29 -0700205def TestNoUnmappedNewTypes():
206 global alltypes
207 global oldalltypes
208 global compatMapping
Tri Voe3f4f772018-09-28 17:21:08 -0700209 global pubtypes
Dan Cashman91d398d2017-09-26 12:58:29 -0700210 newt = alltypes - oldalltypes
211 ret = ""
212 violators = []
213
214 for n in newt:
Tri Voe3f4f772018-09-28 17:21:08 -0700215 if n in pubtypes and compatMapping.rTypeattributesets.get(n) is None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700216 violators.append(n)
217
218 if len(violators) > 0:
Tri Voe3f4f772018-09-28 17:21:08 -0700219 ret += "SELinux: The following public types were found added to the "
220 ret += "policy without an entry into the compatibility mapping file(s) "
Tri Vo438684b2018-09-29 17:47:10 -0700221 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
222 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800223 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
224 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700225 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/781036\n"
226 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/852612\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700227 return ret
228
229###
230# Make sure that any public type removed in the current policy has its
231# declaration added to the mapping file for use in non-platform policy
232def TestNoUnmappedRmTypes():
233 global alltypes
234 global oldalltypes
235 global compatMapping
236 rmt = oldalltypes - alltypes
237 ret = ""
238 violators = []
239
240 for o in rmt:
241 if o in compatMapping.pubtypes and not o in compatMapping.types:
242 violators.append(o)
243
244 if len(violators) > 0:
245 ret += "SELinux: The following formerly public types were removed from "
246 ret += "policy without a declaration in the compatibility mapping "
Tri Vo438684b2018-09-29 17:47:10 -0700247 ret += "found in private/compat/V.v/V.v[.ignore].cil, where V.v is the "
248 ret += "latest API level.\n"
Tri Vo14519382019-01-06 18:17:32 -0800249 ret += " ".join(str(x) for x in sorted(violators)) + "\n\n"
250 ret += "See examples of how to fix this:\n"
Tri Vo462c9c42019-08-09 10:27:46 -0700251 ret += "https://android-review.googlesource.com/c/platform/system/sepolicy/+/822743\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700252 return ret
253
254def TestTrebleCompatMapping():
255 ret = TestNoUnmappedNewTypes()
256 ret += TestNoUnmappedRmTypes()
257 return ret
258
259def TestViolatorAttribute(attribute):
260 global FakeTreble
261 ret = ""
262 if FakeTreble:
263 return ret
264
265 violators = DomainsWithAttribute(attribute)
266 if len(violators) > 0:
267 ret += "SELinux: The following domains violate the Treble ban "
268 ret += "against use of the " + attribute + " attribute: "
269 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
270 return ret
271
272def TestViolatorAttributes():
273 ret = TestViolatorAttribute("binder_in_vendor_violators")
274 ret += TestViolatorAttribute("socket_between_core_and_vendor_violators")
275 ret += TestViolatorAttribute("vendor_executes_system_violators")
276 return ret
277
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800278# TODO move this to sepolicy_tests
279def TestCoreDataTypeViolations():
280 global pol
281 return pol.AssertPathTypesDoNotHaveAttr(["/data/vendor/", "/data/vendor_ce/",
282 "/data/vendor_de/"], [], "core_data_file_type")
283
Dan Cashman91d398d2017-09-26 12:58:29 -0700284###
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700285# extend OptionParser to allow the same option flag to be used multiple times.
286# This is used to allow multiple file_contexts files and tests to be
287# specified.
288#
289class MultipleOption(Option):
290 ACTIONS = Option.ACTIONS + ("extend",)
291 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
292 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
293 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
294
295 def take_action(self, action, dest, opt, value, values, parser):
296 if action == "extend":
297 values.ensure_value(dest, []).append(value)
298 else:
299 Option.take_action(self, action, dest, opt, value, values, parser)
300
Dan Cashman91d398d2017-09-26 12:58:29 -0700301Tests = {"CoredomainViolations": TestCoredomainViolations,
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800302 "CoreDatatypeViolations": TestCoreDataTypeViolations,
Dan Cashman91d398d2017-09-26 12:58:29 -0700303 "TrebleCompatMapping": TestTrebleCompatMapping,
304 "ViolatorAttributes": TestViolatorAttributes}
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700305
306if __name__ == '__main__':
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700307 usage = "treble_sepolicy_tests -l $(ANDROID_HOST_OUT)/lib64/libsepolwrap.so "
Dan Cashman91d398d2017-09-26 12:58:29 -0700308 usage += "-f nonplat_file_contexts -f plat_file_contexts "
309 usage += "-p curr_policy -b base_policy -o old_policy "
310 usage +="-m mapping file [--test test] [--help]"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700311 parser = OptionParser(option_class=MultipleOption, usage=usage)
Dan Cashman91d398d2017-09-26 12:58:29 -0700312 parser.add_option("-b", "--basepolicy", dest="basepolicy", metavar="FILE")
Tri Voe3f4f772018-09-28 17:21:08 -0700313 parser.add_option("-u", "--base-pub-policy", dest="base_pub_policy",
314 metavar="FILE")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700315 parser.add_option("-f", "--file_contexts", dest="file_contexts",
316 metavar="FILE", action="extend", type="string")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700317 parser.add_option("-l", "--library-path", dest="libpath", metavar="FILE")
Dan Cashman91d398d2017-09-26 12:58:29 -0700318 parser.add_option("-m", "--mapping", dest="mapping", metavar="FILE")
319 parser.add_option("-o", "--oldpolicy", dest="oldpolicy", metavar="FILE")
320 parser.add_option("-p", "--policy", dest="policy", metavar="FILE")
321 parser.add_option("-t", "--test", dest="tests", action="extend",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700322 help="Test options include "+str(Tests))
Dan Cashman91d398d2017-09-26 12:58:29 -0700323 parser.add_option("--fake-treble", action="store_true", dest="faketreble",
324 default=False)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700325
326 (options, args) = parser.parse_args()
327
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700328 if not options.libpath:
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700329 sys.exit("Must specify path to libsepolwrap library\n" + parser.usage)
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700330 if not os.path.exists(options.libpath):
331 sys.exit("Error: library-path " + options.libpath + " does not exist\n"
332 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700333 if not options.policy:
Dan Cashman91d398d2017-09-26 12:58:29 -0700334 sys.exit("Must specify current monolithic policy file\n" + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700335 if not os.path.exists(options.policy):
336 sys.exit("Error: policy file " + options.policy + " does not exist\n"
337 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700338 if not options.file_contexts:
339 sys.exit("Error: Must specify file_contexts file(s)\n" + parser.usage)
340 for f in options.file_contexts:
341 if not os.path.exists(f):
342 sys.exit("Error: File_contexts file " + f + " does not exist\n" +
343 parser.usage)
344
Tri Voe3f4f772018-09-28 17:21:08 -0700345 # Mapping files and public platform policy are only necessary for the
346 # TrebleCompatMapping test.
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800347 if options.tests is None or options.tests is "TrebleCompatMapping":
348 if not options.basepolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700349 sys.exit("Must specify the current platform-only policy file\n"
350 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800351 if not options.mapping:
Tri Voe3f4f772018-09-28 17:21:08 -0700352 sys.exit("Must specify a compatibility mapping file\n"
353 + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800354 if not options.oldpolicy:
Tri Voe3f4f772018-09-28 17:21:08 -0700355 sys.exit("Must specify the previous monolithic policy file\n"
356 + parser.usage)
357 if not options.base_pub_policy:
358 sys.exit("Must specify the current platform-only public policy "
359 + ".cil file\n" + parser.usage)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800360 basepol = policy.Policy(options.basepolicy, None, options.libpath)
361 oldpol = policy.Policy(options.oldpolicy, None, options.libpath)
362 mapping = mini_parser.MiniCilParser(options.mapping)
Tri Voe3f4f772018-09-28 17:21:08 -0700363 pubpol = mini_parser.MiniCilParser(options.base_pub_policy)
364 compatSetup(basepol, oldpol, mapping, pubpol.types)
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800365
Dan Cashman91d398d2017-09-26 12:58:29 -0700366 if options.faketreble:
367 FakeTreble = True
368
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700369 pol = policy.Policy(options.policy, options.file_contexts, options.libpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700370 setup(pol)
371
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700372 if DEBUG:
373 PrintScontexts()
374
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700375 results = ""
376 # If an individual test is not specified, run all tests.
Dan Cashman91d398d2017-09-26 12:58:29 -0700377 if options.tests is None:
378 for t in Tests.values():
379 results += t()
380 else:
381 for tn in options.tests:
382 t = Tests.get(tn)
383 if t:
384 results += t()
385 else:
386 err = "Error: unknown test: " + tn + "\n"
387 err += "Available tests:\n"
388 for tn in Tests.keys():
389 err += tn + "\n"
390 sys.exit(err)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700391
392 if len(results) > 0:
393 sys.exit(results)