Debian Codegraph @

src/bonsai/active_directory/sid.py

raw symbols SCIP
1 import struct
2
3 from typing import Any, Optional, Tuple
4
5
6 class SID:
7 """
8 A class for representing a Security Identifier, that identifies users,
9 groups, and computer accounts on a Microsoft Windows platform.
10
11 :param str|None str_rep: a string representation of a SID.
12 :param bytes|None bytes_le: a bytes representation of a SID in little-endian
13 byte order.
14 :raises TypeError: when the type of the parameters are invalid, or both
15 parameters are given.
16 :raises ValueError: when the given parameter cannot be parsed as a valid
17 SID.
18 """
19
20 def __init__(
21 self, str_rep: Optional[str] = None, bytes_le: Optional[bytes] = None
22 ) -> None:
23 if str_rep is not None and bytes_le is not None:
24 raise TypeError(
25 "Only one of the `str_rep` or `bytes_le` parameter must be given"
26 )
27 if str_rep is not None:
28 try:
29 if not isinstance(str_rep, str):
30 raise TypeError("The `str_rep` parameter must be a string")
31 parts = str_rep.split("-")
32 if parts[0] != "S":
33 raise ValueError()
34 self.__revision = int(parts[1])
35 self.__identifier_authority = (
36 int(parts[2], 16) if "0x" in parts[2] else int(parts[2])
37 )
38 self.__subauthorities = tuple(int(sub) for sub in parts[3:])
39 except (ValueError, IndexError):
40 raise ValueError(f"String `{str_rep}` is not a valid SID")
41 if bytes_le is not None:
42 try:
43 if not isinstance(bytes_le, bytes):
44 raise TypeError("The `bytes_le` parameter must be bytes")
45 self.__revision, subauth_count, *identifier_auth = struct.unpack(
46 "<BB6B", bytes_le[:8]
47 )
48 self.__subauthorities = struct.unpack(
49 f"<{subauth_count}I", bytes_le[8 : 8 + (subauth_count * 4)]
50 )
51 self.__identifier_authority = sum(
52 num << ((5 - i) * 8) for i, num in enumerate(identifier_auth)
53 )
54 except struct.error as err:
55 raise ValueError(f"Not a valid binary SID, {err}")
56
57 def __str__(self) -> str:
58 """Return the string format of the SID."""
59 ident_auth = (
60 hex(self.__identifier_authority)
61 if self.__identifier_authority > 2**32
62 else self.__identifier_authority
63 )
64 subauths = (
65 "-".join(str(sub) for sub in self.__subauthorities)
66 if self.__subauthorities
67 else "0"
68 )
69 return f"S-1-{ident_auth}-{subauths}"
70
71 def __repr__(self) -> str:
72 """The representation of SID class."""
73 return f"<{self.__class__.__name__}: {str(self)}>"
74
75 def __eq__(self, other: object) -> bool:
76 """
77 Check equality of two SIDs by their identifier_authority and list
78 of subauthorities, or if the other object is a string than by their
79 string formats.
80 """
81 if isinstance(other, SID):
82 return (
83 self.revision == other.revision
84 and self.identifier_authority == other.identifier_authority
85 and self.subauthorities == other.subauthorities
86 )
87 elif isinstance(other, str):
88 return str(self) == other
89 else:
90 return NotImplemented
91
92 def __hash__(self) -> int:
93 return hash(str(self))
94
95 @property
96 def revision(self) -> int:
97 """The revision level of the SID."""
98 return self.__revision
99
100 @property
101 def identifier_authority(self) -> int:
102 """
103 The indentifier that indicates the authority under which
104 the SID was created.
105 """
106 return self.__identifier_authority
107
108 @property
109 def subauthorities(self) -> Tuple[int, ...]:
110 """
111 A tuple of subauthorities that uniquely identifies a principal
112 relative to the identifier authority.
113 """
114 return self.__subauthorities
115
116 @property
117 def bytes_le(self) -> bytes:
118 """The byte format of the SID in little-endian byte order."""
119 subauth_count = len(self.subauthorities)
120 identifier_auth = [
121 item for item in struct.pack(">Q", self.identifier_authority)[2:]
122 ]
123 return struct.pack(
124 f"<BB6B{subauth_count}I",
125 self.revision,
126 subauth_count,
127 *identifier_auth,
128 *self.subauthorities,
129 )
130
131 @property
132 def sddl_alias(self) -> Optional[str]:
133 """
134 The string SDDL alias of the SID if it exists, otherwise it's None.
135 """
136 aliases = {
137 "S-1-1-0": "WD",
138 "S-1-15-2-1": "AC",
139 "S-1-16-12288": "HI",
140 "S-1-16-16384": "SI",
141 "S-1-16-4096": "LW",
142 "S-1-16-8192": "ME",
143 "S-1-16-8448": "MP",
144 "S-1-3-0": "CO",
145 "S-1-3-1": "CG",
146 "S-1-3-4": "OW",
147 "S-1-5-10": "PS",
148 "S-1-5-11": "AU",
149 "S-1-5-12": "RC",
150 "S-1-5-14": "IU",
151 "S-1-5-18": "SY",
152 "S-1-5-19": "LS",
153 "S-1-5-2": "NU",
154 "S-1-5-20": "NS",
155 "S-1-5-32-544": "BA",
156 "S-1-5-32-545": "BU",
157 "S-1-5-32-546": "BG",
158 "S-1-5-32-547": "PU",
159 "S-1-5-32-548": "AO",
160 "S-1-5-32-549": "SO",
161 "S-1-5-32-550": "PO",
162 "S-1-5-32-551": "BO",
163 "S-1-5-32-552": "RE",
164 "S-1-5-32-554": "RU",
165 "S-1-5-32-555": "RD",
166 "S-1-5-32-556": "NO",
167 "S-1-5-32-558": "MU",
168 "S-1-5-32-559": "LU",
169 "S-1-5-32-568": "IS",
170 "S-1-5-32-569": "CY",
171 "S-1-5-32-573": "ER",
172 "S-1-5-32-574": "CD",
173 "S-1-5-32-575": "RA",
174 "S-1-5-32-576": "ES",
175 "S-1-5-32-577": "MS",
176 "S-1-5-32-578": "HA",
177 "S-1-5-32-579": "AA",
178 "S-1-5-32-580": "RM",
179 "S-1-5-33": "WR",
180 "S-1-5-6": "SU",
181 "S-1-5-7": "AN",
182 "S-1-5-84-0-0-0-0-0": "UD",
183 "S-1-5-9": "ED",
184 }
185 domain_aliases = {
186 498: "RO",
187 500: "LA",
188 501: "LG",
189 512: "DA",
190 513: "DU",
191 514: "DG",
192 515: "DC",
193 516: "DD",
194 517: "CA",
195 518: "SA",
196 519: "EA",
197 520: "PA",
198 522: "CN",
199 }
200 alias = aliases.get(str(self), None)
201 if alias:
202 return alias
203 elif self.identifier_authority == 5 and self.subauthorities[0] == 21:
204 alias = domain_aliases.get(self.subauthorities[-1], None)
205 return alias
206
207 @property
208 def size(self) -> int:
209 """The binary size of the SID in bytes."""
210 return 8 + len(self.subauthorities) * 4