| 1 |
//! Memory protection utilities using `memfd_secret`. |
| 2 |
//! |
| 3 |
//! This module provides the [`Vault`] struct, which uses the Linux-specific |
| 4 |
//! `memfd_secret` system call to create a memory region that is invisible to |
| 5 |
//! the kernel's page tables and most other processes, providing a secure |
| 6 |
//! location for sensitive cryptographic material. |
| 7 |
|
| 8 |
use crate::crypto::secret_box::SecretBox; |
| 9 |
use memmap2::MmapMut; |
| 10 |
use std::fs::File; |
| 11 |
use std::io::{Error as IoError, Result as IoResult}; |
| 12 |
use std::os::unix::io::{FromRawFd, RawFd}; |
| 13 |
use zeroize::Zeroize; |
| 14 |
|
| 15 |
/// The system call number for `memfd_secret` on x86_64. |
| 16 |
#[cfg(target_arch = "x86_64")] |
| 17 |
const SYS_MEMFD_SECRET: i64 = 447; |
| 18 |
|
| 19 |
/// A secure container for sensitive data backed by `memfd_secret`. |
| 20 |
/// |
| 21 |
/// `Vault` uses a secret memory file descriptor that is not visible in the |
| 22 |
/// filesystem and whose memory is unmapped from the kernel page tables. |
| 23 |
/// The memory is automatically zeroed when the `Vault` is dropped. |
| 24 |
#[derive(Debug)] |
| 25 |
pub struct Vault { |
| 26 |
mmap: MmapMut, |
| 27 |
#[cfg(test)] |
| 28 |
file: File, |
| 29 |
} |
| 30 |
|
| 31 |
#[cfg(test)] |
| 32 |
impl std::os::unix::io::AsRawFd for Vault { |
| 33 |
fn as_raw_fd(&self) -> RawFd { |
| 34 |
std::os::unix::io::AsRawFd::as_raw_fd(&self.file) |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
impl Drop for Vault { |
| 39 |
fn drop(&mut self) { |
| 40 |
self.mmap[..].zeroize(); |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
impl Vault { |
| 45 |
/// Creates a new `Vault` containing the provided data. |
| 46 |
/// |
| 47 |
/// The provided `data` is copied into the vault. The source `SecretBox` is |
| 48 |
/// dropped at the end, ensuring the original sensitive data is zeroized |
| 49 |
/// from memory. |
| 50 |
/// |
| 51 |
/// # Errors |
| 52 |
/// |
| 53 |
/// Returns an error if the `memfd_secret` syscall fails or if the memory |
| 54 |
/// cannot be mapped. |
| 55 |
pub fn new(data: SecretBox) -> IoResult<Self> { |
| 56 |
// Create the secret memory file descriptor. |
| 57 |
// O_CLOEXEC ensures the FD is closed on exec. |
| 58 |
let fd = unsafe { libc::syscall(SYS_MEMFD_SECRET, libc::O_CLOEXEC as libc::c_long) }; |
| 59 |
|
| 60 |
if fd < 0 { |
| 61 |
return Err(IoError::last_os_error()); |
| 62 |
} |
| 63 |
let fd = fd as RawFd; |
| 64 |
|
| 65 |
// Wrap the raw FD in a File object to manage its lifetime. |
| 66 |
let file = unsafe { File::from_raw_fd(fd) }; |
| 67 |
|
| 68 |
// Set the size of the secret memory region. |
| 69 |
file.set_len(data.as_slice().len() as u64)?; |
| 70 |
|
| 71 |
// Map the secret memory region into the process's address space. |
| 72 |
let mut mmap = unsafe { MmapMut::map_mut(&file)? }; |
| 73 |
|
| 74 |
// Copy the sensitive data into the secure region. |
| 75 |
mmap.copy_from_slice(data.as_slice()); |
| 76 |
|
| 77 |
Ok(Vault { |
| 78 |
mmap, |
| 79 |
#[cfg(test)] |
| 80 |
file, |
| 81 |
}) |
| 82 |
} |
| 83 |
|
| 84 |
/// Returns a new SecretBox containing a copy of the secret key material. |
| 85 |
pub fn get_secret(&self) -> SecretBox { |
| 86 |
SecretBox::new(self.mmap.to_vec()) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
#[cfg(test)] |
| 91 |
mod tests { |
| 92 |
use super::*; |
| 93 |
use std::os::unix::io::AsRawFd; |
| 94 |
|
| 95 |
#[test] |
| 96 |
fn test_vault_creation_and_retrieval() { |
| 97 |
let data = *b"sensitive information"; |
| 98 |
let original_data = data; |
| 99 |
let secret = SecretBox::new(data.to_vec()); |
| 100 |
let vault = Vault::new(secret).expect("Failed to create vault"); |
| 101 |
assert_eq!(vault.get_secret().as_slice(), &original_data); |
| 102 |
} |
| 103 |
|
| 104 |
#[test] |
| 105 |
fn test_vault_with_empty_data() { |
| 106 |
let secret = SecretBox::new(vec![]); |
| 107 |
let vault = Vault::new(secret).expect("Failed to create empty vault"); |
| 108 |
assert!(vault.get_secret().as_slice().is_empty()); |
| 109 |
} |
| 110 |
|
| 111 |
#[test] |
| 112 |
fn test_multiple_vaults() { |
| 113 |
let s1 = *b"secret1"; |
| 114 |
let v1 = Vault::new(SecretBox::new(s1.to_vec())).unwrap(); |
| 115 |
let s2 = *b"secret2"; |
| 116 |
let v2 = Vault::new(SecretBox::new(s2.to_vec())).unwrap(); |
| 117 |
assert_ne!(v1.get_secret().as_slice(), v2.get_secret().as_slice()); |
| 118 |
assert_eq!(v1.get_secret().as_slice(), b"secret1"); |
| 119 |
assert_eq!(v2.get_secret().as_slice(), b"secret2"); |
| 120 |
} |
| 121 |
|
| 122 |
#[test] |
| 123 |
fn test_large_vault() { |
| 124 |
let data = vec![0u8; 1024 * 1024]; // 1MB |
| 125 |
let len = data.len(); |
| 126 |
let vault = Vault::new(SecretBox::new(data)).expect("Failed to create large vault"); |
| 127 |
assert_eq!(vault.get_secret().as_slice().len(), len); |
| 128 |
} |
| 129 |
|
| 130 |
#[test] |
| 131 |
fn test_memfd_backing_verification() { |
| 132 |
let data = *b"verification data"; |
| 133 |
let vault = Vault::new(SecretBox::new(data.to_vec())).unwrap(); |
| 134 |
let fd = vault.as_raw_fd(); |
| 135 |
|
| 136 |
// 1. Verify filesystem magic number using fstatfs |
| 137 |
let mut statfs: libc::statfs = unsafe { std::mem::zeroed() }; |
| 138 |
let ret = unsafe { libc::fstatfs(fd, &mut statfs) }; |
| 139 |
assert_eq!(ret, 0, "fstatfs failed"); |
| 140 |
|
| 141 |
// SECRETMEM_MAGIC is 0x5345434d ("SECM") |
| 142 |
const SECRETMEM_MAGIC: libc::c_long = 0x5345434d; |
| 143 |
assert_eq!( |
| 144 |
statfs.f_type, SECRETMEM_MAGIC, |
| 145 |
"Filesystem is not memfd_secret. Expected magic {:x}, got {:x}", |
| 146 |
SECRETMEM_MAGIC, statfs.f_type |
| 147 |
); |
| 148 |
|
| 149 |
// 2. Verify mapping in /proc/self/maps |
| 150 |
let ptr = vault.mmap.as_ptr() as usize; |
| 151 |
let mut stat: libc::stat = unsafe { std::mem::zeroed() }; |
| 152 |
let ret = unsafe { libc::fstat(fd, &mut stat) }; |
| 153 |
assert_eq!(ret, 0, "fstat failed"); |
| 154 |
let expected_inode = stat.st_ino; |
| 155 |
|
| 156 |
let maps = |
| 157 |
std::fs::read_to_string("/proc/self/maps").expect("Failed to read /proc/self/maps"); |
| 158 |
let found = maps.lines().any(|line| { |
| 159 |
let parts: Vec<&str> = line.split_whitespace().collect(); |
| 160 |
if parts.len() < 6 { |
| 161 |
return false; |
| 162 |
} |
| 163 |
|
| 164 |
let range: Vec<&str> = parts[0].split('-').collect(); |
| 165 |
let start = usize::from_str_radix(range[0], 16).unwrap(); |
| 166 |
let end = usize::from_str_radix(range[1], 16).unwrap(); |
| 167 |
|
| 168 |
if ptr >= start && ptr < end { |
| 169 |
let inode = parts[4].parse::<u64>().unwrap_or(0); |
| 170 |
return inode == expected_inode && line.contains("/secretmem"); |
| 171 |
} |
| 172 |
false |
| 173 |
}); |
| 174 |
|
| 175 |
assert!( |
| 176 |
found, |
| 177 |
"Could not verify memfd_secret mapping in /proc/self/maps" |
| 178 |
); |
| 179 |
} |
| 180 |
|
| 181 |
#[test] |
| 182 |
fn test_zeroize_on_drop() { |
| 183 |
let data = *b"secret to be zeroed"; |
| 184 |
let original_data = data; |
| 185 |
let vault = Vault::new(SecretBox::new(data.to_vec())).unwrap(); |
| 186 |
|
| 187 |
// Create a second mapping of the same memory to spy on it |
| 188 |
// This is possible because we have access to the underlying File in tests |
| 189 |
let spy = unsafe { MmapMut::map_mut(&vault.file).expect("Failed to create spy mapping") }; |
| 190 |
|
| 191 |
// Verify spy sees the data |
| 192 |
assert_eq!(&spy[..], &original_data); |
| 193 |
|
| 194 |
// Drop the vault, which should trigger zeroize |
| 195 |
drop(vault); |
| 196 |
|
| 197 |
// Verify the memory was zeroed |
| 198 |
assert!( |
| 199 |
spy.iter().all(|&b| b == 0), |
| 200 |
"Memory was not zeroed after drop" |
| 201 |
); |
| 202 |
} |
| 203 |
} |