Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -1,5 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
const { sanitizeVolumeSpec, sanitizeTemplateVolumeList, validateTemplateVolumeListPayload } = require("../public/js/template-volumes");
|
||||
|
||||
const POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
||||
|
||||
function cleanString(value) {
|
||||
@@ -63,18 +65,219 @@ function cleanAbsoluteContainerPath(value, fallback = "") {
|
||||
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) continue;
|
||||
out[envKey] = String(value ?? "");
|
||||
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;
|
||||
|
||||
@@ -143,9 +346,9 @@ function sanitizeDockerTemplatePayload(docker) {
|
||||
const restartPolicy = cleanString(docker.restartPolicy);
|
||||
if (restartPolicy) payload.restartPolicy = restartPolicy;
|
||||
|
||||
if (docker.runAsRoot === true || docker.run_as_root === true) {
|
||||
payload.runAsRoot = true;
|
||||
}
|
||||
// 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
|
||||
@@ -163,9 +366,7 @@ function sanitizeDockerTemplatePayload(docker) {
|
||||
);
|
||||
if (portProtocols) payload.portProtocols = portProtocols;
|
||||
|
||||
const volumes = Array.isArray(docker.volumes)
|
||||
? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean)
|
||||
: [];
|
||||
const volumes = sanitizeTemplateVolumeList(docker.volumes);
|
||||
if (volumes.length) payload.volumes = volumes;
|
||||
|
||||
const env = sanitizeEnvPayload(docker.env);
|
||||
@@ -179,7 +380,14 @@ function sanitizeDockerTemplatePayload(docker) {
|
||||
docker.startup,
|
||||
32768
|
||||
);
|
||||
if (adpanelStartup) payload.adpanelStartup = adpanelStartup;
|
||||
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 ||
|
||||
@@ -192,13 +400,24 @@ function sanitizeDockerTemplatePayload(docker) {
|
||||
);
|
||||
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) payload.install = install;
|
||||
|
||||
if (docker.console !== undefined) {
|
||||
payload.console = docker.console;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -206,5 +425,12 @@ module.exports = {
|
||||
sanitizeDockerTemplatePayload,
|
||||
sanitizeDockerInstallPayload,
|
||||
sanitizeEnvPayload,
|
||||
validateTemplateEnvPayload,
|
||||
sanitizePortProtocolPayload,
|
||||
sanitizeConsolePayload,
|
||||
sanitizeVolumeSpec,
|
||||
sanitizeTemplateVolumeList,
|
||||
validateTemplateVolumeListPayload,
|
||||
validateADPanelStartupScriptInput,
|
||||
validateTemplateInstallScriptInput,
|
||||
};
|
||||
Reference in new issue
Block a user