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