Skip to main content

rtci_crypto/
secret.rs

1use std::fmt;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
5
6/// An owned byte vector that zeroizes its allocation when dropped.
7///
8/// The whole allocation is overwritten, spare capacity included. A `SecretVec` never grows: a
9/// buffer that does (`Vec::extend`, `push`) moves to a new allocation and leaves the old one
10/// behind unerased, so build key material in a buffer sized up front and wrap it here.
11pub struct SecretVec(Zeroizing<Vec<u8>>);
12
13impl Zeroize for SecretVec {
14    fn zeroize(&mut self) {
15        self.0.zeroize();
16    }
17}
18
19impl ZeroizeOnDrop for SecretVec {}
20
21impl SecretVec {
22    /// Wraps secret bytes.
23    #[must_use]
24    pub fn new(bytes: Vec<u8>) -> Self {
25        Self(Zeroizing::new(bytes))
26    }
27
28    /// Returns the number of secret bytes.
29    #[must_use]
30    pub fn len(&self) -> usize {
31        self.0.len()
32    }
33
34    /// Returns whether the secret is empty.
35    #[must_use]
36    pub fn is_empty(&self) -> bool {
37        self.0.is_empty()
38    }
39
40    /// Explicitly unwraps the secret bytes. The returned vector is no longer automatically zeroized.
41    #[must_use]
42    pub fn into_bytes(mut self) -> Vec<u8> {
43        std::mem::take(&mut *self.0)
44    }
45}
46
47impl AsRef<[u8]> for SecretVec {
48    fn as_ref(&self) -> &[u8] {
49        self.0.as_slice()
50    }
51}
52
53impl AsMut<[u8]> for SecretVec {
54    fn as_mut(&mut self) -> &mut [u8] {
55        self.0.as_mut_slice()
56    }
57}
58
59impl Clone for SecretVec {
60    fn clone(&self) -> Self {
61        Self::new(self.as_ref().to_vec())
62    }
63}
64
65impl fmt::Debug for SecretVec {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        formatter
68            .debug_struct("SecretVec")
69            .field("len", &self.len())
70            .field("bytes", &"[REDACTED]")
71            .finish()
72    }
73}
74
75impl From<Vec<u8>> for SecretVec {
76    fn from(value: Vec<u8>) -> Self {
77        Self::new(value)
78    }
79}
80
81/// How much stack [`scrub_stack`] overwrites: 32 KiB in an optimised build, 128 KiB in an
82/// unoptimised one (`debug_assertions`, which Cargo's `dev` and `test` profiles turn on with
83/// opt-level 0).
84///
85/// The depth has to cover the stack the work before it used. Building an SRTP context uses
86/// about 3 KiB in an optimised build and 42 to 47 KiB in an unoptimised one, where every
87/// temporary has a stack slot of its own (`rtci-srtp/tests/key_residue.rs`, measured with a
88/// 32 KiB overwrite): the AES key schedules built for the key derivation are the deepest
89/// part, below frames such as
90/// `common::block_encrypt`'s, which holds a cipher object of every AES key length. With rustc
91/// 1.99.1 (x86-64 Linux) the master key and its round keys were left 37.7 to 42.2 KB below the
92/// point the measurement starts from, more than 32 KiB below the context's `on_erased_stack`
93/// frame (which lies less than 4.9 KB below that point), out of a 32 KiB overwrite's reach.
94/// 128 KiB is the deepest unoptimised use measured (47 KiB) times 2.7, for other compilers and
95/// profiles. The optimised depth is unchanged, and so is an optimised build's cost.
96const SCRUB_STACK_BYTES: usize = if cfg!(debug_assertions) {
97    128 * 1024
98} else {
99    32 * 1024
100};
101
102/// Overwrites the stack below the caller's frame (32 KiB of it in an optimised build, 128 KiB in
103/// an unoptimised one).
104///
105/// Building a keyed object leaves copies of the key and its schedule in the stack frames of
106/// the functions that built it: a value moved out of a frame is not dropped there, so its
107/// zeroize-on-drop never runs on the copy left behind, and a provider's own temporaries are
108/// not erased at all. Those dead frames are reused by later calls, and a value later built
109/// there and moved into the heap (into a `Box`, a `Vec`) carries whatever was in its padding
110/// or in the unused part of an enum or union along: the key ends up in memory the heap frees
111/// without erasure. Calling this right after a key schedule is built and moved to where it
112/// lives, from the frame that called the provider, overwrites what the deeper frames left.
113///
114/// What it does: one bulk zero fill (`ptr::write_bytes`, a `memset`) of a buffer of that size
115/// in its own frame, which is never inlined, so the buffer lies in the stack just below the
116/// caller's frame, where the frames of the calls the caller made before lay. The buffer is
117/// then handed to [`std::hint::black_box`] and followed by a compiler fence, so the compiler
118/// cannot treat the fill as a dead store and drop it. The calling thread needs that much stack
119/// free below the caller.
120///
121/// What it does not do: it cannot reach registers, the caller's own frame or any frame above
122/// it, other threads' stacks, or anything deeper than that size below the caller (a build
123/// profile with opt-level 0 and `debug-assertions = false` gets the optimised depth); and
124/// copies the compiler or a provider leaves that no test can see are not observed, so their
125/// absence is not guaranteed. The tests show only that copies carried from dead frames into heap padding
126/// are gone (`tests/dtls_secret_erasure.rs`; docs/key-erasure.md).
127#[inline(never)]
128pub fn scrub_stack() {
129    let mut area = std::mem::MaybeUninit::<[u8; SCRUB_STACK_BYTES]>::uninit();
130    // SAFETY: the pointer is to a local buffer of exactly `SCRUB_STACK_BYTES` bytes, written
131    // as bytes (any value is valid for `u8`) and never read as anything else.
132    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_STACK_BYTES) };
133    // The buffer is never read: without this the fill is a dead store the optimiser may remove.
134    std::hint::black_box(&mut area);
135    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
136}
137
138/// How much stack [`scrub_record_stack`] overwrites: 48 KiB, in an unoptimised build only.
139///
140/// The deepest record-key form measured in an unoptimised build lay 31,288 bytes below the
141/// DTLS key residue measurement's floor (rustc 1.89, the AES-CCM records step,
142/// `rtci-dtls/tests/key_residue.rs`, run 46015302538). Every record call's own frame lies below
143/// that floor, so what the record work leaves lies less than that below the call. 48 KiB is
144/// that depth times 1.5, for other compilers and call paths; it is paid in unoptimised builds
145/// only.
146#[cfg(debug_assertions)]
147const SCRUB_RECORD_STACK_BYTES: usize = 48 * 1024;
148
149/// Overwrites the stack below the caller's frame after one record's work with RustCrypto's AES,
150/// in an unoptimised build (`debug_assertions`); in an optimised build it is not compiled.
151///
152/// At opt-level 0 the AES-NI intrinsics of the `aes` crate are calls whose vector arguments go
153/// through stack copies, so every block encrypted or decrypted leaves round keys (round key 0
154/// is the key) and AES states in stack temporaries; an optimised build keeps them in registers.
155/// Measured: on Windows a DTLS 1.2 AES-CCM write key left there was carried into a freed heap
156/// block by the unwritten bytes of a handshake message moved into a map (docs/key-erasure.md);
157/// with the `aes` and `ccm` crates optimised, with the portable AES, in an optimised build, or
158/// with an overwrite after each AES-CCM call, it was not (runs 46026969169, 46026978042).
159#[cfg(debug_assertions)]
160#[inline(never)]
161pub(crate) fn scrub_record_stack() {
162    let mut area = std::mem::MaybeUninit::<[u8; SCRUB_RECORD_STACK_BYTES]>::uninit();
163    // SAFETY: the pointer is to a local buffer of exactly `SCRUB_RECORD_STACK_BYTES` bytes,
164    // written as bytes and never read as anything else.
165    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_RECORD_STACK_BYTES) };
166    std::hint::black_box(&mut area);
167    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
168}
169
170/// Whether the record paths whose provider leaves key copies in its own stack frames overwrite
171/// the stack after each record ([`set_record_stack_erasure`]). On unless turned off.
172static RECORD_STACK_ERASURE: AtomicBool = AtomicBool::new(true);
173
174/// Turns on or off, for the whole process, the stack overwrite after each record operation of
175/// the paths that leave key copies in dead stack frames of code the crate cannot change: the
176/// AWS-LC provider's AEAD (its AES-GCM leaves a GHASH table entry) and HMAC (each MAC is
177/// computed on a copy of the keyed context, HMAC-SHA1 for SRTP and the DTLS AES-CBC suites);
178/// the ring provider's ChaCha20-Poly1305 (the key is copied to the stack per record); and
179/// AES-CCM (RustCrypto's `aes` under `ccm`, which left round keys with compilers older than
180/// rustc 1.99.1 in an optimised build). Each such call then runs in a frame of its own and the
181/// stack below it is overwritten afterwards, as deep as that path was measured to use
182/// (`record_depth`: a few KiB optimised; 128 KiB unoptimised), so no key is left in a dead stack frame
183/// (RFC 7714 section 13.1: "All keys MUST be properly erased when no longer needed";
184/// `rtci-srtp/tests/key_residue.rs`, `rtci-dtls/tests/key_residue.rs`). On by default.
185///
186/// Off, those copies stay until later calls on the same thread overwrite them, and an
187/// application that cares calls [`scrub_stack`] from that thread when a session ends. The
188/// cost is one overwrite per record on those paths only (docs/performance.md); ring's AES-GCM,
189/// RustCrypto's AES-CTR and AES-CBC and the ring provider's HMAC were measured to leave nothing
190/// and are not affected.
191pub fn set_record_stack_erasure(enabled: bool) {
192    RECORD_STACK_ERASURE.store(enabled, Ordering::Relaxed);
193}
194
195/// Whether the stack overwrite after each record of [`set_record_stack_erasure`] is on.
196#[must_use]
197pub fn record_stack_erasure() -> bool {
198    RECORD_STACK_ERASURE.load(Ordering::Relaxed)
199}
200
201/// How much stack one record call of each covered path dirties below the call, at most, in an
202/// optimised build, and so how much is overwritten after it. Measured by
203/// `record_stack_depth_tests` (a high-water probe: the stack below is filled with a marker,
204/// the provider call is made, and the lowest byte it changed is found), which fails when a
205/// path dirties more than its depth here less a 512-byte margin (every path is measured and
206/// printed before it fails, naming each that is too shallow); the residue measurements
207/// (`rtci-srtp/tests/key_residue.rs`, `rtci-dtls/tests/key_residue.rs`) assert the result. An
208/// unoptimised build overwrites [`SCRUB_STACK_BYTES`] (128 KiB): its frames are many times
209/// larger and nobody benchmarks it. A 32 KiB overwrite per record cost about 350 ns (bench
210/// run 46281647380); a few KiB cost tens.
211pub(crate) mod record_depth {
212    const fn optimised(bytes: usize) -> usize {
213        if cfg!(debug_assertions) {
214            super::SCRUB_STACK_BYTES
215        } else {
216            bytes
217        }
218    }
219    /// The AWS-LC provider's AEAD (AES-GCM, ChaCha20-Poly1305) seal and open: measured at most
220    /// 2,752 bytes (AES-GCM seal, x86-64 Linux) and 1,160 (AArch64 macOS) on the hardware paths,
221    /// and 4,112 (AES-GCM seal) on its portable path (an emulated CPU without SSSE3, AES-NI or
222    /// CLMUL, run 46318613275), so 5 KiB.
223    #[cfg(feature = "crypto-aws-lc-rs")]
224    pub(crate) const AWS_LC_AEAD: usize = optimised(5 * 1024);
225    /// The AWS-LC provider's HMAC (SHA-1, SHA-256, SHA-384, SHA-512): measured 5,256 bytes on
226    /// x86-64 Linux and 5,304 on AArch64 macOS for HMAC-SHA1 (probe runs 46285590132,
227    /// 46285596360), so 8 KiB.
228    #[cfg(feature = "crypto-aws-lc-rs")]
229    pub(crate) const AWS_LC_HMAC: usize = optimised(8 * 1024);
230    /// The AWS-LC provider's DTLS 1.3 record-number mask (AES-ECB or a ChaCha20 block of the
231    /// record-number key), once per record.
232    #[cfg(feature = "crypto-aws-lc-rs")]
233    pub(crate) const AWS_LC_HEADER_MASK: usize = optimised(4 * 1024);
234    /// The ring provider's ChaCha20-Poly1305 seal and open.
235    #[cfg(feature = "crypto-ring")]
236    pub(crate) const RING_CHACHA20: usize = optimised(4 * 1024);
237    /// The ring provider's AES-GCM seal and open on its portable path (vpaes or no-hardware
238    /// AES, fallback GHASH; `providers::ring::ring_aes_gcm_hardware`). The same code in AWS-LC
239    /// was measured at 4,112 bytes (AES-GCM seal, qemu64); the probe below measures ring's.
240    #[cfg(feature = "crypto-ring")]
241    pub(crate) const RING_AES_GCM_PORTABLE: usize = optimised(6 * 1024);
242    /// RustCrypto's AES record operations (AES-CTR for SRTP AES-CM, AES-CBC) on a CPU without
243    /// AES hardware, where `aes` runs its portable fixsliced code
244    /// ([`super::rustcrypto_aes_hardware`]).
245    #[cfg_attr(debug_assertions, allow(dead_code))]
246    pub(crate) const RUSTCRYPTO_AES_PORTABLE: usize = optimised(4 * 1024);
247    /// RustCrypto's AES key set-up and one block (the SRTP key derivation over the master key,
248    /// `common::block_encrypt`) on a CPU without AES hardware: overwritten in every build,
249    /// whatever the record setting. Measured by the probe below for AES-128, -192 and -256: at
250    /// most 5,240 bytes on CPUs without AES hardware (emulated Nehalem and qemu64, run
251    /// 46339769787: 4,968 / 5,240 / 5,224), less with `--cfg aes_force_soft` on AES hardware;
252    /// 8 KiB is that depth times 1.5.
253    pub(crate) const RUSTCRYPTO_AES_KEY_SETUP: usize = optimised(8 * 1024);
254    /// The ring provider's HMAC-SHA1 (RustCrypto `hmac` / `sha1`) on a CPU without SHA
255    /// instructions, where `sha1` runs its portable code ([`super::rustcrypto_sha1_hardware`]).
256    #[cfg(feature = "crypto-ring")]
257    pub(crate) const RUSTCRYPTO_SHA1_PORTABLE: usize = optimised(4 * 1024);
258    /// AES-CCM (RustCrypto's `aes` under `ccm`), either provider.
259    pub(crate) const CCM: usize = optimised(4 * 1024);
260}
261
262/// Whether RustCrypto's `aes` uses AES hardware on this CPU, by the test it makes itself
263/// (aes 0.8.4: `cpufeatures::new!(aes_intrinsics, "aes")` on x86 / x86-64; on AArch64 only when
264/// built with `--cfg aes_armv8`, then the `aes` feature). Without it `aes` runs its portable,
265/// fixsliced code, which leaves key schedule copies in stack frames (the portable pass of
266/// `rtci-srtp/tests/key_residue.rs`); the record operations are then followed by an overwrite.
267///
268/// Built with `--cfg aes_force_soft` (a CI step of its own), `aes` runs its portable code on any
269/// CPU, and this says so.
270pub(crate) fn rustcrypto_aes_hardware() -> bool {
271    if cfg!(aes_force_soft) {
272        return false;
273    }
274    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
275    {
276        std::arch::is_x86_feature_detected!("aes")
277    }
278    #[cfg(target_arch = "aarch64")]
279    {
280        cfg!(aes_armv8) && std::arch::is_aarch64_feature_detected!("aes")
281    }
282    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
283    {
284        false
285    }
286}
287
288/// Whether RustCrypto's `sha1` uses SHA hardware on this CPU, by its own test (sha1 0.11:
289/// `cpufeatures::new!(shani_cpuid, "sha", "sse2", "ssse3", "sse4.1")` on x86 / x86-64,
290/// `cpufeatures::new!(sha2_hwcap, "sha2")` on AArch64).
291#[cfg(feature = "crypto-ring")]
292pub(crate) fn rustcrypto_sha1_hardware() -> bool {
293    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
294    {
295        std::arch::is_x86_feature_detected!("sha")
296            && std::arch::is_x86_feature_detected!("sse2")
297            && std::arch::is_x86_feature_detected!("ssse3")
298            && std::arch::is_x86_feature_detected!("sse4.1")
299    }
300    #[cfg(target_arch = "aarch64")]
301    {
302        std::arch::is_aarch64_feature_detected!("sha2")
303    }
304    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
305    {
306        false
307    }
308}
309
310/// Overwrites `N` bytes of stack below the caller's frame: [`scrub_stack`] of a given depth.
311/// One bulk fill (`ptr::write_bytes`, a `memset`), then [`std::hint::black_box`] and a
312/// compiler fence so the optimiser cannot drop it as a dead store.
313#[inline(never)]
314pub(crate) fn scrub_stack_bytes<const N: usize>() {
315    let mut area = std::mem::MaybeUninit::<[u8; N]>::uninit();
316    // SAFETY: the pointer is to a local buffer of exactly `N` bytes, written as bytes and
317    // never read as anything else.
318    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, N) };
319    std::hint::black_box(&mut area);
320    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
321}
322
323/// One record operation of a path [`set_record_stack_erasure`] covers: while the setting is on,
324/// run in a frame of its own and then `DEPTH` bytes of stack below are overwritten (the
325/// path's [`record_depth`]); as it is otherwise.
326#[inline(always)]
327pub(crate) fn erased_record_call<const DEPTH: usize, R>(work: impl FnOnce() -> R) -> R {
328    #[inline(never)]
329    fn own_frame<R>(work: impl FnOnce() -> R) -> R {
330        work()
331    }
332    if record_stack_erasure() {
333        let value = own_frame(work);
334        scrub_stack_bytes::<DEPTH>();
335        value
336    } else {
337        work()
338    }
339}
340
341#[cfg(test)]
342mod record_stack_erasure_tests {
343    use super::*;
344    use std::sync::Mutex;
345
346    /// The setting is process-wide: the tests that change it run one at a time.
347    static SETTING: Mutex<()> = Mutex::new(());
348
349    /// On by default; the setting turns it off and on again, and a record call returns its
350    /// work's value either way.
351    #[test]
352    fn the_record_stack_erasure_is_on_by_default_and_can_be_turned_off() {
353        let _setting = SETTING.lock().unwrap_or_else(|e| e.into_inner());
354        assert!(record_stack_erasure(), "on by default");
355        set_record_stack_erasure(false);
356        assert!(!record_stack_erasure());
357        assert_eq!(erased_record_call::<64, _>(|| 7), 7);
358        set_record_stack_erasure(true);
359        assert!(record_stack_erasure());
360        assert_eq!(erased_record_call::<64, _>(|| 8), 8);
361    }
362
363    const PROBE_BYTES: usize = 64 * 1024;
364    const MARK: u8 = 0xa5;
365
366    /// Fills `PROBE_BYTES` of stack just below the caller's frame with `MARK`, byte by byte with
367    /// volatile writes, and returns where that area lies.
368    #[inline(never)]
369    fn fill_below() -> (usize, usize) {
370        let mut area = [0u8; PROBE_BYTES];
371        for byte in area.iter_mut() {
372            // SAFETY: `byte` is a valid, aligned, exclusive reference into `area`.
373            unsafe { std::ptr::write_volatile(byte, MARK) };
374        }
375        let start = area.as_ptr() as usize;
376        std::hint::black_box(&mut area);
377        (start, start + PROBE_BYTES)
378    }
379
380    #[inline(never)]
381    fn call(work: &mut dyn FnMut()) {
382        work();
383    }
384
385    /// How deep below its caller one call of `work` writes the stack: the area below is filled
386    /// with a marker, `work` is called from a frame at the same depth, and the lowest byte that
387    /// no longer holds the marker is found. `work` runs once before, so that one-time set-up
388    /// (CPU feature detection, lazy tables) is not counted.
389    #[inline(never)]
390    fn depth_of(mut work: impl FnMut()) -> usize {
391        work();
392        let (start, end) = fill_below();
393        call(&mut work);
394        let mut lowest = end;
395        for address in start..end {
396            // SAFETY: `start..end` is stack this thread owns below the current frame (the area
397            // `fill_below` filled, beyond every live frame now); it is read, never written.
398            let byte = unsafe { std::ptr::read_volatile(address as *const u8) };
399            if byte != MARK {
400                lowest = address;
401                break;
402            }
403        }
404        end - lowest
405    }
406
407    /// Records `path`'s measured depth against its overwrite and prints it; a path that does
408    /// not fit with a 512-byte margin is added to `short`.
409    fn assert_within(short: &mut Vec<String>, path: &str, depth: usize, overwrite: usize) {
410        let fits = depth < PROBE_BYTES && depth + 512 <= overwrite;
411        println!(
412            "RECORD DEPTH {path}: {depth} bytes (overwrite {overwrite}){}",
413            if fits { "" } else { " TOO SHALLOW" }
414        );
415        if !fits {
416            short.push(format!("{path}: {depth} bytes, overwrite {overwrite}"));
417        }
418    }
419
420    fn block_key_len(algorithm: crate::BlockCipherAlgorithm) -> usize {
421        match algorithm {
422            crate::BlockCipherAlgorithm::Aes128 => 16,
423            crate::BlockCipherAlgorithm::Aes192 => 24,
424            crate::BlockCipherAlgorithm::Aes256 => 32,
425        }
426    }
427
428    /// The 64-byte blocks (whole round keys) of RustCrypto's portable (fixsliced) schedule of
429    /// `key`, as the cipher object holds it: each block with at least four distinct byte values,
430    /// not made of 0x00 and 0xff alone. (`rtci-srtp/tests/portable_aes` uses pairs of round
431    /// keys for AES-192 and AES-256, so that a needle identifies its key among others; here only
432    /// this one key's schedule is looked for, in a stack area that holds no other.) Only on the
433    /// portable path, where that schedule is the object's whole content.
434    fn fixsliced_blocks(key: &[u8]) -> Vec<[u8; 64]> {
435        use aes::cipher::KeyInit;
436        fn blocks<T>(value: &T) -> Vec<[u8; 64]> {
437            // SAFETY: only on the portable path (`rustcrypto_aes_hardware()` false): `aes` then
438            // holds its fixsliced schedule, written in full (the larger arm of its union, or the
439            // whole type under `aes_force_soft`); read as bytes only.
440            let bytes = unsafe {
441                std::slice::from_raw_parts((value as *const T).cast::<u8>(), size_of::<T>())
442            };
443            bytes
444                .as_chunks::<64>()
445                .0
446                .iter()
447                .filter(|block| {
448                    let mut seen = [false; 256];
449                    for &b in block.iter() {
450                        seen[usize::from(b)] = true;
451                    }
452                    seen.iter().filter(|&&s| s).count() >= 4
453                        && !block.iter().all(|&b| b == 0 || b == 0xff)
454                })
455                .copied()
456                .collect()
457        }
458        match key.len() {
459            16 => blocks(&aes::Aes128::new_from_slice(key).expect("a key")),
460            24 => blocks(&aes::Aes192::new_from_slice(key).expect("a key")),
461            32 => blocks(&aes::Aes256::new_from_slice(key).expect("a key")),
462            n => panic!("an AES key of {n} bytes"),
463        }
464    }
465
466    /// The SRTP key derivation's AES (`common::block_encrypt`, whose key is the master key)
467    /// leaves no copy of the key's schedule in the dead stack frames below it on the portable
468    /// path (a CPU without AES hardware, or `--cfg aes_force_soft`): the frames are searched
469    /// for the fixsliced schedule's blocks after one call. The same call without the overwrite
470    /// (`block_encrypt_work`) must leave some, so the search is shown to see them. The portable
471    /// pass of `rtci-srtp/tests/key_residue.rs` found that schedule carried from such frames into
472    /// a live ring AES-GCM key object (run 46330510022). On AES hardware the test says so and
473    /// passes.
474    #[test]
475    fn key_derivation_leaves_no_key_schedule_in_dead_stack_frames() {
476        if rustcrypto_aes_hardware() {
477            println!("KEY SETUP: RustCrypto's aes uses AES hardware here: no portable schedule");
478            return;
479        }
480        for algorithm in [
481            crate::BlockCipherAlgorithm::Aes128,
482            crate::BlockCipherAlgorithm::Aes192,
483            crate::BlockCipherAlgorithm::Aes256,
484        ] {
485            let len = block_key_len(algorithm);
486            let key: Vec<u8> = (0..len as u8)
487                .map(|b| b.wrapping_mul(53).wrapping_add(len as u8) ^ 0x3c)
488                .collect();
489            let needles = fixsliced_blocks(&key);
490            assert!(
491                needles.len() >= 8,
492                "{algorithm:?}: only {} fixsliced blocks modelled",
493                needles.len()
494            );
495            let mut snapshot = vec![0u8; PROBE_BYTES];
496            let mut left = |erased: bool| -> usize {
497                let (start, end) = fill_below();
498                call(&mut || {
499                    let mut block = [0x15u8; 16];
500                    let done = if erased {
501                        crate::common::block_encrypt(algorithm, &key, &mut block)
502                    } else {
503                        crate::common::block_encrypt_work(algorithm, &key, &mut block)
504                    };
505                    done.expect("a block");
506                    std::hint::black_box(&block);
507                });
508                // Copied out without a call, so no frame overwrites the area before it is read.
509                for (i, slot) in snapshot.iter_mut().enumerate().take(end - start) {
510                    // SAFETY: `start..end` is stack this thread owns below the current frame
511                    // (the area `fill_below` filled); read, never written.
512                    *slot = unsafe { std::ptr::read_volatile((start + i) as *const u8) };
513                }
514                needles
515                    .iter()
516                    .filter(|n| snapshot.windows(64).any(|w| w == &n[..]))
517                    .count()
518            };
519            let without = left(false);
520            let with = left(true);
521            println!(
522                "KEY SETUP {algorithm:?}: {without} of {} schedule blocks left without the \
523                 overwrite, {with} with it",
524                needles.len()
525            );
526            assert!(
527                without > 0,
528                "{algorithm:?}: without the overwrite the search found no schedule block: it does \
529                 not see what the portable code leaves"
530            );
531            assert_eq!(
532                with, 0,
533                "{algorithm:?}: the key derivation left its key's schedule in dead stack frames"
534            );
535        }
536    }
537
538    fn aead_key_len(algorithm: crate::AeadAlgorithm) -> usize {
539        match algorithm {
540            crate::AeadAlgorithm::Aes256Gcm | crate::AeadAlgorithm::ChaCha20Poly1305 => 32,
541            _ => 16,
542        }
543    }
544
545    fn aead_depths(
546        provider: &dyn crate::RTCCryptoProvider,
547        algorithm: crate::AeadAlgorithm,
548    ) -> (usize, usize) {
549        let mut aead = provider
550            .crypto()
551            .new_aead(algorithm, &[0x42; 32][..aead_key_len(algorithm)])
552            .expect("an AEAD");
553        let tag_len = aead.tag_len();
554        let nonce = [7u8; 12];
555        let mut data = vec![0x33u8; 1200];
556        let mut tag = vec![0u8; tag_len];
557        let seal = depth_of(|| {
558            aead.seal_in_place(&nonce, b"header", &mut data, &mut tag)
559                .expect("sealed");
560        });
561        let mut sealed = vec![0x33u8; 1200];
562        let mut sealed_tag = vec![0u8; tag_len];
563        aead.seal_in_place(&nonce, b"header", &mut sealed, &mut sealed_tag)
564            .expect("sealed");
565        let open = depth_of(|| {
566            let mut copy = sealed.clone();
567            aead.open_in_place(&nonce, b"header", &mut copy, &sealed_tag)
568                .expect("opened");
569        });
570        (seal, open)
571    }
572
573    /// The high-water probe behind `record_depth`: for each path the record overwrite covers,
574    /// with the overwrite itself off, how deep one record call dirties the stack. Each must fit
575    /// the path's overwrite with a 512-byte margin; the depths are printed (`RECORD DEPTH`).
576    /// Meaningful in an optimised build (`cargo test --release`), where `record_depth` is small;
577    /// an unoptimised build overwrites 128 KiB and passes trivially.
578    #[test]
579    fn each_record_path_dirties_no_more_stack_than_its_overwrite() {
580        let _setting = SETTING.lock().unwrap_or_else(|e| e.into_inner());
581        set_record_stack_erasure(false);
582        let result = std::panic::catch_unwind(|| {
583            let mut short = Vec::new();
584            #[cfg(feature = "crypto-aws-lc-rs")]
585            {
586                let provider = crate::providers::AwsLcRsProvider::new();
587                for algorithm in [
588                    crate::AeadAlgorithm::Aes128Gcm,
589                    crate::AeadAlgorithm::Aes256Gcm,
590                    crate::AeadAlgorithm::ChaCha20Poly1305,
591                ] {
592                    let (seal, open) = aead_depths(&provider, algorithm);
593                    assert_within(
594                        &mut short,
595                        &format!("aws-lc-rs {algorithm:?} seal"),
596                        seal,
597                        record_depth::AWS_LC_AEAD,
598                    );
599                    assert_within(
600                        &mut short,
601                        &format!("aws-lc-rs {algorithm:?} open"),
602                        open,
603                        record_depth::AWS_LC_AEAD,
604                    );
605                }
606                for algorithm in [
607                    crate::HmacAlgorithm::Sha1,
608                    crate::HmacAlgorithm::Sha256,
609                    crate::HmacAlgorithm::Sha384,
610                ] {
611                    let mut mac = crate::RTCCryptoProvider::crypto(&provider)
612                        .new_hmac(algorithm, &[0x24; 20])
613                        .expect("an HMAC");
614                    let data = vec![0x55u8; 1200];
615                    let mut out = vec![0u8; algorithm.output_len()];
616                    let depth = depth_of(|| mac.sign(&[&data], &mut out).expect("signed"));
617                    assert_within(
618                        &mut short,
619                        &format!("aws-lc-rs HMAC {algorithm:?}"),
620                        depth,
621                        record_depth::AWS_LC_HMAC,
622                    );
623                }
624                for algorithm in [
625                    crate::HeaderMaskAlgorithm::Aes128,
626                    crate::HeaderMaskAlgorithm::Aes256,
627                    crate::HeaderMaskAlgorithm::ChaCha20,
628                ] {
629                    let mut mask = crate::RTCCryptoProvider::crypto(&provider)
630                        .new_header_mask(algorithm, &[0x61; 32][..algorithm.key_len()])
631                        .expect("a header mask");
632                    let sample = [0x17u8; crate::HEADER_MASK_SAMPLE_LEN];
633                    let depth = depth_of(|| {
634                        std::hint::black_box(mask.mask(&sample).expect("a mask"));
635                    });
636                    assert_within(
637                        &mut short,
638                        &format!("aws-lc-rs header mask {algorithm:?}"),
639                        depth,
640                        record_depth::AWS_LC_HEADER_MASK,
641                    );
642                }
643                for algorithm in [
644                    crate::AeadAlgorithm::Aes128Ccm,
645                    crate::AeadAlgorithm::Aes128Ccm8,
646                ] {
647                    let (seal, open) = aead_depths(&provider, algorithm);
648                    assert_within(
649                        &mut short,
650                        &format!("aws-lc-rs {algorithm:?} seal"),
651                        seal,
652                        record_depth::CCM,
653                    );
654                    assert_within(
655                        &mut short,
656                        &format!("aws-lc-rs {algorithm:?} open"),
657                        open,
658                        record_depth::CCM,
659                    );
660                }
661            }
662            // RustCrypto's AES record operations (either provider builds them), measured on this
663            // CPU: the hardware or the portable code, whichever `aes` chooses here.
664            {
665                let provider = crate::default_provider().expect("a provider");
666                let crypto = provider.crypto();
667                let mut ctr = crypto
668                    .new_stream_cipher(crate::StreamCipherAlgorithm::Aes128Ctr, &[0x24; 16])
669                    .expect("an AES-CTR cipher");
670                let mut data = vec![0x11u8; 1200];
671                let depth = depth_of(|| ctr.apply_keystream(&[0; 16], &mut data).expect("applied"));
672                assert_within(
673                    &mut short,
674                    "RustCrypto AES-128-CTR",
675                    depth,
676                    record_depth::RUSTCRYPTO_AES_PORTABLE,
677                );
678                let mut cbc = crypto
679                    .new_cbc(crate::CbcAlgorithm::Aes256Cbc, &[0x25; 32])
680                    .expect("an AES-CBC cipher");
681                let mut blocks = vec![0x12u8; 1024];
682                let depth = depth_of(|| {
683                    cbc.encrypt_blocks(&[0; 16], &mut blocks)
684                        .expect("encrypted")
685                });
686                assert_within(
687                    &mut short,
688                    "RustCrypto AES-256-CBC encrypt",
689                    depth,
690                    record_depth::RUSTCRYPTO_AES_PORTABLE,
691                );
692                let depth = depth_of(|| {
693                    cbc.decrypt_blocks(&[0; 16], &mut blocks)
694                        .expect("decrypted")
695                });
696                assert_within(
697                    &mut short,
698                    "RustCrypto AES-256-CBC decrypt",
699                    depth,
700                    record_depth::RUSTCRYPTO_AES_PORTABLE,
701                );
702                for algorithm in [
703                    crate::BlockCipherAlgorithm::Aes128,
704                    crate::BlockCipherAlgorithm::Aes192,
705                    crate::BlockCipherAlgorithm::Aes256,
706                ] {
707                    let key = [0x27u8; 32];
708                    let len = block_key_len(algorithm);
709                    let mut block = [0x14u8; 16];
710                    let depth = depth_of(|| {
711                        crate::common::block_encrypt_work(algorithm, &key[..len], &mut block)
712                            .expect("a block");
713                    });
714                    assert_within(
715                        &mut short,
716                        &format!("RustCrypto {algorithm:?} key set-up and block (key derivation)"),
717                        depth,
718                        record_depth::RUSTCRYPTO_AES_KEY_SETUP,
719                    );
720                }
721            }
722            #[cfg(feature = "crypto-ring")]
723            {
724                let provider = crate::providers::RingProvider::new();
725                let mut mac = crate::RTCCryptoProvider::crypto(&provider)
726                    .new_hmac(crate::HmacAlgorithm::Sha1, &[0x26; 20])
727                    .expect("an HMAC-SHA1");
728                let data = vec![0x13u8; 1200];
729                let mut out = [0u8; 20];
730                let depth = depth_of(|| mac.sign(&[&data], &mut out).expect("signed"));
731                assert_within(
732                    &mut short,
733                    "ring provider HMAC-SHA1 (RustCrypto)",
734                    depth,
735                    record_depth::RUSTCRYPTO_SHA1_PORTABLE,
736                );
737                drop(mac);
738                let (seal, open) = aead_depths(&provider, crate::AeadAlgorithm::ChaCha20Poly1305);
739                assert_within(
740                    &mut short,
741                    "ring ChaCha20Poly1305 seal",
742                    seal,
743                    record_depth::RING_CHACHA20,
744                );
745                assert_within(
746                    &mut short,
747                    "ring ChaCha20Poly1305 open",
748                    open,
749                    record_depth::RING_CHACHA20,
750                );
751                for algorithm in [
752                    crate::AeadAlgorithm::Aes128Gcm,
753                    crate::AeadAlgorithm::Aes256Gcm,
754                ] {
755                    let (seal, open) = aead_depths(&provider, algorithm);
756                    assert_within(
757                        &mut short,
758                        &format!("ring {algorithm:?} seal"),
759                        seal,
760                        record_depth::RING_AES_GCM_PORTABLE,
761                    );
762                    assert_within(
763                        &mut short,
764                        &format!("ring {algorithm:?} open"),
765                        open,
766                        record_depth::RING_AES_GCM_PORTABLE,
767                    );
768                }
769                for algorithm in [
770                    crate::AeadAlgorithm::Aes128Ccm,
771                    crate::AeadAlgorithm::Aes128Ccm8,
772                ] {
773                    let (seal, open) = aead_depths(&provider, algorithm);
774                    assert_within(
775                        &mut short,
776                        &format!("ring {algorithm:?} seal"),
777                        seal,
778                        record_depth::CCM,
779                    );
780                    assert_within(
781                        &mut short,
782                        &format!("ring {algorithm:?} open"),
783                        open,
784                        record_depth::CCM,
785                    );
786                }
787            }
788            assert!(
789                short.is_empty(),
790                "record paths that write more stack below their caller than their overwrite \
791                 covers less a 512-byte margin (raise `record_depth`): {short:#?}"
792            );
793        });
794        set_record_stack_erasure(true);
795        if let Err(panic) = result {
796            std::panic::resume_unwind(panic);
797        }
798    }
799
800    /// The probe sees what a call writes: a call that writes 6 KiB of stack measures at least
801    /// 6 KiB, and one that writes nothing below its frame measures less than 1 KiB.
802    #[test]
803    fn the_probe_measures_what_a_call_writes() {
804        #[inline(never)]
805        fn writes_6k() {
806            let mut area = [0u8; 6 * 1024];
807            for byte in area.iter_mut() {
808                // SAFETY: a valid, aligned, exclusive reference into `area`.
809                unsafe { std::ptr::write_volatile(byte, 1) };
810            }
811            std::hint::black_box(&mut area);
812        }
813        let deep = depth_of(writes_6k);
814        let shallow = depth_of(|| {
815            std::hint::black_box(1 + 1);
816        });
817        println!("PROBE CONTROL: 6 KiB call {deep} bytes, empty call {shallow} bytes");
818        assert!(deep >= 6 * 1024, "{deep}");
819        assert!(shallow < 1024, "{shallow}");
820    }
821}