//! AES (FIPS 197) and its GCM mode (SP 800-38D), what most TLS servers //! speak. The blocks are encrypted on the core's AES instructions where it //! has them ([`crate::hw`]); else in software, in time that does not depend //! on the key or the data: the S-box is read by scanning all of it, never //! by an index a secret chooses (a table indexed by secrets leaks through //! the cache). That is slow, and only a fallback: the cores Pinnacle aims //! at have the instructions. GHASH is in software, in constant time too. use crate::hw; /// GF(2^8) multiplication modulo x^8 + x^4 + x^3 + x + 1. const fn gf_mul(mut a: u8, mut b: u8) -> u8 { let mut product = 0; while b != 0 { if b & 1 != 0 { product ^= a; } let carry = a & 0x80; a <<= 1; if carry != 0 { a ^= 0x1b; } b >>= 1; } product } /// The S-box, from its definition: the inverse in GF(2^8) (x^254), then /// the affine map. Computed when compiling, so no table is copied in. const SBOX: [u8; 256] = { let mut sbox = [0u8; 256]; let mut x = 0; while x < 256 { // x^254 by square and multiply: 254 = 0b11111110. let mut inverse = 1u8; let mut power = x as u8; let mut e = 254u32; while e != 0 { if e & 1 != 0 { inverse = gf_mul(inverse, power); } power = gf_mul(power, power); e >>= 1; } let b = inverse; sbox[x] = b ^ b.rotate_left(1) ^ b.rotate_left(2) ^ b.rotate_left(3) ^ b.rotate_left(4) ^ 0x63; x += 1; } sbox }; /// `SBOX[x]`, read by scanning all of it. fn sub_byte(x: u8) -> u8 { let mut out = 0u8; for (i, &s) in SBOX.iter().enumerate() { // 0xff where `i == x`, else 0, without a branch. let same = ((((i as u32) ^ u32::from(x)).wrapping_sub(1)) >> 31) as u8; out |= s & 0u8.wrapping_sub(same); } out } fn xtime(b: u8) -> u8 { (b << 1) ^ (0x1b & 0u8.wrapping_sub(b >> 7)) } /// An AES key, expanded: AES-128 or AES-256. #[derive(Clone)] pub struct Aes { keys: [[u8; 16]; 15], /// Round keys: 11 or 15. count: usize, } impl Aes { /// The key expanded; `None` unless it is 16 or 32 bytes. pub fn new(key: &[u8]) -> Option { let (nk, rounds) = match key.len() { 16 => (4, 10), 32 => (8, 14), _ => return None, }; let total = 4 * (rounds + 1); let mut words = [[0u8; 4]; 60]; for (i, word) in words.iter_mut().take(nk).enumerate() { word.copy_from_slice(&key[i * 4..i * 4 + 4]); } let mut rcon = 1u8; for i in nk..total { let mut t = words[i - 1]; if i % nk == 0 { t = [ sub_byte(t[1]) ^ rcon, sub_byte(t[2]), sub_byte(t[3]), sub_byte(t[0]), ]; rcon = xtime(rcon); } else if nk > 6 && i % nk == 4 { t = t.map(sub_byte); } for (j, b) in t.iter().enumerate() { words[i][j] = words[i - nk][j] ^ b; } } let mut keys = [[0u8; 16]; 15]; for (r, round_key) in keys.iter_mut().take(rounds + 1).enumerate() { for c in 0..4 { round_key[c * 4..c * 4 + 4].copy_from_slice(&words[r * 4 + c]); } } Some(Aes { keys, count: rounds + 1, }) } /// Encrypts whole 16-byte blocks in place. pub fn encrypt_blocks(&self, blocks: &mut [u8]) { if hw::aes() { hw::aes_blocks(&self.keys[..self.count], blocks); } else { self.encrypt_blocks_in_software(blocks); } } /// As [`encrypt_blocks`](Self::encrypt_blocks), in software whatever the /// core has: what the instructions are checked against. pub fn encrypt_blocks_in_software(&self, blocks: &mut [u8]) { for block in blocks.as_chunks_mut::<16>().0 { self.encrypt_block_in_software(block); } } fn encrypt_block_in_software(&self, state: &mut [u8; 16]) { let rounds = self.count - 1; add(state, &self.keys[0]); for (round, key) in self.keys.iter().enumerate().take(rounds + 1).skip(1) { for b in state.iter_mut() { *b = sub_byte(*b); } // Row r of the state, a byte a column, moves r columns left. let old = *state; for c in 0..4 { for r in 0..4 { state[c * 4 + r] = old[((c + r) % 4) * 4 + r]; } } if round != rounds { for column in state.as_chunks_mut::<4>().0 { let [a, b, c, d] = *column; let all = a ^ b ^ c ^ d; column[0] ^= all ^ xtime(a ^ b); column[1] ^= all ^ xtime(b ^ c); column[2] ^= all ^ xtime(c ^ d); column[3] ^= all ^ xtime(d ^ a); } } add(state, key); } } } /// The inverse S-box, from the S-box when compiling. const INV_SBOX: [u8; 256] = { let mut inv = [0u8; 256]; let mut x = 0; while x < 256 { inv[SBOX[x] as usize] = x as u8; x += 1; } inv }; /// `INV_SBOX[x]`, read by scanning all of it. fn inv_sub_byte(x: u8) -> u8 { let mut out = 0u8; for (i, &s) in INV_SBOX.iter().enumerate() { let same = ((((i as u32) ^ u32::from(x)).wrapping_sub(1)) >> 31) as u8; out |= s & 0u8.wrapping_sub(same); } out } /// GF(2^8) multiplication in constant time, for the inverse mix. fn mul(a: u8, b: u8) -> u8 { let (mut a, mut product) = (a, 0u8); for i in 0..8 { product ^= a & 0u8.wrapping_sub((b >> i) & 1); a = xtime(a); } product } impl Aes { /// Decrypts whole 16-byte blocks in place, in software (FIPS 197's /// inverse cipher): what AES key unwrap needs, a few blocks at a time, /// never a stream. pub fn decrypt_blocks(&self, blocks: &mut [u8]) { for state in blocks.as_chunks_mut::<16>().0 { let rounds = self.count - 1; add(state, &self.keys[rounds]); for round in (0..rounds).rev() { // Row r moves r columns right. let old = *state; for c in 0..4 { for r in 0..4 { state[((c + r) % 4) * 4 + r] = old[c * 4 + r]; } } for b in state.iter_mut() { *b = inv_sub_byte(*b); } add(state, &self.keys[round]); if round != 0 { for column in state.as_chunks_mut::<4>().0 { let [a, b, c, d] = *column; column[0] = mul(a, 14) ^ mul(b, 11) ^ mul(c, 13) ^ mul(d, 9); column[1] = mul(a, 9) ^ mul(b, 14) ^ mul(c, 11) ^ mul(d, 13); column[2] = mul(a, 13) ^ mul(b, 9) ^ mul(c, 14) ^ mul(d, 11); column[3] = mul(a, 11) ^ mul(b, 13) ^ mul(c, 9) ^ mul(d, 14); } } } } } } /// AES key wrap's default initial value (RFC 3394, 2.2.3.1). const WRAP_IV: [u8; 8] = [0xa6; 8]; /// Wraps `key` (a multiple of 8 bytes, at least 16) under `kek` (RFC /// 3394) into `out`, which is 8 bytes longer. False for wrong lengths. pub fn wrap(kek: &[u8], key: &[u8], out: &mut [u8]) -> bool { let Some(aes) = Aes::new(kek) else { return false }; if !key.len().is_multiple_of(8) || key.len() < 16 || out.len() != key.len() + 8 { return false; } let n = key.len() / 8; let (a, r) = out.split_at_mut(8); a.copy_from_slice(&WRAP_IV); r.copy_from_slice(key); for j in 0..6 { for i in 0..n { let mut b = [0u8; 16]; b[..8].copy_from_slice(a); b[8..].copy_from_slice(&r[i * 8..i * 8 + 8]); aes.encrypt_blocks(&mut b); let t = (n * j + i + 1) as u64; for (x, (y, z)) in a.iter_mut().zip(b[..8].iter().zip(t.to_be_bytes())) { *x = y ^ z; } r[i * 8..i * 8 + 8].copy_from_slice(&b[8..]); } } true } /// Unwraps what [`wrap`] made into `out` (8 bytes shorter): false when /// its integrity check fails (the wrong key encryption key, or the bytes /// changed), `out` then zeroed. pub fn unwrap(kek: &[u8], wrapped: &[u8], out: &mut [u8]) -> bool { let Some(aes) = Aes::new(kek) else { return false }; if !wrapped.len().is_multiple_of(8) || wrapped.len() < 24 || out.len() + 8 != wrapped.len() { return false; } let n = out.len() / 8; let mut a: [u8; 8] = wrapped[..8].try_into().unwrap(); out.copy_from_slice(&wrapped[8..]); for j in (0..6).rev() { for i in (0..n).rev() { let t = (n * j + i + 1) as u64; for (x, y) in a.iter_mut().zip(t.to_be_bytes()) { *x ^= y; } let mut b = [0u8; 16]; b[..8].copy_from_slice(&a); b[8..].copy_from_slice(&out[i * 8..i * 8 + 8]); aes.decrypt_blocks(&mut b); a.copy_from_slice(&b[..8]); out[i * 8..i * 8 + 8].copy_from_slice(&b[8..]); } } // In constant time: whether the check value came back. if !crate::equal(&a, &WRAP_IV) { out.fill(0); return false; } true } fn add(state: &mut [u8; 16], key: &[u8; 16]) { for (s, k) in state.iter_mut().zip(key) { *s ^= k; } } /// GCM's multiplication in GF(2^128), its bits in GCM's order (the first /// bit the most significant), in constant time. fn gf128_mul(x: u128, y: u128) -> u128 { let mut z = 0u128; let mut v = y; for i in 0..128 { let bit = (x >> (127 - i)) & 1; z ^= v & 0u128.wrapping_sub(bit); let low = v & 1; v = (v >> 1) ^ ((0xe1u128 << 120) & 0u128.wrapping_sub(low)); } z } /// AES-GCM with a 96-bit nonce and a 128-bit tag, as TLS uses it. #[derive(Clone)] pub struct Gcm { aes: Aes, /// The hash key: the zero block, encrypted. h: u128, } impl Gcm { /// `None` unless the key is 16 or 32 bytes. pub fn new(key: &[u8]) -> Option { let aes = Aes::new(key)?; let mut zero = [0u8; 16]; aes.encrypt_blocks(&mut zero); Some(Gcm { aes, h: u128::from_be_bytes(zero), }) } fn ghash(&self, aad: &[u8], data: &[u8]) -> u128 { let mut y = 0u128; for part in [aad, data] { for chunk in part.chunks(16) { let mut block = [0u8; 16]; block[..chunk.len()].copy_from_slice(chunk); y = gf128_mul(y ^ u128::from_be_bytes(block), self.h); } } let lengths = ((aad.len() as u128 * 8) << 64) | (data.len() as u128 * 8); gf128_mul(y ^ lengths, self.h) } /// XORs `data` with the counter stream from the block after `j0`, /// many blocks a call to the cipher. fn ctr(&self, j0: &[u8; 16], data: &mut [u8]) { const BATCH: usize = 32; let mut counter = u32::from_be_bytes(j0[12..].try_into().unwrap()); let mut stream = [0u8; BATCH * 16]; for chunk in data.chunks_mut(BATCH * 16) { let blocks = chunk.len().div_ceil(16); for block in stream.as_chunks_mut::<16>().0.iter_mut().take(blocks) { counter = counter.wrapping_add(1); block[..12].copy_from_slice(&j0[..12]); block[12..].copy_from_slice(&counter.to_be_bytes()); } self.aes.encrypt_blocks(&mut stream[..blocks * 16]); for (d, s) in chunk.iter_mut().zip(stream.iter()) { *d ^= s; } } } fn j0(nonce: &[u8; 12]) -> [u8; 16] { let mut j0 = [0u8; 16]; j0[..12].copy_from_slice(nonce); j0[15] = 1; j0 } fn tag(&self, j0: &[u8; 16], aad: &[u8], ciphertext: &[u8]) -> [u8; 16] { let mut mask = *j0; self.aes.encrypt_blocks(&mut mask); (u128::from_be_bytes(mask) ^ self.ghash(aad, ciphertext)).to_be_bytes() } /// Encrypts `data` in place; returns the tag. pub fn seal(&self, nonce: &[u8; 12], aad: &[u8], data: &mut [u8]) -> [u8; 16] { let j0 = Self::j0(nonce); self.ctr(&j0, data); self.tag(&j0, aad, data) } /// Checks the tag and decrypts `data` in place; false, and `data` as /// it was, when the tag does not match. pub fn open(&self, nonce: &[u8; 12], aad: &[u8], data: &mut [u8], tag: &[u8; 16]) -> bool { let j0 = Self::j0(nonce); if !crate::equal(&self.tag(&j0, aad, data), tag) { return false; } self.ctr(&j0, data); true } } /// AES-CMAC (RFC 4493, SP 800-38B): a message's 128-bit authentication /// code, what Bluetooth's Secure Connections pairing builds its functions /// from. pub fn cmac(key: &[u8; 16], message: &[u8]) -> [u8; 16] { cmac_xorend(key, message, 0) } /// CMAC over `message` with `end` XORed into its last 16 bytes (SIV's /// "xorend"; a message of 16 bytes or more), without copying it. fn cmac_xorend(key: &[u8; 16], message: &[u8], end: u128) -> [u8; 16] { let end = end.to_be_bytes(); let from = message.len().saturating_sub(16); let aes = Aes::new(key).unwrap(); let double = |b: u128| (b << 1) ^ (0x87 & 0u128.wrapping_sub(b >> 127)); let mut l = [0u8; 16]; aes.encrypt_blocks(&mut l); let k1 = double(u128::from_be_bytes(l)); let k2 = double(k1); let blocks = message.len().div_ceil(16).max(1); let mut x = [0u8; 16]; for i in 0..blocks { let chunk = &message[i * 16..message.len().min(i * 16 + 16)]; let mut block = [0u8; 16]; block[..chunk.len()].copy_from_slice(chunk); for (j, b) in block[..chunk.len()].iter_mut().enumerate() { if let Some(e) = (i * 16 + j).checked_sub(from) { *b ^= end[e]; } } if i == blocks - 1 { let k = if chunk.len() == 16 { k1 } else { block[chunk.len()] = 0x80; k2 }; block = (u128::from_be_bytes(block) ^ k).to_be_bytes(); } for (x, b) in x.iter_mut().zip(block) { *x ^= b; } aes.encrypt_blocks(&mut x); } x } /// AES-CCM (SP 800-38C, RFC 3610): counter mode with a CBC-MAC, a nonce of /// 7 to 13 bytes and a tag of 4 to 16; what a Bluetooth link is encrypted /// with (a 13-byte nonce, a 4-byte tag). #[derive(Clone)] pub struct Ccm { aes: Aes, tag: usize, } impl Ccm { /// `None` unless the key is 16 or 32 bytes and the tag 4 to 16 bytes, /// an even number. pub fn new(key: &[u8], tag: usize) -> Option { ((4..=16).contains(&tag) && tag.is_multiple_of(2)).then_some(())?; Some(Ccm { aes: Aes::new(key)?, tag, }) } /// The counter block `i`: flags, the nonce, i in the length field. fn counter(nonce: &[u8], i: usize) -> [u8; 16] { let l = 15 - nonce.len(); let mut a = [0u8; 16]; a[0] = (l - 1) as u8; a[1..1 + nonce.len()].copy_from_slice(nonce); let bytes = (i as u64).to_be_bytes(); a[16 - l..].copy_from_slice(&bytes[8 - l..]); a } fn mac(&self, nonce: &[u8], aad: &[u8], plaintext: &[u8]) -> [u8; 16] { let l = 15 - nonce.len(); let mut b0 = [0u8; 16]; b0[0] = u8::from(!aad.is_empty()) << 6 | ((self.tag as u8 - 2) / 2) << 3 | (l as u8 - 1); b0[1..1 + nonce.len()].copy_from_slice(nonce); let len = (plaintext.len() as u64).to_be_bytes(); b0[16 - l..].copy_from_slice(&len[8 - l..]); let mut x = b0; self.aes.encrypt_blocks(&mut x); // CBC-MAC over the associated data (its length in two bytes first: // CCM's encoding for under 0xff00 bytes), then the plaintext, each // padded with zeros to whole blocks. let length = (aad.len() as u16).to_be_bytes(); let header = if aad.is_empty() { &[][..] } else { &length[..] }; let mut at = 0; for &b in header.iter().chain(aad) { x[at] ^= b; at += 1; if at == 16 { self.aes.encrypt_blocks(&mut x); at = 0; } } if at > 0 { self.aes.encrypt_blocks(&mut x); } for chunk in plaintext.chunks(16) { for (x, b) in x.iter_mut().zip(chunk) { *x ^= b; } self.aes.encrypt_blocks(&mut x); } x } /// XORs `data` with the key stream from counter 1. fn ctr(&self, nonce: &[u8], data: &mut [u8]) { for (i, chunk) in data.chunks_mut(16).enumerate() { let mut s = Self::counter(nonce, i + 1); self.aes.encrypt_blocks(&mut s); for (d, s) in chunk.iter_mut().zip(s) { *d ^= s; } } } fn masked(&self, nonce: &[u8], mac: [u8; 16]) -> [u8; 16] { let mut s0 = Self::counter(nonce, 0); self.aes.encrypt_blocks(&mut s0); let mut tag = [0u8; 16]; for i in 0..16 { tag[i] = mac[i] ^ s0[i]; } tag } /// Encrypts `data` in place and returns its tag (the first `tag` /// bytes of the array). The nonce must be 7 to 13 bytes and never /// used twice with one key. pub fn seal(&self, nonce: &[u8], aad: &[u8], data: &mut [u8]) -> [u8; 16] { let mac = self.mac(nonce, aad, data); self.ctr(nonce, data); let mut tag = self.masked(nonce, mac); tag[self.tag..].fill(0); tag } /// Checks `tag` and decrypts `data` in place; false, and `data` as it /// was, when the tag does not match. pub fn open(&self, nonce: &[u8], aad: &[u8], data: &mut [u8], tag: &[u8]) -> bool { self.ctr(nonce, data); let expected = self.masked(nonce, self.mac(nonce, aad, data)); if tag.len() != self.tag || !crate::equal(&expected[..self.tag], tag) { self.ctr(nonce, data); return false; } true } } /// AES-SIV (RFC 5297) with CMAC on AES-128, `AEAD_AES_SIV_CMAC_256`: a /// 32-byte key, its first half for the synthetic IV, its second for the /// counter mode. What Network Time Security seals its packets with /// (RFC 8915). The IV is a MAC over every piece of associated data and the /// plaintext, so a repeated nonce reveals only that a message repeated. #[derive(Clone)] pub struct Siv { mac: [u8; 16], ctr: Aes, } impl Siv { pub fn new(key: &[u8; 32]) -> Siv { Siv { mac: key[..16].try_into().unwrap(), ctr: Aes::new(&key[16..]).unwrap(), } } /// S2V: the MAC over the pieces of associated data, then `plaintext`. fn s2v(&self, associated: &[&[u8]], plaintext: &[u8]) -> [u8; 16] { let double = |b: u128| (b << 1) ^ (0x87 & 0u128.wrapping_sub(b >> 127)); let mut d = u128::from_be_bytes(cmac(&self.mac, &[0u8; 16])); for piece in associated { d = double(d) ^ u128::from_be_bytes(cmac(&self.mac, piece)); } if plaintext.len() >= 16 { // The last 16 bytes XORed with D. cmac_xorend(&self.mac, plaintext, d) } else { let mut padded = [0u8; 16]; padded[..plaintext.len()].copy_from_slice(plaintext); padded[plaintext.len()] = 0x80; cmac( &self.mac, &(double(d) ^ u128::from_be_bytes(padded)).to_be_bytes(), ) } } /// XORs `data` with the key stream from the IV, its bits 63 and 31 /// cleared (counting from the right). fn ctr(&self, iv: [u8; 16], data: &mut [u8]) { let mut q = u128::from_be_bytes(iv) & !(1 << 63 | 1 << 31); for chunk in data.chunks_mut(16) { let mut s = q.to_be_bytes(); self.ctr.encrypt_blocks(&mut s); for (d, s) in chunk.iter_mut().zip(s) { *d ^= s; } q = q.wrapping_add(1); } } /// Encrypts `data` in place and returns the IV, which goes before it. /// A nonce, where there is one, is the last piece of `associated`. pub fn seal(&self, associated: &[&[u8]], data: &mut [u8]) -> [u8; 16] { let iv = self.s2v(associated, data); self.ctr(iv, data); iv } /// Decrypts `data` in place when `iv` checks; false, and `data` as it /// was, when it does not. pub fn open(&self, associated: &[&[u8]], data: &mut [u8], iv: &[u8; 16]) -> bool { self.ctr(*iv, data); if !crate::equal(&self.s2v(associated, data), iv) { self.ctr(*iv, data); return false; } true } }