rand: avoid using the derivation function for the public and private DRBGs
[openssl.git] / test / bntest.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 #include <assert.h>
10 #include <errno.h>
11 #include <stdio.h>
12 #include <string.h>
13 #ifdef __TANDEM
14 # include <strings.h> /* strcasecmp */
15 #endif
16 #include <ctype.h>
17
18 #include <openssl/bn.h>
19 #include <openssl/crypto.h>
20 #include <openssl/err.h>
21 #include <openssl/rand.h>
22 #include "internal/nelem.h"
23 #include "internal/numbers.h"
24 #include "testutil.h"
25
26 #ifdef OPENSSL_SYS_WINDOWS
27 # define strcasecmp _stricmp
28 #endif
29
30 /*
31  * Things in boring, not in openssl.
32  */
33 #define HAVE_BN_PADDED 0
34 #define HAVE_BN_SQRT 0
35
36 typedef struct filetest_st {
37     const char *name;
38     int (*func)(STANZA *s);
39 } FILETEST;
40
41 typedef struct mpitest_st {
42     const char *base10;
43     const char *mpi;
44     size_t mpi_len;
45 } MPITEST;
46
47 static const int NUM0 = 100;           /* number of tests */
48 static const int NUM1 = 50;            /* additional tests for some functions */
49 static BN_CTX *ctx;
50
51 /*
52  * Polynomial coefficients used in GFM tests.
53  */
54 #ifndef OPENSSL_NO_EC2M
55 static int p0[] = { 163, 7, 6, 3, 0, -1 };
56 static int p1[] = { 193, 15, 0, -1 };
57 #endif
58
59 /*
60  * Look for |key| in the stanza and return it or NULL if not found.
61  */
62 static const char *findattr(STANZA *s, const char *key)
63 {
64     int i = s->numpairs;
65     PAIR *pp = s->pairs;
66
67     for ( ; --i >= 0; pp++)
68         if (strcasecmp(pp->key, key) == 0)
69             return pp->value;
70     return NULL;
71 }
72
73 /*
74  * Parse BIGNUM from sparse hex-strings, return |BN_hex2bn| result.
75  */
76 static int parse_bigBN(BIGNUM **out, const char *bn_strings[])
77 {
78     char *bigstring = glue_strings(bn_strings, NULL);
79     int ret = BN_hex2bn(out, bigstring);
80
81     OPENSSL_free(bigstring);
82     return ret;
83 }
84
85 /*
86  * Parse BIGNUM, return number of bytes parsed.
87  */
88 static int parseBN(BIGNUM **out, const char *in)
89 {
90     *out = NULL;
91     return BN_hex2bn(out, in);
92 }
93
94 static int parsedecBN(BIGNUM **out, const char *in)
95 {
96     *out = NULL;
97     return BN_dec2bn(out, in);
98 }
99
100 static BIGNUM *getBN(STANZA *s, const char *attribute)
101 {
102     const char *hex;
103     BIGNUM *ret = NULL;
104
105     if ((hex = findattr(s, attribute)) == NULL) {
106         TEST_error("%s:%d: Can't find %s", s->test_file, s->start, attribute);
107         return NULL;
108     }
109
110     if (parseBN(&ret, hex) != (int)strlen(hex)) {
111         TEST_error("Could not decode '%s'", hex);
112         return NULL;
113     }
114     return ret;
115 }
116
117 static int getint(STANZA *s, int *out, const char *attribute)
118 {
119     BIGNUM *ret;
120     BN_ULONG word;
121     int st = 0;
122
123     if (!TEST_ptr(ret = getBN(s, attribute))
124             || !TEST_ulong_le(word = BN_get_word(ret), INT_MAX))
125         goto err;
126
127     *out = (int)word;
128     st = 1;
129  err:
130     BN_free(ret);
131     return st;
132 }
133
134 static int equalBN(const char *op, const BIGNUM *expected, const BIGNUM *actual)
135 {
136     if (BN_cmp(expected, actual) == 0)
137         return 1;
138
139     TEST_error("unexpected %s value", op);
140     TEST_BN_eq(expected, actual);
141     return 0;
142 }
143
144 /*
145  * Return a "random" flag for if a BN should be negated.
146  */
147 static int rand_neg(void)
148 {
149     static unsigned int neg = 0;
150     static int sign[8] = { 0, 0, 0, 1, 1, 0, 1, 1 };
151
152     return sign[(neg++) % 8];
153 }
154
155 static int test_swap(void)
156 {
157     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
158     int top, cond, st = 0;
159
160     if (!TEST_ptr(a = BN_new())
161             || !TEST_ptr(b = BN_new())
162             || !TEST_ptr(c = BN_new())
163             || !TEST_ptr(d = BN_new()))
164         goto err;
165
166     if (!(TEST_true(BN_bntest_rand(a, 1024, 1, 0))
167             && TEST_true(BN_bntest_rand(b, 1024, 1, 0))
168             && TEST_ptr(BN_copy(c, a))
169             && TEST_ptr(BN_copy(d, b))))
170         goto err;
171     top = BN_num_bits(a) / BN_BITS2;
172
173     /* regular swap */
174     BN_swap(a, b);
175     if (!equalBN("swap", a, d)
176             || !equalBN("swap", b, c))
177         goto err;
178
179     /* conditional swap: true */
180     cond = 1;
181     BN_consttime_swap(cond, a, b, top);
182     if (!equalBN("cswap true", a, c)
183             || !equalBN("cswap true", b, d))
184         goto err;
185
186     /* conditional swap: false */
187     cond = 0;
188     BN_consttime_swap(cond, a, b, top);
189     if (!equalBN("cswap false", a, c)
190             || !equalBN("cswap false", b, d))
191         goto err;
192
193     /* same tests but checking flag swap */
194     BN_set_flags(a, BN_FLG_CONSTTIME);
195
196     BN_swap(a, b);
197     if (!equalBN("swap, flags", a, d)
198             || !equalBN("swap, flags", b, c)
199             || !TEST_true(BN_get_flags(b, BN_FLG_CONSTTIME))
200             || !TEST_false(BN_get_flags(a, BN_FLG_CONSTTIME)))
201         goto err;
202
203     cond = 1;
204     BN_consttime_swap(cond, a, b, top);
205     if (!equalBN("cswap true, flags", a, c)
206             || !equalBN("cswap true, flags", b, d)
207             || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
208             || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
209         goto err;
210
211     cond = 0;
212     BN_consttime_swap(cond, a, b, top);
213     if (!equalBN("cswap false, flags", a, c)
214             || !equalBN("cswap false, flags", b, d)
215             || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
216             || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
217         goto err;
218
219     st = 1;
220  err:
221     BN_free(a);
222     BN_free(b);
223     BN_free(c);
224     BN_free(d);
225     return st;
226 }
227
228 static int test_sub(void)
229 {
230     BIGNUM *a = NULL, *b = NULL, *c = NULL;
231     int i, st = 0;
232
233     if (!TEST_ptr(a = BN_new())
234             || !TEST_ptr(b = BN_new())
235             || !TEST_ptr(c = BN_new()))
236         goto err;
237
238     for (i = 0; i < NUM0 + NUM1; i++) {
239         if (i < NUM1) {
240             if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0)))
241                     && TEST_ptr(BN_copy(b, a))
242                     && TEST_int_ne(BN_set_bit(a, i), 0)
243                     && TEST_true(BN_add_word(b, i)))
244                 goto err;
245         } else {
246             if (!TEST_true(BN_bntest_rand(b, 400 + i - NUM1, 0, 0)))
247                 goto err;
248             BN_set_negative(a, rand_neg());
249             BN_set_negative(b, rand_neg());
250         }
251         if (!(TEST_true(BN_sub(c, a, b))
252                 && TEST_true(BN_add(c, c, b))
253                 && TEST_true(BN_sub(c, c, a))
254                 && TEST_BN_eq_zero(c)))
255             goto err;
256     }
257     st = 1;
258  err:
259     BN_free(a);
260     BN_free(b);
261     BN_free(c);
262     return st;
263 }
264
265 static int test_div_recip(void)
266 {
267     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
268     BN_RECP_CTX *recp = NULL;
269     int st = 0, i;
270
271     if (!TEST_ptr(a = BN_new())
272             || !TEST_ptr(b = BN_new())
273             || !TEST_ptr(c = BN_new())
274             || !TEST_ptr(d = BN_new())
275             || !TEST_ptr(e = BN_new())
276             || !TEST_ptr(recp = BN_RECP_CTX_new()))
277         goto err;
278
279     for (i = 0; i < NUM0 + NUM1; i++) {
280         if (i < NUM1) {
281             if (!(TEST_true(BN_bntest_rand(a, 400, 0, 0))
282                     && TEST_ptr(BN_copy(b, a))
283                     && TEST_true(BN_lshift(a, a, i))
284                     && TEST_true(BN_add_word(a, i))))
285                 goto err;
286         } else {
287             if (!(TEST_true(BN_bntest_rand(b, 50 + 3 * (i - NUM1), 0, 0))))
288                 goto err;
289         }
290         BN_set_negative(a, rand_neg());
291         BN_set_negative(b, rand_neg());
292         if (!(TEST_true(BN_RECP_CTX_set(recp, b, ctx))
293                 && TEST_true(BN_div_recp(d, c, a, recp, ctx))
294                 && TEST_true(BN_mul(e, d, b, ctx))
295                 && TEST_true(BN_add(d, e, c))
296                 && TEST_true(BN_sub(d, d, a))
297                 && TEST_BN_eq_zero(d)))
298             goto err;
299     }
300     st = 1;
301  err:
302     BN_free(a);
303     BN_free(b);
304     BN_free(c);
305     BN_free(d);
306     BN_free(e);
307     BN_RECP_CTX_free(recp);
308     return st;
309 }
310
311 static struct {
312     int n, divisor, result, remainder;
313 } signed_mod_tests[] = {
314     {  10,   3,   3,   1 },
315     { -10,   3,  -3,  -1 },
316     {  10,  -3,  -3,   1 },
317     { -10,  -3,   3,  -1 },
318 };
319
320 static BIGNUM *set_signed_bn(int value)
321 {
322     BIGNUM *bn = BN_new();
323
324     if (bn == NULL)
325         return NULL;
326     if (!BN_set_word(bn, value < 0 ? -value : value)) {
327         BN_free(bn);
328         return NULL;
329     }
330     BN_set_negative(bn, value < 0);
331     return bn;
332 }
333
334 static int test_signed_mod_replace_ab(int n)
335 {
336     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
337     int st = 0;
338
339     if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n))
340             || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor))
341             || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result))
342             || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder)))
343         goto err;
344
345     if (TEST_true(BN_div(a, b, a, b, ctx))
346             && TEST_BN_eq(a, c)
347             && TEST_BN_eq(b, d))
348         st = 1;
349  err:
350     BN_free(a);
351     BN_free(b);
352     BN_free(c);
353     BN_free(d);
354     return st;
355 }
356
357 static int test_signed_mod_replace_ba(int n)
358 {
359     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
360     int st = 0;
361
362     if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n))
363             || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor))
364             || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result))
365             || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder)))
366         goto err;
367
368     if (TEST_true(BN_div(b, a, a, b, ctx))
369             && TEST_BN_eq(b, c)
370             && TEST_BN_eq(a, d))
371         st = 1;
372  err:
373     BN_free(a);
374     BN_free(b);
375     BN_free(c);
376     BN_free(d);
377     return st;
378 }
379
380 static int test_mod(void)
381 {
382     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
383     int st = 0, i;
384
385     if (!TEST_ptr(a = BN_new())
386             || !TEST_ptr(b = BN_new())
387             || !TEST_ptr(c = BN_new())
388             || !TEST_ptr(d = BN_new())
389             || !TEST_ptr(e = BN_new()))
390         goto err;
391
392     if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0))))
393         goto err;
394     for (i = 0; i < NUM0; i++) {
395         if (!(TEST_true(BN_bntest_rand(b, 450 + i * 10, 0, 0))))
396             goto err;
397         BN_set_negative(a, rand_neg());
398         BN_set_negative(b, rand_neg());
399         if (!(TEST_true(BN_mod(c, a, b, ctx))
400                 && TEST_true(BN_div(d, e, a, b, ctx))
401                 && TEST_BN_eq(e, c)
402                 && TEST_true(BN_mul(c, d, b, ctx))
403                 && TEST_true(BN_add(d, c, e))
404                 && TEST_BN_eq(d, a)))
405             goto err;
406     }
407     st = 1;
408  err:
409     BN_free(a);
410     BN_free(b);
411     BN_free(c);
412     BN_free(d);
413     BN_free(e);
414     return st;
415 }
416
417 static const char *bn1strings[] = {
418     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
419     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
420     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
421     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
422     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
423     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
424     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
425     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF00",
426     "0000000000000000000000000000000000000000000000000000000000000000",
427     "0000000000000000000000000000000000000000000000000000000000000000",
428     "0000000000000000000000000000000000000000000000000000000000000000",
429     "0000000000000000000000000000000000000000000000000000000000000000",
430     "0000000000000000000000000000000000000000000000000000000000000000",
431     "0000000000000000000000000000000000000000000000000000000000000000",
432     "0000000000000000000000000000000000000000000000000000000000000000",
433     "00000000000000000000000000000000000000000000000000FFFFFFFFFFFFFF",
434     NULL
435 };
436
437 static const char *bn2strings[] = {
438     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
439     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
440     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
441     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
442     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
443     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
444     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
445     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF0000000000",
446     "0000000000000000000000000000000000000000000000000000000000000000",
447     "0000000000000000000000000000000000000000000000000000000000000000",
448     "0000000000000000000000000000000000000000000000000000000000000000",
449     "0000000000000000000000000000000000000000000000000000000000000000",
450     "0000000000000000000000000000000000000000000000000000000000000000",
451     "0000000000000000000000000000000000000000000000000000000000000000",
452     "0000000000000000000000000000000000000000000000000000000000000000",
453     "000000000000000000000000000000000000000000FFFFFFFFFFFFFF00000000",
454     NULL
455 };
456
457 /*
458  * Test constant-time modular exponentiation with 1024-bit inputs, which on
459  * x86_64 cause a different code branch to be taken.
460  */
461 static int test_modexp_mont5(void)
462 {
463     BIGNUM *a = NULL, *p = NULL, *m = NULL, *d = NULL, *e = NULL;
464     BIGNUM *b = NULL, *n = NULL, *c = NULL;
465     BN_MONT_CTX *mont = NULL;
466     int st = 0;
467
468     if (!TEST_ptr(a = BN_new())
469             || !TEST_ptr(p = BN_new())
470             || !TEST_ptr(m = BN_new())
471             || !TEST_ptr(d = BN_new())
472             || !TEST_ptr(e = BN_new())
473             || !TEST_ptr(b = BN_new())
474             || !TEST_ptr(n = BN_new())
475             || !TEST_ptr(c = BN_new())
476             || !TEST_ptr(mont = BN_MONT_CTX_new()))
477         goto err;
478
479     /* must be odd for montgomery */
480     if (!(TEST_true(BN_bntest_rand(m, 1024, 0, 1))
481             /* Zero exponent */
482             && TEST_true(BN_bntest_rand(a, 1024, 0, 0))))
483         goto err;
484     BN_zero(p);
485
486     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL)))
487         goto err;
488     if (!TEST_BN_eq_one(d))
489         goto err;
490
491     /* Regression test for carry bug in mulx4x_mont */
492     if (!(TEST_true(BN_hex2bn(&a,
493         "7878787878787878787878787878787878787878787878787878787878787878"
494         "7878787878787878787878787878787878787878787878787878787878787878"
495         "7878787878787878787878787878787878787878787878787878787878787878"
496         "7878787878787878787878787878787878787878787878787878787878787878"))
497         && TEST_true(BN_hex2bn(&b,
498         "095D72C08C097BA488C5E439C655A192EAFB6380073D8C2664668EDDB4060744"
499         "E16E57FB4EDB9AE10A0CEFCDC28A894F689A128379DB279D48A2E20849D68593"
500         "9B7803BCF46CEBF5C533FB0DD35B080593DE5472E3FE5DB951B8BFF9B4CB8F03"
501         "9CC638A5EE8CDD703719F8000E6A9F63BEED5F2FCD52FF293EA05A251BB4AB81"))
502         && TEST_true(BN_hex2bn(&n,
503         "D78AF684E71DB0C39CFF4E64FB9DB567132CB9C50CC98009FEB820B26F2DED9B"
504         "91B9B5E2B83AE0AE4EB4E0523CA726BFBE969B89FD754F674CE99118C3F2D1C5"
505         "D81FDC7C54E02B60262B241D53C040E99E45826ECA37A804668E690E1AFC1CA4"
506         "2C9A15D84D4954425F0B7642FC0BD9D7B24E2618D2DCC9B729D944BADACFDDAF"))))
507         goto err;
508
509     if (!(TEST_true(BN_MONT_CTX_set(mont, n, ctx))
510             && TEST_true(BN_mod_mul_montgomery(c, a, b, mont, ctx))
511             && TEST_true(BN_mod_mul_montgomery(d, b, a, mont, ctx))
512             && TEST_BN_eq(c, d)))
513         goto err;
514
515     /* Regression test for carry bug in sqr[x]8x_mont */
516     if (!(TEST_true(parse_bigBN(&n, bn1strings))
517             && TEST_true(parse_bigBN(&a, bn2strings))))
518         goto err;
519     BN_free(b);
520     if (!(TEST_ptr(b = BN_dup(a))
521             && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
522             && TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
523             && TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
524             && TEST_BN_eq(c, d)))
525         goto err;
526
527     /* Regression test for carry bug in bn_sqrx8x_internal */
528     {
529         static const char *ahex[] = {
530                       "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
531             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
532             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
533             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
534             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8FFEADBCFC4DAE7FFF908E92820306B",
535             "9544D954000000006C0000000000000000000000000000000000000000000000",
536             "00000000000000000000FF030202FFFFF8FFEBDBCFC4DAE7FFF908E92820306B",
537             "9544D954000000006C000000FF0302030000000000FFFFFFFFFFFFFFFFFFFFFF",
538             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01FC00FF02FFFFFFFF",
539             "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FCFD",
540             "FCFFFFFFFFFF000000000000000000FF0302030000000000FFFFFFFFFFFFFFFF",
541             "FF00FCFDFDFF030202FF00000000FFFFFFFFFFFFFFFFFF00FCFDFCFFFFFFFFFF",
542             NULL
543         };
544         static const char *nhex[] = {
545                       "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
546             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
547             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
548             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
549             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8F8F8F8000000",
550             "00000010000000006C0000000000000000000000000000000000000000000000",
551             "00000000000000000000000000000000000000FFFFFFFFFFFFF8F8F8F8000000",
552             "00000010000000006C000000000000000000000000FFFFFFFFFFFFFFFFFFFFFF",
553             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
554             "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
555             "FFFFFFFFFFFF000000000000000000000000000000000000FFFFFFFFFFFFFFFF",
556             "FFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
557             NULL
558         };
559
560         if (!(TEST_true(parse_bigBN(&a, ahex))
561                 && TEST_true(parse_bigBN(&n, nhex))))
562             goto err;
563     }
564     BN_free(b);
565     if (!(TEST_ptr(b = BN_dup(a))
566             && TEST_true(BN_MONT_CTX_set(mont, n, ctx))))
567         goto err;
568
569     if (!TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
570             || !TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
571             || !TEST_BN_eq(c, d))
572         goto err;
573
574     /* Regression test for bug in BN_from_montgomery_word */
575     if (!(TEST_true(BN_hex2bn(&a,
576         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
577         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
578         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
579          && TEST_true(BN_hex2bn(&n,
580         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
581         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
582         && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
583         && TEST_false(BN_mod_mul_montgomery(d, a, a, mont, ctx))))
584         goto err;
585
586     /* Regression test for bug in rsaz_1024_mul_avx2 */
587     if (!(TEST_true(BN_hex2bn(&a,
588         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
589         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
590         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
591         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
592         && TEST_true(BN_hex2bn(&b,
593         "2020202020202020202020202020202020202020202020202020202020202020"
594         "2020202020202020202020202020202020202020202020202020202020202020"
595         "20202020202020FF202020202020202020202020202020202020202020202020"
596         "2020202020202020202020202020202020202020202020202020202020202020"))
597         && TEST_true(BN_hex2bn(&n,
598         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
599         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
600         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
601         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020FF"))
602         && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
603         && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont))
604         && TEST_true(BN_mod_exp_mont(d, a, b, n, ctx, mont))
605         && TEST_BN_eq(c, d)))
606         goto err;
607
608     /*
609      * rsaz_1024_mul_avx2 expects fully-reduced inputs.
610      * BN_mod_exp_mont_consttime should reduce the input first.
611      */
612     if (!(TEST_true(BN_hex2bn(&a,
613         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
614         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
615         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
616         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
617         && TEST_true(BN_hex2bn(&b,
618         "1FA53F26F8811C58BE0357897AA5E165693230BC9DF5F01DFA6A2D59229EC69D"
619         "9DE6A89C36E3B6957B22D6FAAD5A3C73AE587B710DBE92E83D3A9A3339A085CB"
620         "B58F508CA4F837924BB52CC1698B7FDC2FD74362456A595A5B58E38E38E38E38"
621         "E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E"))
622         && TEST_true(BN_hex2bn(&n,
623         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
624         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
625         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
626         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
627         && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
628         && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont))))
629         goto err;
630     BN_zero(d);
631     if (!TEST_BN_eq(c, d))
632         goto err;
633
634     /* Zero input */
635     if (!TEST_true(BN_bntest_rand(p, 1024, 0, 0)))
636         goto err;
637     BN_zero(a);
638     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))
639             || !TEST_BN_eq_zero(d))
640         goto err;
641
642     /*
643      * Craft an input whose Montgomery representation is 1, i.e., shorter
644      * than the modulus m, in order to test the const time precomputation
645      * scattering/gathering.
646      */
647     if (!(TEST_true(BN_one(a))
648             && TEST_true(BN_MONT_CTX_set(mont, m, ctx))))
649         goto err;
650     if (!TEST_true(BN_from_montgomery(e, a, mont, ctx))
651             || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
652             || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
653             || !TEST_BN_eq(a, d))
654         goto err;
655
656     /* Finally, some regular test vectors. */
657     if (!(TEST_true(BN_bntest_rand(e, 1024, 0, 0))
658             && TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
659             && TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
660             && TEST_BN_eq(a, d)))
661         goto err;
662
663     st = 1;
664
665  err:
666     BN_MONT_CTX_free(mont);
667     BN_free(a);
668     BN_free(p);
669     BN_free(m);
670     BN_free(d);
671     BN_free(e);
672     BN_free(b);
673     BN_free(n);
674     BN_free(c);
675     return st;
676 }
677
678 #ifndef OPENSSL_NO_EC2M
679 static int test_gf2m_add(void)
680 {
681     BIGNUM *a = NULL, *b = NULL, *c = NULL;
682     int i, st = 0;
683
684     if (!TEST_ptr(a = BN_new())
685             || !TEST_ptr(b = BN_new())
686             || !TEST_ptr(c = BN_new()))
687         goto err;
688
689     for (i = 0; i < NUM0; i++) {
690         if (!(TEST_true(BN_rand(a, 512, 0, 0))
691                 && TEST_ptr(BN_copy(b, BN_value_one()))))
692             goto err;
693         BN_set_negative(a, rand_neg());
694         BN_set_negative(b, rand_neg());
695         if (!(TEST_true(BN_GF2m_add(c, a, b))
696                 /* Test that two added values have the correct parity. */
697                 && TEST_false((BN_is_odd(a) && BN_is_odd(c))
698                         || (!BN_is_odd(a) && !BN_is_odd(c)))))
699             goto err;
700         if (!(TEST_true(BN_GF2m_add(c, c, c))
701                 /* Test that c + c = 0. */
702                 && TEST_BN_eq_zero(c)))
703             goto err;
704     }
705     st = 1;
706  err:
707     BN_free(a);
708     BN_free(b);
709     BN_free(c);
710     return st;
711 }
712
713 static int test_gf2m_mod(void)
714 {
715     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL, *e = NULL;
716     int i, j, st = 0;
717
718     if (!TEST_ptr(a = BN_new())
719             || !TEST_ptr(b[0] = BN_new())
720             || !TEST_ptr(b[1] = BN_new())
721             || !TEST_ptr(c = BN_new())
722             || !TEST_ptr(d = BN_new())
723             || !TEST_ptr(e = BN_new()))
724         goto err;
725
726     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
727             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
728         goto err;
729
730     for (i = 0; i < NUM0; i++) {
731         if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0)))
732             goto err;
733         for (j = 0; j < 2; j++) {
734             if (!(TEST_true(BN_GF2m_mod(c, a, b[j]))
735                     && TEST_true(BN_GF2m_add(d, a, c))
736                     && TEST_true(BN_GF2m_mod(e, d, b[j]))
737                     /* Test that a + (a mod p) mod p == 0. */
738                     && TEST_BN_eq_zero(e)))
739                 goto err;
740         }
741     }
742     st = 1;
743  err:
744     BN_free(a);
745     BN_free(b[0]);
746     BN_free(b[1]);
747     BN_free(c);
748     BN_free(d);
749     BN_free(e);
750     return st;
751 }
752
753 static int test_gf2m_mul(void)
754 {
755     BIGNUM *a, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
756     BIGNUM *e = NULL, *f = NULL, *g = NULL, *h = NULL;
757     int i, j, st = 0;
758
759     if (!TEST_ptr(a = BN_new())
760             || !TEST_ptr(b[0] = BN_new())
761             || !TEST_ptr(b[1] = BN_new())
762             || !TEST_ptr(c = BN_new())
763             || !TEST_ptr(d = BN_new())
764             || !TEST_ptr(e = BN_new())
765             || !TEST_ptr(f = BN_new())
766             || !TEST_ptr(g = BN_new())
767             || !TEST_ptr(h = BN_new()))
768         goto err;
769
770     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
771             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
772         goto err;
773
774     for (i = 0; i < NUM0; i++) {
775         if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0))
776                 && TEST_true(BN_bntest_rand(c, 1024, 0, 0))
777                 && TEST_true(BN_bntest_rand(d, 1024, 0, 0))))
778             goto err;
779         for (j = 0; j < 2; j++) {
780             if (!(TEST_true(BN_GF2m_mod_mul(e, a, c, b[j], ctx))
781                     && TEST_true(BN_GF2m_add(f, a, d))
782                     && TEST_true(BN_GF2m_mod_mul(g, f, c, b[j], ctx))
783                     && TEST_true(BN_GF2m_mod_mul(h, d, c, b[j], ctx))
784                     && TEST_true(BN_GF2m_add(f, e, g))
785                     && TEST_true(BN_GF2m_add(f, f, h))
786                     /* Test that (a+d)*c = a*c + d*c. */
787                     && TEST_BN_eq_zero(f)))
788                 goto err;
789         }
790     }
791     st = 1;
792
793  err:
794     BN_free(a);
795     BN_free(b[0]);
796     BN_free(b[1]);
797     BN_free(c);
798     BN_free(d);
799     BN_free(e);
800     BN_free(f);
801     BN_free(g);
802     BN_free(h);
803     return st;
804 }
805
806 static int test_gf2m_sqr(void)
807 {
808     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
809     int i, j, st = 0;
810
811     if (!TEST_ptr(a = BN_new())
812             || !TEST_ptr(b[0] = BN_new())
813             || !TEST_ptr(b[1] = BN_new())
814             || !TEST_ptr(c = BN_new())
815             || !TEST_ptr(d = BN_new()))
816         goto err;
817
818     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
819             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
820         goto err;
821
822     for (i = 0; i < NUM0; i++) {
823         if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0)))
824                 goto err;
825         for (j = 0; j < 2; j++) {
826             if (!(TEST_true(BN_GF2m_mod_sqr(c, a, b[j], ctx))
827                     && TEST_true(BN_copy(d, a))
828                     && TEST_true(BN_GF2m_mod_mul(d, a, d, b[j], ctx))
829                     && TEST_true(BN_GF2m_add(d, c, d))
830                     /* Test that a*a = a^2. */
831                     && TEST_BN_eq_zero(d)))
832                 goto err;
833         }
834     }
835     st = 1;
836  err:
837     BN_free(a);
838     BN_free(b[0]);
839     BN_free(b[1]);
840     BN_free(c);
841     BN_free(d);
842     return st;
843 }
844
845 static int test_gf2m_modinv(void)
846 {
847     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
848     int i, j, st = 0;
849
850     if (!TEST_ptr(a = BN_new())
851             || !TEST_ptr(b[0] = BN_new())
852             || !TEST_ptr(b[1] = BN_new())
853             || !TEST_ptr(c = BN_new())
854             || !TEST_ptr(d = BN_new()))
855         goto err;
856
857     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
858             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
859         goto err;
860
861     for (i = 0; i < NUM0; i++) {
862         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
863             goto err;
864         for (j = 0; j < 2; j++) {
865             if (!(TEST_true(BN_GF2m_mod_inv(c, a, b[j], ctx))
866                     && TEST_true(BN_GF2m_mod_mul(d, a, c, b[j], ctx))
867                     /* Test that ((1/a)*a) = 1. */
868                     && TEST_BN_eq_one(d)))
869                 goto err;
870         }
871     }
872     st = 1;
873  err:
874     BN_free(a);
875     BN_free(b[0]);
876     BN_free(b[1]);
877     BN_free(c);
878     BN_free(d);
879     return st;
880 }
881
882 static int test_gf2m_moddiv(void)
883 {
884     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
885     BIGNUM *e = NULL, *f = NULL;
886     int i, j, st = 0;
887
888     if (!TEST_ptr(a = BN_new())
889             || !TEST_ptr(b[0] = BN_new())
890             || !TEST_ptr(b[1] = BN_new())
891             || !TEST_ptr(c = BN_new())
892             || !TEST_ptr(d = BN_new())
893             || !TEST_ptr(e = BN_new())
894             || !TEST_ptr(f = BN_new()))
895         goto err;
896
897     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
898             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
899         goto err;
900
901     for (i = 0; i < NUM0; i++) {
902         if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))
903                 && TEST_true(BN_bntest_rand(c, 512, 0, 0))))
904             goto err;
905         for (j = 0; j < 2; j++) {
906             if (!(TEST_true(BN_GF2m_mod_div(d, a, c, b[j], ctx))
907                     && TEST_true(BN_GF2m_mod_mul(e, d, c, b[j], ctx))
908                     && TEST_true(BN_GF2m_mod_div(f, a, e, b[j], ctx))
909                     /* Test that ((a/c)*c)/a = 1. */
910                     && TEST_BN_eq_one(f)))
911                 goto err;
912         }
913     }
914     st = 1;
915  err:
916     BN_free(a);
917     BN_free(b[0]);
918     BN_free(b[1]);
919     BN_free(c);
920     BN_free(d);
921     BN_free(e);
922     BN_free(f);
923     return st;
924 }
925
926 static int test_gf2m_modexp(void)
927 {
928     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
929     BIGNUM *e = NULL, *f = NULL;
930     int i, j, st = 0;
931
932     if (!TEST_ptr(a = BN_new())
933             || !TEST_ptr(b[0] = BN_new())
934             || !TEST_ptr(b[1] = BN_new())
935             || !TEST_ptr(c = BN_new())
936             || !TEST_ptr(d = BN_new())
937             || !TEST_ptr(e = BN_new())
938             || !TEST_ptr(f = BN_new()))
939         goto err;
940
941     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
942             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
943         goto err;
944
945     for (i = 0; i < NUM0; i++) {
946         if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))
947                 && TEST_true(BN_bntest_rand(c, 512, 0, 0))
948                 && TEST_true(BN_bntest_rand(d, 512, 0, 0))))
949             goto err;
950         for (j = 0; j < 2; j++) {
951             if (!(TEST_true(BN_GF2m_mod_exp(e, a, c, b[j], ctx))
952                     && TEST_true(BN_GF2m_mod_exp(f, a, d, b[j], ctx))
953                     && TEST_true(BN_GF2m_mod_mul(e, e, f, b[j], ctx))
954                     && TEST_true(BN_add(f, c, d))
955                     && TEST_true(BN_GF2m_mod_exp(f, a, f, b[j], ctx))
956                     && TEST_true(BN_GF2m_add(f, e, f))
957                     /* Test that a^(c+d)=a^c*a^d. */
958                     && TEST_BN_eq_zero(f)))
959                 goto err;
960         }
961     }
962     st = 1;
963  err:
964     BN_free(a);
965     BN_free(b[0]);
966     BN_free(b[1]);
967     BN_free(c);
968     BN_free(d);
969     BN_free(e);
970     BN_free(f);
971     return st;
972 }
973
974 static int test_gf2m_modsqrt(void)
975 {
976     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
977     BIGNUM *e = NULL, *f = NULL;
978     int i, j, st = 0;
979
980     if (!TEST_ptr(a = BN_new())
981             || !TEST_ptr(b[0] = BN_new())
982             || !TEST_ptr(b[1] = BN_new())
983             || !TEST_ptr(c = BN_new())
984             || !TEST_ptr(d = BN_new())
985             || !TEST_ptr(e = BN_new())
986             || !TEST_ptr(f = BN_new()))
987         goto err;
988
989     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
990             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
991         goto err;
992
993     for (i = 0; i < NUM0; i++) {
994         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
995             goto err;
996
997         for (j = 0; j < 2; j++) {
998             if (!(TEST_true(BN_GF2m_mod(c, a, b[j]))
999                     && TEST_true(BN_GF2m_mod_sqrt(d, a, b[j], ctx))
1000                     && TEST_true(BN_GF2m_mod_sqr(e, d, b[j], ctx))
1001                     && TEST_true(BN_GF2m_add(f, c, e))
1002                     /* Test that d^2 = a, where d = sqrt(a). */
1003                     && TEST_BN_eq_zero(f)))
1004                 goto err;
1005         }
1006     }
1007     st = 1;
1008  err:
1009     BN_free(a);
1010     BN_free(b[0]);
1011     BN_free(b[1]);
1012     BN_free(c);
1013     BN_free(d);
1014     BN_free(e);
1015     BN_free(f);
1016     return st;
1017 }
1018
1019 static int test_gf2m_modsolvequad(void)
1020 {
1021     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
1022     BIGNUM *e = NULL;
1023     int i, j, s = 0, t, st = 0;
1024
1025     if (!TEST_ptr(a = BN_new())
1026             || !TEST_ptr(b[0] = BN_new())
1027             || !TEST_ptr(b[1] = BN_new())
1028             || !TEST_ptr(c = BN_new())
1029             || !TEST_ptr(d = BN_new())
1030             || !TEST_ptr(e = BN_new()))
1031         goto err;
1032
1033     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
1034             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
1035         goto err;
1036
1037     for (i = 0; i < NUM0; i++) {
1038         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
1039             goto err;
1040         for (j = 0; j < 2; j++) {
1041             t = BN_GF2m_mod_solve_quad(c, a, b[j], ctx);
1042             if (t) {
1043                 s++;
1044                 if (!(TEST_true(BN_GF2m_mod_sqr(d, c, b[j], ctx))
1045                         && TEST_true(BN_GF2m_add(d, c, d))
1046                         && TEST_true(BN_GF2m_mod(e, a, b[j]))
1047                         && TEST_true(BN_GF2m_add(e, e, d))
1048                         /*
1049                          * Test that solution of quadratic c
1050                          * satisfies c^2 + c = a.
1051                          */
1052                         && TEST_BN_eq_zero(e)))
1053                     goto err;
1054             }
1055         }
1056     }
1057     if (!TEST_int_ge(s, 0)) {
1058         TEST_info("%d tests found no roots; probably an error", NUM0);
1059         goto err;
1060     }
1061     st = 1;
1062  err:
1063     BN_free(a);
1064     BN_free(b[0]);
1065     BN_free(b[1]);
1066     BN_free(c);
1067     BN_free(d);
1068     BN_free(e);
1069     return st;
1070 }
1071 #endif
1072
1073 static int test_kronecker(void)
1074 {
1075     BIGNUM *a = NULL, *b = NULL, *r = NULL, *t = NULL;
1076     int i, legendre, kronecker, st = 0;
1077
1078     if (!TEST_ptr(a = BN_new())
1079             || !TEST_ptr(b = BN_new())
1080             || !TEST_ptr(r = BN_new())
1081             || !TEST_ptr(t = BN_new()))
1082         goto err;
1083
1084     /*
1085      * We test BN_kronecker(a, b, ctx) just for b odd (Jacobi symbol). In
1086      * this case we know that if b is prime, then BN_kronecker(a, b, ctx) is
1087      * congruent to $a^{(b-1)/2}$, modulo $b$ (Legendre symbol). So we
1088      * generate a random prime b and compare these values for a number of
1089      * random a's.  (That is, we run the Solovay-Strassen primality test to
1090      * confirm that b is prime, except that we don't want to test whether b
1091      * is prime but whether BN_kronecker works.)
1092      */
1093
1094     if (!TEST_true(BN_generate_prime_ex(b, 512, 0, NULL, NULL, NULL)))
1095         goto err;
1096     BN_set_negative(b, rand_neg());
1097
1098     for (i = 0; i < NUM0; i++) {
1099         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
1100             goto err;
1101         BN_set_negative(a, rand_neg());
1102
1103         /* t := (|b|-1)/2  (note that b is odd) */
1104         if (!TEST_true(BN_copy(t, b)))
1105             goto err;
1106         BN_set_negative(t, 0);
1107         if (!TEST_true(BN_sub_word(t, 1)))
1108             goto err;
1109         if (!TEST_true(BN_rshift1(t, t)))
1110             goto err;
1111         /* r := a^t mod b */
1112         BN_set_negative(b, 0);
1113
1114         if (!TEST_true(BN_mod_exp_recp(r, a, t, b, ctx)))
1115             goto err;
1116         BN_set_negative(b, 1);
1117
1118         if (BN_is_word(r, 1))
1119             legendre = 1;
1120         else if (BN_is_zero(r))
1121             legendre = 0;
1122         else {
1123             if (!TEST_true(BN_add_word(r, 1)))
1124                 goto err;
1125             if (!TEST_int_eq(BN_ucmp(r, b), 0)) {
1126                 TEST_info("Legendre symbol computation failed");
1127                 goto err;
1128             }
1129             legendre = -1;
1130         }
1131
1132         if (!TEST_int_ge(kronecker = BN_kronecker(a, b, ctx), -1))
1133             goto err;
1134         /* we actually need BN_kronecker(a, |b|) */
1135         if (BN_is_negative(a) && BN_is_negative(b))
1136             kronecker = -kronecker;
1137
1138         if (!TEST_int_eq(legendre, kronecker))
1139             goto err;
1140     }
1141
1142     st = 1;
1143  err:
1144     BN_free(a);
1145     BN_free(b);
1146     BN_free(r);
1147     BN_free(t);
1148     return st;
1149 }
1150
1151 static int file_sum(STANZA *s)
1152 {
1153     BIGNUM *a = NULL, *b = NULL, *sum = NULL, *ret = NULL;
1154     BN_ULONG b_word;
1155     int st = 0;
1156
1157     if (!TEST_ptr(a = getBN(s, "A"))
1158             || !TEST_ptr(b = getBN(s, "B"))
1159             || !TEST_ptr(sum = getBN(s, "Sum"))
1160             || !TEST_ptr(ret = BN_new()))
1161         goto err;
1162
1163     if (!TEST_true(BN_add(ret, a, b))
1164             || !equalBN("A + B", sum, ret)
1165             || !TEST_true(BN_sub(ret, sum, a))
1166             || !equalBN("Sum - A", b, ret)
1167             || !TEST_true(BN_sub(ret, sum, b))
1168             || !equalBN("Sum - B", a, ret))
1169         goto err;
1170
1171     /*
1172      * Test that the functions work when |r| and |a| point to the same BIGNUM,
1173      * or when |r| and |b| point to the same BIGNUM.
1174      * There is no test for all of |r|, |a|, and |b| pointint to the same BIGNUM.
1175      */
1176     if (!TEST_true(BN_copy(ret, a))
1177             || !TEST_true(BN_add(ret, ret, b))
1178             || !equalBN("A + B (r is a)", sum, ret)
1179             || !TEST_true(BN_copy(ret, b))
1180             || !TEST_true(BN_add(ret, a, ret))
1181             || !equalBN("A + B (r is b)", sum, ret)
1182             || !TEST_true(BN_copy(ret, sum))
1183             || !TEST_true(BN_sub(ret, ret, a))
1184             || !equalBN("Sum - A (r is a)", b, ret)
1185             || !TEST_true(BN_copy(ret, a))
1186             || !TEST_true(BN_sub(ret, sum, ret))
1187             || !equalBN("Sum - A (r is b)", b, ret)
1188             || !TEST_true(BN_copy(ret, sum))
1189             || !TEST_true(BN_sub(ret, ret, b))
1190             || !equalBN("Sum - B (r is a)", a, ret)
1191             || !TEST_true(BN_copy(ret, b))
1192             || !TEST_true(BN_sub(ret, sum, ret))
1193             || !equalBN("Sum - B (r is b)", a, ret))
1194         goto err;
1195
1196     /*
1197      * Test BN_uadd() and BN_usub() with the prerequisites they are
1198      * documented as having. Note that these functions are frequently used
1199      * when the prerequisites don't hold. In those cases, they are supposed
1200      * to work as if the prerequisite hold, but we don't test that yet.
1201      */
1202     if (!BN_is_negative(a) && !BN_is_negative(b) && BN_cmp(a, b) >= 0) {
1203         if (!TEST_true(BN_uadd(ret, a, b))
1204                 || !equalBN("A +u B", sum, ret)
1205                 || !TEST_true(BN_usub(ret, sum, a))
1206                 || !equalBN("Sum -u A", b, ret)
1207                 || !TEST_true(BN_usub(ret, sum, b))
1208                 || !equalBN("Sum -u B", a, ret))
1209             goto err;
1210         /*
1211          * Test that the functions work when |r| and |a| point to the same
1212          * BIGNUM, or when |r| and |b| point to the same BIGNUM.
1213          * There is no test for all of |r|, |a|, and |b| pointint to the same
1214          * BIGNUM.
1215          */
1216         if (!TEST_true(BN_copy(ret, a))
1217                 || !TEST_true(BN_uadd(ret, ret, b))
1218                 || !equalBN("A +u B (r is a)", sum, ret)
1219                 || !TEST_true(BN_copy(ret, b))
1220                 || !TEST_true(BN_uadd(ret, a, ret))
1221                 || !equalBN("A +u B (r is b)", sum, ret)
1222                 || !TEST_true(BN_copy(ret, sum))
1223                 || !TEST_true(BN_usub(ret, ret, a))
1224                 || !equalBN("Sum -u A (r is a)", b, ret)
1225                 || !TEST_true(BN_copy(ret, a))
1226                 || !TEST_true(BN_usub(ret, sum, ret))
1227                 || !equalBN("Sum -u A (r is b)", b, ret)
1228                 || !TEST_true(BN_copy(ret, sum))
1229                 || !TEST_true(BN_usub(ret, ret, b))
1230                 || !equalBN("Sum -u B (r is a)", a, ret)
1231                 || !TEST_true(BN_copy(ret, b))
1232                 || !TEST_true(BN_usub(ret, sum, ret))
1233                 || !equalBN("Sum -u B (r is b)", a, ret))
1234             goto err;
1235     }
1236
1237     /*
1238      * Test with BN_add_word() and BN_sub_word() if |b| is small enough.
1239      */
1240     b_word = BN_get_word(b);
1241     if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) {
1242         if (!TEST_true(BN_copy(ret, a))
1243                 || !TEST_true(BN_add_word(ret, b_word))
1244                 || !equalBN("A + B (word)", sum, ret)
1245                 || !TEST_true(BN_copy(ret, sum))
1246                 || !TEST_true(BN_sub_word(ret, b_word))
1247                 || !equalBN("Sum - B (word)", a, ret))
1248             goto err;
1249     }
1250     st = 1;
1251
1252  err:
1253     BN_free(a);
1254     BN_free(b);
1255     BN_free(sum);
1256     BN_free(ret);
1257     return st;
1258 }
1259
1260 static int file_lshift1(STANZA *s)
1261 {
1262     BIGNUM *a = NULL, *lshift1 = NULL, *zero = NULL, *ret = NULL;
1263     BIGNUM *two = NULL, *remainder = NULL;
1264     int st = 0;
1265
1266     if (!TEST_ptr(a = getBN(s, "A"))
1267             || !TEST_ptr(lshift1 = getBN(s, "LShift1"))
1268             || !TEST_ptr(zero = BN_new())
1269             || !TEST_ptr(ret = BN_new())
1270             || !TEST_ptr(two = BN_new())
1271             || !TEST_ptr(remainder = BN_new()))
1272         goto err;
1273
1274     BN_zero(zero);
1275
1276     if (!TEST_true(BN_set_word(two, 2))
1277             || !TEST_true(BN_add(ret, a, a))
1278             || !equalBN("A + A", lshift1, ret)
1279             || !TEST_true(BN_mul(ret, a, two, ctx))
1280             || !equalBN("A * 2", lshift1, ret)
1281             || !TEST_true(BN_div(ret, remainder, lshift1, two, ctx))
1282             || !equalBN("LShift1 / 2", a, ret)
1283             || !equalBN("LShift1 % 2", zero, remainder)
1284             || !TEST_true(BN_lshift1(ret, a))
1285             || !equalBN("A << 1", lshift1, ret)
1286             || !TEST_true(BN_rshift1(ret, lshift1))
1287             || !equalBN("LShift >> 1", a, ret)
1288             || !TEST_true(BN_rshift1(ret, lshift1))
1289             || !equalBN("LShift >> 1", a, ret))
1290         goto err;
1291
1292     /* Set the LSB to 1 and test rshift1 again. */
1293     if (!TEST_true(BN_set_bit(lshift1, 0))
1294             || !TEST_true(BN_div(ret, NULL /* rem */ , lshift1, two, ctx))
1295             || !equalBN("(LShift1 | 1) / 2", a, ret)
1296             || !TEST_true(BN_rshift1(ret, lshift1))
1297             || !equalBN("(LShift | 1) >> 1", a, ret))
1298         goto err;
1299
1300     st = 1;
1301  err:
1302     BN_free(a);
1303     BN_free(lshift1);
1304     BN_free(zero);
1305     BN_free(ret);
1306     BN_free(two);
1307     BN_free(remainder);
1308
1309     return st;
1310 }
1311
1312 static int file_lshift(STANZA *s)
1313 {
1314     BIGNUM *a = NULL, *lshift = NULL, *ret = NULL;
1315     int n = 0, st = 0;
1316
1317     if (!TEST_ptr(a = getBN(s, "A"))
1318             || !TEST_ptr(lshift = getBN(s, "LShift"))
1319             || !TEST_ptr(ret = BN_new())
1320             || !getint(s, &n, "N"))
1321         goto err;
1322
1323     if (!TEST_true(BN_lshift(ret, a, n))
1324             || !equalBN("A << N", lshift, ret)
1325             || !TEST_true(BN_rshift(ret, lshift, n))
1326             || !equalBN("A >> N", a, ret))
1327         goto err;
1328
1329     st = 1;
1330  err:
1331     BN_free(a);
1332     BN_free(lshift);
1333     BN_free(ret);
1334     return st;
1335 }
1336
1337 static int file_rshift(STANZA *s)
1338 {
1339     BIGNUM *a = NULL, *rshift = NULL, *ret = NULL;
1340     int n = 0, st = 0;
1341
1342     if (!TEST_ptr(a = getBN(s, "A"))
1343             || !TEST_ptr(rshift = getBN(s, "RShift"))
1344             || !TEST_ptr(ret = BN_new())
1345             || !getint(s, &n, "N"))
1346         goto err;
1347
1348     if (!TEST_true(BN_rshift(ret, a, n))
1349             || !equalBN("A >> N", rshift, ret))
1350         goto err;
1351
1352     /* If N == 1, try with rshift1 as well */
1353     if (n == 1) {
1354         if (!TEST_true(BN_rshift1(ret, a))
1355                 || !equalBN("A >> 1 (rshift1)", rshift, ret))
1356             goto err;
1357     }
1358     st = 1;
1359
1360  err:
1361     BN_free(a);
1362     BN_free(rshift);
1363     BN_free(ret);
1364     return st;
1365 }
1366
1367 static int file_square(STANZA *s)
1368 {
1369     BIGNUM *a = NULL, *square = NULL, *zero = NULL, *ret = NULL;
1370     BIGNUM *remainder = NULL, *tmp = NULL;
1371     int st = 0;
1372
1373     if (!TEST_ptr(a = getBN(s, "A"))
1374             || !TEST_ptr(square = getBN(s, "Square"))
1375             || !TEST_ptr(zero = BN_new())
1376             || !TEST_ptr(ret = BN_new())
1377             || !TEST_ptr(remainder = BN_new()))
1378         goto err;
1379
1380     BN_zero(zero);
1381     if (!TEST_true(BN_sqr(ret, a, ctx))
1382             || !equalBN("A^2", square, ret)
1383             || !TEST_true(BN_mul(ret, a, a, ctx))
1384             || !equalBN("A * A", square, ret)
1385             || !TEST_true(BN_div(ret, remainder, square, a, ctx))
1386             || !equalBN("Square / A", a, ret)
1387             || !equalBN("Square % A", zero, remainder))
1388         goto err;
1389
1390 #if HAVE_BN_SQRT
1391     BN_set_negative(a, 0);
1392     if (!TEST_true(BN_sqrt(ret, square, ctx))
1393             || !equalBN("sqrt(Square)", a, ret))
1394         goto err;
1395
1396     /* BN_sqrt should fail on non-squares and negative numbers. */
1397     if (!TEST_BN_eq_zero(square)) {
1398         if (!TEST_ptr(tmp = BN_new())
1399                 || !TEST_true(BN_copy(tmp, square)))
1400             goto err;
1401         BN_set_negative(tmp, 1);
1402
1403         if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx), 0))
1404             goto err;
1405         ERR_clear_error();
1406
1407         BN_set_negative(tmp, 0);
1408         if (BN_add(tmp, tmp, BN_value_one()))
1409             goto err;
1410         if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx)))
1411             goto err;
1412         ERR_clear_error();
1413     }
1414 #endif
1415
1416     st = 1;
1417  err:
1418     BN_free(a);
1419     BN_free(square);
1420     BN_free(zero);
1421     BN_free(ret);
1422     BN_free(remainder);
1423     BN_free(tmp);
1424     return st;
1425 }
1426
1427 static int file_product(STANZA *s)
1428 {
1429     BIGNUM *a = NULL, *b = NULL, *product = NULL, *ret = NULL;
1430     BIGNUM *remainder = NULL, *zero = NULL;
1431     int st = 0;
1432
1433     if (!TEST_ptr(a = getBN(s, "A"))
1434             || !TEST_ptr(b = getBN(s, "B"))
1435             || !TEST_ptr(product = getBN(s, "Product"))
1436             || !TEST_ptr(ret = BN_new())
1437             || !TEST_ptr(remainder = BN_new())
1438             || !TEST_ptr(zero = BN_new()))
1439         goto err;
1440
1441     BN_zero(zero);
1442
1443     if (!TEST_true(BN_mul(ret, a, b, ctx))
1444             || !equalBN("A * B", product, ret)
1445             || !TEST_true(BN_div(ret, remainder, product, a, ctx))
1446             || !equalBN("Product / A", b, ret)
1447             || !equalBN("Product % A", zero, remainder)
1448             || !TEST_true(BN_div(ret, remainder, product, b, ctx))
1449             || !equalBN("Product / B", a, ret)
1450             || !equalBN("Product % B", zero, remainder))
1451         goto err;
1452
1453     st = 1;
1454  err:
1455     BN_free(a);
1456     BN_free(b);
1457     BN_free(product);
1458     BN_free(ret);
1459     BN_free(remainder);
1460     BN_free(zero);
1461     return st;
1462 }
1463
1464 static int file_quotient(STANZA *s)
1465 {
1466     BIGNUM *a = NULL, *b = NULL, *quotient = NULL, *remainder = NULL;
1467     BIGNUM *ret = NULL, *ret2 = NULL, *nnmod = NULL;
1468     BN_ULONG b_word, ret_word;
1469     int st = 0;
1470
1471     if (!TEST_ptr(a = getBN(s, "A"))
1472             || !TEST_ptr(b = getBN(s, "B"))
1473             || !TEST_ptr(quotient = getBN(s, "Quotient"))
1474             || !TEST_ptr(remainder = getBN(s, "Remainder"))
1475             || !TEST_ptr(ret = BN_new())
1476             || !TEST_ptr(ret2 = BN_new())
1477             || !TEST_ptr(nnmod = BN_new()))
1478         goto err;
1479
1480     if (!TEST_true(BN_div(ret, ret2, a, b, ctx))
1481             || !equalBN("A / B", quotient, ret)
1482             || !equalBN("A % B", remainder, ret2)
1483             || !TEST_true(BN_mul(ret, quotient, b, ctx))
1484             || !TEST_true(BN_add(ret, ret, remainder))
1485             || !equalBN("Quotient * B + Remainder", a, ret))
1486         goto err;
1487
1488     /*
1489      * Test with BN_mod_word() and BN_div_word() if the divisor is
1490      * small enough.
1491      */
1492     b_word = BN_get_word(b);
1493     if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) {
1494         BN_ULONG remainder_word = BN_get_word(remainder);
1495
1496         assert(remainder_word != (BN_ULONG)-1);
1497         if (!TEST_ptr(BN_copy(ret, a)))
1498             goto err;
1499         ret_word = BN_div_word(ret, b_word);
1500         if (ret_word != remainder_word) {
1501 #ifdef BN_DEC_FMT1
1502             TEST_error(
1503                     "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1,
1504                     ret_word, remainder_word);
1505 #else
1506             TEST_error("Got A %% B (word) mismatch");
1507 #endif
1508             goto err;
1509         }
1510         if (!equalBN ("A / B (word)", quotient, ret))
1511             goto err;
1512
1513         ret_word = BN_mod_word(a, b_word);
1514         if (ret_word != remainder_word) {
1515 #ifdef BN_DEC_FMT1
1516             TEST_error(
1517                     "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1 "",
1518                     ret_word, remainder_word);
1519 #else
1520             TEST_error("Got A %% B (word) mismatch");
1521 #endif
1522             goto err;
1523         }
1524     }
1525
1526     /* Test BN_nnmod. */
1527     if (!BN_is_negative(b)) {
1528         if (!TEST_true(BN_copy(nnmod, remainder))
1529                 || (BN_is_negative(nnmod)
1530                         && !TEST_true(BN_add(nnmod, nnmod, b)))
1531                 || !TEST_true(BN_nnmod(ret, a, b, ctx))
1532                 || !equalBN("A % B (non-negative)", nnmod, ret))
1533             goto err;
1534     }
1535
1536     st = 1;
1537  err:
1538     BN_free(a);
1539     BN_free(b);
1540     BN_free(quotient);
1541     BN_free(remainder);
1542     BN_free(ret);
1543     BN_free(ret2);
1544     BN_free(nnmod);
1545     return st;
1546 }
1547
1548 static int file_modmul(STANZA *s)
1549 {
1550     BIGNUM *a = NULL, *b = NULL, *m = NULL, *mod_mul = NULL, *ret = NULL;
1551     int st = 0;
1552
1553     if (!TEST_ptr(a = getBN(s, "A"))
1554             || !TEST_ptr(b = getBN(s, "B"))
1555             || !TEST_ptr(m = getBN(s, "M"))
1556             || !TEST_ptr(mod_mul = getBN(s, "ModMul"))
1557             || !TEST_ptr(ret = BN_new()))
1558         goto err;
1559
1560     if (!TEST_true(BN_mod_mul(ret, a, b, m, ctx))
1561             || !equalBN("A * B (mod M)", mod_mul, ret))
1562         goto err;
1563
1564     if (BN_is_odd(m)) {
1565         /* Reduce |a| and |b| and test the Montgomery version. */
1566         BN_MONT_CTX *mont = BN_MONT_CTX_new();
1567         BIGNUM *a_tmp = BN_new();
1568         BIGNUM *b_tmp = BN_new();
1569
1570         if (mont == NULL || a_tmp == NULL || b_tmp == NULL
1571                 || !TEST_true(BN_MONT_CTX_set(mont, m, ctx))
1572                 || !TEST_true(BN_nnmod(a_tmp, a, m, ctx))
1573                 || !TEST_true(BN_nnmod(b_tmp, b, m, ctx))
1574                 || !TEST_true(BN_to_montgomery(a_tmp, a_tmp, mont, ctx))
1575                 || !TEST_true(BN_to_montgomery(b_tmp, b_tmp, mont, ctx))
1576                 || !TEST_true(BN_mod_mul_montgomery(ret, a_tmp, b_tmp,
1577                                                     mont, ctx))
1578                 || !TEST_true(BN_from_montgomery(ret, ret, mont, ctx))
1579                 || !equalBN("A * B (mod M) (mont)", mod_mul, ret))
1580             st = 0;
1581         else
1582             st = 1;
1583         BN_MONT_CTX_free(mont);
1584         BN_free(a_tmp);
1585         BN_free(b_tmp);
1586         if (st == 0)
1587             goto err;
1588     }
1589
1590     st = 1;
1591  err:
1592     BN_free(a);
1593     BN_free(b);
1594     BN_free(m);
1595     BN_free(mod_mul);
1596     BN_free(ret);
1597     return st;
1598 }
1599
1600 static int file_modexp(STANZA *s)
1601 {
1602     BIGNUM *a = NULL, *e = NULL, *m = NULL, *mod_exp = NULL, *ret = NULL;
1603     BIGNUM *b = NULL, *c = NULL, *d = NULL;
1604     int st = 0;
1605
1606     if (!TEST_ptr(a = getBN(s, "A"))
1607             || !TEST_ptr(e = getBN(s, "E"))
1608             || !TEST_ptr(m = getBN(s, "M"))
1609             || !TEST_ptr(mod_exp = getBN(s, "ModExp"))
1610             || !TEST_ptr(ret = BN_new())
1611             || !TEST_ptr(d = BN_new()))
1612         goto err;
1613
1614     if (!TEST_true(BN_mod_exp(ret, a, e, m, ctx))
1615             || !equalBN("A ^ E (mod M)", mod_exp, ret))
1616         goto err;
1617
1618     if (BN_is_odd(m)) {
1619         if (!TEST_true(BN_mod_exp_mont(ret, a, e, m, ctx, NULL))
1620                 || !equalBN("A ^ E (mod M) (mont)", mod_exp, ret)
1621                 || !TEST_true(BN_mod_exp_mont_consttime(ret, a, e, m,
1622                                                         ctx, NULL))
1623                 || !equalBN("A ^ E (mod M) (mont const", mod_exp, ret))
1624             goto err;
1625     }
1626
1627     /* Regression test for carry propagation bug in sqr8x_reduction */
1628     BN_hex2bn(&a, "050505050505");
1629     BN_hex2bn(&b, "02");
1630     BN_hex2bn(&c,
1631         "4141414141414141414141274141414141414141414141414141414141414141"
1632         "4141414141414141414141414141414141414141414141414141414141414141"
1633         "4141414141414141414141800000000000000000000000000000000000000000"
1634         "0000000000000000000000000000000000000000000000000000000000000000"
1635         "0000000000000000000000000000000000000000000000000000000000000000"
1636         "0000000000000000000000000000000000000000000000000000000001");
1637     if (!TEST_true(BN_mod_exp(d, a, b, c, ctx))
1638         || !TEST_true(BN_mul(e, a, a, ctx))
1639         || !TEST_BN_eq(d, e))
1640         goto err;
1641
1642     st = 1;
1643  err:
1644     BN_free(a);
1645     BN_free(b);
1646     BN_free(c);
1647     BN_free(d);
1648     BN_free(e);
1649     BN_free(m);
1650     BN_free(mod_exp);
1651     BN_free(ret);
1652     return st;
1653 }
1654
1655 static int file_exp(STANZA *s)
1656 {
1657     BIGNUM *a = NULL, *e = NULL, *exp = NULL, *ret = NULL;
1658     int st = 0;
1659
1660     if (!TEST_ptr(a = getBN(s, "A"))
1661             || !TEST_ptr(e = getBN(s, "E"))
1662             || !TEST_ptr(exp = getBN(s, "Exp"))
1663             || !TEST_ptr(ret = BN_new()))
1664         goto err;
1665
1666     if (!TEST_true(BN_exp(ret, a, e, ctx))
1667             || !equalBN("A ^ E", exp, ret))
1668         goto err;
1669
1670     st = 1;
1671  err:
1672     BN_free(a);
1673     BN_free(e);
1674     BN_free(exp);
1675     BN_free(ret);
1676     return st;
1677 }
1678
1679 static int file_modsqrt(STANZA *s)
1680 {
1681     BIGNUM *a = NULL, *p = NULL, *mod_sqrt = NULL, *ret = NULL, *ret2 = NULL;
1682     int st = 0;
1683
1684     if (!TEST_ptr(a = getBN(s, "A"))
1685             || !TEST_ptr(p = getBN(s, "P"))
1686             || !TEST_ptr(mod_sqrt = getBN(s, "ModSqrt"))
1687             || !TEST_ptr(ret = BN_new())
1688             || !TEST_ptr(ret2 = BN_new()))
1689         goto err;
1690
1691     /* There are two possible answers. */
1692     if (!TEST_true(BN_mod_sqrt(ret, a, p, ctx))
1693             || !TEST_true(BN_sub(ret2, p, ret)))
1694         goto err;
1695
1696     /* The first condition should NOT be a test. */
1697     if (BN_cmp(ret2, mod_sqrt) != 0
1698             && !equalBN("sqrt(A) (mod P)", mod_sqrt, ret))
1699         goto err;
1700
1701     st = 1;
1702  err:
1703     BN_free(a);
1704     BN_free(p);
1705     BN_free(mod_sqrt);
1706     BN_free(ret);
1707     BN_free(ret2);
1708     return st;
1709 }
1710
1711 static int file_gcd(STANZA *s)
1712 {
1713     BIGNUM *a = NULL, *b = NULL, *gcd = NULL, *ret = NULL;
1714     int st = 0;
1715
1716     if (!TEST_ptr(a = getBN(s, "A"))
1717             || !TEST_ptr(b = getBN(s, "B"))
1718             || !TEST_ptr(gcd = getBN(s, "GCD"))
1719             || !TEST_ptr(ret = BN_new()))
1720         goto err;
1721
1722     if (!TEST_true(BN_gcd(ret, a, b, ctx))
1723             || !equalBN("gcd(A,B)", gcd, ret))
1724         goto err;
1725
1726     st = 1;
1727  err:
1728     BN_free(a);
1729     BN_free(b);
1730     BN_free(gcd);
1731     BN_free(ret);
1732     return st;
1733 }
1734
1735 static int test_bn2padded(void)
1736 {
1737 #if HAVE_BN_PADDED
1738     uint8_t zeros[256], out[256], reference[128];
1739     BIGNUM *n = BN_new();
1740     int st = 0;
1741
1742     /* Test edge case at 0. */
1743     if (n == NULL)
1744         goto err;
1745     if (!TEST_true(BN_bn2bin_padded(NULL, 0, n)))
1746         goto err;
1747     memset(out, -1, sizeof(out));
1748     if (!TEST_true(BN_bn2bin_padded(out, sizeof(out)), n))
1749         goto err;
1750     memset(zeros, 0, sizeof(zeros));
1751     if (!TEST_mem_eq(zeros, sizeof(zeros), out, sizeof(out)))
1752         goto err;
1753
1754     /* Test a random numbers at various byte lengths. */
1755     for (size_t bytes = 128 - 7; bytes <= 128; bytes++) {
1756 # define TOP_BIT_ON 0
1757 # define BOTTOM_BIT_NOTOUCH 0
1758         if (!TEST_true(BN_rand(n, bytes * 8, TOP_BIT_ON, BOTTOM_BIT_NOTOUCH)))
1759             goto err;
1760         if (!TEST_int_eq(BN_num_bytes(n),A) bytes
1761                 || TEST_int_eq(BN_bn2bin(n, reference), bytes))
1762             goto err;
1763         /* Empty buffer should fail. */
1764         if (!TEST_int_eq(BN_bn2bin_padded(NULL, 0, n)), 0)
1765             goto err;
1766         /* One byte short should fail. */
1767         if (BN_bn2bin_padded(out, bytes - 1, n))
1768             goto err;
1769         /* Exactly right size should encode. */
1770         if (!TEST_true(BN_bn2bin_padded(out, bytes, n))
1771                 || TEST_mem_eq(out, bytes, reference, bytes))
1772             goto err;
1773         /* Pad up one byte extra. */
1774         if (!TEST_true(BN_bn2bin_padded(out, bytes + 1, n))
1775                 || !TEST_mem_eq(out + 1, bytes, reference, bytes)
1776                 || !TEST_mem_eq(out, 1, zeros, 1))
1777             goto err;
1778         /* Pad up to 256. */
1779         if (!TEST_true(BN_bn2bin_padded(out, sizeof(out)), n)
1780                 || !TEST_mem_eq(out + sizeof(out) - bytes, bytes,
1781                                 reference, bytes)
1782                 || !TEST_mem_eq(out, sizseof(out) - bytes,
1783                                 zeros, sizeof(out) - bytes))
1784             goto err;
1785     }
1786
1787     st = 1;
1788  err:
1789     BN_free(n);
1790     return st;
1791 #else
1792     return ctx != NULL;
1793 #endif
1794 }
1795
1796 static int test_dec2bn(void)
1797 {
1798     BIGNUM *bn = NULL;
1799     int st = 0;
1800
1801     if (!TEST_int_eq(parsedecBN(&bn, "0"), 1)
1802             || !TEST_BN_eq_word(bn, 0)
1803             || !TEST_BN_eq_zero(bn)
1804             || !TEST_BN_le_zero(bn)
1805             || !TEST_BN_ge_zero(bn)
1806             || !TEST_BN_even(bn))
1807         goto err;
1808     BN_free(bn);
1809     bn = NULL;
1810
1811     if (!TEST_int_eq(parsedecBN(&bn, "256"), 3)
1812             || !TEST_BN_eq_word(bn, 256)
1813             || !TEST_BN_ge_zero(bn)
1814             || !TEST_BN_gt_zero(bn)
1815             || !TEST_BN_ne_zero(bn)
1816             || !TEST_BN_even(bn))
1817         goto err;
1818     BN_free(bn);
1819     bn = NULL;
1820
1821     if (!TEST_int_eq(parsedecBN(&bn, "-42"), 3)
1822             || !TEST_BN_abs_eq_word(bn, 42)
1823             || !TEST_BN_lt_zero(bn)
1824             || !TEST_BN_le_zero(bn)
1825             || !TEST_BN_ne_zero(bn)
1826             || !TEST_BN_even(bn))
1827         goto err;
1828     BN_free(bn);
1829     bn = NULL;
1830
1831     if (!TEST_int_eq(parsedecBN(&bn, "1"), 1)
1832             || !TEST_BN_eq_word(bn, 1)
1833             || !TEST_BN_ne_zero(bn)
1834             || !TEST_BN_gt_zero(bn)
1835             || !TEST_BN_ge_zero(bn)
1836             || !TEST_BN_eq_one(bn)
1837             || !TEST_BN_odd(bn))
1838         goto err;
1839     BN_free(bn);
1840     bn = NULL;
1841
1842     if (!TEST_int_eq(parsedecBN(&bn, "-0"), 2)
1843             || !TEST_BN_eq_zero(bn)
1844             || !TEST_BN_ge_zero(bn)
1845             || !TEST_BN_le_zero(bn)
1846             || !TEST_BN_even(bn))
1847         goto err;
1848     BN_free(bn);
1849     bn = NULL;
1850
1851     if (!TEST_int_eq(parsedecBN(&bn, "42trailing garbage is ignored"), 2)
1852             || !TEST_BN_abs_eq_word(bn, 42)
1853             || !TEST_BN_ge_zero(bn)
1854             || !TEST_BN_gt_zero(bn)
1855             || !TEST_BN_ne_zero(bn)
1856             || !TEST_BN_even(bn))
1857         goto err;
1858
1859     st = 1;
1860  err:
1861     BN_free(bn);
1862     return st;
1863 }
1864
1865 static int test_hex2bn(void)
1866 {
1867     BIGNUM *bn = NULL;
1868     int st = 0;
1869
1870     if (!TEST_int_eq(parseBN(&bn, "0"), 1)
1871             || !TEST_BN_eq_zero(bn)
1872             || !TEST_BN_ge_zero(bn)
1873             || !TEST_BN_even(bn))
1874         goto err;
1875     BN_free(bn);
1876     bn = NULL;
1877
1878     if (!TEST_int_eq(parseBN(&bn, "256"), 3)
1879             || !TEST_BN_eq_word(bn, 0x256)
1880             || !TEST_BN_ge_zero(bn)
1881             || !TEST_BN_gt_zero(bn)
1882             || !TEST_BN_ne_zero(bn)
1883             || !TEST_BN_even(bn))
1884         goto err;
1885     BN_free(bn);
1886     bn = NULL;
1887
1888     if (!TEST_int_eq(parseBN(&bn, "-42"), 3)
1889             || !TEST_BN_abs_eq_word(bn, 0x42)
1890             || !TEST_BN_lt_zero(bn)
1891             || !TEST_BN_le_zero(bn)
1892             || !TEST_BN_ne_zero(bn)
1893             || !TEST_BN_even(bn))
1894         goto err;
1895     BN_free(bn);
1896     bn = NULL;
1897
1898     if (!TEST_int_eq(parseBN(&bn, "cb"), 2)
1899             || !TEST_BN_eq_word(bn, 0xCB)
1900             || !TEST_BN_ge_zero(bn)
1901             || !TEST_BN_gt_zero(bn)
1902             || !TEST_BN_ne_zero(bn)
1903             || !TEST_BN_odd(bn))
1904         goto err;
1905     BN_free(bn);
1906     bn = NULL;
1907
1908     if (!TEST_int_eq(parseBN(&bn, "-0"), 2)
1909             || !TEST_BN_eq_zero(bn)
1910             || !TEST_BN_ge_zero(bn)
1911             || !TEST_BN_le_zero(bn)
1912             || !TEST_BN_even(bn))
1913         goto err;
1914     BN_free(bn);
1915     bn = NULL;
1916
1917     if (!TEST_int_eq(parseBN(&bn, "abctrailing garbage is ignored"), 3)
1918             || !TEST_BN_eq_word(bn, 0xabc)
1919             || !TEST_BN_ge_zero(bn)
1920             || !TEST_BN_gt_zero(bn)
1921             || !TEST_BN_ne_zero(bn)
1922             || !TEST_BN_even(bn))
1923         goto err;
1924     st = 1;
1925
1926  err:
1927     BN_free(bn);
1928     return st;
1929 }
1930
1931 static int test_asc2bn(void)
1932 {
1933     BIGNUM *bn = NULL;
1934     int st = 0;
1935
1936     if (!TEST_ptr(bn = BN_new()))
1937         goto err;
1938
1939     if (!TEST_true(BN_asc2bn(&bn, "0"))
1940             || !TEST_BN_eq_zero(bn)
1941             || !TEST_BN_ge_zero(bn))
1942         goto err;
1943
1944     if (!TEST_true(BN_asc2bn(&bn, "256"))
1945             || !TEST_BN_eq_word(bn, 256)
1946             || !TEST_BN_ge_zero(bn))
1947         goto err;
1948
1949     if (!TEST_true(BN_asc2bn(&bn, "-42"))
1950             || !TEST_BN_abs_eq_word(bn, 42)
1951             || !TEST_BN_lt_zero(bn))
1952         goto err;
1953
1954     if (!TEST_true(BN_asc2bn(&bn, "0x1234"))
1955             || !TEST_BN_eq_word(bn, 0x1234)
1956             || !TEST_BN_ge_zero(bn))
1957         goto err;
1958
1959     if (!TEST_true(BN_asc2bn(&bn, "0X1234"))
1960             || !TEST_BN_eq_word(bn, 0x1234)
1961             || !TEST_BN_ge_zero(bn))
1962         goto err;
1963
1964     if (!TEST_true(BN_asc2bn(&bn, "-0xabcd"))
1965             || !TEST_BN_abs_eq_word(bn, 0xabcd)
1966             || !TEST_BN_lt_zero(bn))
1967         goto err;
1968
1969     if (!TEST_true(BN_asc2bn(&bn, "-0"))
1970             || !TEST_BN_eq_zero(bn)
1971             || !TEST_BN_ge_zero(bn))
1972         goto err;
1973
1974     if (!TEST_true(BN_asc2bn(&bn, "123trailing garbage is ignored"))
1975             || !TEST_BN_eq_word(bn, 123)
1976             || !TEST_BN_ge_zero(bn))
1977         goto err;
1978
1979     st = 1;
1980  err:
1981     BN_free(bn);
1982     return st;
1983 }
1984
1985 static const MPITEST kMPITests[] = {
1986     {"0", "\x00\x00\x00\x00", 4},
1987     {"1", "\x00\x00\x00\x01\x01", 5},
1988     {"-1", "\x00\x00\x00\x01\x81", 5},
1989     {"128", "\x00\x00\x00\x02\x00\x80", 6},
1990     {"256", "\x00\x00\x00\x02\x01\x00", 6},
1991     {"-256", "\x00\x00\x00\x02\x81\x00", 6},
1992 };
1993
1994 static int test_mpi(int i)
1995 {
1996     uint8_t scratch[8];
1997     const MPITEST *test = &kMPITests[i];
1998     size_t mpi_len, mpi_len2;
1999     BIGNUM *bn = NULL;
2000     BIGNUM *bn2 = NULL;
2001     int st = 0;
2002
2003     if (!TEST_ptr(bn = BN_new())
2004             || !TEST_true(BN_asc2bn(&bn, test->base10)))
2005         goto err;
2006     mpi_len = BN_bn2mpi(bn, NULL);
2007     if (!TEST_size_t_le(mpi_len, sizeof(scratch)))
2008         goto err;
2009
2010     if (!TEST_size_t_eq(mpi_len2 = BN_bn2mpi(bn, scratch), mpi_len)
2011             || !TEST_mem_eq(test->mpi, test->mpi_len, scratch, mpi_len))
2012         goto err;
2013
2014     if (!TEST_ptr(bn2 = BN_mpi2bn(scratch, mpi_len, NULL)))
2015         goto err;
2016
2017     if (!TEST_BN_eq(bn, bn2)) {
2018         BN_free(bn2);
2019         goto err;
2020     }
2021     BN_free(bn2);
2022
2023     st = 1;
2024  err:
2025     BN_free(bn);
2026     return st;
2027 }
2028
2029 static int test_rand(void)
2030 {
2031     BIGNUM *bn = NULL;
2032     int st = 0;
2033
2034     if (!TEST_ptr(bn = BN_new()))
2035         return 0;
2036
2037     /* Test BN_rand for degenerate cases with |top| and |bottom| parameters. */
2038     if (!TEST_false(BN_rand(bn, 0, 0 /* top */ , 0 /* bottom */ ))
2039             || !TEST_false(BN_rand(bn, 0, 1 /* top */ , 1 /* bottom */ ))
2040             || !TEST_true(BN_rand(bn, 1, 0 /* top */ , 0 /* bottom */ ))
2041             || !TEST_BN_eq_one(bn)
2042             || !TEST_false(BN_rand(bn, 1, 1 /* top */ , 0 /* bottom */ ))
2043             || !TEST_true(BN_rand(bn, 1, -1 /* top */ , 1 /* bottom */ ))
2044             || !TEST_BN_eq_one(bn)
2045             || !TEST_true(BN_rand(bn, 2, 1 /* top */ , 0 /* bottom */ ))
2046             || !TEST_BN_eq_word(bn, 3))
2047         goto err;
2048
2049     st = 1;
2050  err:
2051     BN_free(bn);
2052     return st;
2053 }
2054
2055 /*
2056  * Run some statistical tests to provide a degree confidence that the
2057  * BN_rand_range() function works as expected.  The test cases and
2058  * critical values are generated by the bn_rand_range script.
2059  *
2060  * Each individual test is a Chi^2 goodness of fit for a specified number
2061  * of samples and range.  The samples are assumed to be independent and
2062  * that they are from a discrete uniform distribution.
2063  *
2064  * Some of these individual tests are expected to fail, the success/failure
2065  * of each is an independent Bernoulli trial.  The number of such successes
2066  * will form a binomial distribution.  The count of the successes is compared
2067  * against a precomputed critical value to determine the overall outcome.
2068  */
2069 struct rand_range_case {
2070     unsigned int range;
2071     unsigned int iterations;
2072     double critical;
2073 };
2074
2075 #include "bn_rand_range.h"
2076
2077 static int test_rand_range_single(size_t n)
2078 {
2079     const unsigned int range = rand_range_cases[n].range;
2080     const unsigned int iterations = rand_range_cases[n].iterations;
2081     const double critical = rand_range_cases[n].critical;
2082     const double expected = iterations / (double)range;
2083     double sum = 0;
2084     BIGNUM *rng = NULL, *val = NULL;
2085     size_t *counts;
2086     unsigned int i, v;
2087     int res = 0;
2088
2089     if (!TEST_ptr(counts = OPENSSL_zalloc(sizeof(*counts) * range))
2090         || !TEST_ptr(rng = BN_new())
2091         || !TEST_ptr(val = BN_new())
2092         || !TEST_true(BN_set_word(rng, range)))
2093         goto err;
2094     for (i = 0; i < iterations; i++) {
2095         if (!TEST_true(BN_rand_range(val, rng))
2096             || !TEST_uint_lt(v = (unsigned int)BN_get_word(val), range))
2097             goto err;
2098         counts[v]++;
2099     }
2100
2101     for (i = 0; i < range; i++) {
2102         const double delta = counts[i] - expected;
2103         sum += delta * delta;
2104     }
2105     sum /= expected;
2106
2107     if (sum > critical) {
2108         TEST_info("Chi^2 test negative %.4f > %4.f", sum, critical);
2109         TEST_note("test case %zu  range %u  iterations %u", n + 1, range,
2110                   iterations);
2111         goto err;
2112     }
2113
2114     res = 1;
2115 err:
2116     BN_free(rng);
2117     BN_free(val);
2118     OPENSSL_free(counts);
2119     return res;
2120 }
2121
2122 static int test_rand_range(void)
2123 {
2124     int n_success = 0;
2125     size_t i;
2126
2127     for (i = 0; i < OSSL_NELEM(rand_range_cases); i++)
2128         n_success += test_rand_range_single(i);
2129     if (TEST_int_ge(n_success, binomial_critical))
2130         return 1;
2131     TEST_note("This test is expected to fail by chance 0.01%% of the time.");
2132     return 0;
2133 }
2134
2135 static int test_negzero(void)
2136 {
2137     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
2138     BIGNUM *numerator = NULL, *denominator = NULL;
2139     int consttime, st = 0;
2140
2141     if (!TEST_ptr(a = BN_new())
2142             || !TEST_ptr(b = BN_new())
2143             || !TEST_ptr(c = BN_new())
2144             || !TEST_ptr(d = BN_new()))
2145         goto err;
2146
2147     /* Test that BN_mul never gives negative zero. */
2148     if (!TEST_true(BN_set_word(a, 1)))
2149         goto err;
2150     BN_set_negative(a, 1);
2151     BN_zero(b);
2152     if (!TEST_true(BN_mul(c, a, b, ctx)))
2153         goto err;
2154     if (!TEST_BN_eq_zero(c)
2155             || !TEST_BN_ge_zero(c))
2156         goto err;
2157
2158     for (consttime = 0; consttime < 2; consttime++) {
2159         if (!TEST_ptr(numerator = BN_new())
2160                 || !TEST_ptr(denominator = BN_new()))
2161             goto err;
2162         if (consttime) {
2163             BN_set_flags(numerator, BN_FLG_CONSTTIME);
2164             BN_set_flags(denominator, BN_FLG_CONSTTIME);
2165         }
2166         /* Test that BN_div never gives negative zero in the quotient. */
2167         if (!TEST_true(BN_set_word(numerator, 1))
2168                 || !TEST_true(BN_set_word(denominator, 2)))
2169             goto err;
2170         BN_set_negative(numerator, 1);
2171         if (!TEST_true(BN_div(a, b, numerator, denominator, ctx))
2172                 || !TEST_BN_eq_zero(a)
2173                 || !TEST_BN_ge_zero(a))
2174             goto err;
2175
2176         /* Test that BN_div never gives negative zero in the remainder. */
2177         if (!TEST_true(BN_set_word(denominator, 1))
2178                 || !TEST_true(BN_div(a, b, numerator, denominator, ctx))
2179                 || !TEST_BN_eq_zero(b)
2180                 || !TEST_BN_ge_zero(b))
2181             goto err;
2182         BN_free(numerator);
2183         BN_free(denominator);
2184         numerator = denominator = NULL;
2185     }
2186
2187     /* Test that BN_set_negative will not produce a negative zero. */
2188     BN_zero(a);
2189     BN_set_negative(a, 1);
2190     if (BN_is_negative(a))
2191         goto err;
2192     st = 1;
2193
2194  err:
2195     BN_free(a);
2196     BN_free(b);
2197     BN_free(c);
2198     BN_free(d);
2199     BN_free(numerator);
2200     BN_free(denominator);
2201     return st;
2202 }
2203
2204 static int test_badmod(void)
2205 {
2206     BIGNUM *a = NULL, *b = NULL, *zero = NULL;
2207     BN_MONT_CTX *mont = NULL;
2208     int st = 0;
2209
2210     if (!TEST_ptr(a = BN_new())
2211             || !TEST_ptr(b = BN_new())
2212             || !TEST_ptr(zero = BN_new())
2213             || !TEST_ptr(mont = BN_MONT_CTX_new()))
2214         goto err;
2215     BN_zero(zero);
2216
2217     if (!TEST_false(BN_div(a, b, BN_value_one(), zero, ctx)))
2218         goto err;
2219     ERR_clear_error();
2220
2221     if (!TEST_false(BN_mod_mul(a, BN_value_one(), BN_value_one(), zero, ctx)))
2222         goto err;
2223     ERR_clear_error();
2224
2225     if (!TEST_false(BN_mod_exp(a, BN_value_one(), BN_value_one(), zero, ctx)))
2226         goto err;
2227     ERR_clear_error();
2228
2229     if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(),
2230                                     zero, ctx, NULL)))
2231         goto err;
2232     ERR_clear_error();
2233
2234     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
2235                                               zero, ctx, NULL)))
2236         goto err;
2237     ERR_clear_error();
2238
2239     if (!TEST_false(BN_MONT_CTX_set(mont, zero, ctx)))
2240         goto err;
2241     ERR_clear_error();
2242
2243     /* Some operations also may not be used with an even modulus. */
2244     if (!TEST_true(BN_set_word(b, 16)))
2245         goto err;
2246
2247     if (!TEST_false(BN_MONT_CTX_set(mont, b, ctx)))
2248         goto err;
2249     ERR_clear_error();
2250
2251     if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(),
2252                                     b, ctx, NULL)))
2253         goto err;
2254     ERR_clear_error();
2255
2256     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
2257                                               b, ctx, NULL)))
2258         goto err;
2259     ERR_clear_error();
2260
2261     st = 1;
2262  err:
2263     BN_free(a);
2264     BN_free(b);
2265     BN_free(zero);
2266     BN_MONT_CTX_free(mont);
2267     return st;
2268 }
2269
2270 static int test_expmodzero(void)
2271 {
2272     BIGNUM *a = NULL, *r = NULL, *zero = NULL;
2273     int st = 0;
2274
2275     if (!TEST_ptr(zero = BN_new())
2276             || !TEST_ptr(a = BN_new())
2277             || !TEST_ptr(r = BN_new()))
2278         goto err;
2279     BN_zero(zero);
2280
2281     if (!TEST_true(BN_mod_exp(r, a, zero, BN_value_one(), NULL))
2282             || !TEST_BN_eq_zero(r)
2283             || !TEST_true(BN_mod_exp_mont(r, a, zero, BN_value_one(),
2284                                           NULL, NULL))
2285             || !TEST_BN_eq_zero(r)
2286             || !TEST_true(BN_mod_exp_mont_consttime(r, a, zero,
2287                                                     BN_value_one(),
2288                                                     NULL, NULL))
2289             || !TEST_BN_eq_zero(r)
2290             || !TEST_true(BN_mod_exp_mont_word(r, 42, zero,
2291                                                BN_value_one(), NULL, NULL))
2292             || !TEST_BN_eq_zero(r))
2293         goto err;
2294
2295     st = 1;
2296  err:
2297     BN_free(zero);
2298     BN_free(a);
2299     BN_free(r);
2300     return st;
2301 }
2302
2303 static int test_expmodone(void)
2304 {
2305     int ret = 0, i;
2306     BIGNUM *r = BN_new();
2307     BIGNUM *a = BN_new();
2308     BIGNUM *p = BN_new();
2309     BIGNUM *m = BN_new();
2310
2311     if (!TEST_ptr(r)
2312             || !TEST_ptr(a)
2313             || !TEST_ptr(p)
2314             || !TEST_ptr(p)
2315             || !TEST_ptr(m)
2316             || !TEST_true(BN_set_word(a, 1))
2317             || !TEST_true(BN_set_word(p, 0))
2318             || !TEST_true(BN_set_word(m, 1)))
2319         goto err;
2320
2321     /* Calculate r = 1 ^ 0 mod 1, and check the result is always 0 */
2322     for (i = 0; i < 2; i++) {
2323         if (!TEST_true(BN_mod_exp(r, a, p, m, NULL))
2324                 || !TEST_BN_eq_zero(r)
2325                 || !TEST_true(BN_mod_exp_mont(r, a, p, m, NULL, NULL))
2326                 || !TEST_BN_eq_zero(r)
2327                 || !TEST_true(BN_mod_exp_mont_consttime(r, a, p, m, NULL, NULL))
2328                 || !TEST_BN_eq_zero(r)
2329                 || !TEST_true(BN_mod_exp_mont_word(r, 1, p, m, NULL, NULL))
2330                 || !TEST_BN_eq_zero(r)
2331                 || !TEST_true(BN_mod_exp_simple(r, a, p, m, NULL))
2332                 || !TEST_BN_eq_zero(r)
2333                 || !TEST_true(BN_mod_exp_recp(r, a, p, m, NULL))
2334                 || !TEST_BN_eq_zero(r))
2335             goto err;
2336         /* Repeat for r = 1 ^ 0 mod -1 */
2337         if (i == 0)
2338             BN_set_negative(m, 1);
2339     }
2340
2341     ret = 1;
2342  err:
2343     BN_free(r);
2344     BN_free(a);
2345     BN_free(p);
2346     BN_free(m);
2347     return ret;
2348 }
2349
2350 static int test_smallprime(int kBits)
2351 {
2352     BIGNUM *r;
2353     int st = 0;
2354
2355     if (!TEST_ptr(r = BN_new()))
2356         goto err;
2357
2358     if (kBits <= 1) {
2359         if (!TEST_false(BN_generate_prime_ex(r, kBits, 0,
2360                                              NULL, NULL, NULL)))
2361             goto err;
2362     } else {
2363         if (!TEST_true(BN_generate_prime_ex(r, kBits, 0,
2364                                             NULL, NULL, NULL))
2365                 || !TEST_int_eq(BN_num_bits(r), kBits))
2366             goto err;
2367     }
2368
2369     st = 1;
2370  err:
2371     BN_free(r);
2372     return st;
2373 }
2374
2375 static int test_smallsafeprime(int kBits)
2376 {
2377     BIGNUM *r;
2378     int st = 0;
2379
2380     if (!TEST_ptr(r = BN_new()))
2381         goto err;
2382
2383     if (kBits <= 5 && kBits != 3) {
2384         if (!TEST_false(BN_generate_prime_ex(r, kBits, 1,
2385                                              NULL, NULL, NULL)))
2386             goto err;
2387     } else {
2388         if (!TEST_true(BN_generate_prime_ex(r, kBits, 1,
2389                                             NULL, NULL, NULL))
2390                 || !TEST_int_eq(BN_num_bits(r), kBits))
2391             goto err;
2392     }
2393
2394     st = 1;
2395  err:
2396     BN_free(r);
2397     return st;
2398 }
2399
2400 static int primes[] = { 2, 3, 5, 7, 17863 };
2401
2402 static int test_is_prime(int i)
2403 {
2404     int ret = 0;
2405     BIGNUM *r = NULL;
2406     int trial;
2407
2408     if (!TEST_ptr(r = BN_new()))
2409         goto err;
2410
2411     for (trial = 0; trial <= 1; ++trial) {
2412         if (!TEST_true(BN_set_word(r, primes[i]))
2413                 || !TEST_int_eq(BN_check_prime(r, ctx, NULL),
2414                                 1))
2415             goto err;
2416     }
2417
2418     ret = 1;
2419  err:
2420     BN_free(r);
2421     return ret;
2422 }
2423
2424 static int not_primes[] = { -1, 0, 1, 4 };
2425
2426 static int test_not_prime(int i)
2427 {
2428     int ret = 0;
2429     BIGNUM *r = NULL;
2430     int trial;
2431
2432     if (!TEST_ptr(r = BN_new()))
2433         goto err;
2434
2435     for (trial = 0; trial <= 1; ++trial) {
2436         if (!TEST_true(BN_set_word(r, not_primes[i]))
2437                 || !TEST_false(BN_check_prime(r, ctx, NULL)))
2438             goto err;
2439     }
2440
2441     ret = 1;
2442  err:
2443     BN_free(r);
2444     return ret;
2445 }
2446
2447 static int test_ctx_set_ct_flag(BN_CTX *c)
2448 {
2449     int st = 0;
2450     size_t i;
2451     BIGNUM *b[15];
2452
2453     BN_CTX_start(c);
2454     for (i = 0; i < OSSL_NELEM(b); i++) {
2455         if (!TEST_ptr(b[i] = BN_CTX_get(c)))
2456             goto err;
2457         if (i % 2 == 1)
2458             BN_set_flags(b[i], BN_FLG_CONSTTIME);
2459     }
2460
2461     st = 1;
2462  err:
2463     BN_CTX_end(c);
2464     return st;
2465 }
2466
2467 static int test_ctx_check_ct_flag(BN_CTX *c)
2468 {
2469     int st = 0;
2470     size_t i;
2471     BIGNUM *b[30];
2472
2473     BN_CTX_start(c);
2474     for (i = 0; i < OSSL_NELEM(b); i++) {
2475         if (!TEST_ptr(b[i] = BN_CTX_get(c)))
2476             goto err;
2477         if (!TEST_false(BN_get_flags(b[i], BN_FLG_CONSTTIME)))
2478             goto err;
2479     }
2480
2481     st = 1;
2482  err:
2483     BN_CTX_end(c);
2484     return st;
2485 }
2486
2487 static int test_ctx_consttime_flag(void)
2488 {
2489     /*-
2490      * The constant-time flag should not "leak" among BN_CTX frames:
2491      *
2492      * - test_ctx_set_ct_flag() starts a frame in the given BN_CTX and
2493      *   sets the BN_FLG_CONSTTIME flag on some of the BIGNUMs obtained
2494      *   from the frame before ending it.
2495      * - test_ctx_check_ct_flag() then starts a new frame and gets a
2496      *   number of BIGNUMs from it. In absence of leaks, none of the
2497      *   BIGNUMs in the new frame should have BN_FLG_CONSTTIME set.
2498      *
2499      * In actual BN_CTX usage inside libcrypto the leak could happen at
2500      * any depth level in the BN_CTX stack, with varying results
2501      * depending on the patterns of sibling trees of nested function
2502      * calls sharing the same BN_CTX object, and the effect of
2503      * unintended BN_FLG_CONSTTIME on the called BN_* functions.
2504      *
2505      * This simple unit test abstracts away this complexity and verifies
2506      * that the leak does not happen between two sibling functions
2507      * sharing the same BN_CTX object at the same level of nesting.
2508      *
2509      */
2510     BN_CTX *nctx = NULL;
2511     BN_CTX *sctx = NULL;
2512     size_t i = 0;
2513     int st = 0;
2514
2515     if (!TEST_ptr(nctx = BN_CTX_new())
2516             || !TEST_ptr(sctx = BN_CTX_secure_new()))
2517         goto err;
2518
2519     for (i = 0; i < 2; i++) {
2520         BN_CTX *c = i == 0 ? nctx : sctx;
2521         if (!TEST_true(test_ctx_set_ct_flag(c))
2522                 || !TEST_true(test_ctx_check_ct_flag(c)))
2523             goto err;
2524     }
2525
2526     st = 1;
2527  err:
2528     BN_CTX_free(nctx);
2529     BN_CTX_free(sctx);
2530     return st;
2531 }
2532
2533 static int test_gcd_prime(void)
2534 {
2535     BIGNUM *a = NULL, *b = NULL, *gcd = NULL;
2536     int i, st = 0;
2537
2538     if (!TEST_ptr(a = BN_new())
2539             || !TEST_ptr(b = BN_new())
2540             || !TEST_ptr(gcd = BN_new()))
2541         goto err;
2542
2543     if (!TEST_true(BN_generate_prime_ex(a, 1024, 0, NULL, NULL, NULL)))
2544             goto err;
2545     for (i = 0; i < NUM0; i++) {
2546         if (!TEST_true(BN_generate_prime_ex(b, 1024, 0,
2547                                             NULL, NULL, NULL))
2548                 || !TEST_true(BN_gcd(gcd, a, b, ctx))
2549                 || !TEST_true(BN_is_one(gcd)))
2550             goto err;
2551     }
2552
2553     st = 1;
2554  err:
2555     BN_free(a);
2556     BN_free(b);
2557     BN_free(gcd);
2558     return st;
2559 }
2560
2561 typedef struct mod_exp_test_st
2562 {
2563   const char *base;
2564   const char *exp;
2565   const char *mod;
2566   const char *res;
2567 } MOD_EXP_TEST;
2568
2569 static const MOD_EXP_TEST ModExpTests[] = {
2570    /* original test vectors for rsaz_512_sqr bug, by OSS-Fuzz */
2571    {
2572        "1166180238001879113042182292626169621106255558914000595999312084"
2573        "4627946820899490684928760491249738643524880720584249698100907201"
2574        "002086675047927600340800371",
2575        "8000000000000000000000000000000000000000000000000000000000000000"
2576        "0000000000000000000000000000000000000000000000000000000000000000"
2577        "00000000",
2578        "1340780792684523720980737645613191762604395855615117867483316354"
2579        "3294276330515137663421134775482798690129946803802212663956180562"
2580        "088664022929883876655300863",
2581        "8243904058268085430037326628480645845409758077568738532059032482"
2582        "8294114415890603594730158120426756266457928475330450251339773498"
2583        "26758407619521544102068438"
2584    },
2585    {
2586        "4974270041410803822078866696159586946995877618987010219312844726"
2587        "0284386121835740784990869050050504348861513337232530490826340663"
2588        "197278031692737429054",
2589        "4974270041410803822078866696159586946995877428188754995041148539"
2590        "1663243362592271353668158565195557417149981094324650322556843202"
2591        "946445882670777892608",
2592        "1340780716511420227215592830971452482815377482627251725537099028"
2593        "4429769497230131760206012644403029349547320953206103351725462999"
2594        "947509743623340557059752191",
2595        "5296244594780707015616522701706118082963369547253192207884519362"
2596        "1767869984947542695665420219028522815539559194793619684334900442"
2597        "49304558011362360473525933"
2598    },
2599    /* test vectors for rsaz_512_srq bug, with rcx/rbx=1 */
2600    {   /* between first and second iteration */
2601        "5148719036160389201525610950887605325980251964889646556085286545"
2602        "3931548809178823413169359635978762036512397113080988070677858033"
2603        "36463909753993540214027190",
2604        "6703903964971298549787012499102923063739682910296196688861780721"
2605        "8608820150367734884009371490834517138450159290932430254268769414"
2606        "05973284973216824503042158",
2607        "6703903964971298549787012499102923063739682910296196688861780721"
2608        "8608820150367734884009371490834517138450159290932430254268769414"
2609        "05973284973216824503042159",
2610        "1"
2611    },
2612    {   /* between second and third iteration */
2613        "8908340854353752577419678771330460827942371434853054158622636544"
2614        "8151360109722890949471912566649465436296659601091730745087014189"
2615        "2672764191218875181826063",
2616        "6703903964971298549787012499102923063739682910296196688861780721"
2617        "8608820150367734884009371490834517138450159290932430254268769414"
2618        "05973284973216824503042158",
2619        "6703903964971298549787012499102923063739682910296196688861780721"
2620        "8608820150367734884009371490834517138450159290932430254268769414"
2621        "05973284973216824503042159",
2622        "1"
2623    },
2624    {   /* between third and fourth iteration */
2625        "3427446396505596330634350984901719674479522569002785244080234738"
2626        "4288743635435746136297299366444548736533053717416735379073185344"
2627        "26985272974404612945608761",
2628        "6703903964971298549787012499102923063739682910296196688861780721"
2629        "8608820150367734884009371490834517138450159290932430254268769414"
2630        "05973284973216824503042158",
2631        "6703903964971298549787012499102923063739682910296196688861780721"
2632        "8608820150367734884009371490834517138450159290932430254268769414"
2633        "05973284973216824503042159",
2634        "1"
2635    },
2636    {   /* between fourth and fifth iteration */
2637        "3472743044917564564078857826111874560045331237315597383869652985"
2638        "6919870028890895988478351133601517365908445058405433832718206902"
2639        "4088133164805266956353542",
2640        "6703903964971298549787012499102923063739682910296196688861780721"
2641        "8608820150367734884009371490834517138450159290932430254268769414"
2642        "05973284973216824503042158",
2643        "6703903964971298549787012499102923063739682910296196688861780721"
2644        "8608820150367734884009371490834517138450159290932430254268769414"
2645        "05973284973216824503042159",
2646        "1"
2647    },
2648    {   /* between fifth and sixth iteration */
2649        "3608632990153469264412378349742339216742409743898601587274768025"
2650        "0110772032985643555192767717344946174122842255204082586753499651"
2651        "14483434992887431333675068",
2652        "6703903964971298549787012499102923063739682910296196688861780721"
2653        "8608820150367734884009371490834517138450159290932430254268769414"
2654        "05973284973216824503042158",
2655        "6703903964971298549787012499102923063739682910296196688861780721"
2656        "8608820150367734884009371490834517138450159290932430254268769414"
2657        "05973284973216824503042159",
2658        "1"
2659    },
2660    {   /* between sixth and seventh iteration */
2661        "8455374370234070242910508226941981520235709767260723212165264877"
2662        "8689064388017521524568434328264431772644802567028663962962025746"
2663        "9283458217850119569539086",
2664        "6703903964971298549787012499102923063739682910296196688861780721"
2665        "8608820150367734884009371490834517138450159290932430254268769414"
2666        "05973284973216824503042158",
2667        "6703903964971298549787012499102923063739682910296196688861780721"
2668        "8608820150367734884009371490834517138450159290932430254268769414"
2669        "05973284973216824503042159",
2670        "1"
2671    },
2672    {   /* between seventh and eighth iteration */
2673        "5155371529688532178421209781159131443543419764974688878527112131"
2674        "7446518205609427412336183157918981038066636807317733319323257603"
2675        "04416292040754017461076359",
2676        "1005585594745694782468051874865438459560952436544429503329267108"
2677        "2791323022555160232601405723625177570767523893639864538140315412"
2678        "108959927459825236754563832",
2679        "1005585594745694782468051874865438459560952436544429503329267108"
2680        "2791323022555160232601405723625177570767523893639864538140315412"
2681        "108959927459825236754563833",
2682        "1"
2683    },
2684    /* test vectors for rsaz_512_srq bug, with rcx/rbx=2 */
2685    {   /* between first and second iteration */
2686        "3155666506033786929967309937640790361084670559125912405342594979"
2687        "4345142818528956285490897841406338022378565972533508820577760065"
2688        "58494345853302083699912572",
2689        "6703903964971298549787012499102923063739682910296196688861780721"
2690        "8608820150367734884009371490834517138450159290932430254268769414"
2691        "05973284973216824503042158",
2692        "6703903964971298549787012499102923063739682910296196688861780721"
2693        "8608820150367734884009371490834517138450159290932430254268769414"
2694        "05973284973216824503042159",
2695        "1"
2696    },
2697    {   /* between second and third iteration */
2698        "3789819583801342198190405714582958759005991915505282362397087750"
2699        "4213544724644823098843135685133927198668818185338794377239590049"
2700        "41019388529192775771488319",
2701        "6703903964971298549787012499102923063739682910296196688861780721"
2702        "8608820150367734884009371490834517138450159290932430254268769414"
2703        "05973284973216824503042158",
2704        "6703903964971298549787012499102923063739682910296196688861780721"
2705        "8608820150367734884009371490834517138450159290932430254268769414"
2706        "05973284973216824503042159",
2707        "1"
2708    },
2709    {   /* between third and forth iteration */
2710        "4695752552040706867080542538786056470322165281761525158189220280"
2711        "4025547447667484759200742764246905647644662050122968912279199065"
2712        "48065034299166336940507214",
2713        "6703903964971298549787012499102923063739682910296196688861780721"
2714        "8608820150367734884009371490834517138450159290932430254268769414"
2715        "05973284973216824503042158",
2716        "6703903964971298549787012499102923063739682910296196688861780721"
2717        "8608820150367734884009371490834517138450159290932430254268769414"
2718        "05973284973216824503042159",
2719        "1"
2720    },
2721    {   /* between forth and fifth iteration */
2722        "2159140240970485794188159431017382878636879856244045329971239574"
2723        "8919691133560661162828034323196457386059819832804593989740268964"
2724        "74502911811812651475927076",
2725        "6703903964971298549787012499102923063739682910296196688861780721"
2726        "8608820150367734884009371490834517138450159290932430254268769414"
2727        "05973284973216824503042158",
2728        "6703903964971298549787012499102923063739682910296196688861780721"
2729        "8608820150367734884009371490834517138450159290932430254268769414"
2730        "05973284973216824503042159",
2731        "1"
2732    },
2733    {   /* between fifth and sixth iteration */
2734        "5239312332984325668414624633307915097111691815000872662334695514"
2735        "5436533521392362443557163429336808208137221322444780490437871903"
2736        "99972784701334569424519255",
2737        "6703903964971298549787012499102923063739682910296196688861780721"
2738        "8608820150367734884009371490834517138450159290932430254268769414"
2739        "05973284973216824503042158",
2740        "6703903964971298549787012499102923063739682910296196688861780721"
2741        "8608820150367734884009371490834517138450159290932430254268769414"
2742        "05973284973216824503042159",
2743        "1"
2744    },
2745    {   /* between sixth and seventh iteration */
2746        "1977953647322612860406858017869125467496941904523063466791308891"
2747        "1172796739058531929470539758361774569875505293428856181093904091"
2748        "33788264851714311303725089",
2749        "6703903964971298549787012499102923063739682910296196688861780721"
2750        "8608820150367734884009371490834517138450159290932430254268769414"
2751        "05973284973216824503042158",
2752        "6703903964971298549787012499102923063739682910296196688861780721"
2753        "8608820150367734884009371490834517138450159290932430254268769414"
2754        "05973284973216824503042159",
2755        "1"
2756    },
2757    {   /* between seventh and eighth iteration */
2758        "6456987954117763835533395796948878140715006860263624787492985786"
2759        "8514630216966738305923915688821526449499763719943997120302368211"
2760        "04813318117996225041943964",
2761        "1340780792994259709957402499820584612747936582059239337772356144"
2762        "3721764030073546976801874298166903427690031858186486050853753882"
2763        "811946551499689575296532556",
2764        "1340780792994259709957402499820584612747936582059239337772356144"
2765        "3721764030073546976801874298166903427690031858186486050853753882"
2766        "811946551499689575296532557",
2767        "1"
2768    }
2769 };
2770
2771 static int test_mod_exp(int i)
2772 {
2773     const MOD_EXP_TEST *test = &ModExpTests[i];
2774     int res = 0;
2775     BIGNUM* result = NULL;
2776     BIGNUM *base = NULL, *exponent = NULL, *modulo = NULL;
2777     char *s = NULL;
2778
2779     if (!TEST_ptr(result = BN_new())
2780             || !TEST_true(BN_dec2bn(&base, test->base))
2781             || !TEST_true(BN_dec2bn(&exponent, test->exp))
2782             || !TEST_true(BN_dec2bn(&modulo, test->mod)))
2783         goto err;
2784
2785     if (!TEST_int_eq(BN_mod_exp(result, base, exponent, modulo, ctx), 1))
2786         goto err;
2787
2788     if (!TEST_ptr(s = BN_bn2dec(result)))
2789         goto err;
2790
2791     if (!TEST_mem_eq(s, strlen(s), test->res, strlen(test->res)))
2792         goto err;
2793
2794     res = 1;
2795
2796  err:
2797     OPENSSL_free(s);
2798     BN_free(result);
2799     BN_free(base);
2800     BN_free(exponent);
2801     BN_free(modulo);
2802     return res;
2803 }
2804
2805 static int test_mod_exp_consttime(int i)
2806 {
2807     const MOD_EXP_TEST *test = &ModExpTests[i];
2808     int res = 0;
2809     BIGNUM* result = NULL;
2810     BIGNUM *base = NULL, *exponent = NULL, *modulo = NULL;
2811     char *s = NULL;
2812
2813     if (!TEST_ptr(result = BN_new())
2814             || !TEST_true(BN_dec2bn(&base, test->base))
2815             || !TEST_true(BN_dec2bn(&exponent, test->exp))
2816             || !TEST_true(BN_dec2bn(&modulo, test->mod)))
2817         goto err;
2818
2819     BN_set_flags(base, BN_FLG_CONSTTIME);
2820     BN_set_flags(exponent, BN_FLG_CONSTTIME);
2821     BN_set_flags(modulo, BN_FLG_CONSTTIME);
2822
2823     if (!TEST_int_eq(BN_mod_exp(result, base, exponent, modulo, ctx), 1))
2824         goto err;
2825
2826     if (!TEST_ptr(s = BN_bn2dec(result)))
2827         goto err;
2828
2829     if (!TEST_mem_eq(s, strlen(s), test->res, strlen(test->res)))
2830         goto err;
2831
2832     res = 1;
2833
2834  err:
2835     OPENSSL_free(s);
2836     BN_free(result);
2837     BN_free(base);
2838     BN_free(exponent);
2839     BN_free(modulo);
2840     return res;
2841 }
2842
2843 static int file_test_run(STANZA *s)
2844 {
2845     static const FILETEST filetests[] = {
2846         {"Sum", file_sum},
2847         {"LShift1", file_lshift1},
2848         {"LShift", file_lshift},
2849         {"RShift", file_rshift},
2850         {"Square", file_square},
2851         {"Product", file_product},
2852         {"Quotient", file_quotient},
2853         {"ModMul", file_modmul},
2854         {"ModExp", file_modexp},
2855         {"Exp", file_exp},
2856         {"ModSqrt", file_modsqrt},
2857         {"GCD", file_gcd},
2858     };
2859     int numtests = OSSL_NELEM(filetests);
2860     const FILETEST *tp = filetests;
2861
2862     for ( ; --numtests >= 0; tp++) {
2863         if (findattr(s, tp->name) != NULL) {
2864             if (!tp->func(s)) {
2865                 TEST_info("%s:%d: Failed %s test",
2866                           s->test_file, s->start, tp->name);
2867                 return 0;
2868             }
2869             return 1;
2870         }
2871     }
2872     TEST_info("%s:%d: Unknown test", s->test_file, s->start);
2873     return 0;
2874 }
2875
2876 static int run_file_tests(int i)
2877 {
2878     STANZA *s = NULL;
2879     char *testfile = test_get_argument(i);
2880     int c;
2881
2882     if (!TEST_ptr(s = OPENSSL_zalloc(sizeof(*s))))
2883         return 0;
2884     if (!test_start_file(s, testfile)) {
2885         OPENSSL_free(s);
2886         return 0;
2887     }
2888
2889     /* Read test file. */
2890     while (!BIO_eof(s->fp) && test_readstanza(s)) {
2891         if (s->numpairs == 0)
2892             continue;
2893         if (!file_test_run(s))
2894             s->errors++;
2895         s->numtests++;
2896         test_clearstanza(s);
2897     }
2898     test_end_file(s);
2899     c = s->errors;
2900     OPENSSL_free(s);
2901
2902     return c == 0;
2903 }
2904
2905 typedef enum OPTION_choice {
2906     OPT_ERR = -1,
2907     OPT_EOF = 0,
2908     OPT_STOCHASTIC_TESTS,
2909     OPT_TEST_ENUM
2910 } OPTION_CHOICE;
2911
2912 const OPTIONS *test_get_options(void)
2913 {
2914     static const OPTIONS test_options[] = {
2915         OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
2916         { "stochastic", OPT_STOCHASTIC_TESTS, '-', "Run stochastic tests" },
2917         { OPT_HELP_STR, 1, '-',
2918           "file\tFile to run tests on. Normal tests are not run\n" },
2919         { NULL }
2920     };
2921     return test_options;
2922 }
2923
2924 int setup_tests(void)
2925 {
2926     OPTION_CHOICE o;
2927     int n, stochastic = 0;
2928
2929     while ((o = opt_next()) != OPT_EOF) {
2930         switch (o) {
2931         case OPT_STOCHASTIC_TESTS:
2932             stochastic = 1;
2933             break;
2934         case OPT_TEST_CASES:
2935            break;
2936         default:
2937         case OPT_ERR:
2938             return 0;
2939         }
2940     }
2941     n  = test_get_argument_count();
2942
2943     if (!TEST_ptr(ctx = BN_CTX_new()))
2944         return 0;
2945
2946     if (n == 0) {
2947         ADD_TEST(test_sub);
2948         ADD_TEST(test_div_recip);
2949         ADD_ALL_TESTS(test_signed_mod_replace_ab, OSSL_NELEM(signed_mod_tests));
2950         ADD_ALL_TESTS(test_signed_mod_replace_ba, OSSL_NELEM(signed_mod_tests));
2951         ADD_TEST(test_mod);
2952         ADD_TEST(test_modexp_mont5);
2953         ADD_TEST(test_kronecker);
2954         ADD_TEST(test_rand);
2955         ADD_TEST(test_bn2padded);
2956         ADD_TEST(test_dec2bn);
2957         ADD_TEST(test_hex2bn);
2958         ADD_TEST(test_asc2bn);
2959         ADD_ALL_TESTS(test_mpi, (int)OSSL_NELEM(kMPITests));
2960         ADD_TEST(test_negzero);
2961         ADD_TEST(test_badmod);
2962         ADD_TEST(test_expmodzero);
2963         ADD_TEST(test_expmodone);
2964         ADD_ALL_TESTS(test_smallprime, 16);
2965         ADD_ALL_TESTS(test_smallsafeprime, 16);
2966         ADD_TEST(test_swap);
2967         ADD_TEST(test_ctx_consttime_flag);
2968 #ifndef OPENSSL_NO_EC2M
2969         ADD_TEST(test_gf2m_add);
2970         ADD_TEST(test_gf2m_mod);
2971         ADD_TEST(test_gf2m_mul);
2972         ADD_TEST(test_gf2m_sqr);
2973         ADD_TEST(test_gf2m_modinv);
2974         ADD_TEST(test_gf2m_moddiv);
2975         ADD_TEST(test_gf2m_modexp);
2976         ADD_TEST(test_gf2m_modsqrt);
2977         ADD_TEST(test_gf2m_modsolvequad);
2978 #endif
2979         ADD_ALL_TESTS(test_is_prime, (int)OSSL_NELEM(primes));
2980         ADD_ALL_TESTS(test_not_prime, (int)OSSL_NELEM(not_primes));
2981         ADD_TEST(test_gcd_prime);
2982         ADD_ALL_TESTS(test_mod_exp, (int)OSSL_NELEM(ModExpTests));
2983         ADD_ALL_TESTS(test_mod_exp_consttime, (int)OSSL_NELEM(ModExpTests));
2984         if (stochastic)
2985             ADD_TEST(test_rand_range);
2986     } else {
2987         ADD_ALL_TESTS(run_file_tests, n);
2988     }
2989     return 1;
2990 }
2991
2992 void cleanup_tests(void)
2993 {
2994     BN_CTX_free(ctx);
2995 }