Skip to main content

rtci_crypto/
secret.rs

1use std::fmt;
2
3use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
4
5/// An owned byte vector that zeroizes its allocation when dropped.
6///
7/// The whole allocation is overwritten, spare capacity included. A `SecretVec` never grows: a
8/// buffer that does (`Vec::extend`, `push`) moves to a new allocation and leaves the old one
9/// behind unerased, so build key material in a buffer sized up front and wrap it here.
10pub struct SecretVec(Zeroizing<Vec<u8>>);
11
12impl Zeroize for SecretVec {
13    fn zeroize(&mut self) {
14        self.0.zeroize();
15    }
16}
17
18impl ZeroizeOnDrop for SecretVec {}
19
20impl SecretVec {
21    /// Wraps secret bytes.
22    #[must_use]
23    pub fn new(bytes: Vec<u8>) -> Self {
24        Self(Zeroizing::new(bytes))
25    }
26
27    /// Returns the number of secret bytes.
28    #[must_use]
29    pub fn len(&self) -> usize {
30        self.0.len()
31    }
32
33    /// Returns whether the secret is empty.
34    #[must_use]
35    pub fn is_empty(&self) -> bool {
36        self.0.is_empty()
37    }
38
39    /// Explicitly unwraps the secret bytes. The returned vector is no longer automatically zeroized.
40    #[must_use]
41    pub fn into_bytes(mut self) -> Vec<u8> {
42        std::mem::take(&mut *self.0)
43    }
44}
45
46impl AsRef<[u8]> for SecretVec {
47    fn as_ref(&self) -> &[u8] {
48        self.0.as_slice()
49    }
50}
51
52impl AsMut<[u8]> for SecretVec {
53    fn as_mut(&mut self) -> &mut [u8] {
54        self.0.as_mut_slice()
55    }
56}
57
58impl Clone for SecretVec {
59    fn clone(&self) -> Self {
60        Self::new(self.as_ref().to_vec())
61    }
62}
63
64impl fmt::Debug for SecretVec {
65    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66        formatter
67            .debug_struct("SecretVec")
68            .field("len", &self.len())
69            .field("bytes", &"[REDACTED]")
70            .finish()
71    }
72}
73
74impl From<Vec<u8>> for SecretVec {
75    fn from(value: Vec<u8>) -> Self {
76        Self::new(value)
77    }
78}
79
80/// How much stack [`scrub_stack`] overwrites.
81const SCRUB_STACK_BYTES: usize = 32 * 1024;
82
83/// Overwrites the stack below the caller's frame (32 KiB of it).
84///
85/// Building a keyed object leaves copies of the key and its schedule in the stack frames of
86/// the functions that built it: a value moved out of a frame is not dropped there, so its
87/// zeroize-on-drop never runs on the copy left behind, and a provider's own temporaries are
88/// not erased at all. Those dead frames are reused by later calls, and a value later built
89/// there and moved into the heap (into a `Box`, a `Vec`) carries whatever was in its padding
90/// or in the unused part of an enum or union along: the key ends up in memory the heap frees
91/// without erasure. Calling this right after a key schedule is built and moved to where it
92/// lives, from the frame that called the provider, overwrites what the deeper frames left.
93///
94/// What it does: one bulk zero fill (`ptr::write_bytes`, a `memset`) of a 32 KiB buffer in its
95/// own frame, which is never inlined, so the buffer lies in the stack just below the caller's
96/// frame, where the frames of the calls the caller made before lay. The buffer is then handed
97/// to [`std::hint::black_box`] and followed by a compiler fence, so the compiler cannot treat
98/// the fill as a dead store and drop it.
99///
100/// What it does not do: it cannot reach registers, the caller's own frame or any frame above
101/// it, other threads' stacks, or anything deeper than 32 KiB below the caller; and copies the
102/// compiler or a provider leaves that no test can see are not observed, so their absence is
103/// not guaranteed. The tests show only that copies carried from dead frames into heap padding
104/// are gone (`tests/dtls_secret_erasure.rs`; docs/key-erasure.md).
105#[inline(never)]
106pub fn scrub_stack() {
107    let mut area = std::mem::MaybeUninit::<[u8; SCRUB_STACK_BYTES]>::uninit();
108    // SAFETY: the pointer is to a local buffer of exactly `SCRUB_STACK_BYTES` bytes, written
109    // as bytes (any value is valid for `u8`) and never read as anything else.
110    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_STACK_BYTES) };
111    // The buffer is never read: without this the fill is a dead store the optimiser may remove.
112    std::hint::black_box(&mut area);
113    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
114}