diff --git a/src/private_key.rs b/src/private_key.rs index d0252180..40a40d09 100644 --- a/src/private_key.rs +++ b/src/private_key.rs @@ -244,6 +244,15 @@ impl PrivateKey { let n_bits = n.bit_width_vartime(); let n = n.resize_unchecked(n_bits); + // Bound the modulus size before any heavy bigint work below (Montgomery setup and the + // O(bits^2) prime product), mirroring the public-key path, where `PublicKey::new` rejects a + // modulus over `MAX_SIZE`. Without this, `from_components` on an attacker-sized modulus runs + // that work before validation can reject it. #793 applies the same bound at the PKCS#1 + // decode layer; this covers the direct component-construction API too. + if n_bits as usize > PublicKey::MAX_SIZE { + return Err(Error::ModulusTooLarge); + } + // Use a public storage width even when the caller supplies a short or zero-padded `d`. // Check for truncation before resizing so an oversized exponent cannot become valid. let d = d @@ -772,6 +781,19 @@ mod tests { use crate::algorithms::rsa::{rsa_decrypt_and_check, rsa_encrypt}; use crate::traits::{PrivateKeyParts, PublicKeyParts}; + #[test] + fn from_components_rejects_oversized_modulus() { + // A modulus above `PublicKey::MAX_SIZE` must be rejected before the heavy Montgomery setup + // and O(bits^2) product run (DoS guard), rather than accepted or executed. + let n = BoxedUint::max(9000); + let e = BoxedUint::from(65537u64); + let d = BoxedUint::from(3u64); + let p = BoxedUint::from(3u64); + let q = BoxedUint::from(5u64); + let err = PrivateKey::from_components(n, e, d, vec![p, q]).unwrap_err(); + assert!(matches!(err, Error::ModulusTooLarge)); + } + use hex_literal::hex; use rand::rngs::ChaCha8Rng; use rand_core::SeedableRng;