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