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    std::env::split_paths(&path).filter(|d| d.is_absolute()).map(|d| d.join(name)).find(|p| is_executable(p))
137}
138
139#[cfg(unix)]
140fn is_executable(p: &Path) -> bool {
141    use std::os::unix::fs::PermissionsExt;
142    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
143}
144
145#[cfg(not(unix))]
146fn is_executable(p: &Path) -> bool {
147    p.is_file()
148}
149
150/// Folders a sandbox must let an interpreter (`python3`, a venv's `python`) read beyond
151/// the system folders: its venv (`<venv>/pyvenv.cfg`) and its real installation prefix
152/// (`<prefix>/lib/python3*`). Never the home folder itself or anything above it.
153pub fn interpreter_read_paths(program: &OsStr) -> Vec<PathBuf> {
154    let Some(path) = which(program) else { return Vec::new() };
155    let mut out = Vec::new();
156    if let Some(venv) = path.parent().and_then(Path::parent)
157        && venv.join("pyvenv.cfg").is_file()
158    {
159        out.push(venv.canonicalize().unwrap_or_else(|_| venv.to_path_buf()));
160    }
161    if let Ok(real) = path.canonicalize()
162        && let Some(prefix) = real.parent().and_then(Path::parent)
163        && looks_like_python_prefix(prefix)
164    {
165        out.push(prefix.to_path_buf());
166    }
167    let home = std::env::var_os("HOME").map(PathBuf::from).and_then(|h| h.canonicalize().ok());
168    out.retain(|p| p.parent().is_some() && !home.as_ref().is_some_and(|h| h.starts_with(p)));
169    out
170}
171
172fn looks_like_python_prefix(prefix: &Path) -> bool {
173    prefix.join("Lib").is_dir()
174        || std::fs::read_dir(prefix.join("lib")).is_ok_and(|rd| rd.flatten().any(|e| e.file_name().to_string_lossy().starts_with("python3")))
175}
176
177/// Inherited variables that are safe and useful to pass to sandboxed code.
178const PASS_ENV: &[&str] = &[
179    "PATH",
180    "LANG",
181    "LANGUAGE",
182    "LC_ALL",
183    "LC_CTYPE",
184    "LC_NUMERIC",
185    "LC_TIME",
186    "LC_COLLATE",
187    "LC_MONETARY",
188    "LC_MESSAGES",
189    "TZ",
190    "TZDIR",
191    "LOCALE_ARCHIVE",
192    "SSL_CERT_FILE",
193    "SSL_CERT_DIR",
194    "NIX_SSL_CERT_FILE",
195    "FONTCONFIG_FILE",
196    "FONTCONFIG_PATH",
197    "SYSTEMROOT",
198];
199
200/// Replace `cmd`'s environment with a minimal one: no inherited secrets (API keys,
201/// tokens), `HOME` and temp folders pointing at `tmp`, matplotlib on the Agg backend.
202pub fn clean_env(cmd: &mut Command, tmp: &Path) {
203    cmd.env_clear();
204    for k in PASS_ENV {
205        if let Some(v) = std::env::var_os(k) {
206            cmd.env(k, v);
207        }
208    }
209    if std::env::var_os("PATH").is_none() {
210        cmd.env("PATH", "/usr/local/bin:/usr/bin:/bin");
211    }
212    if std::env::var_os("LANG").is_none() && std::env::var_os("LC_ALL").is_none() {
213        cmd.env("LANG", "C.UTF-8");
214    }
215    for k in ["HOME", "TMPDIR", "TMP", "TEMP", "USERPROFILE"] {
216        cmd.env(k, tmp);
217    }
218    cmd.env("XDG_CACHE_HOME", tmp.join(".cache"))
219        .env("XDG_CONFIG_HOME", tmp.join(".config"))
220        .env("MPLCONFIGDIR", tmp.join(".matplotlib"))
221        .env("MPLBACKEND", "Agg")
222        .env("PYTHONIOENCODING", "utf-8")
223        .env("PYTHONDONTWRITEBYTECODE", "1")
224        .env("PYTHONNOUSERSITE", "1")
225        .env("PYTHONUNBUFFERED", "1")
226        .env("PIP_DISABLE_PIP_VERSION_CHECK", "1")
227        .env("TERM", "dumb")
228        .env("NO_COLOR", "1")
229        .env("PAGER", "cat")
230        .env("GIT_PAGER", "cat");
231}
232
233/// A private temp folder for one run, removed when dropped.
234#[derive(Debug)]
235pub struct TempDir(PathBuf);
236
237impl TempDir {
238    pub fn new(prefix: &str) -> Result<Self, String> {
239        let base = std::env::temp_dir();
240        for attempt in 0..16u32 {
241            let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
242            let p = base.join(format!("{prefix}{}-{nanos:x}-{attempt}", std::process::id()));
243            match std::fs::create_dir(&p) {
244                Ok(()) => {
245                    #[cfg(unix)]
246                    {
247                        use std::os::unix::fs::PermissionsExt;
248                        let _ = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o700));
249                    }
250                    return Ok(Self(p.canonicalize().unwrap_or(p)));
251                }
252                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
253                Err(e) => return Err(format!("can't create a temp folder in {}: {e}", base.display())),
254            }
255        }
256        Err("can't create a temp folder".into())
257    }
258
259    pub fn path(&self) -> &Path {
260        &self.0
261    }
262}
263
264impl Drop for TempDir {
265    fn drop(&mut self) {
266        let _ = std::fs::remove_dir_all(&self.0);
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn argv_shape() {
276        let sb = Sandbox::new("/bin/byob");
277        let p = Policy::default();
278        let v = sb.argv(&p, "sh", ["-c", "true"]);
279        let parsed = parse_helper_args(&v[1..]).unwrap();
280        assert_eq!(parsed, HelperArgs::Exec { policy: Box::new(p), program: "sh".into(), args: vec!["-c".into(), "true".into()] });
281        assert_eq!(v[0], HELPER_ARG);
282    }
283
284    #[test]
285    fn temp_dir_is_private_and_removed() {
286        let t = TempDir::new("byob-test-").unwrap();
287        let p = t.path().to_path_buf();
288        assert!(p.is_dir());
289        drop(t);
290        assert!(!p.exists());
291    }
292}