Add --keep-fd to pass chosen inherited descriptors into the sandbox

This commit is contained in:
2026-11-04 18:18:24 +01:00
parent f9ac595d63
commit c7d88d87d9
10 changed files with 141 additions and 25 deletions
+23 -2
View File
@@ -1,10 +1,20 @@
use std::io;
use std::os::fd::RawFd;
use crate::SandboxError;
const FIRST_FD_AFTER_STDIO: libc::c_uint = 3;
pub fn keep_out_of_sandbox() -> Result<(), SandboxError> {
pub fn keep_out_of_sandbox(kept_fds: &[RawFd]) -> Result<(), SandboxError> {
mark_all_after_stdio_cloexec().map_err(SandboxError::InheritedFdsCloexec)?;
for &fd in kept_fds {
clear_cloexec(fd).map_err(|e| SandboxError::KeepFd(fd, e))?;
}
Ok(())
}
fn mark_all_after_stdio_cloexec() -> io::Result<()> {
let result = unsafe {
libc::syscall(
libc::SYS_close_range,
@@ -14,7 +24,18 @@ pub fn keep_out_of_sandbox() -> Result<(), SandboxError> {
)
};
if result < 0 {
return Err(SandboxError::InheritedFdsCloexec(io::Error::last_os_error()));
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn clear_cloexec(fd: RawFd) -> io::Result<()> {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags < 0 {
return Err(io::Error::last_os_error());
}
if unsafe { libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) } < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}