Skip to content

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

Merge origin/main: the hardened launcher from 0.1.144, the tunnel token in the secrets file, HTTPS published on IPv4

milind-soni9771aca0c448
diff --cc connector/src/home.ts
index c3355ca435,d1236619b0..875d95bc03
--- a/connector/src/home.ts
+++ b/connector/src/home.ts
@@@ -9,8 -10,7 +10,8 @@@ import { digestPinnedOnly, type ImageCh
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, HARDENED_LAUNCHER_VERSION, HIDEPID_CAPABILITIES, HOME_CAPABILITIES, HOME_OOM_SCORE_ADJ, HOME_PORT, HOME_SECRET_ENV, HOME_SECRETS_DIR,
- 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_TLS_PORT,
+ 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";
@@@ -27,38 -26,20 +28,42 @@@ export function envDigest(env: Record<s
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 : []);
++ const tls = env.OMB_CLOUD_EDGE_TLS === "1";
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`]: {} },
++ ExposedPorts: { [`${HOME_PORT}/tcp`]: {}, ...(tls ? { [`${HOME_TLS_PORT}/tcp`]: {} } : {}) },
StopTimeout: HOME_STOP_TIMEOUT_S,
HostConfig: {
Init: true,
ShmSize: HOME_SHM_BYTES,
-- PortBindings: { [`${HOME_PORT}/tcp`]: [{ HostIp: "127.0.0.1", HostPort: String(HOME_PORT) }] },
- Mounts: [DATA],
++ PortBindings: {
++ [`${HOME_PORT}/tcp`]: [{ HostIp: "127.0.0.1", HostPort: String(HOME_PORT) }],
++ ...(tls ? { [`${HOME_TLS_PORT}/tcp`]: [{ HostIp: "0.0.0.0", HostPort: String(HOME_TLS_PORT) }] } : {}),
++ },
+ 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: [],
@@@ -544,7 -551,7 +588,8 @@@ export class Home
} catch (error) {
const message = errorText(error);
if (/port is already allocated|address already in use/i.test(message)) {
-- throw new JobFailure("port_in_use", `Port ${HOME_PORT} on this server's loopback is used by another program, and MausBot's home needs it.`);
++ const port = /:(\d+) failed/.exec(message)?.[1] ?? String(HOME_PORT);
++ throw new JobFailure("port_in_use", `Port ${port} on this server is used by another program, and MausBot's home needs it.`);
}
if (error instanceof DockerError && /apparmor|seccomp/i.test(message)) {
throw new JobFailure("box_unavailable", "The bot box's security profiles are not installed on this server. Run the install command again to repair it.");
diff --cc connector/src/protocol.ts
index c1dd66e24c,b11ec065ea..8f19f7a69c
--- a/connector/src/protocol.ts
+++ b/connector/src/protocol.ts
@@@ -207,7 -207,7 +207,7 @@@ export const REQUIRED_HOME_ENV = ["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_CLOUD_CAPS_DROPPED",
- "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", "OMB_CLOUD_TUNNEL_BIN",
]);
export type Checked<T> = { ok: true; value: T } | { ok: false; message: string };
diff --cc connector/src/settings.ts
index 8f74ec539a,891ba15dfe..23f1d6d927
--- a/connector/src/settings.ts
+++ b/connector/src/settings.ts
@@@ -38,8 -44,8 +44,12 @@@ export const AUDIT_FILE = "audit.jsonl"
export const SECCOMP_FILE = "seccomp-omb-home.json";
export const APPARMOR_PROFILE = "omb-home-narrow";
--/** Where the home's edge listens on the server: loopback only, reached by the tunnel and by the connector. */
++/** Where the home's edge listens on the server: loopback only, reached by the connector. */
export const HOME_PORT = 8080;
++/** With OMB_CLOUD_EDGE_TLS=1 the edge also serves HTTPS on the owner's domain here, published on IPv4 only: over IPv6, Docker's
++ * proxy on the default bridge hands every client the bridge's address, the connector's own, so one stranger's wrong
++ * pairing codes would lock out the Admin's signed pairing too. */
++export const HOME_TLS_PORT = 443;
/**
* On a stock Docker host the bot box needs our AppArmor and seccomp profiles and no masked /proc paths; the home needs
@@@ -55,25 -61,6 +65,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 HARDENED_LAUNCHER_VERSION = [0, 1, 144] 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",
++ "OMB_CLOUD_CONNECTED_APPS_GRANT", "OMB_CLOUD_X_TOKEN", "OMB_CLOUD_TUNNEL_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 --cc connector/test/home.test.ts
index d901404f6c,7d5aff6bca..cd6caf37ff
--- a/connector/test/home.test.ts
+++ b/connector/test/home.test.ts
@@@ -34,8 -34,12 +34,12 @@@ function fixture(options: { free?: numb
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"], [D, "v0.1.143"]] as const) docker.publish(ref, version);
- 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.144"]] as const) docker.publish(ref, version);
+ const healthy = new Set<string>([A, B, C, D]);
+ /** What each image's bot box reports; every check passes unless a test says otherwise. */
+ const boxes = new Map<string, { box: string; checks: string | null; failed: string[] }>();
+ const steps: string[] = [];
+ const refused = new Set<string>();
const lines: string[] = [];
const readHealth: HealthRead = async (target) => {
const home = docker.container("mausbot-home");
@@@ -126,60 -127,6 +132,76 @@@ 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;
+ // The host's path as Docker reports the state volume's mount point, with a / like any Linux path.
+ const secretsDir = `${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("publishes HTTPS on IPv4 when the home serves its own domain, and keeps the connector's loopback port", async () => {
++ const f = fixture();
++ const tunnel = "t".repeat(40);
++ await f.home.start("start-1", D, { ...env, OMB_CLOUD_EDGE_TLS: "1" });
++ const spec = f.docker.container("mausbot-home")!.spec;
++ expect(spec.HostConfig.PortBindings).toEqual({ "8080/tcp": [{ HostIp: "127.0.0.1", HostPort: "8080" }], "443/tcp": [{ HostIp: "0.0.0.0", HostPort: "443" }] });
++ expect(spec.ExposedPorts).toEqual({ "8080/tcp": {}, "443/tcp": {} });
++ expect(spec.Env).toContain("OMB_CLOUD_EDGE_TLS=1");
++ // A home reached through a tunnel publishes nothing more, and its token rides the secrets file, not the environment.
++ await f.home.start("start-2", D, { ...env, OMB_CLOUD_TUNNEL_TOKEN: tunnel });
++ const tunnelled = f.docker.container("mausbot-home")!.spec;
++ expect(tunnelled.HostConfig.PortBindings).toEqual({ "8080/tcp": [{ HostIp: "127.0.0.1", HostPort: "8080" }] });
++ expect(JSON.stringify(tunnelled)).not.toContain(tunnel);
++ expect(JSON.parse(readFileSync(join(f.state.dir, "home-secrets", "secrets.json"), "utf8")).OMB_CLOUD_TUNNEL_TOKEN).toBe(tunnel);
++ });
++
+ 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, 1, 143])).toEqual({ secretsFile: false, dropsCapabilities: false });
++ expect(launcherOf([0, 1, 144])).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", {});
@@@ -437,7 -439,7 +514,9 @@@
expect(failed.code).toBe("docker");
expect(JSON.stringify(failed.toJobError())).not.toContain(SECRET);
f.docker.startFailures.set("mausbot-home", "driver failed programming external connectivity: Bind for 127.0.0.1:8080 failed: port is already allocated");
-- expect((await failure(f.home.restart())).toJobError()).toEqual({ code: "port_in_use", message: "Port 8080 on this server's loopback is used by another program, and MausBot's home needs it." });
++ expect((await failure(f.home.restart())).toJobError()).toEqual({ code: "port_in_use", message: "Port 8080 on this server is used by another program, and MausBot's home needs it." });
++ f.docker.startFailures.set("mausbot-home", "driver failed programming external connectivity: Bind for 0.0.0.0:443 failed: port is already allocated");
++ expect((await failure(f.home.restart())).message).toBe("Port 443 on this server is used by another program, and MausBot's home needs it.");
f.docker.startFailures.set("mausbot-home", "OCI runtime create failed: apparmor failed to apply profile: write /proc/self/attr/apparmor/exec: no such file or directory");
expect((await failure(f.home.restart())).code).toBe("box_unavailable");
expect(existsSync(f.state.path("agent.json"))).toBe(false);
diff --cc connector/test/protocol.test.ts
index 2cc72c6d48,70dfc38c47..5bc8aeca10
--- a/connector/test/protocol.test.ts
+++ b/connector/test/protocol.test.ts
@@@ -1,8 -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 { CAPS_DROPPED_ENV, CLOUD_SECRETS_FILE, CLOUD_SECRETS_FILE_KEYS } 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";
@@@ -69,12 -67,6 +69,13 @@@ 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_SECRET_ENV].sort()).toEqual([...CLOUD_SECRETS_FILE_KEYS].sort());
++ expect(CLOUD_SECRETS_FILE_KEYS).toEqual(expect.arrayContaining([...CLOUD_HOME_SECRET_KEYS]));
+ 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 --cc server/cloud-home-start.ts
index 9037cee434,246b1e1927..3387c080e2
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@@ -3,14 -3,14 +3,15 @@@
// 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 { isIP } from "node:net";
import { dirname, join, posix, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
-- CLOUD_SECRETS_FD_ENV, cloudHomeConfiguration, cloudHomeHost, cloudHomeSecrets, prepareCloudHomeVolume,
++ CLOUD_HOME_SECRET_KEYS, 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";
@@@ -136,100 -224,25 +225,104 @@@ export function cloudHomeChildEnvironme
// 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),
...edgeClientAddress(env),
+ ...(edgeTerminatesTls(env) ? { OMB_CLOUD_EDGE_STORAGE: edgeCertificateStorage(home) } : {}),
};
- return { server, edge, secrets: cloudHomeSecrets(env), dropped };
+ return { server, edge, edgeFiles: edgeConfigFiles(env), tunnelToken: edgeTunnelToken(env), 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";
++/** What the file may hold: the server's secrets, and the tunnel's token, which only cloudflared gets. */
++export const CLOUD_SECRETS_FILE_KEYS = [...CLOUD_HOME_SECRET_KEYS, "OMB_CLOUD_TUNNEL_TOKEN"] as const;
+
+/** 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);
++ const record = parsed as Record<string, unknown>;
++ return Object.fromEntries(CLOUD_SECRETS_FILE_KEYS.flatMap((key) => (typeof record[key] === "string" && record[key] ? [[key, record[key] as string]] : [])));
}
/** Each file and every folder above it must be root's and not writable by others, and never on the `maus`-owned volume:
@@@ -276,6 -281,8 +369,7 @@@ export function startCloudHome(processE
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 { server, edge, edgeFiles, tunnelToken, secrets, dropped } = cloudHomeChildEnvironments(config, env, home);
const prepare = () => prepareCloudHomeData(home, cloudHomeDataDir(env, home), config.machineId);
let prepared: ReturnType<typeof prepare>;
let ids: { uid: number; gid: number } | null = null;
diff --cc server/cloud-home.test.ts
index 7b062fe515,151edaba2e..c8cfaedfed
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@@ -576,70 -577,13 +586,73 @@@ it("the Cloud supervisor hardens the ho
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" }),
++ read: () => overrides.text ?? JSON.stringify({
++ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_CLOUD_BOAT_TOKEN: `box_omb_${"b".repeat(43)}`, OMB_CLOUD_TUNNEL_TOKEN: "t".repeat(40),
++ 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())).toEqual({ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_CLOUD_BOAT_TOKEN: `box_omb_${"b".repeat(43)}`, OMB_CLOUD_TUNNEL_TOKEN: "t".repeat(40) });
+ 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", () => {