FIPS 186-4 RSA Generation & Validation
[openssl.git] / crypto / bn / bn_prime.c
1 /*
2  * Copyright 1995-2019 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 #include <stdio.h>
11 #include <time.h>
12 #include "internal/cryptlib.h"
13 #include "bn_lcl.h"
14
15 /*
16  * The quick sieve algorithm approach to weeding out primes is Philip
17  * Zimmermann's, as implemented in PGP.  I have had a read of his comments
18  * and implemented my own version.
19  */
20 #include "bn_prime.h"
21
22 static int probable_prime(BIGNUM *rnd, int bits, prime_t *mods);
23 static int probable_prime_dh_safe(BIGNUM *rnd, int bits,
24                                   const BIGNUM *add, const BIGNUM *rem,
25                                   BN_CTX *ctx);
26
27 #if BN_BITS2 == 64
28 # define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo
29 #else
30 # define BN_DEF(lo, hi) lo, hi
31 #endif
32
33 /*
34  * See SP800 89 5.3.3 (Step f)
35  * The product of the set of primes ranging from 3 to 751
36  * Generated using process in test/bn_internal_test.c test_bn_small_factors().
37  * This includes 751 (which is not currently included in SP 800-89).
38  */
39 static const BN_ULONG small_prime_factors[] = {
40     BN_DEF(0x3ef4e3e1, 0xc4309333), BN_DEF(0xcd2d655f, 0x71161eb6),
41     BN_DEF(0x0bf94862, 0x95e2238c), BN_DEF(0x24f7912b, 0x3eb233d3),
42     BN_DEF(0xbf26c483, 0x6b55514b), BN_DEF(0x5a144871, 0x0a84d817),
43     BN_DEF(0x9b82210a, 0x77d12fee), BN_DEF(0x97f050b3, 0xdb5b93c2),
44     BN_DEF(0x4d6c026b, 0x4acad6b9), BN_DEF(0x54aec893, 0xeb7751f3),
45     BN_DEF(0x36bc85c4, 0xdba53368), BN_DEF(0x7f5ec78e, 0xd85a1b28),
46     BN_DEF(0x6b322244, 0x2eb072d8), BN_DEF(0x5e2b3aea, 0xbba51112),
47     BN_DEF(0x0e2486bf, 0x36ed1a6c), BN_DEF(0xec0c5727, 0x5f270460),
48     (BN_ULONG)0x000017b1
49 };
50
51 #define BN_SMALL_PRIME_FACTORS_TOP OSSL_NELEM(small_prime_factors)
52 static const BIGNUM _bignum_small_prime_factors = {
53     (BN_ULONG *)small_prime_factors,
54     BN_SMALL_PRIME_FACTORS_TOP,
55     BN_SMALL_PRIME_FACTORS_TOP,
56     0,
57     BN_FLG_STATIC_DATA
58 };
59
60 const BIGNUM *bn_get0_small_factors(void)
61 {
62     return &_bignum_small_prime_factors;
63 }
64
65 int BN_GENCB_call(BN_GENCB *cb, int a, int b)
66 {
67     /* No callback means continue */
68     if (!cb)
69         return 1;
70     switch (cb->ver) {
71     case 1:
72         /* Deprecated-style callbacks */
73         if (!cb->cb.cb_1)
74             return 1;
75         cb->cb.cb_1(a, b, cb->arg);
76         return 1;
77     case 2:
78         /* New-style callbacks */
79         return cb->cb.cb_2(a, b, cb);
80     default:
81         break;
82     }
83     /* Unrecognised callback type */
84     return 0;
85 }
86
87 int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe,
88                          const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb)
89 {
90     BIGNUM *t;
91     int found = 0;
92     int i, j, c1 = 0;
93     BN_CTX *ctx = NULL;
94     prime_t *mods = NULL;
95     int checks = BN_prime_checks_for_size(bits);
96
97     if (bits < 2) {
98         /* There are no prime numbers this small. */
99         BNerr(BN_F_BN_GENERATE_PRIME_EX, BN_R_BITS_TOO_SMALL);
100         return 0;
101     } else if (bits == 2 && safe) {
102         /* The smallest safe prime (7) is three bits. */
103         BNerr(BN_F_BN_GENERATE_PRIME_EX, BN_R_BITS_TOO_SMALL);
104         return 0;
105     }
106
107     mods = OPENSSL_zalloc(sizeof(*mods) * NUMPRIMES);
108     if (mods == NULL)
109         goto err;
110
111     ctx = BN_CTX_new();
112     if (ctx == NULL)
113         goto err;
114     BN_CTX_start(ctx);
115     t = BN_CTX_get(ctx);
116     if (t == NULL)
117         goto err;
118  loop:
119     /* make a random number and set the top and bottom bits */
120     if (add == NULL) {
121         if (!probable_prime(ret, bits, mods))
122             goto err;
123     } else {
124         if (safe) {
125             if (!probable_prime_dh_safe(ret, bits, add, rem, ctx))
126                 goto err;
127         } else {
128             if (!bn_probable_prime_dh(ret, bits, add, rem, ctx))
129                 goto err;
130         }
131     }
132
133     if (!BN_GENCB_call(cb, 0, c1++))
134         /* aborted */
135         goto err;
136
137     if (!safe) {
138         i = BN_is_prime_fasttest_ex(ret, checks, ctx, 0, cb);
139         if (i == -1)
140             goto err;
141         if (i == 0)
142             goto loop;
143     } else {
144         /*
145          * for "safe prime" generation, check that (p-1)/2 is prime. Since a
146          * prime is odd, We just need to divide by 2
147          */
148         if (!BN_rshift1(t, ret))
149             goto err;
150
151         for (i = 0; i < checks; i++) {
152             j = BN_is_prime_fasttest_ex(ret, 1, ctx, 0, cb);
153             if (j == -1)
154                 goto err;
155             if (j == 0)
156                 goto loop;
157
158             j = BN_is_prime_fasttest_ex(t, 1, ctx, 0, cb);
159             if (j == -1)
160                 goto err;
161             if (j == 0)
162                 goto loop;
163
164             if (!BN_GENCB_call(cb, 2, c1 - 1))
165                 goto err;
166             /* We have a safe prime test pass */
167         }
168     }
169     /* we have a prime :-) */
170     found = 1;
171  err:
172     OPENSSL_free(mods);
173     if (ctx != NULL)
174         BN_CTX_end(ctx);
175     BN_CTX_free(ctx);
176     bn_check_top(ret);
177     return found;
178 }
179
180 int BN_is_prime_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed,
181                    BN_GENCB *cb)
182 {
183     return BN_is_prime_fasttest_ex(a, checks, ctx_passed, 0, cb);
184 }
185
186 /* See FIPS 186-4 C.3.1 Miller Rabin Probabilistic Primality Test. */
187 int BN_is_prime_fasttest_ex(const BIGNUM *w, int checks, BN_CTX *ctx_passed,
188                             int do_trial_division, BN_GENCB *cb)
189 {
190     int i, status, ret = -1;
191     BN_CTX *ctx = NULL;
192
193     /* w must be bigger than 1 */
194     if (BN_cmp(w, BN_value_one()) <= 0)
195         return 0;
196
197     /* w must be odd */
198     if (BN_is_odd(w)) {
199         /* Take care of the really small prime 3 */
200         if (BN_is_word(w, 3))
201             return 1;
202     } else {
203         /* 2 is the only even prime */
204         return BN_is_word(w, 2);
205     }
206
207     /* first look for small factors */
208     if (do_trial_division) {
209         for (i = 1; i < NUMPRIMES; i++) {
210             BN_ULONG mod = BN_mod_word(w, primes[i]);
211             if (mod == (BN_ULONG)-1)
212                 return -1;
213             if (mod == 0)
214                 return BN_is_word(w, primes[i]);
215         }
216         if (!BN_GENCB_call(cb, 1, -1))
217             return -1;
218     }
219     if (ctx_passed != NULL)
220         ctx = ctx_passed;
221     else if ((ctx = BN_CTX_new()) == NULL)
222         goto err;
223
224     ret = bn_miller_rabin_is_prime(w, checks, ctx, cb, 0, &status);
225     if (!ret)
226         goto err;
227     ret = (status == BN_PRIMETEST_PROBABLY_PRIME);
228 err:
229     if (ctx_passed == NULL)
230         BN_CTX_free(ctx);
231     return ret;
232 }
233
234 /*
235  * Refer to FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test.
236  * OR C.3.1 Miller-Rabin Probabilistic Primality Test (if enhanced is zero).
237  * The Step numbers listed in the code refer to the enhanced case.
238  *
239  * if enhanced is set, then status returns one of the following:
240  *     BN_PRIMETEST_PROBABLY_PRIME
241  *     BN_PRIMETEST_COMPOSITE_WITH_FACTOR
242  *     BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME
243  * if enhanced is zero, then status returns either
244  *     BN_PRIMETEST_PROBABLY_PRIME or
245  *     BN_PRIMETEST_COMPOSITE
246  *
247  * returns 0 if there was an error, otherwise it returns 1.
248  */
249 int bn_miller_rabin_is_prime(const BIGNUM *w, int iterations, BN_CTX *ctx,
250                              BN_GENCB *cb, int enhanced, int *status)
251 {
252     int i, j, a, ret = 0;
253     BIGNUM *g, *w1, *w3, *x, *m, *z, *b;
254     BN_MONT_CTX *mont = NULL;
255
256     /* w must be odd */
257     if (!BN_is_odd(w))
258         return 0;
259
260     BN_CTX_start(ctx);
261     g = BN_CTX_get(ctx);
262     w1 = BN_CTX_get(ctx);
263     w3 = BN_CTX_get(ctx);
264     x = BN_CTX_get(ctx);
265     m = BN_CTX_get(ctx);
266     z = BN_CTX_get(ctx);
267     b = BN_CTX_get(ctx);
268
269     if (!(b != NULL
270             /* w1 := w - 1 */
271             && BN_copy(w1, w)
272             && BN_sub_word(w1, 1)
273             /* w3 := w - 3 */
274             && BN_copy(w3, w)
275             && BN_sub_word(w3, 3)))
276         goto err;
277
278     /* check w is larger than 3, otherwise the random b will be too small */
279     if (BN_is_zero(w3) || BN_is_negative(w3))
280         goto err;
281
282     /* (Step 1) Calculate largest integer 'a' such that 2^a divides w-1 */
283     a = 1;
284     while (!BN_is_bit_set(w1, a))
285         a++;
286     /* (Step 2) m = (w-1) / 2^a */
287     if (!BN_rshift(m, w1, a))
288         goto err;
289
290     /* Montgomery setup for computations mod a */
291     mont = BN_MONT_CTX_new();
292     if (mont == NULL || !BN_MONT_CTX_set(mont, w, ctx))
293         goto err;
294
295     if (iterations == BN_prime_checks)
296         iterations = BN_prime_checks_for_size(BN_num_bits(w));
297
298     /* (Step 4) */
299     for (i = 0; i < iterations; ++i) {
300         /* (Step 4.1) obtain a Random string of bits b where 1 < b < w-1 */
301         if (!BN_priv_rand_range(b, w3) || !BN_add_word(b, 2)) /* 1 < b < w-1 */
302             goto err;
303
304         if (enhanced) {
305             /* (Step 4.3) */
306             if (!BN_gcd(g, b, w, ctx))
307                 goto err;
308             /* (Step 4.4) */
309             if (!BN_is_one(g)) {
310                 *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR;
311                 ret = 1;
312                 goto err;
313             }
314         }
315         /* (Step 4.5) z = b^m mod w */
316         if (!BN_mod_exp_mont(z, b, m, w, ctx, mont))
317             goto err;
318         /* (Step 4.6) if (z = 1 or z = w-1) */
319         if (BN_is_one(z) || BN_cmp(z, w1) == 0)
320             goto outer_loop;
321         /* (Step 4.7) for j = 1 to a-1 */
322         for (j = 1; j < a ; ++j) {
323             /* (Step 4.7.1 - 4.7.2) x = z. z = x^2 mod w */
324             if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx))
325                 goto err;
326             /* (Step 4.7.3) */
327             if (BN_cmp(z, w1) == 0)
328                 goto outer_loop;
329             /* (Step 4.7.4) */
330             if (BN_is_one(z))
331                 goto composite;
332         }
333         if (!BN_GENCB_call(cb, 1, i))
334             goto err;
335         /* At this point z = b^((w-1)/2) mod w */
336         /* (Steps 4.8 - 4.9) x = z, z = x^2 mod w */
337         if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx))
338             goto err;
339         /* (Step 4.10) */
340         if (BN_is_one(z))
341             goto composite;
342         /* (Step 4.11) x = b^(w-1) mod w */
343         if (!BN_copy(x, z))
344             goto err;
345 composite:
346         if (enhanced) {
347             /* (Step 4.1.2) g = GCD(x-1, w) */
348             if (!BN_sub_word(x, 1) || !BN_gcd(g, x, w, ctx))
349                 goto err;
350             /* (Steps 4.1.3 - 4.1.4) */
351             if (BN_is_one(g))
352                 *status = BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME;
353             else
354                 *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR;
355         } else {
356             *status = BN_PRIMETEST_COMPOSITE;
357         }
358         ret = 1;
359         goto err;
360 outer_loop: ;
361         /* (Step 4.1.5) */
362     }
363     /* (Step 5) */
364     *status = BN_PRIMETEST_PROBABLY_PRIME;
365     ret = 1;
366 err:
367     BN_clear(g);
368     BN_clear(w1);
369     BN_clear(w3);
370     BN_clear(x);
371     BN_clear(m);
372     BN_clear(z);
373     BN_clear(b);
374     BN_CTX_end(ctx);
375     BN_MONT_CTX_free(mont);
376     return ret;
377 }
378
379 static int probable_prime(BIGNUM *rnd, int bits, prime_t *mods)
380 {
381     int i;
382     BN_ULONG delta;
383     BN_ULONG maxdelta = BN_MASK2 - primes[NUMPRIMES - 1];
384     char is_single_word = bits <= BN_BITS2;
385
386  again:
387     /* TODO: Not all primes are private */
388     if (!BN_priv_rand(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD))
389         return 0;
390     /* we now have a random number 'rnd' to test. */
391     for (i = 1; i < NUMPRIMES; i++) {
392         BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]);
393         if (mod == (BN_ULONG)-1)
394             return 0;
395         mods[i] = (prime_t) mod;
396     }
397     /*
398      * If bits is so small that it fits into a single word then we
399      * additionally don't want to exceed that many bits.
400      */
401     if (is_single_word) {
402         BN_ULONG size_limit;
403
404         if (bits == BN_BITS2) {
405             /*
406              * Shifting by this much has undefined behaviour so we do it a
407              * different way
408              */
409             size_limit = ~((BN_ULONG)0) - BN_get_word(rnd);
410         } else {
411             size_limit = (((BN_ULONG)1) << bits) - BN_get_word(rnd) - 1;
412         }
413         if (size_limit < maxdelta)
414             maxdelta = size_limit;
415     }
416     delta = 0;
417  loop:
418     if (is_single_word) {
419         BN_ULONG rnd_word = BN_get_word(rnd);
420
421         /*-
422          * In the case that the candidate prime is a single word then
423          * we check that:
424          *   1) It's greater than primes[i] because we shouldn't reject
425          *      3 as being a prime number because it's a multiple of
426          *      three.
427          *   2) That it's not a multiple of a known prime. We don't
428          *      check that rnd-1 is also coprime to all the known
429          *      primes because there aren't many small primes where
430          *      that's true.
431          */
432         for (i = 1; i < NUMPRIMES && primes[i] < rnd_word; i++) {
433             if ((mods[i] + delta) % primes[i] == 0) {
434                 delta += 2;
435                 if (delta > maxdelta)
436                     goto again;
437                 goto loop;
438             }
439         }
440     } else {
441         for (i = 1; i < NUMPRIMES; i++) {
442             /*
443              * check that rnd is not a prime and also that gcd(rnd-1,primes)
444              * == 1 (except for 2)
445              */
446             if (((mods[i] + delta) % primes[i]) <= 1) {
447                 delta += 2;
448                 if (delta > maxdelta)
449                     goto again;
450                 goto loop;
451             }
452         }
453     }
454     if (!BN_add_word(rnd, delta))
455         return 0;
456     if (BN_num_bits(rnd) != bits)
457         goto again;
458     bn_check_top(rnd);
459     return 1;
460 }
461
462 int bn_probable_prime_dh(BIGNUM *rnd, int bits,
463                          const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx)
464 {
465     int i, ret = 0;
466     BIGNUM *t1;
467
468     BN_CTX_start(ctx);
469     if ((t1 = BN_CTX_get(ctx)) == NULL)
470         goto err;
471
472     if (!BN_rand(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD))
473         goto err;
474
475     /* we need ((rnd-rem) % add) == 0 */
476
477     if (!BN_mod(t1, rnd, add, ctx))
478         goto err;
479     if (!BN_sub(rnd, rnd, t1))
480         goto err;
481     if (rem == NULL) {
482         if (!BN_add_word(rnd, 1))
483             goto err;
484     } else {
485         if (!BN_add(rnd, rnd, rem))
486             goto err;
487     }
488
489     /* we now have a random number 'rand' to test. */
490
491  loop:
492     for (i = 1; i < NUMPRIMES; i++) {
493         /* check that rnd is a prime */
494         BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]);
495         if (mod == (BN_ULONG)-1)
496             goto err;
497         if (mod <= 1) {
498             if (!BN_add(rnd, rnd, add))
499                 goto err;
500             goto loop;
501         }
502     }
503     ret = 1;
504
505  err:
506     BN_CTX_end(ctx);
507     bn_check_top(rnd);
508     return ret;
509 }
510
511 static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd,
512                                   const BIGNUM *rem, BN_CTX *ctx)
513 {
514     int i, ret = 0;
515     BIGNUM *t1, *qadd, *q;
516
517     bits--;
518     BN_CTX_start(ctx);
519     t1 = BN_CTX_get(ctx);
520     q = BN_CTX_get(ctx);
521     qadd = BN_CTX_get(ctx);
522     if (qadd == NULL)
523         goto err;
524
525     if (!BN_rshift1(qadd, padd))
526         goto err;
527
528     if (!BN_rand(q, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD))
529         goto err;
530
531     /* we need ((rnd-rem) % add) == 0 */
532     if (!BN_mod(t1, q, qadd, ctx))
533         goto err;
534     if (!BN_sub(q, q, t1))
535         goto err;
536     if (rem == NULL) {
537         if (!BN_add_word(q, 1))
538             goto err;
539     } else {
540         if (!BN_rshift1(t1, rem))
541             goto err;
542         if (!BN_add(q, q, t1))
543             goto err;
544     }
545
546     /* we now have a random number 'rand' to test. */
547     if (!BN_lshift1(p, q))
548         goto err;
549     if (!BN_add_word(p, 1))
550         goto err;
551
552  loop:
553     for (i = 1; i < NUMPRIMES; i++) {
554         /* check that p and q are prime */
555         /*
556          * check that for p and q gcd(p-1,primes) == 1 (except for 2)
557          */
558         BN_ULONG pmod = BN_mod_word(p, (BN_ULONG)primes[i]);
559         BN_ULONG qmod = BN_mod_word(q, (BN_ULONG)primes[i]);
560         if (pmod == (BN_ULONG)-1 || qmod == (BN_ULONG)-1)
561             goto err;
562         if (pmod == 0 || qmod == 0) {
563             if (!BN_add(p, p, padd))
564                 goto err;
565             if (!BN_add(q, q, qadd))
566                 goto err;
567             goto loop;
568         }
569     }
570     ret = 1;
571
572  err:
573     BN_CTX_end(ctx);
574     bn_check_top(p);
575     return ret;
576 }