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