From b96488fa45fe55c2d3a50cecbf57838386ac7a6c Mon Sep 17 00:00:00 2001 From: Portll Date: Thu, 3 Dec 2026 23:14:20 +1030 Subject: [PATCH] Cap modulus size in PrivateKey::from_components from_components_inner builds Montgomery parameters and (for the 2-prime case) an O(bits^2) product of the supplied primes before any validation runs. On the public-key path PublicKey::new rejects a modulus over MAX_SIZE first, so that heavy work is bounded; from_components applied no such bound, letting it run seconds of CPU on an attacker-sized modulus before rejecting it (CPU-exhaustion DoS on untrusted private-key import). Reject n over PublicKey::MAX_SIZE in from_components, before the heavy path. #793 applies the same bound at the PKCS#1 decode layer, which goes through from_components; this also covers direct calls. Keys larger than MAX_SIZE remain supported where the caller opts in or chose the size: from_components_with_wide_primes and the hazmat from_components_with_large_exponent are unbounded, and key generation (PrivateKey::new and friends) skips the import limit. --- src/private_key.rs | 50 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/src/private_key.rs b/src/private_key.rs index d0252180..192a3b6d 100644 --- a/src/private_key.rs +++ b/src/private_key.rs @@ -187,7 +187,7 @@ impl PrivateKey { } let components = generate_multi_prime_key_with_exp(rng, 2, bit_size, exp)?; - PrivateKey::from_components( + PrivateKey::from_generated_components( components.n.get(), components.e, components.d, @@ -213,7 +213,7 @@ impl PrivateKey { exp: BoxedUint, ) -> Result { let components = generate_multi_prime_key_with_exp(rng, 2, bit_size, exp)?; - PrivateKey::from_components( + PrivateKey::from_generated_components( components.n.get(), components.e, components.d, @@ -236,6 +236,7 @@ impl PrivateKey { d: BoxedUint, mut primes: Vec, wide_primes: bool, + max_modulus_bits: Option, ) -> Result { let n = Odd::new(n).into_option().ok_or(Error::InvalidModulus)?; @@ -244,6 +245,12 @@ impl PrivateKey { let n_bits = n.bit_width_vartime(); let n = n.resize_unchecked(n_bits); + // Reject before the Montgomery setup and O(bits^2) prime product below, which would + // otherwise run on an attacker-sized modulus before validation can reject it. + if max_modulus_bits.is_some_and(|max| n_bits as usize > max) { + 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 @@ -341,7 +348,7 @@ impl PrivateKey { d: BoxedUint, primes: Vec, ) -> Result { - let mut k = Self::from_components_inner(n, e, d, primes, false)?; + let mut k = Self::from_components_inner(n, e, d, primes, false, None)?; // Validate everything except exponent size bounds. validate_skip_exponent_size(&k)?; @@ -367,6 +374,10 @@ impl PrivateKey { /// Use [`Self::from_components_with_wide_primes`] to explicitly import unbalanced factors. /// Multiprime keys use modulus-width factors and the non-CRT private operation. /// + /// The modulus may be at most [`PublicKey::MAX_SIZE`] bits; larger moduli are rejected with + /// [`Error::ModulusTooLarge`] before any expensive arithmetic. To import a larger key, use + /// [`Self::from_components_with_wide_primes`]. + /// /// [NIST SP 800-56B Revision 2]: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf #[allow(clippy::missing_errors_doc, reason = "TODO")] pub fn from_components( @@ -375,7 +386,21 @@ impl PrivateKey { d: BoxedUint, primes: Vec, ) -> Result { - let mut k = Self::from_components_inner(n, e, d, primes, false)?; + let mut k = Self::from_components_inner(n, e, d, primes, false, Some(PublicKey::MAX_SIZE))?; + k.validate()?; + k.precompute()?; + Ok(k) + } + + /// Generated keys come from a caller-chosen `bit_size`, not untrusted input, so they are not + /// subject to the [`PublicKey::MAX_SIZE`] import limit. + fn from_generated_components( + n: BoxedUint, + e: BoxedUint, + d: BoxedUint, + primes: Vec, + ) -> Result { + let mut k = Self::from_components_inner(n, e, d, primes, false, None)?; k.validate()?; k.precompute()?; Ok(k) @@ -397,7 +422,7 @@ impl PrivateKey { d: BoxedUint, primes: Vec, ) -> Result { - let mut k = Self::from_components_inner(n, e, d, primes, true)?; + let mut k = Self::from_components_inner(n, e, d, primes, true, None)?; k.validate()?; k.precompute()?; Ok(k) @@ -772,6 +797,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; @@ -794,6 +832,7 @@ mod tests { d.clone(), primes.clone(), false, + None, ) .unwrap(); key.validate().unwrap(); @@ -853,6 +892,7 @@ mod tests { d.clone(), primes.clone(), false, + None, ) .unwrap(); assert_eq!(key.validate(), Err(Error::InvalidPrime));