Skip to content

Commit 29dfa1f

Browse files
committed
Add locked secret slice constructor
1 parent 0419cb8 commit 29dfa1f

4 files changed

Lines changed: 99 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
- Added the optional Linux `memory-lock` feature with `LockedSecretBytes<N>` for
2424
fixed-size secrets backed by private `mmap` storage and `mlock`.
2525
- Added `MADV_DONTDUMP` setup for Linux memory-locked secret mappings.
26+
- Added `LockedSecretBytes::from_slice` for direct runtime-buffer loading.
2627
- Added the optional x86_64 `asm-compare` feature for assembly-backed
2728
equal-length byte comparison with portable fallback elsewhere.
2829
- Added the optional x86_64 `cache-flush` feature for explicit volatile-clear

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,8 @@ and locked with `mlock`.
274274
```rust
275275
use sanitization::LockedSecretBytes;
276276

277-
let mut key = LockedSecretBytes::<32>::from_array([7; 32]).unwrap();
277+
let runtime_key = [7_u8; 32];
278+
let mut key = LockedSecretBytes::<32>::from_slice(&runtime_key).unwrap();
278279

279280
assert!(key.constant_time_eq(&[7; 32]));
280281

@@ -290,6 +291,8 @@ assert!(key.constant_time_eq(&[0; 32]));
290291
bytes. It creates a private Linux mapping with `mmap`, marks that mapping with
291292
`MADV_DONTDUMP`, locks it with `mlock`, volatile-clears the full mapping on
292293
drop, then calls `munlock` and `munmap`.
294+
Use `from_slice` when loading bytes from a runtime buffer. `from_array` is still
295+
available for fixed arrays and clears its owned input array before returning.
293296

294297
This feature is explicit because OS memory locking has platform limits. It can
295298
fail due to resource limits or policy. `MADV_DONTDUMP` reduces ordinary Linux

‎examples/high_assurance.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ fn main() {
3030
any(target_arch = "x86_64", target_arch = "aarch64")
3131
))]
3232
{
33-
let mut key = LockedSecretBytes::<32>::from_array([9; 32]).unwrap();
33+
let source = [9_u8; 32];
34+
let mut key = LockedSecretBytes::<32>::from_slice(&source).unwrap();
3435
assert!(key.constant_time_eq(&[9; 32]));
3536
key.secure_clear();
3637
}

‎src/lib.rs‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,46 @@ mod memory_lock {
302302
#[cfg(feature = "std")]
303303
impl std::error::Error for MemoryLockError {}
304304

305+
/// Error returned when constructing [`LockedSecretBytes`] from a slice.
306+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
307+
pub enum LockedSecretBytesError {
308+
/// The caller provided a slice with the wrong length.
309+
Length(crate::LengthError),
310+
/// Linux mapping, core-dump exclusion, locking, unlocking, or unmapping
311+
/// failed.
312+
Memory(MemoryLockError),
313+
}
314+
315+
impl fmt::Display for LockedSecretBytesError {
316+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
317+
match self {
318+
Self::Length(error) => write!(
319+
formatter,
320+
"length mismatch: expected {} bytes, got {} bytes",
321+
error.expected, error.actual
322+
),
323+
Self::Memory(error) => error.fmt(formatter),
324+
}
325+
}
326+
}
327+
328+
#[cfg(feature = "std")]
329+
impl std::error::Error for LockedSecretBytesError {}
330+
331+
impl From<crate::LengthError> for LockedSecretBytesError {
332+
#[inline]
333+
fn from(error: crate::LengthError) -> Self {
334+
Self::Length(error)
335+
}
336+
}
337+
338+
impl From<MemoryLockError> for LockedSecretBytesError {
339+
#[inline]
340+
fn from(error: MemoryLockError) -> Self {
341+
Self::Memory(error)
342+
}
343+
}
344+
305345
/// Fixed-size secret bytes stored in a private locked Linux mapping.
306346
///
307347
/// This type is available with the `memory-lock` feature on Linux
@@ -362,6 +402,29 @@ mod memory_lock {
362402
Ok(secret)
363403
}
364404

405+
/// Allocate locked storage and copy bytes from a same-length slice.
406+
///
407+
/// This is the preferred constructor when the secret is already held in
408+
/// a runtime buffer. It creates the private mapping, applies
409+
/// `MADV_DONTDUMP`, and locks it with `mlock` before copying bytes into
410+
/// the mapping. The source slice is borrowed and cannot be cleared by
411+
/// this function.
412+
#[inline]
413+
pub fn from_slice(source: &[u8]) -> Result<Self, LockedSecretBytesError> {
414+
if source.len() != N {
415+
return Err(crate::LengthError {
416+
expected: N,
417+
actual: source.len(),
418+
}
419+
.into());
420+
}
421+
422+
let mut secret = Self::zeroed()?;
423+
secret.as_mut_slice().copy_from_slice(source);
424+
compiler_fence(Ordering::SeqCst);
425+
Ok(secret)
426+
}
427+
365428
/// Number of secret bytes stored in the locked mapping.
366429
#[must_use]
367430
#[inline]
@@ -669,7 +732,9 @@ mod memory_lock {
669732
target_os = "linux",
670733
any(target_arch = "x86_64", target_arch = "aarch64")
671734
))]
672-
pub use memory_lock::{LockedSecretBytes, MemoryLockError, MemoryLockOperation};
735+
pub use memory_lock::{
736+
LockedSecretBytes, LockedSecretBytesError, MemoryLockError, MemoryLockOperation,
737+
};
673738

674739
#[cfg(all(feature = "asm-compare", target_arch = "x86_64", not(miri)))]
675740
#[allow(unsafe_code)]
@@ -2989,6 +3054,32 @@ mod tests {
29893054
assert_eq!(out, [0, 0, 0, 0]);
29903055
}
29913056

3057+
#[cfg(all(
3058+
feature = "memory-lock",
3059+
target_os = "linux",
3060+
any(target_arch = "x86_64", target_arch = "aarch64"),
3061+
not(miri)
3062+
))]
3063+
#[test]
3064+
fn locked_secret_bytes_can_load_from_slice() {
3065+
let mut secret = LockedSecretBytes::<4>::from_slice(&[1, 2, 3, 4]).unwrap();
3066+
let mut out = [0; 4];
3067+
3068+
assert!(secret.copy_to_slice(&mut out).is_ok());
3069+
assert_eq!(out, [1, 2, 3, 4]);
3070+
assert!(secret.constant_time_eq(&[1, 2, 3, 4]));
3071+
3072+
assert_eq!(
3073+
LockedSecretBytes::<4>::from_slice(&[1, 2]).err(),
3074+
Some(LockedSecretBytesError::Length(LengthError {
3075+
expected: 4,
3076+
actual: 2,
3077+
}))
3078+
);
3079+
3080+
secret.secure_clear();
3081+
}
3082+
29923083
#[cfg(all(
29933084
feature = "memory-lock",
29943085
feature = "cache-flush",

0 commit comments

Comments
 (0)