Skip to content
Open
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
19 changes: 16 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,12 @@ impl<S: Zeroize> Drop for SecretBox<S> {

#[cfg(windows)]
unsafe {
if windows_sys::Win32::System::Memory::VirtualUnlock(secret_ptr.cast(), len) == 0 {
panic!("VirtualUnlock failed",);
}
// VirtualLock does not maintain a lock count for overlapping pages.
// Heap allocations commonly share pages, so dropping one SecretBox
// can unlock a page that still contains another SecretBox. A later
// VirtualUnlock then reports ERROR_NOT_LOCKED. Drop must still
// zeroize the secret and must never panic while unwinding.
let _ = windows_sys::Win32::System::Memory::VirtualUnlock(secret_ptr.cast(), len);
}

self.zeroize()
Expand Down Expand Up @@ -363,6 +366,16 @@ mod tests {
assert!(TestSecret::default().check_zero());
}

#[cfg(windows)]
#[test]
fn dropping_multiple_secrets_does_not_panic() {
let secrets = (0..64)
.map(|index| SecretString::new(Box::new(format!("secret-{index}"))))
.collect::<Vec<_>>();

drop(secrets);
}

#[test]
fn test_secret_box_expose_secret_mut() {
let secret = Box::new(String::from("Encrypted"));
Expand Down