Coverage Report

Created: 2023-03-26 07:25

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