unkernel-rs 0.6.0

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Defense-in-depth host sandboxing (Linux Landlock ABI v1-v4 + PR_SET_NO_NEW_PRIVS)
//! and cross-platform host process telemetry (`getrusage` peak RSS, `getrandom` entropy).

use std::path::PathBuf;

/// Host path allowed through Landlock when sandboxing is enabled.
#[derive(Debug, Clone)]
pub struct SandboxPathGrant {
    pub path: PathBuf,
    pub read_only: bool,
}

/// Summary of the OS sandbox enforcement status.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxStatus {
    pub enabled: bool,
    pub landlock_abi: Option<i32>,
    pub net_blocked: bool,
    pub reason: Option<String>,
}

/// Read peak resident set size (MiB) accurately:
/// - On Linux, reads `VmHWM:` from `/proc/self/status` (using a pre-opened fd cached before
///   Landlock when available), which is immune to the Linux `fork->exec` `ru_maxrss` parent
///   inheritance quirk.
/// - Falls back to `getrusage(RUSAGE_SELF)` on non-Linux targets or if `/proc` is unavailable.
pub fn peak_rss_mib() -> f64 {
    #[cfg(target_os = "linux")]
    {
        if let Some(mib) = read_proc_vm_hwm_mib() {
            return mib;
        }
    }
    #[cfg(unix)]
    unsafe {
        let mut ru: libc::rusage = std::mem::zeroed();
        if libc::getrusage(libc::RUSAGE_SELF, &mut ru) == 0 {
            #[cfg(target_os = "macos")]
            {
                return ru.ru_maxrss as f64 / (1024.0 * 1024.0);
            }
            #[cfg(not(target_os = "macos"))]
            {
                return ru.ru_maxrss as f64 / 1024.0;
            }
        }
    }
    #[cfg(windows)]
    {
        #[repr(C)]
        #[allow(dead_code)]
        struct ProcessMemoryCounters {
            cb: u32,
            page_fault_count: u32,
            peak_working_set_size: usize,
            working_set_size: usize,
            quota_peak_paged_pool_usage: usize,
            quota_paged_pool_usage: usize,
            quota_peak_non_paged_pool_usage: usize,
            quota_non_paged_pool_usage: usize,
            pagefile_usage: usize,
            peak_pagefile_usage: usize,
        }
        #[link(name = "kernel32")]
        unsafe extern "system" {
            fn GetCurrentProcess() -> *mut core::ffi::c_void;
            fn K32GetProcessMemoryInfo(
                process: *mut core::ffi::c_void,
                ppsmem_counters: *mut ProcessMemoryCounters,
                cb: u32,
            ) -> i32;
        }
        let mut pmc: ProcessMemoryCounters = unsafe { std::mem::zeroed() };
        pmc.cb = std::mem::size_of::<ProcessMemoryCounters>() as u32;
        let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) };
        if ok != 0 {
            return pmc.peak_working_set_size as f64 / (1024.0 * 1024.0);
        }
    }
    0.0
}

#[cfg(target_os = "linux")]
static PROC_STATUS_FD: std::sync::OnceLock<Option<std::fs::File>> = std::sync::OnceLock::new();

/// Pre-open `/proc/self/status` before applying Landlock so `peak_rss_mib()` can continue reading
/// `VmHWM:` without opening any paths afterward.
pub fn init_rss_handle() {
    #[cfg(target_os = "linux")]
    {
        let _ = PROC_STATUS_FD.get_or_init(|| std::fs::File::open("/proc/self/status").ok());
    }
}

#[cfg(target_os = "linux")]
fn read_proc_vm_hwm_mib() -> Option<f64> {
    use std::os::unix::fs::FileExt;
    let mut buf = [0u8; 4096];
    let n = if let Some(Some(file)) = PROC_STATUS_FD.get() {
        file.read_at(&mut buf, 0).ok()?
    } else if let Ok(file) = std::fs::File::open("/proc/self/status") {
        file.read_at(&mut buf, 0).ok()?
    } else {
        return None;
    };
    let text = std::str::from_utf8(&buf[..n]).ok()?;
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("VmHWM:")
            && let Some(kb_str) = rest.split_whitespace().next()
            && let Ok(kb) = kb_str.parse::<f64>()
        {
            return Some(kb / 1024.0);
        }
    }
    None
}

/// Fill `dst` with cryptographic entropy via syscall (`getrandom` on Linux) so no `/dev/urandom`
/// filesystem access is required after Landlock is applied.
pub fn fill_random(dst: &mut [u8]) {
    #[cfg(target_os = "linux")]
    {
        let mut offset = 0usize;
        while offset < dst.len() {
            let ret = unsafe {
                libc::syscall(
                    libc::SYS_getrandom,
                    dst.as_mut_ptr().add(offset),
                    dst.len() - offset,
                    0u32,
                )
            };
            if ret > 0 {
                offset += ret as usize;
            } else if ret == -1 {
                let err = std::io::Error::last_os_error();
                if err.kind() == std::io::ErrorKind::Interrupted {
                    continue;
                }
                break;
            } else {
                break;
            }
        }
        if offset == dst.len() {
            return;
        }
    }

    #[cfg(windows)]
    {
        #[link(name = "bcrypt")]
        unsafe extern "system" {
            fn BCryptGenRandom(
                h_algorithm: *mut core::ffi::c_void,
                pb_buffer: *mut u8,
                cb_buffer: u32,
                dw_flags: u32,
            ) -> i32;
        }
        const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x0000_0002;
        let mut offset = 0usize;
        while offset < dst.len() {
            let chunk = (dst.len() - offset).min(u32::MAX as usize) as u32;
            let status = unsafe {
                BCryptGenRandom(
                    std::ptr::null_mut(),
                    dst.as_mut_ptr().add(offset),
                    chunk,
                    BCRYPT_USE_SYSTEM_PREFERRED_RNG,
                )
            };
            if status == 0 {
                offset += chunk as usize;
            } else {
                break;
            }
        }
    }

    // Fallback for non-Linux Unix targets (e.g. macOS)
    #[cfg(unix)]
    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
        use std::io::Read;
        let _ = f.read_exact(dst);
    }
}

/// Apply Linux Landlock + `PR_SET_NO_NEW_PRIVS` to the current thread and all threads it
/// subsequently spawns.
///
/// Must be called **after** loading `.cwasm` and opening the `.erofs` image descriptor,
/// and **before** spawning VM kernel threads.
///
/// Once applied:
/// - No host filesystem path can be opened except the explicitly granted `paths` (e.g. 9p mounts).
/// - On Landlock ABI v4+ (Linux >= 6.7), host TCP bind is always blocked; host TCP connect is also
///   blocked unless `allow_outbound_tcp == true` (for opt-in `--net`).
#[cfg(target_os = "linux")]
pub fn apply_landlock(
    paths: &[SandboxPathGrant],
    allow_outbound_tcp: bool,
) -> Result<SandboxStatus, String> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    // Landlock syscall numbers are architecture-independent on modern Linux (444/445/446)
    const SYS_LANDLOCK_CREATE_RULESET: libc::c_long = 444;
    const SYS_LANDLOCK_ADD_RULE: libc::c_long = 445;
    const SYS_LANDLOCK_RESTRICT_SELF: libc::c_long = 446;

    const LANDLOCK_CREATE_RULESET_VERSION: u32 = 1 << 0;
    const LANDLOCK_RULE_PATH_BENEATH: u32 = 1;

    // Filesystem access rights (ABI v1..v3)
    const ACCESS_FS_EXECUTE: u64 = 1 << 0;
    const ACCESS_FS_WRITE_FILE: u64 = 1 << 1;
    const ACCESS_FS_READ_FILE: u64 = 1 << 2;
    const ACCESS_FS_READ_DIR: u64 = 1 << 3;
    const ACCESS_FS_REMOVE_DIR: u64 = 1 << 4;
    const ACCESS_FS_REMOVE_FILE: u64 = 1 << 5;
    const ACCESS_FS_MAKE_CHAR: u64 = 1 << 6;
    const ACCESS_FS_MAKE_DIR: u64 = 1 << 7;
    const ACCESS_FS_MAKE_REG: u64 = 1 << 8;
    const ACCESS_FS_MAKE_SOCK: u64 = 1 << 9;
    const ACCESS_FS_MAKE_FIFO: u64 = 1 << 10;
    const ACCESS_FS_MAKE_BLOCK: u64 = 1 << 11;
    const ACCESS_FS_MAKE_SYM: u64 = 1 << 12;
    const ACCESS_FS_REFER: u64 = 1 << 13; // ABI v2+
    const ACCESS_FS_TRUNCATE: u64 = 1 << 14; // ABI v3+

    // Network access rights (ABI v4+)
    const ACCESS_NET_BIND_TCP: u64 = 1 << 0;
    const ACCESS_NET_CONNECT_TCP: u64 = 1 << 1;

    #[repr(C)]
    struct LandlockRulesetAttr {
        handled_access_fs: u64,
        handled_access_net: u64,
    }

    #[repr(C, packed)]
    struct LandlockPathBeneathAttr {
        allowed_access: u64,
        parent_fd: i32,
    }

    let abi = unsafe {
        libc::syscall(
            SYS_LANDLOCK_CREATE_RULESET,
            std::ptr::null::<libc::c_void>(),
            0usize,
            LANDLOCK_CREATE_RULESET_VERSION,
        )
    };
    if abi < 1 {
        let err = std::io::Error::last_os_error();
        return Ok(SandboxStatus {
            enabled: false,
            landlock_abi: None,
            net_blocked: false,
            reason: Some(format!("Landlock unavailable on this kernel: {err}")),
        });
    }
    let abi = abi as i32;

    let mut handled_fs = ACCESS_FS_EXECUTE
        | ACCESS_FS_WRITE_FILE
        | ACCESS_FS_READ_FILE
        | ACCESS_FS_READ_DIR
        | ACCESS_FS_REMOVE_DIR
        | ACCESS_FS_REMOVE_FILE
        | ACCESS_FS_MAKE_CHAR
        | ACCESS_FS_MAKE_DIR
        | ACCESS_FS_MAKE_REG
        | ACCESS_FS_MAKE_SOCK
        | ACCESS_FS_MAKE_FIFO
        | ACCESS_FS_MAKE_BLOCK
        | ACCESS_FS_MAKE_SYM;
    if abi >= 2 {
        handled_fs |= ACCESS_FS_REFER;
    }
    if abi >= 3 {
        handled_fs |= ACCESS_FS_TRUNCATE;
    }

    let (handled_net, attr_size) = if abi >= 4 {
        let net_mask = if allow_outbound_tcp {
            ACCESS_NET_BIND_TCP
        } else {
            ACCESS_NET_BIND_TCP | ACCESS_NET_CONNECT_TCP
        };
        (net_mask, std::mem::size_of::<LandlockRulesetAttr>())
    } else {
        (0u64, std::mem::size_of::<u64>())
    };

    let attr = LandlockRulesetAttr {
        handled_access_fs: handled_fs,
        handled_access_net: handled_net,
    };

    let ruleset_fd = unsafe {
        libc::syscall(
            SYS_LANDLOCK_CREATE_RULESET,
            &attr as *const LandlockRulesetAttr,
            attr_size,
            0u32,
        )
    };
    if ruleset_fd < 0 {
        return Err(format!(
            "landlock_create_ruleset failed: {}",
            std::io::Error::last_os_error()
        ));
    }
    let ruleset_fd = ruleset_fd as i32;

    let mut ro_rights = ACCESS_FS_READ_FILE | ACCESS_FS_READ_DIR;
    let mut rw_rights = ro_rights
        | ACCESS_FS_WRITE_FILE
        | ACCESS_FS_REMOVE_DIR
        | ACCESS_FS_REMOVE_FILE
        | ACCESS_FS_MAKE_DIR
        | ACCESS_FS_MAKE_REG
        | ACCESS_FS_MAKE_SYM;
    if abi >= 2 {
        rw_rights |= ACCESS_FS_REFER;
    }
    if abi >= 3 {
        rw_rights |= ACCESS_FS_TRUNCATE;
    }
    ro_rights &= handled_fs;
    rw_rights &= handled_fs;

    for grant in paths {
        let canonical = std::fs::canonicalize(&grant.path).map_err(|e| {
            unsafe { libc::close(ruleset_fd) };
            format!("canonicalize mount {}: {e}", grant.path.display())
        })?;
        let cpath = CString::new(canonical.as_os_str().as_bytes()).map_err(|e| {
            unsafe { libc::close(ruleset_fd) };
            format!("invalid mount path {}: {e}", canonical.display())
        })?;
        let fd = unsafe { libc::open(cpath.as_ptr(), libc::O_PATH | libc::O_CLOEXEC) };
        if fd < 0 {
            let err = std::io::Error::last_os_error();
            unsafe { libc::close(ruleset_fd) };
            return Err(format!("open(O_PATH) {}: {err}", canonical.display()));
        }
        let rule = LandlockPathBeneathAttr {
            allowed_access: if grant.read_only {
                ro_rights
            } else {
                rw_rights
            },
            parent_fd: fd,
        };
        let ret = unsafe {
            libc::syscall(
                SYS_LANDLOCK_ADD_RULE,
                ruleset_fd,
                LANDLOCK_RULE_PATH_BENEATH,
                &rule as *const LandlockPathBeneathAttr,
                0u32,
            )
        };
        unsafe { libc::close(fd) };
        if ret < 0 {
            let err = std::io::Error::last_os_error();
            unsafe { libc::close(ruleset_fd) };
            return Err(format!(
                "landlock_add_rule for {} failed: {err}",
                canonical.display()
            ));
        }
    }

    if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
        let err = std::io::Error::last_os_error();
        unsafe { libc::close(ruleset_fd) };
        return Err(format!("prctl(PR_SET_NO_NEW_PRIVS) failed: {err}"));
    }

    let res = unsafe { libc::syscall(SYS_LANDLOCK_RESTRICT_SELF, ruleset_fd, 0u32) };
    unsafe { libc::close(ruleset_fd) };
    if res < 0 {
        return Err(format!(
            "landlock_restrict_self failed: {}",
            std::io::Error::last_os_error()
        ));
    }

    Ok(SandboxStatus {
        enabled: true,
        landlock_abi: Some(abi),
        net_blocked: abi >= 4 && !allow_outbound_tcp,
        reason: None,
    })
}

#[cfg(not(target_os = "linux"))]
pub fn apply_landlock(
    _paths: &[SandboxPathGrant],
    _allow_outbound_tcp: bool,
) -> Result<SandboxStatus, String> {
    Ok(SandboxStatus {
        enabled: false,
        landlock_abi: None,
        net_blocked: false,
        reason: Some("Landlock is Linux-only".to_string()),
    })
}