diff --git a/crates/ccc-crypto-boring/src/aead.rs b/crates/ccc-crypto-boring/src/aead.rs new file mode 100644 index 0000000..cf1f284 --- /dev/null +++ b/crates/ccc-crypto-boring/src/aead.rs @@ -0,0 +1,216 @@ +//! AEADs from BoringSSL's `EVP_AEAD` interface. +//! +//! Wire format matches the other providers: `ciphertext || 16-byte tag`. +//! +//! | Algorithm | BoringSSL | +//! |--------------------|---------------------------------| +//! | AES-256-GCM | `EVP_aead_aes_256_gcm` | +//! | ChaCha20-Poly1305 | `EVP_aead_chacha20_poly1305` | +//! | XChaCha20-Poly1305 | `EVP_aead_xchacha20_poly1305` | +//! +//! BoringSSL has AES-256-GCM-SIV, but `boring` exposes it only through a raw +//! pointer (`unsafe`), so ID 16 is not offered. Ascon is not in BoringSSL. +//! Those IDs return [`CryptoError::FeatureNotCompiled`]. +//! +//! The key schedule lives in the `EVP_AEAD_CTX`, which BoringSSL wipes when +//! it is freed (`OPENSSL_free` cleanses). + +use boring::aead::{AeadCtx, Algorithm}; +use zeroize::Zeroize; + +use ccc_crypto_core::{algorithms::AeadAlgorithm, error::CryptoError}; + +const TAG_LEN: usize = 16; + +fn algorithm(algo: AeadAlgorithm) -> Result { + match algo { + AeadAlgorithm::AesGcm256 => Ok(Algorithm::aes_256_gcm()), + AeadAlgorithm::ChaCha20Poly1305 => Ok(Algorithm::chacha20_poly1305()), + AeadAlgorithm::XChaCha20Poly1305 => Ok(Algorithm::xchacha20_poly1305()), + AeadAlgorithm::AesGcmSiv256 | AeadAlgorithm::Ascon128a | AeadAlgorithm::AsconAead128 => { + Err(CryptoError::FeatureNotCompiled(format!( + "{} is not offered by the boring provider", + algo.name() + ))) + } + } +} + +fn context(algo: AeadAlgorithm, key: &[u8], nonce: &[u8]) -> Result { + let alg = algorithm(algo)?; + if key.len() != algo.key_len() { + return Err(CryptoError::InvalidKey(format!( + "{}: expected {}-byte key, got {}", + algo.name(), + algo.key_len(), + key.len() + ))); + } + if nonce.len() != algo.nonce_len() { + return Err(CryptoError::InvalidNonce(format!( + "{}: expected {}-byte nonce, got {}", + algo.name(), + algo.nonce_len(), + nonce.len() + ))); + } + AeadCtx::new(&alg, key, TAG_LEN) + .map_err(|e| CryptoError::InternalError(format!("{}: {e}", algo.name()))) +} + +/// Encrypt `plaintext`; returns `ciphertext || tag`. +pub fn encrypt( + algo: AeadAlgorithm, + key: &[u8], + nonce: &[u8], + plaintext: &[u8], + aad: &[u8], +) -> Result, CryptoError> { + let mut ctx = context(algo, key, nonce)?; + let mut out = Vec::with_capacity(plaintext.len() + TAG_LEN); + out.extend_from_slice(plaintext); + out.resize(plaintext.len() + TAG_LEN, 0); + let (body, tag) = out.split_at_mut(plaintext.len()); + let written = ctx + .seal_in_place_mut(nonce, body, tag, aad) + .map_err(|e| CryptoError::InvalidInput(format!("{}: seal failed: {e}", algo.name())))? + .len(); + if written != TAG_LEN { + out.zeroize(); + return Err(CryptoError::InternalError(format!( + "{}: unexpected {written}-byte tag", + algo.name() + ))); + } + Ok(out) +} + +/// Authenticate and decrypt `ciphertext || tag`. +/// +/// Returns [`CryptoError::AuthenticationFailed`] if the tag does not verify; +/// no unauthenticated plaintext is returned or left in memory. +pub fn decrypt( + algo: AeadAlgorithm, + key: &[u8], + nonce: &[u8], + ciphertext_and_tag: &[u8], + aad: &[u8], +) -> Result, CryptoError> { + let mut ctx = context(algo, key, nonce)?; + if ciphertext_and_tag.len() < TAG_LEN { + return Err(CryptoError::InvalidInput(format!( + "{}: ciphertext too short (no room for tag)", + algo.name() + ))); + } + let (ct, tag) = ciphertext_and_tag.split_at(ciphertext_and_tag.len() - TAG_LEN); + let mut buf = ct.to_vec(); + // Key and nonce lengths were checked above, so a failure is the tag. + if ctx.open_in_place_mut(nonce, &mut buf, tag, aad).is_err() { + buf.zeroize(); + return Err(CryptoError::AuthenticationFailed); + } + Ok(buf) +} + +#[cfg(test)] +mod tests { + use super::*; + + const OFFERED: [AeadAlgorithm; 3] = [ + AeadAlgorithm::AesGcm256, + AeadAlgorithm::ChaCha20Poly1305, + AeadAlgorithm::XChaCha20Poly1305, + ]; + + fn inputs(algo: AeadAlgorithm) -> (Vec, Vec) { + let key = (0..algo.key_len() as u8).collect(); + let nonce = (0..algo.nonce_len() as u8).map(|b| b ^ 0x5a).collect(); + (key, nonce) + } + + #[test] + fn roundtrip_all_offered() { + for algo in OFFERED { + let (key, nonce) = inputs(algo); + for (pt, aad) in [ + (&b"hello cascade"[..], &b"hdr"[..]), + (b"", b""), + (b"x", b""), + (b"", b"aad only"), + ] { + let ct = encrypt(algo, &key, &nonce, pt, aad).unwrap(); + assert_eq!(ct.len(), pt.len() + TAG_LEN, "{}", algo.name()); + assert_eq!(decrypt(algo, &key, &nonce, &ct, aad).unwrap(), pt); + } + } + } + + #[test] + fn tampering_is_rejected() { + for algo in OFFERED { + let (key, nonce) = inputs(algo); + let ct = encrypt(algo, &key, &nonce, b"payload", b"aad").unwrap(); + for i in [0, ct.len() - 1] { + let mut bad = ct.clone(); + bad[i] ^= 0x01; + assert!(matches!( + decrypt(algo, &key, &nonce, &bad, b"aad"), + Err(CryptoError::AuthenticationFailed) + )); + } + assert!(matches!( + decrypt(algo, &key, &nonce, &ct, b"aaD"), + Err(CryptoError::AuthenticationFailed) + )); + } + } + + #[test] + fn bad_lengths_are_rejected() { + for algo in OFFERED { + let (key, nonce) = inputs(algo); + assert!(matches!( + encrypt(algo, &key[1..], &nonce, b"", b""), + Err(CryptoError::InvalidKey(_)) + )); + assert!(matches!( + encrypt(algo, &key, &nonce[1..], b"", b""), + Err(CryptoError::InvalidNonce(_)) + )); + assert!(matches!( + decrypt(algo, &key, &nonce, &[0u8; 15], b""), + Err(CryptoError::InvalidInput(_)) + )); + } + } + + #[test] + fn missing_aeads_are_not_compiled() { + for algo in [ + AeadAlgorithm::AesGcmSiv256, + AeadAlgorithm::Ascon128a, + AeadAlgorithm::AsconAead128, + ] { + let (key, nonce) = inputs(algo); + assert!(matches!( + encrypt(algo, &key, &nonce, b"", b""), + Err(CryptoError::FeatureNotCompiled(_)) + )); + assert!(matches!( + decrypt(algo, &key, &nonce, &[0u8; 16], b""), + Err(CryptoError::FeatureNotCompiled(_)) + )); + } + } + + #[test] + fn algorithms_are_not_interchangeable() { + let key = [7u8; 32]; + let nonce = [9u8; 12]; + let gcm = encrypt(AeadAlgorithm::AesGcm256, &key, &nonce, b"same", b"").unwrap(); + let cha = encrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, b"same", b"").unwrap(); + assert_ne!(gcm, cha); + assert!(decrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, &gcm, b"").is_err()); + } +} diff --git a/crates/ccc-crypto-boring/src/lib.rs b/crates/ccc-crypto-boring/src/lib.rs index b154d86..d93955d 100644 --- a/crates/ccc-crypto-boring/src/lib.rs +++ b/crates/ccc-crypto-boring/src/lib.rs @@ -16,6 +16,7 @@ #![forbid(unsafe_code)] +pub mod aead; pub mod hash; pub mod kdf; pub mod mac;