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