Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/support.py

raw
1 # Copyright (c) 2016, Yanis Guenane <[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 errno
12 import hashlib
13 import os
14 import typing as t
15
16 from ansible.module_utils.common.text.converters import to_bytes
17
18 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
19 is_potential_certificate_issuer_private_key,
20 is_potential_certificate_private_key,
21 )
22 from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import (
23 identify_pem_format,
24 )
25
26 try:
27 from cryptography import x509
28 from cryptography.exceptions import UnsupportedAlgorithm
29 from cryptography.hazmat.primitives import hashes, serialization
30 from cryptography.hazmat.primitives.serialization import load_pem_private_key
31 except ImportError:
32 # Error handled in the calling module.
33 pass
34
35 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
36 OpenSSLBadPassphraseError,
37 OpenSSLObjectError,
38 )
39
40 if t.TYPE_CHECKING:
41 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
42 from cryptography.hazmat.primitives.asymmetric.types import ( # pragma: no cover
43 CertificateIssuerPrivateKeyTypes,
44 PrivateKeyTypes,
45 PublicKeyTypes,
46 )
47
48 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover
49 CertificatePrivateKeyTypes,
50 )
51
52
53 # This list of preferred fingerprints is used when prefer_one=True is supplied to the
54 # fingerprinting methods.
55 PREFERRED_FINGERPRINTS = (
56 "sha256",
57 "sha3_256",
58 "sha512",
59 "sha3_512",
60 "sha384",
61 "sha3_384",
62 "sha1",
63 "md5",
64 )
65
66
67 def get_fingerprint_of_bytes(
68 source: bytes, *, prefer_one: bool = False
69 ) -> dict[str, str]:
70 """Generate the fingerprint of the given bytes."""
71
72 fingerprint = {}
73
74 algorithms: t.Iterable[str] = hashlib.algorithms_guaranteed
75
76 if prefer_one:
77 # Sort algorithms to have the ones in PREFERRED_FINGERPRINTS at the beginning
78 prefered_algorithms = [
79 algorithm for algorithm in PREFERRED_FINGERPRINTS if algorithm in algorithms
80 ]
81 prefered_algorithms += sorted(
82 [
83 algorithm
84 for algorithm in algorithms
85 if algorithm not in PREFERRED_FINGERPRINTS
86 ]
87 )
88 algorithms = prefered_algorithms
89
90 for algo in algorithms:
91 f = getattr(hashlib, algo)
92 try:
93 h = f(source)
94 except ValueError:
95 # This can happen for hash algorithms not supported in FIPS mode
96 # (https://github.com/ansible/ansible/issues/67213)
97 continue
98 try:
99 # Certain hash functions have a hexdigest() which expects a length parameter
100 pubkey_digest = h.hexdigest()
101 except TypeError:
102 pubkey_digest = h.hexdigest(32)
103 fingerprint[algo] = ":".join(
104 pubkey_digest[i : i + 2] for i in range(0, len(pubkey_digest), 2)
105 )
106 if prefer_one:
107 break
108
109 return fingerprint
110
111
112 def get_fingerprint_of_privatekey(
113 privatekey: PrivateKeyTypes, *, prefer_one: bool = False
114 ) -> dict[str, str]:
115 """Generate the fingerprint of the public key."""
116
117 publickey = privatekey.public_key().public_bytes(
118 serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
119 )
120
121 return get_fingerprint_of_bytes(publickey, prefer_one=prefer_one)
122
123
124 def get_fingerprint(
125 *,
126 path: os.PathLike | str | None = None,
127 passphrase: str | bytes | None = None,
128 content: bytes | None = None,
129 prefer_one: bool = False,
130 ) -> dict[str, str]:
131 """Generate the fingerprint of the public key."""
132
133 privatekey = load_privatekey(
134 path=path,
135 passphrase=passphrase,
136 content=content,
137 check_passphrase=False,
138 )
139
140 return get_fingerprint_of_privatekey(privatekey, prefer_one=prefer_one)
141
142
143 def load_privatekey(
144 *,
145 path: os.PathLike | str | None = None,
146 passphrase: str | bytes | None = None,
147 check_passphrase: bool = True,
148 content: bytes | None = None,
149 ) -> PrivateKeyTypes:
150 """Load the specified OpenSSL private key.
151
152 The content can also be specified via content; in that case,
153 this function will not load the key from disk.
154 """
155
156 try:
157 if content is None:
158 if path is None:
159 raise OpenSSLObjectError("Must provide either path or content")
160 with open(path, "rb") as b_priv_key_fh:
161 priv_key_detail = b_priv_key_fh.read()
162 else:
163 priv_key_detail = content
164 except (IOError, OSError) as exc:
165 raise OpenSSLObjectError(exc) from exc
166
167 try:
168 return load_pem_private_key(
169 priv_key_detail,
170 None if passphrase is None else to_bytes(passphrase),
171 )
172 except UnsupportedAlgorithm as exc:
173 raise OpenSSLBadPassphraseError(f"Unsupported private key type: {exc}") from exc
174 except TypeError as exc:
175 raise OpenSSLBadPassphraseError(
176 "Wrong or empty passphrase provided for private key"
177 ) from exc
178 except ValueError as exc:
179 raise OpenSSLBadPassphraseError(
180 f"Wrong passphrase provided for private key, or private key cannot be parsed: {exc}"
181 ) from exc
182
183
184 def load_certificate_privatekey(
185 *,
186 path: os.PathLike | str | None = None,
187 content: bytes | None = None,
188 passphrase: str | bytes | None = None,
189 check_passphrase: bool = True,
190 ) -> CertificatePrivateKeyTypes:
191 """
192 Load the specified OpenSSL private key that can be used as a private key for certificates.
193 """
194 private_key = load_privatekey(
195 path=path,
196 passphrase=passphrase,
197 check_passphrase=check_passphrase,
198 content=content,
199 )
200 if not is_potential_certificate_private_key(private_key):
201 raise OpenSSLObjectError(
202 f"Key of type {type(private_key)} not supported for certificates"
203 )
204 return private_key
205
206
207 def load_certificate_issuer_privatekey(
208 *,
209 path: os.PathLike | str | None = None,
210 content: bytes | None = None,
211 passphrase: str | bytes | None = None,
212 check_passphrase: bool = True,
213 ) -> CertificateIssuerPrivateKeyTypes:
214 """
215 Load the specified OpenSSL private key that can be used for issuing certificates.
216 """
217 private_key = load_privatekey(
218 path=path,
219 passphrase=passphrase,
220 check_passphrase=check_passphrase,
221 content=content,
222 )
223 if not is_potential_certificate_issuer_private_key(private_key):
224 raise OpenSSLObjectError(
225 f"Key of type {type(private_key)} not supported for issuing certificates"
226 )
227 return private_key
228
229
230 def load_publickey(
231 *, path: os.PathLike | str | None = None, content: bytes | None = None
232 ) -> PublicKeyTypes:
233 if content is None:
234 if path is None:
235 raise OpenSSLObjectError("Must provide either path or content")
236 try:
237 with open(path, "rb") as b_priv_key_fh:
238 content = b_priv_key_fh.read()
239 except (IOError, OSError) as exc:
240 raise OpenSSLObjectError(exc) from exc
241
242 try:
243 return serialization.load_pem_public_key(content)
244 except Exception as e:
245 raise OpenSSLObjectError(f"Error while deserializing key: {e}") from e
246
247
248 def load_certificate(
249 *,
250 path: os.PathLike | str | None = None,
251 content: bytes | None = None,
252 der_support_enabled: bool = False,
253 ) -> x509.Certificate:
254 """Load the specified certificate."""
255
256 try:
257 if content is None:
258 if path is None:
259 raise OpenSSLObjectError("Must provide either path or content")
260 with open(path, "rb") as cert_fh:
261 cert_content = cert_fh.read()
262 else:
263 cert_content = content
264 except (IOError, OSError) as exc:
265 raise OpenSSLObjectError(exc) from exc
266 if der_support_enabled is False or identify_pem_format(cert_content):
267 try:
268 return x509.load_pem_x509_certificate(cert_content)
269 except ValueError as exc:
270 raise OpenSSLObjectError(exc) from exc
271 elif der_support_enabled:
272 try:
273 return x509.load_der_x509_certificate(cert_content)
274 except ValueError as exc:
275 raise OpenSSLObjectError(f"Cannot parse DER certificate: {exc}") from exc
276
277
278 def load_certificate_request(
279 *, path: os.PathLike | str | None = None, content: bytes | None = None
280 ) -> x509.CertificateSigningRequest:
281 """Load the specified certificate signing request."""
282 try:
283 if content is None:
284 if path is None:
285 raise OpenSSLObjectError("Must provide either path or content")
286 with open(path, "rb") as csr_fh:
287 csr_content = csr_fh.read()
288 else:
289 csr_content = content
290 except (IOError, OSError) as exc:
291 raise OpenSSLObjectError(exc) from exc
292 try:
293 return x509.load_pem_x509_csr(csr_content)
294 except ValueError as exc:
295 raise OpenSSLObjectError(exc) from exc
296
297
298 @t.overload
299 def parse_name_field(
300 input_dict: dict[str, list[str] | str],
301 *,
302 name_field_name: str | None = None,
303 ) -> list[tuple[str, str]]: ...
304
305
306 @t.overload
307 def parse_name_field(
308 input_dict: dict[str, list[str | bytes] | str | bytes],
309 *,
310 name_field_name: str | None = None,
311 ) -> list[tuple[str, str | bytes]]: ...
312
313
314 def parse_name_field(
315 input_dict: dict[str, t.Any],
316 *,
317 name_field_name: str | None = None,
318 ) -> list:
319 """Take a dict with key: value or key: list_of_values mappings and return a list of tuples"""
320
321 def error_str(key: str) -> str:
322 if name_field_name is None:
323 return f"{key}"
324 return f"{key} in {name_field_name}"
325
326 result = []
327 for key, value in input_dict.items():
328 if isinstance(value, list):
329 for entry in value:
330 if not isinstance(entry, (str, bytes)):
331 raise TypeError(f"Values {error_str(key)} must be strings")
332 if not entry:
333 raise ValueError(
334 f"Values for {error_str(key)} must not be empty strings"
335 )
336 result.append((key, entry))
337 elif isinstance(value, (str, bytes)):
338 if not value:
339 raise ValueError(
340 f"Value for {error_str(key)} must not be an empty string"
341 )
342 result.append((key, value))
343 else:
344 raise TypeError(
345 f"Value for {error_str(key)} must be either a string or a list of strings"
346 )
347 return result
348
349
350 @t.overload
351 def parse_ordered_name_field(
352 input_list: list[dict[str, list[str] | str]],
353 *,
354 name_field_name: str,
355 ) -> list[tuple[str, str]]: ...
356
357
358 @t.overload
359 def parse_ordered_name_field(
360 input_list: list[dict[str, list[str | bytes] | str | bytes]],
361 *,
362 name_field_name: str,
363 ) -> list[tuple[str, str | bytes]]: ...
364
365
366 def parse_ordered_name_field(
367 input_list: list[dict[str, t.Any]],
368 *,
369 name_field_name: str,
370 ) -> list:
371 """Take a dict with key: value or key: list_of_values mappings and return a list of tuples"""
372
373 result = []
374 for index, entry in enumerate(input_list):
375 if len(entry) != 1:
376 raise ValueError(
377 f"Entry #{index + 1} in {name_field_name} must be a dictionary with exactly one key-value pair"
378 )
379 try:
380 result.extend(parse_name_field(entry, name_field_name=name_field_name))
381 except (TypeError, ValueError) as exc:
382 raise ValueError(
383 f"Error while processing entry #{index + 1} in {name_field_name}: {exc}"
384 ) from exc
385 return result
386
387
388 @t.overload
389 def select_message_digest(
390 digest_string: t.Literal["sha256", "sha384", "sha512", "sha1", "md5"],
391 ) -> hashes.SHA256 | hashes.SHA384 | hashes.SHA512 | hashes.SHA1 | hashes.MD5: ...
392
393
394 @t.overload
395 def select_message_digest(
396 digest_string: str,
397 ) -> (
398 hashes.SHA256 | hashes.SHA384 | hashes.SHA512 | hashes.SHA1 | hashes.MD5 | None
399 ): ...
400
401
402 def select_message_digest(
403 digest_string: str,
404 ) -> hashes.SHA256 | hashes.SHA384 | hashes.SHA512 | hashes.SHA1 | hashes.MD5 | None:
405 if digest_string == "sha256":
406 return hashes.SHA256()
407 if digest_string == "sha384":
408 return hashes.SHA384()
409 if digest_string == "sha512":
410 return hashes.SHA512()
411 if digest_string == "sha1":
412 return hashes.SHA1()
413 if digest_string == "md5":
414 return hashes.MD5()
415 return None
416
417
418 class OpenSSLObject(metaclass=abc.ABCMeta):
419 def __init__(self, *, path: str, state: str, force: bool, check_mode: bool) -> None:
420 self.path = path
421 self.state = state
422 self.force = force
423 self.name = os.path.basename(path)
424 self.changed = False
425 self.check_mode = check_mode
426
427 def check(self, module: AnsibleModule, *, perms_required: bool = True) -> bool:
428 """Ensure the resource is in its desired state."""
429
430 def _check_state() -> bool:
431 return os.path.exists(self.path)
432
433 def _check_perms(module: AnsibleModule) -> bool:
434 file_args = module.load_file_common_arguments(module.params)
435 if module.check_file_absent_if_check_mode(file_args["path"]):
436 return False
437 return not module.set_fs_attributes_if_different(file_args, False)
438
439 if not perms_required:
440 return _check_state()
441
442 return _check_state() and _check_perms(module)
443
444 @abc.abstractmethod
445 def dump(self) -> dict[str, t.Any]:
446 """Serialize the object into a dictionary."""
447
448 @abc.abstractmethod
449 def generate(self, module: AnsibleModule) -> None:
450 """Generate the resource."""
451
452 def remove(self, module: AnsibleModule) -> None:
453 """Remove the resource from the filesystem."""
454 if self.check_mode:
455 if os.path.exists(self.path):
456 self.changed = True
457 return
458
459 try:
460 os.remove(self.path)
461 self.changed = True
462 except OSError as exc:
463 if exc.errno != errno.ENOENT:
464 raise OpenSSLObjectError(exc) from exc
465
466
467 __all__ = (
468 "OpenSSLObject",
469 "get_fingerprint",
470 "get_fingerprint_of_bytes",
471 "get_fingerprint_of_privatekey",
472 "load_certificate",
473 "load_certificate_issuer_privatekey",
474 "load_certificate_privatekey",
475 "load_certificate_request",
476 "load_privatekey",
477 "load_publickey",
478 "parse_name_field",
479 "parse_ordered_name_field",
480 "select_message_digest",
481 )