blob: 2f9e9948b9c3ffbeaa2060b59a32fd0fca664ee5 [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',
Tom Cherry9c778042018-01-25 11:31:09 -080041 'vendor_init',
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070042 }
43coredomainWhitelist |= coreAppdomain
44
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 = []
54
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070055def PrintScontexts():
56 for d in sorted(alldomains.keys()):
57 sctx = alldomains[d]
58 print d
59 print "\tcoredomain="+str(sctx.coredomain)
60 print "\tappdomain="+str(sctx.appdomain)
61 print "\tfromSystem="+str(sctx.fromSystem)
62 print "\tfromVendor="+str(sctx.fromVendor)
63 print "\tattributes="+str(sctx.attributes)
64 print "\tentrypoints="+str(sctx.entrypoints)
65 print "\tentrypointpaths="
66 if sctx.entrypointpaths is not None:
67 for path in sctx.entrypointpaths:
68 print "\t\t"+str(path)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070069
70alldomains = {}
71coredomains = set()
72appdomains = set()
73vendordomains = set()
74
Dan Cashman91d398d2017-09-26 12:58:29 -070075# compat vars
76alltypes = set()
77oldalltypes = set()
78compatMapping = None
79
80# Distinguish between PRODUCT_FULL_TREBLE and PRODUCT_FULL_TREBLE_OVERRIDE
81FakeTreble = False
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070082
83def GetAllDomains(pol):
84 global alldomains
85 for result in pol.QueryTypeAttribute("domain", True):
86 alldomains[result] = scontext()
87
88def GetAppDomains():
89 global appdomains
90 global alldomains
91 for d in alldomains:
92 # The application of the "appdomain" attribute is trusted because core
93 # selinux policy contains neverallow rules that enforce that only zygote
94 # and runas spawned processes may transition to processes that have
95 # the appdomain attribute.
96 if "appdomain" in alldomains[d].attributes:
97 alldomains[d].appdomain = True
98 appdomains.add(d)
99
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700100def GetCoreDomains():
101 global alldomains
102 global coredomains
103 for d in alldomains:
Dan Cashman91d398d2017-09-26 12:58:29 -0700104 # TestCoredomainViolations will verify if coredomain was incorrectly
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700105 # applied.
106 if "coredomain" in alldomains[d].attributes:
107 alldomains[d].coredomain = True
108 coredomains.add(d)
109 # check whether domains are executed off of /system or /vendor
110 if d in coredomainWhitelist:
111 continue
112 # TODO, add checks to prevent app domains from being incorrectly
113 # labeled as coredomain. Apps don't have entrypoints as they're always
114 # dynamically transitioned to by zygote.
115 if d in appdomains:
116 continue
117 if not alldomains[d].entrypointpaths:
118 continue
119 for path in alldomains[d].entrypointpaths:
120 # Processes with entrypoint on /system
121 if ((MatchPathPrefix(path, "/system") and not
122 MatchPathPrefix(path, "/system/vendor")) or
123 MatchPathPrefix(path, "/init") or
124 MatchPathPrefix(path, "/charger")):
125 alldomains[d].fromSystem = True
126 # Processes with entrypoint on /vendor or /system/vendor
127 if (MatchPathPrefix(path, "/vendor") or
128 MatchPathPrefix(path, "/system/vendor")):
129 alldomains[d].fromVendor = True
130
131###
132# Add the entrypoint type and path(s) to each domain.
133#
134def GetDomainEntrypoints(pol):
135 global alldomains
Dan Cashman91d398d2017-09-26 12:58:29 -0700136 for x in pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])):
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700137 if not x.sctx in alldomains:
138 continue
139 alldomains[x.sctx].entrypoints.append(str(x.tctx))
140 # postinstall_file represents a special case specific to A/B OTAs.
141 # Update_engine mounts a partition and relabels it postinstall_file.
142 # There is no file_contexts entry associated with postinstall_file
143 # so skip the lookup.
144 if x.tctx == "postinstall_file":
145 continue
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700146 entrypointpath = pol.QueryFc(x.tctx)
147 if not entrypointpath:
148 continue
149 alldomains[x.sctx].entrypointpaths.extend(entrypointpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700150###
151# Get attributes associated with each domain
152#
153def GetAttributes(pol):
154 global alldomains
155 for domain in alldomains:
156 for result in pol.QueryTypeAttribute(domain, False):
157 alldomains[domain].attributes.add(result)
158
Dan Cashman91d398d2017-09-26 12:58:29 -0700159def GetAllTypes(pol, oldpol):
160 global alltypes
161 global oldalltypes
162 alltypes = pol.GetAllTypes(False)
163 oldalltypes = oldpol.GetAllTypes(False)
164
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700165def setup(pol):
166 GetAllDomains(pol)
167 GetAttributes(pol)
168 GetDomainEntrypoints(pol)
169 GetAppDomains()
170 GetCoreDomains()
171
Dan Cashman91d398d2017-09-26 12:58:29 -0700172# setup for the policy compatibility tests
173def compatSetup(pol, oldpol, mapping):
174 global compatMapping
175
176 GetAllTypes(pol, oldpol)
177 compatMapping = mapping
178
179def DomainsWithAttribute(attr):
180 global alldomains
181 domains = []
182 for domain in alldomains:
183 if attr in alldomains[domain].attributes:
184 domains.append(domain)
185 return domains
186
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700187#############################################################
188# Tests
189#############################################################
190def TestCoredomainViolations():
191 global alldomains
192 # verify that all domains launched from /system have the coredomain
193 # attribute
194 ret = ""
195 violators = []
196 for d in alldomains:
197 domain = alldomains[d]
198 if domain.fromSystem and "coredomain" not in domain.attributes:
199 violators.append(d);
200 if len(violators) > 0:
201 ret += "The following domain(s) must be associated with the "
202 ret += "\"coredomain\" attribute because they are executed off of "
203 ret += "/system:\n"
204 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
205
206 # verify that all domains launched form /vendor do not have the coredomain
207 # attribute
208 violators = []
209 for d in alldomains:
210 domain = alldomains[d]
211 if domain.fromVendor and "coredomain" in domain.attributes:
212 violators.append(d)
213 if len(violators) > 0:
214 ret += "The following domains must not be associated with the "
215 ret += "\"coredomain\" attribute because they are executed off of "
216 ret += "/vendor or /system/vendor:\n"
217 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
218
219 return ret
220
221###
Dan Cashman91d398d2017-09-26 12:58:29 -0700222# Make sure that any new type introduced in the new policy that was not present
223# in the old policy has been recorded in the mapping file.
224def TestNoUnmappedNewTypes():
225 global alltypes
226 global oldalltypes
227 global compatMapping
228 newt = alltypes - oldalltypes
229 ret = ""
230 violators = []
231
232 for n in newt:
233 if compatMapping.rTypeattributesets.get(n) is None:
234 violators.append(n)
235
236 if len(violators) > 0:
237 ret += "SELinux: The following types were found added to the policy "
238 ret += "without an entry into the compatibility mapping file(s) found "
239 ret += "in private/compat/" + compatMapping.apiLevel + "/"
Jeff Vander Stoepe6368602018-01-19 14:56:45 -0800240 ret += compatMapping.apiLevel + "[.ignore].cil\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700241 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
242 return ret
243
244###
245# Make sure that any public type removed in the current policy has its
246# declaration added to the mapping file for use in non-platform policy
247def TestNoUnmappedRmTypes():
248 global alltypes
249 global oldalltypes
250 global compatMapping
251 rmt = oldalltypes - alltypes
252 ret = ""
253 violators = []
254
255 for o in rmt:
256 if o in compatMapping.pubtypes and not o in compatMapping.types:
257 violators.append(o)
258
259 if len(violators) > 0:
260 ret += "SELinux: The following formerly public types were removed from "
261 ret += "policy without a declaration in the compatibility mapping "
262 ret += "file(s) found in prebuilts/api/" + compatMapping.apiLevel + "/\n"
263 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
264 return ret
265
266def TestTrebleCompatMapping():
267 ret = TestNoUnmappedNewTypes()
268 ret += TestNoUnmappedRmTypes()
269 return ret
270
271def TestViolatorAttribute(attribute):
272 global FakeTreble
273 ret = ""
274 if FakeTreble:
275 return ret
276
277 violators = DomainsWithAttribute(attribute)
278 if len(violators) > 0:
279 ret += "SELinux: The following domains violate the Treble ban "
280 ret += "against use of the " + attribute + " attribute: "
281 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
282 return ret
283
284def TestViolatorAttributes():
285 ret = TestViolatorAttribute("binder_in_vendor_violators")
286 ret += TestViolatorAttribute("socket_between_core_and_vendor_violators")
287 ret += TestViolatorAttribute("vendor_executes_system_violators")
288 return ret
289
290###
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700291# extend OptionParser to allow the same option flag to be used multiple times.
292# This is used to allow multiple file_contexts files and tests to be
293# specified.
294#
295class MultipleOption(Option):
296 ACTIONS = Option.ACTIONS + ("extend",)
297 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
298 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
299 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
300
301 def take_action(self, action, dest, opt, value, values, parser):
302 if action == "extend":
303 values.ensure_value(dest, []).append(value)
304 else:
305 Option.take_action(self, action, dest, opt, value, values, parser)
306
Dan Cashman91d398d2017-09-26 12:58:29 -0700307Tests = {"CoredomainViolations": TestCoredomainViolations,
308 "TrebleCompatMapping": TestTrebleCompatMapping,
309 "ViolatorAttributes": TestViolatorAttributes}
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700310
311if __name__ == '__main__':
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700312 usage = "treble_sepolicy_tests -l $(ANDROID_HOST_OUT)/lib64/libsepolwrap.so "
Dan Cashman91d398d2017-09-26 12:58:29 -0700313 usage += "-f nonplat_file_contexts -f plat_file_contexts "
314 usage += "-p curr_policy -b base_policy -o old_policy "
315 usage +="-m mapping file [--test test] [--help]"
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700316 parser = OptionParser(option_class=MultipleOption, usage=usage)
Dan Cashman91d398d2017-09-26 12:58:29 -0700317 parser.add_option("-b", "--basepolicy", dest="basepolicy", metavar="FILE")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700318 parser.add_option("-f", "--file_contexts", dest="file_contexts",
319 metavar="FILE", action="extend", type="string")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700320 parser.add_option("-l", "--library-path", dest="libpath", metavar="FILE")
Dan Cashman91d398d2017-09-26 12:58:29 -0700321 parser.add_option("-m", "--mapping", dest="mapping", metavar="FILE")
322 parser.add_option("-o", "--oldpolicy", dest="oldpolicy", metavar="FILE")
323 parser.add_option("-p", "--policy", dest="policy", metavar="FILE")
324 parser.add_option("-t", "--test", dest="tests", action="extend",
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700325 help="Test options include "+str(Tests))
Dan Cashman91d398d2017-09-26 12:58:29 -0700326 parser.add_option("--fake-treble", action="store_true", dest="faketreble",
327 default=False)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700328
329 (options, args) = parser.parse_args()
330
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700331 if not options.libpath:
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700332 sys.exit("Must specify path to libsepolwrap library\n" + parser.usage)
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700333 if not os.path.exists(options.libpath):
334 sys.exit("Error: library-path " + options.libpath + " does not exist\n"
335 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700336 if not options.policy:
Dan Cashman91d398d2017-09-26 12:58:29 -0700337 sys.exit("Must specify current monolithic policy file\n" + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700338 if not os.path.exists(options.policy):
339 sys.exit("Error: policy file " + options.policy + " does not exist\n"
340 + parser.usage)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700341 if not options.file_contexts:
342 sys.exit("Error: Must specify file_contexts file(s)\n" + parser.usage)
343 for f in options.file_contexts:
344 if not os.path.exists(f):
345 sys.exit("Error: File_contexts file " + f + " does not exist\n" +
346 parser.usage)
347
Jeff Vander Stoepfe0910c2017-11-20 13:25:47 -0800348 # Mapping files are only necessary for the TrebleCompatMapping test
349 if options.tests is None or options.tests is "TrebleCompatMapping":
350 if not options.basepolicy:
351 sys.exit("Must specify the current platform-only policy file\n" + parser.usage)
352 if not options.mapping:
353 sys.exit("Must specify a compatibility mapping file\n" + parser.usage)
354 if not options.oldpolicy:
355 sys.exit("Must specify the previous monolithic policy file\n" + parser.usage)
356 basepol = policy.Policy(options.basepolicy, None, options.libpath)
357 oldpol = policy.Policy(options.oldpolicy, None, options.libpath)
358 mapping = mini_parser.MiniCilParser(options.mapping)
359 compatSetup(basepol, oldpol, mapping)
360
361
Dan Cashman91d398d2017-09-26 12:58:29 -0700362 if options.faketreble:
363 FakeTreble = True
364
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700365 pol = policy.Policy(options.policy, options.file_contexts, options.libpath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700366 setup(pol)
367
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700368 if DEBUG:
369 PrintScontexts()
370
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700371 results = ""
372 # If an individual test is not specified, run all tests.
Dan Cashman91d398d2017-09-26 12:58:29 -0700373 if options.tests is None:
374 for t in Tests.values():
375 results += t()
376 else:
377 for tn in options.tests:
378 t = Tests.get(tn)
379 if t:
380 results += t()
381 else:
382 err = "Error: unknown test: " + tn + "\n"
383 err += "Available tests:\n"
384 for tn in Tests.keys():
385 err += tn + "\n"
386 sys.exit(err)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700387
388 if len(results) > 0:
389 sys.exit(results)