Files
Kelx/utils/ip-subnet-validation.js
T
2026-11-30 16:32:37 +00:00

149 lines
5.6 KiB
JavaScript

"use strict";
// Strict validation for trusted subnet entries (IPv4/IPv6, bare IP or CIDR).
// Every entry stored in security.json must pass isValidSubnet() so that:
// - the value space is limited to [0-9A-Fa-f.:/] (no HTML/JSON metacharacters),
// which makes admin-UI rendering of stored values injection-safe,
// - ip-range-check/ipaddr.js always parse stored entries deterministically
// (its lenient forms like "127.1" or bare integers are rejected here).
// The production consumer is the global anti-abuse rate-limiter bypass in
// index.js: ipMatchesTrustedSubnets() matches request IPs against the stored
// entries in both limiter stores (the Redis-backed global rate-limit owner
// and the in-memory rateLimiterMiddleware). Validation leans on Node's built-in
// net.isIP plus ipaddr.js (for IPv4-mapped detection); matching uses the
// existing ip-range-check dependency.
const net = require("net");
const ipaddr = require("ipaddr.js");
const ipRangeCheck = require("ip-range-check");
const MAX_TRUSTED_SUBNETS = 50;
// Longest valid IPv6 textual forms: a fully-expanded 8-group address is 39
// chars, and its IPv4-mapped expansion ("::ffff:" prefix on an embedded
// dotted-quad tail) reaches 45; 64 leaves headroom without allowing
// arbitrary strings.
const MAX_SUBNET_LENGTH = 64;
const PREFIX_RE = /^(0|[1-9][0-9]*)$/;
// Accepts a bare IP ("10.0.0.5", "2001:db8::1") or a CIDR ("10.0.0.0/24",
// "2001:db8::/32"). The entry must already be trimmed. Zone IDs ("%eth0"),
// IPv4 shorthand ("127.1"), integer forms and IPv4-mapped CIDRs are all
// rejected. Bare IPv4-mapped addresses ("::ffff:10.0.0.1") stay valid: the
// matcher normalizes both sides to plain IPv4, so they match their IPv4
// address. A mapped CIDR ("::ffff:10.0.0.0/120") is rejected because its
// prefix applies to the IPv6 form while the matcher compares plain IPv4 —
// such an entry could never match, and validation refuses to store silent
// no-ops.
function isValidSubnet(raw) {
if (typeof raw !== "string") return false;
const entry = raw.trim();
if (entry.length === 0 || entry.length > MAX_SUBNET_LENGTH) return false;
if (/\s/.test(entry)) return false;
// Zone IDs ("fe80::1%eth0"): net.isIP accepts them, but socket-reported
// addresses carry no zone, so such an entry could never match — reject.
if (entry.indexOf("%") !== -1) return false;
const slashIdx = entry.indexOf("/");
let ipPart;
let prefixPart;
if (slashIdx === -1) {
ipPart = entry;
prefixPart = null;
} else {
ipPart = entry.slice(0, slashIdx);
prefixPart = entry.slice(slashIdx + 1);
if (!ipPart || !prefixPart || prefixPart.indexOf("/") !== -1) return false;
if (!PREFIX_RE.test(prefixPart)) return false;
}
const ipVersion = net.isIP(ipPart);
if (ipVersion !== 4 && ipVersion !== 6) return false;
if (prefixPart !== null) {
// An IPv4-mapped IPv6 CIDR can never match: request addresses are
// normalized to plain IPv4 before comparison, and an IPv4 address never
// matches an IPv6 CIDR. Reject the entry rather than store a no-op.
if (ipVersion === 6) {
try {
if (ipaddr.parse(ipPart).isIPv4MappedAddress()) return false;
} catch {
return false;
}
}
const prefix = parseInt(prefixPart, 10);
const maxPrefix = ipVersion === 4 ? 32 : 128;
if (prefix > maxPrefix) return false;
}
return true;
}
// For admin-supplied arrays (POST /api/settings/security): all-or-nothing.
// Returns { ok: true, entries } with trimmed, deduplicated, capped values,
// or { ok: false, invalid } listing the offending entries.
function validateTrustedSubnetsInput(value) {
if (!Array.isArray(value)) {
return { ok: false, invalid: [], reason: "trusted_subnets must be an array" };
}
if (value.length > MAX_TRUSTED_SUBNETS) {
return { ok: false, invalid: [], reason: `trusted_subnets must contain at most ${MAX_TRUSTED_SUBNETS} entries` };
}
const invalid = [];
for (const raw of value) {
if (!isValidSubnet(raw) && invalid.indexOf(String(raw)) === -1) {
invalid.push(String(raw));
}
}
if (invalid.length > 0) {
return { ok: false, invalid, reason: "invalid subnet entries" };
}
const entries = [];
for (const raw of value) {
const entry = String(raw).trim();
if (entries.indexOf(entry) === -1) entries.push(entry);
}
return { ok: true, entries };
}
// For trusted-file loads and consumer hardening: keep only valid entries,
// deduplicated and capped. Never throws; always returns an array of strings.
function sanitizeTrustedSubnets(value) {
if (!Array.isArray(value)) return [];
const entries = [];
for (const raw of value) {
if (!isValidSubnet(raw)) continue;
const entry = String(raw).trim();
if (entries.indexOf(entry) === -1) entries.push(entry);
if (entries.length >= MAX_TRUSTED_SUBNETS) break;
}
return entries;
}
// True only when `ip` falls inside one of the validated trusted-subnet
// entries. Fail-closed by construction: an unparseable address, an empty or
// non-array list, or a malformed entry all resolve to "not trusted" — a
// broken configuration must never widen the bypass.
function ipMatchesTrustedSubnets(ip, subnets) {
if (typeof ip !== "string" || ip.length === 0) return false;
if (!Array.isArray(subnets) || subnets.length === 0) return false;
for (const entry of subnets) {
if (typeof entry !== "string" || entry.length === 0) continue;
try {
if (ipRangeCheck(ip, entry)) return true;
} catch { }
}
return false;
}
module.exports = {
isValidSubnet,
validateTrustedSubnetsInput,
sanitizeTrustedSubnets,
ipMatchesTrustedSubnets,
MAX_TRUSTED_SUBNETS,
MAX_SUBNET_LENGTH
};