Coverage Report

Created: 2025-06-13 06:55

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