Skip to main content

oa/crypto/
secure_buffer.rs

1//! Borrowed host storage with best-effort page locking and mandatory erasure.
2
3use crate::core::memory::zero_secure;
4
5/// A non-owning mutable byte range that is securely erased when reset or
6/// dropped.
7///
8/// Linux page locking is best effort and observable through [`Self::is_locked`].
9/// The borrow guarantees that the backing range remains alive for this guard.
10pub struct SecureBuffer<'a> {
11	bytes: Option<&'a mut [u8]>,
12	locked: bool,
13}
14
15impl<'a> SecureBuffer<'a> {
16	/// Guard a mutable byte range and attempt to keep it out of swap.
17	#[must_use]
18	pub fn new(bytes: &'a mut [u8]) -> Self {
19		#[cfg(target_os = "linux")]
20		let locked = if bytes.is_empty() {
21			false
22		} else {
23			// SAFETY: the mutable borrow proves that the range is live and uniquely
24			// accessible for the complete lifetime of this guard.
25			unsafe { libc::mlock(bytes.as_ptr().cast(), bytes.len()) == 0 }
26		};
27		#[cfg(not(target_os = "linux"))]
28		let locked = false;
29
30		Self {
31			bytes: Some(bytes),
32			locked,
33		}
34	}
35
36	/// Return the guarded bytes.
37	#[must_use]
38	pub fn as_slice(&self) -> &[u8] {
39		self.bytes.as_deref().unwrap_or_default()
40	}
41
42	/// Return the guarded bytes mutably.
43	#[must_use]
44	pub fn as_mut_slice(&mut self) -> &mut [u8] {
45		self.bytes.as_deref_mut().unwrap_or_default()
46	}
47
48	/// Return the guarded range size in bytes.
49	#[must_use]
50	pub fn size_bytes(&self) -> usize {
51		self.bytes.as_deref().map_or(0, <[u8]>::len)
52	}
53
54	/// Return whether this guard currently owns a non-empty range.
55	#[must_use]
56	pub fn is_valid(&self) -> bool {
57		self.size_bytes() != 0
58	}
59
60	/// Return whether the operating system accepted the page-lock request.
61	#[must_use]
62	pub const fn is_locked(&self) -> bool {
63		self.locked
64	}
65
66	/// Erase the guarded range without releasing it.
67	pub fn secure_zero(&mut self) {
68		if let Some(bytes) = self.bytes.as_deref_mut() {
69			zero_secure(bytes);
70		}
71	}
72
73	/// Erase and release the guarded range.
74	pub fn reset(&mut self) {
75		self.secure_zero();
76		if let Some(bytes) = self.bytes.take() {
77			#[cfg(target_os = "linux")]
78			if self.locked {
79				// SAFETY: `bytes` is the exact live range passed to the successful
80				// `mlock` call and remains borrowed until after this call.
81				unsafe {
82					libc::munlock(bytes.as_ptr().cast(), bytes.len());
83				}
84			}
85		}
86		self.locked = false;
87	}
88}
89
90impl Drop for SecureBuffer<'_> {
91	fn drop(&mut self) {
92		self.reset();
93	}
94}
95
96impl std::fmt::Debug for SecureBuffer<'_> {
97	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98		formatter
99			.debug_struct("SecureBuffer")
100			.field("size_bytes", &self.size_bytes())
101			.field("locked", &self.locked)
102			.finish_non_exhaustive()
103	}
104}