From 4b801f811e210aa0ae1ce71ed37e52553610fe43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Tue, 17 Nov 2026 19:07:40 +0100 Subject: [PATCH] Stop --chdir from binding the working directory read-write --- README.md | 6 +++- config-example.toml | 3 +- src/cli.rs | 2 +- src/sandbox.rs | 7 ----- tests/e2e/common.rs | 3 ++ tests/e2e/forwarding.rs | 3 +- tests/e2e/mounts.rs | 65 ++++++++++++++++++++++++++++++++++++----- tests/e2e/namespaces.rs | 4 +-- 8 files changed, 72 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 2298b3b..ec36e4e 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Sandbox agentic coding assistants with [bubblewrap](https://github.com/container ### Whitelist -Tight sandbox for normal agent coding tasks. Only explicitly listed paths are visible — system binaries, libraries, a subset of `/etc`, `/sys` (all read-only), synthetic `/dev`, private `/proc`, `/tmp`, `/run`, and the working directory (read-write). Everything else is invisible. Whitelist always runs with hardening on (see below). +Tight sandbox for normal agent coding tasks. Only explicitly listed paths are visible — system binaries, libraries, a subset of `/etc`, `/sys` (all read-only), synthetic `/dev`, private `/proc`, `/tmp` and `/run`. Everything else is invisible, including the working directory: bind it with `--rw .` (or `rw = ["$PWD"]` in the config). Whitelist always runs with hardening on (see below). ### Blacklist @@ -82,6 +82,10 @@ Every sandbox contains a read-only `/run/agent-sandbox/bwrap-args` holding the e A user `--rw`/`--ro` targeting `/run/agent-sandbox` overrides the directory, like any other built-in path. +## Working directory + +The sandbox starts in the directory agent-sandbox was launched from, or in `--chdir PATH` (`chdir` in the config). Neither makes that directory visible or writable; only `--ro` and `--rw` do. If nothing binds it, bwrap refuses to start with `Can't chdir to PATH: No such file or directory`. + ## Escape hatches When the agent needs access to something the sandbox blocks, use `--rw` or `--ro` for paths and `--setenv`/`--unsetenv` for env vars. User overrides always win over the built-in policies. diff --git a/config-example.toml b/config-example.toml index f5f5498..05ef43e 100644 --- a/config-example.toml +++ b/config-example.toml @@ -20,7 +20,7 @@ whitelist = true # seccomp = false # default: true # env-filter = false # default: true # dry-run = true -# chdir = "~/projects/my-repo" +# chdir = "~/projects/my-repo" # only sets the working directory; bind it with ro/rw ro = [ "~/.config/agents", @@ -29,6 +29,7 @@ ro = [ # "/host/path:/sandbox/path", # SRC:DST -> mount host SRC at a different target ] rw = [ + "$PWD", # the directory agent-sandbox was launched from "~/.cargo", "~/.rustup", ] diff --git a/src/cli.rs b/src/cli.rs index 82e0100..d81e1ca 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -79,7 +79,7 @@ pub struct Args { #[arg(long = "persistent-key", value_name = "LABEL")] pub persistent_key: Option, - /// Working directory inside the sandbox (default: current directory) + /// Working directory inside the sandbox (default: current directory); bind it with --ro or --rw #[arg(long, value_name = "PATH")] pub chdir: Option, diff --git a/src/sandbox.rs b/src/sandbox.rs index dc03549..aa806be 100644 --- a/src/sandbox.rs +++ b/src/sandbox.rs @@ -71,7 +71,6 @@ fn build_command( for spec in &config.extra_ro { add_ro_bind(&mut cmd, spec)?; } - add_rw_bind_path(&mut cmd, &config.chdir)?; for spec in &config.extra_rw { add_rw_bind(&mut cmd, spec)?; } @@ -307,12 +306,6 @@ fn add_ro_bind(cmd: &mut Command, spec: &BindSpec) -> Result<(), SandboxError> { Ok(()) } -fn add_rw_bind_path(cmd: &mut Command, path: &Path) -> Result<(), SandboxError> { - let source = resolve_bind_source(path)?; - cmd.arg("--bind").arg(source).arg(path); - Ok(()) -} - fn resolve_bind_source(path: &Path) -> Result { std::fs::canonicalize(path).map_err(|_| SandboxError::PathMissing(path.to_path_buf())) } diff --git a/tests/e2e/common.rs b/tests/e2e/common.rs index 92c285a..390ce8a 100644 --- a/tests/e2e/common.rs +++ b/tests/e2e/common.rs @@ -66,11 +66,14 @@ impl Sandbox { fn build(prefix: &[&str], extra_args: &[&str], guard: Option) -> Self { let mut cmd = Command::new(env!("CARGO_BIN_EXE_agent-sandbox")); cmd.args(prefix); + cmd.args(LAUNCH_DIR_WRITABLE); cmd.args(extra_args); Self { cmd, _guard: guard } } } +const LAUNCH_DIR_WRITABLE: [&str; 2] = ["--rw", "."]; + fn scan_guard_for(extra_args: &[&str]) -> Option { extra_args .contains(&"--blacklist") diff --git a/tests/e2e/forwarding.rs b/tests/e2e/forwarding.rs index d505fbe..ee633d9 100644 --- a/tests/e2e/forwarding.rs +++ b/tests/e2e/forwarding.rs @@ -171,9 +171,10 @@ fn interrupt_during_grace_period_kills_child_processes_at_once() { } fn spawn_sandbox(args: &[&str], dir: &Path, script: &str) -> (Sandbox, Child) { + let dir = dir.to_str().unwrap(); let mut sandbox = Sandbox::new(args); let child = sandbox - .args(["--chdir", dir.to_str().unwrap(), "--", "sh", "-c", script]) + .args(["--rw", dir, "--chdir", dir, "--", "sh", "-c", script]) .stdout(Stdio::null()) .spawn() .expect("agent-sandbox binary failed to execute"); diff --git a/tests/e2e/mounts.rs b/tests/e2e/mounts.rs index 299d3e9..2f06fc9 100644 --- a/tests/e2e/mounts.rs +++ b/tests/e2e/mounts.rs @@ -28,19 +28,65 @@ impl Drop for CleanupPath { } } #[test] -fn cwd_is_writable() { - let _cleanup = CleanupPath::new("./sandbox_canary"); +fn chdir_alone_makes_nothing_visible() { + let dir = TempDir::new().unwrap(); + let dir_str = dir.path().to_str().unwrap(); - let output = Sandbox::new(&[]) - .args(["--", "bash", "-c", "touch ./sandbox_canary && echo ok"]) + let output = Sandbox::new(&["--chdir", dir_str]) + .args(["--", "true"]) + .output() + .expect("agent-sandbox binary failed to execute"); + + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "chdir into an unbound path ran"); + assert!( + stderr.contains(&format!( + "Can't chdir to {dir_str}: No such file or directory" + )), + "expected bwrap's chdir error, got: {stderr}" + ); +} + +#[test] +fn chdir_under_ro_is_read_only() { + let dir = TempDir::new().unwrap(); + let dir_str = dir.path().to_str().unwrap(); + + let output = Sandbox::new(&["--ro", dir_str, "--chdir", dir_str]) + .args([ + "--", + "bash", + "-c", + "touch canary 2>/dev/null || echo readonly", + ]) .output() .expect("agent-sandbox binary failed to execute"); let stdout = String::from_utf8_lossy(&output.stdout); assert!( - stdout.contains("ok"), - "expected 'ok' in stdout, got: {stdout}" + stdout.contains("readonly"), + "expected 'readonly' in stdout, got: {stdout}, stderr: {}", + String::from_utf8_lossy(&output.stderr) ); + assert!(!dir.path().join("canary").exists()); +} + +#[test] +fn chdir_under_rw_is_writable() { + let dir = TempDir::new().unwrap(); + let dir_str = dir.path().to_str().unwrap(); + + let output = Sandbox::new(&["--rw", dir_str, "--chdir", dir_str]) + .args(["--", "touch", "canary"]) + .output() + .expect("agent-sandbox binary failed to execute"); + + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(dir.path().join("canary").exists()); } #[test] @@ -647,7 +693,7 @@ fn persistent_tmp_resumes_with_explicit_key_matching_derived_hash() { let _cleanup_tmp = CleanupPath::new(format!("/tmp/agent-sandbox-{key}")); let _cleanup_var = CleanupPath::new(format!("/var/tmp/agent-sandbox-{key}")); - let writer = Sandbox::new(&["--persistent-tmp", "--chdir", chdir_str]) + let writer = Sandbox::new(&["--persistent-tmp", "--ro", chdir_str, "--chdir", chdir_str]) .args(["--", "bash", "-c", "echo persisted > /tmp/canary"]) .output() .expect("write run failed"); @@ -660,12 +706,15 @@ fn persistent_tmp_resumes_with_explicit_key_matching_derived_hash() { // Second run: different chdir (would have derived a different hash) plus an // extra flag, but an explicit key pinning the same host directory. let other_chdir = TempDir::new().unwrap(); + let other_chdir_str = other_chdir.path().to_str().unwrap(); let reader = Sandbox::new(&[ "--persistent-tmp", "--persistent-key", &key, + "--ro", + other_chdir_str, "--chdir", - other_chdir.path().to_str().unwrap(), + other_chdir_str, "--unshare-net", ]) .args(["--", "cat", "/tmp/canary"]) diff --git a/tests/e2e/namespaces.rs b/tests/e2e/namespaces.rs index 1fe882f..5ad5bf0 100644 --- a/tests/e2e/namespaces.rs +++ b/tests/e2e/namespaces.rs @@ -65,7 +65,7 @@ fn chdir_override() { let dir = TempDir::new().expect("failed to create temp dir"); let dir_str = dir.path().to_str().unwrap(); - let output = Sandbox::new(&["--chdir", dir_str]) + let output = Sandbox::new(&["--ro", dir_str, "--chdir", dir_str]) .args(["--", "bash", "-c", "pwd"]) .output() .expect("agent-sandbox binary failed to execute"); @@ -82,7 +82,7 @@ fn chdir_under_hardened_tmp() { let dir = TempDir::new().expect("failed to create temp dir"); let dir_str = dir.path().to_str().unwrap(); - let output = Sandbox::new(&["--hardened", "--chdir", dir_str]) + let output = Sandbox::new(&["--hardened", "--rw", dir_str, "--chdir", dir_str]) .args(["--", "bash", "-c", "pwd && touch ./ok && echo done"]) .output() .expect("agent-sandbox binary failed to execute");