blob: 3c5c535128f87c1c056a207d7a905d32947efd47 [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###
17# Differentiate between domains that are part of the core Android platform and
18# domains introduced by vendors
19coreAppdomain = {
20 'bluetooth',
21 'ephemeral_app',
22 'isolated_app',
23 'nfc',
24 'platform_app',
25 'priv_app',
26 'radio',
27 'shared_relro',
28 'shell',
29 'system_app',
30 'untrusted_app',
31 'untrusted_app_25',
32 'untrusted_v2_app',
33 }
34coredomainWhitelist = {
35 'adbd',
36 'kernel',
37 'postinstall',
38 'postinstall_dexopt',
39 'recovery',
40 'system_server',
41 }
42coredomainWhitelist |= coreAppdomain
43
44class scontext:
45 def __init__(self):
46 self.fromSystem = False
47 self.fromVendor = False
48 self.coredomain = False
49 self.appdomain = False
50 self.attributes = set()
51 self.entrypoints = []
52 self.entrypointpaths = []
53
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070054def PrintScontexts():
55 for d in sorted(alldomains.keys()):
56 sctx = alldomains[d]
57 print d
58 print "\tcoredomain="+str(sctx.coredomain)
59 print "\tappdomain="+str(sctx.appdomain)
60 print "\tfromSystem="+str(sctx.fromSystem)
61 print "\tfromVendor="+str(sctx.fromVendor)
62 print "\tattributes="+str(sctx.attributes)
63 print "\tentrypoints="+str(sctx.entrypoints)
64 print "\tentrypointpaths="
65 if sctx.entrypointpaths is not None:
66 for path in sctx.entrypointpaths:
67 print "\t\t"+str(path)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070068
69alldomains = {}
70coredomains = set()
71appdomains = set()
72vendordomains = set()
73
Dan Cashman91d398d2017-09-26 12:58:29 -070074# compat vars
75alltypes = set()
76oldalltypes = set()
77compatMapping = None
78
79# Distinguish between PRODUCT_FULL_TREBLE and PRODUCT_FULL_TREBLE_OVERRIDE
80FakeTreble = False
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070081
82def GetAllDomains(pol):
83 global alldomains
84 for result in pol.QueryTypeAttribute("domain", True):
85 alldomains[result] = scontext()
86
87def GetAppDomains():
88 global appdomains
89 global alldomains
90 for d in alldomains:
91 # The application of the "appdomain" attribute is trusted because core
92 # selinux policy contains neverallow rules that enforce that only zygote
93 # and runas spawned processes may transition to processes that have
94 # the appdomain attribute.
95 if "appdomain" in alldomains[d].attributes:
96 alldomains[d].appdomain = True
97 appdomains.add(d)
98
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070099def GetCoreDomains():
100 global alldomains
101 global coredomains
102 for d in alldomains:
Dan Cashman91d398d2017-09-26 12:58:29 -0700103 # TestCoredomainViolations will verify if coredomain was incorrectly
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700104 # applied.
105 if "coredomain" in alldomains[d].attributes:
106 alldomains[d].coredomain = True
107 coredomains.add(d)
108 # check whether domains are executed off of /system or /vendor
109 if d in coredomainWhitelist:
110 continue
111 # TODO, add checks to prevent app domains from being incorrectly
112 # labeled as coredomain. Apps don't have entrypoints as they're always
113 # dynamically transitioned to by zygote.
114 if d in appdomains:
115 continue
116 if not alldomains[d].entrypointpaths:
117 continue
118 for path in alldomains[d].entrypointpaths:
119 # Processes with entrypoint on /system
120 if ((MatchPathPrefix(path, "/system") and not
121 MatchPathPrefix(path, "/system/vendor")) or
122 MatchPathPrefix(path, "/init") or
123 MatchPathPrefix(path, "/charger")):
124 alldomains[d].fromSystem = True
125 # Processes with entrypoint on /vendor or /system/vendor
126 if (MatchPathPrefix(path, "/vendor") or
127 MatchPathPrefix(path, "/system/vendor")):
128 alldomains[d].fromVendor = True
129
130###
131# Add the entrypoint type and path(s) to each domain.
132#
133def GetDomainEntrypoints(pol):
134 global alldomains
Dan Cashman91d398d2017-09-26 12:58:29 -0700135 for x in pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])):
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700136 if not x.sctx in alldomains:
137 continue
138 alldomains[x.sctx].entrypoints.append(str(x.tctx))
139 # postinstall_file represents a special case specific to A/B OTAs.
140 # Update_engine mounts a partition and relabels it postinstall_file.
141 # There is no file_contexts entry associated with postinstall_file
142 # so skip the lookup.
143 if x.tctx == "postinstall_file":
144 continue
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700145 entrypointpath = pol.QueryFc(x.tctx)
146 if not entrypointpath:
147 continue
148 alldomains[x.sctx].entrypointpaths.extend(entrypointpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700149###
150# Get attributes associated with each domain
151#
152def GetAttributes(pol):
153 global alldomains
154 for domain in alldomains:
155 for result in pol.QueryTypeAttribute(domain, False):
156 alldomains[domain].attributes.add(result)
157
Dan Cashman91d398d2017-09-26 12:58:29 -0700158def GetAllTypes(pol, oldpol):
159 global alltypes
160 global oldalltypes
161 alltypes = pol.GetAllTypes(False)
162 oldalltypes = oldpol.GetAllTypes(False)
163
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700164def setup(pol):
165 GetAllDomains(pol)
166 GetAttributes(pol)
167 GetDomainEntrypoints(pol)
168 GetAppDomains()
169 GetCoreDomains()
170
Dan Cashman91d398d2017-09-26 12:58:29 -0700171# setup for the policy compatibility tests
172def compatSetup(pol, oldpol, mapping):
173 global compatMapping
174
175 GetAllTypes(pol, oldpol)
176 compatMapping = mapping
177
178def DomainsWithAttribute(attr):
179 global alldomains
180 domains = []
181 for domain in alldomains:
182 if attr in alldomains[domain].attributes:
183 domains.append(domain)
184 return domains
185
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700186#############################################################
187# Tests
188#############################################################
189def TestCoredomainViolations():
190 global alldomains
191 # verify that all domains launched from /system have the coredomain
192 # attribute
193 ret = ""
194 violators = []
195 for d in alldomains:
196 domain = alldomains[d]
197 if domain.fromSystem and "coredomain" not in domain.attributes:
198 violators.append(d);
199 if len(violators) > 0:
200 ret += "The following domain(s) must be associated with the "
201 ret += "\"coredomain\" attribute because they are executed off of "
202 ret += "/system:\n"
203 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
204
205 # verify that all domains launched form /vendor do not have the coredomain
206 # attribute
207 violators = []
208 for d in alldomains:
209 domain = alldomains[d]
210 if domain.fromVendor and "coredomain" in domain.attributes:
211 violators.append(d)
212 if len(violators) > 0:
213 ret += "The following domains must not be associated with the "
214 ret += "\"coredomain\" attribute because they are executed off of "
215 ret += "/vendor or /system/vendor:\n"
216 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
217
218 return ret
219
220###
Dan Cashman91d398d2017-09-26 12:58:29 -0700221# Make sure that any new type introduced in the new policy that was not present
222# in the old policy has been recorded in the mapping file.
223def TestNoUnmappedNewTypes():
224 global alltypes
225 global oldalltypes
226 global compatMapping
227 newt = alltypes - oldalltypes
228 ret = ""
229 violators = []
230
231 for n in newt:
232 if compatMapping.rTypeattributesets.get(n) is None:
233 violators.append(n)
234
235 if len(violators) > 0:
236 ret += "SELinux: The following types were found added to the policy "
237 ret += "without an entry into the compatibility mapping file(s) found "
238 ret += "in private/compat/" + compatMapping.apiLevel + "/"
Jeff Vander Stoepe6368602018-01-19 14:56:45 -0800239 ret += compatMapping.apiLevel + "[.ignore].cil\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700240 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
241 return ret
242
243###
244# Make sure that any public type removed in the current policy has its
245# declaration added to the mapping file for use in non-platform policy
246def TestNoUnmappedRmTypes():
247 global alltypes
248 global oldalltypes
249 global compatMapping
250 rmt = oldalltypes - alltypes
251 ret = ""
252 violators = []
253
254 for o in rmt:
255 if o in compatMapping.pubtypes and not o in compatMapping.types:
256 violators.append(o)
257
258 if len(violators) > 0:
259 ret += "SELinux: The following formerly public types were removed from "
260 ret += "policy without a declaration in the compatibility mapping "
261 ret += "file(s) found in prebuilts/api/" + compatMapping.apiLevel + "/\n"
262 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
263 return ret
264
265def TestTrebleCompatMapping():
266 ret = TestNoUnmappedNewTypes()
267 ret += TestNoUnmappedRmTypes()
268 return ret
269
270def TestViolatorAttribute(attribute):
271 global FakeTreble
272 ret = ""
273 if FakeTreble:
274 return ret
275
276 violators = DomainsWithAttribute(attribute)
277 if len(violators) > 0:
278 ret += "SELinux: The following domains violate the Treble ban "
279 ret += "against use of the " + attribute + " attribute: "
280 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
281 return ret
282
283def TestViolatorAttributes():
284 ret = TestViolatorAttribute("binder_in_vendor_violators")
285 ret += TestViolatorAttribute("socket_between_core_and_vendor_violators")
286 ret += TestViolatorAttribute("vendor_executes_system_violators")
287 return ret
288
289###
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700290# extend OptionParser to allow the same option flag to be used multiple times.
291# This is used to allow multiple file_contexts files and tests to be
292# specified.
293#
294class MultipleOption(Option):
295 ACTIONS = Option.ACTIONS + ("extend",)
296 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
297 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
298 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
299
300 def take_action(self, action, dest, opt, value, values, parser):
301 if action == "extend":
302 values.ensure_value(dest, []).append(value)
303 else:
304 Option.take_action(self, action, dest, opt, value, values, parser)
305
Dan Cashman91d398d2017-09-26 12:58:29 -0700306Tests = {"CoredomainViolations": TestCoredomainViolations,
307 "TrebleCompatMapping": TestTrebleCompatMapping,
308 "ViolatorAttributes": TestViolatorAttributes}
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700309
310if __name__ == '__main__':
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700311 usage = "treble_sepolicy_tests -l $(ANDROID_HOST_OUT)/lib64/libsepolwrap.so "
Dan Cashman91d398d2017-09-26 12:58:29 -0700312 usage += "-f nonplat_file_contexts -f plat_file_contexts "
313 usage += "-p curr_policy -b base_policy -o old_policy "
314 usage +="-m mapping file [--test test] [--help]"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700315 parser = OptionParser(option_class=MultipleOption, usage=usage)
Dan Cashman91d398d2017-09-26 12:58:29 -0700316 parser.add_option("-b", "--basepolicy", dest="basepolicy", metavar="FILE")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700317 parser.add_option("-f", "--file_contexts", dest="file_contexts",
318 metavar="FILE", action="extend", type="string")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700319 parser.add_option("-l", "--library-path", dest="libpath", metavar="FILE")
Dan Cashman91d398d2017-09-26 12:58:29 -0700320 parser.add_option("-m", "--mapping", dest="mapping", metavar="FILE")
321 parser.add_option("-o", "--oldpolicy", dest="oldpolicy", metavar="FILE")
322 parser.add_option("-p", "--policy", dest="policy", metavar="FILE")
323 parser.add_option("-t", "--test", dest="tests", action="extend",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700324 help="Test options include "+str(Tests))
Dan Cashman91d398d2017-09-26 12:58:29 -0700325 parser.add_option("--fake-treble", action="store_true", dest="faketreble",
326 default=False)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700327
328 (options, args) = parser.parse_args()
329
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700330 if not options.libpath:
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700331 sys.exit("Must specify path to libsepolwrap library\n" + parser.usage)
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700332 if not os.path.exists(options.libpath):
333 sys.exit("Error: library-path " + options.libpath + " does not exist\n"
334 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700335 if not options.policy:
Dan Cashman91d398d2017-09-26 12:58:29 -0700336 sys.exit("Must specify current monolithic policy file\n" + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700337 if not os.path.exists(options.policy):
338 sys.exit("Error: policy file " + options.policy + " does not exist\n"
339 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700340 if not options.file_contexts:
341 sys.exit("Error: Must specify file_contexts file(s)\n" + parser.usage)
342 for f in options.file_contexts:
343 if not os.path.exists(f):
344 sys.exit("Error: File_contexts file " + f + " does not exist\n" +
345 parser.usage)
346
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800347 # Mapping files are only necessary for the TrebleCompatMapping test
348 if options.tests is None or options.tests is "TrebleCompatMapping":
349 if not options.basepolicy:
350 sys.exit("Must specify the current platform-only policy file\n" + parser.usage)
351 if not options.mapping:
352 sys.exit("Must specify a compatibility mapping file\n" + parser.usage)
353 if not options.oldpolicy:
354 sys.exit("Must specify the previous monolithic policy file\n" + parser.usage)
355 basepol = policy.Policy(options.basepolicy, None, options.libpath)
356 oldpol = policy.Policy(options.oldpolicy, None, options.libpath)
357 mapping = mini_parser.MiniCilParser(options.mapping)
358 compatSetup(basepol, oldpol, mapping)
359
360
Dan Cashman91d398d2017-09-26 12:58:29 -0700361 if options.faketreble:
362 FakeTreble = True
363
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700364 pol = policy.Policy(options.policy, options.file_contexts, options.libpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700365 setup(pol)
366
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700367 if DEBUG:
368 PrintScontexts()
369
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700370 results = ""
371 # If an individual test is not specified, run all tests.
Dan Cashman91d398d2017-09-26 12:58:29 -0700372 if options.tests is None:
373 for t in Tests.values():
374 results += t()
375 else:
376 for tn in options.tests:
377 t = Tests.get(tn)
378 if t:
379 results += t()
380 else:
381 err = "Error: unknown test: " + tn + "\n"
382 err += "Available tests:\n"
383 for tn in Tests.keys():
384 err += tn + "\n"
385 sys.exit(err)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700386
387 if len(results) > 0:
388 sys.exit(results)