Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Own server: the home's secrets in a read-only file, and CAP_SYS_ADMIN only for the hidepid remount

milind-soni0d551ad9412f
diff --git a/connector/src/docker.ts b/connector/src/docker.ts
index 407e1bd79b..a382881b39 100644
--- a/connector/src/docker.ts
+++ b/connector/src/docker.ts
@@ -46,10 +46,13 @@ export interface VolumeInfo {
Name: string;
Labels: Record<string, string> | null;
CreatedAt?: string;
+ /** Where the volume's files are on the host (the local driver's `_data` folder). */
+ Mountpoint?: string;
}
+/** A named volume, or (`bind`) a folder on the host by its absolute path. */
export interface Mount {
- Type: "volume";
+ Type: "volume" | "bind";
Source: string;
Target: string;
ReadOnly?: boolean;
diff --git a/connector/src/home.ts b/connector/src/home.ts
index 1c61ebe1ef..c3355ca435 100644
--- a/connector/src/home.ts
+++ b/connector/src/home.ts
@@ -9,12 +9,14 @@ import { publicHost, summarizeHealth, type HealthRead } from "./home-health.ts";
import { errorText, registerSecret, type Log } from "./log.ts";
import { EXPORT_PATH, UPDATE_HEALTH_WINDOW_MS, type CopyInfo, type HomeHealth, type HomeReport, type HomeState, type JobError, type JobReply, type JobResults } from "./protocol.ts";
import {
- APPARMOR_PROFILE, BACKUPS_KEPT, HOME_CAPABILITIES, HOME_OOM_SCORE_ADJ, HOME_PORT, HOME_SHM_BYTES, HOME_STOP_TIMEOUT_S, LABELS, LEASE_FIXED_VERSION, NAMES,
+ APPARMOR_PROFILE, BACKUPS_KEPT, HARDENED_LAUNCHER_VERSION, HIDEPID_CAPABILITIES, HOME_CAPABILITIES, HOME_OOM_SCORE_ADJ, HOME_PORT, HOME_SECRET_ENV, HOME_SECRETS_DIR,
+ HOME_SECRETS_TARGET, HOME_SHM_BYTES, HOME_STOP_TIMEOUT_S, LABELS, LEASE_FIXED_VERSION, NAMES,
} from "./settings.ts";
import type { HomeRecord, Operation, StateStore } from "./state.ts";
import type { Transfer } from "./transfer.ts";
const DATA: Mount = { Type: "volume", Source: NAMES.dataVolume, Target: "/data" };
+const VERSION_LABEL = "org.opencontainers.image.version";
/** What a copy of /data needs as root: read every file, and write it back with its owner, mode and times. */
const COPY_CAPS = ["CHOWN", "DAC_OVERRIDE", "DAC_READ_SEARCH", "FOWNER", "FSETID"];
const READ_CAPS = ["DAC_READ_SEARCH"];
@@ -25,12 +27,30 @@ export function envDigest(env: Record<string, string>): string {
return createHash("sha256").update(JSON.stringify(Object.entries(env).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))).digest("hex");
}
-/** The home container, with exactly the settings its bot box needs on a stock Docker host, and nothing more. */
-export function homeSpec(image: string, env: Record<string, string>, seccomp: string): ContainerSpec {
+/** What a home image's launcher does, by its version: an older image gets exactly the settings it always had. */
+export interface Launcher {
+ /** Reads its secrets from HOME_SECRETS_TARGET, so they stay out of the container's environment. */
+ secretsFile: boolean;
+ /** Drops CAP_SYS_ADMIN and CAP_SETPCAP once it has remounted /proc with hidepid, so it may be given them for that. */
+ dropsCapabilities: boolean;
+}
+
+export function launcherOf(version: readonly number[] | null): Launcher {
+ const hardened = version !== null && !versionBelow(version, HARDENED_LAUNCHER_VERSION);
+ return { secretsFile: hardened, dropsCapabilities: hardened };
+}
+
+/**
+ * The home container, with exactly the settings its bot box needs on a stock Docker host, and nothing more. With
+ * `secretsDir` (the host folder holding the secrets file) the secrets are mounted read-only instead of set in the
+ * environment.
+ */
+export function homeSpec(image: string, env: Record<string, string>, seccomp: string, options: { secretsDir?: string | null; dropsCapabilities?: boolean } = {}): ContainerSpec {
const environment = { ...env, OMB_CLOUD_IMAGE: image };
+ const secret = new Set<string>(options.secretsDir ? HOME_SECRET_ENV : []);
return {
Image: image,
- Env: Object.entries(environment).map(([name, value]) => `${name}=${value}`),
+ Env: Object.entries(environment).filter(([name]) => !secret.has(name)).map(([name, value]) => `${name}=${value}`),
Labels: { [LABELS.role]: "home", [LABELS.image]: image, [LABELS.env]: envDigest(environment) },
ExposedPorts: { [`${HOME_PORT}/tcp`]: {} },
StopTimeout: HOME_STOP_TIMEOUT_S,
@@ -38,13 +58,13 @@ export function homeSpec(image: string, env: Record<string, string>, seccomp: st
Init: true,
ShmSize: HOME_SHM_BYTES,
PortBindings: { [`${HOME_PORT}/tcp`]: [{ HostIp: "127.0.0.1", HostPort: String(HOME_PORT) }] },
- Mounts: [DATA],
+ Mounts: options.secretsDir ? [DATA, { Type: "bind", Source: options.secretsDir, Target: HOME_SECRETS_TARGET, ReadOnly: true }] : [DATA],
SecurityOpt: [`apparmor=${APPARMOR_PROFILE}`, `seccomp=${seccomp}`, "no-new-privileges=true"],
// Docker's `--security-opt systempaths=unconfined`: no masked or read-only /proc paths (the AppArmor profile denies them).
MaskedPaths: [],
ReadonlyPaths: [],
CapDrop: ["ALL"],
- CapAdd: [...HOME_CAPABILITIES],
+ CapAdd: [...HOME_CAPABILITIES, ...(options.dropsCapabilities ? HIDEPID_CAPABILITIES : [])],
OomScoreAdj: HOME_OOM_SCORE_ADJ,
RestartPolicy: { Name: "no" },
LogConfig: { Type: "json-file", Config: { "max-size": "20m", "max-file": "5" } },
@@ -133,7 +153,10 @@ export class Home {
this.startWindowMs = options.startWindowMs ?? UPDATE_HEALTH_WINDOW_MS;
this.pollMs = options.pollMs ?? 2_000;
const env = this.state.homeEnv();
- if (env) registerHomeSecrets(env);
+ if (env) {
+ registerHomeSecrets(env);
+ this.state.saveHomeSecrets(env);
+ }
}
/** True while a job or a restart holds the home. */
@@ -500,8 +523,18 @@ export class Home {
}
private async createContainer(image: string, env: Record<string, string>): Promise<void> {
+ const launcher = launcherOf(imageVersion((await this.docker.imageInspect(image))?.Config?.Labels?.[VERSION_LABEL]));
+ const secretsDir = launcher.secretsFile ? await this.hostSecretsDir(env) : null;
await this.docker.removeContainer(NAMES.home);
- await this.docker.createContainer(NAMES.home, homeSpec(image, env, this.options.seccomp()));
+ await this.docker.createContainer(NAMES.home, homeSpec(image, env, this.options.seccomp(), { secretsDir, dropsCapabilities: launcher.dropsCapabilities }));
+ }
+
+ /** The secrets folder in the state volume, as the host sees it: Docker mounts it into the home by that path. */
+ private async hostSecretsDir(env: Record<string, string>): Promise<string> {
+ this.state.saveHomeSecrets(env);
+ const volume = await this.docker.volumeInspect(NAMES.stateVolume);
+ if (!volume?.Mountpoint) throw new JobFailure("docker", `The connector's state volume ${NAMES.stateVolume} is missing. Run the install command again to repair it.`);
+ return `${volume.Mountpoint}/${HOME_SECRETS_DIR}`;
}
private async startHome(image: string): Promise<void> {
@@ -527,7 +560,7 @@ export class Home {
* while no container at all runs on the volume, so a live server's lease is never touched.
*/
private async clearStaleLease(image: string): Promise<void> {
- const version = imageVersion((await this.docker.imageInspect(image))?.Config?.Labels?.["org.opencontainers.image.version"]);
+ const version = imageVersion((await this.docker.imageInspect(image))?.Config?.Labels?.[VERSION_LABEL]);
if (version && !versionBelow(version, LEASE_FIXED_VERSION)) return;
if ((await this.docker.containersUsing(NAMES.dataVolume)).some((container) => container.State === "running" || container.State === "paused")) return;
const cleared = await this.helper(image, [DATA], [
diff --git a/connector/src/protocol.ts b/connector/src/protocol.ts
index 10be62e43b..c1dd66e24c 100644
--- a/connector/src/protocol.ts
+++ b/connector/src/protocol.ts
@@ -207,7 +207,7 @@ export const REQUIRED_HOME_ENV = ["OMB_CLOUD_ROLE", "OMB_CLOUD_MACHINE_ID", "OMB
/** Settings the image owns, or that make sense only on Fly; a home on an own server never takes them from outside. */
export const REFUSED_HOME_ENV = new Set([
"OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_EDGE_CONFIG", "OMB_CLOUD_HARDEN",
- "OMB_DATA_DIR", "OMB_STATIC_DIR", "OMB_DUCKDB_DIR", "OMB_PORT", "OMB_WEBHOOK_PORT", "OMB_CLOUD_SECRETS_FD",
+ "OMB_DATA_DIR", "OMB_STATIC_DIR", "OMB_DUCKDB_DIR", "OMB_PORT", "OMB_WEBHOOK_PORT", "OMB_CLOUD_SECRETS_FD", "OMB_CLOUD_CAPS_DROPPED",
]);
export type Checked<T> = { ok: true; value: T } | { ok: false; message: string };
diff --git a/connector/src/settings.ts b/connector/src/settings.ts
index 013ae5bde5..8f74ec539a 100644
--- a/connector/src/settings.ts
+++ b/connector/src/settings.ts
@@ -55,6 +55,25 @@ export const HOME_OOM_SCORE_ADJ = -800;
/** The first home image whose launcher clears another container's data-directory lease itself. */
export const LEASE_FIXED_VERSION = [0, 1, 131] as const;
+/**
+ * The first home image whose launcher reads its secrets from HOME_SECRETS_FILE and drops CAP_SYS_ADMIN and CAP_SETPCAP
+ * as soon as it has remounted /proc with hidepid. An older image gets its secrets in its environment and never these
+ * two capabilities: it would keep CAP_SYS_ADMIN for life.
+ */
+export const HARDENED_LAUNCHER_VERSION = [0, 1, 143] as const;
+export const HIDEPID_CAPABILITIES = ["SYS_ADMIN", "SETPCAP"] as const;
+
+/** The home's secrets: kept out of its container's environment (docker inspect shows that) once its launcher reads the file. */
+export const HOME_SECRET_ENV = [
+ "OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_CLOUD_BOAT_TOKEN", "OMB_CLOUD_VOICE_TOKEN", "OMB_CLOUD_DECIDER_TOKEN", "OMB_CLOUD_AI_TOKEN",
+ "OMB_CLOUD_CONNECTED_APPS_GRANT", "OMB_CLOUD_X_TOKEN",
+] as const;
+/** In the home: a read-only folder holding only `secrets.json`, root's alone. The launcher reads it at start. */
+export const HOME_SECRETS_TARGET = "/run/mausbot";
+/** In the connector's state volume: the folder mounted at HOME_SECRETS_TARGET. */
+export const HOME_SECRETS_DIR = "home-secrets";
+export const HOME_SECRETS_FILE = "secrets.json";
+
export function envSeconds(name: string, fallback: number, min: number, max: number): number {
const raw = process.env[name];
const value = raw === undefined ? NaN : Number(raw);
diff --git a/connector/src/state.ts b/connector/src/state.ts
index e0cf77af80..c318a61a30 100644
--- a/connector/src/state.ts
+++ b/connector/src/state.ts
@@ -1,8 +1,11 @@
// The connector's state volume: small JSON files, each written whole (temp file, then rename) and readable by root only,
-// in a folder only root may enter. The agent token and the home's environment live here and nowhere else.
+// in a folder only root may enter. The agent token and the home's environment live here and nowhere else; the home's
+// secrets are also in their own folder, the only one a container (the home, read-only) ever mounts.
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
+import { HOME_SECRET_ENV, HOME_SECRETS_DIR, HOME_SECRETS_FILE } from "./settings.ts";
+
export interface AgentRecord {
version: 1;
admin: string;
@@ -71,8 +74,7 @@ export class StateStore {
constructor(dir: string) {
this.dir = dir;
- mkdirSync(dir, { recursive: true, mode: 0o700 });
- if (process.platform !== "win32" && (statSync(dir).mode & 0o077) !== 0) chmodSync(dir, 0o700);
+ privateDir(dir);
}
path(name: string): string {
@@ -123,6 +125,19 @@ export class StateStore {
saveHomeEnv(env: Record<string, string>): void {
this.write(FILES.env, env);
+ this.saveHomeSecrets(env);
+ }
+
+ /** The folder holding only the home's secrets file. */
+ get homeSecretsDir(): string {
+ return this.path(HOME_SECRETS_DIR);
+ }
+
+ /** The secrets of `env`, and nothing else, for the home's launcher to read. */
+ saveHomeSecrets(env: Record<string, string>): void {
+ privateDir(this.homeSecretsDir);
+ const secrets = Object.fromEntries(HOME_SECRET_ENV.flatMap((name) => (env[name] ? [[name, env[name]]] : [])));
+ this.write(join(HOME_SECRETS_DIR, HOME_SECRETS_FILE), secrets);
}
status(): StatusRecord {
@@ -165,3 +180,8 @@ export class StateStore {
this.remove("self-update.aborted.json");
}
}
+
+function privateDir(dir: string): void {
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ if (process.platform !== "win32" && (statSync(dir).mode & 0o077) !== 0) chmodSync(dir, 0o700);
+}
diff --git a/connector/test/fake-docker.ts b/connector/test/fake-docker.ts
index a1100c0753..112b43f9be 100644
--- a/connector/test/fake-docker.ts
+++ b/connector/test/fake-docker.ts
@@ -1,6 +1,6 @@
// An in-memory Docker Engine for the connector's tests: images, containers, volumes holding files, and the fixed
// helper commands the connector runs (cp, find, du, tar, the box probe) carried out on those files.
-import { readFileSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import type { ContainerInfo, ContainerSpec, ContainerSummary, Docker, DockerInfo, DockerVersion, ImageInfo, VolumeInfo } from "../src/docker.ts";
@@ -131,7 +131,9 @@ export class FakeDocker implements Docker {
if (this.containers.has(name)) throw new DockerError(409, `Conflict. The container name "/${name}" is already in use`);
if (!this.images.has(spec.Image)) throw new DockerError(404, `No such image: ${spec.Image}`);
for (const mount of spec.HostConfig.Mounts ?? []) {
- if (!this.volumes.has(mount.Source)) this.volumes.set(mount.Source, { labels: {}, files: new Map() });
+ if (mount.Type === "bind") {
+ if (!existsSync(mount.Source)) throw new DockerError(400, `invalid mount config for type "bind": bind source path does not exist: ${mount.Source}`);
+ } else if (!this.volumes.has(mount.Source)) this.volumes.set(mount.Source, { labels: {}, files: new Map() });
}
const id = `c${String(this.nextId++).padStart(11, "0")}`;
this.containers.set(name, { id, name, spec, status: "created", exitCode: 0, startedAt: 0, logs: "" });
@@ -194,8 +196,9 @@ export class FakeDocker implements Docker {
}
async volumeInspect(name: string): Promise<VolumeInfo | null> {
+ if (name === "mausbot-connector") return { Name: name, Labels: {}, Mountpoint: this.stateDir };
const volume = this.volumes.get(name);
- return volume ? { Name: name, Labels: volume.labels } : null;
+ return volume ? { Name: name, Labels: volume.labels, Mountpoint: `/var/lib/docker/volumes/${name}/_data` } : null;
}
async createVolume(name: string, labels: Record<string, string>): Promise<void> {
diff --git a/connector/test/home.test.ts b/connector/test/home.test.ts
index cb55e0d802..14be796fa7 100644
--- a/connector/test/home.test.ts
+++ b/connector/test/home.test.ts
@@ -5,14 +5,14 @@ import { afterEach, describe, expect, it } from "vitest";
import { JobFailure } from "../src/failure.ts";
import type { HealthRead } from "../src/home-health.ts";
-import { Home, homeSpec, imageVersion } from "../src/home.ts";
+import { Home, homeSpec, imageVersion, launcherOf } from "../src/home.ts";
import { registerSecret } from "../src/log.ts";
import { StateStore, type Operation } from "../src/state.ts";
import type { Transfer } from "../src/transfer.ts";
import { FakeDocker } from "./fake-docker.ts";
const image = (letter: string) => `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${letter.repeat(64)}`;
-const A = image("a"), B = image("b"), C = image("c");
+const A = image("a"), B = image("b"), C = image("c"), D = image("d");
const SECRET = "Bootstrap-secret-0123456789abcdefghijklmnopq";
const RELAY = "box_omb_relay-token-0123456789abcdefghijklmnop";
const env = {
@@ -34,13 +34,18 @@ function fixture(options: { free?: number } = {}) {
const docker = new FakeDocker(state.dir);
let clock = 1_800_000_000_000;
docker.now = () => clock;
- for (const [ref, version] of [[A, "v0.1.130"], [B, "v0.1.131"], [C, "v0.1.132"]] as const) docker.publish(ref, version);
- const healthy = new Set<string>([A, B, C]);
+ for (const [ref, version] of [[A, "v0.1.130"], [B, "v0.1.131"], [C, "v0.1.132"], [D, "v0.1.143"]] as const) docker.publish(ref, version);
+ const healthy = new Set<string>([A, B, C, D]);
const lines: string[] = [];
const readHealth: HealthRead = async (target) => {
const home = docker.container("mausbot-home");
if (!home || home.status !== "running") return { status: 0, report: null };
- const homeEnv = Object.fromEntries((home.spec.Env ?? []).map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]));
+ // As the launcher does: its environment, and the secrets file when one is mounted.
+ const secrets = home.spec.HostConfig.Mounts?.find((mount) => mount.Target === "/run/mausbot");
+ const homeEnv: Record<string, string> = {
+ ...Object.fromEntries((home.spec.Env ?? []).map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)])),
+ ...(secrets ? JSON.parse(readFileSync(join(secrets.Source, "secrets.json"), "utf8")) as Record<string, string> : {}),
+ };
if (target.secret !== homeEnv.OMB_CLOUD_BOOTSTRAP_SECRET) return { status: 401, report: { error: "invalid_signature" } };
if (target.publicHost !== new URL(homeEnv.OMB_PUBLIC_URL).hostname || target.port !== 8080) return { status: 403, report: null };
if (!healthy.has(home.spec.Image)) return { status: 0, report: null };
@@ -121,6 +126,59 @@ describe("the home on an own server", () => {
}
});
+ it("gives a hardened launcher its secrets in a read-only file, never its environment, and the two capabilities it drops", async () => {
+ const f = fixture();
+ await started(f, D);
+ const spec = f.docker.container("mausbot-home")!.spec;
+ const secretsDir = join(f.state.dir, "home-secrets");
+ expect(spec).toEqual(homeSpec(D, env, SECCOMP, { secretsDir, dropsCapabilities: true }));
+ expect(JSON.stringify(spec)).not.toContain(SECRET);
+ expect(JSON.stringify(spec)).not.toContain(RELAY);
+ expect(spec.Env).toEqual([
+ "OMB_CLOUD_ROLE=home", `OMB_CLOUD_MACHINE_ID=${env.OMB_CLOUD_MACHINE_ID}`, `OMB_CLOUD_ADMIN_URL=${env.OMB_CLOUD_ADMIN_URL}`, `OMB_PUBLIC_URL=${env.OMB_PUBLIC_URL}`, `OMB_CLOUD_IMAGE=${D}`,
+ ]);
+ expect(spec.HostConfig.Mounts).toEqual([
+ { Type: "volume", Source: "mausbot-data", Target: "/data" },
+ { Type: "bind", Source: secretsDir, Target: "/run/mausbot", ReadOnly: true },
+ ]);
+ expect(spec.HostConfig.CapAdd).toEqual(["CHOWN", "SETUID", "SETGID", "KILL", "SYS_ADMIN", "SETPCAP"]);
+ expect(readdirSync(secretsDir)).toEqual(["secrets.json"]);
+ expect(JSON.parse(readFileSync(join(secretsDir, "secrets.json"), "utf8"))).toEqual({ OMB_CLOUD_BOOTSTRAP_SECRET: SECRET, OMB_CLOUD_BOAT_TOKEN: RELAY });
+ if (process.platform !== "win32") {
+ expect(statSync(secretsDir).mode & 0o777).toBe(0o700);
+ expect(statSync(join(secretsDir, "secrets.json")).mode & 0o777).toBe(0o600);
+ }
+ // A new secret makes a new container, which reads the new file.
+ const rotated = { ...env, OMB_CLOUD_BOOTSTRAP_SECRET: `${SECRET}-rotated` };
+ await f.home.start("start-2", D, rotated);
+ expect(JSON.parse(readFileSync(join(secretsDir, "secrets.json"), "utf8")).OMB_CLOUD_BOOTSTRAP_SECRET).toBe(`${SECRET}-rotated`);
+ expect((await f.home.report()).health).toMatchObject({ ok: true, image: D });
+ });
+
+ it("gives an older image exactly what it always had: secrets in its environment, no added capability", async () => {
+ const f = fixture();
+ await started(f);
+ await f.home.update("update-1", D);
+ expect(f.docker.container("mausbot-home")!.spec.HostConfig.CapAdd).toContain("SYS_ADMIN");
+ await f.home.update("update-2", C);
+ const old = f.docker.container("mausbot-home")!.spec;
+ expect(old.Image).toBe(C);
+ expect(old.HostConfig.CapAdd).toEqual(["CHOWN", "SETUID", "SETGID", "KILL"]);
+ expect(old.HostConfig.Mounts).toEqual([{ Type: "volume", Source: "mausbot-data", Target: "/data" }]);
+ expect(old.Env).toContain(`OMB_CLOUD_BOOTSTRAP_SECRET=${SECRET}`);
+ expect(launcherOf(null)).toEqual({ secretsFile: false, dropsCapabilities: false });
+ expect(launcherOf([0, 1, 142])).toEqual({ secretsFile: false, dropsCapabilities: false });
+ expect(launcherOf([0, 1, 143])).toEqual({ secretsFile: true, dropsCapabilities: true });
+ expect(launcherOf([0, 2, 0])).toEqual({ secretsFile: true, dropsCapabilities: true });
+ });
+
+ it("writes the secrets file for a home an older connector started, before anything starts it again", () => {
+ const f = fixture();
+ f.state.write("home-env.json", env);
+ new Home({ docker: f.docker, state: f.state, log: () => {}, readHealth: async () => ({ status: 0, report: null }), seccomp: () => SECCOMP, transfer: { download: async () => ({ bytes: 0 }), upload: async () => ({ bytes: 0, sha256: "" }) }, diskFree: () => 1e12 });
+ expect(JSON.parse(readFileSync(join(f.state.dir, "home-secrets", "secrets.json"), "utf8"))).toEqual({ OMB_CLOUD_BOOTSTRAP_SECRET: SECRET, OMB_CLOUD_BOAT_TOKEN: RELAY });
+ });
+
it("clears the lease a killed home left before each start, until the image clears it itself, and never while a home runs", async () => {
const f = fixture();
await f.docker.createVolume("mausbot-data", {});
@@ -251,7 +309,7 @@ describe("the home on an own server", () => {
const f = fixture();
await started(f);
f.docker.calls.splice(0);
- const missing = image("d");
+ const missing = image("e");
expect((await failure(f.home.update("update-1", missing))).toJobError()).toMatchObject({ code: "pull_failed" });
expect(f.docker.calls.filter((call) => call.startsWith("stop") || call.startsWith("rm"))).toEqual([]);
expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });
diff --git a/connector/test/protocol.test.ts b/connector/test/protocol.test.ts
index 70dfc38c47..2cc72c6d48 100644
--- a/connector/test/protocol.test.ts
+++ b/connector/test/protocol.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
-import { cloudRequestSignature as homeSignature } from "../../server/cloud-home.ts";
+import { CLOUD_HOME_SECRET_KEYS, cloudRequestSignature as homeSignature } from "../../server/cloud-home.ts";
+import { CAPS_DROPPED_ENV, CLOUD_SECRETS_FILE } from "../../server/cloud-home-start.ts";
+import { HOME_SECRET_ENV, HOME_SECRETS_FILE, HOME_SECRETS_TARGET } from "../src/settings.ts";
import { cloudRequestSignature, summarizeHealth } from "../src/home-health.ts";
import { checkEnrollCode, checkEnrollResponse, checkHomeEnv, checkJob, checkTransferUrl, JOB_TYPES, REQUIRED_HOME_ENV } from "../src/protocol.ts";
@@ -51,7 +53,7 @@ describe("the connector protocol", () => {
}
const refused = (extra: Record<string, unknown>) => checkHomeEnv({ ...env, ...extra });
for (const name of ["FLY_APP_NAME", "PATH", "NODE_OPTIONS", "HOME", "LD_PRELOAD", "omb_lower", "OMB_"]) expect(refused({ [name]: "x" }).ok, name).toBe(false);
- for (const name of ["OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_HARDEN", "OMB_DATA_DIR", "OMB_PORT", "OMB_CLOUD_SECRETS_FD"]) {
+ for (const name of ["OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_HARDEN", "OMB_DATA_DIR", "OMB_PORT", "OMB_CLOUD_SECRETS_FD", "OMB_CLOUD_CAPS_DROPPED"]) {
expect(refused({ [name]: "x" }), name).toMatchObject({ ok: false, message: `env name ${name} is the image's own setting` });
}
const secret = "T0P-SECRET-VALUE";
@@ -67,6 +69,12 @@ describe("the connector protocol", () => {
expect(checkHomeEnv([]).ok).toBe(false);
});
+ it("keeps out of the home's environment exactly the secrets its launcher reads from the file, where it reads it", () => {
+ expect([...HOME_SECRET_ENV].sort()).toEqual([...CLOUD_HOME_SECRET_KEYS].sort());
+ expect(`${HOME_SECRETS_TARGET}/${HOME_SECRETS_FILE}`).toBe(CLOUD_SECRETS_FILE);
+ expect(checkHomeEnv({ ...env, [CAPS_DROPPED_ENV]: "1" }).ok).toBe(false);
+ });
+
it("transfers only over https, or http to a test Admin on this machine, never with credentials in the address", () => {
expect(checkTransferUrl("https://storage.example.test/disk.tar.gz?sig=abc")).toEqual({ ok: true, value: "https://storage.example.test/disk.tar.gz?sig=abc" });
expect(checkTransferUrl("http://127.0.0.1:8123/disk").ok).toBe(true);
diff --git a/docs/bot-box.md b/docs/bot-box.md
index 49034e536c..2b825c939b 100644
--- a/docs/bot-box.md
+++ b/docs/bot-box.md
@@ -103,7 +103,7 @@ or files, the base URL is the broker, a call with the token reaches the upstream
| Environment allow-list | every boxed process | `OMB_CLOUD_*`, the server's placement, workspace credentials, any unlisted name | the engines' own settings |
| Credential broker (T0b) | every boxed process with its own network | holding a provider key or an MCP header; using a token after its process or conversation ends; choosing the upstream | keys with no base-URL setting (named in the report); subscription logins |
| seccomp filter (T0c) | every boxed process on x86-64 | 34 system calls that only reach the kernel's attack surface: mount family, kernel modules, bpf, perf, userfaultfd, the kernel keyring, `open_by_handle_at`, `setns`, kexec, reboot, swap, clock setting, I/O ports (EPERM); a process of another architecture (killed) | anything an engine, shell, git, npm, python or Chrome uses: all allowed |
-| `hidepid=invisible` on the host's /proc (T0c) | the whole machine, set by the root supervisor at boot | a `maus` process outside a box (the browser engine, a helper) listing or reading root's processes | `maus` processes seeing each other; a box has its own /proc anyway |
+| `hidepid=invisible` on the host's /proc (T0c) | the whole machine, set by the root supervisor at boot, which then starts itself again through `setpriv` without CAP_SYS_ADMIN and CAP_SETPCAP (an own server's connector grants those two only for that remount, and only to an image that drops them) | a `maus` process outside a box (the browser engine, a helper) listing or reading root's processes | `maus` processes seeing each other; a box has its own /proc anyway |
| `/.fly` root-only (T0c) | the whole machine | a `maus` process reaching Fly's local API socket | nothing else |
Not built, and why: a **separate Linux user per bot**. The server runs as `maus` under a root supervisor and cannot
diff --git a/server/bot-box/box-probe.ts b/server/bot-box/box-probe.ts
index 1ba4a96255..c59ae0b606 100644
--- a/server/bot-box/box-probe.ts
+++ b/server/bot-box/box-probe.ts
@@ -27,6 +27,9 @@ export interface ProbeSpec {
marker: string;
canaryPid: number;
serverPid: number;
+ /** When each started (processStart): a process of the box's own may have the same pid number, never the same start. */
+ canaryStart?: string | null;
+ serverStart?: string | null;
hostTmpFile: string;
harnessPort: number;
egressPort: number;
@@ -46,6 +49,21 @@ export interface ProbeSpec {
export interface ProbeResult { id: string; ok: boolean; detail: string }
+/** A process's start, in clock ticks since boot: field 22 of /proc/<pid>/stat, counted after the command's last ")". */
+export function processStart(pid: number | "self", read: (path: string) => string = (path) => readFileSync(path, "utf8")): string | null {
+ try {
+ const stat = read(`/proc/${pid}/stat`);
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/** The box's /proc shows that very process, not one of its own that got the same pid. */
+export function seesProcess(pid: number, start: string | null | undefined, startOf: (pid: number) => string | null = processStart): boolean {
+ return start ? startOf(pid) === start : existsSync(`/proc/${pid}`);
+}
+
const fails = (fn: () => unknown): { failed: boolean; code: string } => {
try { fn(); return { failed: false, code: "ok" }; } catch (error) { return { failed: true, code: (error as NodeJS.ErrnoException).code ?? "error" }; }
};
@@ -118,10 +136,12 @@ export async function runProbe(spec: ProbeSpec, env: Record<string, string | und
add("secret-not-in-env", inEnv.length === 0, inEnv.length ? `in ${inEnv.join(",")}` : "absent");
const onDisk = scanForMarker(spec.dataDir, spec.marker, { files: 5_000 }) + scanForMarker("/tmp", spec.marker, { files: 5_000 }) + scanForMarker(spec.cwd, spec.marker, { files: 5_000 });
add("secret-not-on-disk", onDisk === 0, `${onDisk} hits`);
- add("other-pid-hidden", !existsSync(`/proc/${spec.canaryPid}`), existsSync(`/proc/${spec.canaryPid}`) ? "visible" : "absent");
+ const canaryVisible = seesProcess(spec.canaryPid, spec.canaryStart);
+ add("other-pid-hidden", !canaryVisible, canaryVisible ? "visible" : "absent");
const environ = fails(() => readFileSync(`/proc/${spec.canaryPid}/environ`));
- add("other-env-unreadable", environ.failed, environ.code);
- add("server-pid-hidden", !existsSync(`/proc/${spec.serverPid}`), existsSync(`/proc/${spec.serverPid}`) ? "visible" : "absent");
+ add("other-env-unreadable", !canaryVisible || environ.failed, canaryVisible ? environ.code : "absent");
+ const serverVisible = seesProcess(spec.serverPid, spec.serverStart);
+ add("server-pid-hidden", !serverVisible, serverVisible ? "visible" : "absent");
const own = fails(() => { writeFileSync(join(spec.cwd, ".box-probe"), "ok"); if (readFileSync(join(spec.cwd, ".box-probe"), "utf8") !== "ok") throw new Error("mismatch"); });
add("own-cwd-rw", !own.failed, own.code);
const folder = fails(() => writeFileSync(join(spec.botFolder, ".box-probe"), "ok"));
diff --git a/server/bot-box/box.test.ts b/server/bot-box/box.test.ts
index 49e81c9236..c3105ba016 100644
--- a/server/bot-box/box.test.ts
+++ b/server/bot-box/box.test.ts
@@ -3,7 +3,9 @@ import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { BotBox, BoxRunner, BOX_EGRESS_PORT, flyApiPrivate, procHidepid, writeSeccompFile } from "./box.ts";
+import { BotBox, BoxRunner, BOX_EGRESS_PORT, flyApiPrivate, writeSeccompFile } from "./box.ts";
+import { processStart, seesProcess } from "./box-probe.ts";
+import { procHidepid } from "./hidepid.ts";
import { visibleInBox } from "./plan.ts";
import { DENIED_SYSCALLS, seccompBytes } from "./seccomp.ts";
import { engineInstallRoots, npmEnginesPrefix } from "../engine-roots.ts";
@@ -255,3 +257,20 @@ describe("BoxRunner.lend", () => {
expect(runner.lentTo("bot-a", "thread-1")).toEqual([]);
});
});
+
+describe("the probe tells the server and the canary from a box process with the same pid", () => {
+ // /proc/<pid>/stat as Linux 6.8 writes it; the command may hold spaces and parentheses.
+ const stat = (start: string) => `331 (node (MainThread)) S 1 331 331 0 -1 4194560 26085 0 0 0 63 12 0 0 20 0 11 0 ${start} 1270784000 23468 18446744073709551615`;
+
+ it("reads a process's start after its command, however that is spelled", () => {
+ expect(processStart(331, () => stat("4321789"))).toBe("4321789");
+ expect(processStart(331, () => { throw new Error("ENOENT"); })).toBeNull();
+ if (process.platform === "linux") expect(processStart("self")).toMatch(/^\d+$/);
+ });
+
+ it("counts a pid as the same process only when it started at the same moment", () => {
+ expect(seesProcess(7, "4321789", () => "4321789")).toBe(true);
+ expect(seesProcess(7, "4321789", () => "88")).toBe(false);
+ expect(seesProcess(7, "4321789", () => null)).toBe(false);
+ });
+});
diff --git a/server/bot-box/box.ts b/server/bot-box/box.ts
index 639fe7f10b..f45acd999a 100644
--- a/server/bot-box/box.ts
+++ b/server/bot-box/box.ts
@@ -2,7 +2,7 @@
// boxes reach through unix sockets (egress-gate.ts, harness-gate.ts), and wraps each bot spawn (server/procs.ts spawnCli
// with owner "bot") in bubblewrap by the plan (plan.ts). Nothing here changes a spawn when the box is off: the command,
// its arguments and its environment go through untouched, so every host that is not a Cloud home behaves as before.
-import { existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, openSync, rmSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { engineInstallRoots } from "../engine-roots.ts";
@@ -14,6 +14,7 @@ import { detectBox, type BoxDetection, type BoxKind } from "./detect.ts";
import { openBoxEgressGate, type BoxEgressGate } from "./egress-gate.ts";
import { boxEnvironment } from "./env.ts";
import { openHarnessGate, type HarnessGate } from "./harness-gate.ts";
+import { procHidepid } from "./hidepid.ts";
import { DENIED_SYSCALLS, seccompBytes, seccompSupported } from "./seccomp.ts";
import { boxUploadsDir, bwrapArgs, planBox, taskWorkspaceIds, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";
@@ -155,11 +156,6 @@ export function writeSeccompFile(dir: string): string | null {
return file;
}
-/** Whether the host's /proc hides other users' processes (the Cloud supervisor remounts it so at boot). */
-export function procHidepid(mounts: () => string = () => readFileSync("/proc/mounts", "utf8")): boolean {
- try { return /^proc \/proc proc [^\n]*\bhidepid=(?:2|invisible)\b/m.test(mounts()); } catch { return false; }
-}
-
/** Whether Fly's local API socket folder is root's alone (no bits for group or others). */
export function flyApiPrivate(stat: (path: string) => { mode: number } = statSync): boolean {
try { return (stat("/.fly").mode & 0o077) === 0; } catch { return true; }
diff --git a/server/bot-box/hidepid.ts b/server/bot-box/hidepid.ts
new file mode 100644
index 0000000000..bffa435c06
--- /dev/null
+++ b/server/bot-box/hidepid.ts
@@ -0,0 +1,6 @@
+import { readFileSync } from "node:fs";
+
+/** /proc hides other users' processes (`hidepid=invisible`, spelled `hidepid=2` before Linux 5.8). */
+export function procHidepid(mounts: () => string = () => readFileSync("/proc/mounts", "utf8")): boolean {
+ try { return /^proc \/proc proc [^\n]*\bhidepid=(?:2|invisible)\b/m.test(mounts()); } catch { return false; }
+}
diff --git a/server/bot-box/self-check.ts b/server/bot-box/self-check.ts
index 2025286dd4..75ddf5e263 100644
--- a/server/bot-box/self-check.ts
+++ b/server/bot-box/self-check.ts
@@ -18,7 +18,7 @@ import { openCredentialBroker } from "./broker.ts";
import { openBoxEgressGate } from "./egress-gate.ts";
import { openHarnessGate } from "./harness-gate.ts";
import type { BoxBridge, BoxMutation } from "./plan.ts";
-import { PROBE_SPEC_ENV, type ProbeResult, type ProbeSpec } from "./box-probe.ts";
+import { PROBE_SPEC_ENV, processStart, type ProbeResult, type ProbeSpec } from "./box-probe.ts";
export interface SelfCheckOptions {
bwrap: string;
@@ -130,6 +130,7 @@ export async function runBoxSelfCheck(options: SelfCheckOptions): Promise<SelfCh
const spec: ProbeSpec = {
dataDir: data, cwd, botFolder, messagesDb: join(data, "messages.db"), configJson: join(data, "config.json"), serverFiles,
otherWorkspace, otherTaskWorkspace: otherTask, engine: { bin: engineBin, name: engineName, says: engineSays }, marker, canaryPid: canary.pid ?? 0, serverPid: process.pid, hostTmpFile,
+ canaryStart: canary.pid ? processStart(canary.pid) : null, serverStart: processStart("self"),
harnessPort: serverPort, egressPort: BOX_EGRESS_PORT, privatePort, publicTarget, isolatedNet,
// Checked whenever a filter is in the setup: the no-seccomp mutation leaves it out of the box, so the check must fail.
seccomp: Boolean(options.seccompFile),
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index 6c79fa257d..9037cee434 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -3,13 +3,14 @@
// loopback trust. Secrets never ride a child's environment (/proc/<pid>/environ stays readable by the same user): the
// server reads them from an inherited pipe. Root runs and trusts only the image's code, never the volume's.
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
-import { chmodSync, chownSync, closeSync, existsSync, openSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs";
+import { chmodSync, chownSync, closeSync, existsSync, lstatSync, openSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs";
import { dirname, join, posix, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
CLOUD_SECRETS_FD_ENV, cloudHomeConfiguration, cloudHomeHost, cloudHomeSecrets, prepareCloudHomeVolume,
withoutCloudSecrets, withoutIgnoredCloudKeys, type CloudHomeConfig,
} from "./cloud-home.ts";
+import { procHidepid } from "./bot-box/hidepid.ts";
import { boxMemory, heapSizeArgs } from "./box-memory.ts";
import { clearRecordsFromOtherMachines } from "./data-dir-lease.ts";
import { OOM_SCORE, protectSupervisor, spawnWithOomScore } from "./oom-score.ts";
@@ -116,7 +117,7 @@ export function prepareCloudHomeData(home: string, dataDir: string, machineId: s
export function cloudHomeChildEnvironments(config: CloudHomeConfig, env: NodeJS.ProcessEnv, home: string) {
const offered = withoutCloudSecrets(withoutIgnoredCloudKeys(env));
const allowed = Object.fromEntries(Object.entries(offered).filter(([name, value]) => value !== undefined && serverEnvironmentAllowed(name)));
- const dropped = Object.keys(offered).filter((name) => !serverEnvironmentAllowed(name) && name !== "HOME").sort();
+ const dropped = Object.keys(offered).filter((name) => !serverEnvironmentAllowed(name) && name !== "HOME" && name !== CAPS_DROPPED_ENV).sort();
const dataDir = cloudHomeDataDir(env, home);
const server: NodeJS.ProcessEnv = {
...allowed, HOME: home, OMB_DATA_DIR: dataDir,
@@ -128,7 +129,9 @@ export function cloudHomeChildEnvironments(config: CloudHomeConfig, env: NodeJS.
};
const edge: NodeJS.ProcessEnv = {
PATH: env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: "/tmp/omb-edge",
- XDG_DATA_HOME: "/tmp/omb-edge/data", XDG_CONFIG_HOME: "/tmp/omb-edge/config",
+ // On the volume: certificates the edge gets for an own server's address outlive a new container, and Let's Encrypt
+ // issues the same certificate only 5 times a week.
+ XDG_DATA_HOME: posix.join(home, ".omb-edge"), XDG_CONFIG_HOME: "/tmp/omb-edge/config",
OMB_CLOUD_PUBLIC_HOST: cloudHomeHost(config),
// A plan whose home sleeps: requests wait this long for the server while it starts (deploy/fly/Caddyfile). Unset: 0s.
OMB_CLOUD_EDGE_HOLD: edgeHold(env.OMB_CLOUD_EDGE_HOLD),
@@ -137,20 +140,96 @@ export function cloudHomeChildEnvironments(config: CloudHomeConfig, env: NodeJS.
return { server, edge, secrets: cloudHomeSecrets(env), dropped };
}
+/** Set in the supervisor's own environment once it has started again without CAP_SYS_ADMIN, so it never loops. */
+export const CAPS_DROPPED_ENV = "OMB_CLOUD_CAPS_DROPPED";
+const CAP_SYS_ADMIN = 21;
+const SETPRIV = "/usr/bin/setpriv";
+
+/** A capability's bit in one of /proc/self/status's sets (CapBnd, CapEff, CapInh). */
+export function hasCapability(status: string, set: "CapBnd" | "CapEff" | "CapInh", bit: number): boolean {
+ const hex = new RegExp(`^${set}:\\s*([0-9a-f]+)$`, "m").exec(status)?.[1];
+ return hex ? ((BigInt(`0x${hex}`) >> BigInt(bit)) & 1n) === 1n : false;
+}
+
+export interface HostHardening {
+ notes: string[];
+ /** CAP_SYS_ADMIN served the remount and nothing after it: start again through setpriv without it (dropCapabilities). */
+ dropCapabilities: boolean;
+}
+
/** What root does to the machine before anything runs as `maus` (docs/bot-box.md, "What each layer stops"): /proc hides
* other users' processes (`hidepid=invisible`), so no `maus` process lists root's, and Fly's local API socket folder is
- * root's alone. Each step is one command; a failure is logged, never fatal, and OMB_CLOUD_HARDEN=0 skips them all. */
-export function hardenHost(env: NodeJS.ProcessEnv, run: { exec: (command: string, args: string[]) => { status: number | null; stderr?: string }; chmod: (path: string, mode: number) => void; exists: (path: string) => boolean } = {
+ * root's alone. Each step is one command; a failure is logged, never fatal, and OMB_CLOUD_HARDEN=0 skips them all.
+ * CAP_SYS_ADMIN, which an own server's connector grants only for the remount, must not outlive it. */
+export function hardenHost(env: NodeJS.ProcessEnv, run: {
+ exec: (command: string, args: string[]) => { status: number | null; stderr?: string };
+ chmod: (path: string, mode: number) => void;
+ exists: (path: string) => boolean;
+ read: (path: string) => string;
+} = {
exec: (command, args) => spawnSync(command, args, { stdio: ["ignore", "ignore", "pipe"], encoding: "utf8", timeout: 10_000 }), chmod: chmodSync, exists: existsSync,
-}): string[] {
- if (env.OMB_CLOUD_HARDEN === "0") return ["hardening skipped (OMB_CLOUD_HARDEN=0)"];
+ read: (path) => { try { return readFileSync(path, "utf8"); } catch { return ""; } },
+}): HostHardening {
+ if (env.OMB_CLOUD_HARDEN === "0") return { notes: ["hardening skipped (OMB_CLOUD_HARDEN=0)"], dropCapabilities: false };
const notes: string[] = [];
- const remount = run.exec("mount", ["-o", "remount,hidepid=invisible", "/proc"]);
- notes.push(remount.status === 0 ? "/proc: hidepid=invisible" : `/proc: hidepid not applied (${String(remount.stderr ?? "").trim().split("\n")[0] || `exit ${remount.status}`})`);
+ if (procHidepid(() => run.read("/proc/mounts"))) notes.push("/proc: hidepid=invisible");
+ else {
+ const remount = run.exec("mount", ["-o", "remount,hidepid=invisible", "/proc"]);
+ notes.push(remount.status === 0 ? "/proc: hidepid=invisible" : `/proc: hidepid not applied (${String(remount.stderr ?? "").trim().split("\n")[0] || `exit ${remount.status}`})`);
+ }
+ const status = run.read("/proc/self/status");
+ const kept = hasCapability(status, "CapBnd", CAP_SYS_ADMIN) || hasCapability(status, "CapEff", CAP_SYS_ADMIN);
+ if (kept && env[CAPS_DROPPED_ENV] !== "1") {
+ if (run.exists(SETPRIV)) return { notes, dropCapabilities: true };
+ notes.push(`CAP_SYS_ADMIN kept: ${SETPRIV} is missing`);
+ } else if (kept) {
+ // libcap-ng (setpriv) skips a bounding-set drop without CAP_SETPCAP and still exits 0.
+ notes.push("CAP_SYS_ADMIN kept: it could not be dropped (CAP_SETPCAP is missing)");
+ } else if (env[CAPS_DROPPED_ENV] === "1") {
+ notes.push("CAP_SYS_ADMIN dropped");
+ }
if (run.exists("/.fly")) {
try { run.chmod("/.fly", 0o700); notes.push("/.fly: root only"); } catch (error) { notes.push(`/.fly: left as is (${error instanceof Error ? error.message : String(error)})`); }
}
- return notes;
+ return { notes, dropCapabilities: false };
+}
+
+/** Starts this supervisor again in its own process, without CAP_SYS_ADMIN or CAP_SETPCAP in any set it could regain them from. */
+export function setprivArgs(execPath: string, script: string): string[] {
+ return ["setpriv", "--inh-caps=-sys_admin,-setpcap", "--bounding-set=-sys_admin,-setpcap", "--", execPath, script];
+}
+
+/** Replaces this process; returns only why it could not. */
+function dropCapabilities(env: NodeJS.ProcessEnv): string {
+ if (typeof process.execve !== "function") return "this Node cannot start itself again in place";
+ try {
+ process.execve(SETPRIV, setprivArgs(process.execPath, fileURLToPath(import.meta.url)), { ...env, [CAPS_DROPPED_ENV]: "1" });
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ return "setpriv did not start";
+}
+
+/** Where an own server's connector mounts the home's secrets, read-only, instead of putting them in its environment. */
+export const CLOUD_SECRETS_FILE = "/run/mausbot/secrets.json";
+
+/** The secrets in CLOUD_SECRETS_FILE, when it is there: root's, readable by root alone, off the volume; known names only. */
+export function readCloudSecretsFile(home: string, file = CLOUD_SECRETS_FILE, fs: {
+ exists: (path: string) => boolean;
+ lstat: (path: string) => Pick<Stats, "uid" | "mode" | "isFile" | "isSymbolicLink">;
+ stat: (path: string) => Pick<Stats, "uid" | "mode">;
+ read: (path: string) => string;
+} = { exists: existsSync, lstat: lstatSync, stat: statSync, read: (path) => readFileSync(path, "utf8") }): Record<string, string> {
+ if (!fs.exists(file)) return {};
+ const entry = fs.lstat(file);
+ const problem = !entry.isFile() || entry.isSymbolicLink() ? `${file} is not a plain file`
+ : entry.mode & 0o077 ? `${file} is readable by others than root`
+ : codeTrustProblem([file], home, fs.stat);
+ if (problem) throw new Error(`The home's secrets file is not safe to read: ${problem}.`);
+ let parsed: unknown;
+ try { parsed = JSON.parse(fs.read(file)); } catch { parsed = null; }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`The home's secrets file ${file} is not a JSON object.`);
+ return cloudHomeSecrets(parsed as NodeJS.ProcessEnv);
}
/** Each file and every folder above it must be root's and not writable by others, and never on the `maus`-owned volume:
@@ -183,20 +262,26 @@ export function spawnWithSecrets(command: string, args: string[], env: NodeJS.Pr
return child;
}
-export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {
+export function startCloudHome(processEnv: NodeJS.ProcessEnv = process.env) {
process.umask(0o077);
+ const root = process.getuid?.() === 0;
+ if (root && process.platform === "linux") {
+ const hardening = hardenHost(processEnv);
+ const notes = hardening.dropCapabilities ? [...hardening.notes, `CAP_SYS_ADMIN kept: ${dropCapabilities(processEnv)}`] : hardening.notes;
+ for (const note of notes) console.log(`cloud home: ${note}`);
+ }
+ const home = processEnv.HOME || "/data";
+ const env = root ? { ...processEnv, ...readCloudSecretsFile(home) } : processEnv;
const config = cloudHomeConfiguration(env);
if (!config) throw new Error("This image runs a My Cloud machine for MausBot Cloud; set its boot contract (docs/cloud-pro.md).");
// Logged here once: the server child never sees what they are about.
for (const warning of config.warnings) console.warn(`cloud home: ${warning}`);
- const home = env.HOME || "/data";
const prepare = () => prepareCloudHomeData(home, cloudHomeDataDir(env, home), config.machineId);
let prepared: ReturnType<typeof prepare>;
let ids: { uid: number; gid: number } | null = null;
- if (process.getuid?.() === 0) {
+ if (root) {
ids = passwdIds(readFileSync("/etc/passwd", "utf8"), SERVICE_USER);
if (!ids) throw new Error(`The ${SERVICE_USER} user is missing from this image.`);
- if (process.platform === "linux") for (const note of hardenHost(env)) console.log(`cloud home: ${note}`);
if (protectSupervisor()) console.log("cloud home: the supervisor is never stopped for memory");
// Only the mount point changes owner; anything inside keeps its owner.
const stat = statSync(home);
diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.ts
index f9e5d67577..7b062fe515 100644
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@ -10,7 +10,10 @@ import {
cloudHomeHost, cloudHomeOffersPlace, cloudHomePlaceRefusal, cloudPairingSignature, cloudRequestSignature, createCloudPairing, firstCloudTurnPatch, prepareCloudHomeVolume,
withoutIgnoredCloudKeys,
} from "./cloud-home.ts";
-import { cloudHomeChildEnvironments, cloudHomeDataDir, codeTrustProblem, edgeClientAddress, edgeHold, hardenHost, holdVolume, passwdIds, prepareCloudHomeData, spawnWithSecrets } from "./cloud-home-start.ts";
+import {
+ cloudHomeChildEnvironments, cloudHomeDataDir, codeTrustProblem, edgeClientAddress, edgeHold, hardenHost, hasCapability, holdVolume, passwdIds, prepareCloudHomeData,
+ readCloudSecretsFile, setprivArgs, spawnWithSecrets,
+} from "./cloud-home-start.ts";
import { RESTART_EXIT_CODE, restartPolicy } from "./restart.ts";
import { hostedModelPolicy } from "./hosted-models.ts";
import { resolveRequestAuth } from "./request-auth.ts";
@@ -352,6 +355,8 @@ it("lets only the tunnel name the client on an own server, and only Fly's proxy
const fly = cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin", FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }, "/data").edge;
expect(fly).toMatchObject({ OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "Fly-Client-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "private_ranges" });
expect(edgeClientAddress({ FLY_APP_NAME: " " })).toEqual(edgeClientAddress({}));
+ // Certificates for an own server's address live on the volume, so a new container reuses them.
+ expect(own.XDG_DATA_HOME).toBe("/data/.omb-edge");
// Both values are written into the edge's config as they are, so neither may come from anywhere but here.
for (const env of [{}, { FLY_APP_NAME: "omb-u-1a2b3c4d5e6f" }, { OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Real-IP", OMB_CLOUD_EDGE_TRUSTED_PROXIES: "0.0.0.0/0" }]) {
const edge = cloudHomeChildEnvironments(config, { ...contract(), PATH: "/usr/bin", ...env }, "/data").edge;
@@ -559,19 +564,82 @@ it("captures a child's stdout and stderr when asked, and shares this process's o
expect(shared.child.stderr).toBeNull();
});
+// /proc/mounts and /proc/self/status as a Docker container on Linux 6.8 shows them.
+const mounts = (procOptions: string) => `overlay / overlay rw,relatime,lowerdir=/var/lib/docker/overlay2/l/A 0 0\nproc /proc proc ${procOptions} 0 0\ntmpfs /dev tmpfs rw,nosuid,size=65536k,mode=755 0 0\n`;
+const capStatus = (bounding: string, effective = bounding) => `Name:\tnode\nCapInh:\t0000000000000000\nCapPrm:\t${effective}\nCapEff:\t${effective}\nCapBnd:\t${bounding}\nCapAmb:\t0000000000000000\n`;
+// CHOWN, KILL, SETGID, SETUID; with SETPCAP and SYS_ADMIN, as the connector grants an image that drops them.
+const FOUR = "00000000000000e1", WITH_SYS_ADMIN = "00000000002001e1";
+
it("the Cloud supervisor hardens the host before anything runs as maus: hidepid on /proc and Fly's socket folder root-only, each a note, never fatal", () => {
const calls: string[] = [];
- const run = (status: number, exists = true) => ({
+ const run = (status: number, exists = true, files: Record<string, string> = {}) => ({
exec: (command: string, args: string[]) => { calls.push(`${command} ${args.join(" ")}`); return { status, stderr: status ? "mount: permission denied\n" : "" }; },
chmod: (path: string, mode: number) => { calls.push(`chmod ${mode.toString(8)} ${path}`); },
exists: () => exists,
+ read: (path: string) => files[path] ?? "",
});
- expect(hardenHost({}, run(0))).toEqual(["/proc: hidepid=invisible", "/.fly: root only"]);
+ expect(hardenHost({}, run(0))).toEqual({ notes: ["/proc: hidepid=invisible", "/.fly: root only"], dropCapabilities: false });
expect(calls).toEqual(["mount -o remount,hidepid=invisible /proc", "chmod 700 /.fly"]);
- expect(hardenHost({}, run(32, false))).toEqual(["/proc: hidepid not applied (mount: permission denied)"]);
- expect(hardenHost({ OMB_CLOUD_HARDEN: "0" }, run(0))).toEqual(["hardening skipped (OMB_CLOUD_HARDEN=0)"]);
+ expect(hardenHost({}, run(32, false)).notes).toEqual(["/proc: hidepid not applied (mount: permission denied)"]);
+ expect(hardenHost({ OMB_CLOUD_HARDEN: "0" }, run(0))).toEqual({ notes: ["hardening skipped (OMB_CLOUD_HARDEN=0)"], dropCapabilities: false });
const failing = { ...run(0), chmod: () => { throw new Error("read-only"); } };
- expect(hardenHost({}, failing)).toEqual(["/proc: hidepid=invisible", "/.fly: left as is (read-only)"]);
+ expect(hardenHost({}, failing).notes).toEqual(["/proc: hidepid=invisible", "/.fly: left as is (read-only)"]);
+ // Already hidden (the supervisor started again, or the platform mounted /proc so): no second remount, no false failure.
+ calls.splice(0);
+ expect(hardenHost({}, run(32, false, { "/proc/mounts": mounts("rw,hidepid=invisible") })).notes).toEqual(["/proc: hidepid=invisible"]);
+ expect(calls).toEqual([]);
+});
+
+it("CAP_SYS_ADMIN serves only the hidepid remount: the supervisor starts again through setpriv without it, and says when it could not", () => {
+ const run = (files: Record<string, string>, setpriv = true) => ({
+ exec: () => ({ status: 0 }), chmod: () => {}, exists: (path: string) => path === "/usr/bin/setpriv" && setpriv,
+ read: (path: string) => files[path] ?? "",
+ });
+ const granted = { "/proc/mounts": mounts("rw"), "/proc/self/status": capStatus(WITH_SYS_ADMIN) };
+ expect(hardenHost({}, run(granted))).toEqual({ notes: ["/proc: hidepid=invisible"], dropCapabilities: true });
+ // Started again: hidepid stays, and the capability is gone from every set it could come back from.
+ const dropped = { "/proc/mounts": mounts("rw,hidepid=invisible"), "/proc/self/status": capStatus(FOUR) };
+ expect(hardenHost({ OMB_CLOUD_CAPS_DROPPED: "1" }, run(dropped))).toEqual({ notes: ["/proc: hidepid=invisible", "CAP_SYS_ADMIN dropped"], dropCapabilities: false });
+ // setpriv without CAP_SETPCAP exits 0 and drops nothing: the next start sees it and never loops.
+ const kept = { "/proc/mounts": mounts("rw,hidepid=invisible"), "/proc/self/status": capStatus(WITH_SYS_ADMIN) };
+ expect(hardenHost({ OMB_CLOUD_CAPS_DROPPED: "1" }, run(kept))).toEqual({ notes: ["/proc: hidepid=invisible", "CAP_SYS_ADMIN kept: it could not be dropped (CAP_SETPCAP is missing)"], dropCapabilities: false });
+ expect(hardenHost({}, run(granted, false)).notes).toEqual(["/proc: hidepid=invisible", "CAP_SYS_ADMIN kept: /usr/bin/setpriv is missing"]);
+ // A remount that failed still drops a capability nothing needs.
+ expect(hardenHost({}, { ...run(granted), exec: () => ({ status: 32, stderr: "mount: denied" }) }).dropCapabilities).toBe(true);
+ // The connector's four capabilities: nothing to drop, nothing to start again.
+ expect(hardenHost({}, run({ "/proc/self/status": capStatus(FOUR) })).dropCapabilities).toBe(false);
+ expect(setprivArgs("/usr/local/bin/node", "/app/dist-server/cloud-home-start.js")).toEqual([
+ "setpriv", "--inh-caps=-sys_admin,-setpcap", "--bounding-set=-sys_admin,-setpcap", "--", "/usr/local/bin/node", "/app/dist-server/cloud-home-start.js",
+ ]);
+});
+
+it("reads a capability bit the way the kernel writes it", () => {
+ expect(hasCapability(capStatus(WITH_SYS_ADMIN), "CapBnd", 21)).toBe(true);
+ expect(hasCapability(capStatus(FOUR), "CapBnd", 21)).toBe(false);
+ expect(hasCapability(capStatus(FOUR, WITH_SYS_ADMIN), "CapEff", 21)).toBe(true);
+ expect(hasCapability(capStatus("000001ffffffffff"), "CapBnd", 21)).toBe(true);
+ expect(hasCapability("", "CapBnd", 21)).toBe(false);
+});
+
+it("takes an own server's secrets from the root-only file the connector mounts, and only the secrets it knows", () => {
+ const file = "/run/mausbot/secrets.json";
+ const fs = (overrides: { file?: { uid: number; mode: number; symlink?: boolean }; dir?: { uid: number; mode: number }; text?: string; exists?: boolean } = {}) => ({
+ exists: () => overrides.exists ?? true,
+ lstat: () => {
+ const entry = overrides.file ?? { uid: 0, mode: 0o100400 };
+ return { ...entry, isFile: () => !entry.symlink, isSymbolicLink: () => Boolean(entry.symlink) };
+ },
+ stat: (path: string) => (path === file ? overrides.file ?? { uid: 0, mode: 0o100400 } : path === "/run/mausbot" ? overrides.dir ?? { uid: 0, mode: 0o40700 } : { uid: 0, mode: 0o40755 }),
+ read: () => overrides.text ?? JSON.stringify({ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_CLOUD_BOAT_TOKEN: `box_omb_${"b".repeat(43)}`, OMB_PUBLIC_URL: "https://elsewhere.example", PATH: "/tmp" }),
+ });
+ expect(readCloudSecretsFile("/data", file, fs())).toEqual({ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_CLOUD_BOAT_TOKEN: `box_omb_${"b".repeat(43)}` });
+ expect(readCloudSecretsFile("/data", file, fs({ exists: false }))).toEqual({});
+ expect(() => readCloudSecretsFile("/data", file, fs({ file: { uid: 0, mode: 0o100644 } }))).toThrow("readable by others than root");
+ expect(() => readCloudSecretsFile("/data", file, fs({ file: { uid: 1001, mode: 0o100400 } }))).toThrow(`${file} is not root's`);
+ expect(() => readCloudSecretsFile("/data", file, fs({ dir: { uid: 0, mode: 0o40777 } }))).toThrow("/run/mausbot is writable by others than root");
+ expect(() => readCloudSecretsFile("/data", file, fs({ file: { uid: 0, mode: 0o120777, symlink: true } }))).toThrow("is not a plain file");
+ expect(() => readCloudSecretsFile("/data", file, fs({ text: "[1]" }))).toThrow("is not a JSON object");
+ expect(() => readCloudSecretsFile("/data", "/data/secrets.json", fs())).toThrow("is on the volume");
});
it("boots as a Team Cloud with the Admin's team id and name, and refuses a team without them", () => {