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