Skip to main content

weirdnet_ext/sandbox/
mod.rs

1//! The process sandbox for native extensions.
2//!
3//! An extension process starts with an empty environment, its own process group, resource
4//! limits, and a parent-death signal, and talks to the host only over the private socket the
5//! host hands it. On top of that:
6//!
7//! - **Linux**: `no_new_privs`, a Landlock ruleset (files: only the paths in the [`Policy`];
8//!   TCP bind and connect denied from ABI 4; abstract Unix sockets and signals outside the
9//!   sandbox denied from ABI 6) and a seccomp filter that denies `socket()` (the extension
10//!   already has its socket, so it can open no other), namespace and mount calls, `ptrace`,
11//!   `bpf`, `io_uring`, kernel module and keyring calls, and terminal input injection.
12//! - **macOS**: a `sandbox-exec` profile denying by default, allowing reads of the system
13//!   libraries and the policy's paths, writes to the policy's write paths, and no network.
14//! - **Windows**: native extensions don't run yet (see the README); use WASM.
15//!
16//! [`probe`] says what this machine gives; [`Policy::require`] refuses to start an
17//! extension when a layer is missing instead of running it with less.
18
19#[cfg(target_os = "linux")]
20pub(crate) mod linux;
21#[cfg(target_os = "macos")]
22pub(crate) mod macos;
23
24use std::path::PathBuf;
25
26/// Resource limits for an extension process.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Limits {
29    /// Address space in bytes (`RLIMIT_AS`); `None` for no limit.
30    pub memory: Option<u64>,
31    /// CPU seconds (`RLIMIT_CPU`).
32    pub cpu_secs: Option<u64>,
33    /// Open files (`RLIMIT_NOFILE`).
34    pub open_files: Option<u64>,
35}
36
37impl Default for Limits {
38    fn default() -> Self {
39        Self { memory: Some(4 << 30), cpu_secs: None, open_files: Some(256) }
40    }
41}
42
43/// How strict a launch must be.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum Require {
46    /// Every layer this OS has must be in force (Landlock with network rules and seccomp on
47    /// Linux; the profile on macOS). The default.
48    #[default]
49    Full,
50    /// Run with whatever this machine gives (older kernels), and say so in the [`Report`].
51    BestEffort,
52}
53
54/// What an extension process may touch.
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct Policy {
57    /// Paths it may read (files or directories, recursively).
58    pub read: Vec<PathBuf>,
59    /// Paths it may read and execute (its own binary, the system libraries).
60    pub read_exec: Vec<PathBuf>,
61    /// Paths it may read and write (its data directory).
62    pub write: Vec<PathBuf>,
63    /// Resource limits.
64    pub limits: Limits,
65    /// How strict to be.
66    pub require: Require,
67}
68
69impl Policy {
70    /// The policy for an installed extension: read and execute its own directory and the
71    /// system libraries, read the few system files a dynamically linked program needs, read
72    /// and write `data`.
73    pub fn for_extension(ext_dir: impl Into<PathBuf>, data: impl Into<PathBuf>) -> Self {
74        let mut read_exec: Vec<PathBuf> = vec![ext_dir.into()];
75        let mut read = Vec::new();
76        #[cfg(target_os = "linux")]
77        {
78            for p in ["/usr/lib", "/usr/lib64", "/lib", "/lib64", "/usr/libexec", "/nix/store"] {
79                read_exec.push(p.into());
80            }
81            for p in [
82                "/etc/ld.so.cache",
83                "/etc/ld.so.preload",
84                "/etc/localtime",
85                "/usr/share/zoneinfo",
86                "/dev/null",
87                "/dev/urandom",
88                "/dev/random",
89                "/sys/devices/system/cpu",
90                "/sys/fs/cgroup",
91            ] {
92                read.push(p.into());
93            }
94        }
95        #[cfg(target_os = "macos")]
96        {
97            for p in ["/usr/lib", "/System/Library", "/System/Volumes/Preboot/Cryptexes", "/System/Cryptexes", "/Library/Apple/usr/lib"] {
98                read_exec.push(p.into());
99            }
100            for p in ["/dev/null", "/dev/urandom", "/dev/random", "/private/var/db/timezone", "/usr/share/zoneinfo"] {
101                read.push(p.into());
102            }
103        }
104        Self { read, read_exec, write: vec![data.into()], limits: Limits::default(), require: Require::Full }
105    }
106}
107
108/// What the sandbox did (or could do) on this machine.
109#[derive(Debug, Clone, Default, PartialEq, Eq)]
110pub struct Report {
111    /// The OS mechanism: "landlock+seccomp", "sandbox-exec", or "none".
112    pub mechanism: &'static str,
113    /// The Landlock ABI version, if any (Linux).
114    pub landlock_abi: Option<u32>,
115    /// Whether file access is limited to the policy.
116    pub files: bool,
117    /// Whether the extension can't open network connections of its own.
118    pub network: bool,
119    /// Whether the syscall filter is in force (Linux).
120    pub syscalls: bool,
121    /// What is missing that [`Require::Full`] needs, in words.
122    pub missing: Vec<String>,
123    /// Weaker spots that don't stop a launch, in words (such as signal scoping on kernels
124    /// before 6.12).
125    pub notes: Vec<String>,
126}
127
128impl Report {
129    /// True if nothing is missing.
130    pub fn full(&self) -> bool {
131        self.missing.is_empty()
132    }
133}
134
135/// Whether native extensions can run on this OS at all.
136pub fn native_allowed() -> bool {
137    cfg!(any(target_os = "linux", target_os = "macos"))
138}
139
140/// What the sandbox can do on this machine.
141pub fn probe() -> Report {
142    #[cfg(target_os = "linux")]
143    {
144        linux::probe()
145    }
146    #[cfg(target_os = "macos")]
147    {
148        macos::probe()
149    }
150    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
151    {
152        Report { mechanism: "none", missing: vec!["native extensions are not supported on this OS".into()], ..Default::default() }
153    }
154}
155
156/// Marks every descriptor from 3 up, except `keep`, close-on-exec. Async-signal-safe.
157#[cfg(unix)]
158pub(crate) fn cloexec_all_but(keep: std::os::fd::RawFd) {
159    // SAFETY: getrlimit and fcntl on integers.
160    unsafe {
161        let mut l: libc::rlimit = std::mem::zeroed();
162        let max = if libc::getrlimit(libc::RLIMIT_NOFILE, &mut l) == 0 { (l.rlim_cur as u64).min(1 << 16) as i32 } else { 1024 };
163        for fd in 3..max.max(keep + 1) {
164            if fd != keep {
165                let f = libc::fcntl(fd, libc::F_GETFD);
166                if f >= 0 && f & libc::FD_CLOEXEC == 0 {
167                    libc::fcntl(fd, libc::F_SETFD, f | libc::FD_CLOEXEC);
168                }
169            }
170        }
171    }
172}
173
174/// Builds the command for a native extension: sandboxed, empty environment except `env`,
175/// own process group, killed when dropped. `keep_fd` is the only descriptor it inherits.
176#[cfg(unix)]
177pub(crate) fn command(
178    binary: &std::path::Path,
179    args: &[String],
180    policy: &Policy,
181    keep_fd: std::os::fd::RawFd,
182    env: &[(String, String)],
183) -> crate::error::Result<(tokio::process::Command, Report)> {
184    #[cfg(target_os = "linux")]
185    let (prep, report, mut cmd) = {
186        let (p, r) = linux::prepare(policy, keep_fd)?;
187        (p, r, tokio::process::Command::new(binary))
188    };
189    #[cfg(target_os = "macos")]
190    let (prep, report, mut cmd) = {
191        let (p, r) = macos::prepare(policy, keep_fd)?;
192        let mut c = tokio::process::Command::new(macos::SANDBOX_EXEC);
193        c.arg("-p").arg(&p.profile).arg(binary);
194        (p, r, c)
195    };
196    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
197    {
198        let _ = (binary, args, policy, keep_fd, env);
199        return Err(crate::error::Error::Unsupported("native extensions don't run on this OS".into()));
200    }
201    #[cfg(any(target_os = "linux", target_os = "macos"))]
202    {
203        cmd.args(args).env_clear().envs(env.iter().map(|(k, v)| (k, v))).kill_on_drop(true).process_group(0);
204        cmd.stdin(std::process::Stdio::null());
205        if let Some(dir) = policy.write.first() {
206            cmd.current_dir(dir);
207        }
208        // SAFETY: `apply` makes only async-signal-safe calls on memory prepared before the fork.
209        unsafe {
210            cmd.pre_exec(move || prep.apply());
211        }
212        Ok((cmd, report))
213    }
214}