blob: a0ddb909614102273509e2d63b2199165842a5e8 [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 Stoepbdfc0302017-05-25 09:53:47 -07005
Dan Cashman91d398d2017-09-26 12:58:29 -07006###
7# Check whether the regex will match a file path starting with the provided
8# prefix
9#
10# Compares regex entries in file_contexts with a path prefix. Regex entries
11# are often more specific than this file prefix. For example, the regex could
12# be /system/bin/foo\.sh and the prefix could be /system. This function
13# loops over the regex removing characters from the end until
14# 1) there is a match - return True or 2) run out of characters - return
15# False.
16#
17def MatchPathPrefix(pathregex, prefix):
18 for i in range(len(pathregex), 0, -1):
19 try:
20 pattern = re.compile('^' + pathregex[0:i] + "$")
21 except:
22 continue
23 if pattern.match(prefix):
24 return True
25 return False
26
27def MatchPathPrefixes(pathregex, Prefixes):
28 for Prefix in Prefixes:
29 if MatchPathPrefix(pathregex, Prefix):
30 return True
31 return False
32
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070033class TERule:
34 def __init__(self, rule):
35 data = rule.split(',')
36 self.flavor = data[0]
37 self.sctx = data[1]
38 self.tctx = data[2]
39 self.tclass = data[3]
40 self.perms = set((data[4].strip()).split(' '))
41 self.rule = rule
42
43class Policy:
Dan Cashman91d398d2017-09-26 12:58:29 -070044 __ExpandedRules = set()
45 __Rules = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070046 __FcDict = None
47 __libsepolwrap = None
48 __policydbP = None
Dan Cashman91d398d2017-09-26 12:58:29 -070049 __BUFSIZE = 2048
50
51 # Check that path prefixes that match MatchPrefix, and do not Match
52 # DoNotMatchPrefix have the attribute Attr.
53 # For example assert that all types in /sys, and not in /sys/kernel/debugfs
54 # have the sysfs_type attribute.
55 def AssertPathTypesHaveAttr(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 paths/types that should be associated with
59 # Attr.
60 TypesFc = self.__GetTypesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix)
61 violators = TypesFc.difference(TypesPol)
62
63 ret = ""
64 if len(violators) > 0:
65 ret += "The following types on "
66 ret += " ".join(str(x) for x in sorted(MatchPrefix))
67 ret += " must be associated with the "
68 ret += "\"" + Attr + "\" attribute: "
69 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
70 return ret
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070071
72 # Return all file_contexts entries that map to the input Type.
73 def QueryFc(self, Type):
74 if Type in self.__FcDict:
75 return self.__FcDict[Type]
76 else:
77 return None
78
79 # Return all attributes associated with a type if IsAttr=False or
80 # all types associated with an attribute if IsAttr=True
81 def QueryTypeAttribute(self, Type, IsAttr):
Dan Cashman91d398d2017-09-26 12:58:29 -070082 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP,
83 create_string_buffer(Type), IsAttr)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070084 if (TypeIterP == None):
85 sys.exit("Failed to initialize type iterator")
Dan Cashman91d398d2017-09-26 12:58:29 -070086 buf = create_string_buffer(self.__BUFSIZE)
87 TypeAttr = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070088 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -070089 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
90 self.__policydbP, TypeIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070091 if ret == 0:
Dan Cashman91d398d2017-09-26 12:58:29 -070092 TypeAttr.add(buf.value)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070093 continue
94 if ret == 1:
95 break;
96 # We should never get here.
97 sys.exit("Failed to import policy")
Dan Cashman91d398d2017-09-26 12:58:29 -070098 self.__libsepolwrap.destroy_type_iter(TypeIterP)
99 return TypeAttr
100
101 def __TERuleMatch(self, Rule, **kwargs):
102 # Match source type
103 if ("scontext" in kwargs and
104 len(kwargs['scontext']) > 0 and
105 Rule.sctx not in kwargs['scontext']):
106 return False
107 # Match target type
108 if ("tcontext" in kwargs and
109 len(kwargs['tcontext']) > 0 and
110 Rule.tctx not in kwargs['tcontext']):
111 return False
112 # Match target class
113 if ("tclass" in kwargs and
114 len(kwargs['tclass']) > 0 and
115 not bool(set([Rule.tclass]) & kwargs['tclass'])):
116 return False
117 # Match any perms
118 if ("perms" in kwargs and
119 len(kwargs['perms']) > 0 and
120 not bool(Rule.perms & kwargs['perms'])):
121 return False
122 return True
123
124 # resolve a type to its attributes or
125 # resolve an attribute to its types and attributes
126 # For example if scontext is the domain attribute, then we need to
127 # include all types with the domain attribute such as untrusted_app and
128 # priv_app and all the attributes of those types such as appdomain.
129 def ResolveTypeAttribute(self, Type):
130 types = self.GetAllTypes(False)
131 attributes = self.GetAllTypes(True)
132
133 if Type in types:
134 return self.QueryTypeAttribute(Type, False)
135 elif Type in attributes:
136 TypesAndAttributes = set()
137 Types = self.QueryTypeAttribute(Type, True)
138 TypesAndAttributes |= Types
139 for T in Types:
140 TypesAndAttributes |= self.QueryTypeAttribute(T, False)
141 return TypesAndAttributes
142 else:
143 return set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700144
145 # Return all TERules that match:
146 # (any scontext) or (any tcontext) or (any tclass) or (any perms),
147 # perms.
148 # Any unspecified paramenter will match all.
149 #
150 # Example: QueryTERule(tcontext=["foo", "bar"], perms=["entrypoint"])
151 # Will return any rule with:
152 # (tcontext="foo" or tcontext="bar") and ("entrypoint" in perms)
153 def QueryTERule(self, **kwargs):
Dan Cashman91d398d2017-09-26 12:58:29 -0700154 if len(self.__Rules) == 0:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700155 self.__InitTERules()
Dan Cashman91d398d2017-09-26 12:58:29 -0700156
157 # add any matching types and attributes for scontext and tcontext
158 if ("scontext" in kwargs and len(kwargs['scontext']) > 0):
159 scontext = set()
160 for sctx in kwargs['scontext']:
161 scontext |= self.ResolveTypeAttribute(sctx)
162 kwargs['scontext'] = scontext
163 if ("tcontext" in kwargs and len(kwargs['tcontext']) > 0):
164 tcontext = set()
165 for tctx in kwargs['tcontext']:
166 tcontext |= self.ResolveTypeAttribute(tctx)
167 kwargs['tcontext'] = tcontext
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700168 for Rule in self.__Rules:
Dan Cashman91d398d2017-09-26 12:58:29 -0700169 if self.__TERuleMatch(Rule, **kwargs):
170 yield Rule
171
172 # Same as QueryTERule but only using the expanded ruleset.
173 # i.e. all attributes have been expanded to their various types.
174 def QueryExpandedTERule(self, **kwargs):
175 if len(self.__ExpandedRules) == 0:
176 self.__InitExpandedTERules()
177 for Rule in self.__ExpandedRules:
178 if self.__TERuleMatch(Rule, **kwargs):
179 yield Rule
180
181 def GetAllTypes(self, isAttr):
182 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP, None, isAttr)
183 if (TypeIterP == None):
184 sys.exit("Failed to initialize type iterator")
185 buf = create_string_buffer(self.__BUFSIZE)
186 AllTypes = set()
187 while True:
188 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
189 self.__policydbP, TypeIterP)
190 if ret == 0:
191 AllTypes.add(buf.value)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700192 continue
Dan Cashman91d398d2017-09-26 12:58:29 -0700193 if ret == 1:
194 break;
195 # We should never get here.
196 sys.exit("Failed to import policy")
197 self.__libsepolwrap.destroy_type_iter(TypeIterP)
198 return AllTypes
199
200 def __GetTypesByFilePathPrefix(self, MatchPrefixes, DoNotMatchPrefixes):
201 Types = set()
202 for Type in self.__FcDict:
203 for pathregex in self.__FcDict[Type]:
204 if not MatchPathPrefixes(pathregex, MatchPrefixes):
205 continue
206 if MatchPathPrefixes(pathregex, DoNotMatchPrefixes):
207 continue
208 Types.add(Type)
209 return Types
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700210
211
Dan Cashman91d398d2017-09-26 12:58:29 -0700212 def __GetTERules(self, policydbP, avtabIterP, Rules):
213 if Rules is None:
214 Rules = set()
215 buf = create_string_buffer(self.__BUFSIZE)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700216 ret = 0
217 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -0700218 ret = self.__libsepolwrap.get_allow_rule(buf, self.__BUFSIZE,
219 policydbP, avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700220 if ret == 0:
221 Rule = TERule(buf.value)
Dan Cashman91d398d2017-09-26 12:58:29 -0700222 Rules.add(Rule)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700223 continue
224 if ret == 1:
225 break;
226 # We should never get here.
227 sys.exit("Failed to import policy")
228
229 def __InitTERules(self):
Dan Cashman91d398d2017-09-26 12:58:29 -0700230 avtabIterP = self.__libsepolwrap.init_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700231 if (avtabIterP == None):
232 sys.exit("Failed to initialize avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700233 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
234 self.__libsepolwrap.destroy_avtab(avtabIterP)
235 avtabIterP = self.__libsepolwrap.init_cond_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700236 if (avtabIterP == None):
237 sys.exit("Failed to initialize conditional avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700238 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
239 self.__libsepolwrap.destroy_avtab(avtabIterP)
240
241 def __InitExpandedTERules(self):
242 avtabIterP = self.__libsepolwrap.init_expanded_avtab(self.__policydbP)
243 if (avtabIterP == None):
244 sys.exit("Failed to initialize avtab")
245 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
246 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
247 avtabIterP = self.__libsepolwrap.init_expanded_cond_avtab(self.__policydbP)
248 if (avtabIterP == None):
249 sys.exit("Failed to initialize conditional avtab")
250 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
251 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700252
253 # load ctypes-ified libsepol wrapper
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700254 def __InitLibsepolwrap(self, LibPath):
255 if "linux" in sys.platform:
Dan Cashman91d398d2017-09-26 12:58:29 -0700256 lib = CDLL(LibPath + "/libsepolwrap.so")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700257 elif "darwin" in sys.platform:
Dan Cashman91d398d2017-09-26 12:58:29 -0700258 lib = CDLL(LibPath + "/libsepolwrap.dylib")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700259 else:
260 sys.exit("only Linux and Mac currrently supported")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700261
Dan Cashman91d398d2017-09-26 12:58:29 -0700262 # int get_allow_rule(char *out, size_t len, void *policydbp, void *avtab_iterp);
263 lib.get_allow_rule.restype = c_int
264 lib.get_allow_rule.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p];
265 # void *load_policy(const char *policy_path);
266 lib.load_policy.restype = c_void_p
267 lib.load_policy.argtypes = [c_char_p]
268 # void destroy_policy(void *policydbp);
269 lib.destroy_policy.argtypes = [c_void_p]
270 # void *init_expanded_avtab(void *policydbp);
271 lib.init_expanded_avtab.restype = c_void_p
272 lib.init_expanded_avtab.argtypes = [c_void_p]
273 # void *init_expanded_cond_avtab(void *policydbp);
274 lib.init_expanded_cond_avtab.restype = c_void_p
275 lib.init_expanded_cond_avtab.argtypes = [c_void_p]
276 # void destroy_expanded_avtab(void *avtab_iterp);
277 lib.destroy_expanded_avtab.argtypes = [c_void_p]
278 # void *init_avtab(void *policydbp);
279 lib.init_avtab.restype = c_void_p
280 lib.init_avtab.argtypes = [c_void_p]
281 # void *init_cond_avtab(void *policydbp);
282 lib.init_cond_avtab.restype = c_void_p
283 lib.init_cond_avtab.argtypes = [c_void_p]
284 # void destroy_avtab(void *avtab_iterp);
285 lib.destroy_avtab.argtypes = [c_void_p]
286 # int get_type(char *out, size_t max_size, void *policydbp, void *type_iterp);
287 lib.get_type.restype = c_int
288 lib.get_type.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]
289 # void *init_type_iter(void *policydbp, const char *type, bool is_attr);
290 lib.init_type_iter.restype = c_void_p
291 lib.init_type_iter.argtypes = [c_void_p, c_char_p, c_bool]
292 # void destroy_type_iter(void *type_iterp);
293 lib.destroy_type_iter.argtypes = [c_void_p]
294
295 self.__libsepolwrap = lib
296
297
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700298 # load file_contexts
299 def __InitFC(self, FcPaths):
Dan Cashman91d398d2017-09-26 12:58:29 -0700300 if FcPaths is None:
301 return
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700302 fc = []
303 for path in FcPaths:
304 if not os.path.exists(path):
305 sys.exit("file_contexts file " + path + " does not exist.")
306 fd = open(path, "r")
307 fc += fd.readlines()
308 fd.close()
309 self.__FcDict = {}
310 for i in fc:
311 rec = i.split()
312 try:
313 t = rec[-1].split(":")[2]
314 if t in self.__FcDict:
315 self.__FcDict[t].append(rec[0])
316 else:
317 self.__FcDict[t] = [rec[0]]
318 except:
319 pass
320
321 # load policy
322 def __InitPolicy(self, PolicyPath):
Dan Cashman91d398d2017-09-26 12:58:29 -0700323 cPolicyPath = create_string_buffer(PolicyPath)
324 self.__policydbP = self.__libsepolwrap.load_policy(cPolicyPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700325 if (self.__policydbP is None):
326 sys.exit("Failed to load policy")
327
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700328 def __init__(self, PolicyPath, FcPaths, LibPath):
329 self.__InitLibsepolwrap(LibPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700330 self.__InitFC(FcPaths)
331 self.__InitPolicy(PolicyPath)
332
333 def __del__(self):
334 if self.__policydbP is not None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700335 self.__libsepolwrap.destroy_policy(self.__policydbP)