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