| 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 copy |
| 12 |
import datetime |
| 13 |
import json |
| 14 |
import locale |
| 15 |
import time |
| 16 |
import typing as t |
| 17 |
|
| 18 |
from ansible.module_utils.basic import missing_required_lib |
| 19 |
from ansible.module_utils.common.text.converters import to_bytes |
| 20 |
from ansible.module_utils.urls import fetch_url |
| 21 |
|
| 22 |
from ansible_collections.community.crypto.plugins.module_utils._acme.backend_cryptography import ( |
| 23 |
CRYPTOGRAPHY_ERROR, |
| 24 |
CRYPTOGRAPHY_MINIMAL_VERSION, |
| 25 |
CRYPTOGRAPHY_VERSION, |
| 26 |
HAS_CURRENT_CRYPTOGRAPHY, |
| 27 |
CryptographyBackend, |
| 28 |
) |
| 29 |
from ansible_collections.community.crypto.plugins.module_utils._acme.backend_openssl_cli import ( |
| 30 |
OpenSSLCLIBackend, |
| 31 |
) |
| 32 |
from ansible_collections.community.crypto.plugins.module_utils._acme.errors import ( |
| 33 |
ACMEProtocolException, |
| 34 |
KeyParsingError, |
| 35 |
ModuleFailException, |
| 36 |
NetworkException, |
| 37 |
format_http_status, |
| 38 |
) |
| 39 |
from ansible_collections.community.crypto.plugins.module_utils._acme.utils import ( |
| 40 |
compute_cert_id, |
| 41 |
nopad_b64, |
| 42 |
parse_retry_after, |
| 43 |
) |
| 44 |
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( |
| 45 |
ArgumentSpec, |
| 46 |
) |
| 47 |
from ansible_collections.community.crypto.plugins.module_utils._time import ( |
| 48 |
get_now_datetime, |
| 49 |
) |
| 50 |
|
| 51 |
if t.TYPE_CHECKING: |
| 52 |
import http.client # pragma: no cover |
| 53 |
import os # pragma: no cover |
| 54 |
import urllib.error # pragma: no cover |
| 55 |
|
| 56 |
from ansible.module_utils.basic import AnsibleModule # pragma: no cover |
| 57 |
|
| 58 |
from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover |
| 59 |
CertificateInformation, |
| 60 |
CryptoBackend, |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
# -1 usually means connection problems |
| 65 |
RETRY_STATUS_CODES = (-1, 408, 429, 502, 503, 504) |
| 66 |
|
| 67 |
RETRY_COUNT = 20 |
| 68 |
|
| 69 |
|
| 70 |
def _decode_retry( |
| 71 |
*, |
| 72 |
module: AnsibleModule, |
| 73 |
response: urllib.error.HTTPError | http.client.HTTPResponse | None, |
| 74 |
info: dict[str, t.Any], |
| 75 |
retry_count: int, |
| 76 |
) -> bool: |
| 77 |
if info["status"] not in RETRY_STATUS_CODES: |
| 78 |
return False |
| 79 |
|
| 80 |
if retry_count >= RETRY_COUNT: |
| 81 |
raise ACMEProtocolException( |
| 82 |
module=module, |
| 83 |
msg=f"Giving up after {RETRY_COUNT} retries", |
| 84 |
info=info, |
| 85 |
response=response, |
| 86 |
) |
| 87 |
|
| 88 |
# 429 and 503 should have a Retry-After header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) |
| 89 |
now = get_now_datetime(with_timezone=True) |
| 90 |
try: |
| 91 |
then = parse_retry_after( |
| 92 |
info.get("retry-after", "10"), relative_with_timezone=True, now=now |
| 93 |
) |
| 94 |
retry_after = (then - now).total_seconds() |
| 95 |
retry_after = min(max(1, retry_after), 60) |
| 96 |
except (TypeError, ValueError): |
| 97 |
retry_after = 10 |
| 98 |
module.log( |
| 99 |
f"Retrieved a {format_http_status(info['status'])} HTTP status on {info['url']}, retrying in {retry_after} seconds" |
| 100 |
) |
| 101 |
|
| 102 |
time.sleep(retry_after) |
| 103 |
return True |
| 104 |
|
| 105 |
|
| 106 |
def _assert_fetch_url_success( |
| 107 |
*, |
| 108 |
module: AnsibleModule, |
| 109 |
response: urllib.error.HTTPError | http.client.HTTPResponse | None, |
| 110 |
info: dict[str, t.Any], |
| 111 |
allow_redirect: bool = False, |
| 112 |
allow_client_error: bool = True, |
| 113 |
allow_server_error: bool = True, |
| 114 |
) -> None: |
| 115 |
if info["status"] < 0: |
| 116 |
raise NetworkException(msg=f"Failure downloading {info['url']}, {info['msg']}") |
| 117 |
|
| 118 |
if ( |
| 119 |
(300 <= info["status"] < 400 and not allow_redirect) |
| 120 |
or (400 <= info["status"] < 500 and not allow_client_error) |
| 121 |
or (info["status"] >= 500 and not allow_server_error) |
| 122 |
): |
| 123 |
raise ACMEProtocolException(module=module, info=info, response=response) |
| 124 |
|
| 125 |
|
| 126 |
def _is_failed( |
| 127 |
*, info: dict[str, t.Any], expected_status_codes: t.Iterable[int] | None = None |
| 128 |
) -> bool: |
| 129 |
if info["status"] < 200 or info["status"] >= 400: |
| 130 |
return True |
| 131 |
return bool( |
| 132 |
expected_status_codes is not None |
| 133 |
and info["status"] not in expected_status_codes |
| 134 |
) |
| 135 |
|
| 136 |
|
| 137 |
class ACMEDirectory: |
| 138 |
""" |
| 139 |
The ACME server directory. Gives access to the available resources, |
| 140 |
and allows to obtain a Replay-Nonce. The acme_directory URL |
| 141 |
needs to support unauthenticated GET requests; ACME endpoints |
| 142 |
requiring authentication are not supported. |
| 143 |
https://tools.ietf.org/html/rfc8555#section-7.1.1 |
| 144 |
""" |
| 145 |
|
| 146 |
def __init__(self, *, module: AnsibleModule, client: ACMEClient) -> None: |
| 147 |
self.module = module |
| 148 |
self.directory_root = module.params["acme_directory"] |
| 149 |
self.version = module.params["acme_version"] |
| 150 |
|
| 151 |
directory, info = client.get_request(self.directory_root, get_only=True) |
| 152 |
if not isinstance(directory, dict): |
| 153 |
raise ACMEProtocolException( |
| 154 |
module=module, |
| 155 |
msg=f"ACME directory is not a dictionary, but {type(directory)}", |
| 156 |
info=info, |
| 157 |
content_json=directory, |
| 158 |
) |
| 159 |
self.directory = directory |
| 160 |
|
| 161 |
self.request_timeout = module.params["request_timeout"] |
| 162 |
|
| 163 |
# Check whether self.version matches what we expect |
| 164 |
if self.version == 2: |
| 165 |
for key in ("newNonce", "newAccount", "newOrder"): |
| 166 |
if key not in self.directory: |
| 167 |
raise ModuleFailException( |
| 168 |
"ACME directory does not seem to follow protocol ACME v2" |
| 169 |
) |
| 170 |
# Make sure that 'meta' is always available |
| 171 |
if "meta" not in self.directory: |
| 172 |
self.directory["meta"] = {} |
| 173 |
|
| 174 |
def __getitem__(self, key: str) -> t.Any: |
| 175 |
return self.directory[key] |
| 176 |
|
| 177 |
def __contains__(self, key: str) -> bool: |
| 178 |
return key in self.directory |
| 179 |
|
| 180 |
def get(self, key: str, default_value: t.Any = None) -> t.Any: |
| 181 |
return self.directory.get(key, default_value) |
| 182 |
|
| 183 |
def get_nonce(self, resource: str | None = None) -> str: |
| 184 |
url = self.directory["newNonce"] |
| 185 |
if resource is not None: |
| 186 |
url = resource |
| 187 |
retry_count = 0 |
| 188 |
while True: |
| 189 |
response, info = fetch_url( |
| 190 |
self.module, url, method="HEAD", timeout=self.request_timeout |
| 191 |
) |
| 192 |
if _decode_retry( |
| 193 |
module=self.module, |
| 194 |
response=response, |
| 195 |
info=info, |
| 196 |
retry_count=retry_count, |
| 197 |
): |
| 198 |
retry_count += 1 |
| 199 |
continue |
| 200 |
if info["status"] not in (200, 204): |
| 201 |
raise NetworkException( |
| 202 |
f"Failed to get replay-nonce, got status {format_http_status(info['status'])}" |
| 203 |
) |
| 204 |
if "replay-nonce" in info: |
| 205 |
return info["replay-nonce"] |
| 206 |
self.module.log( |
| 207 |
f"HEAD to {url} did return status {format_http_status(info['status'])}, but no replay-nonce header!" |
| 208 |
) |
| 209 |
if retry_count >= 5: |
| 210 |
raise ACMEProtocolException( |
| 211 |
module=self.module, |
| 212 |
msg="Was not able to obtain nonce, giving up after 5 retries", |
| 213 |
info=info, |
| 214 |
response=response, |
| 215 |
) |
| 216 |
retry_count += 1 |
| 217 |
|
| 218 |
def has_renewal_info_endpoint(self) -> bool: |
| 219 |
return "renewalInfo" in self.directory |
| 220 |
|
| 221 |
|
| 222 |
class ACMEClient: |
| 223 |
""" |
| 224 |
ACME client object. Handles the authorized communication with the |
| 225 |
ACME server. |
| 226 |
""" |
| 227 |
|
| 228 |
def __init__(self, *, module: AnsibleModule, backend: CryptoBackend) -> None: |
| 229 |
# Set to true to enable logging of all signed requests |
| 230 |
self._debug = False |
| 231 |
|
| 232 |
self.module = module |
| 233 |
self.backend = backend |
| 234 |
self.version = module.params["acme_version"] |
| 235 |
# account_key path and content are mutually exclusive |
| 236 |
self.account_key_file = module.params.get("account_key_src") |
| 237 |
self.account_key_content = module.params.get("account_key_content") |
| 238 |
self.account_key_passphrase = module.params.get("account_key_passphrase") |
| 239 |
|
| 240 |
# Grab account URI from module parameters. |
| 241 |
# Make sure empty string is treated as None. |
| 242 |
self.account_uri = module.params.get("account_uri") or None |
| 243 |
|
| 244 |
self.request_timeout = module.params["request_timeout"] |
| 245 |
|
| 246 |
self.account_key_data = None |
| 247 |
self.account_jwk = None |
| 248 |
self.account_jws_header = None |
| 249 |
if self.account_key_file is not None or self.account_key_content is not None: |
| 250 |
try: |
| 251 |
self.account_key_data = self.parse_key( |
| 252 |
key_file=self.account_key_file, |
| 253 |
key_content=self.account_key_content, |
| 254 |
passphrase=self.account_key_passphrase, |
| 255 |
) |
| 256 |
except KeyParsingError as e: |
| 257 |
raise ModuleFailException( |
| 258 |
f"Error while parsing account key: {e.msg}" |
| 259 |
) from e |
| 260 |
self.account_jwk = self.account_key_data["jwk"] |
| 261 |
self.account_jws_header = { |
| 262 |
"alg": self.account_key_data["alg"], |
| 263 |
"jwk": self.account_jwk, |
| 264 |
} |
| 265 |
if self.account_uri: |
| 266 |
# Make sure self.account_jws_header is updated |
| 267 |
self.set_account_uri(self.account_uri) |
| 268 |
|
| 269 |
self.directory = ACMEDirectory(module=module, client=self) |
| 270 |
|
| 271 |
def set_account_uri(self, uri: str) -> None: |
| 272 |
""" |
| 273 |
Set account URI. For ACME v2, it needs to be used to sending signed |
| 274 |
requests. |
| 275 |
""" |
| 276 |
self.account_uri = uri |
| 277 |
if self.account_jws_header: |
| 278 |
self.account_jws_header.pop("jwk", None) |
| 279 |
self.account_jws_header["kid"] = self.account_uri |
| 280 |
|
| 281 |
def parse_key( |
| 282 |
self, |
| 283 |
*, |
| 284 |
key_file: str | os.PathLike | None = None, |
| 285 |
key_content: str | None = None, |
| 286 |
passphrase: str | None = None, |
| 287 |
) -> dict[str, t.Any]: |
| 288 |
""" |
| 289 |
Parses an RSA or Elliptic Curve key file in PEM format and returns key_data. |
| 290 |
In case of an error, raises KeyParsingError. |
| 291 |
""" |
| 292 |
if key_file is None and key_content is None: |
| 293 |
raise AssertionError( |
| 294 |
"One of key_file and key_content must be specified!" |
| 295 |
) # pragma: no cover |
| 296 |
return self.backend.parse_key( |
| 297 |
key_file=key_file, key_content=key_content, passphrase=passphrase |
| 298 |
) |
| 299 |
|
| 300 |
@t.overload |
| 301 |
def sign_request( |
| 302 |
self, |
| 303 |
*, |
| 304 |
protected: dict[str, t.Any], |
| 305 |
payload: dict[str, t.Any] | None, |
| 306 |
key_data: dict[str, t.Any], |
| 307 |
encode_payload: t.Literal[True] = True, |
| 308 |
) -> dict[str, t.Any]: ... |
| 309 |
|
| 310 |
@t.overload |
| 311 |
def sign_request( |
| 312 |
self, |
| 313 |
*, |
| 314 |
protected: dict[str, t.Any], |
| 315 |
payload: str | bytes | None, |
| 316 |
key_data: dict[str, t.Any], |
| 317 |
encode_payload: t.Literal[False], |
| 318 |
) -> dict[str, t.Any]: ... |
| 319 |
|
| 320 |
@t.overload |
| 321 |
def sign_request( |
| 322 |
self, |
| 323 |
*, |
| 324 |
protected: dict[str, t.Any], |
| 325 |
payload: str | bytes | dict[str, t.Any] | None, |
| 326 |
key_data: dict[str, t.Any], |
| 327 |
encode_payload: bool = True, |
| 328 |
) -> dict[str, t.Any]: ... |
| 329 |
|
| 330 |
def sign_request( |
| 331 |
self, |
| 332 |
*, |
| 333 |
protected: dict[str, t.Any], |
| 334 |
payload: str | bytes | dict[str, t.Any] | None, |
| 335 |
key_data: dict[str, t.Any], |
| 336 |
encode_payload: bool = True, |
| 337 |
) -> dict[str, t.Any]: |
| 338 |
""" |
| 339 |
Signs an ACME request. |
| 340 |
""" |
| 341 |
try: |
| 342 |
if payload is None: |
| 343 |
# POST-as-GET |
| 344 |
payload64 = "" |
| 345 |
else: |
| 346 |
# POST |
| 347 |
if encode_payload: |
| 348 |
payload = self.module.jsonify(payload).encode("utf8") |
| 349 |
payload64 = nopad_b64(to_bytes(payload)) |
| 350 |
protected64 = nopad_b64(self.module.jsonify(protected).encode("utf8")) |
| 351 |
except Exception as e: |
| 352 |
raise ModuleFailException( |
| 353 |
f"Failed to encode payload / headers as JSON: {e}" |
| 354 |
) from e |
| 355 |
|
| 356 |
return self.backend.sign( |
| 357 |
payload64=payload64, protected64=protected64, key_data=key_data |
| 358 |
) |
| 359 |
|
| 360 |
def _log(self, msg: str, *, data: t.Any = None) -> None: |
| 361 |
""" |
| 362 |
Write arguments to acme.log when logging is enabled. |
| 363 |
""" |
| 364 |
if self._debug: |
| 365 |
with open("acme.log", "ab") as f: |
| 366 |
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%s") |
| 367 |
f.write(f"[{timestamp}] {msg}\n".encode("utf-8")) |
| 368 |
if data is not None: |
| 369 |
f.write( |
| 370 |
f"{json.dumps(data, indent=2, sort_keys=True)}\n\n".encode( |
| 371 |
"utf-8" |
| 372 |
) |
| 373 |
) |
| 374 |
|
| 375 |
@t.overload |
| 376 |
def send_signed_request( |
| 377 |
self, |
| 378 |
url: str, |
| 379 |
payload: dict[str, t.Any] | None, |
| 380 |
*, |
| 381 |
key_data: dict[str, t.Any] | None = None, |
| 382 |
jws_header: dict[str, t.Any] | None = None, |
| 383 |
parse_json_result: t.Literal[True] = True, |
| 384 |
encode_payload: t.Literal[True] = True, |
| 385 |
fail_on_error: bool = True, |
| 386 |
error_msg: str | None = None, |
| 387 |
expected_status_codes: t.Iterable[int] | None = None, |
| 388 |
) -> tuple[object | bytes, dict[str, t.Any]]: ... |
| 389 |
|
| 390 |
@t.overload |
| 391 |
def send_signed_request( |
| 392 |
self, |
| 393 |
url: str, |
| 394 |
payload: str | bytes | None, |
| 395 |
*, |
| 396 |
key_data: dict[str, t.Any] | None = None, |
| 397 |
jws_header: dict[str, t.Any] | None = None, |
| 398 |
parse_json_result: t.Literal[True] = True, |
| 399 |
encode_payload: t.Literal[False], |
| 400 |
fail_on_error: bool = True, |
| 401 |
error_msg: str | None = None, |
| 402 |
expected_status_codes: t.Iterable[int] | None = None, |
| 403 |
) -> tuple[object | bytes, dict[str, t.Any]]: ... |
| 404 |
|
| 405 |
@t.overload |
| 406 |
def send_signed_request( |
| 407 |
self, |
| 408 |
url: str, |
| 409 |
payload: dict[str, t.Any] | None, |
| 410 |
*, |
| 411 |
key_data: dict[str, t.Any] | None = None, |
| 412 |
jws_header: dict[str, t.Any] | None = None, |
| 413 |
parse_json_result: t.Literal[False], |
| 414 |
encode_payload: t.Literal[True] = True, |
| 415 |
fail_on_error: bool = True, |
| 416 |
error_msg: str | None = None, |
| 417 |
expected_status_codes: t.Iterable[int] | None = None, |
| 418 |
) -> tuple[bytes, dict[str, t.Any]]: ... |
| 419 |
|
| 420 |
@t.overload |
| 421 |
def send_signed_request( |
| 422 |
self, |
| 423 |
url: str, |
| 424 |
payload: str | bytes | None, |
| 425 |
*, |
| 426 |
key_data: dict[str, t.Any] | None = None, |
| 427 |
jws_header: dict[str, t.Any] | None = None, |
| 428 |
parse_json_result: t.Literal[False], |
| 429 |
encode_payload: t.Literal[False], |
| 430 |
fail_on_error: bool = True, |
| 431 |
error_msg: str | None = None, |
| 432 |
expected_status_codes: t.Iterable[int] | None = None, |
| 433 |
) -> tuple[bytes, dict[str, t.Any]]: ... |
| 434 |
|
| 435 |
def send_signed_request( |
| 436 |
self, |
| 437 |
url: str, |
| 438 |
payload: str | bytes | dict[str, t.Any] | None, |
| 439 |
*, |
| 440 |
key_data: dict[str, t.Any] | None = None, |
| 441 |
jws_header: dict[str, t.Any] | None = None, |
| 442 |
parse_json_result: bool = True, |
| 443 |
encode_payload: bool = True, |
| 444 |
fail_on_error: bool = True, |
| 445 |
error_msg: str | None = None, |
| 446 |
expected_status_codes: t.Iterable[int] | None = None, |
| 447 |
) -> tuple[object | bytes, dict[str, t.Any]]: |
| 448 |
""" |
| 449 |
Sends a JWS signed HTTP POST request to the ACME server and returns |
| 450 |
the response as dictionary (if parse_json_result is True) or in raw form |
| 451 |
(if parse_json_result is False). |
| 452 |
https://tools.ietf.org/html/rfc8555#section-6.2 |
| 453 |
|
| 454 |
If payload is None, a POST-as-GET is performed. |
| 455 |
(https://tools.ietf.org/html/rfc8555#section-6.3) |
| 456 |
""" |
| 457 |
key_data = key_data or self.account_key_data |
| 458 |
if key_data is None: |
| 459 |
raise ModuleFailException("Missing key data") |
| 460 |
jws_header = jws_header or self.account_jws_header |
| 461 |
if jws_header is None: |
| 462 |
raise ModuleFailException("Missing JWS header") |
| 463 |
failed_tries = 0 |
| 464 |
while True: |
| 465 |
protected = copy.deepcopy(jws_header) |
| 466 |
protected["nonce"] = self.directory.get_nonce() |
| 467 |
protected["url"] = url |
| 468 |
|
| 469 |
self._log("URL", data=url) |
| 470 |
self._log("protected", data=protected) |
| 471 |
self._log("payload", data=payload) |
| 472 |
data = self.sign_request( |
| 473 |
protected=protected, |
| 474 |
payload=payload, |
| 475 |
key_data=key_data, |
| 476 |
encode_payload=encode_payload, |
| 477 |
) |
| 478 |
self._log("signed request", data=data) |
| 479 |
data_str = self.module.jsonify(data) |
| 480 |
|
| 481 |
headers = { |
| 482 |
"Content-Type": "application/jose+json", |
| 483 |
} |
| 484 |
resp, info = fetch_url( |
| 485 |
self.module, |
| 486 |
url, |
| 487 |
data=data_str, |
| 488 |
headers=headers, |
| 489 |
method="POST", |
| 490 |
timeout=self.request_timeout, |
| 491 |
) |
| 492 |
if _decode_retry( |
| 493 |
module=self.module, response=resp, info=info, retry_count=failed_tries |
| 494 |
): |
| 495 |
failed_tries += 1 |
| 496 |
continue |
| 497 |
_assert_fetch_url_success(module=self.module, response=resp, info=info) |
| 498 |
result: object | bytes = {} |
| 499 |
|
| 500 |
try: |
| 501 |
# In Python 2, reading from a closed response yields a TypeError. |
| 502 |
# In Python 3, read() simply returns '' |
| 503 |
if resp.closed: |
| 504 |
raise TypeError |
| 505 |
content = resp.read() |
| 506 |
except (AttributeError, TypeError): |
| 507 |
content = info.pop("body", None) |
| 508 |
|
| 509 |
if content or not parse_json_result: |
| 510 |
if ( |
| 511 |
parse_json_result |
| 512 |
and info["content-type"].startswith("application/json") |
| 513 |
) or 400 <= info["status"] < 600: |
| 514 |
try: |
| 515 |
decoded_result = self.module.from_json(content.decode("utf8")) |
| 516 |
self._log("parsed result", data=decoded_result) |
| 517 |
# In case of badNonce error, try again (up to 5 times) |
| 518 |
# (https://tools.ietf.org/html/rfc8555#section-6.7) |
| 519 |
if ( |
| 520 |
400 <= info["status"] < 600 |
| 521 |
and failed_tries <= 5 |
| 522 |
and isinstance(decoded_result, dict) |
| 523 |
and decoded_result.get("type") |
| 524 |
== "urn:ietf:params:acme:error:badNonce" |
| 525 |
): |
| 526 |
failed_tries += 1 |
| 527 |
continue |
| 528 |
if parse_json_result: |
| 529 |
result = decoded_result |
| 530 |
else: |
| 531 |
result = content |
| 532 |
except ValueError as exc: |
| 533 |
raise NetworkException( |
| 534 |
f"Failed to parse the ACME response: {url} {content}" |
| 535 |
) from exc |
| 536 |
else: |
| 537 |
result = content |
| 538 |
|
| 539 |
if fail_on_error and _is_failed( |
| 540 |
info=info, expected_status_codes=expected_status_codes |
| 541 |
): |
| 542 |
raise ACMEProtocolException( |
| 543 |
module=self.module, |
| 544 |
msg=error_msg, |
| 545 |
info=info, |
| 546 |
content=content, |
| 547 |
content_json=result if parse_json_result else None, |
| 548 |
) |
| 549 |
return result, info |
| 550 |
|
| 551 |
@t.overload |
| 552 |
def get_request( |
| 553 |
self, |
| 554 |
uri: str, |
| 555 |
*, |
| 556 |
parse_json_result: t.Literal[True] = True, |
| 557 |
headers: dict[str, str] | None = None, |
| 558 |
get_only: bool = False, |
| 559 |
fail_on_error: bool = True, |
| 560 |
error_msg: str | None = None, |
| 561 |
expected_status_codes: t.Iterable[int] | None = None, |
| 562 |
) -> tuple[object, dict[str, t.Any]]: ... |
| 563 |
|
| 564 |
@t.overload |
| 565 |
def get_request( |
| 566 |
self, |
| 567 |
uri: str, |
| 568 |
*, |
| 569 |
parse_json_result: t.Literal[False], |
| 570 |
headers: dict[str, str] | None = None, |
| 571 |
get_only: bool = False, |
| 572 |
fail_on_error: bool = True, |
| 573 |
error_msg: str | None = None, |
| 574 |
expected_status_codes: t.Iterable[int] | None = None, |
| 575 |
) -> tuple[bytes, dict[str, t.Any]]: ... |
| 576 |
|
| 577 |
def get_request( |
| 578 |
self, |
| 579 |
uri: str, |
| 580 |
*, |
| 581 |
parse_json_result: bool = True, |
| 582 |
headers: dict[str, str] | None = None, |
| 583 |
get_only: bool = False, |
| 584 |
fail_on_error: bool = True, |
| 585 |
error_msg: str | None = None, |
| 586 |
expected_status_codes: t.Iterable[int] | None = None, |
| 587 |
) -> tuple[object | bytes, dict[str, t.Any]]: |
| 588 |
""" |
| 589 |
Perform a GET-like request. Will try POST-as-GET for ACMEv2, with fallback |
| 590 |
to GET if server replies with a status code of 405. |
| 591 |
""" |
| 592 |
if not get_only: |
| 593 |
# Try POST-as-GET |
| 594 |
content, info = self.send_signed_request( |
| 595 |
uri, None, parse_json_result=False, fail_on_error=False |
| 596 |
) |
| 597 |
if info["status"] == 405: |
| 598 |
# Instead, do unauthenticated GET |
| 599 |
get_only = True |
| 600 |
else: |
| 601 |
# Do unauthenticated GET |
| 602 |
get_only = True |
| 603 |
|
| 604 |
if get_only: |
| 605 |
# Perform unauthenticated GET |
| 606 |
retry_count = 0 |
| 607 |
while True: |
| 608 |
resp, info = fetch_url( |
| 609 |
self.module, |
| 610 |
uri, |
| 611 |
method="GET", |
| 612 |
headers=headers, |
| 613 |
timeout=self.request_timeout, |
| 614 |
) |
| 615 |
if not _decode_retry( |
| 616 |
module=self.module, |
| 617 |
response=resp, |
| 618 |
info=info, |
| 619 |
retry_count=retry_count, |
| 620 |
): |
| 621 |
break |
| 622 |
retry_count += 1 |
| 623 |
|
| 624 |
_assert_fetch_url_success(module=self.module, response=resp, info=info) |
| 625 |
|
| 626 |
try: |
| 627 |
# In Python 2, reading from a closed response yields a TypeError. |
| 628 |
# In Python 3, read() simply returns '' |
| 629 |
if resp.closed: |
| 630 |
raise TypeError |
| 631 |
content = resp.read() |
| 632 |
except (AttributeError, TypeError): |
| 633 |
content = info.pop("body", None) |
| 634 |
|
| 635 |
# Process result |
| 636 |
parsed_json_result = False |
| 637 |
result: object | bytes |
| 638 |
if parse_json_result: |
| 639 |
result = {} |
| 640 |
if content: |
| 641 |
if info["content-type"].startswith("application/json"): |
| 642 |
try: |
| 643 |
result = self.module.from_json(content.decode("utf8")) |
| 644 |
parsed_json_result = True |
| 645 |
except ValueError as exc: |
| 646 |
raise NetworkException( |
| 647 |
f"Failed to parse the ACME response: {uri} {content!r}" |
| 648 |
) from exc |
| 649 |
else: |
| 650 |
result = content |
| 651 |
else: |
| 652 |
result = content |
| 653 |
|
| 654 |
if fail_on_error and _is_failed( |
| 655 |
info=info, expected_status_codes=expected_status_codes |
| 656 |
): |
| 657 |
raise ACMEProtocolException( |
| 658 |
module=self.module, |
| 659 |
msg=error_msg, |
| 660 |
info=info, |
| 661 |
content=content, |
| 662 |
content_json=( |
| 663 |
t.cast(dict[str, t.Any], result) if parsed_json_result else None |
| 664 |
), |
| 665 |
) |
| 666 |
return result, info |
| 667 |
|
| 668 |
def get_renewal_info( |
| 669 |
self, |
| 670 |
*, |
| 671 |
cert_id: str | None = None, |
| 672 |
cert_info: CertificateInformation | None = None, |
| 673 |
cert_filename: str | os.PathLike | None = None, |
| 674 |
cert_content: str | bytes | None = None, |
| 675 |
include_retry_after: bool = False, |
| 676 |
retry_after_relative_with_timezone: bool = True, |
| 677 |
) -> dict[str, t.Any]: |
| 678 |
if not self.directory.has_renewal_info_endpoint(): |
| 679 |
raise ModuleFailException( |
| 680 |
"The ACME endpoint does not support ACME Renewal Information retrieval" |
| 681 |
) |
| 682 |
|
| 683 |
if cert_id is None: |
| 684 |
cert_id = compute_cert_id( |
| 685 |
backend=self.backend, |
| 686 |
cert_info=cert_info, |
| 687 |
cert_filename=cert_filename, |
| 688 |
cert_content=cert_content, |
| 689 |
) |
| 690 |
url = f"{self.directory.directory['renewalInfo'].rstrip('/')}/{cert_id}" |
| 691 |
|
| 692 |
data, info = self.get_request( |
| 693 |
url, parse_json_result=True, fail_on_error=True, get_only=True |
| 694 |
) |
| 695 |
if not isinstance(data, dict): |
| 696 |
raise ACMEProtocolException( |
| 697 |
module=self.module, |
| 698 |
msg="Unexpected renewal information", |
| 699 |
info=info, |
| 700 |
content_json=data, |
| 701 |
) |
| 702 |
|
| 703 |
# Include Retry-After header if asked for |
| 704 |
if include_retry_after and "retry-after" in info: |
| 705 |
try: |
| 706 |
data["retryAfter"] = parse_retry_after( |
| 707 |
info["retry-after"], |
| 708 |
relative_with_timezone=retry_after_relative_with_timezone, |
| 709 |
) |
| 710 |
except ValueError: |
| 711 |
pass |
| 712 |
return data |
| 713 |
|
| 714 |
|
| 715 |
def create_default_argspec( |
| 716 |
*, |
| 717 |
with_account: bool = True, |
| 718 |
require_account_key: bool = True, |
| 719 |
with_certificate: bool = False, |
| 720 |
) -> ArgumentSpec: |
| 721 |
""" |
| 722 |
Provides default argument spec for the options documented in the acme doc fragment. |
| 723 |
""" |
| 724 |
result = ArgumentSpec( |
| 725 |
argument_spec={ |
| 726 |
"acme_directory": {"type": "str", "required": True}, |
| 727 |
"acme_version": {"type": "int", "choices": [2], "default": 2}, |
| 728 |
"validate_certs": {"type": "bool", "default": True}, |
| 729 |
"select_crypto_backend": { |
| 730 |
"type": "str", |
| 731 |
"default": "auto", |
| 732 |
"choices": ["auto", "openssl", "cryptography"], |
| 733 |
}, |
| 734 |
"request_timeout": {"type": "int", "default": 10}, |
| 735 |
}, |
| 736 |
) |
| 737 |
if with_account: |
| 738 |
result.update_argspec( |
| 739 |
account_key_src={"type": "path", "aliases": ["account_key"]}, |
| 740 |
account_key_content={"type": "str", "no_log": True}, |
| 741 |
account_key_passphrase={"type": "str", "no_log": True}, |
| 742 |
account_uri={"type": "str"}, |
| 743 |
) |
| 744 |
if require_account_key: |
| 745 |
result.update(required_one_of=[["account_key_src", "account_key_content"]]) |
| 746 |
result.update(mutually_exclusive=[["account_key_src", "account_key_content"]]) |
| 747 |
if with_certificate: |
| 748 |
result.update_argspec( |
| 749 |
csr={"type": "path"}, |
| 750 |
csr_content={"type": "str"}, |
| 751 |
) |
| 752 |
result.update( |
| 753 |
required_one_of=[["csr", "csr_content"]], |
| 754 |
mutually_exclusive=[["csr", "csr_content"]], |
| 755 |
) |
| 756 |
return result |
| 757 |
|
| 758 |
|
| 759 |
def create_backend( |
| 760 |
module: AnsibleModule, *, needs_acme_v2: bool = True |
| 761 |
) -> CryptoBackend: |
| 762 |
backend = module.params["select_crypto_backend"] |
| 763 |
|
| 764 |
# Backend autodetect |
| 765 |
if backend == "auto": |
| 766 |
backend = "cryptography" if HAS_CURRENT_CRYPTOGRAPHY else "openssl" |
| 767 |
|
| 768 |
# Create backend object |
| 769 |
module_backend: CryptoBackend |
| 770 |
if backend == "cryptography": |
| 771 |
if CRYPTOGRAPHY_ERROR is not None: |
| 772 |
# Either we could not import cryptography at all, or there was an unexpected error |
| 773 |
if CRYPTOGRAPHY_VERSION is None: |
| 774 |
msg = missing_required_lib("cryptography") |
| 775 |
else: |
| 776 |
msg = f"Unexpected error while preparing cryptography: {CRYPTOGRAPHY_ERROR.splitlines()[-1]}" |
| 777 |
module.fail_json(msg=msg, exception=CRYPTOGRAPHY_ERROR) |
| 778 |
if not HAS_CURRENT_CRYPTOGRAPHY: |
| 779 |
# We succeeded importing cryptography, but its version is too old. |
| 780 |
mrl = missing_required_lib( |
| 781 |
f"cryptography >= {CRYPTOGRAPHY_MINIMAL_VERSION}" |
| 782 |
) |
| 783 |
module.fail_json( |
| 784 |
msg=f"Found cryptography, but only version {CRYPTOGRAPHY_VERSION}. {mrl}" |
| 785 |
) |
| 786 |
module.debug( |
| 787 |
f"Using cryptography backend (library version {CRYPTOGRAPHY_VERSION})" |
| 788 |
) |
| 789 |
module_backend = CryptographyBackend(module=module) |
| 790 |
elif backend == "openssl": |
| 791 |
module.debug("Using OpenSSL binary backend") |
| 792 |
module_backend = OpenSSLCLIBackend(module=module) |
| 793 |
else: |
| 794 |
module.fail_json(msg=f'Unknown crypto backend "{backend}"!') |
| 795 |
|
| 796 |
# Check common module parameters |
| 797 |
if not module.params["validate_certs"]: |
| 798 |
module.warn( |
| 799 |
"Disabling certificate validation for communications with ACME endpoint. " |
| 800 |
"This should only be done for testing against a local ACME server for " |
| 801 |
"development purposes, but *never* for production purposes." |
| 802 |
) |
| 803 |
|
| 804 |
# AnsibleModule() changes the locale, so change it back to C because we rely |
| 805 |
# on datetime.datetime.strptime() when parsing certificate dates. |
| 806 |
locale.setlocale(locale.LC_ALL, "C") |
| 807 |
|
| 808 |
return module_backend |
| 809 |
|
| 810 |
|
| 811 |
__all__ = ( |
| 812 |
"ACMEClient", |
| 813 |
"ACMEDirectory", |
| 814 |
"create_backend", |
| 815 |
"create_default_argspec", |
| 816 |
) |