blob: 4bc9c9118cdb352b8347ef99972dfa54ad6166c4 [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 Stoepbdfc0302017-05-25 09:53:47 -07006
Dan Cashman91d398d2017-09-26 12:58:29 -07007###
8# Check whether the regex will match a file path starting with the provided
9# prefix
10#
11# Compares regex entries in file_contexts with a path prefix. Regex entries
12# are often more specific than this file prefix. For example, the regex could
13# be /system/bin/foo\.sh and the prefix could be /system. This function
14# loops over the regex removing characters from the end until
15# 1) there is a match - return True or 2) run out of characters - return
16# False.
17#
18def MatchPathPrefix(pathregex, prefix):
19 for i in range(len(pathregex), 0, -1):
20 try:
21 pattern = re.compile('^' + pathregex[0:i] + "$")
22 except:
23 continue
24 if pattern.match(prefix):
25 return True
26 return False
27
28def MatchPathPrefixes(pathregex, Prefixes):
29 for Prefix in Prefixes:
30 if MatchPathPrefix(pathregex, Prefix):
31 return True
32 return False
33
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070034class TERule:
35 def __init__(self, rule):
36 data = rule.split(',')
37 self.flavor = data[0]
38 self.sctx = data[1]
39 self.tctx = data[2]
40 self.tclass = data[3]
41 self.perms = set((data[4].strip()).split(' '))
42 self.rule = rule
43
44class Policy:
Dan Cashman91d398d2017-09-26 12:58:29 -070045 __ExpandedRules = set()
46 __Rules = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070047 __FcDict = None
48 __libsepolwrap = None
49 __policydbP = None
Dan Cashman91d398d2017-09-26 12:58:29 -070050 __BUFSIZE = 2048
51
52 # Check that path prefixes that match MatchPrefix, and do not Match
53 # DoNotMatchPrefix have the attribute Attr.
54 # For example assert that all types in /sys, and not in /sys/kernel/debugfs
55 # have the sysfs_type attribute.
56 def AssertPathTypesHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr):
57 # Query policy for the types associated with Attr
58 TypesPol = self.QueryTypeAttribute(Attr, True)
59 # Search file_contexts to find paths/types that should be associated with
60 # Attr.
61 TypesFc = self.__GetTypesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix)
62 violators = TypesFc.difference(TypesPol)
63
64 ret = ""
65 if len(violators) > 0:
66 ret += "The following types on "
67 ret += " ".join(str(x) for x in sorted(MatchPrefix))
68 ret += " must be associated with the "
69 ret += "\"" + Attr + "\" attribute: "
70 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
71 return ret
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070072
73 # Return all file_contexts entries that map to the input Type.
74 def QueryFc(self, Type):
75 if Type in self.__FcDict:
76 return self.__FcDict[Type]
77 else:
78 return None
79
80 # Return all attributes associated with a type if IsAttr=False or
81 # all types associated with an attribute if IsAttr=True
82 def QueryTypeAttribute(self, Type, IsAttr):
Dan Cashman91d398d2017-09-26 12:58:29 -070083 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP,
84 create_string_buffer(Type), IsAttr)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070085 if (TypeIterP == None):
86 sys.exit("Failed to initialize type iterator")
Dan Cashman91d398d2017-09-26 12:58:29 -070087 buf = create_string_buffer(self.__BUFSIZE)
88 TypeAttr = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070089 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -070090 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
91 self.__policydbP, TypeIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070092 if ret == 0:
Dan Cashman91d398d2017-09-26 12:58:29 -070093 TypeAttr.add(buf.value)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070094 continue
95 if ret == 1:
96 break;
97 # We should never get here.
98 sys.exit("Failed to import policy")
Dan Cashman91d398d2017-09-26 12:58:29 -070099 self.__libsepolwrap.destroy_type_iter(TypeIterP)
100 return TypeAttr
101
102 def __TERuleMatch(self, Rule, **kwargs):
103 # Match source type
104 if ("scontext" in kwargs and
105 len(kwargs['scontext']) > 0 and
106 Rule.sctx not in kwargs['scontext']):
107 return False
108 # Match target type
109 if ("tcontext" in kwargs and
110 len(kwargs['tcontext']) > 0 and
111 Rule.tctx not in kwargs['tcontext']):
112 return False
113 # Match target class
114 if ("tclass" in kwargs and
115 len(kwargs['tclass']) > 0 and
116 not bool(set([Rule.tclass]) & kwargs['tclass'])):
117 return False
118 # Match any perms
119 if ("perms" in kwargs and
120 len(kwargs['perms']) > 0 and
121 not bool(Rule.perms & kwargs['perms'])):
122 return False
123 return True
124
125 # resolve a type to its attributes or
126 # resolve an attribute to its types and attributes
127 # For example if scontext is the domain attribute, then we need to
128 # include all types with the domain attribute such as untrusted_app and
129 # priv_app and all the attributes of those types such as appdomain.
130 def ResolveTypeAttribute(self, Type):
131 types = self.GetAllTypes(False)
132 attributes = self.GetAllTypes(True)
133
134 if Type in types:
135 return self.QueryTypeAttribute(Type, False)
136 elif Type in attributes:
137 TypesAndAttributes = set()
138 Types = self.QueryTypeAttribute(Type, True)
139 TypesAndAttributes |= Types
140 for T in Types:
141 TypesAndAttributes |= self.QueryTypeAttribute(T, False)
142 return TypesAndAttributes
143 else:
144 return set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700145
146 # Return all TERules that match:
147 # (any scontext) or (any tcontext) or (any tclass) or (any perms),
148 # perms.
149 # Any unspecified paramenter will match all.
150 #
151 # Example: QueryTERule(tcontext=["foo", "bar"], perms=["entrypoint"])
152 # Will return any rule with:
153 # (tcontext="foo" or tcontext="bar") and ("entrypoint" in perms)
154 def QueryTERule(self, **kwargs):
Dan Cashman91d398d2017-09-26 12:58:29 -0700155 if len(self.__Rules) == 0:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700156 self.__InitTERules()
Dan Cashman91d398d2017-09-26 12:58:29 -0700157
158 # add any matching types and attributes for scontext and tcontext
159 if ("scontext" in kwargs and len(kwargs['scontext']) > 0):
160 scontext = set()
161 for sctx in kwargs['scontext']:
162 scontext |= self.ResolveTypeAttribute(sctx)
163 kwargs['scontext'] = scontext
164 if ("tcontext" in kwargs and len(kwargs['tcontext']) > 0):
165 tcontext = set()
166 for tctx in kwargs['tcontext']:
167 tcontext |= self.ResolveTypeAttribute(tctx)
168 kwargs['tcontext'] = tcontext
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700169 for Rule in self.__Rules:
Dan Cashman91d398d2017-09-26 12:58:29 -0700170 if self.__TERuleMatch(Rule, **kwargs):
171 yield Rule
172
173 # Same as QueryTERule but only using the expanded ruleset.
174 # i.e. all attributes have been expanded to their various types.
175 def QueryExpandedTERule(self, **kwargs):
176 if len(self.__ExpandedRules) == 0:
177 self.__InitExpandedTERules()
178 for Rule in self.__ExpandedRules:
179 if self.__TERuleMatch(Rule, **kwargs):
180 yield Rule
181
182 def GetAllTypes(self, isAttr):
183 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP, None, isAttr)
184 if (TypeIterP == None):
185 sys.exit("Failed to initialize type iterator")
186 buf = create_string_buffer(self.__BUFSIZE)
187 AllTypes = set()
188 while True:
189 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
190 self.__policydbP, TypeIterP)
191 if ret == 0:
192 AllTypes.add(buf.value)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700193 continue
Dan Cashman91d398d2017-09-26 12:58:29 -0700194 if ret == 1:
195 break;
196 # We should never get here.
197 sys.exit("Failed to import policy")
198 self.__libsepolwrap.destroy_type_iter(TypeIterP)
199 return AllTypes
200
201 def __GetTypesByFilePathPrefix(self, MatchPrefixes, DoNotMatchPrefixes):
202 Types = set()
203 for Type in self.__FcDict:
204 for pathregex in self.__FcDict[Type]:
205 if not MatchPathPrefixes(pathregex, MatchPrefixes):
206 continue
207 if MatchPathPrefixes(pathregex, DoNotMatchPrefixes):
208 continue
209 Types.add(Type)
210 return Types
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700211
212
Dan Cashman91d398d2017-09-26 12:58:29 -0700213 def __GetTERules(self, policydbP, avtabIterP, Rules):
214 if Rules is None:
215 Rules = set()
216 buf = create_string_buffer(self.__BUFSIZE)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700217 ret = 0
218 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -0700219 ret = self.__libsepolwrap.get_allow_rule(buf, self.__BUFSIZE,
220 policydbP, avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700221 if ret == 0:
222 Rule = TERule(buf.value)
Dan Cashman91d398d2017-09-26 12:58:29 -0700223 Rules.add(Rule)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700224 continue
225 if ret == 1:
226 break;
227 # We should never get here.
228 sys.exit("Failed to import policy")
229
230 def __InitTERules(self):
Dan Cashman91d398d2017-09-26 12:58:29 -0700231 avtabIterP = self.__libsepolwrap.init_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700232 if (avtabIterP == None):
233 sys.exit("Failed to initialize avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700234 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
235 self.__libsepolwrap.destroy_avtab(avtabIterP)
236 avtabIterP = self.__libsepolwrap.init_cond_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700237 if (avtabIterP == None):
238 sys.exit("Failed to initialize conditional avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700239 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
240 self.__libsepolwrap.destroy_avtab(avtabIterP)
241
242 def __InitExpandedTERules(self):
243 avtabIterP = self.__libsepolwrap.init_expanded_avtab(self.__policydbP)
244 if (avtabIterP == None):
245 sys.exit("Failed to initialize avtab")
246 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
247 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
248 avtabIterP = self.__libsepolwrap.init_expanded_cond_avtab(self.__policydbP)
249 if (avtabIterP == None):
250 sys.exit("Failed to initialize conditional avtab")
251 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
252 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700253
254 # load ctypes-ified libsepol wrapper
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700255 def __InitLibsepolwrap(self, LibPath):
Jeff Vander Stoepe9777e32017-09-23 15:11:25 -0700256 if "linux" in platform.system().lower():
Dan Cashman91d398d2017-09-26 12:58:29 -0700257 lib = CDLL(LibPath + "/libsepolwrap.so")
Jeff Vander Stoepe9777e32017-09-23 15:11:25 -0700258 elif "darwin" in platform.system().lower():
Dan Cashman91d398d2017-09-26 12:58:29 -0700259 lib = CDLL(LibPath + "/libsepolwrap.dylib")
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700260 else:
Jeff Vander Stoepe9777e32017-09-23 15:11:25 -0700261 sys.exit("policy.py: " + platform.system() + " not supported." +
262 " Only Linux and Darwin platforms are currently supported.")
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700263
Dan Cashman91d398d2017-09-26 12:58:29 -0700264 # int get_allow_rule(char *out, size_t len, void *policydbp, void *avtab_iterp);
265 lib.get_allow_rule.restype = c_int
266 lib.get_allow_rule.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p];
267 # void *load_policy(const char *policy_path);
268 lib.load_policy.restype = c_void_p
269 lib.load_policy.argtypes = [c_char_p]
270 # void destroy_policy(void *policydbp);
271 lib.destroy_policy.argtypes = [c_void_p]
272 # void *init_expanded_avtab(void *policydbp);
273 lib.init_expanded_avtab.restype = c_void_p
274 lib.init_expanded_avtab.argtypes = [c_void_p]
275 # void *init_expanded_cond_avtab(void *policydbp);
276 lib.init_expanded_cond_avtab.restype = c_void_p
277 lib.init_expanded_cond_avtab.argtypes = [c_void_p]
278 # void destroy_expanded_avtab(void *avtab_iterp);
279 lib.destroy_expanded_avtab.argtypes = [c_void_p]
280 # void *init_avtab(void *policydbp);
281 lib.init_avtab.restype = c_void_p
282 lib.init_avtab.argtypes = [c_void_p]
283 # void *init_cond_avtab(void *policydbp);
284 lib.init_cond_avtab.restype = c_void_p
285 lib.init_cond_avtab.argtypes = [c_void_p]
286 # void destroy_avtab(void *avtab_iterp);
287 lib.destroy_avtab.argtypes = [c_void_p]
288 # int get_type(char *out, size_t max_size, void *policydbp, void *type_iterp);
289 lib.get_type.restype = c_int
290 lib.get_type.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]
291 # void *init_type_iter(void *policydbp, const char *type, bool is_attr);
292 lib.init_type_iter.restype = c_void_p
293 lib.init_type_iter.argtypes = [c_void_p, c_char_p, c_bool]
294 # void destroy_type_iter(void *type_iterp);
295 lib.destroy_type_iter.argtypes = [c_void_p]
296
297 self.__libsepolwrap = lib
298
299
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700300 # load file_contexts
301 def __InitFC(self, FcPaths):
Dan Cashman91d398d2017-09-26 12:58:29 -0700302 if FcPaths is None:
303 return
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700304 fc = []
305 for path in FcPaths:
306 if not os.path.exists(path):
307 sys.exit("file_contexts file " + path + " does not exist.")
308 fd = open(path, "r")
309 fc += fd.readlines()
310 fd.close()
311 self.__FcDict = {}
312 for i in fc:
313 rec = i.split()
314 try:
315 t = rec[-1].split(":")[2]
316 if t in self.__FcDict:
317 self.__FcDict[t].append(rec[0])
318 else:
319 self.__FcDict[t] = [rec[0]]
320 except:
321 pass
322
323 # load policy
324 def __InitPolicy(self, PolicyPath):
Dan Cashman91d398d2017-09-26 12:58:29 -0700325 cPolicyPath = create_string_buffer(PolicyPath)
326 self.__policydbP = self.__libsepolwrap.load_policy(cPolicyPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700327 if (self.__policydbP is None):
328 sys.exit("Failed to load policy")
329
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700330 def __init__(self, PolicyPath, FcPaths, LibPath):
331 self.__InitLibsepolwrap(LibPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700332 self.__InitFC(FcPaths)
333 self.__InitPolicy(PolicyPath)
334
335 def __del__(self):
336 if self.__policydbP is not None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700337 self.__libsepolwrap.destroy_policy(self.__policydbP)