xref: /aosp_15_r20/external/boringssl/src/crypto/fipsmodule/rsa/rsa_impl.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson ([email protected]).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young ([email protected])"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson ([email protected])"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <openssl/rsa.h>
58 
59 #include <assert.h>
60 #include <limits.h>
61 #include <string.h>
62 
63 #include <openssl/bn.h>
64 #include <openssl/err.h>
65 #include <openssl/mem.h>
66 #include <openssl/thread.h>
67 
68 #include "../../internal.h"
69 #include "../bn/internal.h"
70 #include "../delocate.h"
71 #include "../rand/fork_detect.h"
72 #include "../service_indicator/internal.h"
73 #include "internal.h"
74 
75 
rsa_check_public_key(const RSA * rsa)76 int rsa_check_public_key(const RSA *rsa) {
77   if (rsa->n == NULL) {
78     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
79     return 0;
80   }
81 
82   // TODO(davidben): 16384-bit RSA is huge. Can we bring this down to a limit of
83   // 8192-bit?
84   unsigned n_bits = BN_num_bits(rsa->n);
85   if (n_bits > 16 * 1024) {
86     OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE);
87     return 0;
88   }
89 
90   // TODO(crbug.com/boringssl/607): Raise this limit. 512-bit RSA was factored
91   // in 1999.
92   if (n_bits < 512) {
93     OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
94     return 0;
95   }
96 
97   // RSA moduli must be positive and odd. In addition to being necessary for RSA
98   // in general, we cannot setup Montgomery reduction with even moduli.
99   if (!BN_is_odd(rsa->n) || BN_is_negative(rsa->n)) {
100     OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS);
101     return 0;
102   }
103 
104   static const unsigned kMaxExponentBits = 33;
105   if (rsa->e != NULL) {
106     // Reject e = 1, negative e, and even e. e must be odd to be relatively
107     // prime with phi(n).
108     unsigned e_bits = BN_num_bits(rsa->e);
109     if (e_bits < 2 || BN_is_negative(rsa->e) || !BN_is_odd(rsa->e)) {
110       OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
111       return 0;
112     }
113     if (rsa->flags & RSA_FLAG_LARGE_PUBLIC_EXPONENT) {
114       // The caller has requested disabling DoS protections. Still, e must be
115       // less than n.
116       if (BN_ucmp(rsa->n, rsa->e) <= 0) {
117         OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
118         return 0;
119       }
120     } else {
121       // Mitigate DoS attacks by limiting the exponent size. 33 bits was chosen
122       // as the limit based on the recommendations in [1] and [2]. Windows
123       // CryptoAPI doesn't support values larger than 32 bits [3], so it is
124       // unlikely that exponents larger than 32 bits are being used for anything
125       // Windows commonly does.
126       //
127       // [1] https://www.imperialviolet.org/2012/03/16/rsae.html
128       // [2] https://www.imperialviolet.org/2012/03/17/rsados.html
129       // [3] https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx
130       if (e_bits > kMaxExponentBits) {
131         OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
132         return 0;
133       }
134 
135       // The upper bound on |e_bits| and lower bound on |n_bits| imply e is
136       // bounded by n.
137       assert(BN_ucmp(rsa->n, rsa->e) > 0);
138     }
139   } else if (!(rsa->flags & RSA_FLAG_NO_PUBLIC_EXPONENT)) {
140     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
141     return 0;
142   }
143 
144   return 1;
145 }
146 
ensure_fixed_copy(BIGNUM ** out,const BIGNUM * in,int width)147 static int ensure_fixed_copy(BIGNUM **out, const BIGNUM *in, int width) {
148   if (*out != NULL) {
149     return 1;
150   }
151   BIGNUM *copy = BN_dup(in);
152   if (copy == NULL ||
153       !bn_resize_words(copy, width)) {
154     BN_free(copy);
155     return 0;
156   }
157   *out = copy;
158   bn_secret(copy);
159 
160   return 1;
161 }
162 
163 // freeze_private_key finishes initializing |rsa|'s private key components.
164 // After this function has returned, |rsa| may not be changed. This is needed
165 // because |RSA| is a public struct and, additionally, OpenSSL 1.1.0 opaquified
166 // it wrong (see https://github.com/openssl/openssl/issues/5158).
freeze_private_key(RSA * rsa,BN_CTX * ctx)167 static int freeze_private_key(RSA *rsa, BN_CTX *ctx) {
168   CRYPTO_MUTEX_lock_read(&rsa->lock);
169   int frozen = rsa->private_key_frozen;
170   CRYPTO_MUTEX_unlock_read(&rsa->lock);
171   if (frozen) {
172     return 1;
173   }
174 
175   int ret = 0;
176   CRYPTO_MUTEX_lock_write(&rsa->lock);
177   if (rsa->private_key_frozen) {
178     ret = 1;
179     goto err;
180   }
181 
182   // Check the public components are within DoS bounds.
183   if (!rsa_check_public_key(rsa)) {
184     goto err;
185   }
186 
187   // Pre-compute various intermediate values, as well as copies of private
188   // exponents with correct widths. Note that other threads may concurrently
189   // read from |rsa->n|, |rsa->e|, etc., so any fixes must be in separate
190   // copies. We use |mont_n->N|, |mont_p->N|, and |mont_q->N| as copies of |n|,
191   // |p|, and |q| with the correct minimal widths.
192 
193   if (rsa->mont_n == NULL) {
194     rsa->mont_n = BN_MONT_CTX_new_for_modulus(rsa->n, ctx);
195     if (rsa->mont_n == NULL) {
196       goto err;
197     }
198   }
199   const BIGNUM *n_fixed = &rsa->mont_n->N;
200 
201   // The only public upper-bound of |rsa->d| is the bit length of |rsa->n|. The
202   // ASN.1 serialization of RSA private keys unfortunately leaks the byte length
203   // of |rsa->d|, but normalize it so we only leak it once, rather than per
204   // operation.
205   if (rsa->d != NULL &&
206       !ensure_fixed_copy(&rsa->d_fixed, rsa->d, n_fixed->width)) {
207     goto err;
208   }
209 
210   if (rsa->e != NULL && rsa->p != NULL && rsa->q != NULL) {
211     // TODO: p and q are also CONSTTIME_SECRET but not yet marked as such
212     // because the Montgomery code does things like test whether or not values
213     // are zero. So the secret marking probably needs to happen inside that
214     // code.
215 
216     if (rsa->mont_p == NULL) {
217       rsa->mont_p = BN_MONT_CTX_new_consttime(rsa->p, ctx);
218       if (rsa->mont_p == NULL) {
219         goto err;
220       }
221     }
222     const BIGNUM *p_fixed = &rsa->mont_p->N;
223 
224     if (rsa->mont_q == NULL) {
225       rsa->mont_q = BN_MONT_CTX_new_consttime(rsa->q, ctx);
226       if (rsa->mont_q == NULL) {
227         goto err;
228       }
229     }
230     const BIGNUM *q_fixed = &rsa->mont_q->N;
231 
232     if (rsa->dmp1 != NULL && rsa->dmq1 != NULL) {
233       // Key generation relies on this function to compute |iqmp|.
234       if (rsa->iqmp == NULL) {
235         BIGNUM *iqmp = BN_new();
236         if (iqmp == NULL ||
237             !bn_mod_inverse_secret_prime(iqmp, rsa->q, rsa->p, ctx,
238                                          rsa->mont_p)) {
239           BN_free(iqmp);
240           goto err;
241         }
242         rsa->iqmp = iqmp;
243       }
244 
245       // CRT components are only publicly bounded by their corresponding
246       // moduli's bit lengths.
247       if (!ensure_fixed_copy(&rsa->dmp1_fixed, rsa->dmp1, p_fixed->width) ||
248           !ensure_fixed_copy(&rsa->dmq1_fixed, rsa->dmq1, q_fixed->width)) {
249         goto err;
250       }
251 
252       // Compute |iqmp_mont|, which is |iqmp| in Montgomery form and with the
253       // correct bit width.
254       if (rsa->iqmp_mont == NULL) {
255         BIGNUM *iqmp_mont = BN_new();
256         if (iqmp_mont == NULL ||
257             !BN_to_montgomery(iqmp_mont, rsa->iqmp, rsa->mont_p, ctx)) {
258           BN_free(iqmp_mont);
259           goto err;
260         }
261         rsa->iqmp_mont = iqmp_mont;
262         bn_secret(rsa->iqmp_mont);
263       }
264     }
265   }
266 
267   rsa->private_key_frozen = 1;
268   ret = 1;
269 
270 err:
271   CRYPTO_MUTEX_unlock_write(&rsa->lock);
272   return ret;
273 }
274 
rsa_invalidate_key(RSA * rsa)275 void rsa_invalidate_key(RSA *rsa) {
276   rsa->private_key_frozen = 0;
277 
278   BN_MONT_CTX_free(rsa->mont_n);
279   rsa->mont_n = NULL;
280   BN_MONT_CTX_free(rsa->mont_p);
281   rsa->mont_p = NULL;
282   BN_MONT_CTX_free(rsa->mont_q);
283   rsa->mont_q = NULL;
284 
285   BN_free(rsa->d_fixed);
286   rsa->d_fixed = NULL;
287   BN_free(rsa->dmp1_fixed);
288   rsa->dmp1_fixed = NULL;
289   BN_free(rsa->dmq1_fixed);
290   rsa->dmq1_fixed = NULL;
291   BN_free(rsa->iqmp_mont);
292   rsa->iqmp_mont = NULL;
293 
294   for (size_t i = 0; i < rsa->num_blindings; i++) {
295     BN_BLINDING_free(rsa->blindings[i]);
296   }
297   OPENSSL_free(rsa->blindings);
298   rsa->blindings = NULL;
299   rsa->num_blindings = 0;
300   OPENSSL_free(rsa->blindings_inuse);
301   rsa->blindings_inuse = NULL;
302   rsa->blinding_fork_generation = 0;
303 }
304 
rsa_default_size(const RSA * rsa)305 size_t rsa_default_size(const RSA *rsa) {
306   return BN_num_bytes(rsa->n);
307 }
308 
309 // MAX_BLINDINGS_PER_RSA defines the maximum number of cached BN_BLINDINGs per
310 // RSA*. Then this limit is exceeded, BN_BLINDING objects will be created and
311 // destroyed as needed.
312 #if defined(OPENSSL_TSAN)
313 // Smaller under TSAN so that the edge case can be hit with fewer threads.
314 #define MAX_BLINDINGS_PER_RSA 2
315 #else
316 #define MAX_BLINDINGS_PER_RSA 1024
317 #endif
318 
319 // rsa_blinding_get returns a BN_BLINDING to use with |rsa|. It does this by
320 // allocating one of the cached BN_BLINDING objects in |rsa->blindings|. If
321 // none are free, the cache will be extended by a extra element and the new
322 // BN_BLINDING is returned.
323 //
324 // On success, the index of the assigned BN_BLINDING is written to
325 // |*index_used| and must be passed to |rsa_blinding_release| when finished.
rsa_blinding_get(RSA * rsa,size_t * index_used,BN_CTX * ctx)326 static BN_BLINDING *rsa_blinding_get(RSA *rsa, size_t *index_used,
327                                      BN_CTX *ctx) {
328   assert(ctx != NULL);
329   assert(rsa->mont_n != NULL);
330 
331   BN_BLINDING *ret = NULL;
332   const uint64_t fork_generation = CRYPTO_get_fork_generation();
333   CRYPTO_MUTEX_lock_write(&rsa->lock);
334 
335   // Wipe the blinding cache on |fork|.
336   if (rsa->blinding_fork_generation != fork_generation) {
337     for (size_t i = 0; i < rsa->num_blindings; i++) {
338       // The inuse flag must be zero unless we were forked from a
339       // multi-threaded process, in which case calling back into BoringSSL is
340       // forbidden.
341       assert(rsa->blindings_inuse[i] == 0);
342       BN_BLINDING_invalidate(rsa->blindings[i]);
343     }
344     rsa->blinding_fork_generation = fork_generation;
345   }
346 
347   uint8_t *const free_inuse_flag =
348       OPENSSL_memchr(rsa->blindings_inuse, 0, rsa->num_blindings);
349   if (free_inuse_flag != NULL) {
350     *free_inuse_flag = 1;
351     *index_used = free_inuse_flag - rsa->blindings_inuse;
352     ret = rsa->blindings[*index_used];
353     goto out;
354   }
355 
356   if (rsa->num_blindings >= MAX_BLINDINGS_PER_RSA) {
357     // No |BN_BLINDING| is free and nor can the cache be extended. This index
358     // value is magic and indicates to |rsa_blinding_release| that a
359     // |BN_BLINDING| was not inserted into the array.
360     *index_used = MAX_BLINDINGS_PER_RSA;
361     ret = BN_BLINDING_new();
362     goto out;
363   }
364 
365   // Double the length of the cache.
366   static_assert(MAX_BLINDINGS_PER_RSA < UINT_MAX / 2,
367                 "MAX_BLINDINGS_PER_RSA too large");
368   size_t new_num_blindings = rsa->num_blindings * 2;
369   if (new_num_blindings == 0) {
370     new_num_blindings = 1;
371   }
372   if (new_num_blindings > MAX_BLINDINGS_PER_RSA) {
373     new_num_blindings = MAX_BLINDINGS_PER_RSA;
374   }
375   assert(new_num_blindings > rsa->num_blindings);
376 
377   BN_BLINDING **new_blindings =
378       OPENSSL_calloc(new_num_blindings, sizeof(BN_BLINDING *));
379   uint8_t *new_blindings_inuse = OPENSSL_malloc(new_num_blindings);
380   if (new_blindings == NULL || new_blindings_inuse == NULL) {
381     goto err;
382   }
383 
384   OPENSSL_memcpy(new_blindings, rsa->blindings,
385                  sizeof(BN_BLINDING *) * rsa->num_blindings);
386   OPENSSL_memcpy(new_blindings_inuse, rsa->blindings_inuse, rsa->num_blindings);
387 
388   for (size_t i = rsa->num_blindings; i < new_num_blindings; i++) {
389     new_blindings[i] = BN_BLINDING_new();
390     if (new_blindings[i] == NULL) {
391       for (size_t j = rsa->num_blindings; j < i; j++) {
392         BN_BLINDING_free(new_blindings[j]);
393       }
394       goto err;
395     }
396   }
397   memset(&new_blindings_inuse[rsa->num_blindings], 0,
398          new_num_blindings - rsa->num_blindings);
399 
400   new_blindings_inuse[rsa->num_blindings] = 1;
401   *index_used = rsa->num_blindings;
402   assert(*index_used != MAX_BLINDINGS_PER_RSA);
403   ret = new_blindings[rsa->num_blindings];
404 
405   OPENSSL_free(rsa->blindings);
406   rsa->blindings = new_blindings;
407   OPENSSL_free(rsa->blindings_inuse);
408   rsa->blindings_inuse = new_blindings_inuse;
409   rsa->num_blindings = new_num_blindings;
410 
411   goto out;
412 
413 err:
414   OPENSSL_free(new_blindings_inuse);
415   OPENSSL_free(new_blindings);
416 
417 out:
418   CRYPTO_MUTEX_unlock_write(&rsa->lock);
419   return ret;
420 }
421 
422 // rsa_blinding_release marks the cached BN_BLINDING at the given index as free
423 // for other threads to use.
rsa_blinding_release(RSA * rsa,BN_BLINDING * blinding,size_t blinding_index)424 static void rsa_blinding_release(RSA *rsa, BN_BLINDING *blinding,
425                                  size_t blinding_index) {
426   if (blinding_index == MAX_BLINDINGS_PER_RSA) {
427     // This blinding wasn't cached.
428     BN_BLINDING_free(blinding);
429     return;
430   }
431 
432   CRYPTO_MUTEX_lock_write(&rsa->lock);
433   rsa->blindings_inuse[blinding_index] = 0;
434   CRYPTO_MUTEX_unlock_write(&rsa->lock);
435 }
436 
437 // signing
rsa_default_sign_raw(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)438 int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out,
439                          size_t max_out, const uint8_t *in, size_t in_len,
440                          int padding) {
441   const unsigned rsa_size = RSA_size(rsa);
442   uint8_t *buf = NULL;
443   int i, ret = 0;
444 
445   if (max_out < rsa_size) {
446     OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
447     return 0;
448   }
449 
450   buf = OPENSSL_malloc(rsa_size);
451   if (buf == NULL) {
452     goto err;
453   }
454 
455   switch (padding) {
456     case RSA_PKCS1_PADDING:
457       i = RSA_padding_add_PKCS1_type_1(buf, rsa_size, in, in_len);
458       break;
459     case RSA_NO_PADDING:
460       i = RSA_padding_add_none(buf, rsa_size, in, in_len);
461       break;
462     default:
463       OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
464       goto err;
465   }
466 
467   if (i <= 0) {
468     goto err;
469   }
470 
471   if (!rsa_private_transform_no_self_test(rsa, out, buf, rsa_size)) {
472     goto err;
473   }
474 
475   CONSTTIME_DECLASSIFY(out, rsa_size);
476   *out_len = rsa_size;
477   ret = 1;
478 
479 err:
480   OPENSSL_free(buf);
481 
482   return ret;
483 }
484 
485 
486 static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
487 
rsa_verify_raw_no_self_test(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)488 int rsa_verify_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out,
489                                 size_t max_out, const uint8_t *in,
490                                 size_t in_len, int padding) {
491   if (rsa->n == NULL || rsa->e == NULL) {
492     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
493     return 0;
494   }
495 
496   if (!rsa_check_public_key(rsa)) {
497     return 0;
498   }
499 
500   const unsigned rsa_size = RSA_size(rsa);
501   BIGNUM *f, *result;
502 
503   if (max_out < rsa_size) {
504     OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
505     return 0;
506   }
507 
508   if (in_len != rsa_size) {
509     OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
510     return 0;
511   }
512 
513   BN_CTX *ctx = BN_CTX_new();
514   if (ctx == NULL) {
515     return 0;
516   }
517 
518   int ret = 0;
519   uint8_t *buf = NULL;
520 
521   BN_CTX_start(ctx);
522   f = BN_CTX_get(ctx);
523   result = BN_CTX_get(ctx);
524   if (f == NULL || result == NULL) {
525     goto err;
526   }
527 
528   if (padding == RSA_NO_PADDING) {
529     buf = out;
530   } else {
531     // Allocate a temporary buffer to hold the padded plaintext.
532     buf = OPENSSL_malloc(rsa_size);
533     if (buf == NULL) {
534       goto err;
535     }
536   }
537 
538   if (BN_bin2bn(in, in_len, f) == NULL) {
539     goto err;
540   }
541 
542   if (BN_ucmp(f, rsa->n) >= 0) {
543     OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
544     goto err;
545   }
546 
547   if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
548       !BN_mod_exp_mont(result, f, rsa->e, &rsa->mont_n->N, ctx, rsa->mont_n)) {
549     goto err;
550   }
551 
552   if (!BN_bn2bin_padded(buf, rsa_size, result)) {
553     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
554     goto err;
555   }
556 
557   switch (padding) {
558     case RSA_PKCS1_PADDING:
559       ret =
560           RSA_padding_check_PKCS1_type_1(out, out_len, rsa_size, buf, rsa_size);
561       break;
562     case RSA_NO_PADDING:
563       ret = 1;
564       *out_len = rsa_size;
565       break;
566     default:
567       OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
568       goto err;
569   }
570 
571   if (!ret) {
572     OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
573     goto err;
574   }
575 
576 err:
577   BN_CTX_end(ctx);
578   BN_CTX_free(ctx);
579   if (buf != out) {
580     OPENSSL_free(buf);
581   }
582   return ret;
583 }
584 
RSA_verify_raw(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)585 int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out,
586                                 size_t max_out, const uint8_t *in,
587                                 size_t in_len, int padding) {
588   boringssl_ensure_rsa_self_test();
589   return rsa_verify_raw_no_self_test(rsa, out_len, out, max_out, in, in_len,
590                                      padding);
591 }
592 
rsa_default_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)593 int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
594                                   size_t len) {
595   if (rsa->n == NULL || rsa->d == NULL) {
596     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
597     return 0;
598   }
599 
600   BIGNUM *f, *result;
601   BN_CTX *ctx = NULL;
602   size_t blinding_index = 0;
603   BN_BLINDING *blinding = NULL;
604   int ret = 0;
605 
606   ctx = BN_CTX_new();
607   if (ctx == NULL) {
608     goto err;
609   }
610   BN_CTX_start(ctx);
611   f = BN_CTX_get(ctx);
612   result = BN_CTX_get(ctx);
613 
614   if (f == NULL || result == NULL) {
615     goto err;
616   }
617 
618   // The caller should have ensured this.
619   assert(len == BN_num_bytes(rsa->n));
620   if (BN_bin2bn(in, len, f) == NULL) {
621     goto err;
622   }
623 
624   // The input to the RSA private transform may be secret, but padding is
625   // expected to construct a value within range, so we can leak this comparison.
626   if (constant_time_declassify_int(BN_ucmp(f, rsa->n) >= 0)) {
627     // Usually the padding functions would catch this.
628     OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
629     goto err;
630   }
631 
632   if (!freeze_private_key(rsa, ctx)) {
633     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
634     goto err;
635   }
636 
637   const int do_blinding =
638       (rsa->flags & (RSA_FLAG_NO_BLINDING | RSA_FLAG_NO_PUBLIC_EXPONENT)) == 0;
639 
640   if (rsa->e == NULL && do_blinding) {
641     // We cannot do blinding or verification without |e|, and continuing without
642     // those countermeasures is dangerous. However, the Java/Android RSA API
643     // requires support for keys where only |d| and |n| (and not |e|) are known.
644     // The callers that require that bad behavior must set
645     // |RSA_FLAG_NO_BLINDING| or use |RSA_new_private_key_no_e|.
646     //
647     // TODO(davidben): Update this comment when Conscrypt is updated to use
648     // |RSA_new_private_key_no_e|.
649     OPENSSL_PUT_ERROR(RSA, RSA_R_NO_PUBLIC_EXPONENT);
650     goto err;
651   }
652 
653   if (do_blinding) {
654     blinding = rsa_blinding_get(rsa, &blinding_index, ctx);
655     if (blinding == NULL) {
656       OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
657       goto err;
658     }
659     if (!BN_BLINDING_convert(f, blinding, rsa->e, rsa->mont_n, ctx)) {
660       goto err;
661     }
662   }
663 
664   if (rsa->p != NULL && rsa->q != NULL && rsa->e != NULL && rsa->dmp1 != NULL &&
665       rsa->dmq1 != NULL && rsa->iqmp != NULL &&
666       // Require that we can reduce |f| by |rsa->p| and |rsa->q| in constant
667       // time, which requires primes be the same size, rounded to the Montgomery
668       // coefficient. (See |mod_montgomery|.) This is not required by RFC 8017,
669       // but it is true for keys generated by us and all common implementations.
670       bn_less_than_montgomery_R(rsa->q, rsa->mont_p) &&
671       bn_less_than_montgomery_R(rsa->p, rsa->mont_q)) {
672     if (!mod_exp(result, f, rsa, ctx)) {
673       goto err;
674     }
675   } else if (!BN_mod_exp_mont_consttime(result, f, rsa->d_fixed, rsa->n, ctx,
676                                         rsa->mont_n)) {
677     goto err;
678   }
679 
680   // Verify the result to protect against fault attacks as described in the
681   // 1997 paper "On the Importance of Checking Cryptographic Protocols for
682   // Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton. Some
683   // implementations do this only when the CRT is used, but we do it in all
684   // cases. Section 6 of the aforementioned paper describes an attack that
685   // works when the CRT isn't used. That attack is much less likely to succeed
686   // than the CRT attack, but there have likely been improvements since 1997.
687   //
688   // This check is cheap assuming |e| is small, which we require in
689   // |rsa_check_public_key|.
690   if (rsa->e != NULL) {
691     BIGNUM *vrfy = BN_CTX_get(ctx);
692     if (vrfy == NULL ||
693         !BN_mod_exp_mont(vrfy, result, rsa->e, rsa->n, ctx, rsa->mont_n) ||
694         !constant_time_declassify_int(BN_equal_consttime(vrfy, f))) {
695       OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
696       goto err;
697     }
698   }
699 
700   if (do_blinding &&
701       !BN_BLINDING_invert(result, blinding, rsa->mont_n, ctx)) {
702     goto err;
703   }
704 
705   // The computation should have left |result| as a maximally-wide number, so
706   // that it and serializing does not leak information about the magnitude of
707   // the result.
708   //
709   // See Falko Strenzke, "Manger's Attack revisited", ICICS 2010.
710   assert(result->width == rsa->mont_n->N.width);
711   bn_assert_fits_in_bytes(result, len);
712   if (!BN_bn2bin_padded(out, len, result)) {
713     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
714     goto err;
715   }
716 
717   ret = 1;
718 
719 err:
720   if (ctx != NULL) {
721     BN_CTX_end(ctx);
722     BN_CTX_free(ctx);
723   }
724   if (blinding != NULL) {
725     rsa_blinding_release(rsa, blinding, blinding_index);
726   }
727 
728   return ret;
729 }
730 
731 // mod_montgomery sets |r| to |I| mod |p|. |I| must already be fully reduced
732 // modulo |p| times |q|. It returns one on success and zero on error.
mod_montgomery(BIGNUM * r,const BIGNUM * I,const BIGNUM * p,const BN_MONT_CTX * mont_p,const BIGNUM * q,BN_CTX * ctx)733 static int mod_montgomery(BIGNUM *r, const BIGNUM *I, const BIGNUM *p,
734                           const BN_MONT_CTX *mont_p, const BIGNUM *q,
735                           BN_CTX *ctx) {
736   // Reducing in constant-time with Montgomery reduction requires I <= p * R. We
737   // have I < p * q, so this follows if q < R. The caller should have checked
738   // this already.
739   if (!bn_less_than_montgomery_R(q, mont_p)) {
740     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
741     return 0;
742   }
743 
744   if (// Reduce mod p with Montgomery reduction. This computes I * R^-1 mod p.
745       !BN_from_montgomery(r, I, mont_p, ctx) ||
746       // Multiply by R^2 and do another Montgomery reduction to compute
747       // I * R^-1 * R^2 * R^-1 = I mod p.
748       !BN_to_montgomery(r, r, mont_p, ctx)) {
749     return 0;
750   }
751 
752   // By precomputing R^3 mod p (normally |BN_MONT_CTX| only uses R^2 mod p) and
753   // adjusting the API for |BN_mod_exp_mont_consttime|, we could instead compute
754   // I * R mod p here and save a reduction per prime. But this would require
755   // changing the RSAZ code and may not be worth it. Note that the RSAZ code
756   // uses a different radix, so it uses R' = 2^1044. There we'd actually want
757   // R^2 * R', and would futher benefit from a precomputed R'^2. It currently
758   // converts |mont_p->RR| to R'^2.
759   return 1;
760 }
761 
mod_exp(BIGNUM * r0,const BIGNUM * I,RSA * rsa,BN_CTX * ctx)762 static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) {
763   assert(ctx != NULL);
764 
765   assert(rsa->n != NULL);
766   assert(rsa->e != NULL);
767   assert(rsa->d != NULL);
768   assert(rsa->p != NULL);
769   assert(rsa->q != NULL);
770   assert(rsa->dmp1 != NULL);
771   assert(rsa->dmq1 != NULL);
772   assert(rsa->iqmp != NULL);
773 
774   BIGNUM *r1, *m1;
775   int ret = 0;
776 
777   BN_CTX_start(ctx);
778   r1 = BN_CTX_get(ctx);
779   m1 = BN_CTX_get(ctx);
780   if (r1 == NULL ||
781       m1 == NULL) {
782     goto err;
783   }
784 
785   if (!freeze_private_key(rsa, ctx)) {
786     goto err;
787   }
788 
789   // Use the minimal-width versions of |n|, |p|, and |q|. Either works, but if
790   // someone gives us non-minimal values, these will be slightly more efficient
791   // on the non-Montgomery operations.
792   const BIGNUM *n = &rsa->mont_n->N;
793   const BIGNUM *p = &rsa->mont_p->N;
794   const BIGNUM *q = &rsa->mont_q->N;
795 
796   // This is a pre-condition for |mod_montgomery|. It was already checked by the
797   // caller.
798   declassify_assert(BN_ucmp(I, n) < 0);
799 
800   if (// |m1| is the result modulo |q|.
801       !mod_montgomery(r1, I, q, rsa->mont_q, p, ctx) ||
802       !BN_mod_exp_mont_consttime(m1, r1, rsa->dmq1_fixed, q, ctx,
803                                  rsa->mont_q) ||
804       // |r0| is the result modulo |p|.
805       !mod_montgomery(r1, I, p, rsa->mont_p, q, ctx) ||
806       !BN_mod_exp_mont_consttime(r0, r1, rsa->dmp1_fixed, p, ctx,
807                                  rsa->mont_p) ||
808       // Compute r0 = r0 - m1 mod p. |m1| is reduced mod |q|, not |p|, so we
809       // just run |mod_montgomery| again for simplicity. This could be more
810       // efficient with more cases: if |p > q|, |m1| is already reduced. If
811       // |p < q| but they have the same bit width, |bn_reduce_once| suffices.
812       // However, compared to over 2048 Montgomery multiplications above, this
813       // difference is not measurable.
814       !mod_montgomery(r1, m1, p, rsa->mont_p, q, ctx) ||
815       !bn_mod_sub_consttime(r0, r0, r1, p, ctx) ||
816       // r0 = r0 * iqmp mod p. We use Montgomery multiplication to compute this
817       // in constant time. |iqmp_mont| is in Montgomery form and r0 is not, so
818       // the result is taken out of Montgomery form.
819       !BN_mod_mul_montgomery(r0, r0, rsa->iqmp_mont, rsa->mont_p, ctx) ||
820       // r0 = r0 * q + m1 gives the final result. Reducing modulo q gives m1, so
821       // it is correct mod p. Reducing modulo p gives (r0-m1)*iqmp*q + m1 = r0,
822       // so it is correct mod q. Finally, the result is bounded by [m1, n + m1),
823       // and the result is at least |m1|, so this must be the unique answer in
824       // [0, n).
825       !bn_mul_consttime(r0, r0, q, ctx) ||  //
826       !bn_uadd_consttime(r0, r0, m1)) {
827     goto err;
828   }
829 
830   // The result should be bounded by |n|, but fixed-width operations may
831   // bound the width slightly higher, so fix it. This trips constant-time checks
832   // because a naive data flow analysis does not realize the excess words are
833   // publicly zero.
834   declassify_assert(BN_cmp(r0, n) < 0);
835   bn_assert_fits_in_bytes(r0, BN_num_bytes(n));
836   if (!bn_resize_words(r0, n->width)) {
837     goto err;
838   }
839 
840   ret = 1;
841 
842 err:
843   BN_CTX_end(ctx);
844   return ret;
845 }
846 
ensure_bignum(BIGNUM ** out)847 static int ensure_bignum(BIGNUM **out) {
848   if (*out == NULL) {
849     *out = BN_new();
850   }
851   return *out != NULL;
852 }
853 
854 // kBoringSSLRSASqrtTwo is the BIGNUM representation of ⌊2²⁰⁴⁷×√2⌋. This is
855 // chosen to give enough precision for 4096-bit RSA, the largest key size FIPS
856 // specifies. Key sizes beyond this will round up.
857 //
858 // To calculate, use the following Haskell code:
859 //
860 // import Text.Printf (printf)
861 // import Data.List (intercalate)
862 //
863 // pow2 = 4095
864 // target = 2^pow2
865 //
866 // f x = x*x - (toRational target)
867 //
868 // fprime x = 2*x
869 //
870 // newtonIteration x = x - (f x) / (fprime x)
871 //
872 // converge x =
873 //   let n = floor x in
874 //   if n*n - target < 0 && (n+1)*(n+1) - target > 0
875 //     then n
876 //     else converge (newtonIteration x)
877 //
878 // divrem bits x = (x `div` (2^bits), x `rem` (2^bits))
879 //
880 // bnWords :: Integer -> [Integer]
881 // bnWords x =
882 //   if x == 0
883 //     then []
884 //     else let (high, low) = divrem 64 x in low : bnWords high
885 //
886 // showWord x = let (high, low) = divrem 32 x in printf "TOBN(0x%08x, 0x%08x)" high low
887 //
888 // output :: String
889 // output = intercalate ", " $ map showWord $ bnWords $ converge (2 ^ (pow2 `div` 2))
890 //
891 // To verify this number, check that n² < 2⁴⁰⁹⁵ < (n+1)², where n is value
892 // represented here. Note the components are listed in little-endian order. Here
893 // is some sample Python code to check:
894 //
895 //   >>> TOBN = lambda a, b: a << 32 | b
896 //   >>> l = [ <paste the contents of kSqrtTwo> ]
897 //   >>> n = sum(a * 2**(64*i) for i, a in enumerate(l))
898 //   >>> n**2 < 2**4095 < (n+1)**2
899 //   True
900 const BN_ULONG kBoringSSLRSASqrtTwo[] = {
901     TOBN(0x4d7c60a5, 0xe633e3e1), TOBN(0x5fcf8f7b, 0xca3ea33b),
902     TOBN(0xc246785e, 0x92957023), TOBN(0xf9acce41, 0x797f2805),
903     TOBN(0xfdfe170f, 0xd3b1f780), TOBN(0xd24f4a76, 0x3facb882),
904     TOBN(0x18838a2e, 0xaff5f3b2), TOBN(0xc1fcbdde, 0xa2f7dc33),
905     TOBN(0xdea06241, 0xf7aa81c2), TOBN(0xf6a1be3f, 0xca221307),
906     TOBN(0x332a5e9f, 0x7bda1ebf), TOBN(0x0104dc01, 0xfe32352f),
907     TOBN(0xb8cf341b, 0x6f8236c7), TOBN(0x4264dabc, 0xd528b651),
908     TOBN(0xf4d3a02c, 0xebc93e0c), TOBN(0x81394ab6, 0xd8fd0efd),
909     TOBN(0xeaa4a089, 0x9040ca4a), TOBN(0xf52f120f, 0x836e582e),
910     TOBN(0xcb2a6343, 0x31f3c84d), TOBN(0xc6d5a8a3, 0x8bb7e9dc),
911     TOBN(0x460abc72, 0x2f7c4e33), TOBN(0xcab1bc91, 0x1688458a),
912     TOBN(0x53059c60, 0x11bc337b), TOBN(0xd2202e87, 0x42af1f4e),
913     TOBN(0x78048736, 0x3dfa2768), TOBN(0x0f74a85e, 0x439c7b4a),
914     TOBN(0xa8b1fe6f, 0xdc83db39), TOBN(0x4afc8304, 0x3ab8a2c3),
915     TOBN(0xed17ac85, 0x83339915), TOBN(0x1d6f60ba, 0x893ba84c),
916     TOBN(0x597d89b3, 0x754abe9f), TOBN(0xb504f333, 0xf9de6484),
917 };
918 const size_t kBoringSSLRSASqrtTwoLen = OPENSSL_ARRAY_SIZE(kBoringSSLRSASqrtTwo);
919 
920 // generate_prime sets |out| to a prime with length |bits| such that |out|-1 is
921 // relatively prime to |e|. If |p| is non-NULL, |out| will also not be close to
922 // |p|. |sqrt2| must be ⌊2^(bits-1)×√2⌋ (or a slightly overestimate for large
923 // sizes), and |pow2_bits_100| must be 2^(bits-100).
924 //
925 // This function fails with probability around 2^-21.
generate_prime(BIGNUM * out,int bits,const BIGNUM * e,const BIGNUM * p,const BIGNUM * sqrt2,const BIGNUM * pow2_bits_100,BN_CTX * ctx,BN_GENCB * cb)926 static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e,
927                           const BIGNUM *p, const BIGNUM *sqrt2,
928                           const BIGNUM *pow2_bits_100, BN_CTX *ctx,
929                           BN_GENCB *cb) {
930   if (bits < 128 || (bits % BN_BITS2) != 0) {
931     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
932     return 0;
933   }
934   assert(BN_is_pow2(pow2_bits_100));
935   assert(BN_is_bit_set(pow2_bits_100, bits - 100));
936 
937   // See FIPS 186-4 appendix B.3.3, steps 4 and 5. Note |bits| here is nlen/2.
938 
939   // Use the limit from steps 4.7 and 5.8 for most values of |e|. When |e| is 3,
940   // the 186-4 limit is too low, so we use a higher one. Note this case is not
941   // reachable from |RSA_generate_key_fips|.
942   //
943   // |limit| determines the failure probability. We must find a prime that is
944   // not 1 mod |e|. By the prime number theorem, we'll find one with probability
945   // p = (e-1)/e * 2/(ln(2)*bits). Note the second term is doubled because we
946   // discard even numbers.
947   //
948   // The failure probability is thus (1-p)^limit. To convert that to a power of
949   // two, we take logs. -log_2((1-p)^limit) = -limit * ln(1-p) / ln(2).
950   //
951   // >>> def f(bits, e, limit):
952   // ...   p = (e-1.0)/e * 2.0/(math.log(2)*bits)
953   // ...   return -limit * math.log(1 - p) / math.log(2)
954   // ...
955   // >>> f(1024, 65537, 5*1024)
956   // 20.842750558272634
957   // >>> f(1536, 65537, 5*1536)
958   // 20.83294549602474
959   // >>> f(2048, 65537, 5*2048)
960   // 20.828047576234948
961   // >>> f(1024, 3, 8*1024)
962   // 22.222147925962307
963   // >>> f(1536, 3, 8*1536)
964   // 22.21518251065506
965   // >>> f(2048, 3, 8*2048)
966   // 22.211701985875937
967   if (bits >= INT_MAX/32) {
968     OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE);
969     return 0;
970   }
971   int limit = BN_is_word(e, 3) ? bits * 8 : bits * 5;
972 
973   int ret = 0, tries = 0, rand_tries = 0;
974   BN_CTX_start(ctx);
975   BIGNUM *tmp = BN_CTX_get(ctx);
976   if (tmp == NULL) {
977     goto err;
978   }
979 
980   for (;;) {
981     // Generate a random number of length |bits| where the bottom bit is set
982     // (steps 4.2, 4.3, 5.2 and 5.3) and the top bit is set (implied by the
983     // bound checked below in steps 4.4 and 5.5).
984     if (!BN_rand(out, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD) ||
985         !BN_GENCB_call(cb, BN_GENCB_GENERATED, rand_tries++)) {
986       goto err;
987     }
988 
989     if (p != NULL) {
990       // If |p| and |out| are too close, try again (step 5.4).
991       if (!bn_abs_sub_consttime(tmp, out, p, ctx)) {
992         goto err;
993       }
994       if (BN_cmp(tmp, pow2_bits_100) <= 0) {
995         continue;
996       }
997     }
998 
999     // If out < 2^(bits-1)×√2, try again (steps 4.4 and 5.5). This is equivalent
1000     // to out <= ⌊2^(bits-1)×√2⌋, or out <= sqrt2 for FIPS key sizes.
1001     //
1002     // For larger keys, the comparison is approximate, leaning towards
1003     // retrying. That is, we reject a negligible fraction of primes that are
1004     // within the FIPS bound, but we will never accept a prime outside the
1005     // bound, ensuring the resulting RSA key is the right size.
1006     //
1007     // Values over the threshold are discarded, so it is safe to leak this
1008     // comparison.
1009     if (constant_time_declassify_int(BN_cmp(out, sqrt2) <= 0)) {
1010       continue;
1011     }
1012 
1013     // RSA key generation's bottleneck is discarding composites. If it fails
1014     // trial division, do not bother computing a GCD or performing Miller-Rabin.
1015     if (!bn_odd_number_is_obviously_composite(out)) {
1016       // Check gcd(out-1, e) is one (steps 4.5 and 5.6). Leaking the final
1017       // result of this comparison is safe because, if not relatively prime, the
1018       // value will be discarded.
1019       int relatively_prime;
1020       if (!bn_usub_consttime(tmp, out, BN_value_one()) ||
1021           !bn_is_relatively_prime(&relatively_prime, tmp, e, ctx)) {
1022         goto err;
1023       }
1024       if (constant_time_declassify_int(relatively_prime)) {
1025         // Test |out| for primality (steps 4.5.1 and 5.6.1).
1026         int is_probable_prime;
1027         if (!BN_primality_test(&is_probable_prime, out,
1028                                BN_prime_checks_for_generation, ctx, 0, cb)) {
1029           goto err;
1030         }
1031         if (is_probable_prime) {
1032           ret = 1;
1033           goto err;
1034         }
1035       }
1036     }
1037 
1038     // If we've tried too many times to find a prime, abort (steps 4.7 and
1039     // 5.8).
1040     tries++;
1041     if (tries >= limit) {
1042       OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_MANY_ITERATIONS);
1043       goto err;
1044     }
1045     if (!BN_GENCB_call(cb, 2, tries)) {
1046       goto err;
1047     }
1048   }
1049 
1050 err:
1051   BN_CTX_end(ctx);
1052   return ret;
1053 }
1054 
1055 // rsa_generate_key_impl generates an RSA key using a generalized version of
1056 // FIPS 186-4 appendix B.3. |RSA_generate_key_fips| performs additional checks
1057 // for FIPS-compliant key generation.
1058 //
1059 // This function returns one on success and zero on failure. It has a failure
1060 // probability of about 2^-20.
rsa_generate_key_impl(RSA * rsa,int bits,const BIGNUM * e_value,BN_GENCB * cb)1061 static int rsa_generate_key_impl(RSA *rsa, int bits, const BIGNUM *e_value,
1062                                  BN_GENCB *cb) {
1063   // See FIPS 186-4 appendix B.3. This function implements a generalized version
1064   // of the FIPS algorithm. |RSA_generate_key_fips| performs additional checks
1065   // for FIPS-compliant key generation.
1066 
1067   // Always generate RSA keys which are a multiple of 128 bits. Round |bits|
1068   // down as needed.
1069   bits &= ~127;
1070 
1071   // Reject excessively small keys.
1072   if (bits < 256) {
1073     OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
1074     return 0;
1075   }
1076 
1077   // Reject excessively large public exponents. Windows CryptoAPI and Go don't
1078   // support values larger than 32 bits, so match their limits for generating
1079   // keys. (|rsa_check_public_key| uses a slightly more conservative value, but
1080   // we don't need to support generating such keys.)
1081   // https://github.com/golang/go/issues/3161
1082   // https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx
1083   if (BN_num_bits(e_value) > 32) {
1084     OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
1085     return 0;
1086   }
1087 
1088   int ret = 0;
1089   int prime_bits = bits / 2;
1090   BN_CTX *ctx = BN_CTX_new();
1091   if (ctx == NULL) {
1092     goto bn_err;
1093   }
1094   BN_CTX_start(ctx);
1095   BIGNUM *totient = BN_CTX_get(ctx);
1096   BIGNUM *pm1 = BN_CTX_get(ctx);
1097   BIGNUM *qm1 = BN_CTX_get(ctx);
1098   BIGNUM *sqrt2 = BN_CTX_get(ctx);
1099   BIGNUM *pow2_prime_bits_100 = BN_CTX_get(ctx);
1100   BIGNUM *pow2_prime_bits = BN_CTX_get(ctx);
1101   if (totient == NULL || pm1 == NULL || qm1 == NULL || sqrt2 == NULL ||
1102       pow2_prime_bits_100 == NULL || pow2_prime_bits == NULL ||
1103       !BN_set_bit(pow2_prime_bits_100, prime_bits - 100) ||
1104       !BN_set_bit(pow2_prime_bits, prime_bits)) {
1105     goto bn_err;
1106   }
1107 
1108   // We need the RSA components non-NULL.
1109   if (!ensure_bignum(&rsa->n) ||
1110       !ensure_bignum(&rsa->d) ||
1111       !ensure_bignum(&rsa->e) ||
1112       !ensure_bignum(&rsa->p) ||
1113       !ensure_bignum(&rsa->q) ||
1114       !ensure_bignum(&rsa->dmp1) ||
1115       !ensure_bignum(&rsa->dmq1)) {
1116     goto bn_err;
1117   }
1118 
1119   if (!BN_copy(rsa->e, e_value)) {
1120     goto bn_err;
1121   }
1122 
1123   // Compute sqrt2 >= ⌊2^(prime_bits-1)×√2⌋.
1124   if (!bn_set_words(sqrt2, kBoringSSLRSASqrtTwo, kBoringSSLRSASqrtTwoLen)) {
1125     goto bn_err;
1126   }
1127   int sqrt2_bits = kBoringSSLRSASqrtTwoLen * BN_BITS2;
1128   assert(sqrt2_bits == (int)BN_num_bits(sqrt2));
1129   if (sqrt2_bits > prime_bits) {
1130     // For key sizes up to 4096 (prime_bits = 2048), this is exactly
1131     // ⌊2^(prime_bits-1)×√2⌋.
1132     if (!BN_rshift(sqrt2, sqrt2, sqrt2_bits - prime_bits)) {
1133       goto bn_err;
1134     }
1135   } else if (prime_bits > sqrt2_bits) {
1136     // For key sizes beyond 4096, this is approximate. We err towards retrying
1137     // to ensure our key is the right size and round up.
1138     if (!BN_add_word(sqrt2, 1) ||
1139         !BN_lshift(sqrt2, sqrt2, prime_bits - sqrt2_bits)) {
1140       goto bn_err;
1141     }
1142   }
1143   assert(prime_bits == (int)BN_num_bits(sqrt2));
1144 
1145   do {
1146     // Generate p and q, each of size |prime_bits|, using the steps outlined in
1147     // appendix FIPS 186-4 appendix B.3.3.
1148     //
1149     // Each call to |generate_prime| fails with probability p = 2^-21. The
1150     // probability that either call fails is 1 - (1-p)^2, which is around 2^-20.
1151     if (!generate_prime(rsa->p, prime_bits, rsa->e, NULL, sqrt2,
1152                         pow2_prime_bits_100, ctx, cb) ||
1153         !BN_GENCB_call(cb, 3, 0) ||
1154         !generate_prime(rsa->q, prime_bits, rsa->e, rsa->p, sqrt2,
1155                         pow2_prime_bits_100, ctx, cb) ||
1156         !BN_GENCB_call(cb, 3, 1)) {
1157       goto bn_err;
1158     }
1159 
1160     if (BN_cmp(rsa->p, rsa->q) < 0) {
1161       BIGNUM *tmp = rsa->p;
1162       rsa->p = rsa->q;
1163       rsa->q = tmp;
1164     }
1165 
1166     // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-4. This differs
1167     // from typical RSA implementations which use (p-1)*(q-1).
1168     //
1169     // Note this means the size of d might reveal information about p-1 and
1170     // q-1. However, we do operations with Chinese Remainder Theorem, so we only
1171     // use d (mod p-1) and d (mod q-1) as exponents. Using a minimal totient
1172     // does not affect those two values.
1173     int no_inverse;
1174     if (!bn_usub_consttime(pm1, rsa->p, BN_value_one()) ||
1175         !bn_usub_consttime(qm1, rsa->q, BN_value_one()) ||
1176         !bn_lcm_consttime(totient, pm1, qm1, ctx) ||
1177         !bn_mod_inverse_consttime(rsa->d, &no_inverse, rsa->e, totient, ctx)) {
1178       goto bn_err;
1179     }
1180 
1181     // Retry if |rsa->d| <= 2^|prime_bits|. See appendix B.3.1's guidance on
1182     // values for d. When we retry, p and q are discarded, so it is safe to leak
1183     // this comparison.
1184   } while (constant_time_declassify_int(BN_cmp(rsa->d, pow2_prime_bits) <= 0));
1185 
1186   assert(BN_num_bits(pm1) == (unsigned)prime_bits);
1187   assert(BN_num_bits(qm1) == (unsigned)prime_bits);
1188   if (// Calculate n.
1189       !bn_mul_consttime(rsa->n, rsa->p, rsa->q, ctx) ||
1190       // Calculate d mod (p-1).
1191       !bn_div_consttime(NULL, rsa->dmp1, rsa->d, pm1, prime_bits, ctx) ||
1192       // Calculate d mod (q-1)
1193       !bn_div_consttime(NULL, rsa->dmq1, rsa->d, qm1, prime_bits, ctx)) {
1194     goto bn_err;
1195   }
1196   bn_set_minimal_width(rsa->n);
1197 
1198   // |rsa->n| is computed from the private key, but is public.
1199   bn_declassify(rsa->n);
1200 
1201   // Sanity-check that |rsa->n| has the specified size. This is implied by
1202   // |generate_prime|'s bounds.
1203   if (BN_num_bits(rsa->n) != (unsigned)bits) {
1204     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
1205     goto err;
1206   }
1207 
1208   // Call |freeze_private_key| to compute the inverse of q mod p, by way of
1209   // |rsa->mont_p|.
1210   if (!freeze_private_key(rsa, ctx)) {
1211     goto bn_err;
1212   }
1213 
1214   // The key generation process is complex and thus error-prone. It could be
1215   // disastrous to generate and then use a bad key so double-check that the key
1216   // makes sense.
1217   if (!RSA_check_key(rsa)) {
1218     OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR);
1219     goto err;
1220   }
1221 
1222   ret = 1;
1223 
1224 bn_err:
1225   if (!ret) {
1226     OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
1227   }
1228 err:
1229   if (ctx != NULL) {
1230     BN_CTX_end(ctx);
1231     BN_CTX_free(ctx);
1232   }
1233   return ret;
1234 }
1235 
replace_bignum(BIGNUM ** out,BIGNUM ** in)1236 static void replace_bignum(BIGNUM **out, BIGNUM **in) {
1237   BN_free(*out);
1238   *out = *in;
1239   *in = NULL;
1240 }
1241 
replace_bn_mont_ctx(BN_MONT_CTX ** out,BN_MONT_CTX ** in)1242 static void replace_bn_mont_ctx(BN_MONT_CTX **out, BN_MONT_CTX **in) {
1243   BN_MONT_CTX_free(*out);
1244   *out = *in;
1245   *in = NULL;
1246 }
1247 
RSA_generate_key_ex_maybe_fips(RSA * rsa,int bits,const BIGNUM * e_value,BN_GENCB * cb,int check_fips)1248 static int RSA_generate_key_ex_maybe_fips(RSA *rsa, int bits,
1249                                           const BIGNUM *e_value, BN_GENCB *cb,
1250                                           int check_fips) {
1251   boringssl_ensure_rsa_self_test();
1252 
1253   if (rsa == NULL) {
1254     OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
1255     return 0;
1256   }
1257 
1258   RSA *tmp = NULL;
1259   uint32_t err;
1260   int ret = 0;
1261 
1262   // |rsa_generate_key_impl|'s 2^-20 failure probability is too high at scale,
1263   // so we run the FIPS algorithm four times, bringing it down to 2^-80. We
1264   // should just adjust the retry limit, but FIPS 186-4 prescribes that value
1265   // and thus results in unnecessary complexity.
1266   int failures = 0;
1267   do {
1268     ERR_clear_error();
1269     // Generate into scratch space, to avoid leaving partial work on failure.
1270     tmp = RSA_new();
1271     if (tmp == NULL) {
1272       goto out;
1273     }
1274 
1275     if (rsa_generate_key_impl(tmp, bits, e_value, cb)) {
1276       break;
1277     }
1278 
1279     err = ERR_peek_error();
1280     RSA_free(tmp);
1281     tmp = NULL;
1282     failures++;
1283 
1284     // Only retry on |RSA_R_TOO_MANY_ITERATIONS|. This is so a caller-induced
1285     // failure in |BN_GENCB_call| is still fatal.
1286   } while (failures < 4 && ERR_GET_LIB(err) == ERR_LIB_RSA &&
1287            ERR_GET_REASON(err) == RSA_R_TOO_MANY_ITERATIONS);
1288 
1289   if (tmp == NULL || (check_fips && !RSA_check_fips(tmp))) {
1290     goto out;
1291   }
1292 
1293   rsa_invalidate_key(rsa);
1294   replace_bignum(&rsa->n, &tmp->n);
1295   replace_bignum(&rsa->e, &tmp->e);
1296   replace_bignum(&rsa->d, &tmp->d);
1297   replace_bignum(&rsa->p, &tmp->p);
1298   replace_bignum(&rsa->q, &tmp->q);
1299   replace_bignum(&rsa->dmp1, &tmp->dmp1);
1300   replace_bignum(&rsa->dmq1, &tmp->dmq1);
1301   replace_bignum(&rsa->iqmp, &tmp->iqmp);
1302   replace_bn_mont_ctx(&rsa->mont_n, &tmp->mont_n);
1303   replace_bn_mont_ctx(&rsa->mont_p, &tmp->mont_p);
1304   replace_bn_mont_ctx(&rsa->mont_q, &tmp->mont_q);
1305   replace_bignum(&rsa->d_fixed, &tmp->d_fixed);
1306   replace_bignum(&rsa->dmp1_fixed, &tmp->dmp1_fixed);
1307   replace_bignum(&rsa->dmq1_fixed, &tmp->dmq1_fixed);
1308   replace_bignum(&rsa->iqmp_mont, &tmp->iqmp_mont);
1309   rsa->private_key_frozen = tmp->private_key_frozen;
1310   ret = 1;
1311 
1312 out:
1313   RSA_free(tmp);
1314   return ret;
1315 }
1316 
RSA_generate_key_ex(RSA * rsa,int bits,const BIGNUM * e_value,BN_GENCB * cb)1317 int RSA_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e_value,
1318                         BN_GENCB *cb) {
1319   return RSA_generate_key_ex_maybe_fips(rsa, bits, e_value, cb,
1320                                         /*check_fips=*/0);
1321 }
1322 
RSA_generate_key_fips(RSA * rsa,int bits,BN_GENCB * cb)1323 int RSA_generate_key_fips(RSA *rsa, int bits, BN_GENCB *cb) {
1324   // FIPS 186-4 allows 2048-bit and 3072-bit RSA keys (1024-bit and 1536-bit
1325   // primes, respectively) with the prime generation method we use.
1326   // Subsequently, IG A.14 stated that larger modulus sizes can be used and ACVP
1327   // testing supports 4096 bits.
1328   if (bits != 2048 && bits != 3072 && bits != 4096) {
1329     OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS);
1330     return 0;
1331   }
1332 
1333   BIGNUM *e = BN_new();
1334   int ret = e != NULL &&
1335             BN_set_word(e, RSA_F4) &&
1336             RSA_generate_key_ex_maybe_fips(rsa, bits, e, cb, /*check_fips=*/1);
1337   BN_free(e);
1338 
1339   if (ret) {
1340     FIPS_service_indicator_update_state();
1341   }
1342   return ret;
1343 }
1344 
DEFINE_METHOD_FUNCTION(RSA_METHOD,RSA_default_method)1345 DEFINE_METHOD_FUNCTION(RSA_METHOD, RSA_default_method) {
1346   // All of the methods are NULL to make it easier for the compiler/linker to
1347   // drop unused functions. The wrapper functions will select the appropriate
1348   // |rsa_default_*| implementation.
1349   OPENSSL_memset(out, 0, sizeof(RSA_METHOD));
1350   out->common.is_static = 1;
1351 }
1352