blob: 06157fd163b860909db6cd60039e6b1623b1d981 [file] [log] [blame]
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +11001# Copyright 2021 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070015from ctypes import *
16import re
17import os
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -070018import sys
Jeff Vander Stoepe9777e32017-09-23 15:11:25 -070019import platform
Jeff Vander Stoep1ca7a4c2019-04-10 16:53:17 -070020import fc_sort
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070021
Dan Cashman91d398d2017-09-26 12:58:29 -070022###
23# Check whether the regex will match a file path starting with the provided
24# prefix
25#
26# Compares regex entries in file_contexts with a path prefix. Regex entries
27# are often more specific than this file prefix. For example, the regex could
28# be /system/bin/foo\.sh and the prefix could be /system. This function
29# loops over the regex removing characters from the end until
30# 1) there is a match - return True or 2) run out of characters - return
31# False.
32#
33def MatchPathPrefix(pathregex, prefix):
34 for i in range(len(pathregex), 0, -1):
35 try:
36 pattern = re.compile('^' + pathregex[0:i] + "$")
37 except:
38 continue
39 if pattern.match(prefix):
40 return True
41 return False
42
43def MatchPathPrefixes(pathregex, Prefixes):
44 for Prefix in Prefixes:
45 if MatchPathPrefix(pathregex, Prefix):
46 return True
47 return False
48
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070049class TERule:
50 def __init__(self, rule):
51 data = rule.split(',')
52 self.flavor = data[0]
53 self.sctx = data[1]
54 self.tctx = data[2]
55 self.tclass = data[3]
56 self.perms = set((data[4].strip()).split(' '))
57 self.rule = rule
58
59class Policy:
Dan Cashman91d398d2017-09-26 12:58:29 -070060 __ExpandedRules = set()
61 __Rules = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070062 __FcDict = None
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080063 __FcSorted = None
Jeff Vander Stoep1b828442018-03-21 17:27:20 -070064 __GenfsDict = None
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -070065 __libsepolwrap = None
66 __policydbP = None
Dan Cashman91d398d2017-09-26 12:58:29 -070067 __BUFSIZE = 2048
68
Alan Stokes668e74f2020-11-12 18:08:18 +000069 def AssertPathTypesDoNotHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr, ExcludedTypes = []):
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080070 # Query policy for the types associated with Attr
Alan Stokes668e74f2020-11-12 18:08:18 +000071 TypesPol = self.QueryTypeAttribute(Attr, True) - set(ExcludedTypes)
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080072 # Search file_contexts to find types associated with input paths.
Steven Moreland7f116502020-11-03 23:18:32 +000073 TypesFc, Files = self.__GetTypesAndFilesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix)
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080074 violators = TypesFc.intersection(TypesPol)
75 ret = ""
76 if len(violators) > 0:
77 ret += "The following types on "
78 ret += " ".join(str(x) for x in sorted(MatchPrefix))
79 ret += " must not be associated with the "
80 ret += "\"" + Attr + "\" attribute: "
81 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
Steven Moreland7f116502020-11-03 23:18:32 +000082 ret += " corresponding to files: "
83 ret += " ".join(str(x) for x in sorted(Files)) + "\n"
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -080084 return ret
85
Jeff Vander Stoep1b828442018-03-21 17:27:20 -070086 # Check that all types for "filesystem" have "attribute" associated with them
87 # for types labeled in genfs_contexts.
88 def AssertGenfsFilesystemTypesHaveAttr(self, Filesystem, Attr):
89 TypesPol = self.QueryTypeAttribute(Attr, True)
90 TypesGenfs = self.__GenfsDict[Filesystem]
91 violators = TypesGenfs.difference(TypesPol)
92
93 ret = ""
94 if len(violators) > 0:
95 ret += "The following types in " + Filesystem
96 ret += " must be associated with the "
97 ret += "\"" + Attr + "\" attribute: "
98 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
99 return ret
100
Dan Cashman91d398d2017-09-26 12:58:29 -0700101 # Check that path prefixes that match MatchPrefix, and do not Match
102 # DoNotMatchPrefix have the attribute Attr.
103 # For example assert that all types in /sys, and not in /sys/kernel/debugfs
104 # have the sysfs_type attribute.
105 def AssertPathTypesHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr):
106 # Query policy for the types associated with Attr
107 TypesPol = self.QueryTypeAttribute(Attr, True)
108 # Search file_contexts to find paths/types that should be associated with
109 # Attr.
Steven Moreland7f116502020-11-03 23:18:32 +0000110 TypesFc, Files = self.__GetTypesAndFilesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix)
Dan Cashman91d398d2017-09-26 12:58:29 -0700111 violators = TypesFc.difference(TypesPol)
112
113 ret = ""
114 if len(violators) > 0:
115 ret += "The following types on "
116 ret += " ".join(str(x) for x in sorted(MatchPrefix))
117 ret += " must be associated with the "
118 ret += "\"" + Attr + "\" attribute: "
119 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
Steven Moreland7f116502020-11-03 23:18:32 +0000120 ret += " corresponding to files: "
121 ret += " ".join(str(x) for x in sorted(Files)) + "\n"
Dan Cashman91d398d2017-09-26 12:58:29 -0700122 return ret
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700123
Inseob Kim1b8b1f62020-10-23 15:16:11 +0900124 def AssertPropertyOwnersAreExclusive(self):
125 systemProps = self.QueryTypeAttribute('system_property_type', True)
126 vendorProps = self.QueryTypeAttribute('vendor_property_type', True)
127 violators = systemProps.intersection(vendorProps)
128 ret = ""
129 if len(violators) > 0:
130 ret += "The following types have both system_property_type "
131 ret += "and vendor_property_type: "
132 ret += " ".join(str(x) for x in sorted(violators)) + "\n"
133 return ret
134
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700135 # Return all file_contexts entries that map to the input Type.
136 def QueryFc(self, Type):
137 if Type in self.__FcDict:
138 return self.__FcDict[Type]
139 else:
140 return None
141
142 # Return all attributes associated with a type if IsAttr=False or
143 # all types associated with an attribute if IsAttr=True
144 def QueryTypeAttribute(self, Type, IsAttr):
Dan Cashman91d398d2017-09-26 12:58:29 -0700145 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP,
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100146 create_string_buffer(Type.encode("ascii")), IsAttr)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700147 if (TypeIterP == None):
148 sys.exit("Failed to initialize type iterator")
Dan Cashman91d398d2017-09-26 12:58:29 -0700149 buf = create_string_buffer(self.__BUFSIZE)
150 TypeAttr = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700151 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -0700152 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
153 self.__policydbP, TypeIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700154 if ret == 0:
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100155 TypeAttr.add(buf.value.decode("ascii"))
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700156 continue
157 if ret == 1:
158 break;
159 # We should never get here.
160 sys.exit("Failed to import policy")
Dan Cashman91d398d2017-09-26 12:58:29 -0700161 self.__libsepolwrap.destroy_type_iter(TypeIterP)
162 return TypeAttr
163
164 def __TERuleMatch(self, Rule, **kwargs):
165 # Match source type
166 if ("scontext" in kwargs and
167 len(kwargs['scontext']) > 0 and
168 Rule.sctx not in kwargs['scontext']):
169 return False
170 # Match target type
171 if ("tcontext" in kwargs and
172 len(kwargs['tcontext']) > 0 and
173 Rule.tctx not in kwargs['tcontext']):
174 return False
175 # Match target class
176 if ("tclass" in kwargs and
177 len(kwargs['tclass']) > 0 and
178 not bool(set([Rule.tclass]) & kwargs['tclass'])):
179 return False
180 # Match any perms
181 if ("perms" in kwargs and
182 len(kwargs['perms']) > 0 and
183 not bool(Rule.perms & kwargs['perms'])):
184 return False
185 return True
186
187 # resolve a type to its attributes or
188 # resolve an attribute to its types and attributes
189 # For example if scontext is the domain attribute, then we need to
190 # include all types with the domain attribute such as untrusted_app and
191 # priv_app and all the attributes of those types such as appdomain.
192 def ResolveTypeAttribute(self, Type):
193 types = self.GetAllTypes(False)
194 attributes = self.GetAllTypes(True)
195
196 if Type in types:
197 return self.QueryTypeAttribute(Type, False)
198 elif Type in attributes:
199 TypesAndAttributes = set()
200 Types = self.QueryTypeAttribute(Type, True)
201 TypesAndAttributes |= Types
202 for T in Types:
203 TypesAndAttributes |= self.QueryTypeAttribute(T, False)
204 return TypesAndAttributes
205 else:
206 return set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700207
208 # Return all TERules that match:
209 # (any scontext) or (any tcontext) or (any tclass) or (any perms),
210 # perms.
211 # Any unspecified paramenter will match all.
212 #
213 # Example: QueryTERule(tcontext=["foo", "bar"], perms=["entrypoint"])
214 # Will return any rule with:
215 # (tcontext="foo" or tcontext="bar") and ("entrypoint" in perms)
216 def QueryTERule(self, **kwargs):
Dan Cashman91d398d2017-09-26 12:58:29 -0700217 if len(self.__Rules) == 0:
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700218 self.__InitTERules()
Dan Cashman91d398d2017-09-26 12:58:29 -0700219
220 # add any matching types and attributes for scontext and tcontext
221 if ("scontext" in kwargs and len(kwargs['scontext']) > 0):
222 scontext = set()
223 for sctx in kwargs['scontext']:
224 scontext |= self.ResolveTypeAttribute(sctx)
225 kwargs['scontext'] = scontext
226 if ("tcontext" in kwargs and len(kwargs['tcontext']) > 0):
227 tcontext = set()
228 for tctx in kwargs['tcontext']:
229 tcontext |= self.ResolveTypeAttribute(tctx)
230 kwargs['tcontext'] = tcontext
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700231 for Rule in self.__Rules:
Dan Cashman91d398d2017-09-26 12:58:29 -0700232 if self.__TERuleMatch(Rule, **kwargs):
233 yield Rule
234
235 # Same as QueryTERule but only using the expanded ruleset.
236 # i.e. all attributes have been expanded to their various types.
237 def QueryExpandedTERule(self, **kwargs):
238 if len(self.__ExpandedRules) == 0:
239 self.__InitExpandedTERules()
240 for Rule in self.__ExpandedRules:
241 if self.__TERuleMatch(Rule, **kwargs):
242 yield Rule
243
244 def GetAllTypes(self, isAttr):
245 TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP, None, isAttr)
246 if (TypeIterP == None):
247 sys.exit("Failed to initialize type iterator")
248 buf = create_string_buffer(self.__BUFSIZE)
249 AllTypes = set()
250 while True:
251 ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE,
252 self.__policydbP, TypeIterP)
253 if ret == 0:
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100254 AllTypes.add(buf.value.decode("ascii"))
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700255 continue
Dan Cashman91d398d2017-09-26 12:58:29 -0700256 if ret == 1:
257 break;
258 # We should never get here.
259 sys.exit("Failed to import policy")
260 self.__libsepolwrap.destroy_type_iter(TypeIterP)
261 return AllTypes
262
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800263 def __ExactMatchPathPrefix(self, pathregex, prefix):
264 pattern = re.compile('^' + pathregex + "$")
265 if pattern.match(prefix):
266 return True
267 return False
268
269 # Return a tuple (prefix, i) where i is the index of the most specific
270 # match of prefix in the sorted file_contexts. This is useful for limiting a
271 # file_contexts search to matches that are more specific and omitting less
272 # specific matches. For example, finding all matches to prefix /data/vendor
273 # should not include /data(/.*)? if /data/vendor(/.*)? is also specified.
274 def __FcSortedIndex(self, prefix):
275 index = 0
276 for i in range(0, len(self.__FcSorted)):
277 if self.__ExactMatchPathPrefix(self.__FcSorted[i].path, prefix):
278 index = i
279 return prefix, index
280
281 # Return a tuple of (path, Type) for all matching paths. Use the sorted
282 # file_contexts and index returned from __FcSortedIndex() to limit results
283 # to results that are more specific than the prefix.
284 def __MatchPathPrefixTypes(self, prefix, index):
285 PathType = []
286 for i in range(index, len(self.__FcSorted)):
287 if MatchPathPrefix(self.__FcSorted[i].path, prefix):
Thiébaud Weksteenb75b4d22021-11-24 14:44:28 +1100288 PathType.append((self.__FcSorted[i].path, self.__FcSorted[i].type))
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800289 return PathType
290
291 # Return types that match MatchPrefixes but do not match
292 # DoNotMatchPrefixes
Steven Moreland7f116502020-11-03 23:18:32 +0000293 def __GetTypesAndFilesByFilePathPrefix(self, MatchPrefixes, DoNotMatchPrefixes):
Dan Cashman91d398d2017-09-26 12:58:29 -0700294 Types = set()
Steven Moreland7f116502020-11-03 23:18:32 +0000295 Files = set()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700296
Jeff Vander Stoep370a52f2018-02-08 09:54:59 -0800297 MatchPrefixesWithIndex = []
298 for MatchPrefix in MatchPrefixes:
299 MatchPrefixesWithIndex.append(self.__FcSortedIndex(MatchPrefix))
300
301 for MatchPrefixWithIndex in MatchPrefixesWithIndex:
302 PathTypes = self.__MatchPathPrefixTypes(*MatchPrefixWithIndex)
303 for PathType in PathTypes:
304 if MatchPathPrefixes(PathType[0], DoNotMatchPrefixes):
305 continue
306 Types.add(PathType[1])
Steven Moreland7f116502020-11-03 23:18:32 +0000307 Files.add(PathType[0])
308 return Types, Files
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700309
Dan Cashman91d398d2017-09-26 12:58:29 -0700310 def __GetTERules(self, policydbP, avtabIterP, Rules):
311 if Rules is None:
312 Rules = set()
313 buf = create_string_buffer(self.__BUFSIZE)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700314 ret = 0
315 while True:
Dan Cashman91d398d2017-09-26 12:58:29 -0700316 ret = self.__libsepolwrap.get_allow_rule(buf, self.__BUFSIZE,
317 policydbP, avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700318 if ret == 0:
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100319 Rule = TERule(buf.value.decode("ascii"))
Dan Cashman91d398d2017-09-26 12:58:29 -0700320 Rules.add(Rule)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700321 continue
322 if ret == 1:
323 break;
324 # We should never get here.
325 sys.exit("Failed to import policy")
326
327 def __InitTERules(self):
Dan Cashman91d398d2017-09-26 12:58:29 -0700328 avtabIterP = self.__libsepolwrap.init_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700329 if (avtabIterP == None):
330 sys.exit("Failed to initialize avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700331 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
332 self.__libsepolwrap.destroy_avtab(avtabIterP)
333 avtabIterP = self.__libsepolwrap.init_cond_avtab(self.__policydbP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700334 if (avtabIterP == None):
335 sys.exit("Failed to initialize conditional avtab")
Dan Cashman91d398d2017-09-26 12:58:29 -0700336 self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules)
337 self.__libsepolwrap.destroy_avtab(avtabIterP)
338
339 def __InitExpandedTERules(self):
340 avtabIterP = self.__libsepolwrap.init_expanded_avtab(self.__policydbP)
341 if (avtabIterP == None):
342 sys.exit("Failed to initialize avtab")
343 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
344 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
345 avtabIterP = self.__libsepolwrap.init_expanded_cond_avtab(self.__policydbP)
346 if (avtabIterP == None):
347 sys.exit("Failed to initialize conditional avtab")
348 self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules)
349 self.__libsepolwrap.destroy_expanded_avtab(avtabIterP)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700350
351 # load ctypes-ified libsepol wrapper
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700352 def __InitLibsepolwrap(self, LibPath):
Jeff Vander Stoep3ca843a2017-10-04 09:42:29 -0700353 lib = CDLL(LibPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700354
Dan Cashman91d398d2017-09-26 12:58:29 -0700355 # int get_allow_rule(char *out, size_t len, void *policydbp, void *avtab_iterp);
356 lib.get_allow_rule.restype = c_int
357 lib.get_allow_rule.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p];
358 # void *load_policy(const char *policy_path);
359 lib.load_policy.restype = c_void_p
360 lib.load_policy.argtypes = [c_char_p]
361 # void destroy_policy(void *policydbp);
362 lib.destroy_policy.argtypes = [c_void_p]
363 # void *init_expanded_avtab(void *policydbp);
364 lib.init_expanded_avtab.restype = c_void_p
365 lib.init_expanded_avtab.argtypes = [c_void_p]
366 # void *init_expanded_cond_avtab(void *policydbp);
367 lib.init_expanded_cond_avtab.restype = c_void_p
368 lib.init_expanded_cond_avtab.argtypes = [c_void_p]
369 # void destroy_expanded_avtab(void *avtab_iterp);
370 lib.destroy_expanded_avtab.argtypes = [c_void_p]
371 # void *init_avtab(void *policydbp);
372 lib.init_avtab.restype = c_void_p
373 lib.init_avtab.argtypes = [c_void_p]
374 # void *init_cond_avtab(void *policydbp);
375 lib.init_cond_avtab.restype = c_void_p
376 lib.init_cond_avtab.argtypes = [c_void_p]
377 # void destroy_avtab(void *avtab_iterp);
378 lib.destroy_avtab.argtypes = [c_void_p]
379 # int get_type(char *out, size_t max_size, void *policydbp, void *type_iterp);
380 lib.get_type.restype = c_int
381 lib.get_type.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]
382 # void *init_type_iter(void *policydbp, const char *type, bool is_attr);
383 lib.init_type_iter.restype = c_void_p
384 lib.init_type_iter.argtypes = [c_void_p, c_char_p, c_bool]
385 # void destroy_type_iter(void *type_iterp);
386 lib.destroy_type_iter.argtypes = [c_void_p]
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700387 # void *init_genfs_iter(void *policydbp)
388 lib.init_genfs_iter.restype = c_void_p
389 lib.init_genfs_iter.argtypes = [c_void_p]
390 # int get_genfs(char *out, size_t max_size, void *genfs_iterp);
391 lib.get_genfs.restype = c_int
392 lib.get_genfs.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]
393 # void destroy_genfs_iter(void *genfs_iterp)
394 lib.destroy_genfs_iter.argtypes = [c_void_p]
Dan Cashman91d398d2017-09-26 12:58:29 -0700395
396 self.__libsepolwrap = lib
397
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700398 def __GenfsDictAdd(self, Dict, buf):
399 fs, path, context = buf.split(" ")
400 Type = context.split(":")[2]
401 if not fs in Dict:
402 Dict[fs] = {Type}
403 else:
404 Dict[fs].add(Type)
405
406 def __InitGenfsCon(self):
407 self.__GenfsDict = {}
408 GenfsIterP = self.__libsepolwrap.init_genfs_iter(self.__policydbP)
409 if (GenfsIterP == None):
410 sys.exit("Failed to retreive genfs entries")
411 buf = create_string_buffer(self.__BUFSIZE)
412 while True:
413 ret = self.__libsepolwrap.get_genfs(buf, self.__BUFSIZE,
414 self.__policydbP, GenfsIterP)
415 if ret == 0:
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100416 self.__GenfsDictAdd(self.__GenfsDict, buf.value.decode("ascii"))
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700417 continue
418 if ret == 1:
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100419 self.__GenfsDictAdd(self.__GenfsDict, buf.value.decode("ascii"))
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700420 break;
421 # We should never get here.
422 sys.exit("Failed to get genfs entries")
423 self.__libsepolwrap.destroy_genfs_iter(GenfsIterP)
Dan Cashman91d398d2017-09-26 12:58:29 -0700424
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700425 # load file_contexts
426 def __InitFC(self, FcPaths):
Dan Cashman91d398d2017-09-26 12:58:29 -0700427 if FcPaths is None:
428 return
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700429 fc = []
430 for path in FcPaths:
431 if not os.path.exists(path):
432 sys.exit("file_contexts file " + path + " does not exist.")
433 fd = open(path, "r")
434 fc += fd.readlines()
435 fd.close()
436 self.__FcDict = {}
437 for i in fc:
438 rec = i.split()
439 try:
440 t = rec[-1].split(":")[2]
441 if t in self.__FcDict:
442 self.__FcDict[t].append(rec[0])
443 else:
444 self.__FcDict[t] = [rec[0]]
445 except:
446 pass
Thiébaud Weksteenb75b4d22021-11-24 14:44:28 +1100447 self.__FcSorted = fc_sort.sort(FcPaths)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700448
449 # load policy
450 def __InitPolicy(self, PolicyPath):
Thiébaud Weksteenf24b4572021-11-26 09:12:41 +1100451 cPolicyPath = create_string_buffer(PolicyPath.encode("ascii"))
Dan Cashman91d398d2017-09-26 12:58:29 -0700452 self.__policydbP = self.__libsepolwrap.load_policy(cPolicyPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700453 if (self.__policydbP is None):
454 sys.exit("Failed to load policy")
455
Jeff Vander Stoep1fc06822017-05-31 15:36:07 -0700456 def __init__(self, PolicyPath, FcPaths, LibPath):
457 self.__InitLibsepolwrap(LibPath)
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700458 self.__InitFC(FcPaths)
459 self.__InitPolicy(PolicyPath)
Jeff Vander Stoep1b828442018-03-21 17:27:20 -0700460 self.__InitGenfsCon()
Jeff Vander Stoepbdfc0302017-05-25 09:53:47 -0700461
462 def __del__(self):
463 if self.__policydbP is not None:
Dan Cashman91d398d2017-09-26 12:58:29 -0700464 self.__libsepolwrap.destroy_policy(self.__policydbP)