From c1562dfcf02827e434847a54452dcd6c2bdc6f3a Mon Sep 17 00:00:00 2001 From: karutoil Date: Mon, 16 Nov 2026 08:52:22 -0500 Subject: [PATCH] fix(security): stop giving the panel the container engine socket by default Closes the S1-7 audit finding, also raised as issue #352. A writable /var/run/docker.sock is equivalent to host root: whoever can talk to it can run a privileged container with the host filesystem mounted. The backend serves the admin API, loads plugins and renders operator data, so any code-execution primitive there escalated from a panel compromise to a host compromise. The mount was unconditional even though the only feature that needs it, in-panel self-update, is disabled by default. The default deployment no longer mounts the socket. Operators who want the Update button opt in with docker-compose.auto-update.yml, which mounts the socket, enables the updater and applies the hardening the audit asked for (no-new-privileges, cap_drop ALL with only CHOWN/SETUID/ SETGID/DAC_OVERRIDE added back). Updating from the host keeps working and needs no privilege change. Both consumers now report the deployment posture instead of a confusing daemon error: - auto-updater refuses with an explanation when the socket is absent and points at the override, rather than blaming the CLI or compose file. - panel log export distinguishes "socket not mounted, intentional" from "no container runtime found" in its existing unavailable fallback. Also tightens the entrypoint: the traversal walk no longer starts from / or /root, so a bad compose path cannot open the filesystem root, and it only ever grants o+x, never read or list. The socket path is overridable via DOCKER_SOCKET_PATH, registered in the env registry. Tests fail without the service changes: the updater gate and the log export posture. Verified the merge with podman-compose config (mount, cap_drop and no-new-privileges present; base file has zero socket occurrences) and exercised the entrypoint block in both states against a real unix socket. --- catalyst-backend/docker-entrypoint.sh | 32 ++++++-- .../src/__tests__/auto-updater.test.ts | 18 +++++ .../src/__tests__/panel-logs-socket.test.ts | 77 +++++++++++++++++++ catalyst-backend/src/lib/env-registry.ts | 7 ++ catalyst-backend/src/services/auto-updater.ts | 39 ++++++++++ .../src/services/diagnostics/panel-logs.ts | 14 +++- catalyst-docker/.env.example | 9 +++ .../docker-compose.auto-update.yml | 67 ++++++++++++++++ catalyst-docker/docker-compose.yml | 13 +++- install.sh | 2 +- 10 files changed, 267 insertions(+), 11 deletions(-) create mode 100644 catalyst-backend/src/__tests__/panel-logs-socket.test.ts create mode 100644 catalyst-docker/docker-compose.auto-update.yml diff --git a/catalyst-backend/docker-entrypoint.sh b/catalyst-backend/docker-entrypoint.sh index 8c48d2e71..04485e3e4 100755 --- a/catalyst-backend/docker-entrypoint.sh +++ b/catalyst-backend/docker-entrypoint.sh @@ -7,9 +7,16 @@ set -e echo "==> Catalyst Backend starting..." # Join the docker.sock group so the panel Update button can talk to the host -# daemon after we drop root. No-op when the socket is not mounted. -if [ "$(id -u)" = "0" ] && [ -S /var/run/docker.sock ]; then - sock_gid="$(stat -c '%g' /var/run/docker.sock 2>/dev/null || true)" +# daemon after we drop root. +# +# SECURITY (audit S1-7): the socket is not mounted by default, so this whole +# block is normally a no-op. It only runs when the operator opted in via +# docker-compose.auto-update.yml (or an equivalent mount). The predecessor here +# widened traversal with `chmod o+x` on every ancestor of the compose dir; the +# walk now refuses to start from / or /root so a bad compose path cannot open +# the filesystem root. +if [ "$(id -u)" = "0" ] && [ -S "${DOCKER_SOCKET_PATH:-/var/run/docker.sock}" ]; then + sock_gid="$(stat -c '%g' "${DOCKER_SOCKET_PATH:-/var/run/docker.sock}" 2>/dev/null || true)" if [ -n "$sock_gid" ]; then if ! getent group "$sock_gid" >/dev/null 2>&1; then addgroup -g "$sock_gid" docker >/dev/null @@ -18,15 +25,24 @@ if [ "$(id -u)" = "0" ] && [ -S /var/run/docker.sock ]; then addgroup catalyst "$sock_group" >/dev/null 2>&1 || true fi # Image /root is 0700. A same-path bind of /root/catalyst-docker is - # unreachable unless parents are traversable by user catalyst. + # unreachable unless parents are traversable by user catalyst. Walk from the + # container user's data roots only, so we do not open / or /root. compose_path="${AUTO_UPDATE_DOCKER_COMPOSE_PATH:-}" if [ -n "$compose_path" ]; then dir=$(dirname "$compose_path") - while [ "$dir" != "/" ]; do - chmod o+x "$dir" 2>/dev/null || true - dir=$(dirname "$dir") - done + case "$dir" in + /|/root|/root/*) ;; + *) + while [ "$dir" != "/" ] && [ "$dir" != "." ]; do + # Only traverse; never grant read or list on the contents. + chmod o+x "$dir" 2>/dev/null || true + dir=$(dirname "$dir") + done + ;; + esac fi +else + echo "==> Container engine socket not mounted; in-panel self-update is disabled (default)." fi # Ensure data directories exist (volumes may be mounted over the Dockerfile-created dirs) diff --git a/catalyst-backend/src/__tests__/auto-updater.test.ts b/catalyst-backend/src/__tests__/auto-updater.test.ts index bcdefd430..e5053e34c 100644 --- a/catalyst-backend/src/__tests__/auto-updater.test.ts +++ b/catalyst-backend/src/__tests__/auto-updater.test.ts @@ -99,12 +99,30 @@ describe("performUpdate", () => { process.env.AUTO_UPDATE_FORCE_DOCKER = "true"; delete process.env.AUTO_UPDATE_DOCKER_COMPOSE_PATH; process.env.DOCKER_BIN = "/tmp/catalyst-no-such-docker"; + // Stand in a socket so this exercises the CLI-failure path rather than + // the no-socket gate covered below. + process.env.DOCKER_SOCKET_PATH = "/tmp/catalyst-fake.sock"; + fs.writeFileSync(process.env.DOCKER_SOCKET_PATH, ""); const result = await performUpdate(); + fs.rmSync(process.env.DOCKER_SOCKET_PATH, { force: true }); + delete process.env.DOCKER_SOCKET_PATH; expect(result.success).toBe(false); expect(result.message).toMatch( /Could not find docker-compose.yml|docker CLI is not available|not found/, ); }); + + it("refuses to update when the engine socket is not mounted (audit S1-7)", async () => { + process.env.AUTO_UPDATE_FORCE_DOCKER = "true"; + process.env.DOCKER_SOCKET_PATH = "/nonexistent/catalyst/docker.sock"; + const result = await performUpdate(); + delete process.env.DOCKER_SOCKET_PATH; + expect(result.success).toBe(false); + // The message explains the deployment posture, not a docker failure. + expect(result.message).toMatch(/socket is not mounted/i); + expect(result.message).toMatch(/default/i); + expect(getUpdateState().state).toBe("failed"); + }); }); describe("update state machine", () => { diff --git a/catalyst-backend/src/__tests__/panel-logs-socket.test.ts b/catalyst-backend/src/__tests__/panel-logs-socket.test.ts new file mode 100644 index 000000000..90b220caf --- /dev/null +++ b/catalyst-backend/src/__tests__/panel-logs-socket.test.ts @@ -0,0 +1,77 @@ +/** + * Panel log export vs. the container engine socket. + * + * Audit S1-7: the backend no longer gets /var/run/docker.sock by default. The + * export must therefore (a) still work when the socket IS mounted, and (b) say + * something useful and non-alarming when it is not, instead of surfacing a raw + * `docker: Cannot connect to the Docker daemon` string as if the install were + * broken. + */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + collectPanelLogs, + type CommandRunner, +} from "../services/diagnostics/panel-logs"; + +const WINDOW = { + since: new Date("2026-11-15T00:00:00Z"), + until: new Date("2026-11-15T01:00:00Z"), +}; + +/** A socket path that exists, so the "socket mounted" branch is exercised. */ +function tempSocket(): { dir: string; socket: string } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "catalyst-sock-")); + const socket = path.join(dir, "docker.sock"); + fs.writeFileSync(socket, ""); + return { dir, socket }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("collectPanelLogs without a container engine socket (default deployment)", () => { + it("reports the deployment posture, not a daemon connection error", async () => { + const runner = vi.fn(async () => ({ + stdout: "", + stderr: "Cannot connect to the Docker daemon at unix:///var/run/docker.sock", + exitCode: 1, + truncated: false, + })); + + const result = await collectPanelLogs({ + ...WINDOW, + runner, + env: { DOCKER_SOCKET_PATH: "/nonexistent/catalyst/docker.sock" }, + }); + + expect(result.source).toBe("unavailable"); + expect(result.lines).toBe(0); + expect(result.warning).toMatch(/socket is not mounted/i); + expect(result.warning).toMatch(/intentional/i); + }); + + it("still attempts the read so an opt-in deployment keeps working", async () => { + const { dir, socket } = tempSocket(); + const runner = vi.fn(async () => ({ + stdout: "2026-11-15T00:01:00Z panel ready\n", + stderr: "", + exitCode: 0, + truncated: false, + })); + + const result = await collectPanelLogs({ + ...WINDOW, + runner, + env: { DOCKER_SOCKET_PATH: socket }, + }); + + expect(runner).toHaveBeenCalled(); + expect(result.source).toBe("docker"); + expect(result.content).toContain("panel ready"); + fs.rmSync(dir, { recursive: true, force: true }); + }); +}); diff --git a/catalyst-backend/src/lib/env-registry.ts b/catalyst-backend/src/lib/env-registry.ts index b99ac89a0..45491940d 100644 --- a/catalyst-backend/src/lib/env-registry.ts +++ b/catalyst-backend/src/lib/env-registry.ts @@ -544,6 +544,13 @@ export const ENV_VAR_REGISTRY: readonly EnvVarSpec[] = [ default: "false", description: "Force the Docker update path even when it cannot be detected.", }), + base("DOCKER_SOCKET_PATH", "updates", "path", { + // Not mounted by default (security audit S1-7). When absent, in-panel + // self-update and the panel log export report the deployment posture + // instead of failing with a daemon connection error. + default: "/var/run/docker.sock", + description: "Container engine socket used by the panel self-updater and log export.", + }), // ── Developer / aggressive ──────────────────────────────────────────── base("DISABLE_RATE_LIMIT", "developer", "boolean", { diff --git a/catalyst-backend/src/services/auto-updater.ts b/catalyst-backend/src/services/auto-updater.ts index 6e55b4362..9a975375c 100644 --- a/catalyst-backend/src/services/auto-updater.ts +++ b/catalyst-backend/src/services/auto-updater.ts @@ -379,6 +379,35 @@ export function formatDockerUpdateError(error: unknown): string { return error instanceof Error ? error.message : "Docker update failed"; } +/** + * Default socket the container engine listens on inside the backend container. + * Kept as a constant so tests can point it at a temp path instead of a real daemon. + */ +export function containerSocketPath(): string { + return process.env.DOCKER_SOCKET_PATH || "/var/run/docker.sock"; +} + +/** + * Whether the backend can actually drive its own container engine. + * + * The socket is NOT mounted by default any more (security-audit S1-7): holding + * it hands the web-facing backend host-root-equivalent access, so the default + * deployment does not get it. When the socket is absent we say so explicitly + * instead of letting `docker` fail with a confusing connection error — the fix + * is an operator action (mount the socket), not a bug in the update itself. + */ +export function composeUpdateUnavailableReason( + socketPath: string = containerSocketPath(), +): string | null { + if (fs.existsSync(socketPath)) return null; + return ( + `The container engine socket is not mounted in the backend container (${socketPath}). ` + + "Panel self-update is disabled in this deployment, which is the default: it keeps the " + + "backend out of host-level control. Start the stack with the auto-update override to " + + "enable in-panel updates, or run the deploy scripts on the host to update." + ); +} + function dockerBin(): string { return process.env.DOCKER_BIN || "docker"; } @@ -527,6 +556,16 @@ export async function performUpdate(logger?: { } if (inDocker) { + // No socket means no way to drive the engine. Report the deployment + // posture rather than a docker connection error (security-audit S1-7). + const unavailable = composeUpdateUnavailableReason(); + if (unavailable) { + logger?.warn?.(unavailable); + setUpdateState("failed", unavailable); + appendUpdateLog(`Update unavailable: ${unavailable}`); + return { success: false, message: unavailable }; + } + const context = resolveComposeContext(); if (!context) { const message = diff --git a/catalyst-backend/src/services/diagnostics/panel-logs.ts b/catalyst-backend/src/services/diagnostics/panel-logs.ts index 5ded696e2..5c496edb5 100644 --- a/catalyst-backend/src/services/diagnostics/panel-logs.ts +++ b/catalyst-backend/src/services/diagnostics/panel-logs.ts @@ -1,4 +1,5 @@ import { spawn } from "node:child_process"; +import fs from "node:fs"; import { redactEnvVar, redactLogText, type RedactionMode } from "../../lib/secret-redaction.js"; /** @@ -139,6 +140,12 @@ export async function collectPanelLogs(options: { ? [env.DIAGNOSTICS_CONTAINER_RUNTIME === "podman" ? "podman" : "docker"] : ["docker", "podman"]; + // The socket is not mounted by default (security-audit S1-7), so `docker logs` + // fails with a connection error rather than a spawn error. That is a + // deployment posture, not a missing CLI — report it as such. + const socketPath = env.DOCKER_SOCKET_PATH || "/var/run/docker.sock"; + const noEngineAccess = !fs.existsSync(socketPath); + let lastError = ""; for (const runtime of runtimes) { for (const withUntil of [true, false]) { @@ -187,7 +194,12 @@ export async function collectPanelLogs(options: { lines: 0, source: "unavailable", truncated: false, - warning: `Panel logs are unavailable in this deployment (${lastError || "no container runtime found"}).`, + warning: noEngineAccess + ? `Panel logs are unavailable in this deployment because the container engine socket ` + + `is not mounted in the backend container (${socketPath}). This is the default and ` + + `intentional: the panel does not get host-level control unless you opt in. ` + + `Use the log export from the host, or start the stack with the auto-update override.` + : `Panel logs are unavailable in this deployment (${lastError || "no container runtime found"}).`, }; } diff --git a/catalyst-docker/.env.example b/catalyst-docker/.env.example index a9da17dc4..566deb1ed 100644 --- a/catalyst-docker/.env.example +++ b/catalyst-docker/.env.example @@ -184,6 +184,15 @@ BACKUP_CREDENTIALS_ENCRYPTION_KEY=CHANGE_ME_GENERATE_WITH_OPENSSL_RAND_BASE64_32 # TRAEFIK_DASHBOARD_PORT=127.0.0.1:8080 # --- Auto Updater (optional) ------------------------------------------------ +# In-panel updates need the container engine socket, which is NOT mounted by +# default: it is equivalent to host root, so the backend only gets it when you +# opt in with docker-compose.auto-update.yml. Without that overlay the Update +# button reports the deployment posture instead of updating. +# podman compose -f docker-compose.yml -f docker-compose.auto-update.yml up -d +# To update without the socket, run from the host: +# cd catalyst-docker && podman compose pull && podman compose up -d +# Host path of the engine socket, if it is not the rootful default. +# DOCKER_SOCKET_PATH=/var/run/docker.sock # Set to true to enable automatic update checking AUTO_UPDATE_ENABLED=false # Check interval in milliseconds (default: 1 hour) diff --git a/catalyst-docker/docker-compose.auto-update.yml b/catalyst-docker/docker-compose.auto-update.yml new file mode 100644 index 000000000..d81dbbf46 --- /dev/null +++ b/catalyst-docker/docker-compose.auto-update.yml @@ -0,0 +1,67 @@ +# ============================================================================= +# Catalyst — Panel self-update overlay (OPT-IN, NOT the default) +# +# Usage: +# podman compose -f docker-compose.yml -f docker-compose.auto-update.yml up -d +# +# You almost certainly do not need this. It exists for operators who want the +# Update button in Admin > System to pull new images and recreate the stack +# from inside the panel, and who accept the trade-off below. +# +# WHY THIS IS OPT-IN (security audit S1-7, MEDIUM / CONFIRMED) +# A mounted /var/run/docker.sock is equivalent to host root. The daemon does +# not distinguish "may run a container" from "may run a privileged container +# with / mounted". Whoever can talk to the socket can read the host filesystem, +# modify any container, and start a new one with the host's privileges. +# +# The backend is the most exposed component in Catalyst: it serves the admin +# API, loads plugins, and renders operator-supplied data. Putting the socket +# in it means any code-execution primitive there escalates from "controls the +# panel" to "controls the host and every tenant container on it". Since the +# Update button is a convenience and the panel is otherwise fully functional +# without it, the default deployment does not get the socket at all. +# +# This overlay is therefore a deliberate, documented opt-in, and it also +# applies the container hardening the audit asked for, so the opt-in path is +# not a step down from the default one. +# +# ALTERNATIVE (no socket, no privileges) +# Update from the host instead: +# cd catalyst-docker && podman compose pull && podman compose up -d +# or re-run the deploy scripts. The panel does not need to orchestrate itself. +# +# NOTE ON PODMAN: use the podman-docker compatibility socket so the backend's +# docker-compatible client can reach it. Point DOCKER_SOCKET_PATH at the real +# podman socket if you mount it somewhere else. +# ============================================================================= + +services: + backend: + volumes: + # Writable on purpose: `compose pull` + `compose up -d` are daemon WRITES. + # A read-only mount cannot update anything, so :ro here would only produce + # confusing failures. The hardening below is what bounds the risk instead. + # + # Only the HOST side is variable. podman-compose 1.3 cannot parse a + # short-syntax mount with a ${VAR:-default} on both sides ("could not + # parse mount"), so the container side stays the real path the backend + # already expects. Point DOCKER_SOCKET_PATH at the host socket if it is + # not the rootful default. + - ${DOCKER_SOCKET_PATH:-/var/run/docker.sock}:/var/run/docker.sock + environment: + # The gate the backend checks before it tries to drive the engine. + DOCKER_SOCKET_PATH: /var/run/docker.sock + AUTO_UPDATE_ENABLED: "true" + # Hardening requested by audit S1-7. The entrypoint still needs to run as + # root briefly to join the socket's group and chown data dirs, then it + # su-execs to `catalyst`; these flags stop that root phase from being + # escalated back into by a compromised process. + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + cap_add: + - CHOWN + - SETUID + - SETGID + - DAC_OVERRIDE diff --git a/catalyst-docker/docker-compose.yml b/catalyst-docker/docker-compose.yml index ab6682de4..6a3413d9c 100644 --- a/catalyst-docker/docker-compose.yml +++ b/catalyst-docker/docker-compose.yml @@ -255,7 +255,18 @@ services: - catalyst-server-data:/var/lib/catalyst/servers - catalyst-backup-data:/var/lib/catalyst/backups - catalyst-plugin-data:/var/lib/catalyst/plugins - - /var/run/docker.sock:/var/run/docker.sock + # SECURITY (audit S1-7): /var/run/docker.sock is deliberately NOT mounted + # here. The socket is equivalent to host root, so any code-execution + # primitive in this web-facing backend (a plugin, an admin API bug, an + # RCE in a dependency) would become full control of the host daemon and + # every container on it. The default deployment does not need it: panel + # self-update is off unless enabled, and the log export degrades to a + # clear "unavailable" warning. + # + # To enable in-panel self-update, add the opt-in overlay, which mounts + # the socket and hardens the container to compensate: + # {podman|docker} compose -f docker-compose.yml -f docker-compose.auto-update.yml up -d + # Everything else about the panel works unchanged without it. - ${CATALYST_COMPOSE_DIR:-/opt/catalyst-docker}:${CATALYST_COMPOSE_DIR:-/opt/catalyst-docker}:ro healthcheck: # $$ defers expansion to the container shell, so the probe follows the diff --git a/install.sh b/install.sh index 44b533ab6..df5787a27 100644 --- a/install.sh +++ b/install.sh @@ -1413,7 +1413,7 @@ phase_configure() { if [[ -f "${COMPOSE_DIR}/docker-compose.yml" ]]; then chmod 644 "${COMPOSE_DIR}/docker-compose.yml" 2>/dev/null || true fi - for cfg in docker-compose.caddy.yml docker-compose.traefik.yml docker-compose.test.yml; do + for cfg in docker-compose.caddy.yml docker-compose.traefik.yml docker-compose.test.yml docker-compose.auto-update.yml; do if [[ -f "${COMPOSE_DIR}/${cfg}" ]]; then chmod 644 "${COMPOSE_DIR}/${cfg}" 2>/dev/null || true fi