Coverage Report

Created: 2026-10-16 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/rsa/rsa_gen.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2026 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
    uint32_t a, uint32_t b);
34
35
/*
36
 * NB: this wrapper would normally be placed in rsa_lib.c and the static
37
 * implementation would probably be in rsa_eay.c. Nonetheless, is kept here
38
 * so that we don't introduce a new linker dependency. Eg. any application
39
 * that wasn't previously linking object code related to key-generation won't
40
 * have to now just because key-generation is part of RSA_METHOD.
41
 */
42
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
43
0
{
44
0
    if (rsa->meth->rsa_keygen != NULL)
45
0
        return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
46
47
0
    return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
48
0
        e_value, cb);
49
0
}
50
51
int ossl_rsa_generate_multi_prime_key(RSA *rsa, int bits, int primes,
52
    BIGNUM *e_value, BN_GENCB *cb,
53
    uint32_t a, uint32_t b)
54
0
{
55
0
#ifndef FIPS_MODULE
56
    /* multi-prime is only supported with the builtin key generation */
57
0
    if (rsa->meth->rsa_multi_prime_keygen != NULL) {
58
0
        return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
59
0
            e_value, cb);
60
0
    } else if (rsa->meth->rsa_keygen != NULL) {
61
        /*
62
         * However, if rsa->meth implements only rsa_keygen, then we
63
         * have to honour it in 2-prime case and assume that it wouldn't
64
         * know what to do with multi-prime key generated by builtin
65
         * subroutine...
66
         */
67
0
        if (primes == 2)
68
0
            return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
69
0
        else
70
0
            return 0;
71
0
    }
72
0
#endif /* FIPS_MODULE */
73
0
    return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0, a, b);
74
0
}
75
76
int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
77
    BIGNUM *e, BN_GENCB *cb)
78
0
{
79
0
    return ossl_rsa_generate_multi_prime_key(rsa, bits, primes, e, cb, 0, 0);
80
0
}
81
82
DEFINE_STACK_OF(BIGNUM)
83
84
/*
85
 * Given input values, q, p, n, d and e, derive the exponents
86
 * and coefficients for each prime in this key, placing the result
87
 * on their respective exps and coeffs stacks
88
 */
89
#ifndef FIPS_MODULE
90
int ossl_rsa_multiprime_derive(RSA *rsa,
91
    STACK_OF(BIGNUM) *factors,
92
    STACK_OF(BIGNUM) *exps,
93
    STACK_OF(BIGNUM) *coeffs)
94
0
{
95
0
    STACK_OF(BIGNUM) *pplist = NULL, *pdlist = NULL;
96
0
    BIGNUM *factor = NULL, *newpp = NULL, *newpd = NULL;
97
0
    BIGNUM *dval = NULL, *newexp = NULL, *newcoeff = NULL;
98
0
    BIGNUM *p = NULL, *q = NULL;
99
0
    BIGNUM *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
100
0
    BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL;
101
0
    BN_CTX *ctx = NULL;
102
0
    BIGNUM *tmp = NULL;
103
0
    int i;
104
0
    int ret = 0;
105
106
0
    ctx = BN_CTX_new_ex(rsa->libctx);
107
0
    if (ctx == NULL)
108
0
        goto err;
109
110
0
    BN_CTX_start(ctx);
111
112
0
    pplist = sk_BIGNUM_new_null();
113
0
    if (pplist == NULL)
114
0
        goto err;
115
116
0
    pdlist = sk_BIGNUM_new_null();
117
0
    if (pdlist == NULL)
118
0
        goto err;
119
120
0
    r0 = BN_CTX_get(ctx);
121
0
    r1 = BN_CTX_get(ctx);
122
0
    r2 = BN_CTX_get(ctx);
123
124
0
    if (r2 == NULL)
125
0
        goto err;
126
127
0
    BN_set_flags(r0, BN_FLG_CONSTTIME);
128
0
    BN_set_flags(r1, BN_FLG_CONSTTIME);
129
0
    BN_set_flags(r2, BN_FLG_CONSTTIME);
130
131
0
    if (BN_copy(r1, rsa->n) == NULL)
132
0
        goto err;
133
134
0
    p = sk_BIGNUM_value(factors, 0);
135
0
    q = sk_BIGNUM_value(factors, 1);
136
137
    /* Build list of partial products of primes */
138
0
    for (i = 0; i < sk_BIGNUM_num(factors); i++) {
139
0
        switch (i) {
140
0
        case 0:
141
            /* our first prime, p */
142
0
            if (!BN_sub(r2, p, BN_value_one()))
143
0
                goto err;
144
0
            BN_set_flags(r2, BN_FLG_CONSTTIME);
145
0
            if (BN_mod_inverse(r1, r2, rsa->e, ctx) == NULL)
146
0
                goto err;
147
0
            break;
148
0
        case 1:
149
            /* second prime q */
150
0
            if (!BN_mul(r1, p, q, ctx))
151
0
                goto err;
152
0
            tmp = BN_dup(r1);
153
0
            if (tmp == NULL)
154
0
                goto err;
155
0
            if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist)))
156
0
                goto err;
157
0
            tmp = NULL;
158
0
            break;
159
0
        default:
160
0
            factor = sk_BIGNUM_value(factors, i);
161
            /* all other primes */
162
0
            if (!BN_mul(r1, r1, factor, ctx))
163
0
                goto err;
164
0
            tmp = BN_dup(r1);
165
0
            if (tmp == NULL)
166
0
                goto err;
167
0
            if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist)))
168
0
                goto err;
169
0
            tmp = NULL;
170
0
            break;
171
0
        }
172
0
    }
173
174
    /* build list of relative d values */
175
    /* p -1 */
176
0
    if (!BN_sub(r1, p, BN_value_one()))
177
0
        goto err;
178
0
    if (!BN_sub(r2, q, BN_value_one()))
179
0
        goto err;
180
0
    if (!BN_mul(r0, r1, r2, ctx))
181
0
        goto err;
182
0
    for (i = 2; i < sk_BIGNUM_num(factors); i++) {
183
0
        factor = sk_BIGNUM_value(factors, i);
184
0
        dval = BN_new();
185
0
        if (dval == NULL)
186
0
            goto err;
187
0
        BN_set_flags(dval, BN_FLG_CONSTTIME);
188
0
        if (!BN_sub(dval, factor, BN_value_one()))
189
0
            goto err;
190
0
        if (!BN_mul(r0, r0, dval, ctx))
191
0
            goto err;
192
0
        if (!sk_BIGNUM_insert(pdlist, dval, sk_BIGNUM_num(pdlist)))
193
0
            goto err;
194
0
        dval = NULL;
195
0
    }
196
197
    /* Calculate dmp1, dmq1 and additional exponents */
198
0
    dmp1 = BN_secure_new();
199
0
    if (dmp1 == NULL)
200
0
        goto err;
201
0
    dmq1 = BN_secure_new();
202
0
    if (dmq1 == NULL)
203
0
        goto err;
204
205
0
    if (!BN_mod(dmp1, rsa->d, r1, ctx))
206
0
        goto err;
207
0
    if (!sk_BIGNUM_insert(exps, dmp1, sk_BIGNUM_num(exps)))
208
0
        goto err;
209
0
    dmp1 = NULL;
210
211
0
    if (!BN_mod(dmq1, rsa->d, r2, ctx))
212
0
        goto err;
213
0
    if (!sk_BIGNUM_insert(exps, dmq1, sk_BIGNUM_num(exps)))
214
0
        goto err;
215
0
    dmq1 = NULL;
216
217
0
    for (i = 2; i < sk_BIGNUM_num(factors); i++) {
218
0
        newpd = sk_BIGNUM_value(pdlist, i - 2);
219
0
        newexp = BN_new();
220
0
        if (newexp == NULL)
221
0
            goto err;
222
0
        if (!BN_mod(newexp, rsa->d, newpd, ctx))
223
0
            goto err;
224
0
        if (!sk_BIGNUM_insert(exps, newexp, sk_BIGNUM_num(exps)))
225
0
            goto err;
226
0
        newexp = NULL;
227
0
    }
228
229
    /* Calculate iqmp and additional coefficients */
230
0
    iqmp = BN_new();
231
0
    if (iqmp == NULL)
232
0
        goto err;
233
234
0
    if (BN_mod_inverse(iqmp, sk_BIGNUM_value(factors, 1),
235
0
            sk_BIGNUM_value(factors, 0), ctx)
236
0
        == NULL)
237
0
        goto err;
238
0
    if (!sk_BIGNUM_insert(coeffs, iqmp, sk_BIGNUM_num(coeffs)))
239
0
        goto err;
240
0
    iqmp = NULL;
241
242
0
    for (i = 2; i < sk_BIGNUM_num(factors); i++) {
243
0
        newpp = sk_BIGNUM_value(pplist, i - 2);
244
0
        newcoeff = BN_new();
245
0
        if (newcoeff == NULL)
246
0
            goto err;
247
0
        if (BN_mod_inverse(newcoeff, newpp, sk_BIGNUM_value(factors, i),
248
0
                ctx)
249
0
            == NULL)
250
0
            goto err;
251
0
        if (!sk_BIGNUM_insert(coeffs, newcoeff, sk_BIGNUM_num(coeffs)))
252
0
            goto err;
253
0
        newcoeff = NULL;
254
0
    }
255
256
0
    ret = 1;
257
0
err:
258
0
    BN_free(newcoeff);
259
0
    BN_free(newexp);
260
0
    BN_free(dval);
261
0
    BN_free(tmp);
262
0
    sk_BIGNUM_pop_free(pplist, BN_free);
263
0
    sk_BIGNUM_pop_free(pdlist, BN_free);
264
0
    BN_CTX_end(ctx);
265
0
    BN_CTX_free(ctx);
266
0
    BN_clear_free(dmp1);
267
0
    BN_clear_free(dmq1);
268
0
    BN_clear_free(iqmp);
269
0
    return ret;
270
0
}
271
272
static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
273
    BIGNUM *e_value, BN_GENCB *cb)
274
0
{
275
0
    BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *tmp2, *prime;
276
0
    int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
277
0
    int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
278
0
    RSA_PRIME_INFO *pinfo = NULL;
279
0
    STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
280
0
    STACK_OF(BIGNUM) *factors = NULL;
281
0
    STACK_OF(BIGNUM) *exps = NULL;
282
0
    STACK_OF(BIGNUM) *coeffs = NULL;
283
0
    BN_CTX *ctx = NULL;
284
0
    BN_ULONG bitst = 0;
285
0
    unsigned long error = 0;
286
0
    int ok = -1;
287
288
0
    if (bits < RSA_MIN_MODULUS_BITS) {
289
0
        ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
290
0
        return 0;
291
0
    }
292
0
    if (e_value == NULL) {
293
0
        ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE);
294
0
        return 0;
295
0
    }
296
    /* A bad value for e can cause infinite loops */
297
0
    if (!ossl_rsa_check_public_exponent(e_value)) {
298
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
299
0
        return 0;
300
0
    }
301
302
0
    if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
303
0
        ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
304
0
        return 0;
305
0
    }
306
307
0
    factors = sk_BIGNUM_new_null();
308
0
    if (factors == NULL)
309
0
        return 0;
310
311
0
    exps = sk_BIGNUM_new_null();
312
0
    if (exps == NULL)
313
0
        goto err;
314
315
0
    coeffs = sk_BIGNUM_new_null();
316
0
    if (coeffs == NULL)
317
0
        goto err;
318
319
0
    ctx = BN_CTX_new_ex(rsa->libctx);
320
0
    if (ctx == NULL)
321
0
        goto err;
322
0
    BN_CTX_start(ctx);
323
0
    r0 = BN_CTX_get(ctx);
324
0
    r1 = BN_CTX_get(ctx);
325
0
    r2 = BN_CTX_get(ctx);
326
0
    if (r2 == NULL)
327
0
        goto err;
328
329
    /* divide bits into 'primes' pieces evenly */
330
0
    quo = bits / primes;
331
0
    rmd = bits % primes;
332
333
0
    for (i = 0; i < primes; i++)
334
0
        bitsr[i] = (i < rmd) ? quo + 1 : quo;
335
336
0
    rsa->dirty_cnt++;
337
338
    /* We need the RSA components non-NULL */
339
0
    if (!rsa->n && ((rsa->n = BN_new()) == NULL))
340
0
        goto err;
341
0
    if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
342
0
        goto err;
343
0
    BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
344
0
    if (!rsa->e && ((rsa->e = BN_new()) == NULL))
345
0
        goto err;
346
0
    if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
347
0
        goto err;
348
0
    BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
349
0
    if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
350
0
        goto err;
351
0
    BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
352
353
    /* initialize multi-prime components */
354
0
    if (primes > RSA_DEFAULT_PRIME_NUM) {
355
0
        rsa->version = RSA_ASN1_VERSION_MULTI;
356
0
        prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
357
0
        if (prime_infos == NULL)
358
0
            goto err;
359
0
        if (rsa->prime_infos != NULL) {
360
            /* could this happen? */
361
0
            sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
362
0
                ossl_rsa_multip_info_free);
363
0
        }
364
0
        rsa->prime_infos = prime_infos;
365
366
        /* prime_info from 2 to |primes| -1 */
367
0
        for (i = 2; i < primes; i++) {
368
0
            pinfo = ossl_rsa_multip_info_new();
369
0
            if (pinfo == NULL)
370
0
                goto err;
371
0
            (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
372
0
        }
373
0
    }
374
375
0
    if (BN_copy(rsa->e, e_value) == NULL)
376
0
        goto err;
377
378
    /* generate p, q and other primes (if any) */
379
0
    for (i = 0; i < primes; i++) {
380
0
        adj = 0;
381
0
        retries = 0;
382
383
0
        if (i == 0) {
384
0
            prime = rsa->p;
385
0
        } else if (i == 1) {
386
0
            prime = rsa->q;
387
0
        } else {
388
0
            pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
389
0
            prime = pinfo->r;
390
0
        }
391
0
        BN_set_flags(prime, BN_FLG_CONSTTIME);
392
393
0
        for (;;) {
394
0
        redo:
395
0
            if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
396
0
                    cb, ctx))
397
0
                goto err;
398
            /*
399
             * prime should not be equal to p, q, r_3...
400
             * (those primes prior to this one)
401
             */
402
0
            {
403
0
                int j;
404
405
0
                for (j = 0; j < i; j++) {
406
0
                    BIGNUM *prev_prime;
407
408
0
                    if (j == 0)
409
0
                        prev_prime = rsa->p;
410
0
                    else if (j == 1)
411
0
                        prev_prime = rsa->q;
412
0
                    else
413
0
                        prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
414
0
                            j - 2)
415
0
                                         ->r;
416
417
0
                    if (!BN_cmp(prime, prev_prime)) {
418
0
                        goto redo;
419
0
                    }
420
0
                }
421
0
            }
422
0
            if (!BN_sub(r2, prime, BN_value_one()))
423
0
                goto err;
424
0
            ERR_set_mark();
425
0
            BN_set_flags(r2, BN_FLG_CONSTTIME);
426
0
            if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
427
                /* GCD == 1 since inverse exists */
428
0
                break;
429
0
            }
430
0
            error = ERR_peek_last_error();
431
0
            if (ERR_GET_LIB(error) == ERR_LIB_BN
432
0
                && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
433
                /* GCD != 1 */
434
0
                ERR_pop_to_mark();
435
0
            } else {
436
0
                goto err;
437
0
            }
438
0
            if (!BN_GENCB_call(cb, 2, n++))
439
0
                goto err;
440
0
        }
441
442
0
        bitse += bitsr[i];
443
444
        /* calculate n immediately to see if it's sufficient */
445
0
        if (i == 1) {
446
            /* we get at least 2 primes */
447
0
            if (!BN_mul(r1, rsa->p, rsa->q, ctx))
448
0
                goto err;
449
0
        } else if (i != 0) {
450
            /* modulus n = p * q * r_3 * r_4 ... */
451
0
            if (!BN_mul(r1, rsa->n, prime, ctx))
452
0
                goto err;
453
0
        } else {
454
            /* i == 0, do nothing */
455
0
            if (!BN_GENCB_call(cb, 3, i))
456
0
                goto err;
457
0
            tmp = BN_dup(prime);
458
0
            if (tmp == NULL)
459
0
                goto err;
460
0
            if (!sk_BIGNUM_insert(factors, tmp, sk_BIGNUM_num(factors))) {
461
0
                BN_clear_free(tmp);
462
0
                goto err;
463
0
            }
464
0
            continue;
465
0
        }
466
467
        /*
468
         * if |r1|, product of factors so far, is not as long as expected
469
         * (by checking the first 4 bits are less than 0x9 or greater than
470
         * 0xF). If so, re-generate the last prime.
471
         *
472
         * NOTE: This actually can't happen in two-prime case, because of
473
         * the way factors are generated.
474
         *
475
         * Besides, another consideration is, for multi-prime case, even the
476
         * length modulus is as long as expected, the modulus could start at
477
         * 0x8, which could be utilized to distinguish a multi-prime private
478
         * key by using the modulus in a certificate. This is also covered
479
         * by checking the length should not be less than 0x9.
480
         */
481
0
        if (!BN_rshift(r2, r1, bitse - 4))
482
0
            goto err;
483
0
        bitst = BN_get_word(r2);
484
485
0
        if (bitst < 0x9 || bitst > 0xF) {
486
            /*
487
             * For keys with more than 4 primes, we attempt longer factor to
488
             * meet length requirement.
489
             *
490
             * Otherwise, we just re-generate the prime with the same length.
491
             *
492
             * This strategy has the following goals:
493
             *
494
             * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
495
             * 2. stay the same logic with normal 2-prime key
496
             */
497
0
            bitse -= bitsr[i];
498
0
            if (!BN_GENCB_call(cb, 2, n++))
499
0
                goto err;
500
0
            if (primes > 4) {
501
0
                if (bitst < 0x9)
502
0
                    adj++;
503
0
                else
504
0
                    adj--;
505
0
            } else if (retries == 4) {
506
                /*
507
                 * re-generate all primes from scratch, mainly used
508
                 * in 4 prime case to avoid long loop. Max retry times
509
                 * is set to 4.
510
                 */
511
0
                i = -1;
512
0
                bitse = 0;
513
0
                sk_BIGNUM_pop_free(factors, BN_clear_free);
514
0
                factors = sk_BIGNUM_new_null();
515
0
                if (factors == NULL)
516
0
                    goto err;
517
0
                continue;
518
0
            }
519
0
            retries++;
520
0
            goto redo;
521
0
        }
522
        /* save product of primes for further use, for multi-prime only */
523
0
        if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
524
0
            goto err;
525
0
        if (BN_copy(rsa->n, r1) == NULL)
526
0
            goto err;
527
0
        if (!BN_GENCB_call(cb, 3, i))
528
0
            goto err;
529
0
        tmp = BN_dup(prime);
530
0
        if (tmp == NULL)
531
0
            goto err;
532
0
        if (!sk_BIGNUM_insert(factors, tmp, sk_BIGNUM_num(factors))) {
533
0
            BN_clear_free(tmp);
534
0
            goto err;
535
0
        }
536
0
    }
537
538
0
    if (BN_cmp(rsa->p, rsa->q) < 0) {
539
0
        tmp = rsa->p;
540
0
        rsa->p = rsa->q;
541
0
        rsa->q = tmp;
542
        /* mirror this in our factor stack */
543
0
        tmp = sk_BIGNUM_delete(factors, 0);
544
0
        if (!sk_BIGNUM_insert(factors, tmp, 1)) {
545
            /* the factor is no longer on the stack, so free it here */
546
0
            BN_clear_free(tmp);
547
0
            goto err;
548
0
        }
549
0
    }
550
551
    /* calculate d */
552
553
    /* p - 1 */
554
0
    if (!BN_sub(r1, rsa->p, BN_value_one()))
555
0
        goto err;
556
    /* q - 1 */
557
0
    if (!BN_sub(r2, rsa->q, BN_value_one()))
558
0
        goto err;
559
    /* (p - 1)(q - 1) */
560
0
    if (!BN_mul(r0, r1, r2, ctx))
561
0
        goto err;
562
    /* multi-prime */
563
0
    for (i = 2; i < primes; i++) {
564
0
        pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
565
        /* save r_i - 1 to pinfo->d temporarily */
566
0
        if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
567
0
            goto err;
568
0
        if (!BN_mul(r0, r0, pinfo->d, ctx))
569
0
            goto err;
570
0
    }
571
572
0
    BN_set_flags(r0, BN_FLG_CONSTTIME);
573
0
    if (BN_mod_inverse(rsa->d, rsa->e, r0, ctx) == NULL) {
574
0
        goto err; /* d */
575
0
    }
576
577
    /* derive any missing exponents and coefficients */
578
0
    if (!ossl_rsa_multiprime_derive(rsa, factors, exps, coeffs))
579
0
        goto err;
580
581
    /*
582
     * first 2 factors/exps are already tracked in p/q/dmq1/dmp1
583
     * and the first coeff is in iqmp, so pop those off the stack
584
     * Note, the first 2 factors/exponents are already tracked by p and q
585
     * assign dmp1/dmq1 and iqmp
586
     * the remaining pinfo values are separately allocated, so copy and delete
587
     * those
588
     */
589
0
    BN_clear_free(sk_BIGNUM_delete(factors, 0));
590
0
    BN_clear_free(sk_BIGNUM_delete(factors, 0));
591
0
    rsa->dmp1 = sk_BIGNUM_delete(exps, 0);
592
0
    rsa->dmq1 = sk_BIGNUM_delete(exps, 0);
593
0
    rsa->iqmp = sk_BIGNUM_delete(coeffs, 0);
594
0
    for (i = 2; i < primes; i++) {
595
0
        pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
596
0
        tmp = sk_BIGNUM_delete(factors, 0);
597
0
        BN_copy(pinfo->r, tmp);
598
0
        BN_clear_free(tmp);
599
0
        tmp = sk_BIGNUM_delete(exps, 0);
600
0
        tmp2 = BN_copy(pinfo->d, tmp);
601
0
        BN_clear_free(tmp);
602
0
        if (tmp2 == NULL)
603
0
            goto err;
604
0
        tmp = sk_BIGNUM_delete(coeffs, 0);
605
0
        tmp2 = BN_copy(pinfo->t, tmp);
606
0
        BN_clear_free(tmp);
607
0
        if (tmp2 == NULL)
608
0
            goto err;
609
0
    }
610
0
    ok = 1;
611
0
err:
612
    /* On error, these stacks may still contain BIGNUMs. */
613
0
    sk_BIGNUM_pop_free(factors, BN_clear_free);
614
0
    sk_BIGNUM_pop_free(exps, BN_clear_free);
615
0
    sk_BIGNUM_pop_free(coeffs, BN_clear_free);
616
0
    if (ok == -1) {
617
0
        ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
618
0
        ok = 0;
619
0
    }
620
0
    BN_CTX_end(ctx);
621
0
    BN_CTX_free(ctx);
622
0
    return ok;
623
0
}
624
#endif /* FIPS_MODULE */
625
626
static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
627
    BIGNUM *e_value, BN_GENCB *cb, int pairwise_test,
628
    uint32_t a, uint32_t b)
629
0
{
630
0
    int ok = 0;
631
632
#ifdef FIPS_MODULE
633
    ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb, a, b);
634
    pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
635
#else
636
    /*
637
     * Only multi-prime keys or insecure keys with a small key length or a
638
     * public exponent <= 2^16 will use the older rsa_multiprime_keygen().
639
     */
640
0
    if (primes == 2
641
0
        && bits >= 2048
642
0
        && (e_value == NULL || BN_num_bits(e_value) > 16))
643
0
        ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb, a, b);
644
0
    else
645
0
        ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
646
0
#endif /* FIPS_MODULE */
647
648
0
    if (pairwise_test && ok > 0) {
649
0
        OSSL_CALLBACK *stcb = NULL;
650
0
        void *stcbarg = NULL;
651
652
0
        OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
653
0
        ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
654
0
        if (!ok) {
655
            /* Clear intermediate results */
656
0
            BN_clear_free(rsa->d);
657
0
            BN_clear_free(rsa->p);
658
0
            BN_clear_free(rsa->q);
659
0
            BN_clear_free(rsa->dmp1);
660
0
            BN_clear_free(rsa->dmq1);
661
0
            BN_clear_free(rsa->iqmp);
662
0
            rsa->d = NULL;
663
0
            rsa->p = NULL;
664
0
            rsa->q = NULL;
665
0
            rsa->dmp1 = NULL;
666
0
            rsa->dmq1 = NULL;
667
0
            rsa->iqmp = NULL;
668
0
        }
669
0
    }
670
0
    return ok;
671
0
}
672
673
/*
674
 * AS10.35 (and its VEs/TEs) of the FIPS 140-3 standard requires a PCT for every
675
 * generated key pair. There are 3 options:
676
 * 1) If the key pair is to be used for key transport (asymmetric cipher), the
677
 *    PCT consists of encrypting a plaintext, verifying that the result
678
 *    (ciphertext) is not equal to the plaintext, decrypting the ciphertext, and
679
 *    verifying that the result is equal to the plaintext.
680
 * 2) If the key pair is to be used for digital signatures, the PCT consists of
681
 *    computing and verifying a signature.
682
 * 3) If the key pair is to be used for key agreement, the exact PCT is defined
683
 *    in the applicable standards. For RSA-based schemes, this is defined in
684
 *    SP 800-56Br2 (Section 6.4.1.1) as:
685
 *    "The owner shall perform a pair-wise consistency test by verifying that m
686
 *    = (m^e)^d mod n for some integer m satisfying 1 < m < (n - 1)."
687
 *
688
 * OpenSSL implements all three use cases: RSA-OAEP for key transport,
689
 * RSA signatures with PKCS#1 v1.5 or PSS padding, and KAS-IFC-SSC (KAS1/KAS2)
690
 * using RSASVE.
691
 *
692
 * According to FIPS 140-3 IG 10.3.A, if at the time when the PCT is performed
693
 * the keys' intended usage is not known, then any of the three PCTs described
694
 * in AS10.35 shall be performed on this key pair.
695
 *
696
 * Because of this allowance from the IG, the simplest option is 3, i.e.
697
 * RSA_public_encrypt() and RSA_private_decrypt() with RSA_NO_PADDING.
698
 */
699
static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
700
0
{
701
0
    int ret = 0;
702
0
    unsigned char *plaintxt = NULL;
703
0
    unsigned char *ciphertxt = NULL;
704
0
    unsigned char *decoded = NULL;
705
0
    int plaintxt_len;
706
0
    int ciphertxt_len;
707
0
    int decoded_len;
708
0
    int padding = RSA_NO_PADDING;
709
0
    OSSL_SELF_TEST *st = NULL;
710
711
0
    st = OSSL_SELF_TEST_new(cb, cbarg);
712
0
    if (st == NULL)
713
0
        goto err;
714
0
    OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
715
0
        OSSL_SELF_TEST_DESC_PCT_RSA);
716
717
    /*
718
     * For RSA_NO_PADDING, RSA_public_encrypt() and RSA_private_decrypt()
719
     * require the 'to' and 'from' parameters to have equal length and a
720
     * maximum of RSA_size() - allocate space for plaintxt, ciphertxt, and
721
     * decoded.
722
     */
723
0
    plaintxt_len = RSA_size(rsa);
724
0
    plaintxt = OPENSSL_calloc(plaintxt_len, 3);
725
0
    if (plaintxt == NULL)
726
0
        goto err;
727
0
    ciphertxt = plaintxt + plaintxt_len;
728
0
    decoded = ciphertxt + plaintxt_len;
729
730
    /* SP 800-56Br2 Section 6.4.1.1 requires that plaintext is greater than 1 */
731
0
    plaintxt[plaintxt_len - 1] = 2;
732
733
0
    ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
734
0
        padding);
735
0
    if (ciphertxt_len <= 0)
736
0
        goto err;
737
738
0
    OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
739
740
0
    decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
741
0
        padding);
742
0
    if (decoded_len != plaintxt_len
743
0
        || memcmp(decoded, plaintxt, decoded_len) != 0)
744
0
        goto err;
745
746
0
    ret = 1;
747
0
err:
748
0
    OSSL_SELF_TEST_onend(st, ret);
749
0
    OSSL_SELF_TEST_free(st);
750
0
    OPENSSL_free(plaintxt);
751
752
0
    return ret;
753
0
}