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