Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/crypto_info.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2021 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 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: crypto_info
10 author: "Felix Fontein (@felixfontein)"
11 short_description: Retrieve cryptographic capabilities
12 version_added: 2.1.0
13 description:
14 - Retrieve information on cryptographic capabilities.
15 - The current version retrieves information on the L(Python cryptography library, https://cryptography.io/) available to
16 Ansible modules, and on the OpenSSL binary C(openssl) found in the path.
17 extends_documentation_fragment:
18 - community.crypto._attributes
19 - community.crypto._attributes.info_module
20 - community.crypto._attributes.idempotent_not_modify_state
21 options: {}
22 """
23
24 EXAMPLES = r"""
25 ---
26 - name: Retrieve information
27 community.crypto.crypto_info:
28 account_key_src: /etc/pki/cert/private/account.key
29 register: crypto_information
30
31 - name: Show retrieved information
32 ansible.builtin.debug:
33 var: crypto_information
34 """
35
36 RETURN = r"""
37 python_cryptography_installed:
38 description: Whether the L(Python cryptography library, https://cryptography.io/) is installed.
39 returned: always
40 type: bool
41 sample: true
42
43 python_cryptography_import_error:
44 description: Import error when trying to import the L(Python cryptography library, https://cryptography.io/).
45 returned: when RV(python_cryptography_installed=false)
46 type: str
47
48 python_cryptography_capabilities:
49 description: Information on the installed L(Python cryptography library, https://cryptography.io/).
50 returned: when RV(python_cryptography_installed=true)
51 type: dict
52 contains:
53 version:
54 description: The library version.
55 type: str
56 curves:
57 description:
58 - List of all supported elliptic curves.
59 - Theoretically this should be non-empty for version 0.5 and higher, depending on the libssl version used.
60 type: list
61 elements: str
62 has_ec:
63 description:
64 - Whether elliptic curves are supported.
65 - Theoretically this should be the case for version 0.5 and higher, depending on the libssl version used.
66 type: bool
67 has_ec_sign:
68 description:
69 - Whether signing with elliptic curves is supported.
70 - Theoretically this should be the case for version 1.5 and higher, depending on the libssl version used.
71 type: bool
72 has_ed25519:
73 description:
74 - Whether Ed25519 keys are supported.
75 - Theoretically this should be the case for version 2.6 and higher, depending on the libssl version used.
76 type: bool
77 has_ed25519_sign:
78 description:
79 - Whether signing with Ed25519 keys is supported.
80 - Theoretically this should be the case for version 2.6 and higher, depending on the libssl version used.
81 type: bool
82 has_ed448:
83 description:
84 - Whether Ed448 keys are supported.
85 - Theoretically this should be the case for version 2.6 and higher, depending on the libssl version used.
86 type: bool
87 has_ed448_sign:
88 description:
89 - Whether signing with Ed448 keys is supported.
90 - Theoretically this should be the case for version 2.6 and higher, depending on the libssl version used.
91 type: bool
92 has_dsa:
93 description:
94 - Whether DSA keys are supported.
95 - Theoretically this should be the case for version 0.5 and higher.
96 type: bool
97 has_dsa_sign:
98 description:
99 - Whether signing with DSA keys is supported.
100 - Theoretically this should be the case for version 1.5 and higher.
101 type: bool
102 has_rsa:
103 description:
104 - Whether RSA keys are supported.
105 - Theoretically this should be the case for version 0.5 and higher.
106 type: bool
107 has_rsa_sign:
108 description:
109 - Whether signing with RSA keys is supported.
110 - Theoretically this should be the case for version 1.4 and higher.
111 type: bool
112 has_x25519:
113 description:
114 - Whether X25519 keys are supported.
115 - Theoretically this should be the case for version 2.0 and higher, depending on the libssl version used.
116 type: bool
117 has_x25519_serialization:
118 description:
119 - Whether serialization of X25519 keys is supported.
120 - Theoretically this should be the case for version 2.5 and higher, depending on the libssl version used.
121 type: bool
122 has_x448:
123 description:
124 - Whether X448 keys are supported.
125 - Theoretically this should be the case for version 2.5 and higher, depending on the libssl version used.
126 type: bool
127
128 openssl_present:
129 description: Whether the OpenSSL binary C(openssl) is installed and can be found in the PATH.
130 returned: always
131 type: bool
132 sample: true
133
134 openssl:
135 description: Information on the installed OpenSSL binary.
136 returned: when RV(openssl_present=true)
137 type: dict
138 contains:
139 path:
140 description: Path of the OpenSSL binary.
141 type: str
142 sample: /usr/bin/openssl
143 version:
144 description: The OpenSSL version.
145 type: str
146 sample: 1.1.1m
147 version_output:
148 description: The complete output of C(openssl version).
149 type: str
150 sample: 'OpenSSL 1.1.1m 14 Dec 2021\n'
151 """
152
153 import traceback
154 import typing as t
155
156 from ansible.module_utils.basic import AnsibleModule
157
158 CRYPTOGRAPHY_VERSION: str | None
159 CRYPTOGRAPHY_IMP_ERR: str | None
160 try:
161 import cryptography
162 import cryptography.hazmat.primitives.asymmetric
163 from cryptography.exceptions import UnsupportedAlgorithm
164
165 try:
166 # While UnsupportedAlgorithm got added in cryptography 0.1, InternalError
167 # only got added in 0.2, so let's guard the import
168 from cryptography.exceptions import InternalError as CryptographyInternalError
169 except ImportError:
170 CryptographyInternalError = Exception # type: ignore
171 except ImportError:
172 UnsupportedAlgorithm = Exception # type: ignore
173 CryptographyInternalError = Exception # type: ignore
174 HAS_CRYPTOGRAPHY = False
175 CRYPTOGRAPHY_VERSION = None # pylint: disable=invalid-name
176 CRYPTOGRAPHY_IMP_ERR = traceback.format_exc() # pylint: disable=invalid-name
177 else:
178 HAS_CRYPTOGRAPHY = True
179 CRYPTOGRAPHY_VERSION = cryptography.__version__ # pylint: disable=invalid-name
180 CRYPTOGRAPHY_IMP_ERR = None # pylint: disable=invalid-name
181
182
183 CURVES = (
184 ("secp224r1", "SECP224R1"),
185 ("secp256k1", "SECP256K1"),
186 ("secp256r1", "SECP256R1"),
187 ("secp384r1", "SECP384R1"),
188 ("secp521r1", "SECP521R1"),
189 ("secp192r1", "SECP192R1"),
190 ("sect163k1", "SECT163K1"),
191 ("sect163r2", "SECT163R2"),
192 ("sect233k1", "SECT233K1"),
193 ("sect233r1", "SECT233R1"),
194 ("sect283k1", "SECT283K1"),
195 ("sect283r1", "SECT283R1"),
196 ("sect409k1", "SECT409K1"),
197 ("sect409r1", "SECT409R1"),
198 ("sect571k1", "SECT571K1"),
199 ("sect571r1", "SECT571R1"),
200 ("brainpoolP256r1", "BrainpoolP256R1"),
201 ("brainpoolP384r1", "BrainpoolP384R1"),
202 ("brainpoolP512r1", "BrainpoolP512R1"),
203 )
204
205
206 def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
207 result: dict[str, t.Any] = {}
208 result["python_cryptography_installed"] = HAS_CRYPTOGRAPHY
209 if not HAS_CRYPTOGRAPHY:
210 result["python_cryptography_import_error"] = CRYPTOGRAPHY_IMP_ERR
211 return result
212
213 # Test for DSA
214 has_dsa = False
215 has_dsa_sign = False
216 try:
217 # added in 0.5 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/dsa/
218 from cryptography.hazmat.primitives.asymmetric import dsa
219
220 has_dsa = True
221 try:
222 # added later in 1.5
223 dsa.DSAPrivateKey.sign # noqa: B018 # pylint: disable=pointless-statement
224 has_dsa_sign = True
225 except AttributeError:
226 pass
227 except ImportError:
228 pass
229
230 # Test for RSA
231 has_rsa = False
232 has_rsa_sign = False
233 try:
234 # added in 0.5 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/
235 from cryptography.hazmat.primitives.asymmetric import rsa
236
237 has_rsa = True
238 try:
239 # added later in 1.4
240 rsa.RSAPrivateKey.sign # noqa: B018 # pylint: disable=pointless-statement
241 has_rsa_sign = True
242 except AttributeError:
243 pass
244 except ImportError:
245 pass
246
247 # Test for Ed25519
248 has_ed25519 = False
249 has_ed25519_sign = False
250 try:
251 # added in 2.6 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ed25519/
252 from cryptography.hazmat.primitives.asymmetric import ed25519
253
254 try:
255 ed25519.Ed25519PrivateKey.from_private_bytes(b"")
256 except ValueError:
257 pass
258
259 has_ed25519 = True
260 try:
261 # added with the primitive in 2.6
262 ed25519.Ed25519PrivateKey.sign # noqa: B018 # pylint: disable=pointless-statement
263 has_ed25519_sign = True
264 except AttributeError:
265 pass
266 except (ImportError, UnsupportedAlgorithm):
267 pass
268
269 # Test for Ed448
270 has_ed448 = False
271 has_ed448_sign = False
272 try:
273 # added in 2.6 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ed448/
274 from cryptography.hazmat.primitives.asymmetric import ed448
275
276 try:
277 ed448.Ed448PrivateKey.from_private_bytes(b"")
278 except ValueError:
279 pass
280
281 has_ed448 = True
282 try:
283 # added with the primitive in 2.6
284 ed448.Ed448PrivateKey.sign # noqa: B018 # pylint: disable=pointless-statement
285 has_ed448_sign = True
286 except AttributeError:
287 pass
288 except (ImportError, UnsupportedAlgorithm):
289 pass
290
291 # Test for X25519
292 has_x25519 = False
293 has_x25519_full = False
294 try:
295 # added in 2.0 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/x25519/
296 from cryptography.hazmat.primitives.asymmetric import x25519
297
298 try:
299 # added later in 2.5
300 x25519.X25519PrivateKey.private_bytes # noqa: B018 # pylint: disable=pointless-statement
301 full = True
302 except AttributeError:
303 full = False
304
305 try:
306 if full:
307 x25519.X25519PrivateKey.from_private_bytes(b"")
308 else:
309 # Some versions do not support serialization and deserialization - use generate() instead
310 x25519.X25519PrivateKey.generate()
311 except ValueError:
312 pass
313
314 has_x25519 = True
315 has_x25519_full = full
316 except (ImportError, UnsupportedAlgorithm):
317 pass
318
319 # Test for X448
320 has_x448 = False
321 try:
322 # added in 2.5 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/x448/
323 from cryptography.hazmat.primitives.asymmetric import x448
324
325 try:
326 x448.X448PrivateKey.from_private_bytes(b"")
327 except ValueError:
328 pass
329
330 has_x448 = True
331 except (ImportError, UnsupportedAlgorithm):
332 pass
333
334 # Test for ECC
335 has_ec = False
336 has_ec_sign = False
337 curves = []
338 try:
339 # added in 0.5 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/
340 from cryptography.hazmat.primitives.asymmetric import ec
341
342 has_ec = True
343 try:
344 # added later in 1.5
345 ec.EllipticCurvePrivateKey.sign # noqa: B018 # pylint: disable=pointless-statement
346 has_ec_sign = True
347 except AttributeError:
348 pass
349 except ImportError:
350 pass
351 else:
352 for curve_name, constructor_name in CURVES:
353 ecclass = getattr(ec, constructor_name, None)
354 if ecclass is not None:
355 try:
356 ec.generate_private_key(curve=ecclass())
357 curves.append(curve_name)
358 except UnsupportedAlgorithm:
359 pass
360 except ( # pylint: disable=duplicate-except,bad-except-order
361 CryptographyInternalError
362 ):
363 # On Fedora 41, some curves result in InternalError. This is probably because
364 # Fedora's cryptography is linked against the system libssl, which has the
365 # curves removed.
366 pass
367
368 # Compose result
369 info = {
370 "version": CRYPTOGRAPHY_VERSION,
371 "curves": curves,
372 "has_ec": has_ec,
373 "has_ec_sign": has_ec_sign,
374 "has_ed25519": has_ed25519,
375 "has_ed25519_sign": has_ed25519_sign,
376 "has_ed448": has_ed448,
377 "has_ed448_sign": has_ed448_sign,
378 "has_dsa": has_dsa,
379 "has_dsa_sign": has_dsa_sign,
380 "has_rsa": has_rsa,
381 "has_rsa_sign": has_rsa_sign,
382 "has_x25519": has_x25519,
383 "has_x25519_serialization": has_x25519 and has_x25519_full,
384 "has_x448": has_x448,
385 }
386 result["python_cryptography_capabilities"] = info
387 return result
388
389
390 def add_openssl_information(module: AnsibleModule) -> dict[str, t.Any]:
391 openssl_binary = module.get_bin_path("openssl")
392 result: dict[str, t.Any] = {
393 "openssl_present": openssl_binary is not None,
394 }
395 if openssl_binary is None:
396 return result
397
398 openssl_result = {
399 "path": openssl_binary,
400 }
401 result["openssl"] = openssl_result
402
403 rc, out, _err = module.run_command([openssl_binary, "version"])
404 if rc == 0:
405 openssl_result["version_output"] = out
406 parts = out.split(None, 2)
407 if len(parts) > 1:
408 openssl_result["version"] = parts[1]
409
410 return result
411
412
413 INFO_FUNCTIONS = (
414 add_crypto_information,
415 add_openssl_information,
416 )
417
418
419 def main() -> t.NoReturn:
420 module = AnsibleModule(argument_spec={}, supports_check_mode=True)
421 result: dict[str, t.Any] = {}
422 for fn in INFO_FUNCTIONS:
423 result.update(fn(module))
424 module.exit_json(**result)
425
426
427 if __name__ == "__main__":
428 main()