blob: 24466e9d517b91c92df79d672040772becd16548 [file] [log] [blame]
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -07001from ctypes import *
2import re
3import os
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -07004import sys
Jeff Vander Stoepe9777e32017-09-23 15:11:25 -07005import platform
Jeff Vander Stoep1ca7a4c2019-04-10 16:53:17 -07006import fc_sort
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -07007
Dan Cashman91d398d2017-09-26 12:58:29 -07008###
9# Check whether the regex will match a file path starting with the provided
10# prefix
11#
12# Compares regex entries in file_contexts with a path prefix. Regex entries
13# are often more specific than this file prefix. For example, the regex could
14# be /system/bin/foo\.sh and the prefix could be /system. This function
15# loops over the regex removing characters from the end until
16# 1) there is a match - return True or 2) run out of characters - return
17# False.
18#
19def MatchPathPrefix(pathregex, prefix):
20 for i in range(len(pathregex), 0, -1):
21 try:
22 pattern = re.compile('^' + pathregex[0:i] + "$")
23 except:
24 continue
25 if pattern.match(prefix):
26 return True
27 return False
28
29def MatchPathPrefixes(pathregex, Prefixes):
30 for Prefix in Prefixes:
31 if MatchPathPrefix(pathregex, Prefix):
32 return True
33 return False
34
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070035class TERule:
36 def __init__(self, rule):
37 data = rule.split(',')
38 self.flavor = data[0]
39 self.sctx = data[1]
40 self.tctx = data[2]
41 self.tclass = data[3]
42 self.perms = set((data[4].strip()).split(' '))
43 self.rule = rule
44
45class Policy:
Dan Cashman91d398d2017-09-26 12:58:29 -070046 __ExpandedRules = set()
47 __Rules = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070048 __FcDict = None
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080049 __FcSorted = None
Jeff Vander Stoep1b828442018-03-21 17:27:20 -070050 __GenfsDict = None
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070051 __libsepolwrap = None
52 __policydbP = None
Dan Cashman91d398d2017-09-26 12:58:29 -070053 __BUFSIZE = 2048
54
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080055 def AssertPathTypesDoNotHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr):
56 # Query policy for the types associated with Attr
57 TypesPol = self.QueryTypeAttribute(Attr, True)
58 # Search file_contexts to find types associated with input paths.
59 TypesFc = self.__GetTypesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix)
60 violators = TypesFc.intersection(TypesPol)
61 ret = ""
62 if len(violators) > 0:
63 ret += "The following types on "
64 ret += " ".join(str(x) for x in sorted(MatchPrefix))
65 ret += " must not be associated with the "
66 ret += "\"" + Attr + "\" attribute: "
67 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
68 return ret
69
Jeff Vander Stoep1b828442018-03-21 17:27:20 -070070 # Check that all types for "filesystem" have "attribute" associated with them
71 # for types labeled in genfs_contexts.
72 def AssertGenfsFilesystemTypesHaveAttr(self, Filesystem, Attr):
73 TypesPol = self.QueryTypeAttribute(Attr, True)
74 TypesGenfs = self.__GenfsDict[Filesystem]
75 violators = TypesGenfs.difference(TypesPol)
76
77 ret = ""
78 if len(violators) > 0:
79 ret += "The following types in " + Filesystem
80 ret += " must be associated with the "
81 ret += "\"" + Attr + "\" attribute: "
82 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
83 return ret
84
Dan Cashman91d398d2017-09-26 12:58:29 -070085 # Check that path prefixes that match MatchPrefix, and do not Match
86 # DoNotMatchPrefix have the attribute Attr.
87 # For example assert that all types in /sys, and not in /sys/kernel/debugfs
88 # have the sysfs_type attribute.
89 def AssertPathTypesHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr):
90 # Query policy for the types associated with Attr
91 TypesPol = self.QueryTypeAttribute(Attr, True)
92 # Search file_contexts to find paths/types that should be associated with
93 # Attr.
94 TypesFc = self.__GetTypesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix)
95 violators = TypesFc.difference(TypesPol)
96
97 ret = ""
98 if len(violators) > 0:
99 ret += "The following types on "
100 ret += " ".join(str(x) for x in sorted(MatchPrefix))
101 ret += " must be associated with the "
102 ret += "\"" + Attr + "\" attribute: "
103 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
104 return ret
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700105
Inseob Kim1b8b1f62020-10-23 15:16:11 +0900106 def AssertPropertyOwnersAreExclusive(self):
107 systemProps = self.QueryTypeAttribute('system_property_type', True)
108 vendorProps = self.QueryTypeAttribute('vendor_property_type', True)
109 violators = systemProps.intersection(vendorProps)
110 ret = ""
111 if len(violators) > 0:
112 ret += "The following types have both system_property_type "
113 ret += "and vendor_property_type: "
114 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
115 return ret
116
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700117 # Return all file_contexts entries that map to the input Type.
118 def QueryFc(self, Type):
119 if Type in self.__FcDict:
120 return self.__FcDict[Type]
121 else:
122 return None
123
124 # Return all attributes associated with a type if IsAttr=False or
125 # all types associated with an attribute if IsAttr=True
126 def QueryTypeAttribute(self, Type, IsAttr):
Dan Cashman91d398d2017-09-26 12:58:29 -0700127 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP,
128 create_string_buffer(Type), IsAttr)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700129 if (TypeIterP == None):
130 sys.exit("Failed to initialize type iterator")
Dan Cashman91d398d2017-09-26 12:58:29 -0700131 buf = create_string_buffer(self.__BUFSIZE)
132 TypeAttr = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700133 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -0700134 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
135 self.__policydbP, TypeIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700136 if ret == 0:
Dan Cashman91d398d2017-09-26 12:58:29 -0700137 TypeAttr.add(buf.value)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700138 continue
139 if ret == 1:
140 break;
141 # We should never get here.
142 sys.exit("Failed to import policy")
Dan Cashman91d398d2017-09-26 12:58:29 -0700143 self.__libsepolwrap.destroy_type_iter(TypeIterP)
144 return TypeAttr
145
146 def __TERuleMatch(self, Rule, **kwargs):
147 # Match source type
148 if ("scontext" in kwargs and
149 len(kwargs['scontext']) > 0 and
150 Rule.sctx not in kwargs['scontext']):
151 return False
152 # Match target type
153 if ("tcontext" in kwargs and
154 len(kwargs['tcontext']) > 0 and
155 Rule.tctx not in kwargs['tcontext']):
156 return False
157 # Match target class
158 if ("tclass" in kwargs and
159 len(kwargs['tclass']) > 0 and
160 not bool(set([Rule.tclass]) & kwargs['tclass'])):
161 return False
162 # Match any perms
163 if ("perms" in kwargs and
164 len(kwargs['perms']) > 0 and
165 not bool(Rule.perms & kwargs['perms'])):
166 return False
167 return True
168
169 # resolve a type to its attributes or
170 # resolve an attribute to its types and attributes
171 # For example if scontext is the domain attribute, then we need to
172 # include all types with the domain attribute such as untrusted_app and
173 # priv_app and all the attributes of those types such as appdomain.
174 def ResolveTypeAttribute(self, Type):
175 types = self.GetAllTypes(False)
176 attributes = self.GetAllTypes(True)
177
178 if Type in types:
179 return self.QueryTypeAttribute(Type, False)
180 elif Type in attributes:
181 TypesAndAttributes = set()
182 Types = self.QueryTypeAttribute(Type, True)
183 TypesAndAttributes |= Types
184 for T in Types:
185 TypesAndAttributes |= self.QueryTypeAttribute(T, False)
186 return TypesAndAttributes
187 else:
188 return set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700189
190 # Return all TERules that match:
191 # (any scontext) or (any tcontext) or (any tclass) or (any perms),
192 # perms.
193 # Any unspecified paramenter will match all.
194 #
195 # Example: QueryTERule(tcontext=["foo", "bar"], perms=["entrypoint"])
196 # Will return any rule with:
197 # (tcontext="foo" or tcontext="bar") and ("entrypoint" in perms)
198 def QueryTERule(self, **kwargs):
Dan Cashman91d398d2017-09-26 12:58:29 -0700199 if len(self.__Rules) == 0:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700200 self.__InitTERules()
Dan Cashman91d398d2017-09-26 12:58:29 -0700201
202 # add any matching types and attributes for scontext and tcontext
203 if ("scontext" in kwargs and len(kwargs['scontext']) > 0):
204 scontext = set()
205 for sctx in kwargs['scontext']:
206 scontext |= self.ResolveTypeAttribute(sctx)
207 kwargs['scontext'] = scontext
208 if ("tcontext" in kwargs and len(kwargs['tcontext']) > 0):
209 tcontext = set()
210 for tctx in kwargs['tcontext']:
211 tcontext |= self.ResolveTypeAttribute(tctx)
212 kwargs['tcontext'] = tcontext
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700213 for Rule in self.__Rules:
Dan Cashman91d398d2017-09-26 12:58:29 -0700214 if self.__TERuleMatch(Rule, **kwargs):
215 yield Rule
216
217 # Same as QueryTERule but only using the expanded ruleset.
218 # i.e. all attributes have been expanded to their various types.
219 def QueryExpandedTERule(self, **kwargs):
220 if len(self.__ExpandedRules) == 0:
221 self.__InitExpandedTERules()
222 for Rule in self.__ExpandedRules:
223 if self.__TERuleMatch(Rule, **kwargs):
224 yield Rule
225
226 def GetAllTypes(self, isAttr):
227 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP, None, isAttr)
228 if (TypeIterP == None):
229 sys.exit("Failed to initialize type iterator")
230 buf = create_string_buffer(self.__BUFSIZE)
231 AllTypes = set()
232 while True:
233 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
234 self.__policydbP, TypeIterP)
235 if ret == 0:
236 AllTypes.add(buf.value)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700237 continue
Dan Cashman91d398d2017-09-26 12:58:29 -0700238 if ret == 1:
239 break;
240 # We should never get here.
241 sys.exit("Failed to import policy")
242 self.__libsepolwrap.destroy_type_iter(TypeIterP)
243 return AllTypes
244
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800245 def __ExactMatchPathPrefix(self, pathregex, prefix):
246 pattern = re.compile('^' + pathregex + "$")
247 if pattern.match(prefix):
248 return True
249 return False
250
251 # Return a tuple (prefix, i) where i is the index of the most specific
252 # match of prefix in the sorted file_contexts. This is useful for limiting a
253 # file_contexts search to matches that are more specific and omitting less
254 # specific matches. For example, finding all matches to prefix /data/vendor
255 # should not include /data(/.*)? if /data/vendor(/.*)? is also specified.
256 def __FcSortedIndex(self, prefix):
257 index = 0
258 for i in range(0, len(self.__FcSorted)):
259 if self.__ExactMatchPathPrefix(self.__FcSorted[i].path, prefix):
260 index = i
261 return prefix, index
262
263 # Return a tuple of (path, Type) for all matching paths. Use the sorted
264 # file_contexts and index returned from __FcSortedIndex() to limit results
265 # to results that are more specific than the prefix.
266 def __MatchPathPrefixTypes(self, prefix, index):
267 PathType = []
268 for i in range(index, len(self.__FcSorted)):
269 if MatchPathPrefix(self.__FcSorted[i].path, prefix):
270 PathType.append((self.__FcSorted[i].path, self.__FcSorted[i].Type))
271 return PathType
272
273 # Return types that match MatchPrefixes but do not match
274 # DoNotMatchPrefixes
Dan Cashman91d398d2017-09-26 12:58:29 -0700275 def __GetTypesByFilePathPrefix(self, MatchPrefixes, DoNotMatchPrefixes):
276 Types = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700277
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800278 MatchPrefixesWithIndex = []
279 for MatchPrefix in MatchPrefixes:
280 MatchPrefixesWithIndex.append(self.__FcSortedIndex(MatchPrefix))
281
282 for MatchPrefixWithIndex in MatchPrefixesWithIndex:
283 PathTypes = self.__MatchPathPrefixTypes(*MatchPrefixWithIndex)
284 for PathType in PathTypes:
285 if MatchPathPrefixes(PathType[0], DoNotMatchPrefixes):
286 continue
287 Types.add(PathType[1])
288 return Types
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700289
Dan Cashman91d398d2017-09-26 12:58:29 -0700290 def __GetTERules(self, policydbP, avtabIterP, Rules):
291 if Rules is None:
292 Rules = set()
293 buf = create_string_buffer(self.__BUFSIZE)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700294 ret = 0
295 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -0700296 ret = self.__libsepolwrap.get_allow_rule(buf, self.__BUFSIZE,
297 policydbP, avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700298 if ret == 0:
299 Rule = TERule(buf.value)
Dan Cashman91d398d2017-09-26 12:58:29 -0700300 Rules.add(Rule)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700301 continue
302 if ret == 1:
303 break;
304 # We should never get here.
305 sys.exit("Failed to import policy")
306
307 def __InitTERules(self):
Dan Cashman91d398d2017-09-26 12:58:29 -0700308 avtabIterP = self.__libsepolwrap.init_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700309 if (avtabIterP == None):
310 sys.exit("Failed to initialize avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700311 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
312 self.__libsepolwrap.destroy_avtab(avtabIterP)
313 avtabIterP = self.__libsepolwrap.init_cond_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700314 if (avtabIterP == None):
315 sys.exit("Failed to initialize conditional avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700316 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
317 self.__libsepolwrap.destroy_avtab(avtabIterP)
318
319 def __InitExpandedTERules(self):
320 avtabIterP = self.__libsepolwrap.init_expanded_avtab(self.__policydbP)
321 if (avtabIterP == None):
322 sys.exit("Failed to initialize avtab")
323 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
324 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
325 avtabIterP = self.__libsepolwrap.init_expanded_cond_avtab(self.__policydbP)
326 if (avtabIterP == None):
327 sys.exit("Failed to initialize conditional avtab")
328 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
329 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700330
331 # load ctypes-ified libsepol wrapper
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700332 def __InitLibsepolwrap(self, LibPath):
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700333 lib = CDLL(LibPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700334
Dan Cashman91d398d2017-09-26 12:58:29 -0700335 # int get_allow_rule(char *out, size_t len, void *policydbp, void *avtab_iterp);
336 lib.get_allow_rule.restype = c_int
337 lib.get_allow_rule.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p];
338 # void *load_policy(const char *policy_path);
339 lib.load_policy.restype = c_void_p
340 lib.load_policy.argtypes = [c_char_p]
341 # void destroy_policy(void *policydbp);
342 lib.destroy_policy.argtypes = [c_void_p]
343 # void *init_expanded_avtab(void *policydbp);
344 lib.init_expanded_avtab.restype = c_void_p
345 lib.init_expanded_avtab.argtypes = [c_void_p]
346 # void *init_expanded_cond_avtab(void *policydbp);
347 lib.init_expanded_cond_avtab.restype = c_void_p
348 lib.init_expanded_cond_avtab.argtypes = [c_void_p]
349 # void destroy_expanded_avtab(void *avtab_iterp);
350 lib.destroy_expanded_avtab.argtypes = [c_void_p]
351 # void *init_avtab(void *policydbp);
352 lib.init_avtab.restype = c_void_p
353 lib.init_avtab.argtypes = [c_void_p]
354 # void *init_cond_avtab(void *policydbp);
355 lib.init_cond_avtab.restype = c_void_p
356 lib.init_cond_avtab.argtypes = [c_void_p]
357 # void destroy_avtab(void *avtab_iterp);
358 lib.destroy_avtab.argtypes = [c_void_p]
359 # int get_type(char *out, size_t max_size, void *policydbp, void *type_iterp);
360 lib.get_type.restype = c_int
361 lib.get_type.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]
362 # void *init_type_iter(void *policydbp, const char *type, bool is_attr);
363 lib.init_type_iter.restype = c_void_p
364 lib.init_type_iter.argtypes = [c_void_p, c_char_p, c_bool]
365 # void destroy_type_iter(void *type_iterp);
366 lib.destroy_type_iter.argtypes = [c_void_p]
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700367 # void *init_genfs_iter(void *policydbp)
368 lib.init_genfs_iter.restype = c_void_p
369 lib.init_genfs_iter.argtypes = [c_void_p]
370 # int get_genfs(char *out, size_t max_size, void *genfs_iterp);
371 lib.get_genfs.restype = c_int
372 lib.get_genfs.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]
373 # void destroy_genfs_iter(void *genfs_iterp)
374 lib.destroy_genfs_iter.argtypes = [c_void_p]
Dan Cashman91d398d2017-09-26 12:58:29 -0700375
376 self.__libsepolwrap = lib
377
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700378 def __GenfsDictAdd(self, Dict, buf):
379 fs, path, context = buf.split(" ")
380 Type = context.split(":")[2]
381 if not fs in Dict:
382 Dict[fs] = {Type}
383 else:
384 Dict[fs].add(Type)
385
386 def __InitGenfsCon(self):
387 self.__GenfsDict = {}
388 GenfsIterP = self.__libsepolwrap.init_genfs_iter(self.__policydbP)
389 if (GenfsIterP == None):
390 sys.exit("Failed to retreive genfs entries")
391 buf = create_string_buffer(self.__BUFSIZE)
392 while True:
393 ret = self.__libsepolwrap.get_genfs(buf, self.__BUFSIZE,
394 self.__policydbP, GenfsIterP)
395 if ret == 0:
396 self.__GenfsDictAdd(self.__GenfsDict, buf.value)
397 continue
398 if ret == 1:
399 self.__GenfsDictAdd(self.__GenfsDict, buf.value)
400 break;
401 # We should never get here.
402 sys.exit("Failed to get genfs entries")
403 self.__libsepolwrap.destroy_genfs_iter(GenfsIterP)
Dan Cashman91d398d2017-09-26 12:58:29 -0700404
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700405 # load file_contexts
406 def __InitFC(self, FcPaths):
Dan Cashman91d398d2017-09-26 12:58:29 -0700407 if FcPaths is None:
408 return
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700409 fc = []
410 for path in FcPaths:
411 if not os.path.exists(path):
412 sys.exit("file_contexts file " + path + " does not exist.")
413 fd = open(path, "r")
414 fc += fd.readlines()
415 fd.close()
416 self.__FcDict = {}
417 for i in fc:
418 rec = i.split()
419 try:
420 t = rec[-1].split(":")[2]
421 if t in self.__FcDict:
422 self.__FcDict[t].append(rec[0])
423 else:
424 self.__FcDict[t] = [rec[0]]
425 except:
426 pass
Jeff Vander Stoep1ca7a4c2019-04-10 16:53:17 -0700427 self.__FcSorted = fc_sort.FcSort(FcPaths)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700428
429 # load policy
430 def __InitPolicy(self, PolicyPath):
Dan Cashman91d398d2017-09-26 12:58:29 -0700431 cPolicyPath = create_string_buffer(PolicyPath)
432 self.__policydbP = self.__libsepolwrap.load_policy(cPolicyPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700433 if (self.__policydbP is None):
434 sys.exit("Failed to load policy")
435
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700436 def __init__(self, PolicyPath, FcPaths, LibPath):
437 self.__InitLibsepolwrap(LibPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700438 self.__InitFC(FcPaths)
439 self.__InitPolicy(PolicyPath)
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700440 self.__InitGenfsCon()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700441
442 def __del__(self):
443 if self.__policydbP is not None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700444 self.__libsepolwrap.destroy_policy(self.__policydbP)