Fix misc external ossl_ symbols.
[openssl.git] / crypto / rsa / rsa_lib.c
1 /*
2  * Copyright 1995-2021 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 /*
11  * RSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <openssl/crypto.h>
17 #include <openssl/core_names.h>
18 #include <openssl/engine.h>
19 #include <openssl/evp.h>
20 #include <openssl/param_build.h>
21 #include "internal/cryptlib.h"
22 #include "internal/refcount.h"
23 #include "crypto/bn.h"
24 #include "crypto/evp.h"
25 #include "crypto/rsa.h"
26 #include "crypto/security_bits.h"
27 #include "rsa_local.h"
28
29 static RSA *rsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx);
30
31 #ifndef FIPS_MODULE
32 RSA *RSA_new(void)
33 {
34     return rsa_new_intern(NULL, NULL);
35 }
36
37 const RSA_METHOD *RSA_get_method(const RSA *rsa)
38 {
39     return rsa->meth;
40 }
41
42 int RSA_set_method(RSA *rsa, const RSA_METHOD *meth)
43 {
44     /*
45      * NB: The caller is specifically setting a method, so it's not up to us
46      * to deal with which ENGINE it comes from.
47      */
48     const RSA_METHOD *mtmp;
49     mtmp = rsa->meth;
50     if (mtmp->finish)
51         mtmp->finish(rsa);
52 #ifndef OPENSSL_NO_ENGINE
53     ENGINE_finish(rsa->engine);
54     rsa->engine = NULL;
55 #endif
56     rsa->meth = meth;
57     if (meth->init)
58         meth->init(rsa);
59     return 1;
60 }
61
62 RSA *RSA_new_method(ENGINE *engine)
63 {
64     return rsa_new_intern(engine, NULL);
65 }
66 #endif
67
68 RSA *ossl_rsa_new_with_ctx(OSSL_LIB_CTX *libctx)
69 {
70     return rsa_new_intern(NULL, libctx);
71 }
72
73 static RSA *rsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx)
74 {
75     RSA *ret = OPENSSL_zalloc(sizeof(*ret));
76
77     if (ret == NULL) {
78         ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
79         return NULL;
80     }
81
82     ret->references = 1;
83     ret->lock = CRYPTO_THREAD_lock_new();
84     if (ret->lock == NULL) {
85         ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
86         OPENSSL_free(ret);
87         return NULL;
88     }
89
90     ret->libctx = libctx;
91     ret->meth = RSA_get_default_method();
92 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
93     ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
94     if (engine) {
95         if (!ENGINE_init(engine)) {
96             ERR_raise(ERR_LIB_RSA, ERR_R_ENGINE_LIB);
97             goto err;
98         }
99         ret->engine = engine;
100     } else {
101         ret->engine = ENGINE_get_default_RSA();
102     }
103     if (ret->engine) {
104         ret->meth = ENGINE_get_RSA(ret->engine);
105         if (ret->meth == NULL) {
106             ERR_raise(ERR_LIB_RSA, ERR_R_ENGINE_LIB);
107             goto err;
108         }
109     }
110 #endif
111
112     ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
113 #ifndef FIPS_MODULE
114     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_RSA, ret, &ret->ex_data)) {
115         goto err;
116     }
117 #endif
118
119     if ((ret->meth->init != NULL) && !ret->meth->init(ret)) {
120         ERR_raise(ERR_LIB_RSA, ERR_R_INIT_FAIL);
121         goto err;
122     }
123
124     return ret;
125
126  err:
127     RSA_free(ret);
128     return NULL;
129 }
130
131 void RSA_free(RSA *r)
132 {
133     int i;
134
135     if (r == NULL)
136         return;
137
138     CRYPTO_DOWN_REF(&r->references, &i, r->lock);
139     REF_PRINT_COUNT("RSA", r);
140     if (i > 0)
141         return;
142     REF_ASSERT_ISNT(i < 0);
143
144     if (r->meth != NULL && r->meth->finish != NULL)
145         r->meth->finish(r);
146 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
147     ENGINE_finish(r->engine);
148 #endif
149
150 #ifndef FIPS_MODULE
151     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RSA, r, &r->ex_data);
152 #endif
153
154     CRYPTO_THREAD_lock_free(r->lock);
155
156     BN_free(r->n);
157     BN_free(r->e);
158     BN_clear_free(r->d);
159     BN_clear_free(r->p);
160     BN_clear_free(r->q);
161     BN_clear_free(r->dmp1);
162     BN_clear_free(r->dmq1);
163     BN_clear_free(r->iqmp);
164
165 #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS)
166     rsa_acvp_test_free(r->acvp_test);
167 #endif
168
169 #ifndef FIPS_MODULE
170     RSA_PSS_PARAMS_free(r->pss);
171     sk_RSA_PRIME_INFO_pop_free(r->prime_infos, rsa_multip_info_free);
172 #endif
173     BN_BLINDING_free(r->blinding);
174     BN_BLINDING_free(r->mt_blinding);
175     OPENSSL_free(r->bignum_data);
176     OPENSSL_free(r);
177 }
178
179 int RSA_up_ref(RSA *r)
180 {
181     int i;
182
183     if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0)
184         return 0;
185
186     REF_PRINT_COUNT("RSA", r);
187     REF_ASSERT_ISNT(i < 2);
188     return i > 1 ? 1 : 0;
189 }
190
191 OSSL_LIB_CTX *ossl_rsa_get0_libctx(RSA *r)
192 {
193     return r->libctx;
194 }
195
196 void ossl_rsa_set0_libctx(RSA *r, OSSL_LIB_CTX *libctx)
197 {
198     r->libctx = libctx;
199 }
200
201 #ifndef FIPS_MODULE
202 int RSA_set_ex_data(RSA *r, int idx, void *arg)
203 {
204     return CRYPTO_set_ex_data(&r->ex_data, idx, arg);
205 }
206
207 void *RSA_get_ex_data(const RSA *r, int idx)
208 {
209     return CRYPTO_get_ex_data(&r->ex_data, idx);
210 }
211 #endif
212
213 /*
214  * Define a scaling constant for our fixed point arithmetic.
215  * This value must be a power of two because the base two logarithm code
216  * makes this assumption.  The exponent must also be a multiple of three so
217  * that the scale factor has an exact cube root.  Finally, the scale factor
218  * should not be so large that a multiplication of two scaled numbers
219  * overflows a 64 bit unsigned integer.
220  */
221 static const unsigned int scale = 1 << 18;
222 static const unsigned int cbrt_scale = 1 << (2 * 18 / 3);
223
224 /* Define some constants, none exceed 32 bits */
225 static const unsigned int log_2  = 0x02c5c8;    /* scale * log(2) */
226 static const unsigned int log_e  = 0x05c551;    /* scale * log2(M_E) */
227 static const unsigned int c1_923 = 0x07b126;    /* scale * 1.923 */
228 static const unsigned int c4_690 = 0x12c28f;    /* scale * 4.690 */
229
230 /*
231  * Multiply two scaled integers together and rescale the result.
232  */
233 static ossl_inline uint64_t mul2(uint64_t a, uint64_t b)
234 {
235     return a * b / scale;
236 }
237
238 /*
239  * Calculate the cube root of a 64 bit scaled integer.
240  * Although the cube root of a 64 bit number does fit into a 32 bit unsigned
241  * integer, this is not guaranteed after scaling, so this function has a
242  * 64 bit return.  This uses the shifting nth root algorithm with some
243  * algebraic simplifications.
244  */
245 static uint64_t icbrt64(uint64_t x)
246 {
247     uint64_t r = 0;
248     uint64_t b;
249     int s;
250
251     for (s = 63; s >= 0; s -= 3) {
252         r <<= 1;
253         b = 3 * r * (r + 1) + 1;
254         if ((x >> s) >= b) {
255             x -= b << s;
256             r++;
257         }
258     }
259     return r * cbrt_scale;
260 }
261
262 /*
263  * Calculate the natural logarithm of a 64 bit scaled integer.
264  * This is done by calculating a base two logarithm and scaling.
265  * The maximum logarithm (base 2) is 64 and this reduces base e, so
266  * a 32 bit result should not overflow.  The argument passed must be
267  * greater than unity so we don't need to handle negative results.
268  */
269 static uint32_t ilog_e(uint64_t v)
270 {
271     uint32_t i, r = 0;
272
273     /*
274      * Scale down the value into the range 1 .. 2.
275      *
276      * If fractional numbers need to be processed, another loop needs
277      * to go here that checks v < scale and if so multiplies it by 2 and
278      * reduces r by scale.  This also means making r signed.
279      */
280     while (v >= 2 * scale) {
281         v >>= 1;
282         r += scale;
283     }
284     for (i = scale / 2; i != 0; i /= 2) {
285         v = mul2(v, v);
286         if (v >= 2 * scale) {
287             v >>= 1;
288             r += i;
289         }
290     }
291     r = (r * (uint64_t)scale) / log_e;
292     return r;
293 }
294
295 /*
296  * NIST SP 800-56B rev 2 Appendix D: Maximum Security Strength Estimates for IFC
297  * Modulus Lengths.
298  *
299  * Note that this formula is also referred to in SP800-56A rev3 Appendix D:
300  * for FFC safe prime groups for modp and ffdhe.
301  * After Table 25 and Table 26 it refers to
302  * "The maximum security strength estimates were calculated using the formula in
303  * Section 7.5 of the FIPS 140 IG and rounded to the nearest multiple of eight
304  * bits".
305  *
306  * The formula is:
307  *
308  * E = \frac{1.923 \sqrt[3]{nBits \cdot log_e(2)}
309  *           \cdot(log_e(nBits \cdot log_e(2))^{2/3} - 4.69}{log_e(2)}
310  * The two cube roots are merged together here.
311  */
312 uint16_t ossl_ifc_ffc_compute_security_bits(int n)
313 {
314     uint64_t x;
315     uint32_t lx;
316     uint16_t y;
317
318     /* Look for common values as listed in SP 800-56B rev 2 Appendix D */
319     switch (n) {
320     case 2048:
321         return 112;
322     case 3072:
323         return 128;
324     case 4096:
325         return 152;
326     case 6144:
327         return 176;
328     case 8192:
329         return 200;
330     }
331     /*
332      * The first incorrect result (i.e. not accurate or off by one low) occurs
333      * for n = 699668.  The true value here is 1200.  Instead of using this n
334      * as the check threshold, the smallest n such that the correct result is
335      * 1200 is used instead.
336      */
337     if (n >= 687737)
338         return 1200;
339     if (n < 8)
340         return 0;
341
342     x = n * (uint64_t)log_2;
343     lx = ilog_e(x);
344     y = (uint16_t)((mul2(c1_923, icbrt64(mul2(mul2(x, lx), lx))) - c4_690)
345                    / log_2);
346     return (y + 4) & ~7;
347 }
348
349
350
351 int RSA_security_bits(const RSA *rsa)
352 {
353     int bits = BN_num_bits(rsa->n);
354
355 #ifndef FIPS_MODULE
356     if (rsa->version == RSA_ASN1_VERSION_MULTI) {
357         /* This ought to mean that we have private key at hand. */
358         int ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos);
359
360         if (ex_primes <= 0 || (ex_primes + 2) > rsa_multip_cap(bits))
361             return 0;
362     }
363 #endif
364     return ossl_ifc_ffc_compute_security_bits(bits);
365 }
366
367 int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d)
368 {
369     /* If the fields n and e in r are NULL, the corresponding input
370      * parameters MUST be non-NULL for n and e.  d may be
371      * left NULL (in case only the public key is used).
372      */
373     if ((r->n == NULL && n == NULL)
374         || (r->e == NULL && e == NULL))
375         return 0;
376
377     if (n != NULL) {
378         BN_free(r->n);
379         r->n = n;
380     }
381     if (e != NULL) {
382         BN_free(r->e);
383         r->e = e;
384     }
385     if (d != NULL) {
386         BN_clear_free(r->d);
387         r->d = d;
388         BN_set_flags(r->d, BN_FLG_CONSTTIME);
389     }
390     r->dirty_cnt++;
391
392     return 1;
393 }
394
395 int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q)
396 {
397     /* If the fields p and q in r are NULL, the corresponding input
398      * parameters MUST be non-NULL.
399      */
400     if ((r->p == NULL && p == NULL)
401         || (r->q == NULL && q == NULL))
402         return 0;
403
404     if (p != NULL) {
405         BN_clear_free(r->p);
406         r->p = p;
407         BN_set_flags(r->p, BN_FLG_CONSTTIME);
408     }
409     if (q != NULL) {
410         BN_clear_free(r->q);
411         r->q = q;
412         BN_set_flags(r->q, BN_FLG_CONSTTIME);
413     }
414     r->dirty_cnt++;
415
416     return 1;
417 }
418
419 int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp)
420 {
421     /* If the fields dmp1, dmq1 and iqmp in r are NULL, the corresponding input
422      * parameters MUST be non-NULL.
423      */
424     if ((r->dmp1 == NULL && dmp1 == NULL)
425         || (r->dmq1 == NULL && dmq1 == NULL)
426         || (r->iqmp == NULL && iqmp == NULL))
427         return 0;
428
429     if (dmp1 != NULL) {
430         BN_clear_free(r->dmp1);
431         r->dmp1 = dmp1;
432         BN_set_flags(r->dmp1, BN_FLG_CONSTTIME);
433     }
434     if (dmq1 != NULL) {
435         BN_clear_free(r->dmq1);
436         r->dmq1 = dmq1;
437         BN_set_flags(r->dmq1, BN_FLG_CONSTTIME);
438     }
439     if (iqmp != NULL) {
440         BN_clear_free(r->iqmp);
441         r->iqmp = iqmp;
442         BN_set_flags(r->iqmp, BN_FLG_CONSTTIME);
443     }
444     r->dirty_cnt++;
445
446     return 1;
447 }
448
449 #ifndef FIPS_MODULE
450 /*
451  * Is it better to export RSA_PRIME_INFO structure
452  * and related functions to let user pass a triplet?
453  */
454 int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[],
455                                 BIGNUM *coeffs[], int pnum)
456 {
457     STACK_OF(RSA_PRIME_INFO) *prime_infos, *old = NULL;
458     RSA_PRIME_INFO *pinfo;
459     int i;
460
461     if (primes == NULL || exps == NULL || coeffs == NULL || pnum == 0)
462         return 0;
463
464     prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum);
465     if (prime_infos == NULL)
466         return 0;
467
468     if (r->prime_infos != NULL)
469         old = r->prime_infos;
470
471     for (i = 0; i < pnum; i++) {
472         pinfo = rsa_multip_info_new();
473         if (pinfo == NULL)
474             goto err;
475         if (primes[i] != NULL && exps[i] != NULL && coeffs[i] != NULL) {
476             BN_clear_free(pinfo->r);
477             BN_clear_free(pinfo->d);
478             BN_clear_free(pinfo->t);
479             pinfo->r = primes[i];
480             pinfo->d = exps[i];
481             pinfo->t = coeffs[i];
482             BN_set_flags(pinfo->r, BN_FLG_CONSTTIME);
483             BN_set_flags(pinfo->d, BN_FLG_CONSTTIME);
484             BN_set_flags(pinfo->t, BN_FLG_CONSTTIME);
485         } else {
486             rsa_multip_info_free(pinfo);
487             goto err;
488         }
489         (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
490     }
491
492     r->prime_infos = prime_infos;
493
494     if (!rsa_multip_calc_product(r)) {
495         r->prime_infos = old;
496         goto err;
497     }
498
499     if (old != NULL) {
500         /*
501          * This is hard to deal with, since the old infos could
502          * also be set by this function and r, d, t should not
503          * be freed in that case. So currently, stay consistent
504          * with other *set0* functions: just free it...
505          */
506         sk_RSA_PRIME_INFO_pop_free(old, rsa_multip_info_free);
507     }
508
509     r->version = RSA_ASN1_VERSION_MULTI;
510     r->dirty_cnt++;
511
512     return 1;
513  err:
514     /* r, d, t should not be freed */
515     sk_RSA_PRIME_INFO_pop_free(prime_infos, rsa_multip_info_free_ex);
516     return 0;
517 }
518 #endif
519
520 void RSA_get0_key(const RSA *r,
521                   const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
522 {
523     if (n != NULL)
524         *n = r->n;
525     if (e != NULL)
526         *e = r->e;
527     if (d != NULL)
528         *d = r->d;
529 }
530
531 void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q)
532 {
533     if (p != NULL)
534         *p = r->p;
535     if (q != NULL)
536         *q = r->q;
537 }
538
539 #ifndef FIPS_MODULE
540 int RSA_get_multi_prime_extra_count(const RSA *r)
541 {
542     int pnum;
543
544     pnum = sk_RSA_PRIME_INFO_num(r->prime_infos);
545     if (pnum <= 0)
546         pnum = 0;
547     return pnum;
548 }
549
550 int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[])
551 {
552     int pnum, i;
553     RSA_PRIME_INFO *pinfo;
554
555     if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0)
556         return 0;
557
558     /*
559      * return other primes
560      * it's caller's responsibility to allocate oth_primes[pnum]
561      */
562     for (i = 0; i < pnum; i++) {
563         pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
564         primes[i] = pinfo->r;
565     }
566
567     return 1;
568 }
569 #endif
570
571 void RSA_get0_crt_params(const RSA *r,
572                          const BIGNUM **dmp1, const BIGNUM **dmq1,
573                          const BIGNUM **iqmp)
574 {
575     if (dmp1 != NULL)
576         *dmp1 = r->dmp1;
577     if (dmq1 != NULL)
578         *dmq1 = r->dmq1;
579     if (iqmp != NULL)
580         *iqmp = r->iqmp;
581 }
582
583 #ifndef FIPS_MODULE
584 int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[],
585                                     const BIGNUM *coeffs[])
586 {
587     int pnum;
588
589     if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0)
590         return 0;
591
592     /* return other primes */
593     if (exps != NULL || coeffs != NULL) {
594         RSA_PRIME_INFO *pinfo;
595         int i;
596
597         /* it's the user's job to guarantee the buffer length */
598         for (i = 0; i < pnum; i++) {
599             pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
600             if (exps != NULL)
601                 exps[i] = pinfo->d;
602             if (coeffs != NULL)
603                 coeffs[i] = pinfo->t;
604         }
605     }
606
607     return 1;
608 }
609 #endif
610
611 const BIGNUM *RSA_get0_n(const RSA *r)
612 {
613     return r->n;
614 }
615
616 const BIGNUM *RSA_get0_e(const RSA *r)
617 {
618     return r->e;
619 }
620
621 const BIGNUM *RSA_get0_d(const RSA *r)
622 {
623     return r->d;
624 }
625
626 const BIGNUM *RSA_get0_p(const RSA *r)
627 {
628     return r->p;
629 }
630
631 const BIGNUM *RSA_get0_q(const RSA *r)
632 {
633     return r->q;
634 }
635
636 const BIGNUM *RSA_get0_dmp1(const RSA *r)
637 {
638     return r->dmp1;
639 }
640
641 const BIGNUM *RSA_get0_dmq1(const RSA *r)
642 {
643     return r->dmq1;
644 }
645
646 const BIGNUM *RSA_get0_iqmp(const RSA *r)
647 {
648     return r->iqmp;
649 }
650
651 const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *r)
652 {
653 #ifdef FIPS_MODULE
654     return NULL;
655 #else
656     return r->pss;
657 #endif
658 }
659
660 /* Internal */
661 RSA_PSS_PARAMS_30 *ossl_rsa_get0_pss_params_30(RSA *r)
662 {
663     return &r->pss_params;
664 }
665
666 void RSA_clear_flags(RSA *r, int flags)
667 {
668     r->flags &= ~flags;
669 }
670
671 int RSA_test_flags(const RSA *r, int flags)
672 {
673     return r->flags & flags;
674 }
675
676 void RSA_set_flags(RSA *r, int flags)
677 {
678     r->flags |= flags;
679 }
680
681 int RSA_get_version(RSA *r)
682 {
683     /* { two-prime(0), multi(1) } */
684     return r->version;
685 }
686
687 #ifndef FIPS_MODULE
688 ENGINE *RSA_get0_engine(const RSA *r)
689 {
690     return r->engine;
691 }
692
693 int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2)
694 {
695     /* If key type not RSA or RSA-PSS return error */
696     if (ctx != NULL && ctx->pmeth != NULL
697         && ctx->pmeth->pkey_id != EVP_PKEY_RSA
698         && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
699         return -1;
700      return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, p1, p2);
701 }
702 #endif
703
704 DEFINE_STACK_OF(BIGNUM)
705
706 int ossl_rsa_set0_all_params(RSA *r, const STACK_OF(BIGNUM) *primes,
707                              const STACK_OF(BIGNUM) *exps,
708                              const STACK_OF(BIGNUM) *coeffs)
709 {
710 #ifndef FIPS_MODULE
711     STACK_OF(RSA_PRIME_INFO) *prime_infos, *old_infos = NULL;
712 #endif
713     int pnum;
714
715     if (primes == NULL || exps == NULL || coeffs == NULL)
716         return 0;
717
718     pnum = sk_BIGNUM_num(primes);
719     if (pnum < 2
720         || pnum != sk_BIGNUM_num(exps)
721         || pnum != sk_BIGNUM_num(coeffs) + 1)
722         return 0;
723
724     if (!RSA_set0_factors(r, sk_BIGNUM_value(primes, 0),
725                           sk_BIGNUM_value(primes, 1))
726         || !RSA_set0_crt_params(r, sk_BIGNUM_value(exps, 0),
727                                 sk_BIGNUM_value(exps, 1),
728                                 sk_BIGNUM_value(coeffs, 0)))
729         return 0;
730
731 #ifndef FIPS_MODULE
732     old_infos = r->prime_infos;
733 #endif
734
735     if (pnum > 2) {
736 #ifndef FIPS_MODULE
737         int i;
738
739         prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum);
740         if (prime_infos == NULL)
741             return 0;
742
743         for (i = 2; i < pnum; i++) {
744             BIGNUM *prime = sk_BIGNUM_value(primes, i);
745             BIGNUM *exp = sk_BIGNUM_value(exps, i);
746             BIGNUM *coeff = sk_BIGNUM_value(coeffs, i - 1);
747             RSA_PRIME_INFO *pinfo = NULL;
748
749             if (!ossl_assert(prime != NULL && exp != NULL && coeff != NULL))
750                 goto err;
751
752             /* Using rsa_multip_info_new() is wasteful, so allocate directly */
753             if ((pinfo = OPENSSL_zalloc(sizeof(*pinfo))) == NULL) {
754                 ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
755                 goto err;
756             }
757
758             pinfo->r = prime;
759             pinfo->d = exp;
760             pinfo->t = coeff;
761             BN_set_flags(pinfo->r, BN_FLG_CONSTTIME);
762             BN_set_flags(pinfo->d, BN_FLG_CONSTTIME);
763             BN_set_flags(pinfo->t, BN_FLG_CONSTTIME);
764             (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
765         }
766
767         r->prime_infos = prime_infos;
768
769         if (!rsa_multip_calc_product(r)) {
770             r->prime_infos = old_infos;
771             goto err;
772         }
773 #else
774         return 0;
775 #endif
776     }
777
778 #ifndef FIPS_MODULE
779     if (old_infos != NULL) {
780         /*
781          * This is hard to deal with, since the old infos could
782          * also be set by this function and r, d, t should not
783          * be freed in that case. So currently, stay consistent
784          * with other *set0* functions: just free it...
785          */
786         sk_RSA_PRIME_INFO_pop_free(old_infos, rsa_multip_info_free);
787     }
788 #endif
789
790     r->version = pnum > 2 ? RSA_ASN1_VERSION_MULTI : RSA_ASN1_VERSION_DEFAULT;
791     r->dirty_cnt++;
792
793     return 1;
794 #ifndef FIPS_MODULE
795  err:
796     /* r, d, t should not be freed */
797     sk_RSA_PRIME_INFO_pop_free(prime_infos, rsa_multip_info_free_ex);
798     return 0;
799 #endif
800 }
801
802 DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM)
803
804 int ossl_rsa_get0_all_params(RSA *r, STACK_OF(BIGNUM_const) *primes,
805                              STACK_OF(BIGNUM_const) *exps,
806                              STACK_OF(BIGNUM_const) *coeffs)
807 {
808 #ifndef FIPS_MODULE
809     RSA_PRIME_INFO *pinfo;
810     int i, pnum;
811 #endif
812
813     if (r == NULL)
814         return 0;
815
816     /* If |p| is NULL, there are no CRT parameters */
817     if (RSA_get0_p(r) == NULL)
818         return 1;
819
820     sk_BIGNUM_const_push(primes, RSA_get0_p(r));
821     sk_BIGNUM_const_push(primes, RSA_get0_q(r));
822     sk_BIGNUM_const_push(exps, RSA_get0_dmp1(r));
823     sk_BIGNUM_const_push(exps, RSA_get0_dmq1(r));
824     sk_BIGNUM_const_push(coeffs, RSA_get0_iqmp(r));
825
826 #ifndef FIPS_MODULE
827     pnum = RSA_get_multi_prime_extra_count(r);
828     for (i = 0; i < pnum; i++) {
829         pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
830         sk_BIGNUM_const_push(primes, pinfo->r);
831         sk_BIGNUM_const_push(exps, pinfo->d);
832         sk_BIGNUM_const_push(coeffs, pinfo->t);
833     }
834 #endif
835
836     return 1;
837 }
838
839 #ifndef FIPS_MODULE
840 /* Helpers to set or get diverse hash algorithm names */
841 static int int_set_rsa_md_name(EVP_PKEY_CTX *ctx,
842                                /* For checks */
843                                int keytype, int optype,
844                                /* For EVP_PKEY_CTX_set_params() */
845                                const char *mdkey, const char *mdname,
846                                const char *propkey, const char *mdprops)
847 {
848     OSSL_PARAM params[3], *p = params;
849
850     if (ctx == NULL || mdname == NULL || (ctx->operation & optype) == 0) {
851         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
852         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
853         return -2;
854     }
855
856     /* If key type not RSA return error */
857     switch (keytype) {
858     case -1:
859         if (!EVP_PKEY_CTX_is_a(ctx, "RSA")
860             && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS"))
861             return -1;
862         break;
863     default:
864         if (!EVP_PKEY_CTX_is_a(ctx, evp_pkey_type2name(keytype)))
865             return -1;
866         break;
867     }
868
869     /* Cast away the const. This is read only so should be safe */
870     *p++ = OSSL_PARAM_construct_utf8_string(mdkey, (char *)mdname, 0);
871     if (evp_pkey_ctx_is_provided(ctx) && mdprops != NULL) {
872         /* Cast away the const. This is read only so should be safe */
873         *p++ = OSSL_PARAM_construct_utf8_string(propkey, (char *)mdprops, 0);
874     }
875     *p++ = OSSL_PARAM_construct_end();
876
877     return evp_pkey_ctx_set_params_strict(ctx, params);
878 }
879
880 /* Helpers to set or get diverse hash algorithm names */
881 static int int_get_rsa_md_name(EVP_PKEY_CTX *ctx,
882                                /* For checks */
883                                int keytype, int optype,
884                                /* For EVP_PKEY_CTX_get_params() */
885                                const char *mdkey,
886                                char *mdname, size_t mdnamesize)
887 {
888     OSSL_PARAM params[2], *p = params;
889
890     if (ctx == NULL || mdname == NULL || (ctx->operation & optype) == 0) {
891         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
892         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
893         return -2;
894     }
895
896     /* If key type not RSA return error */
897     switch (keytype) {
898     case -1:
899         if (!EVP_PKEY_CTX_is_a(ctx, "RSA")
900             && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS"))
901             return -1;
902         break;
903     default:
904         if (!EVP_PKEY_CTX_is_a(ctx, evp_pkey_type2name(keytype)))
905             return -1;
906         break;
907     }
908
909     /* Cast away the const. This is read only so should be safe */
910     *p++ = OSSL_PARAM_construct_utf8_string(mdkey, (char *)mdname, mdnamesize);
911     *p++ = OSSL_PARAM_construct_end();
912
913     return evp_pkey_ctx_get_params_strict(ctx, params);
914 }
915
916 /*
917  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
918  * simply because that's easier.
919  * TODO(3.0) Should this be deprecated?
920  */
921 int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int pad_mode)
922 {
923     return RSA_pkey_ctx_ctrl(ctx, -1, EVP_PKEY_CTRL_RSA_PADDING,
924                              pad_mode, NULL);
925 }
926
927 /*
928  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
929  * simply because that's easier.
930  * TODO(3.0) Should this be deprecated?
931  */
932 int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, int *pad_mode)
933 {
934     return RSA_pkey_ctx_ctrl(ctx, -1, EVP_PKEY_CTRL_GET_RSA_PADDING,
935                              0, pad_mode);
936 }
937
938 /*
939  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
940  * simply because that's easier.
941  * TODO(3.0) Should this be deprecated in favor of passing a name?
942  */
943 int EVP_PKEY_CTX_set_rsa_pss_keygen_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
944 {
945     return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
946                              EVP_PKEY_CTRL_MD, 0, (void *)(md));
947 }
948
949 int EVP_PKEY_CTX_set_rsa_pss_keygen_md_name(EVP_PKEY_CTX *ctx,
950                                             const char *mdname,
951                                             const char *mdprops)
952 {
953     return int_set_rsa_md_name(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
954                                OSSL_PKEY_PARAM_RSA_DIGEST, mdname,
955                                OSSL_PKEY_PARAM_RSA_DIGEST_PROPS, mdprops);
956 }
957
958 /*
959  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
960  * simply because that's easier.
961  * TODO(3.0) Should this be deprecated in favor of passing a name?
962  */
963 int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
964 {
965     return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
966                              EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)(md));
967 }
968
969 int EVP_PKEY_CTX_set_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, const char *mdname,
970                                       const char *mdprops)
971 {
972     return
973         int_set_rsa_md_name(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
974                             OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, mdname,
975                             OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS, mdprops);
976 }
977
978 int EVP_PKEY_CTX_get_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, char *name,
979                                       size_t namesize)
980 {
981     return int_get_rsa_md_name(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
982                                OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,
983                                name, namesize);
984 }
985
986 /*
987  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
988  * simply because that's easier.
989  * TODO(3.0) Should this be deprecated in favor of getting a name?
990  */
991 int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **md)
992 {
993     return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
994                              EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void *)md);
995 }
996
997 /*
998  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
999  * simply because that's easier.
1000  * TODO(3.0) Should this be deprecated in favor of passing a name?
1001  */
1002 int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
1003 {
1004     return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT,
1005                              EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)(md));
1006 }
1007
1008 int EVP_PKEY_CTX_set_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, const char *mdname,
1009                                       const char *mdprops)
1010 {
1011     return int_set_rsa_md_name(ctx, -1,
1012                                EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG,
1013                                OSSL_PKEY_PARAM_MGF1_DIGEST, mdname,
1014                                OSSL_PKEY_PARAM_MGF1_PROPERTIES, mdprops);
1015 }
1016
1017 int EVP_PKEY_CTX_get_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, char *name,
1018                                       size_t namesize)
1019 {
1020     return int_get_rsa_md_name(ctx, -1,
1021                                EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG,
1022                                OSSL_PKEY_PARAM_MGF1_DIGEST, name, namesize);
1023 }
1024
1025 /*
1026  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
1027  * simply because that's easier.
1028  * TODO(3.0) Should this be deprecated in favor of passing a name?
1029  */
1030 int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
1031 {
1032     return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
1033                              EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)(md));
1034 }
1035
1036 int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md_name(EVP_PKEY_CTX *ctx,
1037                                                  const char *mdname)
1038 {
1039     return int_set_rsa_md_name(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
1040                                OSSL_PKEY_PARAM_MGF1_DIGEST, mdname,
1041                                NULL, NULL);
1042 }
1043
1044 /*
1045  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
1046  * simply because that's easier.
1047  * TODO(3.0) Should this be deprecated in favor of getting a name?
1048  */
1049 int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD **md)
1050 {
1051     return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT,
1052                              EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)(md));
1053 }
1054
1055 int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, void *label, int llen)
1056 {
1057     OSSL_PARAM rsa_params[2], *p = rsa_params;
1058
1059     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
1060         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1061         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1062         return -2;
1063     }
1064
1065     /* If key type not RSA return error */
1066     if (!EVP_PKEY_CTX_is_a(ctx, "RSA"))
1067         return -1;
1068
1069     /* Cast away the const. This is read only so should be safe */
1070     *p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL,
1071                                              (void *)label, (size_t)llen);
1072     *p++ = OSSL_PARAM_construct_end();
1073
1074     if (!evp_pkey_ctx_set_params_strict(ctx, rsa_params))
1075         return 0;
1076
1077     /* Ownership is supposed to be transfered to the callee. */
1078     OPENSSL_free(label);
1079     return 1;
1080 }
1081
1082 int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, unsigned char **label)
1083 {
1084     OSSL_PARAM rsa_params[2], *p = rsa_params;
1085     size_t labellen;
1086
1087     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
1088         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1089         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1090         return -2;
1091     }
1092
1093     /* If key type not RSA return error */
1094     if (!EVP_PKEY_CTX_is_a(ctx, "RSA"))
1095         return -1;
1096
1097     *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL,
1098                                           (void **)label, 0);
1099     *p++ = OSSL_PARAM_construct_end();
1100
1101     if (!EVP_PKEY_CTX_get_params(ctx, rsa_params))
1102         return -1;
1103
1104     labellen = rsa_params[0].return_size;
1105     if (labellen > INT_MAX)
1106         return -1;
1107
1108     return (int)labellen;
1109 }
1110
1111 /*
1112  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
1113  * simply because that's easier.
1114  */
1115 int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int saltlen)
1116 {
1117     /*
1118      * For some reason, the optype was set to this:
1119      *
1120      * EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY
1121      *
1122      * However, we do use RSA-PSS with the whole gamut of diverse signature
1123      * and verification operations, so the optype gets upgraded to this:
1124      *
1125      * EVP_PKEY_OP_TYPE_SIG
1126      */
1127     return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG,
1128                              EVP_PKEY_CTRL_RSA_PSS_SALTLEN, saltlen, NULL);
1129 }
1130
1131 /*
1132  * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper,
1133  * simply because that's easier.
1134  */
1135 int EVP_PKEY_CTX_get_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int *saltlen)
1136 {
1137     /*
1138      * Because of circumstances, the optype is updated from:
1139      *
1140      * EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY
1141      *
1142      * to:
1143      *
1144      * EVP_PKEY_OP_TYPE_SIG
1145      */
1146     return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG,
1147                              EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, 0, saltlen);
1148 }
1149
1150 int EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(EVP_PKEY_CTX *ctx, int saltlen)
1151 {
1152     OSSL_PARAM pad_params[2], *p = pad_params;
1153
1154     if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) {
1155         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1156         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1157         return -2;
1158     }
1159
1160     if (!EVP_PKEY_CTX_is_a(ctx, "RSA-PSS"))
1161         return -1;
1162
1163     *p++ = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_PSS_SALTLEN,
1164                                     &saltlen);
1165     *p++ = OSSL_PARAM_construct_end();
1166
1167     return evp_pkey_ctx_set_params_strict(ctx, pad_params);
1168 }
1169
1170 int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int bits)
1171 {
1172     OSSL_PARAM params[2], *p = params;
1173     size_t bits2 = bits;
1174
1175     if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) {
1176         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1177         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1178         return -2;
1179     }
1180
1181     /* If key type not RSA return error */
1182     if (!EVP_PKEY_CTX_is_a(ctx, "RSA")
1183         && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS"))
1184         return -1;
1185
1186     *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_RSA_BITS, &bits2);
1187     *p++ = OSSL_PARAM_construct_end();
1188
1189     return evp_pkey_ctx_set_params_strict(ctx, params);
1190 }
1191
1192 int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp)
1193 {
1194     int ret = RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_KEYGEN,
1195                                 EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, pubexp);
1196
1197     /*
1198      * Satisfy memory semantics for pre-3.0 callers of
1199      * EVP_PKEY_CTX_set_rsa_keygen_pubexp(): their expectation is that input
1200      * pubexp BIGNUM becomes managed by the EVP_PKEY_CTX on success.
1201      */
1202     if (ret > 0 && evp_pkey_ctx_is_provided(ctx)) {
1203         BN_free(ctx->rsa_pubexp);
1204         ctx->rsa_pubexp = pubexp;
1205     }
1206
1207     return ret;
1208 }
1209
1210 int EVP_PKEY_CTX_set1_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp)
1211 {
1212     int ret = 0;
1213
1214     /*
1215      * When we're dealing with a provider, there's no need to duplicate
1216      * pubexp, as it gets copied when transforming to an OSSL_PARAM anyway.
1217      */
1218     if (evp_pkey_ctx_is_legacy(ctx))
1219         pubexp = BN_dup(pubexp);
1220     ret = EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN,
1221                             EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, pubexp);
1222     if (evp_pkey_ctx_is_legacy(ctx) && ret <= 0)
1223         BN_free(pubexp);
1224     return ret;
1225 }
1226
1227 int EVP_PKEY_CTX_set_rsa_keygen_primes(EVP_PKEY_CTX *ctx, int primes)
1228 {
1229     OSSL_PARAM params[2], *p = params;
1230     size_t primes2 = primes;
1231
1232     if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) {
1233         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1234         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1235         return -2;
1236     }
1237
1238     /* If key type not RSA return error */
1239     if (!EVP_PKEY_CTX_is_a(ctx, "RSA")
1240         && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS"))
1241         return -1;
1242
1243     *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_RSA_PRIMES, &primes2);
1244     *p++ = OSSL_PARAM_construct_end();
1245
1246     return evp_pkey_ctx_set_params_strict(ctx, params);
1247 }
1248 #endif