Skip to content

Commit d585b57

Browse files
committed
fix(ingress): give wildcard certificates their own certbot lineage
With both x.com and *.x.com in DOMAINS, certbot names the lineages x.com and x.com-0001, but certman._lineage_name mapped both names to x.com: one of them was served the other's certificate, the evidence attested the wrong certificate, and renewals targeted the wrong lineage. _lineage_name now finds the lineage whose certificate holds exactly the domain, so lineages certbot named itself keep working without being renamed or re-issued. A new lineage is named explicitly: _wildcard.x.com for a wildcard (an underscore cannot appear in a certificate host name), the domain otherwise, with -NNNN appended if another certificate already holds that name. certonly passes it as --cert-name unless it is a --csr issuance, which keeps no lineage. 2.4-2.6 wrote a wildcard's derived-key files under the bare name, so the legacy live/ cleanup looks there. Signed-off-by: Kevin Wang <wy721@qq.com>
1 parent 7ca323f commit d585b57

2 files changed

Lines changed: 136 additions & 21 deletions

File tree

‎custom-domain/dstack-ingress/scripts/certman.py‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,17 @@ def renewal_due(cert: x509.Certificate, now: datetime) -> bool:
3636
return now >= not_before + (lifetime / 2 if lifetime < timedelta(days=10) else lifetime * 2 / 3)
3737

3838

39+
def _cert_names(path: str) -> Optional[List[str]]:
40+
"""The DNS names a certificate file is for, or None if it cannot be read."""
41+
try:
42+
with open(path, "rb") as fh:
43+
cert = x509.load_pem_x509_certificate(fh.read())
44+
return cert.extensions.get_extension_for_class(
45+
x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
46+
except (OSError, ValueError, x509.ExtensionNotFound):
47+
return None
48+
49+
3950
def staging_enabled() -> bool:
4051
"""Whether to use Let's Encrypt staging.
4152
@@ -219,7 +230,7 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
219230
# For `renew`, certbot reuses the authenticator + hooks saved in the
220231
# renewal config from the initial `certonly`, so we don't re-specify
221232
# them here (and must not fall back to the DNS plugin).
222-
if action == "renew":
233+
if "--csr" not in extra_args:
223234
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
224235
# Explicit on `renew` too: certbot would otherwise take the server
225236
# saved in the lineage, whatever the configuration says now.
@@ -262,11 +273,13 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
262273
else:
263274
base_cmd.append("--register-unsafely-without-email")
264275
base_cmd.extend(["-d", domain])
265-
if action == "renew":
276+
if "--csr" not in extra_args:
266277
# Without this, `certbot renew` renews *every* lineage in
267278
# /etc/letsencrypt/renewal. run_pass calls this once per domain, so
268279
# N domains meant N passes over all N lineages, and the result was
269-
# then reported against whichever domain happened to ask.
280+
# then reported against whichever domain happened to ask. On
281+
# `certonly` it picks the lineage (see _lineage_name); --csr
282+
# issues outside any lineage.
270283
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
271284
base_cmd.extend(["--server", acme_server()])
272285

@@ -396,10 +409,11 @@ def _clear_legacy_live(self, domain: str) -> None:
396409
to create the lineage over them left an empty renewal config, which
397410
would push the next lineage to <name>-0001.
398411
"""
399-
conf = self._renewal_conf_path(domain)
412+
base = domain[2:] if domain.startswith("*.") else domain
413+
conf = os.path.join(LETSENCRYPT_DIR, "renewal", f"{base}.conf")
400414
if os.path.isfile(conf) and os.path.getsize(conf) == 0:
401415
os.remove(conf)
402-
live = self._live_dir(domain)
416+
live = os.path.join(LETSENCRYPT_DIR, "live", base)
403417
privkey = os.path.join(live, "privkey.pem")
404418
if not os.path.isfile(privkey) or os.path.islink(privkey):
405419
return
@@ -507,8 +521,28 @@ def certificate_exists(self, domain: str) -> bool:
507521

508522
@staticmethod
509523
def _lineage_name(domain: str) -> str:
510-
"""certbot stores a wildcard lineage under the bare name."""
511-
return domain[2:] if domain.startswith("*.") else domain
524+
"""The lineage holding exactly this domain, else the name to create.
525+
526+
Left to itself certbot named a wildcard's lineage after the bare name,
527+
the same as the base domain's, so with both in DOMAINS one became
528+
<name>-0001. Existing lineages are therefore found by content. A new
529+
wildcard lineage is _wildcard.<name>: an underscore cannot appear in a
530+
certificate host name, so it never collides with a domain.
531+
"""
532+
base = domain[2:] if domain.startswith("*.") else domain
533+
new = f"_wildcard.{base}" if domain.startswith("*.") else domain
534+
renewal = os.path.join(LETSENCRYPT_DIR, "renewal")
535+
pattern = re.compile(rf"(_wildcard\.)?{re.escape(base)}(-\d{{4}})?")
536+
existing = sorted(os.path.basename(p)[:-len(".conf")]
537+
for p in glob.glob(os.path.join(renewal, "*.conf")))
538+
for name in [new] + [n for n in existing if pattern.fullmatch(n)]:
539+
if _cert_names(os.path.join(LETSENCRYPT_DIR, "live", name, "cert.pem")) == [domain]:
540+
return name
541+
name, n = new, 0
542+
while name in existing:
543+
n += 1
544+
name = f"{new}-{n:04d}"
545+
return name
512546

513547
@classmethod
514548
def _live_dir(cls, domain: str) -> str:

‎custom-domain/dstack-ingress/scripts/tests/test_certman.py‎

Lines changed: 95 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,6 @@ def test_a_failed_write_leaves_the_original_intact(self):
141141
os.chmod(self.dir, 0o700)
142142
self.assertEqual(self.read(), original)
143143

144-
def test_wildcard_uses_the_bare_lineage_name(self):
145-
self.assertEqual(
146-
certman.CertManager._lineage_name("*.example.com"), "example.com"
147-
)
148-
self.assertEqual(
149-
certman.CertManager._lineage_name("example.com"), "example.com"
150-
)
151-
152144
def test_wildcard_has_its_own_deterministic_dir(self):
153145
with mock.patch.dict(os.environ, {"DETERMINISTIC_TLS_KEY": "true"}):
154146
self.assertEqual(certman.CertManager.cert_dir("*.example.com"),
@@ -191,6 +183,10 @@ def setUp(self):
191183
self._saved = {v: os.environ.get(v) for v in self.VARS}
192184
for v in self.VARS:
193185
os.environ.pop(v, None)
186+
self.root = tempfile.mkdtemp()
187+
self.addCleanup(shutil.rmtree, self.root)
188+
self.addCleanup(setattr, certman, "LETSENCRYPT_DIR", certman.LETSENCRYPT_DIR)
189+
certman.LETSENCRYPT_DIR = self.root
194190

195191
def tearDown(self):
196192
for v, old in self._saved.items():
@@ -213,15 +209,38 @@ def test_renew_is_scoped_to_one_lineage(self):
213209
self.assertIn("--cert-name", cmd)
214210
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "a.example.com")
215211

216-
def test_renew_uses_the_bare_name_for_a_wildcard(self):
212+
def test_renew_uses_the_wildcard_lineage(self):
217213
cmd = _command_manager()._build_certbot_command("renew", "*.example.com", "")
218-
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "example.com")
219-
220-
def test_certonly_is_scoped_by_d_not_cert_name(self):
214+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.example.com")
215+
216+
def test_certonly_names_the_lineage(self):
217+
"""certbot's own pick for a wildcard is the base domain's name."""
218+
for delegation in ("", "deleg.example.net"):
219+
os.environ["DELEGATION_ZONE"] = delegation
220+
cmd = _command_manager()._build_certbot_command(
221+
"certonly", "*.example.com", "")
222+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.example.com")
223+
self.assertEqual(cmd[cmd.index("-d") + 1], "*.example.com")
224+
225+
def test_csr_issuance_has_no_lineage(self):
226+
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
221227
cmd = _command_manager()._build_certbot_command(
222-
"certonly", "a.example.com", "")
228+
"certonly", "*.example.com", "", ("--csr", "x.csr"))
223229
self.assertNotIn("--cert-name", cmd)
224-
self.assertIn("-d", cmd)
230+
231+
def test_replacing_keeps_the_lineage(self):
232+
mgr = _command_manager()
233+
mgr.install_plugin = lambda: True
234+
mgr.provider.validate_credentials = lambda: True
235+
mgr.setup_credentials = lambda: True
236+
cmds = []
237+
with mock.patch.object(certman.subprocess, "run",
238+
lambda cmd, **kw: cmds.append(cmd) or mock.Mock(returncode=0)):
239+
self.assertTrue(mgr.obtain_certificate("*.x.com", "", replace=True))
240+
cmd = cmds[0]
241+
self.assertIn("--force-renewal", cmd)
242+
self.assertIn("--break-my-certs", cmd)
243+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.x.com")
225244

226245
def test_delegation_renew_is_scoped_too(self):
227246
os.environ["DELEGATION_ZONE"] = "deleg.example.net"
@@ -299,6 +318,68 @@ def test_unknown_server_does_not_replace_every_pass(self):
299318
self.assertEqual(self.run_auto(None), ["renew"])
300319

301320

321+
def _cert_pem(name, key):
322+
from datetime import datetime, timedelta, timezone
323+
from cryptography import x509
324+
from cryptography.hazmat.primitives import hashes, serialization
325+
from cryptography.x509.oid import NameOID
326+
327+
now = datetime.now(timezone.utc)
328+
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
329+
return (x509.CertificateBuilder()
330+
.subject_name(subject).issuer_name(subject)
331+
.public_key(key.public_key()).serial_number(1)
332+
.not_valid_before(now).not_valid_after(now + timedelta(days=90))
333+
.add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False)
334+
.sign(key, hashes.SHA256())
335+
.public_bytes(serialization.Encoding.PEM))
336+
337+
338+
class LineageNameTest(EnvTestCase):
339+
"""Existing lineages are found by content; new ones get a name of their own."""
340+
341+
def setUp(self):
342+
super().setUp()
343+
from cryptography.hazmat.primitives.asymmetric import ec
344+
345+
self.key = ec.generate_private_key(ec.SECP256R1())
346+
self.mgr = object.__new__(certman.CertManager)
347+
348+
def lineage(self, lineage, name):
349+
os.makedirs(f"{self.root}/live/{lineage}")
350+
os.makedirs(f"{self.root}/renewal", exist_ok=True)
351+
with open(f"{self.root}/live/{lineage}/cert.pem", "wb") as fh:
352+
fh.write(_cert_pem(name, self.key))
353+
open(f"{self.root}/renewal/{lineage}.conf", "w").close()
354+
355+
def test_new_wildcard_lineage_is_apart_from_the_base(self):
356+
self.assertEqual(self.mgr._lineage_name("*.x.com"), "_wildcard.x.com")
357+
self.assertEqual(self.mgr._lineage_name("x.com"), "x.com")
358+
359+
def test_lineages_certbot_named_itself_are_found(self):
360+
self.lineage("x.com", "*.x.com")
361+
self.lineage("x.com-0001", "x.com")
362+
self.assertEqual(self.mgr._lineage_name("*.x.com"), "x.com")
363+
self.assertEqual(self.mgr._lineage_name("x.com"), "x.com-0001")
364+
365+
def test_a_name_taken_by_another_certificate_is_not_reused(self):
366+
self.lineage("x.com", "*.x.com")
367+
self.assertEqual(self.mgr._lineage_name("x.com"), "x.com-0001")
368+
369+
def test_legacy_wildcard_files_under_the_bare_name_move_to_the_wildcards(self):
370+
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
371+
live = f"{self.root}/live/x.com"
372+
os.makedirs(live)
373+
for item in ("cert", "fullchain"):
374+
with open(f"{live}/{item}.pem", "wb") as fh:
375+
fh.write(_cert_pem("*.x.com", self.key))
376+
with open(f"{live}/privkey.pem", "wb") as fh:
377+
fh.write(certman.deterministic_key.key_pem(self.key))
378+
self.mgr._clear_legacy_live("*.x.com")
379+
self.assertFalse(os.path.exists(live))
380+
self.assertTrue(os.path.exists(f"{self.root}/deterministic/_wildcard.x.com/fullchain.pem"))
381+
382+
302383
class CertbotTimeoutTest(EnvTestCase):
303384
"""A fixed 300s cap could not fit every provider's own propagation wait."""
304385

0 commit comments

Comments
 (0)