Following the license change, modify the boilerplates in crypto/rsa/
[openssl.git] / crypto / rsa / rsa_ossl.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #include "internal/constant_time_locl.h"
14
15 static int rsa_ossl_public_encrypt(int flen, const unsigned char *from,
16                                   unsigned char *to, RSA *rsa, int padding);
17 static int rsa_ossl_private_encrypt(int flen, const unsigned char *from,
18                                    unsigned char *to, RSA *rsa, int padding);
19 static int rsa_ossl_public_decrypt(int flen, const unsigned char *from,
20                                   unsigned char *to, RSA *rsa, int padding);
21 static int rsa_ossl_private_decrypt(int flen, const unsigned char *from,
22                                    unsigned char *to, RSA *rsa, int padding);
23 static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa,
24                            BN_CTX *ctx);
25 static int rsa_ossl_init(RSA *rsa);
26 static int rsa_ossl_finish(RSA *rsa);
27 static RSA_METHOD rsa_pkcs1_ossl_meth = {
28     "OpenSSL PKCS#1 RSA",
29     rsa_ossl_public_encrypt,
30     rsa_ossl_public_decrypt,     /* signature verification */
31     rsa_ossl_private_encrypt,    /* signing */
32     rsa_ossl_private_decrypt,
33     rsa_ossl_mod_exp,
34     BN_mod_exp_mont,            /* XXX probably we should not use Montgomery
35                                  * if e == 3 */
36     rsa_ossl_init,
37     rsa_ossl_finish,
38     RSA_FLAG_FIPS_METHOD,       /* flags */
39     NULL,
40     0,                          /* rsa_sign */
41     0,                          /* rsa_verify */
42     NULL,                       /* rsa_keygen */
43     NULL                        /* rsa_multi_prime_keygen */
44 };
45
46 static const RSA_METHOD *default_RSA_meth = &rsa_pkcs1_ossl_meth;
47
48 void RSA_set_default_method(const RSA_METHOD *meth)
49 {
50     default_RSA_meth = meth;
51 }
52
53 const RSA_METHOD *RSA_get_default_method(void)
54 {
55     return default_RSA_meth;
56 }
57
58 const RSA_METHOD *RSA_PKCS1_OpenSSL(void)
59 {
60     return &rsa_pkcs1_ossl_meth;
61 }
62
63 const RSA_METHOD *RSA_null_method(void)
64 {
65     return NULL;
66 }
67
68 static int rsa_ossl_public_encrypt(int flen, const unsigned char *from,
69                                   unsigned char *to, RSA *rsa, int padding)
70 {
71     BIGNUM *f, *ret;
72     int i, num = 0, r = -1;
73     unsigned char *buf = NULL;
74     BN_CTX *ctx = NULL;
75
76     if (BN_num_bits(rsa->n) > OPENSSL_RSA_MAX_MODULUS_BITS) {
77         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_MODULUS_TOO_LARGE);
78         return -1;
79     }
80
81     if (BN_ucmp(rsa->n, rsa->e) <= 0) {
82         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
83         return -1;
84     }
85
86     /* for large moduli, enforce exponent limit */
87     if (BN_num_bits(rsa->n) > OPENSSL_RSA_SMALL_MODULUS_BITS) {
88         if (BN_num_bits(rsa->e) > OPENSSL_RSA_MAX_PUBEXP_BITS) {
89             RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_BAD_E_VALUE);
90             return -1;
91         }
92     }
93
94     if ((ctx = BN_CTX_new()) == NULL)
95         goto err;
96     BN_CTX_start(ctx);
97     f = BN_CTX_get(ctx);
98     ret = BN_CTX_get(ctx);
99     num = BN_num_bytes(rsa->n);
100     buf = OPENSSL_malloc(num);
101     if (ret == NULL || buf == NULL) {
102         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, ERR_R_MALLOC_FAILURE);
103         goto err;
104     }
105
106     switch (padding) {
107     case RSA_PKCS1_PADDING:
108         i = RSA_padding_add_PKCS1_type_2(buf, num, from, flen);
109         break;
110     case RSA_PKCS1_OAEP_PADDING:
111         i = RSA_padding_add_PKCS1_OAEP(buf, num, from, flen, NULL, 0);
112         break;
113     case RSA_SSLV23_PADDING:
114         i = RSA_padding_add_SSLv23(buf, num, from, flen);
115         break;
116     case RSA_NO_PADDING:
117         i = RSA_padding_add_none(buf, num, from, flen);
118         break;
119     default:
120         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
121         goto err;
122     }
123     if (i <= 0)
124         goto err;
125
126     if (BN_bin2bn(buf, num, f) == NULL)
127         goto err;
128
129     if (BN_ucmp(f, rsa->n) >= 0) {
130         /* usually the padding functions would catch this */
131         RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT,
132                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
133         goto err;
134     }
135
136     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
137         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
138                                     rsa->n, ctx))
139             goto err;
140
141     if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx,
142                                rsa->_method_mod_n))
143         goto err;
144
145     /*
146      * BN_bn2binpad puts in leading 0 bytes if the number is less than
147      * the length of the modulus.
148      */
149     r = BN_bn2binpad(ret, to, num);
150  err:
151     if (ctx != NULL)
152         BN_CTX_end(ctx);
153     BN_CTX_free(ctx);
154     OPENSSL_clear_free(buf, num);
155     return r;
156 }
157
158 static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx)
159 {
160     BN_BLINDING *ret;
161
162     CRYPTO_THREAD_write_lock(rsa->lock);
163
164     if (rsa->blinding == NULL) {
165         rsa->blinding = RSA_setup_blinding(rsa, ctx);
166     }
167
168     ret = rsa->blinding;
169     if (ret == NULL)
170         goto err;
171
172     if (BN_BLINDING_is_current_thread(ret)) {
173         /* rsa->blinding is ours! */
174
175         *local = 1;
176     } else {
177         /* resort to rsa->mt_blinding instead */
178
179         /*
180          * instructs rsa_blinding_convert(), rsa_blinding_invert() that the
181          * BN_BLINDING is shared, meaning that accesses require locks, and
182          * that the blinding factor must be stored outside the BN_BLINDING
183          */
184         *local = 0;
185
186         if (rsa->mt_blinding == NULL) {
187             rsa->mt_blinding = RSA_setup_blinding(rsa, ctx);
188         }
189         ret = rsa->mt_blinding;
190     }
191
192  err:
193     CRYPTO_THREAD_unlock(rsa->lock);
194     return ret;
195 }
196
197 static int rsa_blinding_convert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
198                                 BN_CTX *ctx)
199 {
200     if (unblind == NULL) {
201         /*
202          * Local blinding: store the unblinding factor in BN_BLINDING.
203          */
204         return BN_BLINDING_convert_ex(f, NULL, b, ctx);
205     } else {
206         /*
207          * Shared blinding: store the unblinding factor outside BN_BLINDING.
208          */
209         int ret;
210
211         BN_BLINDING_lock(b);
212         ret = BN_BLINDING_convert_ex(f, unblind, b, ctx);
213         BN_BLINDING_unlock(b);
214
215         return ret;
216     }
217 }
218
219 static int rsa_blinding_invert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind,
220                                BN_CTX *ctx)
221 {
222     /*
223      * For local blinding, unblind is set to NULL, and BN_BLINDING_invert_ex
224      * will use the unblinding factor stored in BN_BLINDING. If BN_BLINDING
225      * is shared between threads, unblind must be non-null:
226      * BN_BLINDING_invert_ex will then use the local unblinding factor, and
227      * will only read the modulus from BN_BLINDING. In both cases it's safe
228      * to access the blinding without a lock.
229      */
230     return BN_BLINDING_invert_ex(f, unblind, b, ctx);
231 }
232
233 /* signing */
234 static int rsa_ossl_private_encrypt(int flen, const unsigned char *from,
235                                    unsigned char *to, RSA *rsa, int padding)
236 {
237     BIGNUM *f, *ret, *res;
238     int i, num = 0, r = -1;
239     unsigned char *buf = NULL;
240     BN_CTX *ctx = NULL;
241     int local_blinding = 0;
242     /*
243      * Used only if the blinding structure is shared. A non-NULL unblind
244      * instructs rsa_blinding_convert() and rsa_blinding_invert() to store
245      * the unblinding factor outside the blinding structure.
246      */
247     BIGNUM *unblind = NULL;
248     BN_BLINDING *blinding = NULL;
249
250     if ((ctx = BN_CTX_new()) == NULL)
251         goto err;
252     BN_CTX_start(ctx);
253     f = BN_CTX_get(ctx);
254     ret = BN_CTX_get(ctx);
255     num = BN_num_bytes(rsa->n);
256     buf = OPENSSL_malloc(num);
257     if (ret == NULL || buf == NULL) {
258         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
259         goto err;
260     }
261
262     switch (padding) {
263     case RSA_PKCS1_PADDING:
264         i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
265         break;
266     case RSA_X931_PADDING:
267         i = RSA_padding_add_X931(buf, num, from, flen);
268         break;
269     case RSA_NO_PADDING:
270         i = RSA_padding_add_none(buf, num, from, flen);
271         break;
272     case RSA_SSLV23_PADDING:
273     default:
274         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
275         goto err;
276     }
277     if (i <= 0)
278         goto err;
279
280     if (BN_bin2bn(buf, num, f) == NULL)
281         goto err;
282
283     if (BN_ucmp(f, rsa->n) >= 0) {
284         /* usually the padding functions would catch this */
285         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT,
286                RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
287         goto err;
288     }
289
290     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
291         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
292                                     rsa->n, ctx))
293             goto err;
294
295     if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
296         blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
297         if (blinding == NULL) {
298             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
299             goto err;
300         }
301     }
302
303     if (blinding != NULL) {
304         if (!local_blinding && ((unblind = BN_CTX_get(ctx)) == NULL)) {
305             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
306             goto err;
307         }
308         if (!rsa_blinding_convert(blinding, f, unblind, ctx))
309             goto err;
310     }
311
312     if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
313         (rsa->version == RSA_ASN1_VERSION_MULTI) ||
314         ((rsa->p != NULL) &&
315          (rsa->q != NULL) &&
316          (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) {
317         if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx))
318             goto err;
319     } else {
320         BIGNUM *d = BN_new();
321         if (d == NULL) {
322             RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
323             goto err;
324         }
325         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
326
327         if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx,
328                                    rsa->_method_mod_n)) {
329             BN_free(d);
330             goto err;
331         }
332         /* We MUST free d before any further use of rsa->d */
333         BN_free(d);
334     }
335
336     if (blinding)
337         if (!rsa_blinding_invert(blinding, ret, unblind, ctx))
338             goto err;
339
340     if (padding == RSA_X931_PADDING) {
341         if (!BN_sub(f, rsa->n, ret))
342             goto err;
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(&rsa->_method_mod_n, rsa->lock,
447                                         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     RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, RSA_R_PADDING_CHECK_FAILED);
484     err_clear_last_constant_time(r >= 0);
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(&rsa->_method_mod_n, rsa->lock,
553                                     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, smooth = 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     if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
612         BIGNUM *factor = BN_new();
613
614         if (factor == NULL)
615             goto err;
616
617         /*
618          * Make sure BN_mod_inverse in Montgomery initialization uses the
619          * BN_FLG_CONSTTIME flag
620          */
621         if (!(BN_with_flags(factor, rsa->p, BN_FLG_CONSTTIME),
622               BN_MONT_CTX_set_locked(&rsa->_method_mod_p, rsa->lock,
623                                      factor, ctx))
624             || !(BN_with_flags(factor, rsa->q, BN_FLG_CONSTTIME),
625                  BN_MONT_CTX_set_locked(&rsa->_method_mod_q, rsa->lock,
626                                         factor, ctx))) {
627             BN_free(factor);
628             goto err;
629         }
630         for (i = 0; i < ex_primes; i++) {
631             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
632             BN_with_flags(factor, pinfo->r, BN_FLG_CONSTTIME);
633             if (!BN_MONT_CTX_set_locked(&pinfo->m, rsa->lock, factor, ctx)) {
634                 BN_free(factor);
635                 goto err;
636             }
637         }
638         /*
639          * We MUST free |factor| before any further use of the prime factors
640          */
641         BN_free(factor);
642
643         smooth = (ex_primes == 0)
644                  && (rsa->meth->bn_mod_exp == BN_mod_exp_mont)
645                  && (BN_num_bits(rsa->q) == BN_num_bits(rsa->p));
646     }
647
648     if (rsa->flags & RSA_FLAG_CACHE_PUBLIC)
649         if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, rsa->lock,
650                                     rsa->n, ctx))
651             goto err;
652
653     if (smooth) {
654         /*
655          * Conversion from Montgomery domain, a.k.a. Montgomery reduction,
656          * accepts values in [0-m*2^w) range. w is m's bit width rounded up
657          * to limb width. So that at the very least if |I| is fully reduced,
658          * i.e. less than p*q, we can count on from-to round to perform
659          * below modulo operations on |I|. Unlike BN_mod it's constant time.
660          */
661         if (/* m1 = I moq q */
662             !bn_from_mont_fixed_top(m1, I, rsa->_method_mod_q, ctx)
663             || !bn_to_mont_fixed_top(m1, m1, rsa->_method_mod_q, ctx)
664             /* m1 = m1^dmq1 mod q */
665             || !BN_mod_exp_mont_consttime(m1, m1, rsa->dmq1, rsa->q, ctx,
666                                           rsa->_method_mod_q)
667             /* r1 = I mod p */
668             || !bn_from_mont_fixed_top(r1, I, rsa->_method_mod_p, ctx)
669             || !bn_to_mont_fixed_top(r1, r1, rsa->_method_mod_p, ctx)
670             /* r1 = r1^dmp1 mod p */
671             || !BN_mod_exp_mont_consttime(r1, r1, rsa->dmp1, rsa->p, ctx,
672                                           rsa->_method_mod_p)
673             /* r1 = (r1 - m1) mod p */
674             /*
675              * bn_mod_sub_fixed_top is not regular modular subtraction,
676              * it can tolerate subtrahend to be larger than modulus, but
677              * not bit-wise wider. This makes up for uncommon q>p case,
678              * when |m1| can be larger than |rsa->p|.
679              */
680             || !bn_mod_sub_fixed_top(r1, r1, m1, rsa->p)
681
682             /* r1 = r1 * iqmp mod p */
683             || !bn_to_mont_fixed_top(r1, r1, rsa->_method_mod_p, ctx)
684             || !bn_mul_mont_fixed_top(r1, r1, rsa->iqmp, rsa->_method_mod_p,
685                                       ctx)
686             /* r0 = r1 * q + m1 */
687             || !bn_mul_fixed_top(r0, r1, rsa->q, ctx)
688             || !bn_mod_add_fixed_top(r0, r0, m1, rsa->n))
689             goto err;
690
691         goto tail;
692     }
693
694     /* compute I mod q */
695     {
696         BIGNUM *c = BN_new();
697         if (c == NULL)
698             goto err;
699         BN_with_flags(c, I, BN_FLG_CONSTTIME);
700
701         if (!BN_mod(r1, c, rsa->q, ctx)) {
702             BN_free(c);
703             goto err;
704         }
705
706         {
707             BIGNUM *dmq1 = BN_new();
708             if (dmq1 == NULL) {
709                 BN_free(c);
710                 goto err;
711             }
712             BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
713
714             /* compute r1^dmq1 mod q */
715             if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx,
716                                        rsa->_method_mod_q)) {
717                 BN_free(c);
718                 BN_free(dmq1);
719                 goto err;
720             }
721             /* We MUST free dmq1 before any further use of rsa->dmq1 */
722             BN_free(dmq1);
723         }
724
725         /* compute I mod p */
726         if (!BN_mod(r1, c, rsa->p, ctx)) {
727             BN_free(c);
728             goto err;
729         }
730         /* We MUST free c before any further use of I */
731         BN_free(c);
732     }
733
734     {
735         BIGNUM *dmp1 = BN_new();
736         if (dmp1 == NULL)
737             goto err;
738         BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
739
740         /* compute r1^dmp1 mod p */
741         if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx,
742                                    rsa->_method_mod_p)) {
743             BN_free(dmp1);
744             goto err;
745         }
746         /* We MUST free dmp1 before any further use of rsa->dmp1 */
747         BN_free(dmp1);
748     }
749
750     /*
751      * calculate m_i in multi-prime case
752      *
753      * TODO:
754      * 1. squash the following two loops and calculate |m_i| there.
755      * 2. remove cc and reuse |c|.
756      * 3. remove |dmq1| and |dmp1| in previous block and use |di|.
757      *
758      * If these things are done, the code will be more readable.
759      */
760     if (ex_primes > 0) {
761         BIGNUM *di = BN_new(), *cc = BN_new();
762
763         if (cc == NULL || di == NULL) {
764             BN_free(cc);
765             BN_free(di);
766             goto err;
767         }
768
769         for (i = 0; i < ex_primes; i++) {
770             /* prepare m_i */
771             if ((m[i] = BN_CTX_get(ctx)) == NULL) {
772                 BN_free(cc);
773                 BN_free(di);
774                 goto err;
775             }
776
777             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
778
779             /* prepare c and d_i */
780             BN_with_flags(cc, I, BN_FLG_CONSTTIME);
781             BN_with_flags(di, pinfo->d, BN_FLG_CONSTTIME);
782
783             if (!BN_mod(r1, cc, pinfo->r, ctx)) {
784                 BN_free(cc);
785                 BN_free(di);
786                 goto err;
787             }
788             /* compute r1 ^ d_i mod r_i */
789             if (!rsa->meth->bn_mod_exp(m[i], r1, di, pinfo->r, ctx, pinfo->m)) {
790                 BN_free(cc);
791                 BN_free(di);
792                 goto err;
793             }
794         }
795
796         BN_free(cc);
797         BN_free(di);
798     }
799
800     if (!BN_sub(r0, r0, m1))
801         goto err;
802     /*
803      * This will help stop the size of r0 increasing, which does affect the
804      * multiply if it optimised for a power of 2 size
805      */
806     if (BN_is_negative(r0))
807         if (!BN_add(r0, r0, rsa->p))
808             goto err;
809
810     if (!BN_mul(r1, r0, rsa->iqmp, ctx))
811         goto err;
812
813     {
814         BIGNUM *pr1 = BN_new();
815         if (pr1 == NULL)
816             goto err;
817         BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
818
819         if (!BN_mod(r0, pr1, rsa->p, ctx)) {
820             BN_free(pr1);
821             goto err;
822         }
823         /* We MUST free pr1 before any further use of r1 */
824         BN_free(pr1);
825     }
826
827     /*
828      * If p < q it is occasionally possible for the correction of adding 'p'
829      * if r0 is negative above to leave the result still negative. This can
830      * break the private key operations: the following second correction
831      * should *always* correct this rare occurrence. This will *never* happen
832      * with OpenSSL generated keys because they ensure p > q [steve]
833      */
834     if (BN_is_negative(r0))
835         if (!BN_add(r0, r0, rsa->p))
836             goto err;
837     if (!BN_mul(r1, r0, rsa->q, ctx))
838         goto err;
839     if (!BN_add(r0, r1, m1))
840         goto err;
841
842     /* add m_i to m in multi-prime case */
843     if (ex_primes > 0) {
844         BIGNUM *pr2 = BN_new();
845
846         if (pr2 == NULL)
847             goto err;
848
849         for (i = 0; i < ex_primes; i++) {
850             pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
851             if (!BN_sub(r1, m[i], r0)) {
852                 BN_free(pr2);
853                 goto err;
854             }
855
856             if (!BN_mul(r2, r1, pinfo->t, ctx)) {
857                 BN_free(pr2);
858                 goto err;
859             }
860
861             BN_with_flags(pr2, r2, BN_FLG_CONSTTIME);
862
863             if (!BN_mod(r1, pr2, pinfo->r, ctx)) {
864                 BN_free(pr2);
865                 goto err;
866             }
867
868             if (BN_is_negative(r1))
869                 if (!BN_add(r1, r1, pinfo->r)) {
870                     BN_free(pr2);
871                     goto err;
872                 }
873             if (!BN_mul(r1, r1, pinfo->pp, ctx)) {
874                 BN_free(pr2);
875                 goto err;
876             }
877             if (!BN_add(r0, r0, r1)) {
878                 BN_free(pr2);
879                 goto err;
880             }
881         }
882         BN_free(pr2);
883     }
884
885  tail:
886     if (rsa->e && rsa->n) {
887         if (rsa->meth->bn_mod_exp == BN_mod_exp_mont) {
888             if (!BN_mod_exp_mont(vrfy, r0, rsa->e, rsa->n, ctx,
889                                  rsa->_method_mod_n))
890                 goto err;
891         } else {
892             bn_correct_top(r0);
893             if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
894                                        rsa->_method_mod_n))
895                 goto err;
896         }
897         /*
898          * If 'I' was greater than (or equal to) rsa->n, the operation will
899          * be equivalent to using 'I mod n'. However, the result of the
900          * verify will *always* be less than 'n' so we don't check for
901          * absolute equality, just congruency.
902          */
903         if (!BN_sub(vrfy, vrfy, I))
904             goto err;
905         if (BN_is_zero(vrfy)) {
906             bn_correct_top(r0);
907             ret = 1;
908             goto err;   /* not actually error */
909         }
910         if (!BN_mod(vrfy, vrfy, rsa->n, ctx))
911             goto err;
912         if (BN_is_negative(vrfy))
913             if (!BN_add(vrfy, vrfy, rsa->n))
914                 goto err;
915         if (!BN_is_zero(vrfy)) {
916             /*
917              * 'I' and 'vrfy' aren't congruent mod n. Don't leak
918              * miscalculated CRT output, just do a raw (slower) mod_exp and
919              * return that instead.
920              */
921
922             BIGNUM *d = BN_new();
923             if (d == NULL)
924                 goto err;
925             BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
926
927             if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
928                                        rsa->_method_mod_n)) {
929                 BN_free(d);
930                 goto err;
931             }
932             /* We MUST free d before any further use of rsa->d */
933             BN_free(d);
934         }
935     }
936     /*
937      * It's unfortunate that we have to bn_correct_top(r0). What hopefully
938      * saves the day is that correction is highly unlike, and private key
939      * operations are customarily performed on blinded message. Which means
940      * that attacker won't observe correlation with chosen plaintext.
941      * Secondly, remaining code would still handle it in same computational
942      * time and even conceal memory access pattern around corrected top.
943      */
944     bn_correct_top(r0);
945     ret = 1;
946  err:
947     BN_CTX_end(ctx);
948     return ret;
949 }
950
951 static int rsa_ossl_init(RSA *rsa)
952 {
953     rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
954     return 1;
955 }
956
957 static int rsa_ossl_finish(RSA *rsa)
958 {
959     int i;
960     RSA_PRIME_INFO *pinfo;
961
962     BN_MONT_CTX_free(rsa->_method_mod_n);
963     BN_MONT_CTX_free(rsa->_method_mod_p);
964     BN_MONT_CTX_free(rsa->_method_mod_q);
965     for (i = 0; i < sk_RSA_PRIME_INFO_num(rsa->prime_infos); i++) {
966         pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i);
967         BN_MONT_CTX_free(pinfo->m);
968     }
969     return 1;
970 }