Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/backend_cryptography.py

raw
1 # Copyright (c) 2016 Michael Gruener <[email protected]>
2 # Copyright (c) 2021 Felix Fontein <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import base64
12 import binascii
13 import os
14 import traceback
15 import typing as t
16
17 from ansible.module_utils.common.text.converters import to_bytes, to_text
18
19 from ansible_collections.community.crypto.plugins.module_utils._acme.backends import (
20 CertificateInformation,
21 CryptoBackend,
22 )
23 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
24 ChainMatcher,
25 )
26 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
27 BackendException,
28 KeyParsingError,
29 )
30 from ansible_collections.community.crypto.plugins.module_utils._acme.io import read_file
31 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
32 nopad_b64,
33 )
34 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
35 CRYPTOGRAPHY_TIMEZONE,
36 cryptography_name_to_oid,
37 get_not_valid_after,
38 get_not_valid_before,
39 )
40 from ansible_collections.community.crypto.plugins.module_utils._crypto.math import (
41 convert_int_to_bytes,
42 convert_int_to_hex,
43 )
44 from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import (
45 extract_first_pem,
46 )
47 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
48 parse_name_field,
49 )
50 from ansible_collections.community.crypto.plugins.module_utils._time import (
51 add_or_remove_timezone,
52 )
53 from ansible_collections.community.crypto.plugins.module_utils._version import (
54 LooseVersion,
55 )
56
57 CRYPTOGRAPHY_MINIMAL_VERSION = "1.5"
58
59 CRYPTOGRAPHY_ERROR: None | str
60 try:
61 import cryptography
62 import cryptography.hazmat.backends
63 import cryptography.hazmat.primitives.asymmetric.ec
64 import cryptography.hazmat.primitives.asymmetric.padding
65 import cryptography.hazmat.primitives.asymmetric.rsa
66 import cryptography.hazmat.primitives.asymmetric.utils
67 import cryptography.hazmat.primitives.hashes
68 import cryptography.hazmat.primitives.hmac
69 import cryptography.hazmat.primitives.serialization
70 import cryptography.x509
71 import cryptography.x509.oid
72 except ImportError:
73 HAS_CURRENT_CRYPTOGRAPHY = False # pylint: disable=invalid-name
74 CRYPTOGRAPHY_VERSION = None # pylint: disable=invalid-name
75 CRYPTOGRAPHY_ERROR = traceback.format_exc() # pylint: disable=invalid-name
76 else:
77 CRYPTOGRAPHY_VERSION = cryptography.__version__ # pylint: disable=invalid-name
78 HAS_CURRENT_CRYPTOGRAPHY = LooseVersion(CRYPTOGRAPHY_VERSION) >= LooseVersion(
79 CRYPTOGRAPHY_MINIMAL_VERSION
80 )
81 CRYPTOGRAPHY_ERROR = None # pylint: disable=invalid-name
82
83 if t.TYPE_CHECKING:
84 import datetime # pragma: no cover
85
86 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
87
88 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
89 CertificateChain,
90 Criterium,
91 )
92
93
94 class CryptographyChainMatcher(ChainMatcher):
95 @staticmethod
96 def _parse_key_identifier(
97 *,
98 key_identifier: str | None,
99 name: str,
100 criterium_idx: int,
101 module: AnsibleModule,
102 ) -> bytes | None:
103 if key_identifier:
104 try:
105 return binascii.unhexlify(key_identifier.replace(":", ""))
106 except Exception:
107 module.warn(
108 f"Criterium {criterium_idx} in select_chain has invalid {name} value. Ignoring criterium."
109 )
110 return None
111
112 def __init__(self, *, criterium: Criterium, module: AnsibleModule) -> None:
113 self.criterium = criterium
114 self.test_certificates = criterium.test_certificates
115 self.subject: list[tuple[cryptography.x509.oid.ObjectIdentifier, str]] = []
116 self.issuer: list[tuple[cryptography.x509.oid.ObjectIdentifier, str]] = []
117 if criterium.subject:
118 self.subject = [
119 (cryptography_name_to_oid(k), to_text(v))
120 for k, v in parse_name_field(
121 criterium.subject, name_field_name="subject"
122 )
123 ]
124 if criterium.issuer:
125 self.issuer = [
126 (cryptography_name_to_oid(k), to_text(v))
127 for k, v in parse_name_field(criterium.issuer, name_field_name="issuer")
128 ]
129 self.subject_key_identifier = CryptographyChainMatcher._parse_key_identifier(
130 key_identifier=criterium.subject_key_identifier,
131 name="subject_key_identifier",
132 criterium_idx=criterium.index,
133 module=module,
134 )
135 self.authority_key_identifier = CryptographyChainMatcher._parse_key_identifier(
136 key_identifier=criterium.authority_key_identifier,
137 name="authority_key_identifier",
138 criterium_idx=criterium.index,
139 module=module,
140 )
141 self.module = module
142
143 def _match_subject(
144 self,
145 *,
146 x509_subject: cryptography.x509.Name,
147 match_subject: list[tuple[cryptography.x509.oid.ObjectIdentifier, str]],
148 ) -> bool:
149 for oid, value in match_subject:
150 found = False
151 for attribute in x509_subject:
152 if attribute.oid == oid and value == to_text(attribute.value):
153 found = True
154 break
155 if not found:
156 return False
157 return True
158
159 def match(self, *, certificate: CertificateChain) -> bool:
160 """
161 Check whether an alternate chain matches the specified criterium.
162 """
163 chain = certificate.chain
164 if self.test_certificates == "last":
165 chain = chain[-1:]
166 elif self.test_certificates == "first":
167 chain = chain[:1]
168 for cert in chain:
169 try:
170 x509 = cryptography.x509.load_pem_x509_certificate(to_bytes(cert))
171 matches = True
172 if not self._match_subject(
173 x509_subject=x509.subject, match_subject=self.subject
174 ):
175 matches = False
176 if not self._match_subject(
177 x509_subject=x509.issuer, match_subject=self.issuer
178 ):
179 matches = False
180 if self.subject_key_identifier:
181 try:
182 ext_ski = x509.extensions.get_extension_for_class(
183 cryptography.x509.SubjectKeyIdentifier
184 )
185 if self.subject_key_identifier != ext_ski.value.digest:
186 matches = False
187 except cryptography.x509.ExtensionNotFound:
188 matches = False
189 if self.authority_key_identifier:
190 try:
191 ext_aki = x509.extensions.get_extension_for_class(
192 cryptography.x509.AuthorityKeyIdentifier
193 )
194 if (
195 self.authority_key_identifier
196 != ext_aki.value.key_identifier
197 ):
198 matches = False
199 except cryptography.x509.ExtensionNotFound:
200 matches = False
201 if matches:
202 return True
203 except Exception as e:
204 self.module.warn(f"Error while loading certificate {cert}: {e}")
205 return False
206
207
208 class CryptographyBackend(CryptoBackend):
209 def __init__(self, *, module: AnsibleModule) -> None:
210 super().__init__(module=module, with_timezone=CRYPTOGRAPHY_TIMEZONE)
211
212 def parse_key(
213 self,
214 *,
215 key_file: str | os.PathLike | None = None,
216 key_content: str | None = None,
217 passphrase: str | None = None,
218 ) -> dict[str, t.Any]:
219 """
220 Parses an RSA or Elliptic Curve key file in PEM format and returns key_data.
221 Raises KeyParsingError in case of errors.
222 """
223 # If key_content is not given, read key_file
224 if key_content is None:
225 if key_file is None:
226 raise KeyParsingError(
227 "one of key_file and key_content must be specified"
228 )
229 b_key_content = read_file(key_file)
230 else:
231 b_key_content = to_bytes(key_content)
232 # Parse key
233 try:
234 key = cryptography.hazmat.primitives.serialization.load_pem_private_key(
235 b_key_content,
236 password=to_bytes(passphrase) if passphrase is not None else None,
237 )
238 except Exception as e:
239 raise KeyParsingError(f"error while loading key: {e}") from e
240 if isinstance(key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):
241 rsa_pk = key.public_key().public_numbers()
242 return {
243 "key_obj": key,
244 "type": "rsa",
245 "alg": "RS256",
246 "jwk": {
247 "kty": "RSA",
248 "e": nopad_b64(convert_int_to_bytes(rsa_pk.e)),
249 "n": nopad_b64(convert_int_to_bytes(rsa_pk.n)),
250 },
251 "hash": "sha256",
252 }
253 if isinstance(
254 key, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
255 ):
256 ec_pk = key.public_key().public_numbers()
257 if ec_pk.curve.name == "secp256r1":
258 bits = 256
259 alg = "ES256"
260 hashalg = "sha256"
261 point_size = 32
262 curve = "P-256"
263 elif ec_pk.curve.name == "secp384r1":
264 bits = 384
265 alg = "ES384"
266 hashalg = "sha384"
267 point_size = 48
268 curve = "P-384"
269 elif ec_pk.curve.name == "secp521r1":
270 # Not yet supported on Let's Encrypt side, see
271 # https://github.com/letsencrypt/boulder/issues/2217
272 bits = 521
273 alg = "ES512"
274 hashalg = "sha512"
275 point_size = 66
276 curve = "P-521"
277 else:
278 raise KeyParsingError(f"unknown elliptic curve: {ec_pk.curve.name}")
279 num_bytes = (bits + 7) // 8
280 return {
281 "key_obj": key,
282 "type": "ec",
283 "alg": alg,
284 "jwk": {
285 "kty": "EC",
286 "crv": curve,
287 "x": nopad_b64(convert_int_to_bytes(ec_pk.x, count=num_bytes)),
288 "y": nopad_b64(convert_int_to_bytes(ec_pk.y, count=num_bytes)),
289 },
290 "hash": hashalg,
291 "point_size": point_size,
292 }
293 raise KeyParsingError(f'unknown key type "{type(key)}"')
294
295 def sign(
296 self, *, payload64: str, protected64: str, key_data: dict[str, t.Any]
297 ) -> dict[str, t.Any]:
298 sign_payload = f"{protected64}.{payload64}".encode("utf8")
299 hashalg: type[cryptography.hazmat.primitives.hashes.HashAlgorithm]
300 if "mac_obj" in key_data:
301 mac = key_data["mac_obj"]()
302 mac.update(sign_payload)
303 signature = mac.finalize()
304 elif isinstance(
305 key_data["key_obj"],
306 cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey,
307 ):
308 padding = cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15()
309 hashalg = cryptography.hazmat.primitives.hashes.SHA256
310 signature = key_data["key_obj"].sign(sign_payload, padding, hashalg())
311 elif isinstance(
312 key_data["key_obj"],
313 cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey,
314 ):
315 if key_data["hash"] == "sha256":
316 hashalg = cryptography.hazmat.primitives.hashes.SHA256
317 elif key_data["hash"] == "sha384":
318 hashalg = cryptography.hazmat.primitives.hashes.SHA384
319 elif key_data["hash"] == "sha512":
320 hashalg = cryptography.hazmat.primitives.hashes.SHA512
321 ecdsa = cryptography.hazmat.primitives.asymmetric.ec.ECDSA(hashalg())
322 r, s = cryptography.hazmat.primitives.asymmetric.utils.decode_dss_signature(
323 key_data["key_obj"].sign(sign_payload, ecdsa)
324 )
325 rr = convert_int_to_hex(r, digits=2 * key_data["point_size"])
326 ss = convert_int_to_hex(s, digits=2 * key_data["point_size"])
327 signature = binascii.unhexlify(rr) + binascii.unhexlify(ss)
328 else:
329 raise AssertionError("Can never be reached") # pragma: no cover
330
331 return {
332 "protected": protected64,
333 "payload": payload64,
334 "signature": nopad_b64(signature),
335 }
336
337 def create_mac_key(self, *, alg: str, key: str) -> dict[str, t.Any]:
338 """Create a MAC key."""
339 hashalg: type[cryptography.hazmat.primitives.hashes.HashAlgorithm]
340 if alg == "HS256":
341 hashalg = cryptography.hazmat.primitives.hashes.SHA256
342 hashbytes = 32
343 elif alg == "HS384":
344 hashalg = cryptography.hazmat.primitives.hashes.SHA384
345 hashbytes = 48
346 elif alg == "HS512":
347 hashalg = cryptography.hazmat.primitives.hashes.SHA512
348 hashbytes = 64
349 else:
350 raise BackendException(
351 f"Unsupported MAC key algorithm for cryptography backend: {alg}"
352 )
353 key_bytes = base64.urlsafe_b64decode(key)
354 if len(key_bytes) < hashbytes:
355 raise BackendException(
356 f"{alg} key must be at least {hashbytes} bytes long (after Base64 decoding)"
357 )
358 return {
359 "mac_obj": lambda: cryptography.hazmat.primitives.hmac.HMAC(
360 key_bytes, hashalg()
361 ),
362 "type": "hmac",
363 "alg": alg,
364 "jwk": {
365 "kty": "oct",
366 "k": key,
367 },
368 }
369
370 def get_ordered_csr_identifiers(
371 self,
372 *,
373 csr_filename: str | os.PathLike | None = None,
374 csr_content: str | bytes | None = None,
375 ) -> list[tuple[str, str]]:
376 """
377 Return a list of requested identifiers (CN and SANs) for the CSR.
378 Each identifier is a pair (type, identifier), where type is either
379 'dns' or 'ip'.
380
381 The list is deduplicated, and if a CNAME is present, it will be returned
382 as the first element in the result.
383 """
384 if csr_content is None:
385 if csr_filename is None:
386 raise BackendException(
387 "One of csr_content and csr_filename has to be provided"
388 )
389 b_csr_content = read_file(csr_filename)
390 else:
391 b_csr_content = to_bytes(csr_content)
392 csr = cryptography.x509.load_pem_x509_csr(b_csr_content)
393
394 identifiers = set()
395 result = []
396
397 def add_identifier(identifier: tuple[str, str]) -> None:
398 if identifier in identifiers:
399 return
400 identifiers.add(identifier)
401 result.append(identifier)
402
403 for sub in csr.subject:
404 if sub.oid == cryptography.x509.oid.NameOID.COMMON_NAME:
405 add_identifier(("dns", t.cast(str, sub.value)))
406 for extension in csr.extensions:
407 if (
408 extension.oid
409 == cryptography.x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME
410 ):
411 for name in extension.value:
412 if isinstance(name, cryptography.x509.DNSName):
413 add_identifier(("dns", name.value))
414 elif isinstance(name, cryptography.x509.IPAddress):
415 add_identifier(("ip", name.value.compressed))
416 else:
417 raise BackendException(
418 f"Found unsupported SAN identifier {name}"
419 )
420 return result
421
422 def get_csr_identifiers(
423 self,
424 *,
425 csr_filename: str | os.PathLike | None = None,
426 csr_content: str | bytes | bytes | None = None,
427 ) -> set[tuple[str, str]]:
428 """
429 Return a set of requested identifiers (CN and SANs) for the CSR.
430 Each identifier is a pair (type, identifier), where type is either
431 'dns' or 'ip'.
432 """
433 return set(
434 self.get_ordered_csr_identifiers(
435 csr_filename=csr_filename, csr_content=csr_content
436 )
437 )
438
439 def get_cert_days(
440 self,
441 *,
442 cert_filename: str | os.PathLike | None = None,
443 cert_content: str | bytes | None = None,
444 now: datetime.datetime | None = None,
445 ) -> int:
446 """
447 Return the days the certificate in cert_filename remains valid and -1
448 if the file was not found. If cert_filename contains more than one
449 certificate, only the first one will be considered.
450
451 If now is not specified, datetime.datetime.now() is used.
452 """
453 if cert_filename is not None:
454 cert_content = None
455 if os.path.exists(cert_filename):
456 cert_content = read_file(cert_filename)
457 else:
458 cert_content = to_bytes(cert_content)
459
460 if cert_content is None:
461 return -1
462
463 # Make sure we have at most one PEM. Otherwise cryptography 36.0.0 will barf.
464 b_cert_content = to_bytes(extract_first_pem(to_text(cert_content)) or "")
465
466 try:
467 cert = cryptography.x509.load_pem_x509_certificate(b_cert_content)
468 except Exception as e:
469 if cert_filename is None:
470 raise BackendException(f"Cannot parse certificate: {e}") from e
471 raise BackendException(
472 f"Cannot parse certificate {cert_filename}: {e}"
473 ) from e
474
475 if now is None:
476 now = self.get_now()
477 else:
478 now = add_or_remove_timezone(now, with_timezone=CRYPTOGRAPHY_TIMEZONE)
479 return (get_not_valid_after(cert) - now).days
480
481 def create_chain_matcher(self, *, criterium: Criterium) -> ChainMatcher:
482 """
483 Given a Criterium object, creates a ChainMatcher object.
484 """
485 return CryptographyChainMatcher(criterium=criterium, module=self.module)
486
487 def get_cert_information(
488 self,
489 *,
490 cert_filename: str | os.PathLike | None = None,
491 cert_content: str | bytes | None = None,
492 ) -> CertificateInformation:
493 """
494 Return some information on a X.509 certificate as a CertificateInformation object.
495 """
496 if cert_filename is not None:
497 cert_content = read_file(cert_filename)
498 else:
499 cert_content = to_bytes(cert_content)
500
501 # Make sure we have at most one PEM. Otherwise cryptography 36.0.0 will barf.
502 b_cert_content = to_bytes(extract_first_pem(to_text(cert_content)) or "")
503
504 try:
505 cert = cryptography.x509.load_pem_x509_certificate(b_cert_content)
506 except Exception as e:
507 if cert_filename is None:
508 raise BackendException(f"Cannot parse certificate: {e}") from e
509 raise BackendException(
510 f"Cannot parse certificate {cert_filename}: {e}"
511 ) from e
512
513 ski = None
514 try:
515 ext_ski = cert.extensions.get_extension_for_class(
516 cryptography.x509.SubjectKeyIdentifier
517 )
518 ski = ext_ski.value.digest
519 except cryptography.x509.ExtensionNotFound:
520 pass
521
522 aki = None
523 try:
524 ext_aki = cert.extensions.get_extension_for_class(
525 cryptography.x509.AuthorityKeyIdentifier
526 )
527 aki = ext_aki.value.key_identifier
528 except cryptography.x509.ExtensionNotFound:
529 pass
530
531 return CertificateInformation(
532 not_valid_after=get_not_valid_after(cert),
533 not_valid_before=get_not_valid_before(cert),
534 serial_number=cert.serial_number,
535 subject_key_identifier=ski,
536 authority_key_identifier=aki,
537 )
538
539
540 __all__ = (
541 "CRYPTOGRAPHY_ERROR",
542 "CRYPTOGRAPHY_ERROR",
543 "CRYPTOGRAPHY_MINIMAL_VERSION",
544 "CRYPTOGRAPHY_VERSION",
545 "CryptographyBackend",
546 )