feb1ab4f0746dfa10f2f5f8c4389cc279d8dd6fb
[openssl.git] / crypto / rsa / rsa_ossl.c
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/cryptlib.h"
11 #include "internal/bn_int.h"
12 #include "rsa_locl.h"
13
14 static int rsa_ossl_public_encrypt(int flen, const unsigned char *from,
15                                   unsigned char *to, RSA *rsa, int padding);
16 static int rsa_ossl_private_encrypt(int flen, const unsigned char *from,
17                                    unsigned char *to, RSA *rsa, int padding);
18 static int rsa_ossl_public_decrypt(int flen, const unsigned char *from,
19                                   unsigned char *to, RSA *rsa, int padding);
20 static int rsa_ossl_private_decrypt(int flen, const unsigned char *from,
21                                    unsigned char *to, RSA *rsa, int padding);
22 static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa,
23                            BN_CTX *ctx);
24 static int rsa_ossl_init(RSA *rsa);
25 static int rsa_ossl_finish(RSA *rsa);
26 static RSA_METHOD rsa_pkcs1_ossl_meth = {
27     "OpenSSL PKCS#1 RSA",
28     rsa_ossl_public_encrypt,
29     rsa_ossl_public_decrypt,     /* signature verification */
30     rsa_ossl_private_encrypt,    /* signing */
31     rsa_ossl_private_decrypt,
32     rsa_ossl_mod_exp,
33     BN_mod_exp_mont,            /* XXX probably we should not use Montgomery
34                                  * if e == 3 */
35     rsa_ossl_init,
36     rsa_ossl_finish,
37     RSA_FLAG_FIPS_METHOD,       /* flags */
38     NULL,
39     0,                          /* rsa_sign */
40     0,                          /* rsa_verify */
41     NULL,                       /* rsa_keygen */
42     NULL                        /* rsa_multi_prime_keygen */
43 };
44
45 static const RSA_METHOD *default_RSA_meth = &rsa_pkcs1_ossl_meth;
46
47 void RSA_set_default_method(const RSA_METHOD *meth)
48 {
49     default_RSA_meth = meth;
50 }
51
52 const RSA_METHOD *RSA_get_default_method(void)
53 {
54     return default_RSA_meth;
55 }
56
57 const RSA_METHOD *RSA_PKCS1_OpenSSL(void)
58 {
59     return &rsa_pkcs1_ossl_meth;
60 }
61
62 const RSA_METHOD *RSA_null_method(void)
63 {
64     return NULL;
65 }
66
67 static int rsa_ossl_public_encrypt(int flen, const unsigned char *from,
68                                   unsigned char *to, RSA *rsa, int padding)
69 {
70     BIGNUM *f, *ret;
71     int i, num = 0, r = -1;
72     unsigned char *buf = NULL;
73     BN_CTX *ctx = NULL;
74
75     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
76         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_MODULUS_TOO_LARGE);
77         return -1;
78     }
79
80     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
81         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
82         return -1;
83     }
84
85     /* for large moduli, enforce exponent limit */
86     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
87         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
88             RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
89             return -1;
90         }
91     }
92
93     if ((ctx = BN_CTX_new()) == NULL)
94         goto err;
95     BN_CTX_start(ctx);
96     f = BN_CTX_get(ctx);
97     ret = BN_CTX_get(ctx);
98     num = BN_num_bytes(rsa->n);
99     buf = OPENSSL_malloc(num);
100     if (ret == NULL || buf == NULL) {
101         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, ERR_R_MALLOC_FAILURE);
102         goto err;
103     }
104
105     switch (padding) {
106     case RSA_PKCS1_PADDING:
107         i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
108         break;
109     case RSA_PKCS1_OAEP_PADDING:
110         i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
111         break;
112     case RSA_SSLV23_PADDING:
113         i = RSA_padding_add_SSLv23(buf, num, from, flen);
114         break;
115     case RSA_NO_PADDING:
116         i = RSA_padding_add_none(buf, num, from, flen);
117         break;
118     default:
119         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
120         goto err;
121     }
122     if (i <= 0)
123         goto err;
124
125     if (BN_bin2bn(buf, num, f) == NULL)
126         goto err;
127
128     if (BN_ucmp(f, rsa->n) >= 0) {
129         /* usually the padding functions would catch this */
130         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT,
131                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
132         goto err;
133     }
134
135     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
136         if (!BN_MONT_CTX_set_locked
137             (&rsa->_method_mod_n, rsa->lock, rsa->n, ctx))
138             goto err;
139
140     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
141                                rsa->_method_mod_n))
142         goto err;
143
144     /*
145      * BN_bn2binpad puts in leading 0 bytes if the number is less than
146      * the length of the modulus.
147      */
148     r = BN_bn2binpad(ret, to, num);
149  err:
150     if (ctx != NULL)
151         BN_CTX_end(ctx);
152     BN_CTX_free(ctx);
153     OPENSSL_clear_free(buf, num);
154     return r;
155 }
156
157 static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx)
158 {
159     BN_BLINDING *ret;
160
161     CRYPTO_THREAD_write_lock(rsa->lock);
162
163     if (rsa->blinding == NULL) {
164         rsa->blinding = RSA_setup_blinding(rsa, ctx);
165     }
166
167     ret = rsa->blinding;
168     if (ret == NULL)
169         goto err;
170
171     if (BN_BLINDING_is_current_thread(ret)) {
172         /* rsa->blinding is ours! */
173
174         *local = 1;
175     } else {
176         /* resort to rsa->mt_blinding instead */
177
178         /*
179          * instructs rsa_blinding_convert(), rsa_blinding_invert() that the
180          * BN_BLINDING is shared, meaning that accesses require locks, and
181          * that the blinding factor must be stored outside the BN_BLINDING
182          */
183         *local = 0;
184
185         if (rsa->mt_blinding == NULL) {
186             rsa->mt_blinding = RSA_setup_blinding(rsa, ctx);
187         }
188         ret = rsa->mt_blinding;
189     }
190
191  err:
192     CRYPTO_THREAD_unlock(rsa->lock);
193     return ret;
194 }
195
196 static int rsa_blinding_convert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
197                                 BN_CTX *ctx)
198 {
199     if (unblind == NULL) {
200         /*
201          * Local blinding: store the unblinding factor in BN_BLINDING.
202          */
203         return BN_BLINDING_convert_ex(f, NULL, b, ctx);
204     } else {
205         /*
206          * Shared blinding: store the unblinding factor outside BN_BLINDING.
207          */
208         int ret;
209
210         BN_BLINDING_lock(b);
211         ret = BN_BLINDING_convert_ex(f, unblind, b, ctx);
212         BN_BLINDING_unlock(b);
213
214         return ret;
215     }
216 }
217
218 static int rsa_blinding_invert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
219                                BN_CTX *ctx)
220 {
221     /*
222      * For local blinding, unblind is set to NULL, and BN_BLINDING_invert_ex
223      * will use the unblinding factor stored in BN_BLINDING. If BN_BLINDING
224      * is shared between threads, unblind must be non-null:
225      * BN_BLINDING_invert_ex will then use the local unblinding factor, and
226      * will only read the modulus from BN_BLINDING. In both cases it's safe
227      * to access the blinding without a lock.
228      */
229     return BN_BLINDING_invert_ex(f, unblind, b, ctx);
230 }
231
232 /* signing */
233 static int rsa_ossl_private_encrypt(int flen, const unsigned char *from,
234                                    unsigned char *to, RSA *rsa, int padding)
235 {
236     BIGNUM *f, *ret, *res;
237     int i, num = 0, r = -1;
238     unsigned char *buf = NULL;
239     BN_CTX *ctx = NULL;
240     int local_blinding = 0;
241     /*
242      * Used only if the blinding structure is shared. A non-NULL unblind
243      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
244      * the unblinding factor outside the blinding structure.
245      */
246     BIGNUM *unblind = NULL;
247     BN_BLINDING *blinding = NULL;
248
249     if ((ctx = BN_CTX_new()) == NULL)
250         goto err;
251     BN_CTX_start(ctx);
252     f = BN_CTX_get(ctx);
253     ret = BN_CTX_get(ctx);
254     num = BN_num_bytes(rsa->n);
255     buf = OPENSSL_malloc(num);
256     if (ret == NULL || buf == NULL) {
257         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
258         goto err;
259     }
260
261     switch (padding) {
262     case RSA_PKCS1_PADDING:
263         i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
264         break;
265     case RSA_X931_PADDING:
266         i = RSA_padding_add_X931(buf, num, from, flen);
267         break;
268     case RSA_NO_PADDING:
269         i = RSA_padding_add_none(buf, num, from, flen);
270         break;
271     case RSA_SSLV23_PADDING:
272     default:
273         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
274         goto err;
275     }
276     if (i <= 0)
277         goto err;
278
279     if (BN_bin2bn(buf, num, f) == NULL)
280         goto err;
281
282     if (BN_ucmp(f, rsa->n) >= 0) {
283         /* usually the padding functions would catch this */
284         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT,
285                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
286         goto err;
287     }
288
289     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
290         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
291         if (blinding == NULL) {
292             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
293             goto err;
294         }
295     }
296
297     if (blinding != NULL) {
298         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
299             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
300             goto err;
301         }
302         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
303             goto err;
304     }
305
306     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
307         (rsa->version == RSA_ASN1_VERSION_MULTI) ||
308         ((rsa->p != NULL) &&
309          (rsa->q != NULL) &&
310          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
311         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
312             goto err;
313     } else {
314         BIGNUM *d = BN_new();
315         if (d == NULL) {
316             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
317             goto err;
318         }
319         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
320
321         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
322             if (!BN_MONT_CTX_set_locked
323                 (&rsa->_method_mod_n, rsa->lock, rsa->n, ctx)) {
324                 BN_free(d);
325                 goto err;
326             }
327
328         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
329                                    rsa->_method_mod_n)) {
330             BN_free(d);
331             goto err;
332         }
333         /* We MUST free d before any further use of rsa->d */
334         BN_free(d);
335     }
336
337     if (blinding)
338         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
339             goto err;
340
341     if (padding == RSA_X931_PADDING) {
342         BN_sub(f, rsa->n, ret);
343         if (BN_cmp(ret, f) > 0)
344             res = f;
345         else
346             res = ret;
347     } else {
348         res = ret;
349     }
350
351     /*
352      * BN_bn2binpad puts in leading 0 bytes if the number is less than
353      * the length of the modulus.
354      */
355     r = BN_bn2binpad(res, to, num);
356  err:
357     if (ctx != NULL)
358         BN_CTX_end(ctx);
359     BN_CTX_free(ctx);
360     OPENSSL_clear_free(buf, num);
361     return r;
362 }
363
364 static int rsa_ossl_private_decrypt(int flen, const unsigned char *from,
365                                    unsigned char *to, RSA *rsa, int padding)
366 {
367     BIGNUM *f, *ret;
368     int j, num = 0, r = -1;
369     unsigned char *buf = NULL;
370     BN_CTX *ctx = NULL;
371     int local_blinding = 0;
372     /*
373      * Used only if the blinding structure is shared. A non-NULL unblind
374      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
375      * the unblinding factor outside the blinding structure.
376      */
377     BIGNUM *unblind = NULL;
378     BN_BLINDING *blinding = NULL;
379
380     if ((ctx = BN_CTX_new()) == NULL)
381         goto err;
382     BN_CTX_start(ctx);
383     f = BN_CTX_get(ctx);
384     ret = BN_CTX_get(ctx);
385     num = BN_num_bytes(rsa->n);
386     buf = OPENSSL_malloc(num);
387     if (ret == NULL || buf == NULL) {
388         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
389         goto err;
390     }
391
392     /*
393      * This check was for equality but PGP does evil things and chops off the
394      * top '0' bytes
395      */
396     if (flen > num) {
397         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT,
398                RSA_R_DATA_GREATER_THAN_MOD_LEN);
399         goto err;
400     }
401
402     /* make data into a big number */
403     if (BN_bin2bn(from, (int)flen, f) == NULL)
404         goto err;
405
406     if (BN_ucmp(f, rsa->n) >= 0) {
407         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT,
408                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
409         goto err;
410     }
411
412     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
413         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
414         if (blinding == NULL) {
415             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
416             goto err;
417         }
418     }
419
420     if (blinding != NULL) {
421         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
422             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
423             goto err;
424         }
425         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
426             goto err;
427     }
428
429     /* do the decrypt */
430     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
431         (rsa->version == RSA_ASN1_VERSION_MULTI) ||
432         ((rsa->p != NULL) &&
433          (rsa->q != NULL) &&
434          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
435         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
436             goto err;
437     } else {
438         BIGNUM *d = BN_new();
439         if (d == NULL) {
440             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
441             goto err;
442         }
443         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
444
445         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
446             if (!BN_MONT_CTX_set_locked
447                 (&rsa->_method_mod_n, rsa->lock, rsa->n, ctx)) {
448                 BN_free(d);
449                 goto err;
450             }
451         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
452                                    rsa->_method_mod_n)) {
453             BN_free(d);
454             goto err;
455         }
456         /* We MUST free d before any further use of rsa->d */
457         BN_free(d);
458     }
459
460     if (blinding)
461         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
462             goto err;
463
464     j = BN_bn2binpad(ret, buf, num);
465
466     switch (padding) {
467     case RSA_PKCS1_PADDING:
468         r = RSA_padding_check_PKCS1_type_2(to, num, buf, j, num);
469         break;
470     case RSA_PKCS1_OAEP_PADDING:
471         r = RSA_padding_check_PKCS1_OAEP(to, num, buf, j, num, NULL, 0);
472         break;
473     case RSA_SSLV23_PADDING:
474         r = RSA_padding_check_SSLv23(to, num, buf, j, num);
475         break;
476     case RSA_NO_PADDING:
477         memcpy(to, buf, (r = j));
478         break;
479     default:
480         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
481         goto err;
482     }
483     if (r < 0)
484         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
485
486  err:
487     if (ctx != NULL)
488         BN_CTX_end(ctx);
489     BN_CTX_free(ctx);
490     OPENSSL_clear_free(buf, num);
491     return r;
492 }
493
494 /* signature verification */
495 static int rsa_ossl_public_decrypt(int flen, const unsigned char *from,
496                                   unsigned char *to, RSA *rsa, int padding)
497 {
498     BIGNUM *f, *ret;
499     int i, num = 0, r = -1;
500     unsigned char *buf = NULL;
501     BN_CTX *ctx = NULL;
502
503     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
504         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE);
505         return -1;
506     }
507
508     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
509         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
510         return -1;
511     }
512
513     /* for large moduli, enforce exponent limit */
514     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
515         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
516             RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
517             return -1;
518         }
519     }
520
521     if ((ctx = BN_CTX_new()) == NULL)
522         goto err;
523     BN_CTX_start(ctx);
524     f = BN_CTX_get(ctx);
525     ret = BN_CTX_get(ctx);
526     num = BN_num_bytes(rsa->n);
527     buf = OPENSSL_malloc(num);
528     if (ret == NULL || buf == NULL) {
529         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, ERR_R_MALLOC_FAILURE);
530         goto err;
531     }
532
533     /*
534      * This check was for equality but PGP does evil things and chops off the
535      * top '0' bytes
536      */
537     if (flen > num) {
538         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_DATA_GREATER_THAN_MOD_LEN);
539         goto err;
540     }
541
542     if (BN_bin2bn(from, flen, f) == NULL)
543         goto err;
544
545     if (BN_ucmp(f, rsa->n) >= 0) {
546         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT,
547                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
548         goto err;
549     }
550
551     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
552         if (!BN_MONT_CTX_set_locked
553             (&rsa->_method_mod_n, rsa->lock, rsa->n, ctx))
554             goto err;
555
556     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
557                                rsa->_method_mod_n))
558         goto err;
559
560     if ((padding == RSA_X931_PADDING) && ((bn_get_words(ret)[0] & 0xf) != 12))
561         if (!BN_sub(ret, rsa->n, ret))
562             goto err;
563
564     i = BN_bn2binpad(ret, buf, num);
565
566     switch (padding) {
567     case RSA_PKCS1_PADDING:
568         r = RSA_padding_check_PKCS1_type_1(to, num, buf, i, num);
569         break;
570     case RSA_X931_PADDING:
571         r = RSA_padding_check_X931(to, num, buf, i, num);
572         break;
573     case RSA_NO_PADDING:
574         memcpy(to, buf, (r = i));
575         break;
576     default:
577         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
578         goto err;
579     }
580     if (r < 0)
581         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
582
583  err:
584     if (ctx != NULL)
585         BN_CTX_end(ctx);
586     BN_CTX_free(ctx);
587     OPENSSL_clear_free(buf, num);
588     return r;
589 }
590
591 static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
592 {
593     BIGNUM *r1, *m1, *vrfy, *r2, *m[RSA_MAX_PRIME_NUM - 2];
594     int ret = 0, i, ex_primes = 0;
595     RSA_PRIME_INFO *pinfo;
596
597     BN_CTX_start(ctx);
598
599     r1 = BN_CTX_get(ctx);
600     r2 = BN_CTX_get(ctx);
601     m1 = BN_CTX_get(ctx);
602     vrfy = BN_CTX_get(ctx);
603     if (vrfy == NULL)
604         goto err;
605
606     if (rsa->version == RSA_ASN1_VERSION_MULTI
607         && ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0
608              || ex_primes > RSA_MAX_PRIME_NUM - 2))
609         goto err;
610
611     {
612         BIGNUM *p = BN_new(), *q = BN_new();
613
614         /*
615          * Make sure BN_mod_inverse in Montgomery initialization uses the
616          * BN_FLG_CONSTTIME flag
617          */
618         if (p == NULL || q == NULL) {
619             BN_free(p);
620             BN_free(q);
621             goto err;
622         }
623         BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
624         BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
625
626         if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
627             if (!BN_MONT_CTX_set_locked
628                 (&rsa->_method_mod_p, rsa->lock, p, ctx)
629                 || !BN_MONT_CTX_set_locked(&rsa->_method_mod_q,
630                                            rsa->lock, q, ctx)) {
631                 BN_free(p);
632                 BN_free(q);
633                 goto err;
634             }
635             if (ex_primes > 0) {
636                 /* cache BN_MONT_CTX for other primes */
637                 BIGNUM *r = BN_new();
638
639                 if (r == NULL) {
640                     BN_free(p);
641                     BN_free(q);
642                     goto err;
643                 }
644
645                 for (i = 0; i < ex_primes; i++) {
646                     pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
647                     BN_with_flags(r, pinfo->r, BN_FLG_CONSTTIME);
648                     if (!BN_MONT_CTX_set_locked(&pinfo->m, rsa->lock, r, ctx)) {
649                         BN_free(p);
650                         BN_free(q);
651                         BN_free(r);
652                         goto err;
653                     }
654                 }
655                 BN_free(r);
656             }
657         }
658         /*
659          * We MUST free p and q before any further use of rsa->p and rsa->q
660          */
661         BN_free(p);
662         BN_free(q);
663     }
664
665     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
666         if (!BN_MONT_CTX_set_locked
667             (&rsa->_method_mod_n, rsa->lock, rsa->n, ctx))
668             goto err;
669
670     /* compute I mod q */
671     {
672         BIGNUM *c = BN_new();
673         if (c == NULL)
674             goto err;
675         BN_with_flags(c, I, BN_FLG_CONSTTIME);
676
677         if (!BN_mod(r1, c, rsa->q, ctx)) {
678             BN_free(c);
679             goto err;
680         }
681
682         {
683             BIGNUM *dmq1 = BN_new();
684             if (dmq1 == NULL) {
685                 BN_free(c);
686                 goto err;
687             }
688             BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
689
690             /* compute r1^dmq1 mod q */
691             if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx,
692                 rsa->_method_mod_q)) {
693                 BN_free(c);
694                 BN_free(dmq1);
695                 goto err;
696             }
697             /* We MUST free dmq1 before any further use of rsa->dmq1 */
698             BN_free(dmq1);
699         }
700
701         /* compute I mod p */
702         if (!BN_mod(r1, c, rsa->p, ctx)) {
703             BN_free(c);
704             goto err;
705         }
706         /* We MUST free c before any further use of I */
707         BN_free(c);
708     }
709
710     {
711         BIGNUM *dmp1 = BN_new();
712         if (dmp1 == NULL)
713             goto err;
714         BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
715
716         /* compute r1^dmp1 mod p */
717         if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx,
718                                    rsa->_method_mod_p)) {
719             BN_free(dmp1);
720             goto err;
721         }
722         /* We MUST free dmp1 before any further use of rsa->dmp1 */
723         BN_free(dmp1);
724     }
725
726     /*
727      * calculate m_i in multi-prime case
728      *
729      * TODO:
730      * 1. squash the following two loops and calculate |m_i| there.
731      * 2. remove cc and reuse |c|.
732      * 3. remove |dmq1| and |dmp1| in previous block and use |di|.
733      *
734      * If these things are done, the code will be more readable.
735      */
736     if (ex_primes > 0) {
737         BIGNUM *di = BN_new(), *cc = BN_new();
738
739         if (cc == NULL || di == NULL) {
740             BN_free(cc);
741             BN_free(di);
742             goto err;
743         }
744
745         for (i = 0; i < ex_primes; i++) {
746             /* prepare m_i */
747             if ((m[i] = BN_CTX_get(ctx)) == NULL) {
748                 BN_free(cc);
749                 BN_free(di);
750                 goto err;
751             }
752
753             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
754
755             /* prepare c and d_i */
756             BN_with_flags(cc, I, BN_FLG_CONSTTIME);
757             BN_with_flags(di, pinfo->d, BN_FLG_CONSTTIME);
758
759             if (!BN_mod(r1, cc, pinfo->r, ctx)) {
760                 BN_free(cc);
761                 BN_free(di);
762                 goto err;
763             }
764             /* compute r1 ^ d_i mod r_i */
765             if (!rsa->meth->bn_mod_exp(m[i], r1, di, pinfo->r, ctx, pinfo->m)) {
766                 BN_free(cc);
767                 BN_free(di);
768                 goto err;
769             }
770         }
771
772         BN_free(cc);
773         BN_free(di);
774     }
775
776     if (!BN_sub(r0, r0, m1))
777         goto err;
778     /*
779      * This will help stop the size of r0 increasing, which does affect the
780      * multiply if it optimised for a power of 2 size
781      */
782     if (BN_is_negative(r0))
783         if (!BN_add(r0, r0, rsa->p))
784             goto err;
785
786     if (!BN_mul(r1, r0, rsa->iqmp, ctx))
787         goto err;
788
789     {
790         BIGNUM *pr1 = BN_new();
791         if (pr1 == NULL)
792             goto err;
793         BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
794
795         if (!BN_mod(r0, pr1, rsa->p, ctx)) {
796             BN_free(pr1);
797             goto err;
798         }
799         /* We MUST free pr1 before any further use of r1 */
800         BN_free(pr1);
801     }
802
803     /*
804      * If p < q it is occasionally possible for the correction of adding 'p'
805      * if r0 is negative above to leave the result still negative. This can
806      * break the private key operations: the following second correction
807      * should *always* correct this rare occurrence. This will *never* happen
808      * with OpenSSL generated keys because they ensure p > q [steve]
809      */
810     if (BN_is_negative(r0))
811         if (!BN_add(r0, r0, rsa->p))
812             goto err;
813     if (!BN_mul(r1, r0, rsa->q, ctx))
814         goto err;
815     if (!BN_add(r0, r1, m1))
816         goto err;
817
818     /* add m_i to m in multi-prime case */
819     if (ex_primes > 0) {
820         BIGNUM *pr2 = BN_new();
821
822         if (pr2 == NULL)
823             goto err;
824
825         for (i = 0; i < ex_primes; i++) {
826             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
827             if (!BN_sub(r1, m[i], r0)) {
828                 BN_free(pr2);
829                 goto err;
830             }
831
832             if (!BN_mul(r2, r1, pinfo->t, ctx)) {
833                 BN_free(pr2);
834                 goto err;
835             }
836
837             BN_with_flags(pr2, r2, BN_FLG_CONSTTIME);
838
839             if (!BN_mod(r1, pr2, pinfo->r, ctx)) {
840                 BN_free(pr2);
841                 goto err;
842             }
843
844             if (BN_is_negative(r1))
845                 if (!BN_add(r1, r1, pinfo->r)) {
846                     BN_free(pr2);
847                     goto err;
848                 }
849             if (!BN_mul(r1, r1, pinfo->pp, ctx)) {
850                 BN_free(pr2);
851                 goto err;
852             }
853             if (!BN_add(r0, r0, r1)) {
854                 BN_free(pr2);
855                 goto err;
856             }
857         }
858         BN_free(pr2);
859     }
860
861     if (rsa->e && rsa->n) {
862         if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
863                                    rsa->_method_mod_n))
864             goto err;
865         /*
866          * If 'I' was greater than (or equal to) rsa->n, the operation will
867          * be equivalent to using 'I mod n'. However, the result of the
868          * verify will *always* be less than 'n' so we don't check for
869          * absolute equality, just congruency.
870          */
871         if (!BN_sub(vrfy, vrfy, I))
872             goto err;
873         if (!BN_mod(vrfy, vrfy, rsa->n, ctx))
874             goto err;
875         if (BN_is_negative(vrfy))
876             if (!BN_add(vrfy, vrfy, rsa->n))
877                 goto err;
878         if (!BN_is_zero(vrfy)) {
879             /*
880              * 'I' and 'vrfy' aren't congruent mod n. Don't leak
881              * miscalculated CRT output, just do a raw (slower) mod_exp and
882              * return that instead.
883              */
884
885             BIGNUM *d = BN_new();
886             if (d == NULL)
887                 goto err;
888             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
889
890             if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
891                                        rsa->_method_mod_n)) {
892                 BN_free(d);
893                 goto err;
894             }
895             /* We MUST free d before any further use of rsa->d */
896             BN_free(d);
897         }
898     }
899     ret = 1;
900  err:
901     BN_CTX_end(ctx);
902     return ret;
903 }
904
905 static int rsa_ossl_init(RSA *rsa)
906 {
907     rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
908     return 1;
909 }
910
911 static int rsa_ossl_finish(RSA *rsa)
912 {
913     int i;
914     RSA_PRIME_INFO *pinfo;
915
916     BN_MONT_CTX_free(rsa->_method_mod_n);
917     BN_MONT_CTX_free(rsa->_method_mod_p);
918     BN_MONT_CTX_free(rsa->_method_mod_q);
919     for (i = 0; i < sk_RSA_PRIME_INFO_num(rsa->prime_infos); i++) {
920         pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
921         BN_MONT_CTX_free(pinfo->m);
922     }
923     return 1;
924 }