Skip to content

Build your personal knowledge base with Trilium Notes

fix(link_embed): better SSRF protection

Elian Doran67216905ca0f
diff --git a/apps/server/package.json b/apps/server/package.json
index 1616782c3e..43f3c359de 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -41,6 +41,7 @@
"i18next": "26.2.0",
"i18next-fs-backend": "2.6.5",
"js-yaml": "4.1.1",
+ "private-ip": "^3.0.2",
"unpdf": "1.6.2"
},
"devDependencies": {
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index 1ae463d043..691e6275ee 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -1,4 +1,7 @@
import type { Request } from "express";
+import dns from "node:dns";
+import net from "node:net";
+import isIpPrivate from "private-ip";
import { parse } from "node-html-parser";
import type { LinkEmbedMetadata } from "@triliumnext/commons";
import log from "../../services/log.js";
@@ -7,28 +10,41 @@ import { ValidationError } from "@triliumnext/core";
const FETCH_TIMEOUT_MS = 5000;
const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB
const MAX_FAVICON_SIZE = 64 * 1024; // 64KB
+const MAX_REDIRECTS = 5;
const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?.*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;
-const BLOCKED_HOSTNAME_PATTERNS = [
- /^localhost$/i,
- /^127\./,
- /^10\./,
- /^172\.(1[6-9]|2\d|3[01])\./,
- /^192\.168\./,
- /^0\./,
- /^169\.254\./,
- /^\[::1\]$/,
- /^\[fc/i,
- /^\[fd/i,
- /^\[fe80:/i
-];
-
function extractYouTubeVideoId(url: string): string | null {
const match = url.match(YOUTUBE_REGEX);
return match ? match[1] : null;
}
+/**
+ * Resolves the hostname to IP addresses and verifies none are private/reserved.
+ */
+async function validateHostResolution(hostname: string): Promise<void> {
+ // If the hostname is already an IP literal, check it directly
+ if (net.isIP(hostname)) {
+ if (isIpPrivate(hostname) !== false) {
+ throw new ValidationError("URLs pointing to private/internal networks are not allowed");
+ }
+ return;
+ }
+
+ let addresses: dns.LookupAddress[];
+ try {
+ addresses = await dns.promises.lookup(hostname, { all: true });
+ } catch {
+ throw new ValidationError("Could not resolve hostname");
+ }
+
+ for (const addr of addresses) {
+ if (isIpPrivate(addr.address) !== false) {
+ throw new ValidationError("URLs pointing to private/internal networks are not allowed");
+ }
+ }
+}
+
function validateUrl(urlString: string): URL {
let parsed: URL;
try {
@@ -41,13 +57,38 @@ function validateUrl(urlString: string): URL {
throw new ValidationError("Only http and https URLs are supported");
}
- for (const pattern of BLOCKED_HOSTNAME_PATTERNS) {
- if (pattern.test(parsed.hostname)) {
- throw new ValidationError("URLs pointing to private/internal networks are not allowed");
+ return parsed;
+}
+
+/**
+ * Fetches a URL with SSRF protection: resolves the hostname and validates
+ * the resulting IP before each request, including on redirects.
+ */
+async function safeFetch(url: string, options: RequestInit = {}): Promise<Response> {
+ let currentUrl = url;
+
+ for (let i = 0; i <= MAX_REDIRECTS; i++) {
+ const parsed = validateUrl(currentUrl);
+ await validateHostResolution(parsed.hostname);
+
+ const response = await fetch(currentUrl, {
+ ...options,
+ redirect: "manual",
+ signal: options.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS)
+ });
+
+ if (response.status >= 300 && response.status < 400) {
+ const location = response.headers.get("location");
+ if (!location) throw new Error("Redirect without Location header");
+ // Resolve relative redirects against the current URL
+ currentUrl = new URL(location, currentUrl).toString();
+ continue;
}
+
+ return response;
}
- return parsed;
+ throw new Error("Too many redirects");
}
/**
@@ -56,10 +97,7 @@ function validateUrl(urlString: string): URL {
*/
async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | undefined> {
try {
- const response = await fetch(faviconUrl, {
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
- redirect: "follow"
- });
+ const response = await safeFetch(faviconUrl);
if (!response.ok) return undefined;
@@ -133,9 +171,7 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkE
}
async function fetchOpenGraphData(url: string) {
- const response = await fetch(url, {
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
- redirect: "follow",
+ const response = await safeFetch(url, {
headers: {
"User-Agent": "TriliumBot/1.0 (Link Preview)",
"Accept": "text/html"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 245486eb5a..bd70e2d728 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -399,7 +399,7 @@ importers:
version: 6.3.3
copy-webpack-plugin:
specifier: 14.0.0
happy-dom:
specifier: 20.9.0
version: 20.9.0
@@ -616,6 +616,9 @@ importers:
js-yaml:
specifier: 4.1.1
version: 4.1.1
+ private-ip:
+ specifier: ^3.0.2
+ version: 3.0.2
unpdf:
specifier: 1.6.2
version: 1.6.2(@napi-rs/[email protected])
@@ -1927,6 +1930,9 @@ packages:
'@catppuccin/[email protected]':
resolution: {integrity: sha512-qXhwKiLzQomUygUJYB36YAFgs+dET5bIocfkiaFIatQF5Pwc7L112TlF9P8J5Oqs3x3XTjYSucG0ncHXSCuk7Q==}
+ '@chainsafe/[email protected]':
+ resolution: {integrity: sha512-KIjt+6IfysQ4GCv66xihEitBjvhU/bixbbbFxdJ1sqCp4uJ0wuZiYBPhksZoy4lfaF0k9cwNzY5upEW/VWdw3w==}
+
'@chevrotain/[email protected]':
resolution: {integrity: sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==}
@@ -2499,7 +2505,7 @@ packages:
engines: {node: '>=14'}
'@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2':
- resolution: {gitHosted: true, integrity: sha512-MXgzlTDEEndJB3TBbvd5uFQO/8gaINo1Hfen8vef5rq/VHVPeB63uuv/uO5+8GFsAJ/rauu6XB79S6K4+aXc+w==, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}
+ resolution: {gitHosted: true, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}
version: 10.2.0-electron.1
engines: {node: '>=12.13.0'}
hasBin: true
@@ -9135,10 +9141,18 @@ packages:
resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==}
engines: {node: '>= 12'}
+ resolution: {integrity: sha512-fOCG6lhoKKakwv+C6KdsOnGvgXnmgfmp0myi3bcNwj3qfwPAxRKWEuFhvEFF7ceYIz6+1jRZ+yguLFAmUNPEfw==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}
engines: {node: '>= 0.10'}
+ resolution: {integrity: sha512-9VGk3HGanVE6JoZXHiCpnGy5X0jYDnN4EA4lntFPj+1vIWlFhIylq2CrrCOJH9EAhc5CYhq18F2Av2tgoAPsYQ==}
+ engines: {node: '>= 10'}
+
resolution: {integrity: sha512-Xi9/ZSn4NFapG8RP98iNPMOeaV3mXPisxKxzKtHVqr3g56j/fBn+yZmnxSVAA8lmZbl2J9b/a4kJvfU3hqQYgA==}
engines: {node: '>=0.10.0'}
@@ -11124,6 +11138,10 @@ packages:
resolution: {integrity: sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-2pkOVPGYD/4QyAg95c6E/4bLYXPthT5Xw4ocXYzIIsMBhskOMn6IwkWXmg6ZiA6K58+O6VD/n02r1hDhk7vDPw==}
+ engines: {node: '>=14.16'}
+
resolution: {integrity: sha512-Kcmo2FhfDTXdcbfDH76N7uBYHINxc/8GW7UAVuVP9I+Va3uHSerrnKV6dLooga/gh7GlgzuCCr/eoldnL1muGw==}
engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
@@ -13725,6 +13743,8 @@ snapshots:
'@catppuccin/[email protected]': {}
+ '@chainsafe/[email protected]': {}
+
'@chevrotain/[email protected]':
dependencies:
'@chevrotain/gast': 11.0.3
@@ -21338,14 +21358,14 @@ snapshots:
dependencies:
glob-parent: 6.0.2
normalize-path: 3.0.0
schema-utils: 4.3.3
serialize-javascript: 7.0.5
tinyglobby: 0.2.16
dependencies:
@@ -23656,8 +23676,12 @@ snapshots:
+
+
dependencies:
is-relative: 0.1.3
@@ -25828,6 +25852,13 @@ snapshots:
+ dependencies:
+ '@chainsafe/is-ip': 2.1.0
+ ip-regex: 5.0.0
+ ipaddr.js: 2.4.0
+ netmask: 2.1.1
+
@@ -27375,17 +27406,16 @@ snapshots:
rimraf: 2.6.3
optional: true
dependencies:
'@jridgewell/trace-mapping': 0.3.31
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.47.1
optionalDependencies:
esbuild: 0.28.0
lightningcss: 1.32.0
- postcss: 8.5.15
dependencies:
@@ -28221,7 +28251,7 @@ snapshots:
- postcss
- uglify-js
dependencies:
'@types/eslint-scope': 3.7.7
'@types/estree': 1.0.9
@@ -28244,7 +28274,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.3
watchpack: 2.5.1
webpack-sources: 3.4.1
transitivePeerDependencies: