Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/challenges.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 hashlib
13 import ipaddress
14 import json
15 import re
16 import time
17 import typing as t
18
19 from ansible.module_utils.common.text.converters import to_bytes
20
21 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
22 ACMEProtocolException,
23 ModuleFailException,
24 format_error_problem,
25 )
26 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
27 nopad_b64,
28 )
29 from ansible_collections.community.crypto.plugins.module_utils._caa import (
30 _check_domain_name,
31 )
32
33 if t.TYPE_CHECKING:
34 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
35
36 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import ( # pragma: no cover
37 ACMEClient,
38 )
39
40
41 def create_key_authorization(*, client: ACMEClient, token: str) -> str:
42 """
43 Returns the key authorization for the given token
44 https://tools.ietf.org/html/rfc8555#section-8.1
45 """
46 accountkey_json = json.dumps(
47 client.account_jwk, sort_keys=True, separators=(",", ":")
48 )
49 thumbprint = nopad_b64(hashlib.sha256(accountkey_json.encode("utf8")).digest())
50 return f"{token}.{thumbprint}"
51
52
53 def combine_identifier(*, identifier_type: str, identifier: str) -> str:
54 return f"{identifier_type}:{identifier}"
55
56
57 def normalize_combined_identifier(identifier: str) -> str:
58 identifier_type, identifier = split_identifier(identifier)
59 # Normalize DNS names and IPs
60 identifier = identifier.lower()
61 return combine_identifier(identifier_type=identifier_type, identifier=identifier)
62
63
64 def split_identifier(identifier: str) -> tuple[str, str]:
65 parts = identifier.split(":", 1)
66 if len(parts) != 2:
67 raise ModuleFailException(
68 f'Identifier "{identifier}" is not of the form <type>:<identifier>'
69 )
70 return parts[0], parts[1]
71
72
73 _Challenge = t.TypeVar("_Challenge", bound="Challenge")
74
75
76 class Challenge:
77 def __init__(self, *, data: dict[str, t.Any], url: str) -> None:
78 self.data = data
79
80 self.type: str = data["type"]
81 self.url = url
82 self.status: str = data["status"]
83 self.token: str | None = data.get("token")
84
85 @classmethod
86 def from_json(
87 cls: type[_Challenge],
88 *,
89 client: ACMEClient,
90 data: dict[str, t.Any],
91 url: str | None = None,
92 ) -> _Challenge:
93 return cls(data=data, url=url or data["url"])
94
95 def call_validate(self, client: ACMEClient) -> None:
96 challenge_response: dict[str, t.Any] = {}
97 client.send_signed_request(
98 self.url,
99 challenge_response,
100 error_msg="Failed to validate challenge",
101 expected_status_codes=[200, 202],
102 )
103
104 def to_json(self) -> dict[str, t.Any]:
105 return self.data.copy()
106
107 def get_validation_data(
108 self, *, client: ACMEClient, identifier_type: str, identifier: str
109 ) -> dict[str, t.Any] | None:
110 if self.type == "dns-persist-01":
111 # https://www.ietf.org/archive/id/draft-ietf-acme-dns-persist-01.html#section-3.1
112 account_uri = self.data.get("accounturi")
113 issuer_domain_names = self.data.get("issuer-domain-names")
114 if account_uri is None:
115 # In version 00 of the draft, accounturi isn't present.
116 # Since that's what Pebble currently implements,
117 # let's fake the value if we have it.
118 # (https://www.ietf.org/archive/id/draft-ietf-acme-dns-persist-00.html#section-6)
119 account_uri = client.account_uri
120 if (
121 not isinstance(account_uri, str)
122 or not isinstance(issuer_domain_names, list)
123 or not all(isinstance(idn, str) for idn in issuer_domain_names)
124 ):
125 return None
126 if not (1 <= len(issuer_domain_names) <= 10):
127 client.module.warn(
128 f"The dns-persist-01 challenge for DNS:{identifier} has {len(issuer_domain_names)}"
129 " issuer domain names, which is not in [1, 10]. Ignoring malformed challenge."
130 )
131 return None
132 for idn in issuer_domain_names:
133 try:
134 _check_domain_name(idn)
135 if idn != idn.lower() or len(idn) > 253:
136 raise ValueError()
137 except ValueError:
138 client.module.warn(
139 f"The dns-persist-01 challenge for DNS:{identifier} has an invalid"
140 f" issuer domain name {idn!r}. Ignoring malformed challenge."
141 )
142 return None
143 return {
144 "account_uri": account_uri,
145 "issuer_domain_names": issuer_domain_names,
146 }
147
148 if self.token is None:
149 return None
150
151 token = re.sub(r"[^A-Za-z0-9_\-]", "_", self.token)
152 key_authorization = create_key_authorization(client=client, token=token)
153
154 if self.type == "http-01":
155 # https://tools.ietf.org/html/rfc8555#section-8.3
156 return {
157 "resource": f".well-known/acme-challenge/{token}",
158 "resource_value": key_authorization,
159 }
160
161 if self.type == "dns-01":
162 if identifier_type != "dns":
163 return None
164 # https://tools.ietf.org/html/rfc8555#section-8.4
165 resource = "_acme-challenge"
166 value = nopad_b64(hashlib.sha256(to_bytes(key_authorization)).digest())
167 record = f"{resource}.{identifier[2:] if identifier.startswith('*.') else identifier}"
168 return {
169 "resource": resource,
170 "resource_value": value,
171 "record": record,
172 }
173
174 if self.type == "dns-account-01":
175 if identifier_type != "dns" or client.account_uri is None:
176 return None
177 # https://datatracker.ietf.org/doc/html/draft-ietf-acme-dns-account-label-02#section-3.2
178 prefix = (
179 base64.b32encode(
180 hashlib.sha256(client.account_uri.encode("utf8")).digest()[:10]
181 )
182 .decode("ascii")
183 .lower()
184 )
185 resource = f"_{prefix}._acme-challenge"
186 value = nopad_b64(hashlib.sha256(to_bytes(key_authorization)).digest())
187 record = f"{resource}.{identifier[2:] if identifier.startswith('*.') else identifier}"
188 return {
189 "resource": resource,
190 "resource_value": value,
191 "record": record,
192 }
193
194 if self.type == "tls-alpn-01":
195 # https://www.rfc-editor.org/rfc/rfc8737.html#section-3
196 if identifier_type == "ip":
197 # IPv4/IPv6 address: use reverse mapping (RFC1034, RFC3596)
198 resource = ipaddress.ip_address(identifier).reverse_pointer
199 if not resource.endswith("."):
200 resource += "."
201 else:
202 resource = identifier
203 b_value = base64.b64encode(
204 hashlib.sha256(to_bytes(key_authorization)).digest()
205 )
206 return {
207 "resource": resource,
208 "resource_original": combine_identifier(
209 identifier_type=identifier_type, identifier=identifier
210 ),
211 "resource_value": b_value,
212 }
213
214 # Unknown challenge type: ignore
215 return None
216
217
218 _Authorization = t.TypeVar("_Authorization", bound="Authorization")
219
220
221 class Authorization:
222 def __init__(self, *, url: str) -> None:
223 self.url = url
224
225 self.data: dict[str, t.Any] | None = None
226 self.challenges: list[Challenge] = []
227 self.status: str | None = None
228 self.identifier_type: str | None = None
229 self.identifier: str | None = None
230
231 def _setup(self, *, client: ACMEClient, data: dict[str, t.Any]) -> None:
232 data["uri"] = self.url
233 self.data = data
234 # While 'challenges' is a required field, apparently not every CA cares
235 # (https://github.com/ansible-collections/community.crypto/issues/824)
236 if data.get("challenges"):
237 self.challenges = [
238 Challenge.from_json(client=client, data=challenge)
239 for challenge in data["challenges"]
240 ]
241 else:
242 self.challenges = []
243 self.status = data["status"]
244 self.identifier = data["identifier"]["value"]
245 self.identifier_type = data["identifier"]["type"]
246 if data.get("wildcard", False):
247 self.identifier = f"*.{self.identifier}"
248
249 @classmethod
250 def from_json(
251 cls: type[_Authorization],
252 *,
253 client: ACMEClient,
254 data: dict[str, t.Any],
255 url: str,
256 ) -> _Authorization:
257 result = cls(url=url)
258 result._setup(client=client, data=data)
259 return result
260
261 @classmethod
262 def from_url(
263 cls: type[_Authorization], *, client: ACMEClient, url: str
264 ) -> _Authorization:
265 result = cls(url=url)
266 result.refresh(client=client)
267 return result
268
269 @classmethod
270 def create(
271 cls: type[_Authorization],
272 *,
273 client: ACMEClient,
274 identifier_type: str,
275 identifier: str,
276 ) -> _Authorization:
277 """
278 Create a new authorization for the given identifier.
279 Return the authorization object of the new authorization
280 https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-6.4
281 """
282 new_authz = {
283 "identifier": {
284 "type": identifier_type,
285 "value": identifier,
286 },
287 }
288 if "newAuthz" not in client.directory.directory:
289 raise ACMEProtocolException(
290 module=client.module,
291 msg="ACME endpoint does not support pre-authorization",
292 )
293 url = client.directory["newAuthz"]
294
295 result, info = client.send_signed_request(
296 url,
297 new_authz,
298 error_msg="Failed to request challenges",
299 expected_status_codes=[200, 201],
300 )
301 if not isinstance(result, dict):
302 raise ACMEProtocolException(
303 module=client.module,
304 msg="Unexpected authorization creation result",
305 content_json=result,
306 )
307 return cls.from_json(client=client, data=result, url=info["location"])
308
309 @property
310 def combined_identifier(self) -> str:
311 if self.identifier_type is None or self.identifier is None:
312 raise ValueError("Data not present")
313 return combine_identifier(
314 identifier_type=self.identifier_type, identifier=self.identifier
315 )
316
317 def to_json(self) -> dict[str, t.Any]:
318 if self.data is None:
319 raise ValueError("Data not present")
320 return self.data.copy()
321
322 def refresh(self, *, client: ACMEClient) -> bool:
323 result, info = client.get_request(self.url)
324 if not isinstance(result, dict):
325 raise ACMEProtocolException(
326 module=client.module,
327 msg="Unexpected authorization data",
328 info=info,
329 content_json=result,
330 )
331 changed = self.data != result
332 self._setup(client=client, data=result)
333 return changed
334
335 def get_challenge_data(self, *, client: ACMEClient) -> dict[str, t.Any]:
336 """
337 Returns a dict with the data for all proposed (and supported) challenges
338 of the given authorization.
339 """
340 if self.identifier_type is None or self.identifier is None:
341 raise ValueError("Data not present")
342 data = {}
343 for challenge in self.challenges:
344 validation_data = challenge.get_validation_data(
345 client=client,
346 identifier_type=self.identifier_type,
347 identifier=self.identifier,
348 )
349 if validation_data is not None:
350 data[challenge.type] = validation_data
351 return data
352
353 def get_error_details(self) -> str | None:
354 error_details = []
355 for challenge in self.challenges:
356 if challenge.status == "invalid":
357 msg = f"Challenge {challenge.type}"
358 if "error" in challenge.data:
359 problem = format_error_problem(
360 challenge.data["error"],
361 subproblem_prefix=f"{challenge.type}.",
362 )
363 msg = f"{msg}: {problem}"
364 error_details.append(msg)
365 return "; ".join(error_details) if error_details else None
366
367 def raise_error(self, *, error_msg: str, module: AnsibleModule) -> t.NoReturn:
368 """
369 Aborts with a specific error for a challenge.
370 """
371 error_details = self.get_error_details()
372 error_details_str = f" {error_details}" if error_details else ""
373 raise ACMEProtocolException(
374 module=module,
375 msg=f"Failed to validate challenge for {self.combined_identifier}: {error_msg}.{error_details_str}",
376 extras={
377 "identifier": self.combined_identifier,
378 "authorization": self.data,
379 },
380 )
381
382 def find_challenge(self, *, challenge_type: str) -> Challenge | None:
383 for challenge in self.challenges:
384 if challenge_type == challenge.type:
385 return challenge
386 return None
387
388 def wait_for_validation(self, *, client: ACMEClient) -> bool:
389 while True:
390 self.refresh(client=client)
391 if self.status in ["valid", "invalid", "revoked"]:
392 break
393 time.sleep(2)
394
395 if self.status == "invalid":
396 self.raise_error(error_msg='Status is "invalid"', module=client.module)
397
398 return self.status == "valid"
399
400 def call_validate(
401 self, *, client: ACMEClient, challenge_type: str, wait: bool = True
402 ) -> bool:
403 """
404 Validate the authorization provided in the auth dict. Returns True
405 when the validation was successful and False when it was not.
406 """
407 challenge = self.find_challenge(challenge_type=challenge_type)
408 if challenge is None:
409 raise ModuleFailException(
410 f'Found no challenge of type "{challenge_type}" for identifier {self.combined_identifier}!'
411 )
412
413 challenge.call_validate(client)
414
415 if not wait:
416 return self.status == "valid"
417 return self.wait_for_validation(client=client)
418
419 def can_deactivate(self) -> bool:
420 """
421 Deactivates this authorization.
422 https://community.letsencrypt.org/t/authorization-deactivation/19860/2
423 https://tools.ietf.org/html/rfc8555#section-7.5.2
424 """
425 return self.status in ("valid", "pending")
426
427 def is_in_final_state(self, *, allow_valid: bool = True) -> bool:
428 if allow_valid and self.status == "valid":
429 return True
430 return self.status in ("invalid", "revoked", "deactivated", "expired")
431
432 def deactivate(self, *, client: ACMEClient) -> bool | None:
433 """
434 Deactivates this authorization.
435 https://community.letsencrypt.org/t/authorization-deactivation/19860/2
436 https://tools.ietf.org/html/rfc8555#section-7.5.2
437 """
438 if not self.can_deactivate():
439 return None
440 authz_deactivate = {"status": "deactivated"}
441 result, info = client.send_signed_request(
442 self.url, authz_deactivate, fail_on_error=False
443 )
444 if 200 <= info["status"] < 300 and isinstance(result, dict):
445 self._setup(client=client, data=result)
446 return self.status == "deactivated"
447 return False
448
449 @classmethod
450 def deactivate_url(
451 cls: type[_Authorization], *, client: ACMEClient, url: str
452 ) -> _Authorization:
453 """
454 Deactivates this authorization.
455 https://community.letsencrypt.org/t/authorization-deactivation/19860/2
456 https://tools.ietf.org/html/rfc8555#section-7.5.2
457 """
458 authz = cls(url=url)
459 authz_deactivate = {"status": "deactivated"}
460 result, _info = client.send_signed_request(
461 url, authz_deactivate, fail_on_error=True
462 )
463 if not isinstance(result, dict):
464 raise ACMEProtocolException(
465 module=client.module,
466 msg="Unexpected challenge deactivation result",
467 content_json=result,
468 )
469 authz._setup(client=client, data=result)
470 return authz
471
472
473 def wait_for_validation(
474 *, authzs: t.Iterable[Authorization], client: ACMEClient
475 ) -> None:
476 """
477 Wait until a list of authz is valid. Fail if at least one of them is invalid or revoked.
478 """
479 while authzs:
480 authzs_next = []
481 for authz in authzs:
482 authz.refresh(client=client)
483 if authz.status in ["valid", "invalid", "revoked"]:
484 if authz.status != "valid":
485 authz.raise_error(
486 error_msg='Status is not "valid"', module=client.module
487 )
488 else:
489 authzs_next.append(authz)
490 if authzs_next:
491 time.sleep(2)
492 authzs = authzs_next
493
494
495 __all__ = (
496 "Authorization",
497 "Challenge",
498 "combine_identifier",
499 "create_key_authorization",
500 "normalize_combined_identifier",
501 "split_identifier",
502 "wait_for_validation",
503 )