Skip to main content

unkernel_rs/
sandbox.rs

1//! Defense-in-depth host sandboxing (Linux Landlock ABI v1-v4 + PR_SET_NO_NEW_PRIVS)
2//! and cross-platform host process telemetry (`getrusage` peak RSS, `getrandom` entropy).
3
4use std::path::PathBuf;
5
6/// Host path allowed through Landlock when sandboxing is enabled.
7#[derive(Debug, Clone)]
8pub struct SandboxPathGrant {
9    pub path: PathBuf,
10    pub read_only: bool,
11}
12
13/// Summary of the OS sandbox enforcement status.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct SandboxStatus {
16    pub enabled: bool,
17    pub landlock_abi: Option<i32>,
18    pub net_blocked: bool,
19    pub reason: Option<String>,
20}
21
22/// Read peak resident set size (MiB) accurately:
23/// - On Linux, reads `VmHWM:` from `/proc/self/status` (using a pre-opened fd cached before
24///   Landlock when available), which is immune to the Linux `fork->exec` `ru_maxrss` parent
25///   inheritance quirk.
26/// - Falls back to `getrusage(RUSAGE_SELF)` on non-Linux targets or if `/proc` is unavailable.
27pub fn peak_rss_mib() -> f64 {
28    #[cfg(target_os = "linux")]
29    {
30        if let Some(mib) = read_proc_vm_hwm_mib() {
31            return mib;
32        }
33    }
34    #[cfg(unix)]
35    unsafe {
36        let mut ru: libc::rusage = std::mem::zeroed();
37        if libc::getrusage(libc::RUSAGE_SELF, &mut ru) == 0 {
38            #[cfg(target_os = "macos")]
39            {
40                return ru.ru_maxrss as f64 / (1024.0 * 1024.0);
41            }
42            #[cfg(not(target_os = "macos"))]
43            {
44                return ru.ru_maxrss as f64 / 1024.0;
45            }
46        }
47    }
48    #[cfg(windows)]
49    {
50        #[repr(C)]
51        #[allow(dead_code)]
52        struct ProcessMemoryCounters {
53            cb: u32,
54            page_fault_count: u32,
55            peak_working_set_size: usize,
56            working_set_size: usize,
57            quota_peak_paged_pool_usage: usize,
58            quota_paged_pool_usage: usize,
59            quota_peak_non_paged_pool_usage: usize,
60            quota_non_paged_pool_usage: usize,
61            pagefile_usage: usize,
62            peak_pagefile_usage: usize,
63        }
64        #[link(name = "kernel32")]
65        unsafe extern "system" {
66            fn GetCurrentProcess() -> *mut core::ffi::c_void;
67            fn K32GetProcessMemoryInfo(
68                process: *mut core::ffi::c_void,
69                ppsmem_counters: *mut ProcessMemoryCounters,
70                cb: u32,
71            ) -> i32;
72        }
73        let mut pmc: ProcessMemoryCounters = unsafe { std::mem::zeroed() };
74        pmc.cb = std::mem::size_of::<ProcessMemoryCounters>() as u32;
75        let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) };
76        if ok != 0 {
77            return pmc.peak_working_set_size as f64 / (1024.0 * 1024.0);
78        }
79    }
80    0.0
81}
82
83#[cfg(target_os = "linux")]
84static PROC_STATUS_FD: std::sync::OnceLock<Option<std::fs::File>> = std::sync::OnceLock::new();
85
86/// Pre-open `/proc/self/status` before applying Landlock so `peak_rss_mib()` can continue reading
87/// `VmHWM:` without opening any paths afterward.
88pub fn init_rss_handle() {
89    #[cfg(target_os = "linux")]
90    {
91        let _ = PROC_STATUS_FD.get_or_init(|| std::fs::File::open("/proc/self/status").ok());
92    }
93}
94
95#[cfg(target_os = "linux")]
96fn read_proc_vm_hwm_mib() -> Option<f64> {
97    use std::os::unix::fs::FileExt;
98    let mut buf = [0u8; 4096];
99    let n = if let Some(Some(file)) = PROC_STATUS_FD.get() {
100        file.read_at(&mut buf, 0).ok()?
101    } else if let Ok(file) = std::fs::File::open("/proc/self/status") {
102        file.read_at(&mut buf, 0).ok()?
103    } else {
104        return None;
105    };
106    let text = std::str::from_utf8(&buf[..n]).ok()?;
107    for line in text.lines() {
108        if let Some(rest) = line.strip_prefix("VmHWM:")
109            && let Some(kb_str) = rest.split_whitespace().next()
110            && let Ok(kb) = kb_str.parse::<f64>()
111        {
112            return Some(kb / 1024.0);
113        }
114    }
115    None
116}
117
118/// Fill `dst` with cryptographic entropy via syscall (`getrandom` on Linux) so no `/dev/urandom`
119/// filesystem access is required after Landlock is applied.
120pub fn fill_random(dst: &mut [u8]) {
121    #[cfg(target_os = "linux")]
122    {
123        let mut offset = 0usize;
124        while offset < dst.len() {
125            let ret = unsafe {
126                libc::syscall(
127                    libc::SYS_getrandom,
128                    dst.as_mut_ptr().add(offset),
129                    dst.len() - offset,
130                    0u32,
131                )
132            };
133            if ret > 0 {
134                offset += ret as usize;
135            } else if ret == -1 {
136                let err = std::io::Error::last_os_error();
137                if err.kind() == std::io::ErrorKind::Interrupted {
138                    continue;
139                }
140                break;
141            } else {
142                break;
143            }
144        }
145        if offset == dst.len() {
146            return;
147        }
148    }
149
150    #[cfg(windows)]
151    {
152        #[link(name = "bcrypt")]
153        unsafe extern "system" {
154            fn BCryptGenRandom(
155                h_algorithm: *mut core::ffi::c_void,
156                pb_buffer: *mut u8,
157                cb_buffer: u32,
158                dw_flags: u32,
159            ) -> i32;
160        }
161        const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x0000_0002;
162        let mut offset = 0usize;
163        while offset < dst.len() {
164            let chunk = (dst.len() - offset).min(u32::MAX as usize) as u32;
165            let status = unsafe {
166                BCryptGenRandom(
167                    std::ptr::null_mut(),
168                    dst.as_mut_ptr().add(offset),
169                    chunk,
170                    BCRYPT_USE_SYSTEM_PREFERRED_RNG,
171                )
172            };
173            if status == 0 {
174                offset += chunk as usize;
175            } else {
176                break;
177            }
178        }
179    }
180
181    // Fallback for non-Linux Unix targets (e.g. macOS)
182    #[cfg(unix)]
183    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
184        use std::io::Read;
185        let _ = f.read_exact(dst);
186    }
187}
188
189/// Apply Linux Landlock + `PR_SET_NO_NEW_PRIVS` to the current thread and all threads it
190/// subsequently spawns.
191///
192/// Must be called **after** loading `.cwasm` and opening the `.erofs` image descriptor,
193/// and **before** spawning VM kernel threads.
194///
195/// Once applied:
196/// - No host filesystem path can be opened except the explicitly granted `paths` (e.g. 9p mounts).
197/// - On Landlock ABI v4+ (Linux >= 6.7), host TCP bind is always blocked; host TCP connect is also
198///   blocked unless `allow_outbound_tcp == true` (for opt-in `--net`).
199#[cfg(target_os = "linux")]
200pub fn apply_landlock(
201    paths: &[SandboxPathGrant],
202    allow_outbound_tcp: bool,
203) -> Result<SandboxStatus, String> {
204    use std::ffi::CString;
205    use std::os::unix::ffi::OsStrExt;
206
207    // Landlock syscall numbers are architecture-independent on modern Linux (444/445/446)
208    const SYS_LANDLOCK_CREATE_RULESET: libc::c_long = 444;
209    const SYS_LANDLOCK_ADD_RULE: libc::c_long = 445;
210    const SYS_LANDLOCK_RESTRICT_SELF: libc::c_long = 446;
211
212    const LANDLOCK_CREATE_RULESET_VERSION: u32 = 1 << 0;
213    const LANDLOCK_RULE_PATH_BENEATH: u32 = 1;
214
215    // Filesystem access rights (ABI v1..v3)
216    const ACCESS_FS_EXECUTE: u64 = 1 << 0;
217    const ACCESS_FS_WRITE_FILE: u64 = 1 << 1;
218    const ACCESS_FS_READ_FILE: u64 = 1 << 2;
219    const ACCESS_FS_READ_DIR: u64 = 1 << 3;
220    const ACCESS_FS_REMOVE_DIR: u64 = 1 << 4;
221    const ACCESS_FS_REMOVE_FILE: u64 = 1 << 5;
222    const ACCESS_FS_MAKE_CHAR: u64 = 1 << 6;
223    const ACCESS_FS_MAKE_DIR: u64 = 1 << 7;
224    const ACCESS_FS_MAKE_REG: u64 = 1 << 8;
225    const ACCESS_FS_MAKE_SOCK: u64 = 1 << 9;
226    const ACCESS_FS_MAKE_FIFO: u64 = 1 << 10;
227    const ACCESS_FS_MAKE_BLOCK: u64 = 1 << 11;
228    const ACCESS_FS_MAKE_SYM: u64 = 1 << 12;
229    const ACCESS_FS_REFER: u64 = 1 << 13; // ABI v2+
230    const ACCESS_FS_TRUNCATE: u64 = 1 << 14; // ABI v3+
231
232    // Network access rights (ABI v4+)
233    const ACCESS_NET_BIND_TCP: u64 = 1 << 0;
234    const ACCESS_NET_CONNECT_TCP: u64 = 1 << 1;
235
236    #[repr(C)]
237    struct LandlockRulesetAttr {
238        handled_access_fs: u64,
239        handled_access_net: u64,
240    }
241
242    #[repr(C, packed)]
243    struct LandlockPathBeneathAttr {
244        allowed_access: u64,
245        parent_fd: i32,
246    }
247
248    let abi = unsafe {
249        libc::syscall(
250            SYS_LANDLOCK_CREATE_RULESET,
251            std::ptr::null::<libc::c_void>(),
252            0usize,
253            LANDLOCK_CREATE_RULESET_VERSION,
254        )
255    };
256    if abi < 1 {
257        let err = std::io::Error::last_os_error();
258        return Ok(SandboxStatus {
259            enabled: false,
260            landlock_abi: None,
261            net_blocked: false,
262            reason: Some(format!("Landlock unavailable on this kernel: {err}")),
263        });
264    }
265    let abi = abi as i32;
266
267    let mut handled_fs = ACCESS_FS_EXECUTE
268        | ACCESS_FS_WRITE_FILE
269        | ACCESS_FS_READ_FILE
270        | ACCESS_FS_READ_DIR
271        | ACCESS_FS_REMOVE_DIR
272        | ACCESS_FS_REMOVE_FILE
273        | ACCESS_FS_MAKE_CHAR
274        | ACCESS_FS_MAKE_DIR
275        | ACCESS_FS_MAKE_REG
276        | ACCESS_FS_MAKE_SOCK
277        | ACCESS_FS_MAKE_FIFO
278        | ACCESS_FS_MAKE_BLOCK
279        | ACCESS_FS_MAKE_SYM;
280    if abi >= 2 {
281        handled_fs |= ACCESS_FS_REFER;
282    }
283    if abi >= 3 {
284        handled_fs |= ACCESS_FS_TRUNCATE;
285    }
286
287    let (handled_net, attr_size) = if abi >= 4 {
288        let net_mask = if allow_outbound_tcp {
289            ACCESS_NET_BIND_TCP
290        } else {
291            ACCESS_NET_BIND_TCP | ACCESS_NET_CONNECT_TCP
292        };
293        (net_mask, std::mem::size_of::<LandlockRulesetAttr>())
294    } else {
295        (0u64, std::mem::size_of::<u64>())
296    };
297
298    let attr = LandlockRulesetAttr {
299        handled_access_fs: handled_fs,
300        handled_access_net: handled_net,
301    };
302
303    let ruleset_fd = unsafe {
304        libc::syscall(
305            SYS_LANDLOCK_CREATE_RULESET,
306            &attr as *const LandlockRulesetAttr,
307            attr_size,
308            0u32,
309        )
310    };
311    if ruleset_fd < 0 {
312        return Err(format!(
313            "landlock_create_ruleset failed: {}",
314            std::io::Error::last_os_error()
315        ));
316    }
317    let ruleset_fd = ruleset_fd as i32;
318
319    let mut ro_rights = ACCESS_FS_READ_FILE | ACCESS_FS_READ_DIR;
320    let mut rw_rights = ro_rights
321        | ACCESS_FS_WRITE_FILE
322        | ACCESS_FS_REMOVE_DIR
323        | ACCESS_FS_REMOVE_FILE
324        | ACCESS_FS_MAKE_DIR
325        | ACCESS_FS_MAKE_REG
326        | ACCESS_FS_MAKE_SYM;
327    if abi >= 2 {
328        rw_rights |= ACCESS_FS_REFER;
329    }
330    if abi >= 3 {
331        rw_rights |= ACCESS_FS_TRUNCATE;
332    }
333    ro_rights &= handled_fs;
334    rw_rights &= handled_fs;
335
336    for grant in paths {
337        let canonical = std::fs::canonicalize(&grant.path).map_err(|e| {
338            unsafe { libc::close(ruleset_fd) };
339            format!("canonicalize mount {}: {e}", grant.path.display())
340        })?;
341        let cpath = CString::new(canonical.as_os_str().as_bytes()).map_err(|e| {
342            unsafe { libc::close(ruleset_fd) };
343            format!("invalid mount path {}: {e}", canonical.display())
344        })?;
345        let fd = unsafe { libc::open(cpath.as_ptr(), libc::O_PATH | libc::O_CLOEXEC) };
346        if fd < 0 {
347            let err = std::io::Error::last_os_error();
348            unsafe { libc::close(ruleset_fd) };
349            return Err(format!("open(O_PATH) {}: {err}", canonical.display()));
350        }
351        let rule = LandlockPathBeneathAttr {
352            allowed_access: if grant.read_only {
353                ro_rights
354            } else {
355                rw_rights
356            },
357            parent_fd: fd,
358        };
359        let ret = unsafe {
360            libc::syscall(
361                SYS_LANDLOCK_ADD_RULE,
362                ruleset_fd,
363                LANDLOCK_RULE_PATH_BENEATH,
364                &rule as *const LandlockPathBeneathAttr,
365                0u32,
366            )
367        };
368        unsafe { libc::close(fd) };
369        if ret < 0 {
370            let err = std::io::Error::last_os_error();
371            unsafe { libc::close(ruleset_fd) };
372            return Err(format!(
373                "landlock_add_rule for {} failed: {err}",
374                canonical.display()
375            ));
376        }
377    }
378
379    if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
380        let err = std::io::Error::last_os_error();
381        unsafe { libc::close(ruleset_fd) };
382        return Err(format!("prctl(PR_SET_NO_NEW_PRIVS) failed: {err}"));
383    }
384
385    let res = unsafe { libc::syscall(SYS_LANDLOCK_RESTRICT_SELF, ruleset_fd, 0u32) };
386    unsafe { libc::close(ruleset_fd) };
387    if res < 0 {
388        return Err(format!(
389            "landlock_restrict_self failed: {}",
390            std::io::Error::last_os_error()
391        ));
392    }
393
394    Ok(SandboxStatus {
395        enabled: true,
396        landlock_abi: Some(abi),
397        net_blocked: abi >= 4 && !allow_outbound_tcp,
398        reason: None,
399    })
400}
401
402#[cfg(not(target_os = "linux"))]
403pub fn apply_landlock(
404    _paths: &[SandboxPathGrant],
405    _allow_outbound_tcp: bool,
406) -> Result<SandboxStatus, String> {
407    Ok(SandboxStatus {
408        enabled: false,
409        landlock_abi: None,
410        net_blocked: false,
411        reason: Some("Landlock is Linux-only".to_string()),
412    })
413}