Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/__init__.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 """LDAP Helpers.
5
6 This contains the code needed to perform LDAP operations for plugins in this
7 collection. It should only be used by plugins in this collection as the
8 interface is not final and could be subject to change.
9 """
10
11 # FOR INTERNAL COLLECTION USE ONLY
12 # The interfaces in this file are meant for use within this collection
13 # and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release.
14 # See also: https://github.com/ansible/community/issues/539#issuecomment-780839686
15 # Please open an issue if you have questions about this.
16
17 import socket
18 import ssl
19 import typing as t
20
21 try:
22 import sansldap
23
24 LDAP_IMP_ERR = None
25 except Exception as e:
26 LDAP_IMP_ERR = e
27
28 from ._authentication import ClientCertificate, NegotiateCredential, SimpleCredential
29 from ._certificate import load_client_certificate, load_trust_certificate
30 from ._lookup import lookup_ldap_server
31 from .client import Credential, SyncLDAPClient
32
33 from ansible.errors import AnsibleError
34
35
36 def create_ldap_connection(
37 auth_protocol: t.Optional[str] = None,
38 ca_cert: t.Optional[str] = None,
39 cert_validation: t.Optional[str] = None,
40 certificate: t.Optional[str] = None,
41 certificate_key: t.Optional[str] = None,
42 certificate_password: t.Optional[str] = None,
43 connection_timeout: int = 5,
44 encrypt: bool = True,
45 password: t.Optional[str] = None,
46 port: t.Optional[int] = None,
47 server: t.Optional[str] = None,
48 tls_mode: t.Optional[str] = None,
49 username: t.Optional[str] = None,
50 **kwargs: t.Any, # Catches any other module option not needed here
51 ) -> SyncLDAPClient:
52 """Creates the LDAP client.
53
54 Creates the LDAP client using the options specified. The options here
55 correspond to the options defined in the ldap_connection doc fragment.
56
57 Args:
58 auth_protocol: The authentication protocol to use, can be simple,
59 certificate, negotiate, kerberos, or ntlm.
60 ca_cert: The CA PEM path to use for certificate verification.
61 cert_validation: Controls the certificate verification behavior, can
62 be always, ignore, or ignore_hostname.
63 certificate: The client certificate PEM file (optionally key) to use for
64 certificate authentication.
65 certificate_key: The client certificate PEM key to use for certificate
66 authentication.
67 certificate_password: The password used to decrypt the client
68 certificate key if it is encrypted.
69 connection_timeout: The timeout in seconds to wait for connecting to a
70 host.
71 encrypt: The connection should be encrypted, whether through TLS or
72 with authentication encryption.
73 password: The password to authenticate with.
74 port: The LDAP port to use.
75 server: The LDAP server to connect to.
76 tls_mode: The TLS mode, can be ldaps or start_tls.
77 username: The username to authenticate with.
78
79 Returns:
80 LDAPClient: The LDAP client.
81 """
82 if LDAP_IMP_ERR:
83 raise ImportError(str(LDAP_IMP_ERR)) from LDAP_IMP_ERR
84
85 if not server:
86 server, lookup_port = lookup_ldap_server()
87 if not port:
88 port = lookup_port
89
90 if port is None:
91 port = 636 if tls_mode == "ldaps" else 389
92
93 if tls_mode is None and port == 636:
94 tls_mode = "ldaps"
95
96 ssl_context: t.Optional[ssl.SSLContext] = None
97 if tls_mode:
98 ssl_context = ssl.create_default_context()
99 if ca_cert:
100 load_trust_certificate(ssl_context, ca_cert)
101
102 if cert_validation == "ignore":
103 ssl_context.check_hostname = False
104 ssl_context.verify_mode = ssl.VerifyMode.CERT_NONE
105
106 elif cert_validation == "ignore_hostname":
107 ssl_context.check_hostname = False
108
109 if not auth_protocol:
110 auth_protocol = "certificate" if certificate and ssl_context else "negotiate"
111
112 credential: t.Optional[Credential] = None
113 if auth_protocol == "simple":
114 if encrypt and not ssl_context:
115 raise ValueError("Cannot use simple auth with encryption.")
116
117 credential = SimpleCredential(username, password)
118
119 elif auth_protocol == "certificate":
120 if not ssl_context:
121 raise ValueError("TLS must be used for certificate authentication")
122
123 if not certificate:
124 raise ValueError("A certificate must be specified for certificate authentication")
125
126 load_client_certificate(
127 ssl_context,
128 certificate,
129 key=certificate_key,
130 password=certificate_password,
131 )
132
133 # If the client establishes the SSL/TLS-protected connection by means of connecting on a protected LDAPS port,
134 # then the connection is considered to be immediately authenticated (bound) as the credentials represented
135 # by the client certificate. An EXTERNAL bind is not allowed, and the bind will be rejected with an error.
136 # https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/8e73932f-70cf-46d6-88b1-8d9f86235e81
137 if tls_mode == "start_tls":
138 credential = ClientCertificate()
139
140 else:
141 credential = NegotiateCredential(
142 username,
143 password,
144 protocol=auth_protocol,
145 encrypt=encrypt,
146 )
147
148 protocol = sansldap.LDAPClient()
149 tls_sock: t.Optional[ssl.SSLSocket] = None
150 try:
151 sock = socket.create_connection((server, port), timeout=connection_timeout)
152 except OSError as e:
153 raise AnsibleError(f"Failed to connect to {server}:{port}: {e}") from e
154 sock.settimeout(None) # Set socket into blocking mode
155
156 if ssl_context and tls_mode == "ldaps":
157 tls_sock = sock = ssl_context.wrap_socket(sock, server_hostname=server)
158
159 try:
160 if ssl_context and tls_mode == "start_tls":
161 SyncLDAPClient.start_tls(protocol, sock)
162 tls_sock = sock = ssl_context.wrap_socket(sock, server_hostname=server)
163
164 client = SyncLDAPClient(server, protocol, sock)
165 except Exception:
166 try:
167 sock.shutdown(socket.SHUT_RDWR)
168 except OSError:
169 # The socket has already been shutdown for some other reason
170 pass
171 sock.close()
172 raise
173
174 try:
175 if credential:
176 credential.authenticate(client, tls_sock=tls_sock)
177
178 return client
179 except Exception:
180 client.close()
181 raise