Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/module_backends/csr.py

raw
1 # Copyright (c) 2016, Yanis Guenane <[email protected]>
2 # Copyright (c) 2020, 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 binascii
12 import typing as t
13
14 from ansible.module_utils.common.text.converters import to_text
15
16 from ansible_collections.community.crypto.plugins.module_utils._argspec import (
17 ArgumentSpec,
18 )
19 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
20 OpenSSLBadPassphraseError,
21 OpenSSLObjectError,
22 )
23 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_crl import (
24 REVOCATION_REASON_MAP,
25 )
26 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
27 cryptography_get_basic_constraints,
28 cryptography_get_name,
29 cryptography_key_needs_digest_for_signing,
30 cryptography_name_to_oid,
31 cryptography_parse_key_usage_params,
32 cryptography_parse_relative_distinguished_name,
33 is_potential_certificate_issuer_public_key,
34 )
35 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr_info import (
36 get_csr_info,
37 )
38 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
39 load_certificate_issuer_privatekey,
40 load_certificate_request,
41 parse_name_field,
42 parse_ordered_name_field,
43 select_message_digest,
44 )
45 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
46 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
47 assert_required_cryptography_version,
48 )
49
50 if t.TYPE_CHECKING:
51 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
52 from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
53 CertificateIssuerPrivateKeyTypes,
54 )
55
56 _ET = t.TypeVar("_ET", bound="cryptography.x509.ExtensionType") # pragma: no cover
57
58
59 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
60
61 try:
62 import cryptography
63 import cryptography.exceptions
64 import cryptography.hazmat.backends
65 import cryptography.hazmat.primitives.hashes
66 import cryptography.hazmat.primitives.serialization
67 import cryptography.x509
68 import cryptography.x509.oid
69 except ImportError:
70 pass
71
72
73 class CertificateSigningRequestError(OpenSSLObjectError):
74 pass
75
76
77 # From the object called `module`, only the following properties are used:
78 #
79 # - module.params[]
80 # - module.warn(msg: str)
81 # - module.fail_json(msg: str, **kwargs)
82
83
84 def parse_crl_distribution_points(
85 *, module: AnsibleModule, crl_distribution_points: list[dict[str, t.Any]]
86 ) -> list[cryptography.x509.DistributionPoint]:
87 result = []
88 for index, parse_crl_distribution_point in enumerate(crl_distribution_points):
89 try:
90 full_name = None
91 relative_name = None
92 crl_issuer = None
93 reasons = None
94 if parse_crl_distribution_point["full_name"] is not None:
95 if not parse_crl_distribution_point["full_name"]:
96 raise OpenSSLObjectError("full_name must not be empty")
97 full_name = [
98 cryptography_get_name(name, what="full name")
99 for name in parse_crl_distribution_point["full_name"]
100 ]
101 if parse_crl_distribution_point["relative_name"] is not None:
102 if not parse_crl_distribution_point["relative_name"]:
103 raise OpenSSLObjectError("relative_name must not be empty")
104 relative_name = cryptography_parse_relative_distinguished_name(
105 parse_crl_distribution_point["relative_name"]
106 )
107 if parse_crl_distribution_point["crl_issuer"] is not None:
108 if not parse_crl_distribution_point["crl_issuer"]:
109 raise OpenSSLObjectError("crl_issuer must not be empty")
110 crl_issuer = [
111 cryptography_get_name(name, what="CRL issuer")
112 for name in parse_crl_distribution_point["crl_issuer"]
113 ]
114 if parse_crl_distribution_point["reasons"] is not None:
115 reasons_list = []
116 for reason in parse_crl_distribution_point["reasons"]:
117 reasons_list.append(REVOCATION_REASON_MAP[reason])
118 reasons = frozenset(reasons_list)
119 result.append(
120 cryptography.x509.DistributionPoint(
121 full_name=full_name,
122 relative_name=relative_name,
123 crl_issuer=crl_issuer,
124 reasons=reasons,
125 )
126 )
127 except (OpenSSLObjectError, ValueError) as e:
128 raise OpenSSLObjectError(
129 f"Error while parsing CRL distribution point #{index}: {e}"
130 ) from e
131 return result
132
133
134 class CertificateSigningRequestBackend:
135 def __init__(self, *, module: AnsibleModule) -> None:
136 self.module = module
137 self.digest: str = module.params["digest"]
138 self.privatekey_path: str | None = module.params["privatekey_path"]
139 privatekey_content: str | None = module.params["privatekey_content"]
140 if privatekey_content is not None:
141 self.privatekey_content: bytes | None = privatekey_content.encode("utf-8")
142 else:
143 self.privatekey_content = None
144 self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"]
145 self.version: t.Literal[1] = module.params["version"]
146 self.subject_alt_name: list[str] | None = module.params["subject_alt_name"]
147 self.subject_alt_name_critical: bool = module.params[
148 "subject_alt_name_critical"
149 ]
150 self.key_usage: list[str] | None = module.params["key_usage"]
151 self.key_usage_critical: bool = module.params["key_usage_critical"]
152 self.extended_key_usage: list[str] | None = module.params["extended_key_usage"]
153 self.extended_key_usage_critical: bool = module.params[
154 "extended_key_usage_critical"
155 ]
156 self.basic_constraints: list[str] | None = module.params["basic_constraints"]
157 self.basic_constraints_critical: bool = module.params[
158 "basic_constraints_critical"
159 ]
160 self.ocsp_must_staple: bool = module.params["ocsp_must_staple"]
161 self.ocsp_must_staple_critical: bool = module.params[
162 "ocsp_must_staple_critical"
163 ]
164 self.name_constraints_permitted: list[str] = (
165 module.params["name_constraints_permitted"] or []
166 )
167 self.name_constraints_excluded: list[str] = (
168 module.params["name_constraints_excluded"] or []
169 )
170 self.name_constraints_critical: bool = module.params[
171 "name_constraints_critical"
172 ]
173 self.create_subject_key_identifier: bool = module.params[
174 "create_subject_key_identifier"
175 ]
176 subject_key_identifier: str | None = module.params["subject_key_identifier"]
177 authority_key_identifier: str | None = module.params["authority_key_identifier"]
178 self.authority_cert_issuer: list[str] | None = module.params[
179 "authority_cert_issuer"
180 ]
181 self.authority_cert_serial_number: int | None = module.params[
182 "authority_cert_serial_number"
183 ]
184 self.crl_distribution_points: (
185 list[cryptography.x509.DistributionPoint] | None
186 ) = None
187 self.csr: cryptography.x509.CertificateSigningRequest | None = None
188 self.privatekey: CertificateIssuerPrivateKeyTypes | None = None
189
190 if self.create_subject_key_identifier and subject_key_identifier is not None:
191 module.fail_json(
192 msg="subject_key_identifier cannot be specified if create_subject_key_identifier is true"
193 )
194
195 self.ordered_subject = False
196 subject = [
197 ("C", module.params["country_name"]),
198 ("ST", module.params["state_or_province_name"]),
199 ("L", module.params["locality_name"]),
200 ("O", module.params["organization_name"]),
201 ("OU", module.params["organizational_unit_name"]),
202 ("CN", module.params["common_name"]),
203 ("emailAddress", module.params["email_address"]),
204 ]
205 self.subject: list[tuple[str, str]] = [
206 (entry[0], entry[1]) for entry in subject if entry[1]
207 ]
208
209 try:
210 if module.params["subject"]:
211 self.subject = self.subject + parse_name_field(
212 module.params["subject"], name_field_name="subject"
213 )
214 if module.params["subject_ordered"]:
215 if self.subject:
216 raise CertificateSigningRequestError(
217 "subject_ordered cannot be combined with any other subject field"
218 )
219 self.subject = parse_ordered_name_field(
220 module.params["subject_ordered"], name_field_name="subject_ordered"
221 )
222 self.ordered_subject = True
223 except ValueError as exc:
224 raise CertificateSigningRequestError(str(exc)) from exc
225
226 self.using_common_name_for_san = False
227 if not self.subject_alt_name and module.params["use_common_name_for_san"]:
228 for sub in self.subject:
229 if sub[0] in ("commonName", "CN"):
230 self.subject_alt_name = [f"DNS:{sub[1]}"]
231 self.using_common_name_for_san = True
232 break
233
234 self.subject_key_identifier: bytes | None = None
235 if subject_key_identifier is not None:
236 try:
237 self.subject_key_identifier = binascii.unhexlify(
238 subject_key_identifier.replace(":", "")
239 )
240 except Exception as e:
241 raise CertificateSigningRequestError(
242 f"Cannot parse subject_key_identifier: {e}"
243 ) from e
244
245 self.authority_key_identifier: bytes | None = None
246 if authority_key_identifier is not None:
247 try:
248 self.authority_key_identifier = binascii.unhexlify(
249 authority_key_identifier.replace(":", "")
250 )
251 except Exception as e:
252 raise CertificateSigningRequestError(
253 f"Cannot parse authority_key_identifier: {e}"
254 ) from e
255
256 self.existing_csr: cryptography.x509.CertificateSigningRequest | None = None
257 self.existing_csr_bytes: bytes | None = None
258
259 self.diff_before = self._get_info(data=None)
260 self.diff_after = self._get_info(data=None)
261
262 crl_distribution_points: list[dict[str, t.Any]] | None = module.params[
263 "crl_distribution_points"
264 ]
265 if crl_distribution_points:
266 self.crl_distribution_points = parse_crl_distribution_points(
267 module=module, crl_distribution_points=crl_distribution_points
268 )
269
270 def _get_info(self, *, data: bytes | None) -> dict[str, t.Any]:
271 if data is None:
272 return {}
273 try:
274 result = get_csr_info(
275 module=self.module,
276 content=data,
277 validate_signature=False,
278 prefer_one_fingerprint=True,
279 )
280 result["can_parse_csr"] = True
281 return result
282 except Exception:
283 return {"can_parse_csr": False}
284
285 def generate_csr(self) -> None:
286 """(Re-)Generate CSR."""
287 self._ensure_private_key_loaded()
288 assert self.privatekey is not None
289
290 csr = cryptography.x509.CertificateSigningRequestBuilder()
291 try:
292 csr = csr.subject_name(
293 cryptography.x509.Name(
294 [
295 cryptography.x509.NameAttribute(
296 cryptography_name_to_oid(entry[0]), to_text(entry[1])
297 )
298 for entry in self.subject
299 ]
300 )
301 )
302 except ValueError as e:
303 raise CertificateSigningRequestError(e) from e
304
305 if self.subject_alt_name:
306 csr = csr.add_extension(
307 cryptography.x509.SubjectAlternativeName(
308 [cryptography_get_name(name) for name in self.subject_alt_name]
309 ),
310 critical=self.subject_alt_name_critical,
311 )
312
313 if self.key_usage:
314 params = cryptography_parse_key_usage_params(self.key_usage)
315 csr = csr.add_extension(
316 cryptography.x509.KeyUsage(**params), critical=self.key_usage_critical
317 )
318
319 if self.extended_key_usage:
320 usages = [
321 cryptography_name_to_oid(usage) for usage in self.extended_key_usage
322 ]
323 csr = csr.add_extension(
324 cryptography.x509.ExtendedKeyUsage(usages),
325 critical=self.extended_key_usage_critical,
326 )
327
328 if self.basic_constraints:
329 params = {}
330 ca, path_length = cryptography_get_basic_constraints(self.basic_constraints)
331 csr = csr.add_extension(
332 cryptography.x509.BasicConstraints(ca, path_length),
333 critical=self.basic_constraints_critical,
334 )
335
336 if self.ocsp_must_staple:
337 csr = csr.add_extension(
338 cryptography.x509.TLSFeature(
339 [cryptography.x509.TLSFeatureType.status_request]
340 ),
341 critical=self.ocsp_must_staple_critical,
342 )
343
344 if self.name_constraints_permitted or self.name_constraints_excluded:
345 try:
346 csr = csr.add_extension(
347 cryptography.x509.NameConstraints(
348 [
349 cryptography_get_name(
350 name, what="name constraints permitted"
351 )
352 for name in self.name_constraints_permitted
353 ]
354 or None,
355 [
356 cryptography_get_name(
357 name, what="name constraints excluded"
358 )
359 for name in self.name_constraints_excluded
360 ]
361 or None,
362 ),
363 critical=self.name_constraints_critical,
364 )
365 except TypeError as e:
366 raise OpenSSLObjectError(
367 f"Error while parsing name constraint: {e}"
368 ) from e
369
370 if self.create_subject_key_identifier:
371 if not is_potential_certificate_issuer_public_key(
372 self.privatekey.public_key()
373 ):
374 raise OpenSSLObjectError(
375 "Private key can not be used to create subject key identifier"
376 )
377 csr = csr.add_extension(
378 cryptography.x509.SubjectKeyIdentifier.from_public_key(
379 self.privatekey.public_key()
380 ),
381 critical=False,
382 )
383 elif self.subject_key_identifier is not None:
384 csr = csr.add_extension(
385 cryptography.x509.SubjectKeyIdentifier(self.subject_key_identifier),
386 critical=False,
387 )
388
389 if (
390 self.authority_key_identifier is not None
391 or self.authority_cert_issuer is not None
392 or self.authority_cert_serial_number is not None
393 ):
394 issuers = None
395 if self.authority_cert_issuer is not None:
396 issuers = [
397 cryptography_get_name(n, what="authority cert issuer")
398 for n in self.authority_cert_issuer
399 ]
400 csr = csr.add_extension(
401 cryptography.x509.AuthorityKeyIdentifier(
402 self.authority_key_identifier,
403 issuers,
404 self.authority_cert_serial_number,
405 ),
406 critical=False,
407 )
408
409 if self.crl_distribution_points:
410 csr = csr.add_extension(
411 cryptography.x509.CRLDistributionPoints(self.crl_distribution_points),
412 critical=False,
413 )
414
415 # csr.sign() does not accept some digests we theoretically could have in digest.
416 # For that reason we use type t.Any here. csr.sign() will complain if
417 # the digest is not acceptable.
418 digest: t.Any | None = None
419 if cryptography_key_needs_digest_for_signing(self.privatekey):
420 digest = select_message_digest(self.digest)
421 if digest is None:
422 raise CertificateSigningRequestError(
423 f'Unsupported digest "{self.digest}"'
424 )
425 try:
426 self.csr = csr.sign(self.privatekey, digest)
427 except UnicodeError as e:
428 # This catches IDNAErrors, which happens when a bad name is passed as a SAN
429 # (https://github.com/ansible-collections/community.crypto/issues/105).
430 # For older cryptography versions, this is handled by idna, which raises
431 # an idna.core.IDNAError. Later versions of cryptography deprecated and stopped
432 # requiring idna, whence we cannot easily handle this error. Fortunately, in
433 # most versions of idna, IDNAError extends UnicodeError. There is only version
434 # 2.3 where it extends Exception instead (see
435 # https://github.com/kjd/idna/commit/ebefacd3134d0f5da4745878620a6a1cba86d130
436 # and then
437 # https://github.com/kjd/idna/commit/ea03c7b5db7d2a99af082e0239da2b68aeea702a).
438 msg = f"Error while creating CSR: {e}\n"
439 if self.using_common_name_for_san:
440 self.module.fail_json(
441 msg=msg
442 + "This is probably caused because the Common Name is used as a SAN. Specifying use_common_name_for_san=false might fix this."
443 )
444 self.module.fail_json(
445 msg=msg
446 + "This is probably caused by an invalid Subject Alternative DNS Name."
447 )
448
449 def get_csr_data(self) -> bytes:
450 """Return bytes for self.csr."""
451 if self.csr is None:
452 raise AssertionError(
453 "Violated contract: csr is not populated"
454 ) # pragma: no cover
455 return self.csr.public_bytes(
456 cryptography.hazmat.primitives.serialization.Encoding.PEM
457 )
458
459 def set_existing(self, *, csr_bytes: bytes | None) -> None:
460 """Set existing CSR bytes. None indicates that the CSR does not exist."""
461 self.existing_csr_bytes = csr_bytes
462 self.diff_after = self.diff_before = self._get_info(
463 data=self.existing_csr_bytes
464 )
465
466 def has_existing(self) -> bool:
467 """Query whether an existing CSR is/has been there."""
468 return self.existing_csr_bytes is not None
469
470 def _ensure_private_key_loaded(self) -> None:
471 """Load the provided private key into self.privatekey."""
472 if self.privatekey is not None:
473 return
474 try:
475 self.privatekey = load_certificate_issuer_privatekey(
476 path=self.privatekey_path,
477 content=self.privatekey_content,
478 passphrase=self.privatekey_passphrase,
479 )
480 except OpenSSLBadPassphraseError as exc:
481 raise CertificateSigningRequestError(exc) from exc
482
483 def _check_csr(self) -> bool:
484 """Check whether provided parameters, assuming self.existing_csr and self.privatekey have been populated."""
485 if self.existing_csr is None:
486 raise AssertionError(
487 "Violated contract: existing_csr is not populated"
488 ) # pragma: no cover
489 if self.privatekey is None:
490 raise AssertionError(
491 "Violated contract: privatekey is not populated"
492 ) # pragma: no cover
493
494 def _check_subject(csr: cryptography.x509.CertificateSigningRequest) -> bool:
495 subject = [
496 (cryptography_name_to_oid(entry[0]), to_text(entry[1]))
497 for entry in self.subject
498 ]
499 current_subject = [(sub.oid, sub.value) for sub in csr.subject]
500 if self.ordered_subject:
501 return subject == current_subject
502 return set(subject) == set(current_subject)
503
504 def _find_extension(
505 extensions: cryptography.x509.Extensions, exttype: type[_ET]
506 ) -> cryptography.x509.Extension[_ET] | None:
507 return next(
508 (ext for ext in extensions if isinstance(ext.value, exttype)), None
509 )
510
511 def _check_subject_alt_name(extensions: cryptography.x509.Extensions) -> bool:
512 current_altnames_ext = _find_extension(
513 extensions, cryptography.x509.SubjectAlternativeName
514 )
515 current_altnames = (
516 [to_text(altname) for altname in current_altnames_ext.value]
517 if current_altnames_ext
518 else []
519 )
520 altnames = (
521 [
522 to_text(cryptography_get_name(altname))
523 for altname in self.subject_alt_name
524 ]
525 if self.subject_alt_name
526 else []
527 )
528 if set(altnames) != set(current_altnames):
529 return False
530 return not (
531 altnames
532 and current_altnames_ext
533 and current_altnames_ext.critical != self.subject_alt_name_critical
534 )
535
536 def _check_key_usage(extensions: cryptography.x509.Extensions) -> bool:
537 current_keyusage_ext = _find_extension(
538 extensions, cryptography.x509.KeyUsage
539 )
540 if not self.key_usage:
541 return current_keyusage_ext is None
542 if current_keyusage_ext is None:
543 return False
544 params = cryptography_parse_key_usage_params(self.key_usage)
545 for param, value in params.items():
546 try:
547 # param in ('encipher_only', 'decipher_only') can result in ValueError()
548 # being raised if key_agreement == False.
549 current_value = getattr(current_keyusage_ext.value, param)
550 except ValueError:
551 # In that case, assume that the value is False.
552 current_value = False
553 if current_value != value:
554 return False
555 return current_keyusage_ext.critical == self.key_usage_critical
556
557 def _check_extended_key_usage(extensions: cryptography.x509.Extensions) -> bool:
558 current_usages_ext = _find_extension(
559 extensions, cryptography.x509.ExtendedKeyUsage
560 )
561 current_usages = (
562 [str(usage) for usage in current_usages_ext.value]
563 if current_usages_ext
564 else []
565 )
566 usages = (
567 [
568 str(cryptography_name_to_oid(usage))
569 for usage in self.extended_key_usage
570 ]
571 if self.extended_key_usage
572 else []
573 )
574 if set(current_usages) != set(usages):
575 return False
576 return not (
577 usages
578 and current_usages_ext
579 and current_usages_ext.critical != self.extended_key_usage_critical
580 )
581
582 def _check_basic_constraints(extensions: cryptography.x509.Extensions) -> bool:
583 bc_ext = _find_extension(extensions, cryptography.x509.BasicConstraints)
584 current_ca = bc_ext.value.ca if bc_ext else False
585 current_path_length = bc_ext.value.path_length if bc_ext else None
586 ca, path_length = cryptography_get_basic_constraints(self.basic_constraints)
587 # Check CA flag
588 if ca != current_ca:
589 return False
590 # Check path length
591 if path_length != current_path_length:
592 return False
593 # Check criticality
594 if self.basic_constraints:
595 return (
596 bc_ext is not None
597 and bc_ext.critical == self.basic_constraints_critical
598 )
599 return bc_ext is None
600
601 def _check_ocsp_must_staple(extensions: cryptography.x509.Extensions) -> bool:
602 tlsfeature_ext = _find_extension(extensions, cryptography.x509.TLSFeature)
603 if self.ocsp_must_staple:
604 if (
605 not tlsfeature_ext
606 or tlsfeature_ext.critical != self.ocsp_must_staple_critical
607 ):
608 return False
609 return (
610 cryptography.x509.TLSFeatureType.status_request
611 in tlsfeature_ext.value
612 )
613 return tlsfeature_ext is None
614
615 def _check_name_constraints(extensions: cryptography.x509.Extensions) -> bool:
616 current_nc_ext = _find_extension(
617 extensions, cryptography.x509.NameConstraints
618 )
619 current_nc_perm = (
620 [
621 to_text(altname)
622 for altname in current_nc_ext.value.permitted_subtrees or []
623 ]
624 if current_nc_ext
625 else []
626 )
627 current_nc_excl = (
628 [
629 to_text(altname)
630 for altname in current_nc_ext.value.excluded_subtrees or []
631 ]
632 if current_nc_ext
633 else []
634 )
635 nc_perm = [
636 to_text(
637 cryptography_get_name(altname, what="name constraints permitted")
638 )
639 for altname in self.name_constraints_permitted
640 ]
641 nc_excl = [
642 to_text(
643 cryptography_get_name(altname, what="name constraints excluded")
644 )
645 for altname in self.name_constraints_excluded
646 ]
647 if set(nc_perm) != set(current_nc_perm) or set(nc_excl) != set(
648 current_nc_excl
649 ):
650 return False
651 return not (
652 (nc_perm or nc_excl)
653 and current_nc_ext
654 and current_nc_ext.critical != self.name_constraints_critical
655 )
656
657 def _check_subject_key_identifier(
658 extensions: cryptography.x509.Extensions,
659 ) -> bool:
660 ext = _find_extension(extensions, cryptography.x509.SubjectKeyIdentifier)
661 if (
662 self.create_subject_key_identifier
663 or self.subject_key_identifier is not None
664 ):
665 if not ext or ext.critical:
666 return False
667 if self.create_subject_key_identifier:
668 assert self.privatekey is not None
669 digest = cryptography.x509.SubjectKeyIdentifier.from_public_key(
670 self.privatekey.public_key()
671 ).digest
672 return ext.value.digest == digest
673 return ext.value.digest == self.subject_key_identifier
674 return ext is None
675
676 def _check_authority_key_identifier(
677 extensions: cryptography.x509.Extensions,
678 ) -> bool:
679 ext = _find_extension(extensions, cryptography.x509.AuthorityKeyIdentifier)
680 if (
681 self.authority_key_identifier is not None
682 or self.authority_cert_issuer is not None
683 or self.authority_cert_serial_number is not None
684 ):
685 if not ext or ext.critical:
686 return False
687 aci = None
688 csr_aci = None
689 if self.authority_cert_issuer is not None:
690 aci = [
691 to_text(cryptography_get_name(n, what="authority cert issuer"))
692 for n in self.authority_cert_issuer
693 ]
694 if ext.value.authority_cert_issuer is not None:
695 csr_aci = [to_text(n) for n in ext.value.authority_cert_issuer]
696 return (
697 ext.value.key_identifier == self.authority_key_identifier
698 and csr_aci == aci
699 and ext.value.authority_cert_serial_number
700 == self.authority_cert_serial_number
701 )
702 return ext is None
703
704 def _check_crl_distribution_points(
705 extensions: cryptography.x509.Extensions,
706 ) -> bool:
707 ext = _find_extension(extensions, cryptography.x509.CRLDistributionPoints)
708 if self.crl_distribution_points is None:
709 return ext is None
710 if not ext:
711 return False
712 return list(ext.value) == self.crl_distribution_points
713
714 def _check_extensions(csr: cryptography.x509.CertificateSigningRequest) -> bool:
715 extensions = csr.extensions
716 return (
717 _check_subject_alt_name(extensions)
718 and _check_key_usage(extensions)
719 and _check_extended_key_usage(extensions)
720 and _check_basic_constraints(extensions)
721 and _check_ocsp_must_staple(extensions)
722 and _check_subject_key_identifier(extensions)
723 and _check_authority_key_identifier(extensions)
724 and _check_name_constraints(extensions)
725 and _check_crl_distribution_points(extensions)
726 )
727
728 def _check_signature(csr: cryptography.x509.CertificateSigningRequest) -> bool:
729 if not csr.is_signature_valid:
730 return False
731 # To check whether public key of CSR belongs to private key,
732 # encode both public keys and compare PEMs.
733 key_a = csr.public_key().public_bytes(
734 cryptography.hazmat.primitives.serialization.Encoding.PEM,
735 cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo,
736 )
737 assert self.privatekey is not None
738 key_b = self.privatekey.public_key().public_bytes(
739 cryptography.hazmat.primitives.serialization.Encoding.PEM,
740 cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo,
741 )
742 return key_a == key_b
743
744 return (
745 _check_subject(self.existing_csr)
746 and _check_extensions(self.existing_csr)
747 and _check_signature(self.existing_csr)
748 )
749
750 def needs_regeneration(self) -> bool:
751 """Check whether a regeneration is necessary."""
752 if self.existing_csr_bytes is None:
753 return True
754 try:
755 self.existing_csr = load_certificate_request(
756 content=self.existing_csr_bytes,
757 )
758 except Exception:
759 return True
760 self._ensure_private_key_loaded()
761 return not self._check_csr()
762
763 def dump(self, *, include_csr: bool) -> dict[str, t.Any]:
764 """Serialize the object into a dictionary."""
765 result: dict[str, t.Any] = {
766 "privatekey": self.privatekey_path,
767 "subject": self.subject,
768 "subjectAltName": self.subject_alt_name,
769 "keyUsage": self.key_usage,
770 "extendedKeyUsage": self.extended_key_usage,
771 "basicConstraints": self.basic_constraints,
772 "ocspMustStaple": self.ocsp_must_staple,
773 "name_constraints_permitted": self.name_constraints_permitted,
774 "name_constraints_excluded": self.name_constraints_excluded,
775 }
776 # Get hold of CSR bytes
777 csr_bytes = self.existing_csr_bytes
778 if self.csr is not None:
779 csr_bytes = self.get_csr_data()
780 self.diff_after = self._get_info(data=csr_bytes)
781 if include_csr:
782 # Store result
783 result["csr"] = csr_bytes.decode("utf-8") if csr_bytes else None
784
785 result["diff"] = {
786 "before": self.diff_before,
787 "after": self.diff_after,
788 }
789 return result
790
791
792 def select_backend(
793 module: AnsibleModule,
794 ) -> CertificateSigningRequestBackend:
795 assert_required_cryptography_version(
796 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
797 )
798 return CertificateSigningRequestBackend(module=module)
799
800
801 def get_csr_argument_spec() -> ArgumentSpec:
802 return ArgumentSpec(
803 argument_spec={
804 "digest": {"type": "str", "default": "sha256"},
805 "privatekey_path": {"type": "path"},
806 "privatekey_content": {"type": "str", "no_log": True},
807 "privatekey_passphrase": {"type": "str", "no_log": True},
808 "version": {"type": "int", "default": 1, "choices": [1]},
809 "subject": {"type": "dict"},
810 "subject_ordered": {"type": "list", "elements": "dict"},
811 "country_name": {"type": "str", "aliases": ["C", "countryName"]},
812 "state_or_province_name": {
813 "type": "str",
814 "aliases": ["ST", "stateOrProvinceName"],
815 },
816 "locality_name": {"type": "str", "aliases": ["L", "localityName"]},
817 "organization_name": {"type": "str", "aliases": ["O", "organizationName"]},
818 "organizational_unit_name": {
819 "type": "str",
820 "aliases": ["OU", "organizationalUnitName"],
821 },
822 "common_name": {"type": "str", "aliases": ["CN", "commonName"]},
823 "email_address": {"type": "str", "aliases": ["E", "emailAddress"]},
824 "subject_alt_name": {
825 "type": "list",
826 "elements": "str",
827 "aliases": ["subjectAltName"],
828 },
829 "subject_alt_name_critical": {
830 "type": "bool",
831 "default": False,
832 "aliases": ["subjectAltName_critical"],
833 },
834 "use_common_name_for_san": {
835 "type": "bool",
836 "default": True,
837 "aliases": ["useCommonNameForSAN"],
838 },
839 "key_usage": {"type": "list", "elements": "str", "aliases": ["keyUsage"]},
840 "key_usage_critical": {
841 "type": "bool",
842 "default": False,
843 "aliases": ["keyUsage_critical"],
844 },
845 "extended_key_usage": {
846 "type": "list",
847 "elements": "str",
848 "aliases": ["extKeyUsage", "extendedKeyUsage"],
849 },
850 "extended_key_usage_critical": {
851 "type": "bool",
852 "default": False,
853 "aliases": ["extKeyUsage_critical", "extendedKeyUsage_critical"],
854 },
855 "basic_constraints": {
856 "type": "list",
857 "elements": "str",
858 "aliases": ["basicConstraints"],
859 },
860 "basic_constraints_critical": {
861 "type": "bool",
862 "default": False,
863 "aliases": ["basicConstraints_critical"],
864 },
865 "ocsp_must_staple": {
866 "type": "bool",
867 "default": False,
868 "aliases": ["ocspMustStaple"],
869 },
870 "ocsp_must_staple_critical": {
871 "type": "bool",
872 "default": False,
873 "aliases": ["ocspMustStaple_critical"],
874 },
875 "name_constraints_permitted": {"type": "list", "elements": "str"},
876 "name_constraints_excluded": {"type": "list", "elements": "str"},
877 "name_constraints_critical": {"type": "bool", "default": False},
878 "create_subject_key_identifier": {"type": "bool", "default": False},
879 "subject_key_identifier": {"type": "str"},
880 "authority_key_identifier": {"type": "str"},
881 "authority_cert_issuer": {"type": "list", "elements": "str"},
882 "authority_cert_serial_number": {"type": "int"},
883 "crl_distribution_points": {
884 "type": "list",
885 "elements": "dict",
886 "options": {
887 "full_name": {"type": "list", "elements": "str"},
888 "relative_name": {"type": "list", "elements": "str"},
889 "crl_issuer": {"type": "list", "elements": "str"},
890 "reasons": {
891 "type": "list",
892 "elements": "str",
893 "choices": [
894 "key_compromise",
895 "ca_compromise",
896 "affiliation_changed",
897 "superseded",
898 "cessation_of_operation",
899 "certificate_hold",
900 "privilege_withdrawn",
901 "aa_compromise",
902 ],
903 },
904 },
905 "mutually_exclusive": [("full_name", "relative_name")],
906 "required_one_of": [("full_name", "relative_name", "crl_issuer")],
907 },
908 "select_crypto_backend": {
909 "type": "str",
910 "default": "auto",
911 "choices": ["auto", "cryptography"],
912 },
913 },
914 required_together=[
915 ["authority_cert_issuer", "authority_cert_serial_number"],
916 ],
917 mutually_exclusive=[
918 ["privatekey_path", "privatekey_content"],
919 ["subject", "subject_ordered"],
920 ],
921 required_one_of=[
922 ["privatekey_path", "privatekey_content"],
923 ],
924 )
925
926
927 __all__ = (
928 "CertificateSigningRequestBackend",
929 "CertificateSigningRequestError",
930 "get_csr_argument_spec",
931 "select_backend",
932 )