| 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_publickey |
| 10 |
short_description: Generate an OpenSSL public key from its private key |
| 11 |
description: |
| 12 |
- This module allows one to (re)generate public keys from their private keys. |
| 13 |
- Public keys are generated in PEM or OpenSSH format. Private keys must be OpenSSL PEM keys. B(OpenSSH private keys are |
| 14 |
not supported), use the M(community.crypto.openssh_keypair) module to manage these. |
| 15 |
- The module uses the cryptography Python library. |
| 16 |
author: |
| 17 |
- Yanis Guenane (@Spredzy) |
| 18 |
- Felix Fontein (@felixfontein) |
| 19 |
extends_documentation_fragment: |
| 20 |
- ansible.builtin.files |
| 21 |
- community.crypto._attributes |
| 22 |
- community.crypto._attributes.files |
| 23 |
- community.crypto._cryptography_dep.minimum |
| 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 |
options: |
| 36 |
state: |
| 37 |
description: |
| 38 |
- Whether the public key should exist or not, taking action if the state is different from what is stated. |
| 39 |
type: str |
| 40 |
default: present |
| 41 |
choices: [absent, present] |
| 42 |
force: |
| 43 |
description: |
| 44 |
- Should the key be regenerated even it it already exists. |
| 45 |
type: bool |
| 46 |
default: false |
| 47 |
format: |
| 48 |
description: |
| 49 |
- The format of the public key. |
| 50 |
type: str |
| 51 |
default: PEM |
| 52 |
choices: [OpenSSH, PEM] |
| 53 |
path: |
| 54 |
description: |
| 55 |
- Name of the file in which the generated TLS/SSL public key will be written. |
| 56 |
type: path |
| 57 |
required: true |
| 58 |
privatekey_path: |
| 59 |
description: |
| 60 |
- Path to the TLS/SSL private key from which to generate the public key. |
| 61 |
- Either O(privatekey_path) or O(privatekey_content) must be specified, but not both. If O(state) is V(present), one |
| 62 |
of them is required. |
| 63 |
type: path |
| 64 |
privatekey_content: |
| 65 |
description: |
| 66 |
- The content of the TLS/SSL private key from which to generate the public key. |
| 67 |
- Either O(privatekey_path) or O(privatekey_content) must be specified, but not both. If O(state) is V(present), one |
| 68 |
of them is required. |
| 69 |
type: str |
| 70 |
version_added: '1.0.0' |
| 71 |
privatekey_passphrase: |
| 72 |
description: |
| 73 |
- The passphrase for the private key. |
| 74 |
type: str |
| 75 |
backup: |
| 76 |
description: |
| 77 |
- Create a backup file including a timestamp so you can get the original public key back if you overwrote it with a |
| 78 |
different one by accident. |
| 79 |
type: bool |
| 80 |
default: false |
| 81 |
select_crypto_backend: |
| 82 |
description: |
| 83 |
- Determines which crypto backend to use. |
| 84 |
- The default choice is V(auto), which tries to use C(cryptography) if available. |
| 85 |
- If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library. |
| 86 |
- Note that with community.crypto 3.0.0, all values behave the same. |
| 87 |
This option will be deprecated in a later version. |
| 88 |
We recommend to not set it explicitly. |
| 89 |
type: str |
| 90 |
default: auto |
| 91 |
choices: [auto, cryptography] |
| 92 |
return_content: |
| 93 |
description: |
| 94 |
- If set to V(true), will return the (current or generated) public key's content as RV(publickey). |
| 95 |
type: bool |
| 96 |
default: false |
| 97 |
version_added: '1.0.0' |
| 98 |
seealso: |
| 99 |
- module: community.crypto.x509_certificate |
| 100 |
- module: community.crypto.x509_certificate_pipe |
| 101 |
- module: community.crypto.openssl_csr |
| 102 |
- module: community.crypto.openssl_csr_pipe |
| 103 |
- module: community.crypto.openssl_dhparam |
| 104 |
- module: community.crypto.openssl_pkcs12 |
| 105 |
- module: community.crypto.openssl_privatekey |
| 106 |
- module: community.crypto.openssl_privatekey_pipe |
| 107 |
""" |
| 108 |
|
| 109 |
EXAMPLES = r""" |
| 110 |
--- |
| 111 |
- name: Generate an OpenSSL public key in PEM format |
| 112 |
community.crypto.openssl_publickey: |
| 113 |
path: /etc/ssl/public/ansible.com.pem |
| 114 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 115 |
|
| 116 |
- name: Generate an OpenSSL public key in PEM format from an inline key |
| 117 |
community.crypto.openssl_publickey: |
| 118 |
path: /etc/ssl/public/ansible.com.pem |
| 119 |
privatekey_content: "{{ private_key_content }}" |
| 120 |
|
| 121 |
- name: Generate an OpenSSL public key in OpenSSH v2 format |
| 122 |
community.crypto.openssl_publickey: |
| 123 |
path: /etc/ssl/public/ansible.com.pem |
| 124 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 125 |
format: OpenSSH |
| 126 |
|
| 127 |
- name: Generate an OpenSSL public key with a passphrase protected private key |
| 128 |
community.crypto.openssl_publickey: |
| 129 |
path: /etc/ssl/public/ansible.com.pem |
| 130 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 131 |
privatekey_passphrase: ansible |
| 132 |
|
| 133 |
- name: Force regenerate an OpenSSL public key if it already exists |
| 134 |
community.crypto.openssl_publickey: |
| 135 |
path: /etc/ssl/public/ansible.com.pem |
| 136 |
privatekey_path: /etc/ssl/private/ansible.com.pem |
| 137 |
force: true |
| 138 |
|
| 139 |
- name: Remove an OpenSSL public key |
| 140 |
community.crypto.openssl_publickey: |
| 141 |
path: /etc/ssl/public/ansible.com.pem |
| 142 |
state: absent |
| 143 |
""" |
| 144 |
|
| 145 |
RETURN = r""" |
| 146 |
privatekey: |
| 147 |
description: |
| 148 |
- Path to the TLS/SSL private key the public key was generated from. |
| 149 |
- Will be V(none) if the private key has been provided in O(privatekey_content). |
| 150 |
returned: changed or success |
| 151 |
type: str |
| 152 |
sample: /etc/ssl/private/ansible.com.pem |
| 153 |
format: |
| 154 |
description: The format of the public key (PEM, OpenSSH, ...). |
| 155 |
returned: changed or success |
| 156 |
type: str |
| 157 |
sample: PEM |
| 158 |
filename: |
| 159 |
description: Path to the generated TLS/SSL public key file. |
| 160 |
returned: changed or success |
| 161 |
type: str |
| 162 |
sample: /etc/ssl/public/ansible.com.pem |
| 163 |
fingerprint: |
| 164 |
description: |
| 165 |
- The fingerprint of the public key. Fingerprint will be generated for each hashlib.algorithms available. |
| 166 |
returned: changed or success |
| 167 |
type: dict |
| 168 |
sample: |
| 169 |
md5: "84:75:71:72:8d:04:b5:6c:4d:37:6d:66:83:f5:4c:29" |
| 170 |
sha1: "51:cc:7c:68:5d:eb:41:43:88:7e:1a:ae:c7:f8:24:72:ee:71:f6:10" |
| 171 |
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" |
| 172 |
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" |
| 173 |
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" |
| 174 |
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" |
| 175 |
backup_file: |
| 176 |
description: Name of backup file created. |
| 177 |
returned: changed and if O(backup) is V(true) |
| 178 |
type: str |
| 179 |
sample: /path/to/publickey.pem.2019-03-09@11:22~ |
| 180 |
publickey: |
| 181 |
description: The (current or generated) public key's content. |
| 182 |
returned: if O(state) is V(present) and O(return_content) is V(true) |
| 183 |
type: str |
| 184 |
version_added: '1.0.0' |
| 185 |
""" |
| 186 |
|
| 187 |
import os |
| 188 |
import typing as t |
| 189 |
|
| 190 |
from ansible.module_utils.basic import AnsibleModule |
| 191 |
|
| 192 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import ( |
| 193 |
OpenSSLBadPassphraseError, |
| 194 |
OpenSSLObjectError, |
| 195 |
) |
| 196 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.publickey_info import ( |
| 197 |
PublicKeyParseError, |
| 198 |
get_publickey_info, |
| 199 |
) |
| 200 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.support import ( |
| 201 |
OpenSSLObject, |
| 202 |
get_fingerprint, |
| 203 |
load_privatekey, |
| 204 |
) |
| 205 |
from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import ( |
| 206 |
COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION, |
| 207 |
assert_required_cryptography_version, |
| 208 |
) |
| 209 |
from ansible_collections.community.crypto.plugins.module_utils._io import ( |
| 210 |
load_file_if_exists, |
| 211 |
write_file, |
| 212 |
) |
| 213 |
|
| 214 |
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION |
| 215 |
|
| 216 |
try: |
| 217 |
from cryptography.hazmat.primitives import serialization as crypto_serialization |
| 218 |
except ImportError: |
| 219 |
pass |
| 220 |
|
| 221 |
if t.TYPE_CHECKING: |
| 222 |
from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover |
| 223 |
PrivateKeyTypes, |
| 224 |
PublicKeyTypes, |
| 225 |
) |
| 226 |
|
| 227 |
|
| 228 |
class PublicKeyError(OpenSSLObjectError): |
| 229 |
pass |
| 230 |
|
| 231 |
|
| 232 |
class PublicKey(OpenSSLObject): |
| 233 |
def __init__(self, module: AnsibleModule) -> None: |
| 234 |
super().__init__( |
| 235 |
path=module.params["path"], |
| 236 |
state=module.params["state"], |
| 237 |
force=module.params["force"], |
| 238 |
check_mode=module.check_mode, |
| 239 |
) |
| 240 |
self.module = module |
| 241 |
self.format: t.Literal["OpenSSH", "PEM"] = module.params["format"] |
| 242 |
self.privatekey_path: str | None = module.params["privatekey_path"] |
| 243 |
privatekey_content: str | None = module.params["privatekey_content"] |
| 244 |
if privatekey_content is not None: |
| 245 |
self.privatekey_content: bytes | None = privatekey_content.encode("utf-8") |
| 246 |
else: |
| 247 |
self.privatekey_content = None |
| 248 |
self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"] |
| 249 |
self.privatekey: PrivateKeyTypes | None = None |
| 250 |
self.publickey_bytes: bytes | None = None |
| 251 |
self.return_content: bool = module.params["return_content"] |
| 252 |
self.fingerprint: dict[str, str] = {} |
| 253 |
|
| 254 |
self.backup: bool = module.params["backup"] |
| 255 |
self.backup_file: str | None = None |
| 256 |
|
| 257 |
self.diff_before = self._get_info(None) |
| 258 |
self.diff_after = self._get_info(None) |
| 259 |
|
| 260 |
def _get_info(self, data: bytes | None) -> dict[str, t.Any]: |
| 261 |
if data is None: |
| 262 |
return {} |
| 263 |
result = {"can_parse_key": False} |
| 264 |
try: |
| 265 |
result.update( |
| 266 |
get_publickey_info( |
| 267 |
module=self.module, content=data, prefer_one_fingerprint=True |
| 268 |
) |
| 269 |
) |
| 270 |
result["can_parse_key"] = True |
| 271 |
except PublicKeyParseError as exc: |
| 272 |
result.update(exc.result) |
| 273 |
except Exception: |
| 274 |
pass |
| 275 |
return result |
| 276 |
|
| 277 |
def _create_publickey(self, module: AnsibleModule) -> bytes: |
| 278 |
self.privatekey = load_privatekey( |
| 279 |
path=self.privatekey_path, |
| 280 |
content=self.privatekey_content, |
| 281 |
passphrase=self.privatekey_passphrase, |
| 282 |
) |
| 283 |
if self.format == "OpenSSH": |
| 284 |
return self.privatekey.public_key().public_bytes( |
| 285 |
crypto_serialization.Encoding.OpenSSH, |
| 286 |
crypto_serialization.PublicFormat.OpenSSH, |
| 287 |
) |
| 288 |
return self.privatekey.public_key().public_bytes( |
| 289 |
crypto_serialization.Encoding.PEM, |
| 290 |
crypto_serialization.PublicFormat.SubjectPublicKeyInfo, |
| 291 |
) |
| 292 |
|
| 293 |
def generate(self, module: AnsibleModule) -> None: |
| 294 |
"""Generate the public key.""" |
| 295 |
|
| 296 |
if self.privatekey_path is not None and not os.path.exists( |
| 297 |
self.privatekey_path |
| 298 |
): |
| 299 |
raise PublicKeyError( |
| 300 |
f"The private key {self.privatekey_path} does not exist" |
| 301 |
) |
| 302 |
|
| 303 |
if not self.check(module, perms_required=False) or self.force: |
| 304 |
try: |
| 305 |
publickey_content = self._create_publickey(module) |
| 306 |
self.diff_after = self._get_info(publickey_content) |
| 307 |
if self.return_content: |
| 308 |
self.publickey_bytes = publickey_content |
| 309 |
|
| 310 |
if self.backup: |
| 311 |
self.backup_file = module.backup_local(self.path) |
| 312 |
write_file(module=module, content=publickey_content) |
| 313 |
|
| 314 |
self.changed = True |
| 315 |
except OpenSSLBadPassphraseError as exc: |
| 316 |
raise PublicKeyError(exc) from exc |
| 317 |
except (IOError, OSError) as exc: |
| 318 |
raise PublicKeyError(exc) from exc |
| 319 |
|
| 320 |
self.fingerprint = get_fingerprint( |
| 321 |
path=self.privatekey_path, |
| 322 |
content=self.privatekey_content, |
| 323 |
passphrase=self.privatekey_passphrase, |
| 324 |
) |
| 325 |
file_args = module.load_file_common_arguments(module.params) |
| 326 |
if module.check_file_absent_if_check_mode( |
| 327 |
file_args["path"] |
| 328 |
) or module.set_fs_attributes_if_different(file_args, False): |
| 329 |
self.changed = True |
| 330 |
|
| 331 |
def check(self, module: AnsibleModule, *, perms_required: bool = True) -> bool: |
| 332 |
"""Ensure the resource is in its desired state.""" |
| 333 |
|
| 334 |
state_and_perms = super().check(module=module, perms_required=perms_required) |
| 335 |
|
| 336 |
def _check_privatekey() -> bool: |
| 337 |
if self.privatekey_path is not None and not os.path.exists( |
| 338 |
self.privatekey_path |
| 339 |
): |
| 340 |
return False |
| 341 |
|
| 342 |
current_publickey: PublicKeyTypes |
| 343 |
try: |
| 344 |
with open(self.path, "rb") as public_key_fh: |
| 345 |
publickey_content = public_key_fh.read() |
| 346 |
self.diff_before = self.diff_after = self._get_info(publickey_content) |
| 347 |
if self.return_content: |
| 348 |
self.publickey_bytes = publickey_content |
| 349 |
if self.format == "OpenSSH": |
| 350 |
# Read and dump public key. Makes sure that the comment is stripped off. |
| 351 |
current_publickey = crypto_serialization.load_ssh_public_key( |
| 352 |
publickey_content |
| 353 |
) |
| 354 |
publickey_content = current_publickey.public_bytes( |
| 355 |
crypto_serialization.Encoding.OpenSSH, |
| 356 |
crypto_serialization.PublicFormat.OpenSSH, |
| 357 |
) |
| 358 |
else: |
| 359 |
current_publickey = crypto_serialization.load_pem_public_key( |
| 360 |
publickey_content |
| 361 |
) |
| 362 |
publickey_content = current_publickey.public_bytes( |
| 363 |
crypto_serialization.Encoding.PEM, |
| 364 |
crypto_serialization.PublicFormat.SubjectPublicKeyInfo, |
| 365 |
) |
| 366 |
except Exception: |
| 367 |
return False |
| 368 |
|
| 369 |
try: |
| 370 |
desired_publickey = self._create_publickey(module) |
| 371 |
except OpenSSLBadPassphraseError as exc: |
| 372 |
raise PublicKeyError(exc) from exc |
| 373 |
|
| 374 |
return publickey_content == desired_publickey |
| 375 |
|
| 376 |
if not state_and_perms: |
| 377 |
return state_and_perms |
| 378 |
|
| 379 |
return _check_privatekey() |
| 380 |
|
| 381 |
def remove(self, module: AnsibleModule) -> None: |
| 382 |
if self.backup: |
| 383 |
self.backup_file = module.backup_local(self.path) |
| 384 |
super().remove(module) |
| 385 |
|
| 386 |
def dump(self) -> dict[str, t.Any]: |
| 387 |
"""Serialize the object into a dictionary.""" |
| 388 |
|
| 389 |
result: dict[str, t.Any] = { |
| 390 |
"privatekey": self.privatekey_path, |
| 391 |
"filename": self.path, |
| 392 |
"format": self.format, |
| 393 |
"changed": self.changed, |
| 394 |
"fingerprint": self.fingerprint, |
| 395 |
} |
| 396 |
if self.backup_file: |
| 397 |
result["backup_file"] = self.backup_file |
| 398 |
if self.return_content: |
| 399 |
if self.publickey_bytes is None: |
| 400 |
self.publickey_bytes = load_file_if_exists( |
| 401 |
path=self.path, ignore_errors=True |
| 402 |
) |
| 403 |
result["publickey"] = ( |
| 404 |
self.publickey_bytes.decode("utf-8") if self.publickey_bytes else None |
| 405 |
) |
| 406 |
|
| 407 |
result["diff"] = { |
| 408 |
"before": self.diff_before, |
| 409 |
"after": self.diff_after, |
| 410 |
} |
| 411 |
|
| 412 |
return result |
| 413 |
|
| 414 |
|
| 415 |
def main() -> t.NoReturn: |
| 416 |
module = AnsibleModule( |
| 417 |
argument_spec={ |
| 418 |
"state": { |
| 419 |
"type": "str", |
| 420 |
"default": "present", |
| 421 |
"choices": ["present", "absent"], |
| 422 |
}, |
| 423 |
"force": {"type": "bool", "default": False}, |
| 424 |
"path": {"type": "path", "required": True}, |
| 425 |
"privatekey_path": {"type": "path"}, |
| 426 |
"privatekey_content": {"type": "str", "no_log": True}, |
| 427 |
"format": {"type": "str", "default": "PEM", "choices": ["OpenSSH", "PEM"]}, |
| 428 |
"privatekey_passphrase": {"type": "str", "no_log": True}, |
| 429 |
"backup": {"type": "bool", "default": False}, |
| 430 |
"select_crypto_backend": { |
| 431 |
"type": "str", |
| 432 |
"choices": ["auto", "cryptography"], |
| 433 |
"default": "auto", |
| 434 |
}, |
| 435 |
"return_content": {"type": "bool", "default": False}, |
| 436 |
}, |
| 437 |
supports_check_mode=True, |
| 438 |
add_file_common_args=True, |
| 439 |
required_if=[ |
| 440 |
("state", "present", ["privatekey_path", "privatekey_content"], True) |
| 441 |
], |
| 442 |
mutually_exclusive=(["privatekey_path", "privatekey_content"],), |
| 443 |
) |
| 444 |
|
| 445 |
assert_required_cryptography_version( |
| 446 |
module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION |
| 447 |
) |
| 448 |
|
| 449 |
base_dir = os.path.dirname(module.params["path"]) or "." |
| 450 |
if not os.path.isdir(base_dir): |
| 451 |
module.fail_json( |
| 452 |
name=base_dir, |
| 453 |
msg=f"The directory '{base_dir}' does not exist or the file is not a directory", |
| 454 |
) |
| 455 |
|
| 456 |
try: |
| 457 |
public_key = PublicKey(module) |
| 458 |
|
| 459 |
if public_key.state == "present": |
| 460 |
if module.check_mode: |
| 461 |
result = public_key.dump() |
| 462 |
result["changed"] = module.params["force"] or not public_key.check( |
| 463 |
module |
| 464 |
) |
| 465 |
module.exit_json(**result) |
| 466 |
|
| 467 |
public_key.generate(module) |
| 468 |
else: |
| 469 |
if module.check_mode: |
| 470 |
result = public_key.dump() |
| 471 |
result["changed"] = os.path.exists(module.params["path"]) |
| 472 |
module.exit_json(**result) |
| 473 |
|
| 474 |
public_key.remove(module) |
| 475 |
|
| 476 |
result = public_key.dump() |
| 477 |
module.exit_json(**result) |
| 478 |
except OpenSSLObjectError as exc: |
| 479 |
module.fail_json(msg=str(exc)) |
| 480 |
|
| 481 |
|
| 482 |
if __name__ == "__main__": |
| 483 |
main() |