Compare commits

..
4 Commits
Author SHA1 Message Date
parkel ff3e39a2e1 Merge pull request 'Run isolated spam filter checks on mail receivers' (#237) from feature/isolated-mail-filter-check into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #237
2026-12-02 00:49:19 +01:00
parkel 042406b2aa Run isolated spam filter checks on mail receivers
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-12-02 00:48:10 +01:00
parkel ca9543ee0a Merge pull request 'Add operator mail-header diagnostics' (#236) from feature/operator-mail-diagnostics into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #236
2026-12-02 00:33:31 +01:00
parkel b2603a0eef Add operator mail-header diagnostics
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-12-02 00:30:20 +01:00
19 changed files with 1341 additions and 9 deletions

No files matched your search

+42
View File
@@ -2513,6 +2513,48 @@ the mail node's Coulobre state and `/var/lib/coulobre-vacation` in your
server backup if you use these features. Maildir-only archives contain server backup if you use these features. Maildir-only archives contain
messages and folders. Reapply policy settings after a mailbox-only recovery. messages and folders. Reapply policy settings after a mailbox-only recovery.
## Inspect reported spam and authentication results
Sign in as a server administrator with a verified second factor and open
**Admin Tools → Mail diagnostics**. Paste the original headers from the
receiving mail client. The panel summarizes reported SPF, DKIM and DMARC,
plus spam scores and matched rules when the filter includes them. It
compares the reported SPF and DKIM domains with the From domain. Treat
these results as evidence from the named receiver after checking that you
trust the source. Headers supplied by other parties can contain forged
results. The panel processes pasted headers in the request and does not
store them in mail reports.
For a managed From domain, use **Check mail DNS** to check DNS and any
matching DKIM selectors found in the message. **Look up delivery** can
prefill a Postfix queue ID when delivery tracking is configured. Choose
the managed sending or receiving domain and the period to search. Matches
show the journal's delivery state and enhanced status code when present.
The journal search is limited to the selected domain on the configured
mail receiver. Header analysis runs without contacting the mail node.
### Check the incoming spam filter
On **Mail diagnostics**, select a managed mail domain and choose
**Run filter check**. The check runs on the same local or linked mail
receiver that provisions mailboxes for the panel. Keep linked receivers
at the same Coulobre release. The report identifies the receiver, shows
the expected and observed decisions, and lists scores, thresholds and
matching rules for the two synthetic messages.
The direct check covers SpamAssassin's local rules. It uses a transient
unprivileged service with a read-only system, private temporary storage
and no network access. Bayesian learning and online checks are disabled.
The messages never enter Postfix or reach a mailbox. The check is
unavailable when SpamAssassin is absent, including mail nodes that only
use Rspamd for signing. The panel retains the summary for one hour.
[SpamAssassin GTUBE](https://spamassassin.apache.org/gtube/)
For an end-to-end check of the SMTP listener, milter and mailbox delivery,
follow the [SpamAssassin test procedure](#filter-incoming-mail-with-spamassassin)
with a designated test mailbox. Run that procedure separately from the
direct filter check.
## Check and provision mail DNS ## Check and provision mail DNS
Open **Check mail DNS** under **Mail domains**. The check reads MX and Open **Check mail DNS** under **Mail domains**. The check reads MX and
+9 -2
View File
@@ -11,7 +11,7 @@ from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.generic import FormView from django.views.generic import FormView
from coulobre.mail_delivery import MailDeliveryRequest from coulobre.mail_delivery import QUEUE_ID, MailDeliveryRequest
from .access import customer_for_user from .access import customer_for_user
from .domain_policies import policy_for from .domain_policies import policy_for
@@ -35,6 +35,9 @@ class MailDeliveryForm(forms.Form):
) )
sender = forms.EmailField(required=False) sender = forms.EmailField(required=False)
recipient = forms.EmailField(required=False) recipient = forms.EmailField(required=False)
queue_id = forms.RegexField(
QUEUE_ID, required=False, max_length=32, label="Postfix queue ID"
)
def __init__(self, *args, domains, **kwargs): def __init__(self, *args, domains, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
@@ -55,6 +58,7 @@ class MailDeliveryForm(forms.Form):
now, now,
data["sender"], data["sender"],
data["recipient"], data["recipient"],
data["queue_id"],
) )
return data return data
@@ -88,7 +92,10 @@ class MailDeliveryView(FormView):
return super().get_form_kwargs() | {"domains": self.domain_scope()} return super().get_form_kwargs() | {"domains": self.domain_scope()}
def get_initial(self): def get_initial(self):
return {"domain": self.request.GET.get("domain")} return {
"domain": self.request.GET.get("domain"),
"queue_id": self.request.GET.get("queue_id", "")[:32],
}
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
search_id = self.request.GET.get("search") search_id = self.request.GET.get("search")
@@ -0,0 +1,191 @@
from datetime import timedelta
from django import forms
from django.contrib.auth import get_user_model
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import (
sensitive_post_parameters,
sensitive_variables,
)
from django.views.generic import FormView
from coulobre.mail_diagnostics import (
MAX_MESSAGE_BYTES,
MailHeaderError,
inspect_headers,
)
from .access import PanelRole
from .account_administration import OperatorAuthorization
from .domain_policies import policy_for
from .installation_features import panel_feature_allowed
from .models import HostingMailDomain, MailFilterCheck
def diagnostic_domains():
return (
HostingMailDomain.objects.filter(account__retired_at__isnull=True)
.select_related("account")
.order_by("domain")
)
class MailFilterCheckForm(forms.Form):
domain = forms.ModelChoiceField(
queryset=HostingMailDomain.objects.none(),
label="Managed mail domain",
help_text="The check runs on the mail node configured for this panel.",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["domain"].queryset = diagnostic_domains()
def clean_domain(self):
domain = self.cleaned_data["domain"]
if not policy_for(domain.account, domain.domain).mail_managed:
raise forms.ValidationError(
"This domain uses an external provider."
)
return domain
class MailDiagnosticsForm(forms.Form):
headers = forms.CharField(
label="Original mail headers",
max_length=MAX_MESSAGE_BYTES,
widget=forms.Textarea(
attrs={
"rows": 10,
"autocomplete": "off",
"spellcheck": "false",
}
),
help_text="Paste the original headers from your mail client.",
)
@sensitive_variables()
def clean_headers(self):
try:
self.report = inspect_headers(self.cleaned_data["headers"])
except MailHeaderError as error:
raise forms.ValidationError(str(error)) from None
except (ValueError, RecursionError, IndexError, AttributeError):
raise forms.ValidationError(
"These mail headers could not be read."
) from None
return ""
@method_decorator(
[never_cache, sensitive_post_parameters("headers")], name="dispatch"
)
class MailDiagnosticsView(OperatorAuthorization, FormView):
form_class = MailDiagnosticsForm
template_name = "hosting/mail_diagnostics.html"
def test_func(self):
return (
super().test_func()
and getattr(self.request, "active_panel_role", None)
== PanelRole.ADMIN
and not getattr(self.request, "impersonation", None)
)
def get_context_data(self, **kwargs):
available = panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
if available and "filter_form" not in kwargs:
kwargs["filter_form"] = MailFilterCheckForm()
check_id = self.request.GET.get("check")
if check_id is not None and "filter_check" not in kwargs:
if (
not available
or not check_id.isascii()
or not check_id.isdecimal()
or len(check_id) > 18
):
raise Http404
check = get_object_or_404(
MailFilterCheck,
pk=check_id,
actor=self.request.user,
domain__in=diagnostic_domains(),
expires_at__gt=timezone.now(),
)
if not policy_for(
check.domain.account, check.domain.domain
).mail_managed:
raise Http404
kwargs["filter_check"] = check
return super().get_context_data(
mail_delivery_available=available,
**kwargs,
)
def post(self, request, *args, **kwargs):
if request.POST.get("action") == "check-filter":
if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"):
raise Http404
return self.queue_filter_check()
return super().post(request, *args, **kwargs)
@transaction.atomic
def queue_filter_check(self):
form = MailFilterCheckForm(self.request.POST)
if form.is_valid():
get_user_model().objects.select_for_update().get(
pk=self.request.user.pk
)
now = timezone.now()
recent = MailFilterCheck.objects.filter(
actor=self.request.user,
requested_at__gte=now - timedelta(minutes=1),
)
if recent.exists():
form.add_error(None, "Wait a minute between filter checks.")
else:
check = MailFilterCheck.objects.create(
actor=self.request.user,
domain=form.cleaned_data["domain"],
expires_at=now + timedelta(hours=1),
)
url = reverse("panel:mail_diagnostics")
return redirect(f"{url}?check={check.pk}")
return self.render_to_response(
self.get_context_data(
form=self.form_class(), filter_form=form, filter_check=None
)
)
def form_invalid(self, form):
return self.render_to_response(
self.get_context_data(
form=self.form_class(), errors=form.errors.get("headers", ())
)
)
def form_valid(self, form):
report = form.report
dns_domain = None
if report["from_domain"]:
dns_domain = (
HostingMailDomain.objects.filter(
domain=report["from_domain"],
account__retired_at__isnull=True,
)
.only("pk")
.first()
)
return self.render_to_response(
self.get_context_data(
form=self.form_class(),
report=report,
dns_domain=dns_domain,
)
)
+10
View File
@@ -145,6 +145,16 @@ class MailDnsCheckView(
) )
if self.object.dkim_record: if self.object.dkim_record:
selectors = {MANAGED_DKIM_SELECTOR: None} | selectors selectors = {MANAGED_DKIM_SELECTOR: None} | selectors
supplied = self.request.GET.get("selectors", "")[:1024]
if supplied:
requested = MailDnsForm(
{"selectors": supplied}, domain=self.domain
)
if requested.is_valid():
selectors = (
dict.fromkeys(requested.cleaned_data["selectors"])
| selectors
)
initial["selectors"] = ", ".join(tuple(selectors)[:MAX_SELECTORS]) initial["selectors"] = ", ".join(tuple(selectors)[:MAX_SELECTORS])
return initial return initial
@@ -0,0 +1,60 @@
# Generated by Django 5.2.19 on 2026-12-01 23:42
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0086_smtp_applications"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="MailFilterCheck",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("report", models.JSONField(default=dict)),
("expires_at", models.DateTimeField(db_index=True)),
(
"actor",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
(
"domain",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="hosting.hostingmaildomain",
),
),
],
options={
"abstract": False,
},
),
]
+9
View File
@@ -1040,6 +1040,15 @@ class MailDeliverySearch(ProvisioningJob):
expires_at = models.DateTimeField(db_index=True) expires_at = models.DateTimeField(db_index=True)
class MailFilterCheck(ProvisioningJob):
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
domain = models.ForeignKey(HostingMailDomain, on_delete=models.CASCADE)
report = models.JSONField(default=dict)
expires_at = models.DateTimeField(db_index=True)
class AccountRetirement(models.Model): class AccountRetirement(models.Model):
class Policy(models.TextChoices): class Policy(models.TextChoices):
HOLD = "hold", "Keep names reserved" HOLD = "hold", "Keep names reserved"
+47
View File
@@ -55,6 +55,7 @@ from .models import (
MailboxProvisioning, MailboxProvisioning,
MailboxRemoval, MailboxRemoval,
MailDeliverySearch, MailDeliverySearch,
MailFilterCheck,
MailRoutingPublication, MailRoutingPublication,
MailVacationPublication, MailVacationPublication,
OffsiteBackupTransfer, OffsiteBackupTransfer,
@@ -311,6 +312,7 @@ def dispatch_dns_publications():
@shared_task @shared_task
def dispatch_mailbox_provisioning(): def dispatch_mailbox_provisioning():
MailDeliverySearch.objects.filter(expires_at__lte=timezone.now()).delete() MailDeliverySearch.objects.filter(expires_at__lte=timezone.now()).delete()
MailFilterCheck.objects.filter(expires_at__lte=timezone.now()).delete()
if settings.LOCAL_MAILBOX_PROVISIONING: if settings.LOCAL_MAILBOX_PROVISIONING:
dispatch_provisioning_jobs( dispatch_provisioning_jobs(
MailDeliverySearch, MailDeliverySearch,
@@ -318,6 +320,12 @@ def dispatch_mailbox_provisioning():
MAILBOX_PROVISIONING_QUEUE, MAILBOX_PROVISIONING_QUEUE,
expires_at__gt=timezone.now(), expires_at__gt=timezone.now(),
) )
dispatch_provisioning_jobs(
MailFilterCheck,
run_mail_filter_check,
MAILBOX_PROVISIONING_QUEUE,
expires_at__gt=timezone.now(),
)
dispatch_provisioning_jobs( dispatch_provisioning_jobs(
MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE
) )
@@ -1528,6 +1536,45 @@ def search_mail_delivery(job_id):
) )
@shared_task(queue=MAILBOX_PROVISIONING_QUEUE)
def run_mail_filter_check(job_id):
from coulobre.mail_filter_check import (
SCAN_TIMEOUT,
MailFilterCheckRequest,
validated_report,
)
from .domain_policies import policy_for
from .node_client import apply_on_local_node
def apply(job):
domain = job.domain
if (
not job.actor.is_active
or not job.actor.is_superuser
or domain.account.retired_at is not None
or job.expires_at <= timezone.now()
or not policy_for(domain.account, domain.domain).mail_managed
):
raise ValueError("This mail filter check is no longer available.")
reply = apply_on_local_node(
MailFilterCheckRequest(domain.domain),
"/run/coulobre-mail-apply.sock",
"mail node",
"filter check",
timeout=2 * SCAN_TIMEOUT + 10,
)
return {"report": validated_report(reply)}
if settings.LOCAL_MAILBOX_PROVISIONING:
run_provisioning_job(
MailFilterCheck.objects.select_related("domain__account", "actor"),
job_id,
apply,
"The mail node did not return a filter report.",
)
@shared_task(acks_late=True, reject_on_worker_lost=True) @shared_task(acks_late=True, reject_on_worker_lost=True)
def apply_certificate_job(job_id): def apply_certificate_job(job_id):
from django.views.decorators.debug import sensitive_variables from django.views.decorators.debug import sensitive_variables
@@ -15,11 +15,11 @@
{% if search.problem %}<p class="notice">{{ search.problem }}</p> {% if search.problem %}<p class="notice">{{ search.problem }}</p>
{% elif not search.finished_at %}<p class="section-text">{{ search.state|capfirst }}</p> {% elif not search.finished_at %}<p class="section-text">{{ search.state|capfirst }}</p>
{% else %} {% else %}
{% if search.report.partial %}<p class="section-text">Recent matches only. Choose a shorter period or add an address filter.</p>{% endif %} {% if search.report.partial %}<p class="section-text">Recent matches only. Choose a shorter period or add a filter.</p>{% endif %}
<div class="table-scroll"><table> <div class="table-scroll"><table>
<thead><tr><th scope="col">Time (UTC)</th><th scope="col">Queue ID</th><th scope="col">Sender</th><th scope="col">Recipient</th><th scope="col">Delivery</th></tr></thead> <thead><tr><th scope="col">Time (UTC)</th><th scope="col">Queue ID</th><th scope="col">Sender</th><th scope="col">Recipient</th><th scope="col">Delivery</th></tr></thead>
<tbody>{% for event in page_obj %} <tbody>{% for event in page_obj %}
<tr><td>{{ event.timestamp }}</td><td>{{ event.queue_id }}</td><td>{{ event.sender|default:"—" }}</td><td>{{ event.recipient }}{% if event.original_recipient %}<small class="heading-meta"> · originally {{ event.original_recipient }}</small>{% endif %}</td><td>{{ event.status|capfirst }}</td></tr> <tr><td>{{ event.timestamp }}</td><td>{{ event.queue_id }}</td><td>{{ event.sender|default:"—" }}</td><td>{{ event.recipient }}{% if event.original_recipient %}<small class="heading-meta"> · originally {{ event.original_recipient }}</small>{% endif %}</td><td>{{ event.status|capfirst }}{% if event.dsn %} · <code>{{ event.dsn }}</code>{% endif %}</td></tr>
{% empty %}<tr><td colspan="5">No matching deliveries in the available journal.</td></tr>{% endfor %}</tbody> {% empty %}<tr><td colspan="5">No matching deliveries in the available journal.</td></tr>{% endfor %}</tbody>
</table></div> </table></div>
{% if page_obj.has_other_pages %} {% if page_obj.has_other_pages %}
@@ -0,0 +1,111 @@
{% extends "hosting/workspace_page.html" %}
{% block title %}Mail diagnostics · Coulobre Panel{% endblock %}
{% block page_title %}Mail diagnostics{% endblock %}
{% block page_content %}
{% if filter_form %}
<section class="surface editor-surface">
<header class="section-heading"><h2>Check the spam filter</h2></header>
<p class="section-text">Run an isolated SpamAssassin scan with an ordinary sample and GTUBE. This checks local filtering rules. It does not send mail or test SMTP delivery.</p>
<form class="editor" method="post" action="{% url 'panel:mail_diagnostics' %}">
{% csrf_token %}
{{ filter_form.as_div }}
<button class="button secondary" type="submit" name="action" value="check-filter">Run filter check</button>
</form>
</section>
{% endif %}
{% if filter_check %}
<section class="surface" id="filter-check" aria-label="Filter check results" data-live-status="mail-filter-check">
<header class="section-heading">
<h2>Filter check for {{ filter_check.domain.domain }}</h2>
{% if not filter_check.finished_at %}<a class="button secondary" href="?check={{ filter_check.pk }}#filter-check">Refresh status</a>{% endif %}
</header>
{% if filter_check.problem %}
<p class="section-text">{{ filter_check.problem }}</p>
{% elif not filter_check.finished_at %}
<p class="section-text" data-live-pending>{{ filter_check.state|capfirst }}</p>
{% else %}
<p class="section-text">SpamAssassin on <strong>{{ filter_check.report.node }}</strong></p>
<div class="table-scroll"><table>
<thead><tr><th scope="col">Sample</th><th scope="col">Expected</th><th scope="col">Observed</th><th scope="col">Score / threshold</th><th scope="col">Matching rules</th><th scope="col">Check</th></tr></thead>
<tbody>
{% for sample in filter_check.report.samples %}
<tr>
<th scope="row">{% if sample.sample == "gtube" %}GTUBE{% else %}Ordinary message{% endif %}</th>
<td>{{ sample.expected|capfirst }}</td><td>{{ sample.observed|capfirst }}</td>
<td>{{ sample.score }} / {{ sample.threshold }}</td><td>{{ sample.rules|join:", "|default:"—" }}</td>
<td>{% if sample.passed %}Passed{% else %}Unexpected result{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table></div>
{% endif %}
</section>
{% endif %}
<section class="surface editor-surface">
<header class="section-heading"><h2>Analyze a message</h2></header>
<form class="editor" method="post">
{% csrf_token %}
{% if errors %}<ul class="errorlist" role="alert">{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>{% endif %}
{{ form.as_div }}
<button class="button primary" type="submit">Analyze headers</button>
</form>
</section>
{% if report %}
<section class="surface">
<header class="section-heading">
<div>
<h2>Reported authentication</h2>
<p>Confirm the source of these headers before trusting the results. Independent verification needs the original signed message or SMTP session data.</p>
</div>
</header>
{% if report.from_domain %}
<p class="section-text">From domain <code>{{ report.from_domain }}</code>{% if dns_domain %} · <a href="{% url 'panel:mail_dns_check' dns_domain.pk %}{% if report.selectors %}?selectors={{ report.selectors|join:','|urlencode }}{% endif %}">Check mail DNS</a>{% endif %}</p>
{% endif %}
{% if report.authentication %}
<div class="table-scroll"><table>
<thead><tr><th scope="col">Reporting server</th><th scope="col">Method</th><th scope="col">Result</th><th scope="col">Domain</th><th scope="col">From alignment</th></tr></thead>
<tbody>
{% for item in report.authentication %}
<tr>
<th scope="row">{{ item.receiver }}</th>
<td>{{ item.method|upper }}</td>
<td>{{ item.verdict }}{% if item.reason %}<br><span class="heading-meta">{{ item.reason }}</span>{% endif %}</td>
<td>{{ item.identity|default:"Unavailable" }}</td>
<td>{% if item.alignment == "exact" %}Exact match{% elif item.alignment == "different" %}Different domains. Relaxed alignment unavailable{% else %}Unavailable{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table></div>
{% else %}
<p class="section-text">No readable SPF, DKIM or DMARC result was present.</p>
{% endif %}
</section>
<section class="surface">
<header class="section-heading"><h2>Reported spam verdict</h2></header>
{% if report.spam %}
<div class="table-scroll"><table>
<thead><tr><th scope="col">Source</th><th scope="col">Score</th><th scope="col">Threshold</th><th scope="col">Action</th><th scope="col">Matching rules</th></tr></thead>
<tbody>
{% for item in report.spam %}
<tr>
<th scope="row">{{ item.source }}</th>
<td>{{ item.score }}</td><td>{{ item.threshold }}</td><td>{{ item.action|default:"Unavailable" }}</td>
<td>{{ item.rules|join:", "|default:"Unavailable" }}</td>
</tr>
{% endfor %}
</tbody>
</table></div>
{% else %}
<p class="section-text">No readable spam verdict was present.</p>
{% endif %}
</section>
{% if report.queue_id %}
<section class="surface">
<header class="section-heading">
<div><h2>Delivery lookup</h2><p>Reported Postfix queue ID <code>{{ report.queue_id }}</code></p></div>
{% if mail_delivery_available %}<a class="button secondary" href="{% url 'panel:mail_delivery' %}?queue_id={{ report.queue_id }}{% if dns_domain %}&amp;domain={{ dns_domain.pk }}{% endif %}">Look up delivery</a>{% endif %}
</header>
</section>
{% endif %}
{% endif %}
{% endblock %}
+12 -1
View File
@@ -37,7 +37,7 @@ class PostfixProjectionTests(SimpleTestCase):
( (
"smtp", "smtp",
"D1234: to=<amy@else.test>, orig_to=<alias@tenant.test>, " "D1234: to=<amy@else.test>, orig_to=<alias@tenant.test>, "
"status=deferred (timeout)", "dsn=4.4.1, status=deferred (timeout)",
), ),
] ]
entries = [ entries = [
@@ -58,6 +58,17 @@ class PostfixProjectionTests(SimpleTestCase):
[entry["queue_id"] for entry in result["events"]], [entry["queue_id"] for entry in result["events"]],
["D1234", "C1234", "B1234"], ["D1234", "C1234", "B1234"],
) )
self.assertEqual(result["events"][0]["dsn"], "4.4.1")
request = MailDeliveryRequest("tenant.test", 1, 100, queue_id="D1234")
self.assertEqual(
MailDeliveryRequest.from_manifest(request.manifest()), request
)
filtered = project_delivery(entries, request)
self.assertEqual(
[entry["queue_id"] for entry in filtered["events"]], ["D1234"]
)
foreign = MailDeliveryRequest("tenant.test", 1, 100, queue_id="A1234")
self.assertEqual(project_delivery(entries, foreign)["events"], [])
@override_settings(LOCAL_MAILBOX_PROVISIONING=True) @override_settings(LOCAL_MAILBOX_PROVISIONING=True)
@@ -0,0 +1,145 @@
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django_otp import DEVICE_ID_SESSION_KEY
from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.mail_diagnostics import MailHeaderError, inspect_headers
from .models import HostingAccount, HostingMailDomain
HEADERS = """From: Sender <private-sender@sender.test>
Authentication-Results: mx.example.test;
spf=pass (a; nested (comment)) smtp.mailfrom=private-sender@sender.test;
dkim=neutral (invalid public key) header.d=sender.test;
dmarc=pass header.from=sender.test
DKIM-Signature: v=1; s=local; d=sender.test; b=signature
DKIM-Signature: v=1; s=unrelated; d=example.test; b=signature
X-Spam-Status: Yes, score=1000.0 required=5.0 tests=GTUBE autolearn=no
X-Spamd-Result: default: False [-1.50 / 12.00] CLEAN(-1.50)[]
X-Rspamd-Action: no action
X-Rspamd-Queue-Id: ABC123
private-message-body
Authentication-Results: bogus.test; spf=fail smtp.mailfrom=other.test
"""
class HeaderAnalysisTests(SimpleTestCase):
def test_summarizes_receiver_evidence_and_does_not_read_the_body(self):
report = inspect_headers(HEADERS)
self.assertEqual(report["from_domain"], "sender.test")
self.assertEqual(report["queue_id"], "ABC123")
self.assertEqual(report["selectors"], ("local",))
self.assertEqual(
[
(result.method, result.verdict, result.alignment)
for result in report["authentication"]
],
[
("spf", "pass", "exact"),
("dkim", "neutral", ""),
("dmarc", "pass", ""),
],
)
self.assertEqual(
[result.rules for result in report["spam"]],
[("GTUBE",), ("CLEAN",)],
)
self.assertEqual(report["spam"][1].action, "no action")
def test_incomplete_or_conflicting_headers(self):
report = inspect_headers(
"From: first@one.test\nFrom: second@two.test\n"
'Authentication-Results: mx.test; spf=pass reason="unterminated\n'
"X-Rspamd-Queue-Id: ABC123\nX-Rspamd-Queue-Id: ABD123\n"
)
self.assertEqual(report["from_domain"], "")
self.assertEqual(report["queue_id"], "")
self.assertEqual(report["authentication"], [])
self.assertEqual(report["spam"], [])
with self.assertRaises(MailHeaderError):
inspect_headers("Not a header")
with self.assertRaises(MailHeaderError):
inspect_headers("é" * 32769)
def test_extracts_a_postfix_queue_id_from_received_headers(self):
received = (
"Received: from sender.test by mail.example.test (Postfix) "
"with ESMTPSA id ABC123; Tue, 1 Dec 2026 10:00:00 +0000\n"
)
self.assertEqual(inspect_headers(received)["queue_id"], "ABC123")
ambiguous = received + received.replace("ABC123", "XYZ123")
self.assertEqual(inspect_headers(ambiguous)["queue_id"], "")
def test_applicable_domains_require_exact_match_for_exact_alignment(self):
report = inspect_headers(
"From: x@sender.test\nAuthentication-Results: mx.test;"
" dkim=pass header.d=sub.sender.test;"
" spf=fail smtp.mailfrom=sender.test;"
" dmarc=fail header.from=sender.test\n"
"X-Spam-Status: No, score=-1.0 required=5.0\n"
)
first, second, third = report["authentication"]
self.assertEqual(first.alignment, "different")
self.assertEqual(second.alignment, "")
self.assertEqual(third.verdict, "fail")
self.assertEqual(report["spam"][0].action, "Not marked as spam")
@override_settings(LOCAL_MAILBOX_PROVISIONING=True)
class MailDiagnosticsViewTests(TestCase):
def setUp(self):
self.url = reverse("panel:mail_diagnostics")
self.operator = get_user_model().objects.create_superuser("operator")
self.client.force_login(self.operator)
def verify_operator(self):
device = TOTPDevice.objects.create(user=self.operator, name="test")
session = self.client.session
session[DEVICE_ID_SESSION_KEY] = device.persistent_id
session.save()
def test_requires_verified_operator_session(self):
self.assertNotEqual(self.client.get(self.url).status_code, 200)
ordinary_user = get_user_model().objects.create_user("user")
device = TOTPDevice.objects.create(user=ordinary_user, name="test")
self.client.force_login(ordinary_user)
session = self.client.session
session[DEVICE_ID_SESSION_KEY] = device.persistent_id
session.save()
self.assertEqual(self.client.get(self.url).status_code, 403)
def test_displays_report_and_correlation_without_echoing_input(self):
self.verify_operator()
account = HostingAccount.objects.create(
name="Sender", primary_domain="sender.test"
)
domain = HostingMailDomain.objects.create(
account=account, domain=account.primary_domain
)
self.assertContains(self.client.get(self.url), "Analyze headers")
response = self.client.post(self.url, {"headers": HEADERS})
self.assertIn("no-store", response.headers["Cache-Control"])
self.assertContains(response, "GTUBE")
self.assertContains(response, "Invalid public key")
self.assertNotContains(response, "private-sender")
self.assertNotContains(response, "private-message-body")
link = reverse("panel:mail_dns_check", args=[domain.pk])
self.assertContains(response, f'{link}?selectors=local"')
self.assertContains(
self.client.get(f"{link}?selectors=local"), 'value="local"'
)
link = reverse("panel:mail_delivery")
self.assertContains(
response, f"{link}?queue_id=ABC123&amp;domain={domain.pk}"
)
self.assertContains(
self.client.get(f"{link}?queue_id=ABC123"), 'value="ABC123"'
)
def test_validation_does_not_echo_input(self):
self.verify_operator()
response = self.client.post(self.url, {"headers": "private text"})
self.assertContains(response, "Paste the original message headers.")
self.assertNotContains(response, "private text")
@@ -0,0 +1,166 @@
from subprocess import TimeoutExpired
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django_otp import DEVICE_ID_SESSION_KEY
from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.mail_filter_check import (
GTUBE,
SCAN_TIMEOUT,
MailFilterCheckRequest,
scan_result,
scan_sample,
validated_report,
)
from coulobre.mail_node import parse_mailbox_request
from .models import (
DomainServicePolicy,
HostingAccount,
HostingMailDomain,
MailFilterCheck,
)
from .tasks import run_mail_filter_check
ORDINARY = b"X-Spam-Status: No, score=-0.1 required=5.0 tests=none\n\n"
SPAM = b"X-Spam-Status: Yes, score=1000.0 required=5.0 tests=GTUBE\n\n"
def observed_results():
return {
"node": "mail.example.test",
"samples": [
scan_result("ordinary", ORDINARY),
scan_result("gtube", SPAM),
],
}
class FilterReceiverTests(SimpleTestCase):
def test_request_contains_only_a_domain_and_fixed_operation(self):
manifest = MailFilterCheckRequest("mail.example.test").manifest()
self.assertEqual(
parse_mailbox_request(manifest).domain, "mail.example.test"
)
with self.assertRaisesRegex(ValueError, "synthetic mail filter"):
parse_mailbox_request(manifest | {"message": "arbitrary input"})
@patch("coulobre.mail_filter_check.subprocess.run")
def test_scans_use_private_storage_and_avoid_network_and_learning(
self, run
):
run.return_value.stdout = SPAM
scan = scan_sample("gtube")
command = run.call_args.args[0]
self.assertIn("--property=DynamicUser=yes", command)
self.assertIn("--property=ProtectSystem=strict", command)
self.assertIn("--property=PrivateTmp=yes", command)
self.assertIn("--property=PrivateNetwork=yes", command)
self.assertIn("--property=SystemCallFilter=~@network-io", command)
self.assertIn("--property=SystemCallErrorNumber=EPERM", command)
self.assertIn("--local", command)
self.assertIn("--cf=bayes_auto_learn 0", command)
self.assertIn(GTUBE.encode("ascii"), run.call_args.kwargs["input"])
self.assertEqual(scan["rules"], ["GTUBE"])
self.assertEqual(run.call_args.kwargs["timeout"], SCAN_TIMEOUT)
run.side_effect = TimeoutExpired(command, SCAN_TIMEOUT)
with self.assertRaisesRegex(
ValueError, "isolated SpamAssassin scan failed"
):
scan_sample("ordinary")
def test_gtube_must_trigger_the_rule_and_the_spam_verdict(self):
report = observed_results()
self.assertTrue(
all(
result["passed"]
for result in validated_report(report)["samples"]
)
)
report["samples"][1]["rules"] = ["OTHER"]
self.assertFalse(validated_report(report)["samples"][1]["passed"])
report["samples"][1]["observed"] = {"unknown": "checker output"}
with self.assertRaisesRegex(ValueError, "invalid filter result"):
validated_report(report)
with self.assertRaisesRegex(ValueError, "readable verdict"):
scan_result("ordinary", b"From: mail@example.test\n\n")
@override_settings(LOCAL_MAILBOX_PROVISIONING=True)
class FilterCheckTests(TestCase):
def setUp(self):
self.url = reverse("panel:mail_diagnostics")
self.operator = get_user_model().objects.create_superuser(
"filter-operator"
)
self.login_verified(self.operator)
account = HostingAccount.objects.create(
name="Mail test account", primary_domain="sender.test"
)
self.domain = HostingMailDomain.objects.create(
account=account, domain=account.primary_domain
)
self.data = {"action": "check-filter", "domain": self.domain.pk}
def login_verified(self, user):
self.client.force_login(user)
device = TOTPDevice.objects.create(user=user, name="test")
session = self.client.session
session[DEVICE_ID_SESSION_KEY] = device.persistent_id
session.save()
@patch("coulobre.hosting.node_client.apply_on_local_node")
def test_queue_and_render_an_operator_owned_filter_check(self, apply):
response = self.client.post(self.url, self.data)
check = MailFilterCheck.objects.get()
result_url = f"{self.url}?check={check.pk}"
self.assertRedirects(response, result_url)
self.assertContains(self.client.get(result_url), "Queued")
self.assertContains(
self.client.post(self.url, self.data),
"Wait a minute between filter checks.",
)
apply.return_value = observed_results()
run_mail_filter_check.run(check.pk)
check.refresh_from_db()
self.assertEqual(check.problem, "")
request = apply.call_args.args[0]
self.assertEqual(request.domain, self.domain.domain)
response = self.client.get(result_url)
self.assertContains(response, "mail.example.test")
self.assertContains(response, "GTUBE")
self.assertContains(response, "Passed", count=2)
other = get_user_model().objects.create_superuser("other")
self.login_verified(other)
self.assertEqual(self.client.get(result_url).status_code, 404)
@patch("coulobre.hosting.node_client.apply_on_local_node")
def test_does_not_run_after_domain_moves_to_an_external_provider(
self, apply
):
self.client.post(self.url, self.data)
check = MailFilterCheck.objects.get()
DomainServicePolicy.objects.create(
account=self.domain.account,
domain=self.domain.domain,
mail_managed=False,
)
run_mail_filter_check.run(check.pk)
apply.assert_not_called()
check.refresh_from_db()
self.assertIn("no longer available", check.problem)
self.assertEqual(
self.client.get(f"{self.url}?check={check.pk}").status_code, 404
)
def test_verified_customer_cannot_queue_a_check(self):
self.login_verified(get_user_model().objects.create_user("customer"))
self.assertEqual(
self.client.post(self.url, self.data).status_code, 403
)
self.assertFalse(MailFilterCheck.objects.exists())
+6
View File
@@ -50,6 +50,7 @@ from .installation_views import (
) )
from .invitations import AcceptInvitation, ManageInvitation from .invitations import AcceptInvitation, ManageInvitation
from .mail_delivery_views import MailDeliveryView from .mail_delivery_views import MailDeliveryView
from .mail_diagnostics_views import MailDiagnosticsView
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
from .mail_policy_views import ( from .mail_policy_views import (
MailRoutingEditor, MailRoutingEditor,
@@ -196,6 +197,11 @@ urlpatterns = [
"mailboxes/<int:pk>/spam/", MailSpamEditor.as_view(), name="mail_spam" "mailboxes/<int:pk>/spam/", MailSpamEditor.as_view(), name="mail_spam"
), ),
path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"), path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"),
path(
"mail-diagnostics/",
MailDiagnosticsView.as_view(),
name="mail_diagnostics",
),
path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"), path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"),
path( path(
"mail-domains/<int:pk>/queue/change/", "mail-domains/<int:pk>/queue/change/",
+2
View File
@@ -297,6 +297,7 @@ NAVIGATION_ICONS = {
"spam": "shield", "spam": "shield",
"mail_queue_index": "queue", "mail_queue_index": "queue",
"mail_delivery": "mail", "mail_delivery": "mail",
"mail_diagnostics": "mail",
"backups": "archive", "backups": "archive",
"operator_backups": "archive", "operator_backups": "archive",
"system_backup": "archive", "system_backup": "archive",
@@ -446,6 +447,7 @@ def groups_for(request, *, customer, manager):
if user.is_superuser: if user.is_superuser:
admin_tools.extend( admin_tools.extend(
( (
link("mail_diagnostics", "Mail diagnostics"),
link("theme_management", "Themes"), link("theme_management", "Themes"),
link("announcements", "Message"), link("announcements", "Message"),
link("directadmin_guide", "Import"), link("directadmin_guide", "Import"),
+21 -2
View File
@@ -11,6 +11,7 @@ MAX_AGE = 7 * 24 * 60 * 60
MAX_ENTRIES = 10000 MAX_ENTRIES = 10000
MAX_RESULTS = 40 MAX_RESULTS = 40
SERVICES = {"qmgr", "smtpd", "smtp", "lmtp", "local", "virtual", "pipe"} SERVICES = {"qmgr", "smtpd", "smtp", "lmtp", "local", "virtual", "pipe"}
QUEUE_ID = re.compile(r"\A[A-Za-z0-9]{5,32}\Z")
LINE = re.compile(r"([A-Za-z0-9]{5,32}): (.*)") LINE = re.compile(r"([A-Za-z0-9]{5,32}): (.*)")
ADDRESS = re.compile(r"[^<>\s\x00-\x1f]{1,254}") ADDRESS = re.compile(r"[^<>\s\x00-\x1f]{1,254}")
SENDER = re.compile(r"^from=<([^<>]*)>,") SENDER = re.compile(r"^from=<([^<>]*)>,")
@@ -19,6 +20,7 @@ SASL = re.compile(
r"^client=[^,]+, sasl_method=[A-Za-z0-9_-]+, sasl_username=([^,\s]+)" r"^client=[^,]+, sasl_method=[A-Za-z0-9_-]+, sasl_username=([^,\s]+)"
) )
STATUS = re.compile(r"(?:^|, )status=(sent|deferred|bounced|expired)\b") STATUS = re.compile(r"(?:^|, )status=(sent|deferred|bounced|expired)\b")
DSN = re.compile(r"(?:^|, )dsn=([245]\.\d{1,3}\.\d{1,3}), status=")
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -28,6 +30,7 @@ class MailDeliveryRequest:
end: int end: int
sender: str = "" sender: str = ""
recipient: str = "" recipient: str = ""
queue_id: str = ""
def __post_init__(self): def __post_init__(self):
object.__setattr__(self, "domain", canonical_domain(self.domain)) object.__setattr__(self, "domain", canonical_domain(self.domain))
@@ -45,9 +48,13 @@ class MailDeliveryRequest:
query and not ADDRESS.fullmatch(query) query and not ADDRESS.fullmatch(query)
): ):
raise ValueError("Use an email address for the filter.") raise ValueError("Use an email address for the filter.")
if not isinstance(self.queue_id, str) or (
self.queue_id and not QUEUE_ID.fullmatch(self.queue_id)
):
raise ValueError("Enter a valid Postfix queue ID.")
def manifest(self): def manifest(self):
return { manifest = {
"operation": OPERATION, "operation": OPERATION,
"domain": self.domain, "domain": self.domain,
"start": self.start, "start": self.start,
@@ -55,11 +62,18 @@ class MailDeliveryRequest:
"sender": self.sender, "sender": self.sender,
"recipient": self.recipient, "recipient": self.recipient,
} }
if self.queue_id:
manifest["queue_id"] = self.queue_id
return manifest
@classmethod @classmethod
def from_manifest(cls, data): def from_manifest(cls, data):
fields = {"operation", "domain", "start", "end", "sender", "recipient"} fields = {"operation", "domain", "start", "end", "sender", "recipient"}
if data.keys() != fields or data["operation"] != OPERATION: if (
not isinstance(data, dict)
or data.keys() not in (fields, fields | {"queue_id"})
or data["operation"] != OPERATION
):
raise ValueError("Expected a mail delivery request.") raise ValueError("Expected a mail delivery request.")
return cls( return cls(
data["domain"], data["domain"],
@@ -67,6 +81,7 @@ class MailDeliveryRequest:
data["end"], data["end"],
data["sender"], data["sender"],
data["recipient"], data["recipient"],
data.get("queue_id", ""),
) )
@@ -107,6 +122,8 @@ def project_delivery(lines, request):
if not match: if not match:
continue continue
queue_id, text = match.groups() queue_id, text = match.groups()
if request.queue_id and queue_id != request.queue_id:
continue
if service == "qmgr": if service == "qmgr":
if text == "removed": if text == "removed":
envelopes.pop(queue_id, None) envelopes.pop(queue_id, None)
@@ -141,6 +158,7 @@ def project_delivery(lines, request):
original.casefold(), original.casefold(),
): ):
continue continue
dsn = DSN.search(text, addresses.end() - 2, status.end())
records.append( records.append(
{ {
"queue_id": queue_id, "queue_id": queue_id,
@@ -149,6 +167,7 @@ def project_delivery(lines, request):
"recipient": recipient, "recipient": recipient,
"original_recipient": original, "original_recipient": original,
"status": status[1], "status": status[1],
"dsn": dsn[1] if dsn else "",
} }
) )
return { return {
+297
View File
@@ -0,0 +1,297 @@
import re
import shlex
from dataclasses import dataclass
from email import policy
from email.parser import Parser
from .domain_names import canonical_domain
from .mail_delivery import QUEUE_ID
from .mail_dns import MAX_SELECTORS, SELECTOR
MAX_MESSAGE_BYTES = 65536
MAX_AUTH_RESULTS = 30
MAX_RULES = 50
AUTH_METHODS = {"spf", "dkim", "dmarc"}
AUTH_VERDICTS = {
"pass",
"fail",
"softfail",
"neutral",
"none",
"policy",
"temperror",
"permerror",
}
AUTH_REASONS = {
("dkim", "invalid public key"): "Invalid public key",
("dkim", "key not found"): "Signing key not found",
("dkim", "body hash did not verify"): "Message body hash did not match",
("dkim", "signature did not verify"): "Signature did not verify",
}
RULE = re.compile(r"[A-Za-z][A-Za-z0-9_]{0,63}")
SPAM_STATUS = re.compile(
r"^(Yes|No),\s+score=(-?\d{1,8}(?:\.\d{1,8})?)"
r"\s+required=(-?\d{1,8}(?:\.\d{1,8})?)"
r"(?:\s+tests=([A-Za-z0-9_,\s]+?))?(?=\s+\w+=|$)",
re.IGNORECASE,
)
RSPAMD_STATUS = re.compile(
r"^(?:\[[^]]{1,30}\]|[\w-]{1,30}:\s+(?:True|False))\s*"
r"\[(-?\d{1,8}(?:\.\d{1,8})?)\s*/\s*"
r"(-?\d{1,8}(?:\.\d{1,8})?)\]"
)
RSPAMD_RULE = re.compile(r"(?:^|\s)([A-Z][A-Z0-9_]{0,63})\(-?\d")
POSTFIX_RECEIVED = re.compile(
r"\bby\s+(\S+)\s+\(Postfix\)\s+with\s+\w+\s+"
r"id\s+([A-Za-z0-9]{5,32})(?=\s|;|$)",
re.IGNORECASE,
)
RSPAMD_ACTIONS = {
"no action",
"greylist",
"add header",
"rewrite subject",
"soft reject",
"reject",
"discard",
"quarantine",
}
class MailHeaderError(ValueError):
pass
@dataclass(frozen=True)
class AuthenticationResult:
receiver: str
method: str
verdict: str
identity: str
alignment: str
reason: str
@dataclass(frozen=True)
class SpamResult:
source: str
score: str
threshold: str
action: str
rules: tuple[str, ...]
def normalized_domain(value):
try:
return canonical_domain(value)
except ValueError:
return ""
def split_authentication_header(value):
"""Split fields outside comments and quoted text."""
fields = []
field = []
comments = []
comment = []
depth = 0
quote = False
escaped = False
for char in value:
if escaped:
if not depth:
field.append(char)
escaped = False
elif char == "\\" and (depth or quote):
escaped = True
if quote and not depth:
field.append(char)
elif depth:
if char == "(":
depth += 1
elif char == ")":
depth -= 1
if not depth:
comments.append("".join(comment).strip().lower())
comment = []
elif depth == 1:
comment.append(char)
elif char == '"':
quote = not quote
field.append(char)
elif quote:
field.append(char)
elif char == "(":
depth = 1
field.append(" ")
elif char == ";":
fields.append(("".join(field).strip(), comments))
field = []
comments = []
else:
field.append(char)
if depth or quote or escaped:
return ()
fields.append(("".join(field).strip(), comments))
return fields
def identity_for(method, attributes):
if method == "spf":
sender = attributes.get("smtp.mailfrom", "")
if sender == "<>":
return normalized_domain(attributes.get("smtp.helo", ""))
return normalized_domain(sender.strip("<>").rpartition("@")[2])
if method == "dkim":
return normalized_domain(attributes.get("header.d", ""))
return normalized_domain(attributes.get("header.from", ""))
def reported_authentication(message, from_domain):
results = []
for value in message.get_all("Authentication-Results", ()):
fields = split_authentication_header(str(value))
if not fields or not fields[0][0]:
continue
receiver = normalized_domain(fields[0][0].split()[0])
if not receiver:
continue
for field, comments in fields[1:]:
field = re.sub(r"^([a-z]+)(?:/\d+)?\s*=\s*", r"\1=", field)
try:
parts = shlex.split(field)
except ValueError:
continue
if not parts:
continue
method, _, verdict = parts[0].lower().partition("=")
if method not in AUTH_METHODS or verdict not in AUTH_VERDICTS:
continue
attributes = dict(
part.split("=", 1) for part in parts[1:] if "=" in part
)
identity = identity_for(method, attributes)
explanations = [attributes.get("reason", "").lower(), *comments]
reason = next(
(
AUTH_REASONS[method, explanation]
for explanation in explanations
if (method, explanation) in AUTH_REASONS
),
"",
)
alignment = ""
if (
method != "dmarc"
and verdict == "pass"
and from_domain
and identity
):
alignment = "exact" if identity == from_domain else "different"
results.append(
AuthenticationResult(
receiver, method, verdict, identity, alignment, reason
)
)
if len(results) >= MAX_AUTH_RESULTS:
return results
return results
def reported_spam(message):
results = []
for value in message.get_all("X-Spam-Status", ())[:5]:
if match := SPAM_STATUS.match(str(value)):
spam, score, threshold, tests = match.groups()
rules = tuple(
rule
for rule in re.split(r"[,\s]+", tests or "")
if RULE.fullmatch(rule)
)[:MAX_RULES]
results.append(
SpamResult(
"SpamAssassin header",
score,
threshold,
"Marked as spam"
if spam.lower() == "yes"
else "Not marked as spam",
rules,
)
)
action = str(message.get("X-Rspamd-Action", "")).strip().lower()
for value in message.get_all("X-Spamd-Result", ())[:5]:
value = str(value)
if match := RSPAMD_STATUS.match(value):
score, threshold = match.groups()
rules = tuple(RSPAMD_RULE.findall(value[match.end() :]))[
:MAX_RULES
]
results.append(
SpamResult(
"Rspamd header",
score,
threshold,
action if action in RSPAMD_ACTIONS else "",
rules,
)
)
return results
def reported_selectors(message, from_domain):
selectors = {}
for value in message.get_all("DKIM-Signature", ()):
tags = {}
for tag in str(value).split(";"):
name, _, item = tag.partition("=")
tags[name.strip()] = item.strip().lower()
selector = tags.get("s", "")
if (
normalized_domain(tags.get("d", "")) == from_domain
and SELECTOR.fullmatch(selector)
and len(f"{selector}._domainkey.{from_domain}") <= 253
):
selectors[selector] = None
if len(selectors) >= MAX_SELECTORS:
break
return tuple(selectors)
def reported_queue_id(message):
queue_ids = {
str(value).strip()
for value in message.get_all("X-Rspamd-Queue-Id", ())
}
if not queue_ids:
queue_ids = {
match[2]
for value in message.get_all("Received", ())
if (match := POSTFIX_RECEIVED.search(str(value)))
and normalized_domain(match[1])
}
queue_id = next(iter(queue_ids)) if len(queue_ids) == 1 else ""
return queue_id if QUEUE_ID.fullmatch(queue_id) else ""
def inspect_headers(data):
if len(data.encode("utf-8")) > MAX_MESSAGE_BYTES:
raise MailHeaderError("Paste up to 64 KiB of mail headers.")
headers = re.split(r"\r?\n\r?\n|\r\r", data, maxsplit=1)[0]
message = Parser(policy=policy.default).parsestr(headers, headersonly=True)
if not len(message):
raise MailHeaderError("Paste the original message headers.")
from_domain = ""
if len(message.get_all("From", ())) == 1:
addresses = message["From"].addresses
if len(addresses) == 1:
from_domain = normalized_domain(addresses[0].domain)
return {
"from_domain": from_domain,
"authentication": reported_authentication(message, from_domain),
"spam": reported_spam(message),
"selectors": reported_selectors(message, from_domain)
if from_domain
else (),
"queue_id": reported_queue_id(message),
}
+199
View File
@@ -0,0 +1,199 @@
import re
import socket
import subprocess
from dataclasses import dataclass
from email.utils import formatdate
from pathlib import Path
from .domain_names import canonical_domain
from .mail_diagnostics import MAX_RULES, RULE, SPAM_STATUS
OPERATION = "check_spam_filter"
SCAN_TIMEOUT = 30
SPAMASSASSIN = Path("/usr/bin/spamassassin")
# Public-domain sample from https://spamassassin.apache.org/gtube/.
GTUBE = "XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X"
SAMPLES = ("ordinary", "gtube")
NUMBER = re.compile(r"-?\d{1,8}(?:\.\d{1,8})?", re.ASCII)
NODE = re.compile(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}", re.ASCII)
SCAN_PROPERTIES = (
"Type=exec",
"DynamicUser=yes",
"NoNewPrivileges=yes",
"ProtectSystem=strict",
"ProtectHome=yes",
"PrivateTmp=yes",
"PrivateDevices=yes",
"PrivateNetwork=yes",
"SystemCallFilter=~@network-io",
"SystemCallErrorNumber=EPERM",
"RuntimeMaxSec=25s",
"TimeoutStopSec=3s",
"MemoryMax=256M",
"TasksMax=16",
)
SCAN_OPTIONS = (
"--local",
"--nocreate-prefs",
"--prefs-file=/dev/null",
"--cf=use_bayes 0",
"--cf=bayes_auto_learn 0",
"--cf=report_safe 0",
"--cf=add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ "
"tests=_TESTS_ diagnostic=1",
)
@dataclass(frozen=True)
class MailFilterCheckRequest:
domain: str
def __post_init__(self):
if not isinstance(self.domain, str):
raise ValueError("Expected a managed mail domain.")
object.__setattr__(self, "domain", canonical_domain(self.domain))
def manifest(self):
return {"operation": OPERATION, "domain": self.domain}
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys() != {"operation", "domain"}
or data["operation"] != OPERATION
):
raise ValueError("Expected a synthetic mail filter request.")
return cls(data["domain"])
def synthetic_message(sample):
body = (
"Hello, this is a routine mail filter diagnostic.\n"
if sample == "ordinary"
else f"{GTUBE}\n"
)
return (
"From: Filter sender <sender@example.org>\n"
"To: Filter recipient <recipient@example.net>\n"
"Subject: Mail filter diagnostic\n"
f"Date: {formatdate(usegmt=True)}\n"
f"Message-ID: <coulobre-filter-{sample}@example.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=us-ascii\n"
"\n"
f"{body}"
).encode("ascii")
def scan_sample(sample):
command = [
"/usr/bin/systemd-run",
f"--unit=coulobre-spam-filter-check-{sample}",
"--quiet",
"--wait",
"--pipe",
"--collect",
"--setenv=HOME=/tmp",
"--setenv=LC_ALL=C",
*(f"--property={option}" for option in SCAN_PROPERTIES),
str(SPAMASSASSIN),
*SCAN_OPTIONS,
]
try:
# The scanner sees a pipe containing only the synthetic message.
result = subprocess.run(
command,
input=synthetic_message(sample),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True,
timeout=SCAN_TIMEOUT,
)
except (OSError, subprocess.SubprocessError):
raise ValueError(
"The isolated SpamAssassin scan failed. Check this mail node's "
"service journal and SpamAssassin configuration."
) from None
return scan_result(sample, result.stdout)
def scan_result(sample, scanned):
from email.parser import BytesHeaderParser
if len(scanned) > 65536:
raise ValueError("SpamAssassin returned an oversized scan result.")
message = BytesHeaderParser().parsebytes(scanned)
match = SPAM_STATUS.match(message.get("X-Spam-Status", ""))
if not match:
raise ValueError("SpamAssassin did not return a readable verdict.")
verdict, score, threshold, rules = match.groups()
return {
"sample": sample,
"observed": "spam" if verdict.lower() == "yes" else "clean",
"score": score,
"threshold": threshold,
"rules": [
rule
for rule in re.split(r"[,\s]+", rules or "")
if RULE.fullmatch(rule) and rule != "none"
][:MAX_RULES],
}
def check_spam_filter():
if not SPAMASSASSIN.is_file():
raise ValueError(
"SpamAssassin is unavailable on this mail node. "
"This check covers the SpamAssassin inbound filter."
)
return {
"node": socket.gethostname(),
"samples": [scan_sample(sample) for sample in SAMPLES],
}
def validated_report(reply):
node = reply.get("node")
scans = reply.get("samples")
if (
not isinstance(node, str)
or not NODE.fullmatch(node)
or not isinstance(scans, list)
or len(scans) != len(SAMPLES)
):
raise ValueError("The mail node returned an invalid filter report.")
results = []
for sample, result in zip(SAMPLES, scans, strict=True):
if (
not isinstance(result, dict)
or result.keys()
!= {"sample", "observed", "score", "threshold", "rules"}
or result["sample"] != sample
or result["observed"] not in ("clean", "spam")
or any(
not isinstance(result[key], str)
or not NUMBER.fullmatch(result[key])
for key in ("score", "threshold")
)
or not isinstance(result["rules"], list)
or len(result["rules"]) > MAX_RULES
or any(
not isinstance(rule, str) or not RULE.fullmatch(rule)
for rule in result["rules"]
)
):
raise ValueError(
"The mail node returned an invalid filter result."
)
expected = "spam" if sample == "gtube" else "clean"
results.append(
result
| {
"expected": expected,
"passed": result["observed"] == expected
and (sample != "gtube" or "GTUBE" in result["rules"]),
}
)
return {"node": node, "samples": results}
+7
View File
@@ -171,6 +171,8 @@ class MailboxRemovalRequest(RetirementRequest):
def parse_mailbox_request(data): def parse_mailbox_request(data):
from .mail_delivery import OPERATION, MailDeliveryRequest from .mail_delivery import OPERATION, MailDeliveryRequest
from .mail_filter_check import OPERATION as FILTER_OPERATION
from .mail_filter_check import MailFilterCheckRequest
from .mail_policy import OPERATIONS, parse_mail_policy from .mail_policy import OPERATIONS, parse_mail_policy
from .mail_queue import MailQueueAction, MailQueueRequest from .mail_queue import MailQueueAction, MailQueueRequest
from .smtp_application import ( from .smtp_application import (
@@ -190,6 +192,8 @@ def parse_mailbox_request(data):
return parse_mailbox_password_request(data) return parse_mailbox_password_request(data)
if isinstance(data, dict) and data.get("operation") == OPERATION: if isinstance(data, dict) and data.get("operation") == OPERATION:
return MailDeliveryRequest.from_manifest(data) return MailDeliveryRequest.from_manifest(data)
if isinstance(data, dict) and data.get("operation") == FILTER_OPERATION:
return MailFilterCheckRequest.from_manifest(data)
if isinstance(data, dict) and data.get("operation") in { if isinstance(data, dict) and data.get("operation") in {
"inspect_queue", "inspect_queue",
"inspect_queue_entries", "inspect_queue_entries",
@@ -247,6 +251,7 @@ def mailbox_request_identity(spec):
def apply_mailbox_request(request): def apply_mailbox_request(request):
from .mail_delivery import MailDeliveryRequest, inspect_delivery from .mail_delivery import MailDeliveryRequest, inspect_delivery
from .mail_filter_check import MailFilterCheckRequest, check_spam_filter
from .mail_policy import MailRouting, MailVacation from .mail_policy import MailRouting, MailVacation
from .mail_queue import ( from .mail_queue import (
MailQueueAction, MailQueueAction,
@@ -269,6 +274,8 @@ def apply_mailbox_request(request):
return apply_mailbox_password_request(request) return apply_mailbox_password_request(request)
if isinstance(request, MailDeliveryRequest): if isinstance(request, MailDeliveryRequest):
return inspect_delivery(request) return inspect_delivery(request)
if isinstance(request, MailFilterCheckRequest):
return check_spam_filter()
if isinstance(request, MailQueueRequest): if isinstance(request, MailQueueRequest):
return inspect_queue(request) return inspect_queue(request)
if isinstance(request, MailQueueAction): if isinstance(request, MailQueueAction):
+5 -2
View File
@@ -12,6 +12,7 @@ from uuid import uuid4
from . import node_maintenance, node_setup, receiver_scope from . import node_maintenance, node_setup, receiver_scope
from .dns_node import DnsZone from .dns_node import DnsZone
from .mail_filter_check import MailFilterCheckRequest
from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request
from .mail_policy import MailRouting from .mail_policy import MailRouting
from .mail_queue import MailQueueRequest from .mail_queue import MailQueueRequest
@@ -59,6 +60,7 @@ class ReceiverScopeTests(TestCase):
mailbox, mailbox,
MailboxQuotaUpdate(mailbox), MailboxQuotaUpdate(mailbox),
MailQueueRequest(mailbox.domain), MailQueueRequest(mailbox.domain),
MailFilterCheckRequest(mailbox.domain),
MailRouting(mailbox.domain, {}), MailRouting(mailbox.domain, {}),
ServiceAccessRequest(mailbox, True), ServiceAccessRequest(mailbox, True),
RetirementRequest(mailbox, str(uuid4())), RetirementRequest(mailbox, str(uuid4())),
@@ -76,8 +78,9 @@ class ReceiverScopeTests(TestCase):
for request in requests: for request in requests:
check_request("mail", request) check_request("mail", request)
for domain in ("beta.example.test", "sub.alpha.example.test"): for domain in ("beta.example.test", "sub.alpha.example.test"):
with self.assertRaisesRegex(ValueError, "not assigned"): for request_type in (MailQueueRequest, MailFilterCheckRequest):
check_request("mail", MailQueueRequest(domain)) with self.assertRaisesRegex(ValueError, "not assigned"):
check_request("mail", request_type(domain))
def test_empty_scope_allows_probes_and_denies_managed_domains(self): def test_empty_scope_allows_probes_and_denies_managed_domains(self):
with ( with (