Skip to main content

eclipse_core/
sandbox.rs

1//! What a `shell` command can reach once it runs.
2//!
3//! Approvals and `shell_allowlist` answer *whether* a command runs. This answers a different
4//! question: once it does, what can it touch — the machine's files, its network, and the daemons
5//! it leaves behind. M8 called that gap the biggest one left, and the honest answer used to be
6//! "it is your machine, you asked for it".
7//!
8//! The mechanism is bubblewrap (`bwrap`): one binary, no daemon, no setuid bit, no configuration
9//! file, packaged by every mainstream distribution because Flatpak is built on it. It is never
10//! bundled with eclipse. It is looked for once, on `PATH`, and a mode that needs it **refuses**
11//! when it is missing rather than running without it — a security promise that degrades silently
12//! is worse than one that was never made.
13//!
14//! - `process` — a private PID namespace, filesystem untouched. Nothing the command starts
15//!   outlives the call: when the run ends, PID 1 of that namespace dies and the kernel takes the
16//!   rest with it. That closes the hole the cancellation work could not reach (a daemon that
17//!   double-forks and is reparented to init) without a cgroup, and it costs one `clone`.
18//! - `fs` — the same namespace plus a read-only filesystem: `/` read-only, a fresh `/tmp`, the
19//!   workspace and the scripts directory writable, `shell_isolate_hide` paths replaced by an
20//!   empty directory, and the network optional. A build that writes outside the workspace
21//!   (cargo into `~/.cargo`, pip into `~/.cache`) needs that path in `shell_isolate_writable`;
22//!   that is a real cost, and the reason this mode is not the default.
23//!
24//! Both modes are the same argv with different mount flags, so the argument list is built in one
25//! place and can be asserted in a test without bubblewrap installed.
26
27use std::ffi::{OsStr, OsString};
28use std::path::{Path, PathBuf};
29
30use crate::config::{ShellIsolate, ToolsConfig};
31use crate::tools::ToolError;
32
33/// The program and arguments a run should actually invoke: the intended command, wrapped in
34/// bubblewrap when isolation is on.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Plan {
37    pub program: OsString,
38    pub args: Vec<OsString>,
39}
40
41/// Clonable because two places run under the same policy without being able to share one
42/// value: the agent's tool registry and the interface's `!command`.
43#[derive(Debug, Clone)]
44pub struct Sandbox {
45    mode: ShellIsolate,
46    workspace: PathBuf,
47    scripts_dir: Option<PathBuf>,
48    /// Extra paths bound read-write in `fs` mode, with `~` already expanded.
49    writable: Vec<PathBuf>,
50    /// Paths replaced by an empty directory in `fs` mode, with `~` already expanded.
51    hide: Vec<PathBuf>,
52    network: bool,
53    /// Where `bwrap` was found, if it was. `None` in a mode that needs it is a refusal, not a
54    /// fallback.
55    bwrap: Option<PathBuf>,
56}
57
58impl Sandbox {
59    pub fn new(cfg: &ToolsConfig, workspace: &Path, scripts_dir: Option<&Path>) -> Self {
60        let mode = cfg.shell_isolate;
61        Self {
62            mode,
63            workspace: workspace.to_path_buf(),
64            scripts_dir: scripts_dir.map(Path::to_path_buf),
65            writable: cfg
66                .shell_isolate_writable
67                .iter()
68                .map(|p| expand(p))
69                .collect(),
70            hide: cfg.shell_isolate_hide.iter().map(|p| expand(p)).collect(),
71            network: cfg.shell_isolate_network,
72            bwrap: need_bwrap(mode).then(find_bwrap).flatten(),
73        }
74    }
75
76    /// A sandbox that does nothing. Tests of the process-group kill (and anything else that
77    /// wants the plain child) use this, so the two mechanisms stay separately testable.
78    pub fn off() -> Self {
79        Self {
80            mode: ShellIsolate::Off,
81            workspace: PathBuf::new(),
82            scripts_dir: None,
83            writable: Vec::new(),
84            hide: Vec::new(),
85            network: true,
86            bwrap: None,
87        }
88    }
89
90    /// A sandbox in `mode` that has not found a `bwrap`, so the refusal can be tested on a
91    /// machine where bubblewrap is installed.
92    #[cfg(test)]
93    pub fn without_bwrap(mode: ShellIsolate) -> Self {
94        let mut sb = Self::off();
95        sb.mode = mode;
96        sb
97    }
98
99    pub fn mode(&self) -> ShellIsolate {
100        self.mode
101    }
102
103    /// Whether a command runs inside a namespace at all.
104    pub fn is_on(&self) -> bool {
105        self.mode != ShellIsolate::Off
106    }
107
108    /// Whether a mode that promised containment will refuse instead of running at all. True only
109    /// for `fs` without bubblewrap; `process` degrades instead.
110    pub fn refuses(&self) -> bool {
111        self.mode == ShellIsolate::Fs && self.bwrap.is_none()
112    }
113
114    /// Whether isolation was asked for and could not be given: the run happens anyway, and the
115    /// result says so. Only `process` degrades; `fs` refuses in [`Sandbox::plan`], because a
116    /// read-only promise is not one to keep halfway.
117    pub fn degraded(&self) -> bool {
118        self.mode == ShellIsolate::Process && self.bwrap.is_none()
119    }
120
121    /// What `config check` and the docs print: the mode, and whether the mechanism is there.
122    pub fn status(&self) -> String {
123        if !self.is_on() {
124            return "off — a command runs as you, with your files, your network and your daemons"
125                .to_string();
126        }
127        let skipped = self.skipped_hides();
128        let note = if skipped.is_empty() {
129            String::new()
130        } else {
131            format!(
132                "; not hiding {}: it contains a path the run must write",
133                skipped
134                    .iter()
135                    .map(|p| p.display().to_string())
136                    .collect::<Vec<_>>()
137                    .join(", ")
138            )
139        };
140        match (&self.bwrap, self.mode) {
141            (Some(path), _) => format!("{} — bubblewrap at {}{note}", self.mode, path.display()),
142            (None, ShellIsolate::Process) => format!(
143                "process — bubblewrap is NOT on PATH, so commands run uncontained and say so: \
144                 install bubblewrap to contain them{note}"
145            ),
146            (None, _) => format!(
147                "{} — bubblewrap is NOT on PATH, so `shell` will refuse to run: install \
148                 bubblewrap, or set [tools] shell_isolate = \"off\"{note}",
149                self.mode
150            ),
151        }
152    }
153
154    /// The program and arguments to run instead of `program` itself.
155    ///
156    /// `cwd` is passed to bubblewrap rather than left to the caller so the directory is resolved
157    /// inside the namespace, which is the only place it is guaranteed to mean the same thing.
158    pub fn plan(&self, program: &OsStr, args: &[OsString], cwd: &Path) -> Result<Plan, ToolError> {
159        if !self.is_on() {
160            return Ok(Plan {
161                program: program.to_owned(),
162                args: args.to_vec(),
163            });
164        }
165        // `fs` promises that the machine is read-only, and a promise like that is worth a
166        // refusal: running the command anyway would be the one outcome the mode exists to
167        // prevent. `process` promises only what it can — the run still happens, and
168        // `degraded()` makes the caller say so in the result rather than in a comment.
169        if self.mode == ShellIsolate::Fs && self.bwrap.is_none() {
170            return Err(ToolError::Failed(
171                "[tools] shell_isolate = \"fs\" makes the filesystem read-only, and that needs \
172                 bubblewrap, which is not on PATH, so the command was not run. Install it \
173                 (Debian/Ubuntu: `sudo apt install bubblewrap`, Fedora: `sudo dnf install \
174                 bubblewrap`, Arch: `sudo pacman -S bubblewrap`), or use shell_isolate = \
175                 \"process\" for a namespace without the filesystem scoping. Running uncontained \
176                 instead is not something this profile asked for."
177                    .to_string(),
178            ));
179        }
180        let Some(bwrap) = &self.bwrap else {
181            // `process` without the package: run it plainly. The caller appends the note.
182            return Ok(Plan {
183                program: program.to_owned(),
184                args: args.to_vec(),
185            });
186        };
187
188        let mut a: Vec<OsString> = Vec::with_capacity(32);
189        a.push("--die-with-parent".into());
190        a.push("--unshare-pid".into());
191        match self.mode {
192            // The filesystem is left exactly as it is; only the process tree is scoped.
193            ShellIsolate::Process => {
194                a.push("--dev-bind".into());
195                a.push("/".into());
196                a.push("/".into());
197                a.push("--proc".into());
198                a.push("/proc".into());
199            }
200            ShellIsolate::Fs => {
201                a.push("--ro-bind".into());
202                a.push("/".into());
203                a.push("/".into());
204                a.push("--proc".into());
205                a.push("/proc".into());
206                a.push("--dev".into());
207                a.push("/dev".into());
208                a.push("--tmpfs".into());
209                a.push("/tmp".into());
210                if !self.network {
211                    a.push("--unshare-net".into());
212                }
213                for dir in self.writable_paths() {
214                    if dir.is_dir() {
215                        a.push("--bind".into());
216                        a.push(dir.as_os_str().to_owned());
217                        a.push(dir.as_os_str().to_owned());
218                    }
219                }
220                // Bound first, emptied after: mounts stack, so a bind of a parent would cover a
221                // tmpfs put over its child. The hide list wins even inside the workspace, which
222                // is exactly the case a careless `shell_isolate_hide` produces.
223                for dir in self.hides_in_effect() {
224                    a.push("--tmpfs".into());
225                    a.push(dir.as_os_str().to_owned());
226                }
227            }
228            ShellIsolate::Off => unreachable!("handled above"),
229        }
230        a.push("--chdir".into());
231        a.push(cwd.as_os_str().to_owned());
232        a.push("--".into());
233        a.push(program.to_owned());
234        a.extend(args.iter().cloned());
235        Ok(Plan {
236            program: bwrap.as_os_str().to_owned(),
237            args: a,
238        })
239    }
240
241    /// The hides that are actually applied: a hide containing something the run is allowed to
242    /// write is dropped, because emptying it would delete the workspace the command was given —
243    /// a setting that silently broke every run would be worse than the gap it closes.
244    fn hides_in_effect(&self) -> Vec<&PathBuf> {
245        let writes = self.writable_paths();
246        self.hide
247            .iter()
248            .filter(|h| h.is_dir() && !writes.iter().any(|w| w.starts_with(h)))
249            .collect()
250    }
251
252    /// The hides a profile asked for that cannot be applied, for `config check` and the docs to
253    /// name rather than leave someone believing a path is hidden when it is not.
254    pub fn skipped_hides(&self) -> Vec<&PathBuf> {
255        self.hide
256            .iter()
257            .filter(|h| h.is_dir() && !self.hides_in_effect().contains(h))
258            .collect()
259    }
260
261    /// Everything `fs` mode leaves writable, in the order it is bound. The workspace is first so
262    /// it wins if an extra path is a parent of it.
263    fn writable_paths(&self) -> Vec<PathBuf> {
264        let mut out = vec![self.workspace.clone()];
265        for path in self.scripts_dir.iter().chain(self.writable.iter()) {
266            if !out.contains(path) {
267                out.push(path.clone());
268            }
269        }
270        out
271    }
272}
273
274/// `~` and `~/x` mean the home directory; anything else is taken as written.
275fn expand(path: &Path) -> PathBuf {
276    let Some(home) = std::env::var_os("HOME") else {
277        return path.to_path_buf();
278    };
279    match path.strip_prefix("~") {
280        Ok(rest) => PathBuf::from(home).join(rest),
281        Err(_) => path.to_path_buf(),
282    }
283}
284
285fn need_bwrap(mode: ShellIsolate) -> bool {
286    mode != ShellIsolate::Off
287}
288
289/// `bwrap` from `PATH`, executable and not a directory.
290fn find_bwrap() -> Option<PathBuf> {
291    let path = std::env::var_os("PATH")?;
292    std::env::split_paths(&path)
293        .map(|dir| dir.join("bwrap"))
294        .find(|candidate| {
295            std::fs::metadata(candidate).is_ok_and(|m| {
296                m.is_file() && {
297                    #[cfg(unix)]
298                    {
299                        use std::os::unix::fs::PermissionsExt;
300                        m.permissions().mode() & 0o111 != 0
301                    }
302                    #[cfg(not(unix))]
303                    {
304                        true
305                    }
306                }
307            })
308        })
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    fn cfg(mode: ShellIsolate) -> ToolsConfig {
316        ToolsConfig {
317            shell_isolate: mode,
318            ..ToolsConfig::default()
319        }
320    }
321
322    fn strings(args: &[OsString]) -> Vec<String> {
323        args.iter()
324            .map(|a| a.to_string_lossy().into_owned())
325            .collect()
326    }
327
328    #[test]
329    fn off_is_the_command_itself_and_nothing_else() {
330        let sb = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
331        assert!(!sb.is_on());
332        let plan = sb
333            .plan(
334                OsStr::new("sh"),
335                &["-c".into(), "echo hi".into()],
336                Path::new("/w"),
337            )
338            .unwrap();
339        assert_eq!(plan.program, OsString::from("sh"));
340        assert_eq!(strings(&plan.args), vec!["-c", "echo hi"]);
341    }
342
343    #[test]
344    fn fs_refuses_without_bubblewrap_and_process_degrades_out_loud() {
345        // `fs` promised a read-only machine, so it refuses rather than run uncontained.
346        let fs = Sandbox::without_bwrap(ShellIsolate::Fs);
347        let err = fs
348            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
349            .unwrap_err()
350            .to_string();
351        assert!(err.contains("read-only"), "{err}");
352        assert!(err.contains("not run"), "{err}");
353        assert!(err.contains("bubblewrap"), "{err}");
354        assert!(!fs.degraded());
355
356        // `process` promised only a namespace, so it runs plainly and says what it could not do.
357        let process = Sandbox::without_bwrap(ShellIsolate::Process);
358        let plan = process
359            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
360            .unwrap();
361        assert_eq!(plan.program, OsString::from("sh"));
362        assert!(process.degraded());
363        assert!(
364            process.status().contains("uncontained"),
365            "{}",
366            process.status()
367        );
368    }
369
370    #[test]
371    fn process_mode_scopes_the_pid_namespace_and_leaves_the_filesystem_alone() {
372        let sb = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
373        if sb.bwrap.is_none() {
374            return;
375        }
376        let plan = sb
377            .plan(
378                OsStr::new("sh"),
379                &["-c".into(), "echo hi".into()],
380                Path::new("/w"),
381            )
382            .unwrap();
383        assert!(plan.program.to_string_lossy().ends_with("bwrap"));
384        let a = strings(&plan.args);
385        assert!(a.starts_with(&["--die-with-parent".into(), "--unshare-pid".into()]));
386        assert!(a.contains(&"--dev-bind".to_string()));
387        assert!(
388            !a.contains(&"--ro-bind".to_string()),
389            "process mode must not scope files"
390        );
391        assert!(!a.contains(&"--unshare-net".to_string()));
392        assert_eq!(
393            &a[a.len() - 6..],
394            &["--chdir", "/w", "--", "sh", "-c", "echo hi"]
395        );
396    }
397
398    #[test]
399    fn fs_mode_is_read_only_with_the_workspace_bound_back() {
400        let sb = Sandbox::new(
401            &cfg(ShellIsolate::Fs),
402            Path::new("/w"),
403            Some(Path::new("/s")),
404        );
405        if sb.bwrap.is_none() {
406            return;
407        }
408        let plan = sb
409            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
410            .unwrap();
411        let a = strings(&plan.args);
412        assert!(a.contains(&"--ro-bind".to_string()));
413        assert!(a.contains(&"/tmp".to_string()));
414        // The workspace and the scripts directory are the two writes that always survive.
415        let binds: Vec<&String> = a
416            .windows(3)
417            .filter(|w| {
418                w[0] == "--bind" && {
419                    let p = Path::new(&w[1]);
420                    p.is_dir()
421                }
422            })
423            .map(|w| &w[1])
424            .collect();
425        assert!(binds.iter().any(|p| *p == "/w") || !Path::new("/w").is_dir());
426        assert!(a.contains(&"--unshare-pid".to_string()));
427    }
428
429    #[test]
430    fn fs_mode_can_drop_the_network() {
431        let mut c = cfg(ShellIsolate::Fs);
432        c.shell_isolate_network = false;
433        let sb = Sandbox::new(&c, Path::new("/w"), None);
434        if sb.bwrap.is_none() {
435            return;
436        }
437        let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
438        assert!(strings(&plan.args).contains(&"--unshare-net".to_string()));
439    }
440
441    #[test]
442    fn hide_list_is_expanded_and_only_applied_to_existing_directories() {
443        let mut c = cfg(ShellIsolate::Fs);
444        c.shell_isolate_hide = vec![
445            PathBuf::from("~/.eclipse-never-exists"),
446            PathBuf::from("/tmp"),
447        ];
448        let sb = Sandbox::new(&c, Path::new("/w"), None);
449        if let Some(home) = std::env::var_os("HOME") {
450            assert_eq!(
451                sb.hide[0],
452                PathBuf::from(home).join(".eclipse-never-exists")
453            );
454        }
455        if sb.bwrap.is_none() {
456            return;
457        }
458        let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
459        let a = strings(&plan.args);
460        // `/tmp` exists and is hidden; the imaginary home path is not bound at all, because a
461        // `--tmpfs` over a path that does not exist would fail the whole run.
462        assert!(a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == "/tmp"));
463        assert!(!a.iter().any(|w| w.contains(".eclipse-never-exists")));
464    }
465
466    #[test]
467    fn status_says_which_mechanism_and_whether_it_is_there() {
468        let off = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
469        assert!(off.status().starts_with("off"));
470        let on = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
471        let text = on.status();
472        assert!(text.starts_with("process"));
473        assert!(text.contains("bubblewrap"), "{text}");
474    }
475}