From 0099d587a05ad45b0b41fbd07ee8ead1a52152c0 Mon Sep 17 00:00:00 2001 From: bouni Date: Fri, 20 Nov 2026 14:40:23 +0100 Subject: [PATCH] Check template installer hosts as parsed IP addresses The remote template installer's host guard compared IP literals as strings. Parse IPv4 and IPv6 literals into numbers and check the address ranges numerically instead (new utils/ipRanges.ts), so every spelling of an address is handled the same way. Resolved DNS addresses go through the same check. The range list now also covers translated and embedded IPv4 forms, deprecated site-local and multicast IPv6, and the IPv4 multicast, reserved, benchmarking and IETF protocol ranges. Co-Authored-By: Claude Opus 5.5 --- backend/src/controllers/templates.ts | 72 +---------------- backend/src/utils/ipRanges.ts | 114 +++++++++++++++++++++++++++ backend/src/utils/ipRanges_test.ts | 65 +++++++++++++++ 3 files changed, 181 insertions(+), 70 deletions(-) create mode 100644 backend/src/utils/ipRanges.ts create mode 100644 backend/src/utils/ipRanges_test.ts diff --git a/backend/src/controllers/templates.ts b/backend/src/controllers/templates.ts index 0c1a7a2e..88de35c6 100644 --- a/backend/src/controllers/templates.ts +++ b/backend/src/controllers/templates.ts @@ -5,6 +5,7 @@ import { generateUUID } from "../utils/uuid.ts"; import { parse as parseYaml } from "yaml"; import { dirname, isAbsolute, normalize, relative, resolve } from "std/path"; import { ZipReader } from "https://deno.land/x/zipjs@v2.7.34/index.js"; +import { isInternalAddress, stripIpv6Brackets } from "../utils/ipRanges.ts"; // Manifest-based installer (MVP): one HTML file + optional fonts (ignored for now) type ManifestHTML = { @@ -119,82 +120,13 @@ const FORBIDDEN_HOSTS = new Set([ "::1", ]); -function isPrivateIPv4(hostname: string): boolean { - const parts = hostname.split(".").map((p) => Number(p)); - if (parts.length !== 4 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) { - return false; - } - const [a, b] = parts; - if (a === 10) return true; - if (a === 192 && b === 168) return true; - if (a === 172 && b >= 16 && b <= 31) return true; - if (a === 169 && b === 254) return true; - if (a === 127) return true; - if (a === 0) return true; - // CGNAT / carrier-grade NAT (RFC 6598) — internal in shared-hosting envs. - if (a === 100 && b >= 64 && b <= 127) return true; - return false; -} - -// Normalize an IPv6 literal the way URL.hostname returns it: it is wrapped in -// square brackets (e.g. "[::1]"). Strip them so range checks see the raw -// address. Returns the lower-cased address without brackets. -function stripIpv6Brackets(hostname: string): string { - const lower = hostname.toLowerCase(); - if (lower.startsWith("[") && lower.endsWith("]")) { - return lower.slice(1, -1); - } - return lower; -} - -function isPrivateIPv6(hostname: string): boolean { - const addr = stripIpv6Brackets(hostname); - if (!addr.includes(":")) return false; // not an IPv6 literal - // Loopback ::1 and the unspecified address :: - if (addr === "::1" || addr === "::") return true; - // IPv4-mapped (::ffff:a.b.c.d / ::ffff:7f00:1) and IPv4-compatible / NAT64 / - // 6to4 all embed an IPv4 address — extract and re-check against IPv4 rules. - const mappedV4 = extractEmbeddedIPv4(addr); - if (mappedV4 && isPrivateIPv4(mappedV4)) return true; - // Unique-local fc00::/7 (fc.. and fd..) and link-local fe80::/10. - if (/^f[cd][0-9a-f]{0,2}:/.test(addr) || addr === "fc00" || addr === "fd00") { - return true; - } - if (/^fe[89ab][0-9a-f]?:/.test(addr)) return true; - return false; -} - -// Pull an embedded IPv4 address out of IPv4-mapped/compatible/NAT64/6to4 IPv6 -// forms so it can be validated against the IPv4 private ranges. -function extractEmbeddedIPv4(addr: string): string | null { - // Dotted-quad tail, e.g. ::ffff:127.0.0.1 or 64:ff9b::127.0.0.1 - const dotted = addr.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); - if (dotted) return dotted[1]; - // Hextet-encoded IPv4-mapped, e.g. ::ffff:7f00:1 -> 127.0.0.1 - const mapped = addr.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/); - if (mapped) { - const hi = parseInt(mapped[1], 16); - const lo = parseInt(mapped[2], 16); - return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`; - } - // 6to4 2002:V4V4::/16 and NAT64 64:ff9b::V4V4 first two hextets after prefix. - const sixToFour = addr.match(/^2002:([0-9a-f]{1,4}):([0-9a-f]{1,4})/); - if (sixToFour) { - const hi = parseInt(sixToFour[1], 16); - const lo = parseInt(sixToFour[2], 16); - return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`; - } - return null; -} - // True if a literal/resolved IP string targets an internal range. function isForbiddenAddress(host: string): boolean { const h = host.toLowerCase(); if (FORBIDDEN_HOSTS.has(h)) return true; const bare = stripIpv6Brackets(h); if (FORBIDDEN_HOSTS.has(bare)) return true; - if (isPrivateIPv4(bare) || isPrivateIPv6(h)) return true; - return false; + return isInternalAddress(bare); } async function assertSafeRemoteUrl(raw: string, field: string): Promise { diff --git a/backend/src/utils/ipRanges.ts b/backend/src/utils/ipRanges.ts new file mode 100644 index 00000000..f8c43ce3 --- /dev/null +++ b/backend/src/utils/ipRanges.ts @@ -0,0 +1,114 @@ +// Address checks for the SSRF guard of the remote template installer. +// +// Hosts are compared as parsed numbers, not as strings: URL.hostname +// normalizes IP literals (IPv4 shorthand/hex/decimal to dotted quads, IPv6 to +// bracketed, compressed hextets such as "[64:ff9b::7f00:1]"), so string +// prefixes miss many spellings of the same internal address. + +/** Strip the square brackets URL.hostname puts around IPv6 literals. */ +export function stripIpv6Brackets(hostname: string): string { + const lower = hostname.toLowerCase(); + return lower.startsWith("[") && lower.endsWith("]") + ? lower.slice(1, -1) + : lower; +} + +/** Parse a dotted-quad IPv4 address into 4 octets, or null. */ +export function parseIPv4(addr: string): number[] | null { + const parts = addr.split("."); + if (parts.length !== 4) return null; + const octets = parts.map((p) => (/^\d{1,3}$/.test(p) ? Number(p) : NaN)); + return octets.every((n) => n >= 0 && n <= 255) ? octets : null; +} + +/** Parse an IPv6 address (without brackets or zone id) into 8 hextets, or null. */ +export function parseIPv6(addr: string): number[] | null { + if (!addr.includes(":")) return null; + let head = addr; + // A trailing dotted quad stands for the last two hextets + const tail: number[] = []; + const v4 = addr.match(/^(.*:)(\d{1,3}(?:\.\d{1,3}){3})$/); + if (v4) { + const o = parseIPv4(v4[2]); + if (!o) return null; + head = v4[1].endsWith("::") ? v4[1] : v4[1].slice(0, -1); + tail.push((o[0] << 8) | o[1], (o[2] << 8) | o[3]); + } + const halves = head.split("::"); + if (halves.length > 2) return null; + const toHextets = (s: string) => + s === "" ? [] : s.split(":").map((h) => + /^[0-9a-f]{1,4}$/i.test(h) ? parseInt(h, 16) : NaN + ); + const left = toHextets(halves[0]); + const right = halves.length === 2 ? toHextets(halves[1]) : []; + const given = left.length + right.length + tail.length; + if ([...left, ...right].some(Number.isNaN)) return null; + if (halves.length === 1 && given !== 8) return null; + if (halves.length === 2 && given > 7) return null; + const zeros = new Array(8 - given).fill(0); + return [...left, ...zeros, ...right, ...tail]; +} + +/** True for IPv4 addresses that must never be fetched server-side. */ +export function isInternalIPv4(octets: number[]): boolean { + const [a, b, c] = octets; + return ( + a === 0 || // "this network", includes 0.0.0.0 + a === 10 || // private + a === 127 || // loopback + (a === 100 && b >= 64 && b <= 127) || // carrier-grade NAT (RFC 6598) + (a === 169 && b === 254) || // link-local, cloud metadata + (a === 172 && b >= 16 && b <= 31) || // private + (a === 192 && b === 0 && c === 0) || // IETF protocol assignments + (a === 192 && b === 168) || // private + (a === 198 && (b === 18 || b === 19)) || // benchmarking + a >= 224 // multicast, reserved, broadcast + ); +} + +/** IPv4 address embedded in the last two hextets. */ +function embeddedIPv4(h: number[]): number[] { + return [h[6] >> 8, h[6] & 0xff, h[7] >> 8, h[7] & 0xff]; +} + +/** True for IPv6 addresses that must never be fetched server-side. */ +export function isInternalIPv6(h: number[]): boolean { + const firstSixZero = h.slice(0, 6).every((x) => x === 0); + // ::/96 covers :: (unspecified), ::1 (loopback) and the deprecated + // IPv4-compatible addresses ::a.b.c.d + if (firstSixZero) return true; + // IPv4-mapped ::ffff:a.b.c.d + if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) { + return isInternalIPv4(embeddedIPv4(h)); + } + // NAT64 well-known prefix 64:ff9b::/96 translates to the embedded IPv4 + if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every((x) => x === 0)) { + return isInternalIPv4(embeddedIPv4(h)); + } + // Local-use NAT64 64:ff9b:1::/48 is site-internal by definition + if (h[0] === 0x64 && h[1] === 0xff9b && h[2] === 1) return true; + // 6to4 2002:a.b.c.d::/48 + if (h[0] === 0x2002) { + return isInternalIPv4([h[1] >> 8, h[1] & 0xff, h[2] >> 8, h[2] & 0xff]); + } + if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7 + if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10 + if ((h[0] & 0xffc0) === 0xfec0) return true; // site-local fec0::/10 (deprecated) + if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8 + return false; +} + +/** + * True if `host` (a URL hostname or a resolved address) is an IP literal in + * an internal range. Hostnames that aren't IP literals return false; they + * are checked by resolving them. + */ +export function isInternalAddress(host: string): boolean { + const bare = stripIpv6Brackets(host); + const v4 = parseIPv4(bare); + if (v4) return isInternalIPv4(v4); + const v6 = parseIPv6(bare); + if (v6) return isInternalIPv6(v6); + return false; +} diff --git a/backend/src/utils/ipRanges_test.ts b/backend/src/utils/ipRanges_test.ts new file mode 100644 index 00000000..843f3e1e --- /dev/null +++ b/backend/src/utils/ipRanges_test.ts @@ -0,0 +1,65 @@ +import { isInternalAddress, parseIPv6 } from "./ipRanges.ts"; + +function assertEquals(actual: unknown, expected: unknown, label = ""): void { + const a = JSON.stringify(actual); + const e = JSON.stringify(expected); + if (a !== e) throw new Error(`${label}: expected ${e}, received ${a}`); +} + +Deno.test("parseIPv6 expands compressed and dotted forms", () => { + assertEquals(parseIPv6("::1"), [0, 0, 0, 0, 0, 0, 0, 1]); + assertEquals(parseIPv6("::"), [0, 0, 0, 0, 0, 0, 0, 0]); + assertEquals(parseIPv6("fe80::1"), [0xfe80, 0, 0, 0, 0, 0, 0, 1]); + assertEquals( + parseIPv6("::ffff:127.0.0.1"), + [0, 0, 0, 0, 0, 0xffff, 0x7f00, 1], + ); + assertEquals( + parseIPv6("2001:db8:0:0:0:0:2:1"), + [0x2001, 0xdb8, 0, 0, 0, 0, 2, 1], + ); + for (const bad of ["1::2::3", "12345::", "1:2:3:4:5:6:7:8:9", "g::1", "1.2.3.4", "1:2"]) { + assertEquals(parseIPv6(bad), null, bad); + } +}); + +// Hosts as URL.hostname returns them, i.e. after WHATWG normalization +// (that is how the guard sees them). +const hostname = (u: string) => new URL(`https://${u}/`).hostname; + +Deno.test("internal addresses are rejected however they are written", () => { + const internal = [ + // IPv4, including shorthand/hex/decimal spellings URL normalizes + "127.0.0.1", "127.1", "0x7f.1", "2130706433", "0.0.0.0", "10.1.2.3", + "172.16.0.1", "172.31.255.255", "192.168.1.1", "169.254.169.254", + "100.64.0.1", "192.0.0.8", "198.18.0.1", "224.0.0.1", "255.255.255.255", + // IPv6 loopback/unspecified and IPv4-compatible + "[::1]", "[::]", "[0:0:0:0:0:0:0:1]", "[::127.0.0.1]", "[::a00:1]", + // IPv4-mapped + "[::ffff:127.0.0.1]", "[::ffff:a9fe:a9fe]", "[::ffff:10.0.0.1]", + // NAT64 (the hextet form is what URL produces) and local-use NAT64 + "[64:ff9b::127.0.0.1]", "[64:ff9b::7f00:1]", "[64:ff9b::a00:1]", + "[64:ff9b::a9fe:a9fe]", "[64:ff9b:1::1]", + // 6to4 of internal IPv4 + "[2002:7f00:1::]", "[2002:a00:1::1]", + // Unique local, link-local, site-local, multicast + "[fc00::1]", "[fd12:3456::1]", "[fe80::1]", "[febf::1]", "[fec0::1]", + "[ff02::1]", + ]; + for (const host of internal) { + assertEquals(isInternalAddress(hostname(host)), true, host); + } +}); + +Deno.test("public addresses and names pass the literal check", () => { + const external = [ + "1.1.1.1", "8.8.8.8", "100.63.255.255", "100.128.0.1", "172.32.0.1", + "192.169.0.1", "[2606:4700:4700::1111]", "[64:ff9b::808:808]", + "[2002:808:808::]", "[::ffff:8.8.8.8]", + // Names are checked by DNS resolution, not here + "example.com", "raw.githubusercontent.com", + ]; + for (const host of external) { + assertEquals(isInternalAddress(hostname(host)), false, host); + } +});