339 lines
15 KiB
JavaScript
339 lines
15 KiB
JavaScript
"use strict";
|
|
|
|
// Canonical SSRF guard for remote URL fetches: URL uploads, remote imports,
|
|
// update/release downloads — every place the panel (index.js) or the node
|
|
// relay (nodes.js) is about to make the server fetch a user-influenced URL.
|
|
// One implementation, required by both sides, so the rules cannot drift —
|
|
// same convention as utils/upload-filename.js ("shared sanitizers so every
|
|
// side agrees"). nodes.js previously carried a weaker private copy
|
|
// (uploaderAssertSafeRemoteUrl) that missed site-local fec0::/10, multicast
|
|
// ff00::/8, NAT64 64:ff9b::/96 and the 80/443 port allowlist; that copy is
|
|
// gone and this module is the single source of truth.
|
|
//
|
|
// The node daemon independently re-validates URL, ports and resolved IPs at
|
|
// connect time (main.go uploadURLPortAllowed and its own private-IP checks),
|
|
// so this module is the panel-side pre-flight layer of that defense, not the
|
|
// only one.
|
|
//
|
|
// Semantics:
|
|
// - http(s) URLs only, no embedded credentials, no localhost/.local hosts.
|
|
// - Ports 80/443 only, unless REMOTE_FETCH_ALLOW_ANY_PORT=1. F9: strict
|
|
// "1" parsing fails safe (a careless "true"/"yes" leaves the allowlist
|
|
// enforced), both the enabled and the ignored-but-set states are
|
|
// announced at startup, and every non-standard-port acceptance is
|
|
// audit-logged, throttled per host:port so chatty mirrors cannot flood.
|
|
// - No resolution to a private/reserved address: loopback, RFC1918, CGNAT
|
|
// (100.64/10), link-local, TEST-NETs (192.0.2/24, 198.51.100/24,
|
|
// 203.0.113/24), benchmarking (198.18/15), 0/8 and >=224/4 for IPv4;
|
|
// unspecified/loopback, ULA (fc00::/7), link-local (fe80::/10), deprecated
|
|
// site-local (fec0::/10), multicast (ff00::/8), the IPv4-mapped
|
|
// (::ffff:0:0/96) and IPv4-compatible (::/96) transition tails in every
|
|
// textual form, the deprecated transition prefixes 6to4 (2002::/16) and
|
|
// Teredo (2001:0::/32), documentation (2001:db8::/32) and NAT64
|
|
// (64:ff9b::/32) for IPv6. Classification is byte-level (ipv6ToBytes), so
|
|
// "http://[::ffff:a9fe:a9fe]/" is refused exactly like
|
|
// "http://[169.254.169.254]/" — Node dials both as 169.254.169.254. The
|
|
// set matches the daemon's isBlockedOutboundIPv6 (main.go) so the two
|
|
// sides cannot disagree about a literal. Unparseable addresses count as
|
|
// private (fail closed).
|
|
// - IPv6-literal URLs are validated, not rejected: the brackets from
|
|
// u.hostname are stripped before classification (u.hostname keeps them
|
|
// per WHATWG), which used to send "[...]" into dns.lookup and fail every
|
|
// IPv6-literal download with "DNS lookup failed" while the daemon
|
|
// accepted it.
|
|
// - For hostnames, EVERY resolved answer must be public — a record set
|
|
// that mixes one public address with one private one is rejected, so a
|
|
// round-robin A/AAAA pair cannot smuggle an internal target through
|
|
// whichever answer the connect happens to pick.
|
|
// - assertSafeRemoteUrlWithResolvedIp additionally returns the vetted
|
|
// resolvedIp so callers can pin the connection to the exact IP they
|
|
// validated (see createSsrfSafeAgent in index.js), closing the
|
|
// DNS-rebinding TOCTOU window between validation and connect.
|
|
|
|
const net = require("net");
|
|
const dns = require("dns").promises;
|
|
|
|
// F9: strict "1" parsing fails safe (a careless "true"/"yes" leaves the port
|
|
// allowlist enforced), and both the enabled and the ignored-but-set states
|
|
// are announced at startup so the operator's mental model matches reality.
|
|
const REMOTE_FETCH_ALLOW_ANY_PORT_RAW = String(process.env.REMOTE_FETCH_ALLOW_ANY_PORT || "").trim();
|
|
const REMOTE_FETCH_ALLOW_ANY_PORT = REMOTE_FETCH_ALLOW_ANY_PORT_RAW === "1";
|
|
if (REMOTE_FETCH_ALLOW_ANY_PORT) {
|
|
console.warn("[SECURITY] REMOTE_FETCH_ALLOW_ANY_PORT=1: the 80/443 port allowlist for remote fetches is DISABLED — public hosts become fetchable on any port. Every non-standard-port fetch is logged; unset this in production unless required.");
|
|
} else if (REMOTE_FETCH_ALLOW_ANY_PORT_RAW !== "") {
|
|
console.warn(`[SECURITY] REMOTE_FETCH_ALLOW_ANY_PORT="${REMOTE_FETCH_ALLOW_ANY_PORT_RAW}" is ignored (only exactly "1" enables it); the 80/443 port allowlist stays enforced.`);
|
|
}
|
|
|
|
// Audit trail for the escape hatch: keep each non-standard-port fetch visible
|
|
// (throttled per host:port so chatty mirrors cannot flood the log).
|
|
const _REMOTE_ANY_PORT_LAST_LOG = new Map();
|
|
const _REMOTE_ANY_PORT_LOG_INTERVAL_MS = 10 * 60 * 1000;
|
|
function _logRemoteAnyPortUse(hostname, port) {
|
|
if (!REMOTE_FETCH_ALLOW_ANY_PORT) return;
|
|
const key = `${hostname}:${port}`;
|
|
const now = Date.now();
|
|
if (now - (_REMOTE_ANY_PORT_LAST_LOG.get(key) || 0) < _REMOTE_ANY_PORT_LOG_INTERVAL_MS) return;
|
|
if (_REMOTE_ANY_PORT_LAST_LOG.size >= 100) _REMOTE_ANY_PORT_LAST_LOG.clear();
|
|
_REMOTE_ANY_PORT_LAST_LOG.set(key, now);
|
|
console.warn(`[SECURITY ALERT] Remote fetch on non-standard port ${key} allowed via REMOTE_FETCH_ALLOW_ANY_PORT=1 — verify this is intended`);
|
|
}
|
|
|
|
function ipv4ToInt(ip) {
|
|
const parts = ip.split(".");
|
|
if (parts.length !== 4) return null;
|
|
let n = 0;
|
|
for (const p of parts) {
|
|
const v = Number(p);
|
|
if (!Number.isInteger(v) || v < 0 || v > 255) return null;
|
|
n = (n << 8) + v;
|
|
}
|
|
return n >>> 0;
|
|
}
|
|
|
|
function isPrivateIPv4(ip) {
|
|
const n = ipv4ToInt(ip);
|
|
if (n === null) return true;
|
|
const ranges = [
|
|
[ipv4ToInt("0.0.0.0"), ipv4ToInt("0.255.255.255")],
|
|
[ipv4ToInt("10.0.0.0"), ipv4ToInt("10.255.255.255")],
|
|
[ipv4ToInt("100.64.0.0"), ipv4ToInt("100.127.255.255")],
|
|
[ipv4ToInt("127.0.0.0"), ipv4ToInt("127.255.255.255")],
|
|
[ipv4ToInt("169.254.0.0"), ipv4ToInt("169.254.255.255")],
|
|
[ipv4ToInt("172.16.0.0"), ipv4ToInt("172.31.255.255")],
|
|
[ipv4ToInt("192.168.0.0"), ipv4ToInt("192.168.255.255")],
|
|
[ipv4ToInt("192.0.2.0"), ipv4ToInt("192.0.2.255")],
|
|
[ipv4ToInt("198.18.0.0"), ipv4ToInt("198.19.255.255")],
|
|
[ipv4ToInt("198.51.100.0"), ipv4ToInt("198.51.100.255")],
|
|
[ipv4ToInt("203.0.113.0"), ipv4ToInt("203.0.113.255")],
|
|
[ipv4ToInt("224.0.0.0"), ipv4ToInt("255.255.255.255")],
|
|
];
|
|
return ranges.some(([a, b]) => n >= a && n <= b);
|
|
}
|
|
|
|
// Parses any RFC 4291 textual IPv6 form — full, ::-compressed, upper/lower
|
|
// case, and with an embedded dotted-quad tail (::ffff:10.0.0.1) — into its 16
|
|
// bytes. Returns null for anything that is not a pure textual IPv6 address
|
|
// (bare IPv4 strings, zone IDs, garbage); callers treat null as private
|
|
// (fail closed). Byte-level parsing is what makes the classification below
|
|
// independent of the textual form: Node dials the hex form "::ffff:a00:1" as
|
|
// 10.0.0.1 exactly like "::ffff:10.0.0.1", so a prefix-string matcher that
|
|
// only understood the dotted tail mis-classified hex-encoded IPv4-mapped
|
|
// addresses as public.
|
|
function ipv6ToBytes(input) {
|
|
const s = String(input || "").trim().toLowerCase();
|
|
if (!s || s.includes("%")) return null;
|
|
|
|
// An embedded dotted-quad tail is only legal after the last ":"; expand it
|
|
// into two groups. A bare IPv4 string is not an IPv6 form.
|
|
let body = s;
|
|
let v4Groups = null;
|
|
if (s.includes(".")) {
|
|
const lastColon = s.lastIndexOf(":");
|
|
if (lastColon === -1) return null;
|
|
const v4 = ipv4ToInt(s.slice(lastColon + 1));
|
|
if (v4 === null) return null;
|
|
v4Groups = [(v4 >>> 16) & 0xffff, v4 & 0xffff];
|
|
body = `${s.slice(0, lastColon + 1)}0:0`;
|
|
}
|
|
|
|
const dc = body.indexOf("::");
|
|
const hasCompressed = dc !== -1;
|
|
if (hasCompressed && body.indexOf("::", dc + 1) !== -1) return null; // at most one "::"
|
|
|
|
const parseGroups = (part) => {
|
|
if (part === "") return [];
|
|
const groups = [];
|
|
for (const g of part.split(":")) {
|
|
if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
|
|
groups.push(parseInt(g, 16));
|
|
}
|
|
return groups;
|
|
};
|
|
|
|
let head;
|
|
let tail = [];
|
|
if (hasCompressed) {
|
|
head = parseGroups(body.slice(0, dc));
|
|
tail = parseGroups(body.slice(dc + 2));
|
|
} else {
|
|
head = parseGroups(body);
|
|
}
|
|
if (head === null || tail === null) return null;
|
|
|
|
const total = head.length + tail.length;
|
|
if (hasCompressed ? total > 7 : total !== 8) return null;
|
|
|
|
const groups = new Array(8).fill(0);
|
|
for (let i = 0; i < head.length; i++) groups[i] = head[i];
|
|
for (let i = 0; i < tail.length; i++) groups[8 - tail.length + i] = tail[i];
|
|
if (v4Groups) {
|
|
groups[6] = v4Groups[0];
|
|
groups[7] = v4Groups[1];
|
|
}
|
|
|
|
const bytes = new Uint8Array(16);
|
|
for (let i = 0; i < 8; i++) {
|
|
bytes[i * 2] = groups[i] >>> 8;
|
|
bytes[i * 2 + 1] = groups[i] & 0xff;
|
|
}
|
|
return bytes;
|
|
}
|
|
|
|
function isPrivateIPv6(ip) {
|
|
const b = ipv6ToBytes(String(ip || "").split("%")[0]);
|
|
if (!b) return true; // unparseable/zone-scoped input: fail closed
|
|
|
|
const zeros = (from, to) => {
|
|
for (let i = from; i < to; i++) {
|
|
if (b[i] !== 0) return false;
|
|
}
|
|
return true;
|
|
};
|
|
|
|
if (zeros(0, 16)) return true; // :: unspecified
|
|
if (zeros(0, 15) && b[15] === 1) return true; // ::1 loopback
|
|
// ::ffff:0:0/96 IPv4-mapped: the dialer (and the daemon's netip) treats
|
|
// these as plain IPv4, so classify the embedded address in every textual
|
|
// form. "::ffff:a00:1" dials 10.0.0.1 just like "::ffff:10.0.0.1".
|
|
if (zeros(0, 10) && b[10] === 0xff && b[11] === 0xff) {
|
|
return isPrivateIPv4(`${b[12]}.${b[13]}.${b[14]}.${b[15]}`);
|
|
}
|
|
// ::/96 IPv4-compatible (deprecated): a transition encoding, never a
|
|
// legitimate destination.
|
|
if (zeros(0, 12)) return true;
|
|
if ((b[0] & 0xfe) === 0xfc) return true; // fc00::/7 ULA
|
|
if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return true; // fe80::/10 link-local
|
|
if (b[0] === 0xfe && (b[1] & 0xc0) === 0xc0) return true; // fec0::/10 deprecated site-local
|
|
if (b[0] === 0xff) return true; // ff00::/8 multicast
|
|
// Transition ranges whose only payload is an embedded IPv4 address are
|
|
// refused wholesale — same decision as the daemon's isBlockedOutboundIPv6:
|
|
// all three are RFC-deprecated (6to4 RFC 7526, Teredo, ::/96 RFC 4291), no
|
|
// legitimate DNS answer lands in them anymore, and classifying the embedded
|
|
// bytes of attacker-chosen AAAA forms would mean trusting the attacker's
|
|
// encoding. 2001:db8::/32 (documentation) and 64:ff9b::/32 (NAT64
|
|
// well-known + local-use) are blocked for the same parity.
|
|
if (b[0] === 0x20 && b[1] === 0x02) return true; // 2002::/16 6to4
|
|
if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0x00 && b[3] === 0x00) return true; // 2001:0::/32 Teredo
|
|
if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0x0d && b[3] === 0xb8) return true; // 2001:db8::/32
|
|
if (b[0] === 0x00 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b) return true; // 64:ff9b::/32 NAT64
|
|
return false;
|
|
}
|
|
|
|
function isPrivateAddress(ip) {
|
|
const t = net.isIP(ip);
|
|
if (t === 4) return isPrivateIPv4(ip);
|
|
if (t === 6) return isPrivateIPv6(ip);
|
|
return true;
|
|
}
|
|
|
|
// opts.allowAnyPort overrides the module-level REMOTE_FETCH_ALLOW_ANY_PORT
|
|
// default; production callers pass nothing so the env flag governs, and
|
|
// tests use it to exercise both branches without mutating the environment.
|
|
async function assertSafeRemoteUrlWithResolvedIp(inputUrl, opts = {}) {
|
|
const allowAnyPort = opts.allowAnyPort !== undefined ? opts.allowAnyPort === true : REMOTE_FETCH_ALLOW_ANY_PORT;
|
|
let u;
|
|
try {
|
|
u = new URL(String(inputUrl));
|
|
} catch {
|
|
throw new Error("Invalid URL");
|
|
}
|
|
|
|
const proto = (u.protocol || "").toLowerCase();
|
|
if (proto !== "http:" && proto !== "https:") throw new Error("Only http(s) URLs are allowed");
|
|
if (u.username || u.password) throw new Error("Credentials in URL are not allowed");
|
|
|
|
const hostname = u.hostname;
|
|
if (!hostname) throw new Error("Invalid hostname");
|
|
|
|
// WHATWG URL serializes an IPv6 host WITH its brackets in u.hostname
|
|
// ("[2001:db8::1]"), so that string never matched net.isIP() and fell into
|
|
// the dns.lookup branch, which cannot resolve a bracketed literal — every
|
|
// IPv6-literal URL was rejected as "DNS lookup failed" (the Go daemon
|
|
// accepts the same URLs). Strip the brackets for classification and
|
|
// connection pinning; u and originalHostname keep them, so the Host header
|
|
// stays RFC 3986-correct.
|
|
const bareHost = hostname.startsWith("[") && hostname.endsWith("]")
|
|
? hostname.slice(1, -1)
|
|
: hostname;
|
|
// Zone IDs (RFC 4007): WHATWG URL parsing rejects zone-carrying hosts on
|
|
// current Node — "http://[fe80::1%25eth0]/" throws before the guard runs —
|
|
// so this strip is defense in depth for the classification layer rather
|
|
// than a reachable URL shape: isPrivateIPv6 and any future caller handing
|
|
// the guard a pre-parsed host still classify the address part, and the
|
|
// bare literal is what would get dialed/pinned.
|
|
const zoneAt = bareHost.indexOf("%");
|
|
const classificationHost = zoneAt === -1 ? bareHost : bareHost.slice(0, zoneAt);
|
|
|
|
const hostLower = bareHost.toLowerCase();
|
|
if (hostLower === "localhost" || hostLower.endsWith(".localhost") || hostLower.endsWith(".local")) {
|
|
throw new Error("Localhost URLs are not allowed");
|
|
}
|
|
|
|
const port = u.port ? Number(u.port) : (u.protocol === "https:" ? 443 : 80);
|
|
if (!allowAnyPort && port !== 80 && port !== 443) throw new Error("Only ports 80/443 are allowed");
|
|
if (port !== 80 && port !== 443) _logRemoteAnyPortUse(hostname, port);
|
|
|
|
let resolvedIp = null;
|
|
|
|
if (net.isIP(classificationHost)) {
|
|
if (isPrivateAddress(classificationHost)) throw new Error("Private IP is not allowed");
|
|
resolvedIp = classificationHost;
|
|
} else {
|
|
const configuredTimeout = Number(process.env.REMOTE_FETCH_TIMEOUT_MS);
|
|
const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
|
|
? opts.timeoutMs
|
|
: Number.isFinite(configuredTimeout) && configuredTimeout > 0 ? configuredTimeout : 20000;
|
|
const answers = await new Promise((resolve, reject) => {
|
|
let settled = false;
|
|
const finish = (error, values) => {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(timer);
|
|
if (error) reject(error);
|
|
else resolve(values);
|
|
};
|
|
// adpanel:remote-dns-deadline - standalone preflights can hold server
|
|
// operation claims; a late resolver result must never grant a URL.
|
|
const timer = setTimeout(() => finish(new Error("DNS lookup timed out")), timeoutMs);
|
|
Promise.resolve().then(() => dns.lookup(classificationHost, { all: true, verbatim: true }))
|
|
.then((values) => finish(null, values), (error) => finish(error));
|
|
});
|
|
if (!answers || answers.length === 0) throw new Error("DNS lookup failed");
|
|
|
|
for (const a of answers) {
|
|
if (a && a.address && !isPrivateAddress(a.address)) {
|
|
resolvedIp = a.address;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!resolvedIp) throw new Error("Hostname resolves to a private/internal IP");
|
|
|
|
for (const a of answers) {
|
|
if (a && a.address && isPrivateAddress(a.address)) {
|
|
throw new Error("Hostname resolves to a private/internal IP");
|
|
}
|
|
}
|
|
}
|
|
|
|
return { url: u, resolvedIp, originalHostname: hostname };
|
|
}
|
|
|
|
// Convenience wrapper for callers that only need the vetted URL (the resolved
|
|
// IP is used by fetchers that pin the connection; acceptance semantics are
|
|
// identical).
|
|
async function assertSafeRemoteUrl(inputUrl, opts = {}) {
|
|
const { url } = await assertSafeRemoteUrlWithResolvedIp(inputUrl, opts);
|
|
return url;
|
|
}
|
|
|
|
module.exports = {
|
|
ipv4ToInt,
|
|
ipv6ToBytes,
|
|
isPrivateIPv4,
|
|
isPrivateIPv6,
|
|
isPrivateAddress,
|
|
assertSafeRemoteUrl,
|
|
assertSafeRemoteUrlWithResolvedIp,
|
|
};
|