Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / deps / grpc / third_party / boringssl / crypto / fipsmodule / rsa / rsa.c
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 <limits.h>
60 #include <string.h>
61
62 #include <openssl/bn.h>
63 #include <openssl/digest.h>
64 #include <openssl/engine.h>
65 #include <openssl/err.h>
66 #include <openssl/ex_data.h>
67 #include <openssl/md5.h>
68 #include <openssl/mem.h>
69 #include <openssl/nid.h>
70 #include <openssl/sha.h>
71 #include <openssl/thread.h>
72
73 #include "../bn/internal.h"
74 #include "../delocate.h"
75 #include "../../internal.h"
76 #include "internal.h"
77
78
79 DEFINE_STATIC_EX_DATA_CLASS(g_rsa_ex_data_class);
80
81 RSA *RSA_new(void) { return RSA_new_method(NULL); }
82
83 RSA *RSA_new_method(const ENGINE *engine) {
84   RSA *rsa = OPENSSL_malloc(sizeof(RSA));
85   if (rsa == NULL) {
86     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
87     return NULL;
88   }
89
90   OPENSSL_memset(rsa, 0, sizeof(RSA));
91
92   if (engine) {
93     rsa->meth = ENGINE_get_RSA_method(engine);
94   }
95
96   if (rsa->meth == NULL) {
97     rsa->meth = (RSA_METHOD *) RSA_default_method();
98   }
99   METHOD_ref(rsa->meth);
100
101   rsa->references = 1;
102   rsa->flags = rsa->meth->flags;
103   CRYPTO_MUTEX_init(&rsa->lock);
104   CRYPTO_new_ex_data(&rsa->ex_data);
105
106   if (rsa->meth->init && !rsa->meth->init(rsa)) {
107     CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), rsa, &rsa->ex_data);
108     CRYPTO_MUTEX_cleanup(&rsa->lock);
109     METHOD_unref(rsa->meth);
110     OPENSSL_free(rsa);
111     return NULL;
112   }
113
114   return rsa;
115 }
116
117 void RSA_free(RSA *rsa) {
118   unsigned u;
119
120   if (rsa == NULL) {
121     return;
122   }
123
124   if (!CRYPTO_refcount_dec_and_test_zero(&rsa->references)) {
125     return;
126   }
127
128   if (rsa->meth->finish) {
129     rsa->meth->finish(rsa);
130   }
131   METHOD_unref(rsa->meth);
132
133   CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), rsa, &rsa->ex_data);
134
135   BN_free(rsa->n);
136   BN_free(rsa->e);
137   BN_free(rsa->d);
138   BN_free(rsa->p);
139   BN_free(rsa->q);
140   BN_free(rsa->dmp1);
141   BN_free(rsa->dmq1);
142   BN_free(rsa->iqmp);
143   BN_MONT_CTX_free(rsa->mont_n);
144   BN_MONT_CTX_free(rsa->mont_p);
145   BN_MONT_CTX_free(rsa->mont_q);
146   BN_free(rsa->d_fixed);
147   BN_free(rsa->dmp1_fixed);
148   BN_free(rsa->dmq1_fixed);
149   BN_free(rsa->inv_small_mod_large_mont);
150   for (u = 0; u < rsa->num_blindings; u++) {
151     BN_BLINDING_free(rsa->blindings[u]);
152   }
153   OPENSSL_free(rsa->blindings);
154   OPENSSL_free(rsa->blindings_inuse);
155   CRYPTO_MUTEX_cleanup(&rsa->lock);
156   OPENSSL_free(rsa);
157 }
158
159 int RSA_up_ref(RSA *rsa) {
160   CRYPTO_refcount_inc(&rsa->references);
161   return 1;
162 }
163
164 unsigned RSA_bits(const RSA *rsa) { return BN_num_bits(rsa->n); }
165
166 void RSA_get0_key(const RSA *rsa, const BIGNUM **out_n, const BIGNUM **out_e,
167                   const BIGNUM **out_d) {
168   if (out_n != NULL) {
169     *out_n = rsa->n;
170   }
171   if (out_e != NULL) {
172     *out_e = rsa->e;
173   }
174   if (out_d != NULL) {
175     *out_d = rsa->d;
176   }
177 }
178
179 void RSA_get0_factors(const RSA *rsa, const BIGNUM **out_p,
180                       const BIGNUM **out_q) {
181   if (out_p != NULL) {
182     *out_p = rsa->p;
183   }
184   if (out_q != NULL) {
185     *out_q = rsa->q;
186   }
187 }
188
189 void RSA_get0_crt_params(const RSA *rsa, const BIGNUM **out_dmp1,
190                          const BIGNUM **out_dmq1, const BIGNUM **out_iqmp) {
191   if (out_dmp1 != NULL) {
192     *out_dmp1 = rsa->dmp1;
193   }
194   if (out_dmq1 != NULL) {
195     *out_dmq1 = rsa->dmq1;
196   }
197   if (out_iqmp != NULL) {
198     *out_iqmp = rsa->iqmp;
199   }
200 }
201
202 int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
203   if ((rsa->n == NULL && n == NULL) ||
204       (rsa->e == NULL && e == NULL)) {
205     return 0;
206   }
207
208   if (n != NULL) {
209     BN_free(rsa->n);
210     rsa->n = n;
211   }
212   if (e != NULL) {
213     BN_free(rsa->e);
214     rsa->e = e;
215   }
216   if (d != NULL) {
217     BN_free(rsa->d);
218     rsa->d = d;
219   }
220
221   return 1;
222 }
223
224 int RSA_set0_factors(RSA *rsa, BIGNUM *p, BIGNUM *q) {
225   if ((rsa->p == NULL && p == NULL) ||
226       (rsa->q == NULL && q == NULL)) {
227     return 0;
228   }
229
230   if (p != NULL) {
231     BN_free(rsa->p);
232     rsa->p = p;
233   }
234   if (q != NULL) {
235     BN_free(rsa->q);
236     rsa->q = q;
237   }
238
239   return 1;
240 }
241
242 int RSA_set0_crt_params(RSA *rsa, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) {
243   if ((rsa->dmp1 == NULL && dmp1 == NULL) ||
244       (rsa->dmq1 == NULL && dmq1 == NULL) ||
245       (rsa->iqmp == NULL && iqmp == NULL)) {
246     return 0;
247   }
248
249   if (dmp1 != NULL) {
250     BN_free(rsa->dmp1);
251     rsa->dmp1 = dmp1;
252   }
253   if (dmq1 != NULL) {
254     BN_free(rsa->dmq1);
255     rsa->dmq1 = dmq1;
256   }
257   if (iqmp != NULL) {
258     BN_free(rsa->iqmp);
259     rsa->iqmp = iqmp;
260   }
261
262   return 1;
263 }
264
265 int RSA_public_encrypt(size_t flen, const uint8_t *from, uint8_t *to, RSA *rsa,
266                        int padding) {
267   size_t out_len;
268
269   if (!RSA_encrypt(rsa, &out_len, to, RSA_size(rsa), from, flen, padding)) {
270     return -1;
271   }
272
273   if (out_len > INT_MAX) {
274     OPENSSL_PUT_ERROR(RSA, ERR_R_OVERFLOW);
275     return -1;
276   }
277   return out_len;
278 }
279
280 int RSA_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
281                  const uint8_t *in, size_t in_len, int padding) {
282   if (rsa->meth->sign_raw) {
283     return rsa->meth->sign_raw(rsa, out_len, out, max_out, in, in_len, padding);
284   }
285
286   return rsa_default_sign_raw(rsa, out_len, out, max_out, in, in_len, padding);
287 }
288
289 int RSA_private_encrypt(size_t flen, const uint8_t *from, uint8_t *to, RSA *rsa,
290                         int padding) {
291   size_t out_len;
292
293   if (!RSA_sign_raw(rsa, &out_len, to, RSA_size(rsa), from, flen, padding)) {
294     return -1;
295   }
296
297   if (out_len > INT_MAX) {
298     OPENSSL_PUT_ERROR(RSA, ERR_R_OVERFLOW);
299     return -1;
300   }
301   return out_len;
302 }
303
304 int RSA_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
305                 const uint8_t *in, size_t in_len, int padding) {
306   if (rsa->meth->decrypt) {
307     return rsa->meth->decrypt(rsa, out_len, out, max_out, in, in_len, padding);
308   }
309
310   return rsa_default_decrypt(rsa, out_len, out, max_out, in, in_len, padding);
311 }
312
313 int RSA_private_decrypt(size_t flen, const uint8_t *from, uint8_t *to, RSA *rsa,
314                         int padding) {
315   size_t out_len;
316
317   if (!RSA_decrypt(rsa, &out_len, to, RSA_size(rsa), from, flen, padding)) {
318     return -1;
319   }
320
321   if (out_len > INT_MAX) {
322     OPENSSL_PUT_ERROR(RSA, ERR_R_OVERFLOW);
323     return -1;
324   }
325   return out_len;
326 }
327
328 int RSA_public_decrypt(size_t flen, const uint8_t *from, uint8_t *to, RSA *rsa,
329                        int padding) {
330   size_t out_len;
331
332   if (!RSA_verify_raw(rsa, &out_len, to, RSA_size(rsa), from, flen, padding)) {
333     return -1;
334   }
335
336   if (out_len > INT_MAX) {
337     OPENSSL_PUT_ERROR(RSA, ERR_R_OVERFLOW);
338     return -1;
339   }
340   return out_len;
341 }
342
343 unsigned RSA_size(const RSA *rsa) {
344   if (rsa->meth->size) {
345     return rsa->meth->size(rsa);
346   }
347
348   return rsa_default_size(rsa);
349 }
350
351 int RSA_is_opaque(const RSA *rsa) {
352   return rsa->meth && (rsa->meth->flags & RSA_FLAG_OPAQUE);
353 }
354
355 int RSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
356                          CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
357   int index;
358   if (!CRYPTO_get_ex_new_index(g_rsa_ex_data_class_bss_get(), &index, argl,
359                                argp, free_func)) {
360     return -1;
361   }
362   return index;
363 }
364
365 int RSA_set_ex_data(RSA *rsa, int idx, void *arg) {
366   return CRYPTO_set_ex_data(&rsa->ex_data, idx, arg);
367 }
368
369 void *RSA_get_ex_data(const RSA *rsa, int idx) {
370   return CRYPTO_get_ex_data(&rsa->ex_data, idx);
371 }
372
373 // SSL_SIG_LENGTH is the size of an SSL/TLS (prior to TLS 1.2) signature: it's
374 // the length of an MD5 and SHA1 hash.
375 static const unsigned SSL_SIG_LENGTH = 36;
376
377 // pkcs1_sig_prefix contains the ASN.1, DER encoded prefix for a hash that is
378 // to be signed with PKCS#1.
379 struct pkcs1_sig_prefix {
380   // nid identifies the hash function.
381   int nid;
382   // hash_len is the expected length of the hash function.
383   uint8_t hash_len;
384   // len is the number of bytes of |bytes| which are valid.
385   uint8_t len;
386   // bytes contains the DER bytes.
387   uint8_t bytes[19];
388 };
389
390 // kPKCS1SigPrefixes contains the ASN.1 prefixes for PKCS#1 signatures with
391 // different hash functions.
392 static const struct pkcs1_sig_prefix kPKCS1SigPrefixes[] = {
393     {
394      NID_md5,
395      MD5_DIGEST_LENGTH,
396      18,
397      {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
398       0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
399     },
400     {
401      NID_sha1,
402      SHA_DIGEST_LENGTH,
403      15,
404      {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05,
405       0x00, 0x04, 0x14},
406     },
407     {
408      NID_sha224,
409      SHA224_DIGEST_LENGTH,
410      19,
411      {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
412       0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
413     },
414     {
415      NID_sha256,
416      SHA256_DIGEST_LENGTH,
417      19,
418      {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
419       0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
420     },
421     {
422      NID_sha384,
423      SHA384_DIGEST_LENGTH,
424      19,
425      {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
426       0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
427     },
428     {
429      NID_sha512,
430      SHA512_DIGEST_LENGTH,
431      19,
432      {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
433       0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
434     },
435     {
436      NID_undef, 0, 0, {0},
437     },
438 };
439
440 int RSA_add_pkcs1_prefix(uint8_t **out_msg, size_t *out_msg_len,
441                          int *is_alloced, int hash_nid, const uint8_t *msg,
442                          size_t msg_len) {
443   unsigned i;
444
445   if (hash_nid == NID_md5_sha1) {
446     // Special case: SSL signature, just check the length.
447     if (msg_len != SSL_SIG_LENGTH) {
448       OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
449       return 0;
450     }
451
452     *out_msg = (uint8_t*) msg;
453     *out_msg_len = SSL_SIG_LENGTH;
454     *is_alloced = 0;
455     return 1;
456   }
457
458   for (i = 0; kPKCS1SigPrefixes[i].nid != NID_undef; i++) {
459     const struct pkcs1_sig_prefix *sig_prefix = &kPKCS1SigPrefixes[i];
460     if (sig_prefix->nid != hash_nid) {
461       continue;
462     }
463
464     if (msg_len != sig_prefix->hash_len) {
465       OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
466       return 0;
467     }
468
469     const uint8_t* prefix = sig_prefix->bytes;
470     unsigned prefix_len = sig_prefix->len;
471     unsigned signed_msg_len;
472     uint8_t *signed_msg;
473
474     signed_msg_len = prefix_len + msg_len;
475     if (signed_msg_len < prefix_len) {
476       OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_LONG);
477       return 0;
478     }
479
480     signed_msg = OPENSSL_malloc(signed_msg_len);
481     if (!signed_msg) {
482       OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
483       return 0;
484     }
485
486     OPENSSL_memcpy(signed_msg, prefix, prefix_len);
487     OPENSSL_memcpy(signed_msg + prefix_len, msg, msg_len);
488
489     *out_msg = signed_msg;
490     *out_msg_len = signed_msg_len;
491     *is_alloced = 1;
492
493     return 1;
494   }
495
496   OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
497   return 0;
498 }
499
500 int RSA_sign(int hash_nid, const uint8_t *in, unsigned in_len, uint8_t *out,
501              unsigned *out_len, RSA *rsa) {
502   const unsigned rsa_size = RSA_size(rsa);
503   int ret = 0;
504   uint8_t *signed_msg = NULL;
505   size_t signed_msg_len = 0;
506   int signed_msg_is_alloced = 0;
507   size_t size_t_out_len;
508
509   if (rsa->meth->sign) {
510     return rsa->meth->sign(hash_nid, in, in_len, out, out_len, rsa);
511   }
512
513   if (!RSA_add_pkcs1_prefix(&signed_msg, &signed_msg_len,
514                             &signed_msg_is_alloced, hash_nid, in, in_len) ||
515       !RSA_sign_raw(rsa, &size_t_out_len, out, rsa_size, signed_msg,
516                     signed_msg_len, RSA_PKCS1_PADDING)) {
517     goto err;
518   }
519
520   *out_len = size_t_out_len;
521   ret = 1;
522
523 err:
524   if (signed_msg_is_alloced) {
525     OPENSSL_free(signed_msg);
526   }
527   return ret;
528 }
529
530 int RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
531                       const uint8_t *in, size_t in_len, const EVP_MD *md,
532                       const EVP_MD *mgf1_md, int salt_len) {
533   if (in_len != EVP_MD_size(md)) {
534     OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
535     return 0;
536   }
537
538   size_t padded_len = RSA_size(rsa);
539   uint8_t *padded = OPENSSL_malloc(padded_len);
540   if (padded == NULL) {
541     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
542     return 0;
543   }
544
545   int ret =
546       RSA_padding_add_PKCS1_PSS_mgf1(rsa, padded, in, md, mgf1_md, salt_len) &&
547       RSA_sign_raw(rsa, out_len, out, max_out, padded, padded_len,
548                    RSA_NO_PADDING);
549   OPENSSL_free(padded);
550   return ret;
551 }
552
553 int RSA_verify(int hash_nid, const uint8_t *msg, size_t msg_len,
554                const uint8_t *sig, size_t sig_len, RSA *rsa) {
555   if (rsa->n == NULL || rsa->e == NULL) {
556     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
557     return 0;
558   }
559
560   const size_t rsa_size = RSA_size(rsa);
561   uint8_t *buf = NULL;
562   int ret = 0;
563   uint8_t *signed_msg = NULL;
564   size_t signed_msg_len = 0, len;
565   int signed_msg_is_alloced = 0;
566
567   if (hash_nid == NID_md5_sha1 && msg_len != SSL_SIG_LENGTH) {
568     OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
569     return 0;
570   }
571
572   buf = OPENSSL_malloc(rsa_size);
573   if (!buf) {
574     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
575     return 0;
576   }
577
578   if (!RSA_verify_raw(rsa, &len, buf, rsa_size, sig, sig_len,
579                       RSA_PKCS1_PADDING)) {
580     goto out;
581   }
582
583   if (!RSA_add_pkcs1_prefix(&signed_msg, &signed_msg_len,
584                             &signed_msg_is_alloced, hash_nid, msg, msg_len)) {
585     goto out;
586   }
587
588   // Check that no other information follows the hash value (FIPS 186-4 Section
589   // 5.5) and it matches the expected hash.
590   if (len != signed_msg_len || OPENSSL_memcmp(buf, signed_msg, len) != 0) {
591     OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_SIGNATURE);
592     goto out;
593   }
594
595   ret = 1;
596
597 out:
598   OPENSSL_free(buf);
599   if (signed_msg_is_alloced) {
600     OPENSSL_free(signed_msg);
601   }
602   return ret;
603 }
604
605 int RSA_verify_pss_mgf1(RSA *rsa, const uint8_t *msg, size_t msg_len,
606                         const EVP_MD *md, const EVP_MD *mgf1_md, int salt_len,
607                         const uint8_t *sig, size_t sig_len) {
608   if (msg_len != EVP_MD_size(md)) {
609     OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
610     return 0;
611   }
612
613   size_t em_len = RSA_size(rsa);
614   uint8_t *em = OPENSSL_malloc(em_len);
615   if (em == NULL) {
616     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
617     return 0;
618   }
619
620   int ret = 0;
621   if (!RSA_verify_raw(rsa, &em_len, em, em_len, sig, sig_len, RSA_NO_PADDING)) {
622     goto err;
623   }
624
625   if (em_len != RSA_size(rsa)) {
626     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
627     goto err;
628   }
629
630   ret = RSA_verify_PKCS1_PSS_mgf1(rsa, msg, md, mgf1_md, em, salt_len);
631
632 err:
633   OPENSSL_free(em);
634   return ret;
635 }
636
637 static int check_mod_inverse(int *out_ok, const BIGNUM *a, const BIGNUM *ainv,
638                              const BIGNUM *m, int check_reduced, BN_CTX *ctx) {
639   BN_CTX_start(ctx);
640   BIGNUM *tmp = BN_CTX_get(ctx);
641   int ret = tmp != NULL &&
642             bn_mul_consttime(tmp, a, ainv, ctx) &&
643             bn_div_consttime(NULL, tmp, tmp, m, ctx);
644   if (ret) {
645     *out_ok = BN_is_one(tmp);
646     if (check_reduced && (BN_is_negative(ainv) || BN_cmp(ainv, m) >= 0)) {
647       *out_ok = 0;
648     }
649   }
650   BN_CTX_end(ctx);
651   return ret;
652 }
653
654 int RSA_check_key(const RSA *key) {
655   BIGNUM n, pm1, qm1, lcm, dmp1, dmq1, iqmp_times_q;
656   BN_CTX *ctx;
657   int ok = 0, has_crt_values;
658
659   if (RSA_is_opaque(key)) {
660     // Opaque keys can't be checked.
661     return 1;
662   }
663
664   if ((key->p != NULL) != (key->q != NULL)) {
665     OPENSSL_PUT_ERROR(RSA, RSA_R_ONLY_ONE_OF_P_Q_GIVEN);
666     return 0;
667   }
668
669   if (!key->n || !key->e) {
670     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
671     return 0;
672   }
673
674   if (!key->d || !key->p) {
675     // For a public key, or without p and q, there's nothing that can be
676     // checked.
677     return 1;
678   }
679
680   ctx = BN_CTX_new();
681   if (ctx == NULL) {
682     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
683     return 0;
684   }
685
686   BN_init(&n);
687   BN_init(&pm1);
688   BN_init(&qm1);
689   BN_init(&lcm);
690   BN_init(&dmp1);
691   BN_init(&dmq1);
692   BN_init(&iqmp_times_q);
693
694   int d_ok;
695   if (!bn_mul_consttime(&n, key->p, key->q, ctx) ||
696       // lcm = lcm(p, q)
697       !bn_usub_consttime(&pm1, key->p, BN_value_one()) ||
698       !bn_usub_consttime(&qm1, key->q, BN_value_one()) ||
699       !bn_lcm_consttime(&lcm, &pm1, &qm1, ctx) ||
700       // Other implementations use the Euler totient rather than the Carmichael
701       // totient, so allow unreduced |key->d|.
702       !check_mod_inverse(&d_ok, key->e, key->d, &lcm,
703                          0 /* don't require reduced */, ctx)) {
704     OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
705     goto out;
706   }
707
708   if (BN_cmp(&n, key->n) != 0) {
709     OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
710     goto out;
711   }
712
713   if (!d_ok) {
714     OPENSSL_PUT_ERROR(RSA, RSA_R_D_E_NOT_CONGRUENT_TO_1);
715     goto out;
716   }
717
718   if (BN_is_negative(key->d) || BN_cmp(key->d, key->n) >= 0) {
719     OPENSSL_PUT_ERROR(RSA, RSA_R_D_OUT_OF_RANGE);
720     goto out;
721   }
722
723   has_crt_values = key->dmp1 != NULL;
724   if (has_crt_values != (key->dmq1 != NULL) ||
725       has_crt_values != (key->iqmp != NULL)) {
726     OPENSSL_PUT_ERROR(RSA, RSA_R_INCONSISTENT_SET_OF_CRT_VALUES);
727     goto out;
728   }
729
730   if (has_crt_values) {
731     int dmp1_ok, dmq1_ok, iqmp_ok;
732     if (!check_mod_inverse(&dmp1_ok, key->e, key->dmp1, &pm1,
733                            1 /* check reduced */, ctx) ||
734         !check_mod_inverse(&dmq1_ok, key->e, key->dmq1, &qm1,
735                            1 /* check reduced */, ctx) ||
736         !check_mod_inverse(&iqmp_ok, key->q, key->iqmp, key->p,
737                            1 /* check reduced */, ctx)) {
738       OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
739       goto out;
740     }
741
742     if (!dmp1_ok || !dmq1_ok || !iqmp_ok) {
743       OPENSSL_PUT_ERROR(RSA, RSA_R_CRT_VALUES_INCORRECT);
744       goto out;
745     }
746   }
747
748   ok = 1;
749
750 out:
751   BN_free(&n);
752   BN_free(&pm1);
753   BN_free(&qm1);
754   BN_free(&lcm);
755   BN_free(&dmp1);
756   BN_free(&dmq1);
757   BN_free(&iqmp_times_q);
758   BN_CTX_free(ctx);
759
760   return ok;
761 }
762
763
764 // This is the product of the 132 smallest odd primes, from 3 to 751.
765 static const BN_ULONG kSmallFactorsLimbs[] = {
766     TOBN(0xc4309333, 0x3ef4e3e1), TOBN(0x71161eb6, 0xcd2d655f),
767     TOBN(0x95e2238c, 0x0bf94862), TOBN(0x3eb233d3, 0x24f7912b),
768     TOBN(0x6b55514b, 0xbf26c483), TOBN(0x0a84d817, 0x5a144871),
769     TOBN(0x77d12fee, 0x9b82210a), TOBN(0xdb5b93c2, 0x97f050b3),
770     TOBN(0x4acad6b9, 0x4d6c026b), TOBN(0xeb7751f3, 0x54aec893),
771     TOBN(0xdba53368, 0x36bc85c4), TOBN(0xd85a1b28, 0x7f5ec78e),
772     TOBN(0x2eb072d8, 0x6b322244), TOBN(0xbba51112, 0x5e2b3aea),
773     TOBN(0x36ed1a6c, 0x0e2486bf), TOBN(0x5f270460, 0xec0c5727),
774     0x000017b1
775 };
776
777 DEFINE_LOCAL_DATA(BIGNUM, g_small_factors) {
778   out->d = (BN_ULONG *) kSmallFactorsLimbs;
779   out->width = OPENSSL_ARRAY_SIZE(kSmallFactorsLimbs);
780   out->dmax = out->width;
781   out->neg = 0;
782   out->flags = BN_FLG_STATIC_DATA;
783 }
784
785 int RSA_check_fips(RSA *key) {
786   if (RSA_is_opaque(key)) {
787     // Opaque keys can't be checked.
788     OPENSSL_PUT_ERROR(RSA, RSA_R_PUBLIC_KEY_VALIDATION_FAILED);
789     return 0;
790   }
791
792   if (!RSA_check_key(key)) {
793     return 0;
794   }
795
796   BN_CTX *ctx = BN_CTX_new();
797   if (ctx == NULL) {
798     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
799     return 0;
800   }
801
802   BIGNUM small_gcd;
803   BN_init(&small_gcd);
804
805   int ret = 1;
806
807   // Perform partial public key validation of RSA keys (SP 800-89 5.3.3).
808   enum bn_primality_result_t primality_result;
809   if (BN_num_bits(key->e) <= 16 ||
810       BN_num_bits(key->e) > 256 ||
811       !BN_is_odd(key->n) ||
812       !BN_is_odd(key->e) ||
813       !BN_gcd(&small_gcd, key->n, g_small_factors(), ctx) ||
814       !BN_is_one(&small_gcd) ||
815       !BN_enhanced_miller_rabin_primality_test(&primality_result, key->n,
816                                                BN_prime_checks, ctx, NULL) ||
817       primality_result != bn_non_prime_power_composite) {
818     OPENSSL_PUT_ERROR(RSA, RSA_R_PUBLIC_KEY_VALIDATION_FAILED);
819     ret = 0;
820   }
821
822   BN_free(&small_gcd);
823   BN_CTX_free(ctx);
824
825   if (!ret || key->d == NULL || key->p == NULL) {
826     // On a failure or on only a public key, there's nothing else can be
827     // checked.
828     return ret;
829   }
830
831   // FIPS pairwise consistency test (FIPS 140-2 4.9.2). Per FIPS 140-2 IG,
832   // section 9.9, it is not known whether |rsa| will be used for signing or
833   // encryption, so either pair-wise consistency self-test is acceptable. We
834   // perform a signing test.
835   uint8_t data[32] = {0};
836   unsigned sig_len = RSA_size(key);
837   uint8_t *sig = OPENSSL_malloc(sig_len);
838   if (sig == NULL) {
839     OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
840     return 0;
841   }
842
843   if (!RSA_sign(NID_sha256, data, sizeof(data), sig, &sig_len, key)) {
844     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
845     ret = 0;
846     goto cleanup;
847   }
848 #if defined(BORINGSSL_FIPS_BREAK_RSA_PWCT)
849   data[0] = ~data[0];
850 #endif
851   if (!RSA_verify(NID_sha256, data, sizeof(data), sig, sig_len, key)) {
852     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
853     ret = 0;
854   }
855
856 cleanup:
857   OPENSSL_free(sig);
858
859   return ret;
860 }
861
862 int RSA_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
863                           size_t len) {
864   if (rsa->meth->private_transform) {
865     return rsa->meth->private_transform(rsa, out, in, len);
866   }
867
868   return rsa_default_private_transform(rsa, out, in, len);
869 }
870
871 int RSA_flags(const RSA *rsa) { return rsa->flags; }
872
873 int RSA_blinding_on(RSA *rsa, BN_CTX *ctx) {
874   return 1;
875 }