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