Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/laps.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 base64
11 import typing as t
12
13 try:
14 import dpapi_ng
15
16 HAS_DPAPI_NG = True
17 DPAPI_NG_IMP_ERR = None
18 except Exception as e:
19 HAS_DPAPI_NG = False
20 DPAPI_NG_IMP_ERR = e
21
22
23 class LAPSDecryptor:
24
25 def __init__(
26 self,
27 server: t.Optional[str] = None,
28 username: t.Optional[str] = None,
29 password: t.Optional[str] = None,
30 auth_protocol: t.Optional[str] = None,
31 **kwargs: t.Any,
32 ) -> None:
33 self._server = server
34 self._username = username
35 self._password = password
36
37 if not auth_protocol or auth_protocol not in ["kerberos", "negotiate", "ntlm"]:
38 auth_protocol = "negotiate"
39 self._auth_protocol = auth_protocol
40
41 self._cache = None
42 if HAS_DPAPI_NG:
43 self._cache = dpapi_ng.KeyCache()
44
45 def decrypt(
46 self,
47 blob: bytes,
48 ) -> t.Dict[str, t.Any]:
49 update_timestamp_upper = int.from_bytes(blob[:4], byteorder="little")
50 update_timestamp_lower = int.from_bytes(blob[4:8], byteorder="little")
51 update_timestamp = (update_timestamp_upper << 32) | update_timestamp_lower
52 enc_buffer_size = int.from_bytes(blob[8:12], byteorder="little")
53 flags = int.from_bytes(blob[12:16], byteorder="little")
54 enc_buffer = blob[16:16 + enc_buffer_size]
55
56 value = {
57 'update_timestamp': update_timestamp,
58 'flags': flags,
59 'encrypted_value': base64.b64encode(enc_buffer).decode(),
60 }
61
62 if HAS_DPAPI_NG:
63 try:
64 raw_dec_value = dpapi_ng.ncrypt_unprotect_secret(
65 enc_buffer,
66 server=self._server,
67 username=self._username,
68 password=self._password,
69 auth_protocol=self._auth_protocol,
70 cache=self._cache,
71 )
72 value['value'] = raw_dec_value.decode("utf-16-le").rstrip("\00")
73 except Exception as e:
74 value['debug'] = f'Failed to decrypt value due to error - {type(e).__name__} {e}'
75
76 else:
77 value['debug'] = 'Cannot decrypt value as the Python library dpapi-ng is not installed'
78
79 return value