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: 32 KiB in an optimised build, 128 KiB in an
81/// unoptimised one (`debug_assertions`, which Cargo's `dev` and `test` profiles turn on with
82/// opt-level 0).
83///
84/// The depth has to cover the stack the work before it used. Building an SRTP context uses
85/// about 3 KiB in an optimised build and 42 to 47 KiB in an unoptimised one, where every
86/// temporary has a stack slot of its own (`rtci-srtp/tests/key_residue.rs`, measured with a
87/// 32 KiB overwrite): the AES key schedules built for the key derivation are the deepest
88/// part, below frames such as
89/// `common::block_encrypt`'s, which holds a cipher object of every AES key length. With rustc
90/// 1.99.1 (x86-64 Linux) the master key and its round keys were left 37.7 to 42.2 KB below the
91/// point the measurement starts from, more than 32 KiB below the context's `on_erased_stack`
92/// frame (which lies less than 4.9 KB below that point), out of a 32 KiB overwrite's reach.
93/// 128 KiB is the deepest unoptimised use measured (47 KiB) times 2.7, for other compilers and
94/// profiles. The optimised depth is unchanged, and so is an optimised build's cost.
95const SCRUB_STACK_BYTES: usize = if cfg!(debug_assertions) {
96 128 * 1024
97} else {
98 32 * 1024
99};
100
101/// Overwrites the stack below the caller's frame (32 KiB of it in an optimised build, 128 KiB in
102/// an unoptimised one).
103///
104/// Building a keyed object leaves copies of the key and its schedule in the stack frames of
105/// the functions that built it: a value moved out of a frame is not dropped there, so its
106/// zeroize-on-drop never runs on the copy left behind, and a provider's own temporaries are
107/// not erased at all. Those dead frames are reused by later calls, and a value later built
108/// there and moved into the heap (into a `Box`, a `Vec`) carries whatever was in its padding
109/// or in the unused part of an enum or union along: the key ends up in memory the heap frees
110/// without erasure. Calling this right after a key schedule is built and moved to where it
111/// lives, from the frame that called the provider, overwrites what the deeper frames left.
112///
113/// What it does: one bulk zero fill (`ptr::write_bytes`, a `memset`) of a buffer of that size
114/// in its own frame, which is never inlined, so the buffer lies in the stack just below the
115/// caller's frame, where the frames of the calls the caller made before lay. The buffer is
116/// then handed to [`std::hint::black_box`] and followed by a compiler fence, so the compiler
117/// cannot treat the fill as a dead store and drop it. The calling thread needs that much stack
118/// free below the caller.
119///
120/// What it does not do: it cannot reach registers, the caller's own frame or any frame above
121/// it, other threads' stacks, or anything deeper than that size below the caller (a build
122/// profile with opt-level 0 and `debug-assertions = false` gets the optimised depth); and
123/// copies the compiler or a provider leaves that no test can see are not observed, so their
124/// absence is not guaranteed. The tests show only that copies carried from dead frames into heap padding
125/// are gone (`tests/dtls_secret_erasure.rs`; docs/key-erasure.md).
126#[inline(never)]
127pub fn scrub_stack() {
128 let mut area = std::mem::MaybeUninit::<[u8; SCRUB_STACK_BYTES]>::uninit();
129 // SAFETY: the pointer is to a local buffer of exactly `SCRUB_STACK_BYTES` bytes, written
130 // as bytes (any value is valid for `u8`) and never read as anything else.
131 unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_STACK_BYTES) };
132 // The buffer is never read: without this the fill is a dead store the optimiser may remove.
133 std::hint::black_box(&mut area);
134 std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
135}
136
137/// How much stack [`scrub_record_stack`] overwrites: 48 KiB, in an unoptimised build only.
138///
139/// The deepest record-key form measured in an unoptimised build lay 31,288 bytes below the
140/// DTLS key residue measurement's floor (rustc 1.89, the AES-CCM records step,
141/// `rtci-dtls/tests/key_residue.rs`, run 46015302538). Every record call's own frame lies below
142/// that floor, so what the record work leaves lies less than that below the call. 48 KiB is
143/// that depth times 1.5, for other compilers and call paths; it is paid in unoptimised builds
144/// only.
145#[cfg(debug_assertions)]
146const SCRUB_RECORD_STACK_BYTES: usize = 48 * 1024;
147
148/// Overwrites the stack below the caller's frame after one record's work with RustCrypto's AES,
149/// in an unoptimised build (`debug_assertions`); in an optimised build it is not compiled.
150///
151/// At opt-level 0 the AES-NI intrinsics of the `aes` crate are calls whose vector arguments go
152/// through stack copies, so every block encrypted or decrypted leaves round keys (round key 0
153/// is the key) and AES states in stack temporaries; an optimised build keeps them in registers.
154/// Measured: on Windows a DTLS 1.2 AES-CCM write key left there was carried into a freed heap
155/// block by the unwritten bytes of a handshake message moved into a map (docs/key-erasure.md);
156/// with the `aes` and `ccm` crates optimised, with the portable AES, in an optimised build, or
157/// with an overwrite after each AES-CCM call, it was not (runs 46026969169, 46026978042).
158#[cfg(debug_assertions)]
159#[inline(never)]
160pub(crate) fn scrub_record_stack() {
161 let mut area = std::mem::MaybeUninit::<[u8; SCRUB_RECORD_STACK_BYTES]>::uninit();
162 // SAFETY: the pointer is to a local buffer of exactly `SCRUB_RECORD_STACK_BYTES` bytes,
163 // written as bytes and never read as anything else.
164 unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_RECORD_STACK_BYTES) };
165 std::hint::black_box(&mut area);
166 std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
167}