Compare commits

...
2 Commits
Author SHA1 Message Date
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
12 changed files with 692 additions and 7 deletions

No files matched your search

+20
View File
@@ -2513,6 +2513,26 @@ the mail node's Coulobre state and `/var/lib/coulobre-vacation` in your
server backup if you use these features. Maildir-only archives contain
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 and provision mail DNS
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.generic import FormView
from coulobre.mail_delivery import MailDeliveryRequest
from coulobre.mail_delivery import QUEUE_ID, MailDeliveryRequest
from .access import customer_for_user
from .domain_policies import policy_for
@@ -35,6 +35,9 @@ class MailDeliveryForm(forms.Form):
)
sender = 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):
super().__init__(*args, **kwargs)
@@ -55,6 +58,7 @@ class MailDeliveryForm(forms.Form):
now,
data["sender"],
data["recipient"],
data["queue_id"],
)
return data
@@ -88,7 +92,10 @@ class MailDeliveryView(FormView):
return super().get_form_kwargs() | {"domains": self.domain_scope()}
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):
search_id = self.request.GET.get("search")
@@ -0,0 +1,97 @@
from django import forms
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 .installation_features import panel_feature_allowed
from .models import HostingMailDomain
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):
return super().get_context_data(
mail_delivery_available=panel_feature_allowed(
"LOCAL_MAILBOX_PROVISIONING"
),
**kwargs,
)
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:
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])
return initial
@@ -15,11 +15,11 @@
{% if search.problem %}<p class="notice">{{ search.problem }}</p>
{% elif not search.finished_at %}<p class="section-text">{{ search.state|capfirst }}</p>
{% 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>
<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 %}
<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>
</table></div>
{% if page_obj.has_other_pages %}
@@ -0,0 +1,71 @@
{% extends "hosting/workspace_page.html" %}
{% block title %}Mail diagnostics · Coulobre Panel{% endblock %}
{% block page_title %}Mail diagnostics{% endblock %}
{% block page_content %}
<section class="surface editor-surface">
<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",
"D1234: to=<amy@else.test>, orig_to=<alias@tenant.test>, "
"status=deferred (timeout)",
"dsn=4.4.1, status=deferred (timeout)",
),
]
entries = [
@@ -58,6 +58,17 @@ class PostfixProjectionTests(SimpleTestCase):
[entry["queue_id"] for entry in result["events"]],
["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)
@@ -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")
+6
View File
@@ -50,6 +50,7 @@ from .installation_views import (
)
from .invitations import AcceptInvitation, ManageInvitation
from .mail_delivery_views import MailDeliveryView
from .mail_diagnostics_views import MailDiagnosticsView
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
from .mail_policy_views import (
MailRoutingEditor,
@@ -196,6 +197,11 @@ urlpatterns = [
"mailboxes/<int:pk>/spam/", MailSpamEditor.as_view(), name="mail_spam"
),
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-domains/<int:pk>/queue/change/",
+2
View File
@@ -297,6 +297,7 @@ NAVIGATION_ICONS = {
"spam": "shield",
"mail_queue_index": "queue",
"mail_delivery": "mail",
"mail_diagnostics": "mail",
"backups": "archive",
"operator_backups": "archive",
"system_backup": "archive",
@@ -446,6 +447,7 @@ def groups_for(request, *, customer, manager):
if user.is_superuser:
admin_tools.extend(
(
link("mail_diagnostics", "Mail diagnostics"),
link("theme_management", "Themes"),
link("announcements", "Message"),
link("directadmin_guide", "Import"),
+21 -2
View File
@@ -11,6 +11,7 @@ MAX_AGE = 7 * 24 * 60 * 60
MAX_ENTRIES = 10000
MAX_RESULTS = 40
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}): (.*)")
ADDRESS = re.compile(r"[^<>\s\x00-\x1f]{1,254}")
SENDER = re.compile(r"^from=<([^<>]*)>,")
@@ -19,6 +20,7 @@ SASL = re.compile(
r"^client=[^,]+, sasl_method=[A-Za-z0-9_-]+, sasl_username=([^,\s]+)"
)
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)
@@ -28,6 +30,7 @@ class MailDeliveryRequest:
end: int
sender: str = ""
recipient: str = ""
queue_id: str = ""
def __post_init__(self):
object.__setattr__(self, "domain", canonical_domain(self.domain))
@@ -45,9 +48,13 @@ class MailDeliveryRequest:
query and not ADDRESS.fullmatch(query)
):
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):
return {
manifest = {
"operation": OPERATION,
"domain": self.domain,
"start": self.start,
@@ -55,11 +62,18 @@ class MailDeliveryRequest:
"sender": self.sender,
"recipient": self.recipient,
}
if self.queue_id:
manifest["queue_id"] = self.queue_id
return manifest
@classmethod
def from_manifest(cls, data):
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.")
return cls(
data["domain"],
@@ -67,6 +81,7 @@ class MailDeliveryRequest:
data["end"],
data["sender"],
data["recipient"],
data.get("queue_id", ""),
)
@@ -107,6 +122,8 @@ def project_delivery(lines, request):
if not match:
continue
queue_id, text = match.groups()
if request.queue_id and queue_id != request.queue_id:
continue
if service == "qmgr":
if text == "removed":
envelopes.pop(queue_id, None)
@@ -141,6 +158,7 @@ def project_delivery(lines, request):
original.casefold(),
):
continue
dsn = DSN.search(text, addresses.end() - 2, status.end())
records.append(
{
"queue_id": queue_id,
@@ -149,6 +167,7 @@ def project_delivery(lines, request):
"recipient": recipient,
"original_recipient": original,
"status": status[1],
"dsn": dsn[1] if dsn else "",
}
)
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),
}