rsa/rsa_ossl.c: cache MONT_CTX for public modulus earlier.
[openssl.git] / crypto / rsa / rsa_ossl.c
1 /*
2  * Copyright 1995-2018 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(&rsa->_method_mod_n, rsa->lock,
137                                     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_CACHE_PUBLIC)
290         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
291                                     rsa->n, ctx))
292             goto err;
293
294     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
295         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
296         if (blinding == NULL) {
297             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
298             goto err;
299         }
300     }
301
302     if (blinding != NULL) {
303         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
304             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
305             goto err;
306         }
307         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
308             goto err;
309     }
310
311     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
312         (rsa->version == RSA_ASN1_VERSION_MULTI) ||
313         ((rsa->p != NULL) &&
314          (rsa->q != NULL) &&
315          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
316         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
317             goto err;
318     } else {
319         BIGNUM *d = BN_new();
320         if (d == NULL) {
321             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
322             goto err;
323         }
324         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
325
326         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
327                                    rsa->_method_mod_n)) {
328             BN_free(d);
329             goto err;
330         }
331         /* We MUST free d before any further use of rsa->d */
332         BN_free(d);
333     }
334
335     if (blinding)
336         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
337             goto err;
338
339     if (padding == RSA_X931_PADDING) {
340         if (!BN_sub(f, rsa->n, ret))
341             goto err;
342         if (BN_cmp(ret, f) > 0)
343             res = f;
344         else
345             res = ret;
346     } else {
347         res = ret;
348     }
349
350     /*
351      * BN_bn2binpad puts in leading 0 bytes if the number is less than
352      * the length of the modulus.
353      */
354     r = BN_bn2binpad(res, to, num);
355  err:
356     if (ctx != NULL)
357         BN_CTX_end(ctx);
358     BN_CTX_free(ctx);
359     OPENSSL_clear_free(buf, num);
360     return r;
361 }
362
363 static int rsa_ossl_private_decrypt(int flen, const unsigned char *from,
364                                    unsigned char *to, RSA *rsa, int padding)
365 {
366     BIGNUM *f, *ret;
367     int j, num = 0, r = -1;
368     unsigned char *buf = NULL;
369     BN_CTX *ctx = NULL;
370     int local_blinding = 0;
371     /*
372      * Used only if the blinding structure is shared. A non-NULL unblind
373      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
374      * the unblinding factor outside the blinding structure.
375      */
376     BIGNUM *unblind = NULL;
377     BN_BLINDING *blinding = NULL;
378
379     if ((ctx = BN_CTX_new()) == NULL)
380         goto err;
381     BN_CTX_start(ctx);
382     f = BN_CTX_get(ctx);
383     ret = BN_CTX_get(ctx);
384     num = BN_num_bytes(rsa->n);
385     buf = OPENSSL_malloc(num);
386     if (ret == NULL || buf == NULL) {
387         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
388         goto err;
389     }
390
391     /*
392      * This check was for equality but PGP does evil things and chops off the
393      * top '0' bytes
394      */
395     if (flen > num) {
396         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT,
397                RSA_R_DATA_GREATER_THAN_MOD_LEN);
398         goto err;
399     }
400
401     /* make data into a big number */
402     if (BN_bin2bn(from, (int)flen, f) == NULL)
403         goto err;
404
405     if (BN_ucmp(f, rsa->n) >= 0) {
406         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT,
407                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
408         goto err;
409     }
410
411     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
412         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
413         if (blinding == NULL) {
414             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
415             goto err;
416         }
417     }
418
419     if (blinding != NULL) {
420         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
421             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
422             goto err;
423         }
424         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
425             goto err;
426     }
427
428     /* do the decrypt */
429     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
430         (rsa->version == RSA_ASN1_VERSION_MULTI) ||
431         ((rsa->p != NULL) &&
432          (rsa->q != NULL) &&
433          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
434         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
435             goto err;
436     } else {
437         BIGNUM *d = BN_new();
438         if (d == NULL) {
439             RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE);
440             goto err;
441         }
442         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
443
444         if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
445             if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
446                                         rsa->n, ctx)) {
447                 BN_free(d);
448                 goto err;
449             }
450         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
451                                    rsa->_method_mod_n)) {
452             BN_free(d);
453             goto err;
454         }
455         /* We MUST free d before any further use of rsa->d */
456         BN_free(d);
457     }
458
459     if (blinding)
460         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
461             goto err;
462
463     j = BN_bn2binpad(ret, buf, num);
464
465     switch (padding) {
466     case RSA_PKCS1_PADDING:
467         r = RSA_padding_check_PKCS1_type_2(to, num, buf, j, num);
468         break;
469     case RSA_PKCS1_OAEP_PADDING:
470         r = RSA_padding_check_PKCS1_OAEP(to, num, buf, j, num, NULL, 0);
471         break;
472     case RSA_SSLV23_PADDING:
473         r = RSA_padding_check_SSLv23(to, num, buf, j, num);
474         break;
475     case RSA_NO_PADDING:
476         memcpy(to, buf, (r = j));
477         break;
478     default:
479         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
480         goto err;
481     }
482     if (r < 0)
483         RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
484
485  err:
486     if (ctx != NULL)
487         BN_CTX_end(ctx);
488     BN_CTX_free(ctx);
489     OPENSSL_clear_free(buf, num);
490     return r;
491 }
492
493 /* signature verification */
494 static int rsa_ossl_public_decrypt(int flen, const unsigned char *from,
495                                   unsigned char *to, RSA *rsa, int padding)
496 {
497     BIGNUM *f, *ret;
498     int i, num = 0, r = -1;
499     unsigned char *buf = NULL;
500     BN_CTX *ctx = NULL;
501
502     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
503         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE);
504         return -1;
505     }
506
507     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
508         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
509         return -1;
510     }
511
512     /* for large moduli, enforce exponent limit */
513     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
514         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
515             RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE);
516             return -1;
517         }
518     }
519
520     if ((ctx = BN_CTX_new()) == NULL)
521         goto err;
522     BN_CTX_start(ctx);
523     f = BN_CTX_get(ctx);
524     ret = BN_CTX_get(ctx);
525     num = BN_num_bytes(rsa->n);
526     buf = OPENSSL_malloc(num);
527     if (ret == NULL || buf == NULL) {
528         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, ERR_R_MALLOC_FAILURE);
529         goto err;
530     }
531
532     /*
533      * This check was for equality but PGP does evil things and chops off the
534      * top '0' bytes
535      */
536     if (flen > num) {
537         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_DATA_GREATER_THAN_MOD_LEN);
538         goto err;
539     }
540
541     if (BN_bin2bn(from, flen, f) == NULL)
542         goto err;
543
544     if (BN_ucmp(f, rsa->n) >= 0) {
545         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT,
546                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
547         goto err;
548     }
549
550     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
551         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
552                                     rsa->n, ctx))
553             goto err;
554
555     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
556                                rsa->_method_mod_n))
557         goto err;
558
559     if ((padding == RSA_X931_PADDING) && ((bn_get_words(ret)[0] & 0xf) != 12))
560         if (!BN_sub(ret, rsa->n, ret))
561             goto err;
562
563     i = BN_bn2binpad(ret, buf, num);
564
565     switch (padding) {
566     case RSA_PKCS1_PADDING:
567         r = RSA_padding_check_PKCS1_type_1(to, num, buf, i, num);
568         break;
569     case RSA_X931_PADDING:
570         r = RSA_padding_check_X931(to, num, buf, i, num);
571         break;
572     case RSA_NO_PADDING:
573         memcpy(to, buf, (r = i));
574         break;
575     default:
576         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
577         goto err;
578     }
579     if (r < 0)
580         RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
581
582  err:
583     if (ctx != NULL)
584         BN_CTX_end(ctx);
585     BN_CTX_free(ctx);
586     OPENSSL_clear_free(buf, num);
587     return r;
588 }
589
590 static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
591 {
592     BIGNUM *r1, *m1, *vrfy, *r2, *m[RSA_MAX_PRIME_NUM - 2];
593     int ret = 0, i, ex_primes = 0, smooth = 0;
594     RSA_PRIME_INFO *pinfo;
595
596     BN_CTX_start(ctx);
597
598     r1 = BN_CTX_get(ctx);
599     r2 = BN_CTX_get(ctx);
600     m1 = BN_CTX_get(ctx);
601     vrfy = BN_CTX_get(ctx);
602     if (vrfy == NULL)
603         goto err;
604
605     if (rsa->version == RSA_ASN1_VERSION_MULTI
606         && ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0
607              || ex_primes > RSA_MAX_PRIME_NUM - 2))
608         goto err;
609
610     if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
611         BIGNUM *factor = BN_new();
612
613         if (factor == NULL)
614             goto err;
615
616         /*
617          * Make sure BN_mod_inverse in Montgomery initialization uses the
618          * BN_FLG_CONSTTIME flag
619          */
620         if (!(BN_with_flags(factor, rsa->p, BN_FLG_CONSTTIME),
621               BN_MONT_CTX_set_locked(&rsa->_method_mod_p, rsa->lock,
622                                      factor, ctx))
623             || !(BN_with_flags(factor, rsa->q, BN_FLG_CONSTTIME),
624                  BN_MONT_CTX_set_locked(&rsa->_method_mod_q, rsa->lock,
625                                         factor, ctx))) {
626             BN_free(factor);
627             goto err;
628         }
629         for (i = 0; i < ex_primes; i++) {
630             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
631             BN_with_flags(factor, pinfo->r, BN_FLG_CONSTTIME);
632             if (!BN_MONT_CTX_set_locked(&pinfo->m, rsa->lock, factor, ctx)) {
633                 BN_free(factor);
634                 goto err;
635             }
636         }
637         /*
638          * We MUST free |factor| before any further use of the prime factors
639          */
640         BN_free(factor);
641
642         smooth = (ex_primes == 0)
643                  && (rsa->meth->bn_mod_exp == BN_mod_exp_mont)
644                  && (BN_num_bits(rsa->q) == BN_num_bits(rsa->p));
645     }
646
647     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
648         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
649                                     rsa->n, ctx))
650             goto err;
651
652     if (smooth) {
653         /*
654          * Conversion from Montgomery domain, a.k.a. Montgomery reduction,
655          * accepts values in [0-m*2^w) range. w is m's bit width rounded up
656          * to limb width. So that at the very least if |I| is fully reduced,
657          * i.e. less than p*q, we can count on from-to round to perform
658          * below modulo operations on |I|. Unlike BN_mod it's constant time.
659          */
660         if (/* m1 = I moq q */
661             !bn_from_mont_fixed_top(m1, I, rsa->_method_mod_q, ctx)
662             || !bn_to_mont_fixed_top(m1, m1, rsa->_method_mod_q, ctx)
663             /* m1 = m1^dmq1 mod q */
664             || !BN_mod_exp_mont_consttime(m1, m1, rsa->dmq1, rsa->q, ctx,
665                                           rsa->_method_mod_q)
666             /* r1 = I mod p */
667             || !bn_from_mont_fixed_top(r1, I, rsa->_method_mod_p, ctx)
668             || !bn_to_mont_fixed_top(r1, r1, rsa->_method_mod_p, ctx)
669             /* r1 = r1^dmp1 mod p */
670             || !BN_mod_exp_mont_consttime(r1, r1, rsa->dmp1, rsa->p, ctx,
671                                           rsa->_method_mod_p)
672             /* r1 = (r1 - m1) mod p */
673             /*
674              * bn_mod_sub_fixed_top is not regular modular subtraction,
675              * it can tolerate subtrahend to be larger than modulus, but
676              * not bit-wise wider. This makes up for uncommon q>p case,
677              * when |m1| can be larger than |rsa->p|.
678              */
679             || !bn_mod_sub_fixed_top(r1, r1, m1, rsa->p)
680
681             /* r1 = r1 * iqmp mod p */
682             || !bn_to_mont_fixed_top(r1, r1, rsa->_method_mod_p, ctx)
683             || !bn_mul_mont_fixed_top(r1, r1, rsa->iqmp, rsa->_method_mod_p,
684                                       ctx)
685             /* r0 = r1 * q + m1 */
686             || !bn_mul_fixed_top(r0, r1, rsa->q, ctx)
687             || !bn_mod_add_fixed_top(r0, r0, m1, rsa->n))
688             goto err;
689
690         goto tail;
691     }
692
693     /* compute I mod q */
694     {
695         BIGNUM *c = BN_new();
696         if (c == NULL)
697             goto err;
698         BN_with_flags(c, I, BN_FLG_CONSTTIME);
699
700         if (!BN_mod(r1, c, rsa->q, ctx)) {
701             BN_free(c);
702             goto err;
703         }
704
705         {
706             BIGNUM *dmq1 = BN_new();
707             if (dmq1 == NULL) {
708                 BN_free(c);
709                 goto err;
710             }
711             BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
712
713             /* compute r1^dmq1 mod q */
714             if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx,
715                                        rsa->_method_mod_q)) {
716                 BN_free(c);
717                 BN_free(dmq1);
718                 goto err;
719             }
720             /* We MUST free dmq1 before any further use of rsa->dmq1 */
721             BN_free(dmq1);
722         }
723
724         /* compute I mod p */
725         if (!BN_mod(r1, c, rsa->p, ctx)) {
726             BN_free(c);
727             goto err;
728         }
729         /* We MUST free c before any further use of I */
730         BN_free(c);
731     }
732
733     {
734         BIGNUM *dmp1 = BN_new();
735         if (dmp1 == NULL)
736             goto err;
737         BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
738
739         /* compute r1^dmp1 mod p */
740         if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx,
741                                    rsa->_method_mod_p)) {
742             BN_free(dmp1);
743             goto err;
744         }
745         /* We MUST free dmp1 before any further use of rsa->dmp1 */
746         BN_free(dmp1);
747     }
748
749     /*
750      * calculate m_i in multi-prime case
751      *
752      * TODO:
753      * 1. squash the following two loops and calculate |m_i| there.
754      * 2. remove cc and reuse |c|.
755      * 3. remove |dmq1| and |dmp1| in previous block and use |di|.
756      *
757      * If these things are done, the code will be more readable.
758      */
759     if (ex_primes > 0) {
760         BIGNUM *di = BN_new(), *cc = BN_new();
761
762         if (cc == NULL || di == NULL) {
763             BN_free(cc);
764             BN_free(di);
765             goto err;
766         }
767
768         for (i = 0; i < ex_primes; i++) {
769             /* prepare m_i */
770             if ((m[i] = BN_CTX_get(ctx)) == NULL) {
771                 BN_free(cc);
772                 BN_free(di);
773                 goto err;
774             }
775
776             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
777
778             /* prepare c and d_i */
779             BN_with_flags(cc, I, BN_FLG_CONSTTIME);
780             BN_with_flags(di, pinfo->d, BN_FLG_CONSTTIME);
781
782             if (!BN_mod(r1, cc, pinfo->r, ctx)) {
783                 BN_free(cc);
784                 BN_free(di);
785                 goto err;
786             }
787             /* compute r1 ^ d_i mod r_i */
788             if (!rsa->meth->bn_mod_exp(m[i], r1, di, pinfo->r, ctx, pinfo->m)) {
789                 BN_free(cc);
790                 BN_free(di);
791                 goto err;
792             }
793         }
794
795         BN_free(cc);
796         BN_free(di);
797     }
798
799     if (!BN_sub(r0, r0, m1))
800         goto err;
801     /*
802      * This will help stop the size of r0 increasing, which does affect the
803      * multiply if it optimised for a power of 2 size
804      */
805     if (BN_is_negative(r0))
806         if (!BN_add(r0, r0, rsa->p))
807             goto err;
808
809     if (!BN_mul(r1, r0, rsa->iqmp, ctx))
810         goto err;
811
812     {
813         BIGNUM *pr1 = BN_new();
814         if (pr1 == NULL)
815             goto err;
816         BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
817
818         if (!BN_mod(r0, pr1, rsa->p, ctx)) {
819             BN_free(pr1);
820             goto err;
821         }
822         /* We MUST free pr1 before any further use of r1 */
823         BN_free(pr1);
824     }
825
826     /*
827      * If p < q it is occasionally possible for the correction of adding 'p'
828      * if r0 is negative above to leave the result still negative. This can
829      * break the private key operations: the following second correction
830      * should *always* correct this rare occurrence. This will *never* happen
831      * with OpenSSL generated keys because they ensure p > q [steve]
832      */
833     if (BN_is_negative(r0))
834         if (!BN_add(r0, r0, rsa->p))
835             goto err;
836     if (!BN_mul(r1, r0, rsa->q, ctx))
837         goto err;
838     if (!BN_add(r0, r1, m1))
839         goto err;
840
841     /* add m_i to m in multi-prime case */
842     if (ex_primes > 0) {
843         BIGNUM *pr2 = BN_new();
844
845         if (pr2 == NULL)
846             goto err;
847
848         for (i = 0; i < ex_primes; i++) {
849             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
850             if (!BN_sub(r1, m[i], r0)) {
851                 BN_free(pr2);
852                 goto err;
853             }
854
855             if (!BN_mul(r2, r1, pinfo->t, ctx)) {
856                 BN_free(pr2);
857                 goto err;
858             }
859
860             BN_with_flags(pr2, r2, BN_FLG_CONSTTIME);
861
862             if (!BN_mod(r1, pr2, pinfo->r, ctx)) {
863                 BN_free(pr2);
864                 goto err;
865             }
866
867             if (BN_is_negative(r1))
868                 if (!BN_add(r1, r1, pinfo->r)) {
869                     BN_free(pr2);
870                     goto err;
871                 }
872             if (!BN_mul(r1, r1, pinfo->pp, ctx)) {
873                 BN_free(pr2);
874                 goto err;
875             }
876             if (!BN_add(r0, r0, r1)) {
877                 BN_free(pr2);
878                 goto err;
879             }
880         }
881         BN_free(pr2);
882     }
883
884  tail:
885     if (rsa->e && rsa->n) {
886         if (rsa->meth->bn_mod_exp == BN_mod_exp_mont) {
887             if (!BN_mod_exp_mont(vrfy, r0, rsa->e, rsa->n, ctx,
888                                  rsa->_method_mod_n))
889                 goto err;
890         } else {
891             bn_correct_top(r0);
892             if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
893                                        rsa->_method_mod_n))
894                 goto err;
895         }
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_is_zero(vrfy)) {
905             bn_correct_top(r0);
906             ret = 1;
907             goto err;   /* not actually error */
908         }
909         if (!BN_mod(vrfy, vrfy, rsa->n, ctx))
910             goto err;
911         if (BN_is_negative(vrfy))
912             if (!BN_add(vrfy, vrfy, rsa->n))
913                 goto err;
914         if (!BN_is_zero(vrfy)) {
915             /*
916              * 'I' and 'vrfy' aren't congruent mod n. Don't leak
917              * miscalculated CRT output, just do a raw (slower) mod_exp and
918              * return that instead.
919              */
920
921             BIGNUM *d = BN_new();
922             if (d == NULL)
923                 goto err;
924             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
925
926             if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
927                                        rsa->_method_mod_n)) {
928                 BN_free(d);
929                 goto err;
930             }
931             /* We MUST free d before any further use of rsa->d */
932             BN_free(d);
933         }
934     }
935     /*
936      * It's unfortunate that we have to bn_correct_top(r0). What hopefully
937      * saves the day is that correction is highly unlike, and private key
938      * operations are customarily performed on blinded message. Which means
939      * that attacker won't observe correlation with chosen plaintext.
940      * Secondly, remaining code would still handle it in same computational
941      * time and even conceal memory access pattern around corrected top.
942      */
943     bn_correct_top(r0);
944     ret = 1;
945  err:
946     BN_CTX_end(ctx);
947     return ret;
948 }
949
950 static int rsa_ossl_init(RSA *rsa)
951 {
952     rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
953     return 1;
954 }
955
956 static int rsa_ossl_finish(RSA *rsa)
957 {
958     int i;
959     RSA_PRIME_INFO *pinfo;
960
961     BN_MONT_CTX_free(rsa->_method_mod_n);
962     BN_MONT_CTX_free(rsa->_method_mod_p);
963     BN_MONT_CTX_free(rsa->_method_mod_q);
964     for (i = 0; i < sk_RSA_PRIME_INFO_num(rsa->prime_infos); i++) {
965         pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
966         BN_MONT_CTX_free(pinfo->m);
967     }
968     return 1;
969 }