Debian Codegraph @

src/bonsai/active_directory/__init__.py

raw symbols SCIP
1 import struct
2
3 from typing import Dict, Optional, Union
4
5 from .sid import SID
6 from .acl import ACL, ACLRevision, ACE, ACEFlag, ACERight, ACEType
7
8
9 class SecurityDescriptor:
10 """
11 A class that defines the security attributes of an object. These
12 attributes specify who owns the object; who can access the object and
13 what they can do with it; what level of audit logging can be applied to
14 the object; and what kind of restrictions apply to the use of the
15 security descriptor. It can contain two types of :class:`ACL`:
16
17 * A discretionary access control list (DACL) is controlled by the
18 owner of an object or anyone granted WRITE_DAC access to the object.
19 It specifies the access particular users and groups can have to an
20 object. For example, the owner of a file can use a DACL to control
21 which users and groups can and cannot have access to the file.
22 * A system access control list (SACL) is similar to the DACL, except
23 that the SACL is used to audit rather than control access to an
24 object. When an audited action occurs, the operating system records
25 the event in the security log. Each ACE in a SACL has a header that
26 indicates whether auditing is triggered by success, failure, or
27 both; a SID that specifies a particular user or security group to
28 monitor; and an access mask that lists the operations to audit.
29
30 :param dict control: a dict that specifies control access bit flags.
31 :param SID|None owner_sid: the SID of the owner of the object.
32 :param SID|None group_sid: the SID of the group of the object.
33 :param ACL|None sacl: the system access control list.
34 :param ACL|None dacl: the discretionary access control list.
35 :param int revision: the revision of the security descriptor.
36 :param int sbz1: reserved value.
37 """
38
39 def __init__(
40 self,
41 control: Dict[str, bool],
42 owner_sid: Optional[SID],
43 group_sid: Optional[SID],
44 sacl: Optional[ACL],
45 dacl: Optional[ACL],
46 revision: int = 1,
47 sbz1: int = 0,
48 ) -> None:
49 self.__revision = revision
50 self.__sbz1 = sbz1
51 self.__control = control
52 self.__owner_sid = owner_sid
53 self.__group_sid = group_sid
54 self.__sacl = sacl
55 self.__dacl = dacl
56
57 @staticmethod
58 def __convert_ctrl(ctrl, to_int=False):
59 values = {
60 "self_relative": 0x8000,
61 "rm_control_valid": 0x4000,
62 "sacl_protected": 0x2000,
63 "dacl_protected": 0x1000,
64 "sacl_auto_inherited": 0x800,
65 "dacl_auto_inherited": 0x400,
66 "sacl_computed_inheritance_required": 0x200,
67 "dacl_computed_inheritance_required": 0x100,
68 "server_security": 0x80,
69 "dacl_trusted": 0x40,
70 "sacl_defaulted": 0x20,
71 "sacl_present": 0x10,
72 "dacl_defaulted": 0x8,
73 "dacl_present": 0x4,
74 "group_defaulted": 0x2,
75 "owner_defaulted": 0x1,
76 }
77 if to_int:
78 return sum(values[key] for key, val in ctrl.items() if val)
79 else:
80 return {key: bool(ctrl & val) for key, val in values.items()}
81
82 @classmethod
83 def from_binary(cls, data: bytes) -> "SecurityDescriptor":
84 """
85 Create a SecurityDescriptor object from a binary blob.
86
87 :param bytes data: a little-endian byte ordered byte input.
88 :returns: A new SecurityDescriptor instance.
89 :rtype: SecurityDescriptor
90 :raises TypeError: when the parameter is not bytes.
91 :raises ValueError: when the input cannot be parsed as a
92 SecurityDescriptor object.
93 """
94 try:
95 if not isinstance(data, bytes):
96 raise TypeError("The `data` parameter must be bytes")
97 sacl = None
98 dacl = None
99 (
100 rev,
101 sbz1,
102 ctrl,
103 offset_owner,
104 offset_group,
105 offset_sacl,
106 offset_dacl,
107 ) = struct.unpack("<BBHIIII", data[:20])
108 ctrl = cls.__convert_ctrl(ctrl)
109 owner_sid = SID(bytes_le=data[offset_owner:]) if offset_owner else None
110 group_sid = SID(bytes_le=data[offset_group:]) if offset_group else None
111 if ctrl["sacl_present"] and offset_sacl != 0:
112 sacl = ACL.from_binary(data[offset_sacl:])
113 if ctrl["dacl_present"] and offset_dacl != 0:
114 dacl = ACL.from_binary(data[offset_dacl:])
115 return cls(ctrl, owner_sid, group_sid, sacl, dacl, rev, sbz1)
116 except struct.error as err:
117 raise ValueError(f"Not a valid binary SecurityDescriptor, {err}")
118
119 def to_binary(self) -> bytes:
120 """
121 Convert SecurityDescriptor object to binary form with little-endian byte order.
122
123 :returns: Bytes of the binary SecurityDescriptor instance
124 :rtype: bytes
125 """
126 owner = b""
127 group = b""
128 sacl = b""
129 dacl = b""
130 offset_owner = 0
131 offset_group = 0
132 offset_sacl = 0
133 offset_dacl = 0
134 ctrl = self.__convert_ctrl(self.control, True)
135 data = bytearray(20)
136 if self.owner_sid:
137 owner = self.owner_sid.bytes_le
138 offset_owner = 20
139 if self.group_sid:
140 group = self.group_sid.bytes_le
141 offset_group = 20 + len(owner)
142 if self.sacl:
143 sacl = self.sacl.to_binary()
144 offset_sacl = 20 + len(owner) + len(group)
145 if self.dacl:
146 dacl = self.dacl.to_binary()
147 offset_dacl = 20 + len(owner) + len(group) + len(sacl)
148 struct.pack_into(
149 "<BBHIIII",
150 data,
151 0,
152 self.revision,
153 self.sbz1,
154 ctrl,
155 offset_owner,
156 offset_group,
157 offset_sacl,
158 offset_dacl,
159 )
160 data.extend(owner)
161 data.extend(group)
162 data.extend(sacl)
163 data.extend(dacl)
164 return bytes(data)
165
166 def set_control(self, control: Union[Dict[str, bool], int]) -> None:
167 """
168 Set the control access bit flags for the SecurityDescriptor object.
169
170 :param dict|int control: the control flag either as an int or a dict.
171 :raises ValueError: if the provided number is not valid.
172 :raises TypeError: if the parameter neither an int nor a bool value \
173 only dict.
174 """
175 if isinstance(control, int):
176 ctrl = self.__convert_ctrl(control)
177 if control != self.__convert_ctrl(ctrl, to_int=True):
178 raise ValueError(f"{control} is not a valid controll flag.")
179 self.__control = ctrl
180 elif isinstance(control, dict) and all(
181 isinstance(val, bool) for val in control.values()
182 ):
183 self.__control = control
184 else:
185 raise TypeError(
186 "The control parameter must be an int or bool value only dictionary."
187 )
188
189 def set_owner_sid(self, owner_sid: SID) -> None:
190 """
191 Set the owner SID for the the SecurityDescriptor object.
192
193 :param SID owner_sid: the new owner SID.
194 :raises TypeError: if the parameter is not a SID object.
195 """
196 if not isinstance(owner_sid, SID):
197 raise TypeError("The owner_sid must be a SID object.")
198 self.__owner_sid = owner_sid
199
200 def set_group_sid(self, group_sid: SID) -> None:
201 """
202 Set the group SID for the the SecurityDescriptor object.
203
204 :param SID group_sid: the new group SID.
205 :raises TypeError: if the parameter is not a SID object.
206 """
207 if not isinstance(group_sid, SID):
208 raise TypeError("The group_sid must be a SID object.")
209 self.__group_sid = group_sid
210
211 def set_dacl(self, dacl: Optional[ACL]) -> None:
212 """
213 Set the discretionary ACL for the the SecurityDescriptor object.
214 It also sets the `dacl_present` in the control access bit flags
215 accordingly.
216
217 :param ACL|None dacl: the ACL object or None.
218 :raises TypeError: if the parameter is not a ACL object or None.
219 """
220 if dacl is not None and not isinstance(dacl, ACL):
221 raise TypeError("The dacl must be an ACL object or None.")
222 self.__dacl = dacl
223 if dacl is not None:
224 self.__control["dacl_present"] = True
225 else:
226 self.__control["dacl_present"] = False
227
228 def set_sacl(self, sacl: Optional[ACL]) -> None:
229 """
230 Set the system ACL for the the SecurityDescriptor object.
231 It also sets the `sacl_present` in the control access bit flags
232 accordingly.
233
234 :param ACL|None dacl: the ACL object or None.
235 :raises TypeError: if the parameter is not a ACL object or None.
236 """
237 if sacl is not None and not isinstance(sacl, ACL):
238 raise TypeError("The sacl must be an ACL object or None.")
239 self.__sacl = sacl
240 if sacl is not None:
241 self.__control["sacl_present"] = True
242 else:
243 self.__control["sacl_present"] = False
244
245 @property
246 def sbz1(self) -> int:
247 """Reserved field in the security descriptor structure."""
248 return self.__sbz1
249
250 @property
251 def revision(self) -> int:
252 """The revision of the security descriptor."""
253 return self.__revision
254
255 @property
256 def control(self) -> Dict[str, bool]:
257 """The dict of the control access bit flags."""
258 return self.__control
259
260 @control.setter
261 def control(self, value: Union[Dict[str, bool], int]) -> None:
262 self.set_control(value)
263
264 @property
265 def owner_sid(self) -> Optional[SID]:
266 """The :class:`SID` of the owner."""
267 return self.__owner_sid
268
269 @owner_sid.setter
270 def owner_sid(self, value: SID) -> None:
271 self.set_owner_sid(value)
272
273 @property
274 def group_sid(self) -> Optional[SID]:
275 """The :class:`SID` of the group."""
276 return self.__group_sid
277
278 @group_sid.setter
279 def group_sid(self, value: SID) -> None:
280 self.set_group_sid(value)
281
282 @property
283 def sacl(self) -> Optional[ACL]:
284 """The system :class:`ACL`."""
285 return self.__sacl
286
287 @sacl.setter
288 def sacl(self, value: Optional[ACL]) -> None:
289 self.set_sacl(value)
290
291 @property
292 def dacl(self) -> Optional[ACL]:
293 """The discretionary :class:`ACL`."""
294 return self.__dacl
295
296 @dacl.setter
297 def dacl(self, value: Optional[ACL]) -> None:
298 self.set_dacl(value)
299
300
301 class UserAccountControl:
302 """
303 A class for parsing UserAccountControl field.
304
305 :param int flags: integer representing the property flags.
306 :raises TypeError: if flags parameter is not an int.
307 """
308
309 def __init__(self, flags: int) -> None:
310 if not isinstance(flags, int):
311 raise TypeError("The `flags` parameter must be an integer")
312 self.__flag_values = {
313 "script": 0x1,
314 "accountdisable": 0x2,
315 "homedir_required": 0x8,
316 "lockout": 0x10,
317 "passwd_notreqd": 0x20,
318 "passwd_cant_change": 0x40,
319 "encrypted_text_pwd_allowed": 0x80,
320 "temp_duplicate_account": 0x100,
321 "normal_account": 0x200,
322 "interdomain_trust_account": 0x800,
323 "workstation_trust_account": 0x1000,
324 "server_trust_account": 0x2000,
325 "dont_expire_password": 0x10000,
326 "mns_logon_account": 0x20000,
327 "smartcard_required": 0x40000,
328 "trusted_for_delegation": 0x80000,
329 "not_delegated": 0x100000,
330 "use_des_key_only": 0x200000,
331 "dont_req_preauth": 0x400000,
332 "password_expired": 0x800000,
333 "trusted_to_auth_for_delegation": 0x1000000,
334 "partial_secrets_account": 0x4000000,
335 }
336 self.__properties = {
337 key: bool(flags & val) for key, val in self.__flag_values.items()
338 }
339
340 @property
341 def properties(self) -> Dict[str, bool]:
342 """Dictionary of the UserAccountControl properties."""
343 return self.__properties
344
345 @property
346 def value(self) -> int:
347 """The integer value of the properties."""
348 return sum(
349 self.__flag_values[key] for key, val in self.properties.items() if val
350 )
351
352
353 __all__ = [
354 "ACE",
355 "ACEFlag",
356 "ACERight",
357 "ACEType",
358 "ACL",
359 "ACLRevision",
360 "SecurityDescriptor",
361 "SID",
362 "UserAccountControl",
363 ]