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