Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/cryptography_support.py

raw
1 # Copyright (c) 2019, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import base64
11 import binascii
12 import ipaddress
13 import re
14 import traceback
15 import typing as t
16 from urllib.parse import (
17 ParseResult,
18 urlparse,
19 urlunparse,
20 )
21
22 from ansible.module_utils.common.text.converters import to_bytes, to_text
23
24 from ansible_collections.community.crypto.plugins.module_utils._crypto._asn1 import (
25 serialize_asn1_string_as_der,
26 )
27 from ansible_collections.community.crypto.plugins.module_utils._version import (
28 LooseVersion,
29 )
30
31 try:
32 import cryptography
33 from cryptography import x509
34 from cryptography.exceptions import InvalidSignature
35 from cryptography.hazmat.primitives import serialization
36 from cryptography.hazmat.primitives.asymmetric import padding
37 from cryptography.hazmat.primitives.serialization.pkcs12 import (
38 load_key_and_certificates as _load_key_and_certificates,
39 )
40
41 _HAS_CRYPTOGRAPHY = True
42 except ImportError:
43 # Error handled in the calling module.
44 _HAS_CRYPTOGRAPHY = False
45
46 try:
47 import cryptography.hazmat.primitives.asymmetric.dh
48 import cryptography.hazmat.primitives.asymmetric.ed448
49 import cryptography.hazmat.primitives.asymmetric.ed25519
50 import cryptography.hazmat.primitives.asymmetric.rsa
51 import cryptography.hazmat.primitives.asymmetric.x448
52 import cryptography.hazmat.primitives.asymmetric.x25519
53 except ImportError:
54 pass
55
56 try:
57 # This is a separate try/except since this is only present in cryptography 36.0.0 or newer
58 from cryptography.hazmat.primitives.serialization.pkcs12 import (
59 load_pkcs12 as _load_pkcs12,
60 )
61 except ImportError:
62 # Error handled in the calling module.
63 _load_pkcs12 = None # type: ignore
64
65 try:
66 import idna
67
68 HAS_IDNA = True
69 except ImportError:
70 HAS_IDNA = False
71 IDNA_IMP_ERROR = traceback.format_exc()
72
73 from ansible.module_utils.basic import missing_required_lib
74
75 from ansible_collections.community.crypto.plugins.module_utils._crypto._obj2txt import (
76 obj2txt,
77 )
78 from ansible_collections.community.crypto.plugins.module_utils._crypto._objects import (
79 NORMALIZE_NAMES,
80 NORMALIZE_NAMES_SHORT,
81 OID_LOOKUP,
82 OID_MAP,
83 )
84 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
85 OpenSSLObjectError,
86 )
87
88 if t.TYPE_CHECKING:
89 import datetime # pragma: no cover
90
91 from cryptography.hazmat.primitives import hashes # pragma: no cover
92 from cryptography.hazmat.primitives.asymmetric.dh import ( # pragma: no cover
93 DHPrivateKey,
94 DHPublicKey,
95 )
96 from cryptography.hazmat.primitives.asymmetric.dsa import ( # pragma: no cover
97 DSAPrivateKey,
98 DSAPublicKey,
99 )
100 from cryptography.hazmat.primitives.asymmetric.ec import ( # pragma: no cover
101 EllipticCurvePrivateKey,
102 EllipticCurvePublicKey,
103 )
104 from cryptography.hazmat.primitives.asymmetric.rsa import ( # pragma: no cover
105 RSAPrivateKey,
106 RSAPublicKey,
107 )
108 from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
109 CertificateIssuerPrivateKeyTypes,
110 CertificateIssuerPublicKeyTypes,
111 CertificatePublicKeyTypes,
112 PrivateKeyTypes,
113 PublicKeyTypes,
114 )
115
116 CertificatePrivateKeyTypes = t.Union[ # noqa: UP007
117 CertificateIssuerPrivateKeyTypes,
118 cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
119 cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey,
120 ] # pragma: no cover
121 PublicKeyTypesWOEdwards = t.Union[ # noqa: UP007 # pylint: disable=invalid-name
122 DHPublicKey, DSAPublicKey, EllipticCurvePublicKey, RSAPublicKey
123 ] # pragma: no cover
124 PrivateKeyTypesWOEdwards = t.Union[ # noqa: UP007 # pylint: disable=invalid-name
125 DHPrivateKey, DSAPrivateKey, EllipticCurvePrivateKey, RSAPrivateKey
126 ] # pragma: no cover
127 else:
128 PublicKeyTypesWOEdwards = None # pylint: disable=invalid-name
129 PrivateKeyTypesWOEdwards = None # pylint: disable=invalid-name
130
131
132 CRYPTOGRAPHY_TIMEZONE = False # pylint: disable=invalid-name
133 _CRYPTOGRAPHY_36_0_OR_NEWER = False # pylint: disable=invalid-name
134 if _HAS_CRYPTOGRAPHY:
135 CRYPTOGRAPHY_TIMEZONE = LooseVersion(cryptography.__version__) >= LooseVersion(
136 "42.0.0"
137 )
138
139 _CRYPTOGRAPHY_36_0_OR_NEWER = LooseVersion(
140 cryptography.__version__
141 ) >= LooseVersion("36.0")
142
143 DOTTED_OID = re.compile(r"^\d+(?:\.\d+)+$")
144
145
146 def cryptography_get_extensions_from_cert(
147 cert: x509.Certificate,
148 ) -> dict[str, dict[str, bool | str]]:
149 result = {}
150
151 if _CRYPTOGRAPHY_36_0_OR_NEWER:
152 for ext in cert.extensions:
153 result[ext.oid.dotted_string] = {
154 "critical": ext.critical,
155 "value": base64.b64encode(ext.value.public_bytes()).decode("ascii"),
156 }
157 else:
158 # Since cryptography will not give us the DER value for an extension
159 # (that is only stored for unrecognized extensions), we have to re-do
160 # the extension parsing ourselves.
161 from cryptography.hazmat.backends import default_backend
162
163 backend = default_backend()
164
165 # We access a *lot* of internal APIs here, so let's disable that message...
166 # pylint: disable=protected-access
167
168 x509_obj = cert._x509 # type: ignore
169 # With cryptography 35.0.0, we can no longer use obj2txt. Unfortunately it still does
170 # not allow to get the raw value of an extension, so we have to use this ugly hack:
171 exts = list(cert.extensions)
172
173 for i in range(backend._lib.X509_get_ext_count(x509_obj)):
174 ext = backend._lib.X509_get_ext(x509_obj, i)
175 if ext == backend._ffi.NULL:
176 continue
177 crit = backend._lib.X509_EXTENSION_get_critical(ext)
178 data = backend._lib.X509_EXTENSION_get_data(ext)
179 backend.openssl_assert(data != backend._ffi.NULL)
180 der = backend._ffi.buffer(data.data, data.length)[:]
181 entry = {
182 "critical": (crit == 1),
183 "value": base64.b64encode(der).decode("ascii"),
184 }
185 try:
186 oid = obj2txt(
187 backend._lib,
188 backend._ffi,
189 backend._lib.X509_EXTENSION_get_object(ext),
190 )
191 except AttributeError:
192 oid = exts[i].oid.dotted_string
193 result[oid] = entry
194
195 return result
196
197
198 def cryptography_get_extensions_from_csr(
199 csr: x509.CertificateSigningRequest,
200 ) -> dict[str, dict[str, bool | str]]:
201 result = {}
202
203 if _CRYPTOGRAPHY_36_0_OR_NEWER:
204 for ext in csr.extensions:
205 result[ext.oid.dotted_string] = {
206 "critical": ext.critical,
207 "value": base64.b64encode(ext.value.public_bytes()).decode("ascii"),
208 }
209
210 else:
211 # Since cryptography will not give us the DER value for an extension
212 # (that is only stored for unrecognized extensions), we have to re-do
213 # the extension parsing ourselves.
214 from cryptography.hazmat.backends import default_backend
215
216 backend = default_backend()
217
218 # We access a *lot* of internal APIs here, so let's disable that message...
219 # pylint: disable=protected-access
220
221 extensions = backend._lib.X509_REQ_get_extensions(csr._x509_req) # type: ignore
222 extensions = backend._ffi.gc(
223 extensions,
224 lambda ext: backend._lib.sk_X509_EXTENSION_pop_free(
225 ext,
226 backend._ffi.addressof(
227 backend._lib._original_lib, "X509_EXTENSION_free"
228 ),
229 ),
230 )
231
232 # With cryptography 35.0.0, we can no longer use obj2txt. Unfortunately it still does
233 # not allow to get the raw value of an extension, so we have to use this ugly hack:
234 exts = list(csr.extensions)
235
236 for i in range(backend._lib.sk_X509_EXTENSION_num(extensions)):
237 ext = backend._lib.sk_X509_EXTENSION_value(extensions, i)
238 if ext == backend._ffi.NULL:
239 continue
240 crit = backend._lib.X509_EXTENSION_get_critical(ext)
241 data = backend._lib.X509_EXTENSION_get_data(ext)
242 backend.openssl_assert(data != backend._ffi.NULL)
243 der: bytes = backend._ffi.buffer(data.data, data.length)[:] # type: ignore
244 entry = {
245 "critical": (crit == 1),
246 "value": base64.b64encode(der).decode("ascii"),
247 }
248 try:
249 oid = obj2txt(
250 backend._lib,
251 backend._ffi,
252 backend._lib.X509_EXTENSION_get_object(ext),
253 )
254 except AttributeError:
255 oid = exts[i].oid.dotted_string
256 result[oid] = entry
257
258 return result
259
260
261 def cryptography_name_to_oid(name: str) -> x509.oid.ObjectIdentifier:
262 dotted = OID_LOOKUP.get(name)
263 if dotted is None:
264 if DOTTED_OID.match(name):
265 return x509.oid.ObjectIdentifier(name)
266 raise OpenSSLObjectError(f'Cannot find OID for "{name}"')
267 return x509.oid.ObjectIdentifier(dotted)
268
269
270 def cryptography_oid_to_name(
271 oid: x509.oid.ObjectIdentifier, *, short: bool = False
272 ) -> str:
273 dotted_string = oid.dotted_string
274 names = OID_MAP.get(dotted_string)
275 if names:
276 name = names[0]
277 else:
278 try:
279 name = oid._name # pylint: disable=protected-access
280 if name == "Unknown OID":
281 name = dotted_string
282 except AttributeError:
283 name = dotted_string
284 if short:
285 return NORMALIZE_NAMES_SHORT.get(name, name)
286 return NORMALIZE_NAMES.get(name, name)
287
288
289 def _get_hex(bytesstr: bytes) -> str:
290 data = binascii.hexlify(bytesstr)
291 return to_text(b":".join(data[i : i + 2] for i in range(0, len(data), 2)))
292
293
294 @t.overload
295 def _parse_hex(bytesstr: bytes | str) -> bytes: ...
296
297
298 @t.overload
299 def _parse_hex(bytesstr: bytes | str | None) -> bytes | None: ...
300
301
302 def _parse_hex(bytesstr: bytes | str | None) -> bytes | None:
303 if bytesstr is None:
304 return bytesstr
305 data = "".join(
306 [
307 ("0" * (2 - len(p)) + p) if len(p) < 2 else p
308 for p in to_text(bytesstr).split(":")
309 ]
310 )
311 return binascii.unhexlify(data)
312
313
314 DN_COMPONENT_START_RE = re.compile(b"^ *([a-zA-z0-9.]+) *= *")
315 DN_HEX_LETTER = b"0123456789abcdef"
316
317
318 def _int_to_byte(value: int) -> bytes:
319 return bytes((value,))
320
321
322 def _parse_dn_component(
323 name: bytes, *, sep: bytes = b",", decode_remainder: bool = True
324 ) -> tuple[x509.NameAttribute, bytes]:
325 m = DN_COMPONENT_START_RE.match(name)
326 if not m:
327 raise OpenSSLObjectError(f'cannot start part in "{to_text(name)}"')
328 oid = cryptography_name_to_oid(to_text(m.group(1)))
329 idx = len(m.group(0))
330 decoded_name = []
331 sep_str = sep + b"\\"
332 if decode_remainder:
333 length = len(name)
334 if length > idx and name[idx : idx + 1] == b"#":
335 # Decoding a hex string
336 idx += 1
337 while idx + 1 < length:
338 ch1 = name[idx : idx + 1]
339 ch2 = name[idx + 1 : idx + 2]
340 idx1 = DN_HEX_LETTER.find(ch1.lower())
341 idx2 = DN_HEX_LETTER.find(ch2.lower())
342 if idx1 < 0 or idx2 < 0:
343 raise OpenSSLObjectError(
344 f'Invalid hex sequence entry "{to_text(ch1 + ch2)}"'
345 )
346 idx += 2
347 decoded_name.append(_int_to_byte(idx1 * 16 + idx2))
348 else:
349 # Decoding a regular string
350 while idx < length:
351 i = idx
352 while i < length and name[i : i + 1] not in sep_str:
353 i += 1
354 if i > idx:
355 decoded_name.append(name[idx:i])
356 idx = i
357 while idx + 1 < length and name[idx : idx + 1] == b"\\":
358 ch = name[idx + 1 : idx + 2]
359 idx1 = DN_HEX_LETTER.find(ch.lower())
360 if idx1 >= 0:
361 if idx + 2 >= length:
362 raise OpenSSLObjectError(
363 f'Hex escape sequence "\\{to_text(ch)}" incomplete at end of string'
364 )
365 ch2 = name[idx + 2 : idx + 3]
366 idx2 = DN_HEX_LETTER.find(ch2.lower())
367 if idx2 < 0:
368 raise OpenSSLObjectError(
369 f'Hex escape sequence "\\{to_text(ch + ch2)}" has invalid second letter'
370 )
371 ch = _int_to_byte(idx1 * 16 + idx2)
372 idx += 1
373 idx += 2
374 decoded_name.append(ch)
375 if idx < length and name[idx : idx + 1] == sep:
376 break
377 else:
378 decoded_name.append(name[idx:])
379 idx = len(name)
380 return x509.NameAttribute(oid, to_text(b"".join(decoded_name))), name[idx:]
381
382
383 def _parse_dn(name: bytes) -> list[x509.NameAttribute]:
384 """
385 Parse a Distinguished Name.
386
387 Can be of the form ``CN=Test, O = Something`` or ``CN = Test,O= Something``.
388 """
389 original_name = name
390 name = name.lstrip()
391 sep = b","
392 if name.startswith(b"/"):
393 sep = b"/"
394 name = name[1:]
395 result = []
396 while name:
397 try:
398 attribute, name = _parse_dn_component(name, sep=sep)
399 except OpenSSLObjectError as e:
400 raise OpenSSLObjectError(
401 f"Error while parsing distinguished name {to_text(original_name)!r}: {e}"
402 ) from e
403 result.append(attribute)
404 if name:
405 if name[0:1] != sep or len(name) < 2:
406 raise OpenSSLObjectError(
407 f"Error while parsing distinguished name {to_text(original_name)!r}: unexpected end of string"
408 )
409 name = name[1:]
410 return result
411
412
413 def cryptography_parse_relative_distinguished_name(
414 rdn: list[str | bytes],
415 ) -> cryptography.x509.RelativeDistinguishedName:
416 names = []
417 for part in rdn:
418 try:
419 names.append(_parse_dn_component(to_bytes(part), decode_remainder=False)[0])
420 except OpenSSLObjectError as e:
421 raise OpenSSLObjectError(
422 f"Error while parsing relative distinguished name {to_text(part)!r}: {e}"
423 ) from e
424 return cryptography.x509.RelativeDistinguishedName(names)
425
426
427 def _is_ascii(value: str) -> bool:
428 """Check whether the Unicode string `value` contains only ASCII characters."""
429 try:
430 value.encode("ascii")
431 return True
432 except UnicodeEncodeError:
433 return False
434
435
436 def _adjust_idn(
437 value: str, *, idn_rewrite: t.Literal["ignore", "idna", "unicode"]
438 ) -> str:
439 if idn_rewrite == "ignore" or not value:
440 return value
441 if idn_rewrite == "idna" and _is_ascii(value):
442 return value
443 if idn_rewrite not in ("idna", "unicode"):
444 raise ValueError(f'Invalid value for idn_rewrite: "{idn_rewrite}"')
445 if not HAS_IDNA:
446 what = "IDNA" if idn_rewrite == "unicode" else "Unicode"
447 dest = "Unicode" if idn_rewrite == "unicode" else "IDNA"
448 raise OpenSSLObjectError(
449 missing_required_lib(
450 "idna",
451 reason=f'to transform {what} DNS name "{value}" to {dest}',
452 )
453 )
454 # Since IDNA does not like '*' or empty labels (except one empty label at the end),
455 # we split and let IDNA only handle labels that are neither empty or '*'.
456 parts = value.split(".")
457 for index, part in enumerate(parts):
458 if part in ("", "*"):
459 continue
460 try:
461 if idn_rewrite == "idna":
462 parts[index] = idna.encode(part).decode("ascii")
463 elif idn_rewrite == "unicode" and part.startswith("xn--"):
464 parts[index] = idna.decode(part)
465 except idna.IDNAError as exc2008:
466 try:
467 if idn_rewrite == "idna":
468 parts[index] = part.encode("idna").decode("ascii")
469 elif idn_rewrite == "unicode" and part.startswith("xn--"):
470 parts[index] = part.encode("ascii").decode("idna")
471 except Exception as exc2003:
472 what = "IDNA" if idn_rewrite == "unicode" else "Unicode"
473 dest = "Unicode" if idn_rewrite == "unicode" else "IDNA"
474 raise OpenSSLObjectError(
475 f'Error while transforming part "{part}" of {what} DNS name "{value}" to {dest}.'
476 f' IDNA2008 transformation resulted in "{exc2008}", IDNA2003 transformation resulted in "{exc2003}".'
477 ) from exc2003
478 return ".".join(parts)
479
480
481 def _adjust_idn_email(
482 value: str, *, idn_rewrite: t.Literal["ignore", "idna", "unicode"]
483 ) -> str:
484 idx = value.find("@")
485 if idx < 0:
486 return value
487 return f"{value[:idx]}@{_adjust_idn(value[idx + 1 :], idn_rewrite=idn_rewrite)}"
488
489
490 def _adjust_idn_url(
491 value: str, *, idn_rewrite: t.Literal["ignore", "idna", "unicode"]
492 ) -> str:
493 url = urlparse(value)
494 host = _adjust_idn(url.hostname, idn_rewrite=idn_rewrite) if url.hostname else None
495 if url.username is not None and url.password is not None:
496 host = f"{url.username}:{url.password}@{host}"
497 elif url.username is not None:
498 host = f"{url.username}@{host}"
499 if url.port is not None:
500 host = f"{host}:{url.port}"
501 return urlunparse(
502 ParseResult(
503 scheme=url.scheme,
504 netloc=host or "",
505 path=url.path,
506 params=url.params,
507 query=url.query,
508 fragment=url.fragment,
509 )
510 )
511
512
513 def cryptography_get_name(
514 name: str, *, what: str = "Subject Alternative Name"
515 ) -> x509.GeneralName:
516 """
517 Given a name string, returns a cryptography x509.GeneralName object.
518 Raises an OpenSSLObjectError if the name is unknown or cannot be parsed.
519 """
520 try:
521 if name.startswith("DNS:"):
522 return x509.DNSName(_adjust_idn(to_text(name[4:]), idn_rewrite="idna"))
523 if name.startswith("IP:"):
524 address = to_text(name[3:])
525 if "/" in address:
526 return x509.IPAddress(ipaddress.ip_network(address))
527 return x509.IPAddress(ipaddress.ip_address(address))
528 if name.startswith("email:"):
529 return x509.RFC822Name(
530 _adjust_idn_email(to_text(name[6:]), idn_rewrite="idna")
531 )
532 if name.startswith("URI:"):
533 return x509.UniformResourceIdentifier(
534 _adjust_idn_url(to_text(name[4:]), idn_rewrite="idna")
535 )
536 if name.startswith("RID:"):
537 m = re.match(r"^([0-9]+(?:\.[0-9]+)*)$", to_text(name[4:]))
538 if not m:
539 raise OpenSSLObjectError(f'Cannot parse {what} "{name}"')
540 return x509.RegisteredID(x509.oid.ObjectIdentifier(m.group(1)))
541 if name.startswith("otherName:"):
542 # otherName can either be a raw ASN.1 hex string or in the format that OpenSSL works with.
543 m = re.match(
544 r"^([0-9]+(?:\.[0-9]+)*);([0-9a-fA-F]{1,2}(?::[0-9a-fA-F]{1,2})*)$",
545 to_text(name[10:]),
546 )
547 if m:
548 return x509.OtherName(
549 x509.oid.ObjectIdentifier(m.group(1)), _parse_hex(m.group(2))
550 )
551
552 # See https://www.openssl.org/docs/man1.0.2/man5/x509v3_config.html - Subject Alternative Name for more
553 # defailts on the format expected.
554 name = to_text(name[10:], errors="surrogate_or_strict")
555 if ";" not in name:
556 raise OpenSSLObjectError(
557 f'Cannot parse {what} otherName "{name}", must be in the '
558 'format "otherName:<OID>;<ASN.1 OpenSSL Encoded String>" or '
559 '"otherName:<OID>;<hex string>"'
560 )
561
562 oid, value = name.split(";", 1)
563 b_value = serialize_asn1_string_as_der(value)
564 return x509.OtherName(x509.ObjectIdentifier(oid), b_value)
565 if name.startswith("dirName:"):
566 return x509.DirectoryName(
567 x509.Name(reversed(_parse_dn(to_bytes(name[8:]))))
568 )
569 except Exception as e:
570 raise OpenSSLObjectError(f'Cannot parse {what} "{name}": {e}') from e
571 if ":" not in name:
572 raise OpenSSLObjectError(
573 f'Cannot parse {what} "{name}" (forgot "DNS:" prefix?)'
574 )
575 raise OpenSSLObjectError(
576 f'Cannot parse {what} "{name}" (potentially unsupported by cryptography backend)'
577 )
578
579
580 def _dn_escape_value(value: str) -> str:
581 """
582 Escape Distinguished Name's attribute value.
583 """
584 value = value.replace("\\", "\\\\")
585 for ch in [",", "+", "<", ">", ";", '"']:
586 value = value.replace(ch, f"\\{ch}")
587 value = value.replace("\0", "\\00")
588 if value.startswith((" ", "#")):
589 value = f"\\{value[0]}{value[1:]}"
590 if value.endswith(" "):
591 value = f"{value[:-1]}\\ "
592 return value
593
594
595 def cryptography_decode_name(
596 name: x509.GeneralName,
597 *,
598 idn_rewrite: t.Literal["ignore", "idna", "unicode"] = "ignore",
599 ) -> str:
600 """
601 Given a cryptography x509.GeneralName object, returns a string.
602 Raises an OpenSSLObjectError if the name is not supported.
603 """
604 if idn_rewrite not in ("ignore", "idna", "unicode"):
605 raise AssertionError( # pragma: no cover
606 'idn_rewrite must be one of "ignore", "idna", or "unicode"'
607 )
608 if isinstance(name, x509.DNSName):
609 return f"DNS:{_adjust_idn(name.value, idn_rewrite=idn_rewrite)}"
610 if isinstance(name, x509.IPAddress):
611 if isinstance(name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
612 return f"IP:{name.value.network_address.compressed}/{name.value.prefixlen}"
613 return f"IP:{name.value.compressed}"
614 if isinstance(name, x509.RFC822Name):
615 return f"email:{_adjust_idn_email(name.value, idn_rewrite=idn_rewrite)}"
616 if isinstance(name, x509.UniformResourceIdentifier):
617 return f"URI:{_adjust_idn_url(name.value, idn_rewrite=idn_rewrite)}"
618 if isinstance(name, x509.DirectoryName):
619 # According to https://datatracker.ietf.org/doc/html/rfc4514.html#section-2.1 the
620 # list needs to be reversed, and joined by commas
621 return "dirName:" + ",".join(
622 [
623 f"{to_text(cryptography_oid_to_name(attribute.oid, short=True))}={_dn_escape_value(to_text(attribute.value))}"
624 for attribute in reversed(list(name.value))
625 ]
626 )
627 if isinstance(name, x509.RegisteredID):
628 return f"RID:{name.value.dotted_string}"
629 if isinstance(name, x509.OtherName):
630 return f"otherName:{name.type_id.dotted_string};{_get_hex(name.value)}"
631 raise OpenSSLObjectError(f'Cannot decode name "{name}"')
632
633
634 def _cryptography_get_keyusage(usage: str) -> str:
635 """
636 Given a key usage identifier string, returns the parameter name used by cryptography's x509.KeyUsage().
637 Raises an OpenSSLObjectError if the identifier is unknown.
638 """
639 if usage in ("Digital Signature", "digitalSignature"):
640 return "digital_signature"
641 if usage in ("Non Repudiation", "nonRepudiation"):
642 return "content_commitment"
643 if usage in ("Key Encipherment", "keyEncipherment"):
644 return "key_encipherment"
645 if usage in ("Data Encipherment", "dataEncipherment"):
646 return "data_encipherment"
647 if usage in ("Key Agreement", "keyAgreement"):
648 return "key_agreement"
649 if usage in ("Certificate Sign", "keyCertSign"):
650 return "key_cert_sign"
651 if usage in ("CRL Sign", "cRLSign"):
652 return "crl_sign"
653 if usage in ("Encipher Only", "encipherOnly"):
654 return "encipher_only"
655 if usage in ("Decipher Only", "decipherOnly"):
656 return "decipher_only"
657 raise OpenSSLObjectError(f'Unknown key usage "{usage}"')
658
659
660 def cryptography_parse_key_usage_params(usages: t.Iterable[str]) -> dict[str, bool]:
661 """
662 Given a list of key usage identifier strings, returns the parameters for cryptography's x509.KeyUsage().
663 Raises an OpenSSLObjectError if an identifier is unknown.
664 """
665 params = {
666 "digital_signature": False,
667 "content_commitment": False,
668 "key_encipherment": False,
669 "data_encipherment": False,
670 "key_agreement": False,
671 "key_cert_sign": False,
672 "crl_sign": False,
673 "encipher_only": False,
674 "decipher_only": False,
675 }
676 for usage in usages:
677 params[_cryptography_get_keyusage(usage)] = True
678 return params
679
680
681 def cryptography_get_basic_constraints(
682 constraints: t.Iterable[str] | None,
683 ) -> tuple[bool, int | None]:
684 """
685 Given a list of constraints, returns a tuple (ca, path_length).
686 Raises an OpenSSLObjectError if a constraint is unknown or cannot be parsed.
687 """
688 ca = False
689 path_length: int | None = None
690 if constraints:
691 for constraint in constraints:
692 if constraint.startswith("CA:"):
693 if constraint == "CA:TRUE":
694 ca = True
695 elif constraint == "CA:FALSE":
696 ca = False
697 else:
698 raise OpenSSLObjectError(
699 f'Unknown basic constraint value "{constraint[3:]}" for CA'
700 )
701 elif constraint.startswith("pathlen:"):
702 v = constraint[len("pathlen:") :]
703 try:
704 path_length = int(v)
705 except Exception as e:
706 raise OpenSSLObjectError(
707 f'Cannot parse path length constraint "{v}" ({e})'
708 ) from e
709 else:
710 raise OpenSSLObjectError(f'Unknown basic constraint "{constraint}"')
711 return ca, path_length
712
713
714 def cryptography_key_needs_digest_for_signing(
715 key: CertificateIssuerPrivateKeyTypes,
716 ) -> bool:
717 """Tests whether the given private key requires a digest algorithm for signing.
718
719 Ed25519 and Ed448 keys do not; they need None to be passed as the digest algorithm.
720 """
721 if isinstance(
722 key, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey
723 ):
724 return False
725 return not isinstance(
726 key, cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey
727 )
728
729
730 def _compare_public_keys(
731 key1: PublicKeyTypes, key2: PublicKeyTypes, *, clazz: type[PublicKeyTypes]
732 ) -> bool | None:
733 a = isinstance(key1, clazz)
734 b = isinstance(key2, clazz)
735 if not (a or b):
736 return None
737 if not a or not b:
738 return False
739 a_bytes = key1.public_bytes(
740 serialization.Encoding.Raw, serialization.PublicFormat.Raw
741 )
742 b_bytes = key2.public_bytes(
743 serialization.Encoding.Raw, serialization.PublicFormat.Raw
744 )
745 return a_bytes == b_bytes
746
747
748 def cryptography_compare_public_keys(
749 key1: PublicKeyTypes, key2: PublicKeyTypes
750 ) -> bool:
751 """Tests whether two public keys are the same.
752
753 Needs special logic for Ed25519 and Ed448 keys, since they do not have public_numbers().
754 """
755 res = _compare_public_keys(
756 key1,
757 key2,
758 clazz=cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey,
759 )
760 if res is not None:
761 return res
762 res = _compare_public_keys(
763 key1,
764 key2,
765 clazz=cryptography.hazmat.primitives.asymmetric.x25519.X25519PublicKey,
766 )
767 if res is not None:
768 return res
769 res = _compare_public_keys(
770 key1, key2, clazz=cryptography.hazmat.primitives.asymmetric.ed448.Ed448PublicKey
771 )
772 if res is not None:
773 return res
774 res = _compare_public_keys(
775 key1, key2, clazz=cryptography.hazmat.primitives.asymmetric.x448.X448PublicKey
776 )
777 if res is not None:
778 return res
779 return (
780 t.cast(PublicKeyTypesWOEdwards, key1).public_numbers()
781 == t.cast(PublicKeyTypesWOEdwards, key2).public_numbers()
782 )
783
784
785 def _compare_private_keys(
786 key1: PrivateKeyTypes, key2: PrivateKeyTypes, *, clazz: type[PrivateKeyTypes]
787 ) -> bool | None:
788 a = isinstance(key1, clazz)
789 b = isinstance(key2, clazz)
790 if not (a or b):
791 return None
792 if not a or not b:
793 return False
794 encryption_algorithm = cryptography.hazmat.primitives.serialization.NoEncryption()
795 a_bytes = key1.private_bytes(
796 serialization.Encoding.Raw,
797 serialization.PrivateFormat.Raw,
798 encryption_algorithm=encryption_algorithm,
799 )
800 b_bytes = key2.private_bytes(
801 serialization.Encoding.Raw,
802 serialization.PrivateFormat.Raw,
803 encryption_algorithm=encryption_algorithm,
804 )
805 return a_bytes == b_bytes
806
807
808 def cryptography_compare_private_keys(
809 key1: PrivateKeyTypes, key2: PrivateKeyTypes
810 ) -> bool:
811 """Tests whether two private keys are the same.
812
813 Needs special logic for Ed25519, X25519, and Ed448 keys, since they do not have private_numbers().
814 """
815 res = _compare_private_keys(
816 key1,
817 key2,
818 clazz=cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey,
819 )
820 if res is not None:
821 return res
822 res = _compare_private_keys(
823 key1,
824 key2,
825 clazz=cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
826 )
827 if res is not None:
828 return res
829 res = _compare_private_keys(
830 key1,
831 key2,
832 clazz=cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey,
833 )
834 if res is not None:
835 return res
836 res = _compare_private_keys(
837 key1, key2, clazz=cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey
838 )
839 if res is not None:
840 return res
841 return (
842 t.cast(PrivateKeyTypesWOEdwards, key1).private_numbers()
843 == t.cast(PrivateKeyTypesWOEdwards, key2).private_numbers()
844 )
845
846
847 def parse_pkcs12(
848 pkcs12_bytes: bytes, *, passphrase: bytes | str | None = None
849 ) -> tuple[
850 PrivateKeyTypes | None,
851 x509.Certificate | None,
852 list[x509.Certificate],
853 bytes | None,
854 ]:
855 """Returns a tuple (private_key, certificate, additional_certificates, friendly_name)."""
856 passphrase_bytes = None
857 if passphrase is not None:
858 passphrase_bytes = to_bytes(passphrase)
859
860 # Main code for cryptography 36.0.0 and forward
861 if _load_pkcs12 is not None:
862 return _parse_pkcs12_36_0_0(pkcs12_bytes, passphrase=passphrase_bytes)
863
864 if LooseVersion(cryptography.__version__) >= LooseVersion("35.0"): # type: ignore[unreachable]
865 return _parse_pkcs12_35_0_0(pkcs12_bytes, passphrase=passphrase_bytes)
866
867 return _parse_pkcs12_legacy(pkcs12_bytes, passphrase=passphrase_bytes)
868
869
870 def _parse_pkcs12_36_0_0(
871 pkcs12_bytes: bytes, *, passphrase: bytes | None = None
872 ) -> tuple[
873 PrivateKeyTypes | None,
874 x509.Certificate | None,
875 list[x509.Certificate],
876 bytes | None,
877 ]:
878 # Requires cryptography 36.0.0 or newer
879 pkcs12 = _load_pkcs12(pkcs12_bytes, passphrase)
880 additional_certificates = [cert.certificate for cert in pkcs12.additional_certs]
881 private_key = pkcs12.key
882 certificate = None
883 friendly_name = None
884 if pkcs12.cert:
885 certificate = pkcs12.cert.certificate
886 friendly_name = pkcs12.cert.friendly_name
887 return private_key, certificate, additional_certificates, friendly_name
888
889
890 def _parse_pkcs12_35_0_0(
891 pkcs12_bytes: bytes, *, passphrase: bytes | None = None
892 ) -> tuple[
893 PrivateKeyTypes | None,
894 x509.Certificate | None,
895 list[x509.Certificate],
896 bytes | None,
897 ]:
898 # Backwards compatibility code for cryptography 35.x
899 private_key, certificate, additional_certificates = _load_key_and_certificates(
900 pkcs12_bytes, passphrase
901 )
902
903 friendly_name = None
904 if certificate:
905 # See https://github.com/pyca/cryptography/issues/5760#issuecomment-842687238
906 from cryptography.hazmat.backends import default_backend
907
908 backend = default_backend()
909
910 # We access a *lot* of internal APIs here, so let's disable that message...
911 # pylint: disable=protected-access
912
913 # This code basically does what load_key_and_certificates() does, but without error-checking.
914 # Since load_key_and_certificates succeeded, it should not fail.
915 pkcs12 = backend._ffi.gc(
916 backend._lib.d2i_PKCS12_bio(
917 backend._bytes_to_bio(pkcs12_bytes).bio, # pylint: disable=no-member
918 backend._ffi.NULL,
919 ),
920 backend._lib.PKCS12_free,
921 )
922 certificate_x509_ptr = backend._ffi.new("X509 **")
923 with backend._zeroed_null_terminated_buf( # pylint: disable=no-member
924 to_bytes(passphrase) if passphrase is not None else None
925 ) as passphrase_buffer:
926 backend._lib.PKCS12_parse(
927 pkcs12,
928 passphrase_buffer,
929 backend._ffi.new("EVP_PKEY **"),
930 certificate_x509_ptr,
931 backend._ffi.new("Cryptography_STACK_OF_X509 **"),
932 )
933 if certificate_x509_ptr[0] != backend._ffi.NULL:
934 maybe_name = backend._lib.X509_alias_get0(
935 certificate_x509_ptr[0], backend._ffi.NULL
936 )
937 if maybe_name != backend._ffi.NULL:
938 friendly_name = backend._ffi.string(maybe_name)
939
940 return private_key, certificate, additional_certificates, friendly_name
941
942
943 def _parse_pkcs12_legacy(
944 pkcs12_bytes: bytes, *, passphrase: bytes | None = None
945 ) -> tuple[
946 PrivateKeyTypes | None,
947 x509.Certificate | None,
948 list[x509.Certificate],
949 bytes | None,
950 ]:
951 # Backwards compatibility code for cryptography < 35.0.0
952 private_key, certificate, additional_certificates = _load_key_and_certificates(
953 pkcs12_bytes, passphrase
954 )
955
956 # We access a *lot* of internal APIs here, so let's disable that message...
957 # pylint: disable=protected-access
958
959 friendly_name = None
960 if certificate:
961 # See https://github.com/pyca/cryptography/issues/5760#issuecomment-842687238
962 backend = certificate._backend # type: ignore
963 maybe_name = backend._lib.X509_alias_get0(certificate._x509, backend._ffi.NULL) # type: ignore
964 if maybe_name != backend._ffi.NULL:
965 friendly_name = backend._ffi.string(maybe_name)
966 return private_key, certificate, additional_certificates, friendly_name
967
968
969 def cryptography_verify_signature(
970 *,
971 signature: bytes,
972 data: bytes,
973 hash_algorithm: hashes.HashAlgorithm | None,
974 signer_public_key: PublicKeyTypes,
975 ) -> bool:
976 """
977 Check whether the given signature of the given data was signed by the given public key object.
978 """
979 try:
980 if isinstance(
981 signer_public_key,
982 cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey,
983 ):
984 if hash_algorithm is None:
985 raise OpenSSLObjectError("Need hash_algorithm for RSA keys")
986 signer_public_key.verify(
987 signature, data, padding.PKCS1v15(), hash_algorithm
988 )
989 return True
990 if isinstance(
991 signer_public_key,
992 cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey,
993 ):
994 if hash_algorithm is None:
995 raise OpenSSLObjectError("Need hash_algorithm for ECC keys")
996 signer_public_key.verify(
997 signature,
998 data,
999 cryptography.hazmat.primitives.asymmetric.ec.ECDSA(hash_algorithm),
1000 )
1001 return True
1002 if isinstance(
1003 signer_public_key,
1004 cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey,
1005 ):
1006 if hash_algorithm is None:
1007 raise OpenSSLObjectError("Need hash_algorithm for DSA keys")
1008 signer_public_key.verify(signature, data, hash_algorithm)
1009 return True
1010 if isinstance(
1011 signer_public_key,
1012 cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey,
1013 ):
1014 signer_public_key.verify(signature, data)
1015 return True
1016 if isinstance(
1017 signer_public_key,
1018 cryptography.hazmat.primitives.asymmetric.ed448.Ed448PublicKey,
1019 ):
1020 signer_public_key.verify(signature, data)
1021 return True
1022 raise OpenSSLObjectError(
1023 f"Unsupported public key type {type(signer_public_key)}"
1024 )
1025 except InvalidSignature:
1026 return False
1027
1028
1029 def cryptography_verify_certificate_signature(
1030 *, certificate: x509.Certificate, signer_public_key: PublicKeyTypes
1031 ) -> bool:
1032 """
1033 Check whether the given X509 certificate object was signed by the given public key object.
1034 """
1035 return cryptography_verify_signature(
1036 signature=certificate.signature,
1037 data=certificate.tbs_certificate_bytes,
1038 hash_algorithm=certificate.signature_hash_algorithm,
1039 signer_public_key=signer_public_key,
1040 )
1041
1042
1043 def get_not_valid_after(obj: x509.Certificate) -> datetime.datetime:
1044 if CRYPTOGRAPHY_TIMEZONE:
1045 return obj.not_valid_after_utc
1046 return obj.not_valid_after
1047
1048
1049 def get_not_valid_before(obj: x509.Certificate) -> datetime.datetime:
1050 if CRYPTOGRAPHY_TIMEZONE:
1051 return obj.not_valid_before_utc
1052 return obj.not_valid_before
1053
1054
1055 def set_not_valid_after(
1056 builder: x509.CertificateBuilder, value: datetime.datetime
1057 ) -> x509.CertificateBuilder:
1058 return builder.not_valid_after(value)
1059
1060
1061 def set_not_valid_before(
1062 builder: x509.CertificateBuilder, value: datetime.datetime
1063 ) -> x509.CertificateBuilder:
1064 return builder.not_valid_before(value)
1065
1066
1067 def is_potential_certificate_private_key(
1068 key: PrivateKeyTypes,
1069 ) -> t.TypeGuard[CertificatePrivateKeyTypes]:
1070 return not isinstance(
1071 key, cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey
1072 )
1073
1074
1075 def is_potential_certificate_issuer_private_key(
1076 key: PrivateKeyTypes,
1077 ) -> t.TypeGuard[CertificateIssuerPrivateKeyTypes]:
1078 return not isinstance(
1079 key,
1080 (
1081 cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
1082 cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey,
1083 cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey,
1084 ),
1085 )
1086
1087
1088 def is_potential_certificate_public_key(
1089 key: PublicKeyTypes,
1090 ) -> t.TypeGuard[CertificatePublicKeyTypes]:
1091 return not isinstance(key, DHPublicKey)
1092
1093
1094 def is_potential_certificate_issuer_public_key(
1095 key: PublicKeyTypes,
1096 ) -> t.TypeGuard[CertificateIssuerPublicKeyTypes]:
1097 return not isinstance(
1098 key,
1099 (
1100 cryptography.hazmat.primitives.asymmetric.x25519.X25519PublicKey,
1101 cryptography.hazmat.primitives.asymmetric.x448.X448PublicKey,
1102 cryptography.hazmat.primitives.asymmetric.dh.DHPublicKey,
1103 ),
1104 )
1105
1106
1107 __all__ = (
1108 "CRYPTOGRAPHY_TIMEZONE",
1109 "cryptography_compare_private_keys",
1110 "cryptography_compare_public_keys",
1111 "cryptography_decode_name",
1112 "cryptography_get_basic_constraints",
1113 "cryptography_get_extensions_from_cert",
1114 "cryptography_get_extensions_from_csr",
1115 "cryptography_get_name",
1116 "cryptography_key_needs_digest_for_signing",
1117 "cryptography_name_to_oid",
1118 "cryptography_oid_to_name",
1119 "cryptography_parse_key_usage_params",
1120 "cryptography_parse_relative_distinguished_name",
1121 "cryptography_verify_certificate_signature",
1122 "cryptography_verify_signature",
1123 "get_not_valid_after",
1124 "get_not_valid_before",
1125 "is_potential_certificate_issuer_private_key",
1126 "is_potential_certificate_issuer_public_key",
1127 "is_potential_certificate_private_key",
1128 "is_potential_certificate_public_key",
1129 "parse_pkcs12",
1130 "set_not_valid_after",
1131 "set_not_valid_before",
1132 )