Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2016-2017, Yanis Guenane <[email protected]>
3 # Copyright (c) 2017, Markus Teufelberger <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: x509_certificate
11 short_description: Generate and/or check OpenSSL certificates
12 description:
13 - It implements a notion of provider (one of V(selfsigned), V(ownca), and V(acme)) for your certificate.
14 - Please note that the module regenerates existing certificate if it does not match the module's options, or if it seems
15 to be corrupt. If you are concerned that this could overwrite your existing certificate, consider using the O(backup)
16 option.
17 - Note that this module was called C(openssl_certificate) when included directly in Ansible up to version 2.9. When moved
18 to the collection C(community.crypto), it was renamed to M(community.crypto.x509_certificate). From Ansible 2.10 on, it
19 can still be used by the old short name (or by C(ansible.builtin.openssl_certificate)), which redirects to M(community.crypto.x509_certificate).
20 When using FQCNs or when using the L(collections,https://docs.ansible.com/ansible/latest/user_guide/collections_using.html#using-collections-in-a-playbook)
21 keyword, the new name M(community.crypto.x509_certificate) should be used to avoid a deprecation warning.
22 author:
23 - Yanis Guenane (@Spredzy)
24 - Markus Teufelberger (@MarkusTeufelberger)
25 extends_documentation_fragment:
26 - ansible.builtin.files
27 - community.crypto._attributes
28 - community.crypto._attributes.files
29 - community.crypto._module_certificate
30 - community.crypto._module_certificate.backend_acme_documentation
31 - community.crypto._module_certificate.backend_ownca_documentation
32 - community.crypto._module_certificate.backend_selfsigned_documentation
33 attributes:
34 check_mode:
35 support: full
36 safe_file_operations:
37 support: full
38 options:
39 state:
40 description:
41 - Whether the certificate should exist or not, taking action if the state is different from what is stated.
42 type: str
43 default: present
44 choices: [absent, present]
45
46 path:
47 description:
48 - Remote absolute path where the generated certificate file should be created or is already located.
49 type: path
50 required: true
51
52 provider:
53 description:
54 - Name of the provider to use to generate/retrieve the OpenSSL certificate. Please see the examples on how to emulate
55 it with M(community.crypto.x509_certificate_info), M(community.crypto.openssl_csr_info), M(community.crypto.openssl_privatekey_info)
56 and M(ansible.builtin.assert).
57 - Required if O(state) is V(present).
58 - The V(entrust) provider has been removed from community.crypto 3.0.0 due to sunsetting of the ECS API.
59 type: str
60 choices: [acme, ownca, selfsigned]
61
62 return_content:
63 description:
64 - If set to V(true), will return the (current or generated) certificate's content as RV(certificate).
65 type: bool
66 default: false
67 version_added: '1.0.0'
68
69 backup:
70 description:
71 - Create a backup file including a timestamp so you can get the original certificate back if you overwrote it with a
72 new one by accident.
73 type: bool
74 default: false
75
76 csr_content:
77 version_added: '1.0.0'
78 privatekey_content:
79 version_added: '1.0.0'
80 acme_directory:
81 version_added: '1.0.0'
82 ownca_content:
83 version_added: '1.0.0'
84 ownca_privatekey_content:
85 version_added: '1.0.0'
86
87 seealso:
88 - module: community.crypto.x509_certificate_pipe
89 """
90
91 EXAMPLES = r"""
92 ---
93 - name: Generate a Self Signed OpenSSL certificate
94 community.crypto.x509_certificate:
95 path: /etc/ssl/crt/ansible.com.crt
96 privatekey_path: /etc/ssl/private/ansible.com.pem
97 csr_path: /etc/ssl/csr/ansible.com.csr
98 provider: selfsigned
99
100 - name: Generate an OpenSSL certificate signed with your own CA certificate
101 community.crypto.x509_certificate:
102 path: /etc/ssl/crt/ansible.com.crt
103 csr_path: /etc/ssl/csr/ansible.com.csr
104 ownca_path: /etc/ssl/crt/ansible_CA.crt
105 ownca_privatekey_path: /etc/ssl/private/ansible_CA.pem
106 provider: ownca
107
108 - name: Generate a Let's Encrypt Certificate
109 community.crypto.x509_certificate:
110 path: /etc/ssl/crt/ansible.com.crt
111 csr_path: /etc/ssl/csr/ansible.com.csr
112 provider: acme
113 acme_accountkey_path: /etc/ssl/private/ansible.com.pem
114 acme_challenge_path: /etc/ssl/challenges/ansible.com/
115
116 - name: Force (re-)generate a new Let's Encrypt Certificate
117 community.crypto.x509_certificate:
118 path: /etc/ssl/crt/ansible.com.crt
119 csr_path: /etc/ssl/csr/ansible.com.csr
120 provider: acme
121 acme_accountkey_path: /etc/ssl/private/ansible.com.pem
122 acme_challenge_path: /etc/ssl/challenges/ansible.com/
123 force: true
124
125 # The following example shows how to emulate the behavior of the removed
126 # "assertonly" provider with the x509_certificate_info, openssl_csr_info,
127 # openssl_privatekey_info and assert modules:
128
129 - name: Get certificate information
130 community.crypto.x509_certificate_info:
131 path: /etc/ssl/crt/ansible.com.crt
132 # for valid_at, invalid_at and valid_in
133 valid_at:
134 one_day_ten_hours: "+1d10h"
135 fixed_timestamp: 20200331202428Z
136 ten_seconds: "+10"
137 register: result
138
139 - name: Get CSR information
140 community.crypto.openssl_csr_info:
141 # Verifies that the CSR signature is valid; module will fail if not
142 path: /etc/ssl/csr/ansible.com.csr
143 register: result_csr
144
145 - name: Get private key information
146 community.crypto.openssl_privatekey_info:
147 path: /etc/ssl/csr/ansible.com.key
148 register: result_privatekey
149
150 - name: Check conditions on certificate, CSR, and private key
151 ansible.builtin.assert:
152 that:
153 # When private key was specified for assertonly, this was checked:
154 - result.public_key == result_privatekey.public_key
155 # When CSR was specified for assertonly, this was checked:
156 - result.public_key == result_csr.public_key
157 - result.subject_ordered == result_csr.subject_ordered
158 - result.extensions_by_oid == result_csr.extensions_by_oid
159 # signature_algorithms check
160 - "result.signature_algorithm == 'sha256WithRSAEncryption' or result.signature_algorithm == 'sha512WithRSAEncryption'"
161 # subject and subject_strict
162 - "result.subject.commonName == 'ansible.com'"
163 - "result.subject | length == 1" # the number must be the number of entries you check for
164 # issuer and issuer_strict
165 - "result.issuer.commonName == 'ansible.com'"
166 - "result.issuer | length == 1" # the number must be the number of entries you check for
167 # has_expired
168 - not result.expired
169 # version
170 - result.version == 3
171 # key_usage and key_usage_strict
172 - "'Data Encipherment' in result.key_usage"
173 - "result.key_usage | length == 1" # the number must be the number of entries you check for
174 # extended_key_usage and extended_key_usage_strict
175 - "'DVCS' in result.extended_key_usage"
176 - "result.extended_key_usage | length == 1" # the number must be the number of entries you check for
177 # subject_alt_name and subject_alt_name_strict
178 - "'dns:ansible.com' in result.subject_alt_name"
179 - "result.subject_alt_name | length == 1" # the number must be the number of entries you check for
180 # not_before and not_after
181 - "result.not_before == '20190331202428Z'"
182 - "result.not_after == '20190413202428Z'"
183 # valid_at, invalid_at and valid_in
184 - "result.valid_at.one_day_ten_hours" # for valid_at
185 - "not result.valid_at.fixed_timestamp" # for invalid_at
186 - "result.valid_at.ten_seconds" # for valid_in
187 """
188
189 RETURN = r"""
190 filename:
191 description: Path to the generated certificate.
192 returned: changed or success
193 type: str
194 sample: /etc/ssl/crt/www.ansible.com.crt
195 backup_file:
196 description: Name of backup file created.
197 returned: changed and if O(backup) is V(true)
198 type: str
199 sample: /path/to/www.ansible.com.crt.2019-03-09@11:22~
200 certificate:
201 description: The (current or generated) certificate's content.
202 returned: if O(state) is V(present) and O(return_content) is V(true)
203 type: str
204 version_added: '1.0.0'
205 """
206
207
208 import os
209 import typing as t
210
211 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
212 OpenSSLObjectError,
213 )
214 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate import (
215 get_certificate_argument_spec,
216 select_backend,
217 )
218 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate_acme import (
219 AcmeCertificateProvider,
220 add_acme_provider_to_argument_spec,
221 )
222 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate_ownca import (
223 OwnCACertificateProvider,
224 add_ownca_provider_to_argument_spec,
225 )
226 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate_selfsigned import (
227 SelfSignedCertificateProvider,
228 add_selfsigned_provider_to_argument_spec,
229 )
230 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
231 OpenSSLObject,
232 )
233 from ansible_collections.community.crypto.plugins.module_utils._io import (
234 load_file_if_exists,
235 write_file,
236 )
237
238 if t.TYPE_CHECKING:
239 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
240
241 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate import ( # pragma: no cover
242 CertificateBackend,
243 )
244
245
246 class CertificateAbsent(OpenSSLObject):
247 def __init__(self, module: AnsibleModule) -> None:
248 super().__init__(
249 path=module.params["path"],
250 state=module.params["state"],
251 force=module.params["force"],
252 check_mode=module.check_mode,
253 )
254 self.module = module
255 self.return_content: bool = module.params["return_content"]
256 self.backup: bool = module.params["backup"]
257 self.backup_file: str | None = None
258
259 def generate(self, module: AnsibleModule) -> None:
260 pass
261
262 def remove(self, module: AnsibleModule) -> None:
263 if self.backup:
264 self.backup_file = module.backup_local(self.path)
265 super().remove(module)
266
267 def dump(self, check_mode: bool = False) -> dict[str, t.Any]:
268 result = {
269 "changed": self.changed,
270 "filename": self.path,
271 "privatekey": self.module.params["privatekey_path"],
272 "csr": self.module.params["csr_path"],
273 }
274 if self.backup_file:
275 result["backup_file"] = self.backup_file
276 if self.return_content:
277 result["certificate"] = None
278
279 return result
280
281
282 class GenericCertificate(OpenSSLObject):
283 """Retrieve a certificate using the given module backend."""
284
285 def __init__(self, module: AnsibleModule, module_backend: CertificateBackend):
286 super().__init__(
287 path=module.params["path"],
288 state=module.params["state"],
289 force=module.params["force"],
290 check_mode=module.check_mode,
291 )
292 self.module = module
293 self.return_content = module.params["return_content"]
294 self.backup = module.params["backup"]
295 self.backup_file: str | None = None
296
297 self.module_backend = module_backend
298 self.module_backend.set_existing(
299 certificate_bytes=load_file_if_exists(path=self.path, module=module)
300 )
301
302 def generate(self, module: AnsibleModule) -> None:
303 if self.module_backend.needs_regeneration():
304 if not self.check_mode:
305 self.module_backend.generate_certificate()
306 result = self.module_backend.get_certificate_data()
307 if self.backup:
308 self.backup_file = module.backup_local(self.path)
309 write_file(module=module, content=result)
310 self.changed = True
311
312 file_args = module.load_file_common_arguments(module.params)
313 if module.check_file_absent_if_check_mode(file_args["path"]):
314 self.changed = True
315 else:
316 self.changed = module.set_fs_attributes_if_different(
317 file_args, self.changed
318 )
319
320 def check(self, module: AnsibleModule, *, perms_required: bool = True) -> bool:
321 """Ensure the resource is in its desired state."""
322 return (
323 super().check(module=module, perms_required=perms_required)
324 and not self.module_backend.needs_regeneration()
325 )
326
327 def dump(self, check_mode: bool = False) -> dict[str, t.Any]:
328 result = self.module_backend.dump(include_certificate=self.return_content)
329 result.update(
330 {
331 "changed": self.changed,
332 "filename": self.path,
333 }
334 )
335 if self.backup_file:
336 result["backup_file"] = self.backup_file
337 return result
338
339
340 def main() -> t.NoReturn:
341 argument_spec = get_certificate_argument_spec()
342 add_acme_provider_to_argument_spec(argument_spec)
343 add_ownca_provider_to_argument_spec(argument_spec)
344 add_selfsigned_provider_to_argument_spec(argument_spec)
345 argument_spec.argument_spec.update(
346 {
347 "state": {
348 "type": "str",
349 "default": "present",
350 "choices": ["present", "absent"],
351 },
352 "path": {"type": "path", "required": True},
353 "backup": {"type": "bool", "default": False},
354 "return_content": {"type": "bool", "default": False},
355 }
356 )
357 argument_spec.required_if.append(("state", "present", ["provider"]))
358 module = argument_spec.create_ansible_module(
359 add_file_common_args=True,
360 supports_check_mode=True,
361 )
362
363 try:
364 certificate: GenericCertificate | CertificateAbsent
365 if module.params["state"] == "absent":
366 certificate = CertificateAbsent(module)
367
368 if module.check_mode:
369 result = certificate.dump(check_mode=True)
370 result["changed"] = os.path.exists(module.params["path"])
371 module.exit_json(**result)
372
373 certificate.remove(module)
374
375 else:
376 base_dir = os.path.dirname(module.params["path"]) or "."
377 if not os.path.isdir(base_dir):
378 module.fail_json(
379 name=base_dir,
380 msg=f"The directory {base_dir} does not exist or the file is not a directory",
381 )
382
383 provider = module.params["provider"]
384 provider_map: dict[
385 str,
386 type[AcmeCertificateProvider]
387 | type[OwnCACertificateProvider]
388 | type[SelfSignedCertificateProvider],
389 ] = {
390 "acme": AcmeCertificateProvider,
391 "ownca": OwnCACertificateProvider,
392 "selfsigned": SelfSignedCertificateProvider,
393 }
394
395 module_backend = select_backend(
396 module=module, provider=provider_map[provider]()
397 )
398 certificate = GenericCertificate(module, module_backend)
399 certificate.generate(module)
400
401 result = certificate.dump()
402 module.exit_json(**result)
403 except OpenSSLObjectError as exc:
404 module.fail_json(msg=str(exc))
405
406
407 if __name__ == "__main__":
408 main()