Coverage Report

Created: 2025-11-25 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/bn/bn_rsa_fips186_5.c
Line
Count
Source
1
/*
2
 * Copyright 2018-2023 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright (c) 2018-2019, Oracle and/or its affiliates.  All rights reserved.
4
 *
5
 * Licensed under the Apache License 2.0 (the "License").  You may not use
6
 * this file except in compliance with the License.  You can obtain a copy
7
 * in the file LICENSE in the source distribution or at
8
 * https://www.openssl.org/source/license.html
9
 */
10
11
/*
12
 * According to NIST SP800-131A "Transitioning the use of cryptographic
13
 * algorithms and key lengths" Generation of 1024 bit RSA keys are no longer
14
 * allowed for signatures (Table 2) or key transport (Table 5). In the code
15
 * below any attempt to generate 1024 bit RSA keys will result in an error (Note
16
 * that digital signature verification can still use deprecated 1024 bit keys).
17
 *
18
 * FIPS 186-4 relies on the use of the auxiliary primes p1, p2, q1 and q2 that
19
 * must be generated before the module generates the RSA primes p and q.
20
 * Table B.1 in FIPS 186-4 specifies RSA modulus lengths of 2048 and
21
 * 3072 bits only, the min/max total length of the auxiliary primes.
22
 * FIPS 186-5 Table A.1 includes an additional entry for 4096 which has been
23
 * included here.
24
 */
25
#include <stdio.h>
26
#include <openssl/bn.h>
27
#include "bn_local.h"
28
#include "crypto/bn.h"
29
#include "internal/nelem.h"
30
31
#if BN_BITS2 == 64
32
# define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo
33
#else
34
# define BN_DEF(lo, hi) lo, hi
35
#endif
36
37
/* 1 / sqrt(2) * 2^256, rounded up */
38
static const BN_ULONG inv_sqrt_2_val[] = {
39
    BN_DEF(0x83339916UL, 0xED17AC85UL), BN_DEF(0x893BA84CUL, 0x1D6F60BAUL),
40
    BN_DEF(0x754ABE9FUL, 0x597D89B3UL), BN_DEF(0xF9DE6484UL, 0xB504F333UL)
41
};
42
43
const BIGNUM ossl_bn_inv_sqrt_2 = {
44
    (BN_ULONG *)inv_sqrt_2_val,
45
    OSSL_NELEM(inv_sqrt_2_val),
46
    OSSL_NELEM(inv_sqrt_2_val),
47
    0,
48
    BN_FLG_STATIC_DATA
49
};
50
51
/*
52
 * Refer to FIPS 186-5 Table B.1 for minimum rounds of Miller Rabin
53
 * required for generation of RSA aux primes (p1, p2, q1 and q2).
54
 */
55
static int bn_rsa_fips186_5_aux_prime_MR_rounds(int nbits)
56
0
{
57
0
    if (nbits >= 4096)
58
0
        return 44;
59
0
    if (nbits >= 3072)
60
0
        return 41;
61
0
    if (nbits >= 2048)
62
0
        return 38;
63
0
    return 0; /* Error */
64
0
}
65
66
/*
67
 * Refer to FIPS 186-5 Table B.1 for minimum rounds of Miller Rabin
68
 * required for generation of RSA primes (p and q)
69
 */
70
static int bn_rsa_fips186_5_prime_MR_rounds(int nbits)
71
0
{
72
0
    if (nbits >= 3072)
73
0
        return 4;
74
0
    if (nbits >= 2048)
75
0
        return 5;
76
0
    return 0; /* Error */
77
0
}
78
79
/*
80
 * FIPS 186-5 Table A.1. "Min length of auxiliary primes p1, p2, q1, q2".
81
 * (FIPS 186-5 has an entry for >= 4096 bits).
82
 *
83
 * Params:
84
 *     nbits The key size in bits.
85
 * Returns:
86
 *     The minimum size of the auxiliary primes or 0 if nbits is invalid.
87
 */
88
static int bn_rsa_fips186_5_aux_prime_min_size(int nbits)
89
0
{
90
0
    if (nbits >= 4096)
91
0
        return 201;
92
0
    if (nbits >= 3072)
93
0
        return 171;
94
0
    if (nbits >= 2048)
95
0
        return 141;
96
0
    return 0;
97
0
}
98
99
/*
100
 * FIPS 186-5 Table A.1 "Max of len(p1) + len(p2) and
101
 * len(q1) + len(q2) for p,q Probable Primes".
102
 * (FIPS 186-5 has an entry for >= 4096 bits).
103
 * Params:
104
 *     nbits The key size in bits.
105
 *     c If this is non zero then the probable prime is congruent to c mod 8
106
 *       and is 3 bits smaller
107
 * Returns:
108
 *     The maximum length or 0 if nbits is invalid.
109
 */
110
static int bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(int nbits,
111
                                                                   uint32_t c)
112
0
{
113
0
    int reduce_bits = (c == 0) ? 0 : 3;
114
115
0
    if (nbits >= 4096)
116
0
        return 2030 - reduce_bits;
117
0
    if (nbits >= 3072)
118
0
        return 1518 - reduce_bits;
119
0
    if (nbits >= 2048)
120
0
        return 1007 - reduce_bits;
121
0
    return 0;
122
0
}
123
124
/*
125
 * Find the first odd integer that is a probable prime.
126
 *
127
 * See section FIPS 186-5 A.1.6 (Steps 4.2/5.2).
128
 *
129
 * Params:
130
 *     Xp1 The passed in starting point to find a probably prime.
131
 *     p1 The returned probable prime (first odd integer >= Xp1)
132
 *     ctx A BN_CTX object.
133
 *     rounds The number of Miller Rabin rounds
134
 *     cb An optional BIGNUM callback.
135
 * Returns: 1 on success otherwise it returns 0.
136
 */
137
static int bn_rsa_fips186_5_find_aux_prob_prime(const BIGNUM *Xp1,
138
                                                BIGNUM *p1, BN_CTX *ctx,
139
                                                int rounds,
140
                                                BN_GENCB *cb)
141
0
{
142
0
    int ret = 0;
143
0
    int i = 0;
144
0
    int tmp = 0;
145
146
0
    if (BN_copy(p1, Xp1) == NULL)
147
0
        return 0;
148
0
    BN_set_flags(p1, BN_FLG_CONSTTIME);
149
150
    /* Find the first odd number >= Xp1 that is probably prime */
151
0
    for (;;) {
152
0
        i++;
153
0
        BN_GENCB_call(cb, 0, i);
154
        /* MR test with trial division */
155
0
        tmp = ossl_bn_check_generated_prime(p1, rounds, ctx, cb);
156
0
        if (tmp > 0)
157
0
            break;
158
0
        if (tmp < 0)
159
0
            goto err;
160
        /* Get next odd number */
161
0
        if (!BN_add_word(p1, 2))
162
0
            goto err;
163
0
    }
164
0
    BN_GENCB_call(cb, 2, i);
165
0
    ret = 1;
166
0
err:
167
0
    return ret;
168
0
}
169
170
/*
171
 * Generate a probable prime (p or q).
172
 *
173
 * See FIPS 186-5 A.1.6 (Steps 4 & 5)
174
 *
175
 * Params:
176
 *     p The returned probable prime.
177
 *     Xpout An optionally returned random number used during generation of p.
178
 *     p1, p2 The returned auxiliary primes. If NULL they are not returned.
179
 *     Xp An optional passed in value (that is random number used during
180
 *        generation of p).
181
 *     Xp1, Xp2 Optional passed in values that are normally generated
182
 *              internally. Used to find p1, p2.
183
 *     nlen The bit length of the modulus (the key size).
184
 *     e The public exponent.
185
 *     ctx A BN_CTX object.
186
 *     cb An optional BIGNUM callback.
187
 *     c An optional number with a value of 0, 1, 3, 5 or 7 that may be used
188
 *       to add the requirement p is congruent to c mod 8. The value is ignored
189
 *       if it is zero.
190
 * Returns: 1 on success otherwise it returns 0.
191
 */
192
int ossl_bn_rsa_fips186_5_gen_prob_primes(BIGNUM *p, BIGNUM *Xpout,
193
                                          BIGNUM *p1, BIGNUM *p2,
194
                                          const BIGNUM *Xp, const BIGNUM *Xp1,
195
                                          const BIGNUM *Xp2, int nlen,
196
                                          const BIGNUM *e, BN_CTX *ctx,
197
                                          BN_GENCB *cb, uint32_t c)
198
0
{
199
0
    int ret = 0;
200
0
    BIGNUM *p1i = NULL, *p2i = NULL, *Xp1i = NULL, *Xp2i = NULL;
201
0
    int bitlen, rounds;
202
203
0
    if (p == NULL || Xpout == NULL)
204
0
        return 0;
205
206
0
    BN_CTX_start(ctx);
207
208
0
    p1i = (p1 != NULL) ? p1 : BN_CTX_get(ctx);
209
0
    p2i = (p2 != NULL) ? p2 : BN_CTX_get(ctx);
210
0
    Xp1i = (Xp1 != NULL) ? (BIGNUM *)Xp1 : BN_CTX_get(ctx);
211
0
    Xp2i = (Xp2 != NULL) ? (BIGNUM *)Xp2 : BN_CTX_get(ctx);
212
0
    if (p1i == NULL || p2i == NULL || Xp1i == NULL || Xp2i == NULL)
213
0
        goto err;
214
215
0
    bitlen = bn_rsa_fips186_5_aux_prime_min_size(nlen);
216
0
    if (bitlen == 0)
217
0
        goto err;
218
0
    rounds = bn_rsa_fips186_5_aux_prime_MR_rounds(nlen);
219
220
    /* (Steps 4.1/5.1): Randomly generate Xp1 if it is not passed in */
221
0
    if (Xp1 == NULL) {
222
        /* Set the top and bottom bits to make it odd and the correct size */
223
0
        if (!BN_priv_rand_ex(Xp1i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD,
224
0
                             0, ctx))
225
0
            goto err;
226
0
    }
227
    /* (Steps 4.1/5.1): Randomly generate Xp2 if it is not passed in */
228
0
    if (Xp2 == NULL) {
229
        /* Set the top and bottom bits to make it odd and the correct size */
230
0
        if (!BN_priv_rand_ex(Xp2i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD,
231
0
                             0, ctx))
232
0
            goto err;
233
0
    }
234
235
    /* (Steps 4.2/5.2) - find first auxiliary probable primes */
236
0
    if (!bn_rsa_fips186_5_find_aux_prob_prime(Xp1i, p1i, ctx, rounds, cb)
237
0
            || !bn_rsa_fips186_5_find_aux_prob_prime(Xp2i, p2i, ctx, rounds, cb))
238
0
        goto err;
239
    /* (FIPS 186-5 Table A.1) auxiliary prime Max length check */
240
0
    if ((BN_num_bits(p1i) + BN_num_bits(p2i)) >=
241
0
            bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(nlen, c))
242
0
        goto err;
243
    /* (Steps 4.3/5.3) - generate prime */
244
0
    if (!ossl_bn_rsa_fips186_5_derive_prime(p, Xpout, Xp, p1i, p2i, nlen, e,
245
0
                                            ctx, cb, c))
246
0
        goto err;
247
0
    ret = 1;
248
0
err:
249
    /* Zeroize any internally generated values that are not returned */
250
0
    if (p1 == NULL)
251
0
        BN_clear(p1i);
252
0
    if (p2 == NULL)
253
0
        BN_clear(p2i);
254
0
    if (Xp1 == NULL)
255
0
        BN_clear(Xp1i);
256
0
    if (Xp2 == NULL)
257
0
        BN_clear(Xp2i);
258
0
    BN_CTX_end(ctx);
259
0
    return ret;
260
0
}
261
262
static ossl_inline
263
int get_multiple_of_y_congruent_to_cmod8(BIGNUM *y, const BIGNUM *r1r2x2, int c)
264
0
{
265
0
    int i = 0;
266
267
0
    for (i = 0; i < 3; ++i) {
268
        /* Check for Y = c mod 8 */
269
0
        if ((int)(*bn_get_words(y) & 7) == c)
270
0
            return 1;
271
        /* Y = Y + 2r1r2 */
272
0
        if (!BN_add(y, y, r1r2x2))
273
0
            return 0;
274
0
    }
275
    /* Fall through for y = y + 6 * r1r2 */
276
0
    return 1;
277
0
}
278
279
/*
280
 * Constructs a probable prime (a candidate for p or q) using 2 auxiliary
281
 * prime numbers and the Chinese Remainder Theorem.
282
 *
283
 * See FIPS 186-5 B.9 "Compute a Probable Prime Factor Based on Auxiliary
284
 * Primes". Used by FIPS 186-5 A.1.6 Section (4.3) for p and Section (5.3) for q.
285
 *
286
 * Params:
287
 *     Y The returned prime factor (private_prime_factor) of the modulus n.
288
 *     X The returned random number used during generation of the prime factor.
289
 *     Xin An optional passed in value for X used for testing purposes.
290
 *     r1 An auxiliary prime.
291
 *     r2 An auxiliary prime.
292
 *     nlen The desired length of n (the RSA modulus).
293
 *     e The public exponent.
294
 *     ctx A BN_CTX object.
295
 *     cb An optional BIGNUM callback object.
296
 *     c An optional parameter from the set {0, 1, 3, 5, 7} that
297
 *       may be used to add the further requirement that the computed
298
 *       prime is congruent to c mod 8. A value of 0 indicates that the option
299
 *       is ignored.
300
 * Returns: 1 on success otherwise it returns 0.
301
 * Assumptions:
302
 *     Y, X, r1, r2, e are not NULL.
303
 */
304
int ossl_bn_rsa_fips186_5_derive_prime(BIGNUM *Y, BIGNUM *X, const BIGNUM *Xin,
305
                                       const BIGNUM *r1, const BIGNUM *r2,
306
                                       int nlen, const BIGNUM *e,
307
                                       BN_CTX *ctx, BN_GENCB *cb, uint32_t c)
308
0
{
309
0
    int ret = 0;
310
0
    int i, imax, rounds;
311
0
    int bits = nlen >> 1;
312
0
    BIGNUM *tmp, *R, *r1r2x2, *r1r2x8, *y1, *r1x2;
313
0
    BIGNUM *base, *range, *r1r2x2_step;
314
315
0
    BN_CTX_start(ctx);
316
317
0
    base = BN_CTX_get(ctx);
318
0
    range = BN_CTX_get(ctx);
319
0
    R = BN_CTX_get(ctx);
320
0
    tmp = BN_CTX_get(ctx);
321
0
    r1r2x2 = BN_CTX_get(ctx);
322
0
    r1r2x8 = BN_CTX_get(ctx);
323
0
    y1 = BN_CTX_get(ctx);
324
0
    r1x2 = BN_CTX_get(ctx);
325
0
    if (r1x2 == NULL)
326
0
        goto err;
327
328
0
    if (Xin != NULL && BN_copy(X, Xin) == NULL)
329
0
        goto err;
330
331
    /*
332
     * We need to generate a random number X in the range
333
     * 1/sqrt(2) * 2^(nlen/2) <= X < 2^(nlen/2).
334
     * We can rewrite that as:
335
     * base = 1/sqrt(2) * 2^(nlen/2)
336
     * range = ((2^(nlen/2))) - (1/sqrt(2) * 2^(nlen/2))
337
     * X = base + random(range)
338
     * We only have the first 256 bit of 1/sqrt(2)
339
     */
340
0
    if (Xin == NULL) {
341
0
        if (bits < BN_num_bits(&ossl_bn_inv_sqrt_2))
342
0
            goto err;
343
0
        if (!BN_lshift(base, &ossl_bn_inv_sqrt_2,
344
0
                       bits - BN_num_bits(&ossl_bn_inv_sqrt_2))
345
0
            || !BN_lshift(range, BN_value_one(), bits)
346
0
            || !BN_sub(range, range, base))
347
0
            goto err;
348
0
    }
349
350
    /*
351
     * (Step 1) GCD(2r1, r2) = 1.
352
     *    Note: This algorithm was doing a gcd(2r1, r2)=1 test before doing an
353
     *    mod_inverse(2r1, r2) which are effectively the same operation.
354
     *    (The algorithm assumed that the gcd test would be faster). Since the
355
     *    mod_inverse is currently faster than calling the constant time
356
     *    BN_gcd(), the call to BN_gcd() has been omitted. The inverse result
357
     *    is used further down.
358
     */
359
0
    if (!(BN_lshift1(r1x2, r1)
360
0
            && (BN_mod_inverse(tmp, r1x2, r2, ctx) != NULL)
361
            /* (Step 2) R = ((r2^-1 mod 2r1) * r2) - ((2r1^-1 mod r2)*2r1) */
362
0
            && (BN_mod_inverse(R, r2, r1x2, ctx) != NULL)
363
0
            && BN_mul(R, R, r2, ctx) /* R = (r2^-1 mod 2r1) * r2 */
364
0
            && BN_mul(tmp, tmp, r1x2, ctx) /* tmp = (2r1^-1 mod r2)*2r1 */
365
0
            && BN_sub(R, R, tmp)
366
            /* Calculate 2r1r2 */
367
0
            && BN_mul(r1r2x2, r1x2, r2, ctx)))
368
0
        goto err;
369
    /* Make positive by adding the modulus */
370
0
    if (BN_is_negative(R) && !BN_add(R, R, r1r2x2))
371
0
        goto err;
372
373
0
    if (c == 0) {
374
0
        r1r2x2_step = r1r2x2;
375
0
    } else {
376
0
        if (!BN_lshift(r1r2x8, r1r2x2, 2))
377
0
            goto err;
378
0
        r1r2x2_step = r1r2x8;
379
0
    }
380
381
    /*
382
     * In FIPS 186-4 imax was set to 5 * nlen/2.
383
     * Analysis by Allen Roginsky
384
     * (See https://csrc.nist.gov/CSRC/media/Publications/fips/186/4/final/documents/comments-received-fips186-4-december-2015.pdf
385
     * page 68) indicates this has a 1 in 2 million chance of failure.
386
     * The number has been updated to 20 * nlen/2 as used in
387
     * FIPS186-5 Appendix B.9 Step 9.
388
     */
389
0
    rounds = bn_rsa_fips186_5_prime_MR_rounds(nlen);
390
0
    imax = 20 * bits; /* max = 20/2 * nbits */
391
0
    for (;;) {
392
0
        if (Xin == NULL) {
393
            /*
394
             * (Step 3) Choose Random X such that
395
             *    sqrt(2) * 2^(nlen/2-1) <= Random X <= (2^(nlen/2)) - 1.
396
             */
397
0
            if (!BN_priv_rand_range_ex(X, range, 0, ctx) || !BN_add(X, X, base))
398
0
                goto err;
399
0
        }
400
        /* (Step 4) Y = X + ((R - X) mod 2r1r2) */
401
0
        if (!BN_mod_sub(Y, R, X, r1r2x2, ctx) || !BN_add(Y, Y, X))
402
0
            goto err;
403
        /*
404
         * (Step 4.1) If there is an optional requirement that the
405
         * computed prime is equal to c mod 8, then chose the value
406
         * Y, Y + 2r1r2, Y + 4r1r2 OR Y + 6r1r2 that satisfies the requirement.
407
         */
408
0
        if (c != 0) {
409
0
            if (!get_multiple_of_y_congruent_to_cmod8(Y, r1r2x2, c))
410
0
                goto err;
411
0
        }
412
        /* (Step 5) */
413
0
        i = 0;
414
0
        for (;;) {
415
            /* (Step 6) */
416
0
            if (BN_num_bits(Y) > bits) {
417
0
                if (Xin == NULL)
418
0
                    break; /* Randomly Generated X so Go back to Step 3 */
419
0
                else
420
0
                    goto err; /* X is not random so it will always fail */
421
0
            }
422
0
            BN_GENCB_call(cb, 0, 2);
423
424
            /* (Step 7) If GCD(Y-1) == 1 & Y is probably prime then return Y */
425
0
            if (BN_copy(y1, Y) == NULL
426
0
                    || !BN_sub_word(y1, 1))
427
0
                goto err;
428
429
0
            if (BN_are_coprime(y1, e, ctx)) {
430
0
                int rv = ossl_bn_check_generated_prime(Y, rounds, ctx, cb);
431
432
0
                if (rv > 0)
433
0
                    goto end;
434
0
                if (rv < 0)
435
0
                    goto err;
436
0
            }
437
            /* (Step 8-10) */
438
0
            if (++i >= imax) {
439
0
                ERR_raise(ERR_LIB_BN, BN_R_NO_PRIME_CANDIDATE);
440
0
                goto err;
441
0
            }
442
0
            if (!BN_add(Y, Y, r1r2x2_step))
443
0
                goto err;
444
0
        }
445
0
    }
446
0
end:
447
0
    ret = 1;
448
0
    BN_GENCB_call(cb, 3, 0);
449
0
err:
450
0
    BN_clear(y1);
451
0
    BN_CTX_end(ctx);
452
0
    return ret;
453
0
}