Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/module_backends/privatekey.py

raw
1 # Copyright (c) 2016, Yanis Guenane <[email protected]>
2 # Copyright (c) 2020, Felix Fontein <[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 base64
12 import traceback
13 import typing as t
14
15 from ansible.module_utils.common.text.converters import to_bytes
16
17 from ansible_collections.community.crypto.plugins.module_utils._argspec import (
18 ArgumentSpec,
19 )
20 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
21 OpenSSLObjectError,
22 )
23 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey_info import (
24 PrivateKeyConsistencyError,
25 PrivateKeyParseError,
26 get_privatekey_info,
27 )
28 from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import (
29 identify_private_key_format,
30 )
31 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
32 get_fingerprint_of_privatekey,
33 )
34 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
35 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
36 assert_required_cryptography_version,
37 )
38
39 if t.TYPE_CHECKING:
40 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
41 from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
42 PrivateKeyTypes,
43 )
44
45 from ansible_collections.community.crypto.plugins.plugin_utils._action_module import ( # pragma: no cover
46 AnsibleActionModule,
47 )
48
49 GeneralAnsibleModule = t.Union[ # noqa: UP007
50 AnsibleModule, AnsibleActionModule
51 ] # pragma: no cover
52
53
54 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
55
56 try:
57 import cryptography
58 import cryptography.exceptions
59 import cryptography.hazmat.backends
60 import cryptography.hazmat.primitives.asymmetric.dsa
61 import cryptography.hazmat.primitives.asymmetric.ec
62 import cryptography.hazmat.primitives.asymmetric.ed448
63 import cryptography.hazmat.primitives.asymmetric.ed25519
64 import cryptography.hazmat.primitives.asymmetric.rsa
65 import cryptography.hazmat.primitives.asymmetric.utils
66 import cryptography.hazmat.primitives.asymmetric.x448
67 import cryptography.hazmat.primitives.asymmetric.x25519
68 import cryptography.hazmat.primitives.serialization
69 except ImportError:
70 pass
71
72
73 class PrivateKeyError(OpenSSLObjectError):
74 pass
75
76
77 # From the object called `module`, only the following properties are used:
78 #
79 # - module.params[]
80 # - module.warn(msg: str)
81 # - module.fail_json(msg: str, **kwargs)
82
83
84 class _Curve:
85 def __init__(
86 self,
87 *,
88 name: str,
89 ectype: str,
90 deprecated: bool,
91 ) -> None:
92 self.name = name
93 self.ectype = ectype
94 self.deprecated = deprecated
95
96 def _get_ec_class(
97 self, *, module: GeneralAnsibleModule
98 ) -> type[cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve]:
99 ecclass: (
100 type[cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve] | None
101 ) = getattr(cryptography.hazmat.primitives.asymmetric.ec, self.ectype, None)
102 if ecclass is None:
103 module.fail_json(
104 msg=f"Your cryptography version does not support {self.ectype}"
105 )
106 return ecclass
107
108 def create(
109 self, *, size: int, module: GeneralAnsibleModule
110 ) -> cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve:
111 ecclass = self._get_ec_class(module=module)
112 return ecclass()
113
114 def verify(
115 self,
116 *,
117 privatekey: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey,
118 module: GeneralAnsibleModule,
119 ) -> bool:
120 ecclass = self._get_ec_class(module=module)
121 return isinstance(privatekey.private_numbers().public_numbers.curve, ecclass)
122
123
124 class PrivateKeyBackend:
125 def _add_curve(
126 self,
127 name: str,
128 ectype: str,
129 *,
130 deprecated: bool = False,
131 ) -> None:
132 self.curves[name] = _Curve(name=name, ectype=ectype, deprecated=deprecated)
133
134 def __init__(self, *, module: GeneralAnsibleModule) -> None:
135 self.module = module
136 self.type: t.Literal[
137 "DSA", "ECC", "Ed25519", "Ed448", "RSA", "X25519", "X448"
138 ] = module.params["type"]
139 self.size: int = module.params["size"]
140 self.curve: str | None = module.params["curve"]
141 self.passphrase: str | None = module.params["passphrase"]
142 self.cipher: str = module.params["cipher"]
143 self.format: t.Literal["pkcs1", "pkcs8", "raw", "auto", "auto_ignore"] = (
144 module.params["format"]
145 )
146 self.format_mismatch: t.Literal["regenerate", "convert"] = module.params.get(
147 "format_mismatch", "regenerate"
148 )
149 self.regenerate: t.Literal[
150 "never", "fail", "partial_idempotence", "full_idempotence", "always"
151 ] = module.params.get("regenerate", "full_idempotence")
152
153 self.private_key: PrivateKeyTypes | None = None
154
155 self.existing_private_key: PrivateKeyTypes | None = None
156 self.existing_private_key_bytes: bytes | None = None
157
158 self.diff_before = self._get_info(data=None)
159 self.diff_after = self._get_info(data=None)
160
161 self.curves: dict[str, _Curve] = {}
162 self._add_curve("secp224r1", "SECP224R1")
163 self._add_curve("secp256k1", "SECP256K1")
164 self._add_curve("secp256r1", "SECP256R1")
165 self._add_curve("secp384r1", "SECP384R1")
166 self._add_curve("secp521r1", "SECP521R1")
167 self._add_curve("secp192r1", "SECP192R1", deprecated=True)
168 self._add_curve("sect163k1", "SECT163K1", deprecated=True)
169 self._add_curve("sect163r2", "SECT163R2", deprecated=True)
170 self._add_curve("sect233k1", "SECT233K1", deprecated=True)
171 self._add_curve("sect233r1", "SECT233R1", deprecated=True)
172 self._add_curve("sect283k1", "SECT283K1", deprecated=True)
173 self._add_curve("sect283r1", "SECT283R1", deprecated=True)
174 self._add_curve("sect409k1", "SECT409K1", deprecated=True)
175 self._add_curve("sect409r1", "SECT409R1", deprecated=True)
176 self._add_curve("sect571k1", "SECT571K1", deprecated=True)
177 self._add_curve("sect571r1", "SECT571R1", deprecated=True)
178 self._add_curve("brainpoolP256r1", "BrainpoolP256R1", deprecated=True)
179 self._add_curve("brainpoolP384r1", "BrainpoolP384R1", deprecated=True)
180 self._add_curve("brainpoolP512r1", "BrainpoolP512R1", deprecated=True)
181
182 def _get_info(self, *, data: bytes | None) -> dict[str, t.Any]:
183 if data is None:
184 return {}
185 result: dict[str, t.Any] = {"can_parse_key": False}
186 try:
187 result.update(
188 get_privatekey_info(
189 module=self.module,
190 content=data,
191 passphrase=self.passphrase,
192 return_private_key_data=False,
193 prefer_one_fingerprint=True,
194 )
195 )
196 except PrivateKeyConsistencyError as exc:
197 result.update(exc.result)
198 except PrivateKeyParseError as exc:
199 result.update(exc.result)
200 except Exception:
201 pass
202 return result
203
204 def _get_wanted_format(self) -> t.Literal["pkcs1", "pkcs8", "raw"]:
205 if self.format not in ("auto", "auto_ignore"):
206 return self.format # type: ignore
207 if self.type in ("X25519", "X448", "Ed25519", "Ed448"):
208 return "pkcs8"
209 return "pkcs1"
210
211 def generate_private_key(self) -> None:
212 """(Re-)Generate private key."""
213 try:
214 if self.type == "RSA":
215 self.private_key = (
216 cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
217 public_exponent=65537, # OpenSSL always uses this
218 key_size=self.size,
219 )
220 )
221 if self.type == "DSA":
222 self.private_key = (
223 cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key(
224 key_size=self.size
225 )
226 )
227 if self.type == "X25519":
228 self.private_key = (
229 cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.generate()
230 )
231 if self.type == "X448":
232 self.private_key = (
233 cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey.generate()
234 )
235 if self.type == "Ed25519":
236 self.private_key = (
237 cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.generate()
238 )
239 if self.type == "Ed448":
240 self.private_key = (
241 cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey.generate()
242 )
243 if self.type == "ECC" and self.curve in self.curves:
244 if self.curves[self.curve].deprecated:
245 self.module.warn(
246 f"Elliptic curves of type {self.curve} should not be used for new keys!"
247 )
248 self.private_key = (
249 cryptography.hazmat.primitives.asymmetric.ec.generate_private_key(
250 curve=self.curves[self.curve].create(
251 size=self.size, module=self.module
252 ),
253 )
254 )
255 except cryptography.exceptions.UnsupportedAlgorithm:
256 self.module.fail_json(
257 msg=f"Cryptography backend does not support the algorithm required for {self.type}"
258 )
259
260 def convert_private_key(self) -> None:
261 """Convert existing private key (self.existing_private_key) to new private key (self.private_key).
262
263 This is effectively a copy without active conversion. The conversion is done
264 during load and store; get_private_key_data() uses the destination format to
265 serialize the key.
266 """
267 self._ensure_existing_private_key_loaded()
268 self.private_key = self.existing_private_key
269
270 def get_private_key_data(self) -> bytes:
271 """Return bytes for self.private_key"""
272 if self.private_key is None:
273 raise AssertionError("private_key not set") # pragma: no cover
274 # Select export format and encoding
275 try:
276 export_format_txt = self._get_wanted_format()
277 export_encoding = cryptography.hazmat.primitives.serialization.Encoding.PEM
278 if export_format_txt == "pkcs1":
279 # "TraditionalOpenSSL" format is PKCS1
280 export_format = (
281 cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL
282 )
283 elif export_format_txt == "pkcs8":
284 export_format = (
285 cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8
286 )
287 elif export_format_txt == "raw":
288 export_format = (
289 cryptography.hazmat.primitives.serialization.PrivateFormat.Raw
290 )
291 export_encoding = (
292 cryptography.hazmat.primitives.serialization.Encoding.Raw
293 )
294 else:
295 # pylint does not notice that all possible values for export_format_txt have been covered.
296 raise AssertionError("Can never be reached") # pragma: no cover
297 except AttributeError:
298 self.module.fail_json(
299 msg=f'Cryptography backend does not support the selected output format "{self.format}"'
300 )
301
302 # Select key encryption
303 encryption_algorithm: (
304 cryptography.hazmat.primitives.serialization.KeySerializationEncryption
305 ) = cryptography.hazmat.primitives.serialization.NoEncryption()
306 if self.cipher and self.passphrase:
307 if self.cipher == "auto":
308 encryption_algorithm = cryptography.hazmat.primitives.serialization.BestAvailableEncryption(
309 to_bytes(self.passphrase)
310 )
311 else:
312 self.module.fail_json(
313 msg='Cryptography backend can only use "auto" for cipher option.'
314 )
315
316 # Serialize key
317 try:
318 return self.private_key.private_bytes(
319 encoding=export_encoding,
320 format=export_format,
321 encryption_algorithm=encryption_algorithm,
322 )
323 except ValueError:
324 self.module.fail_json(
325 msg=f'Cryptography backend cannot serialize the private key in the required format "{self.format}"'
326 )
327 except Exception:
328 self.module.fail_json(
329 msg=f'Error while serializing the private key in the required format "{self.format}"',
330 exception=traceback.format_exc(),
331 )
332
333 def set_existing(self, *, privatekey_bytes: bytes | None) -> None:
334 """Set existing private key bytes. None indicates that the key does not exist."""
335 self.existing_private_key_bytes = privatekey_bytes
336 self.diff_after = self.diff_before = self._get_info(
337 data=self.existing_private_key_bytes
338 )
339
340 def has_existing(self) -> bool:
341 """Query whether an existing private key is/has been there."""
342 return self.existing_private_key_bytes is not None
343
344 def _load_privatekey(self) -> PrivateKeyTypes:
345 data = self.existing_private_key_bytes
346 if data is None:
347 raise AssertionError(
348 "existing_private_key_bytes not set"
349 ) # pragma: no cover
350 try:
351 # Interpret bytes depending on format.
352 key_format = identify_private_key_format(data)
353 if key_format == "raw":
354 if len(data) == 56:
355 return cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey.from_private_bytes(
356 data
357 )
358 if len(data) == 57:
359 return cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey.from_private_bytes(
360 data
361 )
362 if len(data) == 32:
363 if self.type == "X25519":
364 return cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(
365 data
366 )
367 if self.type == "Ed25519":
368 return cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(
369 data
370 )
371 try:
372 return cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(
373 data
374 )
375 except Exception:
376 return cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(
377 data
378 )
379 raise PrivateKeyError("Cannot load raw key")
380
381 return cryptography.hazmat.primitives.serialization.load_pem_private_key(
382 data,
383 None if self.passphrase is None else to_bytes(self.passphrase),
384 )
385 except Exception as e:
386 raise PrivateKeyError(e) from e
387
388 def _ensure_existing_private_key_loaded(self) -> None:
389 """Make sure that self.existing_private_key is populated from self.existing_private_key_bytes."""
390 if self.existing_private_key is None and self.has_existing():
391 self.existing_private_key = self._load_privatekey()
392
393 def _check_passphrase(self) -> bool:
394 """Check whether provided passphrase matches, assuming self.existing_private_key_bytes has been populated."""
395 if self.existing_private_key_bytes is None:
396 raise AssertionError(
397 "existing_private_key_bytes not set"
398 ) # pragma: no cover
399 try:
400 key_format = identify_private_key_format(self.existing_private_key_bytes)
401 if key_format == "raw":
402 # Raw keys cannot be encrypted. To avoid incompatibilities, we try to
403 # actually load the key (and return False when this fails).
404 self._load_privatekey()
405 # Loading the key succeeded. Only return True when no passphrase was
406 # provided.
407 return self.passphrase is None
408 return bool(
409 cryptography.hazmat.primitives.serialization.load_pem_private_key(
410 self.existing_private_key_bytes,
411 None if self.passphrase is None else to_bytes(self.passphrase),
412 )
413 )
414 except Exception:
415 return False
416
417 def _check_size_and_type(self) -> bool:
418 """Check whether provided size and type matches, assuming self.existing_private_key has been populated."""
419 if isinstance(
420 self.existing_private_key,
421 cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey,
422 ):
423 return (
424 self.type == "RSA" and self.size == self.existing_private_key.key_size
425 )
426 if isinstance(
427 self.existing_private_key,
428 cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey,
429 ):
430 return (
431 self.type == "DSA" and self.size == self.existing_private_key.key_size
432 )
433 if isinstance(
434 self.existing_private_key,
435 cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
436 ):
437 return self.type == "X25519"
438 if isinstance(
439 self.existing_private_key,
440 cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey,
441 ):
442 return self.type == "X448"
443 if isinstance(
444 self.existing_private_key,
445 cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey,
446 ):
447 return self.type == "Ed25519"
448 if isinstance(
449 self.existing_private_key,
450 cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey,
451 ):
452 return self.type == "Ed448"
453 if isinstance(
454 self.existing_private_key,
455 cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey,
456 ):
457 if self.type != "ECC":
458 return False
459 if self.curve not in self.curves:
460 return False
461 return self.curves[self.curve].verify(
462 privatekey=self.existing_private_key, module=self.module
463 )
464
465 return False
466
467 def _check_format(self) -> bool:
468 """Check whether the key file format, assuming self.existing_private_key and self.existing_private_key_bytes has been populated."""
469 if self.existing_private_key_bytes is None:
470 raise AssertionError(
471 "existing_private_key_bytes not set"
472 ) # pragma: no cover
473 if self.format == "auto_ignore":
474 return True
475 try:
476 key_format = identify_private_key_format(self.existing_private_key_bytes)
477 return key_format == self._get_wanted_format()
478 except Exception:
479 return False
480
481 def needs_regeneration(self) -> bool:
482 """Check whether a regeneration is necessary."""
483 if self.regenerate == "always":
484 return True
485 if not self.has_existing():
486 # key does not exist
487 return True
488 if not self._check_passphrase():
489 if self.regenerate == "full_idempotence":
490 return True
491 self.module.fail_json(
492 msg="Unable to read the key. The key is protected with a another passphrase / no passphrase or broken."
493 " Will not proceed. To force regeneration, call the module with `generate`"
494 " set to `full_idempotence` or `always`, or with `force=true`."
495 )
496 self._ensure_existing_private_key_loaded()
497 if self.regenerate != "never" and not self._check_size_and_type():
498 if self.regenerate in ("partial_idempotence", "full_idempotence"):
499 return True
500 self.module.fail_json(
501 msg="Key has wrong type and/or size."
502 " Will not proceed. To force regeneration, call the module with `generate`"
503 " set to `partial_idempotence`, `full_idempotence` or `always`, or with `force=true`."
504 )
505 # During generation step, regenerate if format does not match and format_mismatch == 'regenerate'
506 if (
507 self.format_mismatch == "regenerate"
508 and self.regenerate != "never"
509 and not self._check_format()
510 ):
511 if self.regenerate in ("partial_idempotence", "full_idempotence"):
512 return True
513 self.module.fail_json(
514 msg="Key has wrong format."
515 " Will not proceed. To force regeneration, call the module with `generate`"
516 " set to `partial_idempotence`, `full_idempotence` or `always`, or with `force=true`."
517 " To convert the key, set `format_mismatch` to `convert`."
518 )
519 return False
520
521 def needs_conversion(self) -> bool:
522 """Check whether a conversion is necessary. Must only be called if needs_regeneration() returned False."""
523 # During conversion step, convert if format does not match and format_mismatch == 'convert'
524 self._ensure_existing_private_key_loaded()
525 return (
526 self.has_existing()
527 and self.format_mismatch == "convert"
528 and not self._check_format()
529 )
530
531 def _get_fingerprint(self) -> dict[str, str] | None:
532 if self.private_key:
533 return get_fingerprint_of_privatekey(self.private_key)
534 try:
535 self._ensure_existing_private_key_loaded()
536 except Exception:
537 # Ignore errors
538 pass
539 if self.existing_private_key:
540 return get_fingerprint_of_privatekey(self.existing_private_key)
541 return None
542
543 def dump(self, *, include_key: bool) -> dict[str, t.Any]:
544 """Serialize the object into a dictionary."""
545
546 if not self.private_key:
547 try:
548 self._ensure_existing_private_key_loaded()
549 except Exception:
550 # Ignore errors
551 pass
552 result: dict[str, t.Any] = {
553 "type": self.type,
554 "size": self.size,
555 "fingerprint": self._get_fingerprint(),
556 }
557 if self.type == "ECC":
558 result["curve"] = self.curve
559 # Get hold of private key bytes
560 pk_bytes = self.existing_private_key_bytes
561 if self.private_key is not None:
562 pk_bytes = self.get_private_key_data()
563 self.diff_after = self._get_info(data=pk_bytes)
564 if include_key:
565 # Store result
566 if pk_bytes:
567 if identify_private_key_format(pk_bytes) == "raw":
568 result["privatekey"] = base64.b64encode(pk_bytes)
569 else:
570 result["privatekey"] = pk_bytes.decode("utf-8")
571 else:
572 result["privatekey"] = None
573
574 result["diff"] = {
575 "before": self.diff_before,
576 "after": self.diff_after,
577 }
578 return result
579
580
581 def select_backend(module: GeneralAnsibleModule) -> PrivateKeyBackend:
582 assert_required_cryptography_version(
583 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
584 )
585 return PrivateKeyBackend(module=module)
586
587
588 def get_privatekey_argument_spec() -> ArgumentSpec:
589 return ArgumentSpec(
590 argument_spec={
591 "size": {"type": "int", "default": 4096},
592 "type": {
593 "type": "str",
594 "default": "RSA",
595 "choices": ["DSA", "ECC", "Ed25519", "Ed448", "RSA", "X25519", "X448"],
596 },
597 "curve": {
598 "type": "str",
599 "choices": [
600 "secp224r1",
601 "secp256k1",
602 "secp256r1",
603 "secp384r1",
604 "secp521r1",
605 "secp192r1",
606 "brainpoolP256r1",
607 "brainpoolP384r1",
608 "brainpoolP512r1",
609 "sect163k1",
610 "sect163r2",
611 "sect233k1",
612 "sect233r1",
613 "sect283k1",
614 "sect283r1",
615 "sect409k1",
616 "sect409r1",
617 "sect571k1",
618 "sect571r1",
619 ],
620 },
621 "passphrase": {"type": "str", "no_log": True},
622 "cipher": {"type": "str", "default": "auto"},
623 "format": {
624 "type": "str",
625 "default": "auto_ignore",
626 "choices": ["pkcs1", "pkcs8", "raw", "auto", "auto_ignore"],
627 },
628 "format_mismatch": {
629 "type": "str",
630 "default": "regenerate",
631 "choices": ["regenerate", "convert"],
632 },
633 "select_crypto_backend": {
634 "type": "str",
635 "choices": ["auto", "cryptography"],
636 "default": "auto",
637 },
638 "regenerate": {
639 "type": "str",
640 "default": "full_idempotence",
641 "choices": [
642 "never",
643 "fail",
644 "partial_idempotence",
645 "full_idempotence",
646 "always",
647 ],
648 },
649 },
650 required_if=[
651 ("type", "ECC", ["curve"]),
652 ],
653 )
654
655
656 __all__ = (
657 "PrivateKeyBackend",
658 "PrivateKeyError",
659 "get_privatekey_argument_spec",
660 "select_backend",
661 )