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