Email for professionals and teams
fix(security): never let a header-forged pass hide a real authentication failure (#216)
Hieu Nguyen (Jack)3227ae427025
diff --git a/src/lib/spam/analyzers/authentication.ts b/src/lib/spam/analyzers/authentication.tsindex adf95a8..6b21fe8 100644--- a/src/lib/spam/analyzers/authentication.ts+++ b/src/lib/spam/analyzers/authentication.ts@@ -2,6 +2,8 @@ import type { ProviderVerdicts, SpamSignal } from "../types";import { SPAM_WEIGHTS } from "../weights";import { findHeader } from "./utils";+/** Cloudflare Email Routing writes its verdicts under this authserv-id. */+const TRUSTED_AUTHSERV_ID = "mx.cloudflare.net";const METHODS = ["dmarc", "dkim", "spf"] as const;function methodSignal(method: (typeof METHODS)[number], result: string | undefined): SpamSignal | null {@@ -12,7 +14,8 @@ function methodSignal(method: (typeof METHODS)[number], result: string | undefin/*** SPF, DKIM and DMARC results. Verdicts from the receiving provider (SES) win; otherwise only an- * Authentication-Results header written by Cloudflare is trusted, since senders can add their own.+ * Authentication-Results clause written by Cloudflare is read. Self-hosted SMTP verifies nothing, so+ * mail received there carries no authentication signal and the authentication policy never fires.*/export function analyzeAuthentication(headers?: Record<string, string>, verdicts?: ProviderVerdicts): SpamSignal[] {const signals: SpamSignal[] = [];@@ -29,10 +32,21 @@ export function analyzeAuthentication(headers?: Record<string, string>, verdictsconst value = findHeader(headers, "authentication-results");if (!value) return [];- const authservId = value.split(";", 1)[0]?.trim().toLowerCase() ?? "";- if (!/(^|\.)cloudflare\.(com|net)$/.test(authservId)) return [];+ // A sender can add Authentication-Results lines of its own, and duplicate headers arrive joined,+ // so look at every clause: only Cloudflare's exact authserv-id counts, a failure in any clause+ // wins, and a pass needs all of them to agree. A forged pass can then never hide a real fail.+ const results: Record<string, string[]> = { dmarc: [], dkim: [], spf: [] };+ for (const clause of value.split(/,\s*(?=[a-z0-9-]+(?:\.[a-z0-9-]+)+\s*;)/i)) {+ const authservId = clause.split(";", 1)[0]?.trim().toLowerCase() ?? "";+ if (authservId !== TRUSTED_AUTHSERV_ID) continue;+ for (const method of METHODS) {+ const result = clause.match(new RegExp(`(?:^|[;\\s])${method}=([a-z]+)`, "i"))?.[1]?.toLowerCase();+ if (result) results[method].push(result);+ }+ }for (const method of METHODS) {- const result = value.match(new RegExp(`(?:^|[;\\s])${method}=([a-z]+)`, "i"))?.[1]?.toLowerCase();+ const seen = results[method];+ const result = seen.includes("fail") ? "fail" : seen.length && seen.every((entry) => entry === "pass") ? "pass" : undefined;const signal = methodSignal(method, result);if (signal) signals.push(signal);}