Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/x509_crl.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2019, 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 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: x509_crl
10 version_added: '1.0.0'
11 short_description: Generate Certificate Revocation Lists (CRLs)
12 description:
13 - This module allows one to (re)generate or update Certificate Revocation Lists (CRLs).
14 - Certificates on the revocation list can be either specified by serial number and (optionally) their issuer, or as a path
15 to a certificate file in PEM format.
16 author:
17 - Felix Fontein (@felixfontein)
18 extends_documentation_fragment:
19 - ansible.builtin.files
20 - community.crypto._attributes
21 - community.crypto._attributes.files
22 - community.crypto._cryptography_dep.minimum
23 - community.crypto._name_encoding
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: full
29 safe_file_operations:
30 support: full
31 idempotent:
32 support: partial
33 details:
34 - The module is not idempotent if O(force=true).
35 - If relative timestamps and O(ignore_timestamps=false) (default), the module is not idempotent.
36 options:
37 state:
38 description:
39 - Whether the CRL file should exist or not, taking action if the state is different from what is stated.
40 type: str
41 default: present
42 choices: [absent, present]
43
44 crl_mode:
45 description:
46 - Defines how to process entries of existing CRLs.
47 - If set to V(generate), makes sure that the CRL has the exact set of revoked certificates as specified in O(revoked_certificates).
48 - If set to V(update), makes sure that the CRL contains the revoked certificates from O(revoked_certificates), but can
49 also contain other revoked certificates. If the CRL file already exists, all entries from the existing CRL will also
50 be included in the new CRL. When using V(update), you might be interested in setting O(ignore_timestamps) to V(true).
51 - The default value is V(generate).
52 - This parameter was called O(mode) before community.crypto 2.13.0. It has been renamed to avoid a collision with the
53 common O(mode) parameter for setting the CRL file's access mode.
54 type: str
55 default: generate
56 choices: [generate, update]
57 version_added: 2.13.0
58
59 force:
60 description:
61 - Should the CRL be forced to be regenerated.
62 type: bool
63 default: false
64
65 backup:
66 description:
67 - Create a backup file including a timestamp so you can get the original CRL back if you overwrote it with a new one
68 by accident.
69 type: bool
70 default: false
71
72 path:
73 description:
74 - Remote absolute path where the generated CRL file should be created or is already located.
75 type: path
76 required: true
77
78 format:
79 description:
80 - Whether the CRL file should be in PEM or DER format.
81 - If an existing CRL file does match everything but O(format), it will be converted to the correct format instead of
82 regenerated.
83 type: str
84 choices: [pem, der]
85 default: pem
86
87 privatekey_path:
88 description:
89 - Path to the CA's private key to use when signing the CRL.
90 - Either O(privatekey_path) or O(privatekey_content) must be specified if O(state) is V(present), but not both.
91 type: path
92
93 privatekey_content:
94 description:
95 - The content of the CA's private key to use when signing the CRL.
96 - Either O(privatekey_path) or O(privatekey_content) must be specified if O(state) is V(present), but not both.
97 type: str
98
99 privatekey_passphrase:
100 description:
101 - The passphrase for the O(privatekey_path).
102 - This is required if the private key is password protected.
103 type: str
104
105 issuer:
106 description:
107 - Key/value pairs that will be present in the issuer name field of the CRL.
108 - If you need to specify more than one value with the same key, use a list as value.
109 - If the order of the components is important, use O(issuer_ordered).
110 - One of O(issuer) and O(issuer_ordered) is required if O(state) is V(present).
111 - Mutually exclusive with O(issuer_ordered).
112 type: dict
113 issuer_ordered:
114 description:
115 - A list of dictionaries, where every dictionary must contain one key/value pair. This key/value pair will be present
116 in the issuer name field of the CRL.
117 - If you want to specify more than one value with the same key in a row, you can use a list as value.
118 - One of O(issuer) and O(issuer_ordered) is required if O(state) is V(present).
119 - Mutually exclusive with O(issuer).
120 type: list
121 elements: dict
122 version_added: 2.0.0
123
124 last_update:
125 description:
126 - The point in time from which this CRL can be trusted.
127 - Time can be specified either as relative time or as absolute timestamp.
128 - Time will always be interpreted as UTC.
129 - Valid format is C([+-]timespec | ASN.1 TIME) where timespec can be an integer + C([w | d | h | m | s]) (for example
130 V(+32w1d2h)).
131 - Note that if using relative time this module is NOT idempotent, except when O(ignore_timestamps) is set to V(true).
132 type: str
133 default: "+0s"
134
135 next_update:
136 description:
137 - The absolute latest point in time by which this O(issuer) is expected to have issued another CRL. Many clients will
138 treat a CRL as expired once O(next_update) occurs.
139 - Time can be specified either as relative time or as absolute timestamp.
140 - Time will always be interpreted as UTC.
141 - Valid format is C([+-]timespec | ASN.1 TIME) where timespec can be an integer + C([w | d | h | m | s]) (for example
142 V(+32w1d2h)).
143 - Note that if using relative time this module is NOT idempotent, except when O(ignore_timestamps) is set to V(true).
144 - Required if O(state) is V(present).
145 type: str
146
147 digest:
148 description:
149 - Digest algorithm to be used when signing the CRL.
150 type: str
151 default: sha256
152
153 serial_numbers:
154 description:
155 - This option determines which values will be accepted for O(revoked_certificates[].serial_number).
156 - If set to V(integer) (default), serial numbers are assumed to be integers, for example V(66223). (This example value
157 is equivalent to the hex octet string V(01:02:AF)).
158 - If set to V(hex-octets), serial numbers are assumed to be colon-separated hex octet strings, for example V(01:02:AF).
159 (This example value is equivalent to the integer V(66223)).
160 type: str
161 choices:
162 - integer
163 - hex-octets
164 default: integer
165 version_added: 2.18.0
166
167 revoked_certificates:
168 description:
169 - List of certificates to be revoked.
170 - Required if O(state) is V(present).
171 type: list
172 elements: dict
173 suboptions:
174 path:
175 description:
176 - Path to a certificate in PEM format.
177 - The serial number and issuer will be extracted from the certificate.
178 - Mutually exclusive with O(revoked_certificates[].content) and O(revoked_certificates[].serial_number). One of
179 these three options must be specified.
180 type: path
181 content:
182 description:
183 - Content of a certificate in PEM format.
184 - The serial number and issuer will be extracted from the certificate.
185 - Mutually exclusive with O(revoked_certificates[].path) and O(revoked_certificates[].serial_number). One of these
186 three options must be specified.
187 type: str
188 serial_number:
189 description:
190 - Serial number of the certificate.
191 - Mutually exclusive with O(revoked_certificates[].path) and O(revoked_certificates[].content). One of these three
192 options must be specified.
193 - This option accepts integers or hex octet strings, depending on the value of O(serial_numbers).
194 - If O(serial_numbers=integer), integers such as V(66223) must be provided.
195 - If O(serial_numbers=hex-octets), strings such as V(01:02:AF) must be provided.
196 - You can use the filters P(community.crypto.parse_serial#filter) and P(community.crypto.to_serial#filter) to convert
197 these two representations.
198 type: raw
199 revocation_date:
200 description:
201 - The point in time the certificate was revoked.
202 - Time can be specified either as relative time or as absolute timestamp.
203 - Time will always be interpreted as UTC.
204 - Valid format is C([+-]timespec | ASN.1 TIME) where timespec can be an integer + C([w | d | h | m | s]) (for example
205 V(+32w1d2h)).
206 - Note that if using relative time this module is NOT idempotent, except when O(ignore_timestamps) is set to V(true).
207 type: str
208 default: "+0s"
209 issuer:
210 description:
211 - The certificate's issuer.
212 - 'Example: V(DNS:ca.example.org).'
213 type: list
214 elements: str
215 issuer_critical:
216 description:
217 - Whether the certificate issuer extension should be critical.
218 type: bool
219 default: false
220 reason:
221 description:
222 - The value for the revocation reason extension.
223 type: str
224 choices:
225 - unspecified
226 - key_compromise
227 - ca_compromise
228 - affiliation_changed
229 - superseded
230 - cessation_of_operation
231 - certificate_hold
232 - privilege_withdrawn
233 - aa_compromise
234 - remove_from_crl
235 reason_critical:
236 description:
237 - Whether the revocation reason extension should be critical.
238 type: bool
239 default: false
240 invalidity_date:
241 description:
242 - The point in time it was known/suspected that the private key was compromised or that the certificate otherwise
243 became invalid.
244 - Time can be specified either as relative time or as absolute timestamp.
245 - Time will always be interpreted as UTC.
246 - Valid format is C([+-]timespec | ASN.1 TIME) where timespec can be an integer + C([w | d | h | m | s]) (for example
247 V(+32w1d2h)).
248 - Note that if using relative time this module is NOT idempotent. This will NOT change when O(ignore_timestamps)
249 is set to V(true).
250 type: str
251 invalidity_date_critical:
252 description:
253 - Whether the invalidity date extension should be critical.
254 type: bool
255 default: false
256
257 ignore_timestamps:
258 description:
259 - Whether the timestamps O(last_update), O(next_update) and O(revoked_certificates[].revocation_date) should be ignored
260 for idempotency checks. The timestamp O(revoked_certificates[].invalidity_date) will never be ignored.
261 - Use this in combination with relative timestamps for these values to get idempotency.
262 type: bool
263 default: false
264
265 return_content:
266 description:
267 - If set to V(true), will return the (current or generated) CRL's content as RV(crl).
268 type: bool
269 default: false
270
271 notes:
272 - All ASN.1 TIME values should be specified following the YYYYMMDDHHMMSSZ pattern.
273 - Date specified should be UTC. Minutes and seconds are mandatory.
274 seealso:
275 - plugin: community.crypto.parse_serial
276 plugin_type: filter
277 - plugin: community.crypto.to_serial
278 plugin_type: filter
279 """
280
281 EXAMPLES = r"""
282 ---
283 - name: Generate a CRL
284 community.crypto.x509_crl:
285 path: /etc/ssl/my-ca.crl
286 privatekey_path: /etc/ssl/private/my-ca.pem
287 issuer:
288 CN: My CA
289 last_update: "+0s"
290 next_update: "+7d"
291 revoked_certificates:
292 - serial_number: 1234
293 revocation_date: 20190331202428Z
294 issuer:
295 CN: My CA
296 - serial_number: 2345
297 revocation_date: 20191013152910Z
298 reason: affiliation_changed
299 invalidity_date: 20191001000000Z
300 - path: /etc/ssl/crt/revoked-cert.pem
301 revocation_date: 20191010010203Z
302 """
303
304 RETURN = r"""
305 filename:
306 description: Path to the generated CRL.
307 returned: changed or success
308 type: str
309 sample: /path/to/my-ca.crl
310 backup_file:
311 description: Name of backup file created.
312 returned: changed and if O(backup) is V(true)
313 type: str
314 sample: /path/to/my-ca.crl.2019-03-09@11:22~
315 privatekey:
316 description: Path to the private CA key.
317 returned: changed or success
318 type: str
319 sample: /path/to/my-ca.pem
320 format:
321 description:
322 - Whether the CRL is in PEM format (V(pem)) or in DER format (V(der)).
323 returned: success
324 type: str
325 sample: pem
326 choices:
327 - pem
328 - der
329 issuer:
330 description:
331 - The CRL's issuer.
332 - Note that for repeated values, only the last one will be returned.
333 - See O(name_encoding) for how IDNs are handled.
334 returned: success
335 type: dict
336 sample: {"organizationName": "Ansible", "commonName": "ca.example.com"}
337 issuer_ordered:
338 description: The CRL's issuer as an ordered list of tuples.
339 returned: success
340 type: list
341 elements: list
342 sample: [["organizationName", "Ansible"], ["commonName": "ca.example.com"]]
343 last_update:
344 description: The point in time from which this CRL can be trusted as ASN.1 TIME.
345 returned: success
346 type: str
347 sample: 20190413202428Z
348 next_update:
349 description: The point in time from which a new CRL will be issued and the client has to check for it as ASN.1 TIME.
350 returned: success
351 type: str
352 sample: 20190413202428Z
353 digest:
354 description: The signature algorithm used to sign the CRL.
355 returned: success
356 type: str
357 sample: sha256WithRSAEncryption
358 revoked_certificates:
359 description: List of certificates to be revoked.
360 returned: success
361 type: list
362 elements: dict
363 contains:
364 serial_number:
365 description:
366 - Serial number of the certificate.
367 - This return value is an B(integer). If you need the serial numbers as a colon-separated hex string, such as C(11:22:33),
368 you need to convert it to that form with P(community.crypto.to_serial#filter).
369 type: int
370 sample: 1234
371 revocation_date:
372 description: The point in time the certificate was revoked as ASN.1 TIME.
373 type: str
374 sample: 20190413202428Z
375 issuer:
376 description:
377 - The certificate's issuer.
378 - See O(name_encoding) for how IDNs are handled.
379 type: list
380 elements: str
381 sample: ["DNS:ca.example.org"]
382 issuer_critical:
383 description: Whether the certificate issuer extension is critical.
384 type: bool
385 sample: false
386 reason:
387 description:
388 - The value for the revocation reason extension.
389 type: str
390 sample: key_compromise
391 choices:
392 - unspecified
393 - key_compromise
394 - ca_compromise
395 - affiliation_changed
396 - superseded
397 - cessation_of_operation
398 - certificate_hold
399 - privilege_withdrawn
400 - aa_compromise
401 - remove_from_crl
402 reason_critical:
403 description: Whether the revocation reason extension is critical.
404 type: bool
405 sample: false
406 invalidity_date:
407 description: |-
408 The point in time it was known/suspected that the private key was compromised
409 or that the certificate otherwise became invalid as ASN.1 TIME.
410 type: str
411 sample: 20190413202428Z
412 invalidity_date_critical:
413 description: Whether the invalidity date extension is critical.
414 type: bool
415 sample: false
416 crl:
417 description:
418 - The (current or generated) CRL's content.
419 - Will be the CRL itself if O(format) is V(pem), and Base64 of the CRL if O(format) is V(der).
420 returned: if O(state) is V(present) and O(return_content) is V(true)
421 type: str
422 """
423
424
425 import base64
426 import os
427 import typing as t
428
429 from ansible.module_utils.basic import AnsibleModule
430 from ansible.module_utils.common.text.converters import to_text
431 from ansible.module_utils.common.validation import check_type_int, check_type_str
432
433 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
434 OpenSSLBadPassphraseError,
435 OpenSSLObjectError,
436 )
437 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_crl import (
438 CRYPTOGRAPHY_TIMEZONE_INVALIDITY_DATE,
439 REVOCATION_REASON_MAP,
440 TIMESTAMP_FORMAT,
441 cryptography_decode_revoked_certificate,
442 cryptography_dump_revoked,
443 cryptography_get_signature_algorithm_oid_from_crl,
444 get_last_update,
445 get_next_update,
446 set_last_update,
447 set_next_update,
448 set_revocation_date,
449 )
450 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
451 CRYPTOGRAPHY_TIMEZONE,
452 cryptography_decode_name,
453 cryptography_get_name,
454 cryptography_key_needs_digest_for_signing,
455 cryptography_name_to_oid,
456 cryptography_oid_to_name,
457 )
458 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.crl_info import (
459 get_crl_info,
460 )
461 from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import (
462 identify_pem_format,
463 )
464 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
465 OpenSSLObject,
466 load_certificate,
467 load_certificate_issuer_privatekey,
468 parse_name_field,
469 parse_ordered_name_field,
470 select_message_digest,
471 )
472 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
473 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
474 assert_required_cryptography_version,
475 )
476 from ansible_collections.community.crypto.plugins.module_utils._io import write_file
477 from ansible_collections.community.crypto.plugins.module_utils._serial import (
478 parse_serial,
479 )
480 from ansible_collections.community.crypto.plugins.module_utils._time import (
481 get_relative_time_option,
482 )
483
484 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
485
486 try:
487 from cryptography import x509
488 from cryptography.hazmat.primitives.serialization import Encoding
489 from cryptography.x509 import (
490 CertificateRevocationListBuilder,
491 Name,
492 NameAttribute,
493 RevokedCertificateBuilder,
494 )
495 except ImportError:
496 pass
497
498 if t.TYPE_CHECKING:
499 import datetime # pragma: no cover
500
501
502 class CRLError(OpenSSLObjectError):
503 pass
504
505
506 class CRL(OpenSSLObject):
507 def __init__(self, module: AnsibleModule) -> None:
508 super().__init__(
509 path=module.params["path"],
510 state=module.params["state"],
511 force=module.params["force"],
512 check_mode=module.check_mode,
513 )
514
515 self.format: t.Literal["pem", "der"] = module.params["format"]
516
517 self.update: bool = module.params["crl_mode"] == "update"
518 self.ignore_timestamps: bool = module.params["ignore_timestamps"]
519 self.return_content: bool = module.params["return_content"]
520 self.name_encoding: t.Literal["ignore", "idna", "unicode"] = module.params[
521 "name_encoding"
522 ]
523 self.serial_numbers_format: t.Literal["integer", "hex-octets"] = module.params[
524 "serial_numbers"
525 ]
526 self.crl_content: bytes | None = None
527
528 self.privatekey_path: str | None = module.params["privatekey_path"]
529 privatekey_content: str | None = module.params["privatekey_content"]
530 if privatekey_content is not None:
531 self.privatekey_content: bytes | None = privatekey_content.encode("utf-8")
532 else:
533 self.privatekey_content = None
534 self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"]
535
536 try:
537 issuer_ordered: list[dict[str, t.Any]] | None = module.params[
538 "issuer_ordered"
539 ]
540 issuer: dict[str, list[str | bytes] | bytes | str] | None = module.params[
541 "issuer"
542 ]
543 if issuer_ordered:
544 self.issuer_ordered = True
545 self.issuer = parse_ordered_name_field(
546 issuer_ordered, name_field_name="issuer_ordered"
547 )
548 else:
549 self.issuer_ordered = False
550 self.issuer = (
551 parse_name_field(issuer, name_field_name="issuer")
552 if issuer is not None
553 else []
554 )
555 except (TypeError, ValueError) as exc:
556 module.fail_json(msg=str(exc))
557
558 self.last_update: datetime.datetime = get_relative_time_option(
559 module.params["last_update"],
560 input_name="last_update",
561 with_timezone=CRYPTOGRAPHY_TIMEZONE,
562 )
563 self.next_update: datetime.datetime | None = get_relative_time_option(
564 module.params["next_update"],
565 input_name="next_update",
566 with_timezone=CRYPTOGRAPHY_TIMEZONE,
567 )
568
569 digest = select_message_digest(module.params["digest"])
570 if digest is None:
571 raise CRLError(f'The digest "{module.params["digest"]}" is not supported')
572 self.digest = digest
573
574 self.module = module
575
576 self.revoked_certificates = []
577 revoked_certificates: list[dict[str, t.Any]] = module.params[
578 "revoked_certificates"
579 ]
580 for i, rc in enumerate(revoked_certificates):
581 result: dict[str, t.Any] = {
582 "serial_number": None,
583 "revocation_date": None,
584 "issuer": None,
585 "issuer_critical": False,
586 "reason": None,
587 "reason_critical": False,
588 "invalidity_date": None,
589 "invalidity_date_critical": False,
590 }
591 path_prefix = f"revoked_certificates[{i}]."
592 path: str | None = rc["path"]
593 content_str: str | None = rc["content"]
594 if path is not None or content_str is not None:
595 # Load certificate from file or content
596 try:
597 content: bytes | None = None
598 if content_str is not None:
599 content = content_str.encode("utf-8")
600 rc["content"] = content
601 cert = load_certificate(path=path, content=content)
602 result["serial_number"] = cert.serial_number
603 except OpenSSLObjectError as e:
604 if content_str is not None:
605 module.fail_json(
606 msg=f"Cannot parse certificate from {path_prefix}content: {e}"
607 )
608 else:
609 module.fail_json(
610 msg=f'Cannot read certificate "{path}" from {path_prefix}path: {e}'
611 )
612 else:
613 # Specify serial_number (and potentially issuer) directly
614 result["serial_number"] = self._parse_serial_number(
615 rc["serial_number"], i
616 )
617 # All other options
618 if rc["issuer"]:
619 result["issuer"] = [
620 cryptography_get_name(issuer, what="issuer")
621 for issuer in rc["issuer"]
622 ]
623 result["issuer_critical"] = rc["issuer_critical"]
624 result["revocation_date"] = get_relative_time_option(
625 rc["revocation_date"],
626 input_name=path_prefix + "revocation_date",
627 with_timezone=CRYPTOGRAPHY_TIMEZONE,
628 )
629 if rc["reason"]:
630 result["reason"] = REVOCATION_REASON_MAP[rc["reason"]]
631 result["reason_critical"] = rc["reason_critical"]
632 if rc["invalidity_date"]:
633 result["invalidity_date"] = get_relative_time_option(
634 rc["invalidity_date"],
635 input_name=path_prefix + "invalidity_date",
636 with_timezone=CRYPTOGRAPHY_TIMEZONE_INVALIDITY_DATE,
637 )
638 result["invalidity_date_critical"] = rc["invalidity_date_critical"]
639 self.revoked_certificates.append(result)
640
641 self.backup: bool = module.params["backup"]
642 self.backup_file: str | None = None
643
644 try:
645 self.privatekey = load_certificate_issuer_privatekey(
646 path=self.privatekey_path,
647 content=self.privatekey_content,
648 passphrase=self.privatekey_passphrase,
649 )
650 except OpenSSLBadPassphraseError as exc:
651 raise CRLError(exc) from exc
652
653 self.crl = None
654 try:
655 with open(self.path, "rb") as f:
656 data = f.read()
657 self.actual_format = "pem" if identify_pem_format(data) else "der"
658 if self.actual_format == "pem":
659 self.crl = x509.load_pem_x509_crl(data)
660 if self.return_content:
661 self.crl_content = data
662 else:
663 self.crl = x509.load_der_x509_crl(data)
664 if self.return_content:
665 self.crl_content = base64.b64encode(data)
666 except Exception:
667 self.crl_content = None
668 self.actual_format = self.format
669 data = None
670
671 self.diff_after = self.diff_before = self._get_info(data)
672
673 def _parse_serial_number(self, value: t.Any, index: int) -> int:
674 if self.serial_numbers_format == "integer":
675 try:
676 return check_type_int(value)
677 except TypeError as exc:
678 self.module.fail_json(
679 msg=f"Error while parsing revoked_certificates[{index + 1}].serial_number as an integer: {exc}"
680 )
681 if self.serial_numbers_format == "hex-octets":
682 try:
683 return parse_serial(check_type_str(value))
684 except (TypeError, ValueError) as exc:
685 self.module.fail_json(
686 msg=f"Error while parsing revoked_certificates[{index + 1}].serial_number as an colon-separated hex octet string: {exc}"
687 )
688 raise RuntimeError(
689 f"Unexpected value {self.serial_numbers_format} of serial_numbers"
690 )
691
692 def _get_info(self, data: bytes | None) -> dict[str, t.Any]:
693 if data is None:
694 return {}
695 try:
696 result = get_crl_info(module=self.module, content=data)
697 result["can_parse_crl"] = True
698 return result
699 except Exception:
700 return {"can_parse_crl": False}
701
702 def remove(self, module: AnsibleModule) -> None:
703 if self.backup:
704 self.backup_file = self.module.backup_local(self.path)
705 super().remove(self.module)
706
707 def _compress_entry(self, entry: dict[str, t.Any]) -> (
708 tuple[
709 int | None,
710 tuple[str, ...] | None,
711 bool,
712 int | None,
713 bool,
714 datetime.datetime | None,
715 bool,
716 ]
717 | tuple[
718 int | None,
719 datetime.datetime | None,
720 tuple[str, ...] | None,
721 bool,
722 int | None,
723 bool,
724 datetime.datetime | None,
725 bool,
726 ]
727 ):
728 issuer = None
729 if entry["issuer"] is not None:
730 # Normalize to IDNA. If this is used-provided, it was already converted to
731 # IDNA (by cryptography_get_name) and thus the `idna` library is present.
732 # If this is coming from cryptography and is not already in IDNA (i.e. ascii),
733 # cryptography < 2.1 must be in use, which depends on `idna`. So this should
734 # not require `idna` except if it was already used by code earlier during
735 # this invocation.
736 issuer = tuple(
737 cryptography_decode_name(issuer, idn_rewrite="idna")
738 for issuer in entry["issuer"]
739 )
740 if self.ignore_timestamps:
741 # Throw out revocation_date
742 return (
743 entry["serial_number"],
744 issuer,
745 entry["issuer_critical"],
746 entry["reason"],
747 entry["reason_critical"],
748 entry["invalidity_date"],
749 entry["invalidity_date_critical"],
750 )
751 return (
752 entry["serial_number"],
753 entry["revocation_date"],
754 issuer,
755 entry["issuer_critical"],
756 entry["reason"],
757 entry["reason_critical"],
758 entry["invalidity_date"],
759 entry["invalidity_date_critical"],
760 )
761
762 def check(
763 self,
764 module: AnsibleModule,
765 *,
766 perms_required: bool = True,
767 ignore_conversion: bool = True,
768 ) -> bool:
769 """Ensure the resource is in its desired state."""
770
771 state_and_perms = super().check(
772 module=self.module, perms_required=perms_required
773 )
774
775 if not state_and_perms:
776 return False
777
778 if self.crl is None:
779 return False
780
781 if self.last_update != get_last_update(self.crl) and not self.ignore_timestamps:
782 return False
783 if self.next_update != get_next_update(self.crl) and not self.ignore_timestamps:
784 return False
785 if cryptography_key_needs_digest_for_signing(self.privatekey):
786 if (
787 self.crl.signature_hash_algorithm is None
788 or self.digest.name != self.crl.signature_hash_algorithm.name
789 ):
790 return False
791 else:
792 if self.crl.signature_hash_algorithm is not None:
793 return False
794
795 want_issuer = [
796 (cryptography_name_to_oid(entry[0]), entry[1]) for entry in self.issuer
797 ]
798 is_issuer = [(sub.oid, sub.value) for sub in self.crl.issuer]
799 if not self.issuer_ordered:
800 want_issuer_set = set(want_issuer)
801 is_issuer_set = set(is_issuer)
802 if want_issuer_set != is_issuer_set:
803 return False
804 else:
805 if want_issuer != is_issuer:
806 return False
807
808 old_entries = [
809 self._compress_entry(cryptography_decode_revoked_certificate(cert))
810 for cert in self.crl
811 ]
812 new_entries = [self._compress_entry(cert) for cert in self.revoked_certificates]
813 if self.update:
814 # We do not simply use a set so that duplicate entries are treated correctly
815 for entry in new_entries:
816 try:
817 old_entries.remove(entry)
818 except ValueError:
819 return False
820 else:
821 if old_entries != new_entries:
822 return False
823
824 return not (self.format != self.actual_format and not ignore_conversion)
825
826 def _generate_crl(self) -> bytes:
827 crl = CertificateRevocationListBuilder()
828
829 try:
830 crl = crl.issuer_name(
831 Name(
832 [
833 NameAttribute(
834 cryptography_name_to_oid(entry[0]), to_text(entry[1])
835 )
836 for entry in self.issuer
837 ]
838 )
839 )
840 except ValueError as e:
841 raise CRLError(e) from e
842
843 crl = set_last_update(crl, value=self.last_update)
844 if self.next_update is not None:
845 crl = set_next_update(crl, value=self.next_update)
846
847 if self.update and self.crl:
848 new_entries = {
849 self._compress_entry(entry) for entry in self.revoked_certificates
850 }
851 for entry in self.crl:
852 decoded_entry = self._compress_entry(
853 cryptography_decode_revoked_certificate(entry)
854 )
855 if decoded_entry not in new_entries:
856 crl = crl.add_revoked_certificate(entry)
857 for revoked_entry in self.revoked_certificates:
858 revoked_cert = RevokedCertificateBuilder()
859 revoked_cert = revoked_cert.serial_number(revoked_entry["serial_number"])
860 revoked_cert = set_revocation_date(
861 revoked_cert, value=revoked_entry["revocation_date"]
862 )
863 if revoked_entry["issuer"] is not None:
864 revoked_cert = revoked_cert.add_extension(
865 x509.CertificateIssuer(revoked_entry["issuer"]),
866 revoked_entry["issuer_critical"],
867 )
868 if revoked_entry["reason"] is not None:
869 revoked_cert = revoked_cert.add_extension(
870 x509.CRLReason(revoked_entry["reason"]),
871 revoked_entry["reason_critical"],
872 )
873 if revoked_entry["invalidity_date"] is not None:
874 revoked_cert = revoked_cert.add_extension(
875 x509.InvalidityDate(revoked_entry["invalidity_date"]),
876 revoked_entry["invalidity_date_critical"],
877 )
878 crl = crl.add_revoked_certificate(revoked_cert.build())
879
880 digest = None
881 if cryptography_key_needs_digest_for_signing(self.privatekey):
882 digest = self.digest
883 self.crl = crl.sign(self.privatekey, digest)
884 if self.format == "pem":
885 return self.crl.public_bytes(Encoding.PEM)
886 return self.crl.public_bytes(Encoding.DER)
887
888 def generate(self, module: AnsibleModule) -> None:
889 result = None
890 if (
891 not self.check(self.module, perms_required=False, ignore_conversion=True)
892 or self.force
893 ):
894 result = self._generate_crl()
895 elif (
896 not self.check(self.module, perms_required=False, ignore_conversion=False)
897 and self.crl
898 ):
899 if self.format == "pem":
900 result = self.crl.public_bytes(Encoding.PEM)
901 else:
902 result = self.crl.public_bytes(Encoding.DER)
903
904 if result is not None:
905 self.diff_after = self._get_info(result)
906 if self.return_content:
907 if self.format == "pem":
908 self.crl_content = result
909 else:
910 self.crl_content = base64.b64encode(result)
911 if self.backup:
912 self.backup_file = self.module.backup_local(self.path)
913 write_file(module=self.module, content=result)
914 self.changed = True
915
916 file_args = self.module.load_file_common_arguments(self.module.params)
917 if self.module.check_file_absent_if_check_mode(
918 file_args["path"]
919 ) or self.module.set_fs_attributes_if_different(file_args, False):
920 self.changed = True
921
922 def dump(self, check_mode: bool = False) -> dict[str, t.Any]:
923 result = {
924 "changed": self.changed,
925 "filename": self.path,
926 "privatekey": self.privatekey_path,
927 "format": self.format,
928 "last_update": None,
929 "next_update": None,
930 "digest": None,
931 "issuer_ordered": None,
932 "issuer": None,
933 "revoked_certificates": [],
934 }
935 if self.backup_file:
936 result["backup_file"] = self.backup_file
937
938 if check_mode:
939 result["last_update"] = self.last_update.strftime(TIMESTAMP_FORMAT)
940 result["next_update"] = (
941 self.next_update.strftime(TIMESTAMP_FORMAT)
942 if self.next_update is not None
943 else None
944 )
945 # result['digest'] = cryptography_oid_to_name(self.crl.signature_algorithm_oid)
946 result["digest"] = self.module.params["digest"]
947 result["issuer_ordered"] = self.issuer
948 issuer: dict[str, str | bytes] = {}
949 result["issuer"] = issuer
950 for k, v in self.issuer:
951 issuer[k] = v
952 revoked_certificates: list[dict[str, t.Any]] = []
953 result["revoked_certificates"] = revoked_certificates
954 for entry in self.revoked_certificates:
955 revoked_certificates.append(
956 cryptography_dump_revoked(entry, idn_rewrite=self.name_encoding)
957 )
958 elif self.crl:
959 result["last_update"] = get_last_update(self.crl).strftime(TIMESTAMP_FORMAT)
960 next_update = get_next_update(self.crl)
961 result["next_update"] = (
962 next_update.strftime(TIMESTAMP_FORMAT)
963 if next_update is not None
964 else None
965 )
966 result["digest"] = cryptography_oid_to_name(
967 cryptography_get_signature_algorithm_oid_from_crl(self.crl)
968 )
969 issuer_list: list[list[str]] = []
970 for attribute in self.crl.issuer:
971 issuer_list.append(
972 [
973 cryptography_oid_to_name(attribute.oid),
974 to_text(attribute.value),
975 ]
976 )
977 result["issuer_ordered"] = issuer_list
978 issuer = {}
979 result["issuer"] = issuer
980 for k, v in issuer_list:
981 issuer[k] = v
982 revoked_certificates = []
983 result["revoked_certificates"] = revoked_certificates
984 for cert in self.crl:
985 entry = cryptography_decode_revoked_certificate(cert)
986 revoked_certificates.append(
987 cryptography_dump_revoked(entry, idn_rewrite=self.name_encoding)
988 )
989
990 if self.return_content:
991 result["crl"] = self.crl_content
992
993 result["diff"] = {
994 "before": self.diff_before,
995 "after": self.diff_after,
996 }
997 return result
998
999
1000 def main() -> t.NoReturn:
1001 module = AnsibleModule(
1002 argument_spec={
1003 "state": {
1004 "type": "str",
1005 "default": "present",
1006 "choices": ["present", "absent"],
1007 },
1008 "crl_mode": {
1009 "type": "str",
1010 "default": "generate",
1011 "choices": ["generate", "update"],
1012 },
1013 "force": {"type": "bool", "default": False},
1014 "backup": {"type": "bool", "default": False},
1015 "path": {"type": "path", "required": True},
1016 "format": {"type": "str", "default": "pem", "choices": ["pem", "der"]},
1017 "privatekey_path": {"type": "path"},
1018 "privatekey_content": {"type": "str", "no_log": True},
1019 "privatekey_passphrase": {"type": "str", "no_log": True},
1020 "issuer": {"type": "dict"},
1021 "issuer_ordered": {"type": "list", "elements": "dict"},
1022 "last_update": {"type": "str", "default": "+0s"},
1023 "next_update": {"type": "str"},
1024 "digest": {"type": "str", "default": "sha256"},
1025 "ignore_timestamps": {"type": "bool", "default": False},
1026 "return_content": {"type": "bool", "default": False},
1027 "revoked_certificates": {
1028 "type": "list",
1029 "elements": "dict",
1030 "options": {
1031 "path": {"type": "path"},
1032 "content": {"type": "str"},
1033 "serial_number": {"type": "raw"},
1034 "revocation_date": {"type": "str", "default": "+0s"},
1035 "issuer": {"type": "list", "elements": "str"},
1036 "issuer_critical": {"type": "bool", "default": False},
1037 "reason": {
1038 "type": "str",
1039 "choices": [
1040 "unspecified",
1041 "key_compromise",
1042 "ca_compromise",
1043 "affiliation_changed",
1044 "superseded",
1045 "cessation_of_operation",
1046 "certificate_hold",
1047 "privilege_withdrawn",
1048 "aa_compromise",
1049 "remove_from_crl",
1050 ],
1051 },
1052 "reason_critical": {"type": "bool", "default": False},
1053 "invalidity_date": {"type": "str"},
1054 "invalidity_date_critical": {"type": "bool", "default": False},
1055 },
1056 "required_one_of": [["path", "content", "serial_number"]],
1057 "mutually_exclusive": [["path", "content", "serial_number"]],
1058 },
1059 "name_encoding": {
1060 "type": "str",
1061 "default": "ignore",
1062 "choices": ["ignore", "idna", "unicode"],
1063 },
1064 "serial_numbers": {
1065 "type": "str",
1066 "default": "integer",
1067 "choices": ["integer", "hex-octets"],
1068 },
1069 },
1070 required_if=[
1071 ("state", "present", ["privatekey_path", "privatekey_content"], True),
1072 ("state", "present", ["issuer", "issuer_ordered"], True),
1073 ("state", "present", ["next_update", "revoked_certificates"], False),
1074 ],
1075 mutually_exclusive=(
1076 ["privatekey_path", "privatekey_content"],
1077 ["issuer", "issuer_ordered"],
1078 ),
1079 supports_check_mode=True,
1080 add_file_common_args=True,
1081 )
1082
1083 assert_required_cryptography_version(
1084 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
1085 )
1086
1087 try:
1088 crl = CRL(module)
1089
1090 if module.params["state"] == "present":
1091 if module.check_mode:
1092 result = crl.dump(check_mode=True)
1093 result["changed"] = (
1094 module.params["force"]
1095 or not crl.check(module)
1096 or not crl.check(module, ignore_conversion=False)
1097 )
1098 module.exit_json(**result)
1099
1100 crl.generate(module)
1101 else:
1102 if module.check_mode:
1103 result = crl.dump(check_mode=True)
1104 result["changed"] = os.path.exists(module.params["path"])
1105 module.exit_json(**result)
1106
1107 crl.remove(module)
1108
1109 result = crl.dump()
1110 module.exit_json(**result)
1111 except OpenSSLObjectError as exc:
1112 module.fail_json(msg=str(exc))
1113
1114
1115 if __name__ == "__main__":
1116 main()