437 lines
18 KiB
JavaScript
437 lines
18 KiB
JavaScript
"use strict";
|
|
|
|
const { sanitizeVolumeSpec, sanitizeTemplateVolumeList, validateTemplateVolumeListPayload } = require("../public/js/template-volumes");
|
|
|
|
const POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
|
|
function cleanString(value) {
|
|
return String(value ?? "").trim();
|
|
}
|
|
|
|
function cleanScript(value, maxLength = 262144) {
|
|
return String(value ?? "")
|
|
.replace(/\0/g, "")
|
|
.replace(/\r\n?/g, "\n")
|
|
.trim()
|
|
.slice(0, maxLength);
|
|
}
|
|
|
|
function toFiniteNumber(value) {
|
|
const numeric = Number(value);
|
|
return Number.isFinite(numeric) ? numeric : null;
|
|
}
|
|
|
|
function normalizePortProtocol(value) {
|
|
const protocol = cleanString(value).toLowerCase();
|
|
return protocol === "tcp" || protocol === "udp" || protocol === "sctp" ? protocol : "";
|
|
}
|
|
|
|
function sanitizePortProtocolPayload(portProtocols, ports = []) {
|
|
if (!portProtocols || typeof portProtocols !== "object" || Array.isArray(portProtocols)) return null;
|
|
|
|
const allowedPorts = new Set(
|
|
(Array.isArray(ports) ? ports : [])
|
|
.map((entry) => toFiniteNumber(entry))
|
|
.filter((entry) => Number.isInteger(entry) && entry > 0)
|
|
.map((entry) => String(entry))
|
|
);
|
|
const out = {};
|
|
for (const [rawPort, rawProtocols] of Object.entries(portProtocols)) {
|
|
const port = toFiniteNumber(rawPort);
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
|
|
const portKey = String(port);
|
|
if (allowedPorts.size && !allowedPorts.has(portKey)) continue;
|
|
|
|
const source = Array.isArray(rawProtocols) ? rawProtocols : [rawProtocols];
|
|
const protocols = [];
|
|
const seen = new Set();
|
|
for (const entry of source) {
|
|
const protocol = normalizePortProtocol(entry);
|
|
if (!protocol || seen.has(protocol)) continue;
|
|
seen.add(protocol);
|
|
protocols.push(protocol);
|
|
}
|
|
if (protocols.length) out[portKey] = protocols;
|
|
}
|
|
return Object.keys(out).length ? out : null;
|
|
}
|
|
|
|
function cleanAbsoluteContainerPath(value, fallback = "") {
|
|
let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/");
|
|
if (!raw) return fallback;
|
|
if (!raw.startsWith("/")) return fallback;
|
|
raw = raw.replace(/\/+/g, "/");
|
|
if (raw.length > 1) raw = raw.replace(/\/+$/, "");
|
|
return raw || fallback;
|
|
}
|
|
|
|
// Environment payloads originate from untrusted template JSON and end up in
|
|
// container process environments through two sinks: the Docker Engine API
|
|
// "KEY=VALUE" Env list and `docker run -e KEY=VALUE` argv (installers). Both
|
|
// split on the first "=", so the sanitized key must BE the name the container
|
|
// sees — a key containing "=" would silently rename the variable and could
|
|
// carry a different name past any key-based allowlist/denylist. Whitespace,
|
|
// NUL and control characters break "KEY=VALUE" / argv / env-file framing the
|
|
// same way. Keys are therefore restricted to [A-Za-z0-9_][A-Za-z0-9_.-]*,
|
|
// the same charset the startup template {{KEY}} tokenizer accepts, so every
|
|
// surviving key stays referenceable (non-identifier keys like "my-key" keep
|
|
// working via the quoted-splice path in the node's startup renderer). Values
|
|
// stay opaque single strings: NUL cannot survive execve (runc rejects the
|
|
// whole container), while newlines remain legal (PEM/JSON blobs) because no
|
|
// consumer writes env to line-oriented files and the startup renderer passes
|
|
// values through the shell as quoted data, never as code.
|
|
const ENV_KEY_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
|
|
const ENV_KEY_MAX_LENGTH = 128;
|
|
const ENV_VALUE_MAX_LENGTH = 32768;
|
|
const ENV_MAX_ENTRIES = 128;
|
|
|
|
function sanitizeEnvPayload(env) {
|
|
if (!env || typeof env !== "object" || Array.isArray(env)) return null;
|
|
const out = {};
|
|
let entries = 0;
|
|
for (const [key, value] of Object.entries(env)) {
|
|
if (entries >= ENV_MAX_ENTRIES) break;
|
|
const envKey = cleanString(key);
|
|
if (POLLUTION_KEYS.has(envKey)) continue;
|
|
if (envKey.length > ENV_KEY_MAX_LENGTH || !ENV_KEY_RE.test(envKey)) continue;
|
|
const envValue = String(value ?? "").replace(/\0/g, "");
|
|
if (envValue.length > ENV_VALUE_MAX_LENGTH) continue;
|
|
out[envKey] = envValue;
|
|
entries++;
|
|
}
|
|
return Object.keys(out).length ? out : null;
|
|
}
|
|
|
|
// Fail-closed boundary validator for template ingestion (manual create,
|
|
// manual update and store install). sanitizeEnvPayload silently drops
|
|
// unusable entries while normalizing stored templates — the right policy
|
|
// there, but the wrong policy where untrusted request/store JSON first lands:
|
|
// a payload whose env the panel refuses to persist must answer 400 naming the
|
|
// rejected entry, not store a template whose servers silently run without the
|
|
// variables the admin reviewed (the same fail-closed rule as
|
|
// validateTemplateVolumeListPayload below). Accepts the same shapes — a
|
|
// missing or null env is a valid "no variables" request — and for valid input
|
|
// returns byte-identical output to sanitizeEnvPayload, so the boundary never
|
|
// persists something the runtime normalizer would later drop. install.env
|
|
// stays on the silent sanitizer: that path is normalization-only and the
|
|
// review dialog displays the sanitized result, so nothing is reviewed-then-
|
|
// dropped there either.
|
|
function validateTemplateEnvPayload(value) {
|
|
if (value === undefined || value === null) return { env: {} };
|
|
if (typeof value !== "object" || Array.isArray(value)) {
|
|
return { error: "invalid env — expected an object of KEY=VALUE pairs" };
|
|
}
|
|
const entries = Object.entries(value);
|
|
if (entries.length > ENV_MAX_ENTRIES) {
|
|
return { error: `too many env entries (max ${ENV_MAX_ENTRIES})` };
|
|
}
|
|
const out = {};
|
|
for (const [rawKey, rawValue] of entries) {
|
|
const envKey = cleanString(rawKey);
|
|
if (!envKey) {
|
|
return { error: "invalid env — an entry has an empty key" };
|
|
}
|
|
if (POLLUTION_KEYS.has(envKey) || envKey.length > ENV_KEY_MAX_LENGTH || !ENV_KEY_RE.test(envKey)) {
|
|
const shown = envKey.length > 120 ? `${envKey.slice(0, 120)}…` : envKey;
|
|
return { error: `invalid env key "${shown}" — keys must match [A-Za-z0-9_][A-Za-z0-9_.-]* (max ${ENV_KEY_MAX_LENGTH} characters)` };
|
|
}
|
|
// sanitizeEnvPayload coerces values with String(); a JSON object/array
|
|
// value would survive as "[object Object]" — garbage no admin reviewed —
|
|
// so the boundary refuses it instead.
|
|
if (rawValue !== null && rawValue !== undefined && typeof rawValue === "object") {
|
|
return { error: `invalid env value for "${envKey}" — values must be strings, numbers, booleans or null` };
|
|
}
|
|
const envValue = String(rawValue ?? "").replace(/\0/g, "");
|
|
if (envValue.length > ENV_VALUE_MAX_LENGTH) {
|
|
return { error: `env value for "${envKey}" is too long (max ${ENV_VALUE_MAX_LENGTH} characters)` };
|
|
}
|
|
out[envKey] = envValue;
|
|
}
|
|
return { env: out };
|
|
}
|
|
|
|
const CONSOLE_MODES = new Set(["stdin", "exec", "exec-shell", "shell"]);
|
|
const CONSOLE_TARGET_MAX_LENGTH = 120;
|
|
const CONSOLE_TARGET_MAX_COUNT = 12;
|
|
|
|
function cleanConsoleTargets(rawTargets) {
|
|
if (!Array.isArray(rawTargets)) return [];
|
|
const seen = new Set();
|
|
const out = [];
|
|
for (const entry of rawTargets) {
|
|
let target = cleanString(entry).replace(/^['"]|['"]$/g, "");
|
|
if (!target || target === "<nil>" || /[\0\r\n]/.test(target)) continue;
|
|
if (target.length > CONSOLE_TARGET_MAX_LENGTH) {
|
|
target = target.slice(0, CONSOLE_TARGET_MAX_LENGTH);
|
|
}
|
|
if (seen.has(target)) continue;
|
|
seen.add(target);
|
|
out.push(target);
|
|
if (out.length >= CONSOLE_TARGET_MAX_COUNT) break;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// Console config arrives from remote/store templates untrusted. Only a
|
|
// normalized {type, targetProcesses?} shape is accepted; everything else the
|
|
// console exec machinery understands is rebuilt here.
|
|
function sanitizeConsolePayload(consoleConfig) {
|
|
if (consoleConfig === null || consoleConfig === undefined) return null;
|
|
if (typeof consoleConfig === "string") {
|
|
const mode = consoleConfig.trim().toLowerCase();
|
|
if (CONSOLE_MODES.has(mode)) return { type: mode };
|
|
const targets = cleanConsoleTargets([consoleConfig]);
|
|
return targets.length ? { type: "stdin", targetProcesses: targets } : null;
|
|
}
|
|
if (Array.isArray(consoleConfig)) {
|
|
const targets = cleanConsoleTargets(consoleConfig);
|
|
return targets.length ? { type: "stdin", targetProcesses: targets } : null;
|
|
}
|
|
if (typeof consoleConfig !== "object") return null;
|
|
|
|
const rawMode = cleanString(consoleConfig.type || consoleConfig.mode || "stdin").toLowerCase();
|
|
const mode = CONSOLE_MODES.has(rawMode) ? rawMode : "stdin";
|
|
const rawTargets = consoleConfig.targetProcesses
|
|
?? consoleConfig.target_processes
|
|
?? consoleConfig.processes
|
|
?? consoleConfig.processNames
|
|
?? consoleConfig.process_names
|
|
?? consoleConfig.targetProcess
|
|
?? consoleConfig.target_process
|
|
?? consoleConfig.process
|
|
?? consoleConfig.target;
|
|
const targets = cleanConsoleTargets(rawTargets);
|
|
return {
|
|
type: mode,
|
|
...(targets.length ? { targetProcesses: targets } : {}),
|
|
};
|
|
}
|
|
|
|
// --- Container-boundary script policy -----------------------------------------
|
|
// Templates carry three executable surfaces with different execution models and
|
|
// therefore different rules:
|
|
// * docker.command — argv, no shell at all: index.js's
|
|
// validateRuntimeProcessCommandInput rejects shell semantics outright.
|
|
// * adpanelStartup — arbitrary shell inside the SERVER container; it may do
|
|
// anything within that boundary but must not reach past it (runtime
|
|
// sockets/CLIs, namespace tools, host namespaces).
|
|
// * install.script — arbitrary shell inside the INSTALLER container. Same
|
|
// boundary rule as adpanelStartup, plus whole-word runtime-tool rejection:
|
|
// the installer image is attacker-chosen and networked, so a container
|
|
// runtime reference (docker, podman, ...) can only be an escape attempt —
|
|
// no legitimate install script manages containers.
|
|
// This module and the node agent (validateADPanelStartupScript /
|
|
// validateTemplateInstallScript in main.go) enforce the same lists; keep the
|
|
// copies behavior-equivalent. Defense in depth: containers run with
|
|
// cap-drop-all, no-new-privileges and a bind allowlist.
|
|
const CONTAINER_BOUNDARY_BLOCKED_PATTERNS = [
|
|
'docker.sock', 'podman.sock', 'containerd.sock',
|
|
'--privileged', '--pid=host', '--network=host', '--net=host',
|
|
'/proc/1/root',
|
|
];
|
|
const ADPANEL_STARTUP_BLOCKED_DOCKER_CLI_RE = /\bdocker\s+(run|exec|build|create|cp|save|load|export|import|kill|stop|restart|rm|rmi|volume|network|node|swarm|system|container|image|plugin|secret|service|stack|stats|update)\b/;
|
|
const ADPANEL_STARTUP_BLOCKED_TOOLS_RE = /\b(podman|nerdctl|nsenter|unshare)\b/;
|
|
const INSTALL_SCRIPT_BLOCKED_RUNTIME_RE = /\b(docker|podman|nerdctl|ctr|nsenter|unshare)\b/;
|
|
|
|
// Managed startup scripts are by design arbitrary shell inside the server
|
|
// container; this check keeps them from reaching past the container boundary
|
|
// on every ingestion path. Moved verbatim from index.js so the panel boundary,
|
|
// the runtime normalizer and the dashboard assistant share one policy home.
|
|
function validateADPanelStartupScriptInput(value) {
|
|
const script = String(value ?? '').trim();
|
|
if (!script) return null;
|
|
if (script.length > 32768) return 'Managed startup script is too long (max 32768 characters).';
|
|
const lower = script.toLowerCase();
|
|
for (const pattern of CONTAINER_BOUNDARY_BLOCKED_PATTERNS) {
|
|
if (lower.includes(pattern)) {
|
|
return `Managed startup scripts cannot reference "${pattern}".`;
|
|
}
|
|
}
|
|
const dockerMatch = lower.match(ADPANEL_STARTUP_BLOCKED_DOCKER_CLI_RE);
|
|
if (dockerMatch) {
|
|
return `Managed startup scripts cannot reference "${dockerMatch[0].trim()}". Configure the container via the template instead.`;
|
|
}
|
|
const toolMatch = lower.match(ADPANEL_STARTUP_BLOCKED_TOOLS_RE);
|
|
if (toolMatch) {
|
|
return `Managed startup scripts cannot reference "${toolMatch[1]}".`;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Install scripts run as shell in a dedicated installer container. Length and
|
|
// encoding stay normalization concerns (cleanScript); this check rejects the
|
|
// container-escape surface, mirroring validateADPanelStartupScriptInput plus
|
|
// the stricter whole-word runtime-tool rule above.
|
|
function validateTemplateInstallScriptInput(value) {
|
|
const script = String(value ?? '').trim();
|
|
if (!script) return null;
|
|
const lower = script.toLowerCase();
|
|
for (const pattern of CONTAINER_BOUNDARY_BLOCKED_PATTERNS) {
|
|
if (lower.includes(pattern)) {
|
|
return `Install scripts cannot reference "${pattern}" — the installer container must not reach the container runtime or host namespaces.`;
|
|
}
|
|
}
|
|
const toolMatch = lower.match(INSTALL_SCRIPT_BLOCKED_RUNTIME_RE);
|
|
if (toolMatch) {
|
|
return `Install scripts cannot reference "${toolMatch[0]}". The installer cannot manage containers — configure the image, ports, volumes and env via the template instead.`;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function sanitizeDockerInstallPayload(install) {
|
|
if (!install || typeof install !== "object" || Array.isArray(install)) return null;
|
|
|
|
const script = cleanScript(install.script || install.installScript || install.install_script);
|
|
if (!script) return null;
|
|
|
|
const image = cleanString(install.image || install.container) || "ghcr.io/pterodactyl/installers:debian";
|
|
const mountPath = cleanAbsoluteContainerPath(
|
|
install.mountPath || install.containerPath || install.container_path || install.serverPath,
|
|
"/mnt/server"
|
|
);
|
|
const runtimePath = cleanAbsoluteContainerPath(
|
|
install.runtimePath || install.runtime_path || install.homePath || install.home_path,
|
|
"/home/container"
|
|
);
|
|
|
|
const minimumStorageRaw = toFiniteNumber(install.minimumStorageMb || install.minimum_storage_mb);
|
|
const minimumStorageMb = minimumStorageRaw && minimumStorageRaw > 0
|
|
? Math.max(1, Math.min(Math.trunc(minimumStorageRaw), 1024 * 1024))
|
|
: 0;
|
|
const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds);
|
|
const timeoutSeconds = timeoutRaw && timeoutRaw > 0
|
|
? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200))
|
|
: 1800;
|
|
|
|
const payload = {
|
|
image,
|
|
script,
|
|
mountPath,
|
|
runtimePath,
|
|
timeoutSeconds,
|
|
};
|
|
if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb;
|
|
if (install.allowEmpty === true || install.allowEmptyResult === true) {
|
|
payload.allowEmpty = true;
|
|
}
|
|
|
|
const env = sanitizeEnvPayload(install.env);
|
|
if (env) payload.env = env;
|
|
|
|
return payload;
|
|
}
|
|
|
|
function sanitizeDockerTemplatePayload(docker) {
|
|
if (!docker || typeof docker !== "object") return null;
|
|
|
|
const image = cleanString(docker.image);
|
|
if (!image) return null;
|
|
|
|
const payload = {
|
|
image,
|
|
};
|
|
|
|
const tag = cleanString(docker.tag) || "latest";
|
|
if (tag) payload.tag = tag;
|
|
|
|
const command = cleanString(docker.command);
|
|
if (command) payload.command = command;
|
|
|
|
const workdir = cleanString(docker.workdir || docker.workingDir || docker.working_dir);
|
|
if (workdir) payload.workdir = workdir;
|
|
|
|
const restart = cleanString(docker.restart);
|
|
if (restart) payload.restart = restart;
|
|
|
|
const restartPolicy = cleanString(docker.restartPolicy);
|
|
if (restartPolicy) payload.restartPolicy = restartPolicy;
|
|
|
|
// runAsRoot is intentionally NOT accepted here: templates cannot request a
|
|
// root container. The node agent denies root unless the operator explicitly
|
|
// sets ADPANEL_ALLOW_TEMPLATE_ROOT=1.
|
|
|
|
const ports = Array.isArray(docker.ports)
|
|
? docker.ports
|
|
.map((entry) => {
|
|
const port = toFiniteNumber(entry);
|
|
return Number.isInteger(port) && port > 0 ? port : null;
|
|
})
|
|
.filter((entry) => entry != null)
|
|
: [];
|
|
if (ports.length) payload.ports = ports;
|
|
|
|
const portProtocols = sanitizePortProtocolPayload(
|
|
docker.portProtocols || docker.port_protocols || docker.protocols,
|
|
ports
|
|
);
|
|
if (portProtocols) payload.portProtocols = portProtocols;
|
|
|
|
const volumes = sanitizeTemplateVolumeList(docker.volumes);
|
|
if (volumes.length) payload.volumes = volumes;
|
|
|
|
const env = sanitizeEnvPayload(docker.env);
|
|
if (env && Object.keys(env).length) payload.env = env;
|
|
|
|
const adpanelStartup = cleanScript(
|
|
docker.adpanelStartup ||
|
|
docker.adpanel_startup ||
|
|
docker.pterodactylStartup ||
|
|
docker.pterodactyl_startup ||
|
|
docker.startup,
|
|
32768
|
|
);
|
|
if (adpanelStartup) {
|
|
const startupError = validateADPanelStartupScriptInput(adpanelStartup);
|
|
if (startupError) {
|
|
console.warn(`[templates] dropping unsafe managed startup: ${startupError}`);
|
|
} else {
|
|
payload.adpanelStartup = adpanelStartup;
|
|
}
|
|
}
|
|
|
|
const startupDisplay = cleanScript(
|
|
docker.startupDisplay ||
|
|
docker.startup_display ||
|
|
docker.startupPreview ||
|
|
docker.startup_preview ||
|
|
docker.imageDefaultStartup ||
|
|
docker.image_default_startup,
|
|
32768
|
|
);
|
|
if (startupDisplay) payload.startupDisplay = startupDisplay;
|
|
|
|
// Normalization is the silent-drop layer (stored templates self-heal, the
|
|
// dashboard assistant never forwards what the boundary would refuse); the
|
|
// fail-closed 400 lives in constructTemplateDefinition and the node's create
|
|
// endpoint. A script the boundary would reject never reaches a sink from
|
|
// here.
|
|
const install = sanitizeDockerInstallPayload(docker.install || docker.installation);
|
|
if (install) {
|
|
const installScriptError = validateTemplateInstallScriptInput(install.script);
|
|
if (installScriptError) {
|
|
console.warn(`[templates] dropping unsafe install script: ${installScriptError}`);
|
|
} else {
|
|
payload.install = install;
|
|
}
|
|
}
|
|
|
|
const consolePayload = sanitizeConsolePayload(docker.console);
|
|
if (consolePayload) payload.console = consolePayload;
|
|
|
|
return payload;
|
|
}
|
|
|
|
module.exports = {
|
|
sanitizeDockerTemplatePayload,
|
|
sanitizeDockerInstallPayload,
|
|
sanitizeEnvPayload,
|
|
validateTemplateEnvPayload,
|
|
sanitizePortProtocolPayload,
|
|
sanitizeConsolePayload,
|
|
sanitizeVolumeSpec,
|
|
sanitizeTemplateVolumeList,
|
|
validateTemplateVolumeListPayload,
|
|
validateADPanelStartupScriptInput,
|
|
validateTemplateInstallScriptInput,
|
|
};
|