Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Guillaume Delpierre <[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: openssl_pkcs12
10 author:
11 - Guillaume Delpierre (@gdelpierre)
12 short_description: Generate OpenSSL PKCS#12 archive
13 description:
14 - This module allows one to (re-)generate PKCS#12.
15 - The module uses the cryptography Python library.
16 extends_documentation_fragment:
17 - ansible.builtin.files
18 - community.crypto._attributes
19 - community.crypto._attributes.files
20 - community.crypto._cryptography_dep.minimum
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 safe_file_operations:
27 support: full
28 idempotent:
29 support: partial
30 details:
31 - The module is not idempotent if O(force=true).
32 options:
33 action:
34 description:
35 - V(export) or V(parse) a PKCS#12.
36 type: str
37 default: export
38 choices: [export, parse]
39 other_certificates:
40 description:
41 - List of other certificates to include. Pre Ansible 2.8 this parameter was called O(ca_certificates).
42 - Assumes there is one PEM-encoded certificate per file. If a file contains multiple PEM certificates, set O(other_certificates_parse_all)
43 to V(true).
44 - Mutually exclusive with O(other_certificates_content).
45 type: list
46 elements: path
47 aliases: [ca_certificates]
48 other_certificates_content:
49 description:
50 - List of other certificates to include.
51 - Assumes there is one PEM-encoded certificate per item. If an item contains multiple PEM certificates, set O(other_certificates_parse_all)
52 - Mutually exclusive with O(other_certificates).
53 type: list
54 elements: str
55 version_added: "2.26.0"
56 other_certificates_parse_all:
57 description:
58 - If set to V(true), assumes that the files mentioned in O(other_certificates)/O(other_certificates_content) can contain more than one
59 certificate per file/item (or even none per file/item).
60 type: bool
61 default: false
62 version_added: 1.4.0
63 certificate_path:
64 description:
65 - The path to read certificates and private keys from.
66 - Must be in PEM format.
67 - Mutually exclusive with O(certificate_content).
68 type: path
69 certificate_content:
70 description:
71 - Content of the certificate file in PEM format.
72 - Mutually exclusive with O(certificate_path).
73 type: str
74 version_added: "2.26.0"
75 force:
76 description:
77 - Should the file be regenerated even if it already exists.
78 type: bool
79 default: false
80 friendly_name:
81 description:
82 - Specifies the friendly name for the certificate and private key.
83 type: str
84 aliases: [name]
85 iter_size:
86 description:
87 - Number of times to repeat the encryption step.
88 - This is B(not considered during idempotency checks).
89 - This is only used when O(encryption_level=compatibility2022).
90 - When using it, the default is V(50000).
91 type: int
92 maciter_size:
93 description:
94 - Number of times to repeat the MAC step.
95 - This is B(not considered during idempotency checks).
96 - This value is B(not used). It is deprecated and will be removed from community.crypto 4.0.0.
97 type: int
98 encryption_level:
99 description:
100 - Determines the encryption level used.
101 - V(auto) uses the default of the selected backend. For C(cryptography), this is what the cryptography library's specific
102 version considers the best available encryption.
103 - V(compatibility2022) uses compatibility settings for older software in 2022. This is only supported by the C(cryptography)
104 backend if cryptography >= 38.0.0 is available.
105 - B(Note) that this option is B(not used for idempotency).
106 choices:
107 - auto
108 - compatibility2022
109 default: auto
110 type: str
111 version_added: 2.8.0
112 passphrase:
113 description:
114 - The PKCS#12 password.
115 - B(Note:) PKCS12 encryption is typically not secure and should not be used as a security mechanism. If you need to
116 store or send a PKCS12 file safely, you should additionally encrypt it with something else. (L(Source,
117 https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates)).
118 type: str
119 path:
120 description:
121 - Filename to write the PKCS#12 file to.
122 type: path
123 required: true
124 privatekey_passphrase:
125 description:
126 - Passphrase source to decrypt any input private keys with.
127 type: str
128 privatekey_path:
129 description:
130 - File to read private key from.
131 - Mutually exclusive with O(privatekey_content).
132 type: path
133 privatekey_content:
134 description:
135 - Content of the private key file.
136 - Mutually exclusive with O(privatekey_path).
137 type: str
138 version_added: "2.3.0"
139 state:
140 description:
141 - Whether the file should exist or not. All parameters except O(path) are ignored when state is V(absent).
142 choices: [absent, present]
143 default: present
144 type: str
145 src:
146 description:
147 - PKCS#12 file path to parse.
148 type: path
149 backup:
150 description:
151 - Create a backup file including a timestamp so you can get the original output file back if you overwrote it with a
152 new one by accident.
153 type: bool
154 default: false
155 return_content:
156 description:
157 - If set to V(true), will return the (current or generated) PKCS#12's content as RV(pkcs12).
158 type: bool
159 default: false
160 version_added: "1.0.0"
161 select_crypto_backend:
162 description:
163 - Determines which crypto backend to use.
164 - The default choice is V(auto), which tries to use C(cryptography) if available.
165 - If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library.
166 - The value V(pyopenssl) has been removed for community.crypto 3.0.0.
167 - Note that with community.crypto 3.0.0, all remaining values behave the same.
168 This option will be deprecated in a later version.
169 We recommend to not set it explicitly.
170 type: str
171 default: auto
172 choices: [auto, cryptography]
173 version_added: 1.7.0
174 seealso:
175 - module: community.crypto.x509_certificate
176 - module: community.crypto.openssl_csr
177 - module: community.crypto.openssl_dhparam
178 - module: community.crypto.openssl_privatekey
179 - module: community.crypto.openssl_publickey
180 """
181
182 EXAMPLES = r"""
183 ---
184 - name: Generate PKCS#12 file
185 community.crypto.openssl_pkcs12:
186 action: export
187 path: /opt/certs/ansible.p12
188 friendly_name: raclette
189 privatekey_path: /opt/certs/keys/key.pem
190 certificate_path: /opt/certs/cert.pem
191 other_certificates: /opt/certs/ca.pem
192 # Note that if /opt/certs/ca.pem contains multiple certificates,
193 # only the first one will be used. See the other_certificates_parse_all
194 # option for changing this behavior.
195 state: present
196
197 - name: Generate PKCS#12 file
198 community.crypto.openssl_pkcs12:
199 action: export
200 path: /opt/certs/ansible.p12
201 friendly_name: raclette
202 privatekey_content: '{{ private_key_contents }}'
203 certificate_path: /opt/certs/cert.pem
204 other_certificates_parse_all: true
205 other_certificates:
206 - /opt/certs/ca_bundle.pem
207 # Since we set other_certificates_parse_all to true, all
208 # certificates in the CA bundle are included and not just
209 # the first one.
210 - /opt/certs/intermediate.pem
211 # In case this file has multiple certificates in it,
212 # all will be included as well.
213 state: present
214
215 - name: Change PKCS#12 file permission
216 community.crypto.openssl_pkcs12:
217 action: export
218 path: /opt/certs/ansible.p12
219 friendly_name: raclette
220 privatekey_path: /opt/certs/keys/key.pem
221 certificate_path: /opt/certs/cert.pem
222 other_certificates: /opt/certs/ca.pem
223 state: present
224 mode: '0600'
225
226 - name: Regen PKCS#12 file
227 community.crypto.openssl_pkcs12:
228 action: export
229 src: /opt/certs/ansible.p12
230 path: /opt/certs/ansible.p12
231 friendly_name: raclette
232 privatekey_path: /opt/certs/keys/key.pem
233 certificate_path: /opt/certs/cert.pem
234 other_certificates: /opt/certs/ca.pem
235 state: present
236 mode: '0600'
237 force: true
238
239 - name: Dump/Parse PKCS#12 file
240 community.crypto.openssl_pkcs12:
241 action: parse
242 src: /opt/certs/ansible.p12
243 path: /opt/certs/ansible.pem
244 state: present
245
246 - name: Remove PKCS#12 file
247 community.crypto.openssl_pkcs12:
248 path: /opt/certs/ansible.p12
249 state: absent
250 """
251
252 RETURN = r"""
253 filename:
254 description: Path to the generate PKCS#12 file.
255 returned: changed or success
256 type: str
257 sample: /opt/certs/ansible.p12
258 privatekey:
259 description: Path to the TLS/SSL private key the public key was generated from.
260 returned: changed or success
261 type: str
262 sample: /etc/ssl/private/ansible.com.pem
263 backup_file:
264 description: Name of backup file created.
265 returned: changed and if O(backup) is V(true)
266 type: str
267 sample: /path/to/ansible.com.pem.2019-03-09@11:22~
268 pkcs12:
269 description: The (current or generated) PKCS#12's content Base64 encoded.
270 returned: if O(state) is V(present) and O(return_content) is V(true)
271 type: str
272 version_added: "1.0.0"
273 """
274
275 import base64
276 import itertools
277 import os
278 import stat
279 import traceback
280 import typing as t
281
282 from ansible.module_utils.basic import AnsibleModule
283 from ansible.module_utils.common.text.converters import to_bytes, to_text
284
285 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
286 OpenSSLBadPassphraseError,
287 OpenSSLObjectError,
288 )
289 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
290 parse_pkcs12,
291 )
292 from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import (
293 split_pem_list,
294 )
295 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
296 OpenSSLObject,
297 load_certificate,
298 load_certificate_issuer_privatekey,
299 )
300 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
301 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
302 assert_required_cryptography_version,
303 )
304 from ansible_collections.community.crypto.plugins.module_utils._io import (
305 load_file_if_exists,
306 write_file,
307 )
308
309 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
310
311 try:
312 from cryptography.hazmat.primitives import serialization
313 from cryptography.hazmat.primitives.serialization.pkcs12 import (
314 serialize_key_and_certificates,
315 )
316 except ImportError:
317 pass
318
319 CRYPTOGRAPHY_COMPATIBILITY2022_ERR: str | None
320 try:
321 import cryptography.x509
322 from cryptography.hazmat.primitives import hashes
323 from cryptography.hazmat.primitives.serialization.pkcs12 import PBES
324
325 # Try to build encryption builder for compatibility2022
326 serialization.PrivateFormat.PKCS12.encryption_builder().key_cert_algorithm(
327 PBES.PBESv1SHA1And3KeyTripleDESCBC
328 ).hmac_hash(hashes.SHA1())
329 except Exception:
330 # pylint: disable-next=invalid-name
331 CRYPTOGRAPHY_COMPATIBILITY2022_ERR = traceback.format_exc()
332 CRYPTOGRAPHY_HAS_COMPATIBILITY2022 = False
333 else:
334 CRYPTOGRAPHY_COMPATIBILITY2022_ERR = None # pylint: disable=invalid-name
335 CRYPTOGRAPHY_HAS_COMPATIBILITY2022 = True
336
337 if t.TYPE_CHECKING:
338 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover
339 CertificateIssuerPrivateKeyTypes,
340 )
341
342 PKCS12 = tuple[
343 t.Union[CertificateIssuerPrivateKeyTypes, None], # noqa: UP007
344 t.Union[cryptography.x509.Certificate, None], # noqa: UP007
345 list[cryptography.x509.Certificate],
346 t.Union[bytes, None], # noqa: UP007
347 ] # pragma: no cover
348
349
350 def load_certificate_set(
351 filename: str | os.PathLike,
352 ) -> list[cryptography.x509.Certificate]:
353 """
354 Load list of concatenated PEM files, and return a list of parsed certificates.
355 """
356 with open(filename, "rb") as f:
357 data = f.read().decode("utf-8")
358 return [
359 load_certificate(content=cert.encode("utf-8")) for cert in split_pem_list(data)
360 ]
361
362
363 class PkcsError(OpenSSLObjectError):
364 pass
365
366
367 class Pkcs(OpenSSLObject):
368 path: str
369
370 def __init__(self, module: AnsibleModule, iter_size_default: int = 50000) -> None:
371 super().__init__(
372 path=module.params["path"],
373 state=module.params["state"],
374 force=module.params["force"],
375 check_mode=module.check_mode,
376 )
377 self.action: t.Literal["export", "parse"] = module.params["action"]
378 self.other_certificates: list[cryptography.x509.Certificate] = []
379 self.other_certificates_str: list[str] | None = module.params[
380 "other_certificates"
381 ]
382 self.other_certificates_parse_all: bool = module.params[
383 "other_certificates_parse_all"
384 ]
385 self.other_certificates_content: list[str] | None = module.params[
386 "other_certificates_content"
387 ]
388 self.certificate_path: str | None = module.params["certificate_path"]
389 certificate_content: str | None = module.params["certificate_content"]
390 self.friendly_name: str | None = module.params["friendly_name"]
391 self.iter_size: int = module.params["iter_size"] or iter_size_default
392 self.encryption_level: t.Literal["auto", "compatibility2022"] = module.params[
393 "encryption_level"
394 ]
395 self.passphrase = module.params["passphrase"]
396 self.pkcs12: PKCS12 | None = None
397 self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"]
398 self.privatekey_path: str | None = module.params["privatekey_path"]
399 privatekey_content: str | None = module.params["privatekey_content"]
400 self.pkcs12_bytes: bytes | None = None
401 self.return_content: bool = module.params["return_content"]
402 self.src: str | None = module.params["src"]
403
404 if module.params["mode"] is None:
405 module.params["mode"] = "0400"
406
407 self.backup: bool = module.params["backup"]
408 self.backup_file: str | None = None
409
410 self.certificate_content: bytes | None = None
411 if self.certificate_path is not None:
412 try:
413 with open(self.certificate_path, "rb") as fh:
414 self.certificate_content = fh.read()
415 except (IOError, OSError) as exc:
416 raise PkcsError(exc) from exc
417 elif certificate_content is not None:
418 self.certificate_content = to_bytes(certificate_content)
419
420 self.privatekey_content: bytes | None = None
421 if self.privatekey_path is not None:
422 try:
423 with open(self.privatekey_path, "rb") as fh:
424 self.privatekey_content = fh.read()
425 except (IOError, OSError) as exc:
426 raise PkcsError(exc) from exc
427 elif privatekey_content is not None:
428 self.privatekey_content = to_bytes(privatekey_content)
429
430 if self.other_certificates_str:
431 if self.other_certificates_parse_all:
432 self.other_certificates = []
433 for other_cert_bundle in self.other_certificates_str:
434 self.other_certificates.extend(
435 load_certificate_set(other_cert_bundle)
436 )
437 else:
438 self.other_certificates = [
439 load_certificate(path=other_cert)
440 for other_cert in self.other_certificates_str
441 ]
442 elif self.other_certificates_content:
443 certs = self.other_certificates_content
444 if self.other_certificates_parse_all:
445 certs = list(
446 itertools.chain.from_iterable(
447 split_pem_list(content) for content in certs
448 )
449 )
450 self.other_certificates = [
451 load_certificate(content=to_bytes(other_cert)) for other_cert in certs
452 ]
453
454 if (
455 self.encryption_level == "compatibility2022"
456 and not CRYPTOGRAPHY_HAS_COMPATIBILITY2022
457 ):
458 module.fail_json(
459 msg="The installed cryptography version does not support encryption_level = compatibility2022."
460 " You need cryptography >= 38.0.0 and support for SHA1",
461 exception=CRYPTOGRAPHY_COMPATIBILITY2022_ERR,
462 )
463
464 def generate_bytes(self, module: AnsibleModule) -> bytes:
465 """Generate PKCS#12 file archive."""
466 pkey = None
467 if self.privatekey_content:
468 try:
469 pkey = load_certificate_issuer_privatekey(
470 content=self.privatekey_content,
471 passphrase=self.privatekey_passphrase,
472 )
473 except OpenSSLBadPassphraseError as exc:
474 raise PkcsError(exc) from exc
475
476 cert = None
477 if self.certificate_content:
478 cert = load_certificate(content=self.certificate_content)
479
480 friendly_name = (
481 to_bytes(self.friendly_name) if self.friendly_name is not None else None
482 )
483
484 # Store fake object which can be used to retrieve the components back
485 self.pkcs12 = (pkey, cert, self.other_certificates, friendly_name)
486
487 encryption: serialization.KeySerializationEncryption
488 if not self.passphrase:
489 encryption = serialization.NoEncryption()
490 elif self.encryption_level == "compatibility2022":
491 encryption = (
492 serialization.PrivateFormat.PKCS12.encryption_builder()
493 .kdf_rounds(self.iter_size)
494 .key_cert_algorithm(PBES.PBESv1SHA1And3KeyTripleDESCBC)
495 .hmac_hash(hashes.SHA1())
496 .build(to_bytes(self.passphrase))
497 )
498 else:
499 encryption = serialization.BestAvailableEncryption(
500 to_bytes(self.passphrase)
501 )
502
503 return serialize_key_and_certificates(
504 friendly_name,
505 pkey,
506 cert,
507 self.other_certificates,
508 encryption,
509 )
510
511 def parse_bytes(self, pkcs12_content: bytes) -> tuple[
512 bytes | None,
513 bytes | None,
514 list[bytes],
515 bytes | None,
516 ]:
517 try:
518 private_key, certificate, additional_certificates, friendly_name = (
519 parse_pkcs12(pkcs12_content, passphrase=self.passphrase)
520 )
521
522 pkey = None
523 if private_key is not None:
524 pkey = private_key.private_bytes(
525 encoding=serialization.Encoding.PEM,
526 format=serialization.PrivateFormat.TraditionalOpenSSL,
527 encryption_algorithm=serialization.NoEncryption(),
528 )
529
530 crt = None
531 if certificate is not None:
532 crt = certificate.public_bytes(serialization.Encoding.PEM)
533
534 other_certs = []
535 if additional_certificates is not None:
536 other_certs = [
537 other_cert.public_bytes(serialization.Encoding.PEM)
538 for other_cert in additional_certificates
539 ]
540
541 return (pkey, crt, other_certs, friendly_name)
542 except ValueError as exc:
543 raise PkcsError(exc) from exc
544
545 def _dump_privatekey(self, pkcs12: PKCS12) -> bytes | None:
546 return (
547 pkcs12[0].private_bytes(
548 encoding=serialization.Encoding.PEM,
549 format=serialization.PrivateFormat.TraditionalOpenSSL,
550 encryption_algorithm=serialization.NoEncryption(),
551 )
552 if pkcs12[0]
553 else None
554 )
555
556 def _dump_certificate(self, pkcs12: PKCS12) -> bytes | None:
557 return pkcs12[1].public_bytes(serialization.Encoding.PEM) if pkcs12[1] else None
558
559 def _dump_other_certificates(self, pkcs12: PKCS12) -> list[bytes]:
560 return [
561 other_cert.public_bytes(serialization.Encoding.PEM)
562 for other_cert in pkcs12[2]
563 ]
564
565 def _get_friendly_name(self, pkcs12: PKCS12) -> bytes | None:
566 return pkcs12[3]
567
568 def check(self, module: AnsibleModule, *, perms_required: bool = True) -> bool:
569 """Ensure the resource is in its desired state."""
570 state_and_perms = super().check(module=module, perms_required=perms_required)
571
572 def _check_pkey_passphrase() -> bool:
573 if self.privatekey_passphrase:
574 try:
575 load_certificate_issuer_privatekey(
576 content=self.privatekey_content,
577 passphrase=self.privatekey_passphrase,
578 )
579 except OpenSSLObjectError:
580 return False
581 return True
582
583 if not state_and_perms:
584 return state_and_perms
585
586 if os.path.exists(self.path) and module.params["action"] == "export":
587 self.generate_bytes(module) # ignore result
588 assert self.pkcs12 is not None
589 self.src = self.path
590 try:
591 (
592 pkcs12_privatekey,
593 pkcs12_certificate,
594 pkcs12_other_certificates,
595 pkcs12_friendly_name,
596 ) = self.parse()
597 except OpenSSLObjectError:
598 return False
599 if (pkcs12_privatekey is not None) and (
600 self.privatekey_content is not None
601 ):
602 expected_pkey = self._dump_privatekey(self.pkcs12)
603 if pkcs12_privatekey != expected_pkey:
604 return False
605 elif bool(pkcs12_privatekey) != bool(self.privatekey_content):
606 return False
607
608 if (pkcs12_certificate is not None) and (
609 self.certificate_content is not None
610 ):
611 expected_cert = self._dump_certificate(self.pkcs12)
612 if pkcs12_certificate != expected_cert:
613 return False
614 elif bool(pkcs12_certificate) != bool(self.certificate_content):
615 return False
616
617 expected_other_certs = self._dump_other_certificates(self.pkcs12)
618 if set(pkcs12_other_certificates) != set(expected_other_certs):
619 return False
620
621 if pkcs12_privatekey:
622 # This check is required because pyOpenSSL will not return a friendly name
623 # if the private key is not set in the file
624 friendly_name = self._get_friendly_name(self.pkcs12)
625 if (friendly_name is not None) and (pkcs12_friendly_name is not None):
626 if friendly_name != pkcs12_friendly_name:
627 return False
628 elif bool(friendly_name) != bool(pkcs12_friendly_name):
629 return False
630 elif (
631 module.params["action"] == "parse"
632 and os.path.exists(self.src or "")
633 and os.path.exists(self.path)
634 ):
635 try:
636 pkey, cert, other_certs, friendly_name = self.parse()
637 except OpenSSLObjectError:
638 return False
639 expected_content = to_bytes(
640 "".join(
641 [
642 to_text(pem)
643 for pem in [pkey, cert] + other_certs
644 if pem is not None
645 ]
646 )
647 )
648 dumped_content = load_file_if_exists(path=self.path, ignore_errors=True)
649 if expected_content != dumped_content:
650 return False
651 else:
652 return False
653
654 return _check_pkey_passphrase()
655
656 def dump(self) -> dict[str, t.Any]:
657 """Serialize the object into a dictionary."""
658
659 result: dict[str, t.Any] = {
660 "filename": self.path,
661 }
662 if self.privatekey_path:
663 result["privatekey_path"] = self.privatekey_path
664 if self.backup_file:
665 result["backup_file"] = self.backup_file
666 if self.return_content:
667 if self.pkcs12_bytes is None:
668 self.pkcs12_bytes = load_file_if_exists(
669 path=self.path, ignore_errors=True
670 )
671 result["pkcs12"] = (
672 base64.b64encode(self.pkcs12_bytes) if self.pkcs12_bytes else None
673 )
674
675 return result
676
677 def remove(self, module: AnsibleModule) -> None:
678 if self.backup:
679 self.backup_file = module.backup_local(self.path)
680 super().remove(module)
681
682 def parse(
683 self,
684 ) -> tuple[
685 bytes | None,
686 bytes | None,
687 list[bytes],
688 bytes | None,
689 ]:
690 """Read PKCS#12 file."""
691 if self.src is None:
692 raise AssertionError("Contract violation: src is None") # pragma: no cover
693
694 try:
695 with open(self.src, "rb") as pkcs12_fh:
696 pkcs12_content = pkcs12_fh.read()
697 return self.parse_bytes(pkcs12_content)
698 except IOError as exc:
699 raise PkcsError(exc) from exc
700
701 def generate(self, module: AnsibleModule) -> None:
702 # Empty method because OpenSSLObject wants this
703 pass
704
705 def write(
706 self, module: AnsibleModule, content: bytes, mode: int | str | None = None
707 ) -> None:
708 """Write the PKCS#12 file."""
709 if self.backup:
710 self.backup_file = module.backup_local(self.path)
711 write_file(module=module, content=content, default_mode=mode)
712 if self.return_content:
713 self.pkcs12_bytes = content
714
715
716 def select_backend(module: AnsibleModule) -> Pkcs:
717 assert_required_cryptography_version(
718 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
719 )
720 return Pkcs(module)
721
722
723 def main() -> t.NoReturn:
724 argument_spec = {
725 "action": {"type": "str", "default": "export", "choices": ["export", "parse"]},
726 "other_certificates": {
727 "type": "list",
728 "elements": "path",
729 "aliases": ["ca_certificates"],
730 },
731 "other_certificates_parse_all": {"type": "bool", "default": False},
732 "other_certificates_content": {"type": "list", "elements": "str"},
733 "certificate_path": {"type": "path"},
734 "certificate_content": {"type": "str"},
735 "force": {"type": "bool", "default": False},
736 "friendly_name": {"type": "str", "aliases": ["name"]},
737 "encryption_level": {
738 "type": "str",
739 "choices": ["auto", "compatibility2022"],
740 "default": "auto",
741 },
742 "iter_size": {"type": "int"},
743 "maciter_size": {
744 "type": "int",
745 "removed_in_version": "4.0.0",
746 "removed_from_collection": "community.crypto",
747 },
748 "passphrase": {"type": "str", "no_log": True},
749 "path": {"type": "path", "required": True},
750 "privatekey_passphrase": {"type": "str", "no_log": True},
751 "privatekey_path": {"type": "path"},
752 "privatekey_content": {"type": "str", "no_log": True},
753 "state": {
754 "type": "str",
755 "default": "present",
756 "choices": ["absent", "present"],
757 },
758 "src": {"type": "path"},
759 "backup": {"type": "bool", "default": False},
760 "return_content": {"type": "bool", "default": False},
761 "select_crypto_backend": {
762 "type": "str",
763 "default": "auto",
764 "choices": ["auto", "cryptography"],
765 },
766 }
767
768 required_if = [
769 ["action", "parse", ["src"]],
770 ]
771
772 mutually_exclusive = [
773 ["privatekey_path", "privatekey_content"],
774 ["certificate_path", "certificate_content"],
775 ["other_certificates", "other_certificates_content"],
776 ]
777
778 module = AnsibleModule(
779 add_file_common_args=True,
780 argument_spec=argument_spec,
781 required_if=required_if,
782 mutually_exclusive=mutually_exclusive,
783 supports_check_mode=True,
784 )
785
786 pkcs12 = select_backend(module)
787
788 base_dir = os.path.dirname(module.params["path"]) or "."
789 if not os.path.isdir(base_dir):
790 module.fail_json(
791 name=base_dir,
792 msg=f"The directory '{base_dir}' does not exist or the path is not a directory",
793 )
794
795 try:
796 changed = False
797
798 if module.params["state"] == "present":
799 if module.check_mode:
800 result = pkcs12.dump()
801 result["changed"] = module.params["force"] or not pkcs12.check(module)
802 module.exit_json(**result)
803
804 if not pkcs12.check(module, perms_required=False) or module.params["force"]:
805 if module.params["action"] == "export":
806 if not module.params["friendly_name"]:
807 module.fail_json(msg="Friendly_name is required")
808 pkcs12_content = pkcs12.generate_bytes(module)
809 pkcs12.write(module, pkcs12_content, 0o600)
810 changed = True
811 else:
812 pkey, cert, other_certs, _friendly_name = pkcs12.parse()
813 dump_content = "".join(
814 [
815 to_text(pem)
816 for pem in [pkey, cert] + other_certs
817 if pem is not None
818 ]
819 )
820 pkcs12.write(module, to_bytes(dump_content))
821 changed = True
822
823 file_args = module.load_file_common_arguments(module.params)
824 if module.check_file_absent_if_check_mode(
825 file_args["path"]
826 ) or module.set_fs_attributes_if_different(file_args, changed):
827 changed = True
828 else:
829 if module.check_mode:
830 result = pkcs12.dump()
831 result["changed"] = os.path.exists(module.params["path"])
832 module.exit_json(**result)
833
834 if os.path.exists(module.params["path"]):
835 pkcs12.remove(module)
836 changed = True
837
838 result = pkcs12.dump()
839 result["changed"] = changed
840 if os.path.exists(module.params["path"]):
841 file_mode = f"{stat.S_IMODE(os.stat(module.params['path']).st_mode):04o}"
842 result["mode"] = file_mode
843
844 module.exit_json(**result)
845 except OpenSSLObjectError as exc:
846 module.fail_json(msg=str(exc))
847
848
849 if __name__ == "__main__":
850 main()