diff --git a/docs/deployment.md b/docs/deployment.md index 269e658..594a425 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -993,6 +993,120 @@ Back up mail on the node that hosts the mailbox. The archive can be used to recover messages and folders into a newly provisioned mailbox with the same address. [Mailbox backup and restore](development.md#back-up-and-restore-a-mailbox) +## Check and provision mail DNS + +Open **Check mail DNS** under **Mail domains**. The check reads MX and +its address records, SPF, DMARC, DKIM public keys, the MTA-STS and TLS-RPT +DNS records, and reverse DNS for configured sending addresses. Use the +DKIM selector supplied by the signer or the `s=` value from a sent +message's `DKIM-Signature` header. Coulobre fills in selectors it knows. + +The panel uses its system resolver by default. For internet-facing mail, +set `COULOBRE_MAIL_DNS_RESOLVERS` to a comma-separated list of up to three +trusted recursive resolvers with a public DNS view. An authoritative-only +BIND instance serves zones and may not answer queries for other domains. +Results describe the returned records and their basic validity. Verify +SPF evaluation, DKIM signatures, DMARC alignment and mail delivery with a +message sent to an independent mailbox. The MTA-STS check reads its DNS +policy ID. Checking the HTTPS policy is a separate step. The DKIM check +compares the managed selector with the public key received from the mail +node. + +### Set up signing on a Coulobre mail node + +Install the distribution's `rspamd` package on the mail node, including +when the node is separate from the panel. This example dedicates Rspamd +to signing authenticated Postfix submission. It uses a private Postfix +socket and disables Rspamd's normal and controller listeners. The +mail host can still use [SpamAssassin for incoming SMTP](#filter-incoming-mail-with-spamassassin). +[Rspamd signing options](https://docs.rspamd.com/modules/dkim_signing/) + +```sh +sudo apt install rspamd +sudo install -d -o root -g _rspamd -m 0750 /etc/rspamd/coulobre-dkim +sudo install -d -o root -g postfix -m 0750 /var/spool/postfix/rspamd +sudo install -m 0644 deploy/rspamd/dkim_signing.conf.example \ + /etc/rspamd/override.d/dkim_signing.conf +sudo install -m 0644 deploy/rspamd/worker-proxy.inc.example \ + /etc/rspamd/override.d/worker-proxy.inc +for worker in normal controller; do + sudo install -m 0644 deploy/rspamd/worker-disabled.inc.example \ + "/etc/rspamd/override.d/worker-$worker.inc" +done +sudo install -m 0644 deploy/rspamd/settings.conf.example \ + /etc/rspamd/local.d/settings.conf +sudo rspamadm configtest +sudo systemctl enable rspamd.service +sudo systemctl restart rspamd.service +``` + +Configure TLS for Postfix and include +`deploy/dovecot/submission-auth.conf.example` in the Dovecot configuration +to provide the SASL socket. Use full email addresses for authentication. +Merge `deploy/rspamd/postfix-submission.cf.example` into the +`submission` service in `/etc/postfix/master.cf`. Use the signing socket +only from authenticated submission. Keep any inbound milters on the +public SMTP service. Rspamd signs when the authenticated domain, +envelope sender domain, and header sender domain agree. +[Postfix SASL setup](https://www.postfix.org/SASL_README.html) + +```sh +sudo systemctl restart dovecot.service +sudo postfix check +sudo postfix reload +``` + +Configure the panel and mailbox worker in `/etc/coulobre/panel.env`. +Set the inbound hostname separately from the sending addresses. Set +`COULOBRE_MAIL_MX_IPS` when Coulobre should also create address records for +an MX hostname inside the managed zone. Ensure an MX hostname outside +the zone already has public addresses at its DNS provider. Replace the +documentation addresses below with the real public addresses. + +```ini +COULOBRE_MANAGE_MAIL_DNS=1 +COULOBRE_MAIL_MX_HOST=mx.example.net +COULOBRE_MAIL_MX_IPS=192.0.2.25 +COULOBRE_MAIL_SENDING_IPS=192.0.2.25,2001:db8::25 +``` + +Upgrade Coulobre on the panel and mail node, apply migrations, collect +static files and restart the panel, workers and scheduler. Provisioning a +mailbox creates or reuses a per-domain RSA DKIM key with selector +`coulobre`. The signing key stays on the mail node. Include +`/etc/rspamd/coulobre-dkim` in the operator's protected configuration +backup. For an existing mailbox, an operator can run **Refresh mail DNS +setup** on the domain's checker page. + +### Publish records with Coulobre DNS + +Enable the local or SSH-backed DNS publishing worker and select +**Publish DNS for Coulobre mail automatically** in the zone's editor. +Provision a mailbox or refresh its mail DNS setup. Coulobre adds the MX +record, any needed in-zone addresses, an SPF policy for the configured +sending IPs, a monitoring DMARC record, and the DKIM public key. It +queues the revised zone through the configured DNS worker. + +The job waits for a publishing request already in progress. Publish +unpublished zone edits before applying a conflicting mail setup. Review +existing MX or DKIM conflicts from the checker page. Coulobre preserves +existing SPF and DMARC policies. When other systems also send for the +domain, include them in SPF before asking receivers to enforce DMARC. +Configure PTR with the provider that assigns the public sending IP. + +### Publish records with third-party DNS + +The checker shows the DNS zone and nameservers observed by the resolver. +Open the DNS editor at the company hosting that zone. Use the registrar's +editor when the registrar also runs its nameservers. Leave automatic +publishing off for a zone hosted by a third party. + +Copy the record names, values, and MX priorities from **Where to edit +DNS**. Use the full record name or the relative name expected by the +provider. Keep one SPF policy and merge all authorized senders into it. +For a third-party signer, use its exact DKIM TXT or CNAME records. Publish +the records and run the checker again after the old TTL has expired. + ## Filter incoming mail with SpamAssassin Install the distribution's SpamAssassin and `spamass-milter` packages on diff --git a/src/coulobre/hosting/impersonation.py b/src/coulobre/hosting/impersonation.py index 749e146..9c03b4b 100644 --- a/src/coulobre/hosting/impersonation.py +++ b/src/coulobre/hosting/impersonation.py @@ -20,6 +20,7 @@ PREVIEW_VIEWS = frozenset( "panel:account", "panel:database_create", "panel:mailbox_create", + "panel:mail_dns_check", "panel:sftp_keys", } ) diff --git a/src/coulobre/hosting/mail_dns_views.py b/src/coulobre/hosting/mail_dns_views.py new file mode 100644 index 0000000..d9a715c --- /dev/null +++ b/src/coulobre/hosting/mail_dns_views.py @@ -0,0 +1,274 @@ +import re +from dataclasses import dataclass + +from django import forms +from django.conf import settings +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.http import Http404, HttpResponse +from django.shortcuts import get_object_or_404, redirect +from django.utils.decorators import method_decorator +from django.views import View +from django.views.decorators.cache import never_cache +from django.views.generic import FormView +from django.views.generic.detail import SingleObjectMixin + +from coulobre.mail_dns import ( + MANAGED_DKIM_SELECTOR, + MAX_SELECTORS, + SELECTOR, + matches_version, + run_mail_dns, +) + +from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant +from .mail_dns_setup import ( + closest_zone, + mail_dns_proposal, + queue_mail_dns_setup, +) +from .models import HostingMailDomain +from .views import ( + PROVISION_MAILBOX, + VIEW_ACCOUNTS, + VIEW_DNS_ZONES, + VIEW_MAILBOXES, +) + + +class MailDnsForm(forms.Form): + selectors = forms.CharField( + label="DKIM selectors", + required=False, + max_length=1024, + help_text=( + "Enter up to four selectors, separated by commas or spaces. " + "Use the selector from your mail provider or the s= value in " + "the DKIM-Signature header of a sent message." + ), + widget=forms.TextInput( + attrs={"autocomplete": "off", "spellcheck": "false"} + ), + ) + + def __init__(self, *args, domain, **kwargs): + super().__init__(*args, **kwargs) + self.domain = domain + + def clean_selectors(self): + selectors = tuple( + dict.fromkeys( + selector.lower() + for selector in re.split( + r"[\s,]+", self.cleaned_data["selectors"] + ) + if selector + ) + ) + if len(selectors) > MAX_SELECTORS: + raise forms.ValidationError("Enter up to four DKIM selectors.") + if any( + not selector_fits(selector, self.domain) for selector in selectors + ): + raise forms.ValidationError( + "Enter selector names only, using letters, digits, hyphens " + "and periods between labels." + ) + return selectors + + +def selector_fits(selector, domain): + return bool( + len(f"{selector}._domainkey.{domain}") <= 253 + and SELECTOR.fullmatch(selector) + ) + + +@dataclass(frozen=True) +class DnsEntry: + name: str + kind: str + value: str + priority: int | None = None + + +@method_decorator(never_cache, name="dispatch") +class MailDnsCheckView( + TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView +): + queryset = HostingMailDomain.objects.select_related("account") + customer_relation = "account__customer" + reseller_relation = "account__reseller" + permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES) + template_name = "hosting/mail_dns_check.html" + form_class = MailDnsForm + + def get(self, request, *args, **kwargs): + self.load_domain() + return super().get(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + self.load_domain() + return super().post(request, *args, **kwargs) + + def load_domain(self): + self.object = self.get_object() + self.domain = self.object.domain + self.zone = None + self.zone_txt = () + self.zone_mx = () + self.zone_addresses = () + if is_tenant(self.request.user) or self.request.user.has_perm( + VIEW_DNS_ZONES + ): + self.zone = closest_zone( + self.object.account.dns_zones.all(), self.domain + ) + if self.zone: + spec = self.zone.spec + self.zone_txt = spec.txt_records + self.zone_mx = spec.mx_records + self.zone_addresses = spec.addresses + + def get_initial(self): + initial = super().get_initial() + suffix = f"._domainkey.{self.domain}" + selectors = dict.fromkeys( + record.name.removesuffix(suffix) + for record in self.zone_txt + if record.name.endswith(suffix) + and selector_fits(record.name.removesuffix(suffix), self.domain) + ) + if self.object.dkim_record: + selectors = {MANAGED_DKIM_SELECTOR: None} | selectors + initial["selectors"] = ", ".join(tuple(selectors)[:MAX_SELECTORS]) + return initial + + def get_form_kwargs(self): + return super().get_form_kwargs() | {"domain": self.domain} + + def get_context_data(self, *, report=None, **kwargs): + entries = self.guide_entries(report) + return super().get_context_data( + account=self.object.account, + domain=self.domain, + zone=self.zone, + report=report, + mail_domain=self.object, + can_refresh=( + settings.MANAGE_MAIL_DNS + and settings.LOCAL_MAILBOX_PROVISIONING + and not is_tenant(self.request.user) + and self.request.user.has_perms(PROVISION_MAILBOX) + and self.object.mailboxes.filter( + provisioning__finished_at__isnull=False, + provisioning__problem="", + ).exists() + ), + zone_matches=bool( + report + and self.zone + and report.zone == self.zone.domain + and set(report.nameservers) + == {host + "." for host in self.zone.nameservers} + ), + entries=entries, + sending_ips=settings.MAIL_SENDING_IPS, + explicit_resolver=bool(settings.MAIL_DNS_RESOLVERS), + dmarc_example=not any( + entry.name == f"_dmarc.{self.domain}" for entry in entries + ) + and not ( + report + and any( + check.label == "DMARC" and check.state != "missing" + for check in report.checks + ) + ), + **kwargs, + ) + + def form_valid(self, form): + report = run_mail_dns( + self.domain, + form.cleaned_data["selectors"], + nameservers=settings.MAIL_DNS_RESOLVERS, + expected_mx=settings.MAIL_MX_HOST, + signing_record=self.object.dkim_record, + sending_ips=settings.MAIL_SENDING_IPS, + ) + return self.render_to_response( + self.get_context_data(form=form, report=report) + ) + + def guide_entries(self, report): + addresses, mx, txt = mail_dns_proposal( + self.domain, self.object.dkim_record + ) + entries = [ + DnsEntry(record.name, "MX", record.exchange + ".", record.priority) + for record in self.zone_mx + if record.name == self.domain and record.exchange != "." + ] + if not entries: + entries.extend( + DnsEntry( + record.name, "MX", record.exchange + ".", record.priority + ) + for record in mx + ) + targets = {entry.value.removesuffix(".") for entry in entries} + entries.extend( + DnsEntry(record.name, record.record_type, record.address) + for record in dict.fromkeys(self.zone_addresses + addresses) + if record.name in targets + ) + txt_owners = { + self.domain: "v=spf1", + f"_dmarc.{self.domain}": "v=DMARC1", + f"_mta-sts.{self.domain}": "v=STSv1", + f"_smtp._tls.{self.domain}": "v=TLSRPTv1", + } + own_key = f"{MANAGED_DKIM_SELECTOR}._domainkey.{self.domain}" + entries.extend( + DnsEntry(record.name, "TXT", record.text) + for record in self.zone_txt + if ( + record.name in txt_owners + and matches_version(record.text, txt_owners[record.name]) + ) + or ( + record.name.endswith(f"._domainkey.{self.domain}") + and (record.name != own_key or not self.object.dkim_record) + ) + ) + saved_names = {entry.name for entry in entries if entry.kind == "TXT"} + policy_names = { + check.name + for check in (report.checks if report else ()) + if check.label in {"SPF", "DMARC"} and check.state != "missing" + } + entries.extend( + DnsEntry(record.name, "TXT", record.text) + for record in txt + if record.name not in saved_names | policy_names + ) + return entries + + +class RequestMailDnsSetup(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = PROVISION_MAILBOX + + def post(self, request, pk): + if not ( + settings.MANAGE_MAIL_DNS and settings.LOCAL_MAILBOX_PROVISIONING + ): + raise Http404 + domain = get_object_or_404(HostingMailDomain, pk=pk) + try: + queue_mail_dns_setup(domain) + except ValidationError as error: + return HttpResponse( + " ".join(error.messages), status=409, content_type="text/plain" + ) + return redirect("panel:mail_dns_check", pk=pk) diff --git a/src/coulobre/hosting/static/hosting/credential-copy.js b/src/coulobre/hosting/static/hosting/copy-field.js similarity index 76% rename from src/coulobre/hosting/static/hosting/credential-copy.js rename to src/coulobre/hosting/static/hosting/copy-field.js index b70fb7e..d841e26 100644 --- a/src/coulobre/hosting/static/hosting/credential-copy.js +++ b/src/coulobre/hosting/static/hosting/copy-field.js @@ -1,13 +1,13 @@ "use strict"; -const copyStatus = document.getElementById("credential-copy-status"); +const copyStatus = document.getElementById("copy-field-status"); -for (const button of document.querySelectorAll("[data-copy-credential]")) { +for (const button of document.querySelectorAll("[data-copy-field]")) { if (!navigator.clipboard) { continue; } - const field = document.getElementById(button.dataset.copyCredential); + const field = document.getElementById(button.dataset.copyField); button.hidden = false; button.addEventListener("click", async () => { if (!field.value) { diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 9e29f9c..1ad058a 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -647,3 +647,30 @@ dd { display: none; } } + +.dns-answer { + max-width: 38rem; + white-space: normal; + overflow-wrap: anywhere; +} + +.dns-answer p { + margin: 0.25rem 0; +} + +.dns-instructions { + padding: 1.2rem; +} + +.dns-instructions p, +.dns-instructions ul { + margin: 0; +} + +.dns-instructions li + li { + margin-top: 0.5rem; +} + +.dns-instructions input { + min-width: 12rem; +} diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 19f47a4..f1b1793 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -180,6 +180,26 @@ {% endif %} {% if is_tenant or perms.hosting.view_hostingmailbox %} + {% if mail_domains %} +
+
+

Mail domains

+
+
+ + + + {% for domain in mail_domains %} + + + + + {% endfor %} + +
DomainDNS
{{ domain }}Check mail DNS
+
+
+ {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/copy_value.html b/src/coulobre/hosting/templates/hosting/copy_value.html new file mode 100644 index 0000000..0afcbb8 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/copy_value.html @@ -0,0 +1,4 @@ +
+ + +
diff --git a/src/coulobre/hosting/templates/hosting/mail_dns_check.html b/src/coulobre/hosting/templates/hosting/mail_dns_check.html new file mode 100644 index 0000000..1860f00 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mail_dns_check.html @@ -0,0 +1,140 @@ +{% extends "hosting/base.html" %} +{% load static %} +{% block title %}Mail DNS check · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +
+
+

Mail DNS check

+

{{ domain }}

+
+
+ {% if not request.impersonation %} +
+
+ {% csrf_token %} + {{ form.as_div }} +
+ +
+
+
+ {% endif %} + {% if can_refresh or mail_domain.dns_setup_problem or mail_domain.dns_sync_requested %} +
+

Mail DNS setup

+
+ {% if mail_domain.dns_setup_problem %}

{{ mail_domain.dns_setup_problem }}

{% endif %} + {% if mail_domain.dns_sync_requested %}

Waiting to update the managed zone.

{% endif %} + {% if can_refresh %} +
+ {% csrf_token %} + +
+ {% endif %} +
+
+ {% endif %} + {% if report %} +
+
+
+

DNS results

+

Lookups use {% if explicit_resolver %}the configured DNS resolver{% else %}the panel server’s DNS resolver{% endif %}. Cached records can remain visible until their TTL expires.

+
+
+
+ + + + {% for check in report.checks %} + + + + + + {% endfor %} + +
CheckStatusDNS answer
{{ check.label }} + {% if check.state == "ok" %}Published + {% elif check.state == "attention" %}Needs attention + {% elif check.state == "missing" %}Missing + {% elif check.state == "unavailable" %}Unavailable + {% elif check.state == "optional" %}Optional + {% else %}Not checked{% endif %} + + {{ check.name }}. +

{{ check.detail }}

+ {% for record in check.records %}
{{ record }}
{% endfor %} +
+
+
+ {% endif %} +
+

Where to edit DNS

+
+ {% if report.nameservers %} +

DNS for {{ report.zone }} is served by {{ report.nameservers|join:", " }}.

+ {% elif report %} +

The active DNS zone or its nameservers could not be determined.

+ {% endif %} + {% if zone_matches %} +

The observed nameservers match the Coulobre zone {{ zone.domain }}. Ask the hosting operator to publish updates on the configured local or remote DNS node.

+ {% elif zone %} + {% if report.nameservers %} +

The observed nameservers differ from the saved Coulobre zone {{ zone.domain }}. Use the provider serving the active zone.

+ {% else %} +

A Coulobre zone exists for {{ zone.domain }}. Run the check to compare its nameservers with the active zone.

+ {% endif %} + {% endif %} +

If a third party serves DNS, add the records in that provider's DNS editor. Use the registrar's editor when it also hosts the active DNS zone.

+

Enter the full record name below, or remove the zone suffix if the editor appends it automatically. Use @ only at that zone’s apex. Enter TXT values without extra quotes.

+
    +
  • MX and addresses. Use the mail service’s inbound hostname and priority. Publish A and AAAA for the IPv4 and IPv6 addresses it serves. Use a DNS-only host for mail.
  • +
  • SPF. Publish one TXT policy at {{ domain }}.. Include every authorized sender using the IPs or include mechanism supplied by its mail service. Merge senders into an existing SPF record.
  • +
  • DKIM. Copy the provider’s TXT or CNAME at selector._domainkey.{{ domain }}.. Use the exact selector and public value supplied by the signer. Keep the signing key private.
  • +
  • DMARC. Use a TXT at _dmarc.{{ domain }}.. If no policy applies, start with monitoring and set up aggregate reports before choosing an enforcement policy.
  • +
  • MTA-STS and TLS-RPT. Use the mail provider’s published policy ID at _mta-sts.{{ domain }}. and report URI at _smtp._tls.{{ domain }}.. MTA-STS also needs its HTTPS policy.
  • +
  • PTR. Ask the provider that owns the sending IP to set its reverse record. The PTR hostname must resolve back to the IP.{% if sending_ips %} Configured sending IPs: {{ sending_ips|join:", " }}.{% endif %}
  • +
+ {% if entries or dmarc_example %} + {% if entries %} +

These values come from your saved Coulobre zone and the operator’s mail configuration. Confirm they match the active mail service before publishing them.

+ {% endif %} +
+ + + + {% for entry in entries %} + + + + + + {% endfor %} + {% if dmarc_example %} + + + + + + {% endif %} + +
TypeNameValue
{{ entry.kind }} + {% with id=forloop.counter|stringformat:"s" %} + {% include "hosting/copy_value.html" with key="dns-name-"|add:id label="record name" value=entry.name|add:"." only %} + {% endwith %} + + {% if entry.priority is not None %}

Priority {{ entry.priority }}

{% endif %} + {% with id=forloop.counter|stringformat:"s" %} + {% include "hosting/copy_value.html" with key="dns-value-"|add:id label="record value" value=entry.value only %} + {% endwith %} +
TXT
DMARC monitoring example
{% include "hosting/copy_value.html" with key="dmarc-name" label="DMARC name" value="_dmarc."|add:domain|add:"." only %}{% include "hosting/copy_value.html" with key="dmarc-value" label="DMARC value" value="v=DMARC1; p=none" only %}
+
+

+ + {% endif %} +

Run the check after publishing. To verify that your mail is signed and passes alignment, send a message and inspect its Authentication-Results header at the recipient.

+
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/service_credentials.html b/src/coulobre/hosting/templates/hosting/service_credentials.html index 2981902..6155172 100644 --- a/src/coulobre/hosting/templates/hosting/service_credentials.html +++ b/src/coulobre/hosting/templates/hosting/service_credentials.html @@ -24,17 +24,17 @@
- +
{% endfor %} -

+

Done {% if rotation_url %}Rotate password{% endif %}
- + {% else %}
{% if rotating %} diff --git a/src/coulobre/hosting/test_mail_dns.py b/src/coulobre/hosting/test_mail_dns.py new file mode 100644 index 0000000..36b2877 --- /dev/null +++ b/src/coulobre/hosting/test_mail_dns.py @@ -0,0 +1,318 @@ +import base64 +from unittest.mock import patch + +import dns.message +import dns.name +import dns.resolver +import dns.rrset +from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.mail_dns import ( + Check, + LookupUnavailableError, + MailDnsReport, + check_txt, + dkim_key, + run_mail_dns, + spf_policy, +) + +from .mail_dns_setup import sync_mail_dns +from .models import ( + Customer, + DnsPublication, + HostingAccount, + HostingDnsZone, + HostingMailbox, + HostingMailDomain, + MailboxProvisioning, +) +from .tasks import dispatch_dns_publications, provision_mailbox + +DOMAIN = "example.net" +MX = "mx.example.net" +IP = "93.184.215.14" +DKIM = "v=DKIM1; k=ed25519; p=" + base64.b64encode(bytes(range(32))).decode() + + +def answer(owner, kind, *records): + query = dns.message.make_query(owner + ".", kind) + response = dns.message.make_response(query) + rrset = dns.rrset.from_text(owner + ".", 60, "IN", kind, *records) + response.find_rrset( + response.answer, rrset.name, rrset.rdclass, rrset.rdtype, create=True + ).update(rrset) + return dns.resolver.Answer( + query.question[0].name, query.question[0].rdtype, 1, response + ) + + +class MailDnsRecordsTests(SimpleTestCase): + def test_queries_supported_records_and_joins_split_txt(self): + key_prefix, key_data = DKIM.split("p=") + values = { + (DOMAIN, "MX"): answer(DOMAIN, "MX", f"10 {MX}."), + (MX, "A"): answer(MX, "A", IP), + (DOMAIN, "TXT"): answer( + DOMAIN, "TXT", '"v=spf1 ip4:93.184.215.14 -all"', '"unrelated"' + ), + ("_dmarc.example.net", "TXT"): answer( + "_dmarc.example.net", "TXT", '"v=DMARC1; p=none"' + ), + ("news._domainkey.example.net", "TXT"): answer( + "news._domainkey.example.net", + "TXT", + f'"{key_prefix}p=" "{key_data}"', + ), + ("_mta-sts.example.net", "TXT"): answer( + "_mta-sts.example.net", "TXT", '"v=STSv1; id=20261201"' + ), + ("_smtp._tls.example.net", "TXT"): answer( + "_smtp._tls.example.net", + "TXT", + '"v=TLSRPTv1; rua=mailto:tls@example.net"', + ), + ("14.215.184.93.in-addr.arpa", "PTR"): answer( + "14.215.184.93.in-addr.arpa", "PTR", f"{MX}." + ), + } + with patch("coulobre.mail_dns.MailDnsResolver") as factory: + resolver = factory.return_value + resolver.lookup.side_effect = lambda name, kind: values.get( + (name, kind) + ) + resolver.authoritative_zone.return_value = ( + DOMAIN, + ("dns.example.net.",), + ) + report = run_mail_dns( + DOMAIN, ("news",), expected_mx=MX, sending_ips=(IP,) + ) + self.assertEqual(report.zone, DOMAIN) + self.assertEqual(len(report.checks), 7) + self.assertEqual({check.state for check in report.checks}, {"ok"}) + self.assertEqual(report.checks[3].records, (DKIM,)) + + def test_reports_invalid_or_unavailable_records(self): + owner = "_dmarc.example.net" + with patch("coulobre.mail_dns.MailDnsResolver") as factory: + resolver = factory.return_value + resolver.lookup.side_effect = LookupUnavailableError + self.assertEqual( + check_txt(resolver, "DMARC", owner, "v=DMARC1", None).state, + "unavailable", + ) + resolver.lookup.side_effect = None + resolver.lookup.return_value = answer( + owner, "TXT", '"v=DMARC1; p=none"', '"v=DMARC1; p=reject"' + ) + self.assertEqual( + check_txt(resolver, "DMARC", owner, "v=DMARC1", None).state, + "attention", + ) + self.assertEqual(dkim_key("v=DKIM1; p=")[0], "attention") + self.assertEqual(spf_policy("v=spf1 +all")[0], "attention") + self.assertEqual(spf_policy("v=spf1 ip4:fd00::7 -all")[0], "attention") + + +@override_settings( + LOCAL_DNS_PUBLISHING=True, + LOCAL_MAILBOX_PROVISIONING=True, + MANAGE_MAIL_DNS=True, + MAIL_MX_HOST=MX, + MAIL_MX_IPS=(IP,), + MAIL_SENDING_IPS=(IP,), +) +class MailDnsPanelTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.customer = Customer.objects.create( + user=users.create_user("customer") + ) + cls.other = Customer.objects.create(user=users.create_user("other")) + cls.account = HostingAccount.objects.create( + name="Example", primary_domain=DOMAIN, customer=cls.customer + ) + cls.domain = HostingMailDomain.objects.create( + account=cls.account, domain=DOMAIN + ) + cls.mailbox = HostingMailbox.objects.create( + mail_domain=cls.domain, local_part="hello" + ) + + def zone(self, **values): + return HostingDnsZone.objects.create( + account=self.account, + domain=DOMAIN, + nameservers=["ns.other.example"], + responsible_name="hostmaster.example.net", + **values, + ) + + def test_scopes_check_and_renders_external_copy_fields(self): + url = reverse("panel:mail_dns_check", args=[self.domain.pk]) + report = MailDnsReport( + DOMAIN, + ("dns.third-party.example.",), + (Check("SPF", DOMAIN, "ok", "Public policy", ("v=spf1 -all",)),), + ) + with patch( + "coulobre.hosting.mail_dns_views.run_mail_dns", return_value=report + ) as check: + self.client.force_login(self.other.user) + self.assertEqual( + self.client.post(url, {"selectors": "test"}).status_code, 404 + ) + self.client.force_login(self.customer.user) + self.assertContains( + self.client.get(self.account.get_absolute_url()), url + ) + page = self.client.get(url) + self.assertContains(page, "registrar") + self.assertContains(page, 'value="mx.example.net."') + self.assertContains(page, 'value="v=spf1 ip4:93.184.215.14 ~all"') + self.assertContains(page, 'data-copy-field="dns-name-1"') + self.assertContains( + self.client.post(url, {"selectors": "../outside"}), + "Enter selector names only", + ) + check.assert_not_called() + result = self.client.post(url, {"selectors": "news, news a.b"}) + self.assertContains(result, "dns.third-party.example.") + self.assertContains(result, "Public policy") + self.assertIn("no-store", result["Cache-Control"]) + check.assert_called_once_with( + DOMAIN, + ("news", "a.b"), + nameservers=(), + expected_mx=MX, + signing_record="", + sending_ips=(IP,), + ) + + def test_first_mailbox_adds_public_records_and_retry_keeps_serial(self): + zone = self.zone(manage_mail_dns=True, serial=5) + job = MailboxProvisioning.objects.create(mailbox=self.mailbox) + public_key = generate_private_key( + public_exponent=65537, key_size=2048 + ).public_key() + dkim = ( + "v=DKIM1; k=rsa; p=" + + base64.b64encode( + public_key.public_bytes(Encoding.DER, PublicFormat.PKCS1) + ).decode() + ) + with patch( + "coulobre.hosting.tasks.provision_signing_mailbox", + return_value=dkim, + ): + provision_mailbox(job.pk) + job.refresh_from_db() + 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(dkim_key(DKIM, expected=dkim)[0], "attention") + self.assertEqual(zone.serial, 6) + self.assertEqual( + zone.mx_records, [{"name": DOMAIN, "priority": 10, "exchange": MX}] + ) + self.assertEqual(zone.addresses, [{"name": MX, "address": IP}]) + self.assertEqual( + {item["name"]: item["text"] for item in zone.txt_records}, + { + DOMAIN: f"v=spf1 ip4:{IP} ~all", + "_dmarc.example.net": "v=DMARC1; p=none", + "coulobre._domainkey.example.net": dkim, + }, + ) + publication = DnsPublication.objects.get(zone=zone) + self.assertEqual(publication.manifest, zone.spec.manifest()) + sync_mail_dns(self.domain, public_key=dkim) + zone.refresh_from_db() + self.assertEqual(zone.serial, 6) + + def test_dns_sync_waits_for_inflight_publication(self): + zone = self.zone(manage_mail_dns=True) + publication = DnsPublication.objects.create( + zone=zone, serial=zone.serial, manifest=zone.spec.manifest() + ) + sync_mail_dns(self.domain, public_key=DKIM) + self.domain.refresh_from_db() + self.assertTrue(self.domain.dns_sync_requested) + publication.finished_at = timezone.now() + publication.published_serial = zone.serial + publication.save(update_fields=["finished_at", "published_serial"]) + with patch( + "coulobre.hosting.tasks.publish_dns_zone.apply_async" + ) as dispatch: + dispatch_dns_publications() + self.domain.refresh_from_db() + publication.refresh_from_db() + self.assertFalse(self.domain.dns_sync_requested) + self.assertEqual(publication.serial, 2) + dispatch.assert_called_once() + + def test_external_zone_and_unpublished_edits_are_untouched(self): + zone = self.zone(manage_mail_dns=False, serial=12) + sync_mail_dns(self.domain, public_key=DKIM) + self.domain.refresh_from_db() + self.assertEqual(self.domain.dkim_record, DKIM) + self.assertFalse(DnsPublication.objects.exists()) + zone.manage_mail_dns = True + zone.save(update_fields=["manage_mail_dns"]) + snapshot = DnsPublication.objects.create( + zone=zone, + serial=11, + manifest=zone.spec.manifest(), + finished_at=timezone.now(), + published_serial=11, + ) + sync_mail_dns(self.domain, public_key=DKIM) + zone.refresh_from_db() + self.domain.refresh_from_db() + snapshot.refresh_from_db() + self.assertIn("saved zone revision", self.domain.dns_setup_problem) + self.assertEqual(zone.txt_records, []) + self.assertEqual(snapshot.serial, 11) + + def test_keeps_existing_policies_and_conflicting_mx(self): + current = [ + { + "name": DOMAIN, + "text": "v=spf1 include:_spf.sender.example -all", + }, + {"name": "_dmarc.example.net", "text": "v=DMARC1; p=reject"}, + ] + zone = self.zone( + manage_mail_dns=True, + txt_records=current, + mx_records=[ + { + "name": DOMAIN, + "priority": 10, + "exchange": "mx.other.example", + } + ], + ) + sync_mail_dns(self.domain, public_key=DKIM) + self.assertFalse(DnsPublication.objects.filter(zone=zone).exists()) + self.domain.refresh_from_db() + self.assertIn("Review the current MX", self.domain.dns_setup_problem) + zone.mx_records = [] + zone.save(update_fields=["mx_records"]) + sync_mail_dns(self.domain, public_key=DKIM) + zone.refresh_from_db() + self.domain.refresh_from_db() + self.assertIn( + "Existing SPF policy kept", self.domain.dns_setup_problem + ) + self.assertEqual(zone.txt_records[:2], current) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index e508d9b..cba9a94 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -5,6 +5,7 @@ from . import views from .backup_restores import RestoreKind from .credential_views import DatabaseCredentialView, MailboxCredentialView from .health_views import ServiceHealthView +from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin from .reseller_views import ( ResellerCreate, @@ -212,6 +213,16 @@ urlpatterns = [ views.RequestDnsPublication.as_view(), name="dns_zone_publish", ), + path( + "mail-domains//dns-check/", + MailDnsCheckView.as_view(), + name="mail_dns_check", + ), + path( + "mail-domains//dns-setup/", + RequestMailDnsSetup.as_view(), + name="mail_dns_setup", + ), path( "accounts//mailboxes/new/", views.MailboxCreate.as_view(),