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 */
bn_rsa_fips186_5_aux_prime_MR_rounds(int nbits)55 static int bn_rsa_fips186_5_aux_prime_MR_rounds(int nbits)
56 {
57 if (nbits >= 4096)
58 return 44;
59 if (nbits >= 3072)
60 return 41;
61 if (nbits >= 2048)
62 return 38;
63 return 0; /* Error */
64 }
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 */
bn_rsa_fips186_5_prime_MR_rounds(int nbits)70 static int bn_rsa_fips186_5_prime_MR_rounds(int nbits)
71 {
72 if (nbits >= 3072)
73 return 4;
74 if (nbits >= 2048)
75 return 5;
76 return 0; /* Error */
77 }
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 */
bn_rsa_fips186_5_aux_prime_min_size(int nbits)88 static int bn_rsa_fips186_5_aux_prime_min_size(int nbits)
89 {
90 if (nbits >= 4096)
91 return 201;
92 if (nbits >= 3072)
93 return 171;
94 if (nbits >= 2048)
95 return 141;
96 return 0;
97 }
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 */
bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(int nbits)108 static int bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(int nbits)
109 {
110 if (nbits >= 4096)
111 return 2030;
112 if (nbits >= 3072)
113 return 1518;
114 if (nbits >= 2048)
115 return 1007;
116 return 0;
117 }
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 */
bn_rsa_fips186_4_find_aux_prob_prime(const BIGNUM * Xp1,BIGNUM * p1,BN_CTX * ctx,int rounds,BN_GENCB * cb)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 {
137 int ret = 0;
138 int i = 0;
139 int tmp = 0;
140
141 if (BN_copy(p1, Xp1) == NULL)
142 return 0;
143 BN_set_flags(p1, BN_FLG_CONSTTIME);
144
145 /* Find the first odd number >= Xp1 that is probably prime */
146 for (;;) {
147 i++;
148 BN_GENCB_call(cb, 0, i);
149 /* MR test with trial division */
150 tmp = ossl_bn_check_generated_prime(p1, rounds, ctx, cb);
151 if (tmp > 0)
152 break;
153 if (tmp < 0)
154 goto err;
155 /* Get next odd number */
156 if (!BN_add_word(p1, 2))
157 goto err;
158 }
159 BN_GENCB_call(cb, 2, i);
160 ret = 1;
161 err:
162 return ret;
163 }
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 */
ossl_bn_rsa_fips186_4_gen_prob_primes(BIGNUM * p,BIGNUM * Xpout,BIGNUM * p1,BIGNUM * p2,const BIGNUM * Xp,const BIGNUM * Xp1,const BIGNUM * Xp2,int nlen,const BIGNUM * e,BN_CTX * ctx,BN_GENCB * cb)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 {
191 int ret = 0;
192 BIGNUM *p1i = NULL, *p2i = NULL, *Xp1i = NULL, *Xp2i = NULL;
193 int bitlen, rounds;
194
195 if (p == NULL || Xpout == NULL)
196 return 0;
197
198 BN_CTX_start(ctx);
199
200 p1i = (p1 != NULL) ? p1 : BN_CTX_get(ctx);
201 p2i = (p2 != NULL) ? p2 : BN_CTX_get(ctx);
202 Xp1i = (Xp1 != NULL) ? (BIGNUM *)Xp1 : BN_CTX_get(ctx);
203 Xp2i = (Xp2 != NULL) ? (BIGNUM *)Xp2 : BN_CTX_get(ctx);
204 if (p1i == NULL || p2i == NULL || Xp1i == NULL || Xp2i == NULL)
205 goto err;
206
207 bitlen = bn_rsa_fips186_5_aux_prime_min_size(nlen);
208 if (bitlen == 0)
209 goto err;
210 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 if (Xp1 == NULL) {
214 /* Set the top and bottom bits to make it odd and the correct size */
215 if (!BN_priv_rand_ex(Xp1i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD,
216 0, ctx))
217 goto err;
218 }
219 /* (Steps 4.1/5.1): Randomly generate Xp2 if it is not passed in */
220 if (Xp2 == NULL) {
221 /* Set the top and bottom bits to make it odd and the correct size */
222 if (!BN_priv_rand_ex(Xp2i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD,
223 0, ctx))
224 goto err;
225 }
226
227 /* (Steps 4.2/5.2) - find first auxiliary probable primes */
228 if (!bn_rsa_fips186_4_find_aux_prob_prime(Xp1i, p1i, ctx, rounds, cb)
229 || !bn_rsa_fips186_4_find_aux_prob_prime(Xp2i, p2i, ctx, rounds, cb))
230 goto err;
231 /* (Table B.1) auxiliary prime Max length check */
232 if ((BN_num_bits(p1i) + BN_num_bits(p2i)) >=
233 bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(nlen))
234 goto err;
235 /* (Steps 4.3/5.3) - generate prime */
236 if (!ossl_bn_rsa_fips186_4_derive_prime(p, Xpout, Xp, p1i, p2i, nlen, e,
237 ctx, cb))
238 goto err;
239 ret = 1;
240 err:
241 /* Zeroize any internally generated values that are not returned */
242 if (p1 == NULL)
243 BN_clear(p1i);
244 if (p2 == NULL)
245 BN_clear(p2i);
246 if (Xp1 == NULL)
247 BN_clear(Xp1i);
248 if (Xp2 == NULL)
249 BN_clear(Xp2i);
250 BN_CTX_end(ctx);
251 return ret;
252 }
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 */
ossl_bn_rsa_fips186_4_derive_prime(BIGNUM * Y,BIGNUM * X,const BIGNUM * Xin,const BIGNUM * r1,const BIGNUM * r2,int nlen,const BIGNUM * e,BN_CTX * ctx,BN_GENCB * cb)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 {
280 int ret = 0;
281 int i, imax, rounds;
282 int bits = nlen >> 1;
283 BIGNUM *tmp, *R, *r1r2x2, *y1, *r1x2;
284 BIGNUM *base, *range;
285
286 BN_CTX_start(ctx);
287
288 base = BN_CTX_get(ctx);
289 range = BN_CTX_get(ctx);
290 R = BN_CTX_get(ctx);
291 tmp = BN_CTX_get(ctx);
292 r1r2x2 = BN_CTX_get(ctx);
293 y1 = BN_CTX_get(ctx);
294 r1x2 = BN_CTX_get(ctx);
295 if (r1x2 == NULL)
296 goto err;
297
298 if (Xin != NULL && BN_copy(X, Xin) == NULL)
299 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 if (Xin == NULL) {
311 if (bits < BN_num_bits(&ossl_bn_inv_sqrt_2))
312 goto err;
313 if (!BN_lshift(base, &ossl_bn_inv_sqrt_2,
314 bits - BN_num_bits(&ossl_bn_inv_sqrt_2))
315 || !BN_lshift(range, BN_value_one(), bits)
316 || !BN_sub(range, range, base))
317 goto err;
318 }
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 if (!(BN_lshift1(r1x2, r1)
330 && (BN_mod_inverse(tmp, r1x2, r2, ctx) != NULL)
331 /* (Step 2) R = ((r2^-1 mod 2r1) * r2) - ((2r1^-1 mod r2)*2r1) */
332 && (BN_mod_inverse(R, r2, r1x2, ctx) != NULL)
333 && BN_mul(R, R, r2, ctx) /* R = (r2^-1 mod 2r1) * r2 */
334 && BN_mul(tmp, tmp, r1x2, ctx) /* tmp = (2r1^-1 mod r2)*2r1 */
335 && BN_sub(R, R, tmp)
336 /* Calculate 2r1r2 */
337 && BN_mul(r1r2x2, r1x2, r2, ctx)))
338 goto err;
339 /* Make positive by adding the modulus */
340 if (BN_is_negative(R) && !BN_add(R, R, r1r2x2))
341 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 rounds = bn_rsa_fips186_5_prime_MR_rounds(nlen);
352 imax = 20 * bits; /* max = 20/2 * nbits */
353 for (;;) {
354 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 if (!BN_priv_rand_range_ex(X, range, 0, ctx) || !BN_add(X, X, base))
360 goto err;
361 }
362 /* (Step 4) Y = X + ((R - X) mod 2r1r2) */
363 if (!BN_mod_sub(Y, R, X, r1r2x2, ctx) || !BN_add(Y, Y, X))
364 goto err;
365 /* (Step 5) */
366 i = 0;
367 for (;;) {
368 /* (Step 6) */
369 if (BN_num_bits(Y) > bits) {
370 if (Xin == NULL)
371 break; /* Randomly Generated X so Go back to Step 3 */
372 else
373 goto err; /* X is not random so it will always fail */
374 }
375 BN_GENCB_call(cb, 0, 2);
376
377 /* (Step 7) If GCD(Y-1) == 1 & Y is probably prime then return Y */
378 if (BN_copy(y1, Y) == NULL
379 || !BN_sub_word(y1, 1))
380 goto err;
381
382 if (BN_are_coprime(y1, e, ctx)) {
383 int rv = ossl_bn_check_generated_prime(Y, rounds, ctx, cb);
384
385 if (rv > 0)
386 goto end;
387 if (rv < 0)
388 goto err;
389 }
390 /* (Step 8-10) */
391 if (++i >= imax) {
392 ERR_raise(ERR_LIB_BN, BN_R_NO_PRIME_CANDIDATE);
393 goto err;
394 }
395 if (!BN_add(Y, Y, r1r2x2))
396 goto err;
397 }
398 }
399 end:
400 ret = 1;
401 BN_GENCB_call(cb, 3, 0);
402 err:
403 BN_clear(y1);
404 BN_CTX_end(ctx);
405 return ret;
406 }
407