• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2016 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 //! RSA key pairs.
16 
17 use super::{
18     super::{public, N},
19     Components,
20 };
21 use crate::{
22     arithmetic::{
23         bigint::{self, Prime},
24         montgomery::R,
25     },
26     bits,
27     error::{self, KeyRejected},
28 };
29 use core::convert::TryFrom;
30 
31 // Keep in sync with the documentation comment for `KeyPair`.
32 const PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS: bits::BitLength = bits::BitLength::from_usize_bits(4096);
33 
34 /// An RSA key pair.
35 pub struct RsaKeyPair {
36     p: PrivatePrime<P>,
37     q: PrivatePrime<Q>,
38     qInv: bigint::Elem<P, R>,
39     qq: bigint::Modulus<QQ>,
40     q_mod_n: bigint::Elem<N, R>,
41     public: public::Key,
42 }
43 
44 derive_debug_via_field!(RsaKeyPair, stringify!(RsaKeyPair), public);
45 
46 impl RsaKeyPair {
47     fn try_from_(
48         &Components {
49             public_key,
50             d,
51             p,
52             q,
53             dP,
54             dQ,
55             qInv,
56         }: &Components<&[u8]>,
57     ) -> Result<Self, KeyRejected> {
58         let d = untrusted::Input::from(d);
59         let p = untrusted::Input::from(p);
60         let q = untrusted::Input::from(q);
61         let dP = untrusted::Input::from(dP);
62         let dQ = untrusted::Input::from(dQ);
63         let qInv = untrusted::Input::from(qInv);
64 
65         let (p, p_bits) = bigint::Nonnegative::from_be_bytes_with_bit_length(p)
66             .map_err(|error::Unspecified| KeyRejected::invalid_encoding())?;
67         let (q, q_bits) = bigint::Nonnegative::from_be_bytes_with_bit_length(q)
68             .map_err(|error::Unspecified| KeyRejected::invalid_encoding())?;
69 
70         // Our implementation of CRT-based modular exponentiation used requires
71         // that `p > q` so swap them if `p < q`. If swapped, `qInv` is
72         // recalculated below. `p != q` is verified implicitly below, e.g. when
73         // `q_mod_p` is constructed.
74         let ((p, p_bits, dP), (q, q_bits, dQ, qInv)) = match q.verify_less_than(&p) {
75             Ok(_) => ((p, p_bits, dP), (q, q_bits, dQ, Some(qInv))),
76             Err(error::Unspecified) => {
77                 // TODO: verify `q` and `qInv` are inverses (mod p).
78                 ((q, q_bits, dQ), (p, p_bits, dP, None))
79             }
80         };
81 
82         // XXX: Some steps are done out of order, but the NIST steps are worded
83         // in such a way that it is clear that NIST intends for them to be done
84         // in order. TODO: Does this matter at all?
85 
86         // 6.4.1.4.3/6.4.1.2.1 - Step 1.
87 
88         // Step 1.a is omitted, as explained above.
89 
90         // Step 1.b is omitted per above. Instead, we check that the public
91         // modulus is 2048 to `PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS` bits.
92         // XXX: The maximum limit of 4096 bits is primarily due to lack of
93         // testing of larger key sizes; see, in particular,
94         // https://www.mail-archive.com/openssl-dev@openssl.org/msg44586.html
95         // and
96         // https://www.mail-archive.com/openssl-dev@openssl.org/msg44759.html.
97         // Also, this limit might help with memory management decisions later.
98 
99         // Step 1.c. We validate e >= 65537.
100         let public_key =
101             public::Key::from_modulus_and_exponent(public_key.n, public_key.e, &KeyPairBounds)?;
102 
103         // 6.4.1.4.3 says to skip 6.4.1.2.1 Step 2.
104 
105         // 6.4.1.4.3 Step 3.
106 
107         // Step 3.a is done below, out of order.
108         // Step 3.b is unneeded since `n_bits` is derived here from `n`.
109 
110         // 6.4.1.4.3 says to skip 6.4.1.2.1 Step 4. (We don't need to recover
111         // the prime factors since they are already given.)
112 
113         // 6.4.1.4.3 - Step 5.
114 
115         // Steps 5.a and 5.b are omitted, as explained above.
116 
117         // Step 5.c.
118         //
119         // TODO: First, stop if `p < (√2) * 2**((nBits/2) - 1)`.
120         //
121         // Second, stop if `p > 2**(nBits/2) - 1`.
122         let half_n_bits = public_key.n().len_bits().half_rounded_up();
123         if p_bits != half_n_bits {
124             return Err(KeyRejected::inconsistent_components());
125         }
126 
127         // TODO: Step 5.d: Verify GCD(p - 1, e) == 1.
128 
129         // Steps 5.e and 5.f are omitted as explained above.
130 
131         // Step 5.g.
132         //
133         // TODO: First, stop if `q < (√2) * 2**((nBits/2) - 1)`.
134         //
135         // Second, stop if `q > 2**(nBits/2) - 1`.
136         if p_bits != q_bits {
137             return Err(KeyRejected::inconsistent_components());
138         }
139 
140         // TODO: Step 5.h: Verify GCD(p - 1, e) == 1.
141 
142         let n = &public_key.n().value;
143 
144         let q_mod_n_decoded = q
145             .to_elem(n)
146             .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
147 
148         // TODO: Step 5.i
149         //
150         // 3.b is unneeded since `n_bits` is derived here from `n`.
151 
152         // 6.4.1.4.3 - Step 3.a (out of order).
153         //
154         // Verify that p * q == n. We restrict ourselves to modular
155         // multiplication. We rely on the fact that we've verified
156         // 0 < q < p < n. We check that q and p are close to sqrt(n) and then
157         // assume that these preconditions are enough to let us assume that
158         // checking p * q == 0 (mod n) is equivalent to checking p * q == n.
159         let q_mod_n = bigint::elem_mul(n.oneRR().as_ref(), q_mod_n_decoded.clone(), n);
160         let p_mod_n = p
161             .to_elem(n)
162             .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
163         let pq_mod_n = bigint::elem_mul(&q_mod_n, p_mod_n, n);
164         if !pq_mod_n.is_zero() {
165             return Err(KeyRejected::inconsistent_components());
166         }
167 
168         // 6.4.1.4.3/6.4.1.2.1 - Step 6.
169 
170         // Step 6.a, partial.
171         //
172         // First, validate `2**half_n_bits < d`. Since 2**half_n_bits has a bit
173         // length of half_n_bits + 1, this check gives us 2**half_n_bits <= d,
174         // and knowing d is odd makes the inequality strict.
175         let (d, d_bits) = bigint::Nonnegative::from_be_bytes_with_bit_length(d)
176             .map_err(|_| error::KeyRejected::invalid_encoding())?;
177         if !(half_n_bits < d_bits) {
178             return Err(KeyRejected::inconsistent_components());
179         }
180         // XXX: This check should be `d < LCM(p - 1, q - 1)`, but we don't have
181         // a good way of calculating LCM, so it is omitted, as explained above.
182         d.verify_less_than_modulus(n)
183             .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
184         if !d.is_odd() {
185             return Err(KeyRejected::invalid_component());
186         }
187 
188         // Step 6.b is omitted as explained above.
189 
190         // 6.4.1.4.3 - Step 7.
191 
192         // Step 7.a.
193         let p = PrivatePrime::new(p, dP)?;
194 
195         // Step 7.b.
196         let q = PrivatePrime::new(q, dQ)?;
197 
198         let q_mod_p = q.modulus.to_elem(&p.modulus);
199 
200         // Step 7.c.
201         let qInv = if let Some(qInv) = qInv {
202             bigint::Elem::from_be_bytes_padded(qInv, &p.modulus)
203                 .map_err(|error::Unspecified| KeyRejected::invalid_component())?
204         } else {
205             // We swapped `p` and `q` above, so we need to calculate `qInv`.
206             // Step 7.f below will verify `qInv` is correct.
207             let q_mod_p = bigint::elem_mul(p.modulus.oneRR().as_ref(), q_mod_p.clone(), &p.modulus);
208             bigint::elem_inverse_consttime(q_mod_p, &p.modulus)
209                 .map_err(|error::Unspecified| KeyRejected::unexpected_error())?
210         };
211 
212         // Steps 7.d and 7.e are omitted per the documentation above, and
213         // because we don't (in the long term) have a good way to do modulo
214         // with an even modulus.
215 
216         // Step 7.f.
217         let qInv = bigint::elem_mul(p.modulus.oneRR().as_ref(), qInv, &p.modulus);
218         bigint::verify_inverses_consttime(&qInv, q_mod_p, &p.modulus)
219             .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
220 
221         let qq = bigint::elem_mul(&q_mod_n, q_mod_n_decoded, n).into_modulus::<QQ>()?;
222 
223         Ok(Self {
224             p,
225             q,
226             qInv,
227             q_mod_n,
228             qq,
229             public: public_key,
230         })
231     }
232 
233     /// Returns a reference to the public key.
public(&self) -> &public::Key234     pub fn public(&self) -> &public::Key {
235         &self.public
236     }
237 }
238 
239 // TODO:
240 struct KeyPairBounds;
241 
242 impl crate::sealed::Sealed for KeyPairBounds {}
243 
244 impl super::super::Bounds for KeyPairBounds {
n_min_bits(&self) -> bits::BitLength245     fn n_min_bits(&self) -> bits::BitLength {
246         bits::BitLength::from_usize_bits(2048)
247     }
248 
n_max_bits(&self) -> bits::BitLength249     fn n_max_bits(&self) -> bits::BitLength {
250         PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS
251     }
252 
e_min_value(&self) -> u64253     fn e_min_value(&self) -> u64 {
254         65537
255     }
256 }
257 
258 impl<Public, Private> TryFrom<&Components<Public, Private>> for RsaKeyPair
259 where
260     Public: AsRef<[u8]> + core::fmt::Debug,
261     Private: AsRef<[u8]>,
262 {
263     type Error = KeyRejected;
264 
265     fn try_from(
266         Components {
267             public_key,
268             d,
269             p,
270             q,
271             dP,
272             dQ,
273             qInv,
274         }: &Components<Public, Private>,
275     ) -> Result<Self, Self::Error> {
276         let components = Components {
277             public_key: public::Components {
278                 n: public_key.n.as_ref(),
279                 e: public_key.e.as_ref(),
280             },
281             d: d.as_ref(),
282             p: p.as_ref(),
283             q: q.as_ref(),
284             dP: dP.as_ref(),
285             dQ: dQ.as_ref(),
286             qInv: qInv.as_ref(),
287         };
288         Self::try_from_(&components)
289     }
290 }
291 
292 struct PrivatePrime<M: Prime> {
293     modulus: bigint::Modulus<M>,
294     exponent: bigint::PrivateExponent<M>,
295 }
296 
297 impl<M: Prime + Clone> PrivatePrime<M> {
298     /// Constructs a `PrivatePrime` from the private prime `p` and `dP` where
299     /// dP == d % (p - 1).
new(p: bigint::Nonnegative, dP: untrusted::Input) -> Result<Self, KeyRejected>300     fn new(p: bigint::Nonnegative, dP: untrusted::Input) -> Result<Self, KeyRejected> {
301         let (p, p_bits) = bigint::Modulus::from_nonnegative_with_bit_length(p)?;
302         if p_bits.as_usize_bits() % 512 != 0 {
303             return Err(error::KeyRejected::private_modulus_len_not_multiple_of_512_bits());
304         }
305 
306         // [NIST SP-800-56B rev. 1] 6.4.1.4.3 - Steps 7.a & 7.b.
307         let dP = bigint::PrivateExponent::from_be_bytes_padded(dP, &p)
308             .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
309 
310         // XXX: Steps 7.d and 7.e are omitted. We don't check that
311         // `dP == d % (p - 1)` because we don't (in the long term) have a good
312         // way to do modulo with an even modulus. Instead we just check that
313         // `1 <= dP < p - 1`. We'll check it, to some unknown extent, when we
314         // do the private key operation, since we verify that the result of the
315         // private key operation using the CRT parameters is consistent with `n`
316         // and `e`. TODO: Either prove that what we do is sufficient, or make
317         // it so.
318 
319         Ok(PrivatePrime {
320             modulus: p,
321             exponent: dP,
322         })
323     }
324 }
325 
elem_exp_consttime<M, MM>( c: &bigint::Elem<MM>, p: &PrivatePrime<M>, ) -> Result<bigint::Elem<M>, error::Unspecified> where M: bigint::NotMuchSmallerModulus<MM>, M: Prime,326 fn elem_exp_consttime<M, MM>(
327     c: &bigint::Elem<MM>,
328     p: &PrivatePrime<M>,
329 ) -> Result<bigint::Elem<M>, error::Unspecified>
330 where
331     M: bigint::NotMuchSmallerModulus<MM>,
332     M: Prime,
333 {
334     let c_mod_m = bigint::elem_reduced(c, &p.modulus);
335     // We could precompute `oneRRR = elem_squared(&p.oneRR`) as mentioned
336     // in the Smooth CRT-RSA paper.
337     let c_mod_m = bigint::elem_mul(p.modulus.oneRR().as_ref(), c_mod_m, &p.modulus);
338     let c_mod_m = bigint::elem_mul(p.modulus.oneRR().as_ref(), c_mod_m, &p.modulus);
339     bigint::elem_exp_consttime(c_mod_m, &p.exponent, &p.modulus)
340 }
341 
342 // Type-level representations of the different moduli used in RSA signing, in
343 // addition to `super::N`. See `super::bigint`'s modulue-level documentation.
344 
345 #[derive(Copy, Clone)]
346 enum P {}
347 unsafe impl Prime for P {}
348 unsafe impl bigint::SmallerModulus<N> for P {}
349 unsafe impl bigint::NotMuchSmallerModulus<N> for P {}
350 
351 #[derive(Copy, Clone)]
352 enum QQ {}
353 unsafe impl bigint::SmallerModulus<N> for QQ {}
354 unsafe impl bigint::NotMuchSmallerModulus<N> for QQ {}
355 
356 // `q < p < 2*q` since `q` is slightly smaller than `p` (see below). Thus:
357 //
358 //                         q <  p  < 2*q
359 //                       q*q < p*q < 2*q*q.
360 //                      q**2 <  n  < 2*(q**2).
361 unsafe impl bigint::SlightlySmallerModulus<N> for QQ {}
362 
363 #[derive(Copy, Clone)]
364 enum Q {}
365 unsafe impl Prime for Q {}
366 unsafe impl bigint::SmallerModulus<N> for Q {}
367 unsafe impl bigint::SmallerModulus<P> for Q {}
368 
369 // q < p && `p.bit_length() == q.bit_length()` implies `q < p < 2*q`.
370 unsafe impl bigint::SlightlySmallerModulus<P> for Q {}
371 
372 unsafe impl bigint::SmallerModulus<QQ> for Q {}
373 unsafe impl bigint::NotMuchSmallerModulus<QQ> for Q {}
374 
375 impl RsaKeyPair {
rsa_private_in_place(&self, in_out: &mut [u8]) -> Result<(), error::Unspecified>376     pub(super) fn rsa_private_in_place(&self, in_out: &mut [u8]) -> Result<(), error::Unspecified> {
377         if in_out.len() != self.public.n().len_bits().as_usize_bytes_rounded_up() {
378             return Err(error::Unspecified);
379         }
380 
381         // RFC 8017 Section 5.1.2: RSADP, using the Chinese Remainder Theorem
382         // with Garner's algorithm.
383 
384         let n = &self.public.n().value;
385 
386         // Step 1. The value zero is also rejected.
387         let base = bigint::Elem::from_be_bytes_padded(untrusted::Input::from(in_out), n)?;
388 
389         // Step 2
390         let c = base;
391 
392         // Step 2.b.i.
393         let m_1 = elem_exp_consttime(&c, &self.p)?;
394         let c_mod_qq = bigint::elem_reduced_once(&c, &self.qq);
395         let m_2 = elem_exp_consttime(&c_mod_qq, &self.q)?;
396 
397         // Step 2.b.ii isn't needed since there are only two primes.
398 
399         // Step 2.b.iii.
400         let p = &self.p.modulus;
401         let m_2 = bigint::elem_widen(m_2, p);
402         let m_1_minus_m_2 = bigint::elem_sub(m_1, &m_2, p);
403         let h = bigint::elem_mul(&self.qInv, m_1_minus_m_2, p);
404 
405         // Step 2.b.iv. The reduction in the modular multiplication isn't
406         // necessary because `h < p` and `p * q == n` implies `h * q < n`.
407         // Modular arithmetic is used simply to avoid implementing
408         // non-modular arithmetic.
409         let h = bigint::elem_widen(h, n);
410         let q_times_h = bigint::elem_mul(&self.q_mod_n, h, n);
411         let m_2 = bigint::elem_widen(m_2, n);
412         let m = bigint::elem_add(m_2, q_times_h, n);
413 
414         // Step 2.b.v isn't needed since there are only two primes.
415 
416         // Verify the result to protect against fault attacks as described
417         // in "On the Importance of Checking Cryptographic Protocols for
418         // Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton.
419         // This check is cheap assuming `e` is small, which is ensured during
420         // `KeyPair` construction. Note that this is the only validation of `e`
421         // that is done other than basic checks on its size, oddness, and
422         // minimum value, since the relationship of `e` to `d`, `p`, and `q` is
423         // not verified during `KeyPair` construction.
424         {
425             let verify = bigint::elem_exp_vartime(m.clone(), self.public.e().0, n);
426             let verify = verify.into_unencoded(n);
427             bigint::elem_verify_equal_consttime(&verify, &c)?;
428         }
429 
430         // Step 3.
431         //
432         // See Falko Strenzke, "Manger's Attack revisited", ICICS 2010.
433         m.fill_be_bytes(in_out);
434 
435         Ok(())
436     }
437 
rsa_private<R>( &self, input: &[u8], f: impl FnOnce(&mut [u8]) -> Result<R, error::Unspecified>, ) -> Result<R, error::Unspecified>438     pub(super) fn rsa_private<R>(
439         &self,
440         input: &[u8],
441         f: impl FnOnce(&mut [u8]) -> Result<R, error::Unspecified>,
442     ) -> Result<R, error::Unspecified> {
443         let mut buffer = [0u8; PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS.as_usize_bytes_rounded_up()];
444         let buffer = buffer.get_mut(..input.len()).ok_or(error::Unspecified)?;
445         buffer.copy_from_slice(input);
446         self.rsa_private_in_place(buffer)?;
447         f(buffer)
448     }
449 }
450