Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_openssh/backends/keypair_backend.py

raw
1 # Copyright (c) 2018, David Kainz <[email protected]> <[email protected]>
2 # Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <[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 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import abc
12 import os
13 import typing as t
14
15 from ansible.module_utils.basic import missing_required_lib
16 from ansible.module_utils.common.text.converters import to_bytes, to_text
17
18 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
19 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
20 )
21 from ansible_collections.community.crypto.plugins.module_utils._openssh.backends.common import (
22 KeygenCommand,
23 OpensshModule,
24 PrivateKey,
25 PublicKey,
26 parse_private_key_format,
27 )
28 from ansible_collections.community.crypto.plugins.module_utils._openssh.cryptography import (
29 CRYPTOGRAPHY_VERSION,
30 HAS_OPENSSH_SUPPORT,
31 InvalidCommentError,
32 InvalidPassphraseError,
33 InvalidPrivateKeyFileError,
34 OpenSSHError,
35 OpensshKeypair,
36 )
37 from ansible_collections.community.crypto.plugins.module_utils._openssh.utils import (
38 any_in,
39 file_mode,
40 secure_write,
41 )
42 from ansible_collections.community.crypto.plugins.module_utils._version import (
43 LooseVersion,
44 )
45
46 if t.TYPE_CHECKING:
47 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
48
49
50 class KeypairBackend(OpensshModule, metaclass=abc.ABCMeta):
51 def __init__(self, *, module: AnsibleModule) -> None:
52 super().__init__(module=module)
53
54 self.comment: str | None = self.module.params["comment"]
55 self.private_key_path: str = self.module.params["path"]
56 self.public_key_path = self.private_key_path + ".pub"
57 self.regenerate: t.Literal[
58 "never", "fail", "partial_idempotence", "full_idempotence", "always"
59 ] = (
60 self.module.params["regenerate"]
61 if not self.module.params["force"]
62 else "always"
63 )
64 self.state: t.Literal["present", "absent"] = self.module.params["state"]
65 self.type: t.Literal["rsa", "dsa", "rsa1", "ecdsa", "ed25519"] = (
66 self.module.params["type"]
67 )
68
69 self.size: int = self._get_size(self.module.params["size"])
70 self._validate_path()
71
72 self.original_private_key: PrivateKey | None = None
73 self.original_public_key: PublicKey | None = None
74 self.private_key: PrivateKey | None = None
75 self.public_key: PublicKey | None = None
76
77 def _get_size(self, size: int | None) -> int:
78 if self.type in ("rsa", "rsa1"):
79 result = 4096 if size is None else size
80 if result < 1024:
81 return self.module.fail_json(
82 msg="For RSA keys, the minimum size is 1024 bits and the default is 4096 bits. "
83 + "Attempting to use bit lengths under 1024 will cause the module to fail."
84 )
85 elif self.type == "dsa":
86 result = 1024 if size is None else size
87 if result != 1024:
88 return self.module.fail_json(
89 msg="DSA keys must be exactly 1024 bits as specified by FIPS 186-2."
90 )
91 elif self.type == "ecdsa":
92 result = 256 if size is None else size
93 if result not in (256, 384, 521):
94 return self.module.fail_json(
95 msg="For ECDSA keys, size determines the key length by selecting from one of "
96 + "three elliptic curve sizes: 256, 384 or 521 bits. "
97 + "Attempting to use bit lengths other than these three values for ECDSA keys will "
98 + "cause this module to fail."
99 )
100 elif self.type == "ed25519":
101 # User input is ignored for `key size` when `key type` is ed25519
102 result = 256
103 else:
104 return self.module.fail_json(
105 msg=f"{self.type} is not a valid value for key type"
106 )
107
108 return result
109
110 def _validate_path(self) -> None:
111 self._check_if_base_dir(self.private_key_path)
112
113 if os.path.isdir(self.private_key_path):
114 self.module.fail_json(
115 msg=f"{self.private_key_path} is a directory. Please specify a path to a file."
116 )
117
118 def _execute(self) -> None:
119 self.original_private_key = self._load_private_key()
120 self.original_public_key = self._load_public_key()
121
122 if self.state == "present":
123 self._validate_key_load()
124
125 if self._should_generate():
126 self._generate()
127 elif not self._public_key_valid():
128 self._restore_public_key()
129
130 self.private_key = self._load_private_key()
131 self.public_key = self._load_public_key()
132
133 for path in (self.private_key_path, self.public_key_path):
134 self._update_permissions(path)
135 else:
136 if self._should_remove():
137 self._remove()
138
139 def _load_private_key(self) -> PrivateKey | None:
140 result = None
141 if self._private_key_exists():
142 try:
143 result = self._get_private_key()
144 except Exception:
145 pass
146
147 return result
148
149 def _private_key_exists(self) -> bool:
150 return os.path.exists(self.private_key_path)
151
152 @abc.abstractmethod
153 def _get_private_key(self) -> PrivateKey:
154 pass
155
156 def _load_public_key(self) -> PublicKey | None:
157 result = None
158 if self._public_key_exists():
159 try:
160 result = PublicKey.load(self.public_key_path)
161 except (IOError, OSError):
162 pass
163 return result
164
165 def _public_key_exists(self) -> bool:
166 return os.path.exists(self.public_key_path)
167
168 def _validate_key_load(self) -> None:
169 if (
170 self._private_key_exists()
171 and self.regenerate in ("never", "fail", "partial_idempotence")
172 and (self.original_private_key is None or not self._private_key_readable())
173 ):
174 self.module.fail_json(
175 msg="Unable to read the key. The key is protected with a passphrase or broken. "
176 + "Will not proceed. To force regeneration, call the module with `generate` "
177 + "set to `full_idempotence` or `always`, or with `force=true`."
178 )
179
180 @abc.abstractmethod
181 def _private_key_readable(self) -> bool:
182 pass
183
184 def _should_generate(self) -> bool:
185 if self.original_private_key is None:
186 return True
187 if self.regenerate == "never":
188 return False
189 if self.regenerate == "fail":
190 if not self._private_key_valid():
191 self.module.fail_json(
192 msg="Key has wrong type and/or size. Will not proceed. "
193 + "To force regeneration, call the module with `generate` set to "
194 + "`partial_idempotence`, `full_idempotence` or `always`, or with `force=true`."
195 )
196 return False
197 if self.regenerate in ("partial_idempotence", "full_idempotence"):
198 return not self._private_key_valid()
199 return True
200
201 def _private_key_valid(self) -> bool:
202 if self.original_private_key is None:
203 return False
204
205 return all(
206 [
207 self.size == self.original_private_key.size,
208 self.type == self.original_private_key.type,
209 self._private_key_valid_backend(self.original_private_key),
210 ]
211 )
212
213 @abc.abstractmethod
214 def _private_key_valid_backend(self, original_private_key: PrivateKey) -> bool:
215 pass
216
217 @OpensshModule.trigger_change
218 @OpensshModule.skip_if_check_mode
219 def _generate(self) -> None:
220 temp_private_key, temp_public_key = self._generate_temp_keypair()
221
222 try:
223 self._safe_secure_move(
224 [
225 (temp_private_key, self.private_key_path),
226 (temp_public_key, self.public_key_path),
227 ]
228 )
229 except OSError as e:
230 self.module.fail_json(msg=str(e))
231
232 def _generate_temp_keypair(self) -> tuple[str, str]:
233 temp_private_key = os.path.join(
234 self.module.tmpdir, os.path.basename(self.private_key_path)
235 )
236 temp_public_key = temp_private_key + ".pub"
237
238 try:
239 self._generate_keypair(temp_private_key)
240 except (IOError, OSError) as e:
241 self.module.fail_json(msg=str(e))
242
243 for f in (temp_private_key, temp_public_key):
244 self.module.add_cleanup_file(f)
245
246 return temp_private_key, temp_public_key
247
248 @abc.abstractmethod
249 def _generate_keypair(self, private_key_path: str) -> None:
250 pass
251
252 def _public_key_valid(self) -> bool:
253 if self.original_public_key is None:
254 return False
255
256 valid_public_key = self._get_public_key()
257 if valid_public_key:
258 valid_public_key.comment = self.comment
259
260 return self.original_public_key == valid_public_key
261
262 @abc.abstractmethod
263 def _get_public_key(self) -> PublicKey | t.Literal[""]:
264 pass
265
266 @OpensshModule.trigger_change
267 @OpensshModule.skip_if_check_mode
268 def _restore_public_key(self) -> None:
269 try:
270 temp_public_key = self._create_temp_public_key(
271 str(self._get_public_key()) + "\n"
272 )
273 self._safe_secure_move([(temp_public_key, self.public_key_path)])
274 except (IOError, OSError):
275 self.module.fail_json(
276 msg="The public key is missing or does not match the private key. "
277 + "Unable to regenerate the public key."
278 )
279
280 if self.comment:
281 self._update_comment()
282
283 def _create_temp_public_key(self, content: str | bytes) -> str:
284 temp_public_key: str = os.path.join(
285 self.module.tmpdir, os.path.basename(self.public_key_path)
286 )
287
288 default_permissions = 0o644
289 existing_permissions = file_mode(self.public_key_path)
290
291 try:
292 secure_write(
293 path=temp_public_key,
294 mode=existing_permissions or default_permissions,
295 content=to_bytes(content),
296 )
297 except (IOError, OSError) as e:
298 self.module.fail_json(msg=str(e))
299 self.module.add_cleanup_file(temp_public_key)
300
301 return temp_public_key
302
303 @abc.abstractmethod
304 def _update_comment(self) -> None:
305 pass
306
307 def _should_remove(self) -> bool:
308 return self._private_key_exists() or self._public_key_exists()
309
310 @OpensshModule.trigger_change
311 @OpensshModule.skip_if_check_mode
312 def _remove(self) -> None:
313 try:
314 if self._private_key_exists():
315 os.remove(self.private_key_path)
316 if self._public_key_exists():
317 os.remove(self.public_key_path)
318 except (IOError, OSError) as e:
319 self.module.fail_json(msg=str(e))
320
321 @property
322 def _result(self) -> dict[str, t.Any]:
323 private_key = self.private_key or self.original_private_key
324 public_key = self.public_key or self.original_public_key
325
326 return {
327 "size": self.size,
328 "type": self.type,
329 "filename": self.private_key_path,
330 "fingerprint": private_key.fingerprint if private_key else "",
331 "public_key": str(public_key) if public_key else "",
332 "comment": public_key.comment if public_key else "",
333 }
334
335 @property
336 def diff(self) -> dict[str, t.Any]:
337 before = (
338 self.original_private_key.to_dict() if self.original_private_key else {}
339 )
340 before.update(
341 self.original_public_key.to_dict() if self.original_public_key else {}
342 )
343
344 after = self.private_key.to_dict() if self.private_key else {}
345 after.update(self.public_key.to_dict() if self.public_key else {})
346
347 return {
348 "before": before,
349 "after": after,
350 }
351
352
353 class KeypairBackendOpensshBin(KeypairBackend):
354 def __init__(self, *, module: AnsibleModule) -> None:
355 super().__init__(module=module)
356
357 if self.module.params["private_key_format"] != "auto":
358 self.module.fail_json(
359 msg="'auto' is the only valid option for 'private_key_format' when 'backend' is not 'cryptography'"
360 )
361
362 self.ssh_keygen = KeygenCommand(self.module)
363
364 def _generate_keypair(self, private_key_path: str) -> None:
365 self.ssh_keygen.generate_keypair(
366 private_key_path=private_key_path,
367 size=self.size,
368 key_type=self.type,
369 comment=self.comment,
370 check_rc=True,
371 )
372
373 def _get_private_key(self) -> PrivateKey:
374 rc, private_key_content, err = self.ssh_keygen.get_private_key(
375 private_key_path=self.private_key_path, check_rc=False
376 )
377 if rc != 0:
378 raise ValueError(err)
379 return PrivateKey.from_string(private_key_content)
380
381 def _get_public_key(self) -> PublicKey | t.Literal[""]:
382 public_key_content = self.ssh_keygen.get_matching_public_key(
383 private_key_path=self.private_key_path, check_rc=True
384 )[1]
385 return PublicKey.from_string(public_key_content)
386
387 def _private_key_readable(self) -> bool:
388 rc, _stdout, stderr = self.ssh_keygen.get_matching_public_key(
389 private_key_path=self.private_key_path, check_rc=False
390 )
391 return not (
392 rc == 255
393 or any_in(
394 stderr,
395 "is not a public key file",
396 "incorrect passphrase",
397 "load failed",
398 )
399 )
400
401 def _update_comment(self) -> None:
402 assert self.comment is not None
403 try:
404 ssh_version = self._get_ssh_version() or "7.8"
405 force_new_format = (
406 LooseVersion("6.5") <= LooseVersion(ssh_version) < LooseVersion("7.8")
407 )
408 self.ssh_keygen.update_comment(
409 private_key_path=self.private_key_path,
410 comment=self.comment or "",
411 force_new_format=force_new_format,
412 check_rc=True,
413 )
414 except (IOError, OSError) as e:
415 self.module.fail_json(msg=str(e))
416
417 def _private_key_valid_backend(self, original_private_key: PrivateKey) -> bool:
418 return True
419
420
421 class KeypairBackendCryptography(KeypairBackend):
422 def __init__(self, *, module: AnsibleModule) -> None:
423 super().__init__(module=module)
424
425 if self.type == "rsa1":
426 self.module.fail_json(
427 msg="RSA1 keys are not supported by the cryptography backend"
428 )
429
430 self.passphrase = (
431 to_bytes(module.params["passphrase"])
432 if module.params["passphrase"]
433 else None
434 )
435 key_format: t.Literal["auto", "pkcs1", "pkcs8", "ssh"] = module.params[
436 "private_key_format"
437 ]
438 self.private_key_format = self._get_key_format(key_format)
439
440 def _get_key_format(
441 self, key_format: t.Literal["auto", "pkcs1", "pkcs8", "ssh"]
442 ) -> t.Literal["SSH", "PKCS1", "PKCS8"]:
443 result: t.Literal["SSH", "PKCS1", "PKCS8"] = "SSH"
444
445 if key_format == "auto":
446 # Default to OpenSSH 7.8 compatibility when OpenSSH is not installed
447 ssh_version = self._get_ssh_version() or "7.8"
448
449 if (
450 LooseVersion(ssh_version) < LooseVersion("7.8")
451 and self.type != "ed25519"
452 ):
453 # OpenSSH made SSH formatted private keys available in version 6.5,
454 # but still defaulted to PKCS1 format with the exception of ed25519 keys
455 result = "PKCS1"
456 else:
457 result = key_format.upper() # type: ignore
458
459 return result
460
461 def _generate_keypair(self, private_key_path: str) -> None:
462 assert self.type != "rsa1"
463 keypair = OpensshKeypair.generate(
464 keytype=self.type,
465 size=self.size,
466 passphrase=self.passphrase,
467 comment=self.comment or "",
468 )
469
470 encoded_private_key = OpensshKeypair.encode_openssh_privatekey(
471 asym_keypair=keypair.asymmetric_keypair, key_format=self.private_key_format
472 )
473 secure_write(path=private_key_path, mode=0o600, content=encoded_private_key)
474
475 public_key_path = private_key_path + ".pub"
476 secure_write(path=public_key_path, mode=0o644, content=keypair.public_key)
477
478 def _get_private_key(self) -> PrivateKey:
479 keypair = OpensshKeypair.load(
480 path=self.private_key_path, passphrase=self.passphrase, no_public_key=True
481 )
482
483 return PrivateKey(
484 size=keypair.size,
485 key_type=keypair.key_type,
486 fingerprint=keypair.fingerprint,
487 key_format=parse_private_key_format(path=self.private_key_path),
488 )
489
490 def _get_public_key(self) -> PublicKey | t.Literal[""]:
491 try:
492 keypair = OpensshKeypair.load(
493 path=self.private_key_path,
494 passphrase=self.passphrase,
495 no_public_key=True,
496 )
497 except OpenSSHError:
498 # Simulates the null output of ssh-keygen
499 return ""
500
501 return PublicKey.from_string(to_text(keypair.public_key))
502
503 def _private_key_readable(self) -> bool:
504 try:
505 OpensshKeypair.load(
506 path=self.private_key_path,
507 passphrase=self.passphrase,
508 no_public_key=True,
509 )
510 except (InvalidPrivateKeyFileError, InvalidPassphraseError):
511 return False
512
513 # Cryptography >= 3.0 uses a SSH key loader which does not raise an exception when a passphrase is provided
514 # when loading an unencrypted key
515 if self.passphrase:
516 try:
517 OpensshKeypair.load(
518 path=self.private_key_path, passphrase=None, no_public_key=True
519 )
520 return False
521 except (InvalidPrivateKeyFileError, InvalidPassphraseError):
522 return True
523
524 return True
525
526 def _update_comment(self) -> None:
527 assert self.comment is not None
528 keypair = OpensshKeypair.load(
529 path=self.private_key_path, passphrase=self.passphrase, no_public_key=True
530 )
531 try:
532 keypair.comment = self.comment
533 except InvalidCommentError as e:
534 self.module.fail_json(msg=str(e))
535
536 try:
537 temp_public_key = self._create_temp_public_key(keypair.public_key + b"\n")
538 self._safe_secure_move([(temp_public_key, self.public_key_path)])
539 except (IOError, OSError) as e:
540 self.module.fail_json(msg=str(e))
541
542 def _private_key_valid_backend(self, original_private_key: PrivateKey) -> bool:
543 # avoids breaking behavior and prevents
544 # automatic conversions with OpenSSH upgrades
545 if self.module.params["private_key_format"] == "auto":
546 return True
547
548 return self.private_key_format == original_private_key.format
549
550
551 def select_backend(
552 *, module: AnsibleModule, backend: t.Literal["auto", "opensshbin", "cryptography"]
553 ) -> KeypairBackend:
554 can_use_cryptography = HAS_OPENSSH_SUPPORT and LooseVersion(
555 CRYPTOGRAPHY_VERSION
556 ) >= LooseVersion(COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION)
557 can_use_opensshbin = bool(module.get_bin_path("ssh-keygen"))
558
559 if backend == "auto":
560 if can_use_opensshbin and not module.params["passphrase"]:
561 backend = "opensshbin"
562 elif can_use_cryptography:
563 backend = "cryptography"
564 else:
565 module.fail_json(
566 msg=(
567 f"Cannot find either the OpenSSH binary in the PATH or cryptography >= {COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION} installed on this system"
568 )
569 )
570
571 if backend == "opensshbin":
572 if not can_use_opensshbin:
573 module.fail_json(msg="Cannot find the OpenSSH binary in the PATH")
574 return KeypairBackendOpensshBin(module=module)
575 if backend == "cryptography":
576 if not can_use_cryptography:
577 module.fail_json(
578 msg=missing_required_lib(
579 f"cryptography >= {COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION}"
580 )
581 )
582 return KeypairBackendCryptography(module=module)
583 raise ValueError(f"Unsupported value for backend: {backend}")
584
585
586 __all__ = ("KeypairBackend", "select_backend")