Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/backends.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 abc
12 import datetime
13 import re
14 import typing as t
15
16 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
17 BackendException,
18 )
19 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
20 OpenSSLObjectError,
21 )
22 from ansible_collections.community.crypto.plugins.module_utils._time import (
23 UTC,
24 ensure_utc_timezone,
25 from_epoch_seconds,
26 get_epoch_seconds,
27 get_now_datetime,
28 get_relative_time_option,
29 remove_timezone,
30 )
31
32 if t.TYPE_CHECKING:
33 import os # pragma: no cover
34
35 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
36
37 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
38 ChainMatcher,
39 Criterium,
40 )
41
42
43 class CertificateInformation(t.NamedTuple):
44 not_valid_after: datetime.datetime
45 not_valid_before: datetime.datetime
46 serial_number: int
47 subject_key_identifier: bytes | None
48 authority_key_identifier: bytes | None
49
50
51 _FRACTIONAL_MATCHER = re.compile(
52 r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(|\.\d+)(Z|[+-]\d{2}:?\d{2}.*)$"
53 )
54
55
56 def _reduce_fractional_digits(timestamp_str: str) -> str:
57 """
58 Given a RFC 3339 timestamp that includes too many digits for the fractional seconds part, reduces these to at most 6.
59 """
60 # RFC 3339 (https://www.rfc-editor.org/info/rfc3339)
61 m = _FRACTIONAL_MATCHER.match(timestamp_str)
62 if not m:
63 raise BackendException(f"Cannot parse ISO 8601 timestamp {timestamp_str!r}")
64 timestamp, fractional, timezone = m.groups()
65 if len(fractional) > 7:
66 # Python does not support anything smaller than microseconds
67 # (Golang supports nanoseconds, Boulder often emits more fractional digits, which Python chokes on)
68 fractional = fractional[:7]
69 return f"{timestamp}{fractional}{timezone}"
70
71
72 def _parse_acme_timestamp(
73 timestamp_str: str, *, with_timezone: bool
74 ) -> datetime.datetime:
75 """
76 Parses a RFC 3339 timestamp.
77 """
78 # RFC 3339 (https://www.rfc-editor.org/info/rfc3339)
79 timestamp_str = _reduce_fractional_digits(timestamp_str)
80 for time_format in (
81 "%Y-%m-%dT%H:%M:%SZ",
82 "%Y-%m-%dT%H:%M:%S.%fZ",
83 "%Y-%m-%dT%H:%M:%S%z",
84 "%Y-%m-%dT%H:%M:%S.%f%z",
85 ):
86 try:
87 result = datetime.datetime.strptime(timestamp_str, time_format)
88 except ValueError:
89 pass
90 else:
91 return (
92 ensure_utc_timezone(result)
93 if with_timezone
94 else remove_timezone(result)
95 )
96 raise BackendException(f"Cannot parse ISO 8601 timestamp {timestamp_str!r}")
97
98
99 class CryptoBackend(metaclass=abc.ABCMeta):
100 def __init__(self, *, module: AnsibleModule, with_timezone: bool = False) -> None:
101 self.module = module
102 self._with_timezone = with_timezone
103
104 def get_now(self) -> datetime.datetime:
105 return get_now_datetime(with_timezone=self._with_timezone)
106
107 def parse_acme_timestamp(self, timestamp_str: str) -> datetime.datetime:
108 # RFC 3339 (https://www.rfc-editor.org/info/rfc3339)
109 return _parse_acme_timestamp(timestamp_str, with_timezone=self._with_timezone)
110
111 def parse_module_parameter(self, *, value: str, name: str) -> datetime.datetime:
112 try:
113 result = get_relative_time_option(
114 value, input_name=name, with_timezone=self._with_timezone
115 )
116 if result is None:
117 raise BackendException(f"Invalid value for {name}: {value!r}")
118 return result
119 except OpenSSLObjectError as exc:
120 raise BackendException(str(exc)) from exc
121
122 def interpolate_timestamp(
123 self,
124 timestamp_start: datetime.datetime,
125 timestamp_end: datetime.datetime,
126 *,
127 percentage: float,
128 ) -> datetime.datetime:
129 start = get_epoch_seconds(timestamp_start)
130 end = get_epoch_seconds(timestamp_end)
131 return from_epoch_seconds(
132 start + percentage * (end - start), with_timezone=self._with_timezone
133 )
134
135 def get_utc_datetime(
136 self,
137 year: int,
138 month: int,
139 day: int,
140 hour: int = 0,
141 minute: int = 0,
142 second: int = 0,
143 microsecond: int = 0,
144 tzinfo: datetime.timezone | None = None,
145 ) -> datetime.datetime:
146 has_tzinfo = tzinfo is not None
147 if self._with_timezone and not has_tzinfo:
148 tzinfo = UTC
149 result = datetime.datetime(
150 year, month, day, hour, minute, second, microsecond, tzinfo
151 )
152 if self._with_timezone and has_tzinfo:
153 result = ensure_utc_timezone(result)
154 return result
155
156 @abc.abstractmethod
157 def parse_key(
158 self,
159 *,
160 key_file: str | os.PathLike | None = None,
161 key_content: str | None = None,
162 passphrase: str | None = None,
163 ) -> dict[str, t.Any]:
164 """
165 Parses an RSA or Elliptic Curve key file in PEM format and returns key_data.
166 Raises KeyParsingError in case of errors.
167 """
168
169 @abc.abstractmethod
170 def sign(
171 self, *, payload64: str, protected64: str, key_data: dict[str, t.Any]
172 ) -> dict[str, t.Any]:
173 pass
174
175 @abc.abstractmethod
176 def create_mac_key(self, *, alg: str, key: str) -> dict[str, t.Any]:
177 """Create a MAC key."""
178
179 @abc.abstractmethod
180 def get_ordered_csr_identifiers(
181 self,
182 *,
183 csr_filename: str | os.PathLike | None = None,
184 csr_content: str | bytes | None = None,
185 ) -> list[tuple[str, str]]:
186 """
187 Return a list of requested identifiers (CN and SANs) for the CSR.
188 Each identifier is a pair (type, identifier), where type is either
189 'dns' or 'ip'.
190
191 The list is deduplicated, and if a CNAME is present, it will be returned
192 as the first element in the result.
193 """
194
195 @abc.abstractmethod
196 def get_csr_identifiers(
197 self,
198 *,
199 csr_filename: str | os.PathLike | None = None,
200 csr_content: str | bytes | None = None,
201 ) -> set[tuple[str, str]]:
202 """
203 Return a set of requested identifiers (CN and SANs) for the CSR.
204 Each identifier is a pair (type, identifier), where type is either
205 'dns' or 'ip'.
206 """
207
208 @abc.abstractmethod
209 def get_cert_days(
210 self,
211 *,
212 cert_filename: str | os.PathLike | None = None,
213 cert_content: str | bytes | None = None,
214 now: datetime.datetime | None = None,
215 ) -> int:
216 """
217 Return the days the certificate in cert_filename remains valid and -1
218 if the file was not found. If cert_filename contains more than one
219 certificate, only the first one will be considered.
220
221 If now is not specified, datetime.datetime.now() is used.
222 """
223
224 @abc.abstractmethod
225 def create_chain_matcher(self, *, criterium: Criterium) -> ChainMatcher:
226 """
227 Given a Criterium object, creates a ChainMatcher object.
228 """
229
230 @abc.abstractmethod
231 def get_cert_information(
232 self,
233 *,
234 cert_filename: str | os.PathLike | None = None,
235 cert_content: str | bytes | None = None,
236 ) -> CertificateInformation:
237 """
238 Return some information on a X.509 certificate as a CertificateInformation object.
239 """
240
241
242 __all__ = ("CertificateInformation", "CryptoBackend")