Provision DKIM and publish managed mail DNS records

This commit is contained in:
parkel committed 2026-11-21 22:04:15 +01:00
1 parent bb617a99ee
commit 004a8b4d81
20 files changed
+992 -9

No files matched your search

@@ -0,0 +1,9 @@
# Include in dovecot.conf or a loaded conf.d file.
auth_mechanisms = plain login
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
+5
View File
@@ -23,6 +23,11 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1
# COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION=1
# COULOBRE_MAIL_IMAP_HOST=mail.example.org
# COULOBRE_MAIL_MX_HOST=mx.example.org
# COULOBRE_MAIL_DNS_RESOLVERS=
# COULOBRE_MAIL_SENDING_IPS=
# COULOBRE_MAIL_MX_IPS=
# COULOBRE_MANAGE_MAIL_DNS=1
# COULOBRE_PHPMYADMIN_URL=https://tools.example.org/phpmyadmin
# COULOBRE_PHPMYADMIN_BRIDGE_KEY=
# COULOBRE_ROUNDCUBE_URL=https://webmail.example.org
+15
View File
@@ -0,0 +1,15 @@
# /etc/rspamd/override.d/dkim_signing.conf
enabled = true;
selector = "coulobre";
path = "/etc/rspamd/coulobre-dkim/$domain.$selector.key";
use_domain = "header";
use_esld = false;
try_fallback = true;
sign_authenticated = true;
sign_local = false;
sign_inbound = false;
allow_envfrom_empty = false;
allow_hdrfrom_multiple = false;
allow_hdrfrom_mismatch = false;
allow_hdrfrom_mismatch_local = false;
allow_username_mismatch = false;
@@ -0,0 +1,10 @@
# Merge these options into the existing authenticated submission service.
# Leave the public SMTP service and its inbound milters in place.
submission inet n - y - - smtpd
-o smtpd_tls_security_level=encrypt
-o smtpd_tls_auth_only=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o { smtpd_milters = { unix:rspamd/coulobre.sock, default_action=tempfail } }
+8
View File
@@ -0,0 +1,8 @@
# /etc/rspamd/local.d/settings.conf
coulobre_signing {
authenticated = true;
apply {
symbols_enabled = ["DKIM_SIGNED"];
flags = ["skip_process"];
}
}
@@ -0,0 +1,2 @@
# /etc/rspamd/override.d/worker-normal.inc and worker-controller.inc
enabled = false;
+7
View File
@@ -0,0 +1,7 @@
# /etc/rspamd/override.d/worker-proxy.inc
bind_socket = "/var/spool/postfix/rspamd/coulobre.sock mode=0600 owner=postfix";
milter = true;
upstream "local" {
default = true;
self_scan = true;
}
+2
View File
@@ -12,6 +12,8 @@ license = "Apache-2.0"
dependencies = [
"Django>=5.2.8,<5.3",
"celery>=5.6,<6",
"cryptography>=45",
"dnspython>=2.7,<3",
"idna>=3,<4",
]
+8
View File
@@ -61,6 +61,14 @@ class DnsZoneForm(forms.Form):
"special whitespace or enter an empty value."
),
)
manage_mail_dns = forms.BooleanField(
label="Publish DNS for Coulobre mail automatically",
required=False,
help_text=(
"Use this when this zone is served by a local or remote "
"Coulobre DNS node."
),
)
def __init__(self, *args, domain, **kwargs):
super().__init__(*args, **kwargs)
+11 -1
View File
@@ -1,4 +1,6 @@
from django.conf import settings
from django.db import transaction
from django.db.models import Q
from coulobre.dns_node import DNS_REQUEST_LIMIT
@@ -26,6 +28,15 @@ def publish_for_account(account_id, zone_id, expected_serial):
"This zone changed before publication. "
"Reload the account and try again."
)
queue_zone_snapshot(zone)
if settings.MANAGE_MAIL_DNS and zone.manage_mail_dns:
account.mail_domains.exclude(dkim_record="").filter(
Q(domain=zone.domain) | Q(domain__endswith=f".{zone.domain}")
).update(dns_sync_requested=True)
return zone
def queue_zone_snapshot(zone):
manifest = zone.spec.manifest()
if len(encode_manifest(manifest)) > DNS_REQUEST_LIMIT:
raise ValueError(
@@ -40,4 +51,3 @@ def publish_for_account(account_id, zone_id, expected_serial):
jobs.filter(pk=job.pk).exclude(serial=zone.serial, problem=""),
**snapshot,
)
return zone
+206
View File
@@ -0,0 +1,206 @@
from dataclasses import replace
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from coulobre.dns_node import (
MAX_SOA_SERIAL,
AddressRecord,
MxRecord,
TxtRecord,
)
from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version
from .dns_publication import queue_zone_snapshot
from .models import HostingDnsZone, HostingMailDomain, MailboxProvisioning
from .resource_requests import lock_hosting_account, require_active_services
class MailDnsPublicationPendingError(Exception):
pass
def domain_ancestors(domain):
labels = domain.split(".")
return [".".join(labels[index:]) for index in range(len(labels) - 1)]
def closest_zone(queryset, domain):
zones = queryset.filter(domain__in=domain_ancestors(domain))
return max(zones, key=lambda zone: len(zone.domain), default=None)
def mail_dns_proposal(domain, public_key):
mx_host = settings.MAIL_MX_HOST
addresses = tuple(
AddressRecord(mx_host, address)
for address in settings.MAIL_MX_IPS
if mx_host
)
mx = (MxRecord(domain, 10, mx_host),) if mx_host else ()
records = []
if settings.MANAGE_MAIL_DNS:
senders = " ".join(
f"{'ip6' if ':' in address else 'ip4'}:{address}"
for address in settings.MAIL_SENDING_IPS
)
records.append(TxtRecord(domain, f"v=spf1 {senders} ~all"))
if len(f"_dmarc.{domain}") <= 253:
records.append(TxtRecord(f"_dmarc.{domain}", "v=DMARC1; p=none"))
if public_key:
records.append(
TxtRecord(
f"{MANAGED_DKIM_SELECTOR}._domainkey.{domain}", public_key
)
)
return addresses, mx, tuple(records)
@transaction.atomic
def sync_mail_dns(mail_domain, *, public_key=None):
account = lock_hosting_account(mail_domain.account_id, customer_id=None)
current = HostingMailDomain.objects.filter(
pk=mail_domain.pk, account=account
).first()
if current is None or account.retired_at is not None:
return
if public_key is not None:
current.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:
return
zone = None
if settings.LOCAL_DNS_PUBLISHING:
zone = closest_zone(HostingDnsZone.objects.all(), current.domain)
problem = ""
if (
zone is not None
and zone.account_id == account.pk
and zone.manage_mail_dns
):
try:
with transaction.atomic():
zone = HostingDnsZone.objects.select_for_update().get(
pk=zone.pk, account=account
)
problem = publish_mail_records(
zone, current.domain, current.dkim_record
)
except MailDnsPublicationPendingError:
return
except ValueError as error:
problem = str(error)
current.dns_sync_requested = False
current.dns_setup_problem = problem
current.save(update_fields=["dns_sync_requested", "dns_setup_problem"])
def publish_mail_records(zone, domain, public_key):
addresses, mx, txt = mail_dns_proposal(domain, public_key)
spec = zone.spec
current_mx = [
record for record in spec.mx_records if record.name == domain
]
if current_mx and all(
record.exchange != mx[0].exchange for record in current_mx
):
raise ValueError(
"Review the current MX targets before publishing mail DNS."
)
target = mx[0].exchange
current_addresses = {
record.address for record in spec.addresses if record.name == target
}
managed_target = target == zone.domain or target.endswith(
f".{zone.domain}"
)
additions = ()
if managed_target:
desired = {record.address for record in addresses}
if current_addresses and desired and current_addresses - desired:
raise ValueError("Review the existing addresses of the MX target.")
additions = tuple(
record
for record in addresses
if record.address not in current_addresses
)
if not (current_addresses or additions):
raise ValueError(
"Set addresses for the MX target inside this zone."
)
existing = spec.txt_records
new_txt = []
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."
)
else:
at_owner = tuple(
item
for item in at_owner
if matches_version(item.text, version)
)
if len(at_owner) > 1:
raise ValueError(
"Resolve duplicate SPF or DMARC records before publishing."
)
if not at_owner:
new_txt.append(record)
elif version == "v=spf1" and record != at_owner[0]:
problem = "Existing SPF policy kept. Verify the sending IPs."
publication = getattr(zone, "publication", None)
if publication and publication.serial != zone.serial:
raise ValueError(
"Publish the saved zone revision before updating mail DNS."
)
changed = bool(additions or not current_mx or new_txt)
if publication and publication.finished_at is None:
if changed:
raise MailDnsPublicationPendingError
return problem
if changed:
spec = replace(
spec,
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),
)
manifest = spec.manifest()
zone.serial = spec.serial
zone.addresses = manifest["addresses"]
zone.mx_records = manifest["mx_records"]
zone.txt_records = manifest["txt_records"]
zone.save(
update_fields=["serial", "addresses", "mx_records", "txt_records"]
)
if changed or publication is None or publication.problem:
queue_zone_snapshot(zone)
return problem
@transaction.atomic
def queue_mail_dns_setup(mail_domain):
account = lock_hosting_account(mail_domain.account_id, customer_id=None)
require_active_services(account)
jobs = MailboxProvisioning.objects.filter(
mailbox__mail_domain=mail_domain, finished_at__isnull=False, problem=""
)
job = jobs.select_for_update().order_by("pk").first()
if job is None:
raise ValidationError("Provision a mailbox for this domain first.")
MailboxProvisioning.objects.requeue(
jobs.filter(pk=job.pk), quota_update=False
)
@@ -0,0 +1,32 @@
# Generated by Django 5.2.19 on 2026-11-21 20:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0038_roundcube_signon"),
]
operations = [
migrations.AddField(
model_name="hostingdnszone",
name="manage_mail_dns",
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name="hostingmaildomain",
name="dkim_record",
field=models.CharField(blank=True, max_length=1024),
),
migrations.AddField(
model_name="hostingmaildomain",
name="dns_setup_problem",
field=models.TextField(blank=True),
),
migrations.AddField(
model_name="hostingmaildomain",
name="dns_sync_requested",
field=models.BooleanField(default=False),
),
]
+4
View File
@@ -483,6 +483,7 @@ class HostingDnsZone(models.Model):
addresses = models.JSONField(default=list)
mx_records = models.JSONField(default=list)
txt_records = models.JSONField(default=list)
manage_mail_dns = models.BooleanField(default=False)
class Meta:
ordering = ("domain",)
@@ -520,6 +521,9 @@ class HostingMailDomain(models.Model):
HostingAccount, on_delete=models.PROTECT, related_name="mail_domains"
)
domain = DomainNameField(max_length=253, unique=True)
dkim_record = models.CharField(max_length=1024, blank=True)
dns_setup_problem = models.TextField(blank=True)
dns_sync_requested = models.BooleanField(default=False)
def __str__(self):
return str(self.domain)
+20 -1
View File
@@ -11,7 +11,8 @@ from coulobre.account_restore_request import (
RESTORE_SOCKET,
RESTORE_TIMEOUT_SECONDS,
)
from coulobre.mail_node import MailboxQuotaUpdate
from coulobre.mail_dns import dkim_key
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.web_node import (
MAX_STORAGE_BYTES,
@@ -130,6 +131,24 @@ def provision_local_mailbox(mailbox):
)
def provision_signing_mailbox(mailbox):
reply = apply_on_local_node(
MailboxSigningRequest(mailbox),
"/run/coulobre-mail-apply.sock",
"mail node",
"mailbox and signing key",
)
public = reply.get("dkim")
if (
not isinstance(public, str)
or len(public) > 1024
or not public.startswith("v=DKIM1; k=rsa; p=")
or dkim_key(public)[0] != "ok"
):
raise ValueError("The mail node returned an invalid DKIM public key.")
return public
def update_local_mailbox_quota(mailbox):
apply_on_local_node(
MailboxQuotaUpdate(mailbox),
+14
View File
@@ -31,6 +31,7 @@ from .backup_restores import (
enabled_component_restores,
)
from .backup_retention import plan_backup_expirations
from .mail_dns_setup import sync_mail_dns
from .models import (
AccountBackupExpiration,
AccountBackupJob,
@@ -40,6 +41,7 @@ from .models import (
ComponentRestoreJob,
DatabaseProvisioning,
DnsPublication,
HostingMailDomain,
MailboxProvisioning,
SitePhpSettings,
SiteSFTP,
@@ -60,6 +62,7 @@ from .node_client import (
measure_local_site_storage,
provision_local_database,
provision_local_mailbox,
provision_signing_mailbox,
publish_local_zone,
restore_local_component,
restore_local_website,
@@ -192,6 +195,14 @@ def dispatch_database_provisioning():
@shared_task
def dispatch_dns_publications():
if settings.LOCAL_DNS_PUBLISHING:
if settings.MANAGE_MAIL_DNS:
domains = HostingMailDomain.objects.filter(
dns_sync_requested=True,
account__services_suspended=False,
account__retired_at__isnull=True,
).order_by("pk")[:100]
for mail_domain in domains:
sync_mail_dns(mail_domain)
dispatch_provisioning_jobs(
DnsPublication, publish_dns_zone, DNS_PUBLISHING_QUEUE
)
@@ -609,6 +620,9 @@ def provision_mailbox(provisioning_id):
def apply_mailbox_provisioning(provisioning):
if provisioning.quota_update:
update_local_mailbox_quota(provisioning.mailbox.spec)
elif settings.MANAGE_MAIL_DNS:
public_key = provision_signing_mailbox(provisioning.mailbox.spec)
sync_mail_dns(provisioning.mailbox.mail_domain, public_key=public_key)
else:
provision_local_mailbox(provisioning.mailbox.spec)
+4
View File
@@ -517,6 +517,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
zone.domain == self.object.primary_domain for zone in zones
)
if tenant or user.has_perm(VIEW_MAILBOXES):
context["mail_domains"] = self.object.mail_domains.order_by(
"domain"
)
mailboxes = HostingMailbox.objects.filter(
mail_domain__account=self.object
).select_related("mail_domain")
@@ -1520,6 +1523,7 @@ class DnsZoneEdit(DnsZoneEditor):
def get_initial(self):
return {
"serial": self.zone.serial,
"manage_mail_dns": self.zone.manage_mail_dns,
"nameservers": "\n".join(self.zone.nameservers),
"responsible_name": self.zone.responsible_name,
"addresses": "\n".join(
+477
View File
@@ -0,0 +1,477 @@
import base64
import binascii
import ipaddress
import re
from dataclasses import dataclass
from functools import partial
from time import monotonic
from urllib.parse import urlsplit
import dns.exception
import dns.name
import dns.resolver
import dns.reversename
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from cryptography.hazmat.primitives.serialization import (
Encoding,
PublicFormat,
load_der_public_key,
)
MAX_SELECTORS = 4
MAX_MX_HOSTS = 4
MAX_RECORDS = 8
MANAGED_DKIM_SELECTOR = "coulobre"
SELECTOR = re.compile(
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
r"(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*",
re.ASCII | re.IGNORECASE,
)
SPF_MECHANISM = re.compile(
r"[+?~-]?(?:all|(?:a|mx)(?:[:/].+)?|ptr(?::.+)?|"
r"(?:include|ip4|ip6|exists):.+)",
re.ASCII | re.IGNORECASE,
)
SPF_MODIFIER = re.compile(r"[a-zA-Z][a-zA-Z0-9_.-]*=\S+")
@dataclass(frozen=True)
class Check:
label: str
name: str
state: str
detail: str
records: tuple[str, ...] = ()
@dataclass(frozen=True)
class MailDnsReport:
zone: str
nameservers: tuple[str, ...]
checks: tuple[Check, ...]
class LookupUnavailableError(Exception):
pass
class MailDnsResolver:
def __init__(self, nameservers=()):
self.deadline = monotonic() + 7
self.resolver = None
try:
self.resolver = dns.resolver.Resolver(configure=not nameservers)
except dns.exception.DNSException:
return
if nameservers:
self.resolver.nameservers = list(nameservers)
self.resolver.timeout = 1
def lifetime(self):
remaining = self.deadline - monotonic()
if self.resolver is None or remaining <= 0:
raise LookupUnavailableError
return min(remaining, 2)
def lookup(self, name, record_type):
try:
lifetime = self.lifetime()
answer = self.resolver.resolve(
name + ".", record_type, search=False, lifetime=lifetime
)
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
return None
except dns.exception.DNSException as error:
raise LookupUnavailableError from error
return answer
def authoritative_zone(self, name):
try:
zone = dns.resolver.zone_for_name(
name + ".", resolver=self.resolver, lifetime=self.lifetime()
)
if zone == dns.name.root:
return "", ()
owner = zone.to_text(omit_final_dot=True).lower()
records = self.lookup(owner, "NS")
except (dns.exception.DNSException, LookupUnavailableError):
return "", ()
return owner, tuple(
sorted(record.target.to_text().lower() for record in records or ())
)[:MAX_RECORDS]
def run_mail_dns(
domain,
selectors,
*,
nameservers=(),
expected_mx="",
signing_record="",
sending_ips=(),
):
resolver = MailDnsResolver(nameservers)
checks = [
check_txt(resolver, "SPF", domain, "v=spf1", spf_policy),
check_txt(
resolver,
"DMARC",
f"_dmarc.{domain}",
"v=DMARC1",
dmarc_policy,
),
]
for selector in selectors:
expected = signing_record if selector == MANAGED_DKIM_SELECTOR else ""
checks.append(
check_txt(
resolver,
f"DKIM ({selector})",
f"{selector}._domainkey.{domain}",
"v=DKIM1",
partial(dkim_key, expected=expected),
)
)
if not selectors:
checks.append(
Check("DKIM", domain, "not_checked", "Enter the signing selector.")
)
checks.insert(0, check_mx(resolver, domain, expected_mx))
checks.extend(check_ptr(resolver, address) for address in sending_ips)
zone, delegated_servers = resolver.authoritative_zone(domain)
checks.extend(
(
check_txt(
resolver,
"MTA-STS",
f"_mta-sts.{domain}",
"v=STSv1",
sts_policy,
),
check_txt(
resolver,
"TLS-RPT",
f"_smtp._tls.{domain}",
"v=TLSRPTv1",
tls_reporting,
),
)
)
return MailDnsReport(zone, delegated_servers, tuple(checks))
def check_mx(resolver, domain, expected):
try:
answer = resolver.lookup(domain, "MX")
except LookupUnavailableError:
return unavailable("MX", domain)
if not answer:
return Check("MX", domain, "missing", "Publish an explicit MX record.")
routes = sorted(
(entry.preference, entry.exchange.to_text().lower())
for entry in answer
)
records = tuple(f"{priority} {host}" for priority, host in routes)
if routes == [(0, ".")]:
return Check(
"MX", domain, "attention", "This null MX disables mail.", records
)
if any(host == "." for _, host in routes):
return Check(
"MX",
domain,
"attention",
"Remove the conflicting null MX.",
records,
)
hosts = tuple(dict.fromkeys(host.rstrip(".") for _, host in routes))
results = [check_mx_host(resolver, host) for host in hosts[:MAX_MX_HOSTS]]
if len(hosts) > MAX_MX_HOSTS:
results.append(
("attention", "Only the first four targets were checked.")
)
if expected and expected not in hosts:
results.append(
("attention", f"Expected {expected} among the targets.")
)
states = {state for state, _ in results}
state = next(
item for item in ("attention", "unavailable", "ok") if item in states
)
return Check(
"MX",
domain,
state,
" ".join(detail for _, detail in results),
records[:MAX_RECORDS],
)
def check_mx_host(resolver, host):
addresses = []
unavailable_types = []
for kind in ("A", "AAAA"):
try:
answer = resolver.lookup(host, kind)
except LookupUnavailableError:
unavailable_types.append(kind)
continue
if answer:
if (
answer.canonical_name.to_text(omit_final_dot=True).lower()
!= host
):
return "attention", f"{host} is an alias. Use a direct target."
addresses.extend(
ipaddress.ip_address(row.address) for row in answer
)
if any(
not address.is_global or address.is_multicast for address in addresses
):
return "attention", f"{host} has a non-public address."
if unavailable_types:
return "unavailable", f"Could not check all addresses for {host}."
if not addresses:
return "attention", f"{host} has no A or AAAA record."
return "ok", f"{host} resolves to public addresses."
def check_ptr(resolver, address):
label = f"PTR ({address})"
owner = dns.reversename.from_address(address).to_text(omit_final_dot=True)
try:
records = resolver.lookup(owner, "PTR")
except LookupUnavailableError:
return unavailable(label, owner)
if not records:
return Check(
label, owner, "missing", "Ask the IP provider to set PTR."
)
targets = tuple(record.target.to_text().lower() for record in records)
if len(targets) != 1:
return Check(
label,
owner,
"attention",
"Use one canonical mail hostname.",
targets[:MAX_RECORDS],
)
host = targets[0].rstrip(".")
kind = "A" if ipaddress.ip_address(address).version == 4 else "AAAA"
try:
forward = resolver.lookup(host, kind)
except LookupUnavailableError:
return unavailable(label, owner)
if not forward or all(
ipaddress.ip_address(row.address) != ipaddress.ip_address(address)
for row in forward
):
return Check(
label,
owner,
"attention",
"The PTR target must resolve back to this IP.",
targets,
)
return Check(label, owner, "ok", "Forward and reverse DNS agree.", targets)
def check_txt(resolver, label, name, version, validate):
try:
answer = resolver.lookup(name, "TXT")
except LookupUnavailableError:
return unavailable(label, name)
records = tuple(
b"".join(record.strings).decode("ascii", errors="replace")
for record in answer or ()
)
matches = tuple(
record for record in records if matches_version(record, version)
)
if version == "v=DKIM1":
# A DKIM key can omit its version tag.
matches = records
if not matches:
detail = "The record is missing."
if version == "v=DMARC1":
detail = "No direct record. A parent domain's policy may apply."
elif version == "v=STSv1" or version == "v=TLSRPTv1":
return Check(label, name, "optional", "Optional record absent.")
return Check(label, name, "missing", detail)
if len(matches) > 1:
state, detail = (
"attention",
"Publish one matching record at this name.",
)
elif len(matches[0]) > 4096:
state, detail = (
"attention",
"The record exceeds the checker size limit.",
)
else:
state, detail = validate(matches[0])
if answer.canonical_name.to_text().lower() != f"{name}.".lower():
detail += f" Resolves through {answer.canonical_name.to_text()}."
return Check(
label,
name,
state,
detail,
tuple(record[:2048] for record in matches[:MAX_RECORDS]),
)
def unavailable(label, name):
return Check(label, name, "unavailable", "DNS lookup unavailable.")
def matches_version(record, version):
if version == "v=spf1":
return record.lower() == version or record.lower().startswith(
version + " "
)
first = record.split(";", 1)[0]
key, separator, value = first.partition("=")
return separator and key.strip() == "v" and value.strip() == version[2:]
def spf_policy(record):
terms = record.lower().split()[1:]
if any(
not (SPF_MECHANISM.fullmatch(term) or SPF_MODIFIER.fullmatch(term))
for term in terms
):
return "attention", "A mechanism or modifier is not recognized."
for term in terms:
mechanism = term.lstrip("+?~-")
if mechanism.startswith(("ip4:", "ip6:")):
name, address = mechanism.split(":", 1)
try:
if ipaddress.ip_network(address, strict=False).version != int(
name[-1]
):
raise ValueError
except ValueError:
return (
"attention",
"An IP mechanism has an invalid address or CIDR.",
)
if "all" in terms or "+all" in terms:
return "attention", "The policy contains an all-senders authorization."
if not terms:
return "attention", "The policy does not list any senders."
return (
"ok",
"One SPF policy published. Includes and senders were not evaluated.",
)
def read_tags(record):
tags = {}
# One trailing semicolon is allowed.
for item in record.rstrip().removesuffix(";").split(";"):
key, separator, value = item.partition("=")
key = key.strip()
if not separator or not key or key in tags:
return {}
tags[key] = value.strip()
return tags
def dmarc_policy(record):
tags = read_tags(record)
policy = tags.get("p")
policies = {"none", "quarantine", "reject"}
if policy not in policies or any(
tags.get(name, policy) not in policies for name in ("sp", "np")
):
return (
"attention",
"Check the policy tags. Use none, quarantine or reject.",
)
if any(
tags.get(name, "r") not in {"r", "s"} for name in ("adkim", "aspf")
):
return "attention", "The alignment tags must be r or s."
if policy == "none":
return (
"ok",
"Monitoring policy (p=none). Review reports before enforcement.",
)
return "ok", f"Published enforcement policy (p={policy})."
def dkim_key(record, *, expected=""):
tags = read_tags(record)
if "p" not in tags or (
"v" in tags and (next(iter(tags)) != "v" or tags["v"] != "DKIM1")
):
return "attention", "Check the DKIM key tags."
if not tags["p"]:
return "attention", "The published key is revoked (empty p=)."
try:
public = decode_key(tags["p"])
algorithm = tags.get("k", "rsa")
if algorithm == "ed25519" and len(public) == 32:
if expected:
return "attention", "The key type differs from the mail node."
return "ok", "Ed25519 public key published."
if algorithm == "rsa":
key = load_der_public_key(public)
if isinstance(key, RSAPublicKey):
if key.key_size < 1024:
return (
"attention",
"The RSA key is shorter than 1024 bits.",
)
if key.key_size < 2048:
return (
"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", "")):
return (
"attention",
"The public key differs from the mail node's key.",
)
return "ok", f"RSA public key published ({key.key_size} bits)."
except (binascii.Error, ValueError, UnsupportedAlgorithm):
pass
return "attention", "The public key or key type is invalid or unsupported."
def decode_key(value):
data = re.sub(r"[ \t\r\n]", "", value)
return base64.b64decode(data, validate=True)
def sts_policy(record):
policy_id = read_tags(record).get("id", "")
if not re.fullmatch(r"[A-Za-z0-9]{1,32}", policy_id):
return "attention", "Supply a policy ID of 1 to 32 letters or digits."
return "ok", "DNS policy ID published. The HTTPS policy was not checked."
def tls_reporting(record):
tags = read_tags(record)
addresses = tags.get("rua", "").split(",")
try:
destinations = [urlsplit(item.strip()) for item in addresses]
valid = all(
(
uri.scheme == "mailto"
and re.fullmatch(r"[^@\s]+@[^@\s]+", uri.path)
)
or (
uri.scheme == "https" and uri.hostname and uri.username is None
)
for uri in destinations
)
except ValueError:
valid = False
if not valid:
return "attention", "Supply a mailto or HTTPS report destination."
return "ok", "SMTP TLS reporting record published."
+39 -7
View File
@@ -102,6 +102,26 @@ class MailboxQuotaUpdate:
return {"operation": "set_quota", "mailbox": self.mailbox.manifest()}
@dataclass(frozen=True)
class MailboxSigningRequest:
mailbox: MailboxSpec
def __post_init__(self):
from .mail_dns import MANAGED_DKIM_SELECTOR
owner = f"{MANAGED_DKIM_SELECTOR}._domainkey.{self.mailbox.domain}"
if len(owner) > 253:
raise ValueError(
"The mail domain is too long for the DKIM selector."
)
def manifest(self):
return {
"operation": "provision_with_signing",
"mailbox": self.mailbox.manifest(),
}
def parse_mailbox_request(data):
return parse_retirement(
data, MailboxSpec.from_manifest, parse_mailbox_apply
@@ -109,12 +129,15 @@ def parse_mailbox_request(data):
def parse_mailbox_apply(data):
if (
isinstance(data, dict)
and data.keys() == {"operation", "mailbox"}
and data["operation"] == "set_quota"
):
return MailboxQuotaUpdate(MailboxSpec.from_manifest(data["mailbox"]))
if isinstance(data, dict) and data.keys() == {"operation", "mailbox"}:
if data["operation"] == "set_quota":
return MailboxQuotaUpdate(
MailboxSpec.from_manifest(data["mailbox"])
)
if data["operation"] == "provision_with_signing":
return MailboxSigningRequest(
MailboxSpec.from_manifest(data["mailbox"])
)
return parse_service_request(data, MailboxSpec.from_manifest)
@@ -131,6 +154,12 @@ def apply_mailbox_request(request):
from .mail_node_quota import set_mailbox_quota
set_mailbox_quota(request.mailbox)
elif isinstance(request, MailboxSigningRequest):
from .mail_node_apply import apply_mailbox
from .mail_node_dkim import provision_dkim_key
apply_mailbox(request.mailbox)
return {"dkim": provision_dkim_key(request.mailbox.domain)}
else:
from .mail_node_apply import apply_mailbox
@@ -174,7 +203,10 @@ def main(argv=None):
if args.command == "apply-request":
return serve_apply_request(
MANIFEST_VERSION, parse_mailbox_request, apply_mailbox_request
MANIFEST_VERSION,
parse_mailbox_request,
apply_mailbox_request,
include_result=True,
)
try:
+70
View File
@@ -0,0 +1,70 @@
import base64
import grp
from pathlib import Path
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPrivateKey,
generate_private_key,
)
from cryptography.hazmat.primitives.serialization import (
Encoding,
NoEncryption,
PrivateFormat,
PublicFormat,
load_pem_private_key,
)
from .mail_dns import MANAGED_DKIM_SELECTOR
from .node_files import locked_root_directory, read_root_file, write_new_file
KEY_DIRECTORY = Path("/etc/rspamd/coulobre-dkim")
SIGNER_GROUP = "_rspamd"
def provision_dkim_key(domain):
if not KEY_DIRECTORY.exists():
raise ValueError("Set up the Rspamd DKIM directory on the mail node.")
key_path = KEY_DIRECTORY / f"{domain}.{MANAGED_DKIM_SELECTOR}.key"
with locked_root_directory(KEY_DIRECTORY):
try:
signer_group = grp.getgrnam(SIGNER_GROUP).gr_gid
except KeyError:
raise ValueError(
"Install and configure Rspamd DKIM signing."
) from None
directory = KEY_DIRECTORY.stat()
if (
directory.st_gid != signer_group
or directory.st_mode & 0o777 != 0o750
):
raise ValueError(
"Set the DKIM directory to mode 0750 and the Rspamd group."
)
try:
pem = read_root_file(key_path, mode=0o640)
except FileNotFoundError:
key = generate_private_key(public_exponent=65537, key_size=2048)
pem = key.private_bytes(
Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()
)
write_new_file(
key_path, pem.decode("ascii"), mode=0o640, group=signer_group
)
else:
if key_path.stat().st_gid != signer_group:
raise ValueError("The DKIM key has the wrong group.")
try:
key = load_pem_private_key(pem.encode("ascii"), password=None)
except (TypeError, ValueError, UnsupportedAlgorithm):
raise ValueError(
"Could not read the existing DKIM key."
) from None
if not isinstance(key, RSAPrivateKey) or key.key_size < 2048:
raise ValueError(
"The DKIM key must be RSA with at least 2048 bits."
)
public = key.public_key().public_bytes(
Encoding.DER, PublicFormat.PKCS1
)
return "v=DKIM1; k=rsa; p=" + base64.b64encode(public).decode("ascii")
+49
View File
@@ -1,10 +1,12 @@
import os
import re
from ipaddress import ip_address
from pathlib import Path
from urllib.parse import urlsplit
from django.core.exceptions import ImproperlyConfigured
from .domain_names import canonical_domain
from .service_health import load_health_targets
@@ -15,6 +17,29 @@ def required_env(name):
return value
def ip_addresses_env(name, limit):
values = os.environ.get(name, "").split(",")
try:
if any("%" in value for value in values):
raise ValueError
addresses = tuple(
dict.fromkeys(
str(ip_address(value.strip()))
for value in values
if value.strip()
)
)
except ValueError:
raise ImproperlyConfigured(
f"Set literal IP addresses in {name}."
) from None
if len(addresses) > limit:
raise ImproperlyConfigured(
f"Set up to {limit} unscoped IP addresses in {name}."
)
return addresses
SECRET_KEY = required_env("COULOBRE_SECRET_KEY")
HTTPS_PROXY = os.environ.get("COULOBRE_HTTPS_PROXY") == "1"
DEBUG = not HTTPS_PROXY and os.environ.get("COULOBRE_DEBUG") == "1"
@@ -158,6 +183,30 @@ LOCAL_MAILBOX_CREDENTIALS = (
os.environ.get("COULOBRE_LOCAL_MAILBOX_CREDENTIALS") == "1"
)
MAIL_IMAP_HOST = os.environ.get("COULOBRE_MAIL_IMAP_HOST", "").strip()
MAIL_DNS_RESOLVERS = ip_addresses_env("COULOBRE_MAIL_DNS_RESOLVERS", 3)
MAIL_SENDING_IPS = ip_addresses_env("COULOBRE_MAIL_SENDING_IPS", 4)
MAIL_MX_IPS = ip_addresses_env("COULOBRE_MAIL_MX_IPS", 4)
if any(
not ip_address(address).is_global or ip_address(address).is_multicast
for address in (*MAIL_SENDING_IPS, *MAIL_MX_IPS)
):
raise ImproperlyConfigured(
"Set public IP addresses for the mail MX and sending addresses."
)
MAIL_MX_HOST = os.environ.get("COULOBRE_MAIL_MX_HOST", "").strip()
if MAIL_MX_HOST:
try:
MAIL_MX_HOST = canonical_domain(MAIL_MX_HOST)
except ValueError:
raise ImproperlyConfigured(
"Set a hostname in COULOBRE_MAIL_MX_HOST."
) from None
MANAGE_MAIL_DNS = os.environ.get("COULOBRE_MANAGE_MAIL_DNS") == "1"
if MANAGE_MAIL_DNS and not (MAIL_MX_HOST and MAIL_SENDING_IPS):
raise ImproperlyConfigured(
"Set COULOBRE_MAIL_MX_HOST and COULOBRE_MAIL_SENDING_IPS "
"to provision mail DNS."
)
PHPMYADMIN_URL = os.environ.get("COULOBRE_PHPMYADMIN_URL", "").rstrip("/")
PHPMYADMIN_BRIDGE_KEY = os.environ.get("COULOBRE_PHPMYADMIN_BRIDGE_KEY", "")
if PHPMYADMIN_URL: