| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2017, Yanis Guenane <[email protected]> |
| 3 |
# Copyright (c) 2020, Felix Fontein <[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: openssl_csr |
| 11 |
short_description: Generate OpenSSL Certificate Signing Request (CSR) |
| 12 |
description: |
| 13 |
- Please note that the module regenerates an existing CSR if it does not match the module's options, or if it seems to be |
| 14 |
corrupt. If you are concerned that this could overwrite your existing CSR, consider using the O(backup) option. |
| 15 |
author: |
| 16 |
- Yanis Guenane (@Spredzy) |
| 17 |
- Felix Fontein (@felixfontein) |
| 18 |
extends_documentation_fragment: |
| 19 |
- ansible.builtin.files |
| 20 |
- community.crypto._attributes |
| 21 |
- community.crypto._attributes.files |
| 22 |
- community.crypto._module_csr |
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: full |
| 26 |
safe_file_operations: |
| 27 |
support: full |
| 28 |
options: |
| 29 |
state: |
| 30 |
description: |
| 31 |
- Whether the certificate signing request should exist or not, taking action if the state is different from what is |
| 32 |
stated. |
| 33 |
type: str |
| 34 |
default: present |
| 35 |
choices: [absent, present] |
| 36 |
force: |
| 37 |
description: |
| 38 |
- Should the certificate signing request be forced regenerated by this ansible module. |
| 39 |
type: bool |
| 40 |
default: false |
| 41 |
path: |
| 42 |
description: |
| 43 |
- The name of the file into which the generated OpenSSL certificate signing request will be written. |
| 44 |
type: path |
| 45 |
required: true |
| 46 |
backup: |
| 47 |
description: |
| 48 |
- Create a backup file including a timestamp so you can get the original CSR back if you overwrote it with a new one |
| 49 |
by accident. |
| 50 |
type: bool |
| 51 |
default: false |
| 52 |
return_content: |
| 53 |
description: |
| 54 |
- If set to V(true), will return the (current or generated) CSR's content as RV(csr). |
| 55 |
type: bool |
| 56 |
default: false |
| 57 |
version_added: "1.0.0" |
| 58 |
privatekey_content: |
| 59 |
version_added: "1.0.0" |
| 60 |
name_constraints_permitted: |
| 61 |
version_added: 1.1.0 |
| 62 |
name_constraints_excluded: |
| 63 |
version_added: 1.1.0 |
| 64 |
name_constraints_critical: |
| 65 |
version_added: 1.1.0 |
| 66 |
seealso: |
| 67 |
- module: community.crypto.openssl_csr_pipe |
| 68 |
""" |
| 69 |
|
| 70 |
EXAMPLES = r""" |
| 71 |
--- |
| 72 |
- name: Generate an OpenSSL Certificate Signing Request |
| 73 |
community.crypto.openssl_csr: |
| 74 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 75 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 76 |
common_name: www.ansible.com |
| 77 |
|
| 78 |
- name: Generate an OpenSSL Certificate Signing Request with an inline key |
| 79 |
community.crypto.openssl_csr: |
| 80 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 81 |
privatekey_content: "{{ private_key_content }}" |
| 82 |
common_name: www.ansible.com |
| 83 |
|
| 84 |
- name: Generate an OpenSSL Certificate Signing Request with a passphrase protected private key |
| 85 |
community.crypto.openssl_csr: |
| 86 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 87 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 88 |
privatekey_passphrase: ansible |
| 89 |
common_name: www.ansible.com |
| 90 |
|
| 91 |
- name: Generate an OpenSSL Certificate Signing Request with Subject information |
| 92 |
community.crypto.openssl_csr: |
| 93 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 94 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 95 |
country_name: FR |
| 96 |
organization_name: Ansible |
| 97 |
email_address: [email protected] |
| 98 |
common_name: www.ansible.com |
| 99 |
|
| 100 |
- name: Generate an OpenSSL Certificate Signing Request with subjectAltName extension |
| 101 |
community.crypto.openssl_csr: |
| 102 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 103 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 104 |
subject_alt_name: 'DNS:www.ansible.com,DNS:m.ansible.com' |
| 105 |
|
| 106 |
- name: Generate an OpenSSL CSR with subjectAltName extension with dynamic list |
| 107 |
community.crypto.openssl_csr: |
| 108 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 109 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 110 |
subject_alt_name: "{{ item.value | map('regex_replace', '^', 'DNS:') | list }}" |
| 111 |
with_dict: |
| 112 |
dns_server: |
| 113 |
- www.ansible.com |
| 114 |
- m.ansible.com |
| 115 |
|
| 116 |
- name: Force regenerate an OpenSSL Certificate Signing Request |
| 117 |
community.crypto.openssl_csr: |
| 118 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 119 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 120 |
force: true |
| 121 |
common_name: www.ansible.com |
| 122 |
|
| 123 |
- name: Generate an OpenSSL Certificate Signing Request with special key usages |
| 124 |
community.crypto.openssl_csr: |
| 125 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 126 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 127 |
common_name: www.ansible.com |
| 128 |
key_usage: |
| 129 |
- digitalSignature |
| 130 |
- keyAgreement |
| 131 |
extended_key_usage: |
| 132 |
- clientAuth |
| 133 |
|
| 134 |
- name: Generate an OpenSSL Certificate Signing Request with OCSP Must Staple |
| 135 |
community.crypto.openssl_csr: |
| 136 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 137 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 138 |
common_name: www.ansible.com |
| 139 |
ocsp_must_staple: true |
| 140 |
|
| 141 |
- name: Generate an OpenSSL Certificate Signing Request for WinRM Certificate authentication |
| 142 |
community.crypto.openssl_csr: |
| 143 |
path: /etc/ssl/csr/winrm.auth.csr |
| 144 |
privatekey_path: /etc/ssl/private/winrm.auth.pem |
| 145 |
common_name: username |
| 146 |
extended_key_usage: |
| 147 |
- clientAuth |
| 148 |
subject_alt_name: otherName:1.3.6.1.4.1.311.20.2.3;UTF8:username@localhost |
| 149 |
|
| 150 |
- name: Generate an OpenSSL Certificate Signing Request with a CRL distribution point |
| 151 |
community.crypto.openssl_csr: |
| 152 |
path: /etc/ssl/csr/www.ansible.com.csr |
| 153 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 154 |
common_name: www.ansible.com |
| 155 |
crl_distribution_points: |
| 156 |
- full_name: |
| 157 |
- "URI:https://ca.example.com/revocations.crl" |
| 158 |
crl_issuer: |
| 159 |
- "URI:https://ca.example.com/" |
| 160 |
reasons: |
| 161 |
- key_compromise |
| 162 |
- ca_compromise |
| 163 |
- cessation_of_operation |
| 164 |
""" |
| 165 |
|
| 166 |
RETURN = r""" |
| 167 |
privatekey: |
| 168 |
description: |
| 169 |
- Path to the TLS/SSL private key the CSR was generated for. |
| 170 |
- Will be V(none) if the private key has been provided in O(privatekey_content). |
| 171 |
returned: changed or success |
| 172 |
type: str |
| 173 |
sample: /etc/ssl/private/ansible.com.pem |
| 174 |
filename: |
| 175 |
description: Path to the generated Certificate Signing Request. |
| 176 |
returned: changed or success |
| 177 |
type: str |
| 178 |
sample: /etc/ssl/csr/www.ansible.com.csr |
| 179 |
subject: |
| 180 |
description: A list of the subject tuples attached to the CSR. |
| 181 |
returned: changed or success |
| 182 |
type: list |
| 183 |
elements: list |
| 184 |
sample: [['CN', 'www.ansible.com'], ['O', 'Ansible']] |
| 185 |
subjectAltName: |
| 186 |
description: The alternative names this CSR is valid for. |
| 187 |
returned: changed or success |
| 188 |
type: list |
| 189 |
elements: str |
| 190 |
sample: ['DNS:www.ansible.com', 'DNS:m.ansible.com'] |
| 191 |
keyUsage: |
| 192 |
description: Purpose for which the public key may be used. |
| 193 |
returned: changed or success |
| 194 |
type: list |
| 195 |
elements: str |
| 196 |
sample: ['digitalSignature', 'keyAgreement'] |
| 197 |
extendedKeyUsage: |
| 198 |
description: Additional restriction on the public key purposes. |
| 199 |
returned: changed or success |
| 200 |
type: list |
| 201 |
elements: str |
| 202 |
sample: ['clientAuth'] |
| 203 |
basicConstraints: |
| 204 |
description: Indicates if the certificate belongs to a CA. |
| 205 |
returned: changed or success |
| 206 |
type: list |
| 207 |
elements: str |
| 208 |
sample: ['CA:TRUE', 'pathLenConstraint:0'] |
| 209 |
ocsp_must_staple: |
| 210 |
description: Indicates whether the certificate has the OCSP Must Staple feature enabled. |
| 211 |
returned: changed or success |
| 212 |
type: bool |
| 213 |
sample: false |
| 214 |
name_constraints_permitted: |
| 215 |
description: List of permitted subtrees to sign certificates for. |
| 216 |
returned: changed or success |
| 217 |
type: list |
| 218 |
elements: str |
| 219 |
sample: ['email:.somedomain.com'] |
| 220 |
version_added: 1.1.0 |
| 221 |
name_constraints_excluded: |
| 222 |
description: List of excluded subtrees the CA cannot sign certificates for. |
| 223 |
returned: changed or success |
| 224 |
type: list |
| 225 |
elements: str |
| 226 |
sample: ['email:.com'] |
| 227 |
version_added: 1.1.0 |
| 228 |
backup_file: |
| 229 |
description: Name of backup file created. |
| 230 |
returned: changed and if O(backup) is V(true) |
| 231 |
type: str |
| 232 |
sample: /path/to/www.ansible.com.csr.2019-03-09@11:22~ |
| 233 |
csr: |
| 234 |
description: The (current or generated) CSR's content. |
| 235 |
returned: if O(state) is V(present) and O(return_content) is V(true) |
| 236 |
type: str |
| 237 |
version_added: "1.0.0" |
| 238 |
""" |
| 239 |
|
| 240 |
import os |
| 241 |
import typing as t |
| 242 |
|
| 243 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import ( |
| 244 |
OpenSSLObjectError, |
| 245 |
) |
| 246 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import ( |
| 247 |
get_csr_argument_spec, |
| 248 |
select_backend, |
| 249 |
) |
| 250 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.support import ( |
| 251 |
OpenSSLObject, |
| 252 |
) |
| 253 |
from ansible_collections.community.crypto.plugins.module_utils._io import ( |
| 254 |
load_file_if_exists, |
| 255 |
write_file, |
| 256 |
) |
| 257 |
|
| 258 |
if t.TYPE_CHECKING: |
| 259 |
from ansible.module_utils.basic import AnsibleModule # pragma: no cover |
| 260 |
|
| 261 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import ( # pragma: no cover |
| 262 |
CertificateSigningRequestBackend, |
| 263 |
) |
| 264 |
|
| 265 |
|
| 266 |
class CertificateSigningRequestModule(OpenSSLObject): |
| 267 |
def __init__( |
| 268 |
self, module: AnsibleModule, module_backend: CertificateSigningRequestBackend |
| 269 |
) -> None: |
| 270 |
super().__init__( |
| 271 |
path=module.params["path"], |
| 272 |
state=module.params["state"], |
| 273 |
force=module.params["force"], |
| 274 |
check_mode=module.check_mode, |
| 275 |
) |
| 276 |
self.module_backend = module_backend |
| 277 |
self.return_content = module.params["return_content"] |
| 278 |
|
| 279 |
self.backup = module.params["backup"] |
| 280 |
self.backup_file: str | None = None |
| 281 |
|
| 282 |
self.module_backend.set_existing( |
| 283 |
csr_bytes=load_file_if_exists(path=self.path, module=module) |
| 284 |
) |
| 285 |
|
| 286 |
def generate(self, module: AnsibleModule) -> None: |
| 287 |
"""Generate the certificate signing request.""" |
| 288 |
if self.force or self.module_backend.needs_regeneration(): |
| 289 |
if not self.check_mode: |
| 290 |
self.module_backend.generate_csr() |
| 291 |
result = self.module_backend.get_csr_data() |
| 292 |
if self.backup: |
| 293 |
self.backup_file = module.backup_local(self.path) |
| 294 |
write_file(module=module, content=result) |
| 295 |
self.changed = True |
| 296 |
|
| 297 |
file_args = module.load_file_common_arguments(module.params) |
| 298 |
if module.check_file_absent_if_check_mode(file_args["path"]): |
| 299 |
self.changed = True |
| 300 |
else: |
| 301 |
self.changed = module.set_fs_attributes_if_different( |
| 302 |
file_args, self.changed |
| 303 |
) |
| 304 |
|
| 305 |
def remove(self, module: AnsibleModule) -> None: |
| 306 |
self.module_backend.set_existing(csr_bytes=None) |
| 307 |
if self.backup and not self.check_mode: |
| 308 |
self.backup_file = module.backup_local(self.path) |
| 309 |
super().remove(module) |
| 310 |
|
| 311 |
def dump(self) -> dict[str, t.Any]: |
| 312 |
"""Serialize the object into a dictionary.""" |
| 313 |
result = self.module_backend.dump(include_csr=self.return_content) |
| 314 |
result.update( |
| 315 |
{ |
| 316 |
"filename": self.path, |
| 317 |
"changed": self.changed, |
| 318 |
} |
| 319 |
) |
| 320 |
if self.backup_file: |
| 321 |
result["backup_file"] = self.backup_file |
| 322 |
return result |
| 323 |
|
| 324 |
|
| 325 |
def main() -> t.NoReturn: |
| 326 |
argument_spec = get_csr_argument_spec() |
| 327 |
argument_spec.argument_spec.update( |
| 328 |
{ |
| 329 |
"state": { |
| 330 |
"type": "str", |
| 331 |
"default": "present", |
| 332 |
"choices": ["absent", "present"], |
| 333 |
}, |
| 334 |
"force": {"type": "bool", "default": False}, |
| 335 |
"path": {"type": "path", "required": True}, |
| 336 |
"backup": {"type": "bool", "default": False}, |
| 337 |
"return_content": {"type": "bool", "default": False}, |
| 338 |
} |
| 339 |
) |
| 340 |
argument_spec.required_if.extend( |
| 341 |
[("state", "present", rof, True) for rof in argument_spec.required_one_of] |
| 342 |
) |
| 343 |
argument_spec.required_one_of = [] |
| 344 |
module = argument_spec.create_ansible_module( |
| 345 |
add_file_common_args=True, |
| 346 |
supports_check_mode=True, |
| 347 |
) |
| 348 |
|
| 349 |
base_dir = os.path.dirname(module.params["path"]) or "." |
| 350 |
if not os.path.isdir(base_dir): |
| 351 |
module.fail_json( |
| 352 |
name=base_dir, |
| 353 |
msg=f"The directory {base_dir} does not exist or the file is not a directory", |
| 354 |
) |
| 355 |
|
| 356 |
try: |
| 357 |
module_backend = select_backend(module) |
| 358 |
|
| 359 |
csr = CertificateSigningRequestModule(module, module_backend) |
| 360 |
if module.params["state"] == "present": |
| 361 |
csr.generate(module) |
| 362 |
else: |
| 363 |
csr.remove(module) |
| 364 |
|
| 365 |
result = csr.dump() |
| 366 |
module.exit_json(**result) |
| 367 |
except OpenSSLObjectError as exc: |
| 368 |
module.fail_json(msg=str(exc)) |
| 369 |
|
| 370 |
|
| 371 |
if __name__ == "__main__": |
| 372 |
main() |