Skip to main content

byob_sandbox/
lib.rs

1//! Run untrusted commands (model-written shell and Python, plugin scripts, local MCP
2//! servers) confined to a workspace.
3//!
4//! The workspace forbids `unsafe`, so restrictions can't be applied between `fork` and
5//! `exec` (`pre_exec`). Instead the app binary doubles as a **helper**: run as
6//! `byob __sandbox-exec <policy-json> -- <cmd> <args…>` it confines itself and then becomes
7//! (or, with a PID namespace, starts and supervises) the command. [`Sandbox`] builds such
8//! command lines; [`dispatch_helper`] goes first in the app's `main`.
9//!
10//! ```no_run
11//! # use std::path::Path;
12//! use byob_sandbox::{Policy, RunOptions, Sandbox};
13//! let sandbox = Sandbox::from_current_exe()?;
14//! let policy = Policy::for_workspace(Path::new("/home/me/project"), Path::new("/tmp/byob-run-1"));
15//! let mut cmd = sandbox.command(&policy, "sh", ["-c", "ls"]);
16//! byob_sandbox::clean_env(&mut cmd, Path::new("/tmp/byob-run-1"));
17//! let out = byob_sandbox::run(cmd, &RunOptions::default(), &|| false)?;
18//! # Ok::<(), String>(())
19//! ```
20//!
21//! What's enforced, per platform, is in [`linux`](crate#linux), the macOS profile
22//! ([`seatbelt`]) and [`Enforcement`]. On anything else the helper refuses to run unless
23//! the policy says `allow_unsandboxed` (an explicit user opt-in).
24//!
25//! # Linux
26//! Landlock filesystem allow-list (required), Landlock TCP deny (ABI ≥ 4), abstract
27//! unix socket + signal scoping (ABI ≥ 6), `no_new_privs`, rlimits, and — when
28//! unprivileged user namespaces are allowed — an empty network namespace (no network at
29//! all, UDP included) and a PID namespace (killing the run kills everything it started).
30#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
31
32mod helper;
33mod policy;
34mod run;
35pub mod seatbelt;
36mod snapshot;
37
38#[cfg(target_os = "linux")]
39#[path = "linux.rs"]
40mod platform;
41#[cfg(target_os = "macos")]
42#[path = "macos.rs"]
43mod platform;
44#[cfg(not(any(target_os = "linux", target_os = "macos")))]
45#[path = "other.rs"]
46mod platform;
47
48use std::ffi::{OsStr, OsString};
49use std::path::{Path, PathBuf};
50use std::process::Command;
51use std::sync::{Arc, OnceLock};
52use std::time::Duration;
53
54pub use helper::{ERROR_PREFIX, Enforcement, HELPER_ARG, HelperArgs, PROBE_ARG, SETUP_FAILED, dispatch_helper, helper_main, parse_helper_args};
55pub use policy::{Limits, MAX_PATHS, MAX_POLICY_LEN, Policy, system_read_paths, system_write_paths};
56pub use run::{Captured, Outcome, RunOptions, kill_group, run};
57pub use snapshot::{Changes, Snapshot};
58
59/// Set to `off` to run commands without a sandbox (an explicit user opt-in; logged).
60pub const DISABLE_ENV: &str = "BYOB_SANDBOX";
61
62/// The user turned the sandbox off with `BYOB_SANDBOX=off` (or `0`, `false`, `no`).
63pub fn disabled_by_user() -> bool {
64    std::env::var(DISABLE_ENV).is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "off" | "0" | "false" | "no"))
65}
66
67/// Builds helper command lines. Cheap to clone.
68#[derive(Debug, Clone)]
69pub struct Sandbox {
70    helper: PathBuf,
71    probed: Arc<OnceLock<Enforcement>>,
72}
73
74impl Sandbox {
75    /// `helper` is a binary that calls [`dispatch_helper`] (or [`helper_main`]) first.
76    pub fn new(helper: impl Into<PathBuf>) -> Self {
77        Self { helper: helper.into(), probed: Arc::default() }
78    }
79
80    /// This binary as the helper (it must call [`dispatch_helper`] in `main`).
81    pub fn from_current_exe() -> Result<Self, String> {
82        std::env::current_exe().map(Self::new).map_err(|e| format!("can't find the app binary for the sandbox helper: {e}"))
83    }
84
85    pub fn helper(&self) -> &Path {
86        &self.helper
87    }
88
89    /// What this machine can enforce (runs the helper once, then cached).
90    pub fn probe(&self) -> Enforcement {
91        self.probed.get_or_init(|| self.probe_now()).clone()
92    }
93
94    fn probe_now(&self) -> Enforcement {
95        let mut cmd = Command::new(&self.helper);
96        cmd.args([HELPER_ARG, PROBE_ARG]);
97        let opts = RunOptions { timeout: Duration::from_secs(10), max_output: 16 * 1024, ..Default::default() };
98        match run(cmd, &opts, &|| false) {
99            Ok(o) if o.success() => serde_json::from_slice(&o.stdout.bytes()).unwrap_or_else(|e| Enforcement::none(format!("bad probe output: {e}"))),
100            Ok(o) => Enforcement::none(format!("the sandbox helper failed: {}", o.stderr.text().trim())),
101            Err(e) => Enforcement::none(e),
102        }
103    }
104
105    /// Helper arguments (after the helper binary) that run `program args…` under `policy`.
106    pub fn argv<I, S>(&self, policy: &Policy, program: impl AsRef<OsStr>, args: I) -> Vec<OsString>
107    where
108        I: IntoIterator<Item = S>,
109        S: AsRef<OsStr>,
110    {
111        let mut v = vec![OsString::from(HELPER_ARG), OsString::from(policy.to_json()), OsString::from("--"), program.as_ref().to_os_string()];
112        v.extend(args.into_iter().map(|a| a.as_ref().to_os_string()));
113        v
114    }
115
116    /// A [`Command`] that runs `program args…` under `policy` via the helper. Set the
117    /// working folder and environment on it as usual; hand it to [`run`].
118    pub fn command<I, S>(&self, policy: &Policy, program: impl AsRef<OsStr>, args: I) -> Command
119    where
120        I: IntoIterator<Item = S>,
121        S: AsRef<OsStr>,
122    {
123        let mut cmd = Command::new(&self.helper);
124        cmd.args(self.argv(policy, program, args));
125        cmd
126    }
127}
128
129/// The first executable `name` on `PATH` (or `name` itself if it's a path).
130pub fn which(name: &OsStr) -> Option<PathBuf> {
131    let p = Path::new(name);
132    if p.components().count() > 1 || p.is_absolute() {
133        return is_executable(p).then(|| p.to_path_buf());
134    }
135    let path = std::env::var_os("PATH")?;
136    let exts = executable_extensions(p, std::env::var_os("PATHEXT").as_deref());
137    std::env::split_paths(&path)
138        .filter(|d| d.is_absolute())
139        .flat_map(|d| exts.iter().map(move |ext| d.join(with_extension(name, ext))))
140        .find(|p| is_executable(p))
141}
142
143/// The suffixes to try for a command name: on Windows `PATHEXT`'s (`.COM;.EXE;.BAT;.CMD;…`)
144/// unless the name has one already, so `python` finds `python.exe`; elsewhere just the name.
145fn executable_extensions(name: &Path, pathext: Option<&OsStr>) -> Vec<String> {
146    if !cfg!(windows) || name.extension().is_some() {
147        return vec![String::new()];
148    }
149    let list = pathext.and_then(OsStr::to_str).filter(|s| !s.trim().is_empty()).unwrap_or(".COM;.EXE;.BAT;.CMD");
150    list.split(';').map(str::trim).filter(|e| e.starts_with('.') && e.len() > 1).map(str::to_ascii_lowercase).collect()
151}
152
153fn with_extension(name: &OsStr, ext: &str) -> OsString {
154    let mut n = name.to_owned();
155    n.push(ext);
156    n
157}
158
159#[cfg(unix)]
160fn is_executable(p: &Path) -> bool {
161    use std::os::unix::fs::PermissionsExt;
162    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
163}
164
165#[cfg(not(unix))]
166fn is_executable(p: &Path) -> bool {
167    p.is_file()
168}
169
170/// Folders a sandbox must let an interpreter (`python3`, a venv's `python`) read beyond
171/// the system folders: its venv (`<venv>/pyvenv.cfg`) and its real installation prefix
172/// (`<prefix>/lib/python3*`). Never the home folder itself or anything above it.
173pub fn interpreter_read_paths(program: &OsStr) -> Vec<PathBuf> {
174    let Some(path) = which(program) else { return Vec::new() };
175    let mut out = Vec::new();
176    if let Some(venv) = path.parent().and_then(Path::parent)
177        && venv.join("pyvenv.cfg").is_file()
178    {
179        out.push(venv.canonicalize().unwrap_or_else(|_| venv.to_path_buf()));
180    }
181    if let Ok(real) = path.canonicalize()
182        && let Some(prefix) = real.parent().and_then(Path::parent)
183        && looks_like_python_prefix(prefix)
184    {
185        out.push(prefix.to_path_buf());
186    }
187    let home = std::env::var_os("HOME").map(PathBuf::from).and_then(|h| h.canonicalize().ok());
188    out.retain(|p| p.parent().is_some() && !home.as_ref().is_some_and(|h| h.starts_with(p)));
189    out
190}
191
192fn looks_like_python_prefix(prefix: &Path) -> bool {
193    prefix.join("Lib").is_dir()
194        || std::fs::read_dir(prefix.join("lib")).is_ok_and(|rd| rd.flatten().any(|e| e.file_name().to_string_lossy().starts_with("python3")))
195}
196
197/// Windows variables programs need to start at all (Python can't seed its hash without
198/// `SystemRoot`; PowerShell wants `PSModulePath`), plus where things are installed.
199const PASS_ENV_WINDOWS: &[&str] = &[
200    "SystemRoot",
201    "SystemDrive",
202    "windir",
203    "ComSpec",
204    "PATHEXT",
205    "OS",
206    "PROCESSOR_ARCHITECTURE",
207    "PROCESSOR_IDENTIFIER",
208    "NUMBER_OF_PROCESSORS",
209    "ProgramData",
210    "ProgramFiles",
211    "ProgramFiles(x86)",
212    "ProgramW6432",
213    "CommonProgramFiles",
214    "CommonProgramFiles(x86)",
215    "CommonProgramW6432",
216    "PSModulePath",
217];
218
219/// Inherited variables that are safe and useful to pass to sandboxed code.
220const PASS_ENV: &[&str] = &[
221    "PATH",
222    "LANG",
223    "LANGUAGE",
224    "LC_ALL",
225    "LC_CTYPE",
226    "LC_NUMERIC",
227    "LC_TIME",
228    "LC_COLLATE",
229    "LC_MONETARY",
230    "LC_MESSAGES",
231    "TZ",
232    "TZDIR",
233    "LOCALE_ARCHIVE",
234    "SSL_CERT_FILE",
235    "SSL_CERT_DIR",
236    "NIX_SSL_CERT_FILE",
237    "FONTCONFIG_FILE",
238    "FONTCONFIG_PATH",
239    "SYSTEMROOT",
240];
241
242/// Replace `cmd`'s environment with a minimal one: no inherited secrets (API keys,
243/// tokens), `HOME` and temp folders pointing at `tmp`, matplotlib on the Agg backend.
244pub fn clean_env(cmd: &mut Command, tmp: &Path) {
245    cmd.env_clear();
246    let windows: &[&str] = if cfg!(windows) { PASS_ENV_WINDOWS } else { &[] };
247    for k in PASS_ENV.iter().chain(windows) {
248        if let Some(v) = std::env::var_os(k) {
249            cmd.env(k, v);
250        }
251    }
252    if std::env::var_os("PATH").is_none() && !cfg!(windows) {
253        cmd.env("PATH", "/usr/local/bin:/usr/bin:/bin");
254    }
255    if std::env::var_os("LANG").is_none() && std::env::var_os("LC_ALL").is_none() {
256        cmd.env("LANG", "C.UTF-8");
257    }
258    for k in ["HOME", "TMPDIR", "TMP", "TEMP", "USERPROFILE", "APPDATA", "LOCALAPPDATA"] {
259        cmd.env(k, tmp);
260    }
261    cmd.env("XDG_CACHE_HOME", tmp.join(".cache"))
262        .env("XDG_CONFIG_HOME", tmp.join(".config"))
263        .env("MPLCONFIGDIR", tmp.join(".matplotlib"))
264        .env("MPLBACKEND", "Agg")
265        .env("PYTHONIOENCODING", "utf-8")
266        .env("PYTHONDONTWRITEBYTECODE", "1")
267        .env("PYTHONNOUSERSITE", "1")
268        .env("PYTHONUNBUFFERED", "1")
269        .env("PIP_DISABLE_PIP_VERSION_CHECK", "1")
270        .env("TERM", "dumb")
271        .env("NO_COLOR", "1")
272        .env("PAGER", "cat")
273        .env("GIT_PAGER", "cat");
274}
275
276/// A private temp folder for one run, removed when dropped.
277#[derive(Debug)]
278pub struct TempDir(PathBuf);
279
280impl TempDir {
281    pub fn new(prefix: &str) -> Result<Self, String> {
282        let base = std::env::temp_dir();
283        for attempt in 0..16u32 {
284            let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
285            let p = base.join(format!("{prefix}{}-{nanos:x}-{attempt}", std::process::id()));
286            match std::fs::create_dir(&p) {
287                Ok(()) => {
288                    #[cfg(unix)]
289                    {
290                        use std::os::unix::fs::PermissionsExt;
291                        let _ = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o700));
292                    }
293                    return Ok(Self(p.canonicalize().unwrap_or(p)));
294                }
295                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
296                Err(e) => return Err(format!("can't create a temp folder in {}: {e}", base.display())),
297            }
298        }
299        Err("can't create a temp folder".into())
300    }
301
302    pub fn path(&self) -> &Path {
303        &self.0
304    }
305}
306
307impl Drop for TempDir {
308    fn drop(&mut self) {
309        let _ = std::fs::remove_dir_all(&self.0);
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    /// `which` finds Windows programs by name without their extension (`cmd` is `cmd.exe`).
318    #[cfg(windows)]
319    #[test]
320    fn which_tries_pathext_on_windows() {
321        let cmd = which(OsStr::new("cmd")).expect("cmd.exe is on PATH");
322        assert!(cmd.extension().is_some_and(|e| e.eq_ignore_ascii_case("exe")), "{}", cmd.display());
323        assert_eq!(executable_extensions(Path::new("py.exe"), None), vec![String::new()]);
324        assert!(executable_extensions(Path::new("python"), Some(OsStr::new(".COM;.EXE;junk;"))).contains(&".exe".to_owned()));
325    }
326
327    #[test]
328    fn names_are_tried_as_given_off_windows() {
329        if !cfg!(windows) {
330            assert_eq!(executable_extensions(Path::new("python3"), Some(OsStr::new(".EXE"))), vec![String::new()]);
331        }
332    }
333
334    #[test]
335    fn argv_shape() {
336        let sb = Sandbox::new("/bin/byob");
337        let p = Policy::default();
338        let v = sb.argv(&p, "sh", ["-c", "true"]);
339        let parsed = parse_helper_args(&v[1..]).unwrap();
340        assert_eq!(parsed, HelperArgs::Exec { policy: Box::new(p), program: "sh".into(), args: vec!["-c".into(), "true".into()] });
341        assert_eq!(v[0], HELPER_ARG);
342    }
343
344    #[test]
345    fn temp_dir_is_private_and_removed() {
346        let t = TempDir::new("byob-test-").unwrap();
347        let p = t.path().to_path_buf();
348        assert!(p.is_dir());
349        drop(t);
350        assert!(!p.exists());
351    }
352}