OpenSSL 3.2.0, QUIC, macOS, error 56 on connected UDP socket
[openssl.git] / crypto / rsa / rsa_gen.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 /*
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 #include <stdio.h>
17 #include <time.h>
18 #include "internal/cryptlib.h"
19 #include <openssl/bn.h>
20 #include "rsa_local.h"
21
22 static int rsa_builtin_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value,
23                               BN_GENCB *cb);
24
25 /*
26  * NB: this wrapper would normally be placed in rsa_lib.c and the static
27  * implementation would probably be in rsa_eay.c. Nonetheless, is kept here
28  * so that we don't introduce a new linker dependency. Eg. any application
29  * that wasn't previously linking object code related to key-generation won't
30  * have to now just because key-generation is part of RSA_METHOD.
31  */
32 int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
33 {
34     if (rsa->meth->rsa_keygen != NULL)
35         return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
36
37     return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
38                                         e_value, cb);
39 }
40
41 int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
42                                  BIGNUM *e_value, BN_GENCB *cb)
43 {
44 #ifndef FIPS_MODE
45     /* multi-prime is only supported with the builtin key generation */
46     if (rsa->meth->rsa_multi_prime_keygen != NULL) {
47         return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
48                                                  e_value, cb);
49     } else if (rsa->meth->rsa_keygen != NULL) {
50         /*
51          * However, if rsa->meth implements only rsa_keygen, then we
52          * have to honour it in 2-prime case and assume that it wouldn't
53          * know what to do with multi-prime key generated by builtin
54          * subroutine...
55          */
56         if (primes == 2)
57             return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
58         else
59             return 0;
60     }
61 #endif /* FIPS_MODE */
62     return rsa_builtin_keygen(rsa, bits, primes, e_value, cb);
63 }
64
65 static int rsa_builtin_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value,
66                               BN_GENCB *cb)
67 {
68 #ifdef FIPS_MODE
69     if (primes != 2)
70         return 0;
71     return rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
72 #else
73     BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime;
74     int ok = -1, n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
75     int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
76     RSA_PRIME_INFO *pinfo = NULL;
77     STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
78     BN_CTX *ctx = NULL;
79     BN_ULONG bitst = 0;
80     unsigned long error = 0;
81
82     if (bits < RSA_MIN_MODULUS_BITS) {
83         ok = 0;             /* we set our own err */
84         RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL);
85         goto err;
86     }
87
88     if (primes < RSA_DEFAULT_PRIME_NUM || primes > rsa_multip_cap(bits)) {
89         ok = 0;             /* we set our own err */
90         RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_PRIME_NUM_INVALID);
91         goto err;
92     }
93
94     ctx = BN_CTX_new();
95     if (ctx == NULL)
96         goto err;
97     BN_CTX_start(ctx);
98     r0 = BN_CTX_get(ctx);
99     r1 = BN_CTX_get(ctx);
100     r2 = BN_CTX_get(ctx);
101     if (r2 == NULL)
102         goto err;
103
104     /* divide bits into 'primes' pieces evenly */
105     quo = bits / primes;
106     rmd = bits % primes;
107
108     for (i = 0; i < primes; i++)
109         bitsr[i] = (i < rmd) ? quo + 1 : quo;
110
111     rsa->dirty_cnt++;
112
113     /* We need the RSA components non-NULL */
114     if (!rsa->n && ((rsa->n = BN_new()) == NULL))
115         goto err;
116     if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
117         goto err;
118     if (!rsa->e && ((rsa->e = BN_new()) == NULL))
119         goto err;
120     if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
121         goto err;
122     if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
123         goto err;
124     if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
125         goto err;
126     if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
127         goto err;
128     if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
129         goto err;
130
131     /* initialize multi-prime components */
132     if (primes > RSA_DEFAULT_PRIME_NUM) {
133         rsa->version = RSA_ASN1_VERSION_MULTI;
134         prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
135         if (prime_infos == NULL)
136             goto err;
137         if (rsa->prime_infos != NULL) {
138             /* could this happen? */
139             sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos, rsa_multip_info_free);
140         }
141         rsa->prime_infos = prime_infos;
142
143         /* prime_info from 2 to |primes| -1 */
144         for (i = 2; i < primes; i++) {
145             pinfo = rsa_multip_info_new();
146             if (pinfo == NULL)
147                 goto err;
148             (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
149         }
150     }
151
152     if (BN_copy(rsa->e, e_value) == NULL)
153         goto err;
154
155     /* generate p, q and other primes (if any) */
156     for (i = 0; i < primes; i++) {
157         adj = 0;
158         retries = 0;
159
160         if (i == 0) {
161             prime = rsa->p;
162         } else if (i == 1) {
163             prime = rsa->q;
164         } else {
165             pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
166             prime = pinfo->r;
167         }
168         BN_set_flags(prime, BN_FLG_CONSTTIME);
169
170         for (;;) {
171  redo:
172             if (!BN_generate_prime_ex(prime, bitsr[i] + adj, 0, NULL, NULL, cb))
173                 goto err;
174             /*
175              * prime should not be equal to p, q, r_3...
176              * (those primes prior to this one)
177              */
178             {
179                 int j;
180
181                 for (j = 0; j < i; j++) {
182                     BIGNUM *prev_prime;
183
184                     if (j == 0)
185                         prev_prime = rsa->p;
186                     else if (j == 1)
187                         prev_prime = rsa->q;
188                     else
189                         prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
190                                                              j - 2)->r;
191
192                     if (!BN_cmp(prime, prev_prime)) {
193                         goto redo;
194                     }
195                 }
196             }
197             if (!BN_sub(r2, prime, BN_value_one()))
198                 goto err;
199             ERR_set_mark();
200             BN_set_flags(r2, BN_FLG_CONSTTIME);
201             if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
202                /* GCD == 1 since inverse exists */
203                 break;
204             }
205             error = ERR_peek_last_error();
206             if (ERR_GET_LIB(error) == ERR_LIB_BN
207                 && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
208                 /* GCD != 1 */
209                 ERR_pop_to_mark();
210             } else {
211                 goto err;
212             }
213             if (!BN_GENCB_call(cb, 2, n++))
214                 goto err;
215         }
216
217         bitse += bitsr[i];
218
219         /* calculate n immediately to see if it's sufficient */
220         if (i == 1) {
221             /* we get at least 2 primes */
222             if (!BN_mul(r1, rsa->p, rsa->q, ctx))
223                 goto err;
224         } else if (i != 0) {
225             /* modulus n = p * q * r_3 * r_4 ... */
226             if (!BN_mul(r1, rsa->n, prime, ctx))
227                 goto err;
228         } else {
229             /* i == 0, do nothing */
230             if (!BN_GENCB_call(cb, 3, i))
231                 goto err;
232             continue;
233         }
234         /*
235          * if |r1|, product of factors so far, is not as long as expected
236          * (by checking the first 4 bits are less than 0x9 or greater than
237          * 0xF). If so, re-generate the last prime.
238          *
239          * NOTE: This actually can't happen in two-prime case, because of
240          * the way factors are generated.
241          *
242          * Besides, another consideration is, for multi-prime case, even the
243          * length modulus is as long as expected, the modulus could start at
244          * 0x8, which could be utilized to distinguish a multi-prime private
245          * key by using the modulus in a certificate. This is also covered
246          * by checking the length should not be less than 0x9.
247          */
248         if (!BN_rshift(r2, r1, bitse - 4))
249             goto err;
250         bitst = BN_get_word(r2);
251
252         if (bitst < 0x9 || bitst > 0xF) {
253             /*
254              * For keys with more than 4 primes, we attempt longer factor to
255              * meet length requirement.
256              *
257              * Otherwise, we just re-generate the prime with the same length.
258              *
259              * This strategy has the following goals:
260              *
261              * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
262              * 2. stay the same logic with normal 2-prime key
263              */
264             bitse -= bitsr[i];
265             if (!BN_GENCB_call(cb, 2, n++))
266                 goto err;
267             if (primes > 4) {
268                 if (bitst < 0x9)
269                     adj++;
270                 else
271                     adj--;
272             } else if (retries == 4) {
273                 /*
274                  * re-generate all primes from scratch, mainly used
275                  * in 4 prime case to avoid long loop. Max retry times
276                  * is set to 4.
277                  */
278                 i = -1;
279                 bitse = 0;
280                 continue;
281             }
282             retries++;
283             goto redo;
284         }
285         /* save product of primes for further use, for multi-prime only */
286         if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
287             goto err;
288         if (BN_copy(rsa->n, r1) == NULL)
289             goto err;
290         if (!BN_GENCB_call(cb, 3, i))
291             goto err;
292     }
293
294     if (BN_cmp(rsa->p, rsa->q) < 0) {
295         tmp = rsa->p;
296         rsa->p = rsa->q;
297         rsa->q = tmp;
298     }
299
300     /* calculate d */
301
302     /* p - 1 */
303     if (!BN_sub(r1, rsa->p, BN_value_one()))
304         goto err;
305     /* q - 1 */
306     if (!BN_sub(r2, rsa->q, BN_value_one()))
307         goto err;
308     /* (p - 1)(q - 1) */
309     if (!BN_mul(r0, r1, r2, ctx))
310         goto err;
311     /* multi-prime */
312     for (i = 2; i < primes; i++) {
313         pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
314         /* save r_i - 1 to pinfo->d temporarily */
315         if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
316             goto err;
317         if (!BN_mul(r0, r0, pinfo->d, ctx))
318             goto err;
319     }
320
321     {
322         BIGNUM *pr0 = BN_new();
323
324         if (pr0 == NULL)
325             goto err;
326
327         BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
328         if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
329             BN_free(pr0);
330             goto err;               /* d */
331         }
332         /* We MUST free pr0 before any further use of r0 */
333         BN_free(pr0);
334     }
335
336     {
337         BIGNUM *d = BN_new();
338
339         if (d == NULL)
340             goto err;
341
342         BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
343
344         /* calculate d mod (p-1) and d mod (q - 1) */
345         if (!BN_mod(rsa->dmp1, d, r1, ctx)
346             || !BN_mod(rsa->dmq1, d, r2, ctx)) {
347             BN_free(d);
348             goto err;
349         }
350
351         /* calculate CRT exponents */
352         for (i = 2; i < primes; i++) {
353             pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
354             /* pinfo->d == r_i - 1 */
355             if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
356                 BN_free(d);
357                 goto err;
358             }
359         }
360
361         /* We MUST free d before any further use of rsa->d */
362         BN_free(d);
363     }
364
365     {
366         BIGNUM *p = BN_new();
367
368         if (p == NULL)
369             goto err;
370         BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
371
372         /* calculate inverse of q mod p */
373         if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
374             BN_free(p);
375             goto err;
376         }
377
378         /* calculate CRT coefficient for other primes */
379         for (i = 2; i < primes; i++) {
380             pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
381             BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
382             if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
383                 BN_free(p);
384                 goto err;
385             }
386         }
387
388         /* We MUST free p before any further use of rsa->p */
389         BN_free(p);
390     }
391
392     ok = 1;
393  err:
394     if (ok == -1) {
395         RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN);
396         ok = 0;
397     }
398     BN_CTX_end(ctx);
399     BN_CTX_free(ctx);
400     return ok;
401 #endif /* FIPS_MODE */
402 }