]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/rsa/rsa_gen.c
58c7806ffd2a9a42ead99bbc8ac852c9194ca37c
[thirdparty/openssl.git] / crypto / rsa / rsa_gen.c
1 /*
2 * Copyright 1995-2020 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(OPENSSL_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 ok = 0; /* we set our own err */
90 RSAerr(0, RSA_R_KEY_SIZE_TOO_SMALL);
91 goto err;
92 }
93
94 /* A bad value for e can cause infinite loops */
95 if (e_value != NULL && !ossl_rsa_check_public_exponent(e_value)) {
96 RSAerr(0, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
97 return 0;
98 }
99
100 if (primes < RSA_DEFAULT_PRIME_NUM || primes > rsa_multip_cap(bits)) {
101 ok = 0; /* we set our own err */
102 RSAerr(0, RSA_R_KEY_PRIME_NUM_INVALID);
103 goto err;
104 }
105
106 ctx = BN_CTX_new();
107 if (ctx == NULL)
108 goto err;
109 BN_CTX_start(ctx);
110 r0 = BN_CTX_get(ctx);
111 r1 = BN_CTX_get(ctx);
112 r2 = BN_CTX_get(ctx);
113 if (r2 == NULL)
114 goto err;
115
116 /* divide bits into 'primes' pieces evenly */
117 quo = bits / primes;
118 rmd = bits % primes;
119
120 for (i = 0; i < primes; i++)
121 bitsr[i] = (i < rmd) ? quo + 1 : quo;
122
123 rsa->dirty_cnt++;
124
125 /* We need the RSA components non-NULL */
126 if (!rsa->n && ((rsa->n = BN_new()) == NULL))
127 goto err;
128 if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
129 goto err;
130 BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
131 if (!rsa->e && ((rsa->e = BN_new()) == NULL))
132 goto err;
133 if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
134 goto err;
135 BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
136 if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
137 goto err;
138 BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
139 if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
140 goto err;
141 BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
142 if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
143 goto err;
144 BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
145 if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
146 goto err;
147 BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
148
149 /* initialize multi-prime components */
150 if (primes > RSA_DEFAULT_PRIME_NUM) {
151 rsa->version = RSA_ASN1_VERSION_MULTI;
152 prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
153 if (prime_infos == NULL)
154 goto err;
155 if (rsa->prime_infos != NULL) {
156 /* could this happen? */
157 sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos, rsa_multip_info_free);
158 }
159 rsa->prime_infos = prime_infos;
160
161 /* prime_info from 2 to |primes| -1 */
162 for (i = 2; i < primes; i++) {
163 pinfo = rsa_multip_info_new();
164 if (pinfo == NULL)
165 goto err;
166 (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
167 }
168 }
169
170 if (BN_copy(rsa->e, e_value) == NULL)
171 goto err;
172
173 /* generate p, q and other primes (if any) */
174 for (i = 0; i < primes; i++) {
175 adj = 0;
176 retries = 0;
177
178 if (i == 0) {
179 prime = rsa->p;
180 } else if (i == 1) {
181 prime = rsa->q;
182 } else {
183 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
184 prime = pinfo->r;
185 }
186 BN_set_flags(prime, BN_FLG_CONSTTIME);
187
188 for (;;) {
189 redo:
190 if (!BN_generate_prime_ex(prime, bitsr[i] + adj, 0, NULL, NULL, cb))
191 goto err;
192 /*
193 * prime should not be equal to p, q, r_3...
194 * (those primes prior to this one)
195 */
196 {
197 int j;
198
199 for (j = 0; j < i; j++) {
200 BIGNUM *prev_prime;
201
202 if (j == 0)
203 prev_prime = rsa->p;
204 else if (j == 1)
205 prev_prime = rsa->q;
206 else
207 prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
208 j - 2)->r;
209
210 if (!BN_cmp(prime, prev_prime)) {
211 goto redo;
212 }
213 }
214 }
215 if (!BN_sub(r2, prime, BN_value_one()))
216 goto err;
217 ERR_set_mark();
218 BN_set_flags(r2, BN_FLG_CONSTTIME);
219 if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
220 /* GCD == 1 since inverse exists */
221 break;
222 }
223 error = ERR_peek_last_error();
224 if (ERR_GET_LIB(error) == ERR_LIB_BN
225 && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
226 /* GCD != 1 */
227 ERR_pop_to_mark();
228 } else {
229 goto err;
230 }
231 if (!BN_GENCB_call(cb, 2, n++))
232 goto err;
233 }
234
235 bitse += bitsr[i];
236
237 /* calculate n immediately to see if it's sufficient */
238 if (i == 1) {
239 /* we get at least 2 primes */
240 if (!BN_mul(r1, rsa->p, rsa->q, ctx))
241 goto err;
242 } else if (i != 0) {
243 /* modulus n = p * q * r_3 * r_4 ... */
244 if (!BN_mul(r1, rsa->n, prime, ctx))
245 goto err;
246 } else {
247 /* i == 0, do nothing */
248 if (!BN_GENCB_call(cb, 3, i))
249 goto err;
250 continue;
251 }
252 /*
253 * if |r1|, product of factors so far, is not as long as expected
254 * (by checking the first 4 bits are less than 0x9 or greater than
255 * 0xF). If so, re-generate the last prime.
256 *
257 * NOTE: This actually can't happen in two-prime case, because of
258 * the way factors are generated.
259 *
260 * Besides, another consideration is, for multi-prime case, even the
261 * length modulus is as long as expected, the modulus could start at
262 * 0x8, which could be utilized to distinguish a multi-prime private
263 * key by using the modulus in a certificate. This is also covered
264 * by checking the length should not be less than 0x9.
265 */
266 if (!BN_rshift(r2, r1, bitse - 4))
267 goto err;
268 bitst = BN_get_word(r2);
269
270 if (bitst < 0x9 || bitst > 0xF) {
271 /*
272 * For keys with more than 4 primes, we attempt longer factor to
273 * meet length requirement.
274 *
275 * Otherwise, we just re-generate the prime with the same length.
276 *
277 * This strategy has the following goals:
278 *
279 * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
280 * 2. stay the same logic with normal 2-prime key
281 */
282 bitse -= bitsr[i];
283 if (!BN_GENCB_call(cb, 2, n++))
284 goto err;
285 if (primes > 4) {
286 if (bitst < 0x9)
287 adj++;
288 else
289 adj--;
290 } else if (retries == 4) {
291 /*
292 * re-generate all primes from scratch, mainly used
293 * in 4 prime case to avoid long loop. Max retry times
294 * is set to 4.
295 */
296 i = -1;
297 bitse = 0;
298 continue;
299 }
300 retries++;
301 goto redo;
302 }
303 /* save product of primes for further use, for multi-prime only */
304 if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
305 goto err;
306 if (BN_copy(rsa->n, r1) == NULL)
307 goto err;
308 if (!BN_GENCB_call(cb, 3, i))
309 goto err;
310 }
311
312 if (BN_cmp(rsa->p, rsa->q) < 0) {
313 tmp = rsa->p;
314 rsa->p = rsa->q;
315 rsa->q = tmp;
316 }
317
318 /* calculate d */
319
320 /* p - 1 */
321 if (!BN_sub(r1, rsa->p, BN_value_one()))
322 goto err;
323 /* q - 1 */
324 if (!BN_sub(r2, rsa->q, BN_value_one()))
325 goto err;
326 /* (p - 1)(q - 1) */
327 if (!BN_mul(r0, r1, r2, ctx))
328 goto err;
329 /* multi-prime */
330 for (i = 2; i < primes; i++) {
331 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
332 /* save r_i - 1 to pinfo->d temporarily */
333 if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
334 goto err;
335 if (!BN_mul(r0, r0, pinfo->d, ctx))
336 goto err;
337 }
338
339 {
340 BIGNUM *pr0 = BN_new();
341
342 if (pr0 == NULL)
343 goto err;
344
345 BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
346 if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
347 BN_free(pr0);
348 goto err; /* d */
349 }
350 /* We MUST free pr0 before any further use of r0 */
351 BN_free(pr0);
352 }
353
354 {
355 BIGNUM *d = BN_new();
356
357 if (d == NULL)
358 goto err;
359
360 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
361
362 /* calculate d mod (p-1) and d mod (q - 1) */
363 if (!BN_mod(rsa->dmp1, d, r1, ctx)
364 || !BN_mod(rsa->dmq1, d, r2, ctx)) {
365 BN_free(d);
366 goto err;
367 }
368
369 /* calculate CRT exponents */
370 for (i = 2; i < primes; i++) {
371 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
372 /* pinfo->d == r_i - 1 */
373 if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
374 BN_free(d);
375 goto err;
376 }
377 }
378
379 /* We MUST free d before any further use of rsa->d */
380 BN_free(d);
381 }
382
383 {
384 BIGNUM *p = BN_new();
385
386 if (p == NULL)
387 goto err;
388 BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
389
390 /* calculate inverse of q mod p */
391 if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
392 BN_free(p);
393 goto err;
394 }
395
396 /* calculate CRT coefficient for other primes */
397 for (i = 2; i < primes; i++) {
398 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
399 BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
400 if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
401 BN_free(p);
402 goto err;
403 }
404 }
405
406 /* We MUST free p before any further use of rsa->p */
407 BN_free(p);
408 }
409
410 ok = 1;
411 err:
412 if (ok == -1) {
413 RSAerr(0, ERR_LIB_BN);
414 ok = 0;
415 }
416 BN_CTX_end(ctx);
417 BN_CTX_free(ctx);
418 return ok;
419 }
420 #endif /* FIPS_MODULE */
421
422 static int rsa_keygen(OPENSSL_CTX *libctx, RSA *rsa, int bits, int primes,
423 BIGNUM *e_value, BN_GENCB *cb, int pairwise_test)
424 {
425 int ok = 0;
426
427 /*
428 * Only multi-prime keys or insecure keys with a small key length will use
429 * the older rsa_multiprime_keygen().
430 */
431 if (primes == 2 && bits >= 2048)
432 ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
433 #ifndef FIPS_MODULE
434 else
435 ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
436 #endif /* FIPS_MODULE */
437
438 #ifdef FIPS_MODULE
439 pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
440 #endif
441 if (pairwise_test && ok > 0) {
442 OSSL_CALLBACK *stcb = NULL;
443 void *stcbarg = NULL;
444
445 OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
446 ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
447 if (!ok) {
448 ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
449 /* Clear intermediate results */
450 BN_clear_free(rsa->d);
451 BN_clear_free(rsa->p);
452 BN_clear_free(rsa->q);
453 BN_clear_free(rsa->dmp1);
454 BN_clear_free(rsa->dmq1);
455 BN_clear_free(rsa->iqmp);
456 rsa->d = NULL;
457 rsa->p = NULL;
458 rsa->q = NULL;
459 rsa->dmp1 = NULL;
460 rsa->dmq1 = NULL;
461 rsa->iqmp = NULL;
462 }
463 }
464 return ok;
465 }
466
467 /*
468 * For RSA key generation it is not known whether the key pair will be used
469 * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case
470 * either a signature verification OR an encryption operation may be used to
471 * perform the pairwise consistency check. The simpler encrypt/decrypt operation
472 * has been chosen for this case.
473 */
474 static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
475 {
476 int ret = 0;
477 unsigned int ciphertxt_len;
478 unsigned char *ciphertxt = NULL;
479 const unsigned char plaintxt[16] = {0};
480 unsigned char decoded[256];
481 unsigned int decoded_len;
482 unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
483 int padding = RSA_PKCS1_PADDING;
484 OSSL_SELF_TEST *st = NULL;
485
486 st = OSSL_SELF_TEST_new(cb, cbarg);
487 if (st == NULL)
488 goto err;
489 OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
490 OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
491
492 ciphertxt_len = RSA_size(rsa);
493 ciphertxt = OPENSSL_zalloc(ciphertxt_len);
494 if (ciphertxt == NULL)
495 goto err;
496
497 ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
498 padding);
499 if (ciphertxt_len <= 0)
500 goto err;
501 if (ciphertxt_len == plaintxt_len
502 && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
503 goto err;
504
505 OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
506
507 decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
508 padding);
509 if (decoded_len != plaintxt_len
510 || memcmp(decoded, plaintxt, decoded_len) != 0)
511 goto err;
512
513 ret = 1;
514 err:
515 OSSL_SELF_TEST_onend(st, ret);
516 OSSL_SELF_TEST_free(st);
517 OPENSSL_free(ciphertxt);
518
519 return ret;
520 }