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