Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 45 additions & 5 deletions src/private_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -213,7 +213,7 @@ impl PrivateKey {
exp: BoxedUint,
) -> Result<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,
Expand All @@ -236,6 +236,7 @@ impl PrivateKey {
d: BoxedUint,
mut primes: Vec<BoxedUint>,
wide_primes: bool,
max_modulus_bits: Option<usize>,
) -> Result<PrivateKey> {
let n = Odd::new(n).into_option().ok_or(Error::InvalidModulus)?;

Expand All @@ -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
Expand Down Expand Up @@ -341,7 +348,7 @@ impl PrivateKey {
d: BoxedUint,
primes: Vec<BoxedUint>,
) -> Result<PrivateKey> {
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)?;
Expand All @@ -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(
Expand All @@ -375,7 +386,21 @@ impl PrivateKey {
d: BoxedUint,
primes: Vec<BoxedUint>,
) -> Result<PrivateKey> {
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<BoxedUint>,
) -> Result<PrivateKey> {
let mut k = Self::from_components_inner(n, e, d, primes, false, None)?;
k.validate()?;
k.precompute()?;
Ok(k)
Expand All @@ -397,7 +422,7 @@ impl PrivateKey {
d: BoxedUint,
primes: Vec<BoxedUint>,
) -> Result<PrivateKey> {
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)
Expand Down Expand Up @@ -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;
Expand All @@ -794,6 +832,7 @@ mod tests {
d.clone(),
primes.clone(),
false,
None,
)
.unwrap();
key.validate().unwrap();
Expand Down Expand Up @@ -853,6 +892,7 @@ mod tests {
d.clone(),
primes.clone(),
false,
None,
)
.unwrap();
assert_eq!(key.validate(), Err(Error::InvalidPrime));
Expand Down