]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssl/crypto/rsa/rsa_eay.c
Merge OpenSSL 1.0.2q.
[FreeBSD/FreeBSD.git] / crypto / openssl / crypto / rsa / rsa_eay.c
1 /* crypto/rsa/rsa_eay.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2018 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include "cryptlib.h"
114 #include <openssl/bn.h>
115 #include <openssl/rsa.h>
116 #include <openssl/rand.h>
117 #include "bn_int.h"
118
119 #ifndef RSA_NULL
120
121 static int RSA_eay_public_encrypt(int flen, const unsigned char *from,
122                                   unsigned char *to, RSA *rsa, int padding);
123 static int RSA_eay_private_encrypt(int flen, const unsigned char *from,
124                                    unsigned char *to, RSA *rsa, int padding);
125 static int RSA_eay_public_decrypt(int flen, const unsigned char *from,
126                                   unsigned char *to, RSA *rsa, int padding);
127 static int RSA_eay_private_decrypt(int flen, const unsigned char *from,
128                                    unsigned char *to, RSA *rsa, int padding);
129 static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa,
130                            BN_CTX *ctx);
131 static int RSA_eay_init(RSA *rsa);
132 static int RSA_eay_finish(RSA *rsa);
133 static RSA_METHOD rsa_pkcs1_eay_meth = {
134     "Eric Young's PKCS#1 RSA",
135     RSA_eay_public_encrypt,
136     RSA_eay_public_decrypt,     /* signature verification */
137     RSA_eay_private_encrypt,    /* signing */
138     RSA_eay_private_decrypt,
139     RSA_eay_mod_exp,
140     BN_mod_exp_mont,            /* XXX probably we should not use Montgomery
141                                  * if e == 3 */
142     RSA_eay_init,
143     RSA_eay_finish,
144     0,                          /* flags */
145     NULL,
146     0,                          /* rsa_sign */
147     0,                          /* rsa_verify */
148     NULL                        /* rsa_keygen */
149 };
150
151 const RSA_METHOD *RSA_PKCS1_SSLeay(void)
152 {
153     return (&rsa_pkcs1_eay_meth);
154 }
155
156 static int RSA_eay_public_encrypt(int flen, const unsigned char *from,
157                                   unsigned char *to, RSA *rsa, int padding)
158 {
159     BIGNUM *f, *ret;
160     int i, num = 0, r = -1;
161     unsigned char *buf = NULL;
162     BN_CTX *ctx = NULL;
163
164     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
165         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_MODULUS_TOO_LARGE);
166         return -1;
167     }
168
169     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
170         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
171         return -1;
172     }
173
174     /* for large moduli, enforce exponent limit */
175     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
176         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
177             RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
178             return -1;
179         }
180     }
181
182     if ((ctx = BN_CTX_new()) == NULL)
183         goto err;
184     BN_CTX_start(ctx);
185     f = BN_CTX_get(ctx);
186     ret = BN_CTX_get(ctx);
187     num = BN_num_bytes(rsa->n);
188     buf = OPENSSL_malloc(num);
189     if (!f || !ret || !buf) {
190         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, ERR_R_MALLOC_FAILURE);
191         goto err;
192     }
193
194     switch (padding) {
195     case RSA_PKCS1_PADDING:
196         i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
197         break;
198 # ifndef OPENSSL_NO_SHA
199     case RSA_PKCS1_OAEP_PADDING:
200         i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
201         break;
202 # endif
203     case RSA_SSLV23_PADDING:
204         i = RSA_padding_add_SSLv23(buf, num, from, flen);
205         break;
206     case RSA_NO_PADDING:
207         i = RSA_padding_add_none(buf, num, from, flen);
208         break;
209     default:
210         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
211         goto err;
212     }
213     if (i <= 0)
214         goto err;
215
216     if (BN_bin2bn(buf, num, f) == NULL)
217         goto err;
218
219     if (BN_ucmp(f, rsa->n) >= 0) {
220         /* usually the padding functions would catch this */
221         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT,
222                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
223         goto err;
224     }
225
226     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
227         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA,
228                                     rsa->n, ctx))
229             goto err;
230
231     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
232                                rsa->_method_mod_n))
233         goto err;
234
235     /*
236      * BN_bn2binpad puts in leading 0 bytes if the number is less than
237      * the length of the modulus.
238      */
239     r = bn_bn2binpad(ret, to, num);
240  err:
241     if (ctx != NULL) {
242         BN_CTX_end(ctx);
243         BN_CTX_free(ctx);
244     }
245     if (buf != NULL) {
246         OPENSSL_cleanse(buf, num);
247         OPENSSL_free(buf);
248     }
249     return (r);
250 }
251
252 static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx)
253 {
254     BN_BLINDING *ret;
255     int got_write_lock = 0;
256     CRYPTO_THREADID cur;
257
258     CRYPTO_r_lock(CRYPTO_LOCK_RSA);
259
260     if (rsa->blinding == NULL) {
261         CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
262         CRYPTO_w_lock(CRYPTO_LOCK_RSA);
263         got_write_lock = 1;
264
265         if (rsa->blinding == NULL)
266             rsa->blinding = RSA_setup_blinding(rsa, ctx);
267     }
268
269     ret = rsa->blinding;
270     if (ret == NULL)
271         goto err;
272
273     CRYPTO_THREADID_current(&cur);
274     if (!CRYPTO_THREADID_cmp(&cur, BN_BLINDING_thread_id(ret))) {
275         /* rsa->blinding is ours! */
276
277         *local = 1;
278     } else {
279         /* resort to rsa->mt_blinding instead */
280
281         /*
282          * instructs rsa_blinding_convert(), rsa_blinding_invert() that the
283          * BN_BLINDING is shared, meaning that accesses require locks, and
284          * that the blinding factor must be stored outside the BN_BLINDING
285          */
286         *local = 0;
287
288         if (rsa->mt_blinding == NULL) {
289             if (!got_write_lock) {
290                 CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
291                 CRYPTO_w_lock(CRYPTO_LOCK_RSA);
292                 got_write_lock = 1;
293             }
294
295             if (rsa->mt_blinding == NULL)
296                 rsa->mt_blinding = RSA_setup_blinding(rsa, ctx);
297         }
298         ret = rsa->mt_blinding;
299     }
300
301  err:
302     if (got_write_lock)
303         CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
304     else
305         CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
306     return ret;
307 }
308
309 static int rsa_blinding_convert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
310                                 BN_CTX *ctx)
311 {
312     if (unblind == NULL)
313         /*
314          * Local blinding: store the unblinding factor in BN_BLINDING.
315          */
316         return BN_BLINDING_convert_ex(f, NULL, b, ctx);
317     else {
318         /*
319          * Shared blinding: store the unblinding factor outside BN_BLINDING.
320          */
321         int ret;
322         CRYPTO_w_lock(CRYPTO_LOCK_RSA_BLINDING);
323         ret = BN_BLINDING_convert_ex(f, unblind, b, ctx);
324         CRYPTO_w_unlock(CRYPTO_LOCK_RSA_BLINDING);
325         return ret;
326     }
327 }
328
329 static int rsa_blinding_invert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
330                                BN_CTX *ctx)
331 {
332     /*
333      * For local blinding, unblind is set to NULL, and BN_BLINDING_invert_ex
334      * will use the unblinding factor stored in BN_BLINDING. If BN_BLINDING
335      * is shared between threads, unblind must be non-null:
336      * BN_BLINDING_invert_ex will then use the local unblinding factor, and
337      * will only read the modulus from BN_BLINDING. In both cases it's safe
338      * to access the blinding without a lock.
339      */
340     return BN_BLINDING_invert_ex(f, unblind, b, ctx);
341 }
342
343 /* signing */
344 static int RSA_eay_private_encrypt(int flen, const unsigned char *from,
345                                    unsigned char *to, RSA *rsa, int padding)
346 {
347     BIGNUM *f, *ret, *res;
348     int i, num = 0, r = -1;
349     unsigned char *buf = NULL;
350     BN_CTX *ctx = NULL;
351     int local_blinding = 0;
352     /*
353      * Used only if the blinding structure is shared. A non-NULL unblind
354      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
355      * the unblinding factor outside the blinding structure.
356      */
357     BIGNUM *unblind = NULL;
358     BN_BLINDING *blinding = NULL;
359
360     if ((ctx = BN_CTX_new()) == NULL)
361         goto err;
362     BN_CTX_start(ctx);
363     f = BN_CTX_get(ctx);
364     ret = BN_CTX_get(ctx);
365     num = BN_num_bytes(rsa->n);
366     buf = OPENSSL_malloc(num);
367     if (!f || !ret || !buf) {
368         RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
369         goto err;
370     }
371
372     switch (padding) {
373     case RSA_PKCS1_PADDING:
374         i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
375         break;
376     case RSA_X931_PADDING:
377         i = RSA_padding_add_X931(buf, num, from, flen);
378         break;
379     case RSA_NO_PADDING:
380         i = RSA_padding_add_none(buf, num, from, flen);
381         break;
382     case RSA_SSLV23_PADDING:
383     default:
384         RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
385         goto err;
386     }
387     if (i <= 0)
388         goto err;
389
390     if (BN_bin2bn(buf, num, f) == NULL)
391         goto err;
392
393     if (BN_ucmp(f, rsa->n) >= 0) {
394         /* usually the padding functions would catch this */
395         RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
396                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
397         goto err;
398     }
399
400     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
401         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
402         if (blinding == NULL) {
403             RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
404             goto err;
405         }
406     }
407
408     if (blinding != NULL) {
409         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
410             RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
411             goto err;
412         }
413         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
414             goto err;
415     }
416
417     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
418         ((rsa->p != NULL) &&
419          (rsa->q != NULL) &&
420          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
421         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
422             goto err;
423     } else {
424         BIGNUM local_d;
425         BIGNUM *d = NULL;
426
427         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
428             BN_init(&local_d);
429             d = &local_d;
430             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
431         } else
432             d = rsa->d;
433
434         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
435             if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA,
436                                         rsa->n, ctx))
437                 goto err;
438
439         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
440                                    rsa->_method_mod_n))
441             goto err;
442     }
443
444     if (blinding)
445         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
446             goto err;
447
448     if (padding == RSA_X931_PADDING) {
449         BN_sub(f, rsa->n, ret);
450         if (BN_cmp(ret, f) > 0)
451             res = f;
452         else
453             res = ret;
454     } else
455         res = ret;
456
457     /*
458      * BN_bn2binpad puts in leading 0 bytes if the number is less than
459      * the length of the modulus.
460      */
461     r = bn_bn2binpad(res, to, num);
462  err:
463     if (ctx != NULL) {
464         BN_CTX_end(ctx);
465         BN_CTX_free(ctx);
466     }
467     if (buf != NULL) {
468         OPENSSL_cleanse(buf, num);
469         OPENSSL_free(buf);
470     }
471     return (r);
472 }
473
474 static int RSA_eay_private_decrypt(int flen, const unsigned char *from,
475                                    unsigned char *to, RSA *rsa, int padding)
476 {
477     BIGNUM *f, *ret;
478     int j, num = 0, r = -1;
479     unsigned char *buf = NULL;
480     BN_CTX *ctx = NULL;
481     int local_blinding = 0;
482     /*
483      * Used only if the blinding structure is shared. A non-NULL unblind
484      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
485      * the unblinding factor outside the blinding structure.
486      */
487     BIGNUM *unblind = NULL;
488     BN_BLINDING *blinding = NULL;
489
490     if ((ctx = BN_CTX_new()) == NULL)
491         goto err;
492     BN_CTX_start(ctx);
493     f = BN_CTX_get(ctx);
494     ret = BN_CTX_get(ctx);
495     num = BN_num_bytes(rsa->n);
496     buf = OPENSSL_malloc(num);
497     if (!f || !ret || !buf) {
498         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
499         goto err;
500     }
501
502     /*
503      * This check was for equality but PGP does evil things and chops off the
504      * top '0' bytes
505      */
506     if (flen > num) {
507         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,
508                RSA_R_DATA_GREATER_THAN_MOD_LEN);
509         goto err;
510     }
511
512     /* make data into a big number */
513     if (BN_bin2bn(from, (int)flen, f) == NULL)
514         goto err;
515
516     if (BN_ucmp(f, rsa->n) >= 0) {
517         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,
518                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
519         goto err;
520     }
521
522     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
523         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
524         if (blinding == NULL) {
525             RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
526             goto err;
527         }
528     }
529
530     if (blinding != NULL) {
531         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
532             RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
533             goto err;
534         }
535         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
536             goto err;
537     }
538
539     /* do the decrypt */
540     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
541         ((rsa->p != NULL) &&
542          (rsa->q != NULL) &&
543          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
544         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
545             goto err;
546     } else {
547         BIGNUM local_d;
548         BIGNUM *d = NULL;
549
550         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
551             d = &local_d;
552             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
553         } else
554             d = rsa->d;
555
556         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
557             if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA,
558                                         rsa->n, ctx))
559                 goto err;
560         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
561                                    rsa->_method_mod_n))
562             goto err;
563     }
564
565     if (blinding)
566         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
567             goto err;
568
569     j = bn_bn2binpad(ret, buf, num);
570
571     switch (padding) {
572     case RSA_PKCS1_PADDING:
573         r = RSA_padding_check_PKCS1_type_2(to, num, buf, j, num);
574         break;
575 # ifndef OPENSSL_NO_SHA
576     case RSA_PKCS1_OAEP_PADDING:
577         r = RSA_padding_check_PKCS1_OAEP(to, num, buf, j, num, NULL, 0);
578         break;
579 # endif
580     case RSA_SSLV23_PADDING:
581         r = RSA_padding_check_SSLv23(to, num, buf, j, num);
582         break;
583     case RSA_NO_PADDING:
584         memcpy(to, buf, (r = j));
585         break;
586     default:
587         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
588         goto err;
589     }
590     if (r < 0)
591         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
592
593  err:
594     if (ctx != NULL) {
595         BN_CTX_end(ctx);
596         BN_CTX_free(ctx);
597     }
598     if (buf != NULL) {
599         OPENSSL_cleanse(buf, num);
600         OPENSSL_free(buf);
601     }
602     return (r);
603 }
604
605 /* signature verification */
606 static int RSA_eay_public_decrypt(int flen, const unsigned char *from,
607                                   unsigned char *to, RSA *rsa, int padding)
608 {
609     BIGNUM *f, *ret;
610     int i, num = 0, r = -1;
611     unsigned char *buf = NULL;
612     BN_CTX *ctx = NULL;
613
614     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
615         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE);
616         return -1;
617     }
618
619     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
620         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
621         return -1;
622     }
623
624     /* for large moduli, enforce exponent limit */
625     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
626         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
627             RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
628             return -1;
629         }
630     }
631
632     if ((ctx = BN_CTX_new()) == NULL)
633         goto err;
634     BN_CTX_start(ctx);
635     f = BN_CTX_get(ctx);
636     ret = BN_CTX_get(ctx);
637     num = BN_num_bytes(rsa->n);
638     buf = OPENSSL_malloc(num);
639     if (!f || !ret || !buf) {
640         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, ERR_R_MALLOC_FAILURE);
641         goto err;
642     }
643
644     /*
645      * This check was for equality but PGP does evil things and chops off the
646      * top '0' bytes
647      */
648     if (flen > num) {
649         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_DATA_GREATER_THAN_MOD_LEN);
650         goto err;
651     }
652
653     if (BN_bin2bn(from, flen, f) == NULL)
654         goto err;
655
656     if (BN_ucmp(f, rsa->n) >= 0) {
657         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,
658                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
659         goto err;
660     }
661
662     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
663         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA,
664                                     rsa->n, ctx))
665             goto err;
666
667     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
668                                rsa->_method_mod_n))
669         goto err;
670
671     if ((padding == RSA_X931_PADDING) && ((ret->d[0] & 0xf) != 12))
672         if (!BN_sub(ret, rsa->n, ret))
673             goto err;
674
675     i = bn_bn2binpad(ret, buf, num);
676
677     switch (padding) {
678     case RSA_PKCS1_PADDING:
679         r = RSA_padding_check_PKCS1_type_1(to, num, buf, i, num);
680         break;
681     case RSA_X931_PADDING:
682         r = RSA_padding_check_X931(to, num, buf, i, num);
683         break;
684     case RSA_NO_PADDING:
685         memcpy(to, buf, (r = i));
686         break;
687     default:
688         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
689         goto err;
690     }
691     if (r < 0)
692         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
693
694  err:
695     if (ctx != NULL) {
696         BN_CTX_end(ctx);
697         BN_CTX_free(ctx);
698     }
699     if (buf != NULL) {
700         OPENSSL_cleanse(buf, num);
701         OPENSSL_free(buf);
702     }
703     return (r);
704 }
705
706 static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
707 {
708     BIGNUM *r1, *m1, *vrfy;
709     BIGNUM local_dmp1, local_dmq1, local_c, local_r1;
710     BIGNUM *dmp1, *dmq1, *c, *pr1;
711     int ret = 0, smooth = 0;
712
713     BN_CTX_start(ctx);
714     r1 = BN_CTX_get(ctx);
715     m1 = BN_CTX_get(ctx);
716     vrfy = BN_CTX_get(ctx);
717
718     {
719         BIGNUM local_p, local_q;
720         BIGNUM *p = NULL, *q = NULL;
721
722         /*
723          * Make sure BN_mod_inverse in Montgomery intialization uses the
724          * BN_FLG_CONSTTIME flag (unless RSA_FLAG_NO_CONSTTIME is set)
725          */
726         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
727             BN_init(&local_p);
728             p = &local_p;
729             BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
730
731             BN_init(&local_q);
732             q = &local_q;
733             BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
734         } else {
735             p = rsa->p;
736             q = rsa->q;
737         }
738
739         if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
740             if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_p, CRYPTO_LOCK_RSA,
741                                         p, ctx))
742                 goto err;
743             if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_q, CRYPTO_LOCK_RSA,
744                                         q, ctx))
745                 goto err;
746
747             smooth = (rsa->meth->bn_mod_exp == BN_mod_exp_mont)
748                      && (BN_num_bits(q) == BN_num_bits(p));
749         }
750     }
751
752     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
753         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA,
754                                     rsa->n, ctx))
755             goto err;
756
757     if (smooth) {
758         /*
759          * Conversion from Montgomery domain, a.k.a. Montgomery reduction,
760          * accepts values in [0-m*2^w) range. w is m's bit width rounded up
761          * to limb width. So that at the very least if |I| is fully reduced,
762          * i.e. less than p*q, we can count on from-to round to perform
763          * below modulo operations on |I|. Unlike BN_mod it's constant time.
764          */
765         if (/* m1 = I moq q */
766             !bn_from_mont_fixed_top(m1, I, rsa->_method_mod_q, ctx)
767             || !bn_to_mont_fixed_top(m1, m1, rsa->_method_mod_q, ctx)
768             /* m1 = m1^dmq1 mod q */
769             || !BN_mod_exp_mont_consttime(m1, m1, rsa->dmq1, rsa->q, ctx,
770                                           rsa->_method_mod_q)
771             /* r1 = I mod p */
772             || !bn_from_mont_fixed_top(r1, I, rsa->_method_mod_p, ctx)
773             || !bn_to_mont_fixed_top(r1, r1, rsa->_method_mod_p, ctx)
774             /* r1 = r1^dmp1 mod p */
775             || !BN_mod_exp_mont_consttime(r1, r1, rsa->dmp1, rsa->p, ctx,
776                                           rsa->_method_mod_p)
777             /* r1 = (r1 - m1) mod p */
778             /*
779              * bn_mod_sub_fixed_top is not regular modular subtraction,
780              * it can tolerate subtrahend to be larger than modulus, but
781              * not bit-wise wider. This makes up for uncommon q>p case,
782              * when |m1| can be larger than |rsa->p|.
783              */
784             || !bn_mod_sub_fixed_top(r1, r1, m1, rsa->p)
785
786             /* r1 = r1 * iqmp mod p */
787             || !bn_to_mont_fixed_top(r1, r1, rsa->_method_mod_p, ctx)
788             || !bn_mul_mont_fixed_top(r1, r1, rsa->iqmp, rsa->_method_mod_p,
789                                       ctx)
790             /* r0 = r1 * q + m1 */
791             || !bn_mul_fixed_top(r0, r1, rsa->q, ctx)
792             || !bn_mod_add_fixed_top(r0, r0, m1, rsa->n))
793             goto err;
794
795         goto tail;
796     }
797
798     /* compute I mod q */
799     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
800         c = &local_c;
801         BN_with_flags(c, I, BN_FLG_CONSTTIME);
802         if (!BN_mod(r1, c, rsa->q, ctx))
803             goto err;
804     } else {
805         if (!BN_mod(r1, I, rsa->q, ctx))
806             goto err;
807     }
808
809     /* compute r1^dmq1 mod q */
810     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
811         dmq1 = &local_dmq1;
812         BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
813     } else
814         dmq1 = rsa->dmq1;
815     if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx, rsa->_method_mod_q))
816         goto err;
817
818     /* compute I mod p */
819     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
820         c = &local_c;
821         BN_with_flags(c, I, BN_FLG_CONSTTIME);
822         if (!BN_mod(r1, c, rsa->p, ctx))
823             goto err;
824     } else {
825         if (!BN_mod(r1, I, rsa->p, ctx))
826             goto err;
827     }
828
829     /* compute r1^dmp1 mod p */
830     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
831         dmp1 = &local_dmp1;
832         BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
833     } else
834         dmp1 = rsa->dmp1;
835     if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx, rsa->_method_mod_p))
836         goto err;
837
838     if (!BN_sub(r0, r0, m1))
839         goto err;
840     /*
841      * This will help stop the size of r0 increasing, which does affect the
842      * multiply if it optimised for a power of 2 size
843      */
844     if (BN_is_negative(r0))
845         if (!BN_add(r0, r0, rsa->p))
846             goto err;
847
848     if (!BN_mul(r1, r0, rsa->iqmp, ctx))
849         goto err;
850
851     /* Turn BN_FLG_CONSTTIME flag on before division operation */
852     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
853         pr1 = &local_r1;
854         BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
855     } else
856         pr1 = r1;
857     if (!BN_mod(r0, pr1, rsa->p, ctx))
858         goto err;
859
860     /*
861      * If p < q it is occasionally possible for the correction of adding 'p'
862      * if r0 is negative above to leave the result still negative. This can
863      * break the private key operations: the following second correction
864      * should *always* correct this rare occurrence. This will *never* happen
865      * with OpenSSL generated keys because they ensure p > q [steve]
866      */
867     if (BN_is_negative(r0))
868         if (!BN_add(r0, r0, rsa->p))
869             goto err;
870     if (!BN_mul(r1, r0, rsa->q, ctx))
871         goto err;
872     if (!BN_add(r0, r1, m1))
873         goto err;
874
875  tail:
876     if (rsa->e && rsa->n) {
877         if (rsa->meth->bn_mod_exp == BN_mod_exp_mont) {
878             if (!BN_mod_exp_mont(vrfy, r0, rsa->e, rsa->n, ctx,
879                                  rsa->_method_mod_n))
880                 goto err;
881         } else {
882             bn_correct_top(r0);
883             if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
884                                        rsa->_method_mod_n))
885                 goto err;
886         }
887         /*
888          * If 'I' was greater than (or equal to) rsa->n, the operation will
889          * be equivalent to using 'I mod n'. However, the result of the
890          * verify will *always* be less than 'n' so we don't check for
891          * absolute equality, just congruency.
892          */
893         if (!BN_sub(vrfy, vrfy, I))
894             goto err;
895         if (BN_is_zero(vrfy)) {
896             bn_correct_top(r0);
897             ret = 1;
898             goto err;   /* not actually error */
899         }
900         if (!BN_mod(vrfy, vrfy, rsa->n, ctx))
901             goto err;
902         if (BN_is_negative(vrfy))
903             if (!BN_add(vrfy, vrfy, rsa->n))
904                 goto err;
905         if (!BN_is_zero(vrfy)) {
906             /*
907              * 'I' and 'vrfy' aren't congruent mod n. Don't leak
908              * miscalculated CRT output, just do a raw (slower) mod_exp and
909              * return that instead.
910              */
911
912             BIGNUM local_d;
913             BIGNUM *d = NULL;
914
915             if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
916                 d = &local_d;
917                 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
918             } else
919                 d = rsa->d;
920             if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
921                                        rsa->_method_mod_n))
922                 goto err;
923         }
924     }
925     /*
926      * It's unfortunate that we have to bn_correct_top(r0). What hopefully
927      * saves the day is that correction is highly unlike, and private key
928      * operations are customarily performed on blinded message. Which means
929      * that attacker won't observe correlation with chosen plaintext.
930      * Secondly, remaining code would still handle it in same computational
931      * time and even conceal memory access pattern around corrected top.
932      */
933     bn_correct_top(r0);
934     ret = 1;
935  err:
936     BN_CTX_end(ctx);
937     return (ret);
938 }
939
940 static int RSA_eay_init(RSA *rsa)
941 {
942     rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
943     return (1);
944 }
945
946 static int RSA_eay_finish(RSA *rsa)
947 {
948     if (rsa->_method_mod_n != NULL)
949         BN_MONT_CTX_free(rsa->_method_mod_n);
950     if (rsa->_method_mod_p != NULL)
951         BN_MONT_CTX_free(rsa->_method_mod_p);
952     if (rsa->_method_mod_q != NULL)
953         BN_MONT_CTX_free(rsa->_method_mod_q);
954     return (1);
955 }
956
957 #endif