Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/_authentication.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 ssl
11 import struct
12 import typing as t
13
14 try:
15 import sansldap
16 except Exception:
17 pass # Check is in __init__.py
18
19 try:
20 import spnego
21
22 SPNEGO_IMPORT_ERR = None
23 except Exception as e:
24 SPNEGO_IMPORT_ERR = e
25
26 from ._certificate import get_tls_server_end_point_data
27 from .client import Credential, MessageEncryptor, SyncLDAPClient
28
29
30 class SimpleCredential(Credential):
31 def __init__(self, username: t.Optional[str] = None, password: t.Optional[str] = None) -> None:
32 self.username = username
33 self.password = password
34
35 def authenticate(
36 self,
37 client: SyncLDAPClient,
38 *,
39 tls_sock: t.Optional[ssl.SSLSocket] = None,
40 ) -> None:
41 client.bind(self.username or "", sansldap.SimpleCredential(self.password or ""))
42
43
44 class ClientCertificate(Credential):
45 def authenticate(
46 self,
47 client: SyncLDAPClient,
48 *,
49 tls_sock: t.Optional[ssl.SSLSocket] = None,
50 ) -> None:
51 # The certs are provided in the TLS handshake, the SASL EXTERNAL mech
52 # just tells the server to check those for the bind.
53 client.bind("", sansldap.SaslCredential("EXTERNAL", b""))
54
55
56 class NegotiateCredential(Credential):
57 def __init__(
58 self,
59 username: t.Optional[str] = None,
60 password: t.Optional[str] = None,
61 protocol: str = "negotiate",
62 encrypt: bool = True,
63 ) -> None:
64 if SPNEGO_IMPORT_ERR:
65 raise ImportError(str(SPNEGO_IMPORT_ERR)) from SPNEGO_IMPORT_ERR
66
67 self.username = username
68 self.password = password
69 self.protocol = protocol
70 self.encrypt = encrypt
71
72 def authenticate(
73 self,
74 client: SyncLDAPClient,
75 *,
76 tls_sock: t.Optional[ssl.SSLSocket] = None,
77 ) -> None:
78 context_req = spnego.ContextReq.mutual_auth
79
80 if tls_sock or not self.encrypt:
81 # MS AD rejects any authentication that provides integrity or
82 # confidentiality if the connection is already protected by TLS.
83 # As the GSS-SPNEGO SASL relies on the context attributes to
84 # negotiate whether signing/encryption and Kerberos by default
85 # always uses the integrity attributes we need to tell it
86 # explicitly not to. The no_integrity flag does that for us.
87 needs_encryptor = False
88 context_req |= spnego.ContextReq.no_integrity
89
90 else:
91 # When not operating over TLS request integrity and confidentiality
92 # so that we can encrypt the traffic.
93 needs_encryptor = True
94 context_req |= (
95 spnego.ContextReq.sequence_detect | spnego.ContextReq.integrity | spnego.ContextReq.confidentiality
96 )
97
98 ctx = spnego.client(
99 username=self.username,
100 password=self.password,
101 hostname=client.server,
102 service="ldap",
103 context_req=context_req,
104 protocol=self.protocol,
105 )
106
107 cbt = None
108 if tls_sock:
109 app_data = get_tls_server_end_point_data(tls_sock.getpeercert(True))
110 if app_data:
111 cbt = spnego.channel_bindings.GssChannelBindings(application_data=app_data)
112
113 in_token: t.Optional[bytes] = None
114 while not ctx.complete:
115 out_token = ctx.step(in_token=in_token, channel_bindings=cbt)
116 if not out_token:
117 break
118
119 in_token = client.bind(
120 "",
121 sansldap.SaslCredential("GSS-SPNEGO", out_token),
122 success_only=ctx.complete,
123 )
124
125 if needs_encryptor:
126 client.register_encryptor(SpnegoEncryptor(ctx))
127
128
129 class SpnegoEncryptor(MessageEncryptor):
130 def __init__(
131 self,
132 context: "spnego.ContextProxy",
133 ) -> None:
134 self.context = context
135
136 def wrap(
137 self,
138 data: bytes,
139 ) -> bytes:
140 wrapped_data = self.context.wrap(data, encrypt=True).data
141 return len(wrapped_data).to_bytes(4, byteorder="big") + wrapped_data
142
143 def unwrap(
144 self,
145 data: bytes,
146 ) -> t.Tuple[bytes, int]:
147 data_view = memoryview(data)
148 data_len = struct.unpack(">I", data_view[:4])[0]
149 data_view = data_view[4:]
150 if len(data_view) < data_len:
151 return b"", 0
152
153 data_view = data_view[:data_len]
154
155 return self.context.unwrap(data_view.tobytes()).data, data_len + 4