xref: /openbsd-src/lib/libcrypto/rsa/rsa_eay.c (revision 4fcf65c5c59fcf6124cf9f1fd81aa546850f974c)
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 	BN_init(&f);
365 	BN_init(&ret);
366 
367 	if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS)
368 		{
369 		RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_MODULUS_TOO_LARGE);
370 		return -1;
371 		}
372 
373 	if (BN_ucmp(rsa->n, rsa->e) <= 0)
374 		{
375 		RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
376 		return -1;
377 		}
378 
379 	/* for large moduli, enforce exponent limit */
380 	if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS)
381 		{
382 		if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS)
383 			{
384 			RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
385 			return -1;
386 			}
387 		}
388 
389 	if ((ctx=BN_CTX_new()) == NULL) goto err;
390 	BN_CTX_start(ctx);
391 	f   = BN_CTX_get(ctx);
392 	br  = BN_CTX_get(ctx);
393 	ret = BN_CTX_get(ctx);
394 	num = BN_num_bytes(rsa->n);
395 	buf = OPENSSL_malloc(num);
396 	if(!f || !ret || !buf)
397 		{
398 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,ERR_R_MALLOC_FAILURE);
399 		goto err;
400 		}
401 
402 	switch (padding)
403 		{
404 	case RSA_PKCS1_PADDING:
405 		i=RSA_padding_add_PKCS1_type_1(buf,num,from,flen);
406 		break;
407 	case RSA_X931_PADDING:
408 		i=RSA_padding_add_X931(buf,num,from,flen);
409 		break;
410 	case RSA_NO_PADDING:
411 		i=RSA_padding_add_none(buf,num,from,flen);
412 		break;
413 	case RSA_SSLV23_PADDING:
414 	default:
415 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
416 		goto err;
417 		}
418 	if (i <= 0) goto err;
419 
420 	if (BN_bin2bn(buf,num,f) == NULL) goto err;
421 
422 	if (BN_ucmp(f, rsa->n) >= 0)
423 		{
424 		/* usually the padding functions would catch this */
425 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
426 		goto err;
427 		}
428 
429 	if (!(rsa->flags & RSA_FLAG_NO_BLINDING))
430 		{
431 		blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
432 		if (blinding == NULL)
433 			{
434 			RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
435 			goto err;
436 			}
437 		}
438 
439 	if (blinding != NULL)
440 		if (!rsa_blinding_convert(blinding, local_blinding, f, br, ctx))
441 			goto err;
442 
443 	if ( (rsa->flags & RSA_FLAG_EXT_PKEY) ||
444 		((rsa->p != NULL) &&
445 		(rsa->q != NULL) &&
446 		(rsa->dmp1 != NULL) &&
447 		(rsa->dmq1 != NULL) &&
448 		(rsa->iqmp != NULL)) )
449 		{
450 		if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx)) goto err;
451 		}
452 	else
453 		{
454 		BIGNUM local_d;
455 		BIGNUM *d = NULL;
456 
457 		if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
458 			{
459 			BN_init(&local_d);
460 			d = &local_d;
461 			BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
462 			}
463 		else
464 			d= rsa->d;
465 
466 		MONT_HELPER(rsa->_method_mod_n, ctx, rsa->n, rsa->flags & RSA_FLAG_CACHE_PUBLIC, goto err);
467 
468 		if (!rsa->meth->bn_mod_exp(ret,f,d,rsa->n,ctx,
469 				rsa->_method_mod_n)) goto err;
470 		}
471 
472 	if (blinding)
473 		if (!rsa_blinding_invert(blinding, local_blinding, ret, br, ctx))
474 			goto err;
475 
476 	if (padding == RSA_X931_PADDING)
477 		{
478 		BN_sub(f, rsa->n, ret);
479 		if (BN_cmp(ret, f))
480 			res = f;
481 		else
482 			res = ret;
483 		}
484 	else
485 		res = ret;
486 
487 	/* put in leading 0 bytes if the number is less than the
488 	 * length of the modulus */
489 	j=BN_num_bytes(res);
490 	i=BN_bn2bin(res,&(to[num-j]));
491 	for (k=0; k<(num-i); k++)
492 		to[k]=0;
493 
494 	r=num;
495 err:
496 	if (ctx != NULL)
497 		{
498 		BN_CTX_end(ctx);
499 		BN_CTX_free(ctx);
500 		}
501 	if (buf != NULL)
502 		{
503 		OPENSSL_cleanse(buf,num);
504 		OPENSSL_free(buf);
505 		}
506 	return(r);
507 	}
508 
509 static int RSA_eay_private_decrypt(int flen, const unsigned char *from,
510 	     unsigned char *to, RSA *rsa, int padding)
511 	{
512 	BIGNUM *f, *ret, *br;
513 	int j,num=0,r= -1;
514 	unsigned char *p;
515 	unsigned char *buf=NULL;
516 	BN_CTX *ctx=NULL;
517 	int local_blinding = 0;
518 	BN_BLINDING *blinding = NULL;
519 
520 	if((ctx = BN_CTX_new()) == NULL) goto err;
521 	BN_CTX_start(ctx);
522 	f   = BN_CTX_get(ctx);
523 	br  = BN_CTX_get(ctx);
524 	ret = BN_CTX_get(ctx);
525 	num = BN_num_bytes(rsa->n);
526 	buf = OPENSSL_malloc(num);
527 	if(!f || !ret || !buf)
528 		{
529 		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,ERR_R_MALLOC_FAILURE);
530 		goto err;
531 		}
532 
533 	/* This check was for equality but PGP does evil things
534 	 * and chops off the top '0' bytes */
535 	if (flen > num)
536 		{
537 		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_DATA_GREATER_THAN_MOD_LEN);
538 		goto err;
539 		}
540 
541 	/* make data into a big number */
542 	if (BN_bin2bn(from,(int)flen,f) == NULL) goto err;
543 
544 	if (BN_ucmp(f, rsa->n) >= 0)
545 		{
546 		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
547 		goto err;
548 		}
549 
550 	if (!(rsa->flags & RSA_FLAG_NO_BLINDING))
551 		{
552 		blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
553 		if (blinding == NULL)
554 			{
555 			RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
556 			goto err;
557 			}
558 		}
559 
560 	if (blinding != NULL)
561 		if (!rsa_blinding_convert(blinding, local_blinding, f, br, ctx))
562 			goto err;
563 
564 	/* do the decrypt */
565 	if ( (rsa->flags & RSA_FLAG_EXT_PKEY) ||
566 		((rsa->p != NULL) &&
567 		(rsa->q != NULL) &&
568 		(rsa->dmp1 != NULL) &&
569 		(rsa->dmq1 != NULL) &&
570 		(rsa->iqmp != NULL)) )
571 		{
572 		if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx)) goto err;
573 		}
574 	else
575 		{
576 		BIGNUM local_d;
577 		BIGNUM *d = NULL;
578 
579 		if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
580 			{
581 			d = &local_d;
582 			BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
583 			}
584 		else
585 			d = rsa->d;
586 
587 		MONT_HELPER(rsa->_method_mod_n, ctx, rsa->n, rsa->flags & RSA_FLAG_CACHE_PUBLIC, goto err);
588 		if (!rsa->meth->bn_mod_exp(ret,f,d,rsa->n,ctx,
589 				rsa->_method_mod_n))
590 		  goto err;
591 		}
592 
593 	if (blinding)
594 		if (!rsa_blinding_invert(blinding, local_blinding, ret, br, ctx))
595 			goto err;
596 
597 	p=buf;
598 	j=BN_bn2bin(ret,p); /* j is only used with no-padding mode */
599 
600 	switch (padding)
601 		{
602 	case RSA_PKCS1_PADDING:
603 		r=RSA_padding_check_PKCS1_type_2(to,num,buf,j,num);
604 		break;
605 #ifndef OPENSSL_NO_SHA
606         case RSA_PKCS1_OAEP_PADDING:
607 	        r=RSA_padding_check_PKCS1_OAEP(to,num,buf,j,num,NULL,0);
608                 break;
609 #endif
610  	case RSA_SSLV23_PADDING:
611 		r=RSA_padding_check_SSLv23(to,num,buf,j,num);
612 		break;
613 	case RSA_NO_PADDING:
614 		r=RSA_padding_check_none(to,num,buf,j,num);
615 		break;
616 	default:
617 		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
618 		goto err;
619 		}
620 	if (r < 0)
621 		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_PADDING_CHECK_FAILED);
622 
623 err:
624 	if (ctx != NULL)
625 		{
626 		BN_CTX_end(ctx);
627 		BN_CTX_free(ctx);
628 		}
629 	if (buf != NULL)
630 		{
631 		OPENSSL_cleanse(buf,num);
632 		OPENSSL_free(buf);
633 		}
634 	return(r);
635 	}
636 
637 /* signature verification */
638 static int RSA_eay_public_decrypt(int flen, const unsigned char *from,
639 	     unsigned char *to, RSA *rsa, int padding)
640 	{
641 	BIGNUM *f,*ret;
642 	int i,num=0,r= -1;
643 	unsigned char *p;
644 	unsigned char *buf=NULL;
645 	BN_CTX *ctx=NULL;
646 
647 	if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS)
648 		{
649 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE);
650 		return -1;
651 		}
652 
653 	if (BN_ucmp(rsa->n, rsa->e) <= 0)
654 		{
655 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
656 		return -1;
657 		}
658 
659 	/* for large moduli, enforce exponent limit */
660 	if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS)
661 		{
662 		if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS)
663 			{
664 			RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
665 			return -1;
666 			}
667 		}
668 
669 	if((ctx = BN_CTX_new()) == NULL) goto err;
670 	BN_CTX_start(ctx);
671 	f = BN_CTX_get(ctx);
672 	ret = BN_CTX_get(ctx);
673 	num=BN_num_bytes(rsa->n);
674 	buf = OPENSSL_malloc(num);
675 	if(!f || !ret || !buf)
676 		{
677 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,ERR_R_MALLOC_FAILURE);
678 		goto err;
679 		}
680 
681 	/* This check was for equality but PGP does evil things
682 	 * and chops off the top '0' bytes */
683 	if (flen > num)
684 		{
685 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_DATA_GREATER_THAN_MOD_LEN);
686 		goto err;
687 		}
688 
689 	if (BN_bin2bn(from,flen,f) == NULL) goto err;
690 
691 	if (BN_ucmp(f, rsa->n) >= 0)
692 		{
693 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
694 		goto err;
695 		}
696 
697 	MONT_HELPER(rsa->_method_mod_n, ctx, rsa->n, rsa->flags & RSA_FLAG_CACHE_PUBLIC, goto err);
698 
699 	if (!rsa->meth->bn_mod_exp(ret,f,rsa->e,rsa->n,ctx,
700 		rsa->_method_mod_n)) goto err;
701 
702 	if ((padding == RSA_X931_PADDING) && ((ret->d[0] & 0xf) != 12))
703 		BN_sub(ret, rsa->n, ret);
704 
705 	p=buf;
706 	i=BN_bn2bin(ret,p);
707 
708 	switch (padding)
709 		{
710 	case RSA_PKCS1_PADDING:
711 		r=RSA_padding_check_PKCS1_type_1(to,num,buf,i,num);
712 		break;
713 	case RSA_X931_PADDING:
714 		r=RSA_padding_check_X931(to,num,buf,i,num);
715 		break;
716 	case RSA_NO_PADDING:
717 		r=RSA_padding_check_none(to,num,buf,i,num);
718 		break;
719 	default:
720 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
721 		goto err;
722 		}
723 	if (r < 0)
724 		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_PADDING_CHECK_FAILED);
725 
726 err:
727 	if (ctx != NULL)
728 		{
729 		BN_CTX_end(ctx);
730 		BN_CTX_free(ctx);
731 		}
732 	if (buf != NULL)
733 		{
734 		OPENSSL_cleanse(buf,num);
735 		OPENSSL_free(buf);
736 		}
737 	return(r);
738 	}
739 
740 static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
741 	{
742 	BIGNUM *r1,*m1,*vrfy;
743 	BIGNUM local_dmp1,local_dmq1,local_c,local_r1;
744 	BIGNUM *dmp1,*dmq1,*c,*pr1;
745 	int ret=0;
746 
747 	BN_CTX_start(ctx);
748 	r1 = BN_CTX_get(ctx);
749 	m1 = BN_CTX_get(ctx);
750 	vrfy = BN_CTX_get(ctx);
751 
752 	{
753 		BIGNUM local_p, local_q;
754 		BIGNUM *p = NULL, *q = NULL;
755 
756 		/* Make sure BN_mod_inverse in Montgomery intialization uses the
757 		 * BN_FLG_CONSTTIME flag (unless RSA_FLAG_NO_CONSTTIME is set)
758 		 */
759 		if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
760 			{
761 			BN_init(&local_p);
762 			p = &local_p;
763 			BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
764 
765 			BN_init(&local_q);
766 			q = &local_q;
767 			BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
768 			}
769 		else
770 			{
771 			p = rsa->p;
772 			q = rsa->q;
773 			}
774 
775 		MONT_HELPER(rsa->_method_mod_p, ctx, p, rsa->flags & RSA_FLAG_CACHE_PRIVATE, goto err);
776 		MONT_HELPER(rsa->_method_mod_q, ctx, q, rsa->flags & RSA_FLAG_CACHE_PRIVATE, goto err);
777 	}
778 
779 	MONT_HELPER(rsa->_method_mod_n, ctx, rsa->n, rsa->flags & RSA_FLAG_CACHE_PUBLIC, goto err);
780 
781 	/* compute I mod q */
782 	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
783 		{
784 		c = &local_c;
785 		BN_with_flags(c, I, BN_FLG_CONSTTIME);
786 		if (!BN_mod(r1,c,rsa->q,ctx)) goto err;
787 		}
788 	else
789 		{
790 		if (!BN_mod(r1,I,rsa->q,ctx)) goto err;
791 		}
792 
793 	/* compute r1^dmq1 mod q */
794 	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
795 		{
796 		dmq1 = &local_dmq1;
797 		BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
798 		}
799 	else
800 		dmq1 = rsa->dmq1;
801 	if (!rsa->meth->bn_mod_exp(m1,r1,dmq1,rsa->q,ctx,
802 		rsa->_method_mod_q)) goto err;
803 
804 	/* compute I mod p */
805 	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
806 		{
807 		c = &local_c;
808 		BN_with_flags(c, I, BN_FLG_CONSTTIME);
809 		if (!BN_mod(r1,c,rsa->p,ctx)) goto err;
810 		}
811 	else
812 		{
813 		if (!BN_mod(r1,I,rsa->p,ctx)) goto err;
814 		}
815 
816 	/* compute r1^dmp1 mod p */
817 	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
818 		{
819 		dmp1 = &local_dmp1;
820 		BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
821 		}
822 	else
823 		dmp1 = rsa->dmp1;
824 	if (!rsa->meth->bn_mod_exp(r0,r1,dmp1,rsa->p,ctx,
825 		rsa->_method_mod_p)) goto err;
826 
827 	if (!BN_sub(r0,r0,m1)) goto err;
828 	/* This will help stop the size of r0 increasing, which does
829 	 * affect the multiply if it optimised for a power of 2 size */
830 	if (BN_is_negative(r0))
831 		if (!BN_add(r0,r0,rsa->p)) goto err;
832 
833 	if (!BN_mul(r1,r0,rsa->iqmp,ctx)) goto err;
834 
835 	/* Turn BN_FLG_CONSTTIME flag on before division operation */
836 	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
837 		{
838 		pr1 = &local_r1;
839 		BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
840 		}
841 	else
842 		pr1 = r1;
843 	if (!BN_mod(r0,pr1,rsa->p,ctx)) goto err;
844 
845 	/* If p < q it is occasionally possible for the correction of
846          * adding 'p' if r0 is negative above to leave the result still
847 	 * negative. This can break the private key operations: the following
848 	 * second correction should *always* correct this rare occurrence.
849 	 * This will *never* happen with OpenSSL generated keys because
850          * they ensure p > q [steve]
851          */
852 	if (BN_is_negative(r0))
853 		if (!BN_add(r0,r0,rsa->p)) goto err;
854 	if (!BN_mul(r1,r0,rsa->q,ctx)) goto err;
855 	if (!BN_add(r0,r1,m1)) goto err;
856 
857 	if (rsa->e && rsa->n)
858 		{
859 		if (!rsa->meth->bn_mod_exp(vrfy,r0,rsa->e,rsa->n,ctx,rsa->_method_mod_n)) goto err;
860 		/* If 'I' was greater than (or equal to) rsa->n, the operation
861 		 * will be equivalent to using 'I mod n'. However, the result of
862 		 * the verify will *always* be less than 'n' so we don't check
863 		 * for absolute equality, just congruency. */
864 		if (!BN_sub(vrfy, vrfy, I)) goto err;
865 		if (!BN_mod(vrfy, vrfy, rsa->n, ctx)) goto err;
866 		if (BN_is_negative(vrfy))
867 			if (!BN_add(vrfy, vrfy, rsa->n)) goto err;
868 		if (!BN_is_zero(vrfy))
869 			{
870 			/* 'I' and 'vrfy' aren't congruent mod n. Don't leak
871 			 * miscalculated CRT output, just do a raw (slower)
872 			 * mod_exp and return that instead. */
873 
874 			BIGNUM local_d;
875 			BIGNUM *d = NULL;
876 
877 			if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME))
878 				{
879 				d = &local_d;
880 				BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
881 				}
882 			else
883 				d = rsa->d;
884 			if (!rsa->meth->bn_mod_exp(r0,I,d,rsa->n,ctx,
885 						   rsa->_method_mod_n)) goto err;
886 			}
887 		}
888 	ret=1;
889 err:
890 	BN_CTX_end(ctx);
891 	return(ret);
892 	}
893 
894 static int RSA_eay_init(RSA *rsa)
895 	{
896 	rsa->flags|=RSA_FLAG_CACHE_PUBLIC|RSA_FLAG_CACHE_PRIVATE;
897 	return(1);
898 	}
899 
900 static int RSA_eay_finish(RSA *rsa)
901 	{
902 	if (rsa->_method_mod_n != NULL)
903 		BN_MONT_CTX_free(rsa->_method_mod_n);
904 	if (rsa->_method_mod_p != NULL)
905 		BN_MONT_CTX_free(rsa->_method_mod_p);
906 	if (rsa->_method_mod_q != NULL)
907 		BN_MONT_CTX_free(rsa->_method_mod_q);
908 	return(1);
909 	}
910 
911 #endif
912