Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(files): sandbox stored content served inline
Elian Doranbc528c868770
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.tsindex 8559236985..8e0e43563b 100644--- a/packages/trilium-core/src/routes/api/files.spec.ts+++ b/packages/trilium-core/src/routes/api/files.spec.ts@@ -214,12 +214,65 @@ describe("Files API (core)", () => {expect(download.headers["Content-Disposition"]).toBeTruthy();expect(download.headers["Content-Security-Policy"]).toBeUndefined();- // A non-SVG mime keeps the plain path, scripts and all.+ // A non-SVG mime keeps its bytes, scripts and all; the sandbox below keeps them inert.const plainId = await createSvgNote("text/plain");const plain = await api.get<string>(`/api/notes/${plainId}/open`);expect(plain.status).toBe(200);expect(plain.body).toContain("<script>");- expect(plain.headers["Content-Security-Policy"]).toBeUndefined();+ expect(plain.headers["Content-Security-Policy"]).toBe("sandbox");+ });+ });++ /** Any other mime that renders as a document runs its scripts the same way an SVG does. */+ describe("HTML and other documents served inline", () => {+ const MALICIOUS_HTML = `<!DOCTYPE html><html><body><script>alert(document.domain)</script></body></html>`;++ async function createNote(mime: string, type = "code"): Promise<string> {+ const res = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {+ body: { title: "page.html", type, mime, content: MALICIOUS_HTML }+ });+ expect(res.status).toBe(200);+ return res.body.note.noteId;+ }++ it("sandboxes an HTML note or attachment opened inline", async () => {+ for (const mime of [ "text/html", "application/xhtml+xml", "text/xml" ]) {+ const noteId = await createNote(mime);+ const res = await api.get<string>(`/api/notes/${noteId}/open`);+ expect(res.status, mime).toBe(200);+ expect(res.headers["Content-Type"], mime).toBe(mime);+ expect(res.headers["Content-Security-Policy"], mime).toBe("sandbox");+ expect(res.headers["X-Content-Type-Options"], mime).toBe("nosniff");+ expect(res.body, mime).toBe(MALICIOUS_HTML);+ }++ const { noteId } = await createTextNote(api, { title: "Has HTML" });+ const save = await api.post(`/api/notes/${noteId}/attachments`, {+ body: { role: "file", mime: "text/html", title: "page.html", content: MALICIOUS_HTML }+ });+ expect(save.status).toBe(204);+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);+ const { attachmentId } = list.body[0];++ const res = await api.get<string>(`/api/attachments/${attachmentId}/open`);+ expect(res.status).toBe(200);+ expect(res.headers["Content-Security-Policy"]).toBe("sandbox");+ expect(res.headers["X-Content-Type-Options"]).toBe("nosniff");+ });++ it("leaves a PDF opened inline and an HTML download without a sandbox", async () => {+ // Chrome refuses to display a PDF in a sandboxed document.+ const pdfId = await createNote("application/pdf", "file");+ const pdf = await api.get<string>(`/api/notes/${pdfId}/open`);+ expect(pdf.status).toBe(200);+ expect(pdf.headers["Content-Type"]).toBe("application/pdf");+ expect(pdf.headers["Content-Security-Policy"]).toBeUndefined();++ const htmlId = await createNote("text/html");+ const download = await api.get<string>(`/api/notes/${htmlId}/download`);+ expect(download.status).toBe(200);+ expect(download.headers["Content-Disposition"]).toMatch(/^attachment;/);+ expect(download.headers["Content-Security-Policy"]).toBeUndefined();});});diff --git a/packages/trilium-core/src/routes/api/image.spec.ts b/packages/trilium-core/src/routes/api/image.spec.tsindex 1134de1150..aaca1d2d1b 100644--- a/packages/trilium-core/src/routes/api/image.spec.ts+++ b/packages/trilium-core/src/routes/api/image.spec.ts@@ -105,6 +105,26 @@ describe("Image API (core)", () => {expect(Buffer.from(res.body as Buffer)).toEqual(PNG_BYTES);});+ it("sandboxes an image note or attachment whose mime renders as HTML", async () => {+ const payload = "<html><script>alert(document.domain)</script></html>";+ const noteId = await createImageNote({+ mime: "text/html",+ content: payload,+ attachments: [ { title: "page.html", role: "image", mime: "text/html", content: payload } ]+ });++ const fromNote = await api.get<string>(`/api/images/${noteId}/file.png`);+ expect(fromNote.status).toBe(200);+ expect(fromNote.headers["Content-Security-Policy"]).toBe("sandbox");+ expect(fromNote.headers["X-Content-Type-Options"]).toBe("nosniff");++ const [ attachment ] = becca.getNoteOrThrow(noteId).getAttachments();+ const fromAttachment = await api.get<string>(`/api/attachments/${attachment.attachmentId}/image/file.png`);+ expect(fromAttachment.status).toBe(200);+ expect(fromAttachment.headers["Content-Security-Policy"]).toBe("sandbox");+ expect(fromAttachment.headers["X-Content-Type-Options"]).toBe("nosniff");+ });+it("sanitizes a real SVG image note", async () => {const noteId = await createImageNote({mime: "image/svg+xml",diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.tsindex e472073083..7a258638ee 100644--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@ -1,4 +1,4 @@-import { type ImageCompressionOptions, isAcceptedImageMime, isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";+import { type ImageCompressionOptions, isAcceptedImageMime, isImageAttachmentRole, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import type { Request, Response } from "../../http_interface";import becca from "../../becca/becca.js";@@ -9,7 +9,7 @@ import imageService from "../../services/image.js";import imageCompressionService from "../../services/image_compression.js";import imageInfoService from "../../services/image_info.js";import imageInventoryService from "../../services/image_inventory.js";-import { sendSanitizedSvg } from "../helpers.js";+import { sendInlineContent, sendSanitizedSvg } from "../helpers.js";function returnImageFromNote(req: Request<{ noteId: string }>, res: Response) {const image = becca.getNote(req.params.noteId);@@ -43,12 +43,7 @@ function returnImageInt(image: BNote | BRevision | null, res: Response) {} else {res.set("Content-Type", image.mime);res.set("Cache-Control", "no-cache, no-store, must-revalidate");-- if (isSvgMime(image.mime)) {- sendSanitizedSvg(res, image.getContent());- } else {- res.send(image.getContent());- }+ sendInlineContent(res, image.mime, image.getContent());}}@@ -100,12 +95,7 @@ function returnAttachedImage(req: Request<{ attachmentId: string }>, res: Responres.set("Content-Type", attachment.mime);res.set("Cache-Control", "no-cache, no-store, must-revalidate");-- if (isSvgMime(attachment.mime)) {- sendSanitizedSvg(res, attachment.getContent());- } else {- res.send(attachment.getContent());- }+ sendInlineContent(res, attachment.mime, attachment.getContent());}async function updateImage(req: Request<{ noteId: string }>) {diff --git a/packages/trilium-core/src/routes/helpers.ts b/packages/trilium-core/src/routes/helpers.tsindex 5ca8facf89..b9f214ff19 100644--- a/packages/trilium-core/src/routes/helpers.ts+++ b/packages/trilium-core/src/routes/helpers.ts@@ -6,7 +6,7 @@ import noteService from "../services/notes";import protected_session from "../services/protected_session";import BAttachment from "../becca/entities/battachment";import { unwrapStringOrBuffer } from "../services/utils/binary";-import { getContentDisposition, sanitizeSvg, SVG_CONTENT_SECURITY_POLICY } from "../services/utils/index";+import { getContentDisposition, getInlineContentHeaders, sanitizeSvg, SVG_CONTENT_SECURITY_POLICY } from "../services/utils/index";export function downloadNoteInt(noteId: string, res: Response, contentDisposition = true) {const note = becca.getNote(noteId);@@ -33,16 +33,30 @@ export function downloadData(noteOrAttachment: BNote | BAttachment, res: Responsres.setHeader("Content-Type", noteOrAttachment.mime);// Without a Content-Disposition the browser renders the response instead of saving it, and an SVG- // rendered as a document runs its scripts in Trilium's origin. A download is left byte-for-byte:+ // or HTML document runs its scripts in Trilium's origin. A download is left byte-for-byte:// `getContentDisposition()` marks it `attachment`, which never renders, and the file the user// asked for has to reach the disk as it was stored.- if (!contentDisposition && isSvgMime(noteOrAttachment.mime)) {- return sendSanitizedSvg(res, noteOrAttachment.getContent());+ if (!contentDisposition) {+ if (isSvgMime(noteOrAttachment.mime)) {+ return sendSanitizedSvg(res, noteOrAttachment.getContent());+ }++ setHeaders(res, getInlineContentHeaders(noteOrAttachment.mime));}res.send(noteService.getPortableContent(noteOrAttachment));}+/** Serves stored content inline: an SVG sanitized, anything else as is under {@link getInlineContentHeaders}. */+export function sendInlineContent(res: Response, mime: string, content: string | Uint8Array) {+ if (isSvgMime(mime)) {+ return sendSanitizedSvg(res, content);+ }++ setHeaders(res, getInlineContentHeaders(mime));+ res.send(content);+}+/*** Serves SVG content stripped of everything that executes, behind a Content-Security-Policy that* blocks scripting even if a payload survives {@link sanitizeSvg}, and `nosniff` so the response@@ -54,3 +68,9 @@ export function sendSanitizedSvg(res: Response, content: string | Uint8Array) {res.setHeader("X-Content-Type-Options", "nosniff");res.send(sanitizeSvg(svgString));}++function setHeaders(res: Response, headers: Record<string, string>) {+ for (const [ name, value ] of Object.entries(headers)) {+ res.setHeader(name, value);+ }+}diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsindex 46775b6c8b..954456f9cf 100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@ -212,6 +212,19 @@ export function sanitizeSqlIdentifier(str: string) {*/export const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:";+/**+ * Headers for stored, non-SVG content served without a `Content-Disposition`. A browser that+ * navigates to such a response renders it as a document in Trilium's origin, so `sandbox` keeps+ * its scripts from running. Embedders (`<img>`, `<video>`, `fetch()`, `@font-face`) ignore the+ * policy. A PDF goes without it, because Chrome refuses to display a sandboxed PDF.+ */+export function getInlineContentHeaders(mime: string): Record<string, string> {+ return {+ "X-Content-Type-Options": "nosniff",+ ...(mime === "application/pdf" ? {} : { "Content-Security-Policy": "sandbox" })+ };+}+/*** Sanitize SVG to remove potentially dangerous elements and attributes.* This prevents XSS via script injection in SVG content.diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.tsindex 4975a12392..b3c67b06d4 100644--- a/packages/trilium-core/src/share/handlers.spec.ts+++ b/packages/trilium-core/src/share/handlers.spec.ts@@ -249,6 +249,26 @@ describe("share handlers", () => {}});+ it("sandboxes a note viewed inline unless it is a PDF", () => {+ buildShareTree([+ { id: "htmlFile", type: "file", mime: "text/html", content: "<script>alert(1)</script>" },+ { id: "pdfFile", type: "file", mime: "application/pdf", content: "%PDF" }+ ]);+ const view = (noteId: string) => request("/share/api/notes/:noteId/view", { params: { noteId } });++ const html = view("htmlFile");+ expect(html).toMatchObject({ status: 200, body: "<script>alert(1)</script>" });+ expect(html.headers).toMatchObject({+ "Content-Type": "text/html",+ "Content-Security-Policy": "sandbox",+ "X-Content-Type-Options": "nosniff"+ });++ const pdf = view("pdfFile");+ expect(pdf).toMatchObject({ status: 200, body: "%PDF" });+ expect(pdf.headers).not.toHaveProperty("Content-Security-Policy");+ });+it("locks a raw SVG note down with a content security policy, but not raw HTML", () => {buildShareTree([{ id: "rawSvg", type: "image", mime: "image/svg+xml", content: "<svg/>", "#shareRaw": "" },@@ -405,7 +425,12 @@ describe("share handlers", () => {const png = image("pngAttachment");expect(png).toMatchObject({ status: 200, body: pngBytes });- expect(png.headers).toEqual({ "X-Robots-Tag": "noindex", "Content-Type": "image/png" });+ expect(png.headers).toEqual({+ "X-Robots-Tag": "noindex",+ "Content-Type": "image/png",+ "Content-Security-Policy": "sandbox",+ "X-Content-Type-Options": "nosniff"+ });const svg = image("svgAttachment");expect(svg.body).toBe("<svg></svg>");diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsindex f4963a029e..38c6e75ef2 100644--- a/packages/trilium-core/src/share/handlers.ts+++ b/packages/trilium-core/src/share/handlers.ts@@ -326,7 +326,8 @@ function viewNote(req: ShareRequest): ShareReply {headers: {...noIndexHeaders(note),"Cache-Control": "no-cache, no-store, must-revalidate",- "Content-Type": note.mime+ "Content-Type": note.mime,+ ...utils.getInlineContentHeaders(note.mime)},body: note.getContent()};@@ -659,7 +660,7 @@ function serveImageBytes(content: string | Uint8Array | undefined, mime: string,return {status: 200,- headers: { ...headers, "Content-Type": mime },+ headers: { ...headers, "Content-Type": mime, ...utils.getInlineContentHeaders(mime) },body: content};}