| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2018, David Kainz <[email protected]> <[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: openssh_cert |
| 10 |
author: "David Kainz (@lolcube)" |
| 11 |
short_description: Generate OpenSSH host or user certificates |
| 12 |
description: |
| 13 |
- Generate and regenerate OpenSSH host or user certificates. |
| 14 |
requirements: |
| 15 |
- "ssh-keygen" |
| 16 |
extends_documentation_fragment: |
| 17 |
- ansible.builtin.files |
| 18 |
- community.crypto._attributes |
| 19 |
- community.crypto._attributes.files |
| 20 |
attributes: |
| 21 |
check_mode: |
| 22 |
support: full |
| 23 |
diff_mode: |
| 24 |
support: full |
| 25 |
safe_file_operations: |
| 26 |
support: full |
| 27 |
idempotent: |
| 28 |
support: partial |
| 29 |
details: |
| 30 |
- The module is not idempotent if O(force=true) or O(regenerate=always). |
| 31 |
- If relative timestamps are used and O(ignore_timestamps=false) (default), the module is not idempotent. |
| 32 |
options: |
| 33 |
state: |
| 34 |
description: |
| 35 |
- Whether the host or user certificate should exist or not, taking action if the state is different from what is stated. |
| 36 |
type: str |
| 37 |
default: "present" |
| 38 |
choices: ['present', 'absent'] |
| 39 |
type: |
| 40 |
description: |
| 41 |
- Whether the module should generate a host or a user certificate. |
| 42 |
- Required if O(state) is V(present). |
| 43 |
type: str |
| 44 |
choices: ['host', 'user'] |
| 45 |
force: |
| 46 |
description: |
| 47 |
- Should the certificate be regenerated even if it already exists and is valid. |
| 48 |
- Equivalent to O(regenerate=always). |
| 49 |
type: bool |
| 50 |
default: false |
| 51 |
path: |
| 52 |
description: |
| 53 |
- Path of the file containing the certificate. |
| 54 |
type: path |
| 55 |
required: true |
| 56 |
regenerate: |
| 57 |
description: |
| 58 |
- When V(never) the task will fail if a certificate already exists at O(path) and is unreadable otherwise a new certificate |
| 59 |
will only be generated if there is no existing certificate. |
| 60 |
- When V(fail) the task will fail if a certificate already exists at O(path) and does not match the module's options. |
| 61 |
- When V(partial_idempotence) an existing certificate will be regenerated based on O(serial_number), O(signature_algorithm), |
| 62 |
O(type), O(valid_from), O(valid_to), O(valid_at), and O(principals). O(valid_from) and O(valid_to) can be excluded |
| 63 |
by O(ignore_timestamps=true). |
| 64 |
- When V(full_idempotence) O(identifier), O(options), O(public_key), and O(signing_key) are also considered when compared |
| 65 |
against an existing certificate. |
| 66 |
- V(always) is equivalent to O(force=true). |
| 67 |
type: str |
| 68 |
choices: |
| 69 |
- never |
| 70 |
- fail |
| 71 |
- partial_idempotence |
| 72 |
- full_idempotence |
| 73 |
- always |
| 74 |
default: partial_idempotence |
| 75 |
version_added: 1.8.0 |
| 76 |
signature_algorithm: |
| 77 |
description: |
| 78 |
- As of OpenSSH 8.2 the SHA-1 signature algorithm for RSA keys has been disabled and C(ssh) will refuse host certificates |
| 79 |
signed with the SHA-1 algorithm. OpenSSH 8.1 made V(rsa-sha2-512) the default algorithm when acting as a CA and signing |
| 80 |
certificates with a RSA key. However, for OpenSSH versions less than 8.1 the SHA-2 signature algorithms, V(rsa-sha2-256) |
| 81 |
or V(rsa-sha2-512), must be specified using this option if compatibility with newer C(ssh) clients is required. Conversely |
| 82 |
if hosts using OpenSSH version 8.2 or greater must remain compatible with C(ssh) clients using OpenSSH less than 7.2, |
| 83 |
then V(ssh-rsa) can be used when generating host certificates (a corresponding change to the sshd_config to add V(ssh-rsa) |
| 84 |
to the C(CASignatureAlgorithms) keyword is also required). |
| 85 |
- Using any value for this option with a non-RSA O(signing_key) will cause this module to fail. |
| 86 |
- 'Note: OpenSSH versions prior to 7.2 do not support SHA-2 signature algorithms for RSA keys and OpenSSH versions prior |
| 87 |
to 7.3 do not support SHA-2 signature algorithms for certificates.' |
| 88 |
- See U(https://www.openssh.com/txt/release-8.2) for more information. |
| 89 |
type: str |
| 90 |
choices: |
| 91 |
- ssh-rsa |
| 92 |
- rsa-sha2-256 |
| 93 |
- rsa-sha2-512 |
| 94 |
version_added: 1.10.0 |
| 95 |
signing_key: |
| 96 |
description: |
| 97 |
- The path to the private openssh key that is used for signing the public key in order to generate the certificate. |
| 98 |
- If the private key is on a PKCS#11 token (O(pkcs11_provider)), set this to the path to the public key instead. |
| 99 |
- Required if O(state) is V(present). |
| 100 |
type: path |
| 101 |
pkcs11_provider: |
| 102 |
description: |
| 103 |
- To use a signing key that resides on a PKCS#11 token, set this to the name (or full path) of the shared library to |
| 104 |
use with the token. Usually C(libpkcs11.so). |
| 105 |
- If this is set, O(signing_key) needs to point to a file containing the public key of the CA. |
| 106 |
type: str |
| 107 |
version_added: 1.1.0 |
| 108 |
use_agent: |
| 109 |
description: |
| 110 |
- Should the ssh-keygen use a CA key residing in a ssh-agent. |
| 111 |
type: bool |
| 112 |
default: false |
| 113 |
version_added: 1.3.0 |
| 114 |
public_key: |
| 115 |
description: |
| 116 |
- The path to the public key that will be signed with the signing key in order to generate the certificate. |
| 117 |
- Required if O(state) is V(present). |
| 118 |
type: path |
| 119 |
valid_from: |
| 120 |
description: |
| 121 |
- 'The point in time the certificate is valid from. Time can be specified either as relative time or as absolute timestamp. |
| 122 |
Time will always be interpreted as UTC. Valid formats are: C([+-]timespec | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS | YYYY-MM-DD |
| 123 |
HH:MM:SS | always) where timespec can be an integer + C([w | d | h | m | s]) (for example V(+32w1d2h)). Note that |
| 124 |
if using relative time this module is NOT idempotent.' |
| 125 |
- The value V(always) is only supported for OpenSSH 7.7 and greater, however, the value V(1970-01-01T00:00:01) can be |
| 126 |
used with earlier versions as an equivalent expression. |
| 127 |
- To ignore this value during comparison with an existing certificate set O(ignore_timestamps=true). |
| 128 |
- Required if O(state) is V(present). |
| 129 |
type: str |
| 130 |
valid_to: |
| 131 |
description: |
| 132 |
- 'The point in time the certificate is valid to. Time can be specified either as relative time or as absolute timestamp. |
| 133 |
Time will always be interpreted as UTC. Valid formats are: C([+-]timespec | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS | YYYY-MM-DD |
| 134 |
HH:MM:SS | forever) where timespec can be an integer + C([w | d | h | m | s]) (for example V(+32w1d2h)). Note that |
| 135 |
if using relative time this module is NOT idempotent.' |
| 136 |
- To ignore this value during comparison with an existing certificate set O(ignore_timestamps=true). |
| 137 |
- Required if O(state) is V(present). |
| 138 |
type: str |
| 139 |
valid_at: |
| 140 |
description: |
| 141 |
- Check if the certificate is valid at a certain point in time. If it is not the certificate will be regenerated. Time |
| 142 |
will always be interpreted as UTC. Mainly to be used with relative timespec for O(valid_from) and / or O(valid_to). |
| 143 |
Note that if using relative time this module is NOT idempotent. |
| 144 |
type: str |
| 145 |
ignore_timestamps: |
| 146 |
description: |
| 147 |
- Whether the O(valid_from) and O(valid_to) timestamps should be ignored for idempotency checks. |
| 148 |
- However, the values will still be applied to a new certificate if it meets any other necessary conditions for generation/regeneration. |
| 149 |
type: bool |
| 150 |
default: false |
| 151 |
version_added: 2.2.0 |
| 152 |
principals: |
| 153 |
description: |
| 154 |
- Certificates may be limited to be valid for a set of principal (user/host) names. By default, generated certificates |
| 155 |
are valid for all users or hosts. |
| 156 |
type: list |
| 157 |
elements: str |
| 158 |
options: |
| 159 |
description: |
| 160 |
- 'Specify certificate options when signing a key. The option that are valid for user certificates are:' |
| 161 |
- 'V(clear): Clear all enabled permissions. This is useful for clearing the default set of permissions so permissions |
| 162 |
may be added individually.' |
| 163 |
- 'V(force-command=command): Forces the execution of command instead of any shell or command specified by the user when |
| 164 |
the certificate is used for authentication.' |
| 165 |
- 'V(no-agent-forwarding): Disable ssh-agent forwarding (permitted by default).' |
| 166 |
- 'V(no-port-forwarding): Disable port forwarding (permitted by default).' |
| 167 |
- 'V(no-pty): Disable PTY allocation (permitted by default).' |
| 168 |
- 'V(no-user-rc): Disable execution of C(~/.ssh/rc) by sshd (permitted by default).' |
| 169 |
- 'V(no-x11-forwarding): Disable X11 forwarding (permitted by default).' |
| 170 |
- 'V(permit-agent-forwarding): Allows ssh-agent forwarding.' |
| 171 |
- 'V(permit-port-forwarding): Allows port forwarding.' |
| 172 |
- 'V(permit-pty): Allows PTY allocation.' |
| 173 |
- 'V(permit-user-rc): Allows execution of C(~/.ssh/rc) by sshd.' |
| 174 |
- 'V(permit-x11-forwarding): Allows X11 forwarding.' |
| 175 |
- 'V(source-address=address_list): Restrict the source addresses from which the certificate is considered valid. The |
| 176 |
C(address_list) is a comma-separated list of one or more address/netmask pairs in CIDR format.' |
| 177 |
- At present, no options are valid for host keys. |
| 178 |
type: list |
| 179 |
elements: str |
| 180 |
identifier: |
| 181 |
description: |
| 182 |
- Specify the key identity when signing a public key. The identifier that is logged by the server when the certificate |
| 183 |
is used for authentication. |
| 184 |
type: str |
| 185 |
serial_number: |
| 186 |
description: |
| 187 |
- 'Specify the certificate serial number. The serial number is logged by the server when the certificate is used for |
| 188 |
authentication. The certificate serial number may be used in a KeyRevocationList. The serial number may be omitted |
| 189 |
for checks, but must be specified again for a new certificate. Note: The default value set by ssh-keygen is 0.' |
| 190 |
- This option accepts an B(integer). If you want to provide serial numbers as colon-separated hex strings, such as C(11:22:33), |
| 191 |
you need to convert them to an integer with P(community.crypto.parse_serial#filter). |
| 192 |
type: int |
| 193 |
|
| 194 |
seealso: |
| 195 |
- plugin: community.crypto.parse_serial |
| 196 |
plugin_type: filter |
| 197 |
""" |
| 198 |
|
| 199 |
EXAMPLES = r""" |
| 200 |
--- |
| 201 |
- name: Generate an OpenSSH user certificate that is valid forever and for all users |
| 202 |
community.crypto.openssh_cert: |
| 203 |
type: user |
| 204 |
signing_key: /path/to/private_key |
| 205 |
public_key: /path/to/public_key.pub |
| 206 |
path: /path/to/certificate |
| 207 |
valid_from: always |
| 208 |
valid_to: forever |
| 209 |
|
| 210 |
# Generate an OpenSSH host certificate that is valid for 32 weeks from now and will be regenerated |
| 211 |
# if it is valid for less than 2 weeks from the time the module is being run |
| 212 |
- name: Generate an OpenSSH host certificate with valid_from, valid_to and valid_at parameters |
| 213 |
community.crypto.openssh_cert: |
| 214 |
type: host |
| 215 |
signing_key: /path/to/private_key |
| 216 |
public_key: /path/to/public_key.pub |
| 217 |
path: /path/to/certificate |
| 218 |
valid_from: +0s |
| 219 |
valid_to: +32w |
| 220 |
valid_at: +2w |
| 221 |
ignore_timestamps: true |
| 222 |
|
| 223 |
- name: Generate an OpenSSH host certificate that is valid forever and only for example.com and examplehost |
| 224 |
community.crypto.openssh_cert: |
| 225 |
type: host |
| 226 |
signing_key: /path/to/private_key |
| 227 |
public_key: /path/to/public_key.pub |
| 228 |
path: /path/to/certificate |
| 229 |
valid_from: always |
| 230 |
valid_to: forever |
| 231 |
principals: |
| 232 |
- example.com |
| 233 |
- examplehost |
| 234 |
|
| 235 |
- name: Generate an OpenSSH host Certificate that is valid from 21.1.2001 to 21.1.2019 |
| 236 |
community.crypto.openssh_cert: |
| 237 |
type: host |
| 238 |
signing_key: /path/to/private_key |
| 239 |
public_key: /path/to/public_key.pub |
| 240 |
path: /path/to/certificate |
| 241 |
valid_from: "2001-01-21" |
| 242 |
valid_to: "2019-01-21" |
| 243 |
|
| 244 |
- name: Generate an OpenSSH user Certificate with clear and force-command option |
| 245 |
community.crypto.openssh_cert: |
| 246 |
type: user |
| 247 |
signing_key: /path/to/private_key |
| 248 |
public_key: /path/to/public_key.pub |
| 249 |
path: /path/to/certificate |
| 250 |
valid_from: always |
| 251 |
valid_to: forever |
| 252 |
options: |
| 253 |
- "clear" |
| 254 |
- "force-command=/tmp/bla/foo" |
| 255 |
|
| 256 |
- name: Generate an OpenSSH user certificate using a PKCS#11 token |
| 257 |
community.crypto.openssh_cert: |
| 258 |
type: user |
| 259 |
signing_key: /path/to/ca_public_key.pub |
| 260 |
pkcs11_provider: libpkcs11.so |
| 261 |
public_key: /path/to/public_key.pub |
| 262 |
path: /path/to/certificate |
| 263 |
valid_from: always |
| 264 |
valid_to: forever |
| 265 |
""" |
| 266 |
|
| 267 |
RETURN = r""" |
| 268 |
type: |
| 269 |
description: Type of the certificate (host or user). |
| 270 |
returned: changed or success |
| 271 |
type: str |
| 272 |
sample: host |
| 273 |
filename: |
| 274 |
description: Path to the certificate. |
| 275 |
returned: changed or success |
| 276 |
type: str |
| 277 |
sample: /tmp/certificate-cert.pub |
| 278 |
info: |
| 279 |
description: Information about the certificate. Output of C(ssh-keygen -L -f). |
| 280 |
returned: change or success |
| 281 |
type: list |
| 282 |
elements: str |
| 283 |
""" |
| 284 |
|
| 285 |
import os |
| 286 |
import typing as t |
| 287 |
|
| 288 |
from ansible.module_utils.basic import AnsibleModule |
| 289 |
|
| 290 |
from ansible_collections.community.crypto.plugins.module_utils._openssh.backends.common import ( |
| 291 |
KeygenCommand, |
| 292 |
OpensshModule, |
| 293 |
PrivateKey, |
| 294 |
) |
| 295 |
from ansible_collections.community.crypto.plugins.module_utils._openssh.certificate import ( |
| 296 |
OpensshCertificate, |
| 297 |
OpensshCertificateTimeParameters, |
| 298 |
parse_option_list, |
| 299 |
) |
| 300 |
from ansible_collections.community.crypto.plugins.module_utils._version import ( |
| 301 |
LooseVersion, |
| 302 |
) |
| 303 |
|
| 304 |
|
| 305 |
class Certificate(OpensshModule): |
| 306 |
def __init__(self, module: AnsibleModule) -> None: |
| 307 |
super().__init__(module=module) |
| 308 |
self.ssh_keygen = KeygenCommand(self.module) |
| 309 |
|
| 310 |
self.identifier: str = self.module.params["identifier"] or "" |
| 311 |
self.options: list[str] = self.module.params["options"] or [] |
| 312 |
self.path: str = self.module.params["path"] |
| 313 |
self.pkcs11_provider: str | None = self.module.params["pkcs11_provider"] |
| 314 |
self.principals: list[str] = self.module.params["principals"] or [] |
| 315 |
self.public_key: str | None = self.module.params["public_key"] |
| 316 |
self.regenerate: t.Literal[ |
| 317 |
"never", |
| 318 |
"fail", |
| 319 |
"partial_idempotence", |
| 320 |
"full_idempotence", |
| 321 |
"always", |
| 322 |
] = ( |
| 323 |
self.module.params["regenerate"] |
| 324 |
if not self.module.params["force"] |
| 325 |
else "always" |
| 326 |
) |
| 327 |
self.serial_number: int | None = self.module.params["serial_number"] |
| 328 |
self.signature_algorithm: ( |
| 329 |
t.Literal["ssh-rsa", "rsa-sha2-256", "rsa-sha2-512"] | None |
| 330 |
) = self.module.params["signature_algorithm"] |
| 331 |
self.signing_key: str | None = self.module.params["signing_key"] |
| 332 |
self.state: t.Literal["absent", "present"] = self.module.params["state"] |
| 333 |
self.type: t.Literal["host", "user"] | None = self.module.params["type"] |
| 334 |
self.use_agent: bool = self.module.params["use_agent"] |
| 335 |
self.valid_at: str | None = self.module.params["valid_at"] |
| 336 |
self.ignore_timestamps: bool = self.module.params["ignore_timestamps"] |
| 337 |
|
| 338 |
self._check_if_base_dir(self.path) |
| 339 |
|
| 340 |
if self.state == "present": |
| 341 |
self._validate_parameters() |
| 342 |
|
| 343 |
self.data: OpensshCertificate | None = None |
| 344 |
self.original_data: OpensshCertificate | None = None |
| 345 |
if self._exists(): |
| 346 |
self._load_certificate() |
| 347 |
|
| 348 |
self.time_parameters: OpensshCertificateTimeParameters | None = None |
| 349 |
if self.state == "present": |
| 350 |
self._set_time_parameters() |
| 351 |
|
| 352 |
def _validate_parameters(self) -> None: |
| 353 |
for path in (self.public_key, self.signing_key): |
| 354 |
if ( |
| 355 |
path is not None |
| 356 |
): # should never be None, but the type checker doesn't know |
| 357 |
self._check_if_base_dir(path) |
| 358 |
|
| 359 |
if self.options and self.type == "host": |
| 360 |
self.module.fail_json( |
| 361 |
msg="Options can only be used with user certificates." |
| 362 |
) |
| 363 |
|
| 364 |
if self.use_agent: |
| 365 |
self._use_agent_available() |
| 366 |
|
| 367 |
def _use_agent_available(self) -> None: |
| 368 |
ssh_version = self._get_ssh_version() |
| 369 |
if not ssh_version: |
| 370 |
self.module.fail_json(msg="Failed to determine ssh version") |
| 371 |
elif LooseVersion(ssh_version) < LooseVersion("7.6"): |
| 372 |
self.module.fail_json( |
| 373 |
msg="Signing with CA key in ssh agent requires ssh 7.6 or newer." |
| 374 |
+ f" Your version is: {ssh_version}" |
| 375 |
) |
| 376 |
|
| 377 |
def _exists(self) -> bool: |
| 378 |
return os.path.exists(self.path) |
| 379 |
|
| 380 |
def _load_certificate(self) -> None: |
| 381 |
try: |
| 382 |
self.original_data = OpensshCertificate.load(self.path) |
| 383 |
except (TypeError, ValueError) as e: |
| 384 |
if self.regenerate in ("never", "fail"): |
| 385 |
self.module.fail_json(msg=f"Unable to read existing certificate: {e}") |
| 386 |
self.module.warn(f"Unable to read existing certificate: {e}") |
| 387 |
|
| 388 |
def _set_time_parameters(self) -> None: |
| 389 |
try: |
| 390 |
self.time_parameters = OpensshCertificateTimeParameters( |
| 391 |
valid_from=self.module.params["valid_from"], |
| 392 |
valid_to=self.module.params["valid_to"], |
| 393 |
) |
| 394 |
except ValueError as e: |
| 395 |
self.module.fail_json(msg=str(e)) |
| 396 |
|
| 397 |
def _execute(self) -> None: |
| 398 |
if self.state == "present": |
| 399 |
if self._should_generate(): |
| 400 |
self._generate() |
| 401 |
self._update_permissions(self.path) |
| 402 |
else: |
| 403 |
if self._exists(): |
| 404 |
self._remove() |
| 405 |
|
| 406 |
def _should_generate(self) -> bool: |
| 407 |
if self.regenerate == "never": |
| 408 |
return self.original_data is None |
| 409 |
if self.regenerate == "fail": |
| 410 |
if self.original_data and not self._is_fully_valid(): |
| 411 |
self.module.fail_json( |
| 412 |
msg="Certificate does not match the provided options.", |
| 413 |
cert=get_cert_dict(self.original_data), |
| 414 |
) |
| 415 |
return self.original_data is None |
| 416 |
if self.regenerate == "partial_idempotence": |
| 417 |
return self.original_data is None or not self._is_partially_valid() |
| 418 |
if self.regenerate == "full_idempotence": |
| 419 |
return self.original_data is None or not self._is_fully_valid() |
| 420 |
return True |
| 421 |
|
| 422 |
def _is_fully_valid(self) -> bool: |
| 423 |
if self.original_data is None: |
| 424 |
raise AssertionError( |
| 425 |
"Contract violation original_data not provided" |
| 426 |
) # pragma: no cover |
| 427 |
if self.public_key is None: |
| 428 |
raise AssertionError( |
| 429 |
"Contract violation public_key not provided" |
| 430 |
) # pragma: no cover |
| 431 |
if self.signing_key is None: |
| 432 |
raise AssertionError( |
| 433 |
"Contract violation signing_key not provided" |
| 434 |
) # pragma: no cover |
| 435 |
return self._is_partially_valid() and all( |
| 436 |
[ |
| 437 |
self._compare_options() if self.original_data.type == "user" else True, |
| 438 |
self.original_data.key_id == self.identifier, |
| 439 |
self.original_data.public_key |
| 440 |
== self._get_key_fingerprint(self.public_key), |
| 441 |
self.original_data.signing_key |
| 442 |
== self._get_key_fingerprint(self.signing_key), |
| 443 |
] |
| 444 |
) |
| 445 |
|
| 446 |
def _is_partially_valid(self) -> bool: |
| 447 |
if self.original_data is None: |
| 448 |
raise AssertionError( |
| 449 |
"Contract violation original_data not provided" |
| 450 |
) # pragma: no cover |
| 451 |
return all( |
| 452 |
[ |
| 453 |
set(self.original_data.principals) == set(self.principals), |
| 454 |
( |
| 455 |
self.original_data.signature_type == self.signature_algorithm |
| 456 |
if self.signature_algorithm |
| 457 |
else True |
| 458 |
), |
| 459 |
( |
| 460 |
self.original_data.serial == self.serial_number |
| 461 |
if self.serial_number is not None |
| 462 |
else True |
| 463 |
), |
| 464 |
self.original_data.type == self.type, |
| 465 |
self._compare_time_parameters(), |
| 466 |
] |
| 467 |
) |
| 468 |
|
| 469 |
def _compare_time_parameters(self) -> bool: |
| 470 |
if self.original_data is None: |
| 471 |
raise AssertionError( |
| 472 |
"Contract violation original_data not provided" |
| 473 |
) # pragma: no cover |
| 474 |
try: |
| 475 |
original_time_parameters = OpensshCertificateTimeParameters( |
| 476 |
valid_from=self.original_data.valid_after, |
| 477 |
valid_to=self.original_data.valid_before, |
| 478 |
) |
| 479 |
except ValueError as e: |
| 480 |
return self.module.fail_json(msg=str(e)) |
| 481 |
|
| 482 |
if self.ignore_timestamps: |
| 483 |
return original_time_parameters.within_range(self.valid_at) |
| 484 |
|
| 485 |
return all( |
| 486 |
[ |
| 487 |
original_time_parameters == self.time_parameters, |
| 488 |
original_time_parameters.within_range(self.valid_at), |
| 489 |
] |
| 490 |
) |
| 491 |
|
| 492 |
def _compare_options(self) -> bool: |
| 493 |
if self.original_data is None: |
| 494 |
raise AssertionError( |
| 495 |
"Contract violation original_data not provided" |
| 496 |
) # pragma: no cover |
| 497 |
try: |
| 498 |
critical_options, extensions = parse_option_list(self.options) |
| 499 |
except ValueError as e: |
| 500 |
return self.module.fail_json(msg=str(e)) |
| 501 |
|
| 502 |
return all( |
| 503 |
[ |
| 504 |
set(self.original_data.critical_options) == set(critical_options), |
| 505 |
set(self.original_data.extensions) == set(extensions), |
| 506 |
] |
| 507 |
) |
| 508 |
|
| 509 |
def _get_key_fingerprint(self, path: str) -> str: |
| 510 |
private_key_content = self.ssh_keygen.get_private_key( |
| 511 |
private_key_path=path, check_rc=True |
| 512 |
)[1] |
| 513 |
return PrivateKey.from_string(private_key_content).fingerprint |
| 514 |
|
| 515 |
@OpensshModule.trigger_change |
| 516 |
@OpensshModule.skip_if_check_mode |
| 517 |
def _generate(self) -> None: |
| 518 |
try: |
| 519 |
temp_certificate = self._generate_temp_certificate() |
| 520 |
self._safe_secure_move([(temp_certificate, self.path)]) |
| 521 |
except OSError as e: |
| 522 |
self.module.fail_json( |
| 523 |
msg=f"Unable to write certificate to {self.path}: {e}" |
| 524 |
) |
| 525 |
|
| 526 |
try: |
| 527 |
self.data = OpensshCertificate.load(self.path) |
| 528 |
except (TypeError, ValueError) as e: |
| 529 |
self.module.fail_json(msg=f"Unable to read new certificate: {e}") |
| 530 |
|
| 531 |
def _generate_temp_certificate(self) -> str: |
| 532 |
if self.public_key is None: |
| 533 |
raise AssertionError( |
| 534 |
"Contract violation public_key not provided" |
| 535 |
) # pragma: no cover |
| 536 |
if self.signing_key is None: |
| 537 |
raise AssertionError( |
| 538 |
"Contract violation signing_key not provided" |
| 539 |
) # pragma: no cover |
| 540 |
if self.time_parameters is None: |
| 541 |
raise AssertionError( |
| 542 |
"Contract violation time_parameters not provided" |
| 543 |
) # pragma: no cover |
| 544 |
|
| 545 |
key_copy = os.path.join(self.module.tmpdir, os.path.basename(self.public_key)) |
| 546 |
|
| 547 |
try: |
| 548 |
self.module.preserved_copy(self.public_key, key_copy) |
| 549 |
except OSError as e: |
| 550 |
self.module.fail_json(msg=f"Unable to stage temporary key: {e}") |
| 551 |
self.module.add_cleanup_file(key_copy) |
| 552 |
|
| 553 |
self.ssh_keygen.generate_certificate( |
| 554 |
certificate_path=key_copy, |
| 555 |
identifier=self.identifier, |
| 556 |
options=self.options, |
| 557 |
pkcs11_provider=self.pkcs11_provider, |
| 558 |
principals=self.principals, |
| 559 |
serial_number=self.serial_number, |
| 560 |
signature_algorithm=self.signature_algorithm, |
| 561 |
signing_key_path=self.signing_key, |
| 562 |
cert_type=self.type, |
| 563 |
time_parameters=self.time_parameters, |
| 564 |
use_agent=self.use_agent, |
| 565 |
environ_update={"TZ": "UTC"}, |
| 566 |
check_rc=True, |
| 567 |
) |
| 568 |
|
| 569 |
temp_cert = os.path.splitext(key_copy)[0] + "-cert.pub" |
| 570 |
self.module.add_cleanup_file(temp_cert) |
| 571 |
|
| 572 |
return temp_cert |
| 573 |
|
| 574 |
@OpensshModule.trigger_change |
| 575 |
@OpensshModule.skip_if_check_mode |
| 576 |
def _remove(self) -> None: |
| 577 |
try: |
| 578 |
os.remove(self.path) |
| 579 |
except OSError as e: |
| 580 |
self.module.fail_json(msg=f"Unable to remove existing certificate: {e}") |
| 581 |
|
| 582 |
@property |
| 583 |
def _result(self) -> dict[str, t.Any]: |
| 584 |
if self.state != "present": |
| 585 |
return {} |
| 586 |
|
| 587 |
certificate_info = self.ssh_keygen.get_certificate_info( |
| 588 |
certificate_path=self.path, |
| 589 |
check_rc=self.state == "present" and not self.module.check_mode, |
| 590 |
)[1] |
| 591 |
|
| 592 |
return { |
| 593 |
"type": self.type, |
| 594 |
"filename": self.path, |
| 595 |
"info": format_cert_info(certificate_info), |
| 596 |
} |
| 597 |
|
| 598 |
@property |
| 599 |
def diff(self) -> dict[str, t.Any]: |
| 600 |
return { |
| 601 |
"before": get_cert_dict(self.original_data), |
| 602 |
"after": get_cert_dict(self.data), |
| 603 |
} |
| 604 |
|
| 605 |
|
| 606 |
def format_cert_info(cert_info: str) -> list[str]: |
| 607 |
result = [] |
| 608 |
string = "" |
| 609 |
|
| 610 |
for word in cert_info.split(): |
| 611 |
if word in ( |
| 612 |
"Type:", |
| 613 |
"Public", |
| 614 |
"Signing", |
| 615 |
"Key", |
| 616 |
"Serial:", |
| 617 |
"Valid:", |
| 618 |
"Principals:", |
| 619 |
"Critical", |
| 620 |
"Extensions:", |
| 621 |
): |
| 622 |
result.append(string) |
| 623 |
string = word |
| 624 |
else: |
| 625 |
string += " " + word |
| 626 |
result.append(string) |
| 627 |
# Drop the certificate path |
| 628 |
result.pop(0) |
| 629 |
return result |
| 630 |
|
| 631 |
|
| 632 |
def get_cert_dict(data: OpensshCertificate | None) -> dict[str, t.Any]: |
| 633 |
if data is None: |
| 634 |
return {} |
| 635 |
|
| 636 |
result = data.to_dict() |
| 637 |
result.pop("nonce") |
| 638 |
result["signature_algorithm"] = data.signature_type |
| 639 |
|
| 640 |
return result |
| 641 |
|
| 642 |
|
| 643 |
def main() -> t.NoReturn: |
| 644 |
module = AnsibleModule( |
| 645 |
argument_spec={ |
| 646 |
"force": {"type": "bool", "default": False}, |
| 647 |
"identifier": {"type": "str"}, |
| 648 |
"options": {"type": "list", "elements": "str"}, |
| 649 |
"path": {"type": "path", "required": True}, |
| 650 |
"pkcs11_provider": {"type": "str"}, |
| 651 |
"principals": {"type": "list", "elements": "str"}, |
| 652 |
"public_key": {"type": "path"}, |
| 653 |
"regenerate": { |
| 654 |
"type": "str", |
| 655 |
"default": "partial_idempotence", |
| 656 |
"choices": [ |
| 657 |
"never", |
| 658 |
"fail", |
| 659 |
"partial_idempotence", |
| 660 |
"full_idempotence", |
| 661 |
"always", |
| 662 |
], |
| 663 |
}, |
| 664 |
"signature_algorithm": { |
| 665 |
"type": "str", |
| 666 |
"choices": ["ssh-rsa", "rsa-sha2-256", "rsa-sha2-512"], |
| 667 |
}, |
| 668 |
"signing_key": {"type": "path"}, |
| 669 |
"serial_number": {"type": "int"}, |
| 670 |
"state": { |
| 671 |
"type": "str", |
| 672 |
"default": "present", |
| 673 |
"choices": ["absent", "present"], |
| 674 |
}, |
| 675 |
"type": {"type": "str", "choices": ["host", "user"]}, |
| 676 |
"use_agent": {"type": "bool", "default": False}, |
| 677 |
"valid_at": {"type": "str"}, |
| 678 |
"valid_from": {"type": "str"}, |
| 679 |
"valid_to": {"type": "str"}, |
| 680 |
"ignore_timestamps": {"type": "bool", "default": False}, |
| 681 |
}, |
| 682 |
supports_check_mode=True, |
| 683 |
add_file_common_args=True, |
| 684 |
required_if=[ |
| 685 |
( |
| 686 |
"state", |
| 687 |
"present", |
| 688 |
["type", "signing_key", "public_key", "valid_from", "valid_to"], |
| 689 |
) |
| 690 |
], |
| 691 |
) |
| 692 |
|
| 693 |
Certificate(module).execute() |
| 694 |
|
| 695 |
|
| 696 |
if __name__ == "__main__": |
| 697 |
main() |