Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/backend_openssl_cli.py

raw
1 # Copyright (c) 2016 Michael Gruener <[email protected]>
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 # 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 binascii
13 import datetime
14 import ipaddress
15 import os
16 import re
17 import tempfile
18 import traceback
19 import typing as t
20
21 from ansible.module_utils.common.text.converters import to_bytes, to_text
22
23 from ansible_collections.community.crypto.plugins.module_utils._acme.backends import (
24 CertificateInformation,
25 CryptoBackend,
26 )
27 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
28 BackendException,
29 KeyParsingError,
30 )
31 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
32 nopad_b64,
33 )
34 from ansible_collections.community.crypto.plugins.module_utils._crypto.math import (
35 convert_bytes_to_int,
36 )
37 from ansible_collections.community.crypto.plugins.module_utils._time import (
38 ensure_utc_timezone,
39 )
40
41 if t.TYPE_CHECKING:
42 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
43
44 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
45 Criterium,
46 )
47
48
49 _OPENSSL_ENVIRONMENT_UPDATE = {
50 "LANG": "C",
51 "LC_ALL": "C",
52 "LC_MESSAGES": "C",
53 "LC_CTYPE": "C",
54 }
55
56
57 def _extract_date(
58 out_text: str, *, name: str, cert_filename_suffix: str = ""
59 ) -> datetime.datetime:
60 matcher = re.search(rf"\s+{name}\s*:\s+(.*)", out_text)
61 if matcher is None:
62 raise BackendException(f"No '{name}' date found{cert_filename_suffix}")
63 date_str = matcher.group(1)
64 try:
65 # For some reason Python's strptime() does not return any timezone information,
66 # even though the information is there and a supported timezone for all supported
67 # Python implementations (GMT). So we have to modify the datetime object by
68 # replacing it by UTC.
69 return ensure_utc_timezone(
70 datetime.datetime.strptime(date_str, "%b %d %H:%M:%S %Y %Z")
71 )
72 except ValueError as exc:
73 raise BackendException(
74 f"Failed to parse '{name}' date{cert_filename_suffix}: {exc}"
75 ) from exc
76
77
78 def _decode_octets(octets_text: str) -> bytes:
79 return binascii.unhexlify(re.sub(r"(\s|:)", "", octets_text).encode("utf-8"))
80
81
82 @t.overload
83 def _extract_octets(
84 out_text: str,
85 *,
86 name: str,
87 required: t.Literal[False],
88 potential_prefixes: t.Iterable[str] | None = None,
89 ) -> bytes | None: ...
90
91
92 @t.overload
93 def _extract_octets(
94 out_text: str,
95 *,
96 name: str,
97 required: t.Literal[True],
98 potential_prefixes: t.Iterable[str] | None = None,
99 ) -> bytes: ...
100
101
102 def _extract_octets(
103 out_text: str,
104 *,
105 name: str,
106 required: bool = True,
107 potential_prefixes: t.Iterable[str] | None = None,
108 ) -> bytes | None:
109 part = (
110 f"(?:{'|'.join(re.escape(pp) for pp in potential_prefixes)})"
111 if potential_prefixes
112 else ""
113 )
114 regexp = rf"\s+{name}:\s*\n\s+{part}([A-Fa-f0-9]{{2}}(?::[A-Fa-f0-9]{{2}})*)\s*\n"
115 match = re.search(regexp, out_text, re.MULTILINE | re.DOTALL)
116 if match is not None:
117 return _decode_octets(match.group(1))
118 if not required:
119 return None
120 raise BackendException(f"No '{name}' octet string found")
121
122
123 def _extract_rsa_key(out_text: str, *, key_file: str | None = None) -> dict[str, t.Any]:
124 matcher = re.search(
125 r"modulus:\n\s+(?:00:)?([a-f0-9\:\s]+?)\npublicExponent",
126 out_text,
127 re.MULTILINE | re.DOTALL,
128 )
129 if matcher is None:
130 raise KeyParsingError("cannot parse RSA key: modulus not found")
131 pub_hex = matcher.group(1)
132
133 matcher = re.search(
134 r"\npublicExponent: ([0-9]+)", out_text, re.MULTILINE | re.DOTALL
135 )
136 if matcher is None:
137 raise KeyParsingError("cannot parse RSA key: public exponent not found")
138 pub_exp = matcher.group(1)
139 pub_exp = f"{int(pub_exp):x}"
140 if len(pub_exp) % 2:
141 pub_exp = f"0{pub_exp}"
142
143 return {
144 "key_file": key_file,
145 "type": "rsa",
146 "alg": "RS256",
147 "jwk": {
148 "kty": "RSA",
149 "e": nopad_b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
150 "n": nopad_b64(_decode_octets(pub_hex)),
151 },
152 "hash": "sha256",
153 }
154
155
156 def _extract_ec_key(out_text: str, *, key_file: str | None = None) -> dict[str, t.Any]:
157 pub_data = re.search(
158 r"pub:\s*\n\s+04:([a-f0-9\:\s]+?)\nASN1 OID: (\S+)(?:\nNIST CURVE: (\S+))?",
159 out_text,
160 re.MULTILINE | re.DOTALL,
161 )
162 if pub_data is None:
163 raise KeyParsingError("cannot parse elliptic curve key")
164 pub_hex = _decode_octets(pub_data.group(1))
165 asn1_oid_curve = pub_data.group(2).lower()
166 nist_curve = pub_data.group(3).lower() if pub_data.group(3) else None
167 if asn1_oid_curve == "prime256v1" or nist_curve == "p-256":
168 bits = 256
169 alg = "ES256"
170 hashalg = "sha256"
171 point_size = 32
172 curve = "P-256"
173 elif asn1_oid_curve == "secp384r1" or nist_curve == "p-384":
174 bits = 384
175 alg = "ES384"
176 hashalg = "sha384"
177 point_size = 48
178 curve = "P-384"
179 elif asn1_oid_curve == "secp521r1" or nist_curve == "p-521":
180 # Not yet supported on Let's Encrypt side, see
181 # https://github.com/letsencrypt/boulder/issues/2217
182 bits = 521
183 alg = "ES512"
184 hashalg = "sha512"
185 point_size = 66
186 curve = "P-521"
187 else:
188 raise KeyParsingError(
189 f"unknown elliptic curve: {asn1_oid_curve} / {nist_curve}"
190 )
191 num_bytes = (bits + 7) // 8
192 if len(pub_hex) != 2 * num_bytes:
193 raise KeyParsingError(
194 f"bad elliptic curve point ({asn1_oid_curve} / {nist_curve})"
195 )
196 return {
197 "key_file": key_file,
198 "type": "ec",
199 "alg": alg,
200 "jwk": {
201 "kty": "EC",
202 "crv": curve,
203 "x": nopad_b64(pub_hex[:num_bytes]),
204 "y": nopad_b64(pub_hex[num_bytes:]),
205 },
206 "hash": hashalg,
207 "point_size": point_size,
208 }
209
210
211 class OpenSSLCLIBackend(CryptoBackend):
212 def __init__(
213 self, *, module: AnsibleModule, openssl_binary: str | None = None
214 ) -> None:
215 super().__init__(module=module, with_timezone=True)
216 if openssl_binary is None:
217 openssl_binary = module.get_bin_path("openssl", True)
218 self.openssl_binary = openssl_binary
219
220 def parse_key(
221 self,
222 *,
223 key_file: str | os.PathLike | None = None,
224 key_content: str | None = None,
225 passphrase: str | None = None,
226 ) -> dict[str, t.Any]:
227 """
228 Parses an RSA or Elliptic Curve key file in PEM format and returns key_data.
229 Raises KeyParsingError in case of errors.
230 """
231 if passphrase is not None:
232 raise KeyParsingError("openssl backend does not support key passphrases")
233 # If key_file is not given, but key_content, write that to a temporary file
234 if key_file is None:
235 if key_content is None:
236 raise KeyParsingError(
237 "one of key_file and key_content must be specified"
238 )
239 fd, tmpsrc = tempfile.mkstemp()
240 self.module.add_cleanup_file(tmpsrc) # Ansible will delete the file on exit
241 f = os.fdopen(fd, "wb")
242 try:
243 f.write(key_content.encode("utf-8"))
244 key_file = tmpsrc
245 except Exception as err:
246 try:
247 f.close()
248 except Exception:
249 pass
250 raise KeyParsingError(
251 f"failed to create temporary content file: {err}",
252 exception=traceback.format_exc(),
253 ) from err
254 f.close()
255 # Parse key
256 account_key_type = None
257 with open(key_file, "r", encoding="utf-8") as fi:
258 for line in fi:
259 m = re.match(
260 r"^\s*-{5,}BEGIN\s+(EC|RSA)\s+PRIVATE\s+KEY-{5,}\s*$", line
261 )
262 if m is not None:
263 account_key_type = m.group(1).lower()
264 break
265 if account_key_type is None:
266 # This happens for example if openssl_privatekey created this key
267 # (as opposed to the OpenSSL binary). For now, we assume this is
268 # an RSA key.
269 # FIXME: add some kind of auto-detection
270 account_key_type = "rsa"
271 if account_key_type not in ("rsa", "ec"):
272 raise KeyParsingError(f'unknown key type "{account_key_type}"')
273
274 openssl_keydump_cmd = [
275 self.openssl_binary,
276 account_key_type,
277 "-in",
278 str(key_file),
279 "-noout",
280 "-text",
281 ]
282 rc, out, stderr = self.module.run_command(
283 openssl_keydump_cmd,
284 check_rc=False,
285 environ_update=_OPENSSL_ENVIRONMENT_UPDATE,
286 )
287 if rc != 0:
288 raise BackendException(
289 f"Error while running {' '.join(openssl_keydump_cmd)}: {stderr}"
290 )
291
292 out_text = to_text(out, errors="surrogate_or_strict")
293
294 if account_key_type == "rsa":
295 return _extract_rsa_key(
296 out_text, key_file=str(key_file) if key_file is not None else None
297 )
298 if account_key_type == "ec":
299 return _extract_ec_key(
300 out_text, key_file=str(key_file) if key_file is not None else None
301 )
302 raise KeyParsingError(
303 f"Internal error: unexpected account_key_type = {account_key_type!r}"
304 )
305
306 def sign(
307 self, *, payload64: str, protected64: str, key_data: dict[str, t.Any]
308 ) -> dict[str, t.Any]:
309 sign_payload = f"{protected64}.{payload64}".encode("utf8")
310 if key_data["type"] == "hmac":
311 hex_key = (
312 binascii.hexlify(base64.urlsafe_b64decode(key_data["jwk"]["k"]))
313 ).decode("ascii")
314 cmd_postfix = [
315 "-mac",
316 "hmac",
317 "-macopt",
318 f"hexkey:{hex_key}",
319 "-binary",
320 ]
321 else:
322 cmd_postfix = ["-sign", key_data["key_file"]]
323 openssl_sign_cmd = [
324 self.openssl_binary,
325 "dgst",
326 f"-{key_data['hash']}",
327 ] + cmd_postfix
328
329 out: bytes | str
330
331 rc, out, err = self.module.run_command(
332 openssl_sign_cmd,
333 data=sign_payload,
334 check_rc=False,
335 binary_data=True,
336 environ_update=_OPENSSL_ENVIRONMENT_UPDATE,
337 )
338 if rc != 0:
339 raise BackendException(
340 f"Error while running {' '.join(openssl_sign_cmd)}: {err}"
341 )
342
343 if key_data["type"] == "ec":
344 dummy, der_out, dummy2 = self.module.run_command(
345 [self.openssl_binary, "asn1parse", "-inform", "DER"],
346 data=out,
347 binary_data=True,
348 environ_update=_OPENSSL_ENVIRONMENT_UPDATE,
349 )
350 expected_len = 2 * key_data["point_size"]
351 sig = re.findall(
352 rf"prim:\s+INTEGER\s+:([0-9A-F]{{1,{expected_len}}})\n",
353 to_text(der_out, errors="surrogate_or_strict"),
354 )
355 if len(sig) != 2:
356 der_output = to_text(der_out, errors="surrogate_or_strict")
357 raise BackendException(
358 f"failed to generate Elliptic Curve signature; cannot parse DER output: {der_output}"
359 )
360 sig[0] = (expected_len - len(sig[0])) * "0" + sig[0]
361 sig[1] = (expected_len - len(sig[1])) * "0" + sig[1]
362 out = binascii.unhexlify(sig[0]) + binascii.unhexlify(sig[1])
363
364 return {
365 "protected": protected64,
366 "payload": payload64,
367 "signature": nopad_b64(to_bytes(out)),
368 }
369
370 def create_mac_key(self, *, alg: str, key: str) -> dict[str, t.Any]:
371 """Create a MAC key."""
372 if alg == "HS256":
373 hashalg = "sha256"
374 hashbytes = 32
375 elif alg == "HS384":
376 hashalg = "sha384"
377 hashbytes = 48
378 elif alg == "HS512":
379 hashalg = "sha512"
380 hashbytes = 64
381 else:
382 raise BackendException(
383 f"Unsupported MAC key algorithm for OpenSSL backend: {alg}"
384 )
385 key_bytes = base64.urlsafe_b64decode(key)
386 if len(key_bytes) < hashbytes:
387 raise BackendException(
388 f"{alg} key must be at least {hashbytes} bytes long (after Base64 decoding)"
389 )
390 return {
391 "type": "hmac",
392 "alg": alg,
393 "jwk": {
394 "kty": "oct",
395 "k": key,
396 },
397 "hash": hashalg,
398 }
399
400 @staticmethod
401 def _normalize_ip(ip: str) -> str:
402 try:
403 return ipaddress.ip_address(ip).compressed
404 except ValueError:
405 # We do not want to error out on something IPAddress() cannot parse
406 return ip
407
408 def get_ordered_csr_identifiers(
409 self,
410 *,
411 csr_filename: str | os.PathLike | None = None,
412 csr_content: str | bytes | None = None,
413 ) -> list[tuple[str, str]]:
414 """
415 Return a list of requested identifiers (CN and SANs) for the CSR.
416 Each identifier is a pair (type, identifier), where type is either
417 'dns' or 'ip'.
418
419 The list is deduplicated, and if a CNAME is present, it will be returned
420 as the first element in the result.
421 """
422 filename = csr_filename
423 data = None
424 if csr_content is not None:
425 filename = "/dev/stdin"
426 data = to_bytes(csr_content)
427
428 openssl_csr_cmd = [
429 self.openssl_binary,
430 "req",
431 "-in",
432 str(filename),
433 "-noout",
434 "-text",
435 ]
436 rc, out, err = self.module.run_command(
437 openssl_csr_cmd,
438 data=data,
439 check_rc=False,
440 binary_data=True,
441 environ_update=_OPENSSL_ENVIRONMENT_UPDATE,
442 )
443 if rc != 0:
444 raise BackendException(
445 f"Error while running {' '.join(openssl_csr_cmd)}: {err}"
446 )
447
448 identifiers = set()
449 result = []
450
451 def add_identifier(identifier: tuple[str, str]) -> None:
452 if identifier in identifiers:
453 return
454 identifiers.add(identifier)
455 result.append(identifier)
456
457 common_name = re.search(
458 r"Subject:.* CN\s?=\s?([^\s,;/]+)",
459 to_text(out, errors="surrogate_or_strict"),
460 )
461 if common_name is not None:
462 add_identifier(("dns", common_name.group(1)))
463 subject_alt_names = re.search(
464 r"X509v3 Subject Alternative Name: (?:critical)?\n +([^\n]+)\n",
465 to_text(out, errors="surrogate_or_strict"),
466 re.MULTILINE | re.DOTALL,
467 )
468 if subject_alt_names is not None:
469 for san in subject_alt_names.group(1).split(", "):
470 if san.lower().startswith("dns:"):
471 add_identifier(("dns", san[4:]))
472 elif san.lower().startswith("ip:"):
473 add_identifier(("ip", self._normalize_ip(san[3:])))
474 elif san.lower().startswith("ip address:"):
475 add_identifier(("ip", self._normalize_ip(san[11:])))
476 else:
477 raise BackendException(f'Found unsupported SAN identifier "{san}"')
478 return result
479
480 def get_csr_identifiers(
481 self,
482 *,
483 csr_filename: str | os.PathLike | None = None,
484 csr_content: str | bytes | None = None,
485 ) -> set[tuple[str, str]]:
486 """
487 Return a set of requested identifiers (CN and SANs) for the CSR.
488 Each identifier is a pair (type, identifier), where type is either
489 'dns' or 'ip'.
490 """
491 return set(
492 self.get_ordered_csr_identifiers(
493 csr_filename=csr_filename, csr_content=csr_content
494 )
495 )
496
497 def get_cert_days(
498 self,
499 *,
500 cert_filename: str | os.PathLike | None = None,
501 cert_content: str | bytes | None = None,
502 now: datetime.datetime | None = None,
503 ) -> int:
504 """
505 Return the days the certificate in cert_filename remains valid and -1
506 if the file was not found. If cert_filename contains more than one
507 certificate, only the first one will be considered.
508
509 If now is not specified, datetime.datetime.now() is used.
510 """
511 filename = cert_filename
512 data = None
513 if cert_content is not None:
514 filename = "/dev/stdin"
515 data = to_bytes(cert_content)
516 cert_filename_suffix = ""
517 elif cert_filename is not None:
518 if not os.path.exists(cert_filename):
519 return -1
520 cert_filename_suffix = f" in {cert_filename}"
521 else:
522 return -1
523
524 openssl_cert_cmd = [
525 self.openssl_binary,
526 "x509",
527 "-in",
528 str(filename),
529 "-noout",
530 "-text",
531 ]
532 rc, out, err = self.module.run_command(
533 openssl_cert_cmd,
534 data=data,
535 check_rc=False,
536 binary_data=True,
537 environ_update=_OPENSSL_ENVIRONMENT_UPDATE,
538 )
539 if rc != 0:
540 raise BackendException(
541 f"Error while running {' '.join(openssl_cert_cmd)}: {err}"
542 )
543
544 out_text = to_text(out, errors="surrogate_or_strict")
545 not_after = _extract_date(
546 out_text, name="Not After", cert_filename_suffix=cert_filename_suffix
547 )
548 if now is None:
549 now = self.get_now()
550 else:
551 now = ensure_utc_timezone(now)
552 return (not_after - now).days
553
554 def create_chain_matcher(self, *, criterium: Criterium) -> t.NoReturn:
555 """
556 Given a Criterium object, creates a ChainMatcher object.
557 """
558 raise BackendException(
559 'Alternate chain matching can only be used with the "cryptography" backend.'
560 )
561
562 def get_cert_information(
563 self,
564 *,
565 cert_filename: str | os.PathLike | None = None,
566 cert_content: str | bytes | None = None,
567 ) -> CertificateInformation:
568 """
569 Return some information on a X.509 certificate as a CertificateInformation object.
570 """
571 filename = cert_filename
572 data = None
573 if cert_filename is not None:
574 cert_filename_suffix = f" in {cert_filename}"
575 else:
576 filename = "/dev/stdin"
577 data = to_bytes(cert_content)
578 cert_filename_suffix = ""
579
580 openssl_cert_cmd = [
581 self.openssl_binary,
582 "x509",
583 "-in",
584 str(filename),
585 "-noout",
586 "-text",
587 ]
588 rc, out, err = self.module.run_command(
589 openssl_cert_cmd,
590 data=data,
591 check_rc=False,
592 binary_data=True,
593 environ_update=_OPENSSL_ENVIRONMENT_UPDATE,
594 )
595 if rc != 0:
596 raise BackendException(
597 f"Error while running {' '.join(openssl_cert_cmd)}: {err}"
598 )
599
600 out_text = to_text(out, errors="surrogate_or_strict")
601
602 not_after = _extract_date(
603 out_text, name="Not After", cert_filename_suffix=cert_filename_suffix
604 )
605 not_before = _extract_date(
606 out_text, name="Not Before", cert_filename_suffix=cert_filename_suffix
607 )
608
609 sn = re.search(
610 r" Serial Number: ([0-9]+)",
611 to_text(out, errors="surrogate_or_strict"),
612 re.MULTILINE | re.DOTALL,
613 )
614 if sn:
615 serial = int(sn.group(1))
616 else:
617 serial = convert_bytes_to_int(
618 _extract_octets(out_text, name="Serial Number", required=True)
619 )
620
621 ski = _extract_octets(
622 out_text, name="X509v3 Subject Key Identifier", required=False
623 )
624 aki = _extract_octets(
625 out_text,
626 name="X509v3 Authority Key Identifier",
627 required=False,
628 potential_prefixes=["keyid:", ""],
629 )
630
631 return CertificateInformation(
632 not_valid_after=not_after,
633 not_valid_before=not_before,
634 serial_number=serial,
635 subject_key_identifier=ski,
636 authority_key_identifier=aki,
637 )
638
639
640 __all__ = ("OpenSSLCLIBackend",)