use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
pub struct SecretVec(Zeroizing<Vec<u8>>);
impl Zeroize for SecretVec {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
impl ZeroizeOnDrop for SecretVec {}
impl SecretVec {
#[must_use]
pub fn new(bytes: Vec<u8>) -> Self {
Self(Zeroizing::new(bytes))
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[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)
}
}
const SCRUB_STACK_BYTES: usize = if cfg!(debug_assertions) {
128 * 1024
} else {
32 * 1024
};
#[inline(never)]
pub fn scrub_stack() {
let mut area = std::mem::MaybeUninit::<[u8; SCRUB_STACK_BYTES]>::uninit();
unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_STACK_BYTES) };
std::hint::black_box(&mut area);
std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}
#[cfg(debug_assertions)]
const SCRUB_RECORD_STACK_BYTES: usize = 48 * 1024;
#[cfg(debug_assertions)]
#[inline(never)]
pub(crate) fn scrub_record_stack() {
let mut area = std::mem::MaybeUninit::<[u8; SCRUB_RECORD_STACK_BYTES]>::uninit();
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);
}
static RECORD_STACK_ERASURE: AtomicBool = AtomicBool::new(true);
pub fn set_record_stack_erasure(enabled: bool) {
RECORD_STACK_ERASURE.store(enabled, Ordering::Relaxed);
}
#[must_use]
pub fn record_stack_erasure() -> bool {
RECORD_STACK_ERASURE.load(Ordering::Relaxed)
}
pub(crate) mod record_depth {
const fn optimised(bytes: usize) -> usize {
if cfg!(debug_assertions) {
super::SCRUB_STACK_BYTES
} else {
bytes
}
}
#[cfg(feature = "crypto-aws-lc-rs")]
pub(crate) const AWS_LC_AEAD: usize = optimised(5 * 1024);
#[cfg(feature = "crypto-aws-lc-rs")]
pub(crate) const AWS_LC_HMAC: usize = optimised(8 * 1024);
#[cfg(feature = "crypto-aws-lc-rs")]
pub(crate) const AWS_LC_HEADER_MASK: usize = optimised(4 * 1024);
#[cfg(feature = "crypto-ring")]
pub(crate) const RING_CHACHA20: usize = optimised(4 * 1024);
#[cfg(feature = "crypto-ring")]
pub(crate) const RING_AES_GCM_PORTABLE: usize = optimised(6 * 1024);
#[cfg_attr(debug_assertions, allow(dead_code))]
pub(crate) const RUSTCRYPTO_AES_PORTABLE: usize = optimised(4 * 1024);
pub(crate) const RUSTCRYPTO_AES_KEY_SETUP: usize = optimised(8 * 1024);
#[cfg(feature = "crypto-ring")]
pub(crate) const RUSTCRYPTO_SHA1_PORTABLE: usize = optimised(4 * 1024);
pub(crate) const CCM: usize = optimised(4 * 1024);
}
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
}
}
#[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
}
}
#[inline(never)]
pub(crate) fn scrub_stack_bytes<const N: usize>() {
let mut area = std::mem::MaybeUninit::<[u8; N]>::uninit();
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);
}
#[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;
static SETTING: Mutex<()> = Mutex::new(());
#[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;
#[inline(never)]
fn fill_below() -> (usize, usize) {
let mut area = [0u8; PROBE_BYTES];
for byte in area.iter_mut() {
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();
}
#[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 {
let byte = unsafe { std::ptr::read_volatile(address as *const u8) };
if byte != MARK {
lowest = address;
break;
}
}
end - lowest
}
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,
}
}
fn fixsliced_blocks(key: &[u8]) -> Vec<[u8; 64]> {
use aes::cipher::KeyInit;
fn blocks<T>(value: &T) -> Vec<[u8; 64]> {
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"),
}
}
#[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);
});
for (i, slot) in snapshot.iter_mut().enumerate().take(end - start) {
*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)
}
#[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,
);
}
}
{
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);
}
}
#[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() {
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}");
}
}