diff --git a/docs/deployment.md b/docs/deployment.md index cca03d5..719df52 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1051,6 +1051,21 @@ credential and archive operations. The separate legacy SSH transports for those operations are unavailable on a scoped receiver. Local mail delivery and IMAP keep using their existing configuration. +#### Refresh an existing managed DKIM record + +Upgrade the panels linked to a mail node before upgrading the mail node. +The updated panel accepts public keys from older mail nodes and publishes +the managed RSA key in SubjectPublicKeyInfo format. The existing private +key and selector stay in use. + +Open **Mail DNS check** for a managed mail domain and select +**Refresh mail DNS setup**. If Coulobre publishes the zone and manages its +mail records, it replaces the previous encoding when the public key +matches. A different key at the same selector requires operator review. +For third-party DNS, copy the updated DKIM TXT value to the DNS provider. +Check the authoritative answer, allow cached records to expire, and +verify that a newly delivered message passes DKIM. + ### Use SHA-2 for new managed database logins On a MariaDB build with `auth_mysql_sha2`, you can provision new managed diff --git a/src/coulobre/hosting/mail_dns_setup.py b/src/coulobre/hosting/mail_dns_setup.py index 8da6102..d0ef8f7 100644 --- a/src/coulobre/hosting/mail_dns_setup.py +++ b/src/coulobre/hosting/mail_dns_setup.py @@ -12,7 +12,12 @@ from coulobre.dns_node import ( TxtRecord, dns_name, ) -from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version +from coulobre.mail_dns import ( + MANAGED_DKIM_SELECTOR, + matches_version, + normalize_rsa_dkim_record, + same_rsa_dkim_key, +) from .dns_publication import queue_zone_snapshot from .models import HostingDnsZone, HostingMailDomain, MailboxProvisioning @@ -53,7 +58,8 @@ def mail_dns_proposal(domain, public_key): if public_key: records.append( TxtRecord( - f"{MANAGED_DKIM_SELECTOR}._domainkey.{domain}", public_key + f"{MANAGED_DKIM_SELECTOR}._domainkey.{domain}", + normalize_rsa_dkim_record(public_key), ) ) return addresses, mx, tuple(records) @@ -104,7 +110,7 @@ def sync_mail_dns(mail_domain, *, public_key=None): if current is None or account.retired_at is not None: return if public_key is not None: - current.dkim_record = public_key + current.dkim_record = normalize_rsa_dkim_record(public_key) current.dns_sync_requested = True current.save(update_fields=["dkim_record", "dns_sync_requested"]) if not current.dns_sync_requested or account.services_suspended: @@ -173,15 +179,23 @@ def publish_mail_records(zone, domain, public_key): existing = spec.txt_records new_txt = [] + replacements = {} problem = "" for record in txt: version = record.text.split(" ")[0].rstrip(";") at_owner = tuple(item for item in existing if item.name == record.name) if version == "v=DKIM1": if at_owner and at_owner != (record,): - raise ValueError( - "The Coulobre DKIM selector already has a record." - ) + if len(at_owner) != 1 or not same_rsa_dkim_key( + at_owner[0].text, record.text + ): + raise ValueError( + "The Coulobre DKIM selector already has a record." + ) + previous = at_owner[0] + converted = normalize_rsa_dkim_record(previous.text) + if converted != previous.text: + replacements[previous] = replace(previous, text=converted) else: at_owner = tuple( item @@ -207,7 +221,9 @@ def publish_mail_records(zone, domain, public_key): spec.nameservers, (*spec.addresses, *spec.mx_records, *existing, *spec.extra_records), ) - changed = bool(additions or not current_mx or new_txt or alias) + changed = bool( + additions or not current_mx or new_txt or replacements or alias + ) if publication and publication.finished_at is None: if changed: raise MailDnsPublicationPendingError @@ -219,7 +235,10 @@ def publish_mail_records(zone, domain, public_key): serial=(spec.serial + 1) % (MAX_SOA_SERIAL + 1), addresses=spec.addresses + additions, mx_records=spec.mx_records + (mx if not current_mx else ()), - txt_records=spec.txt_records + tuple(new_txt), + txt_records=tuple( + replacements.get(record, record) for record in existing + ) + + tuple(new_txt), extra_records=spec.extra_records + ((alias,) if alias else ()), ) manifest = spec.manifest() diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index c7f26c6..167bd72 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -13,7 +13,7 @@ from coulobre.account_restore_request import ( RESTORE_TIMEOUT_SECONDS, ) from coulobre.linked_updates import ROLES, UNIT_DIR, read_probe -from coulobre.mail_dns import dkim_key +from coulobre.mail_dns import dkim_key, normalize_rsa_dkim_record from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest from coulobre.node_probe import PROBE_BYTES, parse_status_probe from coulobre.php_pool_settings import PhpPoolSettings @@ -180,7 +180,7 @@ def provision_signing_mailbox(mailbox): or dkim_key(public)[0] != "ok" ): raise ValueError("The mail node returned an invalid DKIM public key.") - return public + return normalize_rsa_dkim_record(public) def update_local_mailbox_quota(mailbox): diff --git a/src/coulobre/hosting/test_mail_dns.py b/src/coulobre/hosting/test_mail_dns.py index 04615ad..f48a572 100644 --- a/src/coulobre/hosting/test_mail_dns.py +++ b/src/coulobre/hosting/test_mail_dns.py @@ -214,6 +214,14 @@ class MailDnsPanelTests(TestCase): public_key.public_bytes(Encoding.DER, PublicFormat.PKCS1) ).decode() ) + spki = ( + "v=DKIM1; k=rsa; p=" + + base64.b64encode( + public_key.public_bytes( + Encoding.DER, PublicFormat.SubjectPublicKeyInfo + ) + ).decode() + ) with patch( "coulobre.hosting.tasks.provision_signing_mailbox", return_value=dkim, @@ -223,8 +231,9 @@ class MailDnsPanelTests(TestCase): self.assertEqual(job.state, "configured") self.domain.refresh_from_db() zone.refresh_from_db() - self.assertEqual(self.domain.dkim_record, dkim) - self.assertEqual(dkim_key(dkim, expected=dkim)[0], "ok") + self.assertEqual(self.domain.dkim_record, spki) + self.assertEqual(dkim_key(dkim, expected=spki)[0], "ok") + self.assertEqual(dkim_key(spki, expected=dkim)[0], "ok") self.assertEqual(dkim_key(DKIM, expected=dkim)[0], "attention") self.assertEqual(zone.serial, 6) self.assertEqual( @@ -246,7 +255,7 @@ class MailDnsPanelTests(TestCase): { DOMAIN: f"v=spf1 ip4:{IP} ~all", "_dmarc.example.net": "v=DMARC1; p=none", - "coulobre._domainkey.example.net": dkim, + "coulobre._domainkey.example.net": spki, }, ) publication = DnsPublication.objects.get(zone=zone) @@ -255,6 +264,54 @@ class MailDnsPanelTests(TestCase): zone.refresh_from_db() self.assertEqual(zone.serial, 6) + def test_existing_dkim_is_reencoded_only_for_the_same_rsa_key(self): + prefix = "v=DKIM1; k=rsa; p=" + selector = f"coulobre._domainkey.{DOMAIN}" + signer = generate_private_key( + public_exponent=65537, key_size=2048 + ).public_key() + previous = ( + prefix + + base64.b64encode( + signer.public_bytes(Encoding.DER, PublicFormat.PKCS1) + ).decode() + ) + other = {"name": DOMAIN, "text": "site-verification=unchanged"} + zone = self.zone( + manage_mail_dns=True, + txt_records=[ + {"name": selector, "text": previous + "; s=email"}, + other, + ], + ) + sync_mail_dns(self.domain, public_key=previous) + zone.refresh_from_db() + self.domain.refresh_from_db() + self.assertNotEqual(self.domain.dkim_record, previous) + self.assertIn( + {"name": selector, "text": self.domain.dkim_record + "; s=email"}, + zone.txt_records, + ) + self.assertIn(other, zone.txt_records) + conflicting_signer = generate_private_key( + public_exponent=65537, key_size=2048 + ).public_key() + different = ( + prefix + + base64.b64encode( + conflicting_signer.public_bytes( + Encoding.DER, PublicFormat.SubjectPublicKeyInfo + ) + ).decode() + ) + records, serial = zone.txt_records, zone.serial + sync_mail_dns(self.domain, public_key=different) + zone.refresh_from_db() + self.domain.refresh_from_db() + self.assertEqual(zone.txt_records, records) + self.assertEqual(zone.serial, serial) + self.assertIn("already has a record", self.domain.dns_setup_problem) + def test_dns_sync_keeps_an_existing_mail_client_host_record(self): address = {"name": f"mail.{DOMAIN}", "address": "192.0.2.43"} zone = self.zone(manage_mail_dns=True, addresses=[address]) diff --git a/src/coulobre/mail_dns.py b/src/coulobre/mail_dns.py index f7ff9b4..452a748 100644 --- a/src/coulobre/mail_dns.py +++ b/src/coulobre/mail_dns.py @@ -430,9 +430,7 @@ def dkim_key(record, *, expected=""): "attention", "RSA key published. Prefer at least 2048 bits.", ) - if expected and key.public_bytes( - Encoding.DER, PublicFormat.PKCS1 - ) != decode_key(read_tags(expected).get("p", "")): + if expected and not same_rsa_dkim_key(record, expected): return ( "attention", "The public key differs from the mail node's key.", @@ -448,6 +446,46 @@ def decode_key(value): return base64.b64decode(data, validate=True) +def rsa_dkim_key(record): + tags = read_tags(record) + if tags.get("k", "rsa") != "rsa" or ( + "v" in tags and (next(iter(tags)) != "v" or tags["v"] != "DKIM1") + ): + return None + try: + key = load_der_public_key(decode_key(tags.get("p", ""))) + except (ValueError, UnsupportedAlgorithm): + return None + return key if isinstance(key, RSAPublicKey) else None + + +def same_rsa_dkim_key(first, second): + first_key = rsa_dkim_key(first) + second_key = rsa_dkim_key(second) + return ( + first_key is not None + and second_key is not None + and first_key.public_numbers() == second_key.public_numbers() + ) + + +def normalize_rsa_dkim_record(record): + """Encode the public key for DNS and preserve other tags.""" + key = rsa_dkim_key(record) + if key is None: + return record + data = key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + encoded = base64.b64encode(data).decode("ascii") + if decode_key(read_tags(record)["p"]) == data: + return record + return re.sub( + r"(^|;)(\s*p\s*=)[^;]*", + lambda match: match[1] + match[2] + encoded, + record, + count=1, + ) + + def sts_policy(record): policy_id = read_tags(record).get("id", "") if not re.fullmatch(r"[A-Za-z0-9]{1,32}", policy_id): diff --git a/src/coulobre/mail_node_dkim.py b/src/coulobre/mail_node_dkim.py index 1f61bb4..205ca77 100644 --- a/src/coulobre/mail_node_dkim.py +++ b/src/coulobre/mail_node_dkim.py @@ -65,6 +65,6 @@ def provision_dkim_key(domain): "The DKIM key must be RSA with at least 2048 bits." ) public = key.public_key().public_bytes( - Encoding.DER, PublicFormat.PKCS1 + Encoding.DER, PublicFormat.SubjectPublicKeyInfo ) return "v=DKIM1; k=rsa; p=" + base64.b64encode(public).decode("ascii")