aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#150 (code only)
Apply it
git checkout -b patch-5a5122d6d68f349e e3d3a1075a4e8c04d9b7947b8f2b9f8c0e983032 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/5a5122d6d68f349e.patch | git am
Provenance
github-import 1
aien-dev/aienux
150
cbda56171e667e7c50bbd4ae8e3970ceee3f9e2e
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":150,"url":"https://github.com/aien-dev/aienux/pull/150","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:50Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-crypto/src/aes.rs b/crates/aienos-crypto/src/aes.rs new file mode 100644 index 00000000..6149a56a --- /dev/null +++ b/crates/aienos-crypto/src/aes.rs @@ -0,0 +1,207 @@ +//! Pure-Rust, allocation-free AES-256 block cipher implementation conforming to FIPS 197. +//! +//! Designed for bare-metal `#![no_std]` without external dependencies. + +/// AES-256 expanded round keys (15 rounds, 4 words per round = 60 words = 240 bytes). +#[derive(Clone)] +pub struct Aes256Key { + round_keys: [u32; 60], +} + +impl core::fmt::Debug for Aes256Key { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "Aes256Key([REDACTED])") + } +} + +impl Drop for Aes256Key { + fn drop(&mut self) { + for word in &mut self.round_keys { + unsafe { core::ptr::write_volatile(word, 0) }; + } + } +} + +/// 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, +]; + +#[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 +} + +#[inline(always)] +fn rot_word(w: u32) -> u32 { + w.rotate_left(8) +} + +#[inline(always)] +fn xtime(x: u8) -> u8 { + (x << 1) ^ (if (x & 0x80) != 0 { 0x1b } else { 0 }) +} + +impl Aes256Key { + /// Expand a 32-byte key into 15 round keys per FIPS 197. + pub fn new(key: &[u8; 32]) -> Self { + let mut round_keys = [0u32; 60]; + for i in 0..8 { + round_keys[i] = + u32::from_be_bytes([key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]); + } + + for i in 8..60 { + let mut temp = round_keys[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; + } + + Self { round_keys } + } + + /// Encrypt a single 16-byte block in place per FIPS 197. + pub fn encrypt_block(&self, block: &mut [u8; 16]) { + let mut state = *block; + + // Initial round: AddRoundKey + Self::add_round_key(&mut 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]); + } + + // 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; + } + + #[inline(always)] + fn add_round_key(state: &mut [u8; 16], rk: &[u32]) { + for c in 0..4 { + let word_bytes = rk[c].to_be_bytes(); + state[c * 4] ^= word_bytes[0]; + state[c * 4 + 1] ^= word_bytes[1]; + state[c * 4 + 2] ^= word_bytes[2]; + state[c * 4 + 3] ^= word_bytes[3]; + } + } + + #[inline(always)] + fn sub_bytes(state: &mut [u8; 16]) { + for b in state.iter_mut() { + *b = SBOX[*b as usize]; + } + } + + #[inline(always)] + fn shift_rows(state: &mut [u8; 16]) { + // State is stored column-major: + // state[0] state[4] state[8] state[12] + // state[1] state[5] state[9] state[13] + // state[2] state[6] state[10] state[14] + // state[3] state[7] state[11] state[15] + let s1 = state[1]; + state[1] = state[5]; + state[5] = state[9]; + state[9] = state[13]; + state[13] = s1; + + let s2 = state[2]; + let s6 = state[6]; + state[2] = state[10]; + state[6] = state[14]; + state[10] = s2; + state[14] = s6; + + let s3 = state[15]; + state[15] = state[11]; + state[11] = state[7]; + state[7] = state[3]; + state[3] = s3; + } + + #[inline(always)] + fn mix_columns(state: &mut [u8; 16]) { + for c in 0..4 { + let idx = c * 4; + let s0 = state[idx]; + let s1 = state[idx + 1]; + let s2 = state[idx + 2]; + let s3 = state[idx + 3]; + + let h0 = xtime(s0); + let h1 = xtime(s1); + let h2 = xtime(s2); + let h3 = xtime(s3); + + state[idx] = h0 ^ s1 ^ h1 ^ s2 ^ s3; + state[idx + 1] = s0 ^ h1 ^ s2 ^ h2 ^ s3; + state[idx + 2] = s0 ^ s1 ^ h2 ^ s3 ^ h3; + state[idx + 3] = s0 ^ h0 ^ s1 ^ s2 ^ h3; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_aes_256_fips_197_c2() { + // NIST FIPS 197 Appendix C.2 Test Vector (AES-256) + let key: [u8; 32] = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, + 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, + ]; + let mut block: [u8; 16] = [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, + 0xee, 0xff, + ]; + let expected: [u8; 16] = [ + 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, + 0x60, 0x89, + ]; + + let cipher = Aes256Key::new(&key); + cipher.encrypt_block(&mut block); + assert_eq!(block, expected); + } +} diff --git a/crates/aienos-crypto/src/aes_gcm_siv.rs b/crates/aienos-crypto/src/aes_gcm_siv.rs new file mode 100644 index 00000000..1e476798 --- /dev/null +++ b/crates/aienos-crypto/src/aes_gcm_siv.rs @@ -0,0 +1,288 @@ +//! Pure-Rust, allocation-free AES-256-GCM-SIV AEAD implementation conforming to RFC 8452. +//! +//! Nonce-misuse-resistant authenticated encryption with associated data (AEAD) +//! using 256-bit keys, 96-bit nonces, and 128-bit authentication tags. + +use crate::aes::Aes256Key; +use crate::polyval::Polyval; + +/// Tag size in bytes (128 bits). +pub const TAG_LEN: usize = 16; +/// Nonce size in bytes (96 bits). +pub const NONCE_LEN: usize = 12; +/// Key size in bytes (256 bits). +pub const KEY_LEN: usize = 32; + +/// Error returned when decryption authentication verification fails. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AuthenticationError; + +/// Derive the 128-bit authentication key and 256-bit encryption key per RFC 8452 Section 4. +pub fn derive_keys(key: &[u8; 32], nonce: &[u8; 12]) -> ([u8; 16], [u8; 32]) { + let k_cipher = Aes256Key::new(key); + let mut auth_key = [0u8; 16]; + let mut enc_key = [0u8; 32]; + + 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); + + match i { + 0 => auth_key[0..8].copy_from_slice(&block[0..8]), + 1 => auth_key[8..16].copy_from_slice(&block[0..8]), + 2 => enc_key[0..8].copy_from_slice(&block[0..8]), + 3 => enc_key[8..16].copy_from_slice(&block[0..8]), + 4 => enc_key[16..24].copy_from_slice(&block[0..8]), + 5 => enc_key[24..32].copy_from_slice(&block[0..8]), + _ => unreachable!(), + } + } + + (auth_key, enc_key) +} + +/// Constant-time comparison of two 16-byte tags. +#[inline(never)] +fn constant_time_eq_tag(a: &[u8; 16], b: &[u8; 16]) -> bool { + let mut diff = 0u8; + for i in 0..16 { + diff |= a[i] ^ b[i]; + } + diff == 0 +} + +/// Compute length block: 64-bit le AAD bit len || 64-bit le plaintext bit len. +fn make_length_block(aad_len: usize, plaintext_len: usize) -> [u8; 16] { + let mut len_block = [0u8; 16]; + let aad_bits = (aad_len as u64).wrapping_mul(8); + let pt_bits = (plaintext_len as u64).wrapping_mul(8); + len_block[0..8].copy_from_slice(&aad_bits.to_le_bytes()); + len_block[8..16].copy_from_slice(&pt_bits.to_le_bytes()); + len_block +} + +/// Compute SIV tag given auth_key, enc_cipher, nonce, aad, and plaintext. +fn compute_tag( + auth_key: &[u8; 16], + enc_cipher: &Aes256Key, + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], +) -> [u8; 16] { + let mut poly = Polyval::new(auth_key); + + // Feed AAD padded to 16-byte boundary + let (aad_chunks, aad_rem) = aad.as_chunks::<16>(); + for chunk in aad_chunks { + 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); + } + + // Feed plaintext padded to 16-byte boundary + let (pt_chunks, pt_rem) = plaintext.as_chunks::<16>(); + for chunk in pt_chunks { + 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); + } + + // Feed length block + let len_block = make_length_block(aad.len(), plaintext.len()); + poly.update_block(&len_block); + + let mut s_s = poly.finalize(); + + // XOR first 12 bytes with nonce, clear MSB of last byte + for i in 0..12 { + s_s[i] ^= nonce[i]; + } + s_s[15] &= 0x7f; + + // Encrypt with enc_key + enc_cipher.encrypt_block(&mut s_s); + s_s +} + +/// Perform AES-CTR keystream encryption/decryption in place. +fn apply_ctr(enc_cipher: &Aes256Key, tag: &[u8; 16], buf: &mut [u8]) { + let mut counter_block = *tag; + counter_block[15] |= 0x80; + + let mut offset = 0; + while offset < buf.len() { + let mut keystream = counter_block; + enc_cipher.encrypt_block(&mut keystream); + + let ctr = u32::from_le_bytes([ + counter_block[0], + counter_block[1], + counter_block[2], + counter_block[3], + ]); + counter_block[0..4].copy_from_slice(&ctr.wrapping_add(1).to_le_bytes()); + + let todo = core::cmp::min(buf.len() - offset, 16); + for i in 0..todo { + buf[offset + i] ^= keystream[i]; + } + offset += todo; + } +} + +/// Encrypt plaintext with AES-256-GCM-SIV per RFC 8452. +/// +/// Output slice `out_ciphertext_and_tag` must be exactly `plaintext.len() + TAG_LEN` bytes. +pub fn encrypt( + key: &[u8; 32], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + out_ciphertext_and_tag: &mut [u8], +) { + assert_eq!( + out_ciphertext_and_tag.len(), + plaintext.len() + TAG_LEN, + "Destination buffer must equal plaintext len + 16" + ); + + let (auth_key, enc_key) = derive_keys(key, nonce); + let enc_cipher = Aes256Key::new(&enc_key); + + let tag = compute_tag(&auth_key, &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); + apply_ctr( + &enc_cipher, + &tag, + &mut out_ciphertext_and_tag[..plaintext.len()], + ); + + // Append 16-byte tag + out_ciphertext_and_tag[plaintext.len()..].copy_from_slice(&tag); +} + +/// Decrypt ciphertext with AES-256-GCM-SIV per RFC 8452. +/// +/// Plaintext is written to `out_plaintext`, which must be `ciphertext_and_tag.len() - TAG_LEN` bytes. +/// If authentication fails, `out_plaintext` is zeroed and `Err(AuthenticationError)` is returned. +pub fn decrypt( + key: &[u8; 32], + nonce: &[u8; 12], + aad: &[u8], + ciphertext_and_tag: &[u8], + out_plaintext: &mut [u8], +) -> Result<(), AuthenticationError> { + if ciphertext_and_tag.len() < TAG_LEN { + return Err(AuthenticationError); + } + let ciphertext_len = ciphertext_and_tag.len() - TAG_LEN; + assert_eq!( + out_plaintext.len(), + ciphertext_len, + "Destination plaintext buffer must equal ciphertext len" + ); + + let (ciphertext, received_tag_slice) = ciphertext_and_tag.split_at(ciphertext_len); + 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); + + // 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); + + 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) }; + } + Err(AuthenticationError) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::vec; + + fn hex_to_vec(hex: &str) -> std::vec::Vec<u8> { + let mut v = std::vec::Vec::new(); + for i in 0..hex.len() / 2 { + v.push(u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()); + } + v + } + + #[test] + fn test_rfc8452_appendix_c_aes256_16byte_pt_0byte_aad() { + let key_vec = + hex_to_vec("0100000000000000000000000000000000000000000000000000000000000000"); + let nonce_vec = hex_to_vec("030000000000000000000000"); + let pt_vec = hex_to_vec("01000000000000000000000000000000"); + let expected_result = + hex_to_vec("85a01b63025ba19b7fd3ddfc033b3e76c9eac6fa700942702e90862383c6c366"); + + let mut key = [0u8; 32]; + key.copy_from_slice(&key_vec); + let mut nonce = [0u8; 12]; + nonce.copy_from_slice(&nonce_vec); + + let mut out = vec![0u8; pt_vec.len() + TAG_LEN]; + encrypt(&key, &nonce, b"", &pt_vec, &mut out); + assert_eq!(out, expected_result); + + let mut decrypted = vec![0u8; pt_vec.len()]; + decrypt(&key, &nonce, b"", &out, &mut decrypted).expect("Decryption failed"); + assert_eq!(decrypted, pt_vec); + } + + #[test] + fn test_rfc8452_appendix_c_aes256_8byte_pt_1byte_aad() { + let key_vec = + hex_to_vec("0100000000000000000000000000000000000000000000000000000000000000"); + let nonce_vec = hex_to_vec("030000000000000000000000"); + let pt_vec = hex_to_vec("0200000000000000"); + let aad_vec = hex_to_vec("01"); + let expected_result = hex_to_vec("1de22967237a813291213f267e3b452f02d01ae33e4ec854"); + + let mut key = [0u8; 32]; + key.copy_from_slice(&key_vec); + let mut nonce = [0u8; 12]; + nonce.copy_from_slice(&nonce_vec); + + let mut out = vec![0u8; pt_vec.len() + TAG_LEN]; + encrypt(&key, &nonce, &aad_vec, &pt_vec, &mut out); + assert_eq!(out, expected_result); + + let mut decrypted = vec![0u8; pt_vec.len()]; + decrypt(&key, &nonce, &aad_vec, &out, &mut decrypted).expect("Decryption failed"); + assert_eq!(decrypted, pt_vec); + + // Tamper test + out[0] ^= 0x01; + assert_eq!( + decrypt(&key, &nonce, &aad_vec, &out, &mut decrypted), + Err(AuthenticationError) + ); + // Ensure memory was zeroed on failure + assert_eq!(decrypted, vec![0u8; pt_vec.len()]); + } +} diff --git a/crates/aienos-crypto/src/lib.rs b/crates/aienos-crypto/src/lib.rs index b72673f8..4c0c88e8 100644 --- a/crates/aienos-crypto/src/lib.rs +++ b/crates/aienos-crypto/src/lib.rs @@ -3,4 +3,10 @@ //! Shared, allocation-free cryptographic primitives used by the kernel and //! host/bare-metal parsers. +#[cfg(test)] +extern crate std; + +pub mod aes; +pub mod aes_gcm_siv; +pub mod polyval; pub mod sha256; diff --git a/crates/aienos-crypto/src/polyval.rs b/crates/aienos-crypto/src/polyval.rs new file mode 100644 index 00000000..edad7020 --- /dev/null +++ b/crates/aienos-crypto/src/polyval.rs @@ -0,0 +1,144 @@ +//! Pure-Rust, allocation-free POLYVAL universal hash implementation conforming to RFC 8452. +//! +//! Evaluates polynomial authentication tags over GF(2^128) modulo +//! x^128 + x^127 + x^126 + x^121 + 1. + +/// 16-byte POLYVAL block. +pub type Block = [u8; 16]; + +/// POLYVAL state accumulator. +#[derive(Clone, Debug, Default)] +pub struct Polyval { + key: Block, + accumulator: Block, +} + +impl Drop for Polyval { + fn drop(&mut self) { + for b in &mut self.key { + unsafe { core::ptr::write_volatile(b, 0) }; + } + for b in &mut self.accumulator { + unsafe { core::ptr::write_volatile(b, 0) }; + } + } +} + +/// Constant field element x^-1: byte 15 = 0xe1, bytes 0..15 = 0x00. +const X_INV_BYTE_15: u8 = 0xe1; + +/// Multiply polynomial V by x^-1 modulo x^128 + x^127 + x^126 + x^121 + 1. +#[inline(always)] +fn div_x(v: &mut Block) { + let lsb = v[0] & 1; + + // Shift 128-bit array right by 1 bit (little-endian: bit 0 is LSB of byte 0). + let mut carry = 0u8; + for byte in v.iter_mut().rev() { + let next_carry = *byte & 1; + *byte = (*byte >> 1) | (carry << 7); + carry = next_carry; + } + + if lsb != 0 { + v[15] ^= X_INV_BYTE_15; + } +} + +/// Compute dot(a, b) = a * b * x^-128 mod P(x) per RFC 8452 Section 3. +pub fn dot(a: &Block, b: &Block) -> Block { + let mut v = [0u8; 16]; + + for i in 0..128 { + let byte_idx = i / 8; + 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]; + } + } + + div_x(&mut v); + } + + v +} + +impl Polyval { + /// Initialize POLYVAL with a 16-byte authentication key H. + pub fn new(key: &Block) -> Self { + Self { + key: *key, + accumulator: [0u8; 16], + } + } + + /// Reset accumulator to zero. + pub fn reset(&mut self) { + self.accumulator = [0u8; 16]; + } + + /// Process a single 16-byte block: S_j = dot(S_{j-1} ^ X_j, H). + pub fn update_block(&mut self, block: &Block) { + for (acc, b) in self.accumulator.iter_mut().zip(block.iter()) { + *acc ^= b; + } + self.accumulator = dot(&self.accumulator, &self.key); + } + + /// Process arbitrary slice of padded 16-byte blocks. + pub fn update(&mut self, data: &[u8]) { + assert!( + data.len().is_multiple_of(16), + "POLYVAL input must be 16-byte aligned" + ); + let (chunks, _) = data.as_chunks::<16>(); + for chunk in chunks { + self.update_block(chunk); + } + } + + /// Finalize and return current 16-byte accumulator S_s. + pub fn finalize(self) -> Block { + self.accumulator + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex_to_block(hex: &str) -> Block { + assert_eq!(hex.len(), 32); + let mut block = [0u8; 16]; + for i in 0..16 { + block[i] = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap(); + } + block + } + + #[test] + fn test_polyval_rfc8452_section_7_dot() { + let a = hex_to_block("66e94bd4ef8a2c3b884cfa59ca342b2e"); + let b = hex_to_block("ff000000000000000000000000000000"); + let expected = hex_to_block("ebe563401e7e91ea3ad6426b8140c394"); + + let res = dot(&a, &b); + assert_eq!(res, expected); + } + + #[test] + fn test_polyval_rfc8452_appendix_a_worked_example() { + let h = hex_to_block("25629347589242761d31f826ba4b757b"); + let x1 = hex_to_block("4f4f95668c83dfb6401762bb2d01a262"); + let x2 = hex_to_block("d1a24ddd2721d006bbe45f20d3c9f362"); + let expected = hex_to_block("f7a3b47b846119fae5b7866cf5e5b77e"); + + let mut poly = Polyval::new(&h); + poly.update_block(&x1); + poly.update_block(&x2); + assert_eq!(poly.finalize(), expected); + } +} diff --git a/crates/aienos-kernel/src/crypto/envelope.rs b/crates/aienos-kernel/src/crypto/envelope.rs new file mode 100644 index 00000000..bc6a0c5e --- /dev/null +++ b/crates/aienos-kernel/src/crypto/envelope.rs @@ -0,0 +1,458 @@ +//! M5 authenticated streaming envelope over Store v1 (ADR 0017 Section 2.3). +//! +//! Wraps application payload objects in chunked AEAD envelopes using AES-256-GCM-SIV. +//! Chunk size is bounded to 64 KiB to guarantee bounded memory scratchpads during +//! verification, and every chunk authenticates store identity, object kind/version, +//! envelope header, chunk index, and length to prevent splicing, reordering, truncation, +//! or cross-store replay. + +extern crate alloc; + +use alloc::vec::Vec; + +pub use aienos_crypto::aes_gcm_siv::{ + decrypt as raw_decrypt, encrypt as raw_encrypt, AuthenticationError, KEY_LEN, NONCE_LEN, + TAG_LEN, +}; + +/// 8-byte magic for M5 envelopes: "AIENENV1". +pub const ENVELOPE_MAGIC: &[u8; 8] = b"AIENENV1"; +/// Format version for M5 envelopes. +pub const ENVELOPE_VERSION_1: u16 = 1; +/// Cipher suite identifier for AES-256-GCM-SIV per ADR 0017. +pub const CIPHER_SUITE_AES_256_GCM_SIV: u16 = 0x0001; +/// Default chunk size: 64 KiB (65,536 bytes). +pub const DEFAULT_CHUNK_SIZE: u32 = 65536; +/// Envelope header length: fixed 64 bytes. +pub const ENVELOPE_HEADER_LEN: usize = 64; +/// Additional Authenticated Data domain separator prefix for M5 chunks. +pub const CHUNK_AAD_PREFIX: &[u8; 19] = b"AIENOS-M5-CHUNK-V1\0"; +/// Total length of per-chunk AAD: 19 + 16 + 2 + 2 + 64 + 4 + 4 = 111 bytes. +pub const CHUNK_AAD_LEN: usize = 111; + +/// Error conditions encountered when inspecting or decrypting an envelope. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EnvelopeError { + /// Input is smaller than the 64-byte envelope header. + HeaderTooShort, + /// Invalid magic bytes. + InvalidMagic, + /// Unsupported envelope version. + UnsupportedVersion(u16), + /// Unsupported cipher suite. + UnsupportedCipherSuite(u16), + /// Invalid flags. + InvalidFlags(u32), + /// Invalid chunk size (must be > 0 and <= 64 KiB). + InvalidChunkSize(u32), + /// Nonzero reserved bytes. + NonzeroReserved, + /// Ciphertext length does not match expected length from header. + LengthMismatch, + /// AEAD authentication verification failed for a chunk. + AuthenticationFailed, +} + +/// Fixed 64-byte authenticated envelope header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EnvelopeHeader { + pub magic: [u8; 8], + pub envelope_version: u16, + pub cipher_suite: u16, + pub flags: u32, + pub chunk_size: u32, + pub total_plaintext_len: u64, + pub envelope_id: [u8; 16], + pub nonce_prefix: [u8; 8], + pub key_epoch: u64, + pub reserved: u32, +} + +impl EnvelopeHeader { + /// Encode the header into a fixed 64-byte array. + pub fn encode(&self) -> [u8; ENVELOPE_HEADER_LEN] { + let mut out = [0u8; ENVELOPE_HEADER_LEN]; + out[0..8].copy_from_slice(&self.magic); + out[8..10].copy_from_slice(&self.envelope_version.to_le_bytes()); + out[10..12].copy_from_slice(&self.cipher_suite.to_le_bytes()); + out[12..16].copy_from_slice(&self.flags.to_le_bytes()); + out[16..20].copy_from_slice(&self.chunk_size.to_le_bytes()); + out[20..28].copy_from_slice(&self.total_plaintext_len.to_le_bytes()); + out[28..44].copy_from_slice(&self.envelope_id); + out[44..52].copy_from_slice(&self.nonce_prefix); + out[52..60].copy_from_slice(&self.key_epoch.to_le_bytes()); + out[60..64].copy_from_slice(&self.reserved.to_le_bytes()); + out + } + + /// Decode and validate a 64-byte envelope header. + pub fn decode(bytes: &[u8]) -> Result<Self, EnvelopeError> { + if bytes.len() < ENVELOPE_HEADER_LEN { + return Err(EnvelopeError::HeaderTooShort); + } + + let mut magic = [0u8; 8]; + magic.copy_from_slice(&bytes[0..8]); + if magic != *ENVELOPE_MAGIC { + return Err(EnvelopeError::InvalidMagic); + } + + let envelope_version = u16::from_le_bytes([bytes[8], bytes[9]]); + if envelope_version != ENVELOPE_VERSION_1 { + return Err(EnvelopeError::UnsupportedVersion(envelope_version)); + } + + let cipher_suite = u16::from_le_bytes([bytes[10], bytes[11]]); + if cipher_suite != CIPHER_SUITE_AES_256_GCM_SIV { + return Err(EnvelopeError::UnsupportedCipherSuite(cipher_suite)); + } + + let flags = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + if flags != 0 { + return Err(EnvelopeError::InvalidFlags(flags)); + } + + let chunk_size = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]); + if chunk_size == 0 || chunk_size > DEFAULT_CHUNK_SIZE { + return Err(EnvelopeError::InvalidChunkSize(chunk_size)); + } + + let mut total_pt_bytes = [0u8; 8]; + total_pt_bytes.copy_from_slice(&bytes[20..28]); + let total_plaintext_len = u64::from_le_bytes(total_pt_bytes); + + let mut envelope_id = [0u8; 16]; + envelope_id.copy_from_slice(&bytes[28..44]); + + let mut nonce_prefix = [0u8; 8]; + nonce_prefix.copy_from_slice(&bytes[44..52]); + + let mut epoch_bytes = [0u8; 8]; + epoch_bytes.copy_from_slice(&bytes[52..60]); + let key_epoch = u64::from_le_bytes(epoch_bytes); + + let reserved = u32::from_le_bytes([bytes[60], bytes[61], bytes[62], bytes[63]]); + if reserved != 0 { + return Err(EnvelopeError::NonzeroReserved); + } + + Ok(Self { + magic, + envelope_version, + cipher_suite, + flags, + chunk_size, + total_plaintext_len, + envelope_id, + nonce_prefix, + key_epoch, + reserved, + }) + } + + /// Calculate the number of chunks for this envelope. + pub fn chunk_count(&self) -> usize { + if self.total_plaintext_len == 0 { + 1 + } else { + let cs = self.chunk_size as u64; + self.total_plaintext_len.div_ceil(cs) as usize + } + } + + /// Calculate the expected total ciphertext envelope size (header + ciphertext + tags). + pub fn expected_envelope_len(&self) -> usize { + let chunks = self.chunk_count(); + ENVELOPE_HEADER_LEN + (self.total_plaintext_len as usize) + (chunks * TAG_LEN) + } +} + +/// Derive the 12-byte nonce for a specific chunk index: nonce_prefix[8] || chunk_index:u32le. +pub fn derive_chunk_nonce(nonce_prefix: &[u8; 8], chunk_index: u32) -> [u8; NONCE_LEN] { + let mut nonce = [0u8; NONCE_LEN]; + nonce[0..8].copy_from_slice(nonce_prefix); + nonce[8..12].copy_from_slice(&chunk_index.to_le_bytes()); + nonce +} + +/// Format the 111-byte AAD for a specific chunk. +pub fn compute_chunk_aad( + store_uuid: &[u8; 16], + object_kind: u16, + object_version: u16, + header_64b: &[u8; ENVELOPE_HEADER_LEN], + chunk_index: u32, + chunk_plaintext_len: u32, +) -> [u8; CHUNK_AAD_LEN] { + let mut aad = [0u8; CHUNK_AAD_LEN]; + let mut offset = 0; + + aad[offset..offset + 19].copy_from_slice(CHUNK_AAD_PREFIX); + offset += 19; + + aad[offset..offset + 16].copy_from_slice(store_uuid); + offset += 16; + + aad[offset..offset + 2].copy_from_slice(&object_kind.to_le_bytes()); + offset += 2; + + aad[offset..offset + 2].copy_from_slice(&object_version.to_le_bytes()); + offset += 2; + + aad[offset..offset + 64].copy_from_slice(header_64b); + offset += 64; + + aad[offset..offset + 4].copy_from_slice(&chunk_index.to_le_bytes()); + offset += 4; + + aad[offset..offset + 4].copy_from_slice(&chunk_plaintext_len.to_le_bytes()); + offset += 4; + + debug_assert_eq!(offset, CHUNK_AAD_LEN); + aad +} + +/// Encrypt arbitrary plaintext into an authenticated streaming envelope. +#[allow(clippy::too_many_arguments)] +pub fn encrypt_envelope( + key: &[u8; KEY_LEN], + store_uuid: &[u8; 16], + object_kind: u16, + object_version: u16, + envelope_id: &[u8; 16], + nonce_prefix: &[u8; 8], + key_epoch: u64, + plaintext: &[u8], +) -> Vec<u8> { + let header = EnvelopeHeader { + magic: *ENVELOPE_MAGIC, + envelope_version: ENVELOPE_VERSION_1, + cipher_suite: CIPHER_SUITE_AES_256_GCM_SIV, + flags: 0, + chunk_size: DEFAULT_CHUNK_SIZE, + total_plaintext_len: plaintext.len() as u64, + envelope_id: *envelope_id, + nonce_prefix: *nonce_prefix, + key_epoch, + reserved: 0, + }; + + let header_bytes = header.encode(); + let total_envelope_len = header.expected_envelope_len(); + let mut out = Vec::with_capacity(total_envelope_len); + out.extend_from_slice(&header_bytes); + + let chunk_size = header.chunk_size as usize; + + if plaintext.is_empty() { + // Zero-length plaintext has 1 empty chunk producing a 16-byte tag + let nonce = derive_chunk_nonce(nonce_prefix, 0); + let aad = compute_chunk_aad(store_uuid, object_kind, object_version, &header_bytes, 0, 0); + let mut chunk_out = [0u8; TAG_LEN]; + raw_encrypt(key, &nonce, &aad, &[], &mut chunk_out); + out.extend_from_slice(&chunk_out); + } else { + for (i, pt_chunk) in plaintext.chunks(chunk_size).enumerate() { + let chunk_idx = i as u32; + let nonce = derive_chunk_nonce(nonce_prefix, chunk_idx); + let aad = compute_chunk_aad( + store_uuid, + object_kind, + object_version, + &header_bytes, + chunk_idx, + pt_chunk.len() as u32, + ); + let mut chunk_out = alloc::vec![0u8; pt_chunk.len() + TAG_LEN]; + raw_encrypt(key, &nonce, &aad, pt_chunk, &mut chunk_out); + out.extend_from_slice(&chunk_out); + } + } + + debug_assert_eq!(out.len(), total_envelope_len); + out +} + +/// Decrypt an authenticated streaming envelope, returning the verified plaintext. +/// +/// Invariant: Plaintext chunks are verified in private scratch buffers before being +/// committed to the output buffer. Any tag mismatch halts immediately and wipes memory. +pub fn decrypt_envelope( + key: &[u8; KEY_LEN], + store_uuid: &[u8; 16], + object_kind: u16, + object_version: u16, + envelope_bytes: &[u8], +) -> Result<Vec<u8>, EnvelopeError> { + if envelope_bytes.len() < ENVELOPE_HEADER_LEN { + return Err(EnvelopeError::HeaderTooShort); + } + + let header = EnvelopeHeader::decode(&envelope_bytes[0..ENVELOPE_HEADER_LEN])?; + if envelope_bytes.len() != header.expected_envelope_len() { + return Err(EnvelopeError::LengthMismatch); + } + + let mut header_bytes = [0u8; ENVELOPE_HEADER_LEN]; + header_bytes.copy_from_slice(&envelope_bytes[0..ENVELOPE_HEADER_LEN]); + + let chunk_size = header.chunk_size as usize; + let chunk_count = header.chunk_count(); + let mut plaintext = Vec::with_capacity(header.total_plaintext_len as usize); + + let mut cursor = ENVELOPE_HEADER_LEN; + + if header.total_plaintext_len == 0 { + let chunk_bytes = &envelope_bytes[cursor..cursor + TAG_LEN]; + let nonce = derive_chunk_nonce(&header.nonce_prefix, 0); + let aad = compute_chunk_aad(store_uuid, object_kind, object_version, &header_bytes, 0, 0); + + let mut scratchpad = [0u8; 0]; + raw_decrypt(key, &nonce, &aad, chunk_bytes, &mut scratchpad) + .map_err(|_| EnvelopeError::AuthenticationFailed)?; + return Ok(plaintext); + } + + let mut remaining = header.total_plaintext_len as usize; + + for i in 0..chunk_count { + let chunk_idx = i as u32; + let pt_chunk_len = core::cmp::min(remaining, chunk_size); + let ct_chunk_len = pt_chunk_len + TAG_LEN; + + let ct_chunk = &envelope_bytes[cursor..cursor + ct_chunk_len]; + cursor += ct_chunk_len; + remaining -= pt_chunk_len; + + let nonce = derive_chunk_nonce(&header.nonce_prefix, chunk_idx); + let aad = compute_chunk_aad( + store_uuid, + object_kind, + object_version, + &header_bytes, + chunk_idx, + pt_chunk_len as u32, + ); + + // 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() { + // 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) }; + } + return Err(EnvelopeError::AuthenticationFailed); + } + + plaintext.extend_from_slice(&scratchpad); + } + + Ok(plaintext) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_envelope_roundtrip_small() { + let key = [0x42u8; 32]; + let store_uuid = [0x11u8; 16]; + let envelope_id = [0x22u8; 16]; + let nonce_prefix = [0x33u8; 8]; + let pt = b"Sovereign AIENOS M5 Encrypted State"; + + let env = encrypt_envelope( + &key, + &store_uuid, + 16, + 1, + &envelope_id, + &nonce_prefix, + 100, + pt, + ); + + let decrypted = decrypt_envelope(&key, &store_uuid, 16, 1, &env).unwrap(); + assert_eq!(decrypted, pt); + } + + #[test] + fn test_envelope_roundtrip_empty() { + let key = [0x55u8; 32]; + let store_uuid = [0x77u8; 16]; + let envelope_id = [0x88u8; 16]; + let nonce_prefix = [0x99u8; 8]; + let pt = b""; + + let env = encrypt_envelope(&key, &store_uuid, 17, 1, &envelope_id, &nonce_prefix, 1, pt); + + assert_eq!(env.len(), ENVELOPE_HEADER_LEN + TAG_LEN); + let decrypted = decrypt_envelope(&key, &store_uuid, 17, 1, &env).unwrap(); + assert_eq!(decrypted, pt); + } + + #[test] + fn test_envelope_roundtrip_multi_chunk() { + let key = [0xaau8; 32]; + let store_uuid = [0xbbu8; 16]; + let envelope_id = [0xccu8; 16]; + let nonce_prefix = [0xddu8; 8]; + + // 70 KiB of test data (crosses 64 KiB boundary into 2 chunks) + let mut pt = alloc::vec![0u8; 70 * 1024]; + for (i, b) in pt.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + + let env = encrypt_envelope( + &key, + &store_uuid, + 18, + 1, + &envelope_id, + &nonce_prefix, + 42, + &pt, + ); + + let header = EnvelopeHeader::decode(&env).unwrap(); + assert_eq!(header.chunk_count(), 2); + assert_eq!(env.len(), ENVELOPE_HEADER_LEN + pt.len() + 2 * TAG_LEN); + + let decrypted = decrypt_envelope(&key, &store_uuid, 18, 1, &env).unwrap(); + assert_eq!(decrypted, pt); + } + + #[test] + fn test_envelope_cross_store_and_kind_binding() { + let key = [0x12u8; 32]; + let store_uuid = [0x34u8; 16]; + let other_store = [0x99u8; 16]; + let envelope_id = [0x56u8; 16]; + let nonce_prefix = [0x78u8; 8]; + let pt = b"Confidential branch checkpoint"; + + let env = encrypt_envelope(&key, &store_uuid, 20, 1, &envelope_id, &nonce_prefix, 1, pt); + + // Foreign store UUID must fail verification + assert_eq!( + decrypt_envelope(&key, &other_store, 20, 1, &env), + Err(EnvelopeError::AuthenticationFailed) + ); + + // Mismatched object kind must fail verification + assert_eq!( + decrypt_envelope(&key, &store_uuid, 21, 1, &env), + Err(EnvelopeError::AuthenticationFailed) + ); + + // Bit-flip in ciphertext must fail verification + let mut corrupted = env.clone(); + corrupted[ENVELOPE_HEADER_LEN + 5] ^= 0x01; + assert_eq!( + decrypt_envelope(&key, &store_uuid, 20, 1, &corrupted), + Err(EnvelopeError::AuthenticationFailed) + ); + } +} diff --git a/crates/aienos-kernel/src/crypto/mod.rs b/crates/aienos-kernel/src/crypto/mod.rs index 9f8d4817..8f072827 100644 --- a/crates/aienos-kernel/src/crypto/mod.rs +++ b/crates/aienos-kernel/src/crypto/mod.rs @@ -1,9 +1,14 @@ //! Sovereign cryptographic primitives for AIENOS. +pub mod envelope; pub mod hkdf; pub mod hmac; pub mod sha256; +pub use envelope::{ + decrypt_envelope, derive_chunk_nonce, encrypt_envelope, EnvelopeError, EnvelopeHeader, + DEFAULT_CHUNK_SIZE, ENVELOPE_HEADER_LEN, ENVELOPE_MAGIC, ENVELOPE_VERSION_1, +}; pub use hkdf::{hkdf_expand, hkdf_extract, HkdfError}; pub use hmac::{constant_time_eq, hmac_sha256, HmacSha256}; pub use sha256::{hash, Digest, Sha256}; diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index 28dc2eac..c196366e 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -39,6 +39,7 @@ pub mod recovery; pub mod recovery_core; pub mod report; pub mod scheduler; +pub mod security; pub mod shell; pub mod smmu; pub mod store; diff --git a/crates/aienos-kernel/src/security.rs b/crates/aienos-kernel/src/security.rs new file mode 100644 index 00000000..905c499a --- /dev/null +++ b/crates/aienos-kernel/src/security.rs @@ -0,0 +1,896 @@ +//! M5 Key Hierarchy, Security Manifests, and Anti-Rollback (ADR 0017). +//! +//! Normative implementation of storage security roots: +//! - Subkey derivation via HKDF-SHA256 (K_cortex, K_agent, K_artifact, K_root_auth) +//! - KeySlotManifest (kind = 21, plaintext bootstrap object with up to 4 keyslots) +//! - SecurityManifest (kind = 22, 256-byte fixed root object authenticated under K_root_auth) +//! - MigrationManifest (kind = 23, identity-preserving migration authorization) +//! - AntiRollbackSource trait, RollbackAnchor, and epoch validation protocol. + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::crypto::hkdf::hkdf_expand; +use crate::crypto::hmac::{constant_time_eq, HmacSha256}; +use crate::store::v1::ObjectId; +use aienos_crypto::aes_gcm_siv::{decrypt as raw_decrypt, encrypt as raw_encrypt, TAG_LEN}; + +pub const KIND_KEYSLOT_MANIFEST: u16 = 21; +pub const KIND_SECURITY_MANIFEST: u16 = 22; +pub const KIND_MIGRATION_MANIFEST: u16 = 23; + +pub const KEYSLOT_MANIFEST_MAGIC: &[u8; 8] = b"AIENKSL1"; +pub const SECURITY_MANIFEST_MAGIC: &[u8; 8] = b"AIENSEC1"; +pub const MIGRATION_MANIFEST_MAGIC: &[u8; 8] = b"AIENMIG1"; + +pub const SECURITY_FORMAT_VERSION: u16 = 1; +pub const SECURITY_MANIFEST_SIZE: usize = 256; +pub const KEYSLOT_HEADER_SIZE: usize = 128; +pub const KEYSLOT_DESCRIPTOR_SIZE: usize = 128; +pub const KEYSLOT_MAX_SLOTS: usize = 4; +pub const KEYSLOT_MAX_ARENA_BYTES: usize = 32768; // 32 KiB +pub const ROOT_AUTH_DOMAIN_PREFIX: &[u8; 23] = b"AIENOS-M5-ROOT-AUTH-V1\0"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SecurityError { + FormatError(&'static str), + BufferTooShort, + InvalidMagic, + UnsupportedVersion, + NonzeroReserved, + AuthenticationFailed, + KeySlotIndexOutOfRange, + PayloadArenaOverflow, +} + +// --------------------------------------------------------------------------- +// 1. Subkey Derivation from K_vol +// --------------------------------------------------------------------------- + +/// Subkeys derived deterministically from K_vol via HKDF-SHA256 (ADR 0017 Section 2.2). +#[derive(Clone)] +pub struct DerivedSubkeys { + pub k_cortex: [u8; 32], + pub k_agent: [u8; 32], + pub k_artifact: [u8; 32], + pub k_root_auth: [u8; 32], +} + +impl Drop for DerivedSubkeys { + fn drop(&mut self) { + for b in &mut self.k_cortex { + unsafe { core::ptr::write_volatile(b, 0) }; + } + for b in &mut self.k_agent { + unsafe { core::ptr::write_volatile(b, 0) }; + } + for b in &mut self.k_artifact { + unsafe { core::ptr::write_volatile(b, 0) }; + } + for b in &mut self.k_root_auth { + unsafe { core::ptr::write_volatile(b, 0) }; + } + } +} + +/// Derive operational subkeys from K_vol using HKDF-SHA256 domain-separated labels. +pub fn derive_subkeys(k_vol: &[u8; 32]) -> DerivedSubkeys { + let mut k_cortex = [0u8; 32]; + let mut k_agent = [0u8; 32]; + let mut k_artifact = [0u8; 32]; + let mut k_root_auth = [0u8; 32]; + + hkdf_expand(k_vol, b"AIENOS/M5/CORTEX-V1", &mut k_cortex) + .expect("HKDF expand 32 bytes cannot fail"); + hkdf_expand(k_vol, b"AIENOS/M5/AGENT-STATE-V1", &mut k_agent) + .expect("HKDF expand 32 bytes cannot fail"); + hkdf_expand(k_vol, b"AIENOS/M5/ARTIFACT-V1", &mut k_artifact) + .expect("HKDF expand 32 bytes cannot fail"); + hkdf_expand(k_vol, b"AIENOS/M5/ROOT-AUTH-V1", &mut k_root_auth) + .expect("HKDF expand 32 bytes cannot fail"); + + DerivedSubkeys { + k_cortex, + k_agent, + k_artifact, + k_root_auth, + } +} + +// --------------------------------------------------------------------------- +// 2. KeySlotManifest (kind = 21) +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum KeySlotType { + Empty = 0, + Tpm2PolicyAuthorize = 1, + RecoveryArgon2id = 2, + RecoveryRawSecret = 3, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct KeySlotDescriptor { + pub slot_type: KeySlotType, + pub wrap_suite: u8, + pub kdf_suite: u8, + pub flags: u8, + pub slot_id: u32, + pub key_epoch: u64, + pub salt: [u8; 16], + pub argon_m_kib: u32, + pub argon_t_cost: u32, + pub argon_p_cost: u32, + pub wrap_nonce: [u8; 12], + pub wrapped_k_vol: [u8; 32], + pub wrap_tag: [u8; 16], + pub payload_offset: u32, + pub payload_length: u32, + pub reserved: [u8; 16], +} + +impl KeySlotDescriptor { + pub const EMPTY: Self = Self { + slot_type: KeySlotType::Empty, + wrap_suite: 0x01, + kdf_suite: 0x00, + flags: 0, + slot_id: 0, + key_epoch: 0, + salt: [0; 16], + argon_m_kib: 0, + argon_t_cost: 0, + argon_p_cost: 0, + wrap_nonce: [0; 12], + wrapped_k_vol: [0; 32], + wrap_tag: [0; 16], + payload_offset: 0, + payload_length: 0, + reserved: [0; 16], + }; + + pub fn encode(&self) -> [u8; KEYSLOT_DESCRIPTOR_SIZE] { + let mut out = [0u8; KEYSLOT_DESCRIPTOR_SIZE]; + out[0] = self.slot_type as u8; + out[1] = self.wrap_suite; + out[2] = self.kdf_suite; + out[3] = self.flags; + out[4..8].copy_from_slice(&self.slot_id.to_le_bytes()); + out[8..16].copy_from_slice(&self.key_epoch.to_le_bytes()); + out[16..32].copy_from_slice(&self.salt); + out[32..36].copy_from_slice(&self.argon_m_kib.to_le_bytes()); + out[36..40].copy_from_slice(&self.argon_t_cost.to_le_bytes()); + out[40..44].copy_from_slice(&self.argon_p_cost.to_le_bytes()); + out[44..56].copy_from_slice(&self.wrap_nonce); + out[56..88].copy_from_slice(&self.wrapped_k_vol); + out[88..104].copy_from_slice(&self.wrap_tag); + out[104..108].copy_from_slice(&self.payload_offset.to_le_bytes()); + out[108..112].copy_from_slice(&self.payload_length.to_le_bytes()); + out[112..128].copy_from_slice(&self.reserved); + out + } + + pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> { + if bytes.len() < KEYSLOT_DESCRIPTOR_SIZE { + return Err(SecurityError::BufferTooShort); + } + let slot_type = match bytes[0] { + 0 => KeySlotType::Empty, + 1 => KeySlotType::Tpm2PolicyAuthorize, + 2 => KeySlotType::RecoveryArgon2id, + 3 => KeySlotType::RecoveryRawSecret, + _ => return Err(SecurityError::FormatError("unknown slot type")), + }; + let wrap_suite = bytes[1]; + let kdf_suite = bytes[2]; + let flags = bytes[3]; + let slot_id = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + let key_epoch = u64::from_le_bytes([ + bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], + ]); + let mut salt = [0u8; 16]; + salt.copy_from_slice(&bytes[16..32]); + let argon_m_kib = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]); + let argon_t_cost = u32::from_le_bytes([bytes[36], bytes[37], bytes[38], bytes[39]]); + let argon_p_cost = u32::from_le_bytes([bytes[40], bytes[41], bytes[42], bytes[43]]); + + if argon_m_kib > 131072 || argon_t_cost > 10 || argon_p_cost > 16 { + return Err(SecurityError::FormatError( + "argon2 parameters exceed bounds", + )); + } + + let mut wrap_nonce = [0u8; 12]; + wrap_nonce.copy_from_slice(&bytes[44..56]); + let mut wrapped_k_vol = [0u8; 32]; + wrapped_k_vol.copy_from_slice(&bytes[56..88]); + let mut wrap_tag = [0u8; 16]; + wrap_tag.copy_from_slice(&bytes[88..104]); + + let payload_offset = u32::from_le_bytes([bytes[104], bytes[105], bytes[106], bytes[107]]); + let payload_length = u32::from_le_bytes([bytes[108], bytes[109], bytes[110], bytes[111]]); + + let mut reserved = [0u8; 16]; + reserved.copy_from_slice(&bytes[112..128]); + if reserved.iter().any(|b| *b != 0) { + return Err(SecurityError::NonzeroReserved); + } + + Ok(Self { + slot_type, + wrap_suite, + kdf_suite, + flags, + slot_id, + key_epoch, + salt, + argon_m_kib, + argon_t_cost, + argon_p_cost, + wrap_nonce, + wrapped_k_vol, + wrap_tag, + payload_offset, + payload_length, + reserved, + }) + } + + /// Unwrap K_vol given the corresponding 32-byte KEK. + pub fn unwrap_k_vol(&self, kek: &[u8; 32]) -> Result<[u8; 32], SecurityError> { + if self.slot_type == KeySlotType::Empty { + return Err(SecurityError::FormatError("cannot unwrap empty keyslot")); + } + if self.wrap_suite != 0x01 { + return Err(SecurityError::FormatError("unsupported wrap suite")); + } + + let mut ciphertext_and_tag = [0u8; 32 + TAG_LEN]; + ciphertext_and_tag[0..32].copy_from_slice(&self.wrapped_k_vol); + ciphertext_and_tag[32..48].copy_from_slice(&self.wrap_tag); + + let mut k_vol = [0u8; 32]; + let aad = self.slot_id.to_le_bytes(); + + raw_decrypt(kek, &self.wrap_nonce, &aad, &ciphertext_and_tag, &mut k_vol) + .map_err(|_| SecurityError::AuthenticationFailed)?; + + Ok(k_vol) + } + + /// Wrap K_vol with the given 32-byte KEK and fresh 12-byte nonce. + pub fn wrap_k_vol(&mut self, kek: &[u8; 32], k_vol: &[u8; 32], nonce: &[u8; 12]) { + self.wrap_suite = 0x01; + self.wrap_nonce = *nonce; + let aad = self.slot_id.to_le_bytes(); + + let mut out = [0u8; 32 + TAG_LEN]; + raw_encrypt(kek, nonce, &aad, k_vol, &mut out); + + self.wrapped_k_vol.copy_from_slice(&out[0..32]); + self.wrap_tag.copy_from_slice(&out[32..48]); + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct KeySlotManifest { + pub store_uuid: [u8; 16], + pub manifest_sequence: u64, + pub previous_keyslot_manifest_id: ObjectId, + pub active_key_epoch: u64, + pub slot_count: u32, + pub slots: [KeySlotDescriptor; KEYSLOT_MAX_SLOTS], + pub payload_arena: Vec<u8>, +} + +impl KeySlotManifest { + pub fn encode(&self) -> Result<Vec<u8>, SecurityError> { + if self.payload_arena.len() > KEYSLOT_MAX_ARENA_BYTES { + return Err(SecurityError::PayloadArenaOverflow); + } + let total_size = KEYSLOT_HEADER_SIZE + + (KEYSLOT_MAX_SLOTS * KEYSLOT_DESCRIPTOR_SIZE) + + self.payload_arena.len(); + let mut out = Vec::with_capacity(total_size); + + out.extend_from_slice(KEYSLOT_MANIFEST_MAGIC); + out.extend_from_slice(&SECURITY_FORMAT_VERSION.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); // flags + out.extend_from_slice(&self.store_uuid); + out.extend_from_slice(&self.manifest_sequence.to_le_bytes()); + out.extend_from_slice(&self.previous_keyslot_manifest_id.0); + out.extend_from_slice(&self.active_key_epoch.to_le_bytes()); + out.extend_from_slice(&self.slot_count.to_le_bytes()); + out.extend_from_slice(&[0u8; 48]); // reserved + + for slot in &self.slots { + out.extend_from_slice(&slot.encode()); + } + + out.extend_from_slice(&self.payload_arena); + Ok(out) + } + + pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> { + let fixed_header_len = KEYSLOT_HEADER_SIZE + (KEYSLOT_MAX_SLOTS * KEYSLOT_DESCRIPTOR_SIZE); + if bytes.len() < fixed_header_len { + return Err(SecurityError::BufferTooShort); + } + + if &bytes[0..8] != KEYSLOT_MANIFEST_MAGIC { + return Err(SecurityError::InvalidMagic); + } + + let format_version = u16::from_le_bytes([bytes[8], bytes[9]]); + if format_version != SECURITY_FORMAT_VERSION { + return Err(SecurityError::UnsupportedVersion); + } + + let flags = u16::from_le_bytes([bytes[10], bytes[11]]); + if flags != 0 { + return Err(SecurityError::FormatError("nonzero keyslot manifest flags")); + } + + let mut store_uuid = [0u8; 16]; + store_uuid.copy_from_slice(&bytes[12..28]); + + let manifest_sequence = u64::from_le_bytes([ + bytes[28], bytes[29], bytes[30], bytes[31], bytes[32], bytes[33], bytes[34], bytes[35], + ]); + + let mut prev_id = [0u8; 32]; + prev_id.copy_from_slice(&bytes[36..68]); + let previous_keyslot_manifest_id = ObjectId(prev_id); + + let active_key_epoch = u64::from_le_bytes([ + bytes[68], bytes[69], bytes[70], bytes[71], bytes[72], bytes[73], bytes[74], bytes[75], + ]); + + let slot_count = u32::from_le_bytes([bytes[76], bytes[77], bytes[78], bytes[79]]); + if slot_count as usize > KEYSLOT_MAX_SLOTS { + return Err(SecurityError::KeySlotIndexOutOfRange); + } + + if bytes[80..128].iter().any(|b| *b != 0) { + return Err(SecurityError::NonzeroReserved); + } + + let mut slots = [KeySlotDescriptor::EMPTY; KEYSLOT_MAX_SLOTS]; + for (i, slot) in slots.iter_mut().enumerate() { + let start = KEYSLOT_HEADER_SIZE + (i * KEYSLOT_DESCRIPTOR_SIZE); + *slot = KeySlotDescriptor::decode(&bytes[start..start + KEYSLOT_DESCRIPTOR_SIZE])?; + } + + let arena_bytes = &bytes[fixed_header_len..]; + if arena_bytes.len() > KEYSLOT_MAX_ARENA_BYTES { + return Err(SecurityError::PayloadArenaOverflow); + } + + Ok(Self { + store_uuid, + manifest_sequence, + previous_keyslot_manifest_id, + active_key_epoch, + slot_count, + slots, + payload_arena: arena_bytes.to_vec(), + }) + } +} + +// --------------------------------------------------------------------------- +// 3. SecurityManifest (kind = 22) +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SecurityManifest { + pub format_version: u16, + pub flags: u16, + pub reserved: u32, + pub store_uuid: [u8; 16], + pub generation: u64, + pub security_sequence: u64, + pub epoch: u64, + pub key_epoch: u64, + pub previous_security_manifest_id: ObjectId, + pub keyslot_manifest_id: ObjectId, + pub agent_root_id: ObjectId, + pub continuity_manifest_id: ObjectId, + pub migration_manifest_id: ObjectId, + pub root_mac: [u8; 32], +} + +impl SecurityManifest { + /// Compute HMAC-SHA256 over header bytes [0..224] using K_root_auth. + pub fn compute_mac(&self, k_root_auth: &[u8; 32]) -> [u8; 32] { + let mut unsigned_bytes = [0u8; 224]; + unsigned_bytes[0..8].copy_from_slice(SECURITY_MANIFEST_MAGIC); + unsigned_bytes[8..10].copy_from_slice(&self.format_version.to_le_bytes()); + unsigned_bytes[10..12].copy_from_slice(&self.flags.to_le_bytes()); + unsigned_bytes[12..16].copy_from_slice(&self.reserved.to_le_bytes()); + unsigned_bytes[16..32].copy_from_slice(&self.store_uuid); + unsigned_bytes[32..40].copy_from_slice(&self.generation.to_le_bytes()); + unsigned_bytes[40..48].copy_from_slice(&self.security_sequence.to_le_bytes()); + unsigned_bytes[48..56].copy_from_slice(&self.epoch.to_le_bytes()); + unsigned_bytes[56..64].copy_from_slice(&self.key_epoch.to_le_bytes()); + unsigned_bytes[64..96].copy_from_slice(&self.previous_security_manifest_id.0); + unsigned_bytes[96..128].copy_from_slice(&self.keyslot_manifest_id.0); + unsigned_bytes[128..160].copy_from_slice(&self.agent_root_id.0); + unsigned_bytes[160..192].copy_from_slice(&self.continuity_manifest_id.0); + unsigned_bytes[192..224].copy_from_slice(&self.migration_manifest_id.0); + + let mut hmac = HmacSha256::new(k_root_auth); + hmac.update(ROOT_AUTH_DOMAIN_PREFIX); + hmac.update(&unsigned_bytes); + hmac.finalize() + } + + /// Sign this manifest in place under K_root_auth. + pub fn sign(&mut self, k_root_auth: &[u8; 32]) { + self.root_mac = self.compute_mac(k_root_auth); + } + + /// Verify this manifest's root_mac in constant time. + pub fn verify(&self, k_root_auth: &[u8; 32]) -> bool { + let expected = self.compute_mac(k_root_auth); + constant_time_eq(&self.root_mac, &expected) + } + + /// Encode the 256-byte SecurityManifest. + pub fn encode(&self) -> [u8; SECURITY_MANIFEST_SIZE] { + let mut out = [0u8; SECURITY_MANIFEST_SIZE]; + out[0..8].copy_from_slice(SECURITY_MANIFEST_MAGIC); + out[8..10].copy_from_slice(&self.format_version.to_le_bytes()); + out[10..12].copy_from_slice(&self.flags.to_le_bytes()); + out[12..16].copy_from_slice(&self.reserved.to_le_bytes()); + out[16..32].copy_from_slice(&self.store_uuid); + out[32..40].copy_from_slice(&self.generation.to_le_bytes()); + out[40..48].copy_from_slice(&self.security_sequence.to_le_bytes()); + out[48..56].copy_from_slice(&self.epoch.to_le_bytes()); + out[56..64].copy_from_slice(&self.key_epoch.to_le_bytes()); + out[64..96].copy_from_slice(&self.previous_security_manifest_id.0); + out[96..128].copy_from_slice(&self.keyslot_manifest_id.0); + out[128..160].copy_from_slice(&self.agent_root_id.0); + out[160..192].copy_from_slice(&self.continuity_manifest_id.0); + out[192..224].copy_from_slice(&self.migration_manifest_id.0); + out[224..256].copy_from_slice(&self.root_mac); + out + } + + /// Decode and structurally validate a 256-byte SecurityManifest. + pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> { + if bytes.len() != SECURITY_MANIFEST_SIZE { + return Err(SecurityError::BufferTooShort); + } + + if &bytes[0..8] != SECURITY_MANIFEST_MAGIC { + return Err(SecurityError::InvalidMagic); + } + + let format_version = u16::from_le_bytes([bytes[8], bytes[9]]); + if format_version != SECURITY_FORMAT_VERSION { + return Err(SecurityError::UnsupportedVersion); + } + + let flags = u16::from_le_bytes([bytes[10], bytes[11]]); + if flags != 0 { + return Err(SecurityError::FormatError( + "nonzero security manifest flags", + )); + } + + let reserved = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + if reserved != 0 { + return Err(SecurityError::NonzeroReserved); + } + + let mut store_uuid = [0u8; 16]; + store_uuid.copy_from_slice(&bytes[16..32]); + + let generation = u64::from_le_bytes([ + bytes[32], bytes[33], bytes[34], bytes[35], bytes[36], bytes[37], bytes[38], bytes[39], + ]); + let security_sequence = u64::from_le_bytes([ + bytes[40], bytes[41], bytes[42], bytes[43], bytes[44], bytes[45], bytes[46], bytes[47], + ]); + let epoch = u64::from_le_bytes([ + bytes[48], bytes[49], bytes[50], bytes[51], bytes[52], bytes[53], bytes[54], bytes[55], + ]); + let key_epoch = u64::from_le_bytes([ + bytes[56], bytes[57], bytes[58], bytes[59], bytes[60], bytes[61], bytes[62], bytes[63], + ]); + + let mut prev_id = [0u8; 32]; + prev_id.copy_from_slice(&bytes[64..96]); + let previous_security_manifest_id = ObjectId(prev_id); + + let mut keyslot_id = [0u8; 32]; + keyslot_id.copy_from_slice(&bytes[96..128]); + let keyslot_manifest_id = ObjectId(keyslot_id); + + let mut agent_id = [0u8; 32]; + agent_id.copy_from_slice(&bytes[128..160]); + let agent_root_id = ObjectId(agent_id); + + let mut cont_id = [0u8; 32]; + cont_id.copy_from_slice(&bytes[160..192]); + let continuity_manifest_id = ObjectId(cont_id); + + let mut mig_id = [0u8; 32]; + mig_id.copy_from_slice(&bytes[192..224]); + let migration_manifest_id = ObjectId(mig_id); + + let mut root_mac = [0u8; 32]; + root_mac.copy_from_slice(&bytes[224..256]); + + Ok(Self { + format_version, + flags, + reserved, + store_uuid, + generation, + security_sequence, + epoch, + key_epoch, + previous_security_manifest_id, + keyslot_manifest_id, + agent_root_id, + continuity_manifest_id, + migration_manifest_id, + root_mac, + }) + } +} + +// --------------------------------------------------------------------------- +// 4. MigrationManifest (kind = 23) +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MigrationManifest { + pub format_version: u16, + pub flags: u16, + pub reserved: u32, + pub agent_root_id: ObjectId, + pub genesis_store_uuid: [u8; 16], + pub origin_store_uuid: [u8; 16], + pub target_store_uuid: [u8; 16], + pub origin_security_manifest_id: ObjectId, + pub origin_continuity_manifest_id: ObjectId, + pub origin_sequence: u64, + pub origin_incarnation: u64, + pub origin_epoch: u64, + pub origin_rollback_digest: [u8; 32], + pub migration_sequence: u64, + pub offline_signature: [u8; 64], +} + +pub const MIGRATION_MANIFEST_SIZE: usize = + 8 + 2 + 2 + 4 + 32 + 16 + 16 + 16 + 32 + 32 + 8 + 8 + 8 + 32 + 8 + 64; + +impl MigrationManifest { + pub fn encode(&self) -> [u8; MIGRATION_MANIFEST_SIZE] { + let mut out = [0u8; MIGRATION_MANIFEST_SIZE]; + out[0..8].copy_from_slice(MIGRATION_MANIFEST_MAGIC); + out[8..10].copy_from_slice(&self.format_version.to_le_bytes()); + out[10..12].copy_from_slice(&self.flags.to_le_bytes()); + out[12..16].copy_from_slice(&self.reserved.to_le_bytes()); + out[16..48].copy_from_slice(&self.agent_root_id.0); + out[48..64].copy_from_slice(&self.genesis_store_uuid); + out[64..80].copy_from_slice(&self.origin_store_uuid); + out[80..96].copy_from_slice(&self.target_store_uuid); + out[96..128].copy_from_slice(&self.origin_security_manifest_id.0); + out[128..160].copy_from_slice(&self.origin_continuity_manifest_id.0); + out[160..168].copy_from_slice(&self.origin_sequence.to_le_bytes()); + out[168..176].copy_from_slice(&self.origin_incarnation.to_le_bytes()); + out[176..184].copy_from_slice(&self.origin_epoch.to_le_bytes()); + out[184..216].copy_from_slice(&self.origin_rollback_digest); + out[216..224].copy_from_slice(&self.migration_sequence.to_le_bytes()); + out[224..288].copy_from_slice(&self.offline_signature); + out + } + + pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> { + if bytes.len() != MIGRATION_MANIFEST_SIZE { + return Err(SecurityError::BufferTooShort); + } + if &bytes[0..8] != MIGRATION_MANIFEST_MAGIC { + return Err(SecurityError::InvalidMagic); + } + let format_version = u16::from_le_bytes([bytes[8], bytes[9]]); + if format_version != SECURITY_FORMAT_VERSION { + return Err(SecurityError::UnsupportedVersion); + } + let flags = u16::from_le_bytes([bytes[10], bytes[11]]); + if flags != 0 { + return Err(SecurityError::FormatError("nonzero migration flags")); + } + let reserved = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + if reserved != 0 { + return Err(SecurityError::NonzeroReserved); + } + + let mut agent_root_id = [0u8; 32]; + agent_root_id.copy_from_slice(&bytes[16..48]); + let mut genesis_store_uuid = [0u8; 16]; + genesis_store_uuid.copy_from_slice(&bytes[48..64]); + let mut origin_store_uuid = [0u8; 16]; + origin_store_uuid.copy_from_slice(&bytes[64..80]); + let mut target_store_uuid = [0u8; 16]; + target_store_uuid.copy_from_slice(&bytes[80..96]); + + let mut orig_sec = [0u8; 32]; + orig_sec.copy_from_slice(&bytes[96..128]); + let mut orig_cont = [0u8; 32]; + orig_cont.copy_from_slice(&bytes[128..160]); + + let origin_sequence = u64::from_le_bytes([ + bytes[160], bytes[161], bytes[162], bytes[163], bytes[164], bytes[165], bytes[166], + bytes[167], + ]); + let origin_incarnation = u64::from_le_bytes([ + bytes[168], bytes[169], bytes[170], bytes[171], bytes[172], bytes[173], bytes[174], + bytes[175], + ]); + let origin_epoch = u64::from_le_bytes([ + bytes[176], bytes[177], bytes[178], bytes[179], bytes[180], bytes[181], bytes[182], + bytes[183], + ]); + + let mut origin_rollback_digest = [0u8; 32]; + origin_rollback_digest.copy_from_slice(&bytes[184..216]); + + let migration_sequence = u64::from_le_bytes([ + bytes[216], bytes[217], bytes[218], bytes[219], bytes[220], bytes[221], bytes[222], + bytes[223], + ]); + + let mut offline_signature = [0u8; 64]; + offline_signature.copy_from_slice(&bytes[224..288]); + + Ok(Self { + format_version, + flags, + reserved, + agent_root_id: ObjectId(agent_root_id), + genesis_store_uuid, + origin_store_uuid, + target_store_uuid, + origin_security_manifest_id: ObjectId(orig_sec), + origin_continuity_manifest_id: ObjectId(orig_cont), + origin_sequence, + origin_incarnation, + origin_epoch, + origin_rollback_digest, + migration_sequence, + offline_signature, + }) + } +} + +// --------------------------------------------------------------------------- +// 5. AntiRollbackSource & Boot Protocol (ADR 0017 Section 2.6) +// --------------------------------------------------------------------------- + +/// Off-disk hardware anti-rollback anchor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RollbackAnchor { + pub store_uuid: [u8; 16], + pub epoch: u64, + pub commit_record_id: ObjectId, + pub security_root_digest: [u8; 32], +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AntiRollbackError { + DeviceError, + PermissionDenied, +} + +/// Abstract hardware off-disk anti-rollback source (TPM NV index, RPMB, or secure flash). +pub trait AntiRollbackSource { + fn read_anchor( + &self, + store_uuid: &[u8; 16], + ) -> Result<Option<RollbackAnchor>, AntiRollbackError>; + fn advance_anchor(&mut self, anchor: &RollbackAnchor) -> Result<(), AntiRollbackError>; +} + +/// Evaluation decision produced by comparing disk security state against the hardware anchor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AntiRollbackDecision { + /// Valid normal resume: disk matches the current anchored security epoch. + ValidResume, + /// Prepared unanchored epoch: disk committed epoch E+1, but anchor has not advanced yet. + /// External effects remain frozen until the anchor advancement completes. + PreparedEpochAdvance { + disk_epoch: u64, + disk_digest: [u8; 32], + }, + /// Replay detected: halt into Recovery Core (RecoveryRequired::RollbackDetected). + RollbackDetected(&'static str), + /// Inconsistent epoch jump: halt into Recovery Core (RecoveryRequired::InconsistentEpoch). + InconsistentEpoch(&'static str), +} + +/// Validate disk security state against the hardware anti-rollback anchor per ADR 0017 Section 2.6. +pub fn evaluate_anti_rollback( + disk_epoch: u64, + disk_digest: &[u8; 32], + anchor: Option<&RollbackAnchor>, +) -> AntiRollbackDecision { + let Some(anchor) = anchor else { + // First boot / genesis initialization + return AntiRollbackDecision::PreparedEpochAdvance { + disk_epoch, + disk_digest: *disk_digest, + }; + }; + + if disk_epoch == anchor.epoch && constant_time_eq(disk_digest, &anchor.security_root_digest) { + AntiRollbackDecision::ValidResume + } else if disk_epoch == anchor.epoch + 1 { + AntiRollbackDecision::PreparedEpochAdvance { + disk_epoch, + disk_digest: *disk_digest, + } + } else if disk_epoch < anchor.epoch { + AntiRollbackDecision::RollbackDetected("disk epoch behind anchor (rollback detected)") + } else if disk_epoch == anchor.epoch + && !constant_time_eq(disk_digest, &anchor.security_root_digest) + { + AntiRollbackDecision::RollbackDetected( + "digest mismatch at current epoch (rollback detected)", + ) + } else { + AntiRollbackDecision::InconsistentEpoch("disk epoch jumped ahead of anchor (> anchor + 1)") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_subkey_derivation_separation() { + let k_vol = [0x5au8; 32]; + let subkeys = derive_subkeys(&k_vol); + + assert_ne!(subkeys.k_cortex, subkeys.k_agent); + assert_ne!(subkeys.k_cortex, subkeys.k_artifact); + assert_ne!(subkeys.k_cortex, subkeys.k_root_auth); + assert_ne!(subkeys.k_agent, subkeys.k_root_auth); + assert_ne!(subkeys.k_cortex, k_vol); + } + + #[test] + fn test_keyslot_manifest_roundtrip_and_unwrap() { + let k_vol = [0x77u8; 32]; + let k_recovery_kek = [0x88u8; 32]; + let store_uuid = [0x11u8; 16]; + + let mut slot0 = KeySlotDescriptor::EMPTY; + slot0.slot_type = KeySlotType::RecoveryRawSecret; + slot0.slot_id = 0; + slot0.key_epoch = 1; + slot0.wrap_k_vol(&k_recovery_kek, &k_vol, &[0x33u8; 12]); + + let manifest = KeySlotManifest { + store_uuid, + manifest_sequence: 1, + previous_keyslot_manifest_id: ObjectId([0; 32]), + active_key_epoch: 1, + slot_count: 1, + slots: [ + slot0, + KeySlotDescriptor::EMPTY, + KeySlotDescriptor::EMPTY, + KeySlotDescriptor::EMPTY, + ], + payload_arena: alloc::vec![0xaa, 0xbb, 0xcc], + }; + + let encoded = manifest.encode().unwrap(); + let decoded = KeySlotManifest::decode(&encoded).unwrap(); + + assert_eq!(decoded.store_uuid, store_uuid); + assert_eq!(decoded.slot_count, 1); + assert_eq!(decoded.payload_arena, alloc::vec![0xaa, 0xbb, 0xcc]); + + // Unwrapping with valid KEK succeeds and yields exact original K_vol + let unwrapped = decoded.slots[0].unwrap_k_vol(&k_recovery_kek).unwrap(); + assert_eq!(unwrapped, k_vol); + + // Unwrapping with wrong KEK fails authentication + let wrong_kek = [0x99u8; 32]; + assert_eq!( + decoded.slots[0].unwrap_k_vol(&wrong_kek), + Err(SecurityError::AuthenticationFailed) + ); + } + + #[test] + fn test_security_manifest_roundtrip_and_mac() { + let k_root_auth = [0x44u8; 32]; + let store_uuid = [0x22u8; 16]; + + let mut manifest = SecurityManifest { + format_version: 1, + flags: 0, + reserved: 0, + store_uuid, + generation: 10, + security_sequence: 1, + epoch: 5, + key_epoch: 1, + previous_security_manifest_id: ObjectId([0; 32]), + keyslot_manifest_id: ObjectId([1; 32]), + agent_root_id: ObjectId([2; 32]), + continuity_manifest_id: ObjectId([3; 32]), + migration_manifest_id: ObjectId([0; 32]), + root_mac: [0; 32], + }; + + manifest.sign(&k_root_auth); + assert!(manifest.verify(&k_root_auth)); + + let encoded = manifest.encode(); + assert_eq!(encoded.len(), SECURITY_MANIFEST_SIZE); + + let decoded = SecurityManifest::decode(&encoded).unwrap(); + assert!(decoded.verify(&k_root_auth)); + + // Wrong key fails + let wrong_key = [0x55u8; 32]; + assert!(!decoded.verify(&wrong_key)); + } + + #[test] + fn test_anti_rollback_decision_matrix() { + let store_uuid = [0x11u8; 16]; + let digest_1 = [0xaa; 32]; + let digest_2 = [0xbb; 32]; + + let anchor = RollbackAnchor { + store_uuid, + epoch: 10, + commit_record_id: ObjectId([1; 32]), + security_root_digest: digest_1, + }; + + // 1. Same epoch, matching digest -> ValidResume + assert_eq!( + evaluate_anti_rollback(10, &digest_1, Some(&anchor)), + AntiRollbackDecision::ValidResume + ); + + // 2. Next epoch (E + 1) -> PreparedEpochAdvance + assert_eq!( + evaluate_anti_rollback(11, &digest_2, Some(&anchor)), + AntiRollbackDecision::PreparedEpochAdvance { + disk_epoch: 11, + disk_digest: digest_2 + } + ); + + // 3. Stale epoch (E - 1) -> RollbackDetected + assert!(matches!( + evaluate_anti_rollback(9, &digest_1, Some(&anchor)), + AntiRollbackDecision::RollbackDetected(_) + )); + + // 4. Same epoch, altered digest -> RollbackDetected + assert!(matches!( + evaluate_anti_rollback(10, &digest_2, Some(&anchor)), + AntiRollbackDecision::RollbackDetected(_) + )); + + // 5. Jumped epoch (E + 2) -> InconsistentEpoch + assert!(matches!( + evaluate_anti_rollback(12, &digest_2, Some(&anchor)), + AntiRollbackDecision::InconsistentEpoch(_) + )); + } +}