From 7b023f6cf47d5624ab08ec2374ff42d9e6ccc7bd Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Tue, 29 Sep 2026 15:00:18 -0500 Subject: [PATCH 1/3] fix(crypto): constant-time AES S-box and POLYVAL, wipe derived keys and scratch - AES S-box computed as GF(2^8) inverse (x^254) plus affine transform, 16 lanes at once in a u128; used by SubBytes and key expansion. No secret-indexed table lookups remain. xtime is branch-free. - POLYVAL dot/div_x use masks instead of secret branches, with a black_box barrier (LLVM re-introduced a branch without it). - AES-256-GCM-SIV: derived auth/enc keys, derivation scratch, CTR keystream and padded tails live in a self-wiping Secret buffer. Round keys are expanded in place; encrypt_block works in place. - Kernel envelope decrypt scratchpad wiped after use. - New test: computed S-box equals FIPS 197 table for all 256 inputs. - docs/CRYPTO_CONSTANT_TIME.md: claims and limits. Hardware AES (FEAT_AES) noted as future speedup, not implemented. In-house replacement for #173 (no vendored crates). Co-authored-by: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- crates/aienos-crypto/src/aes.rs | 214 ++++++++++++++++---- crates/aienos-crypto/src/aes_gcm_siv.rs | 75 ++++--- crates/aienos-crypto/src/lib.rs | 36 ++++ crates/aienos-crypto/src/polyval.rs | 25 ++- crates/aienos-kernel/src/crypto/envelope.rs | 4 + docs/CRYPTO_CONSTANT_TIME.md | 38 ++++ 6 files changed, 315 insertions(+), 77 deletions(-) create mode 100644 docs/CRYPTO_CONSTANT_TIME.md diff --git a/crates/aienos-crypto/src/aes.rs b/crates/aienos-crypto/src/aes.rs index 6149a56a..b6b09e73 100644 --- a/crates/aienos-crypto/src/aes.rs +++ b/crates/aienos-crypto/src/aes.rs @@ -1,6 +1,20 @@ //! Pure-Rust, allocation-free AES-256 block cipher implementation conforming to FIPS 197. //! //! Designed for bare-metal `#![no_std]` without external dependencies. +//! +//! # Constant-time design +//! +//! The S-box is computed, not looked up: each byte is inverted in GF(2^8) +//! (as `x^254`) and then passed through the FIPS 197 affine transform. All +//! arithmetic is shifts, masks and XORs with a fixed number of steps, so no +//! memory address and no branch depends on key or data bytes. The same S-box +//! routine serves encryption (`SubBytes`) and key expansion (`SubWord`). +//! Bytes are processed 16 at a time packed in a `u128` ("SIMD within a +//! register"), which keeps the cost reasonable without a lookup table. +//! +//! This is slower than a table-driven AES. Hardware AES instructions +//! (ARMv8 FEAT_AES: `AESE`/`AESMC`) are constant-time and much faster; they +//! are a possible future speedup and are **not** implemented here. /// AES-256 expanded round keys (15 rounds, 4 words per round = 60 words = 240 bytes). #[derive(Clone)] @@ -19,42 +33,102 @@ impl Drop for Aes256Key { for word in &mut self.round_keys { unsafe { core::ptr::write_volatile(word, 0) }; } + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } } -/// Rijndael S-box. -const SBOX: [u8; 256] = [ - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, -]; - /// Round constants. const RCON: [u32; 10] = [ 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000, ]; +/// `m` repeated in every byte lane of a `u128`. +const fn lanes(m: u8) -> u128 { + (m as u128) * 0x0101_0101_0101_0101_0101_0101_0101_0101 +} + +const LSB: u128 = lanes(0x01); +const LOW7: u128 = lanes(0x7f); + +/// Turn a lane value of 0 or 1 into 0x00 or 0xff, per lane, without branches. +/// +/// `(bits << 8) - bits` equals `bits * 0xff` lane by lane: every lane's +/// product fits in its own byte, so no carry or borrow crosses lanes, and the +/// identity holds modulo 2^128 even when the top lane's shift falls off. +#[inline(always)] +fn lane_mask(bits: u128) -> u128 { + (bits << 8).wrapping_sub(bits) +} + +/// Multiply every byte lane by `x` in GF(2^8) (FIPS 197 `xtime`), branch-free. +#[inline(always)] +fn xtime_lanes(a: u128) -> u128 { + let hi = (a >> 7) & LSB; // 0 or 1 per lane: did the top bit fall out? + // hi * 0x1b per lane, written as shifts so lanes stay independent. + let reduce = hi ^ (hi << 1) ^ (hi << 3) ^ (hi << 4); + ((a & LOW7) << 1) ^ reduce +} + +/// Lane-wise GF(2^8) multiply `a * b` modulo x^8 + x^4 + x^3 + x + 1. +/// +/// Always runs exactly 8 steps; each bit of `b` selects via a mask, not a branch. +#[inline(always)] +fn gf_mul_lanes(mut a: u128, b: u128) -> u128 { + let mut acc = 0u128; + let mut i = 0; + while i < 8 { + acc ^= a & lane_mask((b >> i) & LSB); + a = xtime_lanes(a); + i += 1; + } + acc +} + +/// Lane-wise rotate-left of each byte by `k` (1..=7). +#[inline(always)] +fn rotl_lanes(x: u128, k: u32) -> u128 { + let hi = lanes(0xffu8 << k); + let lo = lanes(0xffu8 >> (8 - k)); + ((x << k) & hi) | ((x >> (8 - k)) & lo) +} + +/// Constant-time AES S-box applied to all 16 byte lanes of `x` at once. +/// +/// S(b) = Affine(b^254), where b^254 is the multiplicative inverse of b in +/// GF(2^8) (and 0 maps to 0). The exponent is reached with a fixed addition +/// chain of 11 multiplications. +#[inline(never)] +fn sub_bytes_ct(x: u128) -> u128 { + let x2 = gf_mul_lanes(x, x); + let x3 = gf_mul_lanes(x2, x); + let x6 = gf_mul_lanes(x3, x3); + let x12 = gf_mul_lanes(x6, x6); + let x15 = gf_mul_lanes(x12, x3); + let x30 = gf_mul_lanes(x15, x15); + let x60 = gf_mul_lanes(x30, x30); + let x120 = gf_mul_lanes(x60, x60); + let x240 = gf_mul_lanes(x120, x120); + let x252 = gf_mul_lanes(x240, x12); + let inv = gf_mul_lanes(x252, x2); + + // FIPS 197 affine transform: b ^ rotl1 ^ rotl2 ^ rotl3 ^ rotl4 ^ 0x63. + inv ^ rotl_lanes(inv, 1) + ^ rotl_lanes(inv, 2) + ^ rotl_lanes(inv, 3) + ^ rotl_lanes(inv, 4) + ^ lanes(0x63) +} + +/// Constant-time S-box of a single byte (used by tests and for clarity). +#[cfg(test)] +fn sbox_ct(b: u8) -> u8 { + sub_bytes_ct(b as u128) as u8 +} + #[inline(always)] fn sub_word(w: u32) -> u32 { - let b0 = SBOX[((w >> 24) & 0xff) as usize] as u32; - let b1 = SBOX[((w >> 16) & 0xff) as usize] as u32; - let b2 = SBOX[((w >> 8) & 0xff) as usize] as u32; - let b3 = SBOX[(w & 0xff) as usize] as u32; - (b0 << 24) | (b1 << 16) | (b2 << 8) | b3 + sub_bytes_ct(w as u128) as u32 } #[inline(always)] @@ -64,52 +138,61 @@ fn rot_word(w: u32) -> u32 { #[inline(always)] fn xtime(x: u8) -> u8 { - (x << 1) ^ (if (x & 0x80) != 0 { 0x1b } else { 0 }) + // Branch-free: 0x1b where the top bit was set, 0 otherwise. + (x << 1) ^ (0x1bu8 & 0u8.wrapping_sub(x >> 7)) } impl Aes256Key { /// Expand a 32-byte key into 15 round keys per FIPS 197. + /// + /// The schedule is built directly inside the returned value, so no + /// separate stack copy of the round keys is left behind. pub fn new(key: &[u8; 32]) -> Self { - let mut round_keys = [0u32; 60]; + let mut out = Self { + round_keys: [0u32; 60], + }; + let rk = &mut out.round_keys; for i in 0..8 { - round_keys[i] = + rk[i] = u32::from_be_bytes([key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]); } + // `i % 8` depends only on the public loop index, never on key bytes. for i in 8..60 { - let mut temp = round_keys[i - 1]; + let mut temp = rk[i - 1]; if i % 8 == 0 { temp = sub_word(rot_word(temp)) ^ RCON[(i / 8) - 1]; } else if i % 8 == 4 { temp = sub_word(temp); } - round_keys[i] = round_keys[i - 8] ^ temp; + rk[i] = rk[i - 8] ^ temp; } - Self { round_keys } + out } /// Encrypt a single 16-byte block in place per FIPS 197. + /// + /// Works directly on the caller's buffer, so no intermediate state copy + /// is left on the stack. pub fn encrypt_block(&self, block: &mut [u8; 16]) { - let mut state = *block; + let state = block; // Initial round: AddRoundKey - Self::add_round_key(&mut state, &self.round_keys[0..4]); + Self::add_round_key(state, &self.round_keys[0..4]); // Rounds 1 to 13 for round in 1..14 { - Self::sub_bytes(&mut state); - Self::shift_rows(&mut state); - Self::mix_columns(&mut state); - Self::add_round_key(&mut state, &self.round_keys[round * 4..(round + 1) * 4]); + Self::sub_bytes(state); + Self::shift_rows(state); + Self::mix_columns(state); + Self::add_round_key(state, &self.round_keys[round * 4..(round + 1) * 4]); } // Final round 14 (no MixColumns) - Self::sub_bytes(&mut state); - Self::shift_rows(&mut state); - Self::add_round_key(&mut state, &self.round_keys[14 * 4..15 * 4]); - - *block = state; + Self::sub_bytes(state); + Self::shift_rows(state); + Self::add_round_key(state, &self.round_keys[14 * 4..15 * 4]); } #[inline(always)] @@ -125,9 +208,7 @@ impl Aes256Key { #[inline(always)] fn sub_bytes(state: &mut [u8; 16]) { - for b in state.iter_mut() { - *b = SBOX[*b as usize]; - } + *state = sub_bytes_ct(u128::from_le_bytes(*state)).to_le_bytes(); } #[inline(always)] @@ -183,6 +264,49 @@ impl Aes256Key { mod tests { use super::*; + /// Reference Rijndael S-box from FIPS 197 Figure 7, used only to check `sub_bytes_ct`. + #[rustfmt::skip] + const SBOX: [u8; 256] = [ + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, + ]; + + #[test] + fn test_constant_time_sbox_matches_fips197_table() { + for b in 0..=255u8 { + assert_eq!( + sbox_ct(b), + SBOX[b as usize], + "S-box mismatch at input {b:#04x}" + ); + } + // All 16 lanes at once, with every lane holding a different input. + for base in (0..=255u8).step_by(16) { + let mut input = [0u8; 16]; + for (i, v) in input.iter_mut().enumerate() { + *v = base.wrapping_add(i as u8); + } + let out = sub_bytes_ct(u128::from_le_bytes(input)).to_le_bytes(); + for i in 0..16 { + assert_eq!(out[i], SBOX[input[i] as usize]); + } + } + } + #[test] fn test_aes_256_fips_197_c2() { // NIST FIPS 197 Appendix C.2 Test Vector (AES-256) diff --git a/crates/aienos-crypto/src/aes_gcm_siv.rs b/crates/aienos-crypto/src/aes_gcm_siv.rs index 1e476798..42171e30 100644 --- a/crates/aienos-crypto/src/aes_gcm_siv.rs +++ b/crates/aienos-crypto/src/aes_gcm_siv.rs @@ -2,9 +2,14 @@ //! //! Nonce-misuse-resistant authenticated encryption with associated data (AEAD) //! using 256-bit keys, 96-bit nonces, and 128-bit authentication tags. +//! +//! Secret intermediates (derived keys, key-derivation scratch, CTR keystream, +//! padded plaintext tails) live in self-wiping buffers, so they are zeroed on +//! every return path, including authentication failure. use crate::aes::Aes256Key; use crate::polyval::Polyval; +use crate::Secret; /// Tag size in bytes (128 bits). pub const TAG_LEN: usize = 16; @@ -18,17 +23,33 @@ pub const KEY_LEN: usize = 32; pub struct AuthenticationError; /// Derive the 128-bit authentication key and 256-bit encryption key per RFC 8452 Section 4. +/// +/// The returned arrays are secret key material and are not wiped automatically; +/// callers must wipe them. `encrypt` and `decrypt` do not use this function: +/// they derive straight into self-wiping buffers. pub fn derive_keys(key: &[u8; 32], nonce: &[u8; 12]) -> ([u8; 16], [u8; 32]) { + let mut auth_key = Secret::<16>::zeroed(); + let mut enc_key = Secret::<32>::zeroed(); + derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0); + (auth_key.0, enc_key.0) +} + +/// Derive both per-nonce keys into caller-owned buffers. The scratch block is wiped. +fn derive_keys_into( + key: &[u8; 32], + nonce: &[u8; 12], + auth_key: &mut [u8; 16], + enc_key: &mut [u8; 32], +) { let k_cipher = Aes256Key::new(key); - let mut auth_key = [0u8; 16]; - let mut enc_key = [0u8; 32]; + let mut scratch = Secret::<16>::zeroed(); + let block = &mut scratch.0; for i in 0..6u32 { - let mut block = [0u8; 16]; block[0..4].copy_from_slice(&i.to_le_bytes()); block[4..16].copy_from_slice(nonce); - k_cipher.encrypt_block(&mut block); + k_cipher.encrypt_block(block); match i { 0 => auth_key[0..8].copy_from_slice(&block[0..8]), @@ -40,8 +61,6 @@ pub fn derive_keys(key: &[u8; 32], nonce: &[u8; 12]) -> ([u8; 16], [u8; 32]) { _ => unreachable!(), } } - - (auth_key, enc_key) } /// Constant-time comparison of two 16-byte tags. @@ -80,9 +99,9 @@ fn compute_tag( poly.update_block(chunk); } if !aad_rem.is_empty() { - let mut b = [0u8; 16]; - b[..aad_rem.len()].copy_from_slice(aad_rem); - poly.update_block(&b); + let mut b = Secret::<16>::zeroed(); + b.0[..aad_rem.len()].copy_from_slice(aad_rem); + poly.update_block(&b.0); } // Feed plaintext padded to 16-byte boundary @@ -91,9 +110,10 @@ fn compute_tag( poly.update_block(chunk); } if !pt_rem.is_empty() { - let mut b = [0u8; 16]; - b[..pt_rem.len()].copy_from_slice(pt_rem); - poly.update_block(&b); + // Holds a plaintext tail: wiped on drop. + let mut b = Secret::<16>::zeroed(); + b.0[..pt_rem.len()].copy_from_slice(pt_rem); + poly.update_block(&b.0); } // Feed length block @@ -118,10 +138,12 @@ fn apply_ctr(enc_cipher: &Aes256Key, tag: &[u8; 16], buf: &mut [u8]) { let mut counter_block = *tag; counter_block[15] |= 0x80; + // Keystream bytes are secret (they unmask the plaintext): wiped on drop. + let mut keystream = Secret::<16>::zeroed(); let mut offset = 0; while offset < buf.len() { - let mut keystream = counter_block; - enc_cipher.encrypt_block(&mut keystream); + keystream.0 = counter_block; + enc_cipher.encrypt_block(&mut keystream.0); let ctr = u32::from_le_bytes([ counter_block[0], @@ -133,7 +155,7 @@ fn apply_ctr(enc_cipher: &Aes256Key, tag: &[u8; 16], buf: &mut [u8]) { let todo = core::cmp::min(buf.len() - offset, 16); for i in 0..todo { - buf[offset + i] ^= keystream[i]; + buf[offset + i] ^= keystream.0[i]; } offset += todo; } @@ -155,10 +177,13 @@ pub fn encrypt( "Destination buffer must equal plaintext len + 16" ); - let (auth_key, enc_key) = derive_keys(key, nonce); - let enc_cipher = Aes256Key::new(&enc_key); + // Derived keys live in self-wiping buffers, wiped on every return path. + let mut auth_key = Secret::<16>::zeroed(); + let mut enc_key = Secret::<32>::zeroed(); + derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0); + let enc_cipher = Aes256Key::new(&enc_key.0); - let tag = compute_tag(&auth_key, &enc_cipher, nonce, aad, plaintext); + let tag = compute_tag(&auth_key.0, &enc_cipher, nonce, aad, plaintext); // Copy plaintext into output slice, then apply CTR in place out_ciphertext_and_tag[..plaintext.len()].copy_from_slice(plaintext); @@ -197,23 +222,25 @@ pub fn decrypt( let mut received_tag = [0u8; 16]; received_tag.copy_from_slice(received_tag_slice); - let (auth_key, enc_key) = derive_keys(key, nonce); - let enc_cipher = Aes256Key::new(&enc_key); + // Derived keys live in self-wiping buffers, wiped on every return path + // (success and authentication failure alike). + let mut auth_key = Secret::<16>::zeroed(); + let mut enc_key = Secret::<32>::zeroed(); + derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0); + let enc_cipher = Aes256Key::new(&enc_key.0); // Decrypt in place into out_plaintext out_plaintext.copy_from_slice(ciphertext); apply_ctr(&enc_cipher, &received_tag, out_plaintext); // Compute expected tag over decrypted plaintext - let expected_tag = compute_tag(&auth_key, &enc_cipher, nonce, aad, out_plaintext); + let expected_tag = compute_tag(&auth_key.0, &enc_cipher, nonce, aad, out_plaintext); if constant_time_eq_tag(&received_tag, &expected_tag) { Ok(()) } else { // Zero decrypted plaintext on failure - for b in out_plaintext.iter_mut() { - unsafe { core::ptr::write_volatile(b, 0) }; - } + crate::wipe(out_plaintext); Err(AuthenticationError) } } diff --git a/crates/aienos-crypto/src/lib.rs b/crates/aienos-crypto/src/lib.rs index 4c0c88e8..fd6a58ed 100644 --- a/crates/aienos-crypto/src/lib.rs +++ b/crates/aienos-crypto/src/lib.rs @@ -2,6 +2,16 @@ //! Shared, allocation-free cryptographic primitives used by the kernel and //! host/bare-metal parsers. +//! +//! # Side-channel stance +//! +//! AES-256, POLYVAL and AES-256-GCM-SIV are written to be constant-time by +//! construction: no table lookup is indexed by secret data and no branch +//! depends on secret data. Secret key material and scratch buffers are wiped +//! with volatile writes when they go out of scope. This has been checked by +//! reading the source and spot-checking AArch64 disassembly; it has not been +//! measured on hardware and has not had an independent side-channel review. +//! See `docs/CRYPTO_CONSTANT_TIME.md`. #[cfg(test)] extern crate std; @@ -10,3 +20,29 @@ pub mod aes; pub mod aes_gcm_siv; pub mod polyval; pub mod sha256; + +/// Overwrite `buf` with zeros using volatile writes the optimizer cannot drop. +#[inline(never)] +pub(crate) fn wipe(buf: &mut [u8]) { + for b in buf.iter_mut() { + // SAFETY: `b` is a valid, aligned, exclusive reference into `buf`. + unsafe { core::ptr::write_volatile(b, 0) }; + } + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); +} + +/// Fixed-size secret byte buffer that is wiped on drop, on every exit path. +pub(crate) struct Secret(pub(crate) [u8; N]); + +impl Secret { + #[inline(always)] + pub(crate) fn zeroed() -> Self { + Self([0u8; N]) + } +} + +impl Drop for Secret { + fn drop(&mut self) { + wipe(&mut self.0); + } +} diff --git a/crates/aienos-crypto/src/polyval.rs b/crates/aienos-crypto/src/polyval.rs index edad7020..5d2f19d5 100644 --- a/crates/aienos-crypto/src/polyval.rs +++ b/crates/aienos-crypto/src/polyval.rs @@ -7,12 +7,18 @@ pub type Block = [u8; 16]; /// POLYVAL state accumulator. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Default)] pub struct Polyval { key: Block, accumulator: Block, } +impl core::fmt::Debug for Polyval { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "Polyval([REDACTED])") + } +} + impl Drop for Polyval { fn drop(&mut self) { for b in &mut self.key { @@ -40,12 +46,13 @@ fn div_x(v: &mut Block) { carry = next_carry; } - if lsb != 0 { - v[15] ^= X_INV_BYTE_15; - } + // Branch-free reduction: mask is 0xff when lsb == 1, 0x00 when lsb == 0. + v[15] ^= X_INV_BYTE_15 & 0u8.wrapping_sub(core::hint::black_box(lsb)); } /// Compute dot(a, b) = a * b * x^-128 mod P(x) per RFC 8452 Section 3. +/// +/// Constant-time: always 128 steps, no branch or memory address depends on `a` or `b`. pub fn dot(a: &Block, b: &Block) -> Block { let mut v = [0u8; 16]; @@ -54,10 +61,12 @@ pub fn dot(a: &Block, b: &Block) -> Block { let bit_idx = i % 8; let bit = (a[byte_idx] >> bit_idx) & 1; - if bit != 0 { - for j in 0..16 { - v[j] ^= b[j]; - } + // Branch-free conditional add: mask is 0xff when bit == 1, else 0x00. + // `black_box` hides that `bit` is 0 or 1, so LLVM cannot turn the mask + // back into a branch (it did so without it; seen in AArch64 disassembly). + let mask = 0u8.wrapping_sub(core::hint::black_box(bit)); + for j in 0..16 { + v[j] ^= b[j] & mask; } div_x(&mut v); diff --git a/crates/aienos-kernel/src/crypto/envelope.rs b/crates/aienos-kernel/src/crypto/envelope.rs index a047b515..60fddfef 100644 --- a/crates/aienos-kernel/src/crypto/envelope.rs +++ b/crates/aienos-kernel/src/crypto/envelope.rs @@ -379,6 +379,10 @@ pub fn decrypt_envelope( } plaintext.extend_from_slice(&scratchpad); + // The scratchpad held verified plaintext: wipe it before the heap block is freed. + for b in scratchpad.iter_mut() { + unsafe { core::ptr::write_volatile(b, 0) }; + } } Ok(plaintext) diff --git a/docs/CRYPTO_CONSTANT_TIME.md b/docs/CRYPTO_CONSTANT_TIME.md new file mode 100644 index 00000000..b05826fa --- /dev/null +++ b/docs/CRYPTO_CONSTANT_TIME.md @@ -0,0 +1,38 @@ +# Constant-time AES/POLYVAL and secret wiping + +Scope: `crates/aienos-crypto` (AES-256, POLYVAL, AES-256-GCM-SIV) and the +kernel envelope decrypt scratchpad. All code is in-house; no outside crates. + +## What changed + +- **AES S-box is computed, not looked up.** Each byte is inverted in GF(2^8) + as `x^254` (fixed chain of 11 multiplications) and passed through the + FIPS 197 affine transform. Only shifts, masks and XORs; 16 bytes at a time + packed in a `u128`. Used by both encryption (`SubBytes`) and key expansion + (`SubWord`). `xtime` in MixColumns is branch-free. +- **POLYVAL multiply is branch-free.** The conditional add and the reduction + step use all-ones/all-zeros masks instead of `if`. +- **Secrets are wiped on every path.** Derived GCM-SIV keys, the key-derivation + scratch block, the CTR keystream and padded plaintext tails live in a + self-wiping buffer (volatile writes on drop). AES round keys are built in + place in the returned key object; encryption works in the caller's buffer + with no extra state copy. The kernel envelope decrypt scratchpad is wiped + after its plaintext is copied out. +- The public `derive_keys` still returns plain arrays; its callers must wipe + them. `encrypt`/`decrypt` do not use it. + +## What is and is not claimed + +- Constant-time by construction in the source, plus an AArch64 release + disassembly spot-check of the S-box routine (no conditional branches, no + data-indexed loads). +- **Not measured** on hardware. **No independent side-channel review.** +- Known remaining gap: the envelope's growing plaintext `Vec` may leave + copies of earlier plaintext in freed heap blocks when it reallocates. +- Existing FIPS 197 and RFC 8452 known-answer vectors pass unchanged; a new + test checks the computed S-box against the standard table for all 256 inputs. + +## Future speedup (not implemented) + +ARMv8 FEAT_AES instructions (`AESE`/`AESMC`) are constant-time in hardware and +much faster than this software S-box. They are a possible future speedup. From 099a9b7d7795b513edbfb82f6b943073f6df2169 Mon Sep 17 00:00:00 2001 From: AIEN Atlas Date: Tue, 29 Sep 2026 15:13:43 -0500 Subject: [PATCH 2/3] Guard exported keys and reserve plaintext only after authentication Co-authored-by: Drake Stapleton --- crates/aienos-crypto/src/aes_gcm_siv.rs | 26 +++++++++++++---- crates/aienos-crypto/src/lib.rs | 22 ++++++++++++++- crates/aienos-kernel/src/crypto/envelope.rs | 31 ++++++++++++++++----- docs/CRYPTO_CONSTANT_TIME.md | 10 ++++--- 4 files changed, 72 insertions(+), 17 deletions(-) diff --git a/crates/aienos-crypto/src/aes_gcm_siv.rs b/crates/aienos-crypto/src/aes_gcm_siv.rs index 42171e30..0620ad29 100644 --- a/crates/aienos-crypto/src/aes_gcm_siv.rs +++ b/crates/aienos-crypto/src/aes_gcm_siv.rs @@ -24,14 +24,12 @@ pub struct AuthenticationError; /// Derive the 128-bit authentication key and 256-bit encryption key per RFC 8452 Section 4. /// -/// The returned arrays are secret key material and are not wiped automatically; -/// callers must wipe them. `encrypt` and `decrypt` do not use this function: -/// they derive straight into self-wiping buffers. -pub fn derive_keys(key: &[u8; 32], nonce: &[u8; 12]) -> ([u8; 16], [u8; 32]) { +/// Both returned buffers wipe themselves on drop, including caller error paths. +pub fn derive_keys(key: &[u8; 32], nonce: &[u8; 12]) -> (Secret<16>, Secret<32>) { let mut auth_key = Secret::<16>::zeroed(); let mut enc_key = Secret::<32>::zeroed(); derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0); - (auth_key.0, enc_key.0) + (auth_key, enc_key) } /// Derive both per-nonce keys into caller-owned buffers. The scratch block is wiped. @@ -250,6 +248,24 @@ mod tests { use super::*; use std::vec; + #[test] + fn public_derived_keys_are_guarded_and_redacted() { + let key = [0x31; KEY_LEN]; + let nonce = [0x72; NONCE_LEN]; + let (auth, enc) = derive_keys(&key, &nonce); + let mut expected_auth = [0; 16]; + let mut expected_enc = [0; 32]; + derive_keys_into(&key, &nonce, &mut expected_auth, &mut expected_enc); + assert_eq!(*auth, expected_auth); + assert_eq!(*enc, expected_enc); + assert_eq!( + std::format!("{auth:?} {enc:?}"), + "Secret([REDACTED]) Secret([REDACTED])" + ); + crate::wipe(&mut expected_auth); + crate::wipe(&mut expected_enc); + } + fn hex_to_vec(hex: &str) -> std::vec::Vec { let mut v = std::vec::Vec::new(); for i in 0..hex.len() / 2 { diff --git a/crates/aienos-crypto/src/lib.rs b/crates/aienos-crypto/src/lib.rs index fd6a58ed..d9cfa48c 100644 --- a/crates/aienos-crypto/src/lib.rs +++ b/crates/aienos-crypto/src/lib.rs @@ -32,7 +32,27 @@ pub(crate) fn wipe(buf: &mut [u8]) { } /// Fixed-size secret byte buffer that is wiped on drop, on every exit path. -pub(crate) struct Secret(pub(crate) [u8; N]); +pub struct Secret(pub(crate) [u8; N]); + +impl core::ops::Deref for Secret { + type Target = [u8; N]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl core::ops::DerefMut for Secret { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl core::fmt::Debug for Secret { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("Secret([REDACTED])") + } +} impl Secret { #[inline(always)] diff --git a/crates/aienos-kernel/src/crypto/envelope.rs b/crates/aienos-kernel/src/crypto/envelope.rs index 60fddfef..f1e863a3 100644 --- a/crates/aienos-kernel/src/crypto/envelope.rs +++ b/crates/aienos-kernel/src/crypto/envelope.rs @@ -62,6 +62,21 @@ pub enum EnvelopeError { PlaintextTooLarge(u64), /// Expected envelope length overflows the platform integer range. LengthOverflow, + /// Allocation failed after the envelope header was authenticated. + AllocationFailed, +} + +/// Temporary plaintext is wiped even when allocation or authentication fails. +struct PlaintextScratch(Vec); + +impl Drop for PlaintextScratch { + fn drop(&mut self) { + for byte in &mut self.0 { + // SAFETY: exclusive reference to a live initialized byte. + unsafe { core::ptr::write_volatile(byte, 0) }; + } + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); + } } /// Fixed 64-byte authenticated envelope header. @@ -331,7 +346,8 @@ pub fn decrypt_envelope( let chunk_size = header.chunk_size as usize; let chunk_count = header.chunk_count(); - // Grow per authenticated chunk; never reserve the header's claimed total up front. + // Reserve only after the first chunk authenticates the complete header. + // One reservation prevents plaintext copies being left in freed growth buffers. let mut plaintext = Vec::new(); let mut cursor = ENVELOPE_HEADER_LEN; @@ -369,8 +385,8 @@ pub fn decrypt_envelope( ); // Verification scratchpad: verified before writing to caller buffer - let mut scratchpad = alloc::vec![0u8; pt_chunk_len]; - if raw_decrypt(key, &nonce, &aad, ct_chunk, &mut scratchpad).is_err() { + let mut scratchpad = PlaintextScratch(alloc::vec![0u8; pt_chunk_len]); + if raw_decrypt(key, &nonce, &aad, ct_chunk, &mut scratchpad.0).is_err() { // Scratchpad was wiped by raw_decrypt on failure; wipe and drop plaintext for b in plaintext.iter_mut() { unsafe { core::ptr::write_volatile(b, 0) }; @@ -378,11 +394,12 @@ pub fn decrypt_envelope( return Err(EnvelopeError::AuthenticationFailed); } - plaintext.extend_from_slice(&scratchpad); - // The scratchpad held verified plaintext: wipe it before the heap block is freed. - for b in scratchpad.iter_mut() { - unsafe { core::ptr::write_volatile(b, 0) }; + if i == 0 { + plaintext + .try_reserve_exact(header.total_plaintext_len as usize) + .map_err(|_| EnvelopeError::AllocationFailed)?; } + plaintext.extend_from_slice(&scratchpad.0); } Ok(plaintext) diff --git a/docs/CRYPTO_CONSTANT_TIME.md b/docs/CRYPTO_CONSTANT_TIME.md index b05826fa..7b69350c 100644 --- a/docs/CRYPTO_CONSTANT_TIME.md +++ b/docs/CRYPTO_CONSTANT_TIME.md @@ -18,8 +18,9 @@ kernel envelope decrypt scratchpad. All code is in-house; no outside crates. place in the returned key object; encryption works in the caller's buffer with no extra state copy. The kernel envelope decrypt scratchpad is wiped after its plaintext is copied out. -- The public `derive_keys` still returns plain arrays; its callers must wipe - them. `encrypt`/`decrypt` do not use it. +- The public `derive_keys` returns self-wiping buffers with redacted debug + output. Callers borrow the contained arrays; explicit copies remain the + caller's responsibility. ## What is and is not claimed @@ -27,8 +28,9 @@ kernel envelope decrypt scratchpad. All code is in-house; no outside crates. disassembly spot-check of the S-box routine (no conditional branches, no data-indexed loads). - **Not measured** on hardware. **No independent side-channel review.** -- Known remaining gap: the envelope's growing plaintext `Vec` may leave - copies of earlier plaintext in freed heap blocks when it reallocates. +- Envelope storage is reserved once after the first chunk authenticates the + complete bounded header. Later chunks cannot trigger growth that leaves + plaintext in freed heap blocks. Allocation failures wipe the temporary chunk. - Existing FIPS 197 and RFC 8452 known-answer vectors pass unchanged; a new test checks the computed S-box against the standard table for all 256 inputs. From 11ec20c674e7556f062311f8f074f5139fd608b8 Mon Sep 17 00:00:00 2001 From: AIEN Atlas Date: Tue, 29 Sep 2026 15:16:49 -0500 Subject: [PATCH 3/3] Check in-house crypto and bare-metal compatibility on Linux Co-authored-by: Drake Stapleton --- .github/workflows/crypto-boundary.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .github/workflows/crypto-boundary.yml diff --git a/.github/workflows/crypto-boundary.yml b/.github/workflows/crypto-boundary.yml new file mode 100644 index 00000000..957c286f --- /dev/null +++ b/.github/workflows/crypto-boundary.yml @@ -0,0 +1,25 @@ +name: Crypto boundary +on: + workflow_dispatch: + pull_request: + paths: + - 'crates/aienos-crypto/**' + - 'crates/aienos-kernel/src/crypto/**' + - '.github/workflows/crypto-boundary.yml' + push: + branches: [main] +permissions: + contents: read +jobs: + crypto: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-unknown-none + components: clippy + - run: cargo test --locked --offline -p aienos-crypto + - run: 'cargo test --locked --offline -p aienos-kernel crypto::' + - run: cargo clippy --locked --offline -p aienos-crypto --all-targets -- -D warnings + - run: cargo check --locked --offline -p aienos-kernel --target aarch64-unknown-none --no-default-features