pub fn enter_sandbox() -> anyhow::Result<()> {
#[cfg(target_os = "freebsd")]
{
enter_capsicum()?;
}
#[cfg(target_os = "linux")]
{
apply_linux_hardening()?;
}
#[cfg(not(any(target_os = "freebsd", target_os = "linux")))]
{
tracing::warn!("No sandbox available for this platform");
}
Ok(())
}
#[cfg(target_os = "freebsd")]
fn enter_capsicum() -> anyhow::Result<()> {
let ret = unsafe { libc::cap_enter() };
if ret != 0 {
let err = std::io::Error::last_os_error();
anyhow::bail!("Failed to enter Capsicum capability mode: {}", err);
}
tracing::info!("Entered Capsicum capability mode");
Ok(())
}
#[cfg(target_os = "linux")]
fn apply_linux_hardening() -> anyhow::Result<()> {
use nix::sys::prctl;
prctl::set_no_new_privs()
.map_err(|e| anyhow::anyhow!("Failed to set PR_SET_NO_NEW_PRIVS: {}", e))?;
if let Err(e) = prctl::set_dumpable(false) {
tracing::warn!("Failed to set PR_SET_DUMPABLE=0: {}", e);
}
tracing::info!("Linux security: NO_NEW_PRIVS + non-dumpable enabled");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sandbox_does_not_panic() {
let _ = enter_sandbox();
}
}