diff --git a/crates/sandlock-core/src/checkpoint/capture.rs b/crates/sandlock-core/src/checkpoint/capture.rs index 67e4e4180..4ef0383e2 100644 --- a/crates/sandlock-core/src/checkpoint/capture.rs +++ b/crates/sandlock-core/src/checkpoint/capture.rs @@ -200,7 +200,7 @@ pub(crate) fn parse_proc_maps(pid: i32) -> io::Result> { } // --------------------------------------------------------------------------- -// Memory capture -- process_vm_readv (scatter-gather, no file I/O) +// Memory capture // --------------------------------------------------------------------------- /// Largest single region capture will dump. @@ -295,33 +295,15 @@ fn capture_memory(pid: i32, maps: &[MemoryMap]) -> Result, Sa let mut data = vec![0u8; size]; - let local_iov = libc::iovec { - iov_base: data.as_mut_ptr() as *mut libc::c_void, - iov_len: size, - }; - let remote_iov = libc::iovec { - iov_base: map.start as *mut libc::c_void, - iov_len: size, - }; - - let ret = unsafe { - libc::process_vm_readv( - pid as libc::pid_t, - &local_iov as *const libc::iovec, - 1, - &remote_iov as *const libc::iovec, - 1, - 0, - ) - }; - - if ret != size as isize { - let why = if ret < 0 { - io::Error::last_os_error().to_string() - } else { - format!("read {ret} of {size} bytes") - }; - return Err(refuse(format!("reading region {}: {why}", describe(map),))); + match crate::sys::remote_mem::read(pid as libc::pid_t, map.start, &mut data) { + Ok(n) if n == size => {} + Ok(n) => { + return Err(refuse(format!( + "reading region {}: read {n} of {size} bytes", + describe(map), + ))) + } + Err(e) => return Err(refuse(format!("reading region {}: {e}", describe(map)))), } segments.push(MemorySegment { start: map.start, diff --git a/crates/sandlock-core/src/checkpoint/resume.rs b/crates/sandlock-core/src/checkpoint/resume.rs index bac88acbf..5f1e3fb98 100644 --- a/crates/sandlock-core/src/checkpoint/resume.rs +++ b/crates/sandlock-core/src/checkpoint/resume.rs @@ -161,32 +161,20 @@ fn relocate_above(fd: RawFd, floor: RawFd) -> io::Result { /// Write `bytes` into the stopped-at-READY child at `addr`. /// -/// `process_vm_writev` can come up short on a large transfer, and it honours the -/// target VMA's protections, which is why the stub maps every data-carrying -/// region read/write and narrows it only after GO. +/// The write can come up short on a large transfer, and `process_vm_writev` +/// honours the target VMA's protections, which is why the stub maps every +/// data-carrying region read/write and narrows it only after GO. fn write_child_mem(pid: i32, addr: u64, bytes: &[u8]) -> io::Result<()> { let mut done = 0usize; while done < bytes.len() { - let chunk = &bytes[done..]; - let local = libc::iovec { - iov_base: chunk.as_ptr() as *mut libc::c_void, - iov_len: chunk.len(), - }; - let remote = libc::iovec { - iov_base: (addr + done as u64) as *mut libc::c_void, - iov_len: chunk.len(), - }; - let n = unsafe { libc::process_vm_writev(pid, &local, 1, &remote, 1, 0) }; - if n < 0 { - return Err(io::Error::last_os_error()); - } + let n = crate::sys::remote_mem::write(pid, addr + done as u64, &bytes[done..])?; if n == 0 { return Err(io::Error::new( io::ErrorKind::WriteZero, format!("wrote {done} of {} bytes", bytes.len()), )); } - done += n as usize; + done += n; } Ok(()) } diff --git a/crates/sandlock-core/src/seccomp/notif.rs b/crates/sandlock-core/src/seccomp/notif.rs index 59d70cef9..e25db2593 100644 --- a/crates/sandlock-core/src/seccomp/notif.rs +++ b/crates/sandlock-core/src/seccomp/notif.rs @@ -1661,50 +1661,27 @@ fn try_set_sync_wakeup(fd: RawFd) { // Child memory access helpers // ============================================================ -/// Read bytes from a child process via process_vm_readv (single syscall). fn read_child_mem_vm(pid: u32, addr: u64, len: usize) -> Result, NotifError> { let mut buf = vec![0u8; len]; - let local_iov = libc::iovec { - iov_base: buf.as_mut_ptr() as *mut libc::c_void, - iov_len: len, - }; - let remote_iov = libc::iovec { - iov_base: addr as *mut libc::c_void, - iov_len: len, - }; - let ret = unsafe { libc::process_vm_readv(pid as i32, &local_iov, 1, &remote_iov, 1, 0) }; - if ret < 0 { - Err(NotifError::ChildMemoryRead(io::Error::last_os_error())) - } else { - buf.truncate(ret as usize); - Ok(buf) - } + let n = crate::sys::remote_mem::read(pid as i32, addr, &mut buf) + .map_err(NotifError::ChildMemoryRead)?; + buf.truncate(n); + Ok(buf) } -/// Write bytes to a child process via process_vm_writev (single syscall). fn write_child_mem_vm(pid: u32, addr: u64, data: &[u8]) -> Result<(), NotifError> { - let local_iov = libc::iovec { - iov_base: data.as_ptr() as *mut libc::c_void, - iov_len: data.len(), - }; - let remote_iov = libc::iovec { - iov_base: addr as *mut libc::c_void, - iov_len: data.len(), - }; - let ret = unsafe { libc::process_vm_writev(pid as i32, &local_iov, 1, &remote_iov, 1, 0) }; - if ret < 0 { - Err(NotifError::ChildMemoryRead(io::Error::last_os_error())) - } else if (ret as usize) < data.len() { - Err(NotifError::ChildMemoryRead(io::Error::new( + let n = crate::sys::remote_mem::write(pid as i32, addr, data) + .map_err(NotifError::ChildMemoryWrite)?; + if n < data.len() { + return Err(NotifError::ChildMemoryWrite(io::Error::new( io::ErrorKind::WriteZero, - format!("short write: {} of {} bytes", ret, data.len()), - ))) - } else { - Ok(()) + format!("short write: {} of {} bytes", n, data.len()), + ))); } + Ok(()) } -/// Read bytes from a child process via `process_vm_readv` with TOCTOU validation. +/// Read bytes from a child process with TOCTOU validation. /// /// Calls `id_valid` before and after the read to ensure the notification is /// still live (kernel did not abort or release the trapped syscall while the @@ -1770,7 +1747,7 @@ pub fn read_child_cstr( String::from_utf8(result).ok() } -/// Write bytes to a child process via `process_vm_writev` with TOCTOU validation. +/// Write bytes to a child process with TOCTOU validation. /// /// Same TOCTOU contract as [`read_child_mem`]. Public for downstream /// `Handler` implementations that synthesise syscall results into diff --git a/crates/sandlock-core/src/sys/mod.rs b/crates/sandlock-core/src/sys/mod.rs index b1d58057a..02d2727be 100644 --- a/crates/sandlock-core/src/sys/mod.rs +++ b/crates/sandlock-core/src/sys/mod.rs @@ -1,3 +1,4 @@ pub mod fs; +pub(crate) mod remote_mem; pub mod structs; pub mod syscall; diff --git a/crates/sandlock-core/src/sys/remote_mem.rs b/crates/sandlock-core/src/sys/remote_mem.rs new file mode 100644 index 000000000..510a7928c --- /dev/null +++ b/crates/sandlock-core/src/sys/remote_mem.rs @@ -0,0 +1,145 @@ +//! Reads and writes of another process's memory. +//! +//! Kernels built without CONFIG_CROSS_MEMORY_ATTACH have no +//! `process_vm_readv`/`process_vm_writev`, so on those every transfer goes +//! through `/proc//mem` instead. + +use std::fs::OpenOptions; +use std::io; +use std::os::unix::fs::FileExt; +use std::sync::OnceLock; + +/// Read up to `buf.len()` bytes at `addr`, returning how many arrived. +pub(crate) fn read(pid: i32, addr: u64, buf: &mut [u8]) -> io::Result { + if has_process_vm() { + vm_read(pid, addr, buf) + } else { + proc_read(pid, addr, buf) + } +} + +/// Write up to `data.len()` bytes at `addr`, returning how many landed. +/// +/// On a kernel without `process_vm_writev` the write also lands on a +/// read-only page, where the syscall would have failed with `EFAULT`. +pub(crate) fn write(pid: i32, addr: u64, data: &[u8]) -> io::Result { + if has_process_vm() { + vm_write(pid, addr, data) + } else { + proc_write(pid, addr, data) + } +} + +fn has_process_vm() -> bool { + static AVAILABLE: OnceLock = OnceLock::new(); + *AVAILABLE.get_or_init(|| { + let probe = 0u8; + let mut out = [0u8; 1]; + let own_pid = std::process::id() as i32; + match vm_read(own_pid, &probe as *const u8 as u64, &mut out) { + Err(e) => e.raw_os_error() != Some(libc::ENOSYS), + Ok(_) => true, + } + }) +} + +fn vm_read(pid: i32, addr: u64, buf: &mut [u8]) -> io::Result { + let local = libc::iovec { + iov_base: buf.as_mut_ptr() as *mut libc::c_void, + iov_len: buf.len(), + }; + let remote = libc::iovec { + iov_base: addr as *mut libc::c_void, + iov_len: buf.len(), + }; + let n = unsafe { libc::process_vm_readv(pid, &local, 1, &remote, 1, 0) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + Ok(n as usize) +} + +fn vm_write(pid: i32, addr: u64, data: &[u8]) -> io::Result { + let local = libc::iovec { + iov_base: data.as_ptr() as *mut libc::c_void, + iov_len: data.len(), + }; + let remote = libc::iovec { + iov_base: addr as *mut libc::c_void, + iov_len: data.len(), + }; + let n = unsafe { libc::process_vm_writev(pid, &local, 1, &remote, 1, 0) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + Ok(n as usize) +} + +fn proc_read(pid: i32, addr: u64, buf: &mut [u8]) -> io::Result { + let mem = OpenOptions::new() + .read(true) + .open(format!("/proc/{pid}/mem"))?; + mem.read_at(buf, addr).map_err(unmapped_as_efault) +} + +fn proc_write(pid: i32, addr: u64, data: &[u8]) -> io::Result { + let mem = OpenOptions::new() + .write(true) + .open(format!("/proc/{pid}/mem"))?; + mem.write_at(data, addr).map_err(unmapped_as_efault) +} + +/// The mem file reports an unmapped address as `EIO`; callers expect the +/// `EFAULT` that `process_vm_readv`/`process_vm_writev` give for it. +fn unmapped_as_efault(e: io::Error) -> io::Error { + if e.raw_os_error() == Some(libc::EIO) { + io::Error::from_raw_os_error(libc::EFAULT) + } else { + e + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn own_pid() -> i32 { + std::process::id() as i32 + } + + #[test] + fn process_vm_is_detected_on_this_kernel() { + let value = 7u8; + let mut out = [0u8; 1]; + let direct = vm_read(own_pid(), &value as *const u8 as u64, &mut out); + assert_eq!(has_process_vm(), direct.is_ok()); + } + + #[test] + fn proc_read_matches_memory() { + let value: u64 = 0xDEADBEEF_CAFEBABE; + let mut out = [0u8; 8]; + let n = proc_read(own_pid(), &value as *const u64 as u64, &mut out).unwrap(); + assert_eq!(n, 8); + assert_eq!(u64::from_ne_bytes(out), value); + } + + #[test] + fn proc_write_lands_in_memory() { + let mut value: u64 = 0; + let payload = 0x1234567890ABCDEFu64.to_ne_bytes(); + let n = proc_write(own_pid(), &mut value as *mut u64 as u64, &payload).unwrap(); + assert_eq!(n, 8); + assert_eq!( + unsafe { std::ptr::read_volatile(&value) }, + 0x1234567890ABCDEF + ); + } + + #[test] + fn proc_read_of_unmapped_address_is_efault() { + let mut out = [0u8; 8]; + let err = proc_read(own_pid(), 0, &mut out).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EFAULT)); + } +} diff --git a/crates/sandlock-core/tests/no_process_vm.rs b/crates/sandlock-core/tests/no_process_vm.rs new file mode 100644 index 000000000..958915d8d --- /dev/null +++ b/crates/sandlock-core/tests/no_process_vm.rs @@ -0,0 +1,114 @@ +//! The chroot, checkpoint and restore suites again, on a supervisor that has +//! no `process_vm_readv`/`process_vm_writev` and so reaches child memory +//! through `/proc//mem`. + +use sandlock_core::Sandbox; + +#[path = "integration/test_chroot.rs"] +mod test_chroot; + +#[cfg(feature = "checkpoint")] +#[path = "integration/test_checkpoint.rs"] +mod test_checkpoint; + +#[cfg(feature = "checkpoint")] +#[path = "integration/test_restore.rs"] +mod test_restore; + +const LOAD_SYSCALL_NR: u16 = 0x20; +const JUMP_IF_EQUAL: u16 = 0x15; +const RETURN: u16 = 0x06; +const SECCOMP_RET_ALLOW: u32 = 0x7fff_0000; +const SECCOMP_RET_ERRNO: u32 = 0x0005_0000; + +// The supervisor caches its probe of process_vm_readv, and a seccomp filter +// covers only threads created after it, so the filter has to be in place +// before the test harness starts. +#[used] +#[link_section = ".init_array"] +static DENY_PROCESS_VM: unsafe extern "C" fn() = deny_process_vm; + +unsafe extern "C" fn deny_process_vm() { + let insn = |code, jt, jf, k| libc::sock_filter { code, jt, jf, k }; + let mut filter = [ + insn(LOAD_SYSCALL_NR, 0, 0, 0), + insn(JUMP_IF_EQUAL, 1, 0, libc::SYS_process_vm_readv as u32), + insn(JUMP_IF_EQUAL, 0, 1, libc::SYS_process_vm_writev as u32), + insn(RETURN, 0, 0, SECCOMP_RET_ERRNO | libc::ENOSYS as u32), + insn(RETURN, 0, 0, SECCOMP_RET_ALLOW), + ]; + let prog = libc::sock_fprog { + len: filter.len() as libc::c_ushort, + filter: filter.as_mut_ptr(), + }; + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); + libc::prctl( + libc::PR_SET_SECCOMP, + libc::SECCOMP_MODE_FILTER, + &prog as *const libc::sock_fprog, + ); +} + +/// Without this the rest of the file would pass on the ordinary path. +#[test] +fn process_vm_readv_is_enosys_here() { + let value = 0u8; + let mut out = 0u8; + let local = libc::iovec { + iov_base: &mut out as *mut u8 as *mut libc::c_void, + iov_len: 1, + }; + let remote = libc::iovec { + iov_base: &value as *const u8 as *mut libc::c_void, + iov_len: 1, + }; + let n = unsafe { libc::process_vm_readv(libc::getpid(), &local, 1, &remote, 1, 0) }; + assert_eq!(n, -1); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::ENOSYS) + ); +} + +fn host_sandbox() -> Sandbox { + Sandbox::builder() + .fs_read("/usr") + .fs_read("/bin") + .fs_read("/lib") + .fs_read_if_exists("/lib64") + .fs_read("/etc") + .build() + .unwrap() +} + +#[tokio::test] +async fn dynamically_linked_command_starts() { + let result = host_sandbox().run(&["true"]).await.unwrap(); + assert!( + result.success(), + "stderr: {}", + result.stderr_str().unwrap_or("") + ); +} + +#[tokio::test] +async fn paths_are_read_and_stat_results_written() { + let result = host_sandbox() + .run(&["ls", "-l", "/etc/passwd"]) + .await + .unwrap(); + assert!( + result.success(), + "stderr: {}", + result.stderr_str().unwrap_or("") + ); + assert!(result.stdout_str().unwrap_or("").contains("/etc/passwd")); + + let result = host_sandbox().run(&["cat", "/etc/passwd"]).await.unwrap(); + assert!( + result.success(), + "stderr: {}", + result.stderr_str().unwrap_or("") + ); + assert!(result.stdout_str().unwrap_or("").contains("root")); +}