use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct SandboxPathGrant {
pub path: PathBuf,
pub read_only: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxStatus {
pub enabled: bool,
pub landlock_abi: Option<i32>,
pub net_blocked: bool,
pub reason: Option<String>,
}
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();
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
}
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;
}
}
}
#[cfg(unix)]
if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
use std::io::Read;
let _ = f.read_exact(dst);
}
}
#[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;
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;
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; const ACCESS_FS_TRUNCATE: u64 = 1 << 14;
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()),
})
}