Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/utils.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 datetime
13 import os
14 import re
15 import textwrap
16 import traceback
17 import typing as t
18 from collections.abc import Callable
19 from urllib.parse import unquote
20
21 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
22 ModuleFailException,
23 )
24 from ansible_collections.community.crypto.plugins.module_utils._crypto.math import (
25 convert_int_to_bytes,
26 )
27 from ansible_collections.community.crypto.plugins.module_utils._time import (
28 get_now_datetime,
29 )
30
31 if t.TYPE_CHECKING:
32 from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
33 CertificateInformation,
34 CryptoBackend,
35 )
36
37
38 def nopad_b64(data: bytes) -> str:
39 return base64.urlsafe_b64encode(data).decode("utf8").replace("=", "")
40
41
42 def der_to_pem(der_cert: bytes) -> str:
43 """
44 Convert the DER format certificate in der_cert to a PEM format certificate and return it.
45 """
46 content = "\n".join(textwrap.wrap(base64.b64encode(der_cert).decode("utf8"), 64))
47 return f"-----BEGIN CERTIFICATE-----\n{content}\n-----END CERTIFICATE-----\n"
48
49
50 def pem_to_der(
51 *, pem_filename: str | os.PathLike | None = None, pem_content: str | None = None
52 ) -> bytes:
53 """
54 Load PEM file, or use PEM file's content, and convert to DER.
55
56 If PEM contains multiple entities, the first entity will be used.
57 """
58 certificate_lines = []
59 if pem_content is not None:
60 lines = pem_content.splitlines()
61 elif pem_filename is not None:
62 try:
63 with open(pem_filename, "r", encoding="utf-8") as f:
64 lines = list(f)
65 except Exception as err:
66 raise ModuleFailException(
67 f"cannot load PEM file {pem_filename}: {err}",
68 exception=traceback.format_exc(),
69 ) from err
70 else:
71 raise ModuleFailException(
72 "One of pem_filename and pem_content must be provided"
73 )
74 header_line_count = 0
75 for line in lines:
76 if line.startswith("-----"):
77 header_line_count += 1
78 if header_line_count == 2:
79 # If certificate file contains other certs appended
80 # (like intermediate certificates), ignore these.
81 break
82 continue
83 certificate_lines.append(line.strip())
84 return base64.b64decode("".join(certificate_lines))
85
86
87 def process_links(
88 *, info: dict[str, t.Any], callback: Callable[[str, str], None]
89 ) -> None:
90 """
91 Process link header, calls callback for every link header with the URL and relation as options.
92
93 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
94 """
95 if "link" in info:
96 link = info["link"]
97 for url, relation in re.findall(r'<([^>]+)>;\s*rel="(\w+)"', link):
98 callback(unquote(url), relation)
99
100
101 def parse_retry_after(
102 value: str,
103 *,
104 relative_with_timezone: bool = True,
105 now: datetime.datetime | None = None,
106 ) -> datetime.datetime:
107 """
108 Parse the value of a Retry-After header and return a timestamp.
109
110 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
111 """
112 # First try a number of seconds
113 try:
114 delta = datetime.timedelta(seconds=int(value))
115 if now is None:
116 now = get_now_datetime(with_timezone=relative_with_timezone)
117 return now + delta
118 except ValueError:
119 pass
120
121 try:
122 return datetime.datetime.strptime(value, "%a, %d %b %Y %H:%M:%S GMT")
123 except ValueError:
124 pass
125
126 raise ValueError(f"Cannot parse Retry-After header value {repr(value)}")
127
128
129 def compute_cert_id(
130 *,
131 backend: CryptoBackend,
132 cert_info: CertificateInformation | None = None,
133 cert_filename: str | os.PathLike | None = None,
134 cert_content: str | bytes | None = None,
135 none_if_required_information_is_missing: bool = False,
136 ) -> str | None:
137 # Obtain certificate info if not provided
138 if cert_info is None:
139 cert_info = backend.get_cert_information(
140 cert_filename=cert_filename, cert_content=cert_content
141 )
142
143 # Convert Authority Key Identifier to string
144 if cert_info.authority_key_identifier is None:
145 if none_if_required_information_is_missing:
146 return None
147 raise ModuleFailException(
148 "Certificate has no Authority Key Identifier extension"
149 )
150 aki = (
151 (base64.urlsafe_b64encode(cert_info.authority_key_identifier))
152 .decode("ascii")
153 .replace("=", "")
154 )
155
156 # Convert serial number to string
157 serial_bytes = convert_int_to_bytes(cert_info.serial_number)
158 if ord(serial_bytes[:1]) >= 128:
159 serial_bytes = b"\x00" + serial_bytes
160 serial = (base64.urlsafe_b64encode(serial_bytes)).decode("ascii").replace("=", "")
161
162 # Compose cert ID
163 return f"{aki}.{serial}"
164
165
166 __all__ = (
167 "compute_cert_id",
168 "der_to_pem",
169 "nopad_b64",
170 "parse_retry_after",
171 "pem_to_der",
172 "process_links",
173 )