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