From a49cf7cbb3ceadf1755bb97f2315f5044c305a02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC=20=D0=9F=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=20=5BArtyom=20Pavlov=5D?= Date: Wed, 6 Aug 2025 17:44:59 +0300 Subject: [PATCH 1/2] zeroize: add `proxy_alloc_test` --- zeroize/tests/alloc.rs | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 zeroize/tests/alloc.rs diff --git a/zeroize/tests/alloc.rs b/zeroize/tests/alloc.rs new file mode 100644 index 00000000..d771c7d6 --- /dev/null +++ b/zeroize/tests/alloc.rs @@ -0,0 +1,48 @@ +use std::alloc::{GlobalAlloc, Layout, System}; + +use zeroize::Zeroize; + +// Allocator that ensures that deallocated data is zeroized. +struct ProxyAllocator; + +unsafe impl GlobalAlloc for ProxyAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + unsafe { System.alloc(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + if layout.size() == 160 { + for i in 0..layout.size() { + let b = unsafe { core::ptr::read(ptr.add(i)) }; + if b != 0 { + panic!() + } + } + } + + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static PROXY_ALLOCATOR: ProxyAllocator = ProxyAllocator; + +struct SecretBox(Box); + +impl SecretBox { + fn new(val: S) -> Self { + Self(Box::new(val)) + } +} + +impl Drop for SecretBox { + fn drop(&mut self) { + self.0.as_mut().zeroize() + } +} + +#[test] +fn proxy_alloc_test() { + let _b1 = SecretBox::new([u128::MAX; 10]); + let _b2 = SecretBox::new([u8::MAX; 160]); +} From 1f6a3012e46c4225917db27a40f827f6446c58c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC=20=D0=9F=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=20=5BArtyom=20Pavlov=5D?= Date: Wed, 6 Aug 2025 17:53:38 +0300 Subject: [PATCH 2/2] use `hint::black_box` --- zeroize/tests/alloc.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zeroize/tests/alloc.rs b/zeroize/tests/alloc.rs index d771c7d6..677a914a 100644 --- a/zeroize/tests/alloc.rs +++ b/zeroize/tests/alloc.rs @@ -43,6 +43,8 @@ impl Drop for SecretBox { #[test] fn proxy_alloc_test() { - let _b1 = SecretBox::new([u128::MAX; 10]); - let _b2 = SecretBox::new([u8::MAX; 160]); + let b1 = SecretBox::new([u128::MAX; 10]); + core::hint::black_box(&b1); + let b2 = SecretBox::new([u8::MAX; 160]); + core::hint::black_box(&b2); }