diff --git a/Cargo.lock b/Cargo.lock index e6790f8..1ef2c9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -303,6 +303,7 @@ dependencies = [ "blake2 0.11.0", "ccc-crypto-core", "chacha20poly1305", + "classic-mceliece-rust", "getrandom", "hex", "hkdf", @@ -310,8 +311,9 @@ dependencies = [ "log", "ml-kem", "poly1305", + "rand_core 0.6.4", "sha2", - "sha3", + "sha3 0.12.0", "subtle", "x-wing", "x25519-dalek", @@ -394,6 +396,17 @@ dependencies = [ "libloading", ] +[[package]] +name = "classic-mceliece-rust" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62a9b6d27e553269a76625911aa8cf6afaa8659f1b0c85b410cb5f51a87183d9" +dependencies = [ + "rand", + "sha3 0.10.9", + "zeroize", +] + [[package]] name = "cmake" version = "0.1.57" @@ -661,7 +674,7 @@ dependencies = [ "ml-kem", "rand_core 0.10.1", "sha2", - "sha3", + "sha3 0.12.0", "shake", "subtle", "turboshake", @@ -735,6 +748,15 @@ dependencies = [ "syn", ] +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures 0.2.17", +] + [[package]] name = "keccak" version = "0.2.2" @@ -800,7 +822,7 @@ dependencies = [ "module-lattice", "pkcs8", "rand_core 0.10.1", - "sha3", + "sha3 0.12.0", "shake", "zeroize", ] @@ -959,6 +981,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -1075,6 +1106,16 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest 0.10.7", + "keccak 0.1.6", +] + [[package]] name = "sha3" version = "0.12.0" @@ -1082,7 +1123,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759" dependencies = [ "digest 0.11.3", - "keccak", + "keccak 0.2.2", "sponge-cursor", ] @@ -1093,7 +1134,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a" dependencies = [ "digest 0.11.3", - "keccak", + "keccak 0.2.2", "sponge-cursor", ] @@ -1166,7 +1207,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f892c6904b0bd5a9241eac848347abcbbbd2b9f3892bad23ac3e6efab8d6f06a" dependencies = [ "digest 0.11.3", - "keccak", + "keccak 0.2.2", "sponge-cursor", ] @@ -1227,7 +1268,7 @@ checksum = "01576e56599d01d75c5efcd5b30fa5de29e776f5a225e43fbf8c92c7302d4c8b" dependencies = [ "kem", "ml-kem", - "sha3", + "sha3 0.12.0", "shake", "x25519-dalek", "zeroize", diff --git a/Cargo.toml b/Cargo.toml index 6bd5daf..c8ddd20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,3 +31,8 @@ ccc-crypto-core = { path = "crates/ccc-crypto-core" } ccc-cascade = { path = "crates/ccc-cascade" } ccc-crypto-rustcrypto = { path = "crates/ccc-crypto-rustcrypto" } + +# Classic McEliece key generation is about 100x slower unoptimised; keep +# debug builds and the provider self-test usable. +[profile.dev.package.classic-mceliece-rust] +opt-level = 3 diff --git a/crates/ccc-crypto-rustcrypto/Cargo.toml b/crates/ccc-crypto-rustcrypto/Cargo.toml index 5198440..3fc29ba 100644 --- a/crates/ccc-crypto-rustcrypto/Cargo.toml +++ b/crates/ccc-crypto-rustcrypto/Cargo.toml @@ -38,6 +38,17 @@ ml-kem = { version = "0.3", features = ["hazmat", "zeroize"] } # X-Wing draft-connolly-cfrg-xwing-kem-06 (ML-KEM-768 + X25519). x-wing = { version = "0.1", features = ["hazmat", "zeroize"] } getrandom = "0.4" +# Classic McEliece 460896f (Ultra U2), the version the R0-6 spike measured. +# Keep its default features: without "zeroize" the crate does not build. +classic-mceliece-rust = { version = "3.1.0", features = ["mceliece460896f"], optional = true } +# classic-mceliece-rust takes rand_core 0.6 RNGs. +rand_core = { version = "0.6", optional = true } + +[features] +default = ["mceliece"] +# Classic McEliece 460896f. The crate builds one parameter set per build, +# so nothing else in the dependency graph may pick another one. +mceliece = ["dep:classic-mceliece-rust", "dep:rand_core"] [dev-dependencies] hex = "0.4" diff --git a/crates/ccc-crypto-rustcrypto/src/kem.rs b/crates/ccc-crypto-rustcrypto/src/kem.rs index 1e14039..d51f666 100644 --- a/crates/ccc-crypto-rustcrypto/src/kem.rs +++ b/crates/ccc-crypto-rustcrypto/src/kem.rs @@ -15,7 +15,9 @@ //! the raw RFC 7748 shared value. An all-zero shared value (a low-order //! peer point) is rejected. //! -//! X448 and Classic McEliece are not offered by this provider. +//! Classic McEliece 460896f (`mceliece` feature, on by default) lives in +//! [`crate::mceliece`]. X448 and Classic McEliece 460896 (non-"f") are not +//! offered by this provider. use ml_kem::array::Array; use ml_kem::kem::{Decapsulate, KeyExport, TryKeyInit}; @@ -48,9 +50,11 @@ pub fn generate_keypair(algo: KemAlgorithm) -> Result { private_key: seed.to_vec(), }) } - KemAlgorithm::X448 - | KemAlgorithm::ClassicMcEliece460896 - | KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo), + #[cfg(feature = "mceliece")] + KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::generate(), + #[cfg(not(feature = "mceliece"))] + KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo), + KemAlgorithm::X448 | KemAlgorithm::ClassicMcEliece460896 => not_compiled(algo), } } @@ -64,9 +68,11 @@ pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result mlkem768::encapsulate_deterministic(public_key, &*random()?), KemAlgorithm::MlKem1024 => mlkem1024::encapsulate_deterministic(public_key, &*random()?), KemAlgorithm::XWing => xwing_encapsulate_deterministic(public_key, &*random()?), - KemAlgorithm::X448 - | KemAlgorithm::ClassicMcEliece460896 - | KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo), + #[cfg(feature = "mceliece")] + KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::encapsulate(public_key), + #[cfg(not(feature = "mceliece"))] + KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo), + KemAlgorithm::X448 | KemAlgorithm::ClassicMcEliece460896 => not_compiled(algo), } } @@ -81,9 +87,11 @@ pub fn decapsulate( KemAlgorithm::MlKem768 => mlkem768::decapsulate(private_key, ciphertext), KemAlgorithm::MlKem1024 => mlkem1024::decapsulate(private_key, ciphertext), KemAlgorithm::XWing => xwing_decapsulate(private_key, ciphertext), - KemAlgorithm::X448 - | KemAlgorithm::ClassicMcEliece460896 - | KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo), + #[cfg(feature = "mceliece")] + KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::decapsulate(private_key, ciphertext), + #[cfg(not(feature = "mceliece"))] + KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo), + KemAlgorithm::X448 | KemAlgorithm::ClassicMcEliece460896 => not_compiled(algo), } } @@ -334,7 +342,12 @@ mod tests { #[test] fn unsupported_kems() { - for algo in [KemAlgorithm::X448, KemAlgorithm::ClassicMcEliece460896] { + for algo in [ + KemAlgorithm::X448, + KemAlgorithm::ClassicMcEliece460896, + #[cfg(not(feature = "mceliece"))] + KemAlgorithm::ClassicMcEliece460896f, + ] { assert!(matches!( generate_keypair(algo), Err(CryptoError::FeatureNotCompiled(_)) diff --git a/crates/ccc-crypto-rustcrypto/src/lib.rs b/crates/ccc-crypto-rustcrypto/src/lib.rs index 034e727..58a86d1 100644 --- a/crates/ccc-crypto-rustcrypto/src/lib.rs +++ b/crates/ccc-crypto-rustcrypto/src/lib.rs @@ -16,6 +16,8 @@ pub mod hash; pub mod kdf; pub mod kem; pub mod mac; +#[cfg(feature = "mceliece")] +pub mod mceliece; pub mod provider; pub mod self_test; diff --git a/crates/ccc-crypto-rustcrypto/src/mceliece.rs b/crates/ccc-crypto-rustcrypto/src/mceliece.rs new file mode 100644 index 0000000..4c62ac9 --- /dev/null +++ b/crates/ccc-crypto-rustcrypto/src/mceliece.rs @@ -0,0 +1,201 @@ +//! Classic McEliece 460896f (`classic-mceliece-rust`, pure Rust), the Ultra +//! conservative KEM layer (U2). Built with the `mceliece` feature. +//! +//! | Private key | Public key | Ciphertext | Secret | +//! |-------------|------------|------------|--------| +//! | 13,608 | 524,160 | 156 | 32 | +//! +//! Keys use the NIST round-4 byte format, so they interoperate with liboqs +//! (`Classic-McEliece-460896f`); the `ccc-crypto-oqs` tests check this both +//! ways. +//! +//! The reference code keeps large matrices on the stack. Every operation +//! runs on a scoped worker thread with [`STACK_SIZE`] bytes of stack, so a +//! caller on a small thread (an iOS secondary thread has 512 KiB, a debug +//! build needs much more than a release one) never overflows. Keys and +//! ciphertexts are copied to the heap, never to the worker's stack. + +use rand_core::{CryptoRng, RngCore}; +use zeroize::Zeroizing; + +use classic_mceliece_rust as cm; +use ccc_crypto_core::{ + error::CryptoError, + types::{KemEncapResult, KemKeyPair}, +}; + +/// Public key length in bytes. +pub const PUBLIC_KEY_LEN: usize = cm::CRYPTO_PUBLICKEYBYTES; +/// Private key length in bytes. +pub const PRIVATE_KEY_LEN: usize = cm::CRYPTO_SECRETKEYBYTES; +/// Ciphertext length in bytes. +pub const CIPHERTEXT_LEN: usize = cm::CRYPTO_CIPHERTEXTBYTES; + +/// Worker stack size. The R0-6 spike ran a release build on 256 KiB; the +/// margin covers unoptimised builds. +pub const STACK_SIZE: usize = 8 * 1024 * 1024; + +const _: () = assert!(PUBLIC_KEY_LEN == 524_160 && CIPHERTEXT_LEN == 156); + +/// Run `f` on a worker thread with a [`STACK_SIZE`] stack and wait for it. +fn on_big_stack(f: impl FnOnce() -> T + Send) -> Result { + std::thread::scope(|s| { + std::thread::Builder::new() + .name("ccc-mceliece".into()) + .stack_size(STACK_SIZE) + .spawn_scoped(s, f) + .map_err(|e| CryptoError::InternalError(format!("McEliece worker: {e}")))? + .join() + .map_err(|_| CryptoError::InternalError("McEliece worker panicked".into())) + }) +} + +/// The OS RNG (`getrandom`) behind the `rand_core` 0.6 traits the crate +/// expects. A failing OS RNG panics inside the worker, which surfaces as an +/// `InternalError`, never as a key made from bad randomness. +struct OsRng; + +impl RngCore for OsRng { + fn next_u32(&mut self) -> u32 { + rand_core::impls::next_u32_via_fill(self) + } + + fn next_u64(&mut self) -> u64 { + rand_core::impls::next_u64_via_fill(self) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + getrandom::fill(dest).expect("getrandom failed"); + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { + self.fill_bytes(dest); + Ok(()) + } +} + +impl CryptoRng for OsRng {} + +fn boxed(bytes: &[u8], what: &str) -> Result, CryptoError> { + if bytes.len() != N { + return Err(CryptoError::InvalidKey(format!( + "Classic-McEliece-460896f: {what} must be {N} bytes" + ))); + } + bytes + .to_vec() + .into_boxed_slice() + .try_into() + .map_err(|_| CryptoError::InternalError("length checked above".into())) +} + +/// Generate a key pair from `rng` (the OS RNG, or a seeded one for KATs). +pub(crate) fn generate_with( + rng: &mut R, +) -> Result { + on_big_stack(|| { + let (pk, sk) = cm::keypair_boxed(rng); + KemKeyPair { + public_key: pk.as_array().to_vec(), + private_key: sk.as_array().to_vec(), + } + }) +} + +/// Encapsulate to `public_key` with randomness from `rng`. +pub(crate) fn encapsulate_with( + public_key: &[u8], + rng: &mut R, +) -> Result { + let pk = cm::PublicKey::from(boxed::(public_key, "public key")?); + on_big_stack(|| { + let (ct, ss) = cm::encapsulate_boxed(&pk, rng); + KemEncapResult { + ciphertext: ct.as_array().to_vec(), + shared_secret: ss.as_array().to_vec(), + } + }) +} + +/// Generate a key pair with the OS RNG. +pub fn generate() -> Result { + generate_with(&mut OsRng) +} + +/// Encapsulate a fresh secret to `public_key`. +pub fn encapsulate(public_key: &[u8]) -> Result { + encapsulate_with(public_key, &mut OsRng) +} + +/// Recover the secret from `ciphertext`. A modified ciphertext yields a +/// pseudo-random secret (implicit rejection), not an error. +pub fn decapsulate( + private_key: &[u8], + ciphertext: &[u8], +) -> Result>, CryptoError> { + let sk = cm::SecretKey::from(boxed::(private_key, "private key")?); + let ct: [u8; CIPHERTEXT_LEN] = ciphertext.try_into().map_err(|_| { + CryptoError::InvalidInput("Classic-McEliece-460896f: wrong ciphertext length".into()) + })?; + let ct = cm::Ciphertext::from(ct); + on_big_stack(|| Zeroizing::new(cm::decapsulate_boxed(&ct, &sk).as_array().to_vec())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + #[test] + fn roundtrip_sizes_and_timings() { + let t = Instant::now(); + let kp = generate().unwrap(); + let keygen = t.elapsed(); + let t = Instant::now(); + let enc = encapsulate(&kp.public_key).unwrap(); + let encap = t.elapsed(); + let t = Instant::now(); + let ss = decapsulate(&kp.private_key, &enc.ciphertext).unwrap(); + let decap = t.elapsed(); + assert_eq!(*ss, enc.shared_secret); + assert_eq!(kp.public_key.len(), 524_160); + assert_eq!(kp.private_key.len(), 13_608); + assert_eq!(enc.ciphertext.len(), 156); + assert_eq!(ss.len(), 32); + println!( + "Classic-McEliece-460896f: pk {} sk {} ct {}; keygen {keygen:?} encap {encap:?} \ + decap {decap:?}", + kp.public_key.len(), + kp.private_key.len(), + enc.ciphertext.len() + ); + } + + #[test] + fn runs_from_a_small_caller_stack() { + // A 128 KiB caller thread is far below what keygen needs. + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(|| { + let kp = generate().unwrap(); + let enc = encapsulate(&kp.public_key).unwrap(); + let ss = decapsulate(&kp.private_key, &enc.ciphertext).unwrap(); + assert_eq!(*ss, enc.shared_secret); + }) + .unwrap() + .join() + .unwrap(); + } + + #[test] + fn implicit_rejection_and_lengths() { + let kp = generate().unwrap(); + let enc = encapsulate(&kp.public_key).unwrap(); + let mut ct = enc.ciphertext.clone(); + ct[0] ^= 1; + assert_ne!(*decapsulate(&kp.private_key, &ct).unwrap(), enc.shared_secret); + assert!(encapsulate(&kp.public_key[1..]).is_err()); + assert!(decapsulate(&kp.private_key[1..], &enc.ciphertext).is_err()); + assert!(decapsulate(&kp.private_key, &enc.ciphertext[1..]).is_err()); + } +}