Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/client.py

raw
1 # Copyright: (c) 2023, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # FOR INTERNAL COLLECTION USE ONLY
5 # The interfaces in this file are meant for use within this collection
6 # and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release.
7 # See also: https://github.com/ansible/community/issues/539#issuecomment-780839686
8 # Please open an issue if you have questions about this.
9
10 import dataclasses
11 import socket
12 import ssl
13 import threading
14 import typing as t
15
16 try:
17 import sansldap
18 except Exception:
19 pass # Check is in __init__.py
20
21
22 MessageType = t.TypeVar("MessageType", bound="sansldap.LDAPMessage")
23
24
25 class Credential:
26 """Credential for LDAP client.
27
28 Base object used to implementation authentication for the LDAP client.
29 """
30
31 def authenticate(
32 self,
33 client: "SyncLDAPClient",
34 *,
35 tls_sock: t.Optional[ssl.SSLSocket] = None,
36 ) -> None:
37 raise NotImplementedError()
38
39
40 class MessageEncryptor:
41 """Message encryptor for LDAP client.
42
43 Base object used by the LDAP client to encrypt and decrypt messages.
44 """
45
46 def wrap(
47 self,
48 data: bytes,
49 ) -> bytes:
50 raise NotImplementedError()
51
52 def unwrap(
53 self,
54 data: bytes,
55 ) -> t.Tuple[bytes, int]:
56 raise NotImplementedError()
57
58
59 class LDAPResultError(Exception):
60 def __init__(
61 self,
62 msg: str,
63 result: "sansldap.LDAPResult",
64 ) -> None:
65 super().__init__(msg)
66 self.result = result
67
68 def __str__(self) -> str:
69 inner_msg = super().__str__()
70 msg = f"Received LDAPResult error {inner_msg} - {self.result.result_code.name}"
71 if self.result.matched_dn:
72 msg += f" - Matched DN {self.result.matched_dn}"
73
74 if self.result.diagnostics_message:
75 msg += f" - {self.result.diagnostics_message}"
76
77 return msg
78
79
80 class ResponseHandler(t.Generic[MessageType]):
81 def __init__(
82 self,
83 message_id: int,
84 message_types: t.Tuple[t.Type[MessageType], ...],
85 ) -> None:
86 self._message_id = message_id
87 self._message_types = message_types
88 self._condition = threading.Condition()
89 self._exp: t.Optional[Exception] = None
90 self._results: t.List[MessageType] = []
91
92 def __iter__(self) -> t.Iterator[MessageType]:
93 return self._iter_next()
94
95 def append(
96 self,
97 value: t.Union[Exception, MessageType],
98 ) -> None:
99 with self._condition:
100 if isinstance(value, Exception):
101 self._exp = value
102 elif isinstance(value, self._message_types) and value.message_id == self._message_id:
103 self._results.append(value)
104 else:
105 return
106
107 self._condition.notify_all()
108
109 def _iter_next(self) -> t.Iterator[MessageType]:
110 idx = 0
111 while True:
112 with self._condition:
113 if self._exp:
114 raise Exception(f"Exception from receiving task: {self._exp}") from self._exp
115
116 if idx < len(self._results):
117 value = self._results[idx]
118 idx += 1
119 yield value
120
121 else:
122 self._condition.wait()
123
124
125 @dataclasses.dataclass(frozen=True)
126 class RootDSE:
127 default_naming_context: str
128 subschema_subentry: str
129 supported_controls: t.List[str]
130
131
132 class SyncLDAPClient:
133 def __init__(
134 self,
135 server: str,
136 protocol: "sansldap.LDAPClient",
137 sock: t.Union[socket.socket, ssl.SSLSocket],
138 ) -> None:
139 self.server = server
140
141 self._protocol = protocol
142 self._sock = sock
143 self._response_handler: t.List[ResponseHandler] = []
144 self._encryptor: t.Optional[MessageEncryptor] = None
145 self._reader_task = threading.Thread(
146 target=self._read_loop,
147 name=f"LDAP({server})",
148 )
149 self._reader_task.start()
150 self._root_dse: t.Optional[RootDSE] = None
151
152 @property
153 def root_dse(self) -> RootDSE:
154 if not self._root_dse:
155 default_naming_context = ""
156 subschema_subentry = ""
157 supported_controls: t.List[str] = []
158
159 for res in self._search_request(
160 base_object="",
161 scope=sansldap.SearchScope.BASE,
162 filter=sansldap.FilterPresent("objectClass"),
163 attributes=[
164 "defaultNamingContext",
165 "subschemaSubentry",
166 "supportedControl",
167 ],
168 ):
169 if not isinstance(res, sansldap.SearchResultEntry):
170 continue
171
172 for attr in res.attributes:
173 if attr.name == "defaultNamingContext":
174 default_naming_context = attr.values[0].decode("utf-8")
175
176 elif attr.name == "subschemaSubentry":
177 subschema_subentry = attr.values[0].decode("utf-8")
178
179 elif attr.name == "supportedControl":
180 supported_controls = [v.decode("utf-8") for v in attr.values]
181
182 self._root_dse = RootDSE(
183 default_naming_context=default_naming_context,
184 subschema_subentry=subschema_subentry,
185 supported_controls=supported_controls,
186 )
187
188 return self._root_dse
189
190 def __enter__(self) -> "SyncLDAPClient":
191 return self
192
193 def __exit__(self, *args: t.Any, **kwargs: t.Any) -> None:
194 self.close()
195
196 @classmethod
197 def start_tls(
198 cls,
199 protocol: "sansldap.LDAPClient",
200 sock: socket.socket,
201 ) -> None:
202 protocol.extended_request(sansldap.ExtendedOperations.LDAP_START_TLS)
203 data = protocol.data_to_send()
204 sock.sendall(data)
205
206 done = False
207 while not done:
208 data = sock.recv(4096)
209 for msg in protocol.receive(data):
210 msg = t.cast(sansldap.ExtendedResponse, msg)
211 if msg.result.result_code != sansldap.LDAPResultCode.SUCCESS:
212 raise LDAPResultError("StartTLS failed", msg.result)
213
214 done = True
215 break
216
217 def bind(
218 self,
219 dn: str,
220 credential: "sansldap.AuthenticationCredential",
221 success_only: bool = True,
222 ) -> t.Optional[bytes]:
223 msg_id = self._protocol.bind(dn, credential)
224 response = self._write_and_wait_one(msg_id, sansldap.BindResponse)
225
226 valid_codes = [sansldap.LDAPResultCode.SUCCESS]
227 if not success_only:
228 valid_codes.append(sansldap.LDAPResultCode.SASL_BIND_IN_PROGRESS)
229
230 if response.result.result_code not in valid_codes:
231 raise LDAPResultError("bind failed", response.result)
232
233 return response.server_sasl_creds
234
235 def close(self) -> None:
236 try:
237 self._sock.shutdown(socket.SHUT_RDWR)
238 except OSError:
239 # The socket has already been shutdown for some other reason
240 pass
241 self._sock.close()
242 self._reader_task.join()
243
244 def register_encryptor(
245 self,
246 encryptor: MessageEncryptor,
247 ) -> None:
248 self._encryptor = encryptor
249
250 def search(
251 self,
252 filter: t.Union[str, "sansldap.LDAPFilter"],
253 attributes: t.List[str],
254 search_base: t.Optional[str] = None,
255 search_scope: t.Optional["sansldap.SearchScope"] = None,
256 ) -> t.Dict[str, t.Dict[str, t.List[bytes]]]:
257 if search_base is None:
258 search_base = self.root_dse.default_naming_context
259
260 controls: t.List[sansldap.LDAPControl] = []
261 pagination_size = 1024
262
263 if sansldap.PagedResultControl.control_type in self.root_dse.supported_controls:
264 controls.append(sansldap.PagedResultControl(False, pagination_size, b""))
265
266 search_kwargs: t.Dict[str, t.Any] = {
267 "base_object": search_base,
268 "scope": search_scope,
269 "filter": filter,
270 "attributes": attributes,
271 }
272 res: t.Dict[str, t.Dict[str, t.List[bytes]]] = {}
273
274 while True:
275 for entry in self._search_request(
276 controls=controls,
277 **search_kwargs,
278 ):
279 if isinstance(entry, sansldap.SearchResultDone):
280 paginated_control = next(
281 iter(c for c in entry.controls if isinstance(c, sansldap.PagedResultControl)),
282 None,
283 )
284 if paginated_control and paginated_control.cookie:
285 controls = [sansldap.PagedResultControl(False, pagination_size, paginated_control.cookie)]
286 else:
287 controls = []
288
289 elif isinstance(entry, sansldap.SearchResultEntry):
290 entry_res = res.setdefault(entry.object_name, {})
291 for attr in entry.attributes:
292 entry_attr = entry_res.setdefault(attr.name, [])
293 entry_attr.extend(attr.values)
294
295 # SearchResultReference is ignored for now.
296
297 if not controls:
298 break
299
300 return res
301
302 def _search_request(
303 self,
304 base_object: t.Optional[str] = None,
305 scope: t.Optional[t.Union[int, "sansldap.SearchScope"]] = None,
306 dereferencing_policy: t.Optional[t.Union[int, "sansldap.DereferencingPolicy"]] = None,
307 size_limit: int = 0,
308 time_limit: int = 0,
309 types_only: bool = False,
310 filter: t.Optional[t.Union[str, "sansldap.LDAPFilter"]] = None,
311 attributes: t.Optional[t.List[str]] = None,
312 controls: t.Optional[t.List["sansldap.LDAPControl"]] = None,
313 ) -> t.Iterator[
314 t.Union["sansldap.SearchResultReference", "sansldap.SearchResultEntry", "sansldap.SearchResultDone"]
315 ]:
316 ldap_filter: t.Optional[sansldap.LDAPFilter] = None
317 if isinstance(filter, sansldap.LDAPFilter):
318 ldap_filter = filter
319 elif filter:
320 ldap_filter = sansldap.LDAPFilter.from_string(filter)
321
322 deref = dereferencing_policy if dereferencing_policy is not None else sansldap.DereferencingPolicy.NEVER
323
324 msg_id = self._protocol.search_request(
325 base_object=base_object,
326 scope=scope if scope is not None else sansldap.SearchScope.SUBTREE,
327 dereferencing_policy=deref,
328 size_limit=size_limit,
329 time_limit=time_limit,
330 types_only=types_only,
331 filter=ldap_filter,
332 attributes=attributes,
333 controls=controls,
334 )
335
336 handler = self._register_response_handler(
337 msg_id,
338 sansldap.SearchResultEntry,
339 sansldap.SearchResultReference,
340 sansldap.SearchResultDone,
341 )
342 try:
343 self._write_msg()
344 for res in handler:
345 yield res # type: ignore[misc]
346
347 if isinstance(res, sansldap.SearchResultDone):
348 self._valid_result(res.result, "search request failed")
349 break
350
351 finally:
352 self._unregister_response_handler(handler)
353
354 def _read_loop(self) -> None:
355 data_buffer = bytearray()
356 while True:
357 try:
358 resp = self._sock.recv(4096)
359 if not resp:
360 raise Exception("LDAP connection has been shutdown")
361
362 data_buffer.extend(resp)
363
364 while data_buffer:
365 if self._encryptor:
366 dec_data, enc_len = self._encryptor.unwrap(data_buffer)
367 if enc_len == 0:
368 break
369
370 data_buffer = data_buffer[enc_len:]
371 else:
372 dec_data = bytes(data_buffer)
373 data_buffer = bytearray()
374
375 for msg in self._protocol.receive(dec_data):
376 for handler in self._response_handler:
377 handler.append(msg)
378
379 except sansldap.ProtocolError as e:
380 if e.response:
381 self._sock.sendall(e.response)
382
383 for handler in self._response_handler:
384 handler.append(e)
385 break
386
387 except Exception as e:
388 for handler in self._response_handler:
389 handler.append(e)
390 break
391
392 def _register_response_handler(
393 self,
394 msg_id: int,
395 *message_types: t.Type[MessageType],
396 ) -> ResponseHandler[MessageType]:
397 handler = ResponseHandler(
398 msg_id,
399 message_types,
400 )
401 self._response_handler.append(handler)
402
403 return handler
404
405 def _valid_result(
406 self,
407 result: "sansldap.LDAPResult",
408 msg: str,
409 ) -> None:
410 if result.result_code != sansldap.LDAPResultCode.SUCCESS:
411 raise LDAPResultError(msg, result)
412
413 def _unregister_response_handler(
414 self,
415 handler: ResponseHandler,
416 ) -> None:
417 self._response_handler.remove(handler)
418
419 def _write_and_wait_one(
420 self,
421 msg_id: int,
422 message_type: t.Type[MessageType],
423 ) -> MessageType:
424 handler = self._register_response_handler(msg_id, message_type)
425 try:
426 self._write_msg()
427
428 return handler.__iter__().__next__()
429
430 finally:
431 self._unregister_response_handler(handler)
432
433 def _write_msg(self) -> None:
434 data = self._protocol.data_to_send()
435 if self._encryptor:
436 data = self._encryptor.wrap(data)
437
438 self._sock.sendall(data)