Debian Codegraph @

src/bonsai/active_directory/acl.py

raw symbols SCIP
1 import struct
2 import uuid
3
4 from enum import IntEnum
5 from typing import List, Optional, Set, Union
6
7 from .sid import SID
8
9
10 class ACEFlag(IntEnum):
11 """ACE type-specific control flags."""
12
13 OBJECT_INHERIT = 0x01
14 CONTAINER_INHERIT = 0x02
15 NO_PROPAGATE_INHERIT = 0x04
16 INHERIT_ONLY = 0x08
17 INHERITED = 0x10
18 SUCCESSFUL_ACCESS = 0x40
19 FAILED_ACCESS = 0x80
20
21 @property
22 def short_name(self) -> str:
23 """The SDDL short name of the flag."""
24 short_names = {
25 "OBJECT_INHERIT": "OI",
26 "CONTAINER_INHERIT": "CI",
27 "NO_PROPAGATE_INHERIT": "NP",
28 "INHERIT_ONLY": "IO",
29 "INHERITED": "ID",
30 "SUCCESSFUL_ACCESS": "SA",
31 "FAILED_ACCESS": "FA",
32 }
33 return short_names[self.name]
34
35
36 class ACEType(IntEnum):
37 """Type of the ACE."""
38
39 ACCESS_ALLOWED = 0
40 ACCESS_DENIED = 1
41 SYSTEM_AUDIT = 2
42 SYSTEM_ALARM = 3
43 ACCESS_ALLOWED_COMPOUND = 4
44 ACCESS_ALLOWED_OBJECT = 5
45 ACCESS_DENIED_OBJECT = 6
46 SYSTEM_AUDIT_OBJECT = 7
47 SYSTEM_ALARM_OBJECT = 8
48 ACCESS_ALLOWED_CALLBACK = 9
49 ACCESS_DENIED_CALLBACK = 10
50 ACCESS_ALLOWED_CALLBACK_OBJECT = 11
51 ACCESS_DENIED_CALLBACK_OBJECT = 12
52 SYSTEM_AUDIT_CALLBACK = 13
53 SYSTEM_ALARM_CALLBACK = 14
54 SYSTEM_AUDIT_CALLBACK_OBJECT = 15
55 SYSTEM_ALARM_CALLBACK_OBJECT = 16
56 SYSTEM_MANDATORY_LABEL = 17
57 SYSTEM_RESOURCE_ATTRIBUTE = 18
58 SYSTEM_SCOPED_POLICY_ID = 19
59
60 @property
61 def short_name(self) -> str:
62 """The SDDL short name of the type."""
63 short_names = {
64 "ACCESS_ALLOWED": "A",
65 "ACCESS_DENIED": "D",
66 "SYSTEM_AUDIT": "AU",
67 "SYSTEM_ALARM": "AL",
68 "ACCESS_ALLOWED_COMPOUND": "",
69 "ACCESS_ALLOWED_OBJECT": "OA",
70 "ACCESS_DENIED_OBJECT": "OD",
71 "SYSTEM_AUDIT_OBJECT": "OU",
72 "SYSTEM_ALARM_OBJECT": "OL",
73 "ACCESS_ALLOWED_CALLBACK": "XA",
74 "ACCESS_DENIED_CALLBACK": "XD",
75 "ACCESS_ALLOWED_CALLBACK_OBJECT": "ZA",
76 "ACCESS_DENIED_CALLBACK_OBJECT": "ZD",
77 "SYSTEM_AUDIT_CALLBACK": "XU",
78 "SYSTEM_ALARM_CALLBACK": "XL",
79 "SYSTEM_AUDIT_CALLBACK_OBJECT": "ZU",
80 "SYSTEM_ALARM_CALLBACK_OBJECT": "ZL",
81 "SYSTEM_MANDATORY_LABEL": "ML",
82 "SYSTEM_RESOURCE_ATTRIBUTE": "RA",
83 "SYSTEM_SCOPED_POLICY_ID": "SP",
84 }
85 return short_names[self.name]
86
87 @property
88 def is_object_type(self) -> bool:
89 """Flag for ACE types with objects."""
90 return self in (
91 ACEType.ACCESS_ALLOWED_OBJECT,
92 ACEType.ACCESS_DENIED_OBJECT,
93 ACEType.SYSTEM_AUDIT_OBJECT,
94 ACEType.SYSTEM_ALARM_OBJECT,
95 ACEType.ACCESS_ALLOWED_CALLBACK_OBJECT,
96 ACEType.ACCESS_DENIED_CALLBACK_OBJECT,
97 ACEType.SYSTEM_AUDIT_CALLBACK_OBJECT,
98 ACEType.SYSTEM_ALARM_CALLBACK_OBJECT,
99 )
100
101 @property
102 def is_access_allowed(self) -> bool:
103 """Flag for ACE types that allow access."""
104 return self in (
105 ACEType.ACCESS_ALLOWED,
106 ACEType.ACCESS_ALLOWED_COMPOUND,
107 ACEType.ACCESS_ALLOWED_OBJECT,
108 ACEType.ACCESS_ALLOWED_CALLBACK,
109 ACEType.ACCESS_ALLOWED_CALLBACK_OBJECT,
110 )
111
112 @property
113 def is_access_denied(self) -> bool:
114 """Flag for ACE types that deny access."""
115 return self in (
116 ACEType.ACCESS_DENIED,
117 ACEType.ACCESS_DENIED_OBJECT,
118 ACEType.ACCESS_DENIED_CALLBACK,
119 ACEType.ACCESS_DENIED_CALLBACK_OBJECT,
120 )
121
122
123 class ACERight(IntEnum):
124 """The rights of the ACE."""
125
126 GENERIC_READ = 0x80000000
127 GENERIC_WRITE = 0x4000000
128 GENERIC_EXECUTE = 0x20000000
129 GENERIC_ALL = 0x10000000
130 MAXIMUM_ALLOWED = 0x02000000
131 ACCESS_SYSTEM_SECURITY = 0x01000000
132 SYNCHRONIZE = 0x00100000
133 WRITE_OWNER = 0x00080000
134 WRITE_DACL = 0x00040000
135 READ_CONTROL = 0x00020000
136 DELETE = 0x00010000
137 DS_CONTROL_ACCESS = 0x00000100
138 DS_CREATE_CHILD = 0x00000001
139 DS_DELETE_CHILD = 0x00000002
140 ACTRL_DS_LIST = 0x00000004
141 DS_SELF = 0x00000008
142 DS_READ_PROP = 0x00000010
143 DS_WRITE_PROP = 0x00000020
144 DS_DELETE_TREE = 0x00000040
145 DS_LIST_OBJECT = 0x00000080
146
147 @property
148 def short_name(self) -> str:
149 """The SDDL short name of the access right."""
150 short_names = {
151 "GENERIC_READ": "GR",
152 "GENERIC_WRITE": "GW",
153 "GENERIC_EXECUTE": "GX",
154 "GENERIC_ALL": "GA",
155 "MAXIMUM_ALLOWED": "MA",
156 "ACCESS_SYSTEM_SECURITY": "AS",
157 "SYNCHRONIZE": "SY",
158 "WRITE_OWNER": "WO",
159 "WRITE_DACL": "WD",
160 "READ_CONTROL": "RC",
161 "DELETE": "SD",
162 "DS_CONTROL_ACCESS": "CR",
163 "DS_CREATE_CHILD": "CC",
164 "DS_DELETE_CHILD": "DC",
165 "ACTRL_DS_LIST": "LC",
166 "DS_SELF": "SW",
167 "DS_READ_PROP": "RP",
168 "DS_WRITE_PROP": "WP",
169 "DS_DELETE_TREE": "DT",
170 "DS_LIST_OBJECT": "LO",
171 }
172 return short_names[self.name]
173
174
175 class ACLRevision(IntEnum):
176 """The ACL revision."""
177
178 ACL_REVISION = 0x02
179 ACL_REVISION_DS = 0x04
180
181
182 class ACE:
183 """
184 A class for the access control entry, that encodes the user rights
185 afforded to a principal.
186
187 :param ACEType ace_type: the type of the ACE.
188 :param Set[ACEFlag] flags: the set of flags for the ACE.
189 :param int mask: the access mask to encode the user rights as an int.
190 :param SID trustee_sid: the SID of the trustee.
191 :param uuid.UUID|None object_type: a UUID that identifies a property
192 set, property, extended right, or type of child object.
193 :param uuid.UUID|None inherited_object_type: a UUID that identifies the
194 type of child object that can inherit the ACE.
195 :param bytes application_data: optional application data.
196 """
197
198 def __init__(
199 self,
200 ace_type: ACEType,
201 flags: Set[ACEFlag],
202 mask: int,
203 trustee_sid: SID,
204 object_type: Optional[uuid.UUID],
205 inherited_object_type: Optional[uuid.UUID],
206 application_data: bytes,
207 ) -> None:
208 self.__type = ace_type
209 self.__flags = flags
210 self.__mask = mask
211 self.__object_type = object_type
212 self.__inherited_object_type = inherited_object_type
213 self.__trustee_sid = trustee_sid
214 self.__application_data = application_data
215
216 @classmethod
217 def from_binary(cls, data: bytes) -> "ACE":
218 """
219 Create an ACE object from a binary blob.
220
221 :param bytes data: a little-endian byte ordered byte input.
222 :returns: A new ACE instance.
223 :rtype: ACE
224 :raises TypeError: when the parameter is not bytes.
225 :raises ValueError: when the input cannot be parsed as an ACE
226 object.
227 """
228 try:
229 if not isinstance(data, bytes):
230 raise TypeError("The `data` parameter must be bytes")
231 object_type = None
232 inherited_object_type = None
233 application_data = None
234 ace_type, flags, size, mask = struct.unpack("<BBHL", data[:8])
235 pos = 8
236 if ACEType(ace_type).is_object_type:
237 obj_flag = struct.unpack("<I", data[8:12])[0]
238 pos += 4
239 if obj_flag & 0x00000001:
240 object_type = uuid.UUID(bytes_le=data[pos : pos + 16])
241 pos += 16
242 if obj_flag & 0x00000002:
243 inherited_object_type = uuid.UUID(bytes_le=data[pos : pos + 16])
244 pos += 16
245 trustee_sid = SID(bytes_le=data[pos:])
246 pos += trustee_sid.size
247 application_data = data[pos:size]
248 this = cls(
249 ACEType(ace_type),
250 {flg for flg in ACEFlag if flags & flg},
251 mask,
252 trustee_sid,
253 object_type,
254 inherited_object_type,
255 application_data,
256 )
257 return this
258 except struct.error as err:
259 raise ValueError(f"Not a valid binary ACE, {err}") from None
260
261 def __eq__(self, other: object) -> bool:
262 """
263 Check that ACE object equals to the other object. If the `other`
264 is also an ACE object, then basically comapre their byte
265 representations.
266
267 :param object other: the other object to compare.
268 """
269 if not isinstance(other, ACE):
270 return NotImplemented
271 if self.type != other.type or self.flags != other.flags:
272 return False
273 if self.size != other.size:
274 return False
275 return self.to_binary() == other.to_binary()
276
277 def __str__(self) -> str:
278 """Return the SDDL string representation of the ACE object."""
279 flags = "".join(
280 flg.short_name for flg in sorted(self.flags, key=lambda f: f.value)
281 )
282 rights = "".join(
283 rgt.short_name for rgt in sorted(self.rights, key=lambda r: r.value)
284 )
285 object_guid = self.object_type if self.object_type else ""
286 inherit_object_guid = (
287 self.inherited_object_type if self.inherited_object_type else ""
288 )
289 sid = (
290 self.trustee_sid.sddl_alias
291 if self.trustee_sid.sddl_alias
292 else str(self.trustee_sid)
293 )
294 return f"({self.type.short_name};{flags};{rights};{object_guid};{inherit_object_guid};{sid})"
295
296 def to_binary(self) -> bytes:
297 """
298 Convert ACE object to binary form with little-endian byte order.
299
300 :returns: Bytes of the binary ACE instance
301 :rtype: bytes
302 """
303 size = self.size
304 data = bytearray(size)
305 struct.pack_into(
306 "<BBHL", data, 0, self.type.value, sum(self.flags), size, self.mask
307 )
308 pos = 8
309 if self.type.is_object_type:
310 obj_flag = 0x00000001 if self.object_type else 0
311 obj_flag |= 0x00000002 if self.inherited_object_type else 0
312 struct.pack_into("<L", data, pos, obj_flag)
313 pos += 4
314 if self.object_type:
315 data[pos : pos + 16] = self.object_type.bytes_le
316 pos += 16
317 if self.inherited_object_type:
318 data[pos : pos + 16] = self.inherited_object_type.bytes_le
319 pos += 16
320 data[pos : pos + self.trustee_sid.size] = self.trustee_sid.bytes_le
321 pos += self.trustee_sid.size
322 data[pos : pos + size] = self.application_data
323 return bytes(data)
324
325 def set_access_rights(self, rights: Union[int, Set[ACERight]]) -> None:
326 """
327 Set the access rights for the ACE object. The `rights`
328 parameter can be a set of ACERight objects or an integer.
329
330 :param int|Set[ACERight] rights: the access rights
331 :raises TypeError: if the parameter not an int or not \
332 every item of the set is an ACERight object.
333 :raises ValueError: if the provided number is not a valid \
334 access mask.
335 """
336 if isinstance(rights, int):
337 if rights != sum({rgt for rgt in ACERight if rights & rgt}):
338 raise ValueError(
339 f"{rights} is not a valid access rights for an ACE object."
340 )
341 self.__mask = rights
342 elif all(isinstance(rgt, ACERight) for rgt in rights):
343 self.__mask = sum(rights)
344 else:
345 raise TypeError(
346 "The rights parameter must be an int or a set of ACERight objects."
347 )
348
349 def set_application_data(self, data: bytes) -> None:
350 """
351 Set application data for the ACE object.
352
353 :param bytes data: the application data.
354 :raises TypeError: if the data is not bytes.
355 """
356 if not isinstance(data, bytes):
357 raise TypeError("Application data must be bytes.")
358 self.__application_data = data
359
360 def set_flags(self, flags: Set[ACEFlag]) -> None:
361 """
362 Set flags for the ACE object.
363
364 :param Set[ACEFlag] flags: a set of ACEFlag objects.
365 :raises TypeError: if any of the elements in the set \
366 is not an ACEFlag object.
367 """
368 if not all(isinstance(flg, ACEFlag) for flg in flags):
369 raise TypeError("All elements in the set must be an ACEFlag.")
370 self.__flags = flags
371
372 def set_object_type(self, object_type: Optional[uuid.UUID]) -> None:
373 """
374 Set the object type for the ACE object.
375
376 :param uuid.UUID|None object_type: the uuid of the object type.
377 :raises TypeError: if the parameter is neither an UUID nor None.
378 """
379 if object_type is not None and not isinstance(object_type, uuid.UUID):
380 raise TypeError("Object type must be UUID or None.")
381 self.__object_type = object_type
382
383 def set_inherited_object_type(self, object_type: Optional[uuid.UUID]) -> None:
384 """
385 Set the inherited object type for the ACE object.
386
387 :param uuid.UUID|None object_type: the uuid of the inherited \
388 object type.
389 :raises TypeError: if the parameter is neither an UUID nor None.
390 """
391 if object_type is not None and not isinstance(object_type, uuid.UUID):
392 raise TypeError("Inherited object type must be UUID or None.")
393 self.__inherited_object_type = object_type
394
395 def set_type(self, ace_type: ACEType) -> None:
396 """
397 Set type for the ACE object.
398
399 :param ACEType ace_type: the type of the ACE object.
400 :raises TypeError: if the parameter is not an ACEType.
401 """
402 if not isinstance(ace_type, ACEType):
403 raise TypeError("The type property must be an ACEType.")
404 self.__type = ace_type
405
406 def set_trustee_sid(self, sid: SID) -> None:
407 """
408 Set the trustee SID for the ACE object.
409
410 :param SID sid: the trustee SID of the ACE object.
411 :raises TypeError: if the parameter is not a SID.
412 """
413 if not isinstance(sid, SID):
414 raise TypeError("The trustee sid property must be a SID object.")
415 self.__trustee_sid = sid
416
417 @property
418 def is_inherited(self) -> bool:
419 """Return true if the ACE object is inherited."""
420 return ACEFlag.INHERITED in self.flags
421
422 @property
423 def type(self) -> ACEType:
424 """The type of the ACE."""
425 return self.__type
426
427 @type.setter
428 def type(self, value: ACEType) -> None:
429 self.set_type(value)
430
431 @property
432 def flags(self) -> Set[ACEFlag]:
433 """The flags of the ACE."""
434 return self.__flags
435
436 @flags.setter
437 def flags(self, value: Set[ACEFlag]) -> None:
438 self.set_flags(value)
439
440 @property
441 def size(self) -> int:
442 """The binary size of ACE in bytes."""
443 size = 8
444 if self.type.is_object_type:
445 size += 4
446 if self.object_type:
447 size += 16
448 if self.inherited_object_type:
449 size += 16
450 size += self.trustee_sid.size
451 size += len(self.application_data)
452 return size
453
454 @property
455 def mask(self) -> int:
456 """The access mask"""
457 return self.__mask
458
459 @mask.setter
460 def mask(self, value: int) -> None:
461 self.set_access_rights(value)
462
463 @property
464 def rights(self) -> Set[ACERight]:
465 """The set of ACERights based on the access mask."""
466 return {rgt for rgt in ACERight if self.mask & rgt}
467
468 @rights.setter
469 def rights(self, value: Set[ACERight]) -> None:
470 self.set_access_rights(value)
471
472 @property
473 def object_type(self) -> Optional[uuid.UUID]:
474 """The uuid of the object type."""
475 return self.__object_type
476
477 @object_type.setter
478 def object_type(self, value: Optional[uuid.UUID]) -> None:
479 self.set_object_type(value)
480
481 @property
482 def inherited_object_type(self) -> Optional[uuid.UUID]:
483 """The uuid of the inherited object type."""
484 return self.__inherited_object_type
485
486 @inherited_object_type.setter
487 def inherited_object_type(self, value: Optional[uuid.UUID]) -> None:
488 self.set_inherited_object_type(value)
489
490 @property
491 def trustee_sid(self) -> SID:
492 """The sid of the trustee."""
493 return self.__trustee_sid
494
495 @trustee_sid.setter
496 def trustee_sid(self, value: SID) -> None:
497 self.set_trustee_sid(value)
498
499 @property
500 def application_data(self) -> bytes:
501 """The possible application data."""
502 return self.__application_data
503
504 @application_data.setter
505 def application_data(self, value: bytes) -> None:
506 self.set_application_data(value)
507
508
509 class ACL:
510 """
511 The access control list (ACL) is used to specify a list of individual
512 access control entries (ACEs). An ACL and an array of ACEs comprise a
513 complete access control list.
514
515 :param ACLRevision revision: the revision of the ACL.
516 :param List[ACE] aces: list of :class:`ACE`.
517 """
518
519 def __init__(self, revision: ACLRevision, aces: List[ACE]) -> None:
520 self.__revision = revision
521 self.__aces = aces
522
523 @classmethod
524 def from_binary(cls, data: bytes) -> "ACL":
525 """
526 Create an ACL object from a binary blob.
527
528 :param bytes data: a little-endian byte ordered byte input.
529 :returns: A new ACL instance.
530 :rtype: ACL
531 :raises TypeError: when the parameter is not bytes.
532 :raises ValueError: when the input cannot be parsed as an ACL
533 object.
534 """
535 try:
536 if not isinstance(data, bytes):
537 raise TypeError("The `data` parameter must be bytes")
538 # Unwanted values are the reserved sbz1, size and sbz2.
539 rev, _, _, count, _ = struct.unpack("<BBHHH", data[:8])
540 pos = 8
541 aces = []
542 for _ in range(count):
543 ace = ACE.from_binary(data[pos:])
544 aces.append(ace)
545 pos += ace.size
546 this = cls(ACLRevision(rev), aces)
547 return this
548 except struct.error as err:
549 raise ValueError(f"Not a valid binary ACL, {err}") from None
550
551 def to_binary(self) -> bytes:
552 """
553 Convert ACL object to binary form with little-endian byte order.
554
555 :returns: Bytes of the binary ACL instance
556 :rtype: bytes
557 """
558 size = self.size
559 data = bytearray(8)
560 struct.pack_into("<BBHHH", data, 0, self.revision, 0, size, len(self.aces), 0)
561 for ace in self.aces:
562 data.extend(ace.to_binary())
563 return bytes(data)
564
565 def set_aces(self, aces: List[ACE]) -> None:
566 """
567 Set a list of ACE object to the ACL.
568
569 :param List[ACE] aces: a list of ACE objects.
570 :raises TypeError: if not every element in the list is \
571 an ACE object.
572 """
573 if not all(isinstance(elem, ACE) for elem in aces):
574 raise TypeError("All elements in the list must be ACE objects.")
575 self.__aces = aces
576
577 @property
578 def revision(self) -> ACLRevision:
579 """The revision of ACL."""
580 return self.__revision
581
582 @property
583 def size(self) -> int:
584 """The binary size in bytes."""
585 return 8 + sum(ace.size for ace in self.aces)
586
587 @property
588 def aces(self) -> List[ACE]:
589 """The list of :class:`ACE` objects."""
590 return self.__aces
591
592 @aces.setter
593 def aces(self, value: List[ACE]) -> None:
594 self.set_aces(value)