Debian Codegraph @

external/boringssl/crypto/rsa/rsa_impl.c

raw
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 <string.h>
61
62 #include <openssl/bn.h>
63 #include <openssl/err.h>
64 #include <openssl/mem.h>
65 #include <openssl/thread.h>
66
67 #include "internal.h"
68 #include "../internal.h"
69
70
71 static int check_modulus_and_exponent_sizes(const RSA *rsa) {
72 unsigned rsa_bits = BN_num_bits(rsa->n);
73
74 if (rsa_bits > 16 * 1024) {
75 OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE);
76 return 0;
77 }
78
79 /* Mitigate DoS attacks by limiting the exponent size. 33 bits was chosen as
80 * the limit based on the recommendations in [1] and [2]. Windows CryptoAPI
81 * doesn't support values larger than 32 bits [3], so it is unlikely that
82 * exponents larger than 32 bits are being used for anything Windows commonly
83 * does.
84 *
85 * [1] https://www.imperialviolet.org/2012/03/16/rsae.html
86 * [2] https://www.imperialviolet.org/2012/03/17/rsados.html
87 * [3] https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx */
88 static const unsigned kMaxExponentBits = 33;
89
90 if (BN_num_bits(rsa->e) > kMaxExponentBits) {
91 OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
92 return 0;
93 }
94
95 /* Verify |n > e|. Comparing |rsa_bits| to |kMaxExponentBits| is a small
96 * shortcut to comparing |n| and |e| directly. In reality, |kMaxExponentBits|
97 * is much smaller than the minimum RSA key size that any application should
98 * accept. */
99 if (rsa_bits <= kMaxExponentBits) {
100 OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
101 return 0;
102 }
103 assert(BN_ucmp(rsa->n, rsa->e) > 0);
104
105 return 1;
106 }
107
108 size_t rsa_default_size(const RSA *rsa) {
109 return BN_num_bytes(rsa->n);
110 }
111
112 int rsa_default_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
113 const uint8_t *in, size_t in_len, int padding) {
114 const unsigned rsa_size = RSA_size(rsa);
115 BIGNUM *f, *result;
116 uint8_t *buf = NULL;
117 BN_CTX *ctx = NULL;
118 int i, ret = 0;
119
120 if (max_out < rsa_size) {
121 OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
122 return 0;
123 }
124
125 if (!check_modulus_and_exponent_sizes(rsa)) {
126 return 0;
127 }
128
129 ctx = BN_CTX_new();
130 if (ctx == NULL) {
131 goto err;
132 }
133
134 BN_CTX_start(ctx);
135 f = BN_CTX_get(ctx);
136 result = BN_CTX_get(ctx);
137 buf = OPENSSL_malloc(rsa_size);
138 if (!f || !result || !buf) {
139 OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
140 goto err;
141 }
142
143 switch (padding) {
144 case RSA_PKCS1_PADDING:
145 i = RSA_padding_add_PKCS1_type_2(buf, rsa_size, in, in_len);
146 break;
147 case RSA_PKCS1_OAEP_PADDING:
148 /* Use the default parameters: SHA-1 for both hashes and no label. */
149 i = RSA_padding_add_PKCS1_OAEP_mgf1(buf, rsa_size, in, in_len,
150 NULL, 0, NULL, NULL);
151 break;
152 case RSA_NO_PADDING:
153 i = RSA_padding_add_none(buf, rsa_size, in, in_len);
154 break;
155 default:
156 OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
157 goto err;
158 }
159
160 if (i <= 0) {
161 goto err;
162 }
163
164 if (BN_bin2bn(buf, rsa_size, f) == NULL) {
165 goto err;
166 }
167
168 if (BN_ucmp(f, rsa->n) >= 0) {
169 /* usually the padding functions would catch this */
170 OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
171 goto err;
172 }
173
174 if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
175 !BN_mod_exp_mont(result, f, rsa->e, rsa->n, ctx, rsa->mont_n)) {
176 goto err;
177 }
178
179 /* put in leading 0 bytes if the number is less than the length of the
180 * modulus */
181 if (!BN_bn2bin_padded(out, rsa_size, result)) {
182 OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
183 goto err;
184 }
185
186 *out_len = rsa_size;
187 ret = 1;
188
189 err:
190 if (ctx != NULL) {
191 BN_CTX_end(ctx);
192 BN_CTX_free(ctx);
193 }
194 if (buf != NULL) {
195 OPENSSL_cleanse(buf, rsa_size);
196 OPENSSL_free(buf);
197 }
198
199 return ret;
200 }
201
202 /* MAX_BLINDINGS_PER_RSA defines the maximum number of cached BN_BLINDINGs per
203 * RSA*. Then this limit is exceeded, BN_BLINDING objects will be created and
204 * destroyed as needed. */
205 #define MAX_BLINDINGS_PER_RSA 1024
206
207 /* rsa_blinding_get returns a BN_BLINDING to use with |rsa|. It does this by
208 * allocating one of the cached BN_BLINDING objects in |rsa->blindings|. If
209 * none are free, the cache will be extended by a extra element and the new
210 * BN_BLINDING is returned.
211 *
212 * On success, the index of the assigned BN_BLINDING is written to
213 * |*index_used| and must be passed to |rsa_blinding_release| when finished. */
214 static BN_BLINDING *rsa_blinding_get(RSA *rsa, unsigned *index_used,
215 BN_CTX *ctx) {
216 assert(ctx != NULL);
217 assert(rsa->mont_n != NULL);
218
219 BN_BLINDING *ret = NULL;
220 BN_BLINDING **new_blindings;
221 uint8_t *new_blindings_inuse;
222 char overflow = 0;
223
224 CRYPTO_MUTEX_lock_write(&rsa->lock);
225
226 unsigned i;
227 for (i = 0; i < rsa->num_blindings; i++) {
228 if (rsa->blindings_inuse[i] == 0) {
229 rsa->blindings_inuse[i] = 1;
230 ret = rsa->blindings[i];
231 *index_used = i;
232 break;
233 }
234 }
235
236 if (ret != NULL) {
237 CRYPTO_MUTEX_unlock_write(&rsa->lock);
238 return ret;
239 }
240
241 overflow = rsa->num_blindings >= MAX_BLINDINGS_PER_RSA;
242
243 /* We didn't find a free BN_BLINDING to use so increase the length of
244 * the arrays by one and use the newly created element. */
245
246 CRYPTO_MUTEX_unlock_write(&rsa->lock);
247 ret = BN_BLINDING_new();
248 if (ret == NULL) {
249 return NULL;
250 }
251
252 if (overflow) {
253 /* We cannot add any more cached BN_BLINDINGs so we use |ret|
254 * and mark it for destruction in |rsa_blinding_release|. */
255 *index_used = MAX_BLINDINGS_PER_RSA;
256 return ret;
257 }
258
259 CRYPTO_MUTEX_lock_write(&rsa->lock);
260
261 new_blindings =
262 OPENSSL_malloc(sizeof(BN_BLINDING *) * (rsa->num_blindings + 1));
263 if (new_blindings == NULL) {
264 goto err1;
265 }
266 memcpy(new_blindings, rsa->blindings,
267 sizeof(BN_BLINDING *) * rsa->num_blindings);
268 new_blindings[rsa->num_blindings] = ret;
269
270 new_blindings_inuse = OPENSSL_malloc(rsa->num_blindings + 1);
271 if (new_blindings_inuse == NULL) {
272 goto err2;
273 }
274 memcpy(new_blindings_inuse, rsa->blindings_inuse, rsa->num_blindings);
275 new_blindings_inuse[rsa->num_blindings] = 1;
276 *index_used = rsa->num_blindings;
277
278 OPENSSL_free(rsa->blindings);
279 rsa->blindings = new_blindings;
280 OPENSSL_free(rsa->blindings_inuse);
281 rsa->blindings_inuse = new_blindings_inuse;
282 rsa->num_blindings++;
283
284 CRYPTO_MUTEX_unlock_write(&rsa->lock);
285 return ret;
286
287 err2:
288 OPENSSL_free(new_blindings);
289
290 err1:
291 CRYPTO_MUTEX_unlock_write(&rsa->lock);
292 BN_BLINDING_free(ret);
293 return NULL;
294 }
295
296 /* rsa_blinding_release marks the cached BN_BLINDING at the given index as free
297 * for other threads to use. */
298 static void rsa_blinding_release(RSA *rsa, BN_BLINDING *blinding,
299 unsigned blinding_index) {
300 if (blinding_index == MAX_BLINDINGS_PER_RSA) {
301 /* This blinding wasn't cached. */
302 BN_BLINDING_free(blinding);
303 return;
304 }
305
306 CRYPTO_MUTEX_lock_write(&rsa->lock);
307 rsa->blindings_inuse[blinding_index] = 0;
308 CRYPTO_MUTEX_unlock_write(&rsa->lock);
309 }
310
311 /* signing */
312 int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out,
313 size_t max_out, const uint8_t *in, size_t in_len,
314 int padding) {
315 const unsigned rsa_size = RSA_size(rsa);
316 uint8_t *buf = NULL;
317 int i, ret = 0;
318
319 if (max_out < rsa_size) {
320 OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
321 return 0;
322 }
323
324 buf = OPENSSL_malloc(rsa_size);
325 if (buf == NULL) {
326 OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
327 goto err;
328 }
329
330 switch (padding) {
331 case RSA_PKCS1_PADDING:
332 i = RSA_padding_add_PKCS1_type_1(buf, rsa_size, in, in_len);
333 break;
334 case RSA_NO_PADDING:
335 i = RSA_padding_add_none(buf, rsa_size, in, in_len);
336 break;
337 default:
338 OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
339 goto err;
340 }
341
342 if (i <= 0) {
343 goto err;
344 }
345
346 if (!RSA_private_transform(rsa, out, buf, rsa_size)) {
347 goto err;
348 }
349
350 *out_len = rsa_size;
351 ret = 1;
352
353 err:
354 if (buf != NULL) {
355 OPENSSL_cleanse(buf, rsa_size);
356 OPENSSL_free(buf);
357 }
358
359 return ret;
360 }
361
362 int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
363 const uint8_t *in, size_t in_len, int padding) {
364 const unsigned rsa_size = RSA_size(rsa);
365 int r = -1;
366 uint8_t *buf = NULL;
367 int ret = 0;
368
369 if (max_out < rsa_size) {
370 OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
371 return 0;
372 }
373
374 if (padding == RSA_NO_PADDING) {
375 buf = out;
376 } else {
377 /* Allocate a temporary buffer to hold the padded plaintext. */
378 buf = OPENSSL_malloc(rsa_size);
379 if (buf == NULL) {
380 OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
381 goto err;
382 }
383 }
384
385 if (in_len != rsa_size) {
386 OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
387 goto err;
388 }
389
390 if (!RSA_private_transform(rsa, buf, in, rsa_size)) {
391 goto err;
392 }
393
394 switch (padding) {
395 case RSA_PKCS1_PADDING:
396 r = RSA_padding_check_PKCS1_type_2(out, rsa_size, buf, rsa_size);
397 break;
398 case RSA_PKCS1_OAEP_PADDING:
399 /* Use the default parameters: SHA-1 for both hashes and no label. */
400 r = RSA_padding_check_PKCS1_OAEP_mgf1(out, rsa_size, buf, rsa_size,
401 NULL, 0, NULL, NULL);
402 break;
403 case RSA_NO_PADDING:
404 r = rsa_size;
405 break;
406 default:
407 OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
408 goto err;
409 }
410
411 if (r < 0) {
412 OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
413 } else {
414 *out_len = r;
415 ret = 1;
416 }
417
418 err:
419 if (padding != RSA_NO_PADDING && buf != NULL) {
420 OPENSSL_cleanse(buf, rsa_size);
421 OPENSSL_free(buf);
422 }
423
424 return ret;
425 }
426
427 static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
428
429 int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
430 const uint8_t *in, size_t in_len, int padding) {
431 if (rsa->n == NULL || rsa->e == NULL) {
432 OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
433 return 0;
434 }
435
436 const unsigned rsa_size = RSA_size(rsa);
437 BIGNUM *f, *result;
438 int r = -1;
439
440 if (max_out < rsa_size) {
441 OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
442 return 0;
443 }
444
445 if (in_len != rsa_size) {
446 OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
447 return 0;
448 }
449
450 if (!check_modulus_and_exponent_sizes(rsa)) {
451 return 0;
452 }
453
454 BN_CTX *ctx = BN_CTX_new();
455 if (ctx == NULL) {
456 return 0;
457 }
458
459 int ret = 0;
460 uint8_t *buf = NULL;
461
462 BN_CTX_start(ctx);
463 f = BN_CTX_get(ctx);
464 result = BN_CTX_get(ctx);
465 if (f == NULL || result == NULL) {
466 OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
467 goto err;
468 }
469
470 if (padding == RSA_NO_PADDING) {
471 buf = out;
472 } else {
473 /* Allocate a temporary buffer to hold the padded plaintext. */
474 buf = OPENSSL_malloc(rsa_size);
475 if (buf == NULL) {
476 OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
477 goto err;
478 }
479 }
480
481 if (BN_bin2bn(in, in_len, f) == NULL) {
482 goto err;
483 }
484
485 if (BN_ucmp(f, rsa->n) >= 0) {
486 OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
487 goto err;
488 }
489
490 if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
491 !BN_mod_exp_mont(result, f, rsa->e, rsa->n, ctx, rsa->mont_n)) {
492 goto err;
493 }
494
495 if (!BN_bn2bin_padded(buf, rsa_size, result)) {
496 OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
497 goto err;
498 }
499
500 switch (padding) {
501 case RSA_PKCS1_PADDING:
502 r = RSA_padding_check_PKCS1_type_1(out, rsa_size, buf, rsa_size);
503 break;
504 case RSA_NO_PADDING:
505 r = rsa_size;
506 break;
507 default:
508 OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
509 goto err;
510 }
511
512 if (r < 0) {
513 OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
514 } else {
515 *out_len = r;
516 ret = 1;
517 }
518
519 err:
520 BN_CTX_end(ctx);
521 BN_CTX_free(ctx);
522 if (buf != out) {
523 OPENSSL_free(buf);
524 }
525 return ret;
526 }
527
528 int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
529 size_t len) {
530 BIGNUM *f, *result;
531 BN_CTX *ctx = NULL;
532 unsigned blinding_index = 0;
533 BN_BLINDING *blinding = NULL;
534 int ret = 0;
535
536 ctx = BN_CTX_new();
537 if (ctx == NULL) {
538 goto err;
539 }
540 BN_CTX_start(ctx);
541 f = BN_CTX_get(ctx);
542 result = BN_CTX_get(ctx);
543
544 if (f == NULL || result == NULL) {
545 OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
546 goto err;
547 }
548
549 if (BN_bin2bn(in, len, f) == NULL) {
550 goto err;
551 }
552
553 if (BN_ucmp(f, rsa->n) >= 0) {
554 /* Usually the padding functions would catch this. */
555 OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
556 goto err;
557 }
558
559 if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx)) {
560 OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
561 goto err;
562 }
563
564 /* We cannot do blinding or verification without |e|, and continuing without
565 * those countermeasures is dangerous. However, the Java/Android RSA API
566 * requires support for keys where only |d| and |n| (and not |e|) are known.
567 * The callers that require that bad behavior set |RSA_FLAG_NO_BLINDING|. */
568 int disable_security = (rsa->flags & RSA_FLAG_NO_BLINDING) && rsa->e == NULL;
569
570 if (!disable_security) {
571 /* Keys without public exponents must have blinding explicitly disabled to
572 * be used. */
573 if (rsa->e == NULL) {
574 OPENSSL_PUT_ERROR(RSA, RSA_R_NO_PUBLIC_EXPONENT);
575 goto err;
576 }
577
578 blinding = rsa_blinding_get(rsa, &blinding_index, ctx);
579 if (blinding == NULL) {
580 OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
581 goto err;
582 }
583 if (!BN_BLINDING_convert(f, blinding, rsa->e, rsa->mont_n, ctx)) {
584 goto err;
585 }
586 }
587
588 if (rsa->p != NULL && rsa->q != NULL && rsa->e != NULL && rsa->dmp1 != NULL &&
589 rsa->dmq1 != NULL && rsa->iqmp != NULL) {
590 if (!mod_exp(result, f, rsa, ctx)) {
591 goto err;
592 }
593 } else {
594 BIGNUM local_d;
595 BIGNUM *d = NULL;
596
597 BN_init(&local_d);
598 d = &local_d;
599 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
600
601 if (!BN_mod_exp_mont_consttime(result, f, d, rsa->n, ctx, rsa->mont_n)) {
602 goto err;
603 }
604 }
605
606 /* Verify the result to protect against fault attacks as described in the
607 * 1997 paper "On the Importance of Checking Cryptographic Protocols for
608 * Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton. Some
609 * implementations do this only when the CRT is used, but we do it in all
610 * cases. Section 6 of the aforementioned paper describes an attack that
611 * works when the CRT isn't used. That attack is much less likely to succeed
612 * than the CRT attack, but there have likely been improvements since 1997.
613 *
614 * This check is cheap assuming |e| is small; it almost always is. */
615 if (!disable_security) {
616 BIGNUM *vrfy = BN_CTX_get(ctx);
617 if (vrfy == NULL ||
618 !BN_mod_exp_mont(vrfy, result, rsa->e, rsa->n, ctx, rsa->mont_n) ||
619 !BN_equal_consttime(vrfy, f)) {
620 OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
621 goto err;
622 }
623
624 if (!BN_BLINDING_invert(result, blinding, rsa->mont_n, ctx)) {
625 goto err;
626 }
627 }
628
629 if (!BN_bn2bin_padded(out, len, result)) {
630 OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
631 goto err;
632 }
633
634 ret = 1;
635
636 err:
637 if (ctx != NULL) {
638 BN_CTX_end(ctx);
639 BN_CTX_free(ctx);
640 }
641 if (blinding != NULL) {
642 rsa_blinding_release(rsa, blinding, blinding_index);
643 }
644
645 return ret;
646 }
647
648 static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) {
649 assert(ctx != NULL);
650
651 assert(rsa->n != NULL);
652 assert(rsa->e != NULL);
653 assert(rsa->d != NULL);
654 assert(rsa->p != NULL);
655 assert(rsa->q != NULL);
656 assert(rsa->dmp1 != NULL);
657 assert(rsa->dmq1 != NULL);
658 assert(rsa->iqmp != NULL);
659
660 BIGNUM *r1, *m1, *vrfy;
661 BIGNUM local_dmp1, local_dmq1, local_c, local_r1;
662 BIGNUM *dmp1, *dmq1, *c, *pr1;
663 int ret = 0;
664 size_t i, num_additional_primes = 0;
665
666 if (rsa->additional_primes != NULL) {
667 num_additional_primes = sk_RSA_additional_prime_num(rsa->additional_primes);
668 }
669
670 BN_CTX_start(ctx);
671 r1 = BN_CTX_get(ctx);
672 m1 = BN_CTX_get(ctx);
673 vrfy = BN_CTX_get(ctx);
674 if (r1 == NULL ||
675 m1 == NULL ||
676 vrfy == NULL) {
677 goto err;
678 }
679
680 {
681 BIGNUM local_p, local_q;
682 BIGNUM *p = NULL, *q = NULL;
683
684 /* Make sure BN_mod_inverse in Montgomery intialization uses the
685 * BN_FLG_CONSTTIME flag. */
686 BN_init(&local_p);
687 p = &local_p;
688 BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
689
690 BN_init(&local_q);
691 q = &local_q;
692 BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
693
694 if (!BN_MONT_CTX_set_locked(&rsa->mont_p, &rsa->lock, p, ctx) ||
695 !BN_MONT_CTX_set_locked(&rsa->mont_q, &rsa->lock, q, ctx)) {
696 goto err;
697 }
698 }
699
700 if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx)) {
701 goto err;
702 }
703
704 /* compute I mod q */
705 c = &local_c;
706 BN_with_flags(c, I, BN_FLG_CONSTTIME);
707 if (!BN_mod(r1, c, rsa->q, ctx)) {
708 goto err;
709 }
710
711 /* compute r1^dmq1 mod q */
712 dmq1 = &local_dmq1;
713 BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
714 if (!BN_mod_exp_mont_consttime(m1, r1, dmq1, rsa->q, ctx, rsa->mont_q)) {
715 goto err;
716 }
717
718 /* compute I mod p */
719 c = &local_c;
720 BN_with_flags(c, I, BN_FLG_CONSTTIME);
721 if (!BN_mod(r1, c, rsa->p, ctx)) {
722 goto err;
723 }
724
725 /* compute r1^dmp1 mod p */
726 dmp1 = &local_dmp1;
727 BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
728 if (!BN_mod_exp_mont_consttime(r0, r1, dmp1, rsa->p, ctx, rsa->mont_p)) {
729 goto err;
730 }
731
732 if (!BN_sub(r0, r0, m1)) {
733 goto err;
734 }
735 /* This will help stop the size of r0 increasing, which does
736 * affect the multiply if it optimised for a power of 2 size */
737 if (BN_is_negative(r0)) {
738 if (!BN_add(r0, r0, rsa->p)) {
739 goto err;
740 }
741 }
742
743 if (!BN_mul(r1, r0, rsa->iqmp, ctx)) {
744 goto err;
745 }
746
747 /* Turn BN_FLG_CONSTTIME flag on before division operation */
748 pr1 = &local_r1;
749 BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
750
751 if (!BN_mod(r0, pr1, rsa->p, ctx)) {
752 goto err;
753 }
754
755 /* If p < q it is occasionally possible for the correction of
756 * adding 'p' if r0 is negative above to leave the result still
757 * negative. This can break the private key operations: the following
758 * second correction should *always* correct this rare occurrence.
759 * This will *never* happen with OpenSSL generated keys because
760 * they ensure p > q [steve] */
761 if (BN_is_negative(r0)) {
762 if (!BN_add(r0, r0, rsa->p)) {
763 goto err;
764 }
765 }
766 if (!BN_mul(r1, r0, rsa->q, ctx)) {
767 goto err;
768 }
769 if (!BN_add(r0, r1, m1)) {
770 goto err;
771 }
772
773 for (i = 0; i < num_additional_primes; i++) {
774 /* multi-prime RSA. */
775 BIGNUM local_exp, local_prime;
776 BIGNUM *exp = &local_exp, *prime = &local_prime;
777 RSA_additional_prime *ap =
778 sk_RSA_additional_prime_value(rsa->additional_primes, i);
779
780 BN_with_flags(exp, ap->exp, BN_FLG_CONSTTIME);
781 BN_with_flags(prime, ap->prime, BN_FLG_CONSTTIME);
782
783 /* c will already point to a BIGNUM with the correct flags. */
784 if (!BN_mod(r1, c, prime, ctx)) {
785 goto err;
786 }
787
788 if (!BN_MONT_CTX_set_locked(&ap->mont, &rsa->lock, prime, ctx) ||
789 !BN_mod_exp_mont_consttime(m1, r1, exp, prime, ctx, ap->mont)) {
790 goto err;
791 }
792
793 BN_set_flags(m1, BN_FLG_CONSTTIME);
794
795 if (!BN_sub(m1, m1, r0) ||
796 !BN_mul(m1, m1, ap->coeff, ctx) ||
797 !BN_mod(m1, m1, prime, ctx) ||
798 (BN_is_negative(m1) && !BN_add(m1, m1, prime)) ||
799 !BN_mul(m1, m1, ap->r, ctx) ||
800 !BN_add(r0, r0, m1)) {
801 goto err;
802 }
803 }
804
805 ret = 1;
806
807 err:
808 BN_CTX_end(ctx);
809 return ret;
810 }
811
812 int rsa_default_multi_prime_keygen(RSA *rsa, int bits, int num_primes,
813 BIGNUM *e_value, BN_GENCB *cb) {
814 BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp;
815 BIGNUM local_r0, local_d, local_p;
816 BIGNUM *pr0, *d, *p;
817 int prime_bits, ok = -1, n = 0, i, j;
818 BN_CTX *ctx = NULL;
819 STACK_OF(RSA_additional_prime) *additional_primes = NULL;
820
821 if (num_primes < 2) {
822 ok = 0; /* we set our own err */
823 OPENSSL_PUT_ERROR(RSA, RSA_R_MUST_HAVE_AT_LEAST_TWO_PRIMES);
824 goto err;
825 }
826
827 ctx = BN_CTX_new();
828 if (ctx == NULL) {
829 goto err;
830 }
831 BN_CTX_start(ctx);
832 r0 = BN_CTX_get(ctx);
833 r1 = BN_CTX_get(ctx);
834 r2 = BN_CTX_get(ctx);
835 r3 = BN_CTX_get(ctx);
836 if (r0 == NULL || r1 == NULL || r2 == NULL || r3 == NULL) {
837 goto err;
838 }
839
840 if (num_primes > 2) {
841 additional_primes = sk_RSA_additional_prime_new_null();
842 if (additional_primes == NULL) {
843 goto err;
844 }
845 }
846
847 for (i = 2; i < num_primes; i++) {
848 RSA_additional_prime *ap = OPENSSL_malloc(sizeof(RSA_additional_prime));
849 if (ap == NULL) {
850 goto err;
851 }
852 memset(ap, 0, sizeof(RSA_additional_prime));
853 ap->prime = BN_new();
854 ap->exp = BN_new();
855 ap->coeff = BN_new();
856 ap->r = BN_new();
857 if (ap->prime == NULL ||
858 ap->exp == NULL ||
859 ap->coeff == NULL ||
860 ap->r == NULL ||
861 !sk_RSA_additional_prime_push(additional_primes, ap)) {
862 RSA_additional_prime_free(ap);
863 goto err;
864 }
865 }
866
867 /* We need the RSA components non-NULL */
868 if (!rsa->n && ((rsa->n = BN_new()) == NULL)) {
869 goto err;
870 }
871 if (!rsa->d && ((rsa->d = BN_new()) == NULL)) {
872 goto err;
873 }
874 if (!rsa->e && ((rsa->e = BN_new()) == NULL)) {
875 goto err;
876 }
877 if (!rsa->p && ((rsa->p = BN_new()) == NULL)) {
878 goto err;
879 }
880 if (!rsa->q && ((rsa->q = BN_new()) == NULL)) {
881 goto err;
882 }
883 if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL)) {
884 goto err;
885 }
886 if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL)) {
887 goto err;
888 }
889 if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL)) {
890 goto err;
891 }
892
893 if (!BN_copy(rsa->e, e_value)) {
894 goto err;
895 }
896
897 /* generate p and q */
898 prime_bits = (bits + (num_primes - 1)) / num_primes;
899 for (;;) {
900 if (!BN_generate_prime_ex(rsa->p, prime_bits, 0, NULL, NULL, cb) ||
901 !BN_sub(r2, rsa->p, BN_value_one()) ||
902 !BN_gcd(r1, r2, rsa->e, ctx)) {
903 goto err;
904 }
905 if (BN_is_one(r1)) {
906 break;
907 }
908 if (!BN_GENCB_call(cb, 2, n++)) {
909 goto err;
910 }
911 }
912 if (!BN_GENCB_call(cb, 3, 0)) {
913 goto err;
914 }
915 prime_bits = ((bits - prime_bits) + (num_primes - 2)) / (num_primes - 1);
916 for (;;) {
917 /* When generating ridiculously small keys, we can get stuck
918 * continually regenerating the same prime values. Check for
919 * this and bail if it happens 3 times. */
920 unsigned int degenerate = 0;
921 do {
922 if (!BN_generate_prime_ex(rsa->q, prime_bits, 0, NULL, NULL, cb)) {
923 goto err;
924 }
925 } while ((BN_cmp(rsa->p, rsa->q) == 0) && (++degenerate < 3));
926 if (degenerate == 3) {
927 ok = 0; /* we set our own err */
928 OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
929 goto err;
930 }
931 if (!BN_sub(r2, rsa->q, BN_value_one()) ||
932 !BN_gcd(r1, r2, rsa->e, ctx)) {
933 goto err;
934 }
935 if (BN_is_one(r1)) {
936 break;
937 }
938 if (!BN_GENCB_call(cb, 2, n++)) {
939 goto err;
940 }
941 }
942
943 if (!BN_GENCB_call(cb, 3, 1) ||
944 !BN_mul(rsa->n, rsa->p, rsa->q, ctx)) {
945 goto err;
946 }
947
948 for (i = 2; i < num_primes; i++) {
949 RSA_additional_prime *ap =
950 sk_RSA_additional_prime_value(additional_primes, i - 2);
951 prime_bits = ((bits - BN_num_bits(rsa->n)) + (num_primes - (i + 1))) /
952 (num_primes - i);
953
954 for (;;) {
955 if (!BN_generate_prime_ex(ap->prime, prime_bits, 0, NULL, NULL, cb)) {
956 goto err;
957 }
958 if (BN_cmp(rsa->p, ap->prime) == 0 ||
959 BN_cmp(rsa->q, ap->prime) == 0) {
960 continue;
961 }
962
963 for (j = 0; j < i - 2; j++) {
964 if (BN_cmp(sk_RSA_additional_prime_value(additional_primes, j)->prime,
965 ap->prime) == 0) {
966 break;
967 }
968 }
969 if (j != i - 2) {
970 continue;
971 }
972
973 if (!BN_sub(r2, ap->prime, BN_value_one()) ||
974 !BN_gcd(r1, r2, rsa->e, ctx)) {
975 goto err;
976 }
977
978 if (!BN_is_one(r1)) {
979 continue;
980 }
981 if (i != num_primes - 1) {
982 break;
983 }
984
985 /* For the last prime we'll check that it makes n large enough. In the
986 * two prime case this isn't a problem because we generate primes with
987 * the top two bits set and so the product is always of the expected
988 * size. In the multi prime case, this doesn't follow. */
989 if (!BN_mul(r1, rsa->n, ap->prime, ctx)) {
990 goto err;
991 }
992 if (BN_num_bits(r1) == (unsigned) bits) {
993 break;
994 }
995
996 if (!BN_GENCB_call(cb, 2, n++)) {
997 goto err;
998 }
999 }
1000
1001 /* ap->r is is the product of all the primes prior to the current one
1002 * (including p and q). */
1003 if (!BN_copy(ap->r, rsa->n)) {
1004 goto err;
1005 }
1006 if (i == num_primes - 1) {
1007 /* In the case of the last prime, we calculated n as |r1| in the loop
1008 * above. */
1009 if (!BN_copy(rsa->n, r1)) {
1010 goto err;
1011 }
1012 } else if (!BN_mul(rsa->n, rsa->n, ap->prime, ctx)) {
1013 goto err;
1014 }
1015
1016 if (!BN_GENCB_call(cb, 3, 1)) {
1017 goto err;
1018 }
1019 }
1020
1021 if (BN_cmp(rsa->p, rsa->q) < 0) {
1022 tmp = rsa->p;
1023 rsa->p = rsa->q;
1024 rsa->q = tmp;
1025 }
1026
1027 /* calculate d */
1028 if (!BN_sub(r1, rsa->p, BN_value_one())) {
1029 goto err; /* p-1 */
1030 }
1031 if (!BN_sub(r2, rsa->q, BN_value_one())) {
1032 goto err; /* q-1 */
1033 }
1034 if (!BN_mul(r0, r1, r2, ctx)) {
1035 goto err; /* (p-1)(q-1) */
1036 }
1037 for (i = 2; i < num_primes; i++) {
1038 RSA_additional_prime *ap =
1039 sk_RSA_additional_prime_value(additional_primes, i - 2);
1040 if (!BN_sub(r3, ap->prime, BN_value_one()) ||
1041 !BN_mul(r0, r0, r3, ctx)) {
1042 goto err;
1043 }
1044 }
1045 pr0 = &local_r0;
1046 BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
1047 if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
1048 goto err; /* d */
1049 }
1050
1051 /* set up d for correct BN_FLG_CONSTTIME flag */
1052 d = &local_d;
1053 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
1054
1055 /* calculate d mod (p-1) */
1056 if (!BN_mod(rsa->dmp1, d, r1, ctx)) {
1057 goto err;
1058 }
1059
1060 /* calculate d mod (q-1) */
1061 if (!BN_mod(rsa->dmq1, d, r2, ctx)) {
1062 goto err;
1063 }
1064
1065 /* calculate inverse of q mod p */
1066 p = &local_p;
1067 BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
1068
1069 if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
1070 goto err;
1071 }
1072
1073 for (i = 2; i < num_primes; i++) {
1074 RSA_additional_prime *ap =
1075 sk_RSA_additional_prime_value(additional_primes, i - 2);
1076 if (!BN_sub(ap->exp, ap->prime, BN_value_one()) ||
1077 !BN_mod(ap->exp, rsa->d, ap->exp, ctx) ||
1078 !BN_mod_inverse(ap->coeff, ap->r, ap->prime, ctx)) {
1079 goto err;
1080 }
1081 }
1082
1083 ok = 1;
1084 rsa->additional_primes = additional_primes;
1085 additional_primes = NULL;
1086
1087 err:
1088 if (ok == -1) {
1089 OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
1090 ok = 0;
1091 }
1092 if (ctx != NULL) {
1093 BN_CTX_end(ctx);
1094 BN_CTX_free(ctx);
1095 }
1096 sk_RSA_additional_prime_pop_free(additional_primes,
1097 RSA_additional_prime_free);
1098 return ok;
1099 }
1100
1101 int rsa_default_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) {
1102 return rsa_default_multi_prime_keygen(rsa, bits, 2 /* num primes */, e_value,
1103 cb);
1104 }
1105
1106 /* All of the methods are NULL to make it easier for the compiler/linker to drop
1107 * unused functions. The wrapper functions will select the appropriate
1108 * |rsa_default_*| implementation. */
1109 const RSA_METHOD RSA_default_method = {
1110 {
1111 0 /* references */,
1112 1 /* is_static */,
1113 },
1114 NULL /* app_data */,
1115
1116 NULL /* init */,
1117 NULL /* finish (defaults to rsa_default_finish) */,
1118
1119 NULL /* size (defaults to rsa_default_size) */,
1120
1121 NULL /* sign */,
1122 NULL /* verify */,
1123
1124 NULL /* encrypt (defaults to rsa_default_encrypt) */,
1125 NULL /* sign_raw (defaults to rsa_default_sign_raw) */,
1126 NULL /* decrypt (defaults to rsa_default_decrypt) */,
1127 NULL /* verify_raw (defaults to rsa_default_verify_raw) */,
1128
1129 NULL /* private_transform (defaults to rsa_default_private_transform) */,
1130
1131 NULL /* mod_exp (ignored) */,
1132 NULL /* bn_mod_exp (ignored) */,
1133
1134 RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE,
1135
1136 NULL /* keygen (defaults to rsa_default_keygen) */,
1137 NULL /* multi_prime_keygen (defaults to rsa_default_multi_prime_keygen) */,
1138
1139 NULL /* supports_digest */,
1140 };