Coverage Report

Created: 2025-06-13 06:36

/src/openssl/crypto/bn/bn_rsa_fips186_4.c
Line
Count
Source (jump to first uncovered line)
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
 * Returns:
106
 *     The maximum length or 0 if nbits is invalid.
107
 */
108
static int bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(int nbits)
109
0
{
110
0
    if (nbits >= 4096)
111
0
        return 2030;
112
0
    if (nbits >= 3072)
113
0
        return 1518;
114
0
    if (nbits >= 2048)
115
0
        return 1007;
116
0
    return 0;
117
0
}
118
119
/*
120
 * Find the first odd integer that is a probable prime.
121
 *
122
 * See section FIPS 186-4 B.3.6 (Steps 4.2/5.2).
123
 *
124
 * Params:
125
 *     Xp1 The passed in starting point to find a probably prime.
126
 *     p1 The returned probable prime (first odd integer >= Xp1)
127
 *     ctx A BN_CTX object.
128
 *     rounds The number of Miller Rabin rounds
129
 *     cb An optional BIGNUM callback.
130
 * Returns: 1 on success otherwise it returns 0.
131
 */
132
static int bn_rsa_fips186_4_find_aux_prob_prime(const BIGNUM *Xp1,
133
                                                BIGNUM *p1, BN_CTX *ctx,
134
                                                int rounds,
135
                                                BN_GENCB *cb)
136
0
{
137
0
    int ret = 0;
138
0
    int i = 0;
139
0
    int tmp = 0;
140
141
0
    if (BN_copy(p1, Xp1) == NULL)
142
0
        return 0;
143
0
    BN_set_flags(p1, BN_FLG_CONSTTIME);
144
145
    /* Find the first odd number >= Xp1 that is probably prime */
146
0
    for (;;) {
147
0
        i++;
148
0
        BN_GENCB_call(cb, 0, i);
149
        /* MR test with trial division */
150
0
        tmp = ossl_bn_check_generated_prime(p1, rounds, ctx, cb);
151
0
        if (tmp > 0)
152
0
            break;
153
0
        if (tmp < 0)
154
0
            goto err;
155
        /* Get next odd number */
156
0
        if (!BN_add_word(p1, 2))
157
0
            goto err;
158
0
    }
159
0
    BN_GENCB_call(cb, 2, i);
160
0
    ret = 1;
161
0
err:
162
0
    return ret;
163
0
}
164
165
/*
166
 * Generate a probable prime (p or q).
167
 *
168
 * See FIPS 186-4 B.3.6 (Steps 4 & 5)
169
 *
170
 * Params:
171
 *     p The returned probable prime.
172
 *     Xpout An optionally returned random number used during generation of p.
173
 *     p1, p2 The returned auxiliary primes. If NULL they are not returned.
174
 *     Xp An optional passed in value (that is random number used during
175
 *        generation of p).
176
 *     Xp1, Xp2 Optional passed in values that are normally generated
177
 *              internally. Used to find p1, p2.
178
 *     nlen The bit length of the modulus (the key size).
179
 *     e The public exponent.
180
 *     ctx A BN_CTX object.
181
 *     cb An optional BIGNUM callback.
182
 * Returns: 1 on success otherwise it returns 0.
183
 */
184
int ossl_bn_rsa_fips186_4_gen_prob_primes(BIGNUM *p, BIGNUM *Xpout,
185
                                          BIGNUM *p1, BIGNUM *p2,
186
                                          const BIGNUM *Xp, const BIGNUM *Xp1,
187
                                          const BIGNUM *Xp2, int nlen,
188
                                          const BIGNUM *e, BN_CTX *ctx,
189
                                          BN_GENCB *cb)
190
0
{
191
0
    int ret = 0;
192
0
    BIGNUM *p1i = NULL, *p2i = NULL, *Xp1i = NULL, *Xp2i = NULL;
193
0
    int bitlen, rounds;
194
195
0
    if (p == NULL || Xpout == NULL)
196
0
        return 0;
197
198
0
    BN_CTX_start(ctx);
199
200
0
    p1i = (p1 != NULL) ? p1 : BN_CTX_get(ctx);
201
0
    p2i = (p2 != NULL) ? p2 : BN_CTX_get(ctx);
202
0
    Xp1i = (Xp1 != NULL) ? (BIGNUM *)Xp1 : BN_CTX_get(ctx);
203
0
    Xp2i = (Xp2 != NULL) ? (BIGNUM *)Xp2 : BN_CTX_get(ctx);
204
0
    if (p1i == NULL || p2i == NULL || Xp1i == NULL || Xp2i == NULL)
205
0
        goto err;
206
207
0
    bitlen = bn_rsa_fips186_5_aux_prime_min_size(nlen);
208
0
    if (bitlen == 0)
209
0
        goto err;
210
0
    rounds = bn_rsa_fips186_5_aux_prime_MR_rounds(nlen);
211
212
    /* (Steps 4.1/5.1): Randomly generate Xp1 if it is not passed in */
213
0
    if (Xp1 == NULL) {
214
        /* Set the top and bottom bits to make it odd and the correct size */
215
0
        if (!BN_priv_rand_ex(Xp1i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD,
216
0
                             0, ctx))
217
0
            goto err;
218
0
    }
219
    /* (Steps 4.1/5.1): Randomly generate Xp2 if it is not passed in */
220
0
    if (Xp2 == NULL) {
221
        /* Set the top and bottom bits to make it odd and the correct size */
222
0
        if (!BN_priv_rand_ex(Xp2i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD,
223
0
                             0, ctx))
224
0
            goto err;
225
0
    }
226
227
    /* (Steps 4.2/5.2) - find first auxiliary probable primes */
228
0
    if (!bn_rsa_fips186_4_find_aux_prob_prime(Xp1i, p1i, ctx, rounds, cb)
229
0
            || !bn_rsa_fips186_4_find_aux_prob_prime(Xp2i, p2i, ctx, rounds, cb))
230
0
        goto err;
231
    /* (Table B.1) auxiliary prime Max length check */
232
0
    if ((BN_num_bits(p1i) + BN_num_bits(p2i)) >=
233
0
            bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(nlen))
234
0
        goto err;
235
    /* (Steps 4.3/5.3) - generate prime */
236
0
    if (!ossl_bn_rsa_fips186_4_derive_prime(p, Xpout, Xp, p1i, p2i, nlen, e,
237
0
                                            ctx, cb))
238
0
        goto err;
239
0
    ret = 1;
240
0
err:
241
    /* Zeroize any internally generated values that are not returned */
242
0
    if (p1 == NULL)
243
0
        BN_clear(p1i);
244
0
    if (p2 == NULL)
245
0
        BN_clear(p2i);
246
0
    if (Xp1 == NULL)
247
0
        BN_clear(Xp1i);
248
0
    if (Xp2 == NULL)
249
0
        BN_clear(Xp2i);
250
0
    BN_CTX_end(ctx);
251
0
    return ret;
252
0
}
253
254
/*
255
 * Constructs a probable prime (a candidate for p or q) using 2 auxiliary
256
 * prime numbers and the Chinese Remainder Theorem.
257
 *
258
 * See FIPS 186-4 C.9 "Compute a Probable Prime Factor Based on Auxiliary
259
 * Primes". Used by FIPS 186-4 B.3.6 Section (4.3) for p and Section (5.3) for q.
260
 *
261
 * Params:
262
 *     Y The returned prime factor (private_prime_factor) of the modulus n.
263
 *     X The returned random number used during generation of the prime factor.
264
 *     Xin An optional passed in value for X used for testing purposes.
265
 *     r1 An auxiliary prime.
266
 *     r2 An auxiliary prime.
267
 *     nlen The desired length of n (the RSA modulus).
268
 *     e The public exponent.
269
 *     ctx A BN_CTX object.
270
 *     cb An optional BIGNUM callback object.
271
 * Returns: 1 on success otherwise it returns 0.
272
 * Assumptions:
273
 *     Y, X, r1, r2, e are not NULL.
274
 */
275
int ossl_bn_rsa_fips186_4_derive_prime(BIGNUM *Y, BIGNUM *X, const BIGNUM *Xin,
276
                                       const BIGNUM *r1, const BIGNUM *r2,
277
                                       int nlen, const BIGNUM *e,
278
                                       BN_CTX *ctx, BN_GENCB *cb)
279
0
{
280
0
    int ret = 0;
281
0
    int i, imax, rounds;
282
0
    int bits = nlen >> 1;
283
0
    BIGNUM *tmp, *R, *r1r2x2, *y1, *r1x2;
284
0
    BIGNUM *base, *range;
285
286
0
    BN_CTX_start(ctx);
287
288
0
    base = BN_CTX_get(ctx);
289
0
    range = BN_CTX_get(ctx);
290
0
    R = BN_CTX_get(ctx);
291
0
    tmp = BN_CTX_get(ctx);
292
0
    r1r2x2 = BN_CTX_get(ctx);
293
0
    y1 = BN_CTX_get(ctx);
294
0
    r1x2 = BN_CTX_get(ctx);
295
0
    if (r1x2 == NULL)
296
0
        goto err;
297
298
0
    if (Xin != NULL && BN_copy(X, Xin) == NULL)
299
0
        goto err;
300
301
    /*
302
     * We need to generate a random number X in the range
303
     * 1/sqrt(2) * 2^(nlen/2) <= X < 2^(nlen/2).
304
     * We can rewrite that as:
305
     * base = 1/sqrt(2) * 2^(nlen/2)
306
     * range = ((2^(nlen/2))) - (1/sqrt(2) * 2^(nlen/2))
307
     * X = base + random(range)
308
     * We only have the first 256 bit of 1/sqrt(2)
309
     */
310
0
    if (Xin == NULL) {
311
0
        if (bits < BN_num_bits(&ossl_bn_inv_sqrt_2))
312
0
            goto err;
313
0
        if (!BN_lshift(base, &ossl_bn_inv_sqrt_2,
314
0
                       bits - BN_num_bits(&ossl_bn_inv_sqrt_2))
315
0
            || !BN_lshift(range, BN_value_one(), bits)
316
0
            || !BN_sub(range, range, base))
317
0
            goto err;
318
0
    }
319
320
    /*
321
     * (Step 1) GCD(2r1, r2) = 1.
322
     *    Note: This algorithm was doing a gcd(2r1, r2)=1 test before doing an
323
     *    mod_inverse(2r1, r2) which are effectively the same operation.
324
     *    (The algorithm assumed that the gcd test would be faster). Since the
325
     *    mod_inverse is currently faster than calling the constant time
326
     *    BN_gcd(), the call to BN_gcd() has been omitted. The inverse result
327
     *    is used further down.
328
     */
329
0
    if (!(BN_lshift1(r1x2, r1)
330
0
            && (BN_mod_inverse(tmp, r1x2, r2, ctx) != NULL)
331
            /* (Step 2) R = ((r2^-1 mod 2r1) * r2) - ((2r1^-1 mod r2)*2r1) */
332
0
            && (BN_mod_inverse(R, r2, r1x2, ctx) != NULL)
333
0
            && BN_mul(R, R, r2, ctx) /* R = (r2^-1 mod 2r1) * r2 */
334
0
            && BN_mul(tmp, tmp, r1x2, ctx) /* tmp = (2r1^-1 mod r2)*2r1 */
335
0
            && BN_sub(R, R, tmp)
336
            /* Calculate 2r1r2 */
337
0
            && BN_mul(r1r2x2, r1x2, r2, ctx)))
338
0
        goto err;
339
    /* Make positive by adding the modulus */
340
0
    if (BN_is_negative(R) && !BN_add(R, R, r1r2x2))
341
0
        goto err;
342
343
    /*
344
     * In FIPS 186-4 imax was set to 5 * nlen/2.
345
     * Analysis by Allen Roginsky
346
     * (See https://csrc.nist.gov/CSRC/media/Publications/fips/186/4/final/documents/comments-received-fips186-4-december-2015.pdf
347
     * page 68) indicates this has a 1 in 2 million chance of failure.
348
     * The number has been updated to 20 * nlen/2 as used in
349
     * FIPS186-5 Appendix B.9 Step 9.
350
     */
351
0
    rounds = bn_rsa_fips186_5_prime_MR_rounds(nlen);
352
0
    imax = 20 * bits; /* max = 20/2 * nbits */
353
0
    for (;;) {
354
0
        if (Xin == NULL) {
355
            /*
356
             * (Step 3) Choose Random X such that
357
             *    sqrt(2) * 2^(nlen/2-1) <= Random X <= (2^(nlen/2)) - 1.
358
             */
359
0
            if (!BN_priv_rand_range_ex(X, range, 0, ctx) || !BN_add(X, X, base))
360
0
                goto err;
361
0
        }
362
        /* (Step 4) Y = X + ((R - X) mod 2r1r2) */
363
0
        if (!BN_mod_sub(Y, R, X, r1r2x2, ctx) || !BN_add(Y, Y, X))
364
0
            goto err;
365
        /* (Step 5) */
366
0
        i = 0;
367
0
        for (;;) {
368
            /* (Step 6) */
369
0
            if (BN_num_bits(Y) > bits) {
370
0
                if (Xin == NULL)
371
0
                    break; /* Randomly Generated X so Go back to Step 3 */
372
0
                else
373
0
                    goto err; /* X is not random so it will always fail */
374
0
            }
375
0
            BN_GENCB_call(cb, 0, 2);
376
377
            /* (Step 7) If GCD(Y-1) == 1 & Y is probably prime then return Y */
378
0
            if (BN_copy(y1, Y) == NULL
379
0
                    || !BN_sub_word(y1, 1))
380
0
                goto err;
381
382
0
            if (BN_are_coprime(y1, e, ctx)) {
383
0
                int rv = ossl_bn_check_generated_prime(Y, rounds, ctx, cb);
384
385
0
                if (rv > 0)
386
0
                    goto end;
387
0
                if (rv < 0)
388
0
                    goto err;
389
0
            }
390
            /* (Step 8-10) */
391
0
            if (++i >= imax) {
392
0
                ERR_raise(ERR_LIB_BN, BN_R_NO_PRIME_CANDIDATE);
393
0
                goto err;
394
0
            }
395
0
            if (!BN_add(Y, Y, r1r2x2))
396
0
                goto err;
397
0
        }
398
0
    }
399
0
end:
400
0
    ret = 1;
401
0
    BN_GENCB_call(cb, 3, 0);
402
0
err:
403
0
    BN_clear(y1);
404
0
    BN_CTX_end(ctx);
405
0
    return ret;
406
0
}