Skip to main content

ati/security/
memory.rs

1//! Secure memory helpers: mlock, madvise, zeroize.
2//!
3//! These prevent secrets from being swapped to disk or included in core dumps.
4//! All functions are best-effort on non-Linux platforms.
5
6/// Lock a memory region to prevent it from being swapped to disk.
7/// Returns Ok(()) on success, Err with a warning message on failure.
8#[cfg(target_os = "linux")]
9pub fn mlock(ptr: *const u8, len: usize) -> Result<(), String> {
10    let ret = unsafe { libc::mlock(ptr as *const libc::c_void, len) };
11    if ret == 0 {
12        Ok(())
13    } else {
14        Err(format!(
15            "mlock failed (errno {}): secrets may be swappable",
16            std::io::Error::last_os_error()
17        ))
18    }
19}
20
21#[cfg(not(target_os = "linux"))]
22pub fn mlock(_ptr: *const u8, _len: usize) -> Result<(), String> {
23    // mlock is not critical on non-Linux; warn and continue
24    Ok(())
25}
26
27/// Advise the kernel to exclude this memory from core dumps.
28#[cfg(target_os = "linux")]
29pub fn madvise_dontdump(ptr: *const u8, len: usize) -> Result<(), String> {
30    let ret = unsafe { libc::madvise(ptr as *mut libc::c_void, len, libc::MADV_DONTDUMP) };
31    if ret == 0 {
32        Ok(())
33    } else {
34        Err("madvise(DONTDUMP) failed: secrets may appear in core dumps".to_string())
35    }
36}
37
38#[cfg(not(target_os = "linux"))]
39pub fn madvise_dontdump(_ptr: *const u8, _len: usize) -> Result<(), String> {
40    Ok(())
41}
42
43/// Unlock a previously locked memory region.
44#[cfg(target_os = "linux")]
45pub fn munlock(ptr: *const u8, len: usize) {
46    unsafe {
47        libc::munlock(ptr as *const libc::c_void, len);
48    }
49}
50
51#[cfg(not(target_os = "linux"))]
52pub fn munlock(_ptr: *const u8, _len: usize) {}