rtci-crypto 0.5.0

Provider-neutral cryptography interface of a sans-I/O WebRTC stack, with ring and aws-lc-rs providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};

use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

/// An owned byte vector that zeroizes its allocation when dropped.
///
/// The whole allocation is overwritten, spare capacity included. A `SecretVec` never grows: a
/// buffer that does (`Vec::extend`, `push`) moves to a new allocation and leaves the old one
/// behind unerased, so build key material in a buffer sized up front and wrap it here.
pub struct SecretVec(Zeroizing<Vec<u8>>);

impl Zeroize for SecretVec {
    fn zeroize(&mut self) {
        self.0.zeroize();
    }
}

impl ZeroizeOnDrop for SecretVec {}

impl SecretVec {
    /// Wraps secret bytes.
    #[must_use]
    pub fn new(bytes: Vec<u8>) -> Self {
        Self(Zeroizing::new(bytes))
    }

    /// Returns the number of secret bytes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the secret is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Explicitly unwraps the secret bytes. The returned vector is no longer automatically zeroized.
    #[must_use]
    pub fn into_bytes(mut self) -> Vec<u8> {
        std::mem::take(&mut *self.0)
    }
}

impl AsRef<[u8]> for SecretVec {
    fn as_ref(&self) -> &[u8] {
        self.0.as_slice()
    }
}

impl AsMut<[u8]> for SecretVec {
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut_slice()
    }
}

impl Clone for SecretVec {
    fn clone(&self) -> Self {
        Self::new(self.as_ref().to_vec())
    }
}

impl fmt::Debug for SecretVec {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SecretVec")
            .field("len", &self.len())
            .field("bytes", &"[REDACTED]")
            .finish()
    }
}

impl From<Vec<u8>> for SecretVec {
    fn from(value: Vec<u8>) -> Self {
        Self::new(value)
    }
}

/// How much stack [`scrub_stack`] overwrites: 32 KiB in an optimised build, 128 KiB in an
/// unoptimised one (`debug_assertions`, which Cargo's `dev` and `test` profiles turn on with
/// opt-level 0).
///
/// The depth has to cover the stack the work before it used. Building an SRTP context uses
/// about 3 KiB in an optimised build and 42 to 47 KiB in an unoptimised one, where every
/// temporary has a stack slot of its own (`rtci-srtp/tests/key_residue.rs`, measured with a
/// 32 KiB overwrite): the AES key schedules built for the key derivation are the deepest
/// part, below frames such as
/// `common::block_encrypt`'s, which holds a cipher object of every AES key length. With rustc
/// 1.99.1 (x86-64 Linux) the master key and its round keys were left 37.7 to 42.2 KB below the
/// point the measurement starts from, more than 32 KiB below the context's `on_erased_stack`
/// frame (which lies less than 4.9 KB below that point), out of a 32 KiB overwrite's reach.
/// 128 KiB is the deepest unoptimised use measured (47 KiB) times 2.7, for other compilers and
/// profiles. The optimised depth is unchanged, and so is an optimised build's cost.
const SCRUB_STACK_BYTES: usize = if cfg!(debug_assertions) {
    128 * 1024
} else {
    32 * 1024
};

/// Overwrites the stack below the caller's frame (32 KiB of it in an optimised build, 128 KiB in
/// an unoptimised one).
///
/// Building a keyed object leaves copies of the key and its schedule in the stack frames of
/// the functions that built it: a value moved out of a frame is not dropped there, so its
/// zeroize-on-drop never runs on the copy left behind, and a provider's own temporaries are
/// not erased at all. Those dead frames are reused by later calls, and a value later built
/// there and moved into the heap (into a `Box`, a `Vec`) carries whatever was in its padding
/// or in the unused part of an enum or union along: the key ends up in memory the heap frees
/// without erasure. Calling this right after a key schedule is built and moved to where it
/// lives, from the frame that called the provider, overwrites what the deeper frames left.
///
/// What it does: one bulk zero fill (`ptr::write_bytes`, a `memset`) of a buffer of that size
/// in its own frame, which is never inlined, so the buffer lies in the stack just below the
/// caller's frame, where the frames of the calls the caller made before lay. The buffer is
/// then handed to [`std::hint::black_box`] and followed by a compiler fence, so the compiler
/// cannot treat the fill as a dead store and drop it. The calling thread needs that much stack
/// free below the caller.
///
/// What it does not do: it cannot reach registers, the caller's own frame or any frame above
/// it, other threads' stacks, or anything deeper than that size below the caller (a build
/// profile with opt-level 0 and `debug-assertions = false` gets the optimised depth); and
/// copies the compiler or a provider leaves that no test can see are not observed, so their
/// absence is not guaranteed. The tests show only that copies carried from dead frames into heap padding
/// are gone (`tests/dtls_secret_erasure.rs`; docs/key-erasure.md).
#[inline(never)]
pub fn scrub_stack() {
    let mut area = std::mem::MaybeUninit::<[u8; SCRUB_STACK_BYTES]>::uninit();
    // SAFETY: the pointer is to a local buffer of exactly `SCRUB_STACK_BYTES` bytes, written
    // as bytes (any value is valid for `u8`) and never read as anything else.
    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_STACK_BYTES) };
    // The buffer is never read: without this the fill is a dead store the optimiser may remove.
    std::hint::black_box(&mut area);
    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}

/// How much stack [`scrub_record_stack`] overwrites: 48 KiB, in an unoptimised build only.
///
/// The deepest record-key form measured in an unoptimised build lay 31,288 bytes below the
/// DTLS key residue measurement's floor (rustc 1.89, the AES-CCM records step,
/// `rtci-dtls/tests/key_residue.rs`, run 46015302538). Every record call's own frame lies below
/// that floor, so what the record work leaves lies less than that below the call. 48 KiB is
/// that depth times 1.5, for other compilers and call paths; it is paid in unoptimised builds
/// only.
#[cfg(debug_assertions)]
const SCRUB_RECORD_STACK_BYTES: usize = 48 * 1024;

/// Overwrites the stack below the caller's frame after one record's work with RustCrypto's AES,
/// in an unoptimised build (`debug_assertions`); in an optimised build it is not compiled.
///
/// At opt-level 0 the AES-NI intrinsics of the `aes` crate are calls whose vector arguments go
/// through stack copies, so every block encrypted or decrypted leaves round keys (round key 0
/// is the key) and AES states in stack temporaries; an optimised build keeps them in registers.
/// Measured: on Windows a DTLS 1.2 AES-CCM write key left there was carried into a freed heap
/// block by the unwritten bytes of a handshake message moved into a map (docs/key-erasure.md);
/// with the `aes` and `ccm` crates optimised, with the portable AES, in an optimised build, or
/// with an overwrite after each AES-CCM call, it was not (runs 46026969169, 46026978042).
#[cfg(debug_assertions)]
#[inline(never)]
pub(crate) fn scrub_record_stack() {
    let mut area = std::mem::MaybeUninit::<[u8; SCRUB_RECORD_STACK_BYTES]>::uninit();
    // SAFETY: the pointer is to a local buffer of exactly `SCRUB_RECORD_STACK_BYTES` bytes,
    // written as bytes and never read as anything else.
    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_RECORD_STACK_BYTES) };
    std::hint::black_box(&mut area);
    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}

/// Whether the record paths whose provider leaves key copies in its own stack frames overwrite
/// the stack after each record ([`set_record_stack_erasure`]). On unless turned off.
static RECORD_STACK_ERASURE: AtomicBool = AtomicBool::new(true);

/// Turns on or off, for the whole process, the stack overwrite after each record operation of
/// the paths that leave key copies in dead stack frames of code the crate cannot change: the
/// AWS-LC provider's AEAD (its AES-GCM leaves a GHASH table entry) and HMAC (each MAC is
/// computed on a copy of the keyed context, HMAC-SHA1 for SRTP and the DTLS AES-CBC suites);
/// the ring provider's ChaCha20-Poly1305 (the key is copied to the stack per record); and
/// AES-CCM (RustCrypto's `aes` under `ccm`, which left round keys with compilers older than
/// rustc 1.99.1 in an optimised build). Each such call then runs in a frame of its own and the
/// stack below it is overwritten afterwards, as deep as that path was measured to use
/// (`record_depth`: a few KiB optimised; 128 KiB unoptimised), so no key is left in a dead stack frame
/// (RFC 7714 section 13.1: "All keys MUST be properly erased when no longer needed";
/// `rtci-srtp/tests/key_residue.rs`, `rtci-dtls/tests/key_residue.rs`). On by default.
///
/// Off, those copies stay until later calls on the same thread overwrite them, and an
/// application that cares calls [`scrub_stack`] from that thread when a session ends. The
/// cost is one overwrite per record on those paths only (docs/performance.md); ring's AES-GCM,
/// RustCrypto's AES-CTR and AES-CBC and the ring provider's HMAC were measured to leave nothing
/// and are not affected.
pub fn set_record_stack_erasure(enabled: bool) {
    RECORD_STACK_ERASURE.store(enabled, Ordering::Relaxed);
}

/// Whether the stack overwrite after each record of [`set_record_stack_erasure`] is on.
#[must_use]
pub fn record_stack_erasure() -> bool {
    RECORD_STACK_ERASURE.load(Ordering::Relaxed)
}

/// How much stack one record call of each covered path dirties below the call, at most, in an
/// optimised build, and so how much is overwritten after it. Measured by
/// `record_stack_depth_tests` (a high-water probe: the stack below is filled with a marker,
/// the provider call is made, and the lowest byte it changed is found), which fails when a
/// path dirties more than its depth here less a 512-byte margin (every path is measured and
/// printed before it fails, naming each that is too shallow); the residue measurements
/// (`rtci-srtp/tests/key_residue.rs`, `rtci-dtls/tests/key_residue.rs`) assert the result. An
/// unoptimised build overwrites [`SCRUB_STACK_BYTES`] (128 KiB): its frames are many times
/// larger and nobody benchmarks it. A 32 KiB overwrite per record cost about 350 ns (bench
/// run 46281647380); a few KiB cost tens.
pub(crate) mod record_depth {
    const fn optimised(bytes: usize) -> usize {
        if cfg!(debug_assertions) {
            super::SCRUB_STACK_BYTES
        } else {
            bytes
        }
    }
    /// The AWS-LC provider's AEAD (AES-GCM, ChaCha20-Poly1305) seal and open: measured at most
    /// 2,752 bytes (AES-GCM seal, x86-64 Linux) and 1,160 (AArch64 macOS) on the hardware paths,
    /// and 4,112 (AES-GCM seal) on its portable path (an emulated CPU without SSSE3, AES-NI or
    /// CLMUL, run 46318613275), so 5 KiB.
    #[cfg(feature = "crypto-aws-lc-rs")]
    pub(crate) const AWS_LC_AEAD: usize = optimised(5 * 1024);
    /// The AWS-LC provider's HMAC (SHA-1, SHA-256, SHA-384, SHA-512): measured 5,256 bytes on
    /// x86-64 Linux and 5,304 on AArch64 macOS for HMAC-SHA1 (probe runs 46285590132,
    /// 46285596360), so 8 KiB.
    #[cfg(feature = "crypto-aws-lc-rs")]
    pub(crate) const AWS_LC_HMAC: usize = optimised(8 * 1024);
    /// The AWS-LC provider's DTLS 1.3 record-number mask (AES-ECB or a ChaCha20 block of the
    /// record-number key), once per record.
    #[cfg(feature = "crypto-aws-lc-rs")]
    pub(crate) const AWS_LC_HEADER_MASK: usize = optimised(4 * 1024);
    /// The ring provider's ChaCha20-Poly1305 seal and open.
    #[cfg(feature = "crypto-ring")]
    pub(crate) const RING_CHACHA20: usize = optimised(4 * 1024);
    /// The ring provider's AES-GCM seal and open on its portable path (vpaes or no-hardware
    /// AES, fallback GHASH; `providers::ring::ring_aes_gcm_hardware`). The same code in AWS-LC
    /// was measured at 4,112 bytes (AES-GCM seal, qemu64); the probe below measures ring's.
    #[cfg(feature = "crypto-ring")]
    pub(crate) const RING_AES_GCM_PORTABLE: usize = optimised(6 * 1024);
    /// RustCrypto's AES record operations (AES-CTR for SRTP AES-CM, AES-CBC) on a CPU without
    /// AES hardware, where `aes` runs its portable fixsliced code
    /// ([`super::rustcrypto_aes_hardware`]).
    #[cfg_attr(debug_assertions, allow(dead_code))]
    pub(crate) const RUSTCRYPTO_AES_PORTABLE: usize = optimised(4 * 1024);
    /// RustCrypto's AES key set-up and one block (the SRTP key derivation over the master key,
    /// `common::block_encrypt`) on a CPU without AES hardware: overwritten in every build,
    /// whatever the record setting. Measured by the probe below for AES-128, -192 and -256: at
    /// most 5,240 bytes on CPUs without AES hardware (emulated Nehalem and qemu64, run
    /// 46339769787: 4,968 / 5,240 / 5,224), less with `--cfg aes_force_soft` on AES hardware;
    /// 8 KiB is that depth times 1.5.
    pub(crate) const RUSTCRYPTO_AES_KEY_SETUP: usize = optimised(8 * 1024);
    /// The ring provider's HMAC-SHA1 (RustCrypto `hmac` / `sha1`) on a CPU without SHA
    /// instructions, where `sha1` runs its portable code ([`super::rustcrypto_sha1_hardware`]).
    #[cfg(feature = "crypto-ring")]
    pub(crate) const RUSTCRYPTO_SHA1_PORTABLE: usize = optimised(4 * 1024);
    /// AES-CCM (RustCrypto's `aes` under `ccm`), either provider.
    pub(crate) const CCM: usize = optimised(4 * 1024);
}

/// Whether RustCrypto's `aes` uses AES hardware on this CPU, by the test it makes itself
/// (aes 0.8.4: `cpufeatures::new!(aes_intrinsics, "aes")` on x86 / x86-64; on AArch64 only when
/// built with `--cfg aes_armv8`, then the `aes` feature). Without it `aes` runs its portable,
/// fixsliced code, which leaves key schedule copies in stack frames (the portable pass of
/// `rtci-srtp/tests/key_residue.rs`); the record operations are then followed by an overwrite.
///
/// Built with `--cfg aes_force_soft` (a CI step of its own), `aes` runs its portable code on any
/// CPU, and this says so.
pub(crate) fn rustcrypto_aes_hardware() -> bool {
    if cfg!(aes_force_soft) {
        return false;
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        std::arch::is_x86_feature_detected!("aes")
    }
    #[cfg(target_arch = "aarch64")]
    {
        cfg!(aes_armv8) && std::arch::is_aarch64_feature_detected!("aes")
    }
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
    {
        false
    }
}

/// Whether RustCrypto's `sha1` uses SHA hardware on this CPU, by its own test (sha1 0.11:
/// `cpufeatures::new!(shani_cpuid, "sha", "sse2", "ssse3", "sse4.1")` on x86 / x86-64,
/// `cpufeatures::new!(sha2_hwcap, "sha2")` on AArch64).
#[cfg(feature = "crypto-ring")]
pub(crate) fn rustcrypto_sha1_hardware() -> bool {
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        std::arch::is_x86_feature_detected!("sha")
            && std::arch::is_x86_feature_detected!("sse2")
            && std::arch::is_x86_feature_detected!("ssse3")
            && std::arch::is_x86_feature_detected!("sse4.1")
    }
    #[cfg(target_arch = "aarch64")]
    {
        std::arch::is_aarch64_feature_detected!("sha2")
    }
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
    {
        false
    }
}

/// Overwrites `N` bytes of stack below the caller's frame: [`scrub_stack`] of a given depth.
/// One bulk fill (`ptr::write_bytes`, a `memset`), then [`std::hint::black_box`] and a
/// compiler fence so the optimiser cannot drop it as a dead store.
#[inline(never)]
pub(crate) fn scrub_stack_bytes<const N: usize>() {
    let mut area = std::mem::MaybeUninit::<[u8; N]>::uninit();
    // SAFETY: the pointer is to a local buffer of exactly `N` bytes, written as bytes and
    // never read as anything else.
    unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, N) };
    std::hint::black_box(&mut area);
    std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}

/// One record operation of a path [`set_record_stack_erasure`] covers: while the setting is on,
/// run in a frame of its own and then `DEPTH` bytes of stack below are overwritten (the
/// path's [`record_depth`]); as it is otherwise.
#[inline(always)]
pub(crate) fn erased_record_call<const DEPTH: usize, R>(work: impl FnOnce() -> R) -> R {
    #[inline(never)]
    fn own_frame<R>(work: impl FnOnce() -> R) -> R {
        work()
    }
    if record_stack_erasure() {
        let value = own_frame(work);
        scrub_stack_bytes::<DEPTH>();
        value
    } else {
        work()
    }
}

#[cfg(test)]
mod record_stack_erasure_tests {
    use super::*;
    use std::sync::Mutex;

    /// The setting is process-wide: the tests that change it run one at a time.
    static SETTING: Mutex<()> = Mutex::new(());

    /// On by default; the setting turns it off and on again, and a record call returns its
    /// work's value either way.
    #[test]
    fn the_record_stack_erasure_is_on_by_default_and_can_be_turned_off() {
        let _setting = SETTING.lock().unwrap_or_else(|e| e.into_inner());
        assert!(record_stack_erasure(), "on by default");
        set_record_stack_erasure(false);
        assert!(!record_stack_erasure());
        assert_eq!(erased_record_call::<64, _>(|| 7), 7);
        set_record_stack_erasure(true);
        assert!(record_stack_erasure());
        assert_eq!(erased_record_call::<64, _>(|| 8), 8);
    }

    const PROBE_BYTES: usize = 64 * 1024;
    const MARK: u8 = 0xa5;

    /// Fills `PROBE_BYTES` of stack just below the caller's frame with `MARK`, byte by byte with
    /// volatile writes, and returns where that area lies.
    #[inline(never)]
    fn fill_below() -> (usize, usize) {
        let mut area = [0u8; PROBE_BYTES];
        for byte in area.iter_mut() {
            // SAFETY: `byte` is a valid, aligned, exclusive reference into `area`.
            unsafe { std::ptr::write_volatile(byte, MARK) };
        }
        let start = area.as_ptr() as usize;
        std::hint::black_box(&mut area);
        (start, start + PROBE_BYTES)
    }

    #[inline(never)]
    fn call(work: &mut dyn FnMut()) {
        work();
    }

    /// How deep below its caller one call of `work` writes the stack: the area below is filled
    /// with a marker, `work` is called from a frame at the same depth, and the lowest byte that
    /// no longer holds the marker is found. `work` runs once before, so that one-time set-up
    /// (CPU feature detection, lazy tables) is not counted.
    #[inline(never)]
    fn depth_of(mut work: impl FnMut()) -> usize {
        work();
        let (start, end) = fill_below();
        call(&mut work);
        let mut lowest = end;
        for address in start..end {
            // SAFETY: `start..end` is stack this thread owns below the current frame (the area
            // `fill_below` filled, beyond every live frame now); it is read, never written.
            let byte = unsafe { std::ptr::read_volatile(address as *const u8) };
            if byte != MARK {
                lowest = address;
                break;
            }
        }
        end - lowest
    }

    /// Records `path`'s measured depth against its overwrite and prints it; a path that does
    /// not fit with a 512-byte margin is added to `short`.
    fn assert_within(short: &mut Vec<String>, path: &str, depth: usize, overwrite: usize) {
        let fits = depth < PROBE_BYTES && depth + 512 <= overwrite;
        println!(
            "RECORD DEPTH {path}: {depth} bytes (overwrite {overwrite}){}",
            if fits { "" } else { " TOO SHALLOW" }
        );
        if !fits {
            short.push(format!("{path}: {depth} bytes, overwrite {overwrite}"));
        }
    }

    fn block_key_len(algorithm: crate::BlockCipherAlgorithm) -> usize {
        match algorithm {
            crate::BlockCipherAlgorithm::Aes128 => 16,
            crate::BlockCipherAlgorithm::Aes192 => 24,
            crate::BlockCipherAlgorithm::Aes256 => 32,
        }
    }

    /// The 64-byte blocks (whole round keys) of RustCrypto's portable (fixsliced) schedule of
    /// `key`, as the cipher object holds it: each block with at least four distinct byte values,
    /// not made of 0x00 and 0xff alone. (`rtci-srtp/tests/portable_aes` uses pairs of round
    /// keys for AES-192 and AES-256, so that a needle identifies its key among others; here only
    /// this one key's schedule is looked for, in a stack area that holds no other.) Only on the
    /// portable path, where that schedule is the object's whole content.
    fn fixsliced_blocks(key: &[u8]) -> Vec<[u8; 64]> {
        use aes::cipher::KeyInit;
        fn blocks<T>(value: &T) -> Vec<[u8; 64]> {
            // SAFETY: only on the portable path (`rustcrypto_aes_hardware()` false): `aes` then
            // holds its fixsliced schedule, written in full (the larger arm of its union, or the
            // whole type under `aes_force_soft`); read as bytes only.
            let bytes = unsafe {
                std::slice::from_raw_parts((value as *const T).cast::<u8>(), size_of::<T>())
            };
            bytes
                .as_chunks::<64>()
                .0
                .iter()
                .filter(|block| {
                    let mut seen = [false; 256];
                    for &b in block.iter() {
                        seen[usize::from(b)] = true;
                    }
                    seen.iter().filter(|&&s| s).count() >= 4
                        && !block.iter().all(|&b| b == 0 || b == 0xff)
                })
                .copied()
                .collect()
        }
        match key.len() {
            16 => blocks(&aes::Aes128::new_from_slice(key).expect("a key")),
            24 => blocks(&aes::Aes192::new_from_slice(key).expect("a key")),
            32 => blocks(&aes::Aes256::new_from_slice(key).expect("a key")),
            n => panic!("an AES key of {n} bytes"),
        }
    }

    /// The SRTP key derivation's AES (`common::block_encrypt`, whose key is the master key)
    /// leaves no copy of the key's schedule in the dead stack frames below it on the portable
    /// path (a CPU without AES hardware, or `--cfg aes_force_soft`): the frames are searched
    /// for the fixsliced schedule's blocks after one call. The same call without the overwrite
    /// (`block_encrypt_work`) must leave some, so the search is shown to see them. The portable
    /// pass of `rtci-srtp/tests/key_residue.rs` found that schedule carried from such frames into
    /// a live ring AES-GCM key object (run 46330510022). On AES hardware the test says so and
    /// passes.
    #[test]
    fn key_derivation_leaves_no_key_schedule_in_dead_stack_frames() {
        if rustcrypto_aes_hardware() {
            println!("KEY SETUP: RustCrypto's aes uses AES hardware here: no portable schedule");
            return;
        }
        for algorithm in [
            crate::BlockCipherAlgorithm::Aes128,
            crate::BlockCipherAlgorithm::Aes192,
            crate::BlockCipherAlgorithm::Aes256,
        ] {
            let len = block_key_len(algorithm);
            let key: Vec<u8> = (0..len as u8)
                .map(|b| b.wrapping_mul(53).wrapping_add(len as u8) ^ 0x3c)
                .collect();
            let needles = fixsliced_blocks(&key);
            assert!(
                needles.len() >= 8,
                "{algorithm:?}: only {} fixsliced blocks modelled",
                needles.len()
            );
            let mut snapshot = vec![0u8; PROBE_BYTES];
            let mut left = |erased: bool| -> usize {
                let (start, end) = fill_below();
                call(&mut || {
                    let mut block = [0x15u8; 16];
                    let done = if erased {
                        crate::common::block_encrypt(algorithm, &key, &mut block)
                    } else {
                        crate::common::block_encrypt_work(algorithm, &key, &mut block)
                    };
                    done.expect("a block");
                    std::hint::black_box(&block);
                });
                // Copied out without a call, so no frame overwrites the area before it is read.
                for (i, slot) in snapshot.iter_mut().enumerate().take(end - start) {
                    // SAFETY: `start..end` is stack this thread owns below the current frame
                    // (the area `fill_below` filled); read, never written.
                    *slot = unsafe { std::ptr::read_volatile((start + i) as *const u8) };
                }
                needles
                    .iter()
                    .filter(|n| snapshot.windows(64).any(|w| w == &n[..]))
                    .count()
            };
            let without = left(false);
            let with = left(true);
            println!(
                "KEY SETUP {algorithm:?}: {without} of {} schedule blocks left without the \
                 overwrite, {with} with it",
                needles.len()
            );
            assert!(
                without > 0,
                "{algorithm:?}: without the overwrite the search found no schedule block: it does \
                 not see what the portable code leaves"
            );
            assert_eq!(
                with, 0,
                "{algorithm:?}: the key derivation left its key's schedule in dead stack frames"
            );
        }
    }

    fn aead_key_len(algorithm: crate::AeadAlgorithm) -> usize {
        match algorithm {
            crate::AeadAlgorithm::Aes256Gcm | crate::AeadAlgorithm::ChaCha20Poly1305 => 32,
            _ => 16,
        }
    }

    fn aead_depths(
        provider: &dyn crate::RTCCryptoProvider,
        algorithm: crate::AeadAlgorithm,
    ) -> (usize, usize) {
        let mut aead = provider
            .crypto()
            .new_aead(algorithm, &[0x42; 32][..aead_key_len(algorithm)])
            .expect("an AEAD");
        let tag_len = aead.tag_len();
        let nonce = [7u8; 12];
        let mut data = vec![0x33u8; 1200];
        let mut tag = vec![0u8; tag_len];
        let seal = depth_of(|| {
            aead.seal_in_place(&nonce, b"header", &mut data, &mut tag)
                .expect("sealed");
        });
        let mut sealed = vec![0x33u8; 1200];
        let mut sealed_tag = vec![0u8; tag_len];
        aead.seal_in_place(&nonce, b"header", &mut sealed, &mut sealed_tag)
            .expect("sealed");
        let open = depth_of(|| {
            let mut copy = sealed.clone();
            aead.open_in_place(&nonce, b"header", &mut copy, &sealed_tag)
                .expect("opened");
        });
        (seal, open)
    }

    /// The high-water probe behind `record_depth`: for each path the record overwrite covers,
    /// with the overwrite itself off, how deep one record call dirties the stack. Each must fit
    /// the path's overwrite with a 512-byte margin; the depths are printed (`RECORD DEPTH`).
    /// Meaningful in an optimised build (`cargo test --release`), where `record_depth` is small;
    /// an unoptimised build overwrites 128 KiB and passes trivially.
    #[test]
    fn each_record_path_dirties_no_more_stack_than_its_overwrite() {
        let _setting = SETTING.lock().unwrap_or_else(|e| e.into_inner());
        set_record_stack_erasure(false);
        let result = std::panic::catch_unwind(|| {
            let mut short = Vec::new();
            #[cfg(feature = "crypto-aws-lc-rs")]
            {
                let provider = crate::providers::AwsLcRsProvider::new();
                for algorithm in [
                    crate::AeadAlgorithm::Aes128Gcm,
                    crate::AeadAlgorithm::Aes256Gcm,
                    crate::AeadAlgorithm::ChaCha20Poly1305,
                ] {
                    let (seal, open) = aead_depths(&provider, algorithm);
                    assert_within(
                        &mut short,
                        &format!("aws-lc-rs {algorithm:?} seal"),
                        seal,
                        record_depth::AWS_LC_AEAD,
                    );
                    assert_within(
                        &mut short,
                        &format!("aws-lc-rs {algorithm:?} open"),
                        open,
                        record_depth::AWS_LC_AEAD,
                    );
                }
                for algorithm in [
                    crate::HmacAlgorithm::Sha1,
                    crate::HmacAlgorithm::Sha256,
                    crate::HmacAlgorithm::Sha384,
                ] {
                    let mut mac = crate::RTCCryptoProvider::crypto(&provider)
                        .new_hmac(algorithm, &[0x24; 20])
                        .expect("an HMAC");
                    let data = vec![0x55u8; 1200];
                    let mut out = vec![0u8; algorithm.output_len()];
                    let depth = depth_of(|| mac.sign(&[&data], &mut out).expect("signed"));
                    assert_within(
                        &mut short,
                        &format!("aws-lc-rs HMAC {algorithm:?}"),
                        depth,
                        record_depth::AWS_LC_HMAC,
                    );
                }
                for algorithm in [
                    crate::HeaderMaskAlgorithm::Aes128,
                    crate::HeaderMaskAlgorithm::Aes256,
                    crate::HeaderMaskAlgorithm::ChaCha20,
                ] {
                    let mut mask = crate::RTCCryptoProvider::crypto(&provider)
                        .new_header_mask(algorithm, &[0x61; 32][..algorithm.key_len()])
                        .expect("a header mask");
                    let sample = [0x17u8; crate::HEADER_MASK_SAMPLE_LEN];
                    let depth = depth_of(|| {
                        std::hint::black_box(mask.mask(&sample).expect("a mask"));
                    });
                    assert_within(
                        &mut short,
                        &format!("aws-lc-rs header mask {algorithm:?}"),
                        depth,
                        record_depth::AWS_LC_HEADER_MASK,
                    );
                }
                for algorithm in [
                    crate::AeadAlgorithm::Aes128Ccm,
                    crate::AeadAlgorithm::Aes128Ccm8,
                ] {
                    let (seal, open) = aead_depths(&provider, algorithm);
                    assert_within(
                        &mut short,
                        &format!("aws-lc-rs {algorithm:?} seal"),
                        seal,
                        record_depth::CCM,
                    );
                    assert_within(
                        &mut short,
                        &format!("aws-lc-rs {algorithm:?} open"),
                        open,
                        record_depth::CCM,
                    );
                }
            }
            // RustCrypto's AES record operations (either provider builds them), measured on this
            // CPU: the hardware or the portable code, whichever `aes` chooses here.
            {
                let provider = crate::default_provider().expect("a provider");
                let crypto = provider.crypto();
                let mut ctr = crypto
                    .new_stream_cipher(crate::StreamCipherAlgorithm::Aes128Ctr, &[0x24; 16])
                    .expect("an AES-CTR cipher");
                let mut data = vec![0x11u8; 1200];
                let depth = depth_of(|| ctr.apply_keystream(&[0; 16], &mut data).expect("applied"));
                assert_within(
                    &mut short,
                    "RustCrypto AES-128-CTR",
                    depth,
                    record_depth::RUSTCRYPTO_AES_PORTABLE,
                );
                let mut cbc = crypto
                    .new_cbc(crate::CbcAlgorithm::Aes256Cbc, &[0x25; 32])
                    .expect("an AES-CBC cipher");
                let mut blocks = vec![0x12u8; 1024];
                let depth = depth_of(|| {
                    cbc.encrypt_blocks(&[0; 16], &mut blocks)
                        .expect("encrypted")
                });
                assert_within(
                    &mut short,
                    "RustCrypto AES-256-CBC encrypt",
                    depth,
                    record_depth::RUSTCRYPTO_AES_PORTABLE,
                );
                let depth = depth_of(|| {
                    cbc.decrypt_blocks(&[0; 16], &mut blocks)
                        .expect("decrypted")
                });
                assert_within(
                    &mut short,
                    "RustCrypto AES-256-CBC decrypt",
                    depth,
                    record_depth::RUSTCRYPTO_AES_PORTABLE,
                );
                for algorithm in [
                    crate::BlockCipherAlgorithm::Aes128,
                    crate::BlockCipherAlgorithm::Aes192,
                    crate::BlockCipherAlgorithm::Aes256,
                ] {
                    let key = [0x27u8; 32];
                    let len = block_key_len(algorithm);
                    let mut block = [0x14u8; 16];
                    let depth = depth_of(|| {
                        crate::common::block_encrypt_work(algorithm, &key[..len], &mut block)
                            .expect("a block");
                    });
                    assert_within(
                        &mut short,
                        &format!("RustCrypto {algorithm:?} key set-up and block (key derivation)"),
                        depth,
                        record_depth::RUSTCRYPTO_AES_KEY_SETUP,
                    );
                }
            }
            #[cfg(feature = "crypto-ring")]
            {
                let provider = crate::providers::RingProvider::new();
                let mut mac = crate::RTCCryptoProvider::crypto(&provider)
                    .new_hmac(crate::HmacAlgorithm::Sha1, &[0x26; 20])
                    .expect("an HMAC-SHA1");
                let data = vec![0x13u8; 1200];
                let mut out = [0u8; 20];
                let depth = depth_of(|| mac.sign(&[&data], &mut out).expect("signed"));
                assert_within(
                    &mut short,
                    "ring provider HMAC-SHA1 (RustCrypto)",
                    depth,
                    record_depth::RUSTCRYPTO_SHA1_PORTABLE,
                );
                drop(mac);
                let (seal, open) = aead_depths(&provider, crate::AeadAlgorithm::ChaCha20Poly1305);
                assert_within(
                    &mut short,
                    "ring ChaCha20Poly1305 seal",
                    seal,
                    record_depth::RING_CHACHA20,
                );
                assert_within(
                    &mut short,
                    "ring ChaCha20Poly1305 open",
                    open,
                    record_depth::RING_CHACHA20,
                );
                for algorithm in [
                    crate::AeadAlgorithm::Aes128Gcm,
                    crate::AeadAlgorithm::Aes256Gcm,
                ] {
                    let (seal, open) = aead_depths(&provider, algorithm);
                    assert_within(
                        &mut short,
                        &format!("ring {algorithm:?} seal"),
                        seal,
                        record_depth::RING_AES_GCM_PORTABLE,
                    );
                    assert_within(
                        &mut short,
                        &format!("ring {algorithm:?} open"),
                        open,
                        record_depth::RING_AES_GCM_PORTABLE,
                    );
                }
                for algorithm in [
                    crate::AeadAlgorithm::Aes128Ccm,
                    crate::AeadAlgorithm::Aes128Ccm8,
                ] {
                    let (seal, open) = aead_depths(&provider, algorithm);
                    assert_within(
                        &mut short,
                        &format!("ring {algorithm:?} seal"),
                        seal,
                        record_depth::CCM,
                    );
                    assert_within(
                        &mut short,
                        &format!("ring {algorithm:?} open"),
                        open,
                        record_depth::CCM,
                    );
                }
            }
            assert!(
                short.is_empty(),
                "record paths that write more stack below their caller than their overwrite \
                 covers less a 512-byte margin (raise `record_depth`): {short:#?}"
            );
        });
        set_record_stack_erasure(true);
        if let Err(panic) = result {
            std::panic::resume_unwind(panic);
        }
    }

    /// The probe sees what a call writes: a call that writes 6 KiB of stack measures at least
    /// 6 KiB, and one that writes nothing below its frame measures less than 1 KiB.
    #[test]
    fn the_probe_measures_what_a_call_writes() {
        #[inline(never)]
        fn writes_6k() {
            let mut area = [0u8; 6 * 1024];
            for byte in area.iter_mut() {
                // SAFETY: a valid, aligned, exclusive reference into `area`.
                unsafe { std::ptr::write_volatile(byte, 1) };
            }
            std::hint::black_box(&mut area);
        }
        let deep = depth_of(writes_6k);
        let shallow = depth_of(|| {
            std::hint::black_box(1 + 1);
        });
        println!("PROBE CONTROL: 6 KiB call {deep} bytes, empty call {shallow} bytes");
        assert!(deep >= 6 * 1024, "{deep}");
        assert!(shallow < 1024, "{shallow}");
    }
}