diff --git a/crates/ccc-crypto-oqs/src/self_test.rs b/crates/ccc-crypto-oqs/src/self_test.rs new file mode 100644 index 0000000..9f5c0d4 --- /dev/null +++ b/crates/ccc-crypto-oqs/src/self_test.rs @@ -0,0 +1,257 @@ +//! Seeded known-answer self-test for every KEM the provider offers. +//! +//! liboqs draws all randomness through `OQS_randombytes`. For the KAT the +//! provider swaps in a deterministic stream, the same one the RustCrypto +//! McEliece KAT uses: `SHA3-256(label || be64(0)) || SHA3-256(label || +//! be64(1)) || ...`, consumed by key generation and then encapsulation. +//! Every liboqs call that draws randomness holds the provider's RNG lock, so +//! no other caller can draw from the seeded stream; the system RNG is +//! restored before the lock is released, even if the KAT panics. +//! +//! Sources of the expected values: +//! +//! - Classic-McEliece-460896f: the values of the RustCrypto provider's KAT +//! (label `ccc-kat/mceliece460896f`), produced there by +//! `classic-mceliece-rust` 3.1.0 and reproduced here by liboqs 0.13.0. +//! Two independent code bases agree, so the vector is a real cross-check. +//! - HQC-192 and FrodoKEM-976-SHAKE: produced by liboqs 0.13.0 itself, so +//! they only catch a changed or miscompiled build, not a wrong one. +//! liboqs checks these algorithms against the NIST KAT files in its CI. +//! +//! Large values are pinned as SHA3-256 digests. + +use std::sync::Mutex; + +use oqs::ffi::rand::{OQS_randombytes_custom_algorithm, OQS_randombytes_switch_algorithm}; +use oqs::ffi::common::OQS_STATUS; + +use ccc_crypto_core::{ + algorithms::KemAlgorithm, + types::{AlgoTestResult, SelfTestReport}, +}; + +use crate::{kem, PROVIDER_NAME}; + +/// One KAT: the stream label and the expected digests. +struct Kat { + algo: KemAlgorithm, + label: &'static [u8], + pk_sha3: &'static str, + sk_sha3: &'static str, + ct_sha3: &'static str, + ss: &'static str, +} + +const KATS: [Kat; 3] = [ + Kat { + algo: KemAlgorithm::ClassicMcEliece460896f, + label: b"ccc-kat/mceliece460896f", + pk_sha3: "e0e4f4faf27adcfedb35b8822a05f7938e80c62fd492f726e6ff76a549b43194", + sk_sha3: "59bf486dc9b6c93f6eb9854821eb237000b421c92710a2172c10570a6a014cf4", + ct_sha3: "a69376ae13d09fe536c544ea6049ee22f64d73761d209e3b44528f646d52a358", + ss: "ce2f2240ab5e51e313b7a1ee3c30e2f1882e37fbba0c8f5cb337b2e01d3e4cf3", + }, + Kat { + algo: KemAlgorithm::Hqc192, + label: b"ccc-kat/hqc192", + pk_sha3: "3e89ff491e0dca52e7978f5d820402197e2d6d7275e4e3835b1d2d9f2061706b", + sk_sha3: "04b467a8fa815cf2fafbf27c8c8869c508401103398af6b73eb0feaa50dda09e", + ct_sha3: "c9389a0f0158ccc04e00b13e54a93feeb4069e4a032062a305d2484f3f26adc3", + ss: "593ad41c4f81b2497d1241042c4a79f6ca7363008413a0b00078522e6aa9fced\ + d3a1ba57be71c49b9252a8a97ddea64b45f4c77897c7c9a358fb9d6bd395b58f", + }, + Kat { + algo: KemAlgorithm::FrodoKem976Shake, + label: b"ccc-kat/frodokem976shake", + pk_sha3: "9dd9f14f5975415b4cfd519dcb2b6642780c71b1ed208b5bf199d6110c071a3d", + sk_sha3: "2bad1349b0a2e951e342f70940942911de7a156a8aeb1b88627d8839710760f5", + ct_sha3: "3b9c60a6c65119ec5481856200b5b98bc10fd6b02cd043bd398ae2f803301431", + ss: "97c1484033bcd60c51cbd6890ed7c1fc89cbdb851090cd56", + }, +]; + +/// Run every KAT. Never panics; failures are reported per algorithm. +pub fn run() -> SelfTestReport { + let results = KATS + .iter() + .map(|kat| { + let outcome = check(kat); + AlgoTestResult { + algo_id: kat.algo as u32, + algo_name: format!("{} seeded KAT", kat.algo.name()), + passed: outcome.is_ok(), + error_message: outcome.err(), + } + }) + .collect(); + SelfTestReport::finalise(PROVIDER_NAME, results) +} + +/// The values a KAT produces: SHA3-256 of pk, sk and ct, and the secret. +pub(crate) type KatOutput = [Vec; 4]; + +/// Keygen and encapsulation from the seeded stream for `label`, then +/// decapsulation, which must give the same secret. +pub(crate) fn kat_output(algo: KemAlgorithm, label: &'static [u8]) -> Result { + let (kp, enc) = { + let _rng = kem::rng_lock(); + let _seeded = SeededRng::install(label); + let kp = kem::generate_locked(algo).map_err(|e| e.to_string())?; + let enc = kem::encapsulate_locked(algo, &kp.public_key).map_err(|e| e.to_string())?; + (kp, enc) + }; + let ss = kem::decapsulate(algo, &kp.private_key, &enc.ciphertext).map_err(|e| e.to_string())?; + if *ss != enc.shared_secret { + return Err("decapsulated secret differs".into()); + } + Ok([ + sha3_256(&kp.public_key).to_vec(), + sha3_256(&kp.private_key).to_vec(), + sha3_256(&enc.ciphertext).to_vec(), + enc.shared_secret.clone(), + ]) +} + +fn check(kat: &Kat) -> Result<(), String> { + let got = kat_output(kat.algo, kat.label)?; + for (what, got, want) in [ + ("public key", &got[0], kat.pk_sha3), + ("private key", &got[1], kat.sk_sha3), + ("ciphertext", &got[2], kat.ct_sha3), + ("secret", &got[3], kat.ss), + ] { + if hex(got) != want { + return Err(format!("{what}: output mismatch")); + } + } + Ok(()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn sha3_256(data: &[u8]) -> [u8; 32] { + use sha3::Digest; + sha3::Sha3_256::digest(data).into() +} + +/// The seeded stream. `None` when no KAT is running. +static STREAM: Mutex> = Mutex::new(None); + +struct Stream { + label: &'static [u8], + counter: u64, + block: [u8; 32], + used: usize, +} + +impl Stream { + fn fill(&mut self, out: &mut [u8]) { + for b in out { + if self.used == 32 { + let mut input = self.label.to_vec(); + input.extend_from_slice(&self.counter.to_be_bytes()); + self.block = sha3_256(&input); + self.counter += 1; + self.used = 0; + } + *b = self.block[self.used]; + self.used += 1; + } + } +} + +/// liboqs randomness callback while a KAT runs. +/// +/// It must not unwind into C, so it never panics. If called with no KAT +/// running (which the RNG lock rules out), it falls back to the OS RNG and +/// aborts if that fails rather than hand out predictable bytes. +unsafe extern "C" fn seeded_randombytes(buf: *mut u8, len: usize) { + if buf.is_null() || len == 0 { + return; + } + // SAFETY: liboqs passes a writable buffer of `len` bytes. + let out = unsafe { std::slice::from_raw_parts_mut(buf, len) }; + let mut stream = STREAM.lock().unwrap_or_else(|p| p.into_inner()); + match stream.as_mut() { + Some(s) => s.fill(out), + None => { + if getrandom::fill(out).is_err() { + std::process::abort(); + } + } + } +} + +/// Installs the seeded stream; dropping it restores the system RNG. The +/// caller must hold the RNG lock for the guard's whole life. +struct SeededRng; + +impl SeededRng { + fn install(label: &'static [u8]) -> Self { + *STREAM.lock().unwrap_or_else(|p| p.into_inner()) = Some(Stream { + label, + counter: 0, + block: [0; 32], + used: 32, + }); + // SAFETY: the callback has the signature liboqs expects and stays + // valid for the life of the program. + unsafe { OQS_randombytes_custom_algorithm(Some(seeded_randombytes)) }; + SeededRng + } +} + +impl Drop for SeededRng { + fn drop(&mut self) { + // SAFETY: a NUL-terminated algorithm name liboqs always knows. + let status = unsafe { OQS_randombytes_switch_algorithm(c"system".as_ptr()) }; + if status != OQS_STATUS::OQS_SUCCESS { + // Never leave liboqs on the seeded stream. + std::process::abort(); + } + *STREAM.lock().unwrap_or_else(|p| p.into_inner()) = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_kats_pass() { + let report = run(); + for r in &report.results { + assert!(r.passed, "{}: {:?}", r.algo_name, r.error_message); + } + assert!(report.all_passed); + } + + #[test] + fn system_rng_is_restored() { + let a = kat_output(KemAlgorithm::Hqc192, b"ccc-kat/hqc192").unwrap(); + let b = kat_output(KemAlgorithm::Hqc192, b"ccc-kat/hqc192").unwrap(); + assert_eq!(a, b); + let x = kem::generate_keypair(KemAlgorithm::Hqc192).unwrap(); + let y = kem::generate_keypair(KemAlgorithm::Hqc192).unwrap(); + assert_ne!(x.public_key, y.public_key); + assert_ne!(sha3_256(&x.public_key).to_vec(), a[0]); + } + + #[test] + #[ignore = "prints the KAT values; run when liboqs changes"] + fn print_kat_values() { + for kat in &KATS { + let got = kat_output(kat.algo, kat.label).unwrap(); + println!( + "{}: pk {} sk {} ct {} ss {}", + kat.algo.name(), + hex(&got[0]), + hex(&got[1]), + hex(&got[2]), + hex(&got[3]) + ); + } + } +}