From 7e0a2bfa1630ca5c3a5bd2c71adc123fa0c48089 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 13:19:04 +0000 Subject: [PATCH 1/2] sandbox: sbx, a standalone sandbox any agent can run under crates/sandbox builds `sbx` and the `incord_sandbox` library, with no dependency on incode, so incode, Insi or any other agent CLI can run a command under one policy file: - filesystem: writable roots, and `deny_read` for paths that must not even be read (a benchmark's hidden tests). Landlock on Linux, carving a hidden path out by granting its siblings level by level; Seatbelt on macOS. - network: allow, deny, or an allowlisting HTTP/CONNECT proxy run in the unconfined parent. The kernel lets the command reach only the proxy's port. The proxy resolves each name once and refuses private answers unless allowed, and chains through an upstream proxy when sbx sits behind one. - environment: the agent-session variables (CLAUDECODE, CLAUDE_CODE_SESSION*, ...) and git redirects (GIT_DIR, ...) are stripped by default; credentials are kept; inherit = "none" keeps only the essentials and what is passed. - limits: setrlimit (cpu, memory, file size, open files) and a wall clock that kills the whole process group. Signals to sbx are forwarded, and a supervisor kills the group if sbx itself is SIGKILLed. - a private TMPDIR per run. Strict by default: a policy this machine cannot enforce in full is refused (exit 125) rather than run with less. `sbx doctor` and `sbx check --json` say what is enforced and how. Escape tests (Linux, through the real binary) cover: - writes outside the root, symlinks, hard links, renames, /proc/self/root, children; - reading a hidden path by six routes; - connect and bind under deny, and bypassing the proxy; - the wall limit, SIGKILL cleanup, limits and exit codes. clippy is clean for Linux, macOS and Windows targets. CI now runs the crate's clippy and tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- .github/workflows/ci.yml | 4 + Cargo.lock | 12 + Cargo.toml | 1 + README.md | 20 + crates/sandbox/Cargo.toml | 32 ++ crates/sandbox/README.md | 146 ++++++ crates/sandbox/src/env.rs | 204 ++++++++ crates/sandbox/src/lib.rs | 828 +++++++++++++++++++++++++++++++++ crates/sandbox/src/limits.rs | 73 +++ crates/sandbox/src/linux.rs | 293 ++++++++++++ crates/sandbox/src/main.rs | 291 ++++++++++++ crates/sandbox/src/policy.rs | 400 ++++++++++++++++ crates/sandbox/src/proxy.rs | 728 +++++++++++++++++++++++++++++ crates/sandbox/src/seatbelt.rs | 118 +++++ crates/sandbox/tests/escape.rs | 374 +++++++++++++++ 15 files changed, 3524 insertions(+) create mode 100644 crates/sandbox/Cargo.toml create mode 100644 crates/sandbox/README.md create mode 100644 crates/sandbox/src/env.rs create mode 100644 crates/sandbox/src/lib.rs create mode 100644 crates/sandbox/src/limits.rs create mode 100644 crates/sandbox/src/linux.rs create mode 100644 crates/sandbox/src/main.rs create mode 100644 crates/sandbox/src/policy.rs create mode 100644 crates/sandbox/src/proxy.rs create mode 100644 crates/sandbox/src/seatbelt.rs create mode 100644 crates/sandbox/tests/escape.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 41e172b..493f312 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,10 @@ jobs: - run: cargo clippy --all-targets - run: cargo test --lib - run: cargo test --bins + # The standalone sandbox (`sbx`). Its escape tests are Linux-only and + # skip, saying so, on a kernel without Landlock. + - run: cargo clippy -p incord-sandbox --all-targets -- -D warnings + - run: cargo test -p incord-sandbox # A test that writes outside its temp dir lands in the checkout — a # Windows drive path is RELATIVE on Linux and macOS — and passes anyway. # Only a clean tree after the run catches it. diff --git a/Cargo.lock b/Cargo.lock index 250a3b5..8e8acfd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2039,6 +2039,18 @@ dependencies = [ "zip", ] +[[package]] +name = "incord-sandbox" +version = "0.1.0" +dependencies = [ + "landlock", + "libc", + "serde", + "serde_json", + "tempfile", + "toml", +] + [[package]] name = "indexmap" version = "1.9.3" diff --git a/Cargo.toml b/Cargo.toml index c7a364a..f94cb1a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [workspace] +members = [".", "crates/sandbox"] # Standalone workspace root. The crate previously inherited version/edition from # a parent workspace that does not exist, so cargo failed while parsing the # manifest, before it could even look at the source. diff --git a/README.md b/README.md index 4588048..4a1b2c7 100644 --- a/README.md +++ b/README.md @@ -740,6 +740,26 @@ confined only when named; the operator's own `/bg` jobs at the REPL are never sandboxed. Where a mode cannot be applied, the command runs unconfined and the trace says which. +### `sbx`: the same sandbox for any agent + +`crates/sandbox` builds `sbx`, a standalone sandbox that doesn't depend on +incode. It runs any command, whether an agent CLI, a test suite or Insi's +workers, under one policy file: +- writable roots, plus paths hidden even from reading (`deny_read`); +- network `allow`, `deny`, or an allowlisting proxy by host name; +- the agent-session and `GIT_DIR` variables stripped; +- CPU, memory, file-size and wall-clock limits. + +It refuses a policy the machine cannot enforce in full instead of running +with less. To confine a whole incode run: + +```sh +sbx run -w . -w ~/.claude -w ~/.claude.json -w ~/.incode --wall 1800 -- incode -t "…" +``` + +Details, the policy format and what each OS enforces are in +[`crates/sandbox/README.md`](crates/sandbox/README.md). + ## Incord Memory integration Every part is optional and fails open, except the owner channel, which fails diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml new file mode 100644 index 0000000..83c6a04 --- /dev/null +++ b/crates/sandbox/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "incord-sandbox" +version = "0.1.0" +edition = "2021" +rust-version = "1.88" +license = "Apache-2.0" +description = "Run any command - an agent CLI, a test suite, a tool call - under one policy file: filesystem, network, environment and resource limits" +repository = "https://github.com/incordai/Incode" +keywords = ["sandbox", "landlock", "seatbelt", "agents", "security"] +categories = ["command-line-utilities", "os"] + +[lib] +name = "incord_sandbox" +path = "src/lib.rs" + +[[bin]] +name = "sbx" +path = "src/main.rs" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(target_os = "linux")'.dependencies] +landlock = "=0.4.7" + +[dev-dependencies] +tempfile = "3" diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md new file mode 100644 index 0000000..9b315b2 --- /dev/null +++ b/crates/sandbox/README.md @@ -0,0 +1,146 @@ +# sbx: one sandbox for any agent + +`sbx` runs a command under one policy: what it may write, what it may read, +which hosts it may reach, which environment it starts with, and how much it +may use. It works with any agent CLI (`claude`, `codex`, `incode`, `aider`, +…), with a test suite a harness runs, or with a single tool call. The policy +means the same thing on every platform. Where a platform cannot enforce part +of it, `sbx` says so before anything runs. By default it then refuses +instead of running with less. + +```sh +# Write only in this project; network only to the package registry; 30 minutes. +sbx run -w . --allow-host crates.io --allow-host '*.crates.io' --wall 1800 -- cargo build + +# An agent CLI confined to its workspace, with a folder it must not see. +sbx run -w . -w ~/.claude -w ~/.claude.json --deny-read ../private-checks -- claude -p "fix the failing test" + +# What would this machine enforce? +sbx doctor +sbx check --policy agent.toml --json +``` + +It's a crate in the incode repository for now and doesn't depend on incode. +It builds to one binary, `sbx`, and a library, `incord_sandbox`. + +## The policy file + +```toml +[fs] +mode = "workspace-write" # off | read-only | workspace-write +write = ["."] # writable roots +deny_read = ["../private"] # hidden: not even readable + +[network] +mode = "proxy" # allow | deny | proxy +allow = ["crates.io", "*.crates.io:443", "registry.npmjs.org"] +allow_private = false # may an allowed name resolve to a private address? + +[env] +inherit = "all" # all | none (essentials kept) +pass = ["ANTHROPIC_API_KEY"] # kept when inherit = "none" +remove = ["AWS_*"] # a trailing * matches a prefix +strip_agent_session = true # CLAUDECODE, CLAUDE_CODE_SESSION*, ... (default) +strip_git_redirects = true # GIT_DIR, GIT_WORK_TREE, ... (default) +set = { CI = "1" } + +[limits] +wall_secs = 1800 # the whole process group is killed +cpu_secs = 1200 # per process +memory_mb = 4096 # address space per process +file_size_mb = 1024 +open_files = 4096 +``` + +Every flag of `sbx run` has a policy key. Flags apply on top of `--policy`. +An unknown key is an error, so a misspelt `wirte` can't silently do nothing. + +## What is enforced, and how + +| | Linux | macOS | Windows | +|---|---|---|---| +| filesystem: write | Landlock (5.13+) | Seatbelt | **not yet** | +| filesystem: `deny_read` | Landlock | Seatbelt | **not yet** | +| network: `deny` | Landlock TCP (6.7+) | Seatbelt | **not yet** | +| network: `proxy` | Landlock: TCP only to the proxy's port | Seatbelt: outbound only to the proxy | **not yet** | +| limits | `setrlimit` + wall clock | `setrlimit` + wall clock | wall clock | +| environment | yes | yes | yes | + +- **Every process it starts.** The confinement is applied in a helper + process just before it execs the command. Children inherit it, and it + can't be widened again (`no_new_privs` is set). +- **A private temp directory.** Each run gets one (`TMPDIR`, `TMP`, + `TEMP`), removed afterwards. The shared `/tmp` is not writable. +- **The proxy.** `proxy` mode runs an allowlisting HTTP proxy in the + unconfined parent and points the command at it (`HTTP(S)_PROXY`). + - It sees host names, not content: TLS is tunnelled with `CONNECT`. + - It resolves each name once and connects to the checked address, so DNS + can't redirect an allowed name to a private address or the cloud + metadata service. Turn this check off with `allow_private`. + - When `sbx` itself runs behind an HTTP proxy, allowed requests are chained + through it, and that proxy does the resolving. +- **`deny_read`.** Landlock only grants, so a hidden path is carved out by + granting its siblings, level by level from `/`. + - Directories *above* a hidden path can't be listed (`ls /` is refused); + files beneath them can still be read. + - A symlink that leads into or above a hidden path isn't granted. + - Not covered: a hard link to a hidden file made elsewhere beforehand, or + the same directory mounted a second time. +- **Process lifetime.** + - With a wall-clock limit, the command gets its own process group. The + limit kills all of it, and `SIGINT`/`SIGTERM`/`SIGHUP` sent to `sbx` are + passed on. + - If `sbx` is killed with `SIGKILL`, a supervisor kills the group too. + - Without a limit, the command stays in the caller's process group, so the + caller's own group kill reaches it. + +**Known limits:** +- Landlock does not cover UDP. Under `deny`, DNS still works. Under + `proxy`, the command doesn't need DNS, but it could still send UDP. +- Landlock matches network ports, not addresses. Under `proxy` the command + could connect to *any* host on the proxy's (random, high) port. +- On macOS the profile is generated and unit-tested, but this crate's + network and `deny_read` clauses have not yet been run on a Mac. + +## Exit codes + +| code | meaning | +|---|---| +| the command's | it ran | +| 124 | the wall-clock limit killed it | +| 125 | `sbx` refused (strict, or a bad policy) or failed | +| 126 / 127 | the command could not be run / found | +| 128 + n | it was killed by signal n | + +## Using it from Rust + +```rust +use incord_sandbox::{Policy, Sandbox}; + +fn main() { + incord_sandbox::enter_if_requested(); // first: the helper is this binary + let mut policy = Policy::workspace("/path/to/worktree"); + policy.fs.deny_read.push("/path/to/hidden-tests".into()); + policy.limits.wall_secs = Some(1800); + let outcome = Sandbox::new(policy) + .run("cargo", &["test".into()], std::path::Path::new("/path/to/worktree")) + .expect("runs"); + std::process::exit(outcome.code()); +} +``` + +`Sandbox::command` returns the `Command` and a guard instead, for a caller +that sets its own pipes. Keep the guard alive until the command exits: it +holds the proxy and the temp directory. + +## Tests + +`cargo test -p incord-sandbox` runs: +- the unit tests (policy, environment, allowlist, Seatbelt profile); +- on Linux, escape tests through the real binary: writes outside the root, + symlinks, hard links, renames, `/proc/self/root`, child processes, reading + a hidden path, connecting and binding under `deny`, bypassing the proxy, + the wall limit and `SIGKILL` cleanup, limits and exit codes. + +Each escape test skips, and says so, on a kernel that cannot enforce what +it checks. diff --git a/crates/sandbox/src/env.rs b/crates/sandbox/src/env.rs new file mode 100644 index 0000000..3ea9650 --- /dev/null +++ b/crates/sandbox/src/env.rs @@ -0,0 +1,204 @@ +//! The environment a confined command starts with. +//! +//! Computed once, as the complete list, and applied with `env_clear` first: +//! a variable the policy removed must not come back because some later code +//! forgot to remove it again. + +use std::ffi::OsString; + +use crate::policy::{Env, Inherit}; + +/// Variables that attach a process to the agent session that started it. +/// An agent CLI started inside another agent's session reads these as its +/// own and joins (or continues) that session; measured with Claude Code, +/// where three concurrent attempts all reported the operator's session id. +/// Credentials (`ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`, ...) are NOT +/// here: they say who may run a session, not which one this is. +pub const AGENT_SESSION: &[&str] = &[ + "CLAUDECODE", + "CLAUDE_CODE_ENTRYPOINT", + "CLAUDE_CODE_CHILD_SESSION", + "CLAUDE_CODE_MESSAGING_SOCKET", + "CLAUDE_CODE_MESSAGING_TOKEN", + "CLAUDE_SESSION_INGRESS_TOKEN_FILE", + "SESSION_INGRESS_URL", + "CLAUDE_CODE_SESSION*", + "CLAUDE_CODE_REMOTE*", +]; + +/// Variables that point git somewhere other than the directory it runs in. +/// A process started from a git hook inherits `GIT_DIR`, and every `git` it +/// runs then acts on the hook's repository instead of its own checkout. +pub const GIT_REDIRECTS: &[&str] = &[ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", + "GIT_NAMESPACE", + "GIT_CEILING_DIRECTORIES", + "GIT_DISCOVERY_ACROSS_FILESYSTEM", +]; + +/// Kept under `inherit = "none"`: without them almost nothing starts. +pub const ESSENTIAL: &[&str] = &[ + "PATH", + "HOME", + "USER", + "LOGNAME", + "SHELL", + "LANG", + "LC_ALL", + "LC_CTYPE", + "TERM", + "TZ", + // Windows: the loader, the shell and the profile directories. + "SYSTEMROOT", + "WINDIR", + "COMSPEC", + "PATHEXT", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + "PROGRAMDATA", + "PROGRAMFILES", +]; + +/// Whether `name` matches `pattern`: exact, or a prefix when the pattern ends +/// in `*`. Case-insensitive, because Windows reads names that way and a +/// differently-cased `Git_Dir` must not slip through. +#[must_use] +pub fn matches(pattern: &str, name: &str) -> bool { + let name = name.to_ascii_uppercase(); + let pattern = pattern.to_ascii_uppercase(); + match pattern.strip_suffix('*') { + Some(prefix) => name.starts_with(prefix), + None => name == pattern, + } +} + +/// The full environment for the command, from `inherited` (normally +/// `std::env::vars_os()`) under `policy`, with `extra` (the proxy settings, +/// the private temp directory) applied before the policy's own `set`. +#[must_use] +pub fn compute( + policy: &Env, + inherited: impl IntoIterator, + extra: &[(String, String)], +) -> Vec<(OsString, OsString)> { + let mut removed: Vec<&str> = policy.remove.iter().map(String::as_str).collect(); + if policy.strip_agent_session { + removed.extend_from_slice(AGENT_SESSION); + } + if policy.strip_git_redirects { + removed.extend_from_slice(GIT_REDIRECTS); + } + + let mut out: Vec<(OsString, OsString)> = inherited + .into_iter() + .filter(|(name, _)| { + let name = name.to_string_lossy(); + let kept = match policy.inherit { + Inherit::All => true, + Inherit::None => ESSENTIAL + .iter() + .copied() + .chain(policy.pass.iter().map(String::as_str)) + .any(|p| matches(p, &name)), + }; + kept && !removed.iter().any(|p| matches(p, &name)) + }) + .collect(); + + let set = extra + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .chain(policy.set.iter().map(|(k, v)| (k.as_str(), v.as_str()))); + for (name, value) in set { + out.retain(|(n, _)| !n.to_string_lossy().eq_ignore_ascii_case(name)); + out.push((name.into(), value.into())); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vars(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> { + pairs + .iter() + .map(|(k, v)| ((*k).into(), (*v).into())) + .collect() + } + + fn names(env: &[(OsString, OsString)]) -> Vec { + env.iter() + .map(|(k, _)| k.to_string_lossy().into_owned()) + .collect() + } + + #[test] + fn the_defaults_strip_the_session_and_git_redirects_and_keep_credentials() { + let env = compute( + &Env::default(), + vars(&[ + ("PATH", "/bin"), + ("CLAUDECODE", "1"), + ("CLAUDE_CODE_SESSION_ID", "parent"), + ("CLAUDE_CODE_REMOTE_SESSION_ID", "x"), + ("Git_Dir", "/elsewhere/.git"), + ("GIT_WORK_TREE", "/elsewhere"), + ("ANTHROPIC_API_KEY", "k"), + ("CLAUDE_CODE_OAUTH_TOKEN", "t"), + ]), + &[], + ); + assert_eq!( + names(&env), + ["PATH", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"] + ); + } + + #[test] + fn inherit_none_keeps_only_the_essentials_and_what_is_passed() { + let policy = Env { + inherit: Inherit::None, + pass: vec!["NPM_*".into()], + ..Env::default() + }; + let env = compute( + &policy, + vars(&[ + ("PATH", "/bin"), + ("HOME", "/h"), + ("AWS_SECRET_ACCESS_KEY", "s"), + ("NPM_TOKEN", "n"), + ]), + &[], + ); + assert_eq!(names(&env), ["PATH", "HOME", "NPM_TOKEN"]); + } + + #[test] + fn remove_wins_over_pass_and_set_wins_over_everything() { + let mut policy = Env { + inherit: Inherit::None, + pass: vec!["TOKEN".into()], + remove: vec!["TOKEN".into()], + ..Env::default() + }; + policy.set.insert("TMPDIR".into(), "/policy".into()); + let env = compute( + &policy, + vars(&[("TOKEN", "x"), ("PATH", "/bin")]), + &[ + ("TMPDIR".into(), "/private".into()), + ("https_proxy".into(), "p".into()), + ], + ); + assert_eq!(names(&env), ["PATH", "https_proxy", "TMPDIR"]); + assert_eq!(env.last().map(|(_, v)| v.clone()), Some("/policy".into())); + } +} diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs new file mode 100644 index 0000000..124db29 --- /dev/null +++ b/crates/sandbox/src/lib.rs @@ -0,0 +1,828 @@ +//! Run any command under one policy: what it may write, what it may reach on +//! the network, which environment it gets, and how much it may use. +//! +//! Built for coding agents and the harnesses around them: an agent CLI, a +//! test suite a worker runs, a tool call. The policy is one file +//! ([`policy`]); the same file means the same thing on every platform, and +//! where a platform cannot enforce part of it, [`Sandbox::enforcement`] says +//! so before anything runs. In strict mode (the default) a policy that cannot +//! be enforced in full is refused rather than run with less. +//! +//! # How a command is confined +//! +//! ```text +//! parent (sbx, or your program) helper (same binary, re-executed) +//! private temp dir setrlimit +//! allowlisting proxy (network=proxy) Landlock restrict_self (Linux) +//! environment computed exec(command) ── confined from here on +//! wall-clock timer, process group +//! ``` +//! +//! On macOS the helper runs under `sandbox-exec` with a generated Seatbelt +//! profile instead of Landlock. The helper is the calling binary re-executed +//! with a private first argument, so a program that embeds this library must +//! call [`enter_if_requested`] first thing in `main`. +//! +//! # Platforms +//! +//! | | filesystem | network | limits | +//! |---|---|---|---| +//! | Linux | Landlock (5.13+) | Landlock TCP (6.7+) | setrlimit + wall | +//! | macOS | Seatbelt | Seatbelt | setrlimit + wall | +//! | Windows | not yet (see incode's ACL sandbox) | not yet | wall only | + +pub mod env; +pub mod limits; +pub mod policy; +pub mod proxy; +pub mod seatbelt; + +#[cfg(target_os = "linux")] +mod linux; + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, ExitStatus}; +use std::time::{Duration, Instant}; + +use serde::{Deserialize, Serialize}; + +pub use policy::{FsMode, Inherit, Limits, NetMode, Policy}; + +/// The first argument that turns the binary into the helper. +pub const ENTER_ARG: &str = "__sbx-enter"; + +/// Exit code for "the sandbox refused or failed", as `docker run` uses it. +pub const EXIT_SANDBOX: i32 = 125; +/// Exit code when the wall-clock limit killed the command, as `timeout` uses it. +pub const EXIT_TIMEOUT: i32 = 124; + +/// Whether one part of the policy is in force. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "status", content = "detail", rename_all = "kebab-case")] +pub enum Status { + /// The policy asks for nothing here. + NotRequested, + /// In force, and how. + Enforced(String), + /// Asked for but not in force on this machine, and why. + NotEnforced(String), +} + +impl Status { + #[must_use] + pub fn is_gap(&self) -> bool { + matches!(self, Self::NotEnforced(_)) + } + + fn line(&self, what: &str) -> String { + match self { + Self::NotRequested => format!("{what}: not restricted"), + Self::Enforced(how) => format!("{what}: enforced - {how}"), + Self::NotEnforced(why) => format!("{what}: NOT ENFORCED - {why}"), + } + } +} + +/// What this machine will enforce of a policy. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Enforcement { + pub filesystem: Status, + pub network: Status, + pub limits: Status, + /// Always enforced: the environment is computed by this process. + pub environment: Status, +} + +impl Enforcement { + /// The parts asked for but not in force. + #[must_use] + pub fn gaps(&self) -> Vec { + [ + ("filesystem", &self.filesystem), + ("network", &self.network), + ("limits", &self.limits), + ] + .into_iter() + .filter(|(_, s)| s.is_gap()) + .map(|(what, s)| s.line(what)) + .collect() + } + + /// One line per part, for a person. + #[must_use] + pub fn report(&self) -> String { + [ + self.filesystem.line("filesystem"), + self.network.line("network"), + self.limits.line("limits"), + self.environment.line("environment"), + ] + .join("\n") + } +} + +/// What the parent hands the helper, as JSON in one argument. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EnterSpec { + pub fs_mode: FsMode, + pub roots: Vec, + #[serde(default)] + pub deny_read: Vec, + pub temp: PathBuf, + pub net_mode: NetMode, + pub proxy_port: Option, + pub limits: Limits, + pub strict: bool, + /// The command has its own process group: the helper stays as its + /// supervisor instead of exec'ing it, so that if the parent dies (even by + /// SIGKILL, which nothing can forward) the whole group dies with it. + #[serde(default)] + pub supervise: bool, +} + +/// Call first thing in `main` of any program that embeds this library. When +/// the process was started as the helper it applies the confinement and +/// execs the command, and never returns; otherwise it returns at once. +pub fn enter_if_requested() { + let mut args = std::env::args_os(); + let _exe = args.next(); + if args.next().as_deref() != Some(std::ffi::OsStr::new(ENTER_ARG)) { + return; + } + let rest: Vec = args.collect(); + let code = match enter(&rest) { + Ok(never) => match never {}, + Err(e) => { + eprintln!("sbx: {e}"); + e.code + } + }; + std::process::exit(code); +} + +enum Never {} + +#[derive(Debug)] +struct EnterError { + message: String, + code: i32, +} + +impl std::fmt::Display for EnterError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +fn sandbox_err(message: impl Into) -> EnterError { + EnterError { + message: message.into(), + code: EXIT_SANDBOX, + } +} + +/// The helper: ` -- [args...]`. +fn enter(args: &[OsString]) -> Result { + let spec_json = args + .first() + .and_then(|a| a.to_str()) + .ok_or_else(|| sandbox_err("helper started without its spec"))?; + let spec: EnterSpec = serde_json::from_str(spec_json) + .map_err(|e| sandbox_err(format!("helper spec does not parse: {e}")))?; + if args.get(1).map(|a| a.as_os_str()) != Some(std::ffi::OsStr::new("--")) { + return Err(sandbox_err("helper expected `--` before the command")); + } + let program = args + .get(2) + .ok_or_else(|| sandbox_err("helper started without a command"))?; + let program_args = &args[3..]; + // Nothing in the spec is enforced by the helper off Unix yet: the parent + // already refused (strict) or reported (best effort) every gap. + #[cfg(not(unix))] + let _ = &spec; + + // If the parent dies (SIGKILL included, which nothing can forward), the + // command must not run on unsupervised. In the caller's process group a + // parent-death SIGKILL on the command is enough (the caller's group kill + // reaches the rest); in its own group the supervisor below handles it. + #[cfg(unix)] + let parent = { + // SAFETY: getppid has no preconditions. + unsafe { libc::getppid() } + }; + #[cfg(target_os = "linux")] + { + let signal = if spec.supervise { + libc::SIGTERM + } else { + libc::SIGKILL + }; + // SAFETY: prctl with integer arguments. + unsafe { + libc::prctl(libc::PR_SET_PDEATHSIG, signal); + } + } + #[cfg(unix)] + { + // SAFETY: getppid has no preconditions. + if unsafe { libc::getppid() } != parent { + return Err(sandbox_err("the parent exited before the command started")); + } + } + + #[cfg(unix)] + if let Err(e) = limits::apply(&spec.limits) { + if spec.strict { + return Err(sandbox_err(e)); + } + eprintln!("sbx: limit not applied (best effort): {e}"); + } + #[cfg(target_os = "linux")] + if let Err(e) = linux::restrict(&spec) { + if spec.strict { + return Err(sandbox_err(format!("Landlock: {e}"))); + } + eprintln!("sbx: Landlock not applied (best effort): {e}"); + } + + #[cfg(unix)] + if spec.supervise { + supervise(program, program_args, parent); + } + exec(program, program_args) +} + +#[cfg(unix)] +static PARENT: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); + +/// Kill the whole process group if the parent is gone. Async-signal-safe. +#[cfg(unix)] +extern "C" fn kill_group_if_orphaned(_sig: libc::c_int) { + // SAFETY: getppid, getpgrp and kill are async-signal-safe. + unsafe { + if libc::getppid() != PARENT.load(std::sync::atomic::Ordering::Relaxed) { + libc::kill(-libc::getpgrp(), libc::SIGKILL); + } + } +} + +/// Stay in the command's process group as its supervisor: run it, pass its +/// exit status on, and kill the group if the parent disappears. Signals the +/// parent forwards to the group (SIGINT, SIGTERM, ...) reach the command +/// directly; here they only trigger the orphan check, so the command can +/// still shut down gracefully while the parent is alive. +#[cfg(unix)] +fn supervise(program: &OsString, args: &[OsString], parent: libc::pid_t) -> Never { + PARENT.store(parent, std::sync::atomic::Ordering::Relaxed); + for sig in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT] { + // SAFETY: a handler that only calls async-signal-safe functions. A + // handler (not SIG_IGN) is reset to the default by exec, so the + // command does not inherit it. + unsafe { + libc::signal( + sig, + kill_group_if_orphaned as extern "C" fn(libc::c_int) as libc::sighandler_t, + ); + } + } + // Where there is no parent-death signal (macOS), notice by polling. + std::thread::spawn(|| loop { + std::thread::sleep(std::time::Duration::from_millis(200)); + kill_group_if_orphaned(0); + }); + let code = match Command::new(program).args(args).status() { + Ok(status) => { + use std::os::unix::process::ExitStatusExt; + status + .code() + .or_else(|| status.signal().map(|s| 128 + s)) + .unwrap_or(1) + } + Err(e) => { + eprintln!("sbx: cannot run {}: {e}", Path::new(program).display()); + if e.kind() == std::io::ErrorKind::NotFound { + 127 + } else { + 126 + } + } + }; + std::process::exit(code); +} + +#[cfg(unix)] +fn exec(program: &OsString, args: &[OsString]) -> Result { + use std::os::unix::process::CommandExt; + let err = Command::new(program).args(args).exec(); + Err(EnterError { + code: if err.kind() == std::io::ErrorKind::NotFound { + 127 + } else { + 126 + }, + message: format!("cannot run {}: {err}", Path::new(program).display()), + }) +} + +#[cfg(not(unix))] +fn exec(program: &OsString, args: &[OsString]) -> Result { + // No exec on Windows: run it and pass its exit code on. + let status = Command::new(program) + .args(args) + .status() + .map_err(|e| EnterError { + code: if e.kind() == std::io::ErrorKind::NotFound { + 127 + } else { + 126 + }, + message: format!("cannot run {}: {e}", Path::new(program).display()), + })?; + std::process::exit(status.code().unwrap_or(1)); +} + +/// A policy ready to run commands. +#[derive(Debug, Clone)] +pub struct Sandbox { + policy: Policy, + helper: Option, + strict: bool, +} + +/// Everything a running command needs kept alive: the proxy and the private +/// temp directory. Dropped after the command exits. +pub struct Guard { + proxy: Option, + temp: TempDir, + pub enforcement: Enforcement, + /// Whether the command runs in its own process group (only with a + /// wall-clock limit and a non-terminal stdin); kill `-pid` to stop it all. + pub own_group: bool, +} + +impl Guard { + /// The proxy's decisions so far (empty without a proxy). + #[must_use] + pub fn decisions(&self) -> Vec { + self.proxy + .as_ref() + .map(proxy::Proxy::decisions) + .unwrap_or_default() + } + + /// The command's private temp directory. + #[must_use] + pub fn temp_dir(&self) -> &Path { + &self.temp.path + } +} + +/// How a command ended. +#[derive(Debug)] +pub struct Outcome { + pub status: ExitStatus, + pub timed_out: bool, + pub decisions: Vec, +} + +impl Outcome { + /// The exit code a shell would report: the command's, 128 + signal, or + /// [`EXIT_TIMEOUT`]. + #[must_use] + pub fn code(&self) -> i32 { + if self.timed_out { + return EXIT_TIMEOUT; + } + if let Some(c) = self.status.code() { + return c; + } + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt; + if let Some(sig) = self.status.signal() { + return 128 + sig; + } + } + 1 + } +} + +impl Sandbox { + #[must_use] + pub fn new(policy: Policy) -> Self { + Self { + policy, + helper: None, + strict: true, + } + } + + /// The binary re-executed as the helper. Default: the current executable, + /// which must then call [`enter_if_requested`]. + #[must_use] + pub fn helper(mut self, exe: impl Into) -> Self { + self.helper = Some(exe.into()); + self + } + + /// Strict (the default): refuse to run when any part of the policy cannot + /// be enforced. Off: run with what can be, and say what could not. + #[must_use] + pub fn strict(mut self, strict: bool) -> Self { + self.strict = strict; + self + } + + #[must_use] + pub fn policy(&self) -> &Policy { + &self.policy + } + + /// What this machine will enforce of the policy. + #[must_use] + pub fn enforcement(&self) -> Enforcement { + enforcement(&self.policy) + } + + /// The confined [`Command`] for `program args`, started in `cwd`, and the + /// guard to keep alive until it exits. The caller sets the pipes and + /// spawns it; [`Self::spawn`] does all of that. + /// + /// # Errors + /// In strict mode when part of the policy cannot be enforced; when a + /// writable root is missing; when the proxy or temp dir cannot be made. + pub fn command( + &self, + program: impl AsRef, + args: &[OsString], + cwd: &Path, + ) -> Result<(Command, Guard), String> { + let enforcement = self.enforcement(); + let gaps = enforcement.gaps(); + if self.strict && !gaps.is_empty() { + return Err(format!( + "this policy cannot be fully enforced here (run with --best-effort to accept):\n {}", + gaps.join("\n ") + )); + } + let roots = self.policy.resolved_roots(cwd)?; + let deny_read = self.policy.resolved_deny_read(cwd, &roots)?; + let temp = TempDir::new()?; + let own_group = self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); + + let proxy = if self.policy.network.mode == NetMode::Proxy { + let allowlist = proxy::Allowlist::new( + &self.policy.network.allow, + self.policy.network.allow_private, + )?; + let upstream = proxy::Upstream::from_env(|k| std::env::var(k).ok()); + Some(proxy::Proxy::start(allowlist, upstream).map_err(|e| format!("proxy: {e}"))?) + } else { + None + }; + + let mut extra: Vec<(String, String)> = Vec::new(); + let temp_str = temp.path.to_string_lossy().into_owned(); + for k in ["TMPDIR", "TMP", "TEMP"] { + extra.push((k.into(), temp_str.clone())); + } + if let Some(p) = &proxy { + extra.extend(p.client_env()); + } + let environment = env::compute(&self.policy.env, std::env::vars_os(), &extra); + + let spec = EnterSpec { + fs_mode: self.policy.fs.mode, + roots: roots.clone(), + deny_read, + temp: temp.path.clone(), + net_mode: self.policy.network.mode, + proxy_port: proxy.as_ref().map(proxy::Proxy::port), + limits: self.policy.limits.clone(), + strict: self.strict, + supervise: own_group, + }; + let helper = match &self.helper { + Some(h) => h.clone(), + None => std::env::current_exe().map_err(|e| format!("cannot name the helper: {e}"))?, + }; + let spec_json = serde_json::to_string(&spec).map_err(|e| e.to_string())?; + + let mut cmd = wrap_platform(&helper, &spec, &roots); + cmd.arg(ENTER_ARG) + .arg(spec_json) + .arg("--") + .arg(program) + .args(args) + .current_dir(cwd) + .env_clear() + .envs(environment); + if own_group { + set_own_process_group(&mut cmd); + } + + Ok(( + cmd, + Guard { + proxy, + temp, + enforcement, + own_group, + }, + )) + } + + /// Run `program args` in `cwd` with the caller's stdio, enforcing the + /// wall-clock limit, and wait for it. + /// + /// # Errors + /// As [`Self::command`], or when the command cannot be started. + pub fn run( + &self, + program: impl AsRef, + args: &[OsString], + cwd: &Path, + ) -> Result { + let (mut cmd, guard) = self.command(program, args, cwd)?; + let wall = self.policy.limits.wall_secs.map(Duration::from_secs); + let own_group = guard.own_group; + let child = cmd + .spawn() + .map_err(|e| format!("cannot start the helper: {e}"))?; + if own_group { + forward_signals_to_group(child.id()); + } + let (status, timed_out) = wait(child, wall, own_group)?; + Ok(Outcome { + status, + timed_out, + decisions: guard.decisions(), + }) + } +} + +/// The enforcement of `policy` on this machine. +#[must_use] +pub fn enforcement(policy: &Policy) -> Enforcement { + Enforcement { + filesystem: fs_status(policy.fs.mode), + network: net_status(policy.network.mode), + limits: limits::status(&policy.limits), + environment: Status::Enforced(environment_summary(&policy.env)), + } +} + +fn environment_summary(e: &policy::Env) -> String { + let mut parts = vec![match e.inherit { + Inherit::All => "inherited".to_string(), + Inherit::None => "only essentials and `pass`".to_string(), + }]; + if e.strip_agent_session { + parts.push("agent session stripped".into()); + } + if e.strip_git_redirects { + parts.push("git redirects stripped".into()); + } + if !e.remove.is_empty() { + parts.push(format!("{} pattern(s) removed", e.remove.len())); + } + parts.push("private TMPDIR".into()); + parts.join(", ") +} + +#[cfg(target_os = "linux")] +fn fs_status(mode: FsMode) -> Status { + linux::fs_status(mode) +} + +#[cfg(target_os = "macos")] +fn fs_status(mode: FsMode) -> Status { + match mode { + FsMode::Off => Status::NotRequested, + _ if Path::new(seatbelt::SANDBOX_EXEC).exists() => { + Status::Enforced("Seatbelt (sandbox-exec)".into()) + } + _ => Status::NotEnforced(format!("{} was not found", seatbelt::SANDBOX_EXEC)), + } +} + +#[cfg(not(any(target_os = "linux", target_os = "macos")))] +fn fs_status(mode: FsMode) -> Status { + match mode { + FsMode::Off => Status::NotRequested, + _ => { + Status::NotEnforced("no filesystem sandbox is implemented for this platform yet".into()) + } + } +} + +#[cfg(target_os = "linux")] +fn net_status(mode: NetMode) -> Status { + linux::net_status(mode) +} + +#[cfg(target_os = "macos")] +fn net_status(mode: NetMode) -> Status { + match mode { + NetMode::Allow => Status::NotRequested, + _ if Path::new(seatbelt::SANDBOX_EXEC).exists() => Status::Enforced(match mode { + NetMode::Proxy => "Seatbelt: outbound only to the proxy (and Unix sockets)".into(), + _ => "Seatbelt: network denied (Unix sockets allowed)".into(), + }), + _ => Status::NotEnforced(format!("{} was not found", seatbelt::SANDBOX_EXEC)), + } +} + +#[cfg(not(any(target_os = "linux", target_os = "macos")))] +fn net_status(mode: NetMode) -> Status { + match mode { + NetMode::Allow => Status::NotRequested, + _ => Status::NotEnforced("no network sandbox is implemented for this platform yet".into()), + } +} + +/// The helper invocation, under `sandbox-exec` on macOS. +#[cfg(target_os = "macos")] +fn wrap_platform(helper: &Path, spec: &EnterSpec, roots: &[PathBuf]) -> Command { + if spec.fs_mode == FsMode::Off && spec.net_mode == NetMode::Allow { + return Command::new(helper); + } + let mut cmd = Command::new(seatbelt::SANDBOX_EXEC); + let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + cmd.arg("-D") + .arg(format!("TMP={}", real(&spec.temp).display())); + for (i, root) in roots.iter().enumerate() { + cmd.arg("-D").arg(format!("WS{i}={}", real(root).display())); + } + for (i, hidden) in spec.deny_read.iter().enumerate() { + cmd.arg("-D") + .arg(format!("DR{i}={}", real(hidden).display())); + } + cmd.arg("-p").arg(seatbelt::profile( + spec.fs_mode, + roots.len(), + spec.deny_read.len(), + spec.net_mode, + spec.proxy_port, + )); + cmd.arg(helper); + cmd +} + +#[cfg(not(target_os = "macos"))] +fn wrap_platform(helper: &Path, _spec: &EnterSpec, _roots: &[PathBuf]) -> Command { + Command::new(helper) +} + +/// A command gets its own process group only when it has a wall-clock limit, +/// so the limit can kill everything it started; [`Sandbox::run`] then +/// forwards the termination signals it receives, and the supervisor in the +/// helper kills the group if the parent dies. Skipped when stdin is a +/// terminal: a background process group cannot read the terminal, so an +/// interactive command keeps the caller's group (the limit then kills the +/// command itself). +fn stdin_is_terminal() -> bool { + #[cfg(unix)] + { + // SAFETY: isatty only inspects the descriptor. + unsafe { libc::isatty(0) == 1 } + } + #[cfg(not(unix))] + { + false + } +} + +fn set_own_process_group(cmd: &mut Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + cmd.process_group(0); + } + #[cfg(not(unix))] + let _ = cmd; +} + +#[cfg(unix)] +static FORWARD_TO: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); + +#[cfg(unix)] +extern "C" fn forward(sig: libc::c_int) { + let pgid = FORWARD_TO.load(std::sync::atomic::Ordering::Relaxed); + if pgid > 0 { + // SAFETY: kill is async-signal-safe. + unsafe { + libc::kill(-pgid, sig); + } + } +} + +/// Pass SIGINT, SIGTERM, SIGHUP and SIGQUIT on to the command's process +/// group, so a caller that stops sbx stops what sbx started. +fn forward_signals_to_group(pid: u32) { + #[cfg(unix)] + { + let Ok(pid) = i32::try_from(pid) else { return }; + FORWARD_TO.store(pid, std::sync::atomic::Ordering::Relaxed); + for sig in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT] { + // SAFETY: installing a handler that only calls kill. + unsafe { + libc::signal( + sig, + forward as extern "C" fn(libc::c_int) as libc::sighandler_t, + ); + } + } + } + #[cfg(not(unix))] + let _ = pid; +} + +fn wait( + mut child: Child, + wall: Option, + own_group: bool, +) -> Result<(ExitStatus, bool), String> { + let Some(wall) = wall else { + return child.wait().map(|s| (s, false)).map_err(|e| e.to_string()); + }; + let deadline = Instant::now() + wall; + loop { + if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { + return Ok((status, false)); + } + if Instant::now() >= deadline { + kill(&mut child, own_group); + let status = child.wait().map_err(|e| e.to_string())?; + return Ok((status, true)); + } + std::thread::sleep(Duration::from_millis(25)); + } +} + +fn kill(child: &mut Child, own_group: bool) { + #[cfg(unix)] + if own_group { + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: signalling a process group we created. + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + return; + } + } + let _ = own_group; + let _ = child.kill(); +} + +/// A private temp directory, removed when dropped. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new() -> Result { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir(); + for _ in 0..16 { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + let name = format!( + "sbx-{}-{}-{nanos:x}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ); + let path = base.join(name); + match create_private_dir(&path) { + Ok(()) => { + let path = std::fs::canonicalize(&path).unwrap_or(path); + return Ok(Self { path }); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(format!("cannot make a temp directory: {e}")), + } + } + Err("cannot make a unique temp directory".into()) + } +} + +#[cfg(unix)] +fn create_private_dir(path: &Path) -> std::io::Result<()> { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new().mode(0o700).create(path) +} + +#[cfg(not(unix))] +fn create_private_dir(path: &Path) -> std::io::Result<()> { + std::fs::create_dir(path) +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} diff --git a/crates/sandbox/src/limits.rs b/crates/sandbox/src/limits.rs new file mode 100644 index 0000000..cdfb2f9 --- /dev/null +++ b/crates/sandbox/src/limits.rs @@ -0,0 +1,73 @@ +//! Resource limits applied in the helper, just before it execs the command. +//! +//! `setrlimit` limits are per process and inherited, so each process the +//! command starts gets the same ceiling (not a shared budget). The wall-clock +//! limit is the parent's: it kills the whole process group. + +use crate::policy::Limits; +use crate::Status; + +#[must_use] +pub fn status(limits: &Limits) -> Status { + let per_process = limits.cpu_secs.is_some() + || limits.memory_mb.is_some() + || limits.file_size_mb.is_some() + || limits.open_files.is_some(); + if !per_process && limits.wall_secs.is_none() { + return Status::NotRequested; + } + if per_process && !cfg!(unix) { + return Status::NotEnforced( + "per-process limits (cpu, memory, file size, open files) need setrlimit; on this \ + platform only wall_secs is enforced" + .into(), + ); + } + let mut what = Vec::new(); + if limits.wall_secs.is_some() { + what.push("wall clock (process group killed)"); + } + if per_process { + what.push("setrlimit per process"); + } + Status::Enforced(what.join(", ")) +} + +/// Apply the per-process limits to the calling process. +/// +/// # Errors +/// When the kernel refuses a limit. On macOS `RLIMIT_AS` is commonly +/// refused; that is reported, and the caller decides (strict refuses). +#[cfg(unix)] +pub(crate) fn apply(limits: &Limits) -> Result<(), String> { + const MB: u64 = 1024 * 1024; + let set = |resource, value: u64, name: &str| -> Result<(), String> { + let lim = libc::rlimit { + rlim_cur: value as libc::rlim_t, + rlim_max: value as libc::rlim_t, + }; + // SAFETY: setrlimit reads a valid, initialised rlimit struct. + let rc = unsafe { libc::setrlimit(resource, &lim) }; + if rc == 0 { + Ok(()) + } else { + Err(format!( + "setrlimit {name} = {value}: {}", + std::io::Error::last_os_error() + )) + } + }; + if let Some(s) = limits.cpu_secs { + set(libc::RLIMIT_CPU, s, "cpu")?; + } + if let Some(mb) = limits.memory_mb { + set(libc::RLIMIT_AS, mb.saturating_mul(MB), "memory")?; + } + if let Some(mb) = limits.file_size_mb { + set(libc::RLIMIT_FSIZE, mb.saturating_mul(MB), "file size")?; + } + if let Some(n) = limits.open_files { + set(libc::RLIMIT_NOFILE, n, "open files")?; + } + Ok(()) +} diff --git a/crates/sandbox/src/linux.rs b/crates/sandbox/src/linux.rs new file mode 100644 index 0000000..3804c4f --- /dev/null +++ b/crates/sandbox/src/linux.rs @@ -0,0 +1,293 @@ +//! Linux: Landlock for the filesystem and TCP, `setrlimit` for the limits. +//! +//! Landlock is the kernel's own unprivileged confinement: the helper process +//! adds its rules, calls `restrict_self`, then execs the command, and from +//! then on the command and every process it starts can touch only what the +//! rules allow. It cannot be widened again, and `no_new_privs` is set with it, +//! so a setuid binary cannot step outside either. +//! +//! What each kernel covers, by Landlock ABI: +//! - v1 (5.13): reads, writes, creating and removing files and directories. +//! - v2 (5.19): `refer`, so a file cannot be linked or renamed from a +//! read-only tree into a writable one and then written there. +//! - v3 (6.2): `truncate`. +//! - v4 (6.7): TCP `bind` and `connect`, by port (not by address). +//! - v5 (6.10): device ioctls. +//! +//! UDP is not covered by any ABI. Under `network = "deny"` that leaves UDP +//! (and so DNS) open; under `proxy` it leaves UDP open too, but the proxy +//! resolves names itself, so the command never needs it. + +use std::path::{Path, PathBuf}; + +use landlock::{ + Access, AccessFs, AccessNet, BitFlags, CompatLevel, Compatible, NetPort, PathBeneath, PathFd, + RulesetAttr, RulesetCreatedAttr, RulesetStatus, ABI, +}; + +use crate::policy::{FsMode, NetMode}; +use crate::{EnterSpec, Status}; + +/// The newest Landlock ABI this crate knows; the kernel downgrades it. +const NEWEST: ABI = ABI::V5; + +/// The highest Landlock ABI whose filesystem rights this kernel enforces in +/// full, or `None` when it has no Landlock at all. +#[must_use] +pub fn fs_abi() -> Option { + [ABI::V5, ABI::V3, ABI::V2, ABI::V1] + .into_iter() + .find(|abi| hard_ruleset_fs(*abi)) +} + +fn hard_ruleset_fs(abi: ABI) -> bool { + landlock::Ruleset::default() + .set_compatibility(CompatLevel::HardRequirement) + .handle_access(AccessFs::from_all(abi)) + .and_then(landlock::Ruleset::create) + .is_ok() +} + +/// Whether this kernel can confine TCP (Landlock ABI v4). +#[must_use] +pub fn net_supported() -> bool { + landlock::Ruleset::default() + .set_compatibility(CompatLevel::HardRequirement) + .handle_access(AccessNet::from_all(ABI::V4)) + .and_then(landlock::Ruleset::create) + .is_ok() +} + +pub(crate) fn fs_status(mode: FsMode) -> Status { + if mode == FsMode::Off { + return Status::NotRequested; + } + match fs_abi() { + None => Status::NotEnforced( + "this kernel has no Landlock (Linux 5.13+ with landlock in the LSM list)".into(), + ), + Some(ABI::V1) => Status::Enforced( + "Landlock ABI v1: writes confined, but a file can be hard-linked or renamed \ + out of a read-only tree (needs v2, Linux 5.19)" + .into(), + ), + Some(abi) => Status::Enforced(format!("Landlock (filesystem ABI {})", abi_number(abi))), + } +} + +pub(crate) fn net_status(mode: NetMode) -> Status { + match mode { + NetMode::Allow => Status::NotRequested, + _ if !net_supported() => Status::NotEnforced( + "this kernel's Landlock predates ABI v4 (Linux 6.7), the first to cover TCP".into(), + ), + NetMode::Deny => Status::Enforced( + "Landlock ABI v4: every TCP bind and connect refused, loopback included \ + (UDP is not covered)" + .into(), + ), + NetMode::Proxy => Status::Enforced( + "Landlock ABI v4: TCP connect only to the proxy's port; binds refused \ + (Landlock matches ports, not addresses; UDP is not covered)" + .into(), + ), + } +} + +fn abi_number(abi: ABI) -> u8 { + match abi { + ABI::V1 => 1, + ABI::V2 => 2, + ABI::V3 => 3, + ABI::V4 => 4, + _ => 5, + } +} + +/// Confine the CALLING process (the helper, just before it execs). +/// +/// # Errors +/// When the ruleset cannot be built or applied, or when `strict` and the +/// kernel enforced less than was asked. +pub(crate) fn restrict(spec: &EnterSpec) -> Result<(), String> { + let wants_fs = spec.fs_mode != FsMode::Off; + let wants_net = spec.net_mode != NetMode::Allow; + if !wants_fs && !wants_net { + return Ok(()); + } + let all: BitFlags = AccessFs::from_all(NEWEST); + let read: BitFlags = AccessFs::from_read(NEWEST); + + let mut ruleset = landlock::Ruleset::default(); + if wants_fs { + ruleset = ruleset.handle_access(all).map_err(|e| e.to_string())?; + } + if wants_net { + ruleset = ruleset + .handle_access(AccessNet::from_all(ABI::V4)) + .map_err(|e| e.to_string())?; + } + let mut ruleset = ruleset.create().map_err(|e| e.to_string())?; + + if wants_fs { + for dir in read_grants(&spec.deny_read) { + // A path that vanished since it was listed is simply not granted. + if let Ok(f) = PathFd::new(&dir) { + ruleset = ruleset + .add_rule(PathBeneath::new(f, read)) + .map_err(|e| e.to_string())?; + } + } + for sink in [ + "/dev/null", + "/dev/zero", + "/dev/full", + "/dev/random", + "/dev/urandom", + "/dev/tty", + "/dev/ptmx", + "/dev/pts", + ] { + if let Ok(f) = PathFd::new(sink) { + ruleset = ruleset + .add_rule(PathBeneath::new(f, all)) + .map_err(|e| e.to_string())?; + } + } + let mut writable: Vec = spec.roots.clone(); + writable.push(spec.temp.clone()); + for dir in &writable { + ruleset = ruleset + .add_rule(PathBeneath::new(fd(dir)?, all)) + .map_err(|e| e.to_string())?; + } + } + if spec.net_mode == NetMode::Proxy { + let port = spec + .proxy_port + .ok_or("network proxy requested but no proxy port was handed over")?; + ruleset = ruleset + .add_rule(NetPort::new(port, AccessNet::ConnectTcp)) + .map_err(|e| e.to_string())?; + } + + let status = ruleset.restrict_self().map_err(|e| e.to_string())?; + if status.ruleset == RulesetStatus::NotEnforced { + return Err("the kernel enforced none of the Landlock rules".into()); + } + if spec.strict && wants_net && ABI::from(status.landlock) < ABI::V4 { + return Err("the network rules did not take (Landlock ABI below v4)".into()); + } + Ok(()) +} + +/// The directories to grant read access beneath so that everything is +/// readable except what lies under `denied` (canonical paths). +/// +/// Landlock only ever grants, and a grant covers a whole subtree, so a +/// denied path is carved out by granting its siblings instead of its +/// parent, level by level from `/`: to hide `/a/b/c`, grant every entry of +/// `/` but `a`, every entry of `/a` but `b`, every entry of `/a/b` but `c`. +/// Path lookup is not restricted by Landlock, so `/a/x` stays reachable +/// through the ungranted `/a`; only listing `/a` itself is refused. +/// +/// The siblings are listed once, when the command starts: an entry created +/// later in `/a` is not readable. An entry that is a symlink is granted only +/// when its target neither lies inside nor contains a denied path, so a link +/// cannot lead back into what was hidden. What this cannot see: a hard link +/// to a hidden FILE made elsewhere beforehand, or the same directory +/// mounted at a second path. +pub(crate) fn read_grants(denied: &[PathBuf]) -> Vec { + let mut grants = vec![PathBuf::from("/")]; + for hidden in denied { + grants = grants + .into_iter() + .flat_map(|g| { + if hidden.starts_with(&g) { + carve(&g, hidden) + } else if g.starts_with(hidden) { + Vec::new() + } else { + vec![g] + } + }) + .collect(); + } + // Siblings are never on the way to a hidden path, so only a symlink + // can resolve into (or above) one. + grants.retain(|g| { + let real = std::fs::canonicalize(g).unwrap_or_else(|_| g.clone()); + !denied + .iter() + .any(|d| real.starts_with(d) || d.starts_with(&real)) + }); + grants +} + +/// The entries beneath `dir` that cover everything except `hidden`. +fn carve(dir: &Path, hidden: &Path) -> Vec { + if dir == hidden { + return Vec::new(); + } + let Ok(rest) = hidden.strip_prefix(dir) else { + return vec![dir.to_path_buf()]; + }; + let Some(next) = rest.components().next() else { + return Vec::new(); + }; + let toward = dir.join(next); + let mut out: Vec = std::fs::read_dir(dir) + .map(|entries| { + entries + .filter_map(Result::ok) + .map(|e| e.path()) + .filter(|p| *p != toward) + .collect() + }) + .unwrap_or_default(); + out.extend(carve(&toward, hidden)); + out +} + +fn fd(path: &Path) -> Result { + PathFd::new(path).map_err(|e| format!("{}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn grants_cover_everything_but_the_hidden_branch() { + let root = tempfile::tempdir().expect("tempdir"); + let base = std::fs::canonicalize(root.path()).expect("canon"); + for d in ["a/b/hidden/deep", "a/b/sibling", "a/other", "z"] { + std::fs::create_dir_all(base.join(d)).expect("mkdir"); + } + std::os::unix::fs::symlink(base.join("a/b/hidden"), base.join("z/link-in")) + .expect("symlink"); + std::os::unix::fs::symlink(&base, base.join("z/link-above")).expect("symlink"); + let hidden = base.join("a/b/hidden"); + let grants = read_grants(std::slice::from_ref(&hidden)); + + let covered = |p: &Path| grants.iter().any(|g| p.starts_with(g)); + assert!( + !covered(&hidden.join("deep")), + "the hidden branch is granted" + ); + assert!(covered(&base.join("a/b/sibling"))); + assert!(covered(&base.join("a/other"))); + assert!(covered(Path::new("/usr")) || !Path::new("/usr").exists()); + assert!(!grants.contains(&base.join("z/link-in")), "a link into it"); + assert!( + !grants.contains(&base.join("z/link-above")), + "a link above it" + ); + assert!(!grants.contains(&PathBuf::from("/"))); + } + + #[test] + fn no_hidden_path_grants_the_root() { + assert_eq!(read_grants(&[]), vec![PathBuf::from("/")]); + } +} diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs new file mode 100644 index 0000000..5272090 --- /dev/null +++ b/crates/sandbox/src/main.rs @@ -0,0 +1,291 @@ +//! `sbx`: run a command under a sandbox policy. +//! +//! ```text +//! sbx run [options] -- [args...] +//! sbx check [options] what this machine would enforce of the policy +//! sbx doctor what this machine can enforce at all +//! ``` + +use std::ffi::OsString; +use std::path::PathBuf; +use std::process::ExitCode; + +use incord_sandbox::{ + enforcement, policy::Inherit, FsMode, NetMode, Policy, Sandbox, Status, EXIT_SANDBOX, +}; + +const USAGE: &str = "\ +sbx - run any command under one sandbox policy + +USAGE: + sbx run [OPTIONS] -- [ARGS...] + sbx check [OPTIONS] print what this machine enforces of the policy (JSON with --json) + sbx doctor print what this machine can enforce at all + +POLICY (a file, then flags on top of it): + -p, --policy TOML (or .json) policy file + --fs off | read-only | workspace-write + -w, --write writable root (implies --fs workspace-write; repeatable) + --deny-read hide this path entirely, reads included (repeatable) + --net allow | deny | proxy + --allow-host host the proxy lets through (implies --net proxy; repeatable) + --allow-private an allowed host may resolve to a private address + --env-none start from an empty environment (essentials kept) + --pass-env keep this variable with --env-none (repeatable; NAME* for a prefix) + --unset-env remove this variable (repeatable; NAME* for a prefix) + --set-env set a variable (repeatable) + --keep-agent-session keep CLAUDECODE / CLAUDE_CODE_SESSION* (stripped by default) + --keep-git-redirects keep GIT_DIR / GIT_WORK_TREE / ... (stripped by default) + --wall kill the command (and everything it started) after SECS + --cpu CPU seconds per process + --mem address space per process + --fsize largest file a process may write + --nofile open files per process + --cwd start the command here (default: the current directory) + --best-effort run even if part of the policy cannot be enforced here + -q, --quiet no report on stderr + +EXIT: + the command's own code; 124 when --wall killed it; 125 when sbx refused or failed; + 126/127 when the command could not be run / found. +"; + +fn main() -> ExitCode { + incord_sandbox::enter_if_requested(); + let args: Vec = std::env::args_os().skip(1).collect(); + match real_main(args) { + Ok(code) => ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)), + Err(e) => { + eprintln!("sbx: {e}"); + ExitCode::from(EXIT_SANDBOX as u8) + } + } +} + +struct Options { + policy: Policy, + cwd: PathBuf, + best_effort: bool, + quiet: bool, + json: bool, + command: Vec, +} + +fn real_main(args: Vec) -> Result { + let Some(sub) = args.first().and_then(|a| a.to_str()) else { + print!("{USAGE}"); + return Ok(2); + }; + match sub { + "-h" | "--help" | "help" => { + print!("{USAGE}"); + Ok(0) + } + "-V" | "--version" => { + println!("sbx {}", env!("CARGO_PKG_VERSION")); + Ok(0) + } + "doctor" => { + doctor(); + Ok(0) + } + "check" => { + let o = parse(&args[1..])?; + let e = enforcement(&o.policy); + if o.json { + println!( + "{}", + serde_json::to_string_pretty(&e).map_err(|e| e.to_string())? + ); + } else { + println!("{}", e.report()); + } + Ok(if e.gaps().is_empty() { 0 } else { 1 }) + } + "run" => run(parse(&args[1..])?), + other => Err(format!("unknown command `{other}` (try `sbx --help`)")), + } +} + +fn run(o: Options) -> Result { + let (program, rest) = o + .command + .split_first() + .ok_or("nothing to run: give the command after `--`")?; + let sandbox = Sandbox::new(o.policy).strict(!o.best_effort); + let e = sandbox.enforcement(); + if !o.quiet { + for gap in e.gaps() { + eprintln!("sbx: {gap}"); + } + } + let outcome = sandbox.run(program, rest, &o.cwd)?; + if !o.quiet { + for d in outcome.decisions.iter().filter(|d| !d.allowed) { + eprintln!("sbx: network refused {} ({})", d.target, d.reason); + } + if outcome.timed_out { + eprintln!("sbx: killed after the wall-clock limit"); + } + } + Ok(outcome.code()) +} + +fn parse(args: &[OsString]) -> Result { + let mut policy: Option = None; + let mut flags: Vec<(String, Option)> = Vec::new(); + let mut command = Vec::new(); + let mut cwd = None; + let (mut best_effort, mut quiet, mut json) = (false, false, false); + + let mut i = 0; + while i < args.len() { + let arg = args[i] + .to_str() + .ok_or_else(|| format!("argument {i} is not valid UTF-8"))?; + if arg == "--" { + command = args[i + 1..].to_vec(); + break; + } + let takes_value = matches!( + arg, + "-p" | "--policy" + | "--fs" + | "-w" + | "--write" + | "--deny-read" + | "--net" + | "--allow-host" + | "--pass-env" + | "--unset-env" + | "--set-env" + | "--wall" + | "--cpu" + | "--mem" + | "--fsize" + | "--nofile" + | "--cwd" + ); + let value = if takes_value { + i += 1; + Some( + args.get(i) + .and_then(|v| v.to_str()) + .ok_or_else(|| format!("{arg} needs a value"))? + .to_string(), + ) + } else { + None + }; + match arg { + "-p" | "--policy" => { + policy = Some(Policy::load(&PathBuf::from(value.unwrap_or_default()))?); + } + "--cwd" => cwd = value.map(PathBuf::from), + "--best-effort" => best_effort = true, + "-q" | "--quiet" => quiet = true, + "--json" => json = true, + _ => flags.push((arg.to_string(), value)), + } + i += 1; + } + + // Flags apply on top of the file, whatever order they were given in. + let mut policy = policy.unwrap_or_default(); + for (flag, value) in flags { + let v = value.unwrap_or_default(); + let num = |v: &str| { + v.parse::() + .map_err(|_| format!("{flag}: `{v}` is not a number")) + }; + match flag.as_str() { + "--fs" => { + policy.fs.mode = FsMode::parse(&v).ok_or(format!("--fs: unknown mode `{v}`"))?; + } + "-w" | "--write" => { + policy.fs.mode = FsMode::WorkspaceWrite; + policy.fs.write.push(PathBuf::from(v)); + } + "--deny-read" => { + if policy.fs.mode == FsMode::Off { + policy.fs.mode = FsMode::ReadOnly; + } + policy.fs.deny_read.push(PathBuf::from(v)); + } + "--net" => { + policy.network.mode = + NetMode::parse(&v).ok_or(format!("--net: unknown mode `{v}`"))?; + } + "--allow-host" => { + policy.network.mode = NetMode::Proxy; + policy.network.allow.push(v); + } + "--allow-private" => policy.network.allow_private = true, + "--env-none" => policy.env.inherit = Inherit::None, + "--pass-env" => policy.env.pass.push(v), + "--unset-env" => policy.env.remove.push(v), + "--set-env" => { + let (k, val) = v + .split_once('=') + .ok_or(format!("--set-env: expected K=V, got `{v}`"))?; + policy.env.set.insert(k.to_string(), val.to_string()); + } + "--keep-agent-session" => policy.env.strip_agent_session = false, + "--keep-git-redirects" => policy.env.strip_git_redirects = false, + "--wall" => policy.limits.wall_secs = Some(num(&v)?), + "--cpu" => policy.limits.cpu_secs = Some(num(&v)?), + "--mem" => policy.limits.memory_mb = Some(num(&v)?), + "--fsize" => policy.limits.file_size_mb = Some(num(&v)?), + "--nofile" => policy.limits.open_files = Some(num(&v)?), + other => return Err(format!("unknown option `{other}` (try `sbx --help`)")), + } + } + + let cwd = match cwd { + Some(c) => c, + None => std::env::current_dir().map_err(|e| format!("no current directory: {e}"))?, + }; + Ok(Options { + policy, + cwd, + best_effort, + quiet, + json, + command, + }) +} + +fn doctor() { + let probe = |fs, net| { + let mut p = Policy::default(); + p.fs.mode = fs; + p.network.mode = net; + p.limits.wall_secs = Some(1); + p.limits.cpu_secs = Some(1); + enforcement(&p) + }; + let full = probe(FsMode::WorkspaceWrite, NetMode::Proxy); + let deny = probe(FsMode::Off, NetMode::Deny); + println!( + "sbx {} on {}", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS + ); + let show = |what: &str, s: &Status| match s { + Status::Enforced(how) => println!(" [ok ] {what:<14} {how}"), + Status::NotEnforced(why) => println!(" [no ] {what:<14} {why}"), + Status::NotRequested => {} + }; + show("filesystem", &full.filesystem); + show("network deny", &deny.network); + show("network proxy", &full.network); + show("limits", &full.limits); + show("environment", &full.environment); + match incord_sandbox::proxy::Upstream::from_env(|k| std::env::var(k).ok()) { + Some(_) => println!( + " [note] proxy this process sits behind an HTTP proxy; allowed requests \ + are chained through it, so the private-address check is that proxy's to make" + ), + None => println!(" [ok ] proxy connects directly; allowed names that resolve to private addresses are refused"), + } +} diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs new file mode 100644 index 0000000..5af234f --- /dev/null +++ b/crates/sandbox/src/policy.rs @@ -0,0 +1,400 @@ +//! The policy: one file that says what a confined command may do. +//! +//! ```toml +//! [fs] +//! mode = "workspace-write" # off | read-only | workspace-write +//! write = ["."] # writable roots (workspace-write only) +//! deny_read = ["../private"] # hidden: not even readable +//! +//! [network] +//! mode = "proxy" # allow | deny | proxy +//! allow = ["crates.io", "*.crates.io:443", "registry.npmjs.org"] +//! allow_private = false # may an allowed name resolve to a private address? +//! +//! [env] +//! inherit = "all" # all | none +//! pass = ["ANTHROPIC_API_KEY"] # kept when inherit = "none" +//! remove = ["AWS_*"] # removed; a trailing * matches a prefix +//! strip_agent_session = true # CLAUDECODE, CLAUDE_CODE_SESSION*, ... (default) +//! strip_git_redirects = true # GIT_DIR, GIT_WORK_TREE, ... (default) +//! set = { CI = "1" } +//! +//! [limits] +//! wall_secs = 1800 +//! cpu_secs = 1200 +//! memory_mb = 4096 +//! file_size_mb = 1024 +//! open_files = 4096 +//! ``` +//! +//! Every section is optional. An empty policy confines nothing, which is why +//! [`Policy::workspace`] exists: the shape most callers want, with the +//! defaults that are safe for an agent. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// Everything a confined command may do. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Policy { + pub fs: Fs, + pub network: Network, + pub env: Env, + pub limits: Limits, +} + +/// What the command may do to the filesystem. Reading is allowed everywhere +/// (a command that cannot read its toolchain cannot run) except beneath +/// `deny_read`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Fs { + pub mode: FsMode, + /// Writable roots under `workspace-write`. Relative paths are resolved + /// against the directory the command starts in. + pub write: Vec, + /// Paths the command may not even read: a benchmark's hidden tests, a + /// secrets folder, another attempt's results. Needs `read-only` or + /// `workspace-write`, must exist, and may not lie inside a writable root + /// (writing implies reading). Relative paths resolve like `write`. + pub deny_read: Vec, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum FsMode { + /// Unconfined. + #[default] + Off, + /// Read anywhere; write nowhere but the run's private temp directory and + /// the null and terminal devices. + ReadOnly, + /// Read anywhere; write only beneath `write` and the private temp directory. + WorkspaceWrite, +} + +impl FsMode { + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Off => "off", + Self::ReadOnly => "read-only", + Self::WorkspaceWrite => "workspace-write", + } + } + + #[must_use] + pub fn parse(word: &str) -> Option { + match word { + "off" => Some(Self::Off), + "read-only" => Some(Self::ReadOnly), + "workspace-write" => Some(Self::WorkspaceWrite), + _ => None, + } + } +} + +/// What the command may reach over the network. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Network { + pub mode: NetMode, + /// Under `proxy`: the hosts the command may reach. `example.com` allows + /// ports 80 and 443, `example.com:8443` that port, `example.com:*` any + /// port, and `*.example.com` any subdomain (not the apex). + pub allow: Vec, + /// Under `proxy`: whether an allowed NAME may resolve to a loopback, + /// private, link-local or cloud-metadata address. Off by default, so a + /// DNS answer cannot turn an allowed host into the metadata service. + pub allow_private: bool, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum NetMode { + /// Unrestricted. + #[default] + Allow, + /// No TCP at all, loopback included. + Deny, + /// TCP only to a proxy this process runs, which lets through only the + /// hosts in `allow`. + Proxy, +} + +impl NetMode { + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Allow => "allow", + Self::Deny => "deny", + Self::Proxy => "proxy", + } + } + + #[must_use] + pub fn parse(word: &str) -> Option { + match word { + "allow" => Some(Self::Allow), + "deny" => Some(Self::Deny), + "proxy" => Some(Self::Proxy), + _ => None, + } + } +} + +/// The environment the command starts with. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Env { + pub inherit: Inherit, + /// Kept under `inherit = "none"` (beside the few every program needs). + pub pass: Vec, + /// Removed in either mode. A trailing `*` matches a prefix. + pub remove: Vec, + /// Remove the variables that attach a process to the agent session that + /// started this one (see [`crate::env::AGENT_SESSION`]). + pub strip_agent_session: bool, + /// Remove the variables that point git at another repository (see + /// [`crate::env::GIT_REDIRECTS`]). + pub strip_git_redirects: bool, + /// Set last, so they win over everything above. + pub set: BTreeMap, +} + +impl Default for Env { + fn default() -> Self { + Self { + inherit: Inherit::All, + pass: Vec::new(), + remove: Vec::new(), + strip_agent_session: true, + strip_git_redirects: true, + set: BTreeMap::new(), + } + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Inherit { + #[default] + All, + None, +} + +/// Resource limits. `None` is unlimited. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Limits { + /// Wall-clock time; the whole process group is killed when it runs out. + pub wall_secs: Option, + /// CPU time per process (RLIMIT_CPU). + pub cpu_secs: Option, + /// Address space per process (RLIMIT_AS). + pub memory_mb: Option, + /// Largest file a process may write (RLIMIT_FSIZE). + pub file_size_mb: Option, + /// Open file descriptors per process (RLIMIT_NOFILE). + pub open_files: Option, +} + +impl Policy { + /// The policy most agent callers want: write only inside `root`, network + /// open, the agent session and git redirects stripped, no limits. + #[must_use] + pub fn workspace(root: impl Into) -> Self { + Self { + fs: Fs { + mode: FsMode::WorkspaceWrite, + write: vec![root.into()], + deny_read: Vec::new(), + }, + ..Self::default() + } + } + + /// Read a policy file (TOML, or JSON when the name ends in `.json`). + /// + /// # Errors + /// When the file cannot be read or does not parse. + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| format!("cannot read the policy {}: {e}", path.display()))?; + if path.extension().is_some_and(|e| e == "json") { + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) + } else { + Self::from_toml(&text).map_err(|e| format!("{}: {e}", path.display())) + } + } + + /// A policy from TOML text. + /// + /// # Errors + /// When the text does not parse or names an unknown key. + pub fn from_toml(text: &str) -> Result { + toml::from_str(text).map_err(|e| e.to_string()) + } + + /// Writable roots made absolute against `cwd`, then canonicalised so a + /// rule matches the path the kernel sees. A root that does not exist is + /// an error: a typo would otherwise leave the command unable to write + /// where it was meant to, or (worse) write nowhere it was meant to. + /// + /// # Errors + /// When a root does not exist. + pub fn resolved_roots(&self, cwd: &Path) -> Result, String> { + if self.fs.mode != FsMode::WorkspaceWrite { + return Ok(Vec::new()); + } + self.fs + .write + .iter() + .map(|root| { + let joined = absolute(root, cwd); + std::fs::canonicalize(&joined).map_err(|e| { + format!("the writable root {} cannot be used: {e}", joined.display()) + }) + }) + .collect() + } + + /// The `deny_read` paths, absolute and canonical, checked against the + /// writable `roots` ([`Self::resolved_roots`]). + /// + /// # Errors + /// When a path does not exist, the filesystem mode is `off`, or a path + /// lies inside a writable root. + pub fn resolved_deny_read( + &self, + cwd: &Path, + roots: &[PathBuf], + ) -> Result, String> { + if self.fs.deny_read.is_empty() { + return Ok(Vec::new()); + } + if self.fs.mode == FsMode::Off { + return Err("fs.deny_read needs fs.mode = \"read-only\" or \"workspace-write\"".into()); + } + self.fs + .deny_read + .iter() + .map(|p| { + let joined = absolute(p, cwd); + let real = std::fs::canonicalize(&joined).map_err(|e| { + format!( + "the deny_read path {} cannot be used: {e}", + joined.display() + ) + })?; + if let Some(root) = roots.iter().find(|r| real.starts_with(r)) { + return Err(format!( + "the deny_read path {} is inside the writable root {}, and writing \ + implies reading", + real.display(), + root.display() + )); + } + Ok(real) + }) + .collect() + } + + /// Whether this policy changes anything about a command. + #[must_use] + pub fn is_unconfined(&self) -> bool { + self.fs.mode == FsMode::Off + && self.network.mode == NetMode::Allow + && self.limits == Limits::default() + } +} + +/// `path` made absolute: a leading `~` is the home directory (policies are +/// often written by hand, and a harness passes arguments without a shell to +/// expand them), anything else relative is taken from `cwd`. +fn absolute(path: &Path, cwd: &Path) -> PathBuf { + let home = || { + std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map(PathBuf::from) + }; + let mut parts = path.components(); + if parts.next().is_some_and(|c| c.as_os_str() == "~") { + if let Some(home) = home() { + return home.join(parts.as_path()); + } + } + if path.is_absolute() { + path.to_path_buf() + } else { + cwd.join(path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_documented_example_parses() { + let doc = include_str!("policy.rs") + .split("//! ```toml\n") + .nth(1) + .and_then(|rest| rest.split("//! ```").next()) + .expect("the module docs carry an example"); + let text: String = doc + .lines() + .map(|l| l.trim_start_matches("//!").trim_start_matches(' ')) + .collect::>() + .join("\n"); + let policy = Policy::from_toml(&text).expect("the example parses"); + assert_eq!(policy.fs.mode, FsMode::WorkspaceWrite); + assert_eq!(policy.network.mode, NetMode::Proxy); + assert_eq!(policy.network.allow.len(), 3); + assert_eq!(policy.env.set.get("CI").map(String::as_str), Some("1")); + assert_eq!(policy.limits.wall_secs, Some(1800)); + } + + #[test] + fn an_unknown_key_is_refused_not_ignored() { + // A misspelt `wirte = [...]` silently ignored would leave the + // command writing nowhere it was meant to. + let err = Policy::from_toml("[fs]\nmode = \"read-only\"\nwirte = [\"x\"]\n") + .expect_err("unknown keys are errors"); + assert!(err.contains("wirte"), "{err}"); + } + + #[test] + fn the_default_strips_the_agent_session_and_git_redirects() { + let policy = Policy::default(); + assert!(policy.env.strip_agent_session); + assert!(policy.env.strip_git_redirects); + assert!(policy.is_unconfined()); + } + + #[test] + fn a_leading_tilde_is_the_home_directory() { + let cwd = Path::new("/work"); + let home = std::env::var_os("HOME").map(PathBuf::from).expect("HOME"); + assert_eq!(absolute(Path::new("~/.claude"), cwd), home.join(".claude")); + assert_eq!(absolute(Path::new("~"), cwd), home); + assert_eq!(absolute(Path::new("a/~b"), cwd), cwd.join("a/~b")); + assert_eq!(absolute(Path::new("/x"), cwd), PathBuf::from("/x")); + } + + #[test] + fn a_missing_root_is_an_error() { + let dir = tempfile::tempdir().expect("tempdir"); + let policy = Policy::workspace("does-not-exist"); + assert!(policy.resolved_roots(dir.path()).is_err()); + let policy = Policy::workspace("."); + let roots = policy.resolved_roots(dir.path()).expect("cwd exists"); + assert_eq!( + roots, + vec![std::fs::canonicalize(dir.path()).expect("canon")] + ); + } +} diff --git a/crates/sandbox/src/proxy.rs b/crates/sandbox/src/proxy.rs new file mode 100644 index 0000000..260b8ae --- /dev/null +++ b/crates/sandbox/src/proxy.rs @@ -0,0 +1,728 @@ +//! The allowlisting proxy behind `network.mode = "proxy"`. +//! +//! The confined command may open TCP only to this proxy (the kernel enforces +//! that, see [`crate::Enforcement`]); the proxy runs in the unconfined parent +//! and lets through only the hosts the policy allows. It speaks the two forms +//! every HTTP client uses through `HTTPS_PROXY` / `HTTP_PROXY`: +//! +//! - `CONNECT host:port` — TLS and anything else tunnelled; the proxy sees the +//! host name and nothing of the content. +//! - `GET http://host/path` — plain HTTP; forwarded with `Connection: close`, +//! so a kept-alive connection cannot be reused for a second host unseen. +//! +//! Decisions are made on the NAME the client asked for, and when the proxy +//! connects directly the name is resolved once and the connection goes to the +//! address that was checked, so a DNS answer cannot redirect an allowed name +//! to a private address or the cloud metadata service between the check and +//! the connect. When this process itself sits behind a proxy (`HTTPS_PROXY` +//! in the parent's environment), requests are chained through it with +//! `CONNECT`; that proxy resolves, so the private-address check cannot apply +//! and the report says so. + +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +const HEAD_LIMIT: usize = 64 * 1024; +const IO_TIMEOUT: Duration = Duration::from_secs(30); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); + +/// One allowlist entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rule { + /// Lower-case host, or the suffix after `*.` when `wildcard`. + host: String, + wildcard: bool, + port: Port, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Port { + /// 80 and 443: what a bare host name means. + Web, + Any, + One(u16), +} + +impl Rule { + /// Parse `host`, `host:port`, `host:*`, `*.suffix` or `*.suffix:port`. + /// + /// # Errors + /// For an empty host, a bad port, or a wildcard anywhere but the front. + pub fn parse(text: &str) -> Result { + let text = text.trim(); + let (host, port) = split_host_port(text); + let port = match port { + None => Port::Web, + Some("*") => Port::Any, + Some(p) => Port::One( + p.parse() + .map_err(|_| format!("network.allow `{text}`: `{p}` is not a port"))?, + ), + }; + let host = normalise_host(host); + let (host, wildcard) = match host.strip_prefix("*.") { + Some(rest) => (rest.to_string(), true), + None => (host, false), + }; + if host.is_empty() || host.contains('*') || host.contains('/') { + return Err(format!( + "network.allow `{text}`: expected host, host:port, host:* or *.domain" + )); + } + Ok(Self { + host, + wildcard, + port, + }) + } + + fn allows(&self, host: &str, port: u16) -> bool { + let host_ok = if self.wildcard { + host.ends_with(&format!(".{}", self.host)) + } else { + host == self.host + }; + let port_ok = match self.port { + Port::Web => port == 80 || port == 443, + Port::Any => true, + Port::One(p) => p == port, + }; + host_ok && port_ok + } +} + +/// `host:port` split, keeping an IPv6 literal in brackets whole. +fn split_host_port(text: &str) -> (&str, Option<&str>) { + if let Some(rest) = text.strip_prefix('[') { + if let Some(end) = rest.find(']') { + let host = &text[..end + 2]; + let port = rest[end + 1..].strip_prefix(':'); + return (host, port); + } + } + match text.rsplit_once(':') { + Some((h, p)) if !h.contains(':') => (h, Some(p)), + _ => (text, None), + } +} + +fn normalise_host(host: &str) -> String { + host.trim_matches(|c| c == '[' || c == ']') + .trim_end_matches('.') + .to_ascii_lowercase() +} + +/// The proxy's allowlist and settings. +#[derive(Debug, Clone)] +pub struct Allowlist { + rules: Vec, + allow_private: bool, +} + +impl Allowlist { + /// # Errors + /// When an entry does not parse. + pub fn new(entries: &[String], allow_private: bool) -> Result { + let rules = entries + .iter() + .map(|e| Rule::parse(e)) + .collect::>()?; + Ok(Self { + rules, + allow_private, + }) + } + + #[must_use] + pub fn allows(&self, host: &str, port: u16) -> bool { + let host = normalise_host(host); + self.rules.iter().any(|r| r.allows(&host, port)) + } +} + +/// Whether an address is one an allowed public name must never lead to. +#[must_use] +pub fn is_private(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => { + let [a, b, ..] = v4.octets(); + v4.is_loopback() + || v4.is_private() + || v4.is_link_local() + || v4.is_unspecified() + || v4.is_broadcast() + || v4.is_multicast() + || (a == 100 && (64..128).contains(&b)) + } + IpAddr::V6(v6) => { + if let Some(v4) = v6.to_ipv4_mapped() { + return is_private(IpAddr::V4(v4)); + } + let first = v6.segments()[0]; + v6.is_loopback() + || v6.is_unspecified() + || v6.is_multicast() + || (first & 0xfe00) == 0xfc00 + || (first & 0xffc0) == 0xfe80 + } + } +} + +/// One decision the proxy made, for the report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decision { + pub target: String, + pub allowed: bool, + pub reason: String, +} + +/// Where requests go after the allowlist: straight out, or through the proxy +/// this process itself was given. +#[derive(Debug, Clone)] +pub struct Upstream { + addr: String, + authorization: Option, +} + +impl Upstream { + /// The upstream named by `HTTPS_PROXY` / `https_proxy` / `HTTP_PROXY` / + /// `http_proxy` in `env`, if it is an `http://` proxy. + pub fn from_env(get: impl Fn(&str) -> Option) -> Option { + let raw = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"] + .iter() + .find_map(|k| get(k).filter(|v| !v.is_empty()))?; + let rest = raw.strip_prefix("http://")?; + let rest = rest.trim_end_matches('/'); + let (auth, addr) = match rest.rsplit_once('@') { + Some((auth, addr)) => (Some(auth), addr), + None => (None, rest), + }; + Some(Self { + addr: addr.to_string(), + authorization: auth.map(|a| format!("Basic {}", base64(a.as_bytes()))), + }) + } +} + +/// A running proxy. Dropping it stops accepting new connections. +pub struct Proxy { + port: u16, + decisions: Arc>>, + stop: Arc, + pub upstream: Option, +} + +impl Proxy { + /// Start listening on 127.0.0.1 on a free port. + /// + /// # Errors + /// When no port can be bound. + pub fn start(allowlist: Allowlist, upstream: Option) -> io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0))?; + let port = listener.local_addr()?.port(); + let decisions = Arc::new(Mutex::new(Vec::new())); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let shared = Arc::new((allowlist, upstream.clone())); + { + let decisions = Arc::clone(&decisions); + let stop = Arc::clone(&stop); + thread::spawn(move || { + for conn in listener.incoming() { + if stop.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + let Ok(conn) = conn else { continue }; + let shared = Arc::clone(&shared); + let decisions = Arc::clone(&decisions); + thread::spawn(move || { + let (allowlist, upstream) = &*shared; + if let Some(d) = serve(conn, allowlist, upstream.as_ref()) { + if let Ok(mut all) = decisions.lock() { + all.push(d); + } + } + }); + } + }); + } + Ok(Self { + port, + decisions, + stop, + upstream: upstream.map(|u| u.addr), + }) + } + + #[must_use] + pub fn port(&self) -> u16 { + self.port + } + + /// The proxy URL a client is given. + #[must_use] + pub fn url(&self) -> String { + format!("http://127.0.0.1:{}", self.port) + } + + /// Every decision so far. + #[must_use] + pub fn decisions(&self) -> Vec { + self.decisions.lock().map(|d| d.clone()).unwrap_or_default() + } + + /// The variables that point a client at this proxy. + #[must_use] + pub fn client_env(&self) -> Vec<(String, String)> { + let url = self.url(); + let mut out: Vec<(String, String)> = [ + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "http_proxy", + "https_proxy", + "all_proxy", + ] + .iter() + .map(|k| ((*k).to_string(), url.clone())) + .collect(); + // Nothing bypasses the proxy: a bypassed host would be refused by + // the kernel anyway, with a less helpful error. + out.push(("NO_PROXY".into(), String::new())); + out.push(("no_proxy".into(), String::new())); + out + } +} + +impl Drop for Proxy { + fn drop(&mut self) { + self.stop.store(true, std::sync::atomic::Ordering::Relaxed); + // Wake the accept loop so it sees the flag. + let _ = TcpStream::connect(("127.0.0.1", self.port)); + } +} + +/// The parsed head of one client request. +struct Head { + method: String, + host: String, + port: u16, + /// For plain HTTP: the head rewritten for the origin server. + forward: Option>, +} + +fn serve( + client: TcpStream, + allowlist: &Allowlist, + upstream: Option<&Upstream>, +) -> Option { + let _ = client.set_read_timeout(Some(IO_TIMEOUT)); + let mut reader = BufReader::new(client.try_clone().ok()?); + let mut writer = client; + let head = match read_head(&mut reader) { + Ok(h) => h, + Err(e) => { + let _ = respond(&mut writer, 400, &e); + return None; + } + }; + let target = format!("{}:{}", head.host, head.port); + + if !allowlist.allows(&head.host, head.port) { + let reason = "not in network.allow".to_string(); + let _ = respond(&mut writer, 403, &format!("sbx: {target} is {reason}")); + return Some(Decision { + target, + allowed: false, + reason, + }); + } + + let upstream_conn = match upstream { + Some(up) => connect_via(up, &head.host, head.port), + None => connect_direct(&head.host, head.port, allowlist.allow_private), + }; + let mut server = match upstream_conn { + Ok(s) => s, + Err(reason) => { + let _ = respond(&mut writer, 502, &format!("sbx: {target}: {reason}")); + return Some(Decision { + target, + allowed: false, + reason, + }); + } + }; + + if head.method == "CONNECT" { + if writer + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .is_err() + { + return None; + } + } else if let Some(forward) = &head.forward { + if server.write_all(forward).is_err() { + return None; + } + } + // Whatever the client sent after the head is still in the reader. + let buffered = reader.buffer().to_vec(); + if !buffered.is_empty() && server.write_all(&buffered).is_err() { + return None; + } + pipe(writer, server); + Some(Decision { + target, + allowed: true, + reason: if upstream.is_some() { + "allowed (through the upstream proxy)".into() + } else { + "allowed".into() + }, + }) +} + +fn read_head(reader: &mut BufReader) -> Result { + let mut lines = Vec::new(); + let mut total = 0; + loop { + let mut line = String::new(); + let n = reader + .read_line(&mut line) + .map_err(|e| format!("reading the request: {e}"))?; + total += n; + if n == 0 || total > HEAD_LIMIT { + return Err("incomplete or oversized request head".into()); + } + if line == "\r\n" || line == "\n" { + break; + } + lines.push(line.trim_end_matches(['\r', '\n']).to_string()); + } + let first = lines.first().ok_or("empty request")?; + let mut parts = first.split_whitespace(); + let method = parts.next().ok_or("no method")?.to_string(); + let target = parts.next().ok_or("no target")?.to_string(); + let version = parts.next().unwrap_or("HTTP/1.1").to_string(); + + if method.eq_ignore_ascii_case("CONNECT") { + let (host, port) = split_host_port(&target); + let port = port + .and_then(|p| p.parse().ok()) + .ok_or("CONNECT needs host:port")?; + return Ok(Head { + method: "CONNECT".into(), + host: normalise_host(host), + port, + forward: None, + }); + } + + let rest = target + .strip_prefix("http://") + .ok_or("only absolute http:// requests and CONNECT are proxied")?; + let (authority, path) = match rest.find('/') { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, "/"), + }; + let (host, port) = split_host_port(authority); + let port = match port { + Some(p) => p.parse().map_err(|_| "bad port")?, + None => 80, + }; + let mut forward = format!("{method} {path} {version}\r\n"); + for line in &lines[1..] { + let name = line.split(':').next().unwrap_or("").trim(); + if name.eq_ignore_ascii_case("connection") + || name.eq_ignore_ascii_case("proxy-connection") + || name.to_ascii_lowercase().starts_with("proxy-") + { + continue; + } + forward.push_str(line); + forward.push_str("\r\n"); + } + forward.push_str("Connection: close\r\n\r\n"); + Ok(Head { + method, + host: normalise_host(host), + port, + forward: Some(forward.into_bytes()), + }) +} + +/// Resolve once, refuse a private answer unless allowed, and connect to the +/// very address that was checked. +fn connect_direct(host: &str, port: u16, allow_private: bool) -> Result { + let addrs: Vec = (host, port) + .to_socket_addrs() + .map_err(|e| format!("cannot resolve: {e}"))? + .collect(); + let usable: Vec = addrs + .iter() + .copied() + .filter(|a| allow_private || !is_private(a.ip())) + .collect(); + if usable.is_empty() { + return Err(if addrs.is_empty() { + "resolved to no address".into() + } else { + "resolves only to private addresses (set network.allow_private to permit)".into() + }); + } + let mut last = String::from("no address answered"); + for addr in usable { + match TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) { + Ok(s) => return Ok(s), + Err(e) => last = format!("{addr}: {e}"), + } + } + Err(last) +} + +/// A tunnel to `host:port` through the upstream proxy. +fn connect_via(up: &Upstream, host: &str, port: u16) -> Result { + let addr = up + .addr + .to_socket_addrs() + .map_err(|e| format!("upstream proxy {}: {e}", up.addr))? + .next() + .ok_or_else(|| format!("upstream proxy {} resolved to nothing", up.addr))?; + let mut stream = TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) + .map_err(|e| format!("upstream proxy {}: {e}", up.addr))?; + let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); + let authority = if host.contains(':') { + format!("[{host}]:{port}") + } else { + format!("{host}:{port}") + }; + let mut req = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n"); + if let Some(auth) = &up.authorization { + req.push_str(&format!("Proxy-Authorization: {auth}\r\n")); + } + req.push_str("\r\n"); + stream + .write_all(req.as_bytes()) + .map_err(|e| format!("upstream proxy: {e}"))?; + // Read the reply head byte by byte so nothing past it is consumed. + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + if head.len() > HEAD_LIMIT { + return Err("upstream proxy reply too large".into()); + } + match stream.read(&mut byte) { + Ok(1) => head.push(byte[0]), + _ => return Err("upstream proxy closed the connection".into()), + } + } + let status = String::from_utf8_lossy(&head); + let code = status.split_whitespace().nth(1).unwrap_or(""); + if code != "200" { + let line = status.lines().next().unwrap_or("").to_string(); + return Err(format!("upstream proxy refused: {line}")); + } + let _ = stream.set_read_timeout(None); + Ok(stream) +} + +fn respond(writer: &mut TcpStream, code: u16, message: &str) -> io::Result<()> { + let reason = match code { + 400 => "Bad Request", + 403 => "Forbidden", + _ => "Bad Gateway", + }; + let body = format!("{message}\n"); + write!( + writer, + "HTTP/1.1 {code} {reason}\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) +} + +/// Copy both ways until either side closes. +fn pipe(client: TcpStream, server: TcpStream) { + let _ = client.set_read_timeout(None); + let _ = server.set_read_timeout(None); + let (Ok(mut c2), Ok(mut s2)) = (client.try_clone(), server.try_clone()) else { + return; + }; + let up = thread::spawn(move || { + let mut client = client; + let mut server = server; + let _ = io::copy(&mut client, &mut server); + let _ = server.shutdown(Shutdown::Write); + }); + let _ = io::copy(&mut s2, &mut c2); + let _ = c2.shutdown(Shutdown::Write); + let _ = up.join(); +} + +fn base64(input: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in input.chunks(3) { + let b = [ + chunk[0], + *chunk.get(1).unwrap_or(&0), + *chunk.get(2).unwrap_or(&0), + ]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for i in 0..4 { + if i <= chunk.len() { + out.push(T[((n >> (18 - 6 * i)) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn list(entries: &[&str]) -> Allowlist { + let entries: Vec = entries.iter().map(|s| (*s).to_string()).collect(); + Allowlist::new(&entries, false).expect("parses") + } + + #[test] + fn rules_match_hosts_ports_and_wildcards() { + let l = list(&["crates.io", "*.npmjs.org", "example.com:8443", "any.dev:*"]); + assert!(l.allows("crates.io", 443)); + assert!(l.allows("CRATES.IO.", 80)); + assert!(!l.allows("crates.io", 22)); + assert!(!l.allows("static.crates.io", 443), "no implicit subdomains"); + assert!(l.allows("registry.npmjs.org", 443)); + assert!(!l.allows("npmjs.org", 443), "a wildcard is not the apex"); + assert!(!l.allows("evilnpmjs.org", 443)); + assert!(l.allows("example.com", 8443)); + assert!(!l.allows("example.com", 443)); + assert!(l.allows("any.dev", 5432)); + } + + #[test] + fn bad_rules_are_errors() { + for bad in ["", "a.*.com", "host:port", "http://x.com"] { + assert!(Rule::parse(bad).is_err(), "{bad} should not parse"); + } + assert!(Rule::parse("[::1]:443").is_ok()); + } + + #[test] + fn private_addresses_are_recognised() { + for ip in [ + "127.0.0.1", + "10.1.2.3", + "172.16.0.1", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "0.0.0.0", + "::1", + "fd00::1", + "fe80::1", + "::ffff:127.0.0.1", + ] { + assert!(is_private(ip.parse().expect("ip")), "{ip}"); + } + for ip in ["1.1.1.1", "140.82.112.3", "2606:4700::1111"] { + assert!(!is_private(ip.parse().expect("ip")), "{ip}"); + } + } + + #[test] + fn upstream_is_read_with_credentials() { + let up = Upstream::from_env(|k| { + (k == "https_proxy").then(|| "http://user:pa%20ss@proxy.local:3128/".to_string()) + }) + .expect("an http proxy"); + assert_eq!(up.addr, "proxy.local:3128"); + assert_eq!(up.authorization.as_deref(), Some("Basic dXNlcjpwYSUyMHNz")); + assert!(Upstream::from_env(|_| Some("socks5://x:1".into())).is_none()); + } + + #[test] + fn base64_matches_the_rfc_vectors() { + for (input, want) in [ + ("", ""), + ("f", "Zg=="), + ("fo", "Zm8="), + ("foo", "Zm9v"), + ("foobar", "Zm9vYmFy"), + ] { + assert_eq!(base64(input.as_bytes()), want); + } + } + + /// A refused host gets a 403 that names it, and the decision is kept. + #[test] + fn a_host_outside_the_list_is_refused_with_a_reason() { + let proxy = Proxy::start(list(&["allowed.example"]), None).expect("starts"); + let mut s = TcpStream::connect(("127.0.0.1", proxy.port())).expect("connects"); + s.write_all(b"CONNECT denied.example:443 HTTP/1.1\r\nHost: denied.example:443\r\n\r\n") + .expect("writes"); + let mut reply = String::new(); + s.read_to_string(&mut reply).expect("reads"); + assert!(reply.starts_with("HTTP/1.1 403"), "{reply}"); + assert!(reply.contains("denied.example:443"), "{reply}"); + thread::sleep(Duration::from_millis(50)); + let d = proxy.decisions(); + assert_eq!(d.len(), 1); + assert!(!d[0].allowed); + } + + /// Plain HTTP to an allowed host is forwarded in origin form with + /// `Connection: close`, and a private answer is refused unless allowed. + #[test] + fn plain_http_is_forwarded_and_private_answers_need_permission() { + let origin = TcpListener::bind(("127.0.0.1", 0)).expect("binds"); + let port = origin.local_addr().expect("addr").port(); + let server = thread::spawn(move || { + let (mut conn, _) = origin.accept().expect("accepts"); + let mut buf = [0u8; 4096]; + let n = conn.read(&mut buf).expect("reads"); + let req = String::from_utf8_lossy(&buf[..n]).into_owned(); + conn.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + .expect("writes"); + req + }); + + let rule = format!("localhost:{port}"); + let strict = Proxy::start(list(&[&rule]), None).expect("starts"); + let mut s = TcpStream::connect(("127.0.0.1", strict.port())).expect("connects"); + write!( + s, + "GET http://localhost:{port}/x HTTP/1.1\r\nHost: localhost\r\n\r\n" + ) + .expect("writes"); + let mut reply = String::new(); + s.read_to_string(&mut reply).expect("reads"); + assert!(reply.starts_with("HTTP/1.1 502"), "{reply}"); + assert!(reply.contains("private"), "{reply}"); + + let open = + Proxy::start(Allowlist::new(&[rule], true).expect("parses"), None).expect("starts"); + let mut s = TcpStream::connect(("127.0.0.1", open.port())).expect("connects"); + write!( + s, + "GET http://localhost:{port}/x HTTP/1.1\r\nHost: localhost\r\nProxy-Connection: keep-alive\r\n\r\n" + ) + .expect("writes"); + let mut reply = String::new(); + s.read_to_string(&mut reply).expect("reads"); + assert!(reply.ends_with("ok"), "{reply}"); + let seen = server.join().expect("server"); + assert!(seen.starts_with("GET /x HTTP/1.1\r\n"), "{seen}"); + assert!(seen.contains("Connection: close"), "{seen}"); + assert!( + !seen.to_ascii_lowercase().contains("proxy-connection"), + "{seen}" + ); + } +} diff --git a/crates/sandbox/src/seatbelt.rs b/crates/sandbox/src/seatbelt.rs new file mode 100644 index 0000000..b35c904 --- /dev/null +++ b/crates/sandbox/src/seatbelt.rs @@ -0,0 +1,118 @@ +//! macOS: `sandbox-exec` with a generated Seatbelt profile. +//! +//! The command becomes `sandbox-exec -D TMP=… -D WS0=… -p +//! …`; the profile is in force for the helper and everything it execs. Paths +//! go in as `-D` parameters, never interpolated, so a quote or backslash in +//! a path cannot break the profile; they are canonicalised first because +//! Seatbelt matches resolved paths. +//! +//! The profile is generated and unit-tested on every platform. It follows the +//! shape incode's sandbox ran on macOS 26 (writes confined, children +//! confined, `git`/`cc` working); the network clauses for `proxy` follow the +//! forms shipping profiles use and have NOT yet been run on a Mac. + +use crate::policy::{FsMode, NetMode}; + +/// Where the tool is. A fixed path, so a workspace cannot shadow it on PATH. +pub const SANDBOX_EXEC: &str = "/usr/bin/sandbox-exec"; + +/// The profile for `fs` with `roots` writable roots, and `net` (with the +/// proxy's port under `proxy`). The last matching rule wins, so each deny is +/// stated before its allows. +#[must_use] +pub fn profile( + fs: FsMode, + roots: usize, + deny_read: usize, + net: NetMode, + proxy_port: Option, +) -> String { + let mut p = String::from("(version 1) (allow default)"); + if fs != FsMode::Off { + let mut allow = String::from("(subpath (param \"TMP\"))"); + for i in 0..roots { + allow.push_str(&format!(" (subpath (param \"WS{i}\"))")); + } + p.push_str(&format!( + " (deny file-write* (subpath \"/\")) \ + (allow file-write* {allow} \ + (literal \"/dev/null\") (literal \"/dev/zero\") (literal \"/dev/tty\") \ + (literal \"/dev/dtracehelper\") (regex #\"^/dev/fd/[0-9]+$\") \ + (regex #\"^/dev/ttys[0-9]+$\"))" + )); + for i in 0..deny_read { + p.push_str(&format!(" (deny file-read* (subpath (param \"DR{i}\")))")); + } + } + match net { + NetMode::Allow => {} + NetMode::Deny | NetMode::Proxy => { + // Unix-domain sockets stay allowed: they are local IPC (an + // ssh-agent, a build daemon), not the network. + p.push_str( + " (deny network*) \ + (allow network-bind (local unix-socket (path-regex #\"^/\"))) \ + (allow network-outbound (remote unix-socket (path-regex #\"^/\")))", + ); + if let (NetMode::Proxy, Some(port)) = (net, proxy_port) { + p.push_str(&format!( + " (allow network-outbound (remote ip \"localhost:{port}\"))" + )); + } + } + } + p +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn workspace_write_denies_then_allows_the_roots() { + let p = profile(FsMode::WorkspaceWrite, 2, 0, NetMode::Allow, None); + let deny = p.find("(deny file-write*").expect("deny"); + let allow = p.find("(allow file-write*").expect("allow"); + assert!(deny < allow, "the deny comes first: {p}"); + assert!(p.contains("(param \"WS0\")") && p.contains("(param \"WS1\")")); + assert!(!p.contains("network")); + } + + #[test] + fn read_only_has_only_the_temp_dir_and_sinks() { + let p = profile(FsMode::ReadOnly, 0, 0, NetMode::Allow, None); + assert!(!p.contains("WS0")); + assert!(p.contains("(param \"TMP\")")); + } + + #[test] + fn proxy_allows_exactly_the_proxy_port() { + let p = profile(FsMode::Off, 0, 0, NetMode::Proxy, Some(41234)); + assert!(p.contains("(deny network*)")); + assert!(p.contains("(remote ip \"localhost:41234\")")); + assert!(!p.contains("file-write")); + let deny = profile(FsMode::Off, 0, 0, NetMode::Deny, None); + assert!(!deny.contains("remote ip")); + } + + #[test] + fn deny_read_comes_after_the_allow_default() { + let p = profile(FsMode::ReadOnly, 0, 2, NetMode::Allow, None); + let allow = p.find("(allow default)").expect("allow"); + let deny = p + .find("(deny file-read* (subpath (param \"DR0\")))") + .expect("DR0"); + assert!(allow < deny, "{p}"); + assert!(p.contains("(param \"DR1\")")); + } + + #[test] + fn parentheses_balance() { + for net in [NetMode::Allow, NetMode::Deny, NetMode::Proxy] { + let p = profile(FsMode::WorkspaceWrite, 3, 2, net, Some(1)); + let open = p.matches('(').count(); + let close = p.matches(')').count(); + assert_eq!(open, close, "{p}"); + } + } +} diff --git a/crates/sandbox/tests/escape.rs b/crates/sandbox/tests/escape.rs new file mode 100644 index 0000000..fba97af --- /dev/null +++ b/crates/sandbox/tests/escape.rs @@ -0,0 +1,374 @@ +//! Escape tests: each one tries to get out of the sandbox the way a confused +//! or hostile command would, through the real `sbx` binary. +//! +//! Linux only, and each test skips (with a note) when the kernel cannot +//! enforce what it checks, so a machine without Landlock reports a skip +//! rather than a false pass. + +#![cfg(target_os = "linux")] + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::path::Path; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +const SBX: &str = env!("CARGO_BIN_EXE_sbx"); + +fn sbx(args: &[&str], cwd: &Path) -> Output { + Command::new(SBX) + .args(args) + .current_dir(cwd) + .stdin(Stdio::null()) + .output() + .expect("sbx runs") +} + +fn sh(cwd: &Path, flags: &[&str], script: &str) -> Output { + let mut args = vec!["run"]; + args.extend_from_slice(flags); + args.extend_from_slice(&["--", "sh", "-c", script]); + sbx(&args, cwd) +} + +fn text(o: &Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&o.stdout), + String::from_utf8_lossy(&o.stderr) + ) +} + +fn landlock_fs() -> bool { + let o = Command::new(SBX) + .args(["check", "--fs", "workspace-write"]) + .output() + .expect("check"); + o.status.success() +} + +fn landlock_net() -> bool { + Command::new(SBX) + .args(["check", "--net", "deny"]) + .output() + .expect("check") + .status + .success() +} + +macro_rules! require { + ($cond:expr, $what:expr) => { + if !$cond { + eprintln!("SKIPPED: this kernel cannot enforce {}", $what); + return; + } + }; +} + +struct Dirs { + _root: tempfile::TempDir, + ws: std::path::PathBuf, + out: std::path::PathBuf, +} + +fn dirs() -> Dirs { + let root = tempfile::tempdir().expect("tempdir"); + let ws = root.path().join("ws"); + let out = root.path().join("out"); + std::fs::create_dir(&ws).expect("ws"); + std::fs::create_dir(&out).expect("out"); + Dirs { + ws, + out, + _root: root, + } +} + +#[test] +fn writes_land_only_inside_the_writable_root() { + require!(landlock_fs(), "the filesystem"); + let d = dirs(); + let outside = d.out.join("x"); + let o = sh( + &d.ws, + &["-w", "."], + &format!("echo ok > inside && echo bad > {}", outside.display()), + ); + assert!(d.ws.join("inside").exists(), "{}", text(&o)); + assert!(!outside.exists(), "wrote outside the root: {}", text(&o)); + assert!(!o.status.success()); +} + +#[test] +fn symlinks_hardlinks_renames_and_proc_root_do_not_escape() { + require!(landlock_fs(), "the filesystem"); + let d = dirs(); + std::fs::write(d.out.join("f"), "secret").expect("seed"); + std::os::unix::fs::symlink(&d.out, d.ws.join("link")).expect("symlink"); + let out = d.out.display(); + for script in [ + "echo bad > link/via-symlink".to_string(), + format!("ln {out}/f hl && echo pwned > hl"), + format!("mv {out}/f ./moved"), + format!("echo bad > /proc/self/root{out}/via-proc"), + format!("sh -c 'touch {out}/via-child'"), + ] { + let o = sh(&d.ws, &["-w", "."], &script); + assert!(!o.status.success(), "`{script}` succeeded: {}", text(&o)); + } + let mut left: Vec = std::fs::read_dir(&d.out) + .expect("read") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .collect(); + left.sort(); + assert_eq!(left, ["f"], "something escaped into {out}"); + assert_eq!( + std::fs::read_to_string(d.out.join("f")).expect("f"), + "secret" + ); +} + +#[test] +fn temp_is_private_and_shared_tmp_is_not_writable() { + require!(landlock_fs(), "the filesystem"); + let d = dirs(); + let marker = std::env::temp_dir().join(format!("sbx-escape-{}", std::process::id())); + let o = sh( + &d.ws, + &["-w", "."], + &format!( + "touch \"$TMPDIR/ok\" && echo \"$TMPDIR\"; touch {}", + marker.display() + ), + ); + let out = text(&o); + assert!(out.contains("sbx-"), "TMPDIR is the private one: {out}"); + assert!(!marker.exists(), "wrote to the shared temp dir"); +} + +#[test] +fn deny_read_hides_a_path_through_every_route() { + require!(landlock_fs(), "the filesystem"); + let d = dirs(); + std::fs::write(d.out.join("answer"), "42").expect("seed"); + std::os::unix::fs::symlink(&d.out, d.ws.join("peek")).expect("symlink"); + let out = d.out.display(); + for script in [ + format!("cat {out}/answer"), + format!("ls {out}"), + "cat peek/answer".to_string(), + format!("cat /proc/self/root{out}/answer"), + format!("cd {out}/.. && cat out/answer"), + format!("sh -c 'cat {out}/answer'"), + ] { + let o = sh( + &d.ws, + &["-w", ".", "--deny-read", &out.to_string()], + &script, + ); + assert!( + !String::from_utf8_lossy(&o.stdout).contains("42"), + "`{script}` read the hidden file: {}", + text(&o) + ); + } + // Everything else is still readable, the workspace included. Listing + // a directory ABOVE the hidden path is refused (Landlock grants whole + // subtrees, so `/` itself is not granted); reading beneath it is not. + std::fs::write(d.ws.join("mine"), "ok").expect("seed"); + let o = sh( + &d.ws, + &["-w", ".", "--deny-read", &out.to_string()], + "cat mine && cat /etc/hostname >/dev/null && ls /usr >/dev/null && echo fine", + ); + assert!(text(&o).contains("okfine"), "{}", text(&o)); +} + +#[test] +fn deny_read_inside_a_writable_root_is_refused() { + let d = dirs(); + std::fs::create_dir(d.ws.join("secret")).expect("mkdir"); + let o = sh(&d.ws, &["-w", ".", "--deny-read", "secret"], "true"); + assert_eq!(o.status.code(), Some(125), "{}", text(&o)); + assert!( + text(&o).contains("inside the writable root"), + "{}", + text(&o) + ); +} + +#[test] +fn read_only_writes_nothing() { + require!(landlock_fs(), "the filesystem"); + let d = dirs(); + let o = sh(&d.ws, &["--fs", "read-only"], "touch x"); + assert!(!o.status.success()); + assert!(!d.ws.join("x").exists()); +} + +#[test] +fn network_deny_refuses_connect_and_bind_even_on_loopback() { + require!(landlock_net(), "TCP (Landlock ABI v4)"); + let d = dirs(); + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind"); + let port = listener.local_addr().expect("addr").port(); + let script = format!( + "exec 3<>/dev/tcp/127.0.0.1/{port} 2>/dev/null && echo connected; \ + python3 -c 'import socket;socket.socket().bind((\"127.0.0.1\",0));print(\"bound\")' 2>/dev/null" + ); + let o = sbx( + &["run", "--net", "deny", "--", "bash", "-c", &script], + &d.ws, + ); + let out = text(&o); + assert!(!out.contains("connected"), "{out}"); + assert!(!out.contains("bound"), "{out}"); +} + +#[test] +fn the_proxy_lets_through_only_the_allowlist_and_cannot_be_bypassed() { + require!(landlock_net(), "TCP (Landlock ABI v4)"); + let d = dirs(); + let origin = TcpListener::bind(("127.0.0.1", 0)).expect("bind"); + let port = origin.local_addr().expect("addr").port(); + std::thread::spawn(move || { + for conn in origin.incoming() { + let Ok(mut conn) = conn else { continue }; + let mut buf = [0u8; 2048]; + let _ = conn.read(&mut buf); + let _ = conn.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\norigin"); + } + }); + let allow = format!("localhost:{port}"); + let script = format!( + "printf 'allowed='; curl -s --max-time 5 http://localhost:{port}/; echo; \ + printf 'other='; curl -s --max-time 5 http://127.0.0.1:{port}/ | head -c 40; echo; \ + printf 'bypass='; curl -s --max-time 5 --noproxy '*' http://localhost:{port}/; echo" + ); + // The test origin is on loopback, so private answers must be allowed, + // and this process's own upstream proxy (if any) must not be used. + let o = Command::new(SBX) + .args([ + "run", + "--allow-host", + &allow, + "--allow-private", + "--", + "sh", + "-c", + &script, + ]) + .current_dir(&d.ws) + .env_remove("HTTPS_PROXY") + .env_remove("https_proxy") + .env_remove("HTTP_PROXY") + .env_remove("http_proxy") + .stdin(Stdio::null()) + .output() + .expect("sbx"); + let out = text(&o); + assert!(out.contains("allowed=origin"), "{out}"); + assert!(out.contains("other=sbx: 127.0.0.1"), "{out}"); + assert!( + out.contains("bypass=\n"), + "the direct connection got through: {out}" + ); + assert!(out.contains("network refused 127.0.0.1"), "{out}"); +} + +#[test] +fn the_agent_session_and_git_redirects_are_stripped_and_credentials_kept() { + let d = dirs(); + let o = Command::new(SBX) + .args([ + "run", + "--", + "sh", + "-c", + "echo \"[$CLAUDECODE][$CLAUDE_CODE_SESSION_ID][$GIT_DIR][$ANTHROPIC_API_KEY]\"", + ]) + .current_dir(&d.ws) + .env("CLAUDECODE", "1") + .env("CLAUDE_CODE_SESSION_ID", "parent") + .env("GIT_DIR", "/elsewhere/.git") + .env("ANTHROPIC_API_KEY", "key") + .output() + .expect("sbx"); + assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), "[][][][key]"); +} + +#[test] +fn the_wall_limit_kills_the_whole_group() { + let d = dirs(); + let tag = format!("sbx_wall_{}", std::process::id()); + let start = Instant::now(); + let script = format!("(exec -a {tag} sleep 30) & (exec -a {tag} sleep 30)"); + let o = sbx(&["run", "--wall", "1", "--", "bash", "-c", &script], &d.ws); + assert_eq!(o.status.code(), Some(124), "{}", text(&o)); + assert!(start.elapsed() < Duration::from_secs(10)); + std::thread::sleep(Duration::from_millis(300)); + assert!(!running(&tag), "a process outlived the wall limit"); +} + +#[test] +fn killing_sbx_with_sigkill_takes_the_command_with_it() { + let d = dirs(); + let tag = format!("sbx_orphan_{}", std::process::id()); + let mut child = Command::new(SBX) + .args([ + "run", + "--wall", + "60", + "--", + "bash", + "-c", + &format!("(exec -a {tag} sleep 30) & (exec -a {tag} sleep 30)"), + ]) + .current_dir(&d.ws) + .stdin(Stdio::null()) + .spawn() + .expect("sbx"); + let deadline = Instant::now() + Duration::from_secs(5); + while !running(&tag) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(running(&tag), "the command never started"); + child.kill().expect("SIGKILL"); + let _ = child.wait(); + let deadline = Instant::now() + Duration::from_secs(3); + while running(&tag) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(!running(&tag), "the command outlived sbx"); +} + +#[test] +fn limits_and_exit_codes() { + let d = dirs(); + let o = sh(&d.ws, &["--wall", "5"], "exit 7"); + assert_eq!(o.status.code(), Some(7)); + let o = sh(&d.ws, &[], "kill -9 $$"); + assert_eq!(o.status.code(), Some(137)); + let o = sh(&d.ws, &["--fsize", "1"], "head -c 3000000 /dev/zero > big"); + assert!(!o.status.success()); + assert_eq!( + std::fs::metadata(d.ws.join("big")).expect("big").len(), + 1024 * 1024 + ); + let o = sbx(&["run", "--", "no-such-command-sbx"], &d.ws); + assert_eq!(o.status.code(), Some(127)); + let o = sbx(&["run", "-w", "missing-root", "--", "true"], &d.ws); + assert_eq!(o.status.code(), Some(125)); +} + +/// Whether a process whose argv[0] is `tag` is running. +fn running(tag: &str) -> bool { + std::fs::read_dir("/proc") + .expect("proc") + .filter_map(Result::ok) + .any(|e| { + std::fs::read(e.path().join("cmdline")) + .ok() + .is_some_and(|c| c.split(|b| *b == 0).next() == Some(tag.as_bytes())) + }) +} From 1b59a53f40720482c8a7085865be1459965b5d6f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 13:34:43 +0000 Subject: [PATCH 2/2] sandbox: seccomp for the sockets Landlock misses; macOS escape tests Landlock's network rules cover TCP bind/connect only. Under `deny` and `proxy` the helper now also installs a hand-written seccomp-bpf filter (after Landlock, before exec) that lets socket() create only AF_UNIX, AF_NETLINK and plain TCP (AF_INET/AF_INET6, SOCK_STREAM, protocol 0 or IPPROTO_TCP, with SOCK_NONBLOCK/SOCK_CLOEXEC masked off); everything else fails with EACCES. It is an allowlist rather than a UDP/raw/packet blocklist because SCTP and MPTCP are not TCP to Landlock either. io_uring_setup/enter/register get EPERM (io_uring creates sockets past seccomp). x86-64 filters i386 (int 0x80, socketcall(SYS_SOCKET) refused) and x32 too; aarch64 filters 32-bit ARM. An unknown audit arch is killed; other build architectures install nothing and report the network as not enforced, so strict mode refuses. AF_NETLINK stays: getaddrinfo and ip need it, it can only read interfaces/routes without CAP_NET_ADMIN, and nothing on it leaves the machine. No new dependency (no seccomp crate was in Cargo.lock; ~40 BPF instructions with libc constants). Measured on Linux 6.18 (root, x86-64), old sbx vs new, --net deny: - UDP sendto 127.0.0.1: delivered -> EACCES (also with NONBLOCK|CLOEXEC) - raw and AF_PACKET sockets: opened -> EACCES - MPTCP connect to a loopback listener: connected -> EACCES (plain TCP was already EACCES via Landlock) - i386 socket(AF_INET, SOCK_DGRAM) via int 0x80: fd 3 -> -EACCES - getaddrinfo/getent example.com: resolved -> fails (EAI_AGAIN) - AF_UNIX, netlink, --net allow UDP: unchanged Lookups a local daemon answers over a Unix socket (nss-resolve, nscd) still work; README says so and the DNS test skips there. net_status, the README and lib docs now say UDP/DNS are covered. New Linux escape tests: UDP/raw/packet refused under deny and proxy (and no datagram arrives), UDP works under allow, DNS fails under deny (with a control lookup). New tests/escape_macos.rs mirrors the escape tests that apply to Seatbelt (writes, symlinks, children, read-only, deny_read by several routes, TCP deny with a control, proxy allowlist and bypass, env, wall limit, SIGKILL cleanup, exit codes) using only sh/bash/nc/curl/ps; checked to compile for x86_64-apple-darwin, to run on the macOS CI job. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- .github/workflows/ci.yml | 4 +- crates/sandbox/README.md | 36 ++- crates/sandbox/src/lib.rs | 19 +- crates/sandbox/src/linux.rs | 41 ++- crates/sandbox/src/seccomp.rs | 433 +++++++++++++++++++++++++++ crates/sandbox/tests/escape.rs | 101 ++++++- crates/sandbox/tests/escape_macos.rs | 377 +++++++++++++++++++++++ 7 files changed, 983 insertions(+), 28 deletions(-) create mode 100644 crates/sandbox/src/seccomp.rs create mode 100644 crates/sandbox/tests/escape_macos.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 493f312..4c412de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,8 +58,8 @@ jobs: - run: cargo clippy --all-targets - run: cargo test --lib - run: cargo test --bins - # The standalone sandbox (`sbx`). Its escape tests are Linux-only and - # skip, saying so, on a kernel without Landlock. + # The standalone sandbox (`sbx`). Its escape tests run on Linux and + # macOS, and skip, saying so, where the OS cannot enforce what they check. - run: cargo clippy -p incord-sandbox --all-targets -- -D warnings - run: cargo test -p incord-sandbox # A test that writes outside its temp dir lands in the checkout — a diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 9b315b2..5b59fcd 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -61,8 +61,8 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. |---|---|---|---| | filesystem: write | Landlock (5.13+) | Seatbelt | **not yet** | | filesystem: `deny_read` | Landlock | Seatbelt | **not yet** | -| network: `deny` | Landlock TCP (6.7+) | Seatbelt | **not yet** | -| network: `proxy` | Landlock: TCP only to the proxy's port | Seatbelt: outbound only to the proxy | **not yet** | +| network: `deny` | Landlock TCP (6.7+) + seccomp for every other socket | Seatbelt | **not yet** | +| network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | **not yet** | | limits | `setrlimit` + wall clock | `setrlimit` + wall clock | wall clock | | environment | yes | yes | yes | @@ -71,6 +71,24 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. can't be widened again (`no_new_privs` is set). - **A private temp directory.** Each run gets one (`TMPDIR`, `TMP`, `TEMP`), removed afterwards. The shared `/tmp` is not writable. +- **Sockets Landlock does not see.** Landlock covers TCP only. Under `deny` + and `proxy` a seccomp filter makes `socket()` fail (`EACCES`) for anything + but Unix sockets, netlink and plain TCP: UDP, ICMP, raw and packet + sockets, SCTP and MPTCP (Landlock's TCP rules do not apply to them: an + MPTCP connect got through `deny` on Linux 6.18), and other families such + as `AF_VSOCK`. + - So under `deny`, DNS is blocked too: a lookup fails. Under `proxy` the + command never needed DNS; the proxy resolves names. + - Netlink stays: `getaddrinfo` and `ip` read the machine's addresses and + routes through it. A command can see the host's interfaces; changing + them needs a capability it does not have, and nothing sent on netlink + leaves the machine. + - `io_uring`, which can open sockets past a seccomp filter, is refused + (`EPERM`; runtimes fall back). On x86-64 the 32-bit syscall entry points + are filtered as well. + - The filter knows x86-64 and aarch64. On any other architecture none is + installed, the network is reported **not enforced**, and strict mode + refuses. - **The proxy.** `proxy` mode runs an allowlisting HTTP proxy in the unconfined parent and points the command at it (`HTTP(S)_PROXY`). - It sees host names, not content: TLS is tunnelled with `CONNECT`. @@ -95,8 +113,10 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. caller's own group kill reaches it. **Known limits:** -- Landlock does not cover UDP. Under `deny`, DNS still works. Under - `proxy`, the command doesn't need DNS, but it could still send UDP. +- A name lookup a local daemon answers over a Unix socket still works + under `deny`: with `nss-resolve` (systemd-resolved) or `nscd` in + `/etc/nsswitch.conf`, the name reaches the resolver and the answer comes + back. Plain `files dns` setups fail the lookup. - Landlock matches network ports, not addresses. Under `proxy` the command could connect to *any* host on the proxy's (random, high) port. - On macOS the profile is generated and unit-tested, but this crate's @@ -139,8 +159,12 @@ holds the proxy and the temp directory. - the unit tests (policy, environment, allowlist, Seatbelt profile); - on Linux, escape tests through the real binary: writes outside the root, symlinks, hard links, renames, `/proc/self/root`, child processes, reading - a hidden path, connecting and binding under `deny`, bypassing the proxy, - the wall limit and `SIGKILL` cleanup, limits and exit codes. + a hidden path, connecting and binding under `deny`, UDP and raw sockets + and DNS under `deny` and `proxy`, bypassing the proxy, the wall limit and + `SIGKILL` cleanup, limits and exit codes; +- on macOS, the same escapes against Seatbelt where they apply (writes, + symlinks, children, read-only, `deny_read`, TCP under `deny`, the proxy, + the environment, the wall limit). Each escape test skips, and says so, on a kernel that cannot enforce what it checks. diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 124db29..1c90b0e 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -14,8 +14,8 @@ //! parent (sbx, or your program) helper (same binary, re-executed) //! private temp dir setrlimit //! allowlisting proxy (network=proxy) Landlock restrict_self (Linux) -//! environment computed exec(command) ── confined from here on -//! wall-clock timer, process group +//! environment computed seccomp socket filter (Linux, network) +//! wall-clock timer, process group exec(command) ── confined from here on //! ``` //! //! On macOS the helper runs under `sandbox-exec` with a generated Seatbelt @@ -27,7 +27,7 @@ //! //! | | filesystem | network | limits | //! |---|---|---|---| -//! | Linux | Landlock (5.13+) | Landlock TCP (6.7+) | setrlimit + wall | +//! | Linux | Landlock (5.13+) | Landlock TCP (6.7+) + seccomp | setrlimit + wall | //! | macOS | Seatbelt | Seatbelt | setrlimit + wall | //! | Windows | not yet (see incode's ACL sandbox) | not yet | wall only | @@ -39,6 +39,8 @@ pub mod seatbelt; #[cfg(target_os = "linux")] mod linux; +#[cfg(target_os = "linux")] +mod seccomp; use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -245,6 +247,17 @@ fn enter(args: &[OsString]) -> Result { } eprintln!("sbx: Landlock not applied (best effort): {e}"); } + // After Landlock, before exec: Landlock confines TCP, this refuses the + // sockets Landlock does not see (UDP, raw, ...). See `seccomp`. + #[cfg(target_os = "linux")] + if spec.net_mode != NetMode::Allow { + if let Err(e) = seccomp::restrict_sockets() { + if spec.strict { + return Err(sandbox_err(format!("seccomp: {e}"))); + } + eprintln!("sbx: seccomp not applied (best effort): {e}"); + } + } #[cfg(unix)] if spec.supervise { diff --git a/crates/sandbox/src/linux.rs b/crates/sandbox/src/linux.rs index 3804c4f..e285e0b 100644 --- a/crates/sandbox/src/linux.rs +++ b/crates/sandbox/src/linux.rs @@ -14,9 +14,10 @@ //! - v4 (6.7): TCP `bind` and `connect`, by port (not by address). //! - v5 (6.10): device ioctls. //! -//! UDP is not covered by any ABI. Under `network = "deny"` that leaves UDP -//! (and so DNS) open; under `proxy` it leaves UDP open too, but the proxy -//! resolves names itself, so the command never needs it. +//! UDP is not covered by any ABI, nor is any socket that is not TCP. Under +//! `network = "deny"` or `"proxy"` a seccomp filter (`seccomp.rs`) refuses +//! to create those sockets, so UDP, and with it DNS, is closed too. Under +//! `proxy` the command never needed DNS: the proxy resolves names itself. use std::path::{Path, PathBuf}; @@ -76,22 +77,30 @@ pub(crate) fn fs_status(mode: FsMode) -> Status { } pub(crate) fn net_status(mode: NetMode) -> Status { - match mode { - NetMode::Allow => Status::NotRequested, - _ if !net_supported() => Status::NotEnforced( + if mode == NetMode::Allow { + return Status::NotRequested; + } + if !net_supported() { + return Status::NotEnforced( "this kernel's Landlock predates ABI v4 (Linux 6.7), the first to cover TCP".into(), + ); + } + // Landlock alone leaves UDP open, so without the filter the policy is + // not what it says: a gap, refused in strict mode. + let sockets = match crate::seccomp::status() { + Status::Enforced(how) => how, + gap => return gap, + }; + Status::Enforced(match mode { + NetMode::Proxy => format!( + "Landlock ABI v4: TCP connect only to the proxy's port, binds refused \ + (Landlock matches ports, not addresses); {sockets}" ), - NetMode::Deny => Status::Enforced( - "Landlock ABI v4: every TCP bind and connect refused, loopback included \ - (UDP is not covered)" - .into(), - ), - NetMode::Proxy => Status::Enforced( - "Landlock ABI v4: TCP connect only to the proxy's port; binds refused \ - (Landlock matches ports, not addresses; UDP is not covered)" - .into(), + _ => format!( + "Landlock ABI v4: every TCP bind and connect refused, loopback included; \ + {sockets} (DNS included)" ), - } + }) } fn abi_number(abi: ABI) -> u8 { diff --git a/crates/sandbox/src/seccomp.rs b/crates/sandbox/src/seccomp.rs new file mode 100644 index 0000000..4cef292 --- /dev/null +++ b/crates/sandbox/src/seccomp.rs @@ -0,0 +1,433 @@ +//! Linux: a seccomp filter for the sockets Landlock does not see. +//! +//! Landlock's network rules cover TCP `bind` and `connect` and nothing else, +//! so under `network = "deny"` or `"proxy"` a command could still send UDP +//! (DNS included), open a raw or packet socket, or speak a stream protocol +//! that is not TCP (SCTP, MPTCP). This filter closes that by refusing to +//! CREATE such sockets: `socket()` fails with `EACCES`, as Landlock's own +//! refusals do, so programs report "permission denied" rather than crash. +//! +//! It is an allowlist of socket families, not a list of what to block: +//! - `AF_UNIX`: local IPC (an ssh-agent, a build daemon, a language server). +//! - `AF_INET`/`AF_INET6` with `SOCK_STREAM` and protocol 0 or TCP: plain +//! TCP, which Landlock then confines (nothing, or the proxy's port). The +//! type's flag bits (`SOCK_NONBLOCK`, `SOCK_CLOEXEC`) are masked off first. +//! - `AF_NETLINK`: the kernel's own message bus. `getaddrinfo` asks it which +//! addresses the machine has (`AI_ADDRCONFIG`), and `ip`, `ss` and many +//! runtimes read routes and links through it. What it allows: reading the +//! machine's interfaces, addresses and routes, and talking to other local +//! netlink listeners. Changing them needs `CAP_NET_ADMIN`, which a +//! sandboxed command does not have over the real network (with +//! `no_new_privs`, even setuid `ip` cannot gain it). Nothing sent on it +//! leaves the machine, so it is kept; the cost is that a command can list +//! the host's interfaces, as it could by reading `/proc/net`. +//! +//! Everything else is refused: UDP, ICMP "ping" sockets, raw, `AF_PACKET`, +//! SCTP, MPTCP, and the families no build needs (`AF_VSOCK`, which reaches a +//! VM's host; Bluetooth; CAN; and so on). +//! +//! Two other ways to make a socket are closed with it: +//! - `io_uring` can create sockets and send on them without the syscalls a +//! seccomp filter sees, so `io_uring_setup` fails with `EPERM` (what +//! Docker's default profile does; runtimes fall back to plain syscalls). +//! - On x86-64 a 64-bit process can still make 32-bit syscalls. Those are +//! checked too, and the 32-bit `socketcall(SYS_SOCKET)`, whose arguments +//! sit in memory a filter cannot read, is refused outright (32-bit glibc +//! uses the direct `socket` syscall on any current kernel). The x32 ABI +//! shares x86-64's syscall numbers with one bit set, which is masked. +//! +//! Not covered: `socketpair` (it only makes connected local pairs), sockets +//! passed in already open (`sbx` passes none but stdio), and name lookups a +//! local daemon does on the command's behalf over a Unix socket: with +//! `nss-resolve` (systemd-resolved) or `nscd` in `/etc/nsswitch.conf`, +//! `getaddrinfo` still answers, and the name reaches the resolver. +//! +//! The filter is written by hand: a few dozen BPF instructions do not justify +//! a dependency. It knows x86-64 (with i386 and x32) and aarch64 (with +//! 32-bit ARM); on any other architecture none is installed and the network +//! status says so, because a filter with the wrong syscall numbers would +//! check the wrong calls. + +use crate::Status; + +/// What the filter covers, for the network status line. +pub(crate) const COVERS: &str = "seccomp: UDP, raw and other non-TCP sockets refused"; + +// From linux/audit.h: the `arch` field of `seccomp_data`. +const AUDIT_ARCH_X86_64: u32 = 0xC000_003E; +const AUDIT_ARCH_I386: u32 = 0x4000_0003; +const AUDIT_ARCH_AARCH64: u32 = 0xC000_00B7; +const AUDIT_ARCH_ARM: u32 = 0x4000_0028; + +/// x32 syscalls are x86-64's numbers with this bit set. +const X32_SYSCALL_BIT: u32 = 0x4000_0000; +/// The kernel's `SOCK_TYPE_MASK`: the type without its flag bits. +const SOCK_TYPE_MASK: u32 = 0xf; +/// `socketcall`'s first argument for `socket`. +const SYS_SOCKET: u32 = 1; +/// `io_uring_setup`, `_enter` and `_register` have one number everywhere. +const IO_URING: [u32; 3] = [425, 426, 427]; + +/// One syscall ABI the kernel may be entered through. +struct Abi { + arch: u32, + socket: u32, + /// The multiplexed `socketcall`, where the ABI has one. + socketcall: Option, + /// Mask `X32_SYSCALL_BIT` off the syscall number first. + x32: bool, +} + +/// x86-64, and the 32-bit ABIs a 64-bit process can still enter: i386 +/// (`int 0x80`) and x32 (x86-64's numbers with a bit set). +const X86_64: &[Abi] = &[ + Abi { + arch: AUDIT_ARCH_X86_64, + socket: 41, + socketcall: None, + x32: true, + }, + Abi { + arch: AUDIT_ARCH_I386, + socket: 359, + socketcall: Some(102), + x32: false, + }, +]; + +/// aarch64, and 32-bit ARM where the kernel has compat support. EABI has no +/// `socketcall`. +const AARCH64: &[Abi] = &[ + Abi { + arch: AUDIT_ARCH_AARCH64, + socket: 198, + socketcall: None, + x32: false, + }, + Abi { + arch: AUDIT_ARCH_ARM, + socket: 281, + socketcall: None, + x32: false, + }, +]; + +/// The ABIs a process on this machine can make syscalls through. +const ABIS: Option<&[Abi]> = if cfg!(target_arch = "x86_64") { + Some(X86_64) +} else if cfg!(target_arch = "aarch64") { + Some(AARCH64) +} else { + None +}; + +/// Whether the filter can be installed here, and if not, why. +pub(crate) fn status() -> Status { + if ABIS.is_none() { + return Status::NotEnforced(format!( + "no seccomp filter for {} yet, so UDP and other non-TCP sockets are not refused", + std::env::consts::ARCH + )); + } + // Asks whether the kernel knows the ERRNO action, without installing + // anything; fails on a kernel without seccomp filters (or before 4.14). + let action: u32 = libc::SECCOMP_RET_ERRNO; + // SAFETY: SECCOMP_GET_ACTION_AVAIL reads one u32 through the pointer. + let rc = unsafe { + libc::syscall( + libc::SYS_seccomp, + libc::SECCOMP_GET_ACTION_AVAIL, + 0, + &raw const action, + ) + }; + if rc == 0 { + Status::Enforced(COVERS.into()) + } else { + Status::NotEnforced(format!( + "this kernel has no seccomp filters ({}), so UDP and other non-TCP sockets \ + are not refused", + std::io::Error::last_os_error() + )) + } +} + +/// Install the filter on the CALLING thread (the helper, single-threaded, +/// just before it execs); every process it starts inherits it, and it cannot +/// be removed. +/// +/// # Errors +/// On an architecture without a filter, or when the kernel refuses it. +pub(crate) fn restrict_sockets() -> Result<(), String> { + let program = + program().ok_or_else(|| format!("no seccomp filter for {} yet", std::env::consts::ARCH))?; + let mut filter: Vec = program; + let prog = libc::sock_fprog { + len: u16::try_from(filter.len()).map_err(|_| "seccomp filter too long")?, + filter: filter.as_mut_ptr(), + }; + // SAFETY: prctl with integer arguments. Landlock already set it, but + // not if Landlock was skipped (best effort); an unprivileged process + // may only install a filter with it set. + if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 { + return Err(format!("no_new_privs: {}", std::io::Error::last_os_error())); + } + // SAFETY: `prog` points at `filter`, which outlives the call; the kernel + // copies the program. + let rc = unsafe { + libc::syscall( + libc::SYS_seccomp, + libc::SECCOMP_SET_MODE_FILTER, + 0, + &raw const prog, + ) + }; + if rc != 0 { + return Err(format!( + "seccomp filter refused: {}", + std::io::Error::last_os_error() + )); + } + Ok(()) +} + +// Offsets into `struct seccomp_data`: nr, arch, then six u64 args. Both +// architectures are little-endian, so an argument's low 32 bits come first, +// and the kernel reads `socket`'s int arguments as exactly those bits. +const NR: u32 = 0; +const ARCH: u32 = 4; +const fn arg(i: u32) -> u32 { + 16 + 8 * i +} + +/// Where a jump goes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum To { + Next, + Label(&'static str), +} + +enum Ins { + Label(&'static str), + Load(u32), + And(u32), + /// `if A == k goto yes else goto no`. + Jeq(u32, To, To), + Ret(u32), +} + +const ALLOW: u32 = libc::SECCOMP_RET_ALLOW; +const EACCES: u32 = libc::SECCOMP_RET_ERRNO | libc::EACCES as u32; +const EPERM: u32 = libc::SECCOMP_RET_ERRNO | libc::EPERM as u32; + +/// The BPF program for this architecture, or `None` where there is none. +pub(crate) fn program() -> Option> { + ABIS.map(|abis| assemble(&source(abis))) +} + +fn source(abis: &[Abi]) -> Vec { + use Ins::{And, Jeq, Label, Load, Ret}; + use To::{Label as L, Next}; + const ABI_LABELS: [&str; 2] = ["abi0", "abi1"]; + const CALL_LABELS: [&str; 2] = ["socketcall0", "socketcall1"]; + assert!(abis.len() <= ABI_LABELS.len()); + + let mut p = vec![Load(ARCH)]; + for (i, abi) in abis.iter().enumerate() { + p.push(Jeq(abi.arch, L(ABI_LABELS[i]), Next)); + } + // A syscall ABI this filter does not know: its numbers mean nothing + // here, so nothing it asks for can be checked. Never seen in practice. + p.push(Ret(libc::SECCOMP_RET_KILL_PROCESS)); + + for (i, abi) in abis.iter().enumerate() { + p.push(Label(ABI_LABELS[i])); + p.push(Load(NR)); + if abi.x32 { + p.push(And(!X32_SYSCALL_BIT)); + } + p.push(Jeq(abi.socket, L("socket"), Next)); + if let Some(nr) = abi.socketcall { + p.push(Jeq(nr, L(CALL_LABELS[i]), Next)); + } + for nr in IO_URING { + p.push(Jeq(nr, L("eperm"), Next)); + } + p.push(Ret(ALLOW)); + if abi.socketcall.is_some() { + p.push(Label(CALL_LABELS[i])); + p.push(Load(arg(0))); + p.push(Jeq(SYS_SOCKET, L("eacces"), L("allow"))); + } + } + + p.extend([ + Label("socket"), + Load(arg(0)), + Jeq(libc::AF_UNIX as u32, L("allow"), Next), + Jeq(libc::AF_NETLINK as u32, L("allow"), Next), + Jeq(libc::AF_INET as u32, L("inet"), Next), + Jeq(libc::AF_INET6 as u32, L("inet"), L("eacces")), + Label("inet"), + Load(arg(1)), + And(SOCK_TYPE_MASK), + Jeq(libc::SOCK_STREAM as u32, Next, L("eacces")), + Load(arg(2)), + Jeq(0, L("allow"), Next), + Jeq(libc::IPPROTO_TCP as u32, L("allow"), L("eacces")), + Label("allow"), + Ret(ALLOW), + Label("eacces"), + Ret(EACCES), + Label("eperm"), + Ret(EPERM), + ]); + p +} + +/// Resolve labels into BPF's forward-only relative jumps. +fn assemble(source: &[Ins]) -> Vec { + let mut at = std::collections::HashMap::new(); + let mut n = 0usize; + for ins in source { + match ins { + Ins::Label(l) => { + at.insert(*l, n); + } + _ => n += 1, + } + } + let offset = |from: usize, to: To| -> u8 { + match to { + To::Next => 0, + To::Label(l) => { + let target = at[l]; + assert!(target > from, "BPF jumps only forward: {l}"); + u8::try_from(target - from - 1).expect("jump fits in u8") + } + } + }; + let stmt = |code: u32, k: u32| libc::sock_filter { + code: code as u16, + jt: 0, + jf: 0, + k, + }; + let mut out = Vec::with_capacity(n); + for ins in source { + let i = out.len(); + out.push(match *ins { + Ins::Label(_) => continue, + Ins::Load(off) => stmt(libc::BPF_LD | libc::BPF_W | libc::BPF_ABS, off), + Ins::And(k) => stmt(libc::BPF_ALU | libc::BPF_AND | libc::BPF_K, k), + Ins::Ret(k) => stmt(libc::BPF_RET | libc::BPF_K, k), + Ins::Jeq(k, yes, no) => libc::sock_filter { + code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, + jt: offset(i, yes), + jf: offset(i, no), + k, + }, + }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A tiny interpreter for the instructions `assemble` emits, so the + /// program's decisions can be checked without installing it. + fn run(prog: &[libc::sock_filter], arch: u32, nr: u32, args: [u32; 3]) -> u32 { + let load = |off: u32| match off { + NR => nr, + ARCH => arch, + o => args[((o - 16) / 8) as usize], + }; + let mut a = 0u32; + let mut pc = 0usize; + loop { + let ins = &prog[pc]; + let code = u32::from(ins.code); + pc += 1; + if code == libc::BPF_LD | libc::BPF_W | libc::BPF_ABS { + a = load(ins.k); + } else if code == libc::BPF_ALU | libc::BPF_AND | libc::BPF_K { + a &= ins.k; + } else if code == libc::BPF_RET | libc::BPF_K { + return ins.k; + } else if code == libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K { + pc += usize::from(if a == ins.k { ins.jt } else { ins.jf }); + } else { + panic!("unexpected instruction {code:#x}"); + } + } + } + + const STREAM: u32 = libc::SOCK_STREAM as u32; + const DGRAM: u32 = libc::SOCK_DGRAM as u32; + const FLAGS: u32 = (libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) as u32; + + fn check(abi: &Abi) { + let prog = assemble(&source(std::slice::from_ref(abi))); + let sock = |family: i32, ty: u32, proto: i32| { + run( + &prog, + abi.arch, + abi.socket, + [family as u32, ty, proto as u32], + ) + }; + let inet = libc::AF_INET; + let inet6 = libc::AF_INET6; + assert_eq!(sock(inet, STREAM, 0), ALLOW); + assert_eq!(sock(inet6, STREAM | FLAGS, libc::IPPROTO_TCP), ALLOW); + assert_eq!(sock(libc::AF_UNIX, DGRAM | FLAGS, 0), ALLOW); + assert_eq!(sock(libc::AF_NETLINK, libc::SOCK_RAW as u32, 0), ALLOW); + assert_eq!(sock(inet, DGRAM, 0), EACCES); + assert_eq!(sock(inet6, DGRAM | FLAGS, 0), EACCES); + assert_eq!(sock(inet, DGRAM, libc::IPPROTO_ICMP), EACCES); + assert_eq!(sock(inet, libc::SOCK_RAW as u32, 0), EACCES); + assert_eq!(sock(inet, libc::SOCK_SEQPACKET as u32, 0), EACCES); + assert_eq!(sock(inet, STREAM, libc::IPPROTO_SCTP), EACCES); + assert_eq!(sock(inet, STREAM, 262), EACCES, "MPTCP"); + assert_eq!(sock(libc::AF_PACKET, libc::SOCK_RAW as u32, 0), EACCES); + assert_eq!(sock(libc::AF_VSOCK, STREAM, 0), EACCES); + for nr in IO_URING { + assert_eq!(run(&prog, abi.arch, nr, [0; 3]), EPERM); + } + // Any other syscall passes, whatever its arguments. + assert_eq!(run(&prog, abi.arch, 0, [2, 2, 0]), ALLOW); + if let Some(nr) = abi.socketcall { + assert_eq!(run(&prog, abi.arch, nr, [SYS_SOCKET, 0, 0]), EACCES); + assert_eq!(run(&prog, abi.arch, nr, [3, 0, 0]), ALLOW, "connect"); + } + if abi.x32 { + let nr = abi.socket | X32_SYSCALL_BIT; + assert_eq!(run(&prog, abi.arch, nr, [inet as u32, DGRAM, 0]), EACCES); + } + } + + #[test] + fn every_known_abi_refuses_what_landlock_misses() { + for abi in X86_64.iter().chain(AARCH64) { + check(abi); + } + } + + #[test] + fn the_installed_program_checks_both_abis_and_kills_unknown_ones() { + let Some(prog) = program() else { return }; + let abis = ABIS.expect("abis"); + for abi in abis { + let udp = [libc::AF_INET as u32, DGRAM, 0]; + assert_eq!(run(&prog, abi.arch, abi.socket, udp), EACCES); + let tcp = [libc::AF_INET as u32, STREAM, 0]; + assert_eq!(run(&prog, abi.arch, abi.socket, tcp), ALLOW); + } + assert_eq!( + run(&prog, 0xdead_beef, 0, [0; 3]), + libc::SECCOMP_RET_KILL_PROCESS + ); + } +} diff --git a/crates/sandbox/tests/escape.rs b/crates/sandbox/tests/escape.rs index fba97af..2ca041b 100644 --- a/crates/sandbox/tests/escape.rs +++ b/crates/sandbox/tests/escape.rs @@ -8,7 +8,7 @@ #![cfg(target_os = "linux")] use std::io::{Read, Write}; -use std::net::TcpListener; +use std::net::{TcpListener, UdpSocket}; use std::path::Path; use std::process::{Command, Output, Stdio}; use std::time::{Duration, Instant}; @@ -225,6 +225,105 @@ fn network_deny_refuses_connect_and_bind_even_on_loopback() { assert!(!out.contains("bound"), "{out}"); } +/// Tries UDP to `port` (plain and with the type's flag bits set), a raw and +/// a packet socket, and a Unix socket pair; prints one line per attempt. +fn socket_probe(port: u16) -> String { + format!( + r#"python3 -c ' +import socket +def t(name, f): + try: + f(); print(name, "ok") + except OSError as e: + print(name, "refused", e.errno) +def udp(flags): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM | flags) + s.sendto(b"escaped", ("127.0.0.1", {port})) +t("udp", lambda: udp(0)) +t("udp-flags", lambda: udp(socket.SOCK_NONBLOCK | socket.SOCK_CLOEXEC)) +t("raw", lambda: socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)) +t("packet", lambda: socket.socket(socket.AF_PACKET, socket.SOCK_RAW)) +t("unix", lambda: socket.socketpair()) +'"# + ) +} + +/// What arrived on `listener` within a short wait. +fn received(listener: &UdpSocket) -> usize { + listener + .set_read_timeout(Some(Duration::from_millis(300))) + .expect("timeout"); + let mut n = 0; + let mut buf = [0u8; 64]; + while listener.recv(&mut buf).is_ok() { + n += 1; + } + n +} + +#[test] +fn udp_raw_and_packet_sockets_are_refused_under_deny_and_proxy() { + require!(landlock_net(), "the network (Landlock ABI v4 and seccomp)"); + let d = dirs(); + let listener = UdpSocket::bind(("127.0.0.1", 0)).expect("bind"); + let port = listener.local_addr().expect("addr").port(); + let script = socket_probe(port); + for flags in [&["--net", "deny"][..], &["--allow-host", "example.com"][..]] { + let o = sh(&d.ws, flags, &script); + let out = text(&o); + // EACCES is the filter's answer; without it, root could open raw + // and packet sockets and UDP would be sent. + for line in ["udp refused 13", "udp-flags refused 13", "raw refused 13"] { + assert!(out.contains(line), "{flags:?}: no `{line}`: {out}"); + } + assert!(out.contains("packet refused 13"), "{flags:?}: {out}"); + assert!(out.contains("unix ok"), "Unix sockets stay: {out}"); + assert_eq!(received(&listener), 0, "{flags:?}: UDP got out: {out}"); + } +} + +#[test] +fn a_udp_socket_works_when_the_network_is_allowed() { + let d = dirs(); + let listener = UdpSocket::bind(("127.0.0.1", 0)).expect("bind"); + let port = listener.local_addr().expect("addr").port(); + let o = sh(&d.ws, &["--net", "allow"], &socket_probe(port)); + let out = text(&o); + assert!(out.contains("udp ok"), "{out}"); + assert!(out.contains("udp-flags ok"), "{out}"); + assert_eq!(received(&listener), 2, "{out}"); +} + +#[test] +fn dns_lookups_fail_under_deny() { + require!(landlock_net(), "the network (Landlock ABI v4 and seccomp)"); + // A lookup a local daemon answers over a Unix socket is not network + // access sbx can see (README, known limits); this checks plain DNS. + let nss = std::fs::read_to_string("/etc/nsswitch.conf").unwrap_or_default(); + let hosts = nss + .lines() + .find(|l| l.trim_start().starts_with("hosts:")) + .unwrap_or(""); + if hosts.contains("resolve") || Path::new("/var/run/nscd/socket").exists() { + eprintln!("SKIPPED: names resolve through a local daemon here ({hosts})"); + return; + } + let d = dirs(); + // example.com is in no /etc/hosts; the control shows DNS works at all. + let lookup = "getent hosts example.com"; + let control = sh(&d.ws, &["--net", "allow"], lookup); + if !control.status.success() { + eprintln!( + "SKIPPED: this machine cannot resolve names: {}", + text(&control) + ); + return; + } + let o = sh(&d.ws, &["--net", "deny"], lookup); + assert!(!o.status.success(), "resolved under deny: {}", text(&o)); + assert!(o.stdout.is_empty(), "{}", text(&o)); +} + #[test] fn the_proxy_lets_through_only_the_allowlist_and_cannot_be_bypassed() { require!(landlock_net(), "TCP (Landlock ABI v4)"); diff --git a/crates/sandbox/tests/escape_macos.rs b/crates/sandbox/tests/escape_macos.rs new file mode 100644 index 0000000..aa7613c --- /dev/null +++ b/crates/sandbox/tests/escape_macos.rs @@ -0,0 +1,377 @@ +//! Escape tests against Seatbelt: the Linux escape tests that apply on +//! macOS, through the real `sbx` binary. +//! +//! They use only what a stock Mac (and the macOS CI runner) has: `sh`, +//! `bash`, `nc`, `curl`, `ps`. Each test skips (with a note) when +//! `sandbox-exec` is missing, so a machine without it reports a skip rather +//! than a false pass. + +#![cfg(target_os = "macos")] + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +const SBX: &str = env!("CARGO_BIN_EXE_sbx"); + +fn sbx(args: &[&str], cwd: &Path) -> Output { + Command::new(SBX) + .args(args) + .current_dir(cwd) + .stdin(Stdio::null()) + .output() + .expect("sbx runs") +} + +fn sh(cwd: &Path, flags: &[&str], script: &str) -> Output { + let mut args = vec!["run"]; + args.extend_from_slice(flags); + args.extend_from_slice(&["--", "sh", "-c", script]); + sbx(&args, cwd) +} + +fn text(o: &Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&o.stdout), + String::from_utf8_lossy(&o.stderr) + ) +} + +fn enforced(flags: &[&str]) -> bool { + let mut args = vec!["check"]; + args.extend_from_slice(flags); + Command::new(SBX) + .args(&args) + .output() + .expect("check") + .status + .success() +} + +macro_rules! require { + ($flags:expr, $what:expr) => { + if !enforced($flags) { + eprintln!("SKIPPED: this Mac cannot enforce {}", $what); + return; + } + }; +} + +const FS: &[&str] = &["--fs", "workspace-write"]; +const NET: &[&str] = &["--net", "deny"]; + +struct Dirs { + _root: tempfile::TempDir, + ws: PathBuf, + out: PathBuf, +} + +/// A workspace and a sibling outside it. Canonical: the temp dir is under +/// `/var`, a symlink to `/private/var`, and Seatbelt matches real paths. +fn dirs() -> Dirs { + let root = tempfile::tempdir().expect("tempdir"); + let base = std::fs::canonicalize(root.path()).expect("canon"); + let ws = base.join("ws"); + let out = base.join("out"); + std::fs::create_dir(&ws).expect("ws"); + std::fs::create_dir(&out).expect("out"); + Dirs { + ws, + out, + _root: root, + } +} + +#[test] +fn writes_land_only_inside_the_writable_root() { + require!(FS, "the filesystem"); + let d = dirs(); + let outside = d.out.join("x"); + let o = sh( + &d.ws, + &["-w", "."], + &format!("echo ok > inside && echo bad > {}", outside.display()), + ); + assert!(d.ws.join("inside").exists(), "{}", text(&o)); + assert!(!outside.exists(), "wrote outside the root: {}", text(&o)); + assert!(!o.status.success()); +} + +#[test] +fn symlinks_and_child_processes_do_not_escape() { + require!(FS, "the filesystem"); + let d = dirs(); + std::fs::write(d.out.join("f"), "secret").expect("seed"); + std::os::unix::fs::symlink(&d.out, d.ws.join("link")).expect("symlink"); + let out = d.out.display(); + for script in [ + "echo bad > link/via-symlink".to_string(), + format!("mv {out}/f ./moved"), + format!("sh -c 'touch {out}/via-child'"), + format!("bash -c '(touch {out}/via-grandchild) & wait $!'"), + ] { + let o = sh(&d.ws, &["-w", "."], &script); + assert!(!o.status.success(), "`{script}` succeeded: {}", text(&o)); + } + let mut left: Vec = std::fs::read_dir(&d.out) + .expect("read") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .collect(); + left.sort(); + assert_eq!(left, ["f"], "something escaped into {out}"); + assert_eq!( + std::fs::read_to_string(d.out.join("f")).expect("f"), + "secret" + ); +} + +#[test] +fn temp_is_private_and_the_shared_temp_dir_is_not_writable() { + require!(FS, "the filesystem"); + let d = dirs(); + let marker = std::env::temp_dir().join(format!("sbx-escape-{}", std::process::id())); + let o = sh( + &d.ws, + &["-w", "."], + &format!( + "touch \"$TMPDIR/ok\" && echo \"$TMPDIR\"; touch {}", + marker.display() + ), + ); + let out = text(&o); + assert!(out.contains("sbx-"), "TMPDIR is the private one: {out}"); + assert!(!marker.exists(), "wrote to the shared temp dir"); +} + +#[test] +fn read_only_writes_nothing() { + require!(&["--fs", "read-only"], "the filesystem"); + let d = dirs(); + let o = sh(&d.ws, &["--fs", "read-only"], "touch x"); + assert!(!o.status.success()); + assert!(!d.ws.join("x").exists()); +} + +#[test] +fn deny_read_hides_a_path_through_every_route() { + require!(FS, "the filesystem"); + let d = dirs(); + std::fs::write(d.out.join("answer"), "42").expect("seed"); + std::os::unix::fs::symlink(&d.out, d.ws.join("peek")).expect("symlink"); + // The same directory by its unresolved path, through /var. + let unresolved = d + .out + .strip_prefix("/private") + .map(|p| Path::new("/").join(p)) + .unwrap_or_else(|_| d.out.clone()); + let out = d.out.display(); + let hidden = d.out.to_string_lossy().into_owned(); + for script in [ + format!("cat {out}/answer"), + format!("ls {out}"), + "cat peek/answer".to_string(), + format!("cat {}/answer", unresolved.display()), + format!("cd {out}/.. && cat out/answer"), + format!("sh -c 'cat {out}/answer'"), + format!("cp {out}/answer ./copy && cat ./copy"), + ] { + let o = sh(&d.ws, &["-w", ".", "--deny-read", &hidden], &script); + assert!( + !String::from_utf8_lossy(&o.stdout).contains("42"), + "`{script}` read the hidden file: {}", + text(&o) + ); + } + std::fs::write(d.ws.join("mine"), "ok").expect("seed"); + let o = sh( + &d.ws, + &["-w", ".", "--deny-read", &hidden], + "cat mine && cat /etc/hosts >/dev/null && ls /usr >/dev/null && echo fine", + ); + assert!(text(&o).contains("okfine"), "{}", text(&o)); +} + +#[test] +fn deny_read_inside_a_writable_root_is_refused() { + let d = dirs(); + std::fs::create_dir(d.ws.join("secret")).expect("mkdir"); + let o = sh(&d.ws, &["-w", ".", "--deny-read", "secret"], "true"); + assert_eq!(o.status.code(), Some(125), "{}", text(&o)); + assert!( + text(&o).contains("inside the writable root"), + "{}", + text(&o) + ); +} + +/// A listener that accepts (and drops) connections for the test's life. +fn local_listener() -> u16 { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind"); + let port = listener.local_addr().expect("addr").port(); + std::thread::spawn(move || { + for conn in listener.incoming() { + drop(conn); + } + }); + port +} + +#[test] +fn network_deny_refuses_tcp_even_on_loopback() { + require!(NET, "the network"); + let d = dirs(); + let port = local_listener(); + let script = format!("nc -z -w 3 127.0.0.1 {port} && echo connected"); + // The control: the same connection without the sandbox's network rules. + let o = sh(&d.ws, &["--net", "allow"], &script); + assert!(text(&o).contains("connected"), "control: {}", text(&o)); + let o = sh(&d.ws, &["--net", "deny"], &script); + assert!(!text(&o).contains("connected"), "{}", text(&o)); +} + +#[test] +fn the_proxy_lets_through_only_the_allowlist_and_cannot_be_bypassed() { + require!(NET, "the network"); + let d = dirs(); + let origin = TcpListener::bind(("127.0.0.1", 0)).expect("bind"); + let port = origin.local_addr().expect("addr").port(); + std::thread::spawn(move || { + for conn in origin.incoming() { + let Ok(mut conn) = conn else { continue }; + let mut buf = [0u8; 2048]; + let _ = conn.read(&mut buf); + let _ = conn.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\norigin"); + } + }); + let allow = format!("localhost:{port}"); + let script = format!( + "printf 'allowed='; curl -s --max-time 5 http://localhost:{port}/; echo; \ + printf 'other='; curl -s --max-time 5 http://127.0.0.1:{port}/ | head -c 40; echo; \ + printf 'bypass='; curl -s --max-time 5 --noproxy '*' http://localhost:{port}/; echo; \ + nc -z -w 3 127.0.0.1 {port} && echo nc-connected" + ); + // The test origin is on loopback, so private answers must be allowed, + // and this process's own upstream proxy (if any) must not be used. + let o = Command::new(SBX) + .args([ + "run", + "--allow-host", + &allow, + "--allow-private", + "--", + "sh", + "-c", + &script, + ]) + .current_dir(&d.ws) + .env_remove("HTTPS_PROXY") + .env_remove("https_proxy") + .env_remove("HTTP_PROXY") + .env_remove("http_proxy") + .stdin(Stdio::null()) + .output() + .expect("sbx"); + let out = text(&o); + assert!(out.contains("allowed=origin"), "{out}"); + assert!(out.contains("other=sbx: 127.0.0.1"), "{out}"); + assert!( + out.contains("bypass=\n"), + "the direct connection got through: {out}" + ); + assert!(!out.contains("nc-connected"), "{out}"); + assert!(out.contains("network refused 127.0.0.1"), "{out}"); +} + +#[test] +fn the_agent_session_and_git_redirects_are_stripped_and_credentials_kept() { + let d = dirs(); + let o = Command::new(SBX) + .args([ + "run", + "--", + "sh", + "-c", + "echo \"[$CLAUDECODE][$CLAUDE_CODE_SESSION_ID][$GIT_DIR][$ANTHROPIC_API_KEY]\"", + ]) + .current_dir(&d.ws) + .env("CLAUDECODE", "1") + .env("CLAUDE_CODE_SESSION_ID", "parent") + .env("GIT_DIR", "/elsewhere/.git") + .env("ANTHROPIC_API_KEY", "key") + .output() + .expect("sbx"); + assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), "[][][][key]"); +} + +#[test] +fn the_wall_limit_kills_the_whole_group() { + let d = dirs(); + let tag = format!("sbx_wall_{}", std::process::id()); + let start = Instant::now(); + let script = format!("(exec -a {tag} sleep 30) & (exec -a {tag} sleep 30)"); + let o = sbx(&["run", "--wall", "1", "--", "bash", "-c", &script], &d.ws); + assert_eq!(o.status.code(), Some(124), "{}", text(&o)); + assert!(start.elapsed() < Duration::from_secs(10)); + std::thread::sleep(Duration::from_millis(300)); + assert!(!running(&tag), "a process outlived the wall limit"); +} + +#[test] +fn killing_sbx_with_sigkill_takes_the_command_with_it() { + let d = dirs(); + let tag = format!("sbx_orphan_{}", std::process::id()); + let mut child = Command::new(SBX) + .args([ + "run", + "--wall", + "60", + "--", + "bash", + "-c", + &format!("(exec -a {tag} sleep 30) & (exec -a {tag} sleep 30)"), + ]) + .current_dir(&d.ws) + .stdin(Stdio::null()) + .spawn() + .expect("sbx"); + let deadline = Instant::now() + Duration::from_secs(5); + while !running(&tag) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(running(&tag), "the command never started"); + child.kill().expect("SIGKILL"); + let _ = child.wait(); + // No parent-death signal on macOS: the supervisor polls every 200ms. + let deadline = Instant::now() + Duration::from_secs(5); + while running(&tag) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(!running(&tag), "the command outlived sbx"); +} + +#[test] +fn limits_and_exit_codes() { + let d = dirs(); + let o = sh(&d.ws, &["--wall", "5"], "exit 7"); + assert_eq!(o.status.code(), Some(7)); + let o = sh(&d.ws, &[], "kill -9 $$"); + assert_eq!(o.status.code(), Some(137)); + let o = sbx(&["run", "--", "no-such-command-sbx"], &d.ws); + assert_eq!(o.status.code(), Some(127)); + let o = sbx(&["run", "-w", "missing-root", "--", "true"], &d.ws); + assert_eq!(o.status.code(), Some(125)); +} + +/// Whether a process whose argv[0] is `tag` is running. +fn running(tag: &str) -> bool { + let o = Command::new("ps") + .args(["-axo", "command="]) + .output() + .expect("ps"); + String::from_utf8_lossy(&o.stdout) + .lines() + .any(|l| l.split_whitespace().next() == Some(tag)) +}