diff --git a/boring-sys/build/main.rs b/boring-sys/build/main.rs index bab757f7d..e64923870 100644 --- a/boring-sys/build/main.rs +++ b/boring-sys/build/main.rs @@ -756,20 +756,26 @@ fn generate_bindings(config: &Config) { bindings .write(Box::new(&mut source_code)) .expect("Couldn't serialize bindings!"); + let mut source_code = String::from_utf8_lossy(&source_code).into_owned(); + + if !source_code.contains("MLKEM768_encap") { + // Fail at runtime to allow boring v5 to compile with mlkem disabled + source_code.push_str("\n#[cfg(not(feature = \"mlkem\"))] #[allow(deprecated)] pub use crate::mlkem_dummy::*;\n"); + } + ensure_err_lib_enum_is_named(&mut source_code); - fs::write(config.out_dir.join("bindings.rs"), source_code).expect("Couldn't write bindings!"); + fs::write(config.out_dir.join("bindings.rs"), source_code.as_bytes()) + .expect("Couldn't write bindings!"); } /// err.h has anonymous `enum { ERR_LIB_NONE = 1 }`, which makes a dodgy `_bindgen_ty_1` name -fn ensure_err_lib_enum_is_named(source_code: &mut Vec) { - let src = String::from_utf8_lossy(source_code); - let enum_type = src +fn ensure_err_lib_enum_is_named(source_code: &mut String) { + let enum_type = source_code .split_once("ERR_LIB_SSL:") .and_then(|(_, def)| Some(def.split_once('=')?.0)) .unwrap_or("_bindgen_ty_1"); - source_code.extend_from_slice( - format!("\n/// Newtype for [`ERR_LIB_SSL`] constants\npub use {enum_type} as ErrLib;\n") - .as_bytes(), - ); + let ty = + format!("\n/// Newtype for [`ERR_LIB_SSL`] constants\npub use {enum_type} as ErrLib;\n"); + source_code.push_str(&ty); } diff --git a/boring-sys/src/lib.rs b/boring-sys/src/lib.rs index 57ceffc76..a969b1051 100644 --- a/boring-sys/src/lib.rs +++ b/boring-sys/src/lib.rs @@ -15,6 +15,9 @@ use std::convert::TryInto; use std::ffi::c_void; use std::os::raw::{c_char, c_int, c_uint, c_ulong}; +#[cfg(not(feature = "mlkem"))] +mod mlkem_dummy; + #[allow( clippy::useless_transmute, clippy::derive_partial_eq_without_eq, diff --git a/boring-sys/src/mlkem_dummy.rs b/boring-sys/src/mlkem_dummy.rs new file mode 100644 index 000000000..cc6c88d1c --- /dev/null +++ b/boring-sys/src/mlkem_dummy.rs @@ -0,0 +1,163 @@ +#![allow(unused, deprecated)] + +use crate::{ERR_put_error, CBB, CBS, ERR_R_FATAL}; +use std::os::raw::c_int; +use std::process::abort; + +#[derive(Copy, Clone, Default)] +pub struct UnimplementedPlaceholder { + pub bytes: [u8; 0], +} + +#[derive(Copy, Clone, Default)] +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub struct MLKEM768_private_key { + pub opaque: UnimplementedPlaceholder, +} + +#[derive(Copy, Clone, Default)] +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub struct MLKEM768_public_key; +#[derive(Copy, Clone, Default)] +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub struct MLKEM1024_private_key { + pub opaque: UnimplementedPlaceholder, +} +#[derive(Copy, Clone, Default)] +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub struct MLKEM1024_public_key; + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub const MLKEM_SEED_BYTES: u32 = 0; +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub const MLKEM_SHARED_SECRET_BYTES: u32 = 0; +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub const MLKEM768_PUBLIC_KEY_BYTES: u32 = 0; +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub const MLKEM1024_PUBLIC_KEY_BYTES: u32 = 0; +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub const MLKEM768_CIPHERTEXT_BYTES: u32 = 0; +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub const MLKEM1024_CIPHERTEXT_BYTES: u32 = 0; + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C-unwind" fn MLKEM1024_generate_key( + _out_encoded_public_key: *mut u8, + _optional_out_seed: *mut u8, + _out_private_key: *mut MLKEM1024_private_key, +) { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM1024_private_key_from_seed( + _out_private_key: *mut MLKEM1024_private_key, + _seed: *const u8, + _seed_len: usize, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C-unwind" fn MLKEM1024_public_from_private( + _out_public_key: *mut MLKEM1024_public_key, + _private_key: *const MLKEM1024_private_key, +) { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C-unwind" fn MLKEM1024_encap( + _out_ciphertext: *mut u8, + _out_shared_secret: *mut u8, + _public_key: *const MLKEM1024_public_key, +) { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM1024_decap( + _out_shared_secret: *mut u8, + _ciphertext: *const u8, + _ciphertext_len: usize, + _private_key: *const MLKEM1024_private_key, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C-unwind" fn MLKEM768_generate_key( + _out_encoded_public_key: *mut u8, + _optional_out_seed: *mut u8, + _out_private_key: *mut MLKEM768_private_key, +) { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM768_private_key_from_seed( + _out_private_key: *mut MLKEM768_private_key, + _seed: *const u8, + _seed_len: usize, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C-unwind" fn MLKEM768_public_from_private( + _out_public_key: *mut MLKEM768_public_key, + _private_key: *const MLKEM768_private_key, +) { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C-unwind" fn MLKEM768_encap( + _out_ciphertext: *mut u8, + _out_shared_secret: *mut u8, + _public_key: *const MLKEM768_public_key, +) { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM768_decap( + _out_shared_secret: *mut u8, + _ciphertext: *const u8, + _ciphertext_len: usize, + _private_key: *const MLKEM768_private_key, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM768_marshal_public_key( + out: *mut CBB, + public_key: *const MLKEM768_public_key, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM768_parse_public_key( + out_public_key: *mut MLKEM768_public_key, + in_: *mut CBS, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM1024_marshal_public_key( + out: *mut CBB, + public_key: *const MLKEM1024_public_key, +) -> c_int { + abort(); +} + +#[deprecated(note = "mlkem.h was missing; this API won't work")] +pub unsafe extern "C" fn MLKEM1024_parse_public_key( + out_public_key: *mut MLKEM1024_public_key, + in_: *mut CBS, +) -> c_int { + abort(); +} diff --git a/boring/src/mlkem.rs b/boring/src/mlkem.rs index f5b84147e..fae453dc5 100644 --- a/boring/src/mlkem.rs +++ b/boring/src/mlkem.rs @@ -89,16 +89,17 @@ impl MlKemPrivateKey { /// /// The private key is a 64-byte seed. Keep it secret. pub fn generate(algorithm: Algorithm) -> Result<(MlKemPublicKey, MlKemPrivateKey), ErrorStack> { + mlkem_available()?; match algorithm { Algorithm::MlKem768 => { - let (pk, sk) = MlKem768PrivateKey::generate(); + let (pk, sk) = MlKem768PrivateKey::generate()?; Ok(( MlKemPublicKey(Either::MlKem768(pk)), MlKemPrivateKey(Either::MlKem768(sk)), )) } Algorithm::MlKem1024 => { - let (pk, sk) = MlKem1024PrivateKey::generate(); + let (pk, sk) = MlKem1024PrivateKey::generate()?; Ok(( MlKemPublicKey(Either::MlKem1024(pk)), MlKemPrivateKey(Either::MlKem1024(sk)), @@ -110,6 +111,7 @@ impl MlKemPrivateKey { impl MlKemPublicKey { pub fn from_slice(algorithm: Algorithm, public_key: &[u8]) -> Result { + mlkem_available()?; match algorithm { Algorithm::MlKem768 => Ok(Self(Either::MlKem768(Box::new( MlKem768PublicKey::from_slice(public_key)?, @@ -158,6 +160,7 @@ impl MlKemPrivateKey { algorithm: Algorithm, private_seed: &MlKemPrivateKeySeed, ) -> Result { + mlkem_available()?; match algorithm { Algorithm::MlKem768 => Ok(Self(Either::MlKem768(Box::new( MlKem768PrivateKey::from_seed(private_seed)?, @@ -222,39 +225,27 @@ impl MlKem768PrivateKey { pub const CIPHERTEXT_BYTES: usize = ffi::MLKEM768_CIPHERTEXT_BYTES as usize; /// Generate a new key pair. - #[must_use] - fn generate() -> (Box, Box) { + fn generate() -> Result<(Box, Box), ErrorStack> { // SAFETY: all buffers are out parameters, correctly sized unsafe { ffi::init(); - let mut public_key_bytes: MaybeUninit<[u8; MlKem768PublicKey::PUBLIC_KEY_BYTES]> = - MaybeUninit::uninit(); - let mut seed: MaybeUninit = MaybeUninit::uninit(); + let mut bytes = [0; MlKem768PublicKey::PUBLIC_KEY_BYTES]; + let mut seed = [0; PRIVATE_KEY_SEED_BYTES]; let mut expanded: MaybeUninit = MaybeUninit::uninit(); ffi::MLKEM768_generate_key( - public_key_bytes.as_mut_ptr().cast(), - seed.as_mut_ptr().cast(), + bytes.as_mut_ptr().cast(), + seed.as_mut_ptr(), expanded.as_mut_ptr(), ); - let bytes = public_key_bytes.assume_init(); - - // Parse the public key bytes to get the parsed struct - let mut cbs = cbs_init(&bytes); - let mut parsed: MaybeUninit = MaybeUninit::uninit(); - ffi::MLKEM768_parse_public_key(parsed.as_mut_ptr(), &mut cbs); - - ( - Box::new(MlKem768PublicKey { - bytes, - parsed: parsed.assume_init(), - }), + Ok(( + Box::new(MlKem768PublicKey::from_slice(&bytes)?), Box::new(MlKem768PrivateKey { - seed: seed.assume_init(), + seed, expanded: expanded.assume_init(), }), - ) + )) } } @@ -439,39 +430,27 @@ impl MlKem1024PrivateKey { pub const CIPHERTEXT_BYTES: usize = ffi::MLKEM1024_CIPHERTEXT_BYTES as usize; /// Generate a new key pair. - #[must_use] - fn generate() -> (Box, Box) { + fn generate() -> Result<(Box, Box), ErrorStack> { // SAFETY: all buffers are out parameters, correctly sized unsafe { ffi::init(); - let mut public_key_bytes: MaybeUninit<[u8; MlKem1024PublicKey::PUBLIC_KEY_BYTES]> = - MaybeUninit::uninit(); - let mut seed: MaybeUninit = MaybeUninit::uninit(); + let mut bytes = [0; MlKem1024PublicKey::PUBLIC_KEY_BYTES]; + let mut seed = [0; PRIVATE_KEY_SEED_BYTES]; let mut expanded: MaybeUninit = MaybeUninit::uninit(); ffi::MLKEM1024_generate_key( - public_key_bytes.as_mut_ptr().cast(), - seed.as_mut_ptr().cast(), + bytes.as_mut_ptr().cast(), + seed.as_mut_ptr(), expanded.as_mut_ptr(), ); - let bytes = public_key_bytes.assume_init(); - - // Parse the public key bytes to get the parsed struct - let mut cbs = cbs_init(&bytes); - let mut parsed: MaybeUninit = MaybeUninit::uninit(); - ffi::MLKEM1024_parse_public_key(parsed.as_mut_ptr(), &mut cbs); - - ( - Box::new(MlKem1024PublicKey { - bytes, - parsed: parsed.assume_init(), - }), + Ok(( + Box::new(MlKem1024PublicKey::from_slice(&bytes)?), Box::new(MlKem1024PrivateKey { - seed: seed.assume_init(), + seed, expanded: expanded.assume_init(), }), - ) + )) } } @@ -638,6 +617,15 @@ impl fmt::Debug for MlKem1024PublicKey { } } +fn mlkem_available() -> Result<(), ErrorStack> { + if SHARED_SECRET_BYTES != 32 || PRIVATE_KEY_SEED_BYTES != 64 { + return Err(ErrorStack::internal_error_str( + "ML-KEM is unavailable in this build", + )); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -649,7 +637,7 @@ mod tests { #[test] fn roundtrip() { - let (pk, sk) = <$priv>::generate(); + let (pk, sk) = <$priv>::generate().unwrap(); let (ct, ss1) = pk.encapsulate(); let ss2 = sk.decapsulate(&ct); assert_eq!(ss1, ss2); @@ -657,7 +645,7 @@ mod tests { #[test] fn seed_roundtrip() { - let (pk, sk) = <$priv>::generate(); + let (pk, sk) = <$priv>::generate().unwrap(); let sk2 = <$priv>::from_seed(&sk.seed).unwrap(); let (ct, ss1) = pk.encapsulate(); let ss2 = sk2.decapsulate(&ct); @@ -666,7 +654,7 @@ mod tests { #[test] fn derive_pubkey() { - let (pk, sk) = <$priv>::generate(); + let (pk, sk) = <$priv>::generate().unwrap(); assert_eq!(pk.bytes, sk.public_key().unwrap().bytes); } @@ -678,14 +666,14 @@ mod tests { #[test] fn from_slice_roundtrip() { - let (pk, _) = <$priv>::generate(); + let (pk, _) = <$priv>::generate().unwrap(); let pk2 = <$pub>::from_slice(&pk.bytes).unwrap(); assert_eq!(pk.bytes, pk2.bytes); } #[test] fn implicit_rejection() { - let (_, sk) = <$priv>::generate(); + let (_, sk) = <$priv>::generate().unwrap(); let bad_ct = [0x42u8; $ct_len]; // bad ciphertext still "works", just returns deterministic garbage let ss1 = sk.decapsulate(&bad_ct); @@ -695,7 +683,7 @@ mod tests { #[test] fn debug_redacts_seed() { - let (_, sk) = <$priv>::generate(); + let (_, sk) = <$priv>::generate().unwrap(); let dbg = format!("{:?}", sk); assert!(dbg.contains("redacted")); }