]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - crypto/openssl/crypto/rsa/rsa_eay.c
Fix multiple OpenSSL vulnerabilities.
[FreeBSD/releng/9.3.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-2006 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
118 #if !defined(RSA_NULL) && !defined(OPENSSL_FIPS)
119
120 static int RSA_eay_public_encrypt(int flen, const unsigned char *from,
121                                   unsigned char *to, RSA *rsa, int padding);
122 static int RSA_eay_private_encrypt(int flen, const unsigned char *from,
123                                    unsigned char *to, RSA *rsa, int padding);
124 static int RSA_eay_public_decrypt(int flen, const unsigned char *from,
125                                   unsigned char *to, RSA *rsa, int padding);
126 static int RSA_eay_private_decrypt(int flen, const unsigned char *from,
127                                    unsigned char *to, RSA *rsa, int padding);
128 static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa,
129                            BN_CTX *ctx);
130 static int RSA_eay_init(RSA *rsa);
131 static int RSA_eay_finish(RSA *rsa);
132 static RSA_METHOD rsa_pkcs1_eay_meth = {
133     "Eric Young's PKCS#1 RSA",
134     RSA_eay_public_encrypt,
135     RSA_eay_public_decrypt,     /* signature verification */
136     RSA_eay_private_encrypt,    /* signing */
137     RSA_eay_private_decrypt,
138     RSA_eay_mod_exp,
139     BN_mod_exp_mont,            /* XXX probably we should not use Montgomery
140                                  * if e == 3 */
141     RSA_eay_init,
142     RSA_eay_finish,
143     0,                          /* flags */
144     NULL,
145     0,                          /* rsa_sign */
146     0,                          /* rsa_verify */
147     NULL                        /* rsa_keygen */
148 };
149
150 const RSA_METHOD *RSA_PKCS1_SSLeay(void)
151 {
152     return (&rsa_pkcs1_eay_meth);
153 }
154
155 static int RSA_eay_public_encrypt(int flen, const unsigned char *from,
156                                   unsigned char *to, RSA *rsa, int padding)
157 {
158     BIGNUM *f, *ret;
159     int i, j, k, num = 0, r = -1;
160     unsigned char *buf = NULL;
161     BN_CTX *ctx = NULL;
162
163     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
164         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_MODULUS_TOO_LARGE);
165         return -1;
166     }
167
168     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
169         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
170         return -1;
171     }
172
173     /* for large moduli, enforce exponent limit */
174     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
175         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
176             RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
177             return -1;
178         }
179     }
180
181     if ((ctx = BN_CTX_new()) == NULL)
182         goto err;
183     BN_CTX_start(ctx);
184     f = BN_CTX_get(ctx);
185     ret = BN_CTX_get(ctx);
186     num = BN_num_bytes(rsa->n);
187     buf = OPENSSL_malloc(num);
188     if (!f || !ret || !buf) {
189         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, ERR_R_MALLOC_FAILURE);
190         goto err;
191     }
192
193     switch (padding) {
194     case RSA_PKCS1_PADDING:
195         i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
196         break;
197 # ifndef OPENSSL_NO_SHA
198     case RSA_PKCS1_OAEP_PADDING:
199         i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
200         break;
201 # endif
202     case RSA_SSLV23_PADDING:
203         i = RSA_padding_add_SSLv23(buf, num, from, flen);
204         break;
205     case RSA_NO_PADDING:
206         i = RSA_padding_add_none(buf, num, from, flen);
207         break;
208     default:
209         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
210         goto err;
211     }
212     if (i <= 0)
213         goto err;
214
215     if (BN_bin2bn(buf, num, f) == NULL)
216         goto err;
217
218     if (BN_ucmp(f, rsa->n) >= 0) {
219         /* usually the padding functions would catch this */
220         RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT,
221                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
222         goto err;
223     }
224
225     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
226         if (!BN_MONT_CTX_set_locked
227             (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
228             goto err;
229
230     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
231                                rsa->_method_mod_n))
232         goto err;
233
234     /*
235      * put in leading 0 bytes if the number is less than the length of the
236      * modulus
237      */
238     j = BN_num_bytes(ret);
239     i = BN_bn2bin(ret, &(to[num - j]));
240     for (k = 0; k < (num - i); k++)
241         to[k] = 0;
242
243     r = num;
244  err:
245     if (ctx != NULL) {
246         BN_CTX_end(ctx);
247         BN_CTX_free(ctx);
248     }
249     if (buf != NULL) {
250         OPENSSL_cleanse(buf, num);
251         OPENSSL_free(buf);
252     }
253     return (r);
254 }
255
256 static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx)
257 {
258     BN_BLINDING *ret;
259     int got_write_lock = 0;
260
261     CRYPTO_r_lock(CRYPTO_LOCK_RSA);
262
263     if (rsa->blinding == NULL) {
264         CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
265         CRYPTO_w_lock(CRYPTO_LOCK_RSA);
266         got_write_lock = 1;
267
268         if (rsa->blinding == NULL)
269             rsa->blinding = RSA_setup_blinding(rsa, ctx);
270     }
271
272     ret = rsa->blinding;
273     if (ret == NULL)
274         goto err;
275
276     if (BN_BLINDING_get_thread_id(ret) == CRYPTO_thread_id()) {
277         /* rsa->blinding is ours! */
278
279         *local = 1;
280     } else {
281         /* resort to rsa->mt_blinding instead */
282
283         /*
284          * instructs rsa_blinding_convert(), rsa_blinding_invert() that the
285          * BN_BLINDING is shared, meaning that accesses require locks, and
286          * that the blinding factor must be stored outside the BN_BLINDING
287          */
288         *local = 0;
289
290         if (rsa->mt_blinding == NULL) {
291             if (!got_write_lock) {
292                 CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
293                 CRYPTO_w_lock(CRYPTO_LOCK_RSA);
294                 got_write_lock = 1;
295             }
296
297             if (rsa->mt_blinding == NULL)
298                 rsa->mt_blinding = RSA_setup_blinding(rsa, ctx);
299         }
300         ret = rsa->mt_blinding;
301     }
302
303  err:
304     if (got_write_lock)
305         CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
306     else
307         CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
308     return ret;
309 }
310
311 static int rsa_blinding_convert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
312                                 BN_CTX *ctx)
313 {
314     if (unblind == NULL)
315         /*
316          * Local blinding: store the unblinding factor in BN_BLINDING.
317          */
318         return BN_BLINDING_convert_ex(f, NULL, b, ctx);
319     else {
320         /*
321          * Shared blinding: store the unblinding factor outside BN_BLINDING.
322          */
323         int ret;
324         CRYPTO_w_lock(CRYPTO_LOCK_RSA_BLINDING);
325         ret = BN_BLINDING_convert_ex(f, unblind, b, ctx);
326         CRYPTO_w_unlock(CRYPTO_LOCK_RSA_BLINDING);
327         return ret;
328     }
329 }
330
331 static int rsa_blinding_invert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
332                                BN_CTX *ctx)
333 {
334     /*
335      * For local blinding, unblind is set to NULL, and BN_BLINDING_invert_ex
336      * will use the unblinding factor stored in BN_BLINDING. If BN_BLINDING
337      * is shared between threads, unblind must be non-null:
338      * BN_BLINDING_invert_ex will then use the local unblinding factor, and
339      * will only read the modulus from BN_BLINDING. In both cases it's safe
340      * to access the blinding without a lock.
341      */
342     return BN_BLINDING_invert_ex(f, unblind, b, ctx);
343 }
344
345 /* signing */
346 static int RSA_eay_private_encrypt(int flen, const unsigned char *from,
347                                    unsigned char *to, RSA *rsa, int padding)
348 {
349     BIGNUM *f, *ret, *res;
350     int i, j, k, num = 0, r = -1;
351     unsigned char *buf = NULL;
352     BN_CTX *ctx = NULL;
353     int local_blinding = 0;
354     /*
355      * Used only if the blinding structure is shared. A non-NULL unblind
356      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
357      * the unblinding factor outside the blinding structure.
358      */
359     BIGNUM *unblind = NULL;
360     BN_BLINDING *blinding = NULL;
361
362     if ((ctx = BN_CTX_new()) == NULL)
363         goto err;
364     BN_CTX_start(ctx);
365     f = BN_CTX_get(ctx);
366     ret = BN_CTX_get(ctx);
367     num = BN_num_bytes(rsa->n);
368     buf = OPENSSL_malloc(num);
369     if (!f || !ret || !buf) {
370         RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
371         goto err;
372     }
373
374     switch (padding) {
375     case RSA_PKCS1_PADDING:
376         i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
377         break;
378     case RSA_X931_PADDING:
379         i = RSA_padding_add_X931(buf, num, from, flen);
380         break;
381     case RSA_NO_PADDING:
382         i = RSA_padding_add_none(buf, num, from, flen);
383         break;
384     case RSA_SSLV23_PADDING:
385     default:
386         RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
387         goto err;
388     }
389     if (i <= 0)
390         goto err;
391
392     if (BN_bin2bn(buf, num, f) == NULL)
393         goto err;
394
395     if (BN_ucmp(f, rsa->n) >= 0) {
396         /* usually the padding functions would catch this */
397         RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
398                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
399         goto err;
400     }
401
402     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
403         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
404         if (blinding == NULL) {
405             RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
406             goto err;
407         }
408     }
409
410     if (blinding != NULL) {
411         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
412             RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
413             goto err;
414         }
415         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
416             goto err;
417     }
418
419     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
420         ((rsa->p != NULL) &&
421          (rsa->q != NULL) &&
422          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
423         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
424             goto err;
425     } else {
426         BIGNUM local_d;
427         BIGNUM *d = NULL;
428
429         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
430             BN_init(&local_d);
431             d = &local_d;
432             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
433         } else
434             d = rsa->d;
435
436         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
437             if (!BN_MONT_CTX_set_locked
438                 (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
439                 goto err;
440
441         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
442                                    rsa->_method_mod_n))
443             goto err;
444     }
445
446     if (blinding)
447         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
448             goto err;
449
450     if (padding == RSA_X931_PADDING) {
451         BN_sub(f, rsa->n, ret);
452         if (BN_cmp(ret, f) > 0)
453             res = f;
454         else
455             res = ret;
456     } else
457         res = ret;
458
459     /*
460      * put in leading 0 bytes if the number is less than the length of the
461      * modulus
462      */
463     j = BN_num_bytes(res);
464     i = BN_bn2bin(res, &(to[num - j]));
465     for (k = 0; k < (num - i); k++)
466         to[k] = 0;
467
468     r = num;
469  err:
470     if (ctx != NULL) {
471         BN_CTX_end(ctx);
472         BN_CTX_free(ctx);
473     }
474     if (buf != NULL) {
475         OPENSSL_cleanse(buf, num);
476         OPENSSL_free(buf);
477     }
478     return (r);
479 }
480
481 static int RSA_eay_private_decrypt(int flen, const unsigned char *from,
482                                    unsigned char *to, RSA *rsa, int padding)
483 {
484     BIGNUM *f, *ret;
485     int j, num = 0, r = -1;
486     unsigned char *p;
487     unsigned char *buf = NULL;
488     BN_CTX *ctx = NULL;
489     int local_blinding = 0;
490     /*
491      * Used only if the blinding structure is shared. A non-NULL unblind
492      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
493      * the unblinding factor outside the blinding structure.
494      */
495     BIGNUM *unblind = NULL;
496     BN_BLINDING *blinding = NULL;
497
498     if ((ctx = BN_CTX_new()) == NULL)
499         goto err;
500     BN_CTX_start(ctx);
501     f = BN_CTX_get(ctx);
502     ret = BN_CTX_get(ctx);
503     num = BN_num_bytes(rsa->n);
504     buf = OPENSSL_malloc(num);
505     if (!f || !ret || !buf) {
506         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
507         goto err;
508     }
509
510     /*
511      * This check was for equality but PGP does evil things and chops off the
512      * top '0' bytes
513      */
514     if (flen > num) {
515         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,
516                RSA_R_DATA_GREATER_THAN_MOD_LEN);
517         goto err;
518     }
519
520     /* make data into a big number */
521     if (BN_bin2bn(from, (int)flen, f) == NULL)
522         goto err;
523
524     if (BN_ucmp(f, rsa->n) >= 0) {
525         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,
526                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
527         goto err;
528     }
529
530     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
531         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
532         if (blinding == NULL) {
533             RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
534             goto err;
535         }
536     }
537
538     if (blinding != NULL) {
539         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
540             RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
541             goto err;
542         }
543         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
544             goto err;
545     }
546
547     /* do the decrypt */
548     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
549         ((rsa->p != NULL) &&
550          (rsa->q != NULL) &&
551          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
552         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
553             goto err;
554     } else {
555         BIGNUM local_d;
556         BIGNUM *d = NULL;
557
558         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
559             d = &local_d;
560             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
561         } else
562             d = rsa->d;
563
564         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
565             if (!BN_MONT_CTX_set_locked
566                 (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
567                 goto err;
568         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
569                                    rsa->_method_mod_n))
570             goto err;
571     }
572
573     if (blinding)
574         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
575             goto err;
576
577     p = buf;
578     j = BN_bn2bin(ret, p);      /* j is only used with no-padding mode */
579
580     switch (padding) {
581     case RSA_PKCS1_PADDING:
582         r = RSA_padding_check_PKCS1_type_2(to, num, buf, j, num);
583         break;
584 # ifndef OPENSSL_NO_SHA
585     case RSA_PKCS1_OAEP_PADDING:
586         r = RSA_padding_check_PKCS1_OAEP(to, num, buf, j, num, NULL, 0);
587         break;
588 # endif
589     case RSA_SSLV23_PADDING:
590         r = RSA_padding_check_SSLv23(to, num, buf, j, num);
591         break;
592     case RSA_NO_PADDING:
593         r = RSA_padding_check_none(to, num, buf, j, num);
594         break;
595     default:
596         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
597         goto err;
598     }
599     if (r < 0)
600         RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
601
602  err:
603     if (ctx != NULL) {
604         BN_CTX_end(ctx);
605         BN_CTX_free(ctx);
606     }
607     if (buf != NULL) {
608         OPENSSL_cleanse(buf, num);
609         OPENSSL_free(buf);
610     }
611     return (r);
612 }
613
614 /* signature verification */
615 static int RSA_eay_public_decrypt(int flen, const unsigned char *from,
616                                   unsigned char *to, RSA *rsa, int padding)
617 {
618     BIGNUM *f, *ret;
619     int i, num = 0, r = -1;
620     unsigned char *p;
621     unsigned char *buf = NULL;
622     BN_CTX *ctx = NULL;
623
624     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
625         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE);
626         return -1;
627     }
628
629     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
630         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
631         return -1;
632     }
633
634     /* for large moduli, enforce exponent limit */
635     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
636         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
637             RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
638             return -1;
639         }
640     }
641
642     if ((ctx = BN_CTX_new()) == NULL)
643         goto err;
644     BN_CTX_start(ctx);
645     f = BN_CTX_get(ctx);
646     ret = BN_CTX_get(ctx);
647     num = BN_num_bytes(rsa->n);
648     buf = OPENSSL_malloc(num);
649     if (!f || !ret || !buf) {
650         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, ERR_R_MALLOC_FAILURE);
651         goto err;
652     }
653
654     /*
655      * This check was for equality but PGP does evil things and chops off the
656      * top '0' bytes
657      */
658     if (flen > num) {
659         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_DATA_GREATER_THAN_MOD_LEN);
660         goto err;
661     }
662
663     if (BN_bin2bn(from, flen, f) == NULL)
664         goto err;
665
666     if (BN_ucmp(f, rsa->n) >= 0) {
667         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,
668                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
669         goto err;
670     }
671
672     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
673         if (!BN_MONT_CTX_set_locked
674             (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
675             goto err;
676
677     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
678                                rsa->_method_mod_n))
679         goto err;
680
681     if ((padding == RSA_X931_PADDING) && ((ret->d[0] & 0xf) != 12))
682         if (!BN_sub(ret, rsa->n, ret))
683             goto err;
684
685     p = buf;
686     i = BN_bn2bin(ret, p);
687
688     switch (padding) {
689     case RSA_PKCS1_PADDING:
690         r = RSA_padding_check_PKCS1_type_1(to, num, buf, i, num);
691         break;
692     case RSA_X931_PADDING:
693         r = RSA_padding_check_X931(to, num, buf, i, num);
694         break;
695     case RSA_NO_PADDING:
696         r = RSA_padding_check_none(to, num, buf, i, num);
697         break;
698     default:
699         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
700         goto err;
701     }
702     if (r < 0)
703         RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
704
705  err:
706     if (ctx != NULL) {
707         BN_CTX_end(ctx);
708         BN_CTX_free(ctx);
709     }
710     if (buf != NULL) {
711         OPENSSL_cleanse(buf, num);
712         OPENSSL_free(buf);
713     }
714     return (r);
715 }
716
717 static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
718 {
719     BIGNUM *r1, *m1, *vrfy;
720     BIGNUM local_dmp1, local_dmq1, local_c, local_r1;
721     BIGNUM *dmp1, *dmq1, *c, *pr1;
722     int ret = 0;
723
724     BN_CTX_start(ctx);
725     r1 = BN_CTX_get(ctx);
726     m1 = BN_CTX_get(ctx);
727     vrfy = BN_CTX_get(ctx);
728
729     {
730         BIGNUM local_p, local_q;
731         BIGNUM *p = NULL, *q = NULL;
732
733         /*
734          * Make sure BN_mod_inverse in Montgomery intialization uses the
735          * BN_FLG_CONSTTIME flag (unless RSA_FLAG_NO_CONSTTIME is set)
736          */
737         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
738             BN_init(&local_p);
739             p = &local_p;
740             BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
741
742             BN_init(&local_q);
743             q = &local_q;
744             BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
745         } else {
746             p = rsa->p;
747             q = rsa->q;
748         }
749
750         if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
751             if (!BN_MONT_CTX_set_locked
752                 (&rsa->_method_mod_p, CRYPTO_LOCK_RSA, p, ctx))
753                 goto err;
754             if (!BN_MONT_CTX_set_locked
755                 (&rsa->_method_mod_q, CRYPTO_LOCK_RSA, q, ctx))
756                 goto err;
757         }
758     }
759
760     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
761         if (!BN_MONT_CTX_set_locked
762             (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
763             goto err;
764
765     /* compute I mod q */
766     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
767         c = &local_c;
768         BN_with_flags(c, I, BN_FLG_CONSTTIME);
769         if (!BN_mod(r1, c, rsa->q, ctx))
770             goto err;
771     } else {
772         if (!BN_mod(r1, I, rsa->q, ctx))
773             goto err;
774     }
775
776     /* compute r1^dmq1 mod q */
777     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
778         dmq1 = &local_dmq1;
779         BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
780     } else
781         dmq1 = rsa->dmq1;
782     if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx, rsa->_method_mod_q))
783         goto err;
784
785     /* compute I mod p */
786     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
787         c = &local_c;
788         BN_with_flags(c, I, BN_FLG_CONSTTIME);
789         if (!BN_mod(r1, c, rsa->p, ctx))
790             goto err;
791     } else {
792         if (!BN_mod(r1, I, rsa->p, ctx))
793             goto err;
794     }
795
796     /* compute r1^dmp1 mod p */
797     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
798         dmp1 = &local_dmp1;
799         BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
800     } else
801         dmp1 = rsa->dmp1;
802     if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx, rsa->_method_mod_p))
803         goto err;
804
805     if (!BN_sub(r0, r0, m1))
806         goto err;
807     /*
808      * This will help stop the size of r0 increasing, which does affect the
809      * multiply if it optimised for a power of 2 size
810      */
811     if (BN_is_negative(r0))
812         if (!BN_add(r0, r0, rsa->p))
813             goto err;
814
815     if (!BN_mul(r1, r0, rsa->iqmp, ctx))
816         goto err;
817
818     /* Turn BN_FLG_CONSTTIME flag on before division operation */
819     if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
820         pr1 = &local_r1;
821         BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
822     } else
823         pr1 = r1;
824     if (!BN_mod(r0, pr1, rsa->p, ctx))
825         goto err;
826
827     /*
828      * If p < q it is occasionally possible for the correction of adding 'p'
829      * if r0 is negative above to leave the result still negative. This can
830      * break the private key operations: the following second correction
831      * should *always* correct this rare occurrence. This will *never* happen
832      * with OpenSSL generated keys because they ensure p > q [steve]
833      */
834     if (BN_is_negative(r0))
835         if (!BN_add(r0, r0, rsa->p))
836             goto err;
837     if (!BN_mul(r1, r0, rsa->q, ctx))
838         goto err;
839     if (!BN_add(r0, r1, m1))
840         goto err;
841
842     if (rsa->e && rsa->n) {
843         if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
844                                    rsa->_method_mod_n))
845             goto err;
846         /*
847          * If 'I' was greater than (or equal to) rsa->n, the operation will
848          * be equivalent to using 'I mod n'. However, the result of the
849          * verify will *always* be less than 'n' so we don't check for
850          * absolute equality, just congruency.
851          */
852         if (!BN_sub(vrfy, vrfy, I))
853             goto err;
854         if (!BN_mod(vrfy, vrfy, rsa->n, ctx))
855             goto err;
856         if (BN_is_negative(vrfy))
857             if (!BN_add(vrfy, vrfy, rsa->n))
858                 goto err;
859         if (!BN_is_zero(vrfy)) {
860             /*
861              * 'I' and 'vrfy' aren't congruent mod n. Don't leak
862              * miscalculated CRT output, just do a raw (slower) mod_exp and
863              * return that instead.
864              */
865
866             BIGNUM local_d;
867             BIGNUM *d = NULL;
868
869             if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
870                 d = &local_d;
871                 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
872             } else
873                 d = rsa->d;
874             if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
875                                        rsa->_method_mod_n))
876                 goto err;
877         }
878     }
879     ret = 1;
880  err:
881     BN_CTX_end(ctx);
882     return (ret);
883 }
884
885 static int RSA_eay_init(RSA *rsa)
886 {
887     rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
888     return (1);
889 }
890
891 static int RSA_eay_finish(RSA *rsa)
892 {
893     if (rsa->_method_mod_n != NULL)
894         BN_MONT_CTX_free(rsa->_method_mod_n);
895     if (rsa->_method_mod_p != NULL)
896         BN_MONT_CTX_free(rsa->_method_mod_p);
897     if (rsa->_method_mod_q != NULL)
898         BN_MONT_CTX_free(rsa->_method_mod_q);
899     return (1);
900 }
901
902 #endif