From cb3e4f2c004c89a0c83ec9b6a7a2d5d7c8127b34 Mon Sep 17 00:00:00 2001 From: Portll Date: Thu, 3 Dec 2026 23:14:20 +1030 Subject: [PATCH] Cap modulus size on private-key component construction 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; the private component-construction API applied no such bound, letting from_components 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_inner, before the heavy path. #793 applies the same bound at the PKCS#1 decode layer; this covers the direct component-construction API (from_components / _with_large_exponent / _with_wide_primes) too. --- src/private_key.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) 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;