Coverage Report

Created: 2024-11-21 07:03

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