Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/_certificate.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 os.path
11 import secrets
12 import ssl
13 import tempfile
14 import typing as t
15
16 # Cryptography is used for the TLS channel binding data and to convert PKCS8/12
17 # certs to a PEM file required by OpenSSL.
18 try:
19 from cryptography import x509
20 from cryptography.exceptions import UnsupportedAlgorithm
21 from cryptography.hazmat.primitives import hashes, serialization
22 from cryptography.hazmat.primitives.serialization import pkcs12
23
24 HAS_CRYPTOGRAPHY = True
25 except Exception:
26 HAS_CRYPTOGRAPHY = False
27
28
29 class _PrivateKey(t.Protocol):
30 def private_bytes(
31 self,
32 encoding: "serialization.Encoding",
33 format: "serialization.PrivateFormat",
34 encryption_algorithm: "serialization.KeySerializationEncryption",
35 ) -> bytes:
36 ...
37
38
39 def get_tls_server_end_point_data(
40 certificate: t.Optional[bytes],
41 ) -> t.Optional[bytes]:
42 """Get the TLS channel binding data.
43
44 Gets the TLS channel binding data for tls-server-end-point used in
45 Negotiate authentication.
46
47 Args:
48 tls_sock: The SSLSocket to get the binding data for.
49
50 Returns:
51 Optional[bytes]: The tls-server-end-point data used in the channel
52 bindings application data value. Can return None if the cryptography
53 isn't installed or it failed to get the certificate info.
54 """
55 if not HAS_CRYPTOGRAPHY or not certificate:
56 return None
57
58 cert = x509.load_der_x509_certificate(certificate)
59 try:
60 hash_algorithm = cert.signature_hash_algorithm
61 except UnsupportedAlgorithm:
62 hash_algorithm = None
63
64 # If the cert signature algorithm is unknown, md5, or sha1 then use sha256
65 # otherwise use the signature algorithm of the cert itself.
66 if not hash_algorithm or hash_algorithm.name in ["md5", "sha1"]:
67 digest = hashes.Hash(hashes.SHA256())
68 else:
69 digest = hashes.Hash(hash_algorithm)
70
71 digest.update(certificate)
72 return b"tls-server-end-point:" + digest.finalize()
73
74
75 def load_trust_certificate(
76 context: ssl.SSLContext,
77 certificate: str,
78 ) -> None:
79 """Loads a certificate as a trusted CA.
80
81 Loads the supplied certificate info into the SSLContext to trust. The
82 certificate can be in the following 3 forms:
83
84 file path: The path to a PEM or DER encoded certificate
85 dir path: The path to a directory containing multiple CA PEM files in
86 a specific OpenSSL format (see c_rehash in OpenSSL).
87 string: A PEM encoded certificate as a string.
88
89 Args:
90 context: The SSLContext to load the cert into.
91 certificate: The certificate info to trust.
92 """
93 if os.path.exists(certificate):
94 if os.path.isdir(certificate):
95 # It is important the caller does not delete the dir because the
96 # lookup happens during the handshake and not now.
97 context.load_verify_locations(capath=certificate)
98
99 else:
100 # cafile only works for PEM encoded certs, whereas cadata can
101 # load DER encoded certs.
102 with open(certificate, mode="rb") as fd:
103 data = fd.read()
104
105 if data.startswith(b"-----BEGIN CERTIFICATE-----"):
106 context.load_verify_locations(cafile=certificate)
107 else:
108 context.load_verify_locations(cadata=data)
109
110 else:
111 context.load_verify_locations(cadata=certificate)
112
113
114 def load_client_certificate(
115 context: ssl.SSLContext,
116 certificate: str,
117 key: t.Optional[str] = None,
118 password: t.Optional[str] = None,
119 ) -> None:
120 """Loads a certificate to use with client authentication.
121
122 Loads the supplied certificate that can be used for client authentication.
123 This function is a wrapper around load_cert_chain and offers the ability to
124 load a cert/key from a string or load a PFX formatted certificate with an
125 optional password.
126
127 The certificate argument can either be a string of the PEM encoded
128 certificate and/or key. It can also be the path to a file of a PEM, DEF, or
129 PKCS12 (pfx) certificate and/or key. The key argument can be used to
130 specify the certificate key if it is not bundled with the certificate
131 argument.
132
133 Args:
134 context: The SSLContext to load the cert info.
135 certificate: The certificate as a string or filepath.
136 key: The optional key as a string or filepath.
137 password: The password that is used to decrypt the key or pfx file.
138 """
139 b_password = password.encode("utf-8", errors="surrogateescape") if password else None
140
141 if os.path.isfile(certificate):
142 with open(certificate, mode="rb") as fd:
143 cert_data = fd.read()
144
145 der_cert = _try_load_der_cert(cert_data)
146 if der_cert:
147 certificate = der_cert
148
149 else:
150 pfx_cert = _try_load_pfx_cert(cert_data, b_password)
151 if pfx_cert:
152 certificate, key, b_password = pfx_cert
153
154 if key and os.path.isfile(key):
155 with open(key, mode="rb") as fd:
156 key_data = fd.read()
157
158 der_key = _try_load_der_key(key_data, b_password)
159 if der_key:
160 key, b_password = der_key
161
162 # Specifying an empty b"" stops OpenSSL from prompting for the password if
163 # it was required. Instead it will just fail to load.
164 b_password = b_password or b""
165
166 # load_cert_chain does not expose a way to load a certificate/key from
167 # memory so a temporary directory is used in the cases where a pfx or
168 # string supplied cert is used.
169 if certificate.startswith("-----") or (key and key.startswith("-----")):
170 with tempfile.TemporaryDirectory() as tmpdir:
171 if certificate.startswith("-----"):
172 cert_path = os.path.join(tmpdir, "cert.pem")
173 with open(cert_path, mode="w") as fd:
174 fd.write(certificate)
175
176 certificate = cert_path
177
178 if key and key.startswith("-----"):
179 key_path = os.path.join(tmpdir, "key.pem")
180 with open(key_path, mode="w") as fd:
181 fd.write(key)
182
183 key = key_path
184
185 context.load_cert_chain(certfile=certificate, keyfile=key, password=b_password)
186
187 return
188
189 context.load_cert_chain(certfile=certificate, keyfile=key, password=b_password)
190
191
192 def _try_load_der_cert(
193 data: bytes,
194 ) -> t.Optional[str]:
195 if not HAS_CRYPTOGRAPHY:
196 return None
197
198 try:
199 cert = x509.load_der_x509_certificate(data)
200 except ValueError:
201 return None
202 else:
203 return cert.public_bytes(encoding=serialization.Encoding.PEM).decode()
204
205
206 def _try_load_der_key(
207 data: bytes,
208 password: t.Optional[bytes],
209 ) -> t.Optional[t.Tuple[str, bytes]]:
210 if not HAS_CRYPTOGRAPHY:
211 return None
212
213 try:
214 key = serialization.load_der_private_key(data, password=password)
215 except ValueError:
216 return None
217 else:
218 return _serialize_key_with_password(key, password)
219
220
221 def _try_load_pfx_cert(
222 data: bytes,
223 password: t.Optional[bytes],
224 ) -> t.Optional[t.Tuple[str, str, bytes]]:
225 if not HAS_CRYPTOGRAPHY:
226 return None
227
228 try:
229 pfx = pkcs12.load_key_and_certificates(data, password)
230 except ValueError:
231 pfx = None
232
233 if not pfx or not pfx[0] or not pfx[1]:
234 return None
235
236 password = password or secrets.token_bytes(32)
237
238 certificate = pfx[1].public_bytes(encoding=serialization.Encoding.PEM).decode()
239 key, password = _serialize_key_with_password(pfx[0], password)
240
241 return certificate, key, password
242
243
244 def _serialize_key_with_password(
245 key: _PrivateKey,
246 password: t.Optional[bytes],
247 ) -> t.Tuple[str, bytes]:
248 password = password or secrets.token_bytes(32)
249
250 return (
251 key.private_bytes(
252 serialization.Encoding.PEM,
253 serialization.PrivateFormat.PKCS8,
254 encryption_algorithm=serialization.BestAvailableEncryption(password),
255 ).decode(),
256 password,
257 )