Fix comment typo
[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 "internal/cryptlib.h"
13 #include "internal/refcount.h"
14 #include "internal/bn_int.h"
15 #include <openssl/engine.h>
16 #include <openssl/evp.h>
17 #include "internal/evp_int.h"
18 #include "rsa_locl.h"
19
20 RSA *RSA_new(void)
21 {
22     return RSA_new_method(NULL);
23 }
24
25 const RSA_METHOD *RSA_get_method(const RSA *rsa)
26 {
27     return rsa->meth;
28 }
29
30 int RSA_set_method(RSA *rsa, const RSA_METHOD *meth)
31 {
32     /*
33      * NB: The caller is specifically setting a method, so it's not up to us
34      * to deal with which ENGINE it comes from.
35      */
36     const RSA_METHOD *mtmp;
37     mtmp = rsa->meth;
38     if (mtmp->finish)
39         mtmp->finish(rsa);
40 #ifndef OPENSSL_NO_ENGINE
41     ENGINE_finish(rsa->engine);
42     rsa->engine = NULL;
43 #endif
44     rsa->meth = meth;
45     if (meth->init)
46         meth->init(rsa);
47     return 1;
48 }
49
50 RSA *RSA_new_method(ENGINE *engine)
51 {
52     RSA *ret = OPENSSL_zalloc(sizeof(*ret));
53
54     if (ret == NULL) {
55         RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_MALLOC_FAILURE);
56         return NULL;
57     }
58
59     ret->references = 1;
60     ret->lock = CRYPTO_THREAD_lock_new();
61     if (ret->lock == NULL) {
62         RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_MALLOC_FAILURE);
63         OPENSSL_free(ret);
64         return NULL;
65     }
66
67     ret->meth = RSA_get_default_method();
68 #ifndef OPENSSL_NO_ENGINE
69     ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
70     if (engine) {
71         if (!ENGINE_init(engine)) {
72             RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_ENGINE_LIB);
73             goto err;
74         }
75         ret->engine = engine;
76     } else {
77         ret->engine = ENGINE_get_default_RSA();
78     }
79     if (ret->engine) {
80         ret->meth = ENGINE_get_RSA(ret->engine);
81         if (ret->meth == NULL) {
82             RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_ENGINE_LIB);
83             goto err;
84         }
85     }
86 #endif
87
88     ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
89     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_RSA, ret, &ret->ex_data)) {
90         goto err;
91     }
92
93     if ((ret->meth->init != NULL) && !ret->meth->init(ret)) {
94         RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_INIT_FAIL);
95         goto err;
96     }
97
98     return ret;
99
100  err:
101     RSA_free(ret);
102     return NULL;
103 }
104
105 void RSA_free(RSA *r)
106 {
107     int i;
108
109     if (r == NULL)
110         return;
111
112     CRYPTO_DOWN_REF(&r->references, &i, r->lock);
113     REF_PRINT_COUNT("RSA", r);
114     if (i > 0)
115         return;
116     REF_ASSERT_ISNT(i < 0);
117
118     if (r->meth != NULL && r->meth->finish != NULL)
119         r->meth->finish(r);
120 #ifndef OPENSSL_NO_ENGINE
121     ENGINE_finish(r->engine);
122 #endif
123
124     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RSA, r, &r->ex_data);
125
126     CRYPTO_THREAD_lock_free(r->lock);
127
128     BN_free(r->n);
129     BN_free(r->e);
130     BN_clear_free(r->d);
131     BN_clear_free(r->p);
132     BN_clear_free(r->q);
133     BN_clear_free(r->dmp1);
134     BN_clear_free(r->dmq1);
135     BN_clear_free(r->iqmp);
136     RSA_PSS_PARAMS_free(r->pss);
137     sk_RSA_PRIME_INFO_pop_free(r->prime_infos, rsa_multip_info_free);
138     BN_BLINDING_free(r->blinding);
139     BN_BLINDING_free(r->mt_blinding);
140     OPENSSL_free(r->bignum_data);
141     OPENSSL_free(r);
142 }
143
144 int RSA_up_ref(RSA *r)
145 {
146     int i;
147
148     if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0)
149         return 0;
150
151     REF_PRINT_COUNT("RSA", r);
152     REF_ASSERT_ISNT(i < 2);
153     return i > 1 ? 1 : 0;
154 }
155
156 int RSA_set_ex_data(RSA *r, int idx, void *arg)
157 {
158     return CRYPTO_set_ex_data(&r->ex_data, idx, arg);
159 }
160
161 void *RSA_get_ex_data(const RSA *r, int idx)
162 {
163     return CRYPTO_get_ex_data(&r->ex_data, idx);
164 }
165
166 /*
167  * Define a scaling constant for our fixed point arithmetic.
168  * This value must be a power of two because the base two logarithm code
169  * makes this assumption.  The exponent must also be a multiple of three so
170  * that the scale factor has an exact cube root.  Finally, the scale factor
171  * should not be so large that a multiplication of two scaled numbers
172  * overflows a 64 bit unsigned integer.
173  */
174 static const unsigned int scale = 1 << 18;
175 static const unsigned int cbrt_scale = 1 << (2 * 18 / 3);
176
177 /* Define some constants, none exceed 32 bits */
178 static const unsigned int log_2  = 0x02c5c8;    /* scale * log(2) */
179 static const unsigned int log_e  = 0x05c551;    /* scale * log2(M_E) */
180 static const unsigned int c1_923 = 0x07b126;    /* scale * 1.923 */
181 static const unsigned int c4_690 = 0x12c28f;    /* scale * 4.690 */
182
183 /*
184  * Multiply two scaled integers together and rescale the result.
185  */
186 static ossl_inline uint64_t mul2(uint64_t a, uint64_t b)
187 {
188     return a * b / scale;
189 }
190
191 /*
192  * Calculate the cube root of a 64 bit scaled integer.
193  * Although the cube root of a 64 bit number does fit into a 32 bit unsigned
194  * integer, this is not guaranteed after scaling, so this function has a
195  * 64 bit return.  This uses the shifting nth root algorithm with some
196  * algebraic simplifications.
197  */
198 static uint64_t icbrt64(uint64_t x)
199 {
200     uint64_t r = 0;
201     uint64_t b;
202     int s;
203
204     for (s = 63; s >= 0; s -= 3) {
205         r <<= 1;
206         b = 3 * r * (r + 1) + 1;
207         if ((x >> s) >= b) {
208             x -= b << s;
209             r++;
210         }
211     }
212     return r * cbrt_scale;
213 }
214
215 /*
216  * Calculate the natural logarithm of a 64 bit scaled integer.
217  * This is done by calculating a base two logarithm and scaling.
218  * The maximum logarithm (base 2) is 64 and this reduces base e, so
219  * a 32 bit result should not overflow.  The argument passed must be
220  * greater than unity so we don't need to handle negative results.
221  */
222 static uint32_t ilog_e(uint64_t v)
223 {
224     uint32_t i, r = 0;
225
226     /*
227      * Scale down the value into the range 1 .. 2.
228      *
229      * If fractional numbers need to be processed, another loop needs
230      * to go here that checks v < scale and if so multiplies it by 2 and
231      * reduces r by scale.  This also means making r signed.
232      */
233     while (v >= 2 * scale) {
234         v >>= 1;
235         r += scale;
236     }
237     for (i = scale / 2; i != 0; i /= 2) {
238         v = mul2(v, v);
239         if (v >= 2 * scale) {
240             v >>= 1;
241             r += i;
242         }
243     }
244     r = (r * (uint64_t)scale) / log_e;
245     return r;
246 }
247
248 /*
249  * NIST SP 800-56B rev 2 Appendix D: Maximum Security Strength Estimates for IFC
250  * Modulus Lengths.
251  *
252  * E = \frac{1.923 \sqrt[3]{nBits \cdot log_e(2)}
253  *           \cdot(log_e(nBits \cdot log_e(2))^{2/3} - 4.69}{log_e(2)}
254  * The two cube roots are merged together here.
255  */
256 static uint16_t rsa_compute_security_bits(int n)
257 {
258     uint64_t x;
259     uint32_t lx;
260     uint16_t y;
261
262     /* Look for common values as listed in SP 800-56B rev 2 Appendix D */
263     switch (n) {
264     case 2048:
265         return 112;
266     case 3072:
267         return 128;
268     case 4096:
269         return 152;
270     case 6144:
271         return 176;
272     case 8192:
273         return 200;
274     }
275     /*
276      * The first incorrect result (i.e. not accurate or off by one low) occurs
277      * for n = 699668.  The true value here is 1200.  Instead of using this n
278      * as the check threshold, the smallest n such that the correct result is
279      * 1200 is used instead.
280      */
281     if (n >= 687737)
282         return 1200;
283     if (n < 8)
284         return 0;
285
286     x = n * (uint64_t)log_2;
287     lx = ilog_e(x);
288     y = (uint16_t)((mul2(c1_923, icbrt64(mul2(mul2(x, lx), lx))) - c4_690)
289                    / log_2);
290     return (y + 4) & ~7;
291 }
292
293 int RSA_security_bits(const RSA *rsa)
294 {
295     int bits = BN_num_bits(rsa->n);
296
297     if (rsa->version == RSA_ASN1_VERSION_MULTI) {
298         /* This ought to mean that we have private key at hand. */
299         int ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos);
300
301         if (ex_primes <= 0 || (ex_primes + 2) > rsa_multip_cap(bits))
302             return 0;
303     }
304     return rsa_compute_security_bits(bits);
305 }
306
307 int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d)
308 {
309     /* If the fields n and e in r are NULL, the corresponding input
310      * parameters MUST be non-NULL for n and e.  d may be
311      * left NULL (in case only the public key is used).
312      */
313     if ((r->n == NULL && n == NULL)
314         || (r->e == NULL && e == NULL))
315         return 0;
316
317     if (n != NULL) {
318         BN_free(r->n);
319         r->n = n;
320     }
321     if (e != NULL) {
322         BN_free(r->e);
323         r->e = e;
324     }
325     if (d != NULL) {
326         BN_clear_free(r->d);
327         r->d = d;
328     }
329
330     return 1;
331 }
332
333 int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q)
334 {
335     /* If the fields p and q in r are NULL, the corresponding input
336      * parameters MUST be non-NULL.
337      */
338     if ((r->p == NULL && p == NULL)
339         || (r->q == NULL && q == NULL))
340         return 0;
341
342     if (p != NULL) {
343         BN_clear_free(r->p);
344         r->p = p;
345     }
346     if (q != NULL) {
347         BN_clear_free(r->q);
348         r->q = q;
349     }
350
351     return 1;
352 }
353
354 int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp)
355 {
356     /* If the fields dmp1, dmq1 and iqmp in r are NULL, the corresponding input
357      * parameters MUST be non-NULL.
358      */
359     if ((r->dmp1 == NULL && dmp1 == NULL)
360         || (r->dmq1 == NULL && dmq1 == NULL)
361         || (r->iqmp == NULL && iqmp == NULL))
362         return 0;
363
364     if (dmp1 != NULL) {
365         BN_clear_free(r->dmp1);
366         r->dmp1 = dmp1;
367     }
368     if (dmq1 != NULL) {
369         BN_clear_free(r->dmq1);
370         r->dmq1 = dmq1;
371     }
372     if (iqmp != NULL) {
373         BN_clear_free(r->iqmp);
374         r->iqmp = iqmp;
375     }
376
377     return 1;
378 }
379
380 /*
381  * Is it better to export RSA_PRIME_INFO structure
382  * and related functions to let user pass a triplet?
383  */
384 int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[],
385                                 BIGNUM *coeffs[], int pnum)
386 {
387     STACK_OF(RSA_PRIME_INFO) *prime_infos, *old = NULL;
388     RSA_PRIME_INFO *pinfo;
389     int i;
390
391     if (primes == NULL || exps == NULL || coeffs == NULL || pnum == 0)
392         return 0;
393
394     prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum);
395     if (prime_infos == NULL)
396         return 0;
397
398     if (r->prime_infos != NULL)
399         old = r->prime_infos;
400
401     for (i = 0; i < pnum; i++) {
402         pinfo = rsa_multip_info_new();
403         if (pinfo == NULL)
404             goto err;
405         if (primes[i] != NULL && exps[i] != NULL && coeffs[i] != NULL) {
406             BN_free(pinfo->r);
407             BN_free(pinfo->d);
408             BN_free(pinfo->t);
409             pinfo->r = primes[i];
410             pinfo->d = exps[i];
411             pinfo->t = coeffs[i];
412         } else {
413             rsa_multip_info_free(pinfo);
414             goto err;
415         }
416         (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
417     }
418
419     r->prime_infos = prime_infos;
420
421     if (!rsa_multip_calc_product(r)) {
422         r->prime_infos = old;
423         goto err;
424     }
425
426     if (old != NULL) {
427         /*
428          * This is hard to deal with, since the old infos could
429          * also be set by this function and r, d, t should not
430          * be freed in that case. So currently, stay consistent
431          * with other *set0* functions: just free it...
432          */
433         sk_RSA_PRIME_INFO_pop_free(old, rsa_multip_info_free);
434     }
435
436     r->version = RSA_ASN1_VERSION_MULTI;
437
438     return 1;
439  err:
440     /* r, d, t should not be freed */
441     sk_RSA_PRIME_INFO_pop_free(prime_infos, rsa_multip_info_free_ex);
442     return 0;
443 }
444
445 void RSA_get0_key(const RSA *r,
446                   const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
447 {
448     if (n != NULL)
449         *n = r->n;
450     if (e != NULL)
451         *e = r->e;
452     if (d != NULL)
453         *d = r->d;
454 }
455
456 void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q)
457 {
458     if (p != NULL)
459         *p = r->p;
460     if (q != NULL)
461         *q = r->q;
462 }
463
464 int RSA_get_multi_prime_extra_count(const RSA *r)
465 {
466     int pnum;
467
468     pnum = sk_RSA_PRIME_INFO_num(r->prime_infos);
469     if (pnum <= 0)
470         pnum = 0;
471     return pnum;
472 }
473
474 int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[])
475 {
476     int pnum, i;
477     RSA_PRIME_INFO *pinfo;
478
479     if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0)
480         return 0;
481
482     /*
483      * return other primes
484      * it's caller's responsibility to allocate oth_primes[pnum]
485      */
486     for (i = 0; i < pnum; i++) {
487         pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
488         primes[i] = pinfo->r;
489     }
490
491     return 1;
492 }
493
494 void RSA_get0_crt_params(const RSA *r,
495                          const BIGNUM **dmp1, const BIGNUM **dmq1,
496                          const BIGNUM **iqmp)
497 {
498     if (dmp1 != NULL)
499         *dmp1 = r->dmp1;
500     if (dmq1 != NULL)
501         *dmq1 = r->dmq1;
502     if (iqmp != NULL)
503         *iqmp = r->iqmp;
504 }
505
506 int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[],
507                                     const BIGNUM *coeffs[])
508 {
509     int pnum;
510
511     if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0)
512         return 0;
513
514     /* return other primes */
515     if (exps != NULL || coeffs != NULL) {
516         RSA_PRIME_INFO *pinfo;
517         int i;
518
519         /* it's the user's job to guarantee the buffer length */
520         for (i = 0; i < pnum; i++) {
521             pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
522             if (exps != NULL)
523                 exps[i] = pinfo->d;
524             if (coeffs != NULL)
525                 coeffs[i] = pinfo->t;
526         }
527     }
528
529     return 1;
530 }
531
532 const BIGNUM *RSA_get0_n(const RSA *r)
533 {
534     return r->n;
535 }
536
537 const BIGNUM *RSA_get0_e(const RSA *r)
538 {
539     return r->e;
540 }
541
542 const BIGNUM *RSA_get0_d(const RSA *r)
543 {
544     return r->d;
545 }
546
547 const BIGNUM *RSA_get0_p(const RSA *r)
548 {
549     return r->p;
550 }
551
552 const BIGNUM *RSA_get0_q(const RSA *r)
553 {
554     return r->q;
555 }
556
557 const BIGNUM *RSA_get0_dmp1(const RSA *r)
558 {
559     return r->dmp1;
560 }
561
562 const BIGNUM *RSA_get0_dmq1(const RSA *r)
563 {
564     return r->dmq1;
565 }
566
567 const BIGNUM *RSA_get0_iqmp(const RSA *r)
568 {
569     return r->iqmp;
570 }
571
572 void RSA_clear_flags(RSA *r, int flags)
573 {
574     r->flags &= ~flags;
575 }
576
577 int RSA_test_flags(const RSA *r, int flags)
578 {
579     return r->flags & flags;
580 }
581
582 void RSA_set_flags(RSA *r, int flags)
583 {
584     r->flags |= flags;
585 }
586
587 int RSA_get_version(RSA *r)
588 {
589     /* { two-prime(0), multi(1) } */
590     return r->version;
591 }
592
593 ENGINE *RSA_get0_engine(const RSA *r)
594 {
595     return r->engine;
596 }
597
598 int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2)
599 {
600     /* If key type not RSA or RSA-PSS return error */
601     if (ctx != NULL && ctx->pmeth != NULL
602         && ctx->pmeth->pkey_id != EVP_PKEY_RSA
603         && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
604         return -1;
605      return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, p1, p2);
606 }