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(server): vet the address behind an image URL before downloading it
Elian Doranae72af69a173
diff --git a/apps/server/src/services/request.spec.ts b/apps/server/src/services/request.spec.tsindex 25cd80fc39..dc767e9598 100644--- a/apps/server/src/services/request.spec.ts+++ b/apps/server/src/services/request.spec.ts@@ -1,3 +1,4 @@+import dns from "node:dns";import { EventEmitter } from "node:events";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -117,7 +118,9 @@ vi.mock("http-proxy-agent", () => ({ HttpProxyAgent }));vi.mock("https-proxy-agent", () => ({ HttpsProxyAgent }));vi.mock("@triliumnext/core", () => ({getLog: () => getLogMock,- sync_options: { getSyncProxy: getSyncProxyMock }+ sync_options: { getSyncProxy: getSyncProxyMock },+ // safe_fetch, reached through getImage's address validation, raises this one.+ ValidationError: class ValidationError extends Error {}}));import type { ExecOpts } from "@triliumnext/core";@@ -470,6 +473,77 @@ describe("NodeRequestProvider.getImage", () => {state.onEnd = null;fakeHttp.request.mockClear();getSyncProxyMock.mockReturnValue(null);+ // Every image URL is resolved before it is fetched, so the hostnames used throughout have+ // to resolve to something — and to something public, or the download is refused.+ vi.spyOn(dns.promises, "lookup").mockResolvedValue([+ { address: "93.184.216.34", family: 4 }+ ] as unknown as dns.LookupAddress);+ });++ describe("address validation", () => {+ /** The bytes an allowed download would have produced, so a leak would be visible. */+ const respondWithBytes = (req: FakeRequest) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from([1, 2, 3]));+ res.emitEnd();+ };++ it("refuses an address inside the network the server itself sits on", async () => {+ state.onEnd = respondWithBytes;++ for (const imageUrl of [+ "http://127.0.0.1/pic.png",+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/",+ "http://10.0.0.1/pic.png",+ "http://192.168.1.1/pic.png",+ "http://172.16.0.1/pic.png",+ "http://[::1]/pic.png"+ ]) {+ await expect(provider.getImage(imageUrl)).rejects.toThrow(/private\/internal/);+ }++ // Refused before anything is sent: the request must not be what discovers the problem.+ expect(state.requests).toHaveLength(0);+ });++ it("refuses a hostname that resolves into that network, however public it looks", async () => {+ vi.spyOn(dns.promises, "lookup").mockResolvedValue([+ { address: "127.0.0.1", family: 4 }+ ] as unknown as dns.LookupAddress);+ state.onEnd = respondWithBytes;++ await expect(provider.getImage("http://images.example.com/pic.png"))+ .rejects.toThrow(/private\/internal/);+ expect(state.requests).toHaveLength(0);+ });++ it("connects only to the address it validated, so a second lookup cannot redirect it", async () => {+ state.onEnd = respondWithBytes;+ await provider.getImage("http://images.example.com/pic.png");++ // The connection resolves the hostname through this, rather than asking DNS again —+ // which is what a rebinding answer would otherwise get to reply to.+ const lookup = state.requests[0].opts.lookup;+ expect(typeof lookup).toBe("function");++ const resolved = await new Promise((resolve, reject) => {+ lookup("images.example.com", { all: true }, (err: Error | null, addresses: unknown) =>+ err ? reject(err) : resolve(addresses));+ });+ expect(resolved).toEqual([{ address: "93.184.216.34", family: 4 }]);+ });++ it("refuses a URL that is not http(s), or that carries credentials", async () => {+ state.onEnd = respondWithBytes;++ await expect(provider.getImage("file:///etc/passwd")).rejects.toThrow(/http and https/);+ await expect(provider.getImage("ftp://example.com/pic.png")).rejects.toThrow(/http and https/);+ await expect(provider.getImage("not-a-url")).rejects.toThrow(/Invalid URL/);+ await expect(provider.getImage("http://user:[email protected]/pic.png"))+ .rejects.toThrow(/credentials/);+ expect(state.requests).toHaveLength(0);+ });});it("downloads image bytes and resolves an ArrayBuffer", async () => {diff --git a/apps/server/src/services/request.ts b/apps/server/src/services/request.tsindex 7b059b0d5d..84a75b55f2 100644--- a/apps/server/src/services/request.ts+++ b/apps/server/src/services/request.ts@@ -3,6 +3,8 @@import { type CookieJar, type ExecOpts, getLog, type RequestProvider, sync_options as syncOptions } from "@triliumnext/core";import url from "url";+import { createPinnedLookup, validateHostResolution, validateUrl } from "./safe_fetch.js";+// this service provides abstraction over node's HTTP/HTTPS modules.// Subclasses (e.g. apps/desktop's ElectronRequestProvider) can override// `getClient` to plug in alternative transports such as `electron.net`@@ -19,6 +21,11 @@ export interface ClientOpts {headers?: Record<string, string | number>;agent?: any;proxy?: string | null;+ /**+ * Resolves the host for the node http/https clients. Supplying one keeps a connection on an+ * address that has already been vetted, rather than on whatever DNS answers at connect time.+ */+ lookup?: unknown;}type RequestEvent = "error" | "response" | "abort";@@ -186,7 +193,23 @@ export default class NodeRequestProvider implements RequestProvider {});}+ /**+ * Fetches an image named by note content.+ *+ * The URL comes from whoever wrote the note, and a note is not always written by the person+ * whose server fetches it — a clipped page and an imported file both name their own images. So+ * the address is vetted before anything is sent: the server's own network is not somewhere note+ * content gets to reach, and what comes back is stored as an attachment the author can read.+ *+ * Vetting an address and then connecting to a name would leave the two free to disagree, so the+ * connection is pinned to the addresses that were actually checked. The pin is honoured by the+ * node clients; `electron.net` and a proxy each resolve the host themselves, and there it is+ * the check above that stands alone.+ */async getImage(imageUrl: string): Promise<ArrayBuffer> {+ const parsedTargetUrl = validateUrl(imageUrl);+ const validatedAddresses = await validateHostResolution(parsedTargetUrl.hostname);+const proxyConf = syncOptions.getSyncProxy();const opts: ClientOpts = {method: "GET",@@ -196,7 +219,6 @@ export default class NodeRequestProvider implements RequestProvider {const client = await this.getClient(opts);const proxyAgent = await getProxyAgent(opts);- const parsedTargetUrl = url.parse(opts.url);return new Promise<ArrayBuffer>((resolve, reject) => {try {@@ -208,10 +230,11 @@ export default class NodeRequestProvider implements RequestProvider {protocol: parsedTargetUrl.protocol,host: parsedTargetUrl.hostname,port: parsedTargetUrl.port,- path: parsedTargetUrl.path,+ path: `${parsedTargetUrl.pathname}${parsedTargetUrl.search}`,timeout: opts.timeout, // works only for the node clientheaders: {},- agent: proxyAgent+ agent: proxyAgent,+ lookup: createPinnedLookup(validatedAddresses)});request.on("error", (err) => reject(generateError(opts, err)));diff --git a/apps/server/src/services/safe_fetch.spec.ts b/apps/server/src/services/safe_fetch.spec.tsindex e54ca32bc0..fb48a838f0 100644--- a/apps/server/src/services/safe_fetch.spec.ts+++ b/apps/server/src/services/safe_fetch.spec.ts@@ -80,6 +80,18 @@ describe("validateHostResolution", () => {await expect(validateHostResolution("fe80::1")).rejects.toThrow("private/internal");});+ it("reads an IPv6 literal still wrapped in the brackets URL.hostname leaves on it", async () => {+ const lookup = vi.spyOn(dns.promises, "lookup");++ await expect(validateHostResolution("[::1]")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("[fe80::1]")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("[2606:4700:4700::1111]")).resolves.toEqual([+ { address: "2606:4700:4700::1111", family: 6 }+ ]);+ // Recognised as an address, so never taken for a name and looked up as one.+ expect(lookup).not.toHaveBeenCalled();+ });+it("allows public IP literals and returns validated addresses", async () => {await expect(validateHostResolution("8.8.8.8")).resolves.toEqual([{ address: "8.8.8.8", family: 4 }]);await expect(validateHostResolution("1.1.1.1")).resolves.toEqual([{ address: "1.1.1.1", family: 4 }]);diff --git a/apps/server/src/services/safe_fetch.ts b/apps/server/src/services/safe_fetch.tsindex 486e22655b..cc72dd607b 100644--- a/apps/server/src/services/safe_fetch.ts+++ b/apps/server/src/services/safe_fetch.ts@@ -32,17 +32,22 @@ function isBlockedIP(ip: string): boolean {* Returns the validated addresses so they can be pinned for the actual connection.*/async function validateHostResolution(hostname: string): Promise<dns.LookupAddress[]> {+ // `URL.hostname` hands back an IPv6 literal still wrapped in its brackets ("[::1]"), which is+ // not a form either net.isIP or ipaddr.js recognises. Left as-is, such an address would be+ // taken for a name and looked up as one instead of being checked as the address it is.+ const host = hostname.replace(/^\[|\]$/g, "");+// If the hostname is already an IP literal, check it directly- if (net.isIP(hostname)) {- if (isBlockedIP(hostname)) {+ if (net.isIP(host)) {+ if (isBlockedIP(host)) {throw new ValidationError("URLs pointing to private/internal networks are not allowed");}- return [{ address: hostname, family: net.isIP(hostname) as 4 | 6 }];+ return [{ address: host, family: net.isIP(host) as 4 | 6 }];}let addresses: dns.LookupAddress[];try {- addresses = await dns.promises.lookup(hostname, { all: true });+ addresses = await dns.promises.lookup(host, { all: true });} catch {throw new ValidationError("Could not resolve hostname");}@@ -210,4 +215,4 @@ async function safeFetch(url: string, options: RequestInit = {}): Promise<Responthrow new Error("Too many redirects");}-export { safeFetch, validateHostResolution, validateUrl };+export { createPinnedLookup, safeFetch, validateHostResolution, validateUrl };