Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 10 additions & 28 deletions crates/sandlock-core/src/checkpoint/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ pub(crate) fn parse_proc_maps(pid: i32) -> io::Result<Vec<MemoryMap>> {
}

// ---------------------------------------------------------------------------
// Memory capture -- process_vm_readv (scatter-gather, no file I/O)
// Memory capture
// ---------------------------------------------------------------------------

/// Largest single region capture will dump.
Expand Down Expand Up @@ -295,33 +295,15 @@ fn capture_memory(pid: i32, maps: &[MemoryMap]) -> Result<Vec<MemorySegment>, 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,
Expand Down
22 changes: 5 additions & 17 deletions crates/sandlock-core/src/checkpoint/resume.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,32 +161,20 @@ fn relocate_above(fd: RawFd, floor: RawFd) -> io::Result<OwnedFd> {

/// 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(())
}
Expand Down
49 changes: 13 additions & 36 deletions crates/sandlock-core/src/seccomp/notif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>, 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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions crates/sandlock-core/src/sys/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod fs;
pub(crate) mod remote_mem;
pub mod structs;
pub mod syscall;
145 changes: 145 additions & 0 deletions crates/sandlock-core/src/sys/remote_mem.rs
Original file line number Diff line number Diff line change
@@ -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/<pid>/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<usize> {
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<usize> {
if has_process_vm() {
vm_write(pid, addr, data)
} else {
proc_write(pid, addr, data)
}
}

fn has_process_vm() -> bool {
static AVAILABLE: OnceLock<bool> = 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<usize> {
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<usize> {
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<usize> {
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<usize> {
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));
}
}
Loading
Loading