Email for professionals and teams
fix(security): verify SNS signatures and reject replayed notifications (#224)
Hieu Nguyen (Jack)12a2afb328e1
diff --git a/src/app/api/inbound/ses/route.ts b/src/app/api/inbound/ses/route.tsindex bf50c59..03c1057 100644--- a/src/app/api/inbound/ses/route.ts+++ b/src/app/api/inbound/ses/route.ts@@ -5,15 +5,17 @@ import { deleteObject, getObject } from "@/lib/aws/s3";import { getSesReceivingState, SES_OBJECT_PREFIX } from "@/lib/aws/ses-receiving";import { intakeProviderMail } from "@/lib/email/provider-intake";import { parseSesNotification, safeEqual, type SnsEnvelope } from "@/lib/aws/ses-notification";+import { verifySnsSignature } from "@/lib/aws/sns-signature";export const dynamic = "force-dynamic";/*** Amazon SNS endpoint for SES inbound mail. SNS posts JSON as text/plain.- * Trust comes from three things rather than SNS's certificate signature: the- * secret token in the URL that only the subscription we created knows, the topic- * ARN matching ours, and the message itself being read from our own S3 bucket- * with our credentials, so a forged notification cannot inject content.+ * Trust comes from four things: the secret token in the URL that only the subscription+ * we created knows, the SNS signature checked against Amazon's published certificate+ * (with a freshness window), the topic ARN matching ours, and the message itself being+ * read from our own S3 bucket with our credentials, so a forged notification cannot+ * inject content.*/export async function POST(request: Request) {const env = getEnv();@@ -24,6 +26,7 @@ export async function POST(request: Request) {let envelope: SnsEnvelope;try { envelope = JSON.parse(await request.text()) as SnsEnvelope; } catch { return NextResponse.json({ error: "Invalid body" }, { status: 400 }); }if (envelope.TopicArn !== state.topicArn) return NextResponse.json({ error: "Unknown topic" }, { status: 403 });+ if (!await verifySnsSignature(envelope)) return NextResponse.json({ error: "Invalid signature" }, { status: 403 });if (envelope.Type === "SubscriptionConfirmation") {const url = envelope.SubscribeURL ? new URL(envelope.SubscribeURL) : null;@@ -41,6 +44,10 @@ export async function POST(request: Request) {return NextResponse.json({ error: "Unexpected object" }, { status: 400 });}+ // A captured, still-fresh notification replays only once: remember delivered MessageIds.+ const seenKey = envelope.MessageId ? `sns-seen/${envelope.MessageId.replace(/[^A-Za-z0-9-]/g, "")}` : null;+ if (seenKey && await env.BUCKET.head(seenKey)) return NextResponse.json({ ignored: "Already processed" });+const config = await requireAwsConfig(env);if (notification.virusFailed) {await deleteObject(config, state.bucket, notification.key);@@ -50,5 +57,6 @@ export async function POST(request: Request) {const result = await intakeProviderMail(env, { from: notification.from, recipients: notification.recipients, raw, headers: notification.headers, verdicts: notification.verdicts });// Only after intake succeeded: a failure above returns 500 so SNS retries with the object intact.await deleteObject(config, state.bucket, notification.key);+ if (seenKey) await env.BUCKET.put(seenKey, new Uint8Array(0));return NextResponse.json(result);}diff --git a/src/lib/aws/ses-notification.ts b/src/lib/aws/ses-notification.tsindex e865d1f..5a9ffc4 100644--- a/src/lib/aws/ses-notification.ts+++ b/src/lib/aws/ses-notification.ts@@ -2,9 +2,16 @@ import type { ProviderVerdicts } from "@/lib/spam/types";export type SnsEnvelope = {Type?: string;+ MessageId?: string;TopicArn?: string;Message?: string;+ Subject?: string;+ Timestamp?: string;SubscribeURL?: string;+ Token?: string;+ SignatureVersion?: string;+ Signature?: string;+ SigningCertURL?: string;};export type SesNotification = {diff --git a/src/lib/aws/sns-signature.ts b/src/lib/aws/sns-signature.tsnew file mode 100644index 0000000..51f6b27--- /dev/null+++ b/src/lib/aws/sns-signature.ts@@ -0,0 +1,113 @@+import type { SnsEnvelope } from "@/lib/aws/ses-notification";++const CERT_HOST = /^sns\.[a-z0-9-]+\.amazonaws\.com(?:\.cn)?$/;+const MAX_AGE_MS = 24 * 60 * 60 * 1000;+const certCache = new Map<string, Promise<ArrayBuffer>>();++/** The fields SNS signs, in the order it signs them (Amazon SNS "Verifying the signatures" docs). */+function stringToSign(envelope: SnsEnvelope): string | null {+ const keys = envelope.Type === "Notification"+ ? ["Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type"]+ : envelope.Type === "SubscriptionConfirmation" || envelope.Type === "UnsubscribeConfirmation"+ ? ["Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"]+ : null;+ if (!keys) return null;+ let out = "";+ for (const key of keys) {+ const value = (envelope as Record<string, string | undefined>)[key];+ if (value === undefined) {+ if (key === "Subject") continue;+ return null;+ }+ out += `${key}\n${value}\n`;+ }+ return out;+}++export function isValidSigningCertUrl(value: string | undefined): value is string {+ if (!value) return false;+ try {+ const url = new URL(value);+ return url.protocol === "https:" && !url.port && CERT_HOST.test(url.hostname) && url.pathname.endsWith(".pem");+ } catch {+ return false;+ }+}++function pemToDer(pem: string): Uint8Array {+ const body = pem.replace(/-----[A-Z ]+-----/g, "").replace(/\s+/g, "");+ return Uint8Array.from(atob(body), (char) => char.charCodeAt(0));+}++/** Reads one DER element at `offset`: its tag, header length and content length. */+function readDer(bytes: Uint8Array, offset: number): { tag: number; header: number; length: number } {+ const tag = bytes[offset];+ const first = bytes[offset + 1];+ if (first < 0x80) return { tag, header: 2, length: first };+ const count = first & 0x7f;+ let length = 0;+ for (let index = 0; index < count; index += 1) length = length * 256 + bytes[offset + 2 + index];+ return { tag, header: 2 + count, length };+}++/** Pulls the SubjectPublicKeyInfo out of an X.509 certificate; Web Crypto cannot import certificates. */+export function spkiFromCertificate(der: Uint8Array): Uint8Array {+ const cert = readDer(der, 0);+ let offset = cert.header;+ const tbs = readDer(der, offset);+ offset += tbs.header;+ const tbsEnd = offset + tbs.length;+ const skip = () => {+ const element = readDer(der, offset);+ offset += element.header + element.length;+ };+ if (der[offset] === 0xa0) skip(); // [0] version+ skip(); // serial+ skip(); // signature algorithm+ skip(); // issuer+ skip(); // validity+ skip(); // subject+ if (offset >= tbsEnd) throw new Error("Certificate has no public key");+ const spki = readDer(der, offset);+ return der.subarray(offset, offset + spki.header + spki.length);+}++async function fetchCertificate(url: string): Promise<ArrayBuffer> {+ const cached = certCache.get(url);+ if (cached) return cached;+ const pending = fetch(url, { redirect: "error", signal: AbortSignal.timeout(5000) }).then(async (response) => {+ if (!response.ok) throw new Error(`Signing certificate fetch failed: ${response.status}`);+ const der = pemToDer(await response.text());+ return der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength) as ArrayBuffer;+ });+ certCache.set(url, pending);+ pending.catch(() => certCache.delete(url));+ return pending;+}++/** Checks the SNS signature against the certificate Amazon published. Returns false on any problem. */+export async function verifySnsSignature(+ envelope: SnsEnvelope,+ options: { now?: number; loadCertificate?: (url: string) => Promise<ArrayBuffer> } = {},+): Promise<boolean> {+ try {+ const version = envelope.SignatureVersion;+ if ((version !== "1" && version !== "2") || !envelope.Signature || !isValidSigningCertUrl(envelope.SigningCertURL)) return false;+ const signed = stringToSign(envelope);+ const sentAt = Date.parse(envelope.Timestamp ?? "");+ if (signed === null || Number.isNaN(sentAt) || Math.abs((options.now ?? Date.now()) - sentAt) > MAX_AGE_MS) return false;+ const der = new Uint8Array(await (options.loadCertificate ?? fetchCertificate)(envelope.SigningCertURL));+ const spki = spkiFromCertificate(der);+ const key = await crypto.subtle.importKey(+ "spki",+ spki as BufferSource,+ { name: "RSASSA-PKCS1-v1_5", hash: version === "2" ? "SHA-256" : "SHA-1" },+ false,+ ["verify"],+ );+ const signature = Uint8Array.from(atob(envelope.Signature), (char) => char.charCodeAt(0));+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, signature, new TextEncoder().encode(signed));+ } catch {+ return false;+ }+}diff --git a/tests/sns-signature.test.mjs b/tests/sns-signature.test.mjsnew file mode 100644index 0000000..330044c--- /dev/null+++ b/tests/sns-signature.test.mjs@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import { createSign } from "node:crypto";+import { execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, 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-sns-test-"));+after(() => rmSync(dir, { recursive: true, force: true }));++await build({+ entryPoints: [join(root, "src/lib/aws/sns-signature.ts")],+ outfile: join(dir, "sns.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent",+});+const { verifySnsSignature, isValidSigningCertUrl } = await import(pathToFileURL(join(dir, "sns.mjs")).href);++execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(dir, "key.pem"), "-out", join(dir, "cert.pem"), "-subj", "/CN=sns.test", "-days", "2"], { stdio: "ignore" });+const keyPem = readFileSync(join(dir, "key.pem"), "utf8");+const certPem = readFileSync(join(dir, "cert.pem"), "utf8");+const der = Buffer.from(certPem.replace(/-----[A-Z ]+-----/g, "").replace(/\s+/g, ""), "base64");+const loadCertificate = async () => der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength);++const base = { Type: "Notification", MessageId: "m-1", TopicArn: "arn:aws:sns:us-east-1:1:t", Message: "{}", Timestamp: new Date().toISOString(), SignatureVersion: "2", SigningCertURL: "https://sns.us-east-1.amazonaws.com/cert.pem" };+function sign(envelope, algorithm = "RSA-SHA256") {+ const signer = createSign(algorithm);+ signer.update(["Message", "MessageId", "Timestamp", "TopicArn", "Type"].map((key) => `${key}\n${envelope[key]}\n`).join(""));+ return signer.sign(keyPem, "base64");+}++test("accepts a correctly signed notification and rejects tampering", async () => {+ const envelope = { ...base, Signature: sign(base) };+ assert.equal(await verifySnsSignature(envelope, { loadCertificate }), true);+ assert.equal(await verifySnsSignature({ ...envelope, Message: "{\"x\":1}" }, { loadCertificate }), false);+ assert.equal(await verifySnsSignature({ ...envelope, TopicArn: "arn:other" }, { loadCertificate }), false);+});++test("accepts SignatureVersion 1 (SHA-1)", async () => {+ const v1 = { ...base, SignatureVersion: "1" };+ assert.equal(await verifySnsSignature({ ...v1, Signature: sign(v1, "RSA-SHA1") }, { loadCertificate }), true);+});++test("rejects stale timestamps, missing signatures and foreign certificate URLs", async () => {+ const old = { ...base, Timestamp: new Date(Date.now() - 3 * 86_400_000).toISOString() };+ assert.equal(await verifySnsSignature({ ...old, Signature: sign(old) }, { loadCertificate }), false);+ assert.equal(await verifySnsSignature(base, { loadCertificate }), false);+ for (const url of ["http://sns.us-east-1.amazonaws.com/c.pem", "https://evil.example/c.pem", "https://sns.us-east-1.amazonaws.com.evil.example/c.pem", "https://sns.us-east-1.amazonaws.com:8443/c.pem", "https://sns.us-east-1.amazonaws.com/c.txt"]) {+ assert.equal(isValidSigningCertUrl(url), false, url);+ }+ assert.equal(isValidSigningCertUrl("https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-abc.pem"), true);+});