Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,655 @@
|
||||
"use strict";
|
||||
|
||||
// SSRF guard for node (daemon) addresses — remediation for audit finding 3.3.
|
||||
//
|
||||
// The panel dials whatever address is stored on a node for every health
|
||||
// check, port probe, console command and file transfer. Before this guard
|
||||
// any non-empty string was accepted (POST /api/nodes), so a hijacked admin
|
||||
// session could point a node at 169.254.169.254, 127.0.0.1:6379 or any
|
||||
// internal service and use the panel's status probing as an internal
|
||||
// network scanner whose results are rendered back in the UI.
|
||||
//
|
||||
// Three layers, all fail-closed:
|
||||
//
|
||||
// 1. validateNodeAddressInput() — creation/update-time validation of the
|
||||
// literal address: loopback / link-local / private / reserved /
|
||||
// metadata targets are rejected unless the deployment explicitly opts
|
||||
// in with ADPANEL_ALLOW_PRIVATE_NODES=1 (genuine LAN deployments).
|
||||
// Hostnames must resolve, and every resolved address must be public.
|
||||
//
|
||||
// 2. guardedNodeLookup() — a socket `lookup` implementation attached to
|
||||
// every outbound node request. It re-validates the *resolved* addresses
|
||||
// at connect time, which closes the two bypass classes that a one-off
|
||||
// string check cannot: getaddrinfo numeric shorthand (dns.lookup accepts
|
||||
// "127.1", "2130706433", "0x7f000001" — all 127.0.0.1) and DNS
|
||||
// rebinding (a public-looking name re-pointed at an internal IP).
|
||||
//
|
||||
// 3. Redirect safety — the outbound primitives in nodes.js use Node's core
|
||||
// http/https modules, which never follow redirects, so a 302 cannot
|
||||
// bounce a request to a different host. Nothing needs to be disabled;
|
||||
// keep it that way if the client is ever swapped out.
|
||||
//
|
||||
// Embedded-IPv4 encodings inside IPv6 literals (IPv4-mapped ::ffff:10.0.0.1,
|
||||
// deprecated IPv4-compatible ::10.0.0.1, 6to4 2002:0a00:0001::, Teredo, and
|
||||
// NAT64 64:ff9b::0a00:0001) are unwrapped and the embedded IPv4 address is
|
||||
// classified with the same IPv4 rules, so none of them can smuggle a private
|
||||
// target past the guard.
|
||||
//
|
||||
// Deployment note: same-host panels (daemon on the panel machine) registered
|
||||
// with a public address reach the daemon by that address, so they pass this
|
||||
// guard only when the address is public — or when the operator opts into
|
||||
// private ranges. Cross-host LAN deployments set ADPANEL_ALLOW_PRIVATE_NODES=1.
|
||||
// (A loopback hairpin fallback used to be exempt here; it was removed because
|
||||
// it could only ever hand the node bearer credential to an impostor — see the
|
||||
// note above callNodeApi in nodes.js. The guard is applied unconditionally.)
|
||||
|
||||
const net = require("net");
|
||||
const dns = require("dns");
|
||||
|
||||
const ALLOW_PRIVATE_ENV_VAR = "ADPANEL_ALLOW_PRIVATE_NODES";
|
||||
|
||||
// Total cap on the address field (covers scheme + host + port forms).
|
||||
const MAX_ADDRESS_LENGTH = 255;
|
||||
const MAX_HOSTNAME_LENGTH = 253;
|
||||
// Additional IPs are bookkeeping/bind metadata (never dialed by the panel),
|
||||
// so they get a syntax check only — but a bounded one.
|
||||
const MAX_ADDITIONAL_NODE_ADDRESSES = 32;
|
||||
|
||||
// Positive cache of validated DNS answers, keyed by "<family>|<host>". Only
|
||||
// literal, previously-validated addresses are ever served from it, so a
|
||||
// rebinding attack cannot slip through via a stale entry: we connect to the
|
||||
// exact IP we validated, never to a fresh unvalidated answer.
|
||||
const LOOKUP_CACHE_TTL_MS = 15 * 1000;
|
||||
const LOOKUP_CACHE_MAX = 1000;
|
||||
const _lookupCache = new Map();
|
||||
|
||||
// One console.warn per host per minute when a connect is refused, so a fleet
|
||||
// of blocked nodes in the health loop cannot flood the log.
|
||||
const BLOCK_LOG_INTERVAL_MS = 60 * 1000;
|
||||
const _blockedWarnAt = new Map();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Environment opt-in
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function allowPrivateNodeAddresses() {
|
||||
const v = String(process.env[ALLOW_PRIVATE_ENV_VAR] || "").trim().toLowerCase();
|
||||
return v === "1" || v === "true" || v === "yes" || v === "on";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IP classification
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// URL.hostname (and some stored forms) keep the surrounding brackets on IPv6
|
||||
// literals; net.isIP rejects those. Strip them before any IP check. A trailing
|
||||
// zone ID ("fe80::1%eth0") is stripped too so the bare address is what gets
|
||||
// classified — the zone never makes a link-local target dialable.
|
||||
function normalizeIpLiteral(ip) {
|
||||
let s = String(ip || "").trim().toLowerCase();
|
||||
if (s.startsWith("[") && s.endsWith("]")) s = s.slice(1, -1);
|
||||
const zoneIdx = s.indexOf("%");
|
||||
if (zoneIdx !== -1) s = s.slice(0, zoneIdx);
|
||||
return s;
|
||||
}
|
||||
|
||||
function ipv4ToBytes(ip) {
|
||||
const parts = String(ip || "").split(".");
|
||||
if (parts.length !== 4) return null;
|
||||
const bytes = [];
|
||||
for (const part of parts) {
|
||||
if (!/^\d{1,3}$/.test(part)) return null;
|
||||
const n = Number(part);
|
||||
if (n > 255) return null;
|
||||
bytes.push(n);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function forbiddenIpv4Reason(bytes) {
|
||||
const [a, b, c] = bytes;
|
||||
if (a === 0) return "the unspecified/this-network IPv4 range (0.0.0.0/8)";
|
||||
if (a === 10) return "a private IPv4 range (10.0.0.0/8)";
|
||||
if (a === 100 && b >= 64 && b <= 127) return "the carrier-grade NAT range (100.64.0.0/10)";
|
||||
if (a === 127) return "the IPv4 loopback range (127.0.0.0/8)";
|
||||
if (a === 169 && b === 254) return "the link-local/cloud-metadata range (169.254.0.0/16)";
|
||||
if (a === 172 && b >= 16 && b <= 31) return "a private IPv4 range (172.16.0.0/12)";
|
||||
if (a === 192 && b === 0 && c === 2) return "the documentation range (192.0.2.0/24)";
|
||||
if (a === 192 && b === 168) return "a private IPv4 range (192.168.0.0/16)";
|
||||
if (a === 198 && (b === 18 || b === 19)) return "the benchmarking range (198.18.0.0/15)";
|
||||
if (a === 198 && b === 51 && c === 100) return "the documentation range (198.51.100.0/24)";
|
||||
if (a === 203 && b === 0 && c === 113) return "the documentation range (203.0.113.0/24)";
|
||||
if (a >= 224) return "the multicast/reserved IPv4 range (224.0.0.0/4 and above)";
|
||||
return null;
|
||||
}
|
||||
|
||||
// Parses any IPv6 textual form net.isIP accepts (excluding zone IDs, which
|
||||
// the callers reject) into its 16 bytes. Handles "::" compression and the
|
||||
// embedded-IPv4 tail forms ("::ffff:1.2.3.4"). Returns null on anything it
|
||||
// cannot fully expand — callers fail closed on null.
|
||||
function ipv6ToBytes(text) {
|
||||
let s = String(text || "").trim().toLowerCase();
|
||||
if (!s || s.includes("%")) return null;
|
||||
if (s.startsWith("[") && s.endsWith("]")) s = s.slice(1, -1);
|
||||
|
||||
// Embedded IPv4 tail: the last colon-group (or bare trailing part) is a
|
||||
// dotted quad; fold it into two hex groups before the main parse.
|
||||
const lastColon = s.lastIndexOf(":");
|
||||
const tail = s.slice(lastColon + 1);
|
||||
if (tail.includes(".")) {
|
||||
const v4 = ipv4ToBytes(tail);
|
||||
if (!v4) return null;
|
||||
s = s.slice(0, lastColon + 1) + ((v4[0] << 8) | v4[1]).toString(16) + ":" + ((v4[2] << 8) | v4[3]).toString(16);
|
||||
}
|
||||
|
||||
const doubleColon = s.indexOf("::");
|
||||
let leftGroups;
|
||||
let rightGroups;
|
||||
if (doubleColon !== -1) {
|
||||
if (s.indexOf("::", doubleColon + 1) !== -1) return null; // more than one "::"
|
||||
const left = s.slice(0, doubleColon);
|
||||
const right = s.slice(doubleColon + 2);
|
||||
leftGroups = left ? left.split(":") : [];
|
||||
rightGroups = right ? right.split(":") : [];
|
||||
} else {
|
||||
leftGroups = s.split(":");
|
||||
rightGroups = [];
|
||||
}
|
||||
|
||||
if (leftGroups.length + rightGroups.length > 8) return null;
|
||||
if (doubleColon === -1 && leftGroups.length !== 8) return null;
|
||||
|
||||
const groups = new Array(8).fill(0);
|
||||
for (let i = 0; i < leftGroups.length; i++) {
|
||||
const g = leftGroups[i];
|
||||
if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
|
||||
groups[i] = parseInt(g, 16);
|
||||
}
|
||||
for (let i = 0; i < rightGroups.length; i++) {
|
||||
const g = rightGroups[rightGroups.length - 1 - i];
|
||||
if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
|
||||
groups[7 - i] = parseInt(g, 16);
|
||||
}
|
||||
|
||||
const bytes = new Array(16);
|
||||
for (let i = 0; i < 8; i++) {
|
||||
bytes[i * 2] = (groups[i] >> 8) & 0xff;
|
||||
bytes[i * 2 + 1] = groups[i] & 0xff;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function ipv4ReasonFromBytes(bytes) {
|
||||
return forbiddenIpv4Reason(bytes);
|
||||
}
|
||||
|
||||
function forbiddenIpv6Reason(bytes) {
|
||||
const allZero = (from, to) => {
|
||||
for (let i = from; i < to; i++) if (bytes[i] !== 0) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
if (allZero(0, 16)) return "the unspecified IPv6 address (::)";
|
||||
if (allZero(0, 15) && bytes[15] === 1) return "the IPv6 loopback address (::1)";
|
||||
if ((bytes[0] & 0xfe) === 0xfc) return "a unique-local IPv6 range (fc00::/7)";
|
||||
if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80) return "the link-local IPv6 range (fe80::/10)";
|
||||
if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0xc0) return "the deprecated site-local IPv6 range (fec0::/10)";
|
||||
if (bytes[0] === 0xff) return "the IPv6 multicast range (ff00::/8)";
|
||||
|
||||
const tailV4 = [bytes[12], bytes[13], bytes[14], bytes[15]];
|
||||
|
||||
// IPv4-mapped ::ffff:0:0/96 and deprecated IPv4-compatible ::/96 — the
|
||||
// embedded IPv4 address decides: mapped-public stays dialable, mapped-
|
||||
// private/link-local/loopback is refused.
|
||||
if (allZero(0, 10) && bytes[10] === 0xff && bytes[11] === 0xff) {
|
||||
return ipv4ReasonFromBytes(tailV4);
|
||||
}
|
||||
if (allZero(0, 12) && !allZero(12, 16)) {
|
||||
return ipv4ReasonFromBytes(tailV4);
|
||||
}
|
||||
|
||||
// 6to4 2002::/16 — the next 32 bits are a public IPv4 address of the edge
|
||||
// router, but the *encoded* host bits are what an attacker would aim at.
|
||||
if (bytes[0] === 0x20 && bytes[1] === 0x02) {
|
||||
const v4 = [bytes[2], bytes[3], bytes[4], bytes[5]];
|
||||
const reason = ipv4ReasonFromBytes(v4);
|
||||
if (reason) return `6to4 encoding wrapping ${reason}`;
|
||||
}
|
||||
|
||||
// Teredo 2001:0000::/32 — the client IPv4 is the obfuscated last 32 bits.
|
||||
if (bytes[0] === 0x20 && bytes[1] === 0x01 && bytes[2] === 0x00 && bytes[3] === 0x00) {
|
||||
const v4 = [bytes[12] ^ 0xff, bytes[13] ^ 0xff, bytes[14] ^ 0xff, bytes[15] ^ 0xff];
|
||||
const reason = ipv4ReasonFromBytes(v4);
|
||||
if (reason) return `teredo encoding wrapping ${reason}`;
|
||||
}
|
||||
|
||||
// NAT64 well-known prefix 64:ff9b::/96.
|
||||
if (bytes[0] === 0 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b && allZero(4, 12)) {
|
||||
const reason = ipv4ReasonFromBytes(tailV4);
|
||||
if (reason) return `nat64 encoding wrapping ${reason}`;
|
||||
}
|
||||
|
||||
// Documentation range 2001:db8::/32 (non-routable by definition).
|
||||
if (bytes[0] === 0x20 && bytes[1] === 0x01 && bytes[2] === 0x0d && bytes[3] === 0xb8) {
|
||||
return "the documentation range (2001:db8::/32)";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Public entry: reason string if the literal IP must not be dialed, else null.
|
||||
// Unparseable input is treated as forbidden (fail closed).
|
||||
function forbiddenNodeIpReason(ip) {
|
||||
const normalized = normalizeIpLiteral(ip);
|
||||
const v = net.isIP(normalized);
|
||||
if (v === 4) {
|
||||
const bytes = ipv4ToBytes(normalized);
|
||||
return bytes ? forbiddenIpv4Reason(bytes) : "not a valid IPv4 literal";
|
||||
}
|
||||
if (v === 6) {
|
||||
const bytes = ipv6ToBytes(normalized);
|
||||
return bytes ? forbiddenIpv6Reason(bytes) : "not a valid IPv6 literal";
|
||||
}
|
||||
return "not a valid IP literal";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Host extraction and hostname policy
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Extracts the host a node address would actually dial. Accepts the same
|
||||
// shapes buildNodeBaseUrl() accepts: bare host, host:port, [v6]:port,
|
||||
// scheme://host[:port][/path]. Returns { ok, host } or { ok:false, error }.
|
||||
function extractNodeAddressHost(rawAddress) {
|
||||
const raw = String(rawAddress || "").trim();
|
||||
if (!raw) return { ok: false, error: "Node address is empty." };
|
||||
if (raw.length > MAX_ADDRESS_LENGTH) {
|
||||
return { ok: false, error: `Node address exceeds ${MAX_ADDRESS_LENGTH} characters.` };
|
||||
}
|
||||
if (/[\s\u0000-\u001F\u007F]/.test(raw)) {
|
||||
return { ok: false, error: "Node address contains whitespace or control characters." };
|
||||
}
|
||||
if (raw.includes("%")) {
|
||||
return { ok: false, error: "Node address must not contain a zone ID (%...)." };
|
||||
}
|
||||
|
||||
let host;
|
||||
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) {
|
||||
let u;
|
||||
try {
|
||||
u = new URL(raw);
|
||||
} catch {
|
||||
return { ok: false, error: "Node address is not a valid URL." };
|
||||
}
|
||||
const proto = (u.protocol || "").toLowerCase();
|
||||
if (proto !== "http:" && proto !== "https:") {
|
||||
return { ok: false, error: "Node address must use http:// or https://." };
|
||||
}
|
||||
if (u.username || u.password) {
|
||||
return { ok: false, error: "Node address must not embed credentials." };
|
||||
}
|
||||
host = u.hostname;
|
||||
// WHATWG URL keeps brackets on IPv6 literals ("[::1]"); strip them so the
|
||||
// literal-IP classification below sees the bare address.
|
||||
if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
|
||||
} else {
|
||||
const head = raw.split(/[/?#]/)[0];
|
||||
if (head.startsWith("[")) {
|
||||
const end = head.indexOf("]");
|
||||
if (end < 0) return { ok: false, error: "Node address has an unterminated IPv6 bracket." };
|
||||
host = head.slice(1, end);
|
||||
const rest = head.slice(end + 1);
|
||||
if (rest && !/^:\d{1,5}$/.test(rest)) {
|
||||
return { ok: false, error: "Node address has an invalid port after the IPv6 bracket." };
|
||||
}
|
||||
if (rest) {
|
||||
const port = Number(rest.slice(1));
|
||||
if (!(port >= 1 && port <= 65535)) {
|
||||
return { ok: false, error: "Node address has an invalid port (must be between 1 and 65535)." };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const colons = (head.match(/:/g) || []).length;
|
||||
if (colons === 1) {
|
||||
const portPart = head.slice(head.indexOf(":") + 1);
|
||||
if (!/^\d{1,5}$/.test(portPart)) {
|
||||
return { ok: false, error: "Node address has an invalid port." };
|
||||
}
|
||||
const port = Number(portPart);
|
||||
if (!(port >= 1 && port <= 65535)) {
|
||||
return { ok: false, error: "Node address has an invalid port (must be between 1 and 65535)." };
|
||||
}
|
||||
host = head.slice(0, head.indexOf(":"));
|
||||
} else {
|
||||
// Bare IPv6 literal (or a single-label name — no colons).
|
||||
host = head;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
host = String(host || "").trim().toLowerCase();
|
||||
while (host.endsWith(".")) host = host.slice(0, -1); // FQDN root dot
|
||||
if (!host) return { ok: false, error: "Node address has an empty host." };
|
||||
return { ok: true, host };
|
||||
}
|
||||
|
||||
function forbiddenNodeHostnameReason(host) {
|
||||
const h = String(host || "").toLowerCase();
|
||||
if (h === "localhost" || h.endsWith(".localhost")) return "the hostname refers to localhost";
|
||||
if (h.endsWith(".local")) return "mDNS/.local names are reserved for local networks";
|
||||
if (h.endsWith(".internal")) return ".internal names are reserved for internal networks (cloud metadata uses them)";
|
||||
if (h.endsWith(".home.arpa")) return ".home.arpa names are reserved for home networks";
|
||||
if (h === "metadata") return "the name is the cloud metadata service alias";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Creation/update-time validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// dns.lookup has no native promise form on the callback namespace (the promise
|
||||
// API lives on dns.promises with a different object identity), so wrap the
|
||||
// callback form — this keeps runtime stubbing/interception trivially possible.
|
||||
function dnsLookupAll(host, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
dns.lookup(host, options, (err, addresses) => {
|
||||
if (err) return reject(err);
|
||||
resolve(addresses);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveAndCheckHostAddresses(host) {
|
||||
let answers;
|
||||
try {
|
||||
answers = await dnsLookupAll(host, { all: true, verbatim: true });
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Cannot resolve node address "${host}" (${(err && (err.code || err.message)) || "DNS failure"}). ` +
|
||||
"Use an IP address, or a hostname the panel host can resolve.",
|
||||
};
|
||||
}
|
||||
if (!answers || !answers.length) {
|
||||
return { ok: false, error: `Node address "${host}" does not resolve to any address.` };
|
||||
}
|
||||
for (const answer of answers) {
|
||||
if (!answer || !answer.address) continue;
|
||||
const reason = forbiddenNodeIpReason(answer.address);
|
||||
if (reason && !allowPrivateNodeAddresses()) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Node address "${host}" resolves to ${answer.address} (${reason}), which is blocked to prevent ` +
|
||||
`server-side request forgery. If this node genuinely lives on a private/LAN network, set ` +
|
||||
`${ALLOW_PRIVATE_ENV_VAR}=1 on the panel host.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
return { ok: true, host, addresses: answers.map(a => a.address) };
|
||||
}
|
||||
|
||||
// The panel dials bare addresses by concatenation (`${proto}://${address}:${apiPort}`),
|
||||
// so a bare address must be exactly "host" or "host:port": a path/query/fragment
|
||||
// suffix or an embedded port silently redirects the dial to port 80/443 or
|
||||
// produces an unparseable URL (there is a dedicated daemon-port field, and full
|
||||
// http(s):// URLs are the supported way to embed a port). Returns null when the
|
||||
// stored string would dial exactly as validated, else the reason.
|
||||
function validateNodeAddressDialShape(rawAddress) {
|
||||
const raw = String(rawAddress || "").trim();
|
||||
if (!raw) return null; // empty is caught by extraction
|
||||
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) return null; // full URL — parsed & honored by the dialer
|
||||
if (/[/?#]/.test(raw)) {
|
||||
return "Node address must be a bare host or host:port — remove the trailing path (it would be dialed on the wrong port). Use the Daemon Port field for the port, or a full http(s):// URL.";
|
||||
}
|
||||
// Bare (unbracketed) IPv6 literals are all colons — the address itself, not
|
||||
// an embedded port.
|
||||
if (net.isIP(raw) === 6) return null;
|
||||
// Bracketed IPv6: "[::1]" (no port) dials fine; "[::1]:8080" is host:port.
|
||||
if (raw.startsWith("[")) {
|
||||
if (raw.endsWith("]")) return null;
|
||||
return "Node address must not embed a port (it would be dialed as host:port:<daemon port>, which is not a valid URL). Use the Daemon Port field instead, or a full http(s):// URL.";
|
||||
}
|
||||
if (raw.includes(":")) {
|
||||
return "Node address must not embed a port (it would be dialed as host:port:<daemon port>, which is not a valid URL). Use the Daemon Port field instead, or a full http(s):// URL.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Validates a node address exactly as it will be dialed: literal IPs are
|
||||
// classified directly, hostnames must not be reserved/internal names and must
|
||||
// resolve to public addresses only. Under Cloudflare proxy the caller skips
|
||||
// this check because verifyCloudflareProxiedAddress() already proves the name
|
||||
// resolves exclusively to Cloudflare's public edge ranges.
|
||||
async function validateNodeAddressInput(rawAddress) {
|
||||
const dialShapeError = validateNodeAddressDialShape(rawAddress);
|
||||
const extracted = extractNodeAddressHost(rawAddress);
|
||||
if (!extracted.ok) return extracted;
|
||||
const host = extracted.host;
|
||||
|
||||
const literalVersion = net.isIP(host);
|
||||
if (literalVersion) {
|
||||
const reason = forbiddenNodeIpReason(host);
|
||||
if (reason && !allowPrivateNodeAddresses()) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Node address "${host}" is blocked: ${reason}. To allow nodes on private/LAN networks, set ` +
|
||||
`${ALLOW_PRIVATE_ENV_VAR}=1 on the panel host.`,
|
||||
};
|
||||
}
|
||||
// Otherwise-valid literal whose stored form would not dial as validated
|
||||
// (embedded port or path suffix) fails closed here.
|
||||
if (dialShapeError) return { ok: false, error: dialShapeError };
|
||||
return { ok: true, host, literal: true, family: literalVersion };
|
||||
}
|
||||
|
||||
if (host.length > MAX_HOSTNAME_LENGTH) {
|
||||
return { ok: false, error: `Node address hostname exceeds ${MAX_HOSTNAME_LENGTH} characters.` };
|
||||
}
|
||||
if (!/^[a-z0-9._-]+$/.test(host)) {
|
||||
return { ok: false, error: `Node address "${host}" contains characters that are not valid in a hostname.` };
|
||||
}
|
||||
const nameReason = forbiddenNodeHostnameReason(host);
|
||||
if (nameReason && !allowPrivateNodeAddresses()) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Node address "${host}" is blocked: ${nameReason}. To allow it, set ${ALLOW_PRIVATE_ENV_VAR}=1 ` +
|
||||
"on the panel host.",
|
||||
};
|
||||
}
|
||||
// Otherwise-valid bare address whose stored form would not dial as validated
|
||||
// (embedded port or path suffix) fails closed here — before any DNS lookup.
|
||||
if (dialShapeError) return { ok: false, error: dialShapeError };
|
||||
return resolveAndCheckHostAddresses(host);
|
||||
}
|
||||
|
||||
// Additional IPs are bind/bookkeeping metadata rendered in the UI and stored
|
||||
// on the node — the panel itself never dials them — so a syntax check is the
|
||||
// right strength: reject injection payloads and garbage, allow LAN-style
|
||||
// values without forcing the env opt-in.
|
||||
function validateNodeAddressSyntaxInput(rawAddress) {
|
||||
const extracted = extractNodeAddressHost(rawAddress);
|
||||
if (!extracted.ok) return extracted;
|
||||
const host = extracted.host;
|
||||
if (net.isIP(host)) return { ok: true, host, literal: true };
|
||||
if (host.length > MAX_HOSTNAME_LENGTH) {
|
||||
return { ok: false, error: `"${host}" exceeds ${MAX_HOSTNAME_LENGTH} characters.` };
|
||||
}
|
||||
if (!/^[a-z0-9._-]+$/.test(host)) {
|
||||
return { ok: false, error: `"${host}" contains characters that are not valid in a hostname.` };
|
||||
}
|
||||
return { ok: true, host };
|
||||
}
|
||||
|
||||
function validateNodeAddressListInput(rawEntries) {
|
||||
const entries = Array.isArray(rawEntries)
|
||||
? rawEntries.map(e => String(e || "").trim()).filter(Boolean)
|
||||
: [];
|
||||
if (entries.length > MAX_ADDITIONAL_NODE_ADDRESSES) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `At most ${MAX_ADDITIONAL_NODE_ADDRESSES} additional addresses are allowed per node.`,
|
||||
};
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const result = validateNodeAddressSyntaxInput(entry);
|
||||
if (!result.ok) {
|
||||
return { ok: false, error: `Additional address "${entry}" is invalid: ${result.error}` };
|
||||
}
|
||||
}
|
||||
return { ok: true, entries };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Connect-time guarded lookup (DNS rebinding / shorthand defense)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function blockedConnectError(host, reason) {
|
||||
const err = new Error(
|
||||
`Outbound node request to "${host}" blocked: target is ${reason}. If this node genuinely runs on a ` +
|
||||
`private network, set ${ALLOW_PRIVATE_ENV_VAR}=1 on the panel host.`
|
||||
);
|
||||
err.code = "EADPANEL_SSRF_BLOCKED";
|
||||
return err;
|
||||
}
|
||||
|
||||
function warnBlockedConnect(host, resolvedIp, reason) {
|
||||
const now = Date.now();
|
||||
const last = _blockedWarnAt.get(host) || 0;
|
||||
if (now - last < BLOCK_LOG_INTERVAL_MS) return;
|
||||
if (_blockedWarnAt.size > 1000) _blockedWarnAt.clear();
|
||||
_blockedWarnAt.set(host, now);
|
||||
console.warn(
|
||||
`[ssrf-guard] Refused outbound node request to "${host}" (${resolvedIp}: ${reason}). ` +
|
||||
`Set ${ALLOW_PRIVATE_ENV_VAR}=1 if this node is genuinely on a private network.`
|
||||
);
|
||||
}
|
||||
|
||||
function cacheValidatedAnswers(cacheKey, answers) {
|
||||
if (_lookupCache.size >= LOOKUP_CACHE_MAX) {
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of _lookupCache) {
|
||||
if (entry.expiresAt <= now) _lookupCache.delete(key);
|
||||
}
|
||||
if (_lookupCache.size >= LOOKUP_CACHE_MAX) _lookupCache.clear();
|
||||
}
|
||||
_lookupCache.set(cacheKey, { expiresAt: Date.now() + LOOKUP_CACHE_TTL_MS, answers });
|
||||
}
|
||||
|
||||
// Synchronous pre-flight for request primitives. net.Socket.connect() has an
|
||||
// isIP fast path that never consults a custom `lookup` when the URL host is
|
||||
// already a literal IP (verified on Node 22), so literal targets must be
|
||||
// classified here as well. Hostname targets need no pre-flight: they are
|
||||
// re-validated by guardedNodeLookup() at connect time, which also catches
|
||||
// getaddrinfo numeric shorthand ("127.1", "2130706433", "0x7f000001") and
|
||||
// rebinding, since it validates whatever the socket would actually dial.
|
||||
// Returns an Error to abort the request, or null to proceed.
|
||||
function assertNodeUrlHostAllowed(fullUrl) {
|
||||
let u;
|
||||
try {
|
||||
u = new URL(String(fullUrl));
|
||||
} catch {
|
||||
return null; // malformed URL — lib.request throws on its own
|
||||
}
|
||||
const proto = (u.protocol || "").toLowerCase();
|
||||
if (proto !== "http:" && proto !== "https:") return null;
|
||||
// URL.hostname keeps brackets on IPv6 literals — normalize before isIP.
|
||||
const host = normalizeIpLiteral(u.hostname);
|
||||
if (!host || !net.isIP(host)) return null;
|
||||
const reason = forbiddenNodeIpReason(host);
|
||||
if (!reason || allowPrivateNodeAddresses()) return null;
|
||||
warnBlockedConnect(host, host, reason);
|
||||
return blockedConnectError(host, reason);
|
||||
}
|
||||
|
||||
// Socket-compatible `lookup` option (net/http/https). Validates whatever the
|
||||
// socket would actually connect to — literal IPs directly, hostnames through
|
||||
// the real getaddrinfo path (so numeric shorthand like "127.1" is caught —
|
||||
// and refuses unless every resolved address is dialable.
|
||||
function guardedNodeLookup(hostname, options, callback) {
|
||||
if (typeof options === "function") {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
const family = Number(options.family) > 0 ? Number(options.family) : 0;
|
||||
const host = String(hostname || "");
|
||||
const wantsAll = !!options.all;
|
||||
|
||||
const deliver = (answers) => {
|
||||
// Belt and braces: when a family was requested, only deliver answers of
|
||||
// that family (getaddrinfo with all:true normally guarantees this).
|
||||
const usable = family ? answers.filter(a => a.family === family) : answers;
|
||||
if (wantsAll) return callback(null, usable);
|
||||
if (!usable.length) {
|
||||
const empty = new Error(`No usable ${family ? `IPv${family} ` : ""}address for ${host}`);
|
||||
empty.code = "EAI_NODATA";
|
||||
return callback(empty);
|
||||
}
|
||||
const chosen = usable[0];
|
||||
return callback(null, chosen.address, chosen.family);
|
||||
};
|
||||
|
||||
const literalVersion = net.isIP(normalizeIpLiteral(host));
|
||||
if (literalVersion) {
|
||||
const literal = normalizeIpLiteral(host);
|
||||
const reason = forbiddenNodeIpReason(literal);
|
||||
if (reason && !allowPrivateNodeAddresses()) {
|
||||
warnBlockedConnect(host, literal, reason);
|
||||
return process.nextTick(callback, blockedConnectError(host, reason));
|
||||
}
|
||||
const answers = [{ address: literal, family: literalVersion }];
|
||||
return process.nextTick(deliver, answers);
|
||||
}
|
||||
|
||||
const cacheKey = `${family}|${host.toLowerCase()}`;
|
||||
const cached = _lookupCache.get(cacheKey);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return process.nextTick(deliver, cached.answers);
|
||||
}
|
||||
|
||||
const lookupOptions = { all: true, verbatim: true };
|
||||
if (family) lookupOptions.family = family;
|
||||
if (options.hints) lookupOptions.hints = options.hints;
|
||||
|
||||
dns.lookup(host, lookupOptions, (err, answers) => {
|
||||
if (err) return callback(err);
|
||||
if (!answers || !answers.length) {
|
||||
const empty = new Error(`Cannot resolve ${host}`);
|
||||
empty.code = "ENOTFOUND";
|
||||
return callback(empty);
|
||||
}
|
||||
for (const answer of answers) {
|
||||
const reason = forbiddenNodeIpReason(answer.address);
|
||||
if (reason && !allowPrivateNodeAddresses()) {
|
||||
warnBlockedConnect(host, answer.address, reason);
|
||||
return callback(blockedConnectError(host, reason));
|
||||
}
|
||||
}
|
||||
const validated = answers.map(a => ({ address: a.address, family: a.family || net.isIP(a.address) }));
|
||||
cacheValidatedAnswers(cacheKey, validated);
|
||||
deliver(validated);
|
||||
});
|
||||
}
|
||||
|
||||
// Test hook: drops the validation cache and warn-rate-limit state.
|
||||
function clearInternalCaches() {
|
||||
_lookupCache.clear();
|
||||
_blockedWarnAt.clear();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ALLOW_PRIVATE_ENV_VAR,
|
||||
MAX_ADDRESS_LENGTH,
|
||||
MAX_ADDITIONAL_NODE_ADDRESSES,
|
||||
allowPrivateNodeAddresses,
|
||||
forbiddenNodeIpReason,
|
||||
forbiddenNodeHostnameReason,
|
||||
extractNodeAddressHost,
|
||||
validateNodeAddressInput,
|
||||
validateNodeAddressDialShape,
|
||||
validateNodeAddressSyntaxInput,
|
||||
validateNodeAddressListInput,
|
||||
guardedNodeLookup,
|
||||
assertNodeUrlHostAllowed,
|
||||
clearInternalCaches,
|
||||
};
|
||||
Reference in new issue
Block a user