Skip to content

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

Bot box: the server's own spawns never look a program up in HOME (#5297)

Milind Soni6b0cead52530
diff --git a/server/bot-box/boot.ts b/server/bot-box/boot.ts
index 74dcddd252..d9c871de82 100644
--- a/server/bot-box/boot.ts
+++ b/server/bot-box/boot.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { CONTROL_PLANE_ENV, WORKSPACE_CREDENTIAL_ENV } from "../config.ts";
import { BOX_BRIDGE_SCRIPT, botBox, type BotBox } from "./box.ts";
+import { serverPath } from "./program-trust.ts";
import { runBoxSelfCheck } from "./self-check.ts";
export { botBox };
@@ -28,6 +29,8 @@ export async function startBotBoxAtBoot(options: {
const box = options.box ?? botBox;
const log = options.log ?? ((line: string) => console.log(line));
const detection = await box.start({ dataDir: options.dataDir, home: options.home ?? homedir(), port: options.port, denyEnv: BOX_DENY_ENV, log });
+ // What the server starts with no PATH of its own (a plain spawn) finds nothing in HOME either.
+ if (box === botBox && box.enabled()) process.env.PATH = serverPath(process.env.PATH);
if (detection.box !== "bwrap" || !detection.tools || options.selfCheck === false) return;
const tools = detection.tools;
const timer = setTimeout(() => {
diff --git a/server/bot-box/box.ts b/server/bot-box/box.ts
index 0de2a40f38..61be4bd766 100644
--- a/server/bot-box/box.ts
+++ b/server/bot-box/box.ts
@@ -7,6 +7,7 @@ import { closeSync, existsSync, mkdirSync, openSync, rmSync, statSync, writeFile
import { dirname, join, resolve } from "node:path";
import { engineInstallRoots } from "../engine-roots.ts";
+import { homeProgramDirs, resetPathCache } from "../env-path.ts";
import { SERVER_ROOT, resolveProxy } from "../proxy-paths.ts";
import { bridgedCommand, type BridgeTools } from "./bridge.ts";
import { brokerRewrite } from "./broker-env.ts";
@@ -15,6 +16,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 { distrustHomePrograms } from "./program-trust.ts";
import { procHidepid } from "./hidepid.ts";
import { DENIED_SYSCALLS, seccompBytes, seccompSupported } from "./seccomp.ts";
import { RELAY_SOCKET_NAME, boxUploadsDir, bwrapArgs, inBoxSocket, planBox, taskWorkspaceIds, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";
@@ -102,6 +104,9 @@ export class BoxRunner {
const env = mutate?.has("env-all")
? Object.fromEntries(Object.entries(request.env).filter((entry): entry is [string, string] => entry[1] !== undefined))
: boxEnvironment(request.env, this.options.denyEnv, new Set(request.allowEnv ?? []));
+ // The server's own PATH leaves out the programs in HOME (program-trust.ts); inside the box they are the bot's own.
+ const homePrograms = homeProgramDirs(resolve(request.home ?? this.options.setup.home)).filter((dir) => !(env.PATH ?? "").split(":").includes(dir));
+ if (homePrograms.length) env.PATH = [...(env.PATH ? [env.PATH] : []), ...homePrograms].join(":");
if (plan.net === "isolated") {
const proxy = `http://127.0.0.1:${this.options.egressPort ?? BOX_EGRESS_PORT}`;
for (const name of BOX_PROXY_ENV) env[name] = proxy;
@@ -235,6 +240,8 @@ export class BotBox {
denyEnv: options.denyEnv, seccompFile: this.seccompFile,
broker: { port: BOX_BROKER_PORT, mintForProcess: this.credentials.mintForProcess, revoke: this.credentials.revoke },
});
+ distrustHomePrograms(options.home, [options.dataDir], ["workspaces", "task-workspaces", "engine-homes"].map((name) => join(options.dataDir, name)));
+ resetPathCache();
log(`bot box: on (bubblewrap, ${this.detection.tools.socat ? "socat" : "node"} bridges, credential broker, seccomp ${this.seccompFile ? "on" : "unsupported here"})`);
return this.detection;
}
@@ -313,6 +320,8 @@ export class BotBox {
this.credentials = null;
this.seccompFile = null;
this.runner = null;
+ distrustHomePrograms(null);
+ resetPathCache();
}
}
diff --git a/server/bot-box/program-trust.test.ts b/server/bot-box/program-trust.test.ts
new file mode 100644
index 0000000000..58a2389309
--- /dev/null
+++ b/server/bot-box/program-trust.test.ts
@@ -0,0 +1,118 @@
+import { chmodSync, mkdirSync, readFileSync, existsSync, rmSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { delimiter, join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { augmentedPath, findCliCandidates, registerPathDir, resetPathCacheForTests } from "../env-path.ts";
+import { execCli, spawnCli } from "../procs.ts";
+import { BoxRunner } from "./box.ts";
+import { distrustHomePrograms, serverMayRunFrom, serverPath } from "./program-trust.ts";
+
+const posix = process.platform !== "win32";
+
+function plant(dir: string, name: string, marker: string): string {
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, name);
+ writeFileSync(file, `#!/bin/sh\necho "$0" >> "${marker}"\necho 9.9.9\n`);
+ chmodSync(file, 0o755);
+ return file;
+}
+
+function run(cli: string, env: NodeJS.ProcessEnv): Promise<{ error: (Error & { code?: unknown }) | null; stdout: string }> {
+ return new Promise((resolve) => execCli(cli, ["--version"], { env, timeout: 10_000 }, (error, stdout) => resolve({ error, stdout })));
+}
+
+afterEach(() => {
+ distrustHomePrograms(null);
+ resetPathCacheForTests();
+});
+
+describe("programs a boxed bot could have written", () => {
+ it("are trusted everywhere while the box is off", () => {
+ expect(serverMayRunFrom("/data/.local/bin")).toBe(true);
+ expect(serverPath("/usr/bin:/data/.local/bin")).toBe("/usr/bin:/data/.local/bin");
+ });
+
+ it("while the box is on: nothing under HOME but the data folder, and no relative folder", () => {
+ distrustHomePrograms("/data", ["/data/.openmausbot"], ["/data/.openmausbot/workspaces", "/srv/omb/task-workspaces"]);
+ expect(serverMayRunFrom("/data/.openmausbot/workspaces/b1/tool")).toBe(false);
+ expect(serverMayRunFrom("/srv/omb/task-workspaces/b1/t1/tool")).toBe(false);
+ expect(serverMayRunFrom("/data/.local/bin")).toBe(false);
+ expect(serverMayRunFrom("/data/.local/bin/pi")).toBe(false);
+ expect(serverMayRunFrom("/data")).toBe(false);
+ expect(serverMayRunFrom("/data/.openmausbot/tools/npm/bin")).toBe(true);
+ expect(serverMayRunFrom("/database/bin")).toBe(true);
+ expect(serverMayRunFrom("/usr/local/bin")).toBe(true);
+ expect(serverMayRunFrom("bin")).toBe(false);
+ expect(serverPath(["/data/.openmausbot/tools/npm/bin", "/usr/local/bin", "/data/.local/bin", "", ".", "/usr/bin", "/data/bin"].join(delimiter)))
+ .toBe(["/data/.openmausbot/tools/npm/bin", "/usr/local/bin", "/usr/bin"].join(delimiter));
+ });
+
+ it.skipIf(!posix)("the server's PATH keeps the app's own engines and the system's, never HOME's program folders", () => {
+ const home = homedir();
+ const dataDir = join(home, ".openmausbot");
+ const marker = join(home, "ran");
+ plant(join(home, ".local", "bin"), "omb-planted-engine", marker);
+ plant(join(home, ".opencode", "bin"), "omb-planted-engine-2", marker);
+ const appBin = join(dataDir, "tools", "npm", "bin");
+ plant(appBin, "omb-app-engine", marker);
+ registerPathDir(appBin);
+ expect(findCliCandidates("omb-planted-engine")).toHaveLength(1);
+
+ distrustHomePrograms(home, [dataDir]);
+ resetPathCacheForTests();
+ registerPathDir(appBin);
+ const parts = augmentedPath().split(delimiter);
+ expect(parts).toContain(appBin);
+ expect(parts.some((dir) => dir === join(home, ".local", "bin") || dir === join(home, ".opencode", "bin"))).toBe(false);
+ expect(findCliCandidates("omb-planted-engine")).toEqual([]);
+ expect(findCliCandidates("omb-planted-engine-2")).toEqual([]);
+ expect(findCliCandidates("omb-app-engine")).toEqual([join(appBin, "omb-app-engine")]);
+ });
+
+ it.skipIf(!posix)("an unboxed spawn neither finds a program in HOME on the PATH it is given nor starts one by its path", async () => {
+ const home = homedir();
+ const dataDir = join(home, ".openmausbot");
+ const marker = join(home, "ran-spawn");
+ rmSync(marker, { force: true });
+ const planted = plant(join(home, ".local", "bin"), "omb-planted-cli", marker);
+ const appCli = plant(join(dataDir, "tools", "npm", "bin"), "omb-app-cli", marker);
+ const linked = join(dataDir, "tools", "npm", "bin", "omb-linked-cli");
+ rmSync(linked, { force: true });
+ (await import("node:fs")).symlinkSync(planted, linked);
+ const env = { ...process.env, PATH: [join(home, ".local", "bin"), join(dataDir, "tools", "npm", "bin"), "/usr/bin", "/bin"].join(delimiter) };
+ distrustHomePrograms(home, [dataDir]);
+
+ const byName = await run("omb-planted-cli", env);
+ expect((byName.error as NodeJS.ErrnoException | null)?.code).toBe("ENOENT");
+ const byPath = await run(planted, env);
+ expect((byPath.error as NodeJS.ErrnoException | null)?.code).toBe("EACCES");
+ const byLink = await run(linked, env);
+ expect((byLink.error as NodeJS.ErrnoException | null)?.code).toBe("EACCES");
+ expect(() => spawnCli(planted, ["--version"], { env, stdio: ["pipe", "pipe", "pipe"] })).toThrow(/bots can write/);
+ expect(existsSync(marker)).toBe(false);
+
+ const app = await run("omb-app-cli", env);
+ expect(app.error).toBeNull();
+ expect(app.stdout.trim()).toBe("9.9.9");
+ expect(readFileSync(marker, "utf8").trim()).toBe(appCli);
+
+ distrustHomePrograms(null);
+ const before = await run("omb-planted-cli", env);
+ expect(before.error).toBeNull();
+ });
+
+ it.skipIf(!posix)("a boxed process keeps HOME's program folders on its own PATH, after the server's", () => {
+ const home = homedir();
+ mkdirSync(join(home, ".local", "bin"), { recursive: true });
+ const runner = new BoxRunner({
+ bwrap: "/usr/bin/bwrap", bridge: { socat: null, bridgeScript: "/x/bridge.js", node: "/usr/bin/node" },
+ setup: { dataDir: join(home, ".openmausbot"), home, codeRoots: [], engineRoots: [], bridges: [] }, denyEnv: new Set(),
+ });
+ distrustHomePrograms(home, [join(home, ".openmausbot")]);
+ const wrapped = runner.wrap({ command: "/usr/bin/true", args: [], env: { PATH: "/usr/bin:/bin", HOME: home }, net: "shared" });
+ const path = wrapped.env.PATH!.split(delimiter);
+ expect(path.slice(0, 2)).toEqual(["/usr/bin", "/bin"]);
+ expect(path).toContain(join(home, ".local", "bin"));
+ });
+});
diff --git a/server/bot-box/program-trust.ts b/server/bot-box/program-trust.ts
new file mode 100644
index 0000000000..5ac64fb930
--- /dev/null
+++ b/server/bot-box/program-trust.ts
@@ -0,0 +1,41 @@
+// Security: while the bot box is on, a boxed bot can write the server's HOME (plan.ts binds it read-write). The server's
+// own processes run outside the box, so they must never look a program up in a folder there, nor start one from there:
+// a program a bot left in ~/.local/bin would otherwise run outside the box at the next engine status read. The data
+// folder is the exception: the box replaces it with an empty one, and the engines the app installs there are read-only.
+import { realpathSync } from "node:fs";
+import { delimiter, isAbsolute, resolve } from "node:path";
+
+import { under } from "./plan.ts";
+
+let distrusted: { homes: readonly string[]; kept: readonly string[]; bots: readonly string[] } | null = null;
+
+/** A folder as given and as the filesystem names it, so a link's target is judged by where it really is. */
+function bothNames(dir: string): string[] {
+ const given = resolve(dir);
+ try { return [...new Set([given, realpathSync(given)])]; } catch { return [given]; }
+}
+
+/** Called with the server's HOME when the box goes on, and with null when it stops. `kept`: folders under HOME no bot
+ * can write (the data folder); `bots`: the folders in it bots do write (their workspaces, a Team Cloud's engine homes). */
+export function distrustHomePrograms(home: string | null, kept: readonly string[] = [], bots: readonly string[] = []): void {
+ distrusted = home ? { homes: bothNames(home), kept: kept.flatMap(bothNames), bots: bots.flatMap(bothNames) } : null;
+}
+
+export function homeProgramsDistrusted(): boolean {
+ return distrusted !== null;
+}
+
+/** Whether the server may run a program from `path` (a folder or a file) outside the box. */
+export function serverMayRunFrom(path: string): boolean {
+ if (!distrusted) return true;
+ if (!isAbsolute(path)) return false;
+ const full = resolve(path);
+ if (distrusted.bots.some((dir) => under(full, dir))) return false;
+ return !distrusted.homes.some((home) => under(full, home)) || distrusted.kept.some((dir) => under(full, dir));
+}
+
+/** `path` without the folders the server may not run programs from. */
+export function serverPath(path: string | undefined): string {
+ if (!distrusted) return path ?? "";
+ return (path ?? "").split(delimiter).filter((dir) => dir && serverMayRunFrom(dir)).join(delimiter);
+}
diff --git a/server/env-path.ts b/server/env-path.ts
index be5fe724cf..e6782957a7 100644
--- a/server/env-path.ts
+++ b/server/env-path.ts
@@ -4,11 +4,12 @@ import { execFile } from "node:child_process";
import { closeSync, existsSync, openSync, readFileSync, readSync, statSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { basename, delimiter, dirname, extname, join } from "node:path";
+import { homeProgramsDistrusted, serverMayRunFrom } from "./bot-box/program-trust.ts";
import { resolvePortableHermes } from "./portable-hermes.ts";
-function nvmBinDirs(): string[] {
+function nvmBinDirs(home: string): string[] {
try {
- const base = join(homedir(), ".nvm", "versions", "node");
+ const base = join(home, ".nvm", "versions", "node");
return readdirSync(base)
.filter((v) => v.startsWith("v"))
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
@@ -23,8 +24,7 @@ export function sealedFixture(): boolean {
return process.env.OMB_TEST_SEALED_PATH === "1";
}
-function knownDirs(): string[] {
- const home = homedir();
+function knownDirs(home: string = homedir()): string[] {
return [
join(home, ".local", "bin"), // claude installer default
join(home, ".npm-global", "bin"), // npm prefix ~/.npm-global (claude, opencode)
@@ -42,7 +42,7 @@ function knownDirs(): string[] {
join(home, ".local", "share", "mise", "shims"), // mise installer
join(home, ".deno", "bin"),
join(home, "bin"),
- ...nvmBinDirs(),
+ ...nvmBinDirs(home),
// Mac Local VM runtimes: Docker Desktop's per-user CLI install and Podman's official pkg.
...(process.platform === "darwin" ? [
join(home, ".docker", "bin"),
@@ -103,6 +103,11 @@ export function resetPathCache(): void {
probed = false;
}
+/** The folders under `home` that CLI installers put programs in, which exist: a boxed process's own PATH keeps them. */
+export function homeProgramDirs(home: string): string[] {
+ return (process.platform === "win32" ? [] : knownDirs(home)).filter((dir) => dir.startsWith(`${home}/`) && existsSync(dir));
+}
+
export function augmentedPath(): string {
if (cached === null) {
const fallback = fallbackDirs.filter((d) => existsSync(d));
@@ -113,9 +118,10 @@ export function augmentedPath(): string {
// Keep the last login-shell result while a rescan re-probes, or rc-only CLIs vanish for the response that triggered it.
...(loginShellPath ? loginShellPath.split(delimiter) : []),
...(process.platform === "win32" ? windowsKnownDirs() : knownDirs()).filter((d) => existsSync(d)),
- ].filter((d) => !fallback.includes(d)).concat(fallback));
+ ].filter((d) => !fallback.includes(d)).concat(fallback).filter(serverMayRunFrom));
}
- if (!probed && !process.env.VITEST && !sealedFixture() && process.platform !== "win32") {
+ // The login shell reads its rc files from HOME, which a boxed bot can write.
+ if (!probed && !process.env.VITEST && !sealedFixture() && process.platform !== "win32" && !homeProgramsDistrusted()) {
probed = true;
probeLoginShellPath();
}
@@ -140,7 +146,7 @@ function probeLoginShellPath(): void {
loginShellPath = m[1];
// Fallback dirs stay last, behind what the person's shell adds.
const fallback = fallbackDirs.filter((d) => existsSync(d));
- cached = mergePaths([...(cached ?? "").split(delimiter).filter((d) => !fallback.includes(d)), ...m[1].split(delimiter), ...fallback]);
+ cached = mergePaths([...(cached ?? "").split(delimiter).filter((d) => !fallback.includes(d)), ...m[1].split(delimiter), ...fallback].filter(serverMayRunFrom));
},
);
}
diff --git a/server/procs.ts b/server/procs.ts
index a125581e6d..33eb014f10 100644
--- a/server/procs.ts
+++ b/server/procs.ts
@@ -9,11 +9,12 @@ import {
type ExecFileOptions,
type SpawnOptions,
} from "node:child_process";
-import { closeSync, existsSync, readdirSync, readFileSync } from "node:fs";
+import { closeSync, existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import type { Readable, Writable } from "node:stream";
import { basename, dirname, join, resolve } from "node:path";
import { botBox, type WrappedSpawn } from "./bot-box/box.ts";
import type { BoxRequest } from "./bot-box/plan.ts";
+import { homeProgramsDistrusted, serverMayRunFrom, serverPath } from "./bot-box/program-trust.ts";
import { engineMemory } from "./engine-memory.ts";
import { engineHomes } from "./engine-homes/engine-homes.ts";
import type { HomedSpawn } from "./engine-homes/layout.ts";
@@ -198,6 +199,22 @@ export function sharedBoxScope(cwd: string): string | null {
return basename(dirname(parent)) === "task-workspaces" ? parent : resolve(cwd);
}
+/** Security (bot-box/program-trust.ts): a spawn outside the box neither starts a program from a folder a boxed bot can
+ * write nor looks one up there. */
+export function outsideBoxOptions<T extends { env?: NodeJS.ProcessEnv; cwd?: string | URL }>(command: string, opts: T): T {
+ if (!homeProgramsDistrusted()) return opts;
+ if (/[/\\]/.test(command)) {
+ const path = resolve(typeof opts.cwd === "string" ? opts.cwd : process.cwd(), command);
+ let real = path;
+ try { real = realpathSync(path); } catch {}
+ if (!serverMayRunFrom(path) || !serverMayRunFrom(real)) {
+ throw Object.assign(new Error(`${command} is in a folder the bots can write, so the server does not run it outside the bot box.`), { code: "EACCES" });
+ }
+ }
+ const env = opts.env ?? process.env;
+ return { ...opts, env: { ...env, PATH: serverPath(env.PATH) } };
+}
+
export function spawnCli(
cli: string,
args: string[],
@@ -209,7 +226,7 @@ export function spawnCli(
const homed = owner === "bot" || opts.engineHome ? engineHomes.forSpawn(opts.env ?? process.env) : null;
const options: CliSpawnOptions = homed ? { ...opts, env: homed.env } : opts;
const boxed = boxedSpawn(resolved, options, owner, homed);
- const { box: _box, engineHome: _engineHome, botWork, ...spawnOpts } = options;
+ const { box: _box, engineHome: _engineHome, botWork, ...spawnOpts } = boxed ? options : outsideBoxOptions(resolved.command, options);
// The box's extra descriptors (its seccomp filter) follow stdio; only a plain three-entry stdio can take them.
const stdio = boxed?.extraFds.length && Array.isArray(spawnOpts.stdio) && spawnOpts.stdio.length === 3 ? [...spawnOpts.stdio, ...boxed.extraFds] : spawnOpts.stdio;
const start = () => spawn(boxed?.command ?? resolved.command, boxed?.args ?? resolved.args, {
@@ -257,6 +274,7 @@ export function execCli(
const resolved = resolveCli(cli, args);
try {
assertSafeCliArgv(resolved);
+ opts = outsideBoxOptions(resolved.command, opts);
} catch (error) {
queueMicrotask(() => cb(error instanceof Error ? error : new Error(String(error)), "", ""));
return;