Copyright year updates
[openssl.git] / crypto / rsa / rsa_gen.c
1 /*
2  * Copyright 1995-2023 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  * NB: these functions have been "upgraded", the deprecated versions (which
12  * are compatibility wrappers using these functions) are in rsa_depr.c. -
13  * Geoff
14  */
15
16 /*
17  * RSA low level APIs are deprecated for public use, but still ok for
18  * internal use.
19  */
20 #include "internal/deprecated.h"
21
22 #include <stdio.h>
23 #include <time.h>
24 #include "internal/cryptlib.h"
25 #include <openssl/bn.h>
26 #include <openssl/self_test.h>
27 #include "prov/providercommon.h"
28 #include "rsa_local.h"
29
30 static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg);
31 static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
32                       BIGNUM *e_value, BN_GENCB *cb, int pairwise_test);
33
34 /*
35  * NB: this wrapper would normally be placed in rsa_lib.c and the static
36  * implementation would probably be in rsa_eay.c. Nonetheless, is kept here
37  * so that we don't introduce a new linker dependency. Eg. any application
38  * that wasn't previously linking object code related to key-generation won't
39  * have to now just because key-generation is part of RSA_METHOD.
40  */
41 int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
42 {
43     if (rsa->meth->rsa_keygen != NULL)
44         return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
45
46     return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
47                                         e_value, cb);
48 }
49
50 int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
51                                  BIGNUM *e_value, BN_GENCB *cb)
52 {
53 #ifndef FIPS_MODULE
54     /* multi-prime is only supported with the builtin key generation */
55     if (rsa->meth->rsa_multi_prime_keygen != NULL) {
56         return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
57                                                  e_value, cb);
58     } else if (rsa->meth->rsa_keygen != NULL) {
59         /*
60          * However, if rsa->meth implements only rsa_keygen, then we
61          * have to honour it in 2-prime case and assume that it wouldn't
62          * know what to do with multi-prime key generated by builtin
63          * subroutine...
64          */
65         if (primes == 2)
66             return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
67         else
68             return 0;
69     }
70 #endif /* FIPS_MODULE */
71     return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0);
72 }
73
74 #ifndef FIPS_MODULE
75 static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
76                                  BIGNUM *e_value, BN_GENCB *cb)
77 {
78     BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime;
79     int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
80     int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
81     RSA_PRIME_INFO *pinfo = NULL;
82     STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
83     BN_CTX *ctx = NULL;
84     BN_ULONG bitst = 0;
85     unsigned long error = 0;
86     int ok = -1;
87
88     if (bits < RSA_MIN_MODULUS_BITS) {
89         ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
90         return 0;
91     }
92     if (e_value == NULL) {
93         ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE);
94         return 0;
95     }
96     /* A bad value for e can cause infinite loops */
97     if (!ossl_rsa_check_public_exponent(e_value)) {
98         ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
99         return 0;
100     }
101
102     if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
103         ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
104         return 0;
105     }
106
107     ctx = BN_CTX_new_ex(rsa->libctx);
108     if (ctx == NULL)
109         goto err;
110     BN_CTX_start(ctx);
111     r0 = BN_CTX_get(ctx);
112     r1 = BN_CTX_get(ctx);
113     r2 = BN_CTX_get(ctx);
114     if (r2 == NULL)
115         goto err;
116
117     /* divide bits into 'primes' pieces evenly */
118     quo = bits / primes;
119     rmd = bits % primes;
120
121     for (i = 0; i < primes; i++)
122         bitsr[i] = (i < rmd) ? quo + 1 : quo;
123
124     rsa->dirty_cnt++;
125
126     /* We need the RSA components non-NULL */
127     if (!rsa->n && ((rsa->n = BN_new()) == NULL))
128         goto err;
129     if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
130         goto err;
131     BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
132     if (!rsa->e && ((rsa->e = BN_new()) == NULL))
133         goto err;
134     if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
135         goto err;
136     BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
137     if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
138         goto err;
139     BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
140     if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
141         goto err;
142     BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
143     if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
144         goto err;
145     BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
146     if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
147         goto err;
148     BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
149
150     /* initialize multi-prime components */
151     if (primes > RSA_DEFAULT_PRIME_NUM) {
152         rsa->version = RSA_ASN1_VERSION_MULTI;
153         prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
154         if (prime_infos == NULL)
155             goto err;
156         if (rsa->prime_infos != NULL) {
157             /* could this happen? */
158             sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
159                                        ossl_rsa_multip_info_free);
160         }
161         rsa->prime_infos = prime_infos;
162
163         /* prime_info from 2 to |primes| -1 */
164         for (i = 2; i < primes; i++) {
165             pinfo = ossl_rsa_multip_info_new();
166             if (pinfo == NULL)
167                 goto err;
168             (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
169         }
170     }
171
172     if (BN_copy(rsa->e, e_value) == NULL)
173         goto err;
174
175     /* generate p, q and other primes (if any) */
176     for (i = 0; i < primes; i++) {
177         adj = 0;
178         retries = 0;
179
180         if (i == 0) {
181             prime = rsa->p;
182         } else if (i == 1) {
183             prime = rsa->q;
184         } else {
185             pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
186             prime = pinfo->r;
187         }
188         BN_set_flags(prime, BN_FLG_CONSTTIME);
189
190         for (;;) {
191  redo:
192             if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
193                                        cb, ctx))
194                 goto err;
195             /*
196              * prime should not be equal to p, q, r_3...
197              * (those primes prior to this one)
198              */
199             {
200                 int j;
201
202                 for (j = 0; j < i; j++) {
203                     BIGNUM *prev_prime;
204
205                     if (j == 0)
206                         prev_prime = rsa->p;
207                     else if (j == 1)
208                         prev_prime = rsa->q;
209                     else
210                         prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
211                                                              j - 2)->r;
212
213                     if (!BN_cmp(prime, prev_prime)) {
214                         goto redo;
215                     }
216                 }
217             }
218             if (!BN_sub(r2, prime, BN_value_one()))
219                 goto err;
220             ERR_set_mark();
221             BN_set_flags(r2, BN_FLG_CONSTTIME);
222             if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
223                /* GCD == 1 since inverse exists */
224                 break;
225             }
226             error = ERR_peek_last_error();
227             if (ERR_GET_LIB(error) == ERR_LIB_BN
228                 && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
229                 /* GCD != 1 */
230                 ERR_pop_to_mark();
231             } else {
232                 goto err;
233             }
234             if (!BN_GENCB_call(cb, 2, n++))
235                 goto err;
236         }
237
238         bitse += bitsr[i];
239
240         /* calculate n immediately to see if it's sufficient */
241         if (i == 1) {
242             /* we get at least 2 primes */
243             if (!BN_mul(r1, rsa->p, rsa->q, ctx))
244                 goto err;
245         } else if (i != 0) {
246             /* modulus n = p * q * r_3 * r_4 ... */
247             if (!BN_mul(r1, rsa->n, prime, ctx))
248                 goto err;
249         } else {
250             /* i == 0, do nothing */
251             if (!BN_GENCB_call(cb, 3, i))
252                 goto err;
253             continue;
254         }
255         /*
256          * if |r1|, product of factors so far, is not as long as expected
257          * (by checking the first 4 bits are less than 0x9 or greater than
258          * 0xF). If so, re-generate the last prime.
259          *
260          * NOTE: This actually can't happen in two-prime case, because of
261          * the way factors are generated.
262          *
263          * Besides, another consideration is, for multi-prime case, even the
264          * length modulus is as long as expected, the modulus could start at
265          * 0x8, which could be utilized to distinguish a multi-prime private
266          * key by using the modulus in a certificate. This is also covered
267          * by checking the length should not be less than 0x9.
268          */
269         if (!BN_rshift(r2, r1, bitse - 4))
270             goto err;
271         bitst = BN_get_word(r2);
272
273         if (bitst < 0x9 || bitst > 0xF) {
274             /*
275              * For keys with more than 4 primes, we attempt longer factor to
276              * meet length requirement.
277              *
278              * Otherwise, we just re-generate the prime with the same length.
279              *
280              * This strategy has the following goals:
281              *
282              * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
283              * 2. stay the same logic with normal 2-prime key
284              */
285             bitse -= bitsr[i];
286             if (!BN_GENCB_call(cb, 2, n++))
287                 goto err;
288             if (primes > 4) {
289                 if (bitst < 0x9)
290                     adj++;
291                 else
292                     adj--;
293             } else if (retries == 4) {
294                 /*
295                  * re-generate all primes from scratch, mainly used
296                  * in 4 prime case to avoid long loop. Max retry times
297                  * is set to 4.
298                  */
299                 i = -1;
300                 bitse = 0;
301                 continue;
302             }
303             retries++;
304             goto redo;
305         }
306         /* save product of primes for further use, for multi-prime only */
307         if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
308             goto err;
309         if (BN_copy(rsa->n, r1) == NULL)
310             goto err;
311         if (!BN_GENCB_call(cb, 3, i))
312             goto err;
313     }
314
315     if (BN_cmp(rsa->p, rsa->q) < 0) {
316         tmp = rsa->p;
317         rsa->p = rsa->q;
318         rsa->q = tmp;
319     }
320
321     /* calculate d */
322
323     /* p - 1 */
324     if (!BN_sub(r1, rsa->p, BN_value_one()))
325         goto err;
326     /* q - 1 */
327     if (!BN_sub(r2, rsa->q, BN_value_one()))
328         goto err;
329     /* (p - 1)(q - 1) */
330     if (!BN_mul(r0, r1, r2, ctx))
331         goto err;
332     /* multi-prime */
333     for (i = 2; i < primes; i++) {
334         pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
335         /* save r_i - 1 to pinfo->d temporarily */
336         if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
337             goto err;
338         if (!BN_mul(r0, r0, pinfo->d, ctx))
339             goto err;
340     }
341
342     {
343         BIGNUM *pr0 = BN_new();
344
345         if (pr0 == NULL)
346             goto err;
347
348         BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
349         if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
350             BN_free(pr0);
351             goto err;               /* d */
352         }
353         /* We MUST free pr0 before any further use of r0 */
354         BN_free(pr0);
355     }
356
357     {
358         BIGNUM *d = BN_new();
359
360         if (d == NULL)
361             goto err;
362
363         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
364
365         /* calculate d mod (p-1) and d mod (q - 1) */
366         if (!BN_mod(rsa->dmp1, d, r1, ctx)
367             || !BN_mod(rsa->dmq1, d, r2, ctx)) {
368             BN_free(d);
369             goto err;
370         }
371
372         /* calculate CRT exponents */
373         for (i = 2; i < primes; i++) {
374             pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
375             /* pinfo->d == r_i - 1 */
376             if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
377                 BN_free(d);
378                 goto err;
379             }
380         }
381
382         /* We MUST free d before any further use of rsa->d */
383         BN_free(d);
384     }
385
386     {
387         BIGNUM *p = BN_new();
388
389         if (p == NULL)
390             goto err;
391         BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
392
393         /* calculate inverse of q mod p */
394         if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
395             BN_free(p);
396             goto err;
397         }
398
399         /* calculate CRT coefficient for other primes */
400         for (i = 2; i < primes; i++) {
401             pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
402             BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
403             if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
404                 BN_free(p);
405                 goto err;
406             }
407         }
408
409         /* We MUST free p before any further use of rsa->p */
410         BN_free(p);
411     }
412
413     ok = 1;
414  err:
415     if (ok == -1) {
416         ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
417         ok = 0;
418     }
419     BN_CTX_end(ctx);
420     BN_CTX_free(ctx);
421     return ok;
422 }
423 #endif /* FIPS_MODULE */
424
425 static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
426                       BIGNUM *e_value, BN_GENCB *cb, int pairwise_test)
427 {
428     int ok = 0;
429
430 #ifdef FIPS_MODULE
431     ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
432     pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
433 #else
434     /*
435      * Only multi-prime keys or insecure keys with a small key length or a
436      * public exponent <= 2^16 will use the older rsa_multiprime_keygen().
437      */
438     if (primes == 2
439             && bits >= 2048
440             && (e_value == NULL || BN_num_bits(e_value) > 16))
441         ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
442     else
443         ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
444 #endif /* FIPS_MODULE */
445
446     if (pairwise_test && ok > 0) {
447         OSSL_CALLBACK *stcb = NULL;
448         void *stcbarg = NULL;
449
450         OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
451         ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
452         if (!ok) {
453             ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
454             /* Clear intermediate results */
455             BN_clear_free(rsa->d);
456             BN_clear_free(rsa->p);
457             BN_clear_free(rsa->q);
458             BN_clear_free(rsa->dmp1);
459             BN_clear_free(rsa->dmq1);
460             BN_clear_free(rsa->iqmp);
461             rsa->d = NULL;
462             rsa->p = NULL;
463             rsa->q = NULL;
464             rsa->dmp1 = NULL;
465             rsa->dmq1 = NULL;
466             rsa->iqmp = NULL;
467         }
468     }
469     return ok;
470 }
471
472 /*
473  * For RSA key generation it is not known whether the key pair will be used
474  * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case
475  * either a signature verification OR an encryption operation may be used to
476  * perform the pairwise consistency check. The simpler encrypt/decrypt operation
477  * has been chosen for this case.
478  */
479 static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
480 {
481     int ret = 0;
482     unsigned int ciphertxt_len;
483     unsigned char *ciphertxt = NULL;
484     const unsigned char plaintxt[16] = {0};
485     unsigned char *decoded = NULL;
486     unsigned int decoded_len;
487     unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
488     int padding = RSA_PKCS1_PADDING;
489     OSSL_SELF_TEST *st = NULL;
490
491     st = OSSL_SELF_TEST_new(cb, cbarg);
492     if (st == NULL)
493         goto err;
494     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
495                            OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
496
497     ciphertxt_len = RSA_size(rsa);
498     /*
499      * RSA_private_encrypt() and RSA_private_decrypt() requires the 'to'
500      * parameter to be a maximum of RSA_size() - allocate space for both.
501      */
502     ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2);
503     if (ciphertxt == NULL)
504         goto err;
505     decoded = ciphertxt + ciphertxt_len;
506
507     ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
508                                        padding);
509     if (ciphertxt_len <= 0)
510         goto err;
511     if (ciphertxt_len == plaintxt_len
512         && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
513         goto err;
514
515     OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
516
517     decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
518                                       padding);
519     if (decoded_len != plaintxt_len
520         || memcmp(decoded, plaintxt,  decoded_len) != 0)
521         goto err;
522
523     ret = 1;
524 err:
525     OSSL_SELF_TEST_onend(st, ret);
526     OSSL_SELF_TEST_free(st);
527     OPENSSL_free(ciphertxt);
528
529     return ret;
530 }