Email for professionals and teams
fix(security): sign relay header map with a timestamp and reject replays (#224)
Hieu Nguyen (Jack)fa9be47f2154
diff --git a/deploy/cloudflare-email-relay/src/index.ts b/deploy/cloudflare-email-relay/src/index.tsindex 6d2a062..0bb45d3 100644--- a/deploy/cloudflare-email-relay/src/index.ts+++ b/deploy/cloudflare-email-relay/src/index.ts@@ -13,9 +13,10 @@ type Decision =| { action: "forward"; forwardTo: string | null; forwardHeaders?: Record<string, string> }| { action: "store"; forwardTo: string | null; forwardHeaders?: Record<string, string> };-async function sign(secret: string, raw: ArrayBuffer, from: string, to: string): Promise<string> {+/** HMAC-SHA256 over `v2\ntimestamp\nfrom\nto\nheaders\n` + raw body; matches src/lib/email/intake-signature.ts. */+async function sign(secret: string, raw: ArrayBuffer, from: string, to: string, headers: string, timestamp: string): Promise<string> {const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);- const prefix = new TextEncoder().encode(`${from}\n${to}\n`);+ const prefix = new TextEncoder().encode(`v2\n${timestamp}\n${from}\n${to}\n${headers}\n`);const data = new Uint8Array(prefix.byteLength + raw.byteLength);data.set(prefix, 0);data.set(new Uint8Array(raw), prefix.byteLength);@@ -29,7 +30,8 @@ export default {return;}const raw = await new Response(message.raw).arrayBuffer();- const headers = Object.fromEntries(message.headers);+ const headers = JSON.stringify(Object.fromEntries(message.headers));+ const timestamp = String(Math.floor(Date.now() / 1000));let decision: Decision;try {const response = await fetch(`${env.MAILFLARE_URL.replace(/\/$/, "")}/api/inbound`, {@@ -38,8 +40,9 @@ export default {"Content-Type": "message/rfc822","X-Mailflare-From": message.from,"X-Mailflare-To": message.to,- "X-Mailflare-Headers": JSON.stringify(headers),- "X-Mailflare-Signature": await sign(env.INBOUND_WEBHOOK_SECRET, raw, message.from, message.to),+ "X-Mailflare-Headers": headers,+ "X-Mailflare-Timestamp": timestamp,+ "X-Mailflare-Signature": await sign(env.INBOUND_WEBHOOK_SECRET, raw, message.from, message.to, headers, timestamp),},body: raw,});diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex bf697be..a878438 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -108,6 +108,7 @@ and the DNS page shows what to set by hand.| `RESEND_API_KEY` | unset | Resend key, used when none is saved in the app || `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` | unset | Amazon SES credentials, used when none are saved in the app || `INBOUND_WEBHOOK_SECRET` | unset | Enables `/api/inbound` for the relay Worker |+| `INBOUND_REQUIRE_SIGNED_HEADERS` | unset | Set to `1` once the relay Worker is updated: refuses relays that do not sign the header map with a timestamp (older relays stay accepted without it, and their requests can be replayed) || `TURNSTILE_SECRET_KEY` | unset | Bot protection on login and reset forms (`NEXT_PUBLIC_TURNSTILE_SITE_KEY` at build time) || `VAPID_PUBLIC_KEY` | unset | Public Web Push application-server key || `VAPID_PRIVATE_KEY` | unset | Secret Web Push application-server key |diff --git a/env.d.ts b/env.d.tsindex aa7667b..b77c8b7 100644--- a/env.d.ts+++ b/env.d.ts@@ -72,6 +72,8 @@ interface CloudflareEnv {MAILFLARE_RUNTIME?: "node";/** Shared secret the Cloudflare email relay signs inbound webhooks with (self-hosted only). */INBOUND_WEBHOOK_SECRET?: string;+ /** "1" refuses relays that do not sign the header map with a timestamp (relay Worker v2). */+ INBOUND_REQUIRE_SIGNED_HEADERS?: string;/** Cloudflare account id, needed for the Email Sending REST API off Workers. */CF_ACCOUNT_ID?: string;/** Public origin of this install (https://mail.example.com) when it sits behind a proxy. */diff --git a/src/app/api/inbound/route.ts b/src/app/api/inbound/route.tsindex f02a7a7..85b384c 100644--- a/src/app/api/inbound/route.ts+++ b/src/app/api/inbound/route.ts@@ -1,7 +1,7 @@import { NextResponse } from "next/server";import { getEnv } from "@/lib/cloudflare";import { intakeIncomingMail } from "@/lib/email/intake";-import { verifyInboundSignature } from "@/lib/email/intake-signature";+import { verifyInboundSignature, verifyInboundSignatureV2 } from "@/lib/email/intake-signature";import { inboundAttachmentLimitReasonFromRaw } from "@/lib/email/inbound-attachments";export const dynamic = "force-dynamic";@@ -22,15 +22,27 @@ export async function POST(request: Request) {const from = request.headers.get("x-mailflare-from") ?? "";const to = request.headers.get("x-mailflare-to") ?? "";const signature = request.headers.get("x-mailflare-signature") ?? "";- if (!from || !to || !(await verifyInboundSignature(secret, signature, raw, from, to))) {- return NextResponse.json({ error: "Invalid signature" }, { status: 401 });+ const headerMap = request.headers.get("x-mailflare-headers") ?? "{}";+ const timestamp = request.headers.get("x-mailflare-timestamp");+ // Relays that send a timestamp sign the header map too and cannot be replayed; older relays only+ // sign the body, which stays accepted unless INBOUND_REQUIRE_SIGNED_HEADERS is set.+ const valid = !from || !to+ ? false+ : timestamp+ ? await verifyInboundSignatureV2(secret, signature, raw, from, to, headerMap, timestamp)+ : env.INBOUND_REQUIRE_SIGNED_HEADERS !== "1" && await verifyInboundSignature(secret, signature, raw, from, to);+ if (!valid) return NextResponse.json({ error: "Invalid signature" }, { status: 401 });+ if (timestamp) {+ const seenKey = `relay-seen/${signature}`;+ if (await env.BUCKET.head(seenKey)) return NextResponse.json({ error: "Replayed request" }, { status: 409 });+ await env.BUCKET.put(seenKey, new Uint8Array(0));}const attachmentLimitReason = await inboundAttachmentLimitReasonFromRaw(raw);if (attachmentLimitReason) return NextResponse.json({ action: "reject", reason: attachmentLimitReason });let headers: Record<string, string> = {};try {- headers = JSON.parse(request.headers.get("x-mailflare-headers") ?? "{}") as Record<string, string>;+ headers = JSON.parse(headerMap) as Record<string, string>;} catch {// The header map is advisory; the raw message is authoritative.}diff --git a/src/lib/email/intake-signature.ts b/src/lib/email/intake-signature.tsindex 7df6265..fe89edd 100644--- a/src/lib/email/intake-signature.ts+++ b/src/lib/email/intake-signature.ts@@ -23,3 +23,41 @@ export async function verifyInboundSignature(secret: string, signature: string,for (let index = 0; index < expected.length; index += 1) diff |= expected.charCodeAt(index) ^ signature.charCodeAt(index);return diff === 0;}++export const INBOUND_SIGNATURE_MAX_AGE_SECONDS = 300;++async function hmacV2(secret: string, raw: ArrayBuffer, from: string, to: string, headers: string, timestamp: string): Promise<string> {+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ const prefix = new TextEncoder().encode(`v2\n${timestamp}\n${from}\n${to}\n${headers}\n`);+ const data = new Uint8Array(prefix.byteLength + raw.byteLength);+ data.set(prefix, 0);+ data.set(new Uint8Array(raw), prefix.byteLength);+ return hex(await crypto.subtle.sign("HMAC", key, data));+}++/**+ * Version 2 also covers the header map and a Unix timestamp (seconds), so neither can be altered+ * in transit and a captured request stops verifying after a few minutes.+ */+export async function signInboundV2(secret: string, raw: ArrayBuffer, from: string, to: string, headers: string, timestamp: string): Promise<string> {+ return hmacV2(secret, raw, from, to, headers, timestamp);+}++export async function verifyInboundSignatureV2(+ secret: string,+ signature: string,+ raw: ArrayBuffer,+ from: string,+ to: string,+ headers: string,+ timestamp: string,+ nowSeconds = Math.floor(Date.now() / 1000),+): Promise<boolean> {+ const sentAt = Number(timestamp);+ if (!Number.isFinite(sentAt) || Math.abs(nowSeconds - sentAt) > INBOUND_SIGNATURE_MAX_AGE_SECONDS) return false;+ const expected = await hmacV2(secret, raw, from, to, headers, timestamp);+ if (expected.length !== signature.length) return false;+ let diff = 0;+ for (let index = 0; index < expected.length; index += 1) diff |= expected.charCodeAt(index) ^ signature.charCodeAt(index);+ return diff === 0;+}diff --git a/tests/intake-signature.test.mjs b/tests/intake-signature.test.mjsnew file mode 100644index 0000000..0c894fa--- /dev/null+++ b/tests/intake-signature.test.mjs@@ -0,0 +1,33 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const dir = mkdtempSync(join(tmpdir(), "mailflare-intake-sig-test-"));+after(() => rmSync(dir, { recursive: true, force: true }));+await build({ entryPoints: [join(root, "src/lib/email/intake-signature.ts")], outfile: join(dir, "sig.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent" });+const sig = await import(pathToFileURL(join(dir, "sig.mjs")).href);++const raw = new TextEncoder().encode("Subject: hi\r\n\r\nbody").buffer;+const headers = JSON.stringify({ subject: "hi", "list-id": "x" });+const now = 1_900_000_000;++test("v2 signature binds headers and timestamp", async () => {+ const signature = await sig.signInboundV2("s3cret", raw, "[email protected]", "[email protected]", headers, String(now));+ assert.equal(await sig.verifyInboundSignatureV2("s3cret", signature, raw, "[email protected]", "[email protected]", headers, String(now), now), true);+ const tampered = JSON.stringify({ subject: "hi", "list-id": "x", "auto-submitted": "no" });+ assert.equal(await sig.verifyInboundSignatureV2("s3cret", signature, raw, "[email protected]", "[email protected]", tampered, String(now), now), false);+ assert.equal(await sig.verifyInboundSignatureV2("s3cret", signature, raw, "[email protected]", "[email protected]", headers, String(now), now), false);+ assert.equal(await sig.verifyInboundSignatureV2("other", signature, raw, "[email protected]", "[email protected]", headers, String(now), now), false);+});++test("v2 signatures expire", async () => {+ const signature = await sig.signInboundV2("s3cret", raw, "[email protected]", "[email protected]", headers, String(now));+ assert.equal(await sig.verifyInboundSignatureV2("s3cret", signature, raw, "[email protected]", "[email protected]", headers, String(now), now + 299), true);+ assert.equal(await sig.verifyInboundSignatureV2("s3cret", signature, raw, "[email protected]", "[email protected]", headers, String(now), now + 301), false);+ assert.equal(await sig.verifyInboundSignatureV2("s3cret", signature, raw, "[email protected]", "[email protected]", headers, "not-a-number", now), false);+});