Skip to main content

sandbox_jail/
lib.rs

1//! Run a command in a sandbox under a policy the caller defines: Seatbelt on macOS, bubblewrap on
2//! Linux, or a throwaway tart or lume VM with [`vm::Vm`]. The crate only enforces the policy
3
4mod bwrap;
5pub mod known;
6#[cfg(target_os = "macos")]
7pub mod macos;
8mod seatbelt;
9pub mod vm;
10
11use std::ffi::{OsStr, OsString};
12use std::fmt;
13use std::path::{Path, PathBuf};
14use std::process::Command;
15
16/// Everything, or only the listed items
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
18pub enum Access<T> {
19    #[default]
20    All,
21    Only(Vec<T>),
22}
23
24/// An overlay mounted on `lower`, which stays unchanged while writes go to `upper`. bwrap only
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Overlay {
27    pub lower: PathBuf,
28    pub upper: PathBuf,
29    pub work: PathBuf,
30}
31
32/// What the command may touch. Every path must be absolute
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Policy {
35    /// Directories the command may write, and read even inside `unreadable`
36    pub writable: Vec<PathBuf>,
37    /// Directories it may not write, even inside `writable`
38    pub read_only: Vec<PathBuf>,
39    /// Paths it may not replace or remove, while what is inside a directory stays writable. Seatbelt only
40    pub pinned: Vec<PathBuf>,
41    /// Directories whose files it may not read, but for `readable` and `writable` inside them.
42    /// bwrap mounts an empty read-only directory over each
43    pub unreadable: Vec<PathBuf>,
44    /// Exceptions inside `unreadable`
45    pub readable: Vec<PathBuf>,
46    /// Directories that start empty and writable, and whose writes go away with the command. bwrap
47    /// only, as a tmpfs. macOS has no way to give one process an empty directory
48    pub scratch: Vec<PathBuf>,
49    /// Paths it may not read or list, even inside `readable` or `writable`
50    pub hidden: Vec<PathBuf>,
51    /// TCP and UDP. Off also hides the host's localhost under bwrap
52    pub network: bool,
53    /// Unix sockets it may connect to, by the directory they are in. Seatbelt also allows the DNS
54    /// resolver's. Under bwrap a socket is out of reach only when its directory is unreadable or hidden
55    pub unix_sockets: Access<PathBuf>,
56    /// Mach services it may look up. Seatbelt only
57    pub mach_services: Access<String>,
58    /// Whether it may send Apple events, which can start a process outside the sandbox. Seatbelt only
59    pub apple_events: bool,
60    /// Signals reach only its own processes. bwrap always does this with a pid namespace
61    pub own_signals: bool,
62    /// It reads and writes only pseudo-terminals it opened, so the caller's terminal is out of reach
63    pub own_terminals: bool,
64    /// Binaries it may not run. Seatbelt only, bwrap already runs setuid binaries without privileges
65    pub no_exec: Vec<PathBuf>,
66    /// bwrap only
67    pub overlays: Vec<Overlay>,
68}
69
70impl Default for Policy {
71    /// Writes nowhere, everything else open
72    fn default() -> Self {
73        Self {
74            writable: vec![],
75            read_only: vec![],
76            pinned: vec![],
77            unreadable: vec![],
78            readable: vec![],
79            scratch: vec![],
80            hidden: vec![],
81            network: true,
82            unix_sockets: Access::All,
83            mach_services: Access::All,
84            apple_events: true,
85            own_signals: false,
86            own_terminals: false,
87            no_exec: vec![],
88            overlays: vec![],
89        }
90    }
91}
92
93impl Policy {
94    fn paths(&self) -> impl Iterator<Item = &PathBuf> {
95        let overlays = self
96            .overlays
97            .iter()
98            .flat_map(|o| [&o.lower, &o.upper, &o.work]);
99        let sockets = match &self.unix_sockets {
100            Access::All => &[][..],
101            Access::Only(dirs) => &dirs[..],
102        };
103        self.writable
104            .iter()
105            .chain(&self.read_only)
106            .chain(&self.pinned)
107            .chain(&self.unreadable)
108            .chain(&self.readable)
109            .chain(&self.scratch)
110            .chain(&self.hidden)
111            .chain(&self.no_exec)
112            .chain(sockets)
113            .chain(overlays)
114    }
115
116    // The sandbox matches the path a symlink resolves to, so `/tmp` must become `/private/tmp`
117    fn resolved(mut self) -> Self {
118        let lists = [
119            &mut self.writable,
120            &mut self.read_only,
121            &mut self.pinned,
122            &mut self.unreadable,
123            &mut self.readable,
124            &mut self.scratch,
125            &mut self.hidden,
126            &mut self.no_exec,
127        ];
128
129        // `/var/run` resolves to `/run` on most Linux systems, so one dir can appear twice
130        for list in lists {
131            for path in list.iter_mut() {
132                *path = real(path);
133            }
134
135            let mut seen = std::collections::HashSet::new();
136            list.retain(|p| seen.insert(p.clone()));
137        }
138
139        if let Access::Only(dirs) = &mut self.unix_sockets {
140            for dir in dirs.iter_mut() {
141                *dir = real(dir);
142            }
143        }
144
145        for o in &mut self.overlays {
146            for path in [&mut o.lower, &mut o.upper, &mut o.work] {
147                *path = real(path);
148            }
149        }
150
151        self
152    }
153}
154
155/// The real path, or for a missing one its real parent and its name, or the path as given
156pub(crate) fn real(path: &Path) -> PathBuf {
157    if let Ok(p) = path.canonicalize() {
158        return p;
159    }
160
161    match (path.parent().map(Path::canonicalize), path.file_name()) {
162        (Some(Ok(parent)), Some(name)) => parent.join(name),
163        _ => path.to_path_buf(),
164    }
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum Backend {
169    Seatbelt,
170    Bwrap,
171}
172
173impl Backend {
174    /// The sandbox this machine can start, or why none starts
175    pub fn detect() -> Result<Backend, Error> {
176        if cfg!(target_os = "macos") {
177            return seatbelt::detect().map(|_| Backend::Seatbelt);
178        }
179
180        if cfg!(target_os = "linux") {
181            return bwrap::detect().map(|_| Backend::Bwrap);
182        }
183
184        Err(Error::Unavailable(
185            "no OS sandbox on this platform, only sandbox-exec on macOS and bubblewrap on Linux"
186                .into(),
187        ))
188    }
189}
190
191/// Whether bwrap can mount an overlay with its layers in `dir`, and why not. It needs bwrap 0.10 or
192/// later and a kernel that mounts overlayfs in a user namespace
193pub fn overlay_supported(dir: &Path) -> Result<(), Error> {
194    bwrap::overlay_supported(dir)
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum Error {
199    /// No sandbox here, with the fix when there is one
200    Unavailable(String),
201    /// macOS refuses a sandbox inside another one, such as an agent's
202    Nested,
203    /// The backend cannot enforce this policy
204    Policy(String),
205}
206
207impl fmt::Display for Error {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        match self {
210            Error::Unavailable(why) => write!(f, "{why}"),
211            Error::Nested => write!(
212                f,
213                "macOS cannot start a sandbox inside another one, such as an agent's: run this outside it"
214            ),
215            Error::Policy(why) => write!(f, "{why}"),
216        }
217    }
218}
219
220impl std::error::Error for Error {}
221
222/// A policy checked against a backend, ready to wrap commands
223#[derive(Debug, Clone)]
224pub struct Sandbox {
225    backend: Backend,
226    policy: Policy,
227    argv: Vec<OsString>,
228}
229
230impl Sandbox {
231    pub fn seatbelt(policy: Policy) -> Result<Self, Error> {
232        Self::new(Backend::Seatbelt, policy)
233    }
234
235    pub fn bwrap(policy: Policy) -> Result<Self, Error> {
236        Self::new(Backend::Bwrap, policy)
237    }
238
239    /// Refuses a policy the backend cannot enforce. bwrap skips paths that do not exist yet, so
240    /// build the sandbox right before running the command
241    pub fn new(backend: Backend, policy: Policy) -> Result<Self, Error> {
242        if let Some(p) = policy.paths().find(|p| !p.is_absolute()) {
243            return Err(Error::Policy(format!(
244                "{}: not an absolute path",
245                p.display()
246            )));
247        }
248
249        let policy = policy.resolved();
250        let argv = match backend {
251            Backend::Seatbelt => seatbelt::argv(&policy)?,
252            Backend::Bwrap => bwrap::argv(&policy)?,
253        };
254        Ok(Self {
255            backend,
256            policy,
257            argv,
258        })
259    }
260
261    pub fn backend(&self) -> Backend {
262        self.backend
263    }
264
265    /// The policy with every path resolved, as the sandbox matches it
266    pub fn policy(&self) -> &Policy {
267        &self.policy
268    }
269
270    /// The program and arguments that go before the command, for a caller that writes a script
271    pub fn argv(&self) -> &[OsString] {
272        &self.argv
273    }
274
275    /// `program` in the sandbox. The caller adds its arguments, environment and directory
276    pub fn command(&self, program: impl AsRef<OsStr>) -> Command {
277        let mut cmd = Command::new(&self.argv[0]);
278        cmd.args(&self.argv[1..]).arg(program);
279        cmd
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn refuses_a_relative_path() {
289        let policy = Policy {
290            hidden: vec!["relative".into()],
291            ..Policy::default()
292        };
293        let err = Sandbox::seatbelt(policy).unwrap_err();
294        assert!(matches!(err, Error::Policy(m) if m.contains("relative")));
295    }
296
297    #[test]
298    fn a_dir_listed_twice_through_a_symlink_appears_once() {
299        let dir = tempfile::tempdir().unwrap();
300        let run = dir.path().join("run");
301        std::fs::create_dir(&run).unwrap();
302        std::os::unix::fs::symlink(&run, dir.path().join("var-run")).unwrap();
303        let policy = Policy {
304            scratch: vec![run.clone(), dir.path().join("var-run")],
305            ..Policy::default()
306        };
307        assert_eq!(policy.resolved().scratch, [real(&run)]);
308    }
309
310    #[test]
311    fn resolves_a_missing_path_through_its_parent() {
312        let dir = tempfile::tempdir().unwrap();
313        let missing = dir.path().join("missing");
314        assert_eq!(
315            real(&missing),
316            dir.path().canonicalize().unwrap().join("missing")
317        );
318    }
319
320    #[test]
321    fn the_command_comes_after_the_sandbox_argv() {
322        let sandbox = Sandbox::bwrap(Policy::default()).unwrap();
323        let cmd = sandbox.command("/bin/sh");
324        assert_eq!(cmd.get_program(), "bwrap");
325        let args: Vec<_> = cmd.get_args().collect();
326        assert_eq!(args[args.len() - 2..], ["--", "/bin/sh"]);
327    }
328}