Skip to main content

adk_sandbox/sandbox/
linux.rs

1//! Linux bubblewrap sandbox enforcer.
2//!
3//! Uses `bwrap` with user namespaces to create isolated filesystem and
4//! process environments without requiring root privileges.
5//!
6//! ## How It Works
7//!
8//! 1. Bubblewrap arguments are generated from the [`SandboxPolicy`]
9//! 2. The original command is wrapped: `bwrap <args> -- <program> <args...>`
10//! 3. The kernel enforces namespace-based isolation on the child process
11//!
12//! ## Key bwrap Arguments
13//!
14//! - `--die-with-parent` — kill child when parent exits
15//! - `--unshare-pid` — isolate process ID namespace
16//! - `--unshare-net` — unless the network is `Open`: an empty network namespace, so no IP
17//!   traffic and no abstract Unix sockets leave the sandbox
18//! - `--ro-bind <src> <dest>` — read-only filesystem bind mount
19//! - `--bind <src> <dest>` — read-write filesystem bind mount
20//! - `--new-session` — always: a new session with no controlling terminal, so the child
21//!   cannot inject input into the caller's terminal with `TIOCSTI`
22//! - `--seccomp <fd>` — seccomp program that denies process creation
23//!
24//! ## Nested Paths
25//!
26//! bubblewrap shows the last mount made over a path, so the policy's paths are mounted
27//! shallowest first and the most specific entry decides (spec 3.1 §10 S3): a read-only entry
28//! inside a read-write entry is mounted after it and stays read-only. Each writable directory
29//! above such an entry is also bound onto itself, which makes it a mount point the kernel
30//! refuses to rename or remove, so the entry cannot be carried away from its path and the
31//! path recreated writable.
32//!
33//! ## Network
34//!
35//! `Denied` network access is `--unshare-net`: an empty network namespace, so no IP traffic and
36//! no abstract Unix sockets. A Unix-domain socket on the filesystem is reached through its
37//! path, not the network namespace, and a read-only bind does not refuse `connect`, so under
38//! `Denied` the enforcer also keeps the host's shared socket directories out:
39//!
40//! | Policy | Effect |
41//! |--------|--------|
42//! | A grant of `/run`, or of a path under it, that holds a socket or cannot be fully listed | Refused with [`SandboxError::Unenforceable`] |
43//! | A grant of `/tmp`, `/var/tmp` or `/dev/shm` itself | Refused the same way; a directory below them can be granted |
44//! | A grant above them, such as `/` | Each is covered with an empty, read-only `tmpfs` before deeper grants are mounted, hiding the sockets of Docker, D-Bus, systemd, tmux, X11 and SSH agents |
45//!
46//! A socket elsewhere under a granted path, such as in a home directory, stays reachable;
47//! grant directories that hold none.
48//!
49//! `Proxied` (feature `egress-proxy`) keeps `--unshare-net` and places the egress proxy's
50//! listener inside the call's network namespace: bubblewrap reports the sandbox's process id on
51//! [`INFO_FD`] and holds the program on [`BLOCK_FD`]; a short-lived helper joins the sandbox's
52//! user and network namespaces, waits for bubblewrap to bring up loopback, opens the listening
53//! socket on `127.0.0.1:<port>` and passes it back; the call's [`CallProxy`] serves it, and only
54//! then is the program released. When any step fails the program is released with no listener, so it
55//! reaches nothing. Without `egress-proxy`, `Proxied` is refused with
56//! [`SandboxError::Unenforceable`].
57//!
58//! [`CallProxy`]: crate::egress_proxy::CallProxy
59//!
60//! ## Process Spawning
61//!
62//! When `allow_process_spawn` is `false`, the wrapped program runs under a seccomp filter
63//! that fails `fork`, `vfork`, and non-thread `clone` with `EPERM` and `clone3` with
64//! `ENOSYS`. Threads and `execve` keep working. The filter is generated for x86-64 and
65//! AArch64; on any other architecture [`SandboxEnforcer::configure_command`] returns
66//! `EnforcerFailed` rather than running without it.
67//!
68//! The filter reaches bubblewrap as file descriptor [`SECCOMP_FD`], which
69//! [`SandboxEnforcer::configure_command`] installs on the command. Running the output of
70//! [`LinuxEnforcer::generate_args`] without that call makes bubblewrap exit with an error.
71
72use std::ffi::{OsStr, OsString};
73
74use super::layering::Layering;
75use super::seccomp;
76use super::{
77    AccessMode, AllowedPath, NetworkAccess, NetworkSupport, ProxyListener, SandboxEnforcer,
78    SandboxPolicy, WrappedCommand, canonicalize_paths,
79};
80use crate::error::SandboxError;
81
82/// Directories where host daemons and sessions keep Unix sockets. Under a restrictive network
83/// a grant of one of them is refused, and a grant above one covers it with an empty `tmpfs`.
84const SOCKET_DIRECTORIES: &[&str] = &["/run", "/tmp", "/var/tmp", "/dev/shm"];
85
86/// File descriptor bubblewrap writes its JSON information, the sandbox's process id among it,
87/// to under `Proxied` network access.
88pub const INFO_FD: i32 = 65;
89
90/// File descriptor bubblewrap waits on before it runs the program under `Proxied` network
91/// access, until the proxy's listener is in place.
92pub const BLOCK_FD: i32 = 66;
93
94/// File descriptor bubblewrap reads the process-creation seccomp program from.
95///
96/// High enough to stay clear of stdio and the descriptors the standard library uses while
97/// spawning, and below every default `RLIMIT_NOFILE`.
98pub const SECCOMP_FD: i32 = 64;
99
100/// Linux bubblewrap sandbox enforcer.
101///
102/// Wraps child processes with `bwrap` arguments to enforce namespace-based
103/// filesystem, network, and process isolation.
104///
105/// # Example
106///
107/// ```rust,ignore
108/// use adk_sandbox::sandbox::linux::LinuxEnforcer;
109/// use adk_sandbox::sandbox::{SandboxEnforcer, SandboxPolicyBuilder};
110/// use std::ffi::OsString;
111///
112/// let enforcer = LinuxEnforcer::new();
113/// enforcer.probe()?;
114///
115/// let policy = SandboxPolicyBuilder::new()
116///     .allow_read("/usr/lib")
117///     .allow_read_write("/tmp/work")
118///     .build();
119///
120/// let wrapped = enforcer.wrap_command(
121///     "python3".as_ref(),
122///     &[OsString::from("-c"), OsString::from("print('hello')")],
123///     &policy,
124/// )?;
125/// // wrapped.program == "bwrap"
126/// // wrapped.args == ["--die-with-parent", "--unshare-pid", "--unshare-net",
127/// //                   "--new-session", "--seccomp", "64",
128/// //                   "--ro-bind", "/usr/lib", "/usr/lib",
129/// //                   "--bind", "/tmp/work", "/tmp/work",
130/// //                   "--", "python3", "-c", "print('hello')"]
131/// // `configure_command` must then be applied to the command built from `wrapped`.
132/// ```
133pub struct LinuxEnforcer;
134
135impl LinuxEnforcer {
136    /// Creates a new Linux bubblewrap enforcer.
137    pub fn new() -> Self {
138        Self
139    }
140
141    /// Generates bubblewrap arguments from the policy.
142    ///
143    /// Always starts with `--die-with-parent` and `--unshare-pid`, and always passes
144    /// `--new-session`. Bind mounts follow, shallowest path first, with a read-write bind
145    /// of each writable directory above a nested read-only entry (see
146    /// [Nested Paths](self#nested-paths)).
147    /// The returned arguments do NOT include the `--` separator or the
148    /// original program/args — those are appended by `wrap_command`.
149    ///
150    /// # Example
151    ///
152    /// ```rust,ignore
153    /// use adk_sandbox::sandbox::linux::LinuxEnforcer;
154    /// use adk_sandbox::sandbox::SandboxPolicyBuilder;
155    ///
156    /// let policy = SandboxPolicyBuilder::new()
157    ///     .allow_read("/usr/lib")
158    ///     .build();
159    ///
160    /// let args = LinuxEnforcer::generate_args(&policy);
161    /// assert_eq!(args[0], "--die-with-parent");
162    /// assert_eq!(args[1], "--unshare-pid");
163    /// assert!(args.contains(&"--unshare-net".to_string()));
164    /// ```
165    pub fn generate_args(policy: &SandboxPolicy) -> Vec<String> {
166        Self::generate_args_from_paths(
167            &policy.allowed_paths,
168            &policy.network,
169            policy.allow_process_spawn,
170        )
171    }
172
173    /// Internal: generates args from pre-canonicalized paths.
174    fn generate_args_from_paths(
175        paths: &[AllowedPath],
176        network: &NetworkAccess,
177        allow_process_spawn: bool,
178    ) -> Vec<String> {
179        let mut args = Vec::with_capacity(16);
180
181        // Always: terminate child when parent exits
182        args.push("--die-with-parent".to_string());
183
184        // Always: isolate PID namespace
185        args.push("--unshare-pid".to_string());
186
187        // Network isolation
188        if network.restricts() {
189            args.push("--unshare-net".to_string());
190        }
191        if let NetworkAccess::Proxied { .. } = network {
192            args.extend(
193                ["--info-fd", &INFO_FD.to_string(), "--block-fd", &BLOCK_FD.to_string()]
194                    .map(str::to_string),
195            );
196        }
197
198        // Always: a new session with no controlling terminal, so the child cannot inject
199        // input into the caller's terminal with `TIOCSTI` (spec 3.1 §10 S2).
200        args.push("--new-session".to_string());
201
202        // Process spawn restriction: the seccomp program is what denies fork and clone.
203        if !allow_process_spawn {
204            args.push("--seccomp".to_string());
205            args.push(SECCOMP_FD.to_string());
206        }
207
208        // Filesystem bind mounts, shallowest first: a later mount covers an earlier one, so the
209        // most specific entry decides. Pinned directories become mount points, which the
210        // kernel refuses to rename or remove. Under a restrictive network a socket directory
211        // below a mount is covered right after it, before any deeper grant is mounted.
212        let mut covered: Vec<&str> = Vec::new();
213        for (path, mode) in Layering::new(paths).mounts() {
214            let path_str = path.to_string_lossy().to_string();
215            match mode {
216                AccessMode::ReadOnly => {
217                    args.push("--ro-bind".to_string());
218                    args.push(path_str.clone());
219                    args.push(path_str);
220                }
221                AccessMode::ReadWrite => {
222                    args.push("--bind".to_string());
223                    args.push(path_str.clone());
224                    args.push(path_str);
225                }
226            }
227            if !network.restricts() {
228                continue;
229            }
230            for directory in SOCKET_DIRECTORIES {
231                let target = std::path::Path::new(directory);
232                let below = target != path && target.starts_with(path);
233                if below
234                    && !covered.contains(directory)
235                    && std::fs::symlink_metadata(target).is_ok_and(|m| m.is_dir())
236                {
237                    args.push("--tmpfs".to_string());
238                    args.push((*directory).to_string());
239                    covered.push(directory);
240                }
241            }
242        }
243        for directory in covered {
244            args.push("--remount-ro".to_string());
245            args.push(directory.to_string());
246        }
247
248        args
249    }
250}
251
252impl Default for LinuxEnforcer {
253    fn default() -> Self {
254        Self::new()
255    }
256}
257
258impl SandboxEnforcer for LinuxEnforcer {
259    fn name(&self) -> &str {
260        "bubblewrap"
261    }
262
263    fn network_support(&self) -> NetworkSupport {
264        NetworkSupport { denied: true, proxied: cfg!(feature = "egress-proxy") }
265    }
266
267    fn proxy_listener(&self) -> ProxyListener {
268        ProxyListener::SandboxLoopback
269    }
270
271    fn probe(&self) -> Result<(), SandboxError> {
272        // Check that bwrap binary exists
273        let result = std::process::Command::new("bwrap")
274            .arg("--version")
275            .stdout(std::process::Stdio::null())
276            .stderr(std::process::Stdio::null())
277            .status();
278
279        match result {
280            Ok(status) if status.success() => {
281                // Also check user namespaces are available
282                // The root bind is not optional. bwrap gives the new namespace an empty
283                // root, so without it `/bin/true` does not exist inside and execvp fails —
284                // which this probe then reported as "user namespaces are not available",
285                // pointing operators at a sysctl that was never the problem. The check
286                // failed on every host, so the enforcer was never selectable on Linux.
287                let ns_check = std::process::Command::new("bwrap")
288                    .args(["--ro-bind", "/", "/", "--unshare-user", "--", "/bin/true"])
289                    .stdout(std::process::Stdio::null())
290                    .stderr(std::process::Stdio::null())
291                    .status();
292
293                match ns_check {
294                    Ok(s) if s.success() => Ok(()),
295                    _ => Err(SandboxError::EnforcerUnavailable {
296                        enforcer: "bubblewrap".to_string(),
297                        message: "user namespaces are not available. Check that \
298                                  `kernel.unprivileged_userns_clone` sysctl is set to 1."
299                            .to_string(),
300                    }),
301                }
302            }
303            Ok(_) => Err(SandboxError::EnforcerUnavailable {
304                enforcer: "bubblewrap".to_string(),
305                message: "bwrap binary found but returned an error. \
306                          Verify installation is complete."
307                    .to_string(),
308            }),
309            Err(e) => Err(SandboxError::EnforcerUnavailable {
310                enforcer: "bubblewrap".to_string(),
311                message: format!(
312                    "bwrap binary not found: {e}. Install bubblewrap: \
313                     `apt install bubblewrap` (Debian/Ubuntu) or \
314                     `dnf install bubblewrap` (Fedora/RHEL)."
315                ),
316            }),
317        }
318    }
319
320    fn wrap_command(
321        &self,
322        program: &OsStr,
323        args: &[OsString],
324        policy: &SandboxPolicy,
325    ) -> Result<WrappedCommand, SandboxError> {
326        self.network_support().check(self.name(), &policy.network)?;
327
328        // 1. Canonicalize all paths in the policy
329        let canonicalized_paths = canonicalize_paths(&policy.allowed_paths)?;
330        if policy.network.restricts() {
331            refuse_socket_directories(&canonicalized_paths, &policy.network)?;
332        }
333
334        // 2. Generate bwrap args from canonicalized paths
335        let bwrap_args = Self::generate_args_from_paths(
336            &canonicalized_paths,
337            &policy.network,
338            policy.allow_process_spawn,
339        );
340
341        // 3. Build the wrapped command: bwrap <args> -- <program> <original_args...>
342        let mut wrapped_args: Vec<OsString> = bwrap_args.into_iter().map(OsString::from).collect();
343        wrapped_args.push(OsString::from("--"));
344        wrapped_args.push(program.to_owned());
345        wrapped_args.extend_from_slice(args);
346
347        Ok(WrappedCommand { program: OsString::from("bwrap"), args: wrapped_args })
348    }
349
350    /// Installs the process-creation seccomp program as file descriptor [`SECCOMP_FD`].
351    ///
352    /// # Errors
353    ///
354    /// Returns `EnforcerFailed` when the policy denies process spawning on an architecture
355    /// without a generated filter, or when the descriptor cannot be prepared.
356    fn configure_command(
357        &self,
358        cmd: &mut tokio::process::Command,
359        policy: &SandboxPolicy,
360    ) -> Result<(), SandboxError> {
361        use std::io::Write;
362        use std::os::fd::{AsRawFd, OwnedFd};
363
364        if let NetworkAccess::Proxied { endpoint } = policy.network {
365            let failed = |error: std::io::Error| SandboxError::EnforcerFailed {
366                enforcer: "bubblewrap".to_string(),
367                message: format!("failed to prepare the egress proxy's descriptors: {error}"),
368            };
369            let (info_reader, info_writer) = std::io::pipe().map_err(failed)?;
370            let (block_reader, block_writer) = std::io::pipe().map_err(failed)?;
371            let (info_fd, block_fd) = (OwnedFd::from(info_writer), OwnedFd::from(block_reader));
372            // SAFETY: the closure runs in the forked child before exec and calls only dup2(2)
373            // and fcntl(2), which are async-signal-safe; it owns both descriptors.
374            unsafe {
375                cmd.pre_exec(move || {
376                    install_fd(info_fd.as_raw_fd(), INFO_FD)?;
377                    install_fd(block_fd.as_raw_fd(), BLOCK_FD)
378                });
379            }
380            std::thread::Builder::new()
381                .name("adk-sandbox-egress-namespace".to_string())
382                .spawn(move || namespace::attach_listener(info_reader, block_writer, endpoint.port))
383                .map_err(failed)?;
384        }
385
386        if policy.allow_process_spawn {
387            return Ok(());
388        }
389
390        let abi = seccomp::Abi::native().ok_or_else(|| SandboxError::EnforcerFailed {
391            enforcer: "bubblewrap".to_string(),
392            message: format!(
393                "no process-creation seccomp filter exists for {}; allow process spawning in \
394                 the policy or run on x86_64 or aarch64",
395                std::env::consts::ARCH
396            ),
397        })?;
398        let program = seccomp::encode(&seccomp::deny_process_creation(abi));
399
400        let failed = |error: std::io::Error| SandboxError::EnforcerFailed {
401            enforcer: "bubblewrap".to_string(),
402            message: format!("failed to prepare the seccomp program descriptor: {error}"),
403        };
404        // The program is a few hundred bytes, well inside a pipe buffer, so the write cannot
405        // block, and closing the writer gives bubblewrap its end-of-file.
406        let (reader, mut writer) = std::io::pipe().map_err(failed)?;
407        writer.write_all(&program).map_err(failed)?;
408        drop(writer);
409        let program_fd = OwnedFd::from(reader);
410
411        // SAFETY: the closure runs in the forked child before exec and calls only dup2(2) and
412        // fcntl(2), which are async-signal-safe. `program_fd` is owned by the closure, so the
413        // descriptor stays open until the command is dropped.
414        unsafe {
415            cmd.pre_exec(move || install_fd(program_fd.as_raw_fd(), SECCOMP_FD));
416        }
417        Ok(())
418    }
419}
420
421/// Canonicalizes all paths in the policy, logging warnings for changed paths.
422/// Makes `source` available to the program as `target`, inheritable across exec.
423///
424/// Runs in the forked child; dup2(2) and fcntl(2) are async-signal-safe.
425fn install_fd(source: i32, target: i32) -> std::io::Result<()> {
426    // SAFETY: plain descriptor syscalls on descriptors the caller owns.
427    let result = unsafe {
428        if source == target {
429            // dup2 onto itself leaves FD_CLOEXEC set, so clear the flag directly.
430            libc::fcntl(source, libc::F_SETFD, 0)
431        } else {
432            libc::dup2(source, target)
433        }
434    };
435    if result == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) }
436}
437
438/// The egress proxy's listener inside a sandbox's network namespace.
439#[cfg(feature = "egress-proxy")]
440mod namespace {
441    use std::fs::File;
442    use std::io::{Read, Write};
443    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
444    use std::os::unix::net::UnixStream;
445    use std::os::unix::process::CommandExt;
446
447    /// Waits for bubblewrap's process id, opens the listener in its namespace, hands it to the
448    /// call's proxy, and releases the program, which runs with no listener if a step failed.
449    pub(super) fn attach_listener(
450        info: std::io::PipeReader,
451        mut block: std::io::PipeWriter,
452        port: u16,
453    ) {
454        let attached =
455            child_pid(info).and_then(|pid| listen_in_namespace(pid, port)).and_then(|listener| {
456                if crate::egress_proxy::deliver_namespace_listener(port, listener) {
457                    Ok(())
458                } else {
459                    Err(std::io::Error::other("no egress proxy waits for this call"))
460                }
461            });
462        if let Err(error) = attached {
463            tracing::warn!(
464                error = %error,
465                sandbox.proxy_port = port,
466                "the egress proxy listener could not be placed in the sandbox; the program \
467                 reaches no network"
468            );
469        }
470        let _ = block.write_all(b"1");
471    }
472
473    /// Reads bubblewrap's JSON information up to its closing brace and returns `child-pid`.
474    fn child_pid(mut info: std::io::PipeReader) -> std::io::Result<u32> {
475        let mut text = Vec::new();
476        let mut chunk = [0u8; 512];
477        while !text.contains(&b'}') {
478            match info.read(&mut chunk)? {
479                0 => break,
480                n => text.extend_from_slice(&chunk[..n]),
481            }
482            if text.len() > 64 * 1024 {
483                break;
484            }
485        }
486        let text = String::from_utf8_lossy(&text);
487        text.split("\"child-pid\"")
488            .nth(1)
489            .and_then(|rest| {
490                let digits: String = rest
491                    .trim_start_matches(|c: char| c == ':' || c.is_whitespace())
492                    .chars()
493                    .take_while(char::is_ascii_digit)
494                    .collect();
495                digits.parse().ok()
496            })
497            .ok_or_else(|| {
498                std::io::Error::other(format!("bubblewrap reported no child-pid: {text}"))
499            })
500    }
501
502    /// Opens a listener on `127.0.0.1:<port>` inside the namespaces of process `pid`, through a
503    /// helper that joins them, since only a single-threaded process may join a user namespace.
504    fn listen_in_namespace(pid: u32, port: u16) -> std::io::Result<std::net::TcpListener> {
505        let user = File::open(format!("/proc/{pid}/ns/user"))?;
506        let net = File::open(format!("/proc/{pid}/ns/net"))?;
507        let (parent, child) = UnixStream::pair()?;
508        let (user_fd, net_fd, child_fd) = (user.as_raw_fd(), net.as_raw_fd(), child.as_raw_fd());
509        let mut helper = std::process::Command::new("true");
510        helper
511            .stdin(std::process::Stdio::null())
512            .stdout(std::process::Stdio::null())
513            .stderr(std::process::Stdio::null());
514        // SAFETY: the closure runs in the forked, single-threaded child before exec and makes
515        // only async-signal-safe system calls on stack data.
516        unsafe {
517            helper.pre_exec(move || {
518                if libc::setns(user_fd, libc::CLONE_NEWUSER) == -1
519                    || libc::setns(net_fd, libc::CLONE_NEWNET) == -1
520                {
521                    return Err(std::io::Error::last_os_error());
522                }
523                wait_for_loopback()?;
524                let listener = bind_loopback(port)?;
525                send_fd(child_fd, listener)
526            });
527        }
528        let status = helper.status()?;
529        if !status.success() {
530            return Err(std::io::Error::other(format!("the namespace helper ended with {status}")));
531        }
532        drop((user, net, child));
533        let fd = receive_fd(&parent)?;
534        Ok(std::net::TcpListener::from(fd))
535    }
536
537    /// Waits until bubblewrap has brought `lo` up in the current network namespace.
538    ///
539    /// bubblewrap reports its child's process id before that child configures loopback, and
540    /// adds `127.0.0.1` exclusively: an interface this helper raised first already carries
541    /// the address, and bubblewrap then exits with `loopback: Failed RTM_NEWADDR`. The helper
542    /// therefore changes nothing and binds only once bubblewrap's own setup shows as `IFF_UP`.
543    unsafe fn wait_for_loopback() -> std::io::Result<()> {
544        // bubblewrap raises the interface within milliseconds; the bound covers a loaded host.
545        const ATTEMPTS: u32 = 2_500;
546        let pause = libc::timespec { tv_sec: 0, tv_nsec: 2_000_000 };
547        // SAFETY: a zeroed `ifreq` is a valid value; the name is NUL-terminated.
548        unsafe {
549            let socket = libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0);
550            if socket == -1 {
551                return Err(std::io::Error::last_os_error());
552            }
553            let mut request: libc::ifreq = std::mem::zeroed();
554            for (slot, byte) in request.ifr_name.iter_mut().zip(b"lo\0") {
555                *slot = *byte as libc::c_char;
556            }
557            let mut outcome = Err(std::io::Error::from_raw_os_error(libc::ETIMEDOUT));
558            for _ in 0..ATTEMPTS {
559                if libc::ioctl(socket, libc::SIOCGIFFLAGS as _, &raw mut request) == -1 {
560                    outcome = Err(std::io::Error::last_os_error());
561                    break;
562                }
563                if request.ifr_ifru.ifru_flags & libc::IFF_UP as libc::c_short != 0 {
564                    outcome = Ok(());
565                    break;
566                }
567                libc::nanosleep(&raw const pause, std::ptr::null_mut());
568            }
569            libc::close(socket);
570            outcome
571        }
572    }
573
574    /// A listening TCP socket on `127.0.0.1:<port>`.
575    unsafe fn bind_loopback(port: u16) -> std::io::Result<libc::c_int> {
576        // SAFETY: `address` is a fully initialised `sockaddr_in` of the length passed.
577        unsafe {
578            let socket = libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0);
579            if socket == -1 {
580                return Err(std::io::Error::last_os_error());
581            }
582            let address = libc::sockaddr_in {
583                sin_family: libc::AF_INET as libc::sa_family_t,
584                sin_port: port.to_be(),
585                sin_addr: libc::in_addr {
586                    s_addr: u32::from(std::net::Ipv4Addr::LOCALHOST).to_be(),
587                },
588                sin_zero: [0; 8],
589            };
590            let length = std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t;
591            if libc::bind(socket, (&raw const address).cast(), length) == -1
592                || libc::listen(socket, 128) == -1
593            {
594                let error = std::io::Error::last_os_error();
595                libc::close(socket);
596                return Err(error);
597            }
598            Ok(socket)
599        }
600    }
601
602    /// Sends `fd` over the Unix socket `socket` (SCM_RIGHTS).
603    unsafe fn send_fd(socket: libc::c_int, fd: libc::c_int) -> std::io::Result<()> {
604        // SAFETY: the control buffer is aligned for `cmsghdr` and large enough for one
605        // descriptor; every pointer refers to stack data that outlives the call.
606        unsafe {
607            let mut byte = [0u8; 1];
608            let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 };
609            let mut control = [0u64; 8];
610            let mut message: libc::msghdr = std::mem::zeroed();
611            message.msg_iov = &mut iov;
612            message.msg_iovlen = 1;
613            message.msg_control = control.as_mut_ptr().cast();
614            message.msg_controllen =
615                libc::CMSG_SPACE(std::mem::size_of::<libc::c_int>() as u32) as _;
616            let header = libc::CMSG_FIRSTHDR(&message);
617            (*header).cmsg_level = libc::SOL_SOCKET;
618            (*header).cmsg_type = libc::SCM_RIGHTS;
619            (*header).cmsg_len = libc::CMSG_LEN(std::mem::size_of::<libc::c_int>() as u32) as _;
620            std::ptr::write_unaligned(libc::CMSG_DATA(header).cast::<libc::c_int>(), fd);
621            if libc::sendmsg(socket, &message, 0) == -1 {
622                return Err(std::io::Error::last_os_error());
623            }
624            Ok(())
625        }
626    }
627
628    /// Receives one descriptor sent with SCM_RIGHTS.
629    fn receive_fd(socket: &UnixStream) -> std::io::Result<OwnedFd> {
630        // SAFETY: as in `send_fd`; the received descriptor is owned by the returned value.
631        unsafe {
632            let mut byte = [0u8; 1];
633            let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 };
634            let mut control = [0u64; 8];
635            let mut message: libc::msghdr = std::mem::zeroed();
636            message.msg_iov = &mut iov;
637            message.msg_iovlen = 1;
638            message.msg_control = control.as_mut_ptr().cast();
639            message.msg_controllen = std::mem::size_of_val(&control) as _;
640            if libc::recvmsg(socket.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC) == -1 {
641                return Err(std::io::Error::last_os_error());
642            }
643            let header = libc::CMSG_FIRSTHDR(&message);
644            if header.is_null()
645                || (*header).cmsg_level != libc::SOL_SOCKET
646                || (*header).cmsg_type != libc::SCM_RIGHTS
647            {
648                return Err(std::io::Error::other("the namespace helper sent no listener"));
649            }
650            let fd = std::ptr::read_unaligned(libc::CMSG_DATA(header).cast::<libc::c_int>());
651            Ok(OwnedFd::from_raw_fd(fd))
652        }
653    }
654}
655
656/// Without `egress-proxy` there is no proxy to serve the listener; `Proxied` is refused before
657/// a command is built, so this only releases the program.
658#[cfg(not(feature = "egress-proxy"))]
659mod namespace {
660    use std::io::Write;
661
662    pub(super) fn attach_listener(
663        _info: std::io::PipeReader,
664        mut block: std::io::PipeWriter,
665        _port: u16,
666    ) {
667        let _ = block.write_all(b"1");
668    }
669}
670
671/// Refuses a grant of a shared socket directory, or of a path under `/run` that holds a Unix
672/// socket: a bind mount keeps its sockets reachable whatever the network namespace.
673fn refuse_socket_directories(
674    paths: &[AllowedPath],
675    network: &NetworkAccess,
676) -> Result<(), SandboxError> {
677    let run = std::path::Path::new("/run");
678    for entry in paths {
679        let shared = SOCKET_DIRECTORIES
680            .iter()
681            .any(|directory| entry.path == std::path::Path::new(directory));
682        // A walk of at most this many entries; a larger tree is refused unread.
683        let mut budget = 4096;
684        if shared || (entry.path.starts_with(run) && holds_socket(&entry.path, &mut budget)) {
685            return Err(SandboxError::Unenforceable {
686                enforcer: "bubblewrap".to_string(),
687                requirement: format!(
688                    "network access {network} while granting '{}': Unix sockets there (Docker, \
689                     D-Bus, systemd, SSH agents) stay reachable through a bind mount; grant a \
690                     directory below it that holds none",
691                    entry.path.display()
692                ),
693            });
694        }
695    }
696    Ok(())
697}
698
699/// Whether `path` is, or holds within `budget` entries, a Unix socket; a directory that cannot
700/// be listed or a tree past the budget counts as holding one.
701fn holds_socket(path: &std::path::Path, budget: &mut usize) -> bool {
702    use std::os::unix::fs::FileTypeExt;
703    let Ok(metadata) = std::fs::symlink_metadata(path) else { return true };
704    if metadata.file_type().is_socket() {
705        return true;
706    }
707    if !metadata.is_dir() {
708        return false;
709    }
710    let Ok(entries) = std::fs::read_dir(path) else { return true };
711    for entry in entries {
712        if *budget == 0 {
713            return true;
714        }
715        *budget -= 1;
716        let Ok(entry) = entry else { return true };
717        let Ok(kind) = entry.file_type() else { return true };
718        if kind.is_socket() || (kind.is_dir() && holds_socket(&entry.path(), budget)) {
719            return true;
720        }
721    }
722    false
723}
724
725// ---------------------------------------------------------------------------
726// Tests
727// ---------------------------------------------------------------------------
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732    use crate::sandbox::SandboxPolicyBuilder;
733
734    #[test]
735    fn test_generate_args_deny_all() {
736        let policy = SandboxPolicyBuilder::new().build();
737        let args = LinuxEnforcer::generate_args(&policy);
738
739        assert_eq!(args[0], "--die-with-parent");
740        assert_eq!(args[1], "--unshare-pid");
741        assert!(args.contains(&"--unshare-net".to_string()));
742        assert!(args.contains(&"--new-session".to_string()));
743        assert!(
744            args.windows(2).any(|pair| pair[0] == "--seccomp" && pair[1] == SECCOMP_FD.to_string())
745        );
746        // No bind mounts
747        assert!(!args.contains(&"--ro-bind".to_string()));
748        assert!(!args.contains(&"--bind".to_string()));
749    }
750
751    #[test]
752    fn test_generate_args_read_only_path() {
753        let policy = SandboxPolicyBuilder::new().allow_read("/usr/lib").build();
754        let args = LinuxEnforcer::generate_args(&policy);
755
756        let ro_idx = args.iter().position(|a| a == "--ro-bind").unwrap();
757        assert_eq!(args[ro_idx + 1], "/usr/lib");
758        assert_eq!(args[ro_idx + 2], "/usr/lib");
759        assert!(!args.contains(&"--bind".to_string()));
760    }
761
762    #[test]
763    fn test_generate_args_read_write_path() {
764        let policy = SandboxPolicyBuilder::new().allow_read_write("/tmp/work").build();
765        let args = LinuxEnforcer::generate_args(&policy);
766
767        let bind_idx = args.iter().position(|a| a == "--bind").unwrap();
768        assert_eq!(args[bind_idx + 1], "/tmp/work");
769        assert_eq!(args[bind_idx + 2], "/tmp/work");
770        assert!(!args.contains(&"--ro-bind".to_string()));
771    }
772
773    #[test]
774    fn test_generate_args_network_allowed() {
775        let policy = SandboxPolicyBuilder::new().allow_network().build();
776        let args = LinuxEnforcer::generate_args(&policy);
777
778        assert!(!args.contains(&"--unshare-net".to_string()));
779    }
780
781    #[test]
782    fn test_generate_args_network_denied() {
783        let policy = SandboxPolicyBuilder::new().build();
784        let args = LinuxEnforcer::generate_args(&policy);
785
786        assert!(args.contains(&"--unshare-net".to_string()));
787    }
788
789    #[test]
790    fn test_generate_args_process_spawn_allowed() {
791        let policy = SandboxPolicyBuilder::new().allow_process_spawn().build();
792        let args = LinuxEnforcer::generate_args(&policy);
793
794        assert!(!args.contains(&"--seccomp".to_string()));
795    }
796
797    /// A shell is the case that allows process spawning, and it is the one that can reach a
798    /// controlling terminal, so the new session cannot depend on the seccomp filter.
799    #[test]
800    fn every_policy_starts_a_new_session() {
801        for allow_process_spawn in [false, true] {
802            for network in [NetworkAccess::Denied, NetworkAccess::Open] {
803                let args =
804                    LinuxEnforcer::generate_args_from_paths(&[], &network, allow_process_spawn);
805                assert_eq!(
806                    args.iter().filter(|arg| *arg == "--new-session").count(),
807                    1,
808                    "spawn={allow_process_spawn} network={network}: {args:?}"
809                );
810            }
811        }
812    }
813
814    #[test]
815    fn test_generate_args_process_spawn_denied() {
816        let policy = SandboxPolicyBuilder::new().build();
817        let args = LinuxEnforcer::generate_args(&policy);
818
819        assert!(args.contains(&"--new-session".to_string()));
820        let seccomp = args.iter().position(|arg| arg == "--seccomp").expect("--seccomp present");
821        assert_eq!(args[seccomp + 1], SECCOMP_FD.to_string());
822    }
823
824    #[test]
825    fn configure_command_is_a_no_op_when_spawning_is_allowed() {
826        let policy = SandboxPolicyBuilder::new().allow_process_spawn().build();
827        let mut cmd = tokio::process::Command::new("true");
828
829        LinuxEnforcer::new().configure_command(&mut cmd, &policy).expect("nothing to configure");
830    }
831
832    #[test]
833    fn configure_command_installs_the_filter_on_supported_architectures() {
834        let policy = SandboxPolicyBuilder::new().build();
835        let mut cmd = tokio::process::Command::new("true");
836
837        let result = LinuxEnforcer::new().configure_command(&mut cmd, &policy);
838        if seccomp::Abi::native().is_some() {
839            result.expect("the filter is prepared on a supported architecture");
840        } else {
841            assert!(matches!(result, Err(SandboxError::EnforcerFailed { .. })), "{result:?}");
842        }
843    }
844
845    #[test]
846    fn test_generate_args_starts_with_die_with_parent() {
847        let policy = SandboxPolicyBuilder::new()
848            .allow_read("/tmp")
849            .allow_network()
850            .allow_process_spawn()
851            .build();
852        let args = LinuxEnforcer::generate_args(&policy);
853
854        assert_eq!(args[0], "--die-with-parent");
855    }
856
857    #[test]
858    fn test_generate_args_no_empty_strings() {
859        let policy = SandboxPolicyBuilder::new()
860            .allow_read("/usr/lib")
861            .allow_read_write("/tmp")
862            .allow_network()
863            .build();
864        let args = LinuxEnforcer::generate_args(&policy);
865
866        for arg in &args {
867            assert!(!arg.is_empty(), "found empty string in bwrap args");
868        }
869    }
870
871    #[test]
872    fn test_name() {
873        let enforcer = LinuxEnforcer::new();
874        assert_eq!(enforcer.name(), "bubblewrap");
875    }
876
877    /// `Proxied` keeps the empty network namespace and asks bubblewrap for its process id and
878    /// to wait for the listener; without `egress-proxy` there is no proxy, and it is refused.
879    #[test]
880    fn proxied_network_access_needs_the_egress_proxy() {
881        let endpoint = super::super::ProxyEndpoint { port: 3128 };
882        let policy = SandboxPolicyBuilder::new().proxied(endpoint).build();
883
884        let result = LinuxEnforcer::new().wrap_command(OsStr::new("true"), &[], &policy);
885
886        if cfg!(feature = "egress-proxy") {
887            let args: Vec<String> = result
888                .expect("Proxied is enforced with the egress proxy")
889                .args
890                .iter()
891                .map(|arg| arg.to_string_lossy().into_owned())
892                .collect();
893            for flag in [
894                vec!["--unshare-net".to_string()],
895                vec!["--info-fd".to_string(), INFO_FD.to_string()],
896                vec!["--block-fd".to_string(), BLOCK_FD.to_string()],
897            ] {
898                assert!(
899                    args.windows(flag.len()).any(|w| w == flag.as_slice()),
900                    "{flag:?} in {args:?}"
901                );
902            }
903        } else {
904            assert!(matches!(result, Err(SandboxError::Unenforceable { .. })), "{result:?}");
905        }
906    }
907
908    /// A read-only bind does not refuse `connect` on a Unix socket, so the shared socket
909    /// directories are refused under a restrictive network; an open network grants them.
910    #[test]
911    fn socket_directories_are_refused_under_denied_network() {
912        let enforcer = LinuxEnforcer::new();
913        for path in ["/run", "/tmp"] {
914            let denied = SandboxPolicyBuilder::new().allow_read(path).build();
915            let result = enforcer.wrap_command(OsStr::new("true"), &[], &denied);
916            assert!(
917                matches!(result, Err(SandboxError::Unenforceable { .. })),
918                "{path}: {result:?}"
919            );
920
921            let open = SandboxPolicyBuilder::new().allow_read(path).allow_network().build();
922            assert!(enforcer.wrap_command(OsStr::new("true"), &[], &open).is_ok(), "{path}");
923        }
924        let narrow = SandboxPolicyBuilder::new().allow_read("/usr").build();
925        assert!(enforcer.wrap_command(OsStr::new("true"), &[], &narrow).is_ok());
926    }
927
928    /// A grant of `/` covers the socket directories with empty read-only `tmpfs` mounts before
929    /// a deeper grant, so the workspace below `/tmp` stays reachable and the rest does not.
930    #[test]
931    fn a_granted_root_covers_the_socket_directories_under_denied_network() {
932        let workspace = tempfile::tempdir().expect("tempdir");
933        let workspace = std::fs::canonicalize(workspace.path()).expect("canonical");
934        let paths = [
935            AllowedPath { path: std::path::PathBuf::from("/"), mode: AccessMode::ReadOnly },
936            AllowedPath { path: workspace.clone(), mode: AccessMode::ReadWrite },
937        ];
938        let args = LinuxEnforcer::generate_args_from_paths(&paths, &NetworkAccess::Denied, true);
939        let position = |needle: &[&str]| args.windows(needle.len()).position(|w| w == needle);
940        let root = position(&["--ro-bind", "/", "/"]).expect("the root is bound");
941        let run = position(&["--tmpfs", "/run"]).expect("/run is covered");
942        let tmp = position(&["--tmpfs", "/tmp"]).expect("/tmp is covered");
943        let workspace = workspace.to_string_lossy().into_owned();
944        let bound = position(&["--bind", &workspace, &workspace]).expect("the workspace is bound");
945        assert!(root < run && run < bound && tmp < bound, "{args:?}");
946        assert!(position(&["--remount-ro", "/run"]).is_some_and(|ro| ro > bound), "{args:?}");
947
948        let open = LinuxEnforcer::generate_args_from_paths(&paths, &NetworkAccess::Open, true);
949        assert!(!open.iter().any(|arg| arg == "--tmpfs"), "{open:?}");
950    }
951
952    #[test]
953    fn test_wrap_command_nonexistent_path_fails() {
954        let enforcer = LinuxEnforcer::new();
955        let policy =
956            SandboxPolicyBuilder::new().allow_read("/nonexistent/path/that/does/not/exist").build();
957
958        let result = enforcer.wrap_command(OsStr::new("echo"), &[], &policy);
959
960        assert!(result.is_err());
961        let err = result.unwrap_err();
962        assert!(
963            matches!(err, SandboxError::PolicyViolation(_)),
964            "expected PolicyViolation, got: {err:?}"
965        );
966    }
967}