| 1 |
# Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import abc |
| 11 |
import os |
| 12 |
import stat |
| 13 |
import traceback |
| 14 |
import typing as t |
| 15 |
from collections.abc import Callable |
| 16 |
|
| 17 |
from ansible_collections.community.crypto.plugins.module_utils._openssh.utils import ( |
| 18 |
parse_openssh_version, |
| 19 |
) |
| 20 |
|
| 21 |
if t.TYPE_CHECKING: |
| 22 |
from ansible.module_utils.basic import AnsibleModule # pragma: no cover |
| 23 |
|
| 24 |
from ansible_collections.community.crypto.plugins.module_utils._openssh.certificate import ( # pragma: no cover |
| 25 |
OpensshCertificateTimeParameters, |
| 26 |
) |
| 27 |
|
| 28 |
Param = t.ParamSpec("Param") # pragma: no cover |
| 29 |
|
| 30 |
|
| 31 |
def restore_on_failure( |
| 32 |
f: Callable[t.Concatenate[AnsibleModule, str | os.PathLike, Param], None], |
| 33 |
) -> Callable[t.Concatenate[AnsibleModule, str | os.PathLike, Param], None]: |
| 34 |
def backup_and_restore( |
| 35 |
module: AnsibleModule, |
| 36 |
path: str | os.PathLike, |
| 37 |
*args: Param.args, |
| 38 |
**kwargs: Param.kwargs, |
| 39 |
) -> None: |
| 40 |
backup_file = module.backup_local(path) if os.path.exists(path) else None |
| 41 |
|
| 42 |
try: |
| 43 |
f(module, path, *args, **kwargs) |
| 44 |
except Exception: |
| 45 |
if backup_file is not None: |
| 46 |
module.atomic_move(os.path.abspath(backup_file), os.path.abspath(path)) |
| 47 |
raise |
| 48 |
if backup_file is not None: |
| 49 |
module.add_cleanup_file(backup_file) |
| 50 |
|
| 51 |
return backup_and_restore |
| 52 |
|
| 53 |
|
| 54 |
@restore_on_failure |
| 55 |
def safe_atomic_move( |
| 56 |
module: AnsibleModule, path: str | os.PathLike, destination: str | os.PathLike |
| 57 |
) -> None: |
| 58 |
module.atomic_move(os.path.abspath(path), os.path.abspath(destination)) |
| 59 |
|
| 60 |
|
| 61 |
def _restore_all_on_failure( |
| 62 |
f: Callable[ |
| 63 |
t.Concatenate[ |
| 64 |
OpensshModule, list[tuple[str | os.PathLike, str | os.PathLike]], Param |
| 65 |
], |
| 66 |
None, |
| 67 |
], |
| 68 |
) -> Callable[ |
| 69 |
t.Concatenate[ |
| 70 |
OpensshModule, list[tuple[str | os.PathLike, str | os.PathLike]], Param |
| 71 |
], |
| 72 |
None, |
| 73 |
]: |
| 74 |
def backup_and_restore( |
| 75 |
self: OpensshModule, |
| 76 |
sources_and_destinations: list[tuple[str | os.PathLike, str | os.PathLike]], |
| 77 |
*args: Param.args, |
| 78 |
**kwargs: Param.kwargs, |
| 79 |
) -> None: |
| 80 |
backups = [ |
| 81 |
(d, self.module.backup_local(d)) |
| 82 |
for s, d in sources_and_destinations |
| 83 |
if os.path.exists(d) |
| 84 |
] |
| 85 |
|
| 86 |
try: |
| 87 |
f(self, sources_and_destinations, *args, **kwargs) |
| 88 |
except Exception: |
| 89 |
for destination, backup in backups: |
| 90 |
self.module.atomic_move( |
| 91 |
os.path.abspath(backup), os.path.abspath(destination) |
| 92 |
) |
| 93 |
raise |
| 94 |
for dummy_destination, backup in backups: |
| 95 |
self.module.add_cleanup_file(backup) |
| 96 |
|
| 97 |
return backup_and_restore |
| 98 |
|
| 99 |
|
| 100 |
_OpensshModule = t.TypeVar("_OpensshModule", bound="OpensshModule") |
| 101 |
|
| 102 |
|
| 103 |
class OpensshModule(metaclass=abc.ABCMeta): |
| 104 |
def __init__(self, *, module: AnsibleModule) -> None: |
| 105 |
self.module = module |
| 106 |
|
| 107 |
self.changed: bool = False |
| 108 |
self.check_mode: bool = self.module.check_mode |
| 109 |
|
| 110 |
def execute(self) -> t.NoReturn: |
| 111 |
try: |
| 112 |
self._execute() |
| 113 |
except Exception as e: |
| 114 |
self.module.fail_json( |
| 115 |
msg=f"unexpected error occurred: {e}", |
| 116 |
exception=traceback.format_exc(), |
| 117 |
) |
| 118 |
|
| 119 |
self.module.exit_json(**self.result) |
| 120 |
|
| 121 |
@abc.abstractmethod |
| 122 |
def _execute(self) -> None: |
| 123 |
pass |
| 124 |
|
| 125 |
@property |
| 126 |
def result(self) -> dict[str, t.Any]: |
| 127 |
result = self._result |
| 128 |
|
| 129 |
result["changed"] = self.changed |
| 130 |
|
| 131 |
if self.module._diff: # pylint: disable=protected-access |
| 132 |
result["diff"] = self.diff |
| 133 |
|
| 134 |
return result |
| 135 |
|
| 136 |
@property |
| 137 |
@abc.abstractmethod |
| 138 |
def _result(self) -> dict[str, t.Any]: |
| 139 |
pass |
| 140 |
|
| 141 |
@property |
| 142 |
@abc.abstractmethod |
| 143 |
def diff(self) -> dict[str, t.Any]: |
| 144 |
pass |
| 145 |
|
| 146 |
@staticmethod |
| 147 |
def skip_if_check_mode( |
| 148 |
f: Callable[t.Concatenate[_OpensshModule, Param], None], |
| 149 |
) -> Callable[t.Concatenate[_OpensshModule, Param], None]: |
| 150 |
def wrapper( |
| 151 |
self: _OpensshModule, *args: Param.args, **kwargs: Param.kwargs |
| 152 |
) -> None: |
| 153 |
if not self.check_mode: |
| 154 |
f(self, *args, **kwargs) |
| 155 |
|
| 156 |
return wrapper # type: ignore |
| 157 |
|
| 158 |
@staticmethod |
| 159 |
def trigger_change( |
| 160 |
f: Callable[t.Concatenate[_OpensshModule, Param], None], |
| 161 |
) -> Callable[t.Concatenate[_OpensshModule, Param], None]: |
| 162 |
def wrapper( |
| 163 |
self: _OpensshModule, *args: Param.args, **kwargs: Param.kwargs |
| 164 |
) -> None: |
| 165 |
f(self, *args, **kwargs) |
| 166 |
self.changed = True |
| 167 |
|
| 168 |
return wrapper # type: ignore |
| 169 |
|
| 170 |
def _check_if_base_dir(self, path: str | os.PathLike) -> None: |
| 171 |
base_dir = os.path.dirname(path) or "." |
| 172 |
if not os.path.isdir(base_dir): |
| 173 |
self.module.fail_json( |
| 174 |
name=base_dir, |
| 175 |
msg=f"The directory {base_dir} does not exist or the file is not a directory", |
| 176 |
) |
| 177 |
|
| 178 |
def _get_ssh_version(self) -> str | None: |
| 179 |
ssh_bin = self.module.get_bin_path("ssh") |
| 180 |
if not ssh_bin: |
| 181 |
return None |
| 182 |
return parse_openssh_version( |
| 183 |
self.module.run_command([ssh_bin, "-V", "-q"], check_rc=True)[2].strip() |
| 184 |
) |
| 185 |
|
| 186 |
@_restore_all_on_failure |
| 187 |
def _safe_secure_move( |
| 188 |
self, |
| 189 |
sources_and_destinations: list[tuple[str | os.PathLike, str | os.PathLike]], |
| 190 |
) -> None: |
| 191 |
"""Moves a list of files from 'source' to 'destination' and restores 'destination' from backup upon failure. |
| 192 |
If 'destination' does not already exist, then 'source' permissions are preserved to prevent |
| 193 |
exposing protected data ('atomic_move' uses the 'destination' base directory mask for |
| 194 |
permissions if 'destination' does not already exists). |
| 195 |
""" |
| 196 |
for source, destination in sources_and_destinations: |
| 197 |
if os.path.exists(destination): |
| 198 |
self.module.atomic_move( |
| 199 |
os.path.abspath(source), os.path.abspath(destination) |
| 200 |
) |
| 201 |
else: |
| 202 |
self.module.preserved_copy(source, destination) |
| 203 |
|
| 204 |
def _update_permissions(self, path: str | os.PathLike) -> None: |
| 205 |
file_args = self.module.load_file_common_arguments(self.module.params) |
| 206 |
file_args["path"] = path |
| 207 |
|
| 208 |
if not self.module.check_file_absent_if_check_mode(path): |
| 209 |
self.changed = self.module.set_fs_attributes_if_different( |
| 210 |
file_args, self.changed |
| 211 |
) |
| 212 |
else: |
| 213 |
self.changed = True |
| 214 |
|
| 215 |
|
| 216 |
if t.TYPE_CHECKING: |
| 217 |
|
| 218 |
class _RunCommandKwarg(t.TypedDict): |
| 219 |
check_rc: t.NotRequired[bool] |
| 220 |
environ_update: t.NotRequired[dict[str, str] | None] |
| 221 |
|
| 222 |
|
| 223 |
class KeygenCommand: |
| 224 |
def __init__(self, module: AnsibleModule) -> None: |
| 225 |
self._bin_path = module.get_bin_path("ssh-keygen", True) |
| 226 |
self._run_command = module.run_command |
| 227 |
|
| 228 |
def generate_certificate( |
| 229 |
self, |
| 230 |
*, |
| 231 |
certificate_path: str, |
| 232 |
identifier: str, |
| 233 |
options: list[str] | None, |
| 234 |
pkcs11_provider: str | None, |
| 235 |
principals: list[str] | None, |
| 236 |
serial_number: int | None, |
| 237 |
signature_algorithm: str | None, |
| 238 |
signing_key_path: str, |
| 239 |
cert_type: t.Literal["host", "user"] | None, |
| 240 |
time_parameters: OpensshCertificateTimeParameters, |
| 241 |
use_agent: bool, |
| 242 |
**kwargs: t.Unpack[_RunCommandKwarg], |
| 243 |
) -> tuple[int, str, str]: |
| 244 |
args = [self._bin_path, "-s", signing_key_path, "-P", "", "-I", identifier] |
| 245 |
|
| 246 |
if options: |
| 247 |
for option in options: |
| 248 |
args.extend(["-O", option]) |
| 249 |
if pkcs11_provider: |
| 250 |
args.extend(["-D", pkcs11_provider]) |
| 251 |
if principals: |
| 252 |
args.extend(["-n", ",".join(principals)]) |
| 253 |
if serial_number is not None: |
| 254 |
args.extend(["-z", str(serial_number)]) |
| 255 |
if cert_type == "host": |
| 256 |
args.extend(["-h"]) |
| 257 |
if use_agent: |
| 258 |
args.extend(["-U"]) |
| 259 |
if time_parameters.validity_string: |
| 260 |
args.extend(["-V", time_parameters.validity_string]) |
| 261 |
if signature_algorithm: |
| 262 |
args.extend(["-t", signature_algorithm]) |
| 263 |
args.append(certificate_path) |
| 264 |
|
| 265 |
return self._run_command(args, **kwargs) |
| 266 |
|
| 267 |
def generate_keypair( |
| 268 |
self, |
| 269 |
*, |
| 270 |
private_key_path: str, |
| 271 |
size: int, |
| 272 |
key_type: str, |
| 273 |
comment: str | None, |
| 274 |
**kwargs: t.Unpack[_RunCommandKwarg], |
| 275 |
) -> tuple[int, str, str]: |
| 276 |
args = [ |
| 277 |
self._bin_path, |
| 278 |
"-q", |
| 279 |
"-N", |
| 280 |
"", |
| 281 |
"-b", |
| 282 |
str(size), |
| 283 |
"-t", |
| 284 |
key_type, |
| 285 |
"-f", |
| 286 |
private_key_path, |
| 287 |
"-C", |
| 288 |
comment or "", |
| 289 |
] |
| 290 |
|
| 291 |
# "y" must be entered in response to the "overwrite" prompt |
| 292 |
data = "y" if os.path.exists(private_key_path) else None |
| 293 |
|
| 294 |
return self._run_command(args, data=data, **kwargs) |
| 295 |
|
| 296 |
def get_certificate_info( |
| 297 |
self, *, certificate_path: str, **kwargs: t.Unpack[_RunCommandKwarg] |
| 298 |
) -> tuple[int, str, str]: |
| 299 |
return self._run_command( |
| 300 |
[self._bin_path, "-L", "-f", certificate_path], **kwargs |
| 301 |
) |
| 302 |
|
| 303 |
def get_matching_public_key( |
| 304 |
self, *, private_key_path: str, **kwargs: t.Unpack[_RunCommandKwarg] |
| 305 |
) -> tuple[int, str, str]: |
| 306 |
return self._run_command( |
| 307 |
[self._bin_path, "-P", "", "-y", "-f", private_key_path], **kwargs |
| 308 |
) |
| 309 |
|
| 310 |
def get_private_key( |
| 311 |
self, *, private_key_path: str, **kwargs: t.Unpack[_RunCommandKwarg] |
| 312 |
) -> tuple[int, str, str]: |
| 313 |
return self._run_command( |
| 314 |
[self._bin_path, "-l", "-f", private_key_path], **kwargs |
| 315 |
) |
| 316 |
|
| 317 |
def update_comment( |
| 318 |
self, |
| 319 |
*, |
| 320 |
private_key_path: str, |
| 321 |
comment: str, |
| 322 |
force_new_format: bool = True, |
| 323 |
**kwargs: t.Unpack[_RunCommandKwarg], |
| 324 |
) -> tuple[int, str, str]: |
| 325 |
if os.path.exists(private_key_path) and not os.access( |
| 326 |
private_key_path, os.W_OK |
| 327 |
): |
| 328 |
try: |
| 329 |
os.chmod(private_key_path, stat.S_IWUSR + stat.S_IRUSR) |
| 330 |
except (IOError, OSError) as e: |
| 331 |
raise ValueError( |
| 332 |
f"The private key at {private_key_path} is not writeable preventing a comment update ({e})" |
| 333 |
) from e |
| 334 |
|
| 335 |
command = [self._bin_path, "-q"] |
| 336 |
if force_new_format: |
| 337 |
command.append("-o") |
| 338 |
command.extend(["-c", "-C", comment, "-f", private_key_path]) |
| 339 |
return self._run_command(command, **kwargs) |
| 340 |
|
| 341 |
|
| 342 |
_PrivateKey = t.TypeVar("_PrivateKey", bound="PrivateKey") |
| 343 |
|
| 344 |
|
| 345 |
class PrivateKey: |
| 346 |
def __init__( |
| 347 |
self, *, size: int, key_type: str, fingerprint: str, key_format: str = "" |
| 348 |
) -> None: |
| 349 |
self._size = size |
| 350 |
self._type = key_type |
| 351 |
self._fingerprint = fingerprint |
| 352 |
self._format = key_format |
| 353 |
|
| 354 |
@property |
| 355 |
def size(self) -> int: |
| 356 |
return self._size |
| 357 |
|
| 358 |
@property |
| 359 |
def type(self) -> str: |
| 360 |
return self._type |
| 361 |
|
| 362 |
@property |
| 363 |
def fingerprint(self) -> str: |
| 364 |
return self._fingerprint |
| 365 |
|
| 366 |
@property |
| 367 |
def format(self) -> str: |
| 368 |
return self._format |
| 369 |
|
| 370 |
@classmethod |
| 371 |
def from_string( |
| 372 |
cls: t.Type[_PrivateKey], string: str # noqa: UP006 |
| 373 |
) -> _PrivateKey: |
| 374 |
properties = string.split() |
| 375 |
|
| 376 |
return cls( |
| 377 |
size=int(properties[0]), |
| 378 |
key_type=properties[-1][1:-1].lower(), |
| 379 |
fingerprint=properties[1], |
| 380 |
) |
| 381 |
|
| 382 |
def to_dict(self) -> dict[str, t.Any]: |
| 383 |
return { |
| 384 |
"size": self._size, |
| 385 |
"type": self._type, |
| 386 |
"fingerprint": self._fingerprint, |
| 387 |
"format": self._format, |
| 388 |
} |
| 389 |
|
| 390 |
|
| 391 |
_PublicKey = t.TypeVar("_PublicKey", bound="PublicKey") |
| 392 |
|
| 393 |
|
| 394 |
class PublicKey: |
| 395 |
def __init__(self, *, type_string: str, data: str, comment: str | None) -> None: |
| 396 |
self._type_string = type_string |
| 397 |
self._data = data |
| 398 |
self._comment = comment |
| 399 |
|
| 400 |
def __eq__(self, other: object) -> bool: |
| 401 |
if not isinstance(other, type(self)): |
| 402 |
return NotImplemented |
| 403 |
|
| 404 |
return all( |
| 405 |
[ |
| 406 |
self._type_string == other._type_string, |
| 407 |
self._data == other._data, |
| 408 |
( |
| 409 |
(self._comment == other._comment) |
| 410 |
if self._comment is not None and other._comment is not None |
| 411 |
else True |
| 412 |
), |
| 413 |
] |
| 414 |
) |
| 415 |
|
| 416 |
def __ne__(self, other: object) -> bool: |
| 417 |
return not self == other |
| 418 |
|
| 419 |
def __str__(self) -> str: |
| 420 |
return f"{self._type_string} {self._data}" |
| 421 |
|
| 422 |
@property |
| 423 |
def comment(self) -> str | None: |
| 424 |
return self._comment |
| 425 |
|
| 426 |
@comment.setter |
| 427 |
def comment(self, value: str | None) -> None: |
| 428 |
self._comment = value |
| 429 |
|
| 430 |
@property |
| 431 |
def data(self) -> str: |
| 432 |
return self._data |
| 433 |
|
| 434 |
@property |
| 435 |
def type_string(self) -> str: |
| 436 |
return self._type_string |
| 437 |
|
| 438 |
@classmethod |
| 439 |
def from_string(cls: type[_PublicKey], string: str) -> _PublicKey: |
| 440 |
properties = string.strip("\n").split(" ", 2) |
| 441 |
|
| 442 |
return cls( |
| 443 |
type_string=properties[0], |
| 444 |
data=properties[1], |
| 445 |
comment=properties[2] if len(properties) > 2 else "", |
| 446 |
) |
| 447 |
|
| 448 |
@classmethod |
| 449 |
def load(cls: type[_PublicKey], path: str | os.PathLike) -> _PublicKey | None: |
| 450 |
with open(path, "r", encoding="utf-8") as f: |
| 451 |
properties = f.read().strip(" \n").split(" ", 2) |
| 452 |
|
| 453 |
if len(properties) < 2: |
| 454 |
return None |
| 455 |
|
| 456 |
return cls( |
| 457 |
type_string=properties[0], |
| 458 |
data=properties[1], |
| 459 |
comment="" if len(properties) <= 2 else properties[2], |
| 460 |
) |
| 461 |
|
| 462 |
def to_dict(self) -> dict[str, t.Any]: |
| 463 |
return { |
| 464 |
"comment": self._comment, |
| 465 |
"public_key": self._data, |
| 466 |
} |
| 467 |
|
| 468 |
|
| 469 |
def parse_private_key_format( |
| 470 |
*, |
| 471 |
path: str | os.PathLike, |
| 472 |
) -> t.Literal["SSH", "PKCS8", "PKCS1", ""]: |
| 473 |
with open(path, "r", encoding="utf-8") as file: |
| 474 |
header = file.readline().strip() |
| 475 |
|
| 476 |
if header == "-----BEGIN OPENSSH PRIVATE KEY-----": |
| 477 |
return "SSH" |
| 478 |
if header == "-----BEGIN PRIVATE KEY-----": |
| 479 |
return "PKCS8" |
| 480 |
if header == "-----BEGIN RSA PRIVATE KEY-----": |
| 481 |
return "PKCS1" |
| 482 |
|
| 483 |
return "" |
| 484 |
|
| 485 |
|
| 486 |
__all__ = ( |
| 487 |
"KeygenCommand", |
| 488 |
"OpensshModule", |
| 489 |
"PrivateKey", |
| 490 |
"PublicKey", |
| 491 |
"parse_private_key_format", |
| 492 |
"restore_on_failure", |
| 493 |
"safe_atomic_move", |
| 494 |
) |