From 36d22d82aa202bb199967e9512281e9a53db42c9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 21:33:14 +0200 Subject: Adding upstream version 115.7.0esr. Signed-off-by: Daniel Baumann --- third_party/rust/ohttp/src/rh/aead.rs | 257 +++++++++++++++++ third_party/rust/ohttp/src/rh/hkdf.rs | 224 +++++++++++++++ third_party/rust/ohttp/src/rh/hpke.rs | 508 ++++++++++++++++++++++++++++++++++ third_party/rust/ohttp/src/rh/mod.rs | 47 ++++ 4 files changed, 1036 insertions(+) create mode 100644 third_party/rust/ohttp/src/rh/aead.rs create mode 100644 third_party/rust/ohttp/src/rh/hkdf.rs create mode 100644 third_party/rust/ohttp/src/rh/hpke.rs create mode 100644 third_party/rust/ohttp/src/rh/mod.rs (limited to 'third_party/rust/ohttp/src/rh') diff --git a/third_party/rust/ohttp/src/rh/aead.rs b/third_party/rust/ohttp/src/rh/aead.rs new file mode 100644 index 0000000000..76a7e4443c --- /dev/null +++ b/third_party/rust/ohttp/src/rh/aead.rs @@ -0,0 +1,257 @@ +#![allow(dead_code)] // TODO: remove + +use super::SymKey; +use crate::{err::Res, hpke::Aead as AeadId}; +use aead::{AeadMut, Key, NewAead, Nonce, Payload}; +use aes_gcm::{Aes128Gcm, Aes256Gcm}; +use chacha20poly1305::ChaCha20Poly1305; +use std::convert::TryFrom; + +/// All the nonces are the same length. Exploit that. +pub const NONCE_LEN: usize = 12; +const COUNTER_LEN: usize = 8; +const TAG_LEN: usize = 16; + +type SequenceNumber = u64; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Encrypt, + Decrypt, +} + +enum AeadEngine { + Aes128Gcm(Box), + Aes256Gcm(Box), + ChaCha20Poly1305(Box), +} + +// Dispatch functions; this just shows how janky that this sort of abstraction can be. +// If this grows too much, this is fairly clearly responsive to using a macro. +impl AeadEngine { + fn encrypt(&mut self, nonce: &[u8], pt: Payload) -> Res> { + let tag = match self { + Self::Aes128Gcm(e) => e.encrypt(Nonce::::from_slice(nonce), pt)?, + Self::Aes256Gcm(e) => e.encrypt(Nonce::::from_slice(nonce), pt)?, + Self::ChaCha20Poly1305(e) => { + e.encrypt(Nonce::::from_slice(nonce), pt)? + } + }; + Ok(tag) + } + fn decrypt(&mut self, nonce: &[u8], pt: Payload) -> Res> { + let tag = match self { + Self::Aes128Gcm(e) => e.decrypt(Nonce::::from_slice(nonce), pt)?, + Self::Aes256Gcm(e) => e.decrypt(Nonce::::from_slice(nonce), pt)?, + Self::ChaCha20Poly1305(e) => { + e.decrypt(Nonce::::from_slice(nonce), pt)? + } + }; + Ok(tag) + } +} + +/// A switch-hitting AEAD that uses a selected primitive. +pub struct Aead { + mode: Mode, + aead: AeadEngine, + nonce_base: [u8; NONCE_LEN], + seq: SequenceNumber, +} + +impl Aead { + #[allow(clippy::unnecessary_wraps)] + pub fn new( + mode: Mode, + algorithm: AeadId, + key: &SymKey, + nonce_base: [u8; NONCE_LEN], + ) -> Res { + let aead = match algorithm { + AeadId::Aes128Gcm => AeadEngine::Aes128Gcm(Box::new(Aes128Gcm::new( + Key::::from_slice(key.as_ref()), + ))), + AeadId::Aes256Gcm => AeadEngine::Aes256Gcm(Box::new(Aes256Gcm::new( + Key::::from_slice(key.as_ref()), + ))), + AeadId::ChaCha20Poly1305 => AeadEngine::ChaCha20Poly1305(Box::new( + ChaCha20Poly1305::new(Key::::from_slice(key.as_ref())), + )), + }; + Ok(Self { + mode, + aead, + nonce_base, + seq: 0, + }) + } + + #[cfg(test)] + #[allow(clippy::unnecessary_wraps)] + fn import_key(_alg: AeadId, k: &[u8]) -> Res { + Ok(SymKey::from(k)) + } + + fn nonce(&self, seq: SequenceNumber) -> Vec { + let mut nonce = Vec::from(self.nonce_base); + for (i, n) in nonce.iter_mut().rev().take(COUNTER_LEN).enumerate() { + *n ^= u8::try_from((seq >> (8 * i)) & 0xff).unwrap(); + } + nonce + } + + pub fn seal(&mut self, aad: &[u8], pt: &[u8]) -> Res> { + assert_eq!(self.mode, Mode::Encrypt); + // A copy for the nonce generator to write into. But we don't use the value. + let nonce = self.nonce(self.seq); + self.seq += 1; + let ct = self.aead.encrypt(&nonce, Payload { msg: pt, aad })?; + Ok(ct) + } + + pub fn open(&mut self, aad: &[u8], seq: SequenceNumber, ct: &[u8]) -> Res> { + assert_eq!(self.mode, Mode::Decrypt); + let nonce = self.nonce(seq); + let pt = self.aead.decrypt(&nonce, Payload { msg: ct, aad })?; + Ok(pt) + } +} + +#[cfg(test)] +mod test { + use super::{ + super::super::{hpke::Aead as AeadId, init}, + Aead, Mode, SequenceNumber, NONCE_LEN, + }; + + /// Check that the first invocation of encryption matches expected values. + /// Also check decryption of the same. + fn check0( + algorithm: AeadId, + key: &[u8], + nonce: &[u8; NONCE_LEN], + aad: &[u8], + pt: &[u8], + ct: &[u8], + ) { + init(); + let k = Aead::import_key(algorithm, key).unwrap(); + + let mut enc = Aead::new(Mode::Encrypt, algorithm, &k, *nonce).unwrap(); + let ciphertext = enc.seal(aad, pt).unwrap(); + assert_eq!(&ciphertext[..], ct); + + let mut dec = Aead::new(Mode::Decrypt, algorithm, &k, *nonce).unwrap(); + let plaintext = dec.open(aad, 0, ct).unwrap(); + assert_eq!(&plaintext[..], pt); + } + + fn decrypt( + algorithm: AeadId, + key: &[u8], + nonce: &[u8; NONCE_LEN], + seq: SequenceNumber, + aad: &[u8], + pt: &[u8], + ct: &[u8], + ) { + let k = Aead::import_key(algorithm, key).unwrap(); + let mut dec = Aead::new(Mode::Decrypt, algorithm, &k, *nonce).unwrap(); + let plaintext = dec.open(aad, seq, ct).unwrap(); + assert_eq!(&plaintext[..], pt); + } + + /// This tests the AEAD in QUIC in combination with the HKDF code. + /// This is an AEAD-only example. + #[test] + fn quic_retry() { + const KEY: &[u8] = &[ + 0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, + 0xc8, 0x4e, + ]; + const NONCE: &[u8; NONCE_LEN] = &[ + 0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb, + ]; + const AAD: &[u8] = &[ + 0x08, 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08, 0xff, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, + 0x6e, + ]; + const CT: &[u8] = &[ + 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, + 0x96, 0xba, + ]; + check0(AeadId::Aes128Gcm, KEY, NONCE, AAD, &[], CT); + } + + #[test] + fn quic_server_initial() { + const ALG: AeadId = AeadId::Aes128Gcm; + const KEY: &[u8] = &[ + 0xcf, 0x3a, 0x53, 0x31, 0x65, 0x3c, 0x36, 0x4c, 0x88, 0xf0, 0xf3, 0x79, 0xb6, 0x06, + 0x7e, 0x37, + ]; + const NONCE_BASE: &[u8; NONCE_LEN] = &[ + 0x0a, 0xc1, 0x49, 0x3c, 0xa1, 0x90, 0x58, 0x53, 0xb0, 0xbb, 0xa0, 0x3e, + ]; + // Note that this integrates the sequence number of 1 from the example, + // otherwise we can't use a sequence number of 0 to encrypt. + const NONCE: &[u8; NONCE_LEN] = &[ + 0x0a, 0xc1, 0x49, 0x3c, 0xa1, 0x90, 0x58, 0x53, 0xb0, 0xbb, 0xa0, 0x3f, + ]; + const AAD: &[u8] = &[ + 0xc1, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, + 0xb5, 0x00, 0x40, 0x75, 0x00, 0x01, + ]; + const PT: &[u8] = &[ + 0x02, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x40, 0x5a, 0x02, 0x00, 0x00, 0x56, 0x03, + 0x03, 0xee, 0xfc, 0xe7, 0xf7, 0xb3, 0x7b, 0xa1, 0xd1, 0x63, 0x2e, 0x96, 0x67, 0x78, + 0x25, 0xdd, 0xf7, 0x39, 0x88, 0xcf, 0xc7, 0x98, 0x25, 0xdf, 0x56, 0x6d, 0xc5, 0x43, + 0x0b, 0x9a, 0x04, 0x5a, 0x12, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00, + 0x24, 0x00, 0x1d, 0x00, 0x20, 0x9d, 0x3c, 0x94, 0x0d, 0x89, 0x69, 0x0b, 0x84, 0xd0, + 0x8a, 0x60, 0x99, 0x3c, 0x14, 0x4e, 0xca, 0x68, 0x4d, 0x10, 0x81, 0x28, 0x7c, 0x83, + 0x4d, 0x53, 0x11, 0xbc, 0xf3, 0x2b, 0xb9, 0xda, 0x1a, 0x00, 0x2b, 0x00, 0x02, 0x03, + 0x04, + ]; + const CT: &[u8] = &[ + 0x5a, 0x48, 0x2c, 0xd0, 0x99, 0x1c, 0xd2, 0x5b, 0x0a, 0xac, 0x40, 0x6a, 0x58, 0x16, + 0xb6, 0x39, 0x41, 0x00, 0xf3, 0x7a, 0x1c, 0x69, 0x79, 0x75, 0x54, 0x78, 0x0b, 0xb3, + 0x8c, 0xc5, 0xa9, 0x9f, 0x5e, 0xde, 0x4c, 0xf7, 0x3c, 0x3e, 0xc2, 0x49, 0x3a, 0x18, + 0x39, 0xb3, 0xdb, 0xcb, 0xa3, 0xf6, 0xea, 0x46, 0xc5, 0xb7, 0x68, 0x4d, 0xf3, 0x54, + 0x8e, 0x7d, 0xde, 0xb9, 0xc3, 0xbf, 0x9c, 0x73, 0xcc, 0x3f, 0x3b, 0xde, 0xd7, 0x4b, + 0x56, 0x2b, 0xfb, 0x19, 0xfb, 0x84, 0x02, 0x2f, 0x8e, 0xf4, 0xcd, 0xd9, 0x37, 0x95, + 0xd7, 0x7d, 0x06, 0xed, 0xbb, 0x7a, 0xaf, 0x2f, 0x58, 0x89, 0x18, 0x50, 0xab, 0xbd, + 0xca, 0x3d, 0x20, 0x39, 0x8c, 0x27, 0x64, 0x56, 0xcb, 0xc4, 0x21, 0x58, 0x40, 0x7d, + 0xd0, 0x74, 0xee, + ]; + check0(ALG, KEY, NONCE, AAD, PT, CT); + decrypt(ALG, KEY, NONCE_BASE, 1, AAD, PT, CT); + } + + #[test] + fn quic_chacha() { + const ALG: AeadId = AeadId::ChaCha20Poly1305; + const KEY: &[u8] = &[ + 0xc6, 0xd9, 0x8f, 0xf3, 0x44, 0x1c, 0x3f, 0xe1, 0xb2, 0x18, 0x20, 0x94, 0xf6, 0x9c, + 0xaa, 0x2e, 0xd4, 0xb7, 0x16, 0xb6, 0x54, 0x88, 0x96, 0x0a, 0x7a, 0x98, 0x49, 0x79, + 0xfb, 0x23, 0xe1, 0xc8, + ]; + const NONCE_BASE: &[u8; NONCE_LEN] = &[ + 0xe0, 0x45, 0x9b, 0x34, 0x74, 0xbd, 0xd0, 0xe4, 0x4a, 0x41, 0xc1, 0x44, + ]; + // Note that this integrates the sequence number of 654360564 from the example, + // otherwise we can't use a sequence number of 0 to encrypt. + const NONCE: &[u8; NONCE_LEN] = &[ + 0xe0, 0x45, 0x9b, 0x34, 0x74, 0xbd, 0xd0, 0xe4, 0x6d, 0x41, 0x7e, 0xb0, + ]; + const AAD: &[u8] = &[0x42, 0x00, 0xbf, 0xf4]; + const PT: &[u8] = &[0x01]; + const CT: &[u8] = &[ + 0x65, 0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57, 0x5d, 0x79, 0x99, 0xc2, + 0x5a, 0x5b, 0xfb, + ]; + check0(ALG, KEY, NONCE, AAD, PT, CT); + // Now use the real nonce and sequence number from the example. + decrypt(ALG, KEY, NONCE_BASE, 654_360_564, AAD, PT, CT); + } +} diff --git a/third_party/rust/ohttp/src/rh/hkdf.rs b/third_party/rust/ohttp/src/rh/hkdf.rs new file mode 100644 index 0000000000..aeb3a8d6e8 --- /dev/null +++ b/third_party/rust/ohttp/src/rh/hkdf.rs @@ -0,0 +1,224 @@ +#![allow(dead_code)] // TODO: remove + +use super::SymKey; +use crate::{ + err::{Error, Res}, + hpke::{Aead, Kdf}, +}; +use hkdf::Hkdf as HkdfImpl; +use log::trace; +use sha2::{Sha256, Sha384, Sha512}; + +#[derive(Clone, Copy)] +pub enum KeyMechanism { + Aead(Aead), + #[allow(dead_code)] // We don't use this one. + Hkdf, +} + +impl KeyMechanism { + fn len(self) -> usize { + match self { + Self::Aead(a) => a.n_k(), + Self::Hkdf => 0, // Let the underlying module decide. + } + } +} + +pub enum Hkdf { + Sha256, + Sha384, + Sha512, +} + +impl Hkdf { + pub fn new(kdf: Kdf) -> Self { + match kdf { + Kdf::HkdfSha256 => Self::Sha256, + Kdf::HkdfSha384 => Self::Sha384, + Kdf::HkdfSha512 => Self::Sha512, + } + } + + #[cfg(test)] + #[allow(clippy::unnecessary_wraps)] + pub fn import_ikm(ikm: &[u8]) -> Res { + Ok(SymKey::from(ikm)) + } + + #[allow(clippy::unnecessary_wraps)] + pub fn extract(&self, salt: &[u8], ikm: &SymKey) -> Res { + let prk = match self { + Self::Sha256 => { + SymKey::from(HkdfImpl::::extract(Some(salt), &ikm.0).0.as_slice()) + } + Self::Sha384 => { + SymKey::from(HkdfImpl::::extract(Some(salt), &ikm.0).0.as_slice()) + } + Self::Sha512 => { + SymKey::from(HkdfImpl::::extract(Some(salt), &ikm.0).0.as_slice()) + } + }; + trace!( + "HKDF extract: salt={} ikm={:?} prk={:?}", + hex::encode(salt), + ikm, + prk + ); + Ok(prk) + } + + pub fn expand_key(&self, prk: &SymKey, info: &[u8], key_mech: KeyMechanism) -> Res { + let okm = SymKey::from(self.expand_data(prk, info, key_mech.len())?); + trace!( + "HKDF expand_key: prk={:?} info={} okm={:?}", + prk, + hex::encode(info), + okm, + ); + Ok(okm) + } + + pub fn expand_data(&self, prk: &SymKey, info: &[u8], len: usize) -> Res> { + let mut okm = vec![0; len]; + match self { + Self::Sha256 => { + let h = HkdfImpl::::from_prk(&prk.0).map_err(|_| Error::Internal)?; + h.expand(info, &mut okm).map_err(|_| Error::Internal)?; + } + Self::Sha384 => { + let h = HkdfImpl::::from_prk(&prk.0).map_err(|_| Error::Internal)?; + h.expand(info, &mut okm).map_err(|_| Error::Internal)?; + } + Self::Sha512 => { + let h = HkdfImpl::::from_prk(&prk.0).map_err(|_| Error::Internal)?; + h.expand(info, &mut okm).map_err(|_| Error::Internal)?; + } + } + trace!( + "HKDF expand_data: prk={:?} info={} len={} okm={:?}", + prk, + hex::encode(info), + len, + hex::encode(&okm), + ); + Ok(okm) + } +} + +#[cfg(test)] +mod test { + use super::{super::super::hpke::Kdf, Hkdf}; + use crate::init; + + fn sha256_example( + ikm: &[u8], + salt: &[u8], + info: &[u8], + l: usize, + expected_prk: &[u8], + expected_okm: &[u8], + ) { + init(); + let hkdf = Hkdf::new(Kdf::HkdfSha256); + let k_ikm = Hkdf::import_ikm(ikm).unwrap(); + let prk = hkdf.extract(salt, &k_ikm).unwrap(); + let prk_data = prk.key_data().unwrap(); + assert_eq!(prk_data, expected_prk); + + let out = hkdf.expand_data(&prk, info, l).unwrap(); + assert_eq!(&out[..], expected_okm); + } + + /// Example 1 from + #[test] + fn example1() { + const IKM: &[u8] = &[ + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + ]; + const SALT: &[u8] = &[ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, + ]; + const INFO: &[u8] = &[0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9]; + const L: usize = 42; + const PRK: &[u8] = &[ + 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, + 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, + 0xd7, 0xc2, 0xb3, 0xe5, + ]; + const OKM: &[u8] = &[ + 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, + 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, + 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65, + ]; + sha256_example(IKM, SALT, INFO, L, PRK, OKM); + } + + /// Example 2 from + #[test] + fn example2() { + const IKM: &[u8] = &[ + 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, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + ]; + const SALT: &[u8] = &[ + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, + 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, + 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, + 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + ]; + const INFO: &[u8] = &[ + 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, + 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, + 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, + 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, + 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + ]; + const L: usize = 82; + const PRK: &[u8] = &[ + 0x06, 0xa6, 0xb8, 0x8c, 0x58, 0x53, 0x36, 0x1a, 0x06, 0x10, 0x4c, 0x9c, 0xeb, 0x35, + 0xb4, 0x5c, 0xef, 0x76, 0x00, 0x14, 0x90, 0x46, 0x71, 0x01, 0x4a, 0x19, 0x3f, 0x40, + 0xc1, 0x5f, 0xc2, 0x44, + ]; + const OKM: &[u8] = &[ + 0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, + 0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, + 0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, + 0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, + 0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, + 0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87, + ]; + sha256_example(IKM, SALT, INFO, L, PRK, OKM); + } + + /// Example 3 from + #[test] + fn example3() { + const IKM: &[u8] = &[ + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + ]; + const SALT: &[u8] = &[]; + const INFO: &[u8] = &[]; + const L: usize = 42; + const PRK: &[u8] = &[ + 0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16, 0x7f, 0x33, 0xa9, 0x1d, 0x6f, 0x64, + 0x8b, 0xdf, 0x96, 0x59, 0x67, 0x76, 0xaf, 0xdb, 0x63, 0x77, 0xac, 0x43, 0x4c, 0x1c, + 0x29, 0x3c, 0xcb, 0x04, + ]; + const OKM: &[u8] = &[ + 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c, + 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, + 0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8, + ]; + sha256_example(IKM, SALT, INFO, L, PRK, OKM); + } +} diff --git a/third_party/rust/ohttp/src/rh/hpke.rs b/third_party/rust/ohttp/src/rh/hpke.rs new file mode 100644 index 0000000000..2ffa08f709 --- /dev/null +++ b/third_party/rust/ohttp/src/rh/hpke.rs @@ -0,0 +1,508 @@ +use super::SymKey; +use crate::{ + hpke::{Aead, Kdf, Kem}, + Error, Res, +}; +use ::hpke::{ + aead::{AeadTag, AesGcm128, ChaCha20Poly1305}, + kdf::HkdfSha256, + kem::{Kem as HpkeKem, X25519HkdfSha256}, + kex::{KeyExchange, X25519}, + op_mode::{OpModeR, OpModeS}, + setup::{setup_receiver, setup_sender}, + AeadCtxR, AeadCtxS, Deserializable, EncappedKey, Serializable, +}; +use ::rand::thread_rng; +use log::trace; +use std::ops::Deref; + +/// Configuration for `Hpke`. +#[derive(Clone, Copy)] +pub struct Config { + kem: Kem, + kdf: Kdf, + aead: Aead, +} + +impl Config { + pub fn new(kem: Kem, kdf: Kdf, aead: Aead) -> Self { + Self { kem, kdf, aead } + } + + pub fn kem(self) -> Kem { + self.kem + } + + pub fn kdf(self) -> Kdf { + self.kdf + } + + pub fn aead(self) -> Aead { + self.aead + } + + pub fn supported(self) -> bool { + // TODO support more options + self.kdf == Kdf::HkdfSha256 && matches!(self.aead, Aead::Aes128Gcm | Aead::ChaCha20Poly1305) + } +} + +impl Default for Config { + fn default() -> Self { + Self { + kem: Kem::X25519Sha256, + kdf: Kdf::HkdfSha256, + aead: Aead::Aes128Gcm, + } + } +} + +pub enum PublicKey { + X25519(<::Kex as KeyExchange>::PublicKey), +} + +impl PublicKey { + #[allow(clippy::unnecessary_wraps)] + pub fn key_data(&self) -> Res> { + Ok(match self { + Self::X25519(k) => Vec::from(k.to_bytes().as_slice()), + }) + } +} + +impl std::fmt::Debug for PublicKey { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + if let Ok(b) = self.key_data() { + write!(f, "PublicKey {}", hex::encode(b)) + } else { + write!(f, "Opaque PublicKey") + } + } +} + +pub enum PrivateKey { + X25519(<::Kex as KeyExchange>::PrivateKey), +} + +impl PrivateKey { + #[allow(clippy::unnecessary_wraps)] + pub fn key_data(&self) -> Res> { + Ok(match self { + Self::X25519(k) => Vec::from(k.to_bytes().as_slice()), + }) + } +} + +impl std::fmt::Debug for PrivateKey { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + if let Ok(b) = self.key_data() { + write!(f, "PrivateKey {}", hex::encode(b)) + } else { + write!(f, "Opaque PrivateKey") + } + } +} + +// TODO: Use macros here. To do that, we needs concat_ident!(), but it's not ready. +// This is what a macro that uses concat_ident!() might produce, written out in full. +enum SenderContextX25519HkdfSha256HkdfSha256 { + AesGcm128(Box>), + ChaCha20Poly1305(Box>), +} + +enum SenderContextX25519HkdfSha256 { + HkdfSha256(SenderContextX25519HkdfSha256HkdfSha256), +} + +enum SenderContext { + X25519HkdfSha256(SenderContextX25519HkdfSha256), +} + +impl SenderContext { + fn seal(&mut self, plaintext: &mut [u8], aad: &[u8]) -> Res> { + Ok(match self { + Self::X25519HkdfSha256(SenderContextX25519HkdfSha256::HkdfSha256( + SenderContextX25519HkdfSha256HkdfSha256::AesGcm128(context), + )) => { + let tag = context.seal(plaintext, aad)?; + Vec::from(tag.to_bytes().as_slice()) + } + Self::X25519HkdfSha256(SenderContextX25519HkdfSha256::HkdfSha256( + SenderContextX25519HkdfSha256HkdfSha256::ChaCha20Poly1305(context), + )) => { + let tag = context.seal(plaintext, aad)?; + Vec::from(tag.to_bytes().as_slice()) + } + }) + } + + fn export(&self, info: &[u8], out_buf: &mut [u8]) -> Res<()> { + match self { + Self::X25519HkdfSha256(SenderContextX25519HkdfSha256::HkdfSha256( + SenderContextX25519HkdfSha256HkdfSha256::AesGcm128(context), + )) => { + context.export(info, out_buf)?; + } + Self::X25519HkdfSha256(SenderContextX25519HkdfSha256::HkdfSha256( + SenderContextX25519HkdfSha256HkdfSha256::ChaCha20Poly1305(context), + )) => { + context.export(info, out_buf)?; + } + } + Ok(()) + } +} + +pub trait Exporter { + fn export(&self, info: &[u8], len: usize) -> Res; +} + +#[allow(clippy::module_name_repetitions)] +pub struct HpkeS { + context: SenderContext, + enc: Vec, + config: Config, +} + +impl HpkeS { + /// Create a new context that uses the KEM mode for sending. + pub fn new(config: Config, pk_r: &mut PublicKey, info: &[u8]) -> Res { + let mut csprng = thread_rng(); + + macro_rules! dispatch_hpkes_new { + { + ($c:expr, $pk:expr, $csprng:expr): [$({ + $kemid:path => $kem:path, + $kdfid:path => $kdf:path, + $aeadid:path => $aead:path, + $pke:path, $ctxt1:path, $ctxt2:path, $ctxt3:path $(,)? + }),* $(,)?] + } => { + match ($c, $pk) { + $( + ( + Config { + kem: $kemid, + kdf: $kdfid, + aead: $aeadid, + }, + $pke(pk_r), + ) => { + let (enc, context) = setup_sender::<$aead, $kdf, $kem, _>( + &OpModeS::Base, + pk_r, + info, + $csprng, + )?; + ($ctxt1($ctxt2($ctxt3(Box::new(context)))), enc) + } + )* + _ => return Err(Error::InvalidKeyType), + } + }; + } + let (context, enc) = dispatch_hpkes_new! { (config, pk_r, &mut csprng): [ + { + Kem::X25519Sha256 => X25519HkdfSha256, + Kdf::HkdfSha256 => HkdfSha256, + Aead::Aes128Gcm => AesGcm128, + PublicKey::X25519, + SenderContext::X25519HkdfSha256, + SenderContextX25519HkdfSha256::HkdfSha256, + SenderContextX25519HkdfSha256HkdfSha256::AesGcm128, + }, + { + Kem::X25519Sha256 => X25519HkdfSha256, + Kdf::HkdfSha256 => HkdfSha256, + Aead::ChaCha20Poly1305 => ChaCha20Poly1305, + PublicKey::X25519, + SenderContext::X25519HkdfSha256, + SenderContextX25519HkdfSha256::HkdfSha256, + SenderContextX25519HkdfSha256HkdfSha256::ChaCha20Poly1305, + }, + ]}; + let enc = Vec::from(enc.to_bytes().as_slice()); + Ok(Self { + context, + enc, + config, + }) + } + + pub fn config(&self) -> Config { + self.config + } + + /// Get the encapsulated KEM secret. + #[allow(clippy::unnecessary_wraps)] + pub fn enc(&self) -> Res> { + Ok(self.enc.clone()) + } + + pub fn seal(&mut self, aad: &[u8], pt: &[u8]) -> Res> { + let mut buf = pt.to_owned(); + let mut tag = self.context.seal(&mut buf, aad)?; + buf.append(&mut tag); + Ok(buf) + } +} + +impl Exporter for HpkeS { + fn export(&self, info: &[u8], len: usize) -> Res { + let mut buf = vec![0; len]; + self.context.export(info, &mut buf)?; + Ok(SymKey::from(buf)) + } +} + +impl Deref for HpkeS { + type Target = Config; + fn deref(&self) -> &Self::Target { + &self.config + } +} + +enum ReceiverContextX25519HkdfSha256HkdfSha256 { + AesGcm128(Box>), + ChaCha20Poly1305(Box>), +} + +enum ReceiverContextX25519HkdfSha256 { + HkdfSha256(ReceiverContextX25519HkdfSha256HkdfSha256), +} + +enum ReceiverContext { + X25519HkdfSha256(ReceiverContextX25519HkdfSha256), +} + +impl ReceiverContext { + fn open<'a>(&mut self, ciphertext: &'a mut [u8], aad: &[u8]) -> Res<&'a [u8]> { + Ok(match self { + Self::X25519HkdfSha256(ReceiverContextX25519HkdfSha256::HkdfSha256( + ReceiverContextX25519HkdfSha256HkdfSha256::AesGcm128(context), + )) => { + if ciphertext.len() < AeadTag::::size() { + return Err(Error::Truncated); + } + let (ct, tag) = + ciphertext.split_at_mut(ciphertext.len() - AeadTag::::size()); + let tag = AeadTag::::from_bytes(tag)?; + context.open(ct, aad, &tag)?; + ct + } + Self::X25519HkdfSha256(ReceiverContextX25519HkdfSha256::HkdfSha256( + ReceiverContextX25519HkdfSha256HkdfSha256::ChaCha20Poly1305(context), + )) => { + if ciphertext.len() < AeadTag::::size() { + return Err(Error::Truncated); + } + let (ct, tag) = + ciphertext.split_at_mut(ciphertext.len() - AeadTag::::size()); + let tag = AeadTag::::from_bytes(tag)?; + context.open(ct, aad, &tag)?; + ct + } + }) + } + + fn export(&self, info: &[u8], out_buf: &mut [u8]) -> Res<()> { + match self { + Self::X25519HkdfSha256(ReceiverContextX25519HkdfSha256::HkdfSha256( + ReceiverContextX25519HkdfSha256HkdfSha256::AesGcm128(context), + )) => { + context.export(info, out_buf)?; + } + Self::X25519HkdfSha256(ReceiverContextX25519HkdfSha256::HkdfSha256( + ReceiverContextX25519HkdfSha256HkdfSha256::ChaCha20Poly1305(context), + )) => { + context.export(info, out_buf)?; + } + } + Ok(()) + } +} + +#[allow(clippy::module_name_repetitions)] +pub struct HpkeR { + context: ReceiverContext, + config: Config, +} + +impl HpkeR { + /// Create a new context that uses the KEM mode for sending. + #[allow(clippy::similar_names)] + pub fn new( + config: Config, + _pk_r: &PublicKey, + sk_r: &mut PrivateKey, + enc: &[u8], + info: &[u8], + ) -> Res { + macro_rules! dispatch_hpker_new { + { + ($c:ident, $sk:ident): [$({ + $kemid:path => $kem:path, + $kdfid:path => $kdf:path, + $aeadid:path => $aead:path, + $ske:path, $ctxt1:path, $ctxt2:path, $ctxt3:path $(,)? + }),* $(,)?] + } => { + match ($c, $sk) { + $( + ( + Config { + kem: $kemid, + kdf: $kdfid, + aead: $aeadid, + }, + $ske(sk_r), + ) => { + let enc = EncappedKey::from_bytes(enc)?; + let context = setup_receiver::<$aead, $kdf, $kem>( + &OpModeR::Base, + sk_r, + &enc, + info, + )?; + $ctxt1($ctxt2($ctxt3(Box::new(context)))) + } + )* + _ => return Err(Error::InvalidKeyType), + } + }; + } + let context = dispatch_hpker_new! {(config, sk_r): [ + { + Kem::X25519Sha256 => X25519HkdfSha256, + Kdf::HkdfSha256 => HkdfSha256, + Aead::Aes128Gcm => AesGcm128, + PrivateKey::X25519, + ReceiverContext::X25519HkdfSha256, + ReceiverContextX25519HkdfSha256::HkdfSha256, + ReceiverContextX25519HkdfSha256HkdfSha256::AesGcm128, + }, + { + Kem::X25519Sha256 => X25519HkdfSha256, + Kdf::HkdfSha256 => HkdfSha256, + Aead::ChaCha20Poly1305 => ChaCha20Poly1305, + PrivateKey::X25519, + ReceiverContext::X25519HkdfSha256, + ReceiverContextX25519HkdfSha256::HkdfSha256, + ReceiverContextX25519HkdfSha256HkdfSha256::ChaCha20Poly1305, + }, + ]}; + Ok(Self { context, config }) + } + + pub fn config(&self) -> Config { + self.config + } + + pub fn decode_public_key(kem: Kem, k: &[u8]) -> Res { + Ok(match kem { + Kem::X25519Sha256 => { + PublicKey::X25519(::PublicKey::from_bytes(k)?) + } + }) + } + + pub fn open(&mut self, aad: &[u8], ct: &[u8]) -> Res> { + let mut buf = ct.to_owned(); + let pt_len = self.context.open(&mut buf, aad)?.len(); + buf.truncate(pt_len); + Ok(buf) + } +} + +impl Exporter for HpkeR { + fn export(&self, info: &[u8], len: usize) -> Res { + let mut buf = vec![0; len]; + self.context.export(info, &mut buf)?; + Ok(SymKey::from(buf)) + } +} + +impl Deref for HpkeR { + type Target = Config; + fn deref(&self) -> &Self::Target { + &self.config + } +} + +/// Generate a key pair for the identified KEM. +#[allow(clippy::unnecessary_wraps)] +pub fn generate_key_pair(kem: Kem) -> Res<(PrivateKey, PublicKey)> { + let mut csprng = thread_rng(); + let (sk, pk) = match kem { + Kem::X25519Sha256 => { + let (sk, pk) = X25519HkdfSha256::gen_keypair(&mut csprng); + (PrivateKey::X25519(sk), PublicKey::X25519(pk)) + } + }; + trace!("Generated key pair: sk={:?} pk={:?}", sk, pk); + Ok((sk, pk)) +} + +#[allow(clippy::unnecessary_wraps)] +pub fn derive_key_pair(kem: Kem, ikm: &[u8]) -> Res<(PrivateKey, PublicKey)> { + let (sk, pk) = match kem { + Kem::X25519Sha256 => { + let (sk, pk) = X25519HkdfSha256::derive_keypair(ikm); + (PrivateKey::X25519(sk), PublicKey::X25519(pk)) + } + }; + trace!("Derived key pair: sk={:?} pk={:?}", sk, pk); + Ok((sk, pk)) +} + +#[cfg(test)] +mod test { + use super::{generate_key_pair, Config, HpkeR, HpkeS}; + use crate::{hpke::Aead, init}; + + const INFO: &[u8] = b"info"; + const AAD: &[u8] = b"aad"; + const PT: &[u8] = b"message"; + + #[allow(clippy::similar_names)] // for sk_x and pk_x + #[test] + fn make() { + init(); + let cfg = Config::default(); + let (mut sk_r, mut pk_r) = generate_key_pair(cfg.kem()).unwrap(); + let hpke_s = HpkeS::new(cfg, &mut pk_r, INFO).unwrap(); + let _hpke_r = HpkeR::new(cfg, &pk_r, &mut sk_r, &hpke_s.enc().unwrap(), INFO).unwrap(); + } + + #[allow(clippy::similar_names)] // for sk_x and pk_x + fn seal_open(aead: Aead) { + // Setup + init(); + let cfg = Config { + aead, + ..Config::default() + }; + assert!(cfg.supported()); + let (mut sk_r, mut pk_r) = generate_key_pair(cfg.kem()).unwrap(); + + // Send + let mut hpke_s = HpkeS::new(cfg, &mut pk_r, INFO).unwrap(); + let enc = hpke_s.enc().unwrap(); + let ct = hpke_s.seal(AAD, PT).unwrap(); + + // Receive + let mut hpke_r = HpkeR::new(cfg, &pk_r, &mut sk_r, &enc, INFO).unwrap(); + let pt = hpke_r.open(AAD, &ct).unwrap(); + assert_eq!(&pt[..], PT); + } + + #[test] + fn seal_open_gcm() { + seal_open(Aead::Aes128Gcm); + } + + #[test] + fn seal_open_chacha() { + seal_open(Aead::ChaCha20Poly1305); + } +} diff --git a/third_party/rust/ohttp/src/rh/mod.rs b/third_party/rust/ohttp/src/rh/mod.rs new file mode 100644 index 0000000000..8f91a2ab17 --- /dev/null +++ b/third_party/rust/ohttp/src/rh/mod.rs @@ -0,0 +1,47 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub mod aead; +pub mod hkdf; +pub mod hpke; + +use crate::err::Res; + +pub struct SymKey(Vec); + +impl SymKey { + #[allow(clippy::unnecessary_wraps)] + pub fn key_data(&self) -> Res<&[u8]> { + Ok(&self.0) + } +} + +impl From> for SymKey { + fn from(v: Vec) -> Self { + SymKey(v) + } +} +impl From<&[u8]> for SymKey { + fn from(v: &[u8]) -> Self { + SymKey(v.to_owned()) + } +} + +impl AsRef<[u8]> for SymKey { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +impl std::fmt::Debug for SymKey { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + if let Ok(b) = self.key_data() { + write!(f, "SymKey {}", hex::encode(b)) + } else { + write!(f, "Opaque SymKey") + } + } +} -- cgit v1.2.3