Email for professionals and teams
fix(security): flag dangerous attachments and gate their download (#218)
Hieu Nguyen (Jack)9e156ee50f44
diff --git a/docs/security.md b/docs/security.mdindex fad69b9..a4306a4 100644--- a/docs/security.md+++ b/docs/security.md@@ -36,3 +36,22 @@ trigger `message.inbound`.Mail Mailflare forwards carries `X-Mailflare-Forwarded`, an HMAC keyed with a server secret(`CF_TOKEN`, `CF_API_KEY` or `INBOUND_WEBHOOK_SECRET`). A sender cannot switch forwardingoff by adding the header. With none of those set the header falls back to `1`.++## Attachments++Mailflare does not run an antivirus engine. What it does instead:++* SES, and Resend (which receives through SES), drop mail the provider flagged as infected.+* Every attachment is judged from its name and type: programs and scripts, macro-enabled+ Office files, double extensions such as `invoice.pdf.exe`, hidden bidi characters, and+ containers that hide other files (HTML, SVG, disk images, archives).+* ZIP files are inspected without extracting anything: the file names in the central+ directory are read with two bounded range requests (at most 1000 entries and 1 MiB of+ directory). Password-protected or unreadable archives are flagged.+* A flagged attachment shows the reasons in the viewer, and the download stays disabled+ until the user ticks "I understand the risk". The server refuses an unacknowledged+ download of a flagged file with HTTP 409, so a direct link cannot bypass it.++This stops one-click downloads of things that are dangerous by design. It does not find+malware in an ordinary-looking PDF or image; put ClamAV or a provider scan in front of the+server if you need that.diff --git a/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts b/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.tsindex 8add0d9..245f775 100644--- a/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts+++ b/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts@@ -1,6 +1,6 @@import { getCurrentUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";-import { getAttachmentForUser } from "@/lib/email/attachments";+import { assessStoredAttachment, getAttachmentForUser } from "@/lib/email/attachments";import { getInlineContentType } from "@/lib/http/content-type";import type { AttachmentRouteParams } from "./types";import { getAttachmentContentDisposition } from "./utils";@@ -23,6 +23,16 @@ export async function GET(request: Request, { params }: AttachmentRouteParams) {// and drops a route's own Content-Security-Policy.const inlineType = downloadRequested ? null : getInlineContentType(attachment.contentType);const inline = inlineType !== null && (attachment.disposition === "inline" || previewRequested);+ // Types that run code, carry macros or hide other files are downloaded only after the user has seen why.+ const risk = await assessStoredAttachment(env, { filename: attachment.filename, type: attachment.contentType, size: attachment.size, r2Key: attachment.r2Key });+ if (url.searchParams.get("risk") === "1") {+ await object.body.cancel().catch(() => undefined);+ return Response.json(risk, { headers: { "Cache-Control": "private, no-store" } });+ }+ if (!inline && risk.level !== "ok" && url.searchParams.get("acknowledge") !== "1") {+ await object.body.cancel().catch(() => undefined);+ return Response.json({ error: "This file is flagged. Review the warning before downloading it.", risk }, { status: 409, headers: { "Cache-Control": "private, no-store" } });+ }const headers = new Headers();object.writeHttpMetadata(headers);headers.set("Content-Type", (inline && inlineType) || "application/octet-stream");diff --git a/src/components/message-attachment-viewer-utils.ts b/src/components/message-attachment-viewer-utils.tsindex ae6816f..843ec03 100644--- a/src/components/message-attachment-viewer-utils.ts+++ b/src/components/message-attachment-viewer-utils.ts@@ -4,9 +4,9 @@ import type { AttachmentPreviewKind } from "./message-attachment-viewer-types";export function getAttachmentFileUrl(messageId: string,attachmentId: string,- mode: "download" | "preview" = "download",+ mode: "download" | "preview" | "risk" | "acknowledged-download" = "download",): string {- const suffix = mode === "preview" ? "?preview=1" : "?download=1";+ const suffix = { preview: "?preview=1", risk: "?risk=1", download: "?download=1", "acknowledged-download": "?download=1&acknowledge=1" }[mode];return `/api/messages/${messageId}/attachments/${attachmentId}${suffix}`;}diff --git a/src/components/message-attachment-viewer.tsx b/src/components/message-attachment-viewer.tsxindex 1627ea2..110eee1 100644--- a/src/components/message-attachment-viewer.tsx+++ b/src/components/message-attachment-viewer.tsx@@ -13,6 +13,7 @@ import {import { useLanguage } from "@/components/language-provider";import { authFetch } from "@/lib/auth/client";import { Skeleton } from "@/components/ui/skeleton";+import type { AttachmentRisk } from "@/lib/email/attachment-risk";import type { MessageAttachmentViewerProps } from "./message-attachment-viewer-types";import {getAttachmentFileUrl,@@ -33,10 +34,25 @@ export function MessageAttachmentViewer({const previewUrl = attachment? getAttachmentFileUrl(messageId, attachment.id, "preview"): "";+ const [risk, setRisk] = useState<AttachmentRisk | null>(null);+ const [acknowledged, setAcknowledged] = useState(false);+ const flagged = !!risk && risk.level !== "ok";const downloadUrl = attachment- ? getAttachmentFileUrl(messageId, attachment.id, "download")+ ? getAttachmentFileUrl(messageId, attachment.id, flagged ? "acknowledged-download" : "download"): "";+ useEffect(() => {+ setRisk(null);+ setAcknowledged(false);+ if (!open || !attachment) return;+ let cancelled = false;+ void authFetch(getAttachmentFileUrl(messageId, attachment.id, "risk"))+ .then(async (response): Promise<AttachmentRisk | null> => (response.ok ? await response.json() : null))+ .then((data) => { if (!cancelled && data) setRisk(data); })+ .catch(() => undefined);+ return () => { cancelled = true; };+ }, [attachment, messageId, open]);+useEffect(() => {if (!open || !attachment || previewKind !== "text") return;let cancelled = false;@@ -114,13 +130,34 @@ export function MessageAttachmentViewer({)}</div>- <div className="flex shrink-0 justify-end">- <Button asChild>- <a href={downloadUrl} download={attachment.filename}>+ {risk && flagged && (+ <div role="alert" className={`shrink-0 rounded-lg border p-3 text-sm ${risk.level === "blocked" ? "border-red-300 bg-red-50 text-red-900" : "border-amber-300 bg-amber-50 text-amber-900"}`}>+ <p className="font-medium">{risk.level === "blocked" ? t("attachment.risk.blocked") : t("attachment.risk.warning")}</p>+ <ul className="mt-1 list-disc pl-5">+ {risk.reasons.map((reason) => <li key={reason}>{reason}</li>)}+ </ul>+ <label className="mt-2 flex items-center gap-2">+ <input type="checkbox" checked={acknowledged} onChange={(event) => setAcknowledged(event.target.checked)} />+ {t("attachment.risk.acknowledge")}+ </label>+ </div>+ )}++ <div className="flex shrink-0 items-center justify-end gap-3">+ {risk && !flagged && <span className="text-xs text-neutral-500">{t("attachment.risk.ok")}</span>}+ {flagged && !acknowledged ? (+ <Button disabled><ArrowDownToLine className="h-4 w-4" />{t("attachment.download")}- </a>- </Button>+ </Button>+ ) : (+ <Button asChild>+ <a href={downloadUrl} download={attachment.filename}>+ <ArrowDownToLine className="h-4 w-4" />+ {t("attachment.download")}+ </a>+ </Button>+ )}</div></DialogContent></Dialog>diff --git a/src/lib/email/attachment-risk.ts b/src/lib/email/attachment-risk.tsnew file mode 100644index 0000000..762a0d5--- /dev/null+++ b/src/lib/email/attachment-risk.ts@@ -0,0 +1,112 @@+/**+ * Attachment risk without an antivirus engine: file types that run code or carry macros, names that+ * disguise their type, and the contents of ZIP archives (bounded). It does not detect malware in+ * ordinary-looking files; it stops a one-click download of things that are dangerous by design.+ */+export type AttachmentRiskLevel = "ok" | "warning" | "blocked";+export type AttachmentRisk = { level: AttachmentRiskLevel; reasons: string[] };++/** Run code when opened. */+const EXECUTABLE = new Set([+ "exe", "scr", "com", "pif", "bat", "cmd", "msi", "msp", "dll", "cpl", "jar", "js", "jse", "vbs", "vbe", "wsf", "wsh",+ "ps1", "psm1", "lnk", "hta", "reg", "apk", "appimage", "scf", "url", "chm", "gadget", "inf", "sh", "command", "app", "pkg", "dmg",+]);+/** Office formats that carry macros. */+const MACRO = new Set(["docm", "xlsm", "pptm", "dotm", "xltm", "potm", "ppam", "xlam", "sldm"]);+/** Open in a browser or mount like a disk: common phishing and smuggling containers. */+const CONTAINER = new Set(["html", "htm", "xhtml", "shtml", "svg", "iso", "img", "vhd", "vhdx", "one"]);+const ARCHIVE = new Set(["zip", "rar", "7z", "tar", "gz", "tgz", "bz2", "xz", "cab", "ace"]);+const DOCUMENT_LOOKING = new Set(["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "rtf", "jpg", "jpeg", "png", "gif", "csv", "mp3", "mp4"]);+// eslint-disable-next-line no-control-regex+const BIDI_OR_CONTROL = /[\u0000-\u001f--]/;++const MAX_ZIP_ENTRIES = 1000;+const MAX_CENTRAL_DIRECTORY_BYTES = 1024 * 1024;+const MAX_ZIP_DEPTH_NAMES = 50;++function extensions(filename: string): string[] {+ return filename.toLowerCase().trim().split(".").slice(1).map((part) => part.replace(/\s+$/, ""));+}++const rank: Record<AttachmentRiskLevel, number> = { ok: 0, warning: 1, blocked: 2 };++export function mergeRisks(...risks: AttachmentRisk[]): AttachmentRisk {+ let level: AttachmentRiskLevel = "ok";+ const reasons: string[] = [];+ for (const risk of risks) {+ if (rank[risk.level] > rank[level]) level = risk.level;+ for (const reason of risk.reasons) if (!reasons.includes(reason)) reasons.push(reason);+ }+ return { level, reasons };+}++/** Risk judged from the name and declared type alone. */+export function assessAttachmentRisk(attachment: { filename: string; type?: string }): AttachmentRisk {+ const reasons: string[] = [];+ let level: AttachmentRiskLevel = "ok";+ const raise = (next: AttachmentRiskLevel, reason: string) => {+ if (rank[next] > rank[level]) level = next;+ reasons.push(reason);+ };+ const exts = extensions(attachment.filename);+ const last = exts[exts.length - 1] ?? "";+ if (BIDI_OR_CONTROL.test(attachment.filename)) raise("blocked", "The file name contains hidden characters that can disguise its real type.");+ if (EXECUTABLE.has(last)) raise("blocked", `.${last} files run code when opened.`);+ else if (MACRO.has(last)) raise("blocked", `.${last} documents can run macros.`);+ else if (CONTAINER.has(last)) raise("warning", `.${last} files can show a fake login page or hide other files.`);+ else if (ARCHIVE.has(last)) raise("warning", "Archives can hide other files; open them only if you expected this.");+ if (exts.length >= 2 && DOCUMENT_LOOKING.has(exts[exts.length - 2]) && (EXECUTABLE.has(last) || MACRO.has(last) || CONTAINER.has(last))) {+ raise("blocked", "The name has two extensions to look like a harmless document.");+ }+ const type = (attachment.type ?? "").toLowerCase();+ if (type === "application/x-msdownload" || type === "application/x-msdos-program" || type === "application/x-sh" || type === "application/vnd.microsoft.portable-executable") {+ raise("blocked", "The file is declared as a program.");+ }+ return { level, reasons };+}++/** Where a ZIP's central directory sits, from the last 64 KiB of the file. */+export function locateZipDirectory(tail: Uint8Array): { offset: number; size: number } | null {+ const view = new DataView(tail.buffer, tail.byteOffset, tail.byteLength);+ for (let index = tail.byteLength - 22; index >= 0; index -= 1) {+ if (view.getUint32(index, true) === 0x06054b50) return { size: view.getUint32(index + 12, true), offset: view.getUint32(index + 16, true) };+ }+ return null;+}++/** Names inside a ZIP, read from its central directory without extracting anything. */+export function inspectZipDirectory(tail: Uint8Array, centralDirectory: (offset: number, size: number) => Uint8Array | null): AttachmentRisk {+ const view = new DataView(tail.buffer, tail.byteOffset, tail.byteLength);+ let eocd = -1;+ for (let index = tail.byteLength - 22; index >= 0; index -= 1) {+ if (view.getUint32(index, true) === 0x06054b50) { eocd = index; break; }+ }+ if (eocd < 0) return { level: "ok", reasons: [] };+ const entries = view.getUint16(eocd + 10, true);+ const size = view.getUint32(eocd + 12, true);+ const offset = view.getUint32(eocd + 16, true);+ if (size === 0xffffffff || offset === 0xffffffff || entries === 0xffff) return { level: "warning", reasons: ["This archive uses a format that cannot be checked here."] };+ if (entries > MAX_ZIP_ENTRIES || size > MAX_CENTRAL_DIRECTORY_BYTES) return { level: "warning", reasons: ["This archive holds an unusually large number of files and was not fully checked."] };+ const directory = centralDirectory(offset, size);+ if (!directory) return { level: "warning", reasons: ["This archive could not be checked."] };+ const dv = new DataView(directory.buffer, directory.byteOffset, directory.byteLength);+ const risks: AttachmentRisk[] = [];+ let encrypted = false;+ let position = 0;+ for (let seen = 0; seen < entries && position + 46 <= directory.byteLength && seen < MAX_ZIP_DEPTH_NAMES * 20; seen += 1) {+ if (dv.getUint32(position, true) !== 0x02014b50) break;+ const flags = dv.getUint16(position + 8, true);+ const nameLength = dv.getUint16(position + 28, true);+ const extraLength = dv.getUint16(position + 30, true);+ const commentLength = dv.getUint16(position + 32, true);+ if (position + 46 + nameLength > directory.byteLength) break;+ if (flags & 1) encrypted = true;+ const name = new TextDecoder().decode(directory.subarray(position + 46, position + 46 + nameLength));+ const inner = assessAttachmentRisk({ filename: name.split("/").pop() ?? name });+ if (inner.level !== "ok") risks.push({ level: inner.level, reasons: inner.reasons.map((reason) => `Inside the archive, ${name}: ${reason}`) });+ position += 46 + nameLength + extraLength + commentLength;+ }+ if (encrypted) risks.push({ level: "warning", reasons: ["This archive is password protected, so its contents could not be checked."] });+ const merged = mergeRisks(...risks);+ return { level: merged.level, reasons: merged.reasons.slice(0, 5) };+}diff --git a/src/lib/email/attachments.ts b/src/lib/email/attachments.tsindex 7bfb9b9..087b89b 100644--- a/src/lib/email/attachments.ts+++ b/src/lib/email/attachments.ts@@ -2,6 +2,7 @@ import { and, eq, isNull } from "drizzle-orm";import { getDb } from "@/db";import { messageAttachments, messages } from "@/db/schema";import { newId } from "@/lib/ids";+import { assessAttachmentRisk, inspectZipDirectory, locateZipDirectory, mergeRisks, type AttachmentRisk } from "@/lib/email/attachment-risk";import { truncateUtf8 } from "@/lib/email/inbound-limits";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import type { SessionUser } from "@/lib/auth/types";@@ -269,3 +270,28 @@ export async function getAttachmentForUser(if (!object) return null;return { attachment, object };}++/**+ * Name-based risk plus, for ZIP files, the names inside the archive (read with two bounded range+ * requests, never extracted). Used before a download and to label attachments in the reader.+ */+export async function assessStoredAttachment(env: CloudflareEnv, attachment: { filename: string; type: string; size: number; r2Key: string }): Promise<AttachmentRisk> {+ const byName = assessAttachmentRisk(attachment);+ const isZip = /\.zip$/i.test(attachment.filename) || attachment.type === "application/zip" || attachment.type === "application/x-zip-compressed";+ if (!isZip || attachment.size < 22) return byName;+ try {+ const tailObject = await env.BUCKET.get(attachment.r2Key, { range: { suffix: Math.min(attachment.size, 65_557) } });+ if (!tailObject) return byName;+ const tail = new Uint8Array(await tailObject.arrayBuffer());+ const located = locateZipDirectory(tail);+ if (!located) return byName;+ let directory: Uint8Array | null = null;+ if (located.size > 0 && located.size <= 1024 * 1024 && located.offset + located.size <= attachment.size) {+ const object = await env.BUCKET.get(attachment.r2Key, { range: { offset: located.offset, length: located.size } });+ if (object) directory = new Uint8Array(await object.arrayBuffer());+ }+ return mergeRisks(byName, inspectZipDirectory(tail, () => directory));+ } catch {+ return mergeRisks(byName, { level: "warning", reasons: ["This archive could not be checked."] });+ }+}diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex 39148bd..4861e96 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -311,6 +311,10 @@"attachment.loadFailed": "Could not load this attachment","attachment.unsupported": "This file type cannot be previewed safely in the browser.","attachment.download": "Download",+ "attachment.risk.ok": "No known risky file type",+ "attachment.risk.warning": "This file may not be what it seems.",+ "attachment.risk.blocked": "This file can run code or hide its real type.",+ "attachment.risk.acknowledge": "I understand the risk and still want to download it","auth.logout": "Log out","license.upgrade": "Upgrade","contact.title": "Contact details",diff --git a/tests/attachment-risk.test.mjs b/tests/attachment-risk.test.mjsnew file mode 100644index 0000000..d8178c0--- /dev/null+++ b/tests/attachment-risk.test.mjs@@ -0,0 +1,65 @@+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-attachment-risk-"));+after(() => rmSync(dir, { recursive: true, force: true }));+await build({ entryPoints: [join(root, "src/lib/email/attachment-risk.ts")], outfile: join(dir, "r.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent" });+const risk = await import(pathToFileURL(join(dir, "r.mjs")).href);++/** A minimal ZIP: only the central directory and end record matter to the inspector. */+function zip(names, { encrypted = false } = {}) {+ const parts = [];+ for (const name of names) {+ const nameBytes = Buffer.from(name);+ const entry = Buffer.alloc(46 + nameBytes.length);+ entry.writeUInt32LE(0x02014b50, 0);+ entry.writeUInt16LE(encrypted ? 1 : 0, 8);+ entry.writeUInt16LE(nameBytes.length, 28);+ nameBytes.copy(entry, 46);+ parts.push(entry);+ }+ const directory = Buffer.concat(parts);+ const end = Buffer.alloc(22);+ end.writeUInt32LE(0x06054b50, 0);+ end.writeUInt16LE(names.length, 10);+ end.writeUInt32LE(directory.length, 12);+ end.writeUInt32LE(0, 16);+ return { tail: new Uint8Array(Buffer.concat([directory, end])), directory: new Uint8Array(directory) };+}++test("dangerous types and disguised names are blocked, plain documents are fine", () => {+ for (const filename of ["setup.exe", "run.JS", "invoice.pdf.exe", "report.docm", "photo.jpg.scr", "evilgpj.exe", "shortcut.lnk"]) {+ assert.equal(risk.assessAttachmentRisk({ filename }).level, "blocked", filename);+ }+ for (const filename of ["login.html", "files.zip", "disk.iso", "logo.svg", "invoice.pdf.html"]) {+ assert.notEqual(risk.assessAttachmentRisk({ filename }).level, "ok", filename);+ }+ for (const filename of ["invoice.pdf", "notes.txt", "photo.jpeg", "budget.xlsx", "archive.2024.final.docx"]) {+ assert.equal(risk.assessAttachmentRisk({ filename, type: "application/octet-stream" }).level, "ok", filename);+ }+ assert.equal(risk.assessAttachmentRisk({ filename: "x.bin", type: "application/x-msdownload" }).level, "blocked");+});++test("a ZIP's contents are read from its central directory", () => {+ const { tail, directory } = zip(["docs/readme.txt", "setup.exe"]);+ const found = risk.inspectZipDirectory(tail, () => directory);+ assert.equal(found.level, "blocked");+ assert.match(found.reasons[0], /setup\.exe/);+ const clean = zip(["a.txt", "b.png"]);+ assert.equal(risk.inspectZipDirectory(clean.tail, () => clean.directory).level, "ok");+ const locked = zip(["a.txt"], { encrypted: true });+ assert.equal(risk.inspectZipDirectory(locked.tail, () => locked.directory).level, "warning");+ assert.equal(risk.inspectZipDirectory(tail, () => null).level, "warning", "unreadable directory is flagged, not trusted");+ assert.equal(risk.inspectZipDirectory(new Uint8Array(100), () => null).level, "ok", "not a zip");+});++test("merging keeps the strongest level and de-duplicates reasons", () => {+ const merged = risk.mergeRisks({ level: "warning", reasons: ["a"] }, { level: "blocked", reasons: ["b", "a"] }, { level: "ok", reasons: [] });+ assert.deepEqual(merged, { level: "blocked", reasons: ["a", "b"] });+});