diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b34aac1b..6a1c303c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,7 @@ on: 'inout-v*', 'sponge-cursor-v*', 'zeroize-v*', + 'zeroize_allocator-v*', 'zeroize_derive-v*', 'zlint-v*' ] diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 1cf8e0de..c12875c1 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -24,7 +24,7 @@ jobs: - uses: RustCrypto/actions/cargo-cache@master - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.92.0 # Pinned to prevent breakages + toolchain: 1.100.0 # Pinned to prevent breakages components: clippy - run: cargo clippy --workspace --all-features --lib --bins --tests -- -Dwarnings diff --git a/.github/workflows/zeroize_allocator.yml b/.github/workflows/zeroize_allocator.yml new file mode 100644 index 00000000..3db169cf --- /dev/null +++ b/.github/workflows/zeroize_allocator.yml @@ -0,0 +1,204 @@ +name: zeroize_allocator + +on: + pull_request: + paths: + - ".github/workflows/zeroize_allocator.yml" + - "zeroize_allocator/**" + - "Cargo.*" + push: + branches: master + workflow_dispatch: + +permissions: + contents: read + +defaults: + run: + working-directory: zeroize_allocator + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +# Cancels CI jobs when new commits are pushed to a PR branch +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + test: + strategy: + matrix: + include: + # 32-bit Linux + - target: i686-unknown-linux-gnu + platform: ubuntu-latest + rust: 1.100.0 # MSRV + deps: sudo apt update && sudo apt install gcc-multilib + - target: i686-unknown-linux-gnu + platform: ubuntu-latest + rust: stable + deps: sudo apt update && sudo apt install gcc-multilib + + # 64-bit Linux + - target: x86_64-unknown-linux-gnu + platform: ubuntu-latest + rust: 1.100.0 # MSRV + - target: x86_64-unknown-linux-gnu + platform: ubuntu-latest + rust: stable + + # 64-bit Windows + - target: x86_64-pc-windows-msvc + platform: windows-latest + rust: 1.100.0 # MSRV + - target: x86_64-pc-windows-msvc + platform: windows-latest + rust: stable + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v7 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: ${{ matrix.deps }} + - run: cargo test --target ${{ matrix.target }} + + # Test using `cargo careful` + test-careful: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@nightly + - run: cargo install cargo-careful + - run: cargo careful test --all-features + + # Cross-compiled tests + test-cross: + strategy: + matrix: + include: + # AArch64 + - target: aarch64-unknown-linux-gnu + rust: 1.100.0 + - target: aarch64-unknown-linux-gnu + rust: stable + + # PPC32 + - target: powerpc-unknown-linux-gnu + rust: 1.100.0 # MSRV + - target: powerpc-unknown-linux-gnu + rust: stable + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - uses: RustCrypto/actions/cross-install@master + - run: cross test --target ${{ matrix.target }} + - run: cross test --target ${{ matrix.target }} --all-features + + # Custom derive tests + test-derive: + runs-on: ubuntu-latest + defaults: + run: + working-directory: zeroize_derive + strategy: + matrix: + rust: + - 1.100.0 # MSRV + - stable + steps: + - uses: actions/checkout@v7 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + - run: cargo test + - run: cargo test --release + + # Test using `cargo miri` + test-miri: + runs-on: ubuntu-latest + env: + MIRIFLAGS: "-Zmiri-symbolic-alignment-check -Zmiri-strict-provenance" + strategy: + matrix: + target: + - x86_64-unknown-linux-gnu + - s390x-unknown-linux-gnu + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly-2026-08-23 + - run: rustup component add miri + - run: cargo miri test --target ${{ matrix.target }} --all-features + + # Tests for x86-64 `simd` support + test-x86-simd: + strategy: + matrix: + include: + - target: x86_64-unknown-linux-gnu + rust: 1.100.0 + - target: x86_64-unknown-linux-gnu + rust: stable + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - uses: RustCrypto/actions/cross-install@master + - run: cargo test --target ${{ matrix.target }} --features simd + - run: cargo test --target ${{ matrix.target }} --all-features + + # Test WASM using `wasmtime` + test-wasm: + runs-on: ubuntu-latest + env: + CARGO_TARGET_WASM32_WASIP1_RUNNER: "wasmtime" + steps: + - uses: actions/checkout@v7 + - uses: bytecodealliance/actions/wasmtime/setup@v1 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + targets: wasm32-wasip1 + - run: cargo test --target wasm32-wasip1 --all-features + - run: cargo test --target wasm32-wasip1 --all-features --release + + minimal-versions: + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} + + no_std: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.100.0 # MSRV + - stable + target: + - armv7a-none-eabi + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v7 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --target ${{ matrix.target }} diff --git a/Cargo.lock b/Cargo.lock index 2030b801..28bcde73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -956,6 +956,13 @@ dependencies = [ "zeroize_derive", ] +[[package]] +name = "zeroize_allocator" +version = "0.1.0" +dependencies = [ + "zeroize 1.9.1", +] + [[package]] name = "zeroize_derive" version = "1.5.0" diff --git a/Cargo.toml b/Cargo.toml index ccfd52f3..646b4b1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "sponge-cursor", "wycheproof2blb", "zeroize", + "zeroize_allocator", "zeroize_derive", "zlint" ] diff --git a/zeroize_allocator/Cargo.toml b/zeroize_allocator/Cargo.toml new file mode 100644 index 00000000..9d59885c --- /dev/null +++ b/zeroize_allocator/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "zeroize_allocator" +version = "0.1.0" +authors = ["The RustCrypto Project Developers"] +edition = "2024" +rust-version = "1.100" +documentation = "https://docs.rs/zeroize_allocator" +repository = "https://github.com/RustCrypto/utils" +license = "Apache-2.0 OR MIT" +keywords = ["memory", "memset", "secure", "volatile", "zero"] +categories = ["cryptography", "memory-management", "no-std", "os"] +description = """ +A wrapping allocator that uses zeroization functions to zeroize memory upon deallocation. +""" + +[dependencies] +zeroize = "1.9" + +[lints] +workspace = true diff --git a/zeroize_allocator/src/lib.rs b/zeroize_allocator/src/lib.rs new file mode 100644 index 00000000..60cdd0b2 --- /dev/null +++ b/zeroize_allocator/src/lib.rs @@ -0,0 +1,78 @@ +#![no_std] +//! This crate provides a `ZeroizingAllocator` that zeroizes memory on deallocation. +//! +//! ``` +//! use zeroize_allocator::ZeroizingAllocator; +//! +//! use std::alloc::System; +//! +//! let alloc_helper = ZeroizingAllocator::new(System); +//! let mut vec_example = Vec::new_in(&alloc_helper); +//! vec_example.extend([2, 3, 5, 7, 11, 13, 17, 19]); +//! ``` + +use zeroize::Zeroize; + +use core::{ + alloc::{AllocError, Allocator, Layout}, + mem::MaybeUninit, + ptr::NonNull, + slice, +}; + +/// An allocator that zeroizes memory before freeing it. +/// The soundness of this allocator depends on adjustments of the Allocator trait +/// safety contract: see for details. +#[repr(transparent)] +#[derive(Debug)] +pub struct ZeroizingAllocator { + inner: A, +} +impl ZeroizingAllocator { + /// Constructs a [`ZeroizingAllocator`] around a pre-existing allocator. + pub fn new(allocator: A) -> Self { + Self { inner: allocator } + } +} + +/* + * SAFETY: Most of the safety invariants are expected to be upheld by the underlying allocator. + * For the rest, see the safety comments inside this impl. + */ +unsafe impl Allocator for ZeroizingAllocator { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.inner.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // Use scoping to ensure that the slice is dead when we call the underlying allocator. + { + /* + * SAFETY: + * - The memory is being deallocated -> we are not bound to avoid touching it + * - The memory is being deallocated -> no references to it still exist + * - ptr is valid and not null. + * - MaybeUninit has the same size, alignment, and ABI as u8. + * - The layout gives us the size of the memory allocation, so the zeroize only + * writes to memory belonging to this allocation. + * Thus, we can create a &mut [MaybeUninit] and zeroize it without causing UB. + * + * We need to use MaybeUninit instead of u8 to handle uninitialized padding bytes. + */ + let allocated_slice: &mut [MaybeUninit] = + unsafe { slice::from_raw_parts_mut(ptr.as_ptr().cast(), layout.size()) }; + // This is a necessary safety comment and needs to be updated as such. + #[allow(clippy::unnecessary_safety_comment)] + /* + * SAFETY: the only panic inside [Z]::zeroize() is an assert that the slice length is + * smaller than isize::MAX, which is a precondition of constructing a Layout value. + * (The checked_mul(size_of::) is a multiplication by 1, so it cannot fail.) + * Therefore, this zeroize call cannot panic. + */ + allocated_slice.zeroize(); + } + // Now do the actual deallocation + // SAFETY: we assume inner's deallocate is sound + unsafe { self.inner.deallocate(ptr, layout) } + } +} diff --git a/zeroize_allocator/tests/check_zeroize.rs b/zeroize_allocator/tests/check_zeroize.rs new file mode 100644 index 00000000..18600392 --- /dev/null +++ b/zeroize_allocator/tests/check_zeroize.rs @@ -0,0 +1,184 @@ +//! Tests for uses of `ZeroizeAllocator`. + +use core::{ + alloc::{AllocError, Allocator, Layout}, + mem::MaybeUninit, + ptr::NonNull, + slice, + sync::atomic::{AtomicBool, Ordering}, +}; +use std::{alloc::System, sync::Mutex}; + +use zeroize_allocator::ZeroizingAllocator; + +/// An Allocator that delays deallocation until it is dropped. +#[derive(Debug)] +struct DelayedDeallocator { + allocator: A, + // Use the System allocator for the Vec to avoid recursions. + dealloc_queue: Mutex, Layout), System>>, +} +impl DelayedDeallocator { + pub fn new(allocator: A) -> Self { + Self { + allocator, + dealloc_queue: Mutex::new(Vec::new_in(System)), + } + } +} +impl Drop for DelayedDeallocator { + fn drop(&mut self) { + /* + * Clear the poison so that the unwrap always succeeds, and free what we've collected. + * Panics elsewhere would not have corrupted any existing items, so at most we leak some + * memory, which is allowed. + */ + self.dealloc_queue.clear_poison(); + let queue_inner = self.dealloc_queue.get_mut().expect("poison wasn't cleared"); + for (ptr, layout) in queue_inner.iter() { + /* + * SAFETY: values on the vec were pushed on by our deallocate, and we expect those + * callers to have satisfied the deallocate preconditions. + */ + unsafe { + self.allocator.deallocate(*ptr, *layout); + } + } + } +} +// SAFETY: see comments in the Drop impl +unsafe impl Allocator for DelayedDeallocator { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.allocator.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // Clear the poison so that the unwrap always succeeds + self.dealloc_queue.clear_poison(); + // This would only panic upon getting close to isize::MAX, which we don't hit in our tests + // TODO: actually prevent unwinding by catching unwinds and aborting if necessary + self.dealloc_queue.lock().expect("poison wasn't cleared").push((ptr, layout)); + } +} + +/// An allocator that tracks whether a non-zeroed byte is present at deallocation time. +#[derive(Debug)] +struct VerifyZeroizedAllocator { + inner: ZeroizingAllocator>, + has_dealloced: AtomicBool, + non_zero_in_dealloc: AtomicBool, +} + +impl VerifyZeroizedAllocator { + pub fn new(allocator: A) -> Self { + Self { + inner: ZeroizingAllocator::new(DelayedDeallocator::new(allocator)), + has_dealloced: AtomicBool::new(false), + non_zero_in_dealloc: AtomicBool::new(false), + } + } + pub fn has_dealloced(&self) -> bool { + // Load from flag synchronizes-with the deallocate method + self.has_dealloced.load(Ordering::Acquire) + } + pub fn non_zero_dealloced(&self) -> bool { + // Load from flag synchronizes-with the deallocate method + self.non_zero_in_dealloc.load(Ordering::Acquire) + } +} + +// SAFETY: see comments within each method +unsafe impl Allocator for VerifyZeroizedAllocator { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + let allocated_ptr = self.inner.allocate(layout)?; + /* + * SAFETY: + * - The memory has just been allocated -> we hold the only reference to it. + * - ptr is valid and not null. + * - MaybeUninit has the same size, alignment, and ABI as u8. + * - The layout gives us the size of the memory allocation, so we only write + * to memory belonging to this allocation. + * Thus, we can create a &mut [MaybeUninit] and write to it without causing UB. + * + * To make our deallocate bytescans sound, we need to initialize all the bytes now, because + * we cannot assume that the code we hand this allocation to will initialize the bytes. + */ + let allocated_slice: &mut [MaybeUninit] = + unsafe { slice::from_raw_parts_mut(allocated_ptr.as_ptr().cast(), layout.size()) }; + allocated_slice.fill(MaybeUninit::new(0x67)); + Ok(allocated_ptr) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: we assume the nested Allocator's deallocate is sound + unsafe { self.inner.deallocate(ptr, layout) }; + /* + * Inspecting the memory after self.inner.deallocate is only safe because DelayedDeallocator + * means that the memory hasn't actually been freed yet. + */ + { + /* + * SAFETY: + * - The memory is being deallocated -> we are not bound to avoid touching it + * - The memory is being deallocated -> no references to it still exist + * - ptr is valid and not null. + * - The layout gives us the size of the memory allocation, so the zeroize only + * writes to memory belonging to this allocation. + * Thus, we can create a &mut [u8] and zeroize it without causing UB. + * + * We don't need MaybeUninit because we initialized all the bytes when we allocated. + */ + let allocated_slice: &[u8] = + unsafe { slice::from_raw_parts(ptr.as_ptr(), layout.size()) }; + for byte in allocated_slice { + if *byte != 0 { + // Store to flag synchronizes-with the non_zero_dealloced method + self.non_zero_in_dealloc.store(true, Ordering::Release); + } + } + } + // Store to flag synchronizes-with the has_dealloced method + self.has_dealloced.store(true, Ordering::Release); + } +} + +#[test] +fn zeroized_alloc_box() { + let alloc_helper = VerifyZeroizedAllocator::new(System); + let mut box_example = Box::new_in( + *b"But you'll look sweet upon the seat\nOf a bicycle built for two!", + &alloc_helper, + ); + box_example = core::hint::black_box(box_example); + drop(box_example); + // Assert that a deallocation actually occurred... + assert!(alloc_helper.has_dealloced()); + // ...and that the deallocation did not leave non-zero bytes hanging. + assert!(!alloc_helper.non_zero_dealloced()); +} + +#[test] +fn zeroized_alloc_box_pads() { + // (u16, u8) has a padding byte-verify that we handle it correctly + let alloc_helper = VerifyZeroizedAllocator::new(System); + let mut box_example = Box::new_in([(16u16, 8u8), (1u16, 0u8)], &alloc_helper); + box_example = core::hint::black_box(box_example); + drop(box_example); + // Assert that a deallocation actually occurred... + assert!(alloc_helper.has_dealloced()); + // ...and that the deallocation did not leave non-zero bytes hanging. + assert!(!alloc_helper.non_zero_dealloced()); +} + +#[test] +fn zeroized_alloc_vec() { + let alloc_helper = VerifyZeroizedAllocator::new(System); + let mut vec_example = Vec::new_in(&alloc_helper); + vec_example.extend([2, 3, 5, 7, 11, 13, 17, 19]); + vec_example = core::hint::black_box(vec_example); + drop(vec_example); + // Assert that a deallocation actually occurred... + assert!(alloc_helper.has_dealloced()); + // ...and that the deallocation did not leave non-zero bytes hanging. + assert!(!alloc_helper.non_zero_dealloced()); +}