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