207 lines
8.0 KiB
JavaScript
207 lines
8.0 KiB
JavaScript
"use strict";
|
|
|
|
// Security policy for database bind/listen hosts (audit finding 2.6).
|
|
//
|
|
// The panel installs PostgreSQL (pgAdmin) and MongoDB and writes the
|
|
// *bind* address those daemons listen on. Accepting "0.0.0.0" / "::"
|
|
// (all-interfaces wildcards) there exposed root-privileged database
|
|
// services to the network two clicks deep. This module centralizes:
|
|
//
|
|
// - validateDbHost: syntax-only validation for any DB host value
|
|
// (connection or bind). Unspecified addresses
|
|
// ("0.0.0.0", "::", "::0", "0:0:...:0") are
|
|
// rejected: they are never a meaningful
|
|
// connection target and are never a safe bind
|
|
// choice for this panel.
|
|
// - isWildcardDbHost: detects the unspecified-address forms above.
|
|
// - isLocalOnlyDbHost: loopback detection (localhost / 127.0.0.1 /
|
|
// ::1, optional brackets).
|
|
// - parseDbBindAllowlist: parses ADPANEL_DB_ALLOWED_HOSTS. Entries may
|
|
// be bare IPs, IPv4/IPv6 CIDRs, or hostnames,
|
|
// comma/space separated. Fail-closed per entry:
|
|
// invalid entries are reported and dropped.
|
|
// - validateDbBindHost: the actual bind policy gate. Loopback is
|
|
// always allowed. Everything else must be
|
|
// explicitly allowlisted, and wildcard
|
|
// addresses are rejected even if an operator
|
|
// lists them (use a specific CIDR instead).
|
|
//
|
|
// Remote database access remains supported through SSH tunneling, the
|
|
// node agent, or the web UIs (phpMyAdmin/pgAdmin are reverse-proxied) —
|
|
// not through a public database listener.
|
|
|
|
const ipRangeCheck = require("ip-range-check");
|
|
const { isValidSubnet } = require("./ip-subnet-validation");
|
|
|
|
const MAX_BIND_ALLOWLIST_ENTRIES = 32;
|
|
const ALLOWLIST_ENV = "ADPANEL_DB_ALLOWED_HOSTS";
|
|
|
|
// --- syntax validators (moved verbatim from index.js) -------------------------
|
|
|
|
function validateIPv4(ip) {
|
|
if (!ip || typeof ip !== 'string') return null;
|
|
const trimmed = ip.trim();
|
|
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
|
|
return ipv4Regex.test(trimmed) ? trimmed : null;
|
|
}
|
|
|
|
function validateIPv6(ip) {
|
|
if (!ip || typeof ip !== 'string') return null;
|
|
const trimmed = ip.trim();
|
|
if (/['"\\$`\s;|&<>(){}[\]!#]/.test(trimmed)) return null;
|
|
const ipv6Regex = /^(?:[a-fA-F0-9]{1,4}:){0,7}[a-fA-F0-9]{0,4}$/;
|
|
if (trimmed === '::' || trimmed === '::1' || trimmed === '::0') return trimmed;
|
|
const parts = trimmed.split(':');
|
|
if (parts.length < 2 || parts.length > 8) return null;
|
|
for (const part of parts) {
|
|
if (part !== '' && !/^[a-fA-F0-9]{1,4}$/.test(part)) return null;
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
function validateHostname(host) {
|
|
if (!host || typeof host !== 'string') return null;
|
|
const trimmed = host.trim().toLowerCase();
|
|
if (trimmed.length === 0 || trimmed.length > 253) return null;
|
|
if (!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/.test(trimmed)) return null;
|
|
const labels = trimmed.split('.');
|
|
for (const label of labels) {
|
|
if (label.length === 0 || label.length > 63) return null;
|
|
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) return null;
|
|
if (label.startsWith('-') || label.endsWith('-')) return null;
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
// --- wildcard (unspecified address) detection ---------------------------------
|
|
|
|
// "0.0.0.0" plus every IPv6 textual form made only of zeros and colons
|
|
// ("::", "::0", "0:0:0:0:0:0:0:0", "0000::" ...). All of them mean
|
|
// INADDR_ANY / in6addr_any — bind-to-every-interface.
|
|
function isWildcardDbHost(host) {
|
|
const normalized = String(host || "").trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
if (normalized === "0.0.0.0") return true;
|
|
return normalized.length > 0 && /^[0:]+$/.test(normalized);
|
|
}
|
|
|
|
// --- loopback detection --------------------------------------------------------
|
|
|
|
function isLocalOnlyDbHost(host) {
|
|
const normalized = String(host || "").trim().toLowerCase();
|
|
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
|
|
}
|
|
|
|
// --- syntax-only host validation (no wildcard, no network policy) -------------
|
|
|
|
function validateDbHost(host) {
|
|
if (!host || typeof host !== 'string') return null;
|
|
const trimmed = host.trim();
|
|
|
|
if (isWildcardDbHost(trimmed)) return null;
|
|
|
|
if (trimmed.toLowerCase() === 'localhost') return 'localhost';
|
|
|
|
const ipv4 = validateIPv4(trimmed);
|
|
if (ipv4) return ipv4;
|
|
|
|
const ipv6 = validateIPv6(trimmed);
|
|
if (ipv6) return ipv6;
|
|
|
|
const hostname = validateHostname(trimmed);
|
|
if (hostname) return hostname;
|
|
|
|
return null;
|
|
}
|
|
|
|
// --- bind allowlist (ADPANEL_DB_ALLOWED_HOSTS) ---------------------------------
|
|
|
|
// Accepts comma and/or whitespace separated entries. Valid entries are
|
|
// bare IPs, IPv4/IPv6 CIDRs ("192.168.1.0/24", "fd00::/8") or hostnames
|
|
// ("db.internal"). Returns { entries, invalid }; entries are trimmed,
|
|
// deduplicated and capped. Never throws.
|
|
function parseDbBindAllowlist(raw) {
|
|
const result = { entries: [], invalid: [] };
|
|
if (raw === undefined || raw === null) return result;
|
|
const parts = String(raw)
|
|
.split(/[\s,]+/)
|
|
.map((s) => s.trim())
|
|
.filter((s) => s.length > 0);
|
|
|
|
for (const part of parts) {
|
|
const ok = isValidSubnet(part) || validateHostname(part) !== null;
|
|
if (!ok) {
|
|
if (!result.invalid.includes(part)) result.invalid.push(part);
|
|
continue;
|
|
}
|
|
if (!result.entries.includes(part)) result.entries.push(part);
|
|
if (result.entries.length >= MAX_BIND_ALLOWLIST_ENTRIES) break;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// Reads the env var, logs invalid entries (fail-closed per entry) and
|
|
// returns the valid entries array.
|
|
function loadDbBindAllowlist(env = process.env, log = console) {
|
|
const raw = env[ALLOWLIST_ENV];
|
|
if (raw === undefined || String(raw).trim() === "") return [];
|
|
const { entries, invalid } = parseDbBindAllowlist(raw);
|
|
if (invalid.length > 0) {
|
|
log.error(`[db-bind-policy] Ignoring invalid ${ALLOWLIST_ENV} entries (each must be an IP, CIDR, or hostname): ${invalid.join(", ")}`);
|
|
}
|
|
if (entries.length > 0) {
|
|
log.warn(`[db-bind-policy] Non-loopback database binds are permitted for: ${entries.join(", ")} (from ${ALLOWLIST_ENV})`);
|
|
}
|
|
return entries;
|
|
}
|
|
|
|
// Exact match for hostnames, subnet membership for IPs. Hosts that are
|
|
// not IP literals are only matched by exact (case-insensitive) string.
|
|
function dbBindAllowlistMatches(host, entries) {
|
|
if (!host || !Array.isArray(entries) || entries.length === 0) return false;
|
|
const candidate = String(host).trim();
|
|
const candidateIp = validateIPv4(candidate) || validateIPv6(candidate);
|
|
|
|
for (const entry of entries) {
|
|
if (!entry) continue;
|
|
if (candidate.toLowerCase() === entry.toLowerCase()) return true;
|
|
if (candidateIp && isValidSubnet(entry)) {
|
|
try {
|
|
if (ipRangeCheck(candidateIp, entry)) return true;
|
|
} catch {
|
|
// Malformed entries are already filtered at parse time; never
|
|
// let a match error widen the policy.
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// --- the bind policy gate ------------------------------------------------------
|
|
|
|
// Returns the normalized host when binding is permitted, null otherwise.
|
|
// Order matters: wildcards are rejected BEFORE the allowlist so even an
|
|
// explicitly listed "0.0.0.0" can never re-enable all-interfaces binds.
|
|
function validateDbBindHost(host, entries) {
|
|
const normalized = validateDbHost(host);
|
|
if (normalized === null) return null;
|
|
if (isWildcardDbHost(normalized)) return null;
|
|
if (isLocalOnlyDbHost(normalized)) return normalized;
|
|
if (dbBindAllowlistMatches(normalized, entries)) return normalized;
|
|
return null;
|
|
}
|
|
|
|
module.exports = {
|
|
validateIPv4,
|
|
validateIPv6,
|
|
validateHostname,
|
|
validateDbHost,
|
|
validateDbBindHost,
|
|
isWildcardDbHost,
|
|
isLocalOnlyDbHost,
|
|
parseDbBindAllowlist,
|
|
loadDbBindAllowlist,
|
|
dbBindAllowlistMatches,
|
|
MAX_BIND_ALLOWLIST_ENTRIES,
|
|
ALLOWLIST_ENV,
|
|
};
|