1// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <openssl/rsa.h>
16
17#include <assert.h>
18#include <limits.h>
19#include <string.h>
20
21#include <openssl/bn.h>
22#include <openssl/digest.h>
23#include <openssl/engine.h>
24#include <openssl/err.h>
25#include <openssl/ex_data.h>
26#include <openssl/md5.h>
27#include <openssl/mem.h>
28#include <openssl/nid.h>
29
30#include "../../internal.h"
31#include "../bcm_interface.h"
32#include "../bn/internal.h"
33#include "../delocate.h"
34#include "internal.h"
35
36
37// RSA_R_BLOCK_TYPE_IS_NOT_02 is part of the legacy SSLv23 padding scheme.
38// Cryptography.io depends on this error code.
39OPENSSL_DECLARE_ERROR_REASON(RSA, BLOCK_TYPE_IS_NOT_02)
40
41DEFINE_STATIC_EX_DATA_CLASS(g_rsa_ex_data_class)
42
43static int bn_dup_into(BIGNUM **dst, const BIGNUM *src) {
44  if (src == NULL) {
45    OPENSSL_PUT_ERROR(RSA, ERR_R_PASSED_NULL_PARAMETER);
46    return 0;
47  }
48
49  BN_free(*dst);
50  *dst = BN_dup(src);
51  return *dst != NULL;
52}
53
54RSA *RSA_new_public_key(const BIGNUM *n, const BIGNUM *e) {
55  RSA *rsa = RSA_new();
56  if (rsa == NULL ||               //
57      !bn_dup_into(&rsa->n, n) ||  //
58      !bn_dup_into(&rsa->e, e) ||  //
59      !RSA_check_key(rsa)) {
60    RSA_free(rsa);
61    return NULL;
62  }
63
64  return rsa;
65}
66
67RSA *RSA_new_private_key(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d,
68                         const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp1,
69                         const BIGNUM *dmq1, const BIGNUM *iqmp) {
70  RSA *rsa = RSA_new();
71  if (rsa == NULL ||                     //
72      !bn_dup_into(&rsa->n, n) ||        //
73      !bn_dup_into(&rsa->e, e) ||        //
74      !bn_dup_into(&rsa->d, d) ||        //
75      !bn_dup_into(&rsa->p, p) ||        //
76      !bn_dup_into(&rsa->q, q) ||        //
77      !bn_dup_into(&rsa->dmp1, dmp1) ||  //
78      !bn_dup_into(&rsa->dmq1, dmq1) ||  //
79      !bn_dup_into(&rsa->iqmp, iqmp) ||  //
80      !RSA_check_key(rsa)) {
81    RSA_free(rsa);
82    return NULL;
83  }
84
85  return rsa;
86}
87
88RSA *RSA_new_private_key_no_crt(const BIGNUM *n, const BIGNUM *e,
89                                const BIGNUM *d) {
90  RSA *rsa = RSA_new();
91  if (rsa == NULL ||               //
92      !bn_dup_into(&rsa->n, n) ||  //
93      !bn_dup_into(&rsa->e, e) ||  //
94      !bn_dup_into(&rsa->d, d) ||  //
95      !RSA_check_key(rsa)) {
96    RSA_free(rsa);
97    return NULL;
98  }
99
100  return rsa;
101}
102
103RSA *RSA_new_private_key_no_e(const BIGNUM *n, const BIGNUM *d) {
104  RSA *rsa = RSA_new();
105  if (rsa == NULL) {
106    return NULL;
107  }
108
109  rsa->flags |= RSA_FLAG_NO_PUBLIC_EXPONENT;
110  if (!bn_dup_into(&rsa->n, n) ||  //
111      !bn_dup_into(&rsa->d, d) ||  //
112      !RSA_check_key(rsa)) {
113    RSA_free(rsa);
114    return NULL;
115  }
116
117  return rsa;
118}
119
120RSA *RSA_new_public_key_large_e(const BIGNUM *n, const BIGNUM *e) {
121  RSA *rsa = RSA_new();
122  if (rsa == NULL) {
123    return NULL;
124  }
125
126  rsa->flags |= RSA_FLAG_LARGE_PUBLIC_EXPONENT;
127  if (!bn_dup_into(&rsa->n, n) ||  //
128      !bn_dup_into(&rsa->e, e) ||  //
129      !RSA_check_key(rsa)) {
130    RSA_free(rsa);
131    return NULL;
132  }
133
134  return rsa;
135}
136
137RSA *RSA_new_private_key_large_e(const BIGNUM *n, const BIGNUM *e,
138                                 const BIGNUM *d, const BIGNUM *p,
139                                 const BIGNUM *q, const BIGNUM *dmp1,
140                                 const BIGNUM *dmq1, const BIGNUM *iqmp) {
141  RSA *rsa = RSA_new();
142  if (rsa == NULL) {
143    return NULL;
144  }
145
146  rsa->flags |= RSA_FLAG_LARGE_PUBLIC_EXPONENT;
147  if (!bn_dup_into(&rsa->n, n) ||        //
148      !bn_dup_into(&rsa->e, e) ||        //
149      !bn_dup_into(&rsa->d, d) ||        //
150      !bn_dup_into(&rsa->p, p) ||        //
151      !bn_dup_into(&rsa->q, q) ||        //
152      !bn_dup_into(&rsa->dmp1, dmp1) ||  //
153      !bn_dup_into(&rsa->dmq1, dmq1) ||  //
154      !bn_dup_into(&rsa->iqmp, iqmp) ||  //
155      !RSA_check_key(rsa)) {
156    RSA_free(rsa);
157    return NULL;
158  }
159
160  return rsa;
161}
162
163RSA *RSA_new(void) { return RSA_new_method(NULL); }
164
165RSA *RSA_new_method(const ENGINE *engine) {
166  RSA *rsa = reinterpret_cast<RSA *>(OPENSSL_zalloc(sizeof(RSA)));
167  if (rsa == NULL) {
168    return NULL;
169  }
170
171  if (engine) {
172    rsa->meth = ENGINE_get_RSA_method(engine);
173  }
174
175  if (rsa->meth == NULL) {
176    rsa->meth = (RSA_METHOD *)RSA_default_method();
177  }
178  METHOD_ref(rsa->meth);
179
180  rsa->references = 1;
181  rsa->flags = rsa->meth->flags;
182  CRYPTO_MUTEX_init(&rsa->lock);
183  CRYPTO_new_ex_data(&rsa->ex_data);
184
185  if (rsa->meth->init && !rsa->meth->init(rsa)) {
186    rsa->meth = nullptr;
187    RSA_free(rsa);
188    return NULL;
189  }
190
191  return rsa;
192}
193
194RSA *RSA_new_method_no_e(const ENGINE *engine, const BIGNUM *n) {
195  RSA *rsa = RSA_new_method(engine);
196  if (rsa == NULL || !bn_dup_into(&rsa->n, n)) {
197    RSA_free(rsa);
198    return NULL;
199  }
200  rsa->flags |= RSA_FLAG_NO_PUBLIC_EXPONENT;
201  return rsa;
202}
203
204void RSA_free(RSA *rsa) {
205  if (rsa == NULL) {
206    return;
207  }
208
209  if (!CRYPTO_refcount_dec_and_test_zero(&rsa->references)) {
210    return;
211  }
212
213  if (rsa->meth != nullptr && rsa->meth->finish != nullptr) {
214    rsa->meth->finish(rsa);
215  }
216  METHOD_unref(rsa->meth);
217
218  CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), &rsa->ex_data);
219
220  BN_free(rsa->n);
221  BN_free(rsa->e);
222  BN_free(rsa->d);
223  BN_free(rsa->p);
224  BN_free(rsa->q);
225  BN_free(rsa->dmp1);
226  BN_free(rsa->dmq1);
227  BN_free(rsa->iqmp);
228  rsa_invalidate_key(rsa);
229  CRYPTO_MUTEX_cleanup(&rsa->lock);
230  OPENSSL_free(rsa);
231}
232
233int RSA_up_ref(RSA *rsa) {
234  CRYPTO_refcount_inc(&rsa->references);
235  return 1;
236}
237
238unsigned RSA_bits(const RSA *rsa) { return BN_num_bits(rsa->n); }
239
240const BIGNUM *RSA_get0_n(const RSA *rsa) { return rsa->n; }
241
242const BIGNUM *RSA_get0_e(const RSA *rsa) { return rsa->e; }
243
244const BIGNUM *RSA_get0_d(const RSA *rsa) { return rsa->d; }
245
246const BIGNUM *RSA_get0_p(const RSA *rsa) { return rsa->p; }
247
248const BIGNUM *RSA_get0_q(const RSA *rsa) { return rsa->q; }
249
250const BIGNUM *RSA_get0_dmp1(const RSA *rsa) { return rsa->dmp1; }
251
252const BIGNUM *RSA_get0_dmq1(const RSA *rsa) { return rsa->dmq1; }
253
254const BIGNUM *RSA_get0_iqmp(const RSA *rsa) { return rsa->iqmp; }
255
256void RSA_get0_key(const RSA *rsa, const BIGNUM **out_n, const BIGNUM **out_e,
257                  const BIGNUM **out_d) {
258  if (out_n != NULL) {
259    *out_n = rsa->n;
260  }
261  if (out_e != NULL) {
262    *out_e = rsa->e;
263  }
264  if (out_d != NULL) {
265    *out_d = rsa->d;
266  }
267}
268
269void RSA_get0_factors(const RSA *rsa, const BIGNUM **out_p,
270                      const BIGNUM **out_q) {
271  if (out_p != NULL) {
272    *out_p = rsa->p;
273  }
274  if (out_q != NULL) {
275    *out_q = rsa->q;
276  }
277}
278
279const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *rsa) {
280  // We do not support the id-RSASSA-PSS key encoding. If we add support later,
281  // the |maskHash| field should be filled in for OpenSSL compatibility.
282  return NULL;
283}
284
285void RSA_get0_crt_params(const RSA *rsa, const BIGNUM **out_dmp1,
286                         const BIGNUM **out_dmq1, const BIGNUM **out_iqmp) {
287  if (out_dmp1 != NULL) {
288    *out_dmp1 = rsa->dmp1;
289  }
290  if (out_dmq1 != NULL) {
291    *out_dmq1 = rsa->dmq1;
292  }
293  if (out_iqmp != NULL) {
294    *out_iqmp = rsa->iqmp;
295  }
296}
297
298int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
299  if ((rsa->n == NULL && n == NULL) || (rsa->e == NULL && e == NULL)) {
300    return 0;
301  }
302
303  if (n != NULL) {
304    BN_free(rsa->n);
305    rsa->n = n;
306  }
307  if (e != NULL) {
308    BN_free(rsa->e);
309    rsa->e = e;
310  }
311  if (d != NULL) {
312    BN_free(rsa->d);
313    rsa->d = d;
314  }
315
316  rsa_invalidate_key(rsa);
317  return 1;
318}
319
320int RSA_set0_factors(RSA *rsa, BIGNUM *p, BIGNUM *q) {
321  if ((rsa->p == NULL && p == NULL) || (rsa->q == NULL && q == NULL)) {
322    return 0;
323  }
324
325  if (p != NULL) {
326    BN_free(rsa->p);
327    rsa->p = p;
328  }
329  if (q != NULL) {
330    BN_free(rsa->q);
331    rsa->q = q;
332  }
333
334  rsa_invalidate_key(rsa);
335  return 1;
336}
337
338int RSA_set0_crt_params(RSA *rsa, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) {
339  if ((rsa->dmp1 == NULL && dmp1 == NULL) ||
340      (rsa->dmq1 == NULL && dmq1 == NULL) ||
341      (rsa->iqmp == NULL && iqmp == NULL)) {
342    return 0;
343  }
344
345  if (dmp1 != NULL) {
346    BN_free(rsa->dmp1);
347    rsa->dmp1 = dmp1;
348  }
349  if (dmq1 != NULL) {
350    BN_free(rsa->dmq1);
351    rsa->dmq1 = dmq1;
352  }
353  if (iqmp != NULL) {
354    BN_free(rsa->iqmp);
355    rsa->iqmp = iqmp;
356  }
357
358  rsa_invalidate_key(rsa);
359  return 1;
360}
361
362static int rsa_sign_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out,
363                                     size_t max_out, const uint8_t *in,
364                                     size_t in_len, int padding) {
365  if (rsa->meth->sign_raw) {
366    return rsa->meth->sign_raw(rsa, out_len, out, max_out, in, in_len, padding);
367  }
368
369  return rsa_default_sign_raw(rsa, out_len, out, max_out, in, in_len, padding);
370}
371
372int RSA_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
373                 const uint8_t *in, size_t in_len, int padding) {
374  boringssl_ensure_rsa_self_test();
375  return rsa_sign_raw_no_self_test(rsa, out_len, out, max_out, in, in_len,
376                                   padding);
377}
378
379unsigned RSA_size(const RSA *rsa) { return BN_num_bytes(rsa->n); }
380
381int RSA_is_opaque(const RSA *rsa) {
382  return rsa->meth && (rsa->meth->flags & RSA_FLAG_OPAQUE);
383}
384
385int RSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
386                         CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
387  return CRYPTO_get_ex_new_index_ex(g_rsa_ex_data_class_bss_get(), argl, argp,
388                                    free_func);
389}
390
391int RSA_set_ex_data(RSA *rsa, int idx, void *arg) {
392  return CRYPTO_set_ex_data(&rsa->ex_data, idx, arg);
393}
394
395void *RSA_get_ex_data(const RSA *rsa, int idx) {
396  return CRYPTO_get_ex_data(&rsa->ex_data, idx);
397}
398
399// SSL_SIG_LENGTH is the size of an SSL/TLS (prior to TLS 1.2) signature: it's
400// the length of an MD5 and SHA1 hash.
401static const unsigned SSL_SIG_LENGTH = 36;
402
403// pkcs1_sig_prefix contains the ASN.1, DER encoded prefix for a hash that is
404// to be signed with PKCS#1.
405struct pkcs1_sig_prefix {
406  // nid identifies the hash function.
407  int nid;
408  // hash_len is the expected length of the hash function.
409  uint8_t hash_len;
410  // len is the number of bytes of |bytes| which are valid.
411  uint8_t len;
412  // bytes contains the DER bytes.
413  uint8_t bytes[19];
414};
415
416// kPKCS1SigPrefixes contains the ASN.1 prefixes for PKCS#1 signatures with
417// different hash functions.
418static const struct pkcs1_sig_prefix kPKCS1SigPrefixes[] = {
419    {
420        NID_md5,
421        MD5_DIGEST_LENGTH,
422        18,
423        {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
424         0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
425    },
426    {
427        NID_sha1,
428        BCM_SHA_DIGEST_LENGTH,
429        15,
430        {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05,
431         0x00, 0x04, 0x14},
432    },
433    {
434        NID_sha224,
435        BCM_SHA224_DIGEST_LENGTH,
436        19,
437        {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
438         0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
439    },
440    {
441        NID_sha256,
442        BCM_SHA256_DIGEST_LENGTH,
443        19,
444        {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
445         0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
446    },
447    {
448        NID_sha384,
449        BCM_SHA384_DIGEST_LENGTH,
450        19,
451        {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
452         0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
453    },
454    {
455        NID_sha512,
456        BCM_SHA512_DIGEST_LENGTH,
457        19,
458        {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
459         0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
460    },
461    {
462        NID_undef,
463        0,
464        0,
465        {0},
466    },
467};
468
469static int rsa_check_digest_size(int hash_nid, size_t digest_len) {
470  if (hash_nid == NID_md5_sha1) {
471    if (digest_len != SSL_SIG_LENGTH) {
472      OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
473      return 0;
474    }
475    return 1;
476  }
477
478  for (size_t i = 0; kPKCS1SigPrefixes[i].nid != NID_undef; i++) {
479    const struct pkcs1_sig_prefix *sig_prefix = &kPKCS1SigPrefixes[i];
480    if (sig_prefix->nid == hash_nid) {
481      if (digest_len != sig_prefix->hash_len) {
482        OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
483        return 0;
484      }
485      return 1;
486    }
487  }
488
489  OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
490  return 0;
491}
492
493int RSA_add_pkcs1_prefix(uint8_t **out_msg, size_t *out_msg_len,
494                         int *is_alloced, int hash_nid, const uint8_t *digest,
495                         size_t digest_len) {
496  if (!rsa_check_digest_size(hash_nid, digest_len)) {
497    return 0;
498  }
499
500  if (hash_nid == NID_md5_sha1) {
501    // The length should already have been checked.
502    assert(digest_len == SSL_SIG_LENGTH);
503    *out_msg = (uint8_t *)digest;
504    *out_msg_len = digest_len;
505    *is_alloced = 0;
506    return 1;
507  }
508
509  for (size_t i = 0; kPKCS1SigPrefixes[i].nid != NID_undef; i++) {
510    const struct pkcs1_sig_prefix *sig_prefix = &kPKCS1SigPrefixes[i];
511    if (sig_prefix->nid != hash_nid) {
512      continue;
513    }
514
515    // The length should already have been checked.
516    assert(digest_len == sig_prefix->hash_len);
517    const uint8_t *prefix = sig_prefix->bytes;
518    size_t prefix_len = sig_prefix->len;
519    size_t signed_msg_len = prefix_len + digest_len;
520    if (signed_msg_len < prefix_len) {
521      OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_LONG);
522      return 0;
523    }
524
525    uint8_t *signed_msg =
526        reinterpret_cast<uint8_t *>(OPENSSL_malloc(signed_msg_len));
527    if (!signed_msg) {
528      return 0;
529    }
530
531    OPENSSL_memcpy(signed_msg, prefix, prefix_len);
532    OPENSSL_memcpy(signed_msg + prefix_len, digest, digest_len);
533
534    *out_msg = signed_msg;
535    *out_msg_len = signed_msg_len;
536    *is_alloced = 1;
537
538    return 1;
539  }
540
541  OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
542  return 0;
543}
544
545int rsa_sign_no_self_test(int hash_nid, const uint8_t *digest,
546                          size_t digest_len, uint8_t *out, unsigned *out_len,
547                          RSA *rsa) {
548  if (rsa->meth->sign) {
549    if (!rsa_check_digest_size(hash_nid, digest_len)) {
550      return 0;
551    }
552    // All supported digest lengths fit in |unsigned|.
553    assert(digest_len <= EVP_MAX_MD_SIZE);
554    static_assert(EVP_MAX_MD_SIZE <= UINT_MAX, "digest too long");
555    return rsa->meth->sign(hash_nid, digest, (unsigned)digest_len, out, out_len,
556                           rsa);
557  }
558
559  const unsigned rsa_size = RSA_size(rsa);
560  int ret = 0;
561  uint8_t *signed_msg = NULL;
562  size_t signed_msg_len = 0;
563  int signed_msg_is_alloced = 0;
564  size_t size_t_out_len;
565  if (!RSA_add_pkcs1_prefix(&signed_msg, &signed_msg_len,
566                            &signed_msg_is_alloced, hash_nid, digest,
567                            digest_len) ||
568      !rsa_sign_raw_no_self_test(rsa, &size_t_out_len, out, rsa_size,
569                                 signed_msg, signed_msg_len,
570                                 RSA_PKCS1_PADDING)) {
571    goto err;
572  }
573
574  if (size_t_out_len > UINT_MAX) {
575    OPENSSL_PUT_ERROR(RSA, ERR_R_OVERFLOW);
576    goto err;
577  }
578
579  *out_len = (unsigned)size_t_out_len;
580  ret = 1;
581
582err:
583  if (signed_msg_is_alloced) {
584    OPENSSL_free(signed_msg);
585  }
586  return ret;
587}
588
589int RSA_sign(int hash_nid, const uint8_t *digest, size_t digest_len,
590             uint8_t *out, unsigned *out_len, RSA *rsa) {
591  boringssl_ensure_rsa_self_test();
592
593  return rsa_sign_no_self_test(hash_nid, digest, digest_len, out, out_len, rsa);
594}
595
596int RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
597                      const uint8_t *digest, size_t digest_len,
598                      const EVP_MD *md, const EVP_MD *mgf1_md, int salt_len) {
599  if (digest_len != EVP_MD_size(md)) {
600    OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
601    return 0;
602  }
603
604  size_t padded_len = RSA_size(rsa);
605  uint8_t *padded = reinterpret_cast<uint8_t *>(OPENSSL_malloc(padded_len));
606  if (padded == NULL) {
607    return 0;
608  }
609
610  int ret = RSA_padding_add_PKCS1_PSS_mgf1(rsa, padded, digest, md, mgf1_md,
611                                           salt_len) &&
612            RSA_sign_raw(rsa, out_len, out, max_out, padded, padded_len,
613                         RSA_NO_PADDING);
614  OPENSSL_free(padded);
615  return ret;
616}
617
618int rsa_verify_no_self_test(int hash_nid, const uint8_t *digest,
619                            size_t digest_len, const uint8_t *sig,
620                            size_t sig_len, RSA *rsa) {
621  if (rsa->n == NULL || rsa->e == NULL) {
622    OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
623    return 0;
624  }
625
626  const size_t rsa_size = RSA_size(rsa);
627  uint8_t *buf = NULL;
628  int ret = 0;
629  uint8_t *signed_msg = NULL;
630  size_t signed_msg_len = 0, len;
631  int signed_msg_is_alloced = 0;
632
633  if (hash_nid == NID_md5_sha1 && digest_len != SSL_SIG_LENGTH) {
634    OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
635    return 0;
636  }
637
638  buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(rsa_size));
639  if (!buf) {
640    return 0;
641  }
642
643  if (!rsa_verify_raw_no_self_test(rsa, &len, buf, rsa_size, sig, sig_len,
644                                   RSA_PKCS1_PADDING) ||
645      !RSA_add_pkcs1_prefix(&signed_msg, &signed_msg_len,
646                            &signed_msg_is_alloced, hash_nid, digest,
647                            digest_len)) {
648    goto out;
649  }
650
651  // Check that no other information follows the hash value (FIPS 186-4 Section
652  // 5.5) and it matches the expected hash.
653  if (len != signed_msg_len || OPENSSL_memcmp(buf, signed_msg, len) != 0) {
654    OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_SIGNATURE);
655    goto out;
656  }
657
658  ret = 1;
659
660out:
661  OPENSSL_free(buf);
662  if (signed_msg_is_alloced) {
663    OPENSSL_free(signed_msg);
664  }
665  return ret;
666}
667
668int RSA_verify(int hash_nid, const uint8_t *digest, size_t digest_len,
669               const uint8_t *sig, size_t sig_len, RSA *rsa) {
670  boringssl_ensure_rsa_self_test();
671  return rsa_verify_no_self_test(hash_nid, digest, digest_len, sig, sig_len,
672                                 rsa);
673}
674
675int RSA_verify_pss_mgf1(RSA *rsa, const uint8_t *digest, size_t digest_len,
676                        const EVP_MD *md, const EVP_MD *mgf1_md, int salt_len,
677                        const uint8_t *sig, size_t sig_len) {
678  if (digest_len != EVP_MD_size(md)) {
679    OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
680    return 0;
681  }
682
683  size_t em_len = RSA_size(rsa);
684  uint8_t *em = reinterpret_cast<uint8_t *>(OPENSSL_malloc(em_len));
685  if (em == NULL) {
686    return 0;
687  }
688
689  int ret = 0;
690  if (!RSA_verify_raw(rsa, &em_len, em, em_len, sig, sig_len, RSA_NO_PADDING)) {
691    goto err;
692  }
693
694  if (em_len != RSA_size(rsa)) {
695    OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
696    goto err;
697  }
698
699  ret = RSA_verify_PKCS1_PSS_mgf1(rsa, digest, md, mgf1_md, em, salt_len);
700
701err:
702  OPENSSL_free(em);
703  return ret;
704}
705
706static int check_mod_inverse(int *out_ok, const BIGNUM *a, const BIGNUM *ainv,
707                             const BIGNUM *m, unsigned m_min_bits,
708                             BN_CTX *ctx) {
709  if (BN_is_negative(ainv) ||
710      constant_time_declassify_int(BN_cmp(ainv, m) >= 0)) {
711    *out_ok = 0;
712    return 1;
713  }
714
715  // Note |bn_mul_consttime| and |bn_div_consttime| do not scale linearly, but
716  // checking |ainv| is in range bounds the running time, assuming |m|'s bounds
717  // were checked by the caller.
718  bssl::BN_CTXScope scope(ctx);
719  BIGNUM *tmp = BN_CTX_get(ctx);
720  if (tmp == nullptr ||  //
721      !bn_mul_consttime(tmp, a, ainv, ctx) ||
722      !bn_div_consttime(NULL, tmp, tmp, m, m_min_bits, ctx)) {
723    return 0;
724  }
725  *out_ok = constant_time_declassify_int(BN_is_one(tmp));
726  return 1;
727}
728
729int RSA_check_key(const RSA *key) {
730  // TODO(davidben): RSA key initialization is spread across
731  // |rsa_check_public_key|, |RSA_check_key|, |freeze_private_key|, and
732  // |BN_MONT_CTX_set_locked| as a result of API issues. See
733  // https://crbug.com/boringssl/316. As a result, we inconsistently check RSA
734  // invariants. We should fix this and integrate that logic.
735
736  if (!rsa_check_public_key(key)) {
737    return 0;
738  }
739
740  if ((key->p != NULL) != (key->q != NULL)) {
741    OPENSSL_PUT_ERROR(RSA, RSA_R_ONLY_ONE_OF_P_Q_GIVEN);
742    return 0;
743  }
744
745  // |key->d| must be bounded by |key->n|. This ensures bounds on |RSA_bits|
746  // translate to bounds on the running time of private key operations.
747  if (key->d != NULL &&
748      (BN_is_negative(key->d) || BN_cmp(key->d, key->n) >= 0)) {
749    OPENSSL_PUT_ERROR(RSA, RSA_R_D_OUT_OF_RANGE);
750    return 0;
751  }
752
753  if (key->d == NULL || key->p == NULL) {
754    // For a public key, or without p and q, there's nothing that can be
755    // checked.
756    return 1;
757  }
758
759  BN_CTX *ctx = BN_CTX_new();
760  if (ctx == NULL) {
761    return 0;
762  }
763
764  BIGNUM tmp, de, pm1, qm1, dmp1, dmq1;
765  int ok = 0, has_crt_values;
766  unsigned pm1_bits, qm1_bits;
767  BN_init(&tmp);
768  BN_init(&de);
769  BN_init(&pm1);
770  BN_init(&qm1);
771  BN_init(&dmp1);
772  BN_init(&dmq1);
773
774  // Check that p * q == n. Before we multiply, we check that p and q are in
775  // bounds, to avoid a DoS vector in |bn_mul_consttime| below. Note that
776  // n was bound by |rsa_check_public_key|. This also implicitly checks p and q
777  // are odd, which is a necessary condition for Montgomery reduction.
778  if (BN_is_negative(key->p) ||
779      constant_time_declassify_int(BN_cmp(key->p, key->n) >= 0) ||
780      BN_is_negative(key->q) ||
781      constant_time_declassify_int(BN_cmp(key->q, key->n) >= 0)) {
782    OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
783    goto out;
784  }
785  if (!bn_mul_consttime(&tmp, key->p, key->q, ctx)) {
786    OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
787    goto out;
788  }
789  if (BN_cmp(&tmp, key->n) != 0) {
790    OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
791    goto out;
792  }
793
794  // d must be an inverse of e mod the Carmichael totient, lcm(p-1, q-1), but it
795  // may be unreduced because other implementations use the Euler totient. We
796  // simply check that d * e is one mod p-1 and mod q-1. Note d and e were bound
797  // by earlier checks in this function.
798  if (!bn_usub_consttime(&pm1, key->p, BN_value_one()) ||
799      !bn_usub_consttime(&qm1, key->q, BN_value_one())) {
800    OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
801    goto out;
802  }
803  pm1_bits = BN_num_bits(&pm1);
804  qm1_bits = BN_num_bits(&qm1);
805  if (!bn_mul_consttime(&de, key->d, key->e, ctx) ||
806      !bn_div_consttime(NULL, &tmp, &de, &pm1, pm1_bits, ctx) ||
807      !bn_div_consttime(NULL, &de, &de, &qm1, qm1_bits, ctx)) {
808    OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
809    goto out;
810  }
811
812  if (constant_time_declassify_int(!BN_is_one(&tmp)) ||
813      constant_time_declassify_int(!BN_is_one(&de))) {
814    OPENSSL_PUT_ERROR(RSA, RSA_R_D_E_NOT_CONGRUENT_TO_1);
815    goto out;
816  }
817
818  has_crt_values = key->dmp1 != NULL;
819  if (has_crt_values != (key->dmq1 != NULL) ||
820      has_crt_values != (key->iqmp != NULL)) {
821    OPENSSL_PUT_ERROR(RSA, RSA_R_INCONSISTENT_SET_OF_CRT_VALUES);
822    goto out;
823  }
824
825  if (has_crt_values) {
826    int dmp1_ok, dmq1_ok, iqmp_ok;
827    if (!check_mod_inverse(&dmp1_ok, key->e, key->dmp1, &pm1, pm1_bits, ctx) ||
828        !check_mod_inverse(&dmq1_ok, key->e, key->dmq1, &qm1, qm1_bits, ctx) ||
829        // |p| is odd, so |pm1| and |p| have the same bit width. If they didn't,
830        // we only need a lower bound anyway.
831        !check_mod_inverse(&iqmp_ok, key->q, key->iqmp, key->p, pm1_bits,
832                           ctx)) {
833      OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
834      goto out;
835    }
836
837    if (!dmp1_ok || !dmq1_ok || !iqmp_ok) {
838      OPENSSL_PUT_ERROR(RSA, RSA_R_CRT_VALUES_INCORRECT);
839      goto out;
840    }
841  }
842
843  ok = 1;
844
845out:
846  BN_free(&tmp);
847  BN_free(&de);
848  BN_free(&pm1);
849  BN_free(&qm1);
850  BN_free(&dmp1);
851  BN_free(&dmq1);
852  BN_CTX_free(ctx);
853
854  return ok;
855}
856
857
858// This is the product of the 132 smallest odd primes, from 3 to 751.
859static const BN_ULONG kSmallFactorsLimbs[] = {TOBN(0xc4309333, 0x3ef4e3e1),
860                                              TOBN(0x71161eb6, 0xcd2d655f),
861                                              TOBN(0x95e2238c, 0x0bf94862),
862                                              TOBN(0x3eb233d3, 0x24f7912b),
863                                              TOBN(0x6b55514b, 0xbf26c483),
864                                              TOBN(0x0a84d817, 0x5a144871),
865                                              TOBN(0x77d12fee, 0x9b82210a),
866                                              TOBN(0xdb5b93c2, 0x97f050b3),
867                                              TOBN(0x4acad6b9, 0x4d6c026b),
868                                              TOBN(0xeb7751f3, 0x54aec893),
869                                              TOBN(0xdba53368, 0x36bc85c4),
870                                              TOBN(0xd85a1b28, 0x7f5ec78e),
871                                              TOBN(0x2eb072d8, 0x6b322244),
872                                              TOBN(0xbba51112, 0x5e2b3aea),
873                                              TOBN(0x36ed1a6c, 0x0e2486bf),
874                                              TOBN(0x5f270460, 0xec0c5727),
875                                              0x000017b1};
876
877DEFINE_LOCAL_DATA(BIGNUM, g_small_factors) {
878  out->d = (BN_ULONG *)kSmallFactorsLimbs;
879  out->width = OPENSSL_ARRAY_SIZE(kSmallFactorsLimbs);
880  out->dmax = out->width;
881  out->neg = 0;
882  out->flags = BN_FLG_STATIC_DATA;
883}
884
885int RSA_check_fips(RSA *key) {
886  if (!RSA_check_key(key)) {
887    return 0;
888  }
889
890  BN_CTX *ctx = BN_CTX_new();
891  if (ctx == NULL) {
892    return 0;
893  }
894
895  BIGNUM small_gcd;
896  BN_init(&small_gcd);
897
898  int ret = 1;
899
900  // Perform partial public key validation of RSA keys (SP 800-89 5.3.3).
901  // Although this is not for primality testing, SP 800-89 cites an RSA
902  // primality testing algorithm, so we use |BN_prime_checks_for_generation| to
903  // match. This is only a plausibility test and we expect the value to be
904  // composite, so too few iterations will cause us to reject the key, not use
905  // an implausible one.
906  //
907  // |key->e| may be nullptr if created with |RSA_new_private_key_no_e|.
908  enum bn_primality_result_t primality_result;
909  if (key->e == nullptr ||          //
910      BN_num_bits(key->e) <= 16 ||  //
911      BN_num_bits(key->e) > 256 ||  //
912      !BN_is_odd(key->n) ||         //
913      !BN_is_odd(key->e) ||
914      !BN_gcd(&small_gcd, key->n, g_small_factors(), ctx) ||
915      !BN_is_one(&small_gcd) ||
916      !BN_enhanced_miller_rabin_primality_test(&primality_result, key->n,
917                                               BN_prime_checks_for_generation,
918                                               ctx, NULL) ||
919      primality_result != bn_non_prime_power_composite) {
920    OPENSSL_PUT_ERROR(RSA, RSA_R_PUBLIC_KEY_VALIDATION_FAILED);
921    ret = 0;
922  }
923
924  BN_free(&small_gcd);
925  BN_CTX_free(ctx);
926
927  if (!ret || key->d == NULL || key->p == NULL) {
928    // On a failure or on only a public key, there's nothing else can be
929    // checked.
930    return ret;
931  }
932
933  // FIPS pairwise consistency test (FIPS 140-2 4.9.2). Per FIPS 140-2 IG,
934  // section 9.9, it is not known whether |rsa| will be used for signing or
935  // encryption, so either pair-wise consistency self-test is acceptable. We
936  // perform a signing test.
937  uint8_t data[32] = {0};
938  unsigned sig_len = RSA_size(key);
939  uint8_t *sig = reinterpret_cast<uint8_t *>(OPENSSL_malloc(sig_len));
940  if (sig == NULL) {
941    return 0;
942  }
943
944  if (!RSA_sign(NID_sha256, data, sizeof(data), sig, &sig_len, key)) {
945    OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
946    ret = 0;
947    goto cleanup;
948  }
949  if (boringssl_fips_break_test("RSA_PWCT")) {
950    data[0] = ~data[0];
951  }
952  if (!RSA_verify(NID_sha256, data, sizeof(data), sig, sig_len, key)) {
953    OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
954    ret = 0;
955  }
956
957cleanup:
958  OPENSSL_free(sig);
959
960  return ret;
961}
962
963int rsa_private_transform_no_self_test(RSA *rsa, uint8_t *out,
964                                       const uint8_t *in, size_t len) {
965  if (rsa->meth->private_transform) {
966    return rsa->meth->private_transform(rsa, out, in, len);
967  }
968
969  return rsa_default_private_transform(rsa, out, in, len);
970}
971
972int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
973                          size_t len) {
974  boringssl_ensure_rsa_self_test();
975  return rsa_private_transform_no_self_test(rsa, out, in, len);
976}
977
978int RSA_flags(const RSA *rsa) { return rsa->flags; }
979
980int RSA_test_flags(const RSA *rsa, int flags) { return rsa->flags & flags; }
981