Debian Codegraph @

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

raw
1 # Copyright (c) 2024 Felix Fontein <[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 os
11 import typing as t
12 from collections.abc import Callable
13
14 from ansible_collections.community.crypto.plugins.module_utils._acme.account import (
15 ACMEAccount,
16 )
17 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
18 ACMEClient,
19 )
20 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
21 CertificateChain,
22 Criterium,
23 )
24 from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import (
25 Authorization,
26 wait_for_validation,
27 )
28 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
29 ModuleFailException,
30 )
31 from ansible_collections.community.crypto.plugins.module_utils._acme.io import (
32 write_file,
33 )
34 from ansible_collections.community.crypto.plugins.module_utils._acme.orders import Order
35 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
36 pem_to_der,
37 )
38
39 if t.TYPE_CHECKING:
40 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
41
42 from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
43 CryptoBackend,
44 )
45 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import ( # pragma: no cover
46 ChainMatcher,
47 )
48 from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import ( # pragma: no cover
49 Challenge,
50 )
51
52
53 class ACMECertificateClient:
54 """
55 ACME v2 client class. Uses an ACME account object and a CSR to
56 start and validate ACME challenges and download the respective
57 certificates.
58 """
59
60 def __init__(
61 self,
62 *,
63 module: AnsibleModule,
64 backend: CryptoBackend,
65 client: ACMEClient | None = None,
66 account: ACMEAccount | None = None,
67 ) -> None:
68 self.module = module
69 self.version = module.params["acme_version"]
70 self.csr = module.params.get("csr")
71 self.csr_content = module.params.get("csr_content")
72 if client is None:
73 client = ACMEClient(module=module, backend=backend)
74 self.client = client
75 if account is None:
76 account = ACMEAccount(client=self.client)
77 self.account = account
78 self.order_uri = module.params.get("order_uri")
79 self.order_creation_error_strategy = module.params.get(
80 "order_creation_error_strategy", "auto"
81 )
82 self.order_creation_max_retries = module.params.get(
83 "order_creation_max_retries", 3
84 )
85
86 # Make sure account exists
87 dummy, account_data = self.account.setup_account(allow_creation=False)
88 if account_data is None:
89 raise ModuleFailException(msg="Account does not exist or is deactivated.")
90
91 if self.csr is not None and not os.path.exists(self.csr):
92 raise ModuleFailException(f"CSR {self.csr} not found")
93
94 # Extract list of identifiers from CSR
95 if self.csr is not None or self.csr_content is not None:
96 self.identifiers: list[tuple[str, str]] | None = (
97 self.client.backend.get_ordered_csr_identifiers(
98 csr_filename=self.csr, csr_content=self.csr_content
99 )
100 )
101 else:
102 self.identifiers = None
103
104 def parse_select_chain(
105 self, select_chain: list[dict[str, t.Any]] | None
106 ) -> list[ChainMatcher]:
107 select_chain_matcher = []
108 if select_chain:
109 for criterium_idx, criterium in enumerate(select_chain):
110 try:
111 select_chain_matcher.append(
112 self.client.backend.create_chain_matcher(
113 criterium=Criterium(
114 criterium=criterium, index=criterium_idx
115 )
116 )
117 )
118 except ValueError as exc:
119 self.module.warn(
120 f"Error while parsing criterium: {exc}. Ignoring criterium."
121 )
122 return select_chain_matcher
123
124 def load_order(self) -> Order:
125 if not self.order_uri:
126 raise ModuleFailException("The order URI has not been provided")
127 order = Order.from_url(client=self.client, url=self.order_uri)
128 order.load_authorizations(client=self.client)
129 return order
130
131 def create_order(
132 self, *, replaces_cert_id: str | None = None, profile: str | None = None
133 ) -> Order:
134 """
135 Create a new order.
136 """
137 if self.identifiers is None:
138 raise ModuleFailException("No identifiers have been provided")
139 order = Order.create_with_error_handling(
140 client=self.client,
141 identifiers=self.identifiers,
142 error_strategy=self.order_creation_error_strategy,
143 error_max_retries=self.order_creation_max_retries,
144 replaces_cert_id=replaces_cert_id,
145 profile=profile,
146 message_callback=self.module.warn,
147 )
148 self.order_uri = order.url
149 order.load_authorizations(client=self.client)
150 return order
151
152 @staticmethod
153 def _update_dns_data(
154 data_dns: dict[str, list[str]],
155 dns_challenge_type: str,
156 challenge_data: dict[str, t.Any],
157 ) -> None:
158 dns_challenge = challenge_data.get(dns_challenge_type)
159 if dns_challenge:
160 values = data_dns.get(dns_challenge["record"])
161 if values is None:
162 values = []
163 data_dns[dns_challenge["record"]] = values
164 values.append(dns_challenge["resource_value"])
165
166 def get_challenges_data(
167 self, order: Order
168 ) -> tuple[list[dict[str, t.Any]], dict[str, list[str]], dict[str, list[str]]]:
169 """
170 Get challenge details.
171
172 Return a tuple of generic challenge details, and specialized DNS challenge details.
173 """
174 data: list[dict[str, t.Any]] = []
175 data_dns: dict[str, list[str]] = {}
176 data_dns_account: dict[str, list[str]] = {}
177 dns_challenge_type = "dns-01"
178 dns_account_challenge_type = "dns-account-01"
179 for authz in order.authorizations.values():
180 # Skip valid authentications: their challenges are already valid
181 # and do not need to be returned
182 if authz.status == "valid":
183 continue
184 challenge_data = authz.get_challenge_data(client=self.client)
185 data.append(
186 {
187 "identifier": authz.identifier,
188 "identifier_type": authz.identifier_type,
189 "challenges": challenge_data,
190 }
191 )
192 self._update_dns_data(data_dns, dns_challenge_type, challenge_data)
193 self._update_dns_data(
194 data_dns_account, dns_account_challenge_type, challenge_data
195 )
196 return data, data_dns, data_dns_account
197
198 def check_that_authorizations_can_be_used(self, order: Order) -> None:
199 bad_authzs = []
200 for authz in order.authorizations.values():
201 if authz.status not in ("valid", "pending"):
202 error_details = authz.get_error_details()
203 error = f"; {error_details}" if error_details else ""
204 bad_authzs.append(
205 f"{authz.combined_identifier} (status={authz.status!r}{error})"
206 )
207 if bad_authzs:
208 bad_authzs_str = ", ".join(sorted(bad_authzs))
209 raise ModuleFailException(
210 f"Some of the authorizations for the order are in a bad state, so the order can no longer be satisfied: {bad_authzs_str}",
211 )
212
213 def collect_invalid_authzs(self, order: Order) -> list[Authorization]:
214 return [
215 authz
216 for authz in order.authorizations.values()
217 if authz.status == "invalid"
218 ]
219
220 def collect_pending_authzs(self, order: Order) -> list[Authorization]:
221 return [
222 authz
223 for authz in order.authorizations.values()
224 if authz.status == "pending"
225 ]
226
227 def call_validate(
228 self,
229 pending_authzs: list[Authorization],
230 *,
231 get_challenge: Callable[[Authorization], str],
232 wait: bool = True,
233 ) -> list[tuple[Authorization, str, Challenge | None]]:
234 authzs_with_challenges_to_wait_for = []
235 for authz in pending_authzs:
236 challenge_type = get_challenge(authz)
237 authz.call_validate(
238 client=self.client, challenge_type=challenge_type, wait=wait
239 )
240 authzs_with_challenges_to_wait_for.append(
241 (
242 authz,
243 challenge_type,
244 authz.find_challenge(challenge_type=challenge_type),
245 )
246 )
247 return authzs_with_challenges_to_wait_for
248
249 def wait_for_validation(self, authzs_to_wait_for: list[Authorization]) -> None:
250 wait_for_validation(authzs=authzs_to_wait_for, client=self.client)
251
252 def _download_alternate_chains(
253 self, cert: CertificateChain
254 ) -> list[CertificateChain]:
255 alternate_chains = []
256 for alternate in cert.alternates:
257 try:
258 alt_cert = CertificateChain.download(client=self.client, url=alternate)
259 except ModuleFailException as e:
260 self.module.warn(
261 f"Error while downloading alternative certificate {alternate}: {e}"
262 )
263 continue
264 if alt_cert.cert is not None:
265 alternate_chains.append(alt_cert)
266 else:
267 self.module.warn(
268 f"Error while downloading alternative certificate {alternate}: no certificate found"
269 )
270 return alternate_chains
271
272 @t.overload
273 def download_certificate(
274 self, order: Order, *, download_all_chains: t.Literal[True] = True
275 ) -> tuple[CertificateChain, list[CertificateChain]]: ...
276
277 @t.overload
278 def download_certificate(
279 self, order: Order, *, download_all_chains: t.Literal[False]
280 ) -> tuple[CertificateChain, None]: ...
281
282 @t.overload
283 def download_certificate(
284 self, order: Order, *, download_all_chains: bool = True
285 ) -> tuple[CertificateChain, list[CertificateChain] | None]: ...
286
287 def download_certificate(
288 self, order: Order, *, download_all_chains: bool = True
289 ) -> tuple[CertificateChain, list[CertificateChain] | None]:
290 """
291 Download certificate from a valid oder.
292 """
293 if order.status != "valid":
294 raise ModuleFailException(
295 f"The order must be valid, but has state {order.status!r}!"
296 )
297
298 if not order.certificate_uri:
299 raise ModuleFailException(
300 f"Order's crtificate URL {order.certificate_uri!r} is empty!"
301 )
302
303 cert = CertificateChain.download(client=self.client, url=order.certificate_uri)
304 if cert.cert is None:
305 raise ModuleFailException(
306 f"Certificate at {order.certificate_uri} is empty!"
307 )
308
309 alternate_chains = None
310 if download_all_chains:
311 alternate_chains = self._download_alternate_chains(cert)
312
313 return cert, alternate_chains
314
315 @t.overload
316 def get_certificate(
317 self, order: Order, *, download_all_chains: t.Literal[True] = True
318 ) -> tuple[CertificateChain, list[CertificateChain] | None]: ...
319
320 @t.overload
321 def get_certificate(
322 self, order: Order, *, download_all_chains: t.Literal[False]
323 ) -> tuple[CertificateChain, list[CertificateChain] | None]: ...
324
325 @t.overload
326 def get_certificate(
327 self, order: Order, *, download_all_chains: bool = True
328 ) -> tuple[CertificateChain, list[CertificateChain] | None]: ...
329
330 def get_certificate(
331 self, order: Order, *, download_all_chains: bool = True
332 ) -> tuple[CertificateChain, list[CertificateChain] | None]:
333 """
334 Request a new certificate and downloads it, and optionally all certificate chains.
335 First verifies whether all authorizations are valid; if not, aborts with an error.
336 """
337 if self.csr is None and self.csr_content is None:
338 raise ModuleFailException("No CSR has been provided")
339 for authz in order.authorizations.values():
340 if authz.status != "valid":
341 authz.raise_error(
342 error_msg=f'Status is {authz.status!r} and not "valid"',
343 module=self.module,
344 )
345
346 order.finalize(
347 client=self.client,
348 csr_der=pem_to_der(pem_filename=self.csr, pem_content=self.csr_content),
349 )
350
351 return self.download_certificate(order, download_all_chains=download_all_chains)
352
353 def find_matching_chain(
354 self,
355 *,
356 chains: list[CertificateChain],
357 select_chain_matcher: t.Iterable[ChainMatcher],
358 ) -> CertificateChain | None:
359 for criterium_idx, matcher in enumerate(select_chain_matcher):
360 for chain in chains:
361 if matcher.match(certificate=chain):
362 self.module.debug(
363 f"Found matching chain for criterium {criterium_idx}"
364 )
365 return chain
366 return None
367
368 def write_cert_chain(
369 self,
370 *,
371 cert: CertificateChain,
372 cert_dest: str | os.PathLike | None = None,
373 fullchain_dest: str | os.PathLike | None = None,
374 chain_dest: str | os.PathLike | None = None,
375 ) -> bool:
376 changed = False
377 if cert.cert is None:
378 raise ValueError("Certificate is not present")
379
380 if cert_dest and write_file(
381 module=self.module, dest=cert_dest, content=cert.cert.encode("utf8")
382 ):
383 changed = True
384
385 if fullchain_dest and write_file(
386 module=self.module,
387 dest=fullchain_dest,
388 content=(cert.cert + "\n".join(cert.chain)).encode("utf8"),
389 ):
390 changed = True
391
392 if chain_dest and write_file(
393 module=self.module,
394 dest=chain_dest,
395 content=("\n".join(cert.chain)).encode("utf8"),
396 ):
397 changed = True
398
399 return changed
400
401 def deactivate_authzs(self, order: Order) -> None:
402 """
403 Deactivates all valid authz's. Does not raise exceptions.
404 https://community.letsencrypt.org/t/authorization-deactivation/19860/2
405 https://tools.ietf.org/html/rfc8555#section-7.5.2
406 """
407 if len(order.authorization_uris) > len(order.authorizations):
408 for authz_uri in order.authorization_uris:
409 authz = None
410 try:
411 authz = Authorization.deactivate_url(
412 client=self.client, url=authz_uri
413 )
414 except Exception:
415 # ignore errors
416 pass
417 if authz is None or not authz.is_in_final_state(allow_valid=False):
418 self.module.warn(
419 warning=f"Could not deactivate authz object {authz_uri}."
420 )
421 else:
422 for authz in order.authorizations.values():
423 try:
424 authz.deactivate(client=self.client)
425 except Exception:
426 # ignore errors
427 pass
428 if not authz.is_in_final_state(allow_valid=False):
429 self.module.warn(
430 warning=f"Could not deactivate authz object {authz.url}."
431 )
432
433
434 __all__ = ("ACMECertificateClient",)