2121# Add script directory to path to import dns_providers
2222sys .path .insert (0 , os .path .dirname (os .path .abspath (__file__ )))
2323
24+ LETSENCRYPT_DIR = "/etc/letsencrypt"
2425# certbot cannot keep a lineage for a key it did not generate, so certificates
2526# for derived keys live here, apart from its lineages, and certman.py renews
2627# them itself.
@@ -228,6 +229,9 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
228229 if os .environ .get ("DELEGATION_ZONE" , "" ).strip ():
229230 hook = "/scripts/acme-dns-alias-hook.sh"
230231 base_cmd = certbot_cmd + [action , "--non-interactive" , "-v" ]
232+ # For `renew`, certbot reuses the authenticator + hooks saved in the
233+ # renewal config from the initial `certonly`, so we don't re-specify
234+ # them here (and must not fall back to the DNS plugin).
231235 if action == "certonly" :
232236 base_cmd .extend ([
233237 "--manual" ,
@@ -243,10 +247,7 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
243247 base_cmd .append ("--register-unsafely-without-email" )
244248 base_cmd .extend (extra_args )
245249 base_cmd .extend (["-d" , domain ])
246- # For `renew`, certbot reuses the authenticator + hooks saved in the
247- # renewal config from the initial `certonly`, so we don't re-specify
248- # them here (and must not fall back to the DNS plugin).
249- if not deterministic_key .enabled ():
250+ if "--csr" not in extra_args :
250251 base_cmd .extend (["--cert-name" , self ._lineage_name (domain )])
251252 # Explicit on `renew` too: certbot would otherwise take the server
252253 # saved in the lineage, whatever the configuration says now.
@@ -289,7 +290,7 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
289290 else :
290291 base_cmd .append ("--register-unsafely-without-email" )
291292 base_cmd .extend (["-d" , domain ])
292- if not deterministic_key . enabled () :
293+ if "--csr" not in extra_args :
293294 # Without this, `certbot renew` renews *every* lineage in
294295 # /etc/letsencrypt/renewal. run_pass calls this once per domain, so
295296 # N domains meant N passes over all N lineages, and the result was
@@ -432,16 +433,16 @@ def _adopt_legacy_deterministic(self, domain: str) -> None:
432433 them left an empty renewal config, which would push the next lineage
433434 to <name>-0001; drop that too.
434435 """
435- conf = self ._renewal_conf_path (domain )
436+ base = domain [2 :] if domain .startswith ("*." ) else domain
437+ conf = f"{ LETSENCRYPT_DIR } /renewal/{ base } .conf"
436438 if os .path .isfile (conf ) and os .path .getsize (conf ) == 0 :
437439 os .remove (conf )
438440 print (f"Removed the empty renewal config { conf } " )
439- live = f"/etc/letsencrypt/ live/{ self . _lineage_name ( domain ) } "
441+ live = f"{ LETSENCRYPT_DIR } / live/{ base } "
440442 privkey = os .path .join (live , "privkey.pem" )
441443 if not os .path .isfile (privkey ) or os .path .islink (privkey ):
442444 return
443445 fullchain = os .path .join (live , "fullchain.pem" )
444- base = self ._lineage_name (domain )
445446 names = _cert_names (os .path .join (live , "cert.pem" ))
446447 target = None
447448 if names in ([base ], [f"*.{ base } " ]):
@@ -556,48 +557,64 @@ def _lineage_name(domain: str) -> str:
556557 return f"_wildcard.{ domain [2 :]} " if domain .startswith ("*." ) else domain
557558
558559 def migrate_wildcard_lineage (self , domain : str ) -> None :
559- """Rename a wildcard lineage certbot named itself (<name> or
560- <name>-NNNN) to _lineage_name, keeping the certificate in service.
561-
562- Only a lineage holding exactly the wildcard moves; one that serves the
563- base name stays. The new renewal config is written last, so an
564- interrupted run leaves the old lineage intact and is simply redone.
560+ """Move certificates out of the lineages certbot named itself.
561+
562+ Left to itself certbot named a wildcard's lineage <name> or <name>-NNNN.
563+ One holding exactly the wildcard is renamed to _lineage_name, and one
564+ holding exactly the base name to <name>, so both stay in service
565+ without re-issuance. The new renewal config is written before the old
566+ one is removed, so a lineage still found once its new name holds the
567+ same certificate names is what an interrupted rename left: it goes.
568+ The deterministic certificate the two used to share moves the same way.
565569 """
566570 base = domain [2 :] if domain .startswith ("*." ) else domain
567571 wildcard = f"*.{ base } "
568572 new = self ._lineage_name (wildcard )
569- root = "/etc/letsencrypt"
570- renewal = f"{ root } /renewal"
571- if not os .path .isdir (renewal ) or os .path .exists (f"{ renewal } /{ new } .conf" ):
573+ shared = os .path .join (DETERMINISTIC_DIR , base )
574+ if _cert_names (os .path .join (shared , "cert.pem" )) == [wildcard ]:
575+ if os .path .exists (self ._deterministic_dir (wildcard )):
576+ shutil .rmtree (shared )
577+ else :
578+ os .replace (shared , self ._deterministic_dir (wildcard ))
579+ print (f"Moved the certificate for { wildcard } out of { shared } " )
580+ renewal = f"{ LETSENCRYPT_DIR } /renewal"
581+ if not os .path .isdir (renewal ):
572582 return
573583 pattern = re .compile (rf"{ re .escape (base )} (-\d{{4}})?\.conf" )
574584 for old in sorted (n [:- len (".conf" )] for n in os .listdir (renewal ) if pattern .fullmatch (n )):
575- try :
576- with open (f"{ root } /live/{ old } /cert.pem" , "rb" ) as fh :
577- cert = x509 .load_pem_x509_certificate (fh .read ())
578- names = cert .extensions .get_extension_for_class (
579- x509 .SubjectAlternativeName ).value .get_values_for_type (x509 .DNSName )
580- with open (f"{ renewal } /{ old } .conf" , encoding = "utf-8" ) as fh :
581- conf = fh .read ()
582- except (OSError , ValueError , x509 .ExtensionNotFound ):
583- continue
584- if names != [wildcard ]:
585+ names = _cert_names (f"{ LETSENCRYPT_DIR } /live/{ old } /cert.pem" )
586+ target = {(wildcard ,): new , (base ,): base }.get (tuple (names or ()))
587+ if target is None or target == old :
585588 continue
586- for path in (f"{ root } /archive/{ new } " , f"{ root } /live/{ new } " ):
587- shutil .rmtree (path , ignore_errors = True )
588- shutil .copytree (f"{ root } /archive/{ old } " , f"{ root } /archive/{ new } " )
589- os .makedirs (f"{ root } /live/{ new } " )
590- for item in ("cert" , "chain" , "fullchain" , "privkey" ):
591- target = os .path .basename (os .readlink (f"{ root } /live/{ old } /{ item } .pem" ))
592- os .symlink (f"../../archive/{ new } /{ target } " , f"{ root } /live/{ new } /{ item } .pem" )
593- conf = conf .replace (f"{ root } /archive/{ old } \n " , f"{ root } /archive/{ new } \n " )
594- conf = conf .replace (f"{ root } /live/{ old } /" , f"{ root } /live/{ new } /" )
595- deterministic_key .write_file (f"{ renewal } /{ new } .conf" , conf .encode ())
596- os .remove (f"{ renewal } /{ old } .conf" )
597- shutil .rmtree (f"{ root } /live/{ old } " , ignore_errors = True )
598- shutil .rmtree (f"{ root } /archive/{ old } " , ignore_errors = True )
599- print (f"Renamed certbot lineage { old } to { new } for { wildcard } " )
600- return
589+ if not os .path .exists (f"{ renewal } /{ target } .conf" ):
590+ self ._rename_lineage (old , target )
591+ print (f"Renamed certbot lineage { old } to { target } " )
592+ elif _cert_names (f"{ LETSENCRYPT_DIR } /live/{ target } /cert.pem" ) == names :
593+ self ._remove_lineage (old )
594+ print (f"Removed certbot lineage { old } , a copy of { target } " )
595+
596+ @staticmethod
597+ def _rename_lineage (old : str , new : str ) -> None :
598+ root = LETSENCRYPT_DIR
599+ with open (f"{ root } /renewal/{ old } .conf" , encoding = "utf-8" ) as fh :
600+ conf = fh .read ()
601+ for path in (f"{ root } /archive/{ new } " , f"{ root } /live/{ new } " ):
602+ shutil .rmtree (path , ignore_errors = True )
603+ shutil .copytree (f"{ root } /archive/{ old } " , f"{ root } /archive/{ new } " )
604+ os .makedirs (f"{ root } /live/{ new } " )
605+ for item in ("cert" , "chain" , "fullchain" , "privkey" ):
606+ target = os .path .basename (os .readlink (f"{ root } /live/{ old } /{ item } .pem" ))
607+ os .symlink (f"../../archive/{ new } /{ target } " , f"{ root } /live/{ new } /{ item } .pem" )
608+ conf = conf .replace (f"{ root } /archive/{ old } \n " , f"{ root } /archive/{ new } \n " )
609+ conf = conf .replace (f"{ root } /live/{ old } /" , f"{ root } /live/{ new } /" )
610+ deterministic_key .write_file (f"{ root } /renewal/{ new } .conf" , conf .encode ())
611+ CertManager ._remove_lineage (old )
612+
613+ @staticmethod
614+ def _remove_lineage (name : str ) -> None :
615+ os .remove (f"{ LETSENCRYPT_DIR } /renewal/{ name } .conf" )
616+ shutil .rmtree (f"{ LETSENCRYPT_DIR } /live/{ name } " , ignore_errors = True )
617+ shutil .rmtree (f"{ LETSENCRYPT_DIR } /archive/{ name } " , ignore_errors = True )
601618
602619 def _renewal_conf_path (self , domain : str ) -> str :
603620 """Where certbot keeps this lineage's renewal config."""
@@ -769,8 +786,8 @@ def run_action(
769786 Returns:
770787 (success, needs_evidence): success status and whether evidence should be generated
771788 """
772- self .migrate_wildcard_lineage (domain )
773789 self ._adopt_legacy_deterministic (domain )
790+ self .migrate_wildcard_lineage (domain )
774791 if action == "auto" :
775792 if not self .certificate_exists (domain ):
776793 success = self .obtain_certificate (domain , email )
0 commit comments