0752f5fd8b4cdc0d00ebfff6ed4e8b43cc95211c
[openssl.git] / crypto / rsa / rsa_ossl.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include "internal/cryptlib.h"
112 #include "internal/bn_int.h"
113 #include <openssl/rsa.h>
114 #include <openssl/rand.h>
115
116 #ifndef RSA_NULL
117
118 static int rsa_ossl_public_encrypt(int flen, const unsigned char *from,
119                                   unsigned char *to, RSA *rsa, int padding);
120 static int rsa_ossl_private_encrypt(int flen, const unsigned char *from,
121                                    unsigned char *to, RSA *rsa, int padding);
122 static int rsa_ossl_public_decrypt(int flen, const unsigned char *from,
123                                   unsigned char *to, RSA *rsa, int padding);
124 static int rsa_ossl_private_decrypt(int flen, const unsigned char *from,
125                                    unsigned char *to, RSA *rsa, int padding);
126 static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa,
127                            BN_CTX *ctx);
128 static int rsa_ossl_init(RSA *rsa);
129 static int rsa_ossl_finish(RSA *rsa);
130 static RSA_METHOD rsa_pkcs1_ossl_meth = {
131     "OpenSSL PKCS#1 RSA (from Eric Young)",
132     rsa_ossl_public_encrypt,
133     rsa_ossl_public_decrypt,     /* signature verification */
134     rsa_ossl_private_encrypt,    /* signing */
135     rsa_ossl_private_decrypt,
136     rsa_ossl_mod_exp,
137     BN_mod_exp_mont,            /* XXX probably we should not use Montgomery
138                                  * if e == 3 */
139     rsa_ossl_init,
140     rsa_ossl_finish,
141     RSA_FLAG_FIPS_METHOD,       /* flags */
142     NULL,
143     0,                          /* rsa_sign */
144     0,                          /* rsa_verify */
145     NULL                        /* rsa_keygen */
146 };
147
148 const RSA_METHOD *RSA_PKCS1_OpenSSL(void)
149 {
150     return &rsa_pkcs1_ossl_meth;
151 }
152
153 static int rsa_ossl_public_encrypt(int flen, const unsigned char *from,
154                                   unsigned char *to, RSA *rsa, int padding)
155 {
156     BIGNUM *f, *ret;
157     int i, j, k, num = 0, r = -1;
158     unsigned char *buf = NULL;
159     BN_CTX *ctx = NULL;
160
161     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
162         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_MODULUS_TOO_LARGE);
163         return -1;
164     }
165
166     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
167         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
168         return -1;
169     }
170
171     /* for large moduli, enforce exponent limit */
172     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
173         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
174             RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
175             return -1;
176         }
177     }
178
179     if ((ctx = BN_CTX_new()) == NULL)
180         goto err;
181     BN_CTX_start(ctx);
182     f = BN_CTX_get(ctx);
183     ret = BN_CTX_get(ctx);
184     num = BN_num_bytes(rsa->n);
185     buf = OPENSSL_malloc(num);
186     if (f == NULL || ret == NULL || buf == NULL) {
187         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, ERR_R_MALLOC_FAILURE);
188         goto err;
189     }
190
191     switch (padding) {
192     case RSA_PKCS1_PADDING:
193         i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
194         break;
195     case RSA_PKCS1_OAEP_PADDING:
196         i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
197         break;
198     case RSA_SSLV23_PADDING:
199         i = RSA_padding_add_SSLv23(buf, num, from, flen);
200         break;
201     case RSA_NO_PADDING:
202         i = RSA_padding_add_none(buf, num, from, flen);
203         break;
204     default:
205         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
206         goto err;
207     }
208     if (i <= 0)
209         goto err;
210
211     if (BN_bin2bn(buf, num, f) == NULL)
212         goto err;
213
214     if (BN_ucmp(f, rsa->n) >= 0) {
215         /* usually the padding functions would catch this */
216         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT,
217                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
218         goto err;
219     }
220
221     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
222         if (!BN_MONT_CTX_set_locked
223             (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
224             goto err;
225
226     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
227                                rsa->_method_mod_n))
228         goto err;
229
230     /*
231      * put in leading 0 bytes if the number is less than the length of the
232      * modulus
233      */
234     j = BN_num_bytes(ret);
235     i = BN_bn2bin(ret, &(to[num - j]));
236     for (k = 0; k < (num - i); k++)
237         to[k] = 0;
238
239     r = num;
240  err:
241     if (ctx != NULL)
242         BN_CTX_end(ctx);
243     BN_CTX_free(ctx);
244     OPENSSL_clear_free(buf, num);
245     return (r);
246 }
247
248 static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx)
249 {
250     BN_BLINDING *ret;
251     int got_write_lock = 0;
252     CRYPTO_THREADID cur;
253
254     CRYPTO_r_lock(CRYPTO_LOCK_RSA);
255
256     if (rsa->blinding == NULL) {
257         CRYPTO_r_unlock(CRYPTO_LOCK_RSA);
258         CRYPTO_w_lock(CRYPTO_LOCK_RSA);
259         got_write_lock = 1;
260
261         if (rsa->blinding == NULL)
262             rsa->blinding = RSA_setup_blinding(rsa, ctx);
263     }
264
265     ret = rsa->blinding;
266     if (ret == NULL)
267         goto err;
268
269     CRYPTO_THREADID_current(&cur);
270     if (!CRYPTO_THREADID_cmp(&cur, BN_BLINDING_thread_id(ret))) {
271         /* rsa->blinding is ours! */
272
273         *local = 1;
274     } else {
275         /* resort to rsa->mt_blinding instead */
276
277         /*
278          * instructs rsa_blinding_convert(), rsa_blinding_invert() that the
279          * BN_BLINDING is shared, meaning that accesses require locks, and
280          * that the blinding factor must be 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 rsa_blinding_convert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
306                                 BN_CTX *ctx)
307 {
308     if (unblind == NULL)
309         /*
310          * Local blinding: store the unblinding factor in BN_BLINDING.
311          */
312         return BN_BLINDING_convert_ex(f, NULL, b, ctx);
313     else {
314         /*
315          * Shared blinding: store the unblinding factor outside BN_BLINDING.
316          */
317         int ret;
318         CRYPTO_w_lock(CRYPTO_LOCK_RSA_BLINDING);
319         ret = BN_BLINDING_convert_ex(f, unblind, b, ctx);
320         CRYPTO_w_unlock(CRYPTO_LOCK_RSA_BLINDING);
321         return ret;
322     }
323 }
324
325 static int rsa_blinding_invert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
326                                BN_CTX *ctx)
327 {
328     /*
329      * For local blinding, unblind is set to NULL, and BN_BLINDING_invert_ex
330      * will use the unblinding factor stored in BN_BLINDING. If BN_BLINDING
331      * is shared between threads, unblind must be non-null:
332      * BN_BLINDING_invert_ex will then use the local unblinding factor, and
333      * will only read the modulus from BN_BLINDING. In both cases it's safe
334      * to access the blinding without a lock.
335      */
336     return BN_BLINDING_invert_ex(f, unblind, b, ctx);
337 }
338
339 /* signing */
340 static int rsa_ossl_private_encrypt(int flen, const unsigned char *from,
341                                    unsigned char *to, RSA *rsa, int padding)
342 {
343     BIGNUM *f, *ret, *res;
344     int i, j, k, num = 0, r = -1;
345     unsigned char *buf = NULL;
346     BN_CTX *ctx = NULL;
347     int local_blinding = 0;
348     /*
349      * Used only if the blinding structure is shared. A non-NULL unblind
350      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
351      * the unblinding factor outside the blinding structure.
352      */
353     BIGNUM *unblind = NULL;
354     BN_BLINDING *blinding = NULL;
355
356     if ((ctx = BN_CTX_new()) == NULL)
357         goto err;
358     BN_CTX_start(ctx);
359     f = BN_CTX_get(ctx);
360     ret = BN_CTX_get(ctx);
361     num = BN_num_bytes(rsa->n);
362     buf = OPENSSL_malloc(num);
363     if (f == NULL || ret == NULL || buf == NULL) {
364         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
365         goto err;
366     }
367
368     switch (padding) {
369     case RSA_PKCS1_PADDING:
370         i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
371         break;
372     case RSA_X931_PADDING:
373         i = RSA_padding_add_X931(buf, num, from, flen);
374         break;
375     case RSA_NO_PADDING:
376         i = RSA_padding_add_none(buf, num, from, flen);
377         break;
378     case RSA_SSLV23_PADDING:
379     default:
380         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
381         goto err;
382     }
383     if (i <= 0)
384         goto err;
385
386     if (BN_bin2bn(buf, num, f) == NULL)
387         goto err;
388
389     if (BN_ucmp(f, rsa->n) >= 0) {
390         /* usually the padding functions would catch this */
391         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT,
392                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
393         goto err;
394     }
395
396     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
397         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
398         if (blinding == NULL) {
399             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
400             goto err;
401         }
402     }
403
404     if (blinding != NULL) {
405         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
406             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
407             goto err;
408         }
409         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
410             goto err;
411     }
412
413     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
414         ((rsa->p != NULL) &&
415          (rsa->q != NULL) &&
416          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
417         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
418             goto err;
419     } else {
420         BIGNUM *d = NULL, *local_d = NULL;
421
422         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
423             local_d = d = BN_new();
424             if (d == NULL) {
425                 RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
426                 goto err;
427             }
428             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
429         } else {
430             d = rsa->d;
431         }
432
433         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
434             if (!BN_MONT_CTX_set_locked
435                 (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx)) {
436                 BN_free(local_d);
437                 goto err;
438             }
439
440         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
441                                    rsa->_method_mod_n)) {
442             BN_free(local_d);
443             goto err;
444         }
445         /* We MUST free local_d before any further use of rsa->d */
446         BN_free(local_d);
447     }
448
449     if (blinding)
450         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
451             goto err;
452
453     if (padding == RSA_X931_PADDING) {
454         BN_sub(f, rsa->n, ret);
455         if (BN_cmp(ret, f) > 0)
456             res = f;
457         else
458             res = ret;
459     } else
460         res = ret;
461
462     /*
463      * put in leading 0 bytes if the number is less than the length of the
464      * modulus
465      */
466     j = BN_num_bytes(res);
467     i = BN_bn2bin(res, &(to[num - j]));
468     for (k = 0; k < (num - i); k++)
469         to[k] = 0;
470
471     r = num;
472  err:
473     if (ctx != NULL)
474         BN_CTX_end(ctx);
475     BN_CTX_free(ctx);
476     OPENSSL_clear_free(buf, num);
477     return (r);
478 }
479
480 static int rsa_ossl_private_decrypt(int flen, const unsigned char *from,
481                                    unsigned char *to, RSA *rsa, int padding)
482 {
483     BIGNUM *f, *ret;
484     int j, num = 0, r = -1;
485     unsigned char *p;
486     unsigned char *buf = NULL;
487     BN_CTX *ctx = NULL;
488     int local_blinding = 0;
489     /*
490      * Used only if the blinding structure is shared. A non-NULL unblind
491      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
492      * the unblinding factor outside the blinding structure.
493      */
494     BIGNUM *unblind = NULL;
495     BN_BLINDING *blinding = NULL;
496
497     if ((ctx = BN_CTX_new()) == NULL)
498         goto err;
499     BN_CTX_start(ctx);
500     f = BN_CTX_get(ctx);
501     ret = BN_CTX_get(ctx);
502     num = BN_num_bytes(rsa->n);
503     buf = OPENSSL_malloc(num);
504     if (f == NULL || ret == NULL || buf == NULL) {
505         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
506         goto err;
507     }
508
509     /*
510      * This check was for equality but PGP does evil things and chops off the
511      * top '0' bytes
512      */
513     if (flen > num) {
514         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT,
515                RSA_R_DATA_GREATER_THAN_MOD_LEN);
516         goto err;
517     }
518
519     /* make data into a big number */
520     if (BN_bin2bn(from, (int)flen, f) == NULL)
521         goto err;
522
523     if (BN_ucmp(f, rsa->n) >= 0) {
524         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT,
525                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
526         goto err;
527     }
528
529     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
530         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
531         if (blinding == NULL) {
532             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
533             goto err;
534         }
535     }
536
537     if (blinding != NULL) {
538         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
539             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
540             goto err;
541         }
542         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
543             goto err;
544     }
545
546     /* do the decrypt */
547     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
548         ((rsa->p != NULL) &&
549          (rsa->q != NULL) &&
550          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
551         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
552             goto err;
553     } else {
554         BIGNUM *d = NULL, *local_d = NULL;
555
556         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
557             local_d = d = BN_new();
558             if (d == NULL) {
559                 RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
560                 goto err;
561             }
562             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
563         } else {
564             d = rsa->d;
565         }
566
567         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
568             if (!BN_MONT_CTX_set_locked
569                 (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx)) {
570                 BN_free(local_d);
571                 goto err;
572             }
573         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
574                                    rsa->_method_mod_n)) {
575             BN_free(local_d);
576             goto err;
577         }
578         /* We MUST free local_d before any further use of rsa->d */
579         BN_free(local_d);
580     }
581
582     if (blinding)
583         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
584             goto err;
585
586     p = buf;
587     j = BN_bn2bin(ret, p);      /* j is only used with no-padding mode */
588
589     switch (padding) {
590     case RSA_PKCS1_PADDING:
591         r = RSA_padding_check_PKCS1_type_2(to, num, buf, j, num);
592         break;
593     case RSA_PKCS1_OAEP_PADDING:
594         r = RSA_padding_check_PKCS1_OAEP(to, num, buf, j, num, NULL, 0);
595         break;
596     case RSA_SSLV23_PADDING:
597         r = RSA_padding_check_SSLv23(to, num, buf, j, num);
598         break;
599     case RSA_NO_PADDING:
600         r = RSA_padding_check_none(to, num, buf, j, num);
601         break;
602     default:
603         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
604         goto err;
605     }
606     if (r < 0)
607         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
608
609  err:
610     if (ctx != NULL)
611         BN_CTX_end(ctx);
612     BN_CTX_free(ctx);
613     OPENSSL_clear_free(buf, num);
614     return (r);
615 }
616
617 /* signature verification */
618 static int rsa_ossl_public_decrypt(int flen, const unsigned char *from,
619                                   unsigned char *to, RSA *rsa, int padding)
620 {
621     BIGNUM *f, *ret;
622     int i, num = 0, r = -1;
623     unsigned char *p;
624     unsigned char *buf = NULL;
625     BN_CTX *ctx = NULL;
626
627     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
628         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE);
629         return -1;
630     }
631
632     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
633         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
634         return -1;
635     }
636
637     /* for large moduli, enforce exponent limit */
638     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
639         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
640             RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
641             return -1;
642         }
643     }
644
645     if ((ctx = BN_CTX_new()) == NULL)
646         goto err;
647     BN_CTX_start(ctx);
648     f = BN_CTX_get(ctx);
649     ret = BN_CTX_get(ctx);
650     num = BN_num_bytes(rsa->n);
651     buf = OPENSSL_malloc(num);
652     if (f == NULL || ret == NULL || buf == NULL) {
653         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, ERR_R_MALLOC_FAILURE);
654         goto err;
655     }
656
657     /*
658      * This check was for equality but PGP does evil things and chops off the
659      * top '0' bytes
660      */
661     if (flen > num) {
662         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_DATA_GREATER_THAN_MOD_LEN);
663         goto err;
664     }
665
666     if (BN_bin2bn(from, flen, f) == NULL)
667         goto err;
668
669     if (BN_ucmp(f, rsa->n) >= 0) {
670         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT,
671                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
672         goto err;
673     }
674
675     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
676         if (!BN_MONT_CTX_set_locked
677             (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
678             goto err;
679
680     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
681                                rsa->_method_mod_n))
682         goto err;
683
684     if ((padding == RSA_X931_PADDING) && ((bn_get_words(ret)[0] & 0xf) != 12))
685         if (!BN_sub(ret, rsa->n, ret))
686             goto err;
687
688     p = buf;
689     i = BN_bn2bin(ret, p);
690
691     switch (padding) {
692     case RSA_PKCS1_PADDING:
693         r = RSA_padding_check_PKCS1_type_1(to, num, buf, i, num);
694         break;
695     case RSA_X931_PADDING:
696         r = RSA_padding_check_X931(to, num, buf, i, num);
697         break;
698     case RSA_NO_PADDING:
699         r = RSA_padding_check_none(to, num, buf, i, num);
700         break;
701     default:
702         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
703         goto err;
704     }
705     if (r < 0)
706         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
707
708  err:
709     if (ctx != NULL)
710         BN_CTX_end(ctx);
711     BN_CTX_free(ctx);
712     OPENSSL_clear_free(buf, num);
713     return (r);
714 }
715
716 static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
717 {
718     BIGNUM *r1, *m1, *vrfy;
719     int ret = 0;
720
721     BN_CTX_start(ctx);
722
723     r1 = BN_CTX_get(ctx);
724     m1 = BN_CTX_get(ctx);
725     vrfy = BN_CTX_get(ctx);
726
727     {
728         BIGNUM *local_p = NULL, *local_q = NULL;
729         BIGNUM *p = NULL, *q = NULL;
730
731         /*
732          * Make sure BN_mod_inverse in Montgomery intialization uses the
733          * BN_FLG_CONSTTIME flag (unless RSA_FLAG_NO_CONSTTIME is set)
734          */
735         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
736             local_p = p = BN_new();
737             if (p == NULL)
738                 goto err;
739             BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
740
741             local_q = q = BN_new();
742             if (q == NULL) {
743                 BN_free(local_p);
744                 goto err;
745             }
746             BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
747         } else {
748             p = rsa->p;
749             q = rsa->q;
750         }
751
752         if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
753             if (!BN_MONT_CTX_set_locked
754                 (&rsa->_method_mod_p, CRYPTO_LOCK_RSA, p, ctx)
755                 || !BN_MONT_CTX_set_locked(&rsa->_method_mod_q,
756                                            CRYPTO_LOCK_RSA, q, ctx)) {
757                 BN_free(local_p);
758                 BN_free(local_q);
759                 goto err;
760             }
761         }
762         /*
763          * We MUST free local_p and local_q before any further use of rsa->p and
764          * rsa->q
765          */
766         BN_free(local_p);
767         BN_free(local_q);
768     }
769
770     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
771         if (!BN_MONT_CTX_set_locked
772             (&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx))
773             goto err;
774
775     /* compute I mod q */
776     {
777         BIGNUM *local_c = NULL;
778         const BIGNUM *c;
779         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
780             local_c = BN_new();
781             if (local_c == NULL)
782                 goto err;
783             BN_with_flags(local_c, I, BN_FLG_CONSTTIME);
784             c = local_c;
785         } else {
786             c = I;
787         }
788         if (!BN_mod(r1, c, rsa->q, ctx)) {
789             BN_free(local_c);
790             goto err;
791         }
792
793         {
794             BIGNUM *local_dmq1 = NULL, *dmq1;
795             /* compute r1^dmq1 mod q */
796             if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
797                 dmq1 = local_dmq1 = BN_new();
798                 if (local_dmq1 == NULL) {
799                     BN_free(local_c);
800                     goto err;
801                 }
802                 BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
803             } else {
804                 dmq1 = rsa->dmq1;
805             }
806             if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx,
807                 rsa->_method_mod_q)) {
808                 BN_free(local_c);
809                 BN_free(local_dmq1);
810                 goto err;
811             }
812             /* We MUST free local_dmq1 before any further use of rsa->dmq1 */
813             BN_free(local_dmq1);
814         }
815
816         /* compute I mod p */
817         if (!BN_mod(r1, c, rsa->p, ctx)) {
818             BN_free(local_c);
819             goto err;
820         }
821         /* We MUST free local_c before any further use of I */
822         BN_free(local_c);
823     }
824
825     {
826         BIGNUM *local_dmp1 = NULL, *dmp1;
827         /* compute r1^dmp1 mod p */
828         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
829             dmp1 = local_dmp1 = BN_new();
830             if (local_dmp1 == NULL)
831                 goto err;
832             BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
833         } else {
834             dmp1 = rsa->dmp1;
835         }
836         if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx,
837                                    rsa->_method_mod_p)) {
838             BN_free(local_dmp1);
839             goto err;
840         }
841         /* We MUST free local_dmp1 before any further use of rsa->dmp1 */
842         BN_free(local_dmp1);
843     }
844
845     if (!BN_sub(r0, r0, m1))
846         goto err;
847     /*
848      * This will help stop the size of r0 increasing, which does affect the
849      * multiply if it optimised for a power of 2 size
850      */
851     if (BN_is_negative(r0))
852         if (!BN_add(r0, r0, rsa->p))
853             goto err;
854
855     if (!BN_mul(r1, r0, rsa->iqmp, ctx))
856         goto err;
857
858     {
859         BIGNUM *local_r1 = NULL, *pr1;
860         /* Turn BN_FLG_CONSTTIME flag on before division operation */
861         if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
862             pr1 = local_r1 = BN_new();
863             if (local_r1 == NULL)
864                 goto err;
865             BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
866         } else {
867             pr1 = r1;
868         }
869         if (!BN_mod(r0, pr1, rsa->p, ctx)) {
870             BN_free(local_r1);
871             goto err;
872         }
873         /* We MUST free local_r1 before any further use of r1 */
874         BN_free(local_r1);
875     }
876
877     /*
878      * If p < q it is occasionally possible for the correction of adding 'p'
879      * if r0 is negative above to leave the result still negative. This can
880      * break the private key operations: the following second correction
881      * should *always* correct this rare occurrence. This will *never* happen
882      * with OpenSSL generated keys because they ensure p > q [steve]
883      */
884     if (BN_is_negative(r0))
885         if (!BN_add(r0, r0, rsa->p))
886             goto err;
887     if (!BN_mul(r1, r0, rsa->q, ctx))
888         goto err;
889     if (!BN_add(r0, r1, m1))
890         goto err;
891
892     if (rsa->e && rsa->n) {
893         if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
894                                    rsa->_method_mod_n))
895             goto err;
896         /*
897          * If 'I' was greater than (or equal to) rsa->n, the operation will
898          * be equivalent to using 'I mod n'. However, the result of the
899          * verify will *always* be less than 'n' so we don't check for
900          * absolute equality, just congruency.
901          */
902         if (!BN_sub(vrfy, vrfy, I))
903             goto err;
904         if (!BN_mod(vrfy, vrfy, rsa->n, ctx))
905             goto err;
906         if (BN_is_negative(vrfy))
907             if (!BN_add(vrfy, vrfy, rsa->n))
908                 goto err;
909         if (!BN_is_zero(vrfy)) {
910             /*
911              * 'I' and 'vrfy' aren't congruent mod n. Don't leak
912              * miscalculated CRT output, just do a raw (slower) mod_exp and
913              * return that instead.
914              */
915
916             BIGNUM *local_d = NULL;
917             BIGNUM *d = NULL;
918
919             if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
920                 local_d = d = BN_new();
921                 if (d == NULL)
922                     goto err;
923                 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
924             } else {
925                 d = rsa->d;
926             }
927             if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
928                                        rsa->_method_mod_n)) {
929                 BN_free(local_d);
930                 goto err;
931             }
932             /* We MUST free local_d before any further use of rsa->d */
933             BN_free(local_d);
934         }
935     }
936     ret = 1;
937  err:
938     BN_CTX_end(ctx);
939     return (ret);
940 }
941
942 static int rsa_ossl_init(RSA *rsa)
943 {
944     rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
945     return (1);
946 }
947
948 static int rsa_ossl_finish(RSA *rsa)
949 {
950     BN_MONT_CTX_free(rsa->_method_mod_n);
951     BN_MONT_CTX_free(rsa->_method_mod_p);
952     BN_MONT_CTX_free(rsa->_method_mod_q);
953     return (1);
954 }
955
956 #endif