Debian Codegraph @

hass_nabucasa/acme.py

raw
1 """Handle ACME and local certificates."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from collections.abc import Callable
7 import contextlib
8 from datetime import datetime, timedelta
9 import logging
10 from pathlib import Path
11 from socket import gaierror
12 from typing import TYPE_CHECKING
13 import urllib
14
15 from acme import challenges, client, crypto_util, errors, messages
16 from atomicwrites import atomic_write
17 import attr
18 from cryptography import x509
19 from cryptography.hazmat.primitives import hashes, serialization
20 from cryptography.hazmat.primitives.asymmetric import rsa
21 from cryptography.x509.extensions import SubjectAlternativeName
22 from cryptography.x509.oid import NameOID
23 import josepy as jose
24 import OpenSSL
25 from requests.exceptions import RequestException
26
27 from .const import CertificateStatus
28 from .utils import seconds_as_dhms, utcnow
29
30 FILE_ACCOUNT_KEY = "acme_account.pem"
31 FILE_PRIVATE_KEY = "remote_private.pem"
32 FILE_FULLCHAIN = "remote_fullchain.pem"
33 FILE_REGISTRATION = "acme_reg.json"
34
35 ACCOUNT_KEY_SIZE = 2048
36 PRIVATE_KEY_SIZE = 2048
37 USER_AGENT = "home-assistant-cloud"
38
39 _LOGGER = logging.getLogger(__name__)
40
41
42 _ACME_CLIENT_EXCEPTIONS = (
43 messages.Error,
44 errors.Error,
45 gaierror,
46 # https://github.com/certbot/certbot/blob/9ba139a9ef5f5a9921d2fe8151f9f05e2dfb339f/acme/src/acme/client.py#L727
47 # The client raises requests.exceptions.RequestException in case of any issue
48 RequestException,
49 )
50
51 if TYPE_CHECKING:
52 from . import Cloud, _ClientT
53
54
55 def _raise_if_jws_verification_failed(exception: Exception) -> None:
56 """Raise if JWS verification failed."""
57 if (
58 isinstance(exception, messages.Error)
59 and exception.typ == "urn:ietf:params:acme:error:malformed"
60 and str(exception.detail).split(" ::", maxsplit=1)[0]
61 in {"JWS verification error", "Unable to validate JWS"}
62 ):
63 raise AcmeJWSVerificationError(
64 f"JWS verification failed: {exception}",
65 ) from exception
66
67
68 class AcmeClientError(Exception):
69 """Raise if a acme client error raise."""
70
71
72 class AcmeChallengeError(AcmeClientError):
73 """Raise if a challenge fails."""
74
75
76 class AcmeJWSVerificationError(AcmeClientError):
77 """Raise if a JWS verification fails."""
78
79
80 class AcmeNabuCasaError(AcmeClientError):
81 """Raise errors on nabucasa API."""
82
83
84 @attr.s
85 class ChallengeHandler:
86 """Handle ACME data over a challenge."""
87
88 challenge = attr.ib(type=messages.ChallengeBody)
89 order = attr.ib(type=messages.OrderResource)
90 response = attr.ib(type=challenges.ChallengeResponse)
91 validation = attr.ib(type=str)
92
93
94 class AcmeHandler:
95 """Class handle a local certification."""
96
97 def __init__(
98 self,
99 cloud: Cloud[_ClientT],
100 domains: list[str],
101 email: str,
102 status_callback: Callable[[CertificateStatus], None],
103 ) -> None:
104 """Initialize local ACME Handler."""
105 self.cloud = cloud
106 self._account_jwk: jose.JWKRSA | None = None
107 self._acme_client: client.ClientV2 | None = None
108 self._x509: x509.Certificate | None = None
109
110 self._domains = domains
111 self._email = email
112 self._status_callback = status_callback
113
114 def _update_status(self, status: CertificateStatus) -> None:
115 """Update certificate status via callback."""
116 self._status_callback(status)
117
118 @property
119 def acme_directory_url(self) -> str:
120 """Return the ACME directory URL."""
121 return self.cloud.service_discovery.action_url("acme_directory")
122
123 @property
124 def email(self) -> str:
125 """Return the email."""
126 return self._email
127
128 @property
129 def domains(self) -> list[str]:
130 """Return the domains."""
131 return self._domains
132
133 @property
134 def path_account_key(self) -> Path:
135 """Return path of account key."""
136 return Path(self.cloud.path(FILE_ACCOUNT_KEY))
137
138 @property
139 def path_private_key(self) -> Path:
140 """Return path of private key."""
141 return Path(self.cloud.path(FILE_PRIVATE_KEY))
142
143 @property
144 def path_fullchain(self) -> Path:
145 """Return path of cert fullchain."""
146 return Path(self.cloud.path(FILE_FULLCHAIN))
147
148 @property
149 def path_registration_info(self) -> Path:
150 """Return path of acme client registration file."""
151 return Path(self.cloud.path(FILE_REGISTRATION))
152
153 @property
154 def certificate_available(self) -> bool:
155 """Return True if a certificate is loaded."""
156 return self._x509 is not None
157
158 @property
159 def is_valid_certificate(self) -> bool:
160 """Validate date of a certificate and return True is valid."""
161 if (expire_date := self.expire_date) is None:
162 return False
163 return expire_date > utcnow()
164
165 @property
166 def expire_date(self) -> datetime | None:
167 """Return datetime of expire date for certificate."""
168 if not self._x509:
169 return None
170 return self._x509.not_valid_after_utc
171
172 @property
173 def common_name(self) -> str | None:
174 """Return CommonName of certificate."""
175 if not self._x509:
176 return None
177 return str(
178 self._x509.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value,
179 )
180
181 @property
182 def alternative_names(self) -> list[str] | None:
183 """Return alternative names of certificate."""
184 if not self._x509:
185 return None
186
187 alternative_names = self._x509.extensions.get_extension_for_class(
188 SubjectAlternativeName,
189 ).value
190 return [str(entry.value) for entry in alternative_names]
191
192 @property
193 def fingerprint(self) -> str | None:
194 """Return SHA1 hex string as fingerprint."""
195 if not self._x509:
196 return None
197 fingerprint = self._x509.fingerprint(hashes.SHA1())
198 return fingerprint.hex()
199
200 def _generate_csr(self) -> bytes:
201 """Load or create private key."""
202 if self.path_private_key.exists():
203 _LOGGER.debug("Load private keyfile: %s", self.path_private_key)
204 key_pem = self.path_private_key.read_bytes()
205 else:
206 _LOGGER.debug("create private keyfile: %s", self.path_private_key)
207 key = OpenSSL.crypto.PKey()
208 key.generate_key(OpenSSL.crypto.TYPE_RSA, PRIVATE_KEY_SIZE)
209 key_pem = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
210
211 self.path_private_key.write_bytes(key_pem)
212 self.path_private_key.chmod(0o600)
213
214 return crypto_util.make_csr(key_pem, self._domains)
215
216 def _load_account_key(self) -> None:
217 """Load or create account key."""
218 if self.path_account_key.exists():
219 _LOGGER.debug("Load account keyfile: %s", self.path_account_key)
220 pem = self.path_account_key.read_bytes()
221 key = serialization.load_pem_private_key(pem, password=None)
222
223 else:
224 _LOGGER.debug("Create new RSA keyfile: %s", self.path_account_key)
225 key = rsa.generate_private_key(
226 public_exponent=65537,
227 key_size=ACCOUNT_KEY_SIZE,
228 )
229
230 # Store it to file
231 pem = key.private_bytes(
232 encoding=serialization.Encoding.PEM,
233 format=serialization.PrivateFormat.PKCS8,
234 encryption_algorithm=serialization.NoEncryption(),
235 )
236 self.path_account_key.write_bytes(pem)
237 self.path_account_key.chmod(0o600)
238
239 if TYPE_CHECKING:
240 assert isinstance(key, rsa.RSAPrivateKey)
241 self._account_jwk = jose.JWKRSA(key=jose.ComparableRSAKey(key))
242
243 def _create_client(self) -> None:
244 """Create new ACME client."""
245 if self.path_registration_info.exists():
246 _LOGGER.info("Load exists ACME registration")
247 regr = messages.RegistrationResource.json_loads(
248 self.path_registration_info.read_text(encoding="utf-8"),
249 )
250
251 acme_url = urllib.parse.urlparse(self.acme_directory_url)
252 regr_url = urllib.parse.urlparse(regr.uri)
253
254 if acme_url[0] != regr_url[0] or acme_url[1] != regr_url[1]:
255 _LOGGER.info("Reset new ACME registration")
256 self.path_registration_info.unlink()
257 self.path_account_key.unlink()
258
259 # Make sure that account key is loaded
260 self._load_account_key()
261 assert self._account_jwk is not None
262
263 # Load a exists registration
264 if self.path_registration_info.exists():
265 try:
266 network = client.ClientNetwork(
267 self._account_jwk,
268 account=regr,
269 user_agent=USER_AGENT,
270 )
271 directory = client.ClientV2.get_directory(
272 url=self.acme_directory_url,
273 net=network,
274 )
275 self._acme_client = client.ClientV2(directory=directory, net=network)
276 except _ACME_CLIENT_EXCEPTIONS as err:
277 _raise_if_jws_verification_failed(err)
278 raise AcmeClientError(f"Can't connect to ACME server: {err}") from err
279 return
280
281 # Create a new registration
282 try:
283 network = client.ClientNetwork(self._account_jwk, user_agent=USER_AGENT)
284 directory = client.ClientV2.get_directory(
285 url=self.acme_directory_url,
286 net=network,
287 )
288 self._acme_client = client.ClientV2(directory=directory, net=network)
289 except _ACME_CLIENT_EXCEPTIONS as err:
290 _raise_if_jws_verification_failed(err)
291 raise AcmeClientError(f"Can't connect to ACME server: {err}") from err
292
293 try:
294 _LOGGER.info(
295 "Register a ACME account with TOS: %s",
296 self._acme_client.directory.meta.terms_of_service,
297 )
298 regr = self._acme_client.new_account(
299 messages.NewRegistration.from_data(
300 email=self._email,
301 terms_of_service_agreed=True,
302 ),
303 )
304 except _ACME_CLIENT_EXCEPTIONS as err:
305 _raise_if_jws_verification_failed(err)
306 raise AcmeClientError(f"Can't register to ACME server: {err}") from err
307
308 # Store registration info
309 self.path_registration_info.write_text(
310 regr.json_dumps_pretty(),
311 encoding="utf-8",
312 )
313 self.path_registration_info.chmod(0o600)
314
315 def _create_order(self, csr_pem: bytes) -> messages.OrderResource:
316 """Initialize domain challenge and return token."""
317 _LOGGER.info("Initialize challenge for a new ACME certificate")
318 assert self._acme_client is not None
319 try:
320 return self._acme_client.new_order(csr_pem)
321 except _ACME_CLIENT_EXCEPTIONS as err:
322 _raise_if_jws_verification_failed(err)
323 raise AcmeChallengeError(
324 f"Can't order a new ACME challenge: {err}",
325 ) from err
326
327 def _start_challenge(self, order: messages.OrderResource) -> list[ChallengeHandler]:
328 """Initialize domain challenge and return token."""
329 _LOGGER.info("Start challenge for a new ACME certificate")
330
331 # Find DNS challenge
332 # pylint: disable=not-an-iterable
333 dns_challenges: list[messages.ChallengeBody] = []
334 for auth in order.authorizations:
335 for challenge in auth.body.challenges:
336 if challenge.typ != "dns-01":
337 continue
338 dns_challenges.append(challenge)
339
340 if len(dns_challenges) == 0:
341 raise AcmeChallengeError("No pending ACME challenge")
342
343 handlers = []
344
345 for dns_challenge in dns_challenges:
346 try:
347 response, validation = dns_challenge.response_and_validation(
348 self._account_jwk,
349 )
350 except _ACME_CLIENT_EXCEPTIONS as err:
351 raise AcmeChallengeError(
352 f"Can't validate the new ACME challenge: {err}",
353 ) from err
354 handlers.append(
355 ChallengeHandler(dns_challenge, order, response, validation),
356 )
357
358 return handlers
359
360 def _answer_challenge(self, handler: ChallengeHandler) -> None:
361 """Answer challenge."""
362 _LOGGER.info("Answer challenge for the new ACME certificate")
363 if TYPE_CHECKING:
364 assert self._acme_client is not None
365 try:
366 self._acme_client.answer_challenge(handler.challenge, handler.response)
367 except _ACME_CLIENT_EXCEPTIONS as err:
368 raise AcmeChallengeError(f"Can't accept ACME challenge: {err}") from err
369
370 def _finish_challenge(self, order: messages.OrderResource) -> None:
371 """Wait until challenge is finished."""
372 # Wait until it's authorize and fetch certification
373 if TYPE_CHECKING:
374 assert self._acme_client is not None
375 deadline = datetime.now() + timedelta(seconds=90)
376 try:
377 order = self._acme_client.poll_authorizations(order, deadline)
378 order = self._acme_client.finalize_order(
379 order,
380 deadline,
381 fetch_alternative_chains=True,
382 )
383 except _ACME_CLIENT_EXCEPTIONS as err:
384 raise AcmeChallengeError(f"Wait of ACME challenge fails: {err}") from err
385 except Exception: # pylint: disable=broad-except
386 _LOGGER.exception("Unexpected exception while finalizing order")
387 raise AcmeChallengeError(
388 "Unexpected exception while finalizing order",
389 ) from None
390
391 # Cleanup the old stuff
392 if self.path_fullchain.exists():
393 _LOGGER.info("Renew old certificate: %s", self.path_fullchain)
394 self.path_fullchain.unlink()
395 else:
396 _LOGGER.info("Create new certificate: %s", self.path_fullchain)
397
398 with atomic_write(self.path_fullchain, overwrite=True) as fp:
399 fp.write(order.fullchain_pem)
400 self.path_fullchain.chmod(0o600)
401
402 async def load_certificate(self) -> None:
403 """Get x509 Cert-Object."""
404 if self._x509:
405 # The certificate is already loaded
406 return
407
408 self._update_status(CertificateStatus.LOADING)
409
410 def _load_cert() -> x509.Certificate | None:
411 """Load certificate in a thread."""
412 if not self.path_fullchain.exists():
413 # The certificate is not available
414 return None
415 return x509.load_pem_x509_certificate(self.path_fullchain.read_bytes())
416
417 try:
418 self._x509 = await self.cloud.run_executor(_load_cert)
419 if self._x509:
420 self._update_status(CertificateStatus.LOADED)
421 except Exception: # pylint: disable=broad-except
422 _LOGGER.exception("Unexpected exception loading certificate")
423 self._update_status(CertificateStatus.ERROR)
424
425 def _revoke_certificate(self) -> None:
426 """Revoke certificate."""
427 if not self.path_fullchain.exists():
428 _LOGGER.warning("Can't revoke a certificate that does not exist")
429 return
430
431 if self._acme_client is None:
432 _LOGGER.error("No acme client")
433 return
434
435 fullchain = OpenSSL.crypto.load_certificate(
436 OpenSSL.crypto.FILETYPE_PEM,
437 self.path_fullchain.read_bytes(),
438 ).to_cryptography()
439
440 _LOGGER.info("Revoke certificate")
441 try:
442 # https://letsencrypt.org/docs/revoking/#specifying-a-reason-code
443 self._acme_client.revoke(fullchain, 4)
444 except errors.ConflictError:
445 pass
446 except _ACME_CLIENT_EXCEPTIONS as err:
447 # Ignore errors where certificate did not exist
448 if "No such certificate" in str(err): # noqa: SIM114
449 pass
450 # Ignore errors where certificate has expired
451 elif "Certificate is expired" in str(err): # noqa: SIM114
452 pass
453 # Ignore errors where unrecognized issuer (happens dev/prod switch)
454 elif "Certificate from unrecognized issuer" in str(err):
455 pass
456 else:
457 raise AcmeClientError(f"Can't revoke certificate: {err}") from err
458
459 def _deactivate_account(self) -> None:
460 """Deactivate account."""
461 if not self.path_registration_info.exists() or self._acme_client is None:
462 return
463
464 _LOGGER.info("Load exists ACME registration")
465 regr = messages.RegistrationResource.json_loads(
466 self.path_registration_info.read_text(encoding="utf-8"),
467 )
468
469 try:
470 self._acme_client.deactivate_registration(regr)
471 except _ACME_CLIENT_EXCEPTIONS as err:
472 raise AcmeClientError(f"Can't deactivate account: {err}") from err
473
474 def _have_any_file(self) -> bool:
475 return (
476 self.path_registration_info.exists()
477 or self.path_account_key.exists()
478 or self.path_fullchain.exists()
479 or self.path_private_key.exists()
480 )
481
482 def _remove_files(self) -> None:
483 self.path_registration_info.unlink(missing_ok=True)
484 self.path_account_key.unlink(missing_ok=True)
485 self.path_fullchain.unlink(missing_ok=True)
486 self.path_private_key.unlink(missing_ok=True)
487
488 async def issue_certificate(self) -> None:
489 """Create/Update certificate."""
490 self._update_status(CertificateStatus.ACME_ACCOUNT_CREATING)
491
492 if not self._acme_client:
493 await self.cloud.run_executor(self._create_client)
494
495 self._update_status(CertificateStatus.ACME_ACCOUNT_CREATED)
496
497 # Initialize challenge / new certificate
498 self._update_status(CertificateStatus.CSR_GENERATING)
499 csr = await self.cloud.run_executor(self._generate_csr)
500
501 self._update_status(CertificateStatus.CHALLENGE_PENDING)
502 order = await self.cloud.run_executor(self._create_order, csr)
503
504 self._update_status(CertificateStatus.CHALLENGE_CREATED)
505 dns_challenges: list[ChallengeHandler] = await self.cloud.run_executor(
506 self._start_challenge,
507 order,
508 )
509
510 try:
511 for challenge in dns_challenges:
512 # Update DNS
513 self._update_status(CertificateStatus.CHALLENGE_DNS_UPDATING)
514 try:
515 async with asyncio.timeout(30):
516 await self.cloud.instance.create_dns_challenge_record(
517 value=challenge.validation
518 )
519 self._update_status(CertificateStatus.CHALLENGE_DNS_UPDATED)
520 except TimeoutError, AssertionError:
521 self._update_status(CertificateStatus.CHALLENGE_DNS_FAILED)
522 raise AcmeNabuCasaError(
523 "Can't set challenge token to NabuCasa DNS!",
524 ) from None
525
526 # Wait for DNS propagation and answer challenge
527 self._update_status(CertificateStatus.CHALLENGE_DNS_PROPAGATING)
528 try:
529 _LOGGER.info(
530 "Waiting %s for publishing DNS to ACME provider",
531 seconds_as_dhms(60),
532 )
533 await asyncio.sleep(60)
534
535 self._update_status(CertificateStatus.CHALLENGE_ANSWERING)
536 await self.cloud.run_executor(self._answer_challenge, challenge)
537
538 self._update_status(CertificateStatus.CHALLENGE_ANSWERED)
539 except AcmeChallengeError as err:
540 _LOGGER.error("Could not complete answer challenge - %s", err)
541 self._update_status(CertificateStatus.CHALLENGE_ANSWER_FAILED)
542 # There is no point in continuing here
543 break
544 except Exception: # pylint: disable=broad-except
545 _LOGGER.exception("Unexpected exception while answering challenge")
546 self._update_status(CertificateStatus.CHALLENGE_UNEXPECTED_ERROR)
547 # There is no point in continuing here
548 break
549 finally:
550 # Cleanup DNS challenge records
551 self._update_status(CertificateStatus.CHALLENGE_CLEANUP)
552 try:
553 async with asyncio.timeout(30):
554 # We only need to cleanup for the last entry
555 await self.cloud.instance.cleanup_dns_challenge_record(
556 value=dns_challenges[-1].validation,
557 )
558 except TimeoutError:
559 _LOGGER.error("Failed to clean up challenge from NabuCasa DNS!")
560
561 # Finish validation
562 self._update_status(CertificateStatus.CERTIFICATE_FINALIZING)
563 try:
564 await self.cloud.run_executor(self._finish_challenge, order)
565 except AcmeChallengeError as err:
566 self._update_status(CertificateStatus.CERTIFICATE_FINALIZATION_FAILED)
567 raise AcmeNabuCasaError(f"Could not finish challenge - {err}") from err
568 await self.load_certificate()
569
570 async def reset_acme(self) -> None:
571 """Revoke and deactivate acme certificate/account."""
572 _LOGGER.info("Revoke and deactivate ACME user/certificate")
573 if (
574 self._acme_client is None
575 and self._account_jwk is None
576 and self._x509 is None
577 and not await self.cloud.run_executor(self._have_any_file)
578 ):
579 _LOGGER.info("ACME user/certificates already cleaned up")
580 return
581
582 if not self._acme_client:
583 await self.cloud.run_executor(self._create_client)
584
585 try:
586 with contextlib.suppress(AcmeClientError):
587 await self.cloud.run_executor(self._revoke_certificate)
588 with contextlib.suppress(AcmeClientError):
589 await self.cloud.run_executor(self._deactivate_account)
590 finally:
591 self._acme_client = None
592 self._account_jwk = None
593 self._x509 = None
594 await self.cloud.run_executor(self._remove_files)
595
596 async def hardening_files(self) -> None:
597 """Control permission on files."""
598
599 def _control() -> None:
600 # Set file permission to 0600
601 if self.path_account_key.exists():
602 self.path_account_key.chmod(0o600)
603 if self.path_registration_info.exists():
604 self.path_registration_info.chmod(0o600)
605 if self.path_fullchain.exists():
606 self.path_fullchain.chmod(0o600)
607 if self.path_private_key.exists():
608 self.path_private_key.chmod(0o600)
609
610 try:
611 await self.cloud.run_executor(_control)
612 except OSError:
613 _LOGGER.warning("Can't check and hardening file permission")