Skip to content

Email for professionals and teams

fix(security): sign the X-Mailflare-Forwarded loop-guard marker (#223)

Hieu Nguyen (Jack)f070a70be365
diff --git a/src/lib/email/account-forwarding.ts b/src/lib/email/account-forwarding.ts
index 29cea81..e378175 100644
--- a/src/lib/email/account-forwarding.ts
+++ b/src/lib/email/account-forwarding.ts
@@ -7,6 +7,39 @@ import { getLicenseEntitlements } from "@/lib/licenses/service";
export const MAILFLARE_FORWARDED_HEADER = "X-Mailflare-Forwarded";
+/** Server-only secrets the loop-guard marker can be keyed with, in order of preference. */
+function markerSecret(env: CloudflareEnv): string | null {
+ return env.CF_TOKEN || env.CF_API_KEY || env.INBOUND_WEBHOOK_SECRET || null;
+}
+
+async function markerMac(secret: string): Promise<string> {
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(`mailflare-forwarded\n${secret}`), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode("forwarded"));
+ return Array.from(new Uint8Array(mac), (byte) => byte.toString(16).padStart(2, "0")).join("");
+}
+
+/**
+ * The loop-guard marker added to mail we forward. It is keyed with a server secret, so a sender
+ * cannot add a bare `X-Mailflare-Forwarded: 1` to switch forwarding off. It is not bound to a
+ * recipient because a forward between two of our own mailboxes must still be recognised. Without
+ * any server secret configured it falls back to the unsigned "1".
+ */
+export async function forwardedMarker(env: CloudflareEnv): Promise<string> {
+ const secret = markerSecret(env);
+ return secret ? `v1.${await markerMac(secret)}` : "1";
+}
+
+export async function isForwardedMarkerValid(env: CloudflareEnv, value: string | null | undefined): Promise<boolean> {
+ if (!value) return false;
+ const secret = markerSecret(env);
+ if (!secret) return value === "1";
+ const expected = `v1.${await markerMac(secret)}`;
+ if (value.length !== expected.length) return false;
+ let diff = 0;
+ for (let index = 0; index < expected.length; index += 1) diff |= expected.charCodeAt(index) ^ value.charCodeAt(index);
+ return diff === 0;
+}
+
export async function getAccountForwardingDestination(
env: CloudflareEnv,
recipient: string,
diff --git a/src/lib/email/incoming.ts b/src/lib/email/incoming.ts
index 9edcce7..cb1e22b 100644
--- a/src/lib/email/incoming.ts
+++ b/src/lib/email/incoming.ts
@@ -1,6 +1,6 @@
import { getDb } from "@/db";
import { recordRuleMatch, resolveInboundAddress, type RoutingDecision } from "@/lib/email/routing";
-import { MAILFLARE_FORWARDED_HEADER } from "@/lib/email/account-forwarding";
+import { forwardedMarker, MAILFLARE_FORWARDED_HEADER } from "@/lib/email/account-forwarding";
/**
* Resolves the routing decision for a live inbound message. Used by the Worker `email`
@@ -38,12 +38,13 @@ export async function resolveIncomingMail(
* The destination must be a verified destination address in Cloudflare Email Routing.
*/
export async function forwardMessage(
+ env: CloudflareEnv,
message: ForwardableEmailMessage,
destination: string,
): Promise<boolean> {
try {
const headers = new Headers();
- headers.set(MAILFLARE_FORWARDED_HEADER, "1");
+ headers.set(MAILFLARE_FORWARDED_HEADER, await forwardedMarker(env));
await message.forward(destination, headers);
return true;
} catch (error) {
diff --git a/src/lib/email/intake.ts b/src/lib/email/intake.ts
index 610b99f..71bc817 100644
--- a/src/lib/email/intake.ts
+++ b/src/lib/email/intake.ts
@@ -1,4 +1,4 @@
-import { getAccountForwardingDestination, MAILFLARE_FORWARDED_HEADER } from "@/lib/email/account-forwarding";
+import { forwardedMarker, getAccountForwardingDestination, isForwardedMarkerValid, MAILFLARE_FORWARDED_HEADER } from "@/lib/email/account-forwarding";
import { resolveIncomingMail } from "@/lib/email/incoming";
import { inboundStorageKey } from "@/lib/email/inbound-id";
import type { InboundQueueMessage } from "@/lib/email/inbound";
@@ -11,7 +11,8 @@ import type { IntakeActions, IntakeInput, IntakeResult } from "@/lib/email/intak
* callbacks, then store the raw MIME and enqueue it for parsing.
*/
export async function intakeIncomingMail(env: CloudflareEnv, input: IntakeInput, actions: IntakeActions): Promise<IntakeResult> {
- const alreadyForwarded = input.headers[MAILFLARE_FORWARDED_HEADER.toLowerCase()] === "1" || input.headers[MAILFLARE_FORWARDED_HEADER] === "1";
+ const alreadyForwarded = await isForwardedMarkerValid(env, input.headers[MAILFLARE_FORWARDED_HEADER.toLowerCase()] ?? input.headers[MAILFLARE_FORWARDED_HEADER]);
+ const marker = { [MAILFLARE_FORWARDED_HEADER]: await forwardedMarker(env) };
const decision = await resolveIncomingMail(env, input.from, input.to, {
subject: input.headers.subject,
alreadyForwarded,
@@ -25,14 +26,14 @@ export async function intakeIncomingMail(env: CloudflareEnv, input: IntakeInput,
let forwardedTo: string | null = null;
if (decision?.action === "forward" && decision.forwardTo) {
- const forwarded = await actions.forward?.(decision.forwardTo, { [MAILFLARE_FORWARDED_HEADER]: "1" });
+ const forwarded = await actions.forward?.(decision.forwardTo, marker);
if (forwarded) forwardedTo = decision.forwardTo;
if (forwarded && !decision.keepCopy) return { action: "forward", forwardedTo };
}
if (!alreadyForwarded) {
const destination = await getAccountForwardingDestination(env, input.to);
- if (destination) await actions.forward?.(destination, { [MAILFLARE_FORWARDED_HEADER]: "1" });
+ if (destination) await actions.forward?.(destination, marker);
}
// A relay retry replays the same bytes, so key the object on a content hash
diff --git a/worker.ts b/worker.ts
index c2bffc0..f6f9ff3 100644
--- a/worker.ts
+++ b/worker.ts
@@ -17,6 +17,7 @@ import { inboundAttachmentLimitReasonFromRaw } from "./src/lib/email/inbound-att
import { hasValidSessionMutationOrigin } from "./src/lib/auth/origin";
import {
getAccountForwardingDestination,
+ isForwardedMarkerValid,
MAILFLARE_FORWARDED_HEADER,
} from "./src/lib/email/account-forwarding";
import { runScheduledDatabaseBackup } from "./src/lib/backups/runner";
@@ -65,9 +66,10 @@ export default {
}
// Domain routing rules are resolved here rather than in the queue because reject and
// forward can only be actioned on the live ForwardableEmailMessage.
+ const alreadyForwarded = await isForwardedMarkerValid(env, message.headers.get(MAILFLARE_FORWARDED_HEADER));
const decision = await resolveIncomingMail(env, message.from, message.to, {
subject: message.headers.get("subject"),
- alreadyForwarded: message.headers.get(MAILFLARE_FORWARDED_HEADER) === "1",
+ alreadyForwarded,
});
if (decision?.action === "reject") {
@@ -82,16 +84,16 @@ export default {
}
if (decision?.action === "forward" && decision.forwardTo) {
- const forwarded = await forwardMessage(message, decision.forwardTo);
+ const forwarded = await forwardMessage(env, message, decision.forwardTo);
// A forward rule drops the message unless it was explicitly asked to keep a copy.
// If the forward itself failed we still store it, so mail is never silently lost.
if (forwarded && !decision.keepCopy) return;
}
- if (message.headers.get(MAILFLARE_FORWARDED_HEADER) !== "1") {
+ if (!alreadyForwarded) {
const forwardingDestination = await getAccountForwardingDestination(env, message.to);
if (forwardingDestination) {
- await forwardMessage(message, forwardingDestination);
+ await forwardMessage(env, message, forwardingDestination);
}
}
const rawR2Key = await storeRawToR2(env, message.from, message.to, raw);