Coverage Report

Created: 2025-06-13 06:58

/src/openssl32/crypto/rsa/rsa_gen.c
Line
Count
Source (jump to first uncovered line)
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
0
{
43
0
    if (rsa->meth->rsa_keygen != NULL)
44
0
        return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
45
46
0
    return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
47
0
                                        e_value, cb);
48
0
}
49
50
int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
51
                                 BIGNUM *e_value, BN_GENCB *cb)
52
0
{
53
0
#ifndef FIPS_MODULE
54
    /* multi-prime is only supported with the builtin key generation */
55
0
    if (rsa->meth->rsa_multi_prime_keygen != NULL) {
56
0
        return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
57
0
                                                 e_value, cb);
58
0
    } 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
0
        if (primes == 2)
66
0
            return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
67
0
        else
68
0
            return 0;
69
0
    }
70
0
#endif /* FIPS_MODULE */
71
0
    return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0);
72
0
}
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
0
{
78
0
    BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime;
79
0
    int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
80
0
    int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
81
0
    RSA_PRIME_INFO *pinfo = NULL;
82
0
    STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
83
0
    BN_CTX *ctx = NULL;
84
0
    BN_ULONG bitst = 0;
85
0
    unsigned long error = 0;
86
0
    int ok = -1;
87
88
0
    if (bits < RSA_MIN_MODULUS_BITS) {
89
0
        ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
90
0
        return 0;
91
0
    }
92
0
    if (e_value == NULL) {
93
0
        ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE);
94
0
        return 0;
95
0
    }
96
    /* A bad value for e can cause infinite loops */
97
0
    if (!ossl_rsa_check_public_exponent(e_value)) {
98
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
99
0
        return 0;
100
0
    }
101
102
0
    if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
103
0
        ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
104
0
        return 0;
105
0
    }
106
107
0
    ctx = BN_CTX_new_ex(rsa->libctx);
108
0
    if (ctx == NULL)
109
0
        goto err;
110
0
    BN_CTX_start(ctx);
111
0
    r0 = BN_CTX_get(ctx);
112
0
    r1 = BN_CTX_get(ctx);
113
0
    r2 = BN_CTX_get(ctx);
114
0
    if (r2 == NULL)
115
0
        goto err;
116
117
    /* divide bits into 'primes' pieces evenly */
118
0
    quo = bits / primes;
119
0
    rmd = bits % primes;
120
121
0
    for (i = 0; i < primes; i++)
122
0
        bitsr[i] = (i < rmd) ? quo + 1 : quo;
123
124
0
    rsa->dirty_cnt++;
125
126
    /* We need the RSA components non-NULL */
127
0
    if (!rsa->n && ((rsa->n = BN_new()) == NULL))
128
0
        goto err;
129
0
    if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
130
0
        goto err;
131
0
    BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
132
0
    if (!rsa->e && ((rsa->e = BN_new()) == NULL))
133
0
        goto err;
134
0
    if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
135
0
        goto err;
136
0
    BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
137
0
    if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
138
0
        goto err;
139
0
    BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
140
0
    if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
141
0
        goto err;
142
0
    BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
143
0
    if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
144
0
        goto err;
145
0
    BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
146
0
    if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
147
0
        goto err;
148
0
    BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
149
150
    /* initialize multi-prime components */
151
0
    if (primes > RSA_DEFAULT_PRIME_NUM) {
152
0
        rsa->version = RSA_ASN1_VERSION_MULTI;
153
0
        prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
154
0
        if (prime_infos == NULL)
155
0
            goto err;
156
0
        if (rsa->prime_infos != NULL) {
157
            /* could this happen? */
158
0
            sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
159
0
                                       ossl_rsa_multip_info_free);
160
0
        }
161
0
        rsa->prime_infos = prime_infos;
162
163
        /* prime_info from 2 to |primes| -1 */
164
0
        for (i = 2; i < primes; i++) {
165
0
            pinfo = ossl_rsa_multip_info_new();
166
0
            if (pinfo == NULL)
167
0
                goto err;
168
0
            (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
169
0
        }
170
0
    }
171
172
0
    if (BN_copy(rsa->e, e_value) == NULL)
173
0
        goto err;
174
175
    /* generate p, q and other primes (if any) */
176
0
    for (i = 0; i < primes; i++) {
177
0
        adj = 0;
178
0
        retries = 0;
179
180
0
        if (i == 0) {
181
0
            prime = rsa->p;
182
0
        } else if (i == 1) {
183
0
            prime = rsa->q;
184
0
        } else {
185
0
            pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
186
0
            prime = pinfo->r;
187
0
        }
188
0
        BN_set_flags(prime, BN_FLG_CONSTTIME);
189
190
0
        for (;;) {
191
0
 redo:
192
0
            if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
193
0
                                       cb, ctx))
194
0
                goto err;
195
            /*
196
             * prime should not be equal to p, q, r_3...
197
             * (those primes prior to this one)
198
             */
199
0
            {
200
0
                int j;
201
202
0
                for (j = 0; j < i; j++) {
203
0
                    BIGNUM *prev_prime;
204
205
0
                    if (j == 0)
206
0
                        prev_prime = rsa->p;
207
0
                    else if (j == 1)
208
0
                        prev_prime = rsa->q;
209
0
                    else
210
0
                        prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
211
0
                                                             j - 2)->r;
212
213
0
                    if (!BN_cmp(prime, prev_prime)) {
214
0
                        goto redo;
215
0
                    }
216
0
                }
217
0
            }
218
0
            if (!BN_sub(r2, prime, BN_value_one()))
219
0
                goto err;
220
0
            ERR_set_mark();
221
0
            BN_set_flags(r2, BN_FLG_CONSTTIME);
222
0
            if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
223
               /* GCD == 1 since inverse exists */
224
0
                break;
225
0
            }
226
0
            error = ERR_peek_last_error();
227
0
            if (ERR_GET_LIB(error) == ERR_LIB_BN
228
0
                && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
229
                /* GCD != 1 */
230
0
                ERR_pop_to_mark();
231
0
            } else {
232
0
                goto err;
233
0
            }
234
0
            if (!BN_GENCB_call(cb, 2, n++))
235
0
                goto err;
236
0
        }
237
238
0
        bitse += bitsr[i];
239
240
        /* calculate n immediately to see if it's sufficient */
241
0
        if (i == 1) {
242
            /* we get at least 2 primes */
243
0
            if (!BN_mul(r1, rsa->p, rsa->q, ctx))
244
0
                goto err;
245
0
        } else if (i != 0) {
246
            /* modulus n = p * q * r_3 * r_4 ... */
247
0
            if (!BN_mul(r1, rsa->n, prime, ctx))
248
0
                goto err;
249
0
        } else {
250
            /* i == 0, do nothing */
251
0
            if (!BN_GENCB_call(cb, 3, i))
252
0
                goto err;
253
0
            continue;
254
0
        }
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
0
        if (!BN_rshift(r2, r1, bitse - 4))
270
0
            goto err;
271
0
        bitst = BN_get_word(r2);
272
273
0
        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
0
            bitse -= bitsr[i];
286
0
            if (!BN_GENCB_call(cb, 2, n++))
287
0
                goto err;
288
0
            if (primes > 4) {
289
0
                if (bitst < 0x9)
290
0
                    adj++;
291
0
                else
292
0
                    adj--;
293
0
            } 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
0
                i = -1;
300
0
                bitse = 0;
301
0
                continue;
302
0
            }
303
0
            retries++;
304
0
            goto redo;
305
0
        }
306
        /* save product of primes for further use, for multi-prime only */
307
0
        if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
308
0
            goto err;
309
0
        if (BN_copy(rsa->n, r1) == NULL)
310
0
            goto err;
311
0
        if (!BN_GENCB_call(cb, 3, i))
312
0
            goto err;
313
0
    }
314
315
0
    if (BN_cmp(rsa->p, rsa->q) < 0) {
316
0
        tmp = rsa->p;
317
0
        rsa->p = rsa->q;
318
0
        rsa->q = tmp;
319
0
    }
320
321
    /* calculate d */
322
323
    /* p - 1 */
324
0
    if (!BN_sub(r1, rsa->p, BN_value_one()))
325
0
        goto err;
326
    /* q - 1 */
327
0
    if (!BN_sub(r2, rsa->q, BN_value_one()))
328
0
        goto err;
329
    /* (p - 1)(q - 1) */
330
0
    if (!BN_mul(r0, r1, r2, ctx))
331
0
        goto err;
332
    /* multi-prime */
333
0
    for (i = 2; i < primes; i++) {
334
0
        pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
335
        /* save r_i - 1 to pinfo->d temporarily */
336
0
        if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
337
0
            goto err;
338
0
        if (!BN_mul(r0, r0, pinfo->d, ctx))
339
0
            goto err;
340
0
    }
341
342
0
    {
343
0
        BIGNUM *pr0 = BN_new();
344
345
0
        if (pr0 == NULL)
346
0
            goto err;
347
348
0
        BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
349
0
        if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
350
0
            BN_free(pr0);
351
0
            goto err;               /* d */
352
0
        }
353
        /* We MUST free pr0 before any further use of r0 */
354
0
        BN_free(pr0);
355
0
    }
356
357
0
    {
358
0
        BIGNUM *d = BN_new();
359
360
0
        if (d == NULL)
361
0
            goto err;
362
363
0
        BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
364
365
        /* calculate d mod (p-1) and d mod (q - 1) */
366
0
        if (!BN_mod(rsa->dmp1, d, r1, ctx)
367
0
            || !BN_mod(rsa->dmq1, d, r2, ctx)) {
368
0
            BN_free(d);
369
0
            goto err;
370
0
        }
371
372
        /* calculate CRT exponents */
373
0
        for (i = 2; i < primes; i++) {
374
0
            pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
375
            /* pinfo->d == r_i - 1 */
376
0
            if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
377
0
                BN_free(d);
378
0
                goto err;
379
0
            }
380
0
        }
381
382
        /* We MUST free d before any further use of rsa->d */
383
0
        BN_free(d);
384
0
    }
385
386
0
    {
387
0
        BIGNUM *p = BN_new();
388
389
0
        if (p == NULL)
390
0
            goto err;
391
0
        BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
392
393
        /* calculate inverse of q mod p */
394
0
        if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
395
0
            BN_free(p);
396
0
            goto err;
397
0
        }
398
399
        /* calculate CRT coefficient for other primes */
400
0
        for (i = 2; i < primes; i++) {
401
0
            pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
402
0
            BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
403
0
            if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
404
0
                BN_free(p);
405
0
                goto err;
406
0
            }
407
0
        }
408
409
        /* We MUST free p before any further use of rsa->p */
410
0
        BN_free(p);
411
0
    }
412
413
0
    ok = 1;
414
0
 err:
415
0
    if (ok == -1) {
416
0
        ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
417
0
        ok = 0;
418
0
    }
419
0
    BN_CTX_end(ctx);
420
0
    BN_CTX_free(ctx);
421
0
    return ok;
422
0
}
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
0
{
428
0
    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
0
    if (primes == 2
439
0
            && bits >= 2048
440
0
            && (e_value == NULL || BN_num_bits(e_value) > 16))
441
0
        ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
442
0
    else
443
0
        ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
444
0
#endif /* FIPS_MODULE */
445
446
0
    if (pairwise_test && ok > 0) {
447
0
        OSSL_CALLBACK *stcb = NULL;
448
0
        void *stcbarg = NULL;
449
450
0
        OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
451
0
        ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
452
0
        if (!ok) {
453
0
            ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
454
            /* Clear intermediate results */
455
0
            BN_clear_free(rsa->d);
456
0
            BN_clear_free(rsa->p);
457
0
            BN_clear_free(rsa->q);
458
0
            BN_clear_free(rsa->dmp1);
459
0
            BN_clear_free(rsa->dmq1);
460
0
            BN_clear_free(rsa->iqmp);
461
0
            rsa->d = NULL;
462
0
            rsa->p = NULL;
463
0
            rsa->q = NULL;
464
0
            rsa->dmp1 = NULL;
465
0
            rsa->dmq1 = NULL;
466
0
            rsa->iqmp = NULL;
467
0
        }
468
0
    }
469
0
    return ok;
470
0
}
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
0
{
481
0
    int ret = 0;
482
0
    unsigned int ciphertxt_len;
483
0
    unsigned char *ciphertxt = NULL;
484
0
    const unsigned char plaintxt[16] = {0};
485
0
    unsigned char *decoded = NULL;
486
0
    unsigned int decoded_len;
487
0
    unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
488
0
    int padding = RSA_PKCS1_PADDING;
489
0
    OSSL_SELF_TEST *st = NULL;
490
491
0
    st = OSSL_SELF_TEST_new(cb, cbarg);
492
0
    if (st == NULL)
493
0
        goto err;
494
0
    OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
495
0
                           OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
496
497
0
    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
0
    ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2);
503
0
    if (ciphertxt == NULL)
504
0
        goto err;
505
0
    decoded = ciphertxt + ciphertxt_len;
506
507
0
    ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
508
0
                                       padding);
509
0
    if (ciphertxt_len <= 0)
510
0
        goto err;
511
0
    if (ciphertxt_len == plaintxt_len
512
0
        && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
513
0
        goto err;
514
515
0
    OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
516
517
0
    decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
518
0
                                      padding);
519
0
    if (decoded_len != plaintxt_len
520
0
        || memcmp(decoded, plaintxt,  decoded_len) != 0)
521
0
        goto err;
522
523
0
    ret = 1;
524
0
err:
525
0
    OSSL_SELF_TEST_onend(st, ret);
526
0
    OSSL_SELF_TEST_free(st);
527
0
    OPENSSL_free(ciphertxt);
528
529
0
    return ret;
530
0
}