zeroize/lib.rs
1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![doc = include_str!("../README.md")]
4#![doc(
5 html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
6 html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
7)]
8#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
9
10//! ## Usage
11//!
12//! To securely zero a byte slice, use [`zeroize_bytes`]. It uses an optimized fill followed by an
13//! assembly optimization barrier on supported targets, and portable bulk volatile writes
14//! elsewhere.
15//!
16//! ### Traits
17//!
18//! The [`Zeroize`] trait is the core API of this crate. It's intended to be impl'd on values that
19//! may-or-may-not contain secrets, for example the `zeroize` crate itself defines them on the
20//! core integers e.g. `u8`, `u16`, `i8`, `i16`, as well as arrays thereof. Its core API is
21//! [`Zeroize::zeroize`], a method which takes `&mut self` and writes over the type's internal
22//! memory with some placeholder value, typically some form of `0`.
23//!
24//! The [`DefaultIsZeroes`] marker trait can be impl'd on types which have a [`Default`] impl that
25//! can be used for [`Zeroize`]. Types which implement this trait receive a blanket impl of the
26//! [`Zeroize`] trait.
27//!
28//! We recommend that types which always contain secrets, and especially ones which need to maintain
29//! complex invariants, do NOT impl the [`Zeroize`] trait, but instead provide a [`Drop`] impl which
30//! takes care of erasing the secret values from memory directly. Such types can mark that they're
31//! doing this with the [`ZeroizeOnDrop`] marker trait. Note that [`ZeroizeOnDrop`] is *just* a
32//! marker trait, and making it actually work requires actually providing a [`Drop`] impl which
33//! takes care of zeroizing secrets.
34//!
35//! Why not impl [`Zeroize`] for such types, e.g. a `SecretKey` type? The problem is [`Zeroize`]
36//! would effectively leave such types in an invalid state, and a sort of use-after-zeroize
37//! condition becomes possible. For that reason, we recommend these types automatically handle
38//! zeroization in their [`Drop`] handler alone.
39//!
40//! ### Supported types
41//!
42//! The [`Zeroize`] trait is impl'd on all of Rust's core scalar types including
43//! integers, floats, `bool`, and `char`.
44//!
45//! Additionally, it's implemented on slices and `IterMut`s of the above types.
46//!
47//! When the `alloc` feature is enabled (which it is by default), it's also
48//! impl'd for `Vec<T>` for the above types as well as `String`, where it provides
49//! [`Vec::clear`] / [`String::clear`]-like behavior (truncating to zero-length)
50//! but ensures the backing memory is securely zeroed with some caveats.
51//!
52//! With the `std` feature enabled (which it is **not** by default), [`Zeroize`]
53//! is also implemented for [`CString`]. After calling `zeroize()` on a `CString`,
54//! its internal buffer will contain exactly one nul byte. The backing
55//! memory is zeroed by converting it to a `Vec<u8>` and back into a `CString`.
56//! (NOTE: see "Stack/Heap Zeroing Notes" for important `Vec`/`String`/`CString` details)
57//!
58//! [`CString`]: https://doc.rust-lang.org/std/ffi/struct.CString.html
59//!
60//! The [`DefaultIsZeroes`] marker trait can be impl'd on types which also
61//! impl [`Default`], which implements [`Zeroize`] by overwriting a value with
62//! the default value.
63//!
64//! ### Custom Derive Support
65//!
66//! This crate has custom derive support for the `Zeroize` trait,
67//! gated under the `zeroize` crate's `zeroize_derive` Cargo feature,
68//! which automatically calls `zeroize()` on all members of a struct
69//! or tuple struct.
70//!
71//! Attributes supported for `Zeroize`:
72//!
73//! On the item level:
74//! - `#[zeroize(drop)]`: *deprecated* use `ZeroizeOnDrop` instead
75//! - `#[zeroize(bound = "T: MyTrait")]`: this replaces any trait bounds
76//! inferred by zeroize
77//!
78//! On the field level:
79//! - `#[zeroize(skip)]`: skips this field or variant when calling `zeroize()`
80//!
81//! Attributes supported for `ZeroizeOnDrop`:
82//!
83//! On the field level:
84//! - `#[zeroize(skip)]`: skips this field or variant when calling `zeroize()`
85//!
86//! Example which derives `Drop`:
87//!
88//! ```
89//! # #[cfg(feature = "zeroize_derive")]
90//! # {
91//! use zeroize::{Zeroize, ZeroizeOnDrop};
92//!
93//! // This struct will be zeroized on drop
94//! #[derive(Zeroize, ZeroizeOnDrop)]
95//! struct MyStruct([u8; 32]);
96//! # }
97//! ```
98//!
99//! Example which does not derive `Drop` (useful for e.g. `Copy` types)
100//!
101//! ```
102//! #[cfg(feature = "zeroize_derive")]
103//! # {
104//! use zeroize::Zeroize;
105//!
106//! // This struct will *NOT* be zeroized on drop
107//! #[derive(Copy, Clone, Zeroize)]
108//! struct MyStruct([u8; 32]);
109//! # }
110//! ```
111//!
112//! Example which only derives `Drop`:
113//!
114//! ```
115//! # #[cfg(feature = "zeroize_derive")]
116//! # {
117//! use zeroize::ZeroizeOnDrop;
118//!
119//! // This struct will be zeroized on drop
120//! #[derive(ZeroizeOnDrop)]
121//! struct MyStruct([u8; 32]);
122//! # }
123//! ```
124//!
125//! ### `Zeroizing<Z>`: wrapper for zeroizing arbitrary values on drop
126//!
127//! `Zeroizing<Z: Zeroize>` is a generic wrapper type that impls `Deref`
128//! and `DerefMut`, allowing access to an inner value of type `Z`, and also
129//! impls a `Drop` handler which calls `zeroize()` on its contents:
130//!
131//! ```
132//! use zeroize::Zeroizing;
133//!
134//! fn use_secret() {
135//! let mut secret = Zeroizing::new([0u8; 5]);
136//!
137//! // Set the air shield password
138//! // Protip (again): don't embed secrets in your source code.
139//! secret.copy_from_slice(&[1, 2, 3, 4, 5]);
140//! assert_eq!(secret.as_ref(), &[1, 2, 3, 4, 5]);
141//!
142//! // The contents of `secret` will be automatically zeroized on drop
143//! }
144//!
145//! # use_secret()
146//! ```
147//!
148//! ## What guarantees does this crate provide?
149//!
150//! The zeroing implementations in this crate prevent the compiler from eliminating writes
151//! using volatile operations or, on supported targets, assembly optimization barriers.
152//! The barriers allow optimized bulk fills, with volatile writes as a portable fallback.
153//!
154//! Previously there were worries that the approach used by this crate (mixing volatile and
155//! non-volatile accesses) was undefined behavior due to language contained
156//! in the documentation for `write_volatile`, however after some discussion
157//! within the [Unsafe Code Guidelines Working Group], [these remarks have been removed] and the
158//! specific usage pattern in this crate is considered to be well-defined.
159//!
160//! All of that said, there is still potential for microarchitectural attacks
161//! (ala Spectre/Meltdown) to leak "zeroized" secrets through covert channels.
162//! This crate makes no guarantees that zeroized values cannot be leaked
163//! through such channels, as they represent flaws in the underlying hardware.
164//!
165//! ## Stack/Heap Zeroing Notes
166//!
167//! This crate can be used to zero values from either the stack or the heap. We recommend storing
168//! sensitive data on the heap whenever possible to reduce the potential for making copies in memory
169//! via Rust move semantics, however note that stack spilling and other optimizations may leave
170//! temporary copies of data from the heap on the stack.
171//!
172//! [`zeroize_stack`] can be used to zeroize stack memory.
173//!
174//! [`Pin`][`core::pin::Pin`] can be leveraged in conjunction with this crate to ensure data kept
175//! on the stack isn't moved.
176//!
177//! The `Zeroize` impls for `Vec`, `String` and `CString` zeroize the entire capacity of their
178//! backing buffer, but cannot guarantee copies of the data were not previously made by buffer
179//! reallocation. It's therefore important when attempting to zeroize such buffers to initialize
180//! them to the correct capacity, and take care to prevent subsequent reallocation.
181//!
182//! The [`secrecy`] crate provides higher-level abstractions for eliminating
183//! usage patterns which can cause reallocations:
184//!
185//! [`secrecy`]: https://docs.rs/secrecy
186//!
187//! ## What about: clearing registers, `mlock()`, `mprotect()`, etc?
188//!
189//! This crate is focused on providing simple, unobtrusive support for reliably
190//! zeroing memory using the best approach possible on stable Rust.
191//!
192//! Clearing registers is a difficult problem that can't easily be solved by
193//! something like a crate, and requires either inline ASM or rustc support.
194//! See <https://github.com/rust-lang/rust/issues/17046> for background on
195//! this particular problem.
196//!
197//! Other memory protection mechanisms are interesting and useful, but often
198//! overkill (e.g. defending against RAM scraping or attackers with swap access).
199//! In as much as there may be merit to these approaches, there are also many
200//! other crates that already implement more sophisticated memory protections.
201//! Such protections are explicitly out-of-scope for this crate.
202//!
203//! Zeroing memory is [good cryptographic hygiene] and this crate seeks to promote
204//! it in the most unobtrusive manner possible. This includes omitting complex
205//! `unsafe` memory protection systems and just trying to make the best memory
206//! zeroing crate available.
207//!
208//! [Unsafe Code Guidelines Working Group]: https://github.com/rust-lang/unsafe-code-guidelines
209//! [these remarks have been removed]: https://github.com/rust-lang/rust/pull/60972
210//! [good cryptographic hygiene]: https://github.com/veorq/cryptocoding#clean-memory-of-secret-data
211//! [`Ordering::SeqCst`]: core::sync::atomic::Ordering::SeqCst
212
213#[cfg(feature = "alloc")]
214extern crate alloc;
215#[cfg(feature = "std")]
216extern crate std;
217
218#[cfg(feature = "zeroize_derive")]
219pub use zeroize_derive::{Zeroize, ZeroizeOnDrop};
220
221#[cfg(target_arch = "aarch64")]
222mod aarch64;
223#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
224mod x86;
225
226mod barrier;
227pub use barrier::optimization_barrier;
228
229mod bulk;
230use bulk::zeroize_byte_ptr;
231
232mod stack;
233pub use stack::zeroize_stack;
234
235use core::{
236 marker::{PhantomData, PhantomPinned},
237 mem::{MaybeUninit, size_of, size_of_val},
238 num::{
239 self, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
240 NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
241 },
242 ops, ptr,
243 slice::IterMut,
244};
245
246#[cfg(feature = "alloc")]
247use alloc::{boxed::Box, string::String, vec::Vec};
248
249#[cfg(feature = "std")]
250use std::ffi::CString;
251
252/// Trait for securely erasing values from memory.
253pub trait Zeroize {
254 /// Zero out this object from memory using Rust intrinsics which ensure the
255 /// zeroization operation is not "optimized away" by the compiler.
256 fn zeroize(&mut self);
257}
258
259/// Marker trait signifying that this type will [`Zeroize::zeroize`] itself on [`Drop`].
260pub trait ZeroizeOnDrop {}
261
262/// Marker trait for types whose [`Default`] is the desired zeroization result
263pub trait DefaultIsZeroes: Copy + Default + Sized {}
264
265/// Fallible trait for representing cases where zeroization may or may not be
266/// possible.
267///
268/// This is primarily useful for scenarios like reference counted data, where
269/// zeroization is only possible when the last reference is dropped.
270pub trait TryZeroize {
271 /// Try to zero out this object from memory using Rust intrinsics which
272 /// ensure the zeroization operation is not "optimized away" by the
273 /// compiler.
274 #[must_use]
275 fn try_zeroize(&mut self) -> bool;
276}
277
278impl<Z> Zeroize for Z
279where
280 Z: DefaultIsZeroes,
281{
282 fn zeroize(&mut self) {
283 volatile_write(self, Z::default());
284 }
285}
286
287macro_rules! impl_zeroize_with_default {
288 ($($type:ty),+) => {
289 $(impl DefaultIsZeroes for $type {})+
290 };
291}
292
293#[rustfmt::skip]
294impl_zeroize_with_default! {
295 PhantomPinned, (), bool, char,
296 f32, f64,
297 i8, i16, i32, i64, i128, isize,
298 u8, u16, u32, u64, u128, usize
299}
300
301/// `PhantomPinned` is zero sized so provide a `ZeroizeOnDrop` implementation.
302impl ZeroizeOnDrop for PhantomPinned {}
303
304/// `()` is zero sized so provide a `ZeroizeOnDrop` implementation.
305impl ZeroizeOnDrop for () {}
306
307macro_rules! impl_zeroize_for_non_zero {
308 ($($type:ty),+) => {
309 $(
310 impl Zeroize for $type {
311 fn zeroize(&mut self) {
312 const ONE: $type = match <$type>::new(1) {
313 Some(one) => one,
314 None => unreachable!(),
315 };
316 volatile_write(self, ONE);
317 }
318 }
319 )+
320 };
321}
322
323impl_zeroize_for_non_zero!(
324 NonZeroI8,
325 NonZeroI16,
326 NonZeroI32,
327 NonZeroI64,
328 NonZeroI128,
329 NonZeroIsize,
330 NonZeroU8,
331 NonZeroU16,
332 NonZeroU32,
333 NonZeroU64,
334 NonZeroU128,
335 NonZeroUsize
336);
337
338impl<Z> Zeroize for num::Wrapping<Z>
339where
340 Z: Zeroize,
341{
342 fn zeroize(&mut self) {
343 self.0.zeroize();
344 }
345}
346
347/// Impl [`Zeroize`] on arrays of types that impl [`Zeroize`].
348impl<Z, const N: usize> Zeroize for [Z; N]
349where
350 Z: Zeroize,
351{
352 fn zeroize(&mut self) {
353 self.iter_mut().zeroize();
354 }
355}
356
357/// Impl [`ZeroizeOnDrop`] on arrays of types that impl [`ZeroizeOnDrop`].
358impl<Z, const N: usize> ZeroizeOnDrop for [Z; N] where Z: ZeroizeOnDrop {}
359
360impl<Z> Zeroize for IterMut<'_, Z>
361where
362 Z: Zeroize,
363{
364 fn zeroize(&mut self) {
365 for elem in self {
366 elem.zeroize();
367 }
368 }
369}
370
371impl<Z> Zeroize for Option<Z>
372where
373 Z: Zeroize,
374{
375 fn zeroize(&mut self) {
376 if let Some(value) = self {
377 value.zeroize();
378
379 // Ensures self is None and that the value was dropped. Without the take, the drop
380 // of the (zeroized) value isn't called, which might lead to a leak or other
381 // unexpected behavior. For example, if this were Option<Vec<T>>, the above call to
382 // zeroize would not free the allocated memory, but the `take` call will.
383 self.take();
384 }
385
386 // Ensure that if the `Option` were previously `Some` but a value was copied/moved out
387 // that the remaining space in the `Option` is zeroized.
388 //
389 // Safety:
390 //
391 // The memory pointed to by `self` is valid for `size_of::<Self>()` bytes.
392 // It is also properly aligned, because `u8` has an alignment of `1`.
393 unsafe {
394 zeroize_byte_ptr(ptr::from_mut::<Self>(self).cast::<u8>(), size_of::<Self>());
395 }
396
397 // Ensures self is overwritten with the `None` bit pattern. volatile_write can't be
398 // used because Option<Z> is not copy.
399 //
400 // Safety:
401 //
402 // self is safe to replace with `None`, which the take() call above should have
403 // already done semantically. Any value which needed to be dropped will have been
404 // done so by take().
405 unsafe { ptr::write_volatile(self, None) }
406 }
407}
408
409impl<Z> ZeroizeOnDrop for Option<Z> where Z: ZeroizeOnDrop {}
410
411/// Impl [`Zeroize`] on [`MaybeUninit`] types.
412///
413/// This fills the memory with zeroes.
414/// Note that this ignore invariants that `Z` might have, because
415/// [`MaybeUninit`] removes all invariants.
416impl<Z> Zeroize for MaybeUninit<Z> {
417 fn zeroize(&mut self) {
418 // SAFETY: `MaybeUninit` is valid for any byte pattern, including zeros.
419 unsafe { ptr::write_volatile(self, MaybeUninit::zeroed()) }
420 }
421}
422
423/// Impl [`Zeroize`] on slices of [`MaybeUninit`] types.
424///
425/// This impl can eventually be optimized using an memset intrinsic,
426/// such as [`core::intrinsics::volatile_set_memory`].
427///
428/// This fills the slice with zeroes.
429///
430/// Note that this ignore invariants that `Z` might have, because
431/// [`MaybeUninit`] removes all invariants.
432impl<Z> Zeroize for [MaybeUninit<Z>] {
433 fn zeroize(&mut self) {
434 let size = size_of_val(self);
435
436 // SAFETY: the slice provides exclusive access to `size` bytes, and
437 // `MaybeUninit<Z>` permits all-zero bytes, including in padding.
438 unsafe { zeroize_byte_ptr(self.as_mut_ptr().cast::<u8>(), size) }
439 }
440}
441
442/// Impl [`Zeroize`] on slices of types that can be zeroized with [`Default`].
443///
444/// To zeroize a mut slice of `Z: Zeroize` which does not impl
445/// [`DefaultIsZeroes`], call `iter_mut().zeroize()`.
446impl<Z> Zeroize for [Z]
447where
448 Z: DefaultIsZeroes,
449{
450 fn zeroize(&mut self) {
451 bulk::fill_slice(self, Z::default());
452 }
453}
454
455impl Zeroize for str {
456 fn zeroize(&mut self) {
457 // SAFETY: a zeroized byte slice is a valid UTF-8 string.
458 unsafe { self.as_bytes_mut().zeroize() }
459 }
460}
461
462/// [`PhantomData`] is always zero sized so provide a [`Zeroize`] implementation.
463impl<Z> Zeroize for PhantomData<Z> {
464 fn zeroize(&mut self) {}
465}
466
467/// [`PhantomData` is always zero sized so provide a `ZeroizeOnDrop` implementation.
468impl<Z> ZeroizeOnDrop for PhantomData<Z> {}
469
470macro_rules! impl_zeroize_tuple {
471 ( $( $type_name:ident ),+ ) => {
472 impl<$($type_name: Zeroize),+> Zeroize for ($($type_name,)+) {
473 fn zeroize(&mut self) {
474 #[allow(non_snake_case)]
475 let ($($type_name,)+) = self;
476 $($type_name.zeroize());+
477 }
478 }
479
480 impl<$($type_name: ZeroizeOnDrop),+> ZeroizeOnDrop for ($($type_name,)+) { }
481 }
482}
483
484// Generic implementations for tuples up to 10 parameters.
485impl_zeroize_tuple!(A);
486impl_zeroize_tuple!(A, B);
487impl_zeroize_tuple!(A, B, C);
488impl_zeroize_tuple!(A, B, C, D);
489impl_zeroize_tuple!(A, B, C, D, E);
490impl_zeroize_tuple!(A, B, C, D, E, F);
491impl_zeroize_tuple!(A, B, C, D, E, F, G);
492impl_zeroize_tuple!(A, B, C, D, E, F, G, H);
493impl_zeroize_tuple!(A, B, C, D, E, F, G, H, I);
494impl_zeroize_tuple!(A, B, C, D, E, F, G, H, I, J);
495
496#[cfg(feature = "alloc")]
497impl<Z> Zeroize for Vec<Z>
498where
499 Z: Zeroize,
500{
501 /// "Best effort" zeroization for `Vec`.
502 ///
503 /// Call `Zeroize` on all `Vec` elements and spare capacity. Cannot ensure that
504 /// previous reallocations did not leave values on the heap.
505 fn zeroize(&mut self) {
506 // Zero the spare (uninitialized) capacity first, i.e. everything
507 // beyond `len`. This must happen before `clear()` resets `len` to 0,
508 // otherwise `spare_capacity_mut()` would cover the whole allocation
509 // and re-zero the initialized elements a second time below.
510 self.spare_capacity_mut().zeroize();
511
512 // Zeroize all the initialized elements.
513 self.iter_mut().zeroize();
514
515 // Set the Vec's length to 0 and drop all the (already-zeroized) elements.
516 self.clear();
517 }
518}
519
520#[cfg(feature = "alloc")]
521impl<Z> ZeroizeOnDrop for Vec<Z> where Z: ZeroizeOnDrop {}
522
523#[cfg(feature = "alloc")]
524impl<Z> Zeroize for Box<[Z]>
525where
526 Z: Zeroize,
527{
528 /// Unlike `Vec`, `Box<[Z]>` cannot reallocate, so we can be sure that we are not leaving
529 /// values on the heap.
530 fn zeroize(&mut self) {
531 self.iter_mut().zeroize();
532 }
533}
534
535#[cfg(feature = "alloc")]
536impl<Z> ZeroizeOnDrop for Box<[Z]> where Z: ZeroizeOnDrop {}
537
538#[cfg(feature = "alloc")]
539impl Zeroize for Box<str> {
540 fn zeroize(&mut self) {
541 self.as_mut().zeroize();
542 }
543}
544
545#[cfg(feature = "alloc")]
546impl Zeroize for String {
547 fn zeroize(&mut self) {
548 unsafe { self.as_mut_vec() }.zeroize();
549 }
550}
551
552#[cfg(feature = "std")]
553impl Zeroize for CString {
554 fn zeroize(&mut self) {
555 use core::mem;
556
557 // mem::take uses replace internally to swap the pointer
558 // Unfortunately this results in an allocation for a Box::new(&[0]) as CString must
559 // contain a trailing zero byte
560 let this = mem::take(self);
561
562 // - CString::into_bytes_with_nul calls ::into_vec which takes ownership of the heap pointer
563 // as a Vec<u8>
564 // - Calling .zeroize() on the resulting vector clears out the bytes
565 // From: https://github.com/RustCrypto/utils/pull/759#issuecomment-1087976570
566 let mut buf = this.into_bytes_with_nul();
567 buf.zeroize();
568
569 // expect() should never fail, because zeroize() truncates the Vec
570 let zeroed = CString::new(buf).expect("buf not truncated");
571
572 // Replace self by the zeroed CString to maintain the original ptr of the buffer
573 let _ = mem::replace(self, zeroed);
574 }
575}
576
577/// `Zeroizing` is a wrapper for any `Z: Zeroize` type which implements a
578/// `Drop` handler which zeroizes dropped values.
579///
580/// `Zeroizing<T>` is defined with `repr(transparent)`, which means it is
581/// guaranteed to have the same physical representation as the underlying type.
582#[derive(Default, Eq, PartialEq)]
583#[repr(transparent)]
584pub struct Zeroizing<Z: Zeroize + ?Sized>(Z);
585
586impl<Z: Zeroize + ?Sized> core::fmt::Debug for Zeroizing<Z> {
587 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
588 f.debug_struct("Zeroizing").finish_non_exhaustive()
589 }
590}
591
592impl<Z> Zeroizing<Z>
593where
594 Z: Zeroize,
595{
596 /// Move value inside a `Zeroizing` wrapper which ensures it will be
597 /// zeroized when it's dropped.
598 #[inline(always)]
599 pub fn new(value: Z) -> Self {
600 Self(value)
601 }
602}
603
604impl<Z: Zeroize + Clone> Clone for Zeroizing<Z> {
605 #[inline(always)]
606 fn clone(&self) -> Self {
607 Self(self.0.clone())
608 }
609
610 #[inline(always)]
611 fn clone_from(&mut self, source: &Self) {
612 self.0.zeroize();
613 self.0.clone_from(&source.0);
614 }
615}
616
617impl<Z> From<Z> for Zeroizing<Z>
618where
619 Z: Zeroize,
620{
621 #[inline(always)]
622 fn from(value: Z) -> Zeroizing<Z> {
623 Zeroizing(value)
624 }
625}
626
627impl<Z> ops::Deref for Zeroizing<Z>
628where
629 Z: Zeroize + ?Sized,
630{
631 type Target = Z;
632
633 #[inline(always)]
634 fn deref(&self) -> &Z {
635 &self.0
636 }
637}
638
639impl<Z> ops::DerefMut for Zeroizing<Z>
640where
641 Z: Zeroize + ?Sized,
642{
643 #[inline(always)]
644 fn deref_mut(&mut self) -> &mut Z {
645 &mut self.0
646 }
647}
648
649impl<T, Z> AsRef<T> for Zeroizing<Z>
650where
651 T: ?Sized,
652 Z: AsRef<T> + Zeroize + ?Sized,
653{
654 #[inline(always)]
655 fn as_ref(&self) -> &T {
656 self.0.as_ref()
657 }
658}
659
660impl<T, Z> AsMut<T> for Zeroizing<Z>
661where
662 T: ?Sized,
663 Z: AsMut<T> + Zeroize + ?Sized,
664{
665 #[inline(always)]
666 fn as_mut(&mut self) -> &mut T {
667 self.0.as_mut()
668 }
669}
670
671impl<Z> Zeroize for Zeroizing<Z>
672where
673 Z: Zeroize + ?Sized,
674{
675 fn zeroize(&mut self) {
676 self.0.zeroize();
677 }
678}
679
680impl<Z> ZeroizeOnDrop for Zeroizing<Z> where Z: Zeroize + ?Sized {}
681
682impl<Z> Drop for Zeroizing<Z>
683where
684 Z: Zeroize + ?Sized,
685{
686 fn drop(&mut self) {
687 self.0.zeroize();
688 }
689}
690
691#[cfg(feature = "serde")]
692impl<Z> serde::Serialize for Zeroizing<Z>
693where
694 Z: Zeroize + serde::Serialize + ?Sized,
695{
696 #[inline(always)]
697 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
698 where
699 S: serde::Serializer,
700 {
701 self.0.serialize(serializer)
702 }
703}
704
705#[cfg(feature = "serde")]
706impl<'de, Z> serde::Deserialize<'de> for Zeroizing<Z>
707where
708 Z: Zeroize + serde::Deserialize<'de>,
709{
710 #[inline(always)]
711 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
712 where
713 D: serde::Deserializer<'de>,
714 {
715 Ok(Self(Z::deserialize(deserializer)?))
716 }
717}
718
719/// Securely zero a byte slice, preventing the compiler from eliminating the writes.
720///
721/// # Examples
722/// ```
723/// let mut secret = [42u8; 32];
724/// zeroize::zeroize_bytes(&mut secret);
725/// assert_eq!(secret, [0u8; 32]);
726/// ```
727#[inline]
728pub fn zeroize_bytes(bytes: &mut [u8]) {
729 // SAFETY: the slice provides exclusive access to its bytes, and zero is a valid u8.
730 unsafe { zeroize_byte_ptr(bytes.as_mut_ptr(), bytes.len()) }
731}
732
733/// Zeroizes a flat type/struct. Only zeroizes the values that it owns, and it does not work on
734/// dynamically sized values or trait objects. It would be inefficient to use this function on a
735/// type that already implements `ZeroizeOnDrop`.
736///
737/// Uses the same backend as [`zeroize_bytes`], including for padding and
738/// uninitialized bytes.
739///
740/// # Safety
741/// - For nonzero-sized `F`, `data` must be non-null and provide exclusive access to
742/// `size_of::<F>()` writable bytes within a single allocation.
743/// - The type must not contain references to outside data or dynamically sized data, such as
744/// `Vec<T>` or `String`.
745/// - Values stored in the type must not have `Drop` impls.
746/// - This function can invalidate the type if it is used after this function is called on it.
747/// It is advisable to call this function only in `impl Drop`.
748/// - The bit pattern of all zeroes must be valid for the data being zeroized. This may not be
749/// true for enums and pointers.
750///
751/// # Incompatible data types
752/// Some data types that cannot be safely zeroized using `zeroize_flat_type` include,
753/// but are not limited to:
754/// - References: `&T` and `&mut T`
755/// - Non-nullable types: `NonNull<T>`, `NonZeroU32`, etc.
756/// - Enums with explicit non-zero tags.
757/// - Smart pointers and collections: `Arc<T>`, `Box<T>`, `Vec<T>`, `HashMap<K, V>`, `String`, etc.
758///
759/// # Examples
760/// Safe usage for a struct containing strictly flat data:
761/// ```
762/// use zeroize::{ZeroizeOnDrop, zeroize_flat_type};
763///
764/// struct DataToZeroize {
765/// flat_data_1: [u8; 32],
766/// flat_data_2: SomeMoreFlatData,
767/// }
768///
769/// struct SomeMoreFlatData(u64);
770///
771/// impl Drop for DataToZeroize {
772/// fn drop(&mut self) {
773/// unsafe { zeroize_flat_type(self as *mut Self) }
774/// }
775/// }
776/// impl ZeroizeOnDrop for DataToZeroize {}
777///
778/// let mut data = DataToZeroize {
779/// flat_data_1: [3u8; 32],
780/// flat_data_2: SomeMoreFlatData(123u64)
781/// };
782///
783/// // data gets zeroized when dropped
784/// ```
785#[inline(always)]
786pub unsafe fn zeroize_flat_type<F: Sized>(data: *mut F) {
787 // `zeroize_byte_ptr` requires a non-NULL pointer, but we allow passing NULL pointers for ZSTs
788 if size_of::<F>() == 0 {
789 return;
790 }
791
792 // SAFETY: the caller provides exclusive access to the object's bytes and
793 // guarantees that zeroes are valid. The backend permits uninitialized padding.
794 unsafe { zeroize_byte_ptr(data.cast::<u8>(), size_of::<F>()) }
795}
796
797/// Perform a volatile write to the destination
798#[inline(always)]
799fn volatile_write<T: Copy + Sized>(dst: &mut T, src: T) {
800 unsafe { ptr::write_volatile(dst, src) }
801}
802
803/// Internal module used as support for `AssertZeroizeOnDrop`.
804#[doc(hidden)]
805pub mod __internal {
806 use super::*;
807
808 /// Auto-deref workaround for deriving `ZeroizeOnDrop`.
809 pub trait AssertZeroizeOnDrop {
810 fn zeroize_or_on_drop(self);
811 }
812
813 impl<T: ZeroizeOnDrop + ?Sized> AssertZeroizeOnDrop for &&mut T {
814 fn zeroize_or_on_drop(self) {}
815 }
816
817 /// Auto-deref workaround for deriving `ZeroizeOnDrop`.
818 pub trait AssertZeroize {
819 fn zeroize_or_on_drop(&mut self);
820 }
821
822 impl<T: Zeroize + ?Sized> AssertZeroize for T {
823 fn zeroize_or_on_drop(&mut self) {
824 self.zeroize();
825 }
826 }
827}