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