diff --git a/crates/ccc-crypto-boring/src/capabilities.rs b/crates/ccc-crypto-boring/src/capabilities.rs new file mode 100644 index 0000000..9e921e2 --- /dev/null +++ b/crates/ccc-crypto-boring/src/capabilities.rs @@ -0,0 +1,270 @@ +//! Live capability probes and the AEAD throughput benchmark. +//! +//! An algorithm is `available` only when a live probe succeeds **and** its +//! known-answer self-test passed, so a failing KAT removes the algorithm +//! (fail closed, D-28). Every other ID is listed as unavailable. + +use std::time::Instant; + +use ccc_crypto_core::{ + algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm}, + capabilities::{AlgorithmCapability, ProviderCapabilities}, + types::{AlgoBenchResult, BenchmarkReport, SelfTestReport}, +}; + +use crate::{aead, hash, kdf, kem, mac, PROVIDER_NAME}; + +/// AEADs this provider implements, in benchmark order. +pub const AEADS: [AeadAlgorithm; 3] = [ + AeadAlgorithm::AesGcm256, + AeadAlgorithm::ChaCha20Poly1305, + AeadAlgorithm::XChaCha20Poly1305, +]; + +/// KDFs this provider implements. +pub const KDFS: [KdfAlgorithm; 3] = [ + KdfAlgorithm::Sha256, + KdfAlgorithm::Sha384, + KdfAlgorithm::Sha512, +]; + +/// MACs this provider implements. +pub const MACS: [MacAlgorithm; 3] = [ + MacAlgorithm::HmacSha256, + MacAlgorithm::HmacSha384, + MacAlgorithm::HmacSha512, +]; + +/// Hashes this provider implements. +pub const HASHES: [HashAlgorithm; 3] = [ + HashAlgorithm::Sha256, + HashAlgorithm::Sha384, + HashAlgorithm::Sha512, +]; + +/// KEMs this provider implements. +pub const KEMS: [KemAlgorithm; 3] = [ + KemAlgorithm::X25519, + KemAlgorithm::MlKem768, + KemAlgorithm::MlKem1024, +]; + +const ALL_KDFS: [KdfAlgorithm; 6] = [ + KdfAlgorithm::Sha256, + KdfAlgorithm::Sha384, + KdfAlgorithm::Sha512, + KdfAlgorithm::Blake2b512, + KdfAlgorithm::Argon2id, + KdfAlgorithm::Kmac256, +]; + +const ALL_MACS: [MacAlgorithm; 5] = [ + MacAlgorithm::HmacSha256, + MacAlgorithm::HmacSha384, + MacAlgorithm::HmacSha512, + MacAlgorithm::Blake2bMac, + MacAlgorithm::Poly1305, +]; + +const ALL_HASHES: [HashAlgorithm; 6] = [ + HashAlgorithm::Sha256, + HashAlgorithm::Sha384, + HashAlgorithm::Sha512, + HashAlgorithm::Blake2b512, + HashAlgorithm::Sha3_256, + HashAlgorithm::Sha3_512, +]; + +fn kat_passed(report: &SelfTestReport, id: u32) -> bool { + let mut results = report.results.iter().filter(|r| r.algo_id == id).peekable(); + // An algorithm without a KAT is never marked available. + results.peek().is_some() && results.all(|r| r.passed) +} + +fn cap(available: bool, deterministic_io: bool, efficiency_score: u8) -> AlgorithmCapability { + if !available { + return AlgorithmCapability::unavailable(); + } + AlgorithmCapability { + available, + deterministic_io, + efficiency_score, + reliability_score: 100, + } +} + +fn aead_probe(algo: AeadAlgorithm) -> bool { + let key = vec![0u8; algo.key_len()]; + let nonce = vec![0u8; algo.nonce_len()]; + aead::encrypt(algo, &key, &nonce, b"x", b"") + .and_then(|ct| aead::decrypt(algo, &key, &nonce, &ct, b"")) + .is_ok_and(|pt| pt == b"x") +} + +fn kem_probe(algo: KemAlgorithm) -> bool { + let Ok(kp) = kem::generate_keypair(algo) else { + return false; + }; + let Ok(enc) = kem::encapsulate(algo, &kp.public_key) else { + return false; + }; + kem::decapsulate(algo, &kp.private_key, &enc.ciphertext) + .is_ok_and(|ss| *ss == enc.shared_secret) +} + +/// Build the capability matrix from live probes, the self-test report and +/// (optionally) benchmark scores. +pub fn probe_capabilities( + self_test: &SelfTestReport, + benchmarks: Option<&BenchmarkReport>, +) -> ProviderCapabilities { + let mut caps = ProviderCapabilities::empty(PROVIDER_NAME); + let score = |id: u32| { + benchmarks + .and_then(|b| b.results.iter().find(|r| r.algo_id == id)) + .map(|r| r.efficiency_score) + .unwrap_or(0) + }; + + for algo in AeadAlgorithm::ALL { + let ok = AEADS.contains(&algo) && aead_probe(algo) && kat_passed(self_test, algo as u32); + caps = caps.with_aead(algo, cap(ok, true, score(algo as u32))); + } + for algo in ALL_KDFS { + let ok = KDFS.contains(&algo) + && kdf::derive_key(algo, b"key", b"salt", b"info", 32).is_ok() + && kat_passed(self_test, algo as u32); + caps = caps.with_kdf(algo, cap(ok, true, 80)); + } + for algo in ALL_MACS { + let ok = MACS.contains(&algo) + && mac::compute_mac(algo, &[0x42; 32], b"data").is_ok() + && kat_passed(self_test, algo as u32); + caps = caps.with_mac(algo, cap(ok, true, 85)); + } + for algo in ALL_HASHES { + let ok = HASHES.contains(&algo) + && hash::hash(algo, b"probe").is_ok() + && kat_passed(self_test, algo as u32); + caps = caps.with_hash(algo, cap(ok, true, 90)); + } + for algo in KemAlgorithm::ALL { + let ok = KEMS.contains(&algo) && kem_probe(algo) && kat_passed(self_test, algo as u32); + // Key generation and encapsulation are randomised. + caps = caps.with_kem(algo, cap(ok, false, 80)); + } + caps +} + +/// The provider benchmark: 100 × 1 MiB per AEAD, as in the other providers. +pub fn run_benchmark() -> BenchmarkReport { + run_benchmark_with(1024 * 1024, 100) +} + +/// Encrypt `iters` × `size` bytes per AEAD and score each relative to the +/// fastest (0–100). +pub fn run_benchmark_with(size: usize, iters: u32) -> BenchmarkReport { + let plaintext = vec![0xABu8; size]; + let mut raw: Vec<(AeadAlgorithm, f64)> = Vec::new(); + for algo in AEADS { + if !aead_probe(algo) { + continue; + } + let key = vec![0u8; algo.key_len()]; + let nonce = vec![0u8; algo.nonce_len()]; + let start = Instant::now(); + for _ in 0..iters { + let _ = aead::encrypt(algo, &key, &nonce, &plaintext, b""); + } + let secs = start.elapsed().as_secs_f64().max(1e-9); + raw.push(( + algo, + (size as f64 * iters as f64) / (1024.0 * 1024.0 * secs), + )); + } + let max = raw.iter().map(|(_, t)| *t).fold(0.0, f64::max); + let results = raw + .into_iter() + .map(|(algo, throughput)| AlgoBenchResult { + algo_id: algo as u32, + algo_name: algo.name().into(), + throughput_mbps: throughput, + efficiency_score: if max > 0.0 { + ((throughput / max) * 100.0).round() as u8 + } else { + 0 + }, + }) + .collect(); + BenchmarkReport { + provider_name: PROVIDER_NAME.into(), + results, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ccc_crypto_core::types::AlgoTestResult; + + #[test] + fn only_kat_backed_algorithms_are_available() { + let report = crate::self_test::run(); + let caps = probe_capabilities(&report, None); + assert_eq!(caps.provider_name, "boring"); + let has_kat = |id: u32| report.results.iter().any(|r| r.algo_id == id && r.passed); + for (algo, c) in &caps.aead { + assert_eq!(c.available, AEADS.contains(algo), "{}", algo.name()); + assert!(!c.available || has_kat(*algo as u32)); + } + for (algo, c) in &caps.kdf { + assert_eq!(c.available, KDFS.contains(algo), "{}", algo.name()); + assert!(!c.available || has_kat(*algo as u32)); + } + for (algo, c) in &caps.mac { + assert_eq!(c.available, MACS.contains(algo), "{}", algo.name()); + assert!(!c.available || has_kat(*algo as u32)); + } + for (algo, c) in &caps.hash { + assert_eq!(c.available, HASHES.contains(algo), "{}", algo.name()); + assert!(!c.available || has_kat(*algo as u32)); + } + for (algo, c) in &caps.kem { + assert_eq!(c.available, KEMS.contains(algo), "{}", algo.name()); + assert!(!c.available || has_kat(*algo as u32)); + } + // Every registry ID is listed, available or not. + assert_eq!(caps.aead.len(), AeadAlgorithm::ALL.len()); + assert_eq!(caps.kdf.len(), ALL_KDFS.len()); + assert_eq!(caps.mac.len(), ALL_MACS.len()); + assert_eq!(caps.hash.len(), ALL_HASHES.len()); + assert_eq!(caps.kem.len(), KemAlgorithm::ALL.len()); + } + + #[test] + fn failed_kat_makes_algorithm_unavailable() { + let mut report = crate::self_test::run(); + report.results.push(AlgoTestResult { + algo_id: AeadAlgorithm::AesGcm256 as u32, + algo_name: "forced failure".into(), + passed: false, + error_message: Some("test".into()), + }); + report + .results + .retain(|r| r.algo_id != KemAlgorithm::MlKem1024 as u32); + let caps = probe_capabilities(&report, None); + assert!(!caps.aead[&AeadAlgorithm::AesGcm256].available); + assert!(caps.aead[&AeadAlgorithm::ChaCha20Poly1305].available); + // A missing KAT counts as a failed one. + assert!(!caps.kem[&KemAlgorithm::MlKem1024].available); + assert!(caps.kem[&KemAlgorithm::MlKem768].available); + } + + #[test] + fn small_benchmark_scores_every_aead() { + let report = run_benchmark_with(4096, 2); + assert_eq!(report.results.len(), AEADS.len()); + assert!(report.results.iter().any(|r| r.efficiency_score == 100)); + } +} diff --git a/crates/ccc-crypto-boring/src/lib.rs b/crates/ccc-crypto-boring/src/lib.rs index 2d5e9db..c63e14c 100644 --- a/crates/ccc-crypto-boring/src/lib.rs +++ b/crates/ccc-crypto-boring/src/lib.rs @@ -17,6 +17,7 @@ #![forbid(unsafe_code)] pub mod aead; +pub mod capabilities; pub mod hash; pub mod kdf; pub mod kem;