| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2016, Yanis Guenane <[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_privatekey |
| 10 |
short_description: Generate OpenSSL private keys |
| 11 |
description: |
| 12 |
- This module allows one to (re)generate OpenSSL private keys. |
| 13 |
- The default mode for the private key file will be V(0600) if O(mode) is not explicitly set. |
| 14 |
- Please note that the module regenerates private keys if they do not match the module's options. In particular, if you |
| 15 |
provide another passphrase (or specify none), change the keysize, and so on, the private key will be regenerated. |
| 16 |
If you are concerned that this could B(overwrite your private key), consider using the O(backup) option. |
| 17 |
author: |
| 18 |
- Yanis Guenane (@Spredzy) |
| 19 |
- Felix Fontein (@felixfontein) |
| 20 |
extends_documentation_fragment: |
| 21 |
- ansible.builtin.files |
| 22 |
- community.crypto._attributes |
| 23 |
- community.crypto._attributes.files |
| 24 |
- community.crypto._module_privatekey |
| 25 |
attributes: |
| 26 |
check_mode: |
| 27 |
support: full |
| 28 |
safe_file_operations: |
| 29 |
support: full |
| 30 |
options: |
| 31 |
state: |
| 32 |
description: |
| 33 |
- Whether the private key should exist or not, taking action if the state is different from what is stated. |
| 34 |
type: str |
| 35 |
default: present |
| 36 |
choices: [absent, present] |
| 37 |
force: |
| 38 |
description: |
| 39 |
- Should the key be regenerated even if it already exists. |
| 40 |
type: bool |
| 41 |
default: false |
| 42 |
path: |
| 43 |
description: |
| 44 |
- Name of the file in which the generated TLS/SSL private key will be written. It will have V(0600) mode if O(mode) |
| 45 |
is not explicitly set. |
| 46 |
type: path |
| 47 |
required: true |
| 48 |
format: |
| 49 |
version_added: '1.0.0' |
| 50 |
format_mismatch: |
| 51 |
version_added: '1.0.0' |
| 52 |
backup: |
| 53 |
description: |
| 54 |
- Create a backup file including a timestamp so you can get the original private key back if you overwrote it with a |
| 55 |
new one by accident. |
| 56 |
type: bool |
| 57 |
default: false |
| 58 |
return_content: |
| 59 |
description: |
| 60 |
- If set to V(true), will return the (current or generated) private key's content as RV(privatekey). |
| 61 |
- Note that especially if the private key is not encrypted, you have to make sure that the returned value is treated |
| 62 |
appropriately and not accidentally written to logs, and so on! Use with care! |
| 63 |
- Use Ansible's C(no_log) task option to avoid the output being shown. See also |
| 64 |
U(https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-keep-secret-data-in-my-playbook). |
| 65 |
type: bool |
| 66 |
default: false |
| 67 |
version_added: '1.0.0' |
| 68 |
regenerate: |
| 69 |
version_added: '1.0.0' |
| 70 |
seealso: |
| 71 |
- module: community.crypto.openssl_privatekey_pipe |
| 72 |
- module: community.crypto.openssl_privatekey_info |
| 73 |
""" |
| 74 |
|
| 75 |
EXAMPLES = r""" |
| 76 |
--- |
| 77 |
- name: Generate an OpenSSL private key with the default values (4096 bits, RSA) |
| 78 |
community.crypto.openssl_privatekey: |
| 79 |
path: /etc/ssl/private/ansible.com.pem |
| 80 |
|
| 81 |
- name: Generate an OpenSSL private key with the default values (4096 bits, RSA) and a passphrase |
| 82 |
community.crypto.openssl_privatekey: |
| 83 |
path: /etc/ssl/private/ansible.com.pem |
| 84 |
passphrase: ansible |
| 85 |
cipher: auto |
| 86 |
|
| 87 |
- name: Generate an OpenSSL private key with a different size (2048 bits) |
| 88 |
community.crypto.openssl_privatekey: |
| 89 |
path: /etc/ssl/private/ansible.com.pem |
| 90 |
size: 2048 |
| 91 |
|
| 92 |
- name: Force regenerate an OpenSSL private key if it already exists |
| 93 |
community.crypto.openssl_privatekey: |
| 94 |
path: /etc/ssl/private/ansible.com.pem |
| 95 |
force: true |
| 96 |
|
| 97 |
- name: Generate an OpenSSL private key with a different algorithm (DSA) |
| 98 |
community.crypto.openssl_privatekey: |
| 99 |
path: /etc/ssl/private/ansible.com.pem |
| 100 |
type: DSA |
| 101 |
|
| 102 |
- name: Generate an OpenSSL private key with elliptic curve cryptography (ECC) |
| 103 |
community.crypto.openssl_privatekey: |
| 104 |
path: /etc/ssl/private/ansible.com.pem |
| 105 |
type: ECC |
| 106 |
curve: secp256r1 |
| 107 |
""" |
| 108 |
|
| 109 |
RETURN = r""" |
| 110 |
size: |
| 111 |
description: Size (in bits) of the TLS/SSL private key. |
| 112 |
returned: changed or success |
| 113 |
type: int |
| 114 |
sample: 4096 |
| 115 |
type: |
| 116 |
description: Algorithm used to generate the TLS/SSL private key. |
| 117 |
returned: changed or success |
| 118 |
type: str |
| 119 |
sample: RSA |
| 120 |
curve: |
| 121 |
description: Elliptic curve used to generate the TLS/SSL private key. |
| 122 |
returned: changed or success, and O(type) is V(ECC) |
| 123 |
type: str |
| 124 |
sample: secp256r1 |
| 125 |
filename: |
| 126 |
description: Path to the generated TLS/SSL private key file. |
| 127 |
returned: changed or success |
| 128 |
type: str |
| 129 |
sample: /etc/ssl/private/ansible.com.pem |
| 130 |
fingerprint: |
| 131 |
description: |
| 132 |
- The fingerprint of the public key. Fingerprint will be generated for each C(hashlib.algorithms) available. |
| 133 |
returned: changed or success |
| 134 |
type: dict |
| 135 |
sample: |
| 136 |
md5: "84:75:71:72:8d:04:b5:6c:4d:37:6d:66:83:f5:4c:29" |
| 137 |
sha1: "51:cc:7c:68:5d:eb:41:43:88:7e:1a:ae:c7:f8:24:72:ee:71:f6:10" |
| 138 |
sha224: "b1:19:a6:6c:14:ac:33:1d:ed:18:50:d3:06:5c:b2:32:91:f1:f1:52:8c:cb:d5:75:e9:f5:9b:46" |
| 139 |
sha256: "41:ab:c7:cb:d5:5f:30:60:46:99:ac:d4:00:70:cf:a1:76:4f:24:5d:10:24:57:5d:51:6e:09:97:df:2f:de:c7" |
| 140 |
sha384: "85:39:50:4e:de:d9:19:33:40:70:ae:10:ab:59:24:19:51:c3:a2:e4:0b:1c:b1:6e:dd:b3:0c:d9:9e:6a:46:af:da:18:f8:ef:ae:2e:c0:9a:75:2c:9b:b3:0f:3a:5f:3d" |
| 141 |
sha512: "fd:ed:5e:39:48:5f:9f:fe:7f:25:06:3f:79:08:cd:ee:a5:e7:b3:3d:13:82:87:1f:84:e1:f5:c7:28:77:53:94:86:56:38:69:f0:d9:35:22:01:1e:a6:60:...:0f:9b" |
| 142 |
backup_file: |
| 143 |
description: Name of backup file created. |
| 144 |
returned: changed and if O(backup) is V(true) |
| 145 |
type: str |
| 146 |
sample: /path/to/privatekey.pem.2019-03-09@11:22~ |
| 147 |
privatekey: |
| 148 |
description: |
| 149 |
- The (current or generated) private key's content. |
| 150 |
- Will be Base64-encoded if the key is in raw format. |
| 151 |
returned: if O(state) is V(present) and O(return_content) is V(true) |
| 152 |
type: str |
| 153 |
version_added: '1.0.0' |
| 154 |
""" |
| 155 |
|
| 156 |
import os |
| 157 |
import typing as t |
| 158 |
|
| 159 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import ( |
| 160 |
OpenSSLObjectError, |
| 161 |
) |
| 162 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey import ( |
| 163 |
get_privatekey_argument_spec, |
| 164 |
select_backend, |
| 165 |
) |
| 166 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.support import ( |
| 167 |
OpenSSLObject, |
| 168 |
) |
| 169 |
from ansible_collections.community.crypto.plugins.module_utils._io import ( |
| 170 |
load_file_if_exists, |
| 171 |
write_file, |
| 172 |
) |
| 173 |
|
| 174 |
if t.TYPE_CHECKING: |
| 175 |
from ansible.module_utils.basic import AnsibleModule # pragma: no cover |
| 176 |
|
| 177 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey import ( # pragma: no cover |
| 178 |
PrivateKeyBackend, |
| 179 |
) |
| 180 |
|
| 181 |
|
| 182 |
class PrivateKeyModule(OpenSSLObject): |
| 183 |
def __init__( |
| 184 |
self, module: AnsibleModule, module_backend: PrivateKeyBackend |
| 185 |
) -> None: |
| 186 |
super().__init__( |
| 187 |
path=module.params["path"], |
| 188 |
state=module.params["state"], |
| 189 |
force=module.params["force"], |
| 190 |
check_mode=module.check_mode, |
| 191 |
) |
| 192 |
self.module_backend = module_backend |
| 193 |
self.return_content: bool = module.params["return_content"] |
| 194 |
if self.force: |
| 195 |
module_backend.regenerate = "always" |
| 196 |
|
| 197 |
self.backup: str | None = module.params["backup"] |
| 198 |
self.backup_file: str | None = None |
| 199 |
|
| 200 |
if module.params["mode"] is None: |
| 201 |
module.params["mode"] = "0600" |
| 202 |
|
| 203 |
module_backend.set_existing( |
| 204 |
privatekey_bytes=load_file_if_exists(path=self.path, module=module) |
| 205 |
) |
| 206 |
|
| 207 |
def generate(self, module: AnsibleModule) -> None: |
| 208 |
"""Generate a keypair.""" |
| 209 |
|
| 210 |
if self.module_backend.needs_regeneration(): |
| 211 |
# Regenerate |
| 212 |
if not self.check_mode: |
| 213 |
if self.backup: |
| 214 |
self.backup_file = module.backup_local(self.path) |
| 215 |
self.module_backend.generate_private_key() |
| 216 |
privatekey_data = self.module_backend.get_private_key_data() |
| 217 |
write_file(module=module, content=privatekey_data, default_mode=0o600) |
| 218 |
self.changed = True |
| 219 |
elif self.module_backend.needs_conversion(): |
| 220 |
# Convert |
| 221 |
if not self.check_mode: |
| 222 |
if self.backup: |
| 223 |
self.backup_file = module.backup_local(self.path) |
| 224 |
self.module_backend.convert_private_key() |
| 225 |
privatekey_data = self.module_backend.get_private_key_data() |
| 226 |
write_file(module=module, content=privatekey_data, default_mode=0o600) |
| 227 |
self.changed = True |
| 228 |
|
| 229 |
file_args = module.load_file_common_arguments(module.params) |
| 230 |
if module.check_file_absent_if_check_mode(file_args["path"]): |
| 231 |
self.changed = True |
| 232 |
else: |
| 233 |
self.changed = module.set_fs_attributes_if_different( |
| 234 |
file_args, self.changed |
| 235 |
) |
| 236 |
|
| 237 |
def remove(self, module: AnsibleModule) -> None: |
| 238 |
self.module_backend.set_existing(privatekey_bytes=None) |
| 239 |
if self.backup and not self.check_mode: |
| 240 |
self.backup_file = module.backup_local(self.path) |
| 241 |
super().remove(module) |
| 242 |
|
| 243 |
def dump(self) -> dict[str, t.Any]: |
| 244 |
"""Serialize the object into a dictionary.""" |
| 245 |
|
| 246 |
result = self.module_backend.dump(include_key=self.return_content) |
| 247 |
result["filename"] = self.path |
| 248 |
result["changed"] = self.changed |
| 249 |
if self.backup_file: |
| 250 |
result["backup_file"] = self.backup_file |
| 251 |
|
| 252 |
return result |
| 253 |
|
| 254 |
|
| 255 |
def main() -> t.NoReturn: |
| 256 |
argument_spec = get_privatekey_argument_spec() |
| 257 |
argument_spec.argument_spec.update( |
| 258 |
{ |
| 259 |
"state": { |
| 260 |
"type": "str", |
| 261 |
"default": "present", |
| 262 |
"choices": ["present", "absent"], |
| 263 |
}, |
| 264 |
"force": {"type": "bool", "default": False}, |
| 265 |
"path": {"type": "path", "required": True}, |
| 266 |
"backup": {"type": "bool", "default": False}, |
| 267 |
"return_content": {"type": "bool", "default": False}, |
| 268 |
} |
| 269 |
) |
| 270 |
module = argument_spec.create_ansible_module( |
| 271 |
supports_check_mode=True, |
| 272 |
add_file_common_args=True, |
| 273 |
) |
| 274 |
|
| 275 |
base_dir = os.path.dirname(module.params["path"]) or "." |
| 276 |
if not os.path.isdir(base_dir): |
| 277 |
module.fail_json( |
| 278 |
name=base_dir, |
| 279 |
msg=f"The directory {base_dir} does not exist or the file is not a directory", |
| 280 |
) |
| 281 |
|
| 282 |
module_backend = select_backend(module=module) |
| 283 |
|
| 284 |
try: |
| 285 |
private_key = PrivateKeyModule(module, module_backend) |
| 286 |
|
| 287 |
if private_key.state == "present": |
| 288 |
private_key.generate(module) |
| 289 |
else: |
| 290 |
private_key.remove(module) |
| 291 |
|
| 292 |
result = private_key.dump() |
| 293 |
module.exit_json(**result) |
| 294 |
except OpenSSLObjectError as exc: |
| 295 |
module.fail_json(msg=str(exc)) |
| 296 |
|
| 297 |
|
| 298 |
if __name__ == "__main__": |
| 299 |
main() |