Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+268
View File
@@ -0,0 +1,268 @@
// Standalone verification harness for the trusted_subnets validation fix (L-3).
// Proves the security properties of utils/ip-subnet-validation.js and the
// wiring in index.js / utils/db-proxy.js:
// 1. The validator accepts every canonical IPv4/IPv6 bare-IP and CIDR form.
// 2. The validator rejects malformed CIDRs AND injection payloads
// (HTML/JS metacharacters never reach stored state).
// 3. The endpoint contract is all-or-nothing: one bad entry rejects the
// whole update with 400 (no partial save), valid input is stored
// trimmed/deduplicated/capped.
// 4. Stored values always match through the real ip-range-check matcher
// exactly as documented (fail-closed on non-matches, no exceptions).
// 5. sanitizeTrustedSubnets() drops garbage from hand-edited security.json
// on every load path (initial load, fs.watch reload).
// 5b. The global rate-limiter bypass matcher ipMatchesTrustedSubnets()
// resolves validated entries exactly as documented, fail-closed.
// Run: node scripts/verify-trusted-subnet-validation.js
const assert = require("assert");
const crypto = require("crypto");
const express = require("express");
const session = require("express-session");
const http = require("http");
const ipRangeCheck = require("ip-range-check");
const {
isValidSubnet,
validateTrustedSubnetsInput,
sanitizeTrustedSubnets,
ipMatchesTrustedSubnets,
MAX_TRUSTED_SUBNETS,
MAX_SUBNET_LENGTH
} = require("../utils/ip-subnet-validation");
let passed = 0;
function ok(cond, label) {
assert.ok(cond, label);
passed++;
console.log(` ok - ${label}`);
}
// ─── 1. Valid forms are accepted ───────────────────────────────
console.log("[1] valid subnet forms");
const validForms = [
"10.0.0.5", // bare IPv4 (exact match semantics)
"10.0.0.0/24", // canonical IPv4 CIDR
"0.0.0.0/0", // IPv4 default route (boundary prefix 0)
"255.255.255.255/32", // IPv4 max prefix
"192.168.1.37/32",
"2001:db8::/32", // IPv6 CIDR
"2001:db8::1", // bare IPv6
"::/0", // IPv6 default route
"fe80::/10",
"::1/128",
"::ffff:10.0.0.1" // IPv4-mapped bare IPv6 (valid; the matcher normalizes it to plain IPv4)
];
for (const entry of validForms) {
ok(isValidSubnet(entry) === true, `accepts ${entry}`);
}
// Leading/trailing whitespace is trimmed by callers, not part of the value.
ok(isValidSubnet(" 10.0.0.0/24 ") === true, "accepts entry that needs trimming");
// ─── 2. Malformed + injection payloads are rejected ────────────
console.log("[2] malformed and hostile inputs");
const invalidForms = [
// malformed CIDRs
"999.1.2.3/8", // octet out of range
"10.0.0.0/33", // prefix > 32
"2001:db8::/129", // prefix > 128
"10.0.0.0/-1", // negative prefix
"10.0.0.0/1.5", // fractional prefix
"10.0.0.0/+8", // prefix with sign
"10.0.0.0/", // empty prefix
"10.0.0.0/24/8", // second slash
"/24", // empty IP part
"10.0.0.0/08", // non-canonical leading-zero prefix
"10.0.0.0/ 24", // whitespace in prefix
"::ffff:10.0.0.0/120", // IPv4-mapped CIDR: prefix applies to the IPv6 form,
"::ffff:0:0/96", // but the matcher compares plain IPv4 — never-matchable
// shorthand / lenient forms ipaddr.js would still parse — kept out on purpose
"127.1", // IPv4 shorthand
"1", // integer form
"3232235520", // 32-bit integer form
"fe80::1%eth0", // zone id
"10.0.0.256", // bad bare IPv4
"10.0.0", // incomplete IPv4
"10.0.0.0:80", // host:port
"not-a-subnet",
"", // empty
" ", // whitespace only
// injection payloads (the stored-XSS class this fix closes)
'"><img src=x onerror=alert(1)>',
"<script>alert(1)</script>",
"10.0.0.0/24<script>",
"javascript:alert(1)",
"&#60;img src=x onerror=alert(1)&#62;",
"${jndi:ldap://x}",
"10.0.0.0/24 OR 1=1",
"' OR '1'='1",
"10.0.0.0/24\n# comment", // env-file / log injection
"10.0.0.0/24\r\nFOO=bar",
"\u0000",
"../../etc/passwd",
"%00%2e%2e%2f"
];
for (const entry of invalidForms) {
ok(isValidSubnet(entry) === false, `rejects ${JSON.stringify(entry.slice(0, 40))}`);
}
ok(isValidSubnet(null) === false, "rejects null");
ok(isValidSubnet(undefined) === false, "rejects undefined");
ok(isValidSubnet(10) === false, "rejects number");
ok(isValidSubnet({}) === false, "rejects object");
ok(isValidSubnet(["10.0.0.0/24"]) === false, "rejects nested array");
ok(isValidSubnet("a".repeat(MAX_SUBNET_LENGTH + 1)) === false, "rejects over-length entry");
ok(isValidSubnet("a".repeat(MAX_SUBNET_LENGTH)) === false, "rejects over-length entry that is not an IP");
// Confirms the stored value space contains no HTML metacharacters.
ok(!/[<>&"'`\\;{}$]/.test("10.0.0.0/24") && !/[<>&"'`\\;{}$]/.test("2001:db8::/32"),
"valid value space excludes HTML/JS metacharacters");
// ─── 3. Endpoint contract: all-or-nothing validation ───────────
console.log("[3] endpoint input contract");
const bad = validateTrustedSubnetsInput(["10.0.0.0/24", '"><img src=x onerror=alert(1)>']);
ok(bad.ok === false, "one malformed entry rejects the whole update");
ok(bad.invalid.length === 1 && bad.invalid[0] === '"><img src=x onerror=alert(1)>',
"400 payload names the offending entry");
const badCount = validateTrustedSubnetsInput(new Array(MAX_TRUSTED_SUBNETS + 1).fill("10.0.0.0/24"));
ok(badCount.ok === false, "more than 50 entries rejected");
const badType = validateTrustedSubnetsInput("10.0.0.0/24");
ok(badType.ok === false, "non-array input rejected");
const good = validateTrustedSubnetsInput([" 10.0.0.0/24 ", "10.0.0.0/24", "2001:DB8::/32"]);
ok(good.ok === true, "valid input accepted");
ok(JSON.stringify(good.entries) === JSON.stringify(["10.0.0.0/24", "2001:DB8::/32"]),
"entries stored trimmed and deduplicated");
const mixedJunk = validateTrustedSubnetsInput([10, null, {}, "10.0.0.0/24"]);
ok(mixedJunk.ok === false, "non-string entries rejected (fail-closed, not coerced)");
// ─── 4. Live route harness replicating the endpoint block ──────
console.log("[4] POST /api/settings/security contract (isolated app)");
function buildApp() {
const app = express();
app.use(express.json());
app.use(session({ secret: crypto.randomBytes(32).toString("hex"), resave: false, saveUninitialized: true, cookie: { httpOnly: true } }));
app.post("/test/login", (req, res) => { req.session.user = "admin"; res.json({ ok: true }); });
const state = { trusted_subnets: [] };
app.post("/api/settings/security", (req, res) => {
const { trusted_subnets } = req.body || {};
if (trusted_subnets !== undefined) {
const subnets = validateTrustedSubnetsInput(trusted_subnets);
if (!subnets.ok) {
const detail = subnets.invalid.length > 0
? `: ${subnets.invalid.map(s => JSON.stringify(s.slice(0, 64))).join(", ")}`
: "";
return res.status(400).json({
error: `${subnets.reason}${detail}. Expected IPv4/IPv6 addresses or CIDRs (e.g. 192.168.1.0/24, 2001:db8::/32).`
});
}
state.trusted_subnets = subnets.entries;
}
res.json({ ok: true, stored: state.trusted_subnets });
});
return app;
}
function post(port, path, body) {
return new Promise((resolve, reject) => {
const data = JSON.stringify(body);
const req = http.request({ host: "127.0.0.1", port, path, method: "POST", headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
let buf = "";
res.on("data", c => (buf += c));
res.on("end", () => resolve({ status: res.statusCode, body: buf }));
});
req.on("error", reject);
req.end(data);
});
}
(async () => {
const app = buildApp();
const server = app.listen(0, "127.0.0.1");
await new Promise(r => server.on("listening", r));
const port = server.address().port;
const r1 = await post(port, "/api/settings/security", { trusted_subnets: ["10.0.0.0/24", "2001:db8::/32"] });
ok(r1.status === 200, "valid update returns 200");
const stored = JSON.parse(r1.body).stored;
ok(JSON.stringify(stored) === JSON.stringify(["10.0.0.0/24", "2001:db8::/32"]), "valid entries persisted");
const r2 = await post(port, "/api/settings/security", { trusted_subnets: ["10.0.0.0/24", "<img src=x onerror=alert(1)>"] });
ok(r2.status === 400, "malformed entry returns 400");
ok(r2.body.includes("<img") || JSON.parse(r2.body).error.includes("<img"), "400 error message identifies the offending entry");
const r3 = await post(port, "/api/settings/security", { trusted_subnets: "10.0.0.0/24" });
ok(r3.status === 400, "non-array trusted_subnets returns 400");
// Previously-stored state survives a rejected update (no partial write).
const r4 = await post(port, "/api/settings/security", {});
ok(r4.status === 200 && JSON.stringify(JSON.parse(r4.body).stored) === JSON.stringify(["10.0.0.0/24", "2001:db8::/32"]),
"request without the key leaves stored state untouched");
server.close();
// ─── 5. Matcher integration: stored values behave as documented ──
console.log("[5] ip-range-check integration on validated entries");
const subnets = sanitizeTrustedSubnets(["10.0.0.0/24", "10.0.0.5", "2001:db8::/32", "junk-<script>"]);
ok(JSON.stringify(subnets) === JSON.stringify(["10.0.0.0/24", "10.0.0.5", "2001:db8::/32"]),
"sanitizer drops malformed entries before matching");
ok(ipRangeCheck("10.0.0.55", subnets) === true, "IPv4 within CIDR matches");
ok(ipRangeCheck("10.0.1.55", subnets) === false, "IPv4 outside CIDR does not match");
ok(ipRangeCheck("10.0.0.5", subnets) === true, "bare-IP entry matches exactly");
ok(ipRangeCheck("10.0.0.6", subnets) === true, "bare-IP entry covered by sibling CIDR (documented)");
ok(ipRangeCheck("2001:db8::1", subnets) === true, "IPv6 within CIDR matches");
ok(ipRangeCheck("2001:db9::1", subnets) === false, "IPv6 outside CIDR does not match");
ok(ipRangeCheck("8.8.8.8", ["0.0.0.0/0"]) === true, "0.0.0.0/0 matches all IPv4");
ok(ipRangeCheck("::1", subnets) === false, "IPv6 not matched by IPv4-only list");
// db-proxy authorization is session-bound only: the IP-based fallback was
// removed (audit finding 2.4 — shared NAT IPs and spoofable forwarding
// headers turned IP "authorization" into a no-session bearer bypass). The
// helper must stay gone so it cannot be casually re-wired.
const dbProxy = require("../utils/db-proxy");
const sha256 = (v) => crypto.createHash("sha256").update(String(v)).digest("hex");
ok(dbProxy.isIpAuthorized === undefined, "db-proxy no longer performs IP-based authorization");
ok(typeof dbProxy.createProxyMiddleware === "function", "db-proxy proxy middleware loads");
ok(typeof dbProxy.sessionMatchesToken === "function", "db-proxy exposes the session-bound matcher");
// Records carry SHA-256(sessionId) instead of the raw panel session id so
// the shared token store cannot be mined for replayable cookie values.
ok(dbProxy.sessionMatchesToken({ sessionIdHash: sha256("s1"), username: "a@x" }, { sessionID: "s1", session: { user: "b@x" } }) === false, "session matcher fails closed on a different username");
ok(dbProxy.sessionMatchesToken({ sessionIdHash: sha256("s1"), username: "a@x" }, { sessionID: "s2", session: { user: "a@x" } }) === false, "session matcher fails closed on a different session id");
ok(dbProxy.sessionMatchesToken({ sessionIdHash: sha256("s1"), username: "a@x" }, { sessionID: "s1", session: { user: "a@x" } }) === true, "session matcher accepts the exact minting session");
// ─── 5b. Global rate-limiter bypass matcher (sole production consumer) ──
console.log("[5b] ipMatchesTrustedSubnets (global limiter bypass matcher)");
ok(ipMatchesTrustedSubnets("10.0.0.55", ["10.0.0.0/24"]) === true, "bypass matcher: IPv4 within CIDR matches");
ok(ipMatchesTrustedSubnets("10.0.1.55", ["10.0.0.0/24"]) === false, "bypass matcher: IPv4 outside CIDR does not match");
ok(ipMatchesTrustedSubnets("10.0.0.5", ["10.0.0.5"]) === true, "bypass matcher: bare-IP entry matches exactly");
ok(ipMatchesTrustedSubnets("10.0.0.6", ["10.0.0.5"]) === false, "bypass matcher: bare-IP entry does not match a different IP");
ok(ipMatchesTrustedSubnets("2001:db8::1", ["2001:db8::/32"]) === true, "bypass matcher: IPv6 within CIDR matches");
ok(ipMatchesTrustedSubnets("2001:db9::1", ["2001:db8::/32"]) === false, "bypass matcher: IPv6 outside CIDR does not match");
ok(ipMatchesTrustedSubnets("::ffff:10.0.0.55", ["10.0.0.0/24"]) === true, "bypass matcher: IPv4-mapped request IP matches the IPv4 CIDR");
ok(ipMatchesTrustedSubnets("10.0.0.1", ["::ffff:10.0.0.1"]) === true, "bypass matcher: bare IPv4-mapped entry matches the plain IPv4 address");
ok(ipMatchesTrustedSubnets("10.0.0.55", ["::ffff:10.0.0.1"]) === false, "bypass matcher: bare IPv4-mapped entry matches only its own address");
ok(ipMatchesTrustedSubnets("10.0.0.0", ["10.0.0.0/24"]) === true, "bypass matcher: network address is inside the CIDR");
ok(ipMatchesTrustedSubnets("10.0.0.255", ["10.0.0.0/24"]) === true, "bypass matcher: last address is inside the CIDR");
ok(ipMatchesTrustedSubnets("10.0.1.0", ["10.0.0.0/24"]) === false, "bypass matcher: first address past the CIDR does not match");
ok(ipMatchesTrustedSubnets("10.0.0.55", ["10.0.0.0/24<script>", "10.0.0.0/24"]) === true, "bypass matcher: malformed entry skipped, valid sibling still matches, no throw");
ok(ipMatchesTrustedSubnets("10.0.0.55", [null, 33, { subnet: true }, "10.0.0.0/24"]) === true, "bypass matcher: junk entry types skipped, valid entry still matches");
ok(ipMatchesTrustedSubnets("10.0.1.55", [null, 33, { subnet: true }, "10.0.0.0/24"]) === false, "bypass matcher: junk entry types skipped, no accidental match");
ok(ipMatchesTrustedSubnets(null, ["10.0.0.0/24"]) === false, "bypass matcher: non-string IP fails closed");
ok(ipMatchesTrustedSubnets("", ["10.0.0.0/24"]) === false, "bypass matcher: empty IP fails closed");
ok(ipMatchesTrustedSubnets("unknown", ["10.0.0.0/24"]) === false, "bypass matcher: 'unknown' IP fails closed");
ok(ipMatchesTrustedSubnets("10.0.0.55", "10.0.0.0/24") === false, "bypass matcher: non-array subnet list fails closed");
ok(ipMatchesTrustedSubnets("10.0.0.55", []) === false, "bypass matcher: empty subnet list fails closed");
ok(ipMatchesTrustedSubnets("8.8.8.8", ["0.0.0.0/0"]) === true, "bypass matcher: 0.0.0.0/0 matches any IPv4");
ok(ipMatchesTrustedSubnets("::1", ["0.0.0.0/0"]) === false, "bypass matcher: 0.0.0.0/0 does not cover IPv6");
// ─── 6. Load-path hardening against hand-edited security.json ────
console.log("[6] load-path sanitization");
const hostile = sanitizeTrustedSubnets(JSON.parse('["10.0.0.0/24","<script>alert(1)</script>","127.1",{"x":1},null,33,"2001:db8::/32"]'));
ok(JSON.stringify(hostile) === JSON.stringify(["10.0.0.0/24", "2001:db8::/32"]),
"hand-edited file entries sanitized to valid CIDRs only");
ok(JSON.stringify(sanitizeTrustedSubnets("<script>")) === JSON.stringify([]),
"scalar garbage from a corrupt file sanitizes to an empty list");
const capped = sanitizeTrustedSubnets(
Array.from({ length: 200 }, (_, i) => `10.${(i >> 8) & 255}.${i & 255}.0/24`)
);
ok(capped.length === MAX_TRUSTED_SUBNETS, "load-path entries capped at 50");
const duped = sanitizeTrustedSubnets(new Array(200).fill("10.0.0.0/24"));
ok(duped.length === 1, "duplicate entries collapse instead of consuming the cap");
console.log(`\nALL ${passed} CHECKS PASSED`);
process.exit(0);
})().catch(err => {
console.error("VERIFY FAILED:", err.message);
process.exit(1);
});