Skip to content

Test zeroization when going out of scope #1310

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
23 changes: 13 additions & 10 deletions secrecy/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
[package]
name = "secrecy"
name = "secrecy"
description = """
Wrapper types and traits for secret management which help ensure
they aren't accidentally copied, logged, or otherwise exposed
(as much as possible), and also ensure secrets are securely wiped
from memory when dropped.
"""
version = "0.10.3"
authors = ["Tony Arcieri <[email protected]>"]
license = "Apache-2.0 OR MIT"
homepage = "https://github.com/iqlusioninc/crates/"
repository = "https://github.com/iqlusioninc/crates/tree/main/secrecy"
readme = "README.md"
categories = ["cryptography", "memory-management", "no-std", "os"]
keywords = ["clear", "memory", "secret", "secure", "wipe"]
edition = "2021"
version = "0.10.3"
authors = ["Tony Arcieri <[email protected]>"]
license = "Apache-2.0 OR MIT"
homepage = "https://github.com/iqlusioninc/crates/"
repository = "https://github.com/iqlusioninc/crates/tree/main/secrecy"
readme = "README.md"
categories = ["cryptography", "memory-management", "no-std", "os"]
keywords = ["clear", "memory", "secret", "secure", "wipe"]
edition = "2021"
rust-version = "1.60"

[dependencies]
Expand All @@ -23,6 +23,9 @@ zeroize = { version = "1.6", default-features = false, features = ["alloc"] }
# optional dependencies
serde = { version = "1", optional = true, default-features = false, features = ["alloc"] }

[features]
test-allocator = []

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
60 changes: 58 additions & 2 deletions secrecy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
//! types of `SecretBox<T>` to be serializable with `serde`, you will need to impl
//! the [`SerializableSecret`] marker trait on `T`.

#![no_std]
#![cfg_attr(not(feature = "test-allocator"), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![forbid(unsafe_code)]
#![deny(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms, unused_qualifications)]

extern crate alloc;
Expand Down Expand Up @@ -345,4 +345,60 @@ mod tests {
let secret = SecretString::from_str("test").unwrap();
assert_eq!(secret.expose_secret(), "test");
}

#[cfg(feature = "test-allocator")]
mod secret_with_custom_allocator {

use super::super::*;
use core::mem::size_of;
use core::ptr;

use std::alloc::{GlobalAlloc, Layout, System};
// Allocator that leaks all memory it allocates, thus leaving the memory open for inspection.
struct UnfreeAllocator;
#[allow(unsafe_code)]
unsafe impl GlobalAlloc for UnfreeAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
System.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
let _ = (ptr, layout);
}
}

#[global_allocator]
static UNFREE_ALLOCATOR: UnfreeAllocator = UnfreeAllocator;

#[test]
#[allow(unsafe_code, unused_assignments)]
fn clears_memory_when_scope_ends() {
let mut ptr: *const u128 = ptr::null();
unsafe {
{
let secret = SecretBox::init_with(|| 0xdeadbeef_u128);
let secretboxptr = &secret as *const SecretBox<u128>;
// Points to the inner_secret of the `SecretBox`
let boxptr = secretboxptr as *const *const u128;
// Pointer to actual heap data
ptr = *boxptr;

assert!(!ptr.is_null(), "ptr is null before drop, not ok");
let bytes: &[u8] =
core::slice::from_raw_parts(ptr as *const u8, size_of::<u128>());
assert!(
!bytes.iter().all(|&b| b == 0),
"Expected non-zero data, instead found 0s: {:X?}",
bytes
);
}
// Check that the memory is cleared after the scope ends
let bytes: &[u8] = core::slice::from_raw_parts(ptr as *const u8, size_of::<u128>());
assert!(
bytes.iter().all(|&b| b == 0),
Comment on lines +395 to +397
Copy link
Member

@tony-iqlusion tony-iqlusion Apr 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is UB since you're making a Rust reference that's UAF.

You could avoid UB by performing only raw pointer operations, i.e. computing new pointers and dereferencing them, which would be fairly trivial to do here.

"Expected zeroized memory, instead found: {:X?}",
bytes
);
}
}
}
}
Loading