Email for professionals and teams
fix(security): harden self-hosted SMTP ingress (#215)
Hieu Nguyen (Jack)c824aebfc012
diff --git a/server/runtime/smtp.ts b/server/runtime/smtp.tsindex 6900355..625a5ab 100644--- a/server/runtime/smtp.ts+++ b/server/runtime/smtp.ts@@ -3,8 +3,17 @@ import { SMTPServer } from "smtp-server";import type { SMTPServerSession } from "smtp-server";import { intakeIncomingMail } from "@/lib/email/intake";import { inboundAttachmentLimitReasonFromRaw } from "@/lib/email/inbound-attachments";+import { isPublicIpv4 } from "@/lib/spam/domain-utils";import type { Mailer } from "./mailer";+const MAX_CLIENTS = 100;+const MAX_CONNECTIONS_PER_IP = 10;+const MAX_RECIPIENTS = 50;+const SOCKET_TIMEOUT_MS = 60_000;++/** Headers a sender can write but only the receiving side may vouch for. */+const UNTRUSTED_HEADERS = ["authentication-results", "received-spf", "arc-authentication-results", "received"];+/*** Receive mail directly on port 25 (or wherever SMTP_INBOUND_PORT points).* One inbound connection per message; each envelope recipient is handed to@@ -18,7 +27,33 @@ export function startSmtpListener() {// STARTTLS is only offered with a real certificate; smtp-server's built-in// one has a public private key, and advertising it would mislead senders.+ const connectionsByIp = new Map<string, number>();const server = new SMTPServer({+ maxClients: MAX_CLIENTS,+ socketTimeout: SOCKET_TIMEOUT_MS,+ onConnect(session, callback) {+ const ip = session.remoteAddress;+ const count = (connectionsByIp.get(ip) ?? 0) + 1;+ if (count > MAX_CONNECTIONS_PER_IP) {+ callback(Object.assign(new Error("Too many connections from your address"), { responseCode: 421 }));+ return;+ }+ connectionsByIp.set(ip, count);+ callback();+ },+ onClose(session) {+ const ip = session.remoteAddress;+ const count = (connectionsByIp.get(ip) ?? 1) - 1;+ if (count <= 0) connectionsByIp.delete(ip);+ else connectionsByIp.set(ip, count);+ },+ onRcptTo(address, session, callback) {+ if (session.envelope.rcptTo.length >= MAX_RECIPIENTS) {+ callback(Object.assign(new Error("Too many recipients"), { responseCode: 452 }));+ return;+ }+ callback();+ },name: options.hostname,authOptional: true,disabledCommands: options.tls ? ["AUTH"] : ["AUTH", "STARTTLS"],@@ -27,7 +62,13 @@ export function startSmtpListener(banner: "Mailflare",onData(stream, session: SMTPServerSession, callback) {const chunks: Buffer[] = [];- stream.on("data", (chunk: Buffer) => chunks.push(chunk));+ let received = 0;+ stream.on("data", (chunk: Buffer) => {+ // Stop buffering once over the limit; the 552 is sent when the stream ends.+ received += chunk.length;+ if (received <= options.maxSize) chunks.push(chunk);+ else chunks.length = 0;+ });stream.on("end", async () => {if (stream.sizeExceeded) {const error = Object.assign(new Error("Message exceeds size limit"), { responseCode: 552 });@@ -49,11 +90,14 @@ export function startSmtpListener(}const from = session.envelope.mailFrom ? session.envelope.mailFrom.address : "";const headers = parseHeaders(raw);+ // No SPF/DKIM/DMARC verification happens here, so anything the sender wrote is untrusted.+ for (const name of UNTRUSTED_HEADERS) delete headers[name];+ const senderIp = isPublicIpv4(session.remoteAddress) ? session.remoteAddress : undefined;let rejectReason: string | null = null;for (const recipient of session.envelope.rcptTo) {const result = await intakeIncomingMail(env,- { from, to: recipient.address, raw: toArrayBuffer(raw), headers },+ { from, to: recipient.address, raw: toArrayBuffer(raw), headers, senderIp },{reject: (reason) => {rejectReason = reason;