Add BN_check_prime()
[openssl.git] / test / bntest.c
index 97ad97aca633188145baed64a146a08e7865c946..07b8aade37abd07ac6fe7dd853cedc6cf7f7eb18 100644 (file)
@@ -1,7 +1,7 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
  *
- * Licensed under the OpenSSL license (the "License").  You may not use
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
  * in the file LICENSE in the source distribution or at
  * https://www.openssl.org/source/license.html
 #include <string.h>
 #include <ctype.h>
 
-#include "e_os.h"
-#include <internal/numbers.h>
 #include <openssl/bn.h>
 #include <openssl/crypto.h>
 #include <openssl/err.h>
 #include <openssl/rand.h>
+#include "internal/nelem.h"
+#include "internal/numbers.h"
 #include "testutil.h"
 
-/*
- * In bn_lcl.h, bn_expand() is defined as a static ossl_inline function.
- * This is fine in itself, it will end up as an unused static function in
- * the worst case.  However, it references bn_expand2(), which is a private
- * function in libcrypto and therefore unavailable on some systems.  This
- * may result in a linker error because of unresolved symbols.
- *
- * To avoid this, we define a dummy variant of bn_expand2() here, and to
- * avoid possible clashes with libcrypto, we rename it first, using a macro.
- */
-#define bn_expand2 dummy_bn_expand2
-BIGNUM *bn_expand2(BIGNUM *b, int words);
-BIGNUM *bn_expand2(BIGNUM *b, int words) { return NULL; }
-#include "../crypto/bn/bn_lcl.h"
-
-#define MAXPAIRS        20
+#ifdef OPENSSL_SYS_WINDOWS
+# define strcasecmp _stricmp
+#endif
 
 /*
  * Things in boring, not in openssl.  TODO we should add them.
@@ -43,17 +30,6 @@ BIGNUM *bn_expand2(BIGNUM *b, int words) { return NULL; }
 #define HAVE_BN_PADDED 0
 #define HAVE_BN_SQRT 0
 
-typedef struct pair_st {
-    char *key;
-    char *value;
-} PAIR;
-
-typedef struct stanza_st {
-    int start;
-    int numpairs;
-    PAIR pairs[MAXPAIRS];
-} STANZA;
-
 typedef struct filetest_st {
     const char *name;
     int (*func)(STANZA *s);
@@ -67,15 +43,15 @@ typedef struct mpitest_st {
 
 static const int NUM0 = 100;           /* number of tests */
 static const int NUM1 = 50;            /* additional tests for some functions */
-static FILE *fp;
 static BN_CTX *ctx;
 
 /*
  * Polynomial coefficients used in GFM tests.
  */
+#ifndef OPENSSL_NO_EC2M
 static int p0[] = { 163, 7, 6, 3, 0, -1 };
 static int p1[] = { 193, 15, 0, -1 };
-
+#endif
 
 /*
  * Look for |key| in the stanza and return it or NULL if not found.
@@ -91,6 +67,18 @@ static const char *findattr(STANZA *s, const char *key)
     return NULL;
 }
 
+/*
+ * Parse BIGNUM from sparse hex-strings, return |BN_hex2bn| result.
+ */
+static int parse_bigBN(BIGNUM **out, const char *bn_strings[])
+{
+    char *bigstring = glue_strings(bn_strings, NULL);
+    int ret = BN_hex2bn(out, bigstring);
+
+    OPENSSL_free(bigstring);
+    return ret;
+}
+
 /*
  * Parse BIGNUM, return number of bytes parsed.
  */
@@ -112,7 +100,7 @@ static BIGNUM *getBN(STANZA *s, const char *attribute)
     BIGNUM *ret = NULL;
 
     if ((hex = findattr(s, attribute)) == NULL) {
-        TEST_error("Can't find %s in test at line %d", attribute, s->start);
+        TEST_error("%s:%d: Can't find %s", s->test_file, s->start, attribute);
         return NULL;
     }
 
@@ -135,39 +123,21 @@ static int getint(STANZA *s, int *out, const char *attribute)
 
     *out = (int)word;
     st = 1;
-err:
+ err:
     BN_free(ret);
     return st;
 }
 
 static int equalBN(const char *op, const BIGNUM *expected, const BIGNUM *actual)
 {
-    char *exstr = NULL;
-    char *actstr = NULL;
-
     if (BN_cmp(expected, actual) == 0)
         return 1;
 
-    if (BN_is_zero(expected) && BN_is_negative(expected))
-        exstr = OPENSSL_strdup("-0");
-    else
-        exstr = BN_bn2hex(expected);
-    if (BN_is_zero(actual) && BN_is_negative(actual))
-        actstr = OPENSSL_strdup("-0");
-    else
-        actstr = BN_bn2hex(actual);
-    if (!TEST_ptr(exstr) || !TEST_ptr(actstr))
-        goto err;
-
-    TEST_error("Got %s =\n\t%s\nwanted:\n\t%s", op, actstr, exstr);
-
-err:
-    OPENSSL_free(exstr);
-    OPENSSL_free(actstr);
+    TEST_error("unexpected %s value", op);
+    TEST_BN_eq(expected, actual);
     return 0;
 }
 
-
 /*
  * Return a "random" flag for if a BN should be negated.
  */
@@ -179,8 +149,80 @@ static int rand_neg(void)
     return sign[(neg++) % 8];
 }
 
+static int test_swap(void)
+{
+    BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
+    int top, cond, st = 0;
+
+    if (!TEST_ptr(a = BN_new())
+            || !TEST_ptr(b = BN_new())
+            || !TEST_ptr(c = BN_new())
+            || !TEST_ptr(d = BN_new()))
+        goto err;
+
+    if (!(TEST_true(BN_bntest_rand(a, 1024, 1, 0))
+            && TEST_true(BN_bntest_rand(b, 1024, 1, 0))
+            && TEST_ptr(BN_copy(c, a))
+            && TEST_ptr(BN_copy(d, b))))
+        goto err;
+    top = BN_num_bits(a) / BN_BITS2;
+
+    /* regular swap */
+    BN_swap(a, b);
+    if (!equalBN("swap", a, d)
+            || !equalBN("swap", b, c))
+        goto err;
+
+    /* conditional swap: true */
+    cond = 1;
+    BN_consttime_swap(cond, a, b, top);
+    if (!equalBN("cswap true", a, c)
+            || !equalBN("cswap true", b, d))
+        goto err;
+
+    /* conditional swap: false */
+    cond = 0;
+    BN_consttime_swap(cond, a, b, top);
+    if (!equalBN("cswap false", a, c)
+            || !equalBN("cswap false", b, d))
+        goto err;
+
+    /* same tests but checking flag swap */
+    BN_set_flags(a, BN_FLG_CONSTTIME);
+
+    BN_swap(a, b);
+    if (!equalBN("swap, flags", a, d)
+            || !equalBN("swap, flags", b, c)
+            || !TEST_true(BN_get_flags(b, BN_FLG_CONSTTIME))
+            || !TEST_false(BN_get_flags(a, BN_FLG_CONSTTIME)))
+        goto err;
+
+    cond = 1;
+    BN_consttime_swap(cond, a, b, top);
+    if (!equalBN("cswap true, flags", a, c)
+            || !equalBN("cswap true, flags", b, d)
+            || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
+            || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
+        goto err;
+
+    cond = 0;
+    BN_consttime_swap(cond, a, b, top);
+    if (!equalBN("cswap false, flags", a, c)
+            || !equalBN("cswap false, flags", b, d)
+            || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
+            || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
+        goto err;
+
+    st = 1;
+ err:
+    BN_free(a);
+    BN_free(b);
+    BN_free(c);
+    BN_free(d);
+    return st;
+}
 
-static int test_sub()
+static int test_sub(void)
 {
     BIGNUM *a = NULL, *b = NULL, *c = NULL;
     int i, st = 0;
@@ -192,32 +234,32 @@ static int test_sub()
 
     for (i = 0; i < NUM0 + NUM1; i++) {
         if (i < NUM1) {
-            BN_bntest_rand(a, 512, 0, 0);
-            BN_copy(b, a);
-            if (!TEST_int_ne(BN_set_bit(a, i), 0))
+            if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0)))
+                    && TEST_ptr(BN_copy(b, a))
+                    && TEST_int_ne(BN_set_bit(a, i), 0)
+                    && TEST_true(BN_add_word(b, i)))
                 goto err;
-            BN_add_word(b, i);
         } else {
-            BN_bntest_rand(b, 400 + i - NUM1, 0, 0);
-            a->neg = rand_neg();
-            b->neg = rand_neg();
+            if (!TEST_true(BN_bntest_rand(b, 400 + i - NUM1, 0, 0)))
+                goto err;
+            BN_set_negative(a, rand_neg());
+            BN_set_negative(b, rand_neg());
         }
-        BN_sub(c, a, b);
-        BN_add(c, c, b);
-        BN_sub(c, c, a);
-        if (!TEST_true(BN_is_zero(c)))
+        if (!(TEST_true(BN_sub(c, a, b))
+                && TEST_true(BN_add(c, c, b))
+                && TEST_true(BN_sub(c, c, a))
+                && TEST_BN_eq_zero(c)))
             goto err;
     }
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(c);
     return st;
 }
 
-
-static int test_div_recip()
+static int test_div_recip(void)
 {
     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
     BN_RECP_CTX *recp = NULL;
@@ -233,24 +275,27 @@ static int test_div_recip()
 
     for (i = 0; i < NUM0 + NUM1; i++) {
         if (i < NUM1) {
-            BN_bntest_rand(a, 400, 0, 0);
-            BN_copy(b, a);
-            BN_lshift(a, a, i);
-            BN_add_word(a, i);
-        } else
-            BN_bntest_rand(b, 50 + 3 * (i - NUM1), 0, 0);
-        a->neg = rand_neg();
-        b->neg = rand_neg();
-        BN_RECP_CTX_set(recp, b, ctx);
-        BN_div_recp(d, c, a, recp, ctx);
-        BN_mul(e, d, b, ctx);
-        BN_add(d, e, c);
-        BN_sub(d, d, a);
-        if (!TEST_true(BN_is_zero(d)))
+            if (!(TEST_true(BN_bntest_rand(a, 400, 0, 0))
+                    && TEST_ptr(BN_copy(b, a))
+                    && TEST_true(BN_lshift(a, a, i))
+                    && TEST_true(BN_add_word(a, i))))
+                goto err;
+        } else {
+            if (!(TEST_true(BN_bntest_rand(b, 50 + 3 * (i - NUM1), 0, 0))))
+                goto err;
+        }
+        BN_set_negative(a, rand_neg());
+        BN_set_negative(b, rand_neg());
+        if (!(TEST_true(BN_RECP_CTX_set(recp, b, ctx))
+                && TEST_true(BN_div_recp(d, c, a, recp, ctx))
+                && TEST_true(BN_mul(e, d, b, ctx))
+                && TEST_true(BN_add(d, e, c))
+                && TEST_true(BN_sub(d, d, a))
+                && TEST_BN_eq_zero(d)))
             goto err;
     }
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(c);
@@ -260,8 +305,7 @@ err:
     return st;
 }
 
-
-static int test_mod()
+static int test_mod(void)
 {
     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
     int st = 0, i;
@@ -273,19 +317,21 @@ static int test_mod()
             || !TEST_ptr(e = BN_new()))
         goto err;
 
-    BN_bntest_rand(a, 1024, 0, 0);
+    if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0))))
+        goto err;
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(b, 450 + i * 10, 0, 0);
-        a->neg = rand_neg();
-        b->neg = rand_neg();
-        BN_mod(c, a, b, ctx);
-        BN_div(d, e, a, b, ctx);
-        BN_sub(e, e, c);
-        if (!TEST_true(BN_is_zero(e)))
+        if (!(TEST_true(BN_bntest_rand(b, 450 + i * 10, 0, 0))))
+            goto err;
+        BN_set_negative(a, rand_neg());
+        BN_set_negative(b, rand_neg());
+        if (!(TEST_true(BN_mod(c, a, b, ctx))
+                && TEST_true(BN_div(d, e, a, b, ctx))
+                && TEST_true(BN_sub(e, e, c))
+                && TEST_BN_eq_zero(e)))
             goto err;
     }
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(c);
@@ -334,31 +380,15 @@ static const char *bn2strings[] = {
     NULL
 };
 
-static char *glue(const char *list[])
-{
-    size_t len = 0;
-    char *p, *save;
-    int i;
-
-    for (i = 0; list[i] != NULL; i++)
-        len += strlen(list[i]);
-    if (!TEST_ptr(p = save = OPENSSL_malloc(len + 1)))
-            return NULL;
-    for (i = 0; list[i] != NULL; i++)
-        p += strlen(strcpy(p, list[i]));
-    return save;
-}
-
 /*
  * Test constant-time modular exponentiation with 1024-bit inputs, which on
  * x86_64 cause a different code branch to be taken.
  */
-static int test_modexp_mont5()
+static int test_modexp_mont5(void)
 {
     BIGNUM *a = NULL, *p = NULL, *m = NULL, *d = NULL, *e = NULL;
     BIGNUM *b = NULL, *n = NULL, *c = NULL;
     BN_MONT_CTX *mont = NULL;
-    char *bigstring;
     int st = 0;
 
     if (!TEST_ptr(a = BN_new())
@@ -372,57 +402,167 @@ static int test_modexp_mont5()
             || !TEST_ptr(mont = BN_MONT_CTX_new()))
         goto err;
 
-    BN_bntest_rand(m, 1024, 0, 1); /* must be odd for montgomery */
-    /* Zero exponent */
-    BN_bntest_rand(a, 1024, 0, 0);
+    /* must be odd for montgomery */
+    if (!(TEST_true(BN_bntest_rand(m, 1024, 0, 1))
+            /* Zero exponent */
+            && TEST_true(BN_bntest_rand(a, 1024, 0, 0))))
+        goto err;
     BN_zero(p);
+
     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL)))
         goto err;
-    if (!TEST_true(BN_is_one(d)))
+    if (!TEST_BN_eq_one(d))
         goto err;
 
     /* Regression test for carry bug in mulx4x_mont */
-    BN_hex2bn(&a,
+    if (!(TEST_true(BN_hex2bn(&a,
         "7878787878787878787878787878787878787878787878787878787878787878"
         "7878787878787878787878787878787878787878787878787878787878787878"
         "7878787878787878787878787878787878787878787878787878787878787878"
-        "7878787878787878787878787878787878787878787878787878787878787878");
-    BN_hex2bn(&b,
+        "7878787878787878787878787878787878787878787878787878787878787878"))
+        && TEST_true(BN_hex2bn(&b,
         "095D72C08C097BA488C5E439C655A192EAFB6380073D8C2664668EDDB4060744"
         "E16E57FB4EDB9AE10A0CEFCDC28A894F689A128379DB279D48A2E20849D68593"
         "9B7803BCF46CEBF5C533FB0DD35B080593DE5472E3FE5DB951B8BFF9B4CB8F03"
-        "9CC638A5EE8CDD703719F8000E6A9F63BEED5F2FCD52FF293EA05A251BB4AB81");
-    BN_hex2bn(&n,
+        "9CC638A5EE8CDD703719F8000E6A9F63BEED5F2FCD52FF293EA05A251BB4AB81"))
+        && TEST_true(BN_hex2bn(&n,
         "D78AF684E71DB0C39CFF4E64FB9DB567132CB9C50CC98009FEB820B26F2DED9B"
         "91B9B5E2B83AE0AE4EB4E0523CA726BFBE969B89FD754F674CE99118C3F2D1C5"
         "D81FDC7C54E02B60262B241D53C040E99E45826ECA37A804668E690E1AFC1CA4"
-        "2C9A15D84D4954425F0B7642FC0BD9D7B24E2618D2DCC9B729D944BADACFDDAF");
-    BN_MONT_CTX_set(mont, n, ctx);
-    BN_mod_mul_montgomery(c, a, b, mont, ctx);
-    BN_mod_mul_montgomery(d, b, a, mont, ctx);
-    if (!TEST_int_eq(BN_cmp(c, d), 0))
+        "2C9A15D84D4954425F0B7642FC0BD9D7B24E2618D2DCC9B729D944BADACFDDAF"))))
+        goto err;
+
+    if (!(TEST_true(BN_MONT_CTX_set(mont, n, ctx))
+            && TEST_true(BN_mod_mul_montgomery(c, a, b, mont, ctx))
+            && TEST_true(BN_mod_mul_montgomery(d, b, a, mont, ctx))
+            && TEST_BN_eq(c, d)))
         goto err;
 
     /* Regression test for carry bug in sqr[x]8x_mont */
-    bigstring = glue(bn1strings);
-    BN_hex2bn(&n, bigstring);
-    OPENSSL_free(bigstring);
-    bigstring = glue(bn2strings);
-    BN_hex2bn(&a, bigstring);
-    OPENSSL_free(bigstring);
+    if (!(TEST_true(parse_bigBN(&n, bn1strings))
+            && TEST_true(parse_bigBN(&a, bn2strings))))
+        goto err;
+    BN_free(b);
+    if (!(TEST_ptr(b = BN_dup(a))
+            && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
+            && TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
+            && TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
+            && TEST_BN_eq(c, d)))
+        goto err;
+
+    /* Regression test for carry bug in bn_sqrx8x_internal */
+    {
+        static const char *ahex[] = {
+                      "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8FFEADBCFC4DAE7FFF908E92820306B",
+            "9544D954000000006C0000000000000000000000000000000000000000000000",
+            "00000000000000000000FF030202FFFFF8FFEBDBCFC4DAE7FFF908E92820306B",
+            "9544D954000000006C000000FF0302030000000000FFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01FC00FF02FFFFFFFF",
+            "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FCFD",
+            "FCFFFFFFFFFF000000000000000000FF0302030000000000FFFFFFFFFFFFFFFF",
+            "FF00FCFDFDFF030202FF00000000FFFFFFFFFFFFFFFFFF00FCFDFCFFFFFFFFFF",
+            NULL
+        };
+        static const char *nhex[] = {
+                      "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8F8F8F8000000",
+            "00000010000000006C0000000000000000000000000000000000000000000000",
+            "00000000000000000000000000000000000000FFFFFFFFFFFFF8F8F8F8000000",
+            "00000010000000006C000000000000000000000000FFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFF000000000000000000000000000000000000FFFFFFFFFFFFFFFF",
+            "FFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
+            NULL
+        };
+
+        if (!(TEST_true(parse_bigBN(&a, ahex))
+                && TEST_true(parse_bigBN(&n, nhex))))
+            goto err;
+    }
     BN_free(b);
-    b = BN_dup(a);
-    BN_MONT_CTX_set(mont, n, ctx);
-    BN_mod_mul_montgomery(c, a, a, mont, ctx);
-    BN_mod_mul_montgomery(d, a, b, mont, ctx);
-    if (!TEST_int_eq(BN_cmp(c, d), 0))
+    if (!(TEST_ptr(b = BN_dup(a))
+            && TEST_true(BN_MONT_CTX_set(mont, n, ctx))))
+        goto err;
+
+    if (!TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
+            || !TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
+            || !TEST_BN_eq(c, d))
+        goto err;
+
+    /* Regression test for bug in BN_from_montgomery_word */
+    if (!(TEST_true(BN_hex2bn(&a,
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
+         && TEST_true(BN_hex2bn(&n,
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
+        && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
+        && TEST_false(BN_mod_mul_montgomery(d, a, a, mont, ctx))))
+        goto err;
+
+    /* Regression test for bug in rsaz_1024_mul_avx2 */
+    if (!(TEST_true(BN_hex2bn(&a,
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
+        && TEST_true(BN_hex2bn(&b,
+        "2020202020202020202020202020202020202020202020202020202020202020"
+        "2020202020202020202020202020202020202020202020202020202020202020"
+        "20202020202020FF202020202020202020202020202020202020202020202020"
+        "2020202020202020202020202020202020202020202020202020202020202020"))
+        && TEST_true(BN_hex2bn(&n,
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020FF"))
+        && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
+        && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont))
+        && TEST_true(BN_mod_exp_mont(d, a, b, n, ctx, mont))
+        && TEST_BN_eq(c, d)))
+        goto err;
+
+    /*
+     * rsaz_1024_mul_avx2 expects fully-reduced inputs.
+     * BN_mod_exp_mont_consttime should reduce the input first.
+     */
+    if (!(TEST_true(BN_hex2bn(&a,
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
+        && TEST_true(BN_hex2bn(&b,
+        "1FA53F26F8811C58BE0357897AA5E165693230BC9DF5F01DFA6A2D59229EC69D"
+        "9DE6A89C36E3B6957B22D6FAAD5A3C73AE587B710DBE92E83D3A9A3339A085CB"
+        "B58F508CA4F837924BB52CC1698B7FDC2FD74362456A595A5B58E38E38E38E38"
+        "E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E"))
+        && TEST_true(BN_hex2bn(&n,
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
+        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
+        && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
+        && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont))))
+        goto err;
+    BN_zero(d);
+    if (!TEST_BN_eq(c, d))
         goto err;
 
     /* Zero input */
-    BN_bntest_rand(p, 1024, 0, 0);
+    if (!TEST_true(BN_bntest_rand(p, 1024, 0, 0)))
+        goto err;
     BN_zero(a);
     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))
-            || !TEST_true(BN_is_zero(d)))
+            || !TEST_BN_eq_zero(d))
         goto err;
 
     /*
@@ -430,24 +570,25 @@ static int test_modexp_mont5()
      * than the modulus m, in order to test the const time precomputation
      * scattering/gathering.
      */
-    BN_one(a);
-    BN_MONT_CTX_set(mont, m, ctx);
+    if (!(TEST_true(BN_one(a))
+            && TEST_true(BN_MONT_CTX_set(mont, m, ctx))))
+        goto err;
     if (!TEST_true(BN_from_montgomery(e, a, mont, ctx))
             || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
             || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
-            || !TEST_int_eq(BN_cmp(a, d), 0))
+            || !TEST_BN_eq(a, d))
         goto err;
 
     /* Finally, some regular test vectors. */
-    BN_bntest_rand(e, 1024, 0, 0);
-    if (!TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
-            || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
-            || !TEST_int_eq(BN_cmp(a, d), 0))
+    if (!(TEST_true(BN_bntest_rand(e, 1024, 0, 0))
+            && TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
+            && TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
+            && TEST_BN_eq(a, d)))
         goto err;
 
     st = 1;
 
-err:
+ err:
     BN_MONT_CTX_free(mont);
     BN_free(a);
     BN_free(p);
@@ -461,7 +602,7 @@ err:
 }
 
 #ifndef OPENSSL_NO_EC2M
-static int test_gf2m_add()
+static int test_gf2m_add(void)
 {
     BIGNUM *a = NULL, *b = NULL, *c = NULL;
     int i, st = 0;
@@ -472,18 +613,19 @@ static int test_gf2m_add()
         goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_rand(a, 512, 0, 0);
-        BN_copy(b, BN_value_one());
-        a->neg = rand_neg();
-        b->neg = rand_neg();
-        BN_GF2m_add(c, a, b);
-        /* Test that two added values have the correct parity. */
-        if (!TEST_false((BN_is_odd(a) && BN_is_odd(c))
-                        || (!BN_is_odd(a) && !BN_is_odd(c))))
+        if (!(TEST_true(BN_rand(a, 512, 0, 0))
+                && TEST_ptr(BN_copy(b, BN_value_one()))))
             goto err;
-        BN_GF2m_add(c, c, c);
-        /* Test that c + c = 0. */
-        if (!TEST_true(BN_is_zero(c)))
+        BN_set_negative(a, rand_neg());
+        BN_set_negative(b, rand_neg());
+        if (!(TEST_true(BN_GF2m_add(c, a, b))
+                /* Test that two added values have the correct parity. */
+                && TEST_false((BN_is_odd(a) && BN_is_odd(c))
+                        || (!BN_is_odd(a) && !BN_is_odd(c)))))
+            goto err;
+        if (!(TEST_true(BN_GF2m_add(c, c, c))
+                /* Test that c + c = 0. */
+                && TEST_BN_eq_zero(c)))
             goto err;
     }
     st = 1;
@@ -494,7 +636,7 @@ static int test_gf2m_add()
     return st;
 }
 
-static int test_gf2m_mod()
+static int test_gf2m_mod(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL, *e = NULL;
     int i, j, st = 0;
@@ -507,17 +649,19 @@ static int test_gf2m_mod()
             || !TEST_ptr(e = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 1024, 0, 0);
+        if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0)))
+            goto err;
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod(c, a, b[j]);
-            BN_GF2m_add(d, a, c);
-            BN_GF2m_mod(e, d, b[j]);
-            /* Test that a + (a mod p) mod p == 0. */
-            if (!TEST_true(BN_is_zero(e)))
+            if (!(TEST_true(BN_GF2m_mod(c, a, b[j]))
+                    && TEST_true(BN_GF2m_add(d, a, c))
+                    && TEST_true(BN_GF2m_mod(e, d, b[j]))
+                    /* Test that a + (a mod p) mod p == 0. */
+                    && TEST_BN_eq_zero(e)))
                 goto err;
         }
     }
@@ -532,7 +676,7 @@ static int test_gf2m_mod()
     return st;
 }
 
-static int test_gf2m_mul()
+static int test_gf2m_mul(void)
 {
     BIGNUM *a, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
     BIGNUM *e = NULL, *f = NULL, *g = NULL, *h = NULL;
@@ -549,22 +693,24 @@ static int test_gf2m_mul()
             || !TEST_ptr(h = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 1024, 0, 0);
-        BN_bntest_rand(c, 1024, 0, 0);
-        BN_bntest_rand(d, 1024, 0, 0);
+        if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0))
+                && TEST_true(BN_bntest_rand(c, 1024, 0, 0))
+                && TEST_true(BN_bntest_rand(d, 1024, 0, 0))))
+            goto err;
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod_mul(e, a, c, b[j], ctx);
-            BN_GF2m_add(f, a, d);
-            BN_GF2m_mod_mul(g, f, c, b[j], ctx);
-            BN_GF2m_mod_mul(h, d, c, b[j], ctx);
-            BN_GF2m_add(f, e, g);
-            BN_GF2m_add(f, f, h);
-            /* Test that (a+d)*c = a*c + d*c. */
-            if (!TEST_true(BN_is_zero(f)))
+            if (!(TEST_true(BN_GF2m_mod_mul(e, a, c, b[j], ctx))
+                    && TEST_true(BN_GF2m_add(f, a, d))
+                    && TEST_true(BN_GF2m_mod_mul(g, f, c, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_mul(h, d, c, b[j], ctx))
+                    && TEST_true(BN_GF2m_add(f, e, g))
+                    && TEST_true(BN_GF2m_add(f, f, h))
+                    /* Test that (a+d)*c = a*c + d*c. */
+                    && TEST_BN_eq_zero(f)))
                 goto err;
         }
     }
@@ -583,7 +729,7 @@ static int test_gf2m_mul()
     return st;
 }
 
-static int test_gf2m_sqr()
+static int test_gf2m_sqr(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
     int i, j, st = 0;
@@ -595,18 +741,20 @@ static int test_gf2m_sqr()
             || !TEST_ptr(d = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 1024, 0, 0);
+        if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0)))
+                goto err;
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod_sqr(c, a, b[j], ctx);
-            BN_copy(d, a);
-            BN_GF2m_mod_mul(d, a, d, b[j], ctx);
-            BN_GF2m_add(d, c, d);
-            /* Test that a*a = a^2. */
-            if (!TEST_true(BN_is_zero(d)))
+            if (!(TEST_true(BN_GF2m_mod_sqr(c, a, b[j], ctx))
+                    && TEST_true(BN_copy(d, a))
+                    && TEST_true(BN_GF2m_mod_mul(d, a, d, b[j], ctx))
+                    && TEST_true(BN_GF2m_add(d, c, d))
+                    /* Test that a*a = a^2. */
+                    && TEST_BN_eq_zero(d)))
                 goto err;
         }
     }
@@ -620,7 +768,7 @@ static int test_gf2m_sqr()
     return st;
 }
 
-static int test_gf2m_modinv()
+static int test_gf2m_modinv(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
     int i, j, st = 0;
@@ -632,16 +780,18 @@ static int test_gf2m_modinv()
             || !TEST_ptr(d = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 512, 0, 0);
+        if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
+            goto err;
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod_inv(c, a, b[j], ctx);
-            BN_GF2m_mod_mul(d, a, c, b[j], ctx);
-            /* Test that ((1/a)*a) = 1. */
-            if (!TEST_true(BN_is_one(d)))
+            if (!(TEST_true(BN_GF2m_mod_inv(c, a, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_mul(d, a, c, b[j], ctx))
+                    /* Test that ((1/a)*a) = 1. */
+                    && TEST_BN_eq_one(d)))
                 goto err;
         }
     }
@@ -655,7 +805,7 @@ static int test_gf2m_modinv()
     return st;
 }
 
-static int test_gf2m_moddiv()
+static int test_gf2m_moddiv(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
     BIGNUM *e = NULL, *f = NULL;
@@ -670,18 +820,20 @@ static int test_gf2m_moddiv()
             || !TEST_ptr(f = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 512, 0, 0);
-        BN_bntest_rand(c, 512, 0, 0);
+        if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))
+                && TEST_true(BN_bntest_rand(c, 512, 0, 0))))
+            goto err;
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod_div(d, a, c, b[j], ctx);
-            BN_GF2m_mod_mul(e, d, c, b[j], ctx);
-            BN_GF2m_mod_div(f, a, e, b[j], ctx);
-            /* Test that ((a/c)*c)/a = 1. */
-            if (!TEST_true(BN_is_one(f)))
+            if (!(TEST_true(BN_GF2m_mod_div(d, a, c, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_mul(e, d, c, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_div(f, a, e, b[j], ctx))
+                    /* Test that ((a/c)*c)/a = 1. */
+                    && TEST_BN_eq_one(f)))
                 goto err;
         }
     }
@@ -697,7 +849,7 @@ static int test_gf2m_moddiv()
     return st;
 }
 
-static int test_gf2m_modexp()
+static int test_gf2m_modexp(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
     BIGNUM *e = NULL, *f = NULL;
@@ -712,22 +864,24 @@ static int test_gf2m_modexp()
             || !TEST_ptr(f = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 512, 0, 0);
-        BN_bntest_rand(c, 512, 0, 0);
-        BN_bntest_rand(d, 512, 0, 0);
+        if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))
+                && TEST_true(BN_bntest_rand(c, 512, 0, 0))
+                && TEST_true(BN_bntest_rand(d, 512, 0, 0))))
+            goto err;
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod_exp(e, a, c, b[j], ctx);
-            BN_GF2m_mod_exp(f, a, d, b[j], ctx);
-            BN_GF2m_mod_mul(e, e, f, b[j], ctx);
-            BN_add(f, c, d);
-            BN_GF2m_mod_exp(f, a, f, b[j], ctx);
-            BN_GF2m_add(f, e, f);
-            /* Test that a^(c+d)=a^c*a^d. */
-            if (!TEST_true(BN_is_zero(f)))
+            if (!(TEST_true(BN_GF2m_mod_exp(e, a, c, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_exp(f, a, d, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_mul(e, e, f, b[j], ctx))
+                    && TEST_true(BN_add(f, c, d))
+                    && TEST_true(BN_GF2m_mod_exp(f, a, f, b[j], ctx))
+                    && TEST_true(BN_GF2m_add(f, e, f))
+                    /* Test that a^(c+d)=a^c*a^d. */
+                    && TEST_BN_eq_zero(f)))
                 goto err;
         }
     }
@@ -743,7 +897,7 @@ static int test_gf2m_modexp()
     return st;
 }
 
-static int test_gf2m_modsqrt()
+static int test_gf2m_modsqrt(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
     BIGNUM *e = NULL, *f = NULL;
@@ -758,18 +912,21 @@ static int test_gf2m_modsqrt()
             || !TEST_ptr(f = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 512, 0, 0);
+        if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
+            goto err;
+
         for (j = 0; j < 2; j++) {
-            BN_GF2m_mod(c, a, b[j]);
-            BN_GF2m_mod_sqrt(d, a, b[j], ctx);
-            BN_GF2m_mod_sqr(e, d, b[j], ctx);
-            BN_GF2m_add(f, c, e);
-            /* Test that d^2 = a, where d = sqrt(a). */
-            if (!TEST_true(BN_is_zero(f)))
+            if (!(TEST_true(BN_GF2m_mod(c, a, b[j]))
+                    && TEST_true(BN_GF2m_mod_sqrt(d, a, b[j], ctx))
+                    && TEST_true(BN_GF2m_mod_sqr(e, d, b[j], ctx))
+                    && TEST_true(BN_GF2m_add(f, c, e))
+                    /* Test that d^2 = a, where d = sqrt(a). */
+                    && TEST_BN_eq_zero(f)))
                 goto err;
         }
     }
@@ -785,7 +942,7 @@ static int test_gf2m_modsqrt()
     return st;
 }
 
-static int test_gf2m_modsolvequad()
+static int test_gf2m_modsolvequad(void)
 {
     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
     BIGNUM *e = NULL;
@@ -799,23 +956,26 @@ static int test_gf2m_modsolvequad()
             || !TEST_ptr(e = BN_new()))
         goto err;
 
-    BN_GF2m_arr2poly(p0, b[0]);
-    BN_GF2m_arr2poly(p1, b[1]);
+    if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
+            && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
+        goto err;
 
     for (i = 0; i < NUM0; i++) {
-        BN_bntest_rand(a, 512, 0, 0);
+        if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
+            goto err;
         for (j = 0; j < 2; j++) {
             t = BN_GF2m_mod_solve_quad(c, a, b[j], ctx);
             if (t) {
                 s++;
-                BN_GF2m_mod_sqr(d, c, b[j], ctx);
-                BN_GF2m_add(d, c, d);
-                BN_GF2m_mod(e, a, b[j]);
-                BN_GF2m_add(e, e, d);
-                /*
-                 * Test that solution of quadratic c satisfies c^2 + c = a.
-                 */
-                if (!TEST_true(BN_is_zero(e)))
+                if (!(TEST_true(BN_GF2m_mod_sqr(d, c, b[j], ctx))
+                        && TEST_true(BN_GF2m_add(d, c, d))
+                        && TEST_true(BN_GF2m_mod(e, a, b[j]))
+                        && TEST_true(BN_GF2m_add(e, e, d))
+                        /*
+                         * Test that solution of quadratic c
+                         * satisfies c^2 + c = a.
+                         */
+                        && TEST_BN_eq_zero(e)))
                     goto err;
             }
         }
@@ -836,7 +996,7 @@ static int test_gf2m_modsolvequad()
 }
 #endif
 
-static int test_kronecker()
+static int test_kronecker(void)
 {
     BIGNUM *a = NULL, *b = NULL, *r = NULL, *t = NULL;
     int i, legendre, kronecker, st = 0;
@@ -859,27 +1019,27 @@ static int test_kronecker()
 
     if (!TEST_true(BN_generate_prime_ex(b, 512, 0, NULL, NULL, NULL)))
         goto err;
-    b->neg = rand_neg();
+    BN_set_negative(b, rand_neg());
 
     for (i = 0; i < NUM0; i++) {
         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
             goto err;
-        a->neg = rand_neg();
+        BN_set_negative(a, rand_neg());
 
         /* t := (|b|-1)/2  (note that b is odd) */
         if (!TEST_true(BN_copy(t, b)))
             goto err;
-        t->neg = 0;
+        BN_set_negative(t, 0);
         if (!TEST_true(BN_sub_word(t, 1)))
             goto err;
         if (!TEST_true(BN_rshift1(t, t)))
             goto err;
         /* r := a^t mod b */
-        b->neg = 0;
+        BN_set_negative(b, 0);
 
         if (!TEST_true(BN_mod_exp_recp(r, a, t, b, ctx)))
             goto err;
-        b->neg = 1;
+        BN_set_negative(b, 1);
 
         if (BN_is_word(r, 1))
             legendre = 1;
@@ -898,7 +1058,7 @@ static int test_kronecker()
         if (!TEST_int_ge(kronecker = BN_kronecker(a, b, ctx), -1))
             goto err;
         /* we actually need BN_kronecker(a, |b|) */
-        if (a->neg && b->neg)
+        if (BN_is_negative(a) && BN_is_negative(b))
             kronecker = -kronecker;
 
         if (!TEST_int_eq(legendre, kronecker))
@@ -1015,7 +1175,7 @@ static int file_sum(STANZA *s)
     }
     st = 1;
 
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(sum);
@@ -1064,7 +1224,7 @@ static int file_lshift1(STANZA *s)
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(lshift1);
     BN_free(zero);
@@ -1082,7 +1242,9 @@ static int file_lshift(STANZA *s)
 
     if (!TEST_ptr(a = getBN(s, "A"))
             || !TEST_ptr(lshift = getBN(s, "LShift"))
-            || !TEST_ptr(ret = BN_new()))
+            || !TEST_ptr(ret = BN_new())
+            || !getint(s, &n, "N"))
+        goto err;
 
     if (!TEST_true(BN_lshift(ret, a, n))
             || !equalBN("A << N", lshift, ret)
@@ -1091,7 +1253,7 @@ static int file_lshift(STANZA *s)
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(lshift);
     BN_free(ret);
@@ -1121,7 +1283,7 @@ static int file_rshift(STANZA *s)
     }
     st = 1;
 
-err:
+ err:
     BN_free(a);
     BN_free(rshift);
     BN_free(ret);
@@ -1158,8 +1320,9 @@ static int file_square(STANZA *s)
         goto err;
 
     /* BN_sqrt should fail on non-squares and negative numbers. */
-    if (!TEST_true(BN_is_zero(square))) {
-        if (!TEST_ptr(tmp = BN_new()) || !TEST_true(BN_copy(tmp, square)))
+    if (!TEST_BN_eq_zero(square)) {
+        if (!TEST_ptr(tmp = BN_new())
+                || !TEST_true(BN_copy(tmp, square)))
             goto err;
         BN_set_negative(tmp, 1);
 
@@ -1177,7 +1340,7 @@ static int file_square(STANZA *s)
 #endif
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(square);
     BN_free(zero);
@@ -1214,7 +1377,7 @@ static int file_product(STANZA *s)
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(product);
@@ -1297,7 +1460,7 @@ static int file_quotient(STANZA *s)
     }
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(quotient);
@@ -1351,7 +1514,7 @@ static int file_modmul(STANZA *s)
     }
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(m);
@@ -1397,13 +1560,13 @@ static int file_modexp(STANZA *s)
         "0000000000000000000000000000000000000000000000000000000000000000"
         "0000000000000000000000000000000000000000000000000000000000000000"
         "0000000000000000000000000000000000000000000000000000000001");
-    BN_mod_exp(d, a, b, c, ctx);
-    BN_mul(e, a, a, ctx);
-    if (!TEST_int_eq(BN_cmp(d, e), 0))
+    if (!TEST_true(BN_mod_exp(d, a, b, c, ctx))
+        || !TEST_true(BN_mul(e, a, a, ctx))
+        || !TEST_BN_eq(d, e))
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(c);
@@ -1431,7 +1594,7 @@ static int file_exp(STANZA *s)
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(e);
     BN_free(exp);
@@ -1462,7 +1625,7 @@ static int file_modsqrt(STANZA *s)
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(p);
     BN_free(mod_sqrt);
@@ -1471,7 +1634,7 @@ err:
     return st;
 }
 
-static int test_bn2padded()
+static int test_bn2padded(void)
 {
 #if HAVE_BN_PADDED
     uint8_t zeros[256], out[256], reference[128];
@@ -1492,8 +1655,8 @@ static int test_bn2padded()
 
     /* Test a random numbers at various byte lengths. */
     for (size_t bytes = 128 - 7; bytes <= 128; bytes++) {
-#define TOP_BIT_ON 0
-#define BOTTOM_BIT_NOTOUCH 0
+# define TOP_BIT_ON 0
+# define BOTTOM_BIT_NOTOUCH 0
         if (!TEST_true(BN_rand(n, bytes * 8, TOP_BIT_ON, BOTTOM_BIT_NOTOUCH)))
             goto err;
         if (!TEST_int_eq(BN_num_bytes(n),A) bytes
@@ -1524,7 +1687,7 @@ static int test_bn2padded()
     }
 
     st = 1;
-err:
+ err:
     BN_free(n);
     return st;
 #else
@@ -1532,87 +1695,142 @@ err:
 #endif
 }
 
-static int test_dec2bn()
+static int test_dec2bn(void)
 {
     BIGNUM *bn = NULL;
     int st = 0;
 
     if (!TEST_int_eq(parsedecBN(&bn, "0"), 1)
-            || !TEST_true(BN_is_zero(bn))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 0)
+            || !TEST_BN_eq_zero(bn)
+            || !TEST_BN_le_zero(bn)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parsedecBN(&bn, "256"), 3)
-            || !TEST_true(BN_is_word(bn, 256))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 256)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_gt_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parsedecBN(&bn, "-42"), 3)
-            || !TEST_true(BN_abs_is_word(bn, 42))
-            || !TEST_true(BN_is_negative(bn)))
+            || !TEST_BN_abs_eq_word(bn, 42)
+            || !TEST_BN_lt_zero(bn)
+            || !TEST_BN_le_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
+
+    if (!TEST_int_eq(parsedecBN(&bn, "1"), 1)
+            || !TEST_BN_eq_word(bn, 1)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_gt_zero(bn)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_eq_one(bn)
+            || !TEST_BN_odd(bn))
+        goto err;
+    BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parsedecBN(&bn, "-0"), 2)
-            || !TEST_true(BN_is_zero(bn))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_zero(bn)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_le_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parsedecBN(&bn, "42trailing garbage is ignored"), 2)
-            || !TEST_true(BN_abs_is_word(bn, 42))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_abs_eq_word(bn, 42)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_gt_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(bn);
     return st;
 }
 
-static int test_hex2bn()
+static int test_hex2bn(void)
 {
     BIGNUM *bn = NULL;
     int st = 0;
 
     if (!TEST_int_eq(parseBN(&bn, "0"), 1)
-            || !TEST_true(BN_is_zero(bn))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_zero(bn)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parseBN(&bn, "256"), 3)
-            || !TEST_true(BN_is_word(bn, 0x256))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 0x256)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_gt_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parseBN(&bn, "-42"), 3)
-            || !TEST_true(BN_abs_is_word(bn, 0x42))
-            || !TEST_true(BN_is_negative(bn)))
+            || !TEST_BN_abs_eq_word(bn, 0x42)
+            || !TEST_BN_lt_zero(bn)
+            || !TEST_BN_le_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_even(bn))
+        goto err;
+    BN_free(bn);
+    bn = NULL;
+
+    if (!TEST_int_eq(parseBN(&bn, "cb"), 2)
+            || !TEST_BN_eq_word(bn, 0xCB)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_gt_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_odd(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parseBN(&bn, "-0"), 2)
-            || !TEST_true(BN_is_zero(bn))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_zero(bn)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_le_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     BN_free(bn);
+    bn = NULL;
 
     if (!TEST_int_eq(parseBN(&bn, "abctrailing garbage is ignored"), 3)
-            || !TEST_true(BN_is_word(bn, 0xabc))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 0xabc)
+            || !TEST_BN_ge_zero(bn)
+            || !TEST_BN_gt_zero(bn)
+            || !TEST_BN_ne_zero(bn)
+            || !TEST_BN_even(bn))
         goto err;
     st = 1;
 
-err:
+ err:
     BN_free(bn);
     return st;
 }
 
-static int test_asc2bn()
+static int test_asc2bn(void)
 {
     BIGNUM *bn = NULL;
     int st = 0;
@@ -1621,47 +1839,47 @@ static int test_asc2bn()
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "0"))
-            || !TEST_true(BN_is_zero(bn))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_zero(bn)
+            || !TEST_BN_ge_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "256"))
-            || !TEST_true(BN_is_word(bn, 256))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 256)
+            || !TEST_BN_ge_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "-42"))
-            || !TEST_true(BN_abs_is_word(bn, 42))
-            || !TEST_true(BN_is_negative(bn)))
+            || !TEST_BN_abs_eq_word(bn, 42)
+            || !TEST_BN_lt_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "0x1234"))
-            || !TEST_true(BN_is_word(bn, 0x1234))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 0x1234)
+            || !TEST_BN_ge_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "0X1234"))
-            || !TEST_true(BN_is_word(bn, 0x1234))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 0x1234)
+            || !TEST_BN_ge_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "-0xabcd"))
-            || !TEST_true(BN_abs_is_word(bn, 0xabcd))
-            || !TEST_true(BN_is_negative(bn)))
+            || !TEST_BN_abs_eq_word(bn, 0xabcd)
+            || !TEST_BN_lt_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "-0"))
-            || !TEST_true(BN_is_zero(bn))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_zero(bn)
+            || !TEST_BN_ge_zero(bn))
         goto err;
 
     if (!TEST_true(BN_asc2bn(&bn, "123trailing garbage is ignored"))
-            || !TEST_true(BN_is_word(bn, 123))
-            || !TEST_false(BN_is_negative(bn)))
+            || !TEST_BN_eq_word(bn, 123)
+            || !TEST_BN_ge_zero(bn))
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(bn);
     return st;
 }
@@ -1698,19 +1916,19 @@ static int test_mpi(int i)
     if (!TEST_ptr(bn2 = BN_mpi2bn(scratch, mpi_len, NULL)))
         goto err;
 
-    if (!TEST_int_eq(BN_cmp(bn, bn2), 0)) {
+    if (!TEST_BN_eq(bn, bn2)) {
         BN_free(bn2);
         goto err;
     }
     BN_free(bn2);
 
     st = 1;
-err:
+ err:
     BN_free(bn);
     return st;
 }
 
-static int test_rand()
+static int test_rand(void)
 {
     BIGNUM *bn = NULL;
     int st = 0;
@@ -1722,21 +1940,101 @@ static int test_rand()
     if (!TEST_false(BN_rand(bn, 0, 0 /* top */ , 0 /* bottom */ ))
             || !TEST_false(BN_rand(bn, 0, 1 /* top */ , 1 /* bottom */ ))
             || !TEST_true(BN_rand(bn, 1, 0 /* top */ , 0 /* bottom */ ))
-            || !TEST_true(BN_is_word(bn, 1))
+            || !TEST_BN_eq_one(bn)
             || !TEST_false(BN_rand(bn, 1, 1 /* top */ , 0 /* bottom */ ))
             || !TEST_true(BN_rand(bn, 1, -1 /* top */ , 1 /* bottom */ ))
-            || !TEST_true(BN_is_word(bn, 1))
+            || !TEST_BN_eq_one(bn)
             || !TEST_true(BN_rand(bn, 2, 1 /* top */ , 0 /* bottom */ ))
-            || !TEST_true(BN_is_word(bn, 3)))
+            || !TEST_BN_eq_word(bn, 3))
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(bn);
     return st;
 }
 
-static int test_negzero()
+/*
+ * Run some statistical tests to provide a degree confidence that the
+ * BN_rand_range() function works as expected.  The test cases and
+ * critical values are generated by the bn_rand_range script.
+ *
+ * Each individual test is a Chi^2 goodness of fit for a specified number
+ * of samples and range.  The samples are assumed to be independent and
+ * that they are from a discrete uniform distribution.
+ *
+ * Some of these individual tests are expected to fail, the success/failure
+ * of each is an independent Bernoulli trial.  The number of such successes
+ * will form a binomial distribution.  The count of the successes is compared
+ * against a precomputed critical value to determine the overall outcome.
+ */
+struct rand_range_case {
+    unsigned int range;
+    unsigned int iterations;
+    double critical;
+};
+
+#include "bn_rand_range.h"
+
+static int test_rand_range_single(size_t n)
+{
+    const unsigned int range = rand_range_cases[n].range;
+    const unsigned int iterations = rand_range_cases[n].iterations;
+    const double critical = rand_range_cases[n].critical;
+    const double expected = iterations / (double)range;
+    double sum = 0;
+    BIGNUM *rng = NULL, *val = NULL;
+    size_t *counts;
+    unsigned int i, v;
+    int res = 0;
+
+    if (!TEST_ptr(counts = OPENSSL_zalloc(sizeof(*counts) * range))
+        || !TEST_ptr(rng = BN_new())
+        || !TEST_ptr(val = BN_new())
+        || !TEST_true(BN_set_word(rng, range)))
+        goto err;
+    for (i = 0; i < iterations; i++) {
+        if (!TEST_true(BN_rand_range(val, rng))
+            || !TEST_uint_lt(v = (unsigned int)BN_get_word(val), range))
+            goto err;
+        counts[v]++;
+    }
+
+    for (i = 0; i < range; i++) {
+        const double delta = counts[i] - expected;
+        sum += delta * delta;
+    }
+    sum /= expected;
+
+    if (sum > critical) {
+        TEST_info("Chi^2 test negative %.4f > %4.f", sum, critical);
+        TEST_note("test case %zu  range %u  iterations %u", n + 1, range,
+                  iterations);
+        goto err;
+    }
+
+    res = 1;
+err:
+    BN_free(rng);
+    BN_free(val);
+    OPENSSL_free(counts);
+    return res;
+}
+
+static int test_rand_range(void)
+{
+    int n_success = 0;
+    size_t i;
+
+    for (i = 0; i < OSSL_NELEM(rand_range_cases); i++)
+        n_success += test_rand_range_single(i);
+    if (TEST_int_ge(n_success, binomial_critical))
+        return 1;
+    TEST_note("This test is expeced to fail by chance 0.01%% of the time.");
+    return 0;
+}
+
+static int test_negzero(void)
 {
     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
     BIGNUM *numerator = NULL, *denominator = NULL;
@@ -1755,8 +2053,8 @@ static int test_negzero()
     BN_zero(b);
     if (!TEST_true(BN_mul(c, a, b, ctx)))
         goto err;
-    if (!TEST_true(BN_is_zero(c))
-            || !TEST_false(BN_is_negative(c)))
+    if (!TEST_BN_eq_zero(c)
+            || !TEST_BN_ge_zero(c))
         goto err;
 
     for (consttime = 0; consttime < 2; consttime++) {
@@ -1773,15 +2071,15 @@ static int test_negzero()
             goto err;
         BN_set_negative(numerator, 1);
         if (!TEST_true(BN_div(a, b, numerator, denominator, ctx))
-                || !TEST_true(BN_is_zero(a))
-                || !TEST_false(BN_is_negative(a)))
+                || !TEST_BN_eq_zero(a)
+                || !TEST_BN_ge_zero(a))
             goto err;
 
         /* Test that BN_div never gives negative zero in the remainder. */
         if (!TEST_true(BN_set_word(denominator, 1))
                 || !TEST_true(BN_div(a, b, numerator, denominator, ctx))
-                || !TEST_true(BN_is_zero(b))
-                || !TEST_false(BN_is_negative(b)))
+                || !TEST_BN_eq_zero(b)
+                || !TEST_BN_ge_zero(b))
             goto err;
         BN_free(numerator);
         BN_free(denominator);
@@ -1795,7 +2093,7 @@ static int test_negzero()
         goto err;
     st = 1;
 
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(c);
@@ -1805,7 +2103,7 @@ err:
     return st;
 }
 
-static int test_badmod()
+static int test_badmod(void)
 {
     BIGNUM *a = NULL, *b = NULL, *zero = NULL;
     BN_MONT_CTX *mont = NULL;
@@ -1836,7 +2134,7 @@ static int test_badmod()
     ERR_clear_error();
 
     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
-                                             zero, ctx, NULL)))
+                                              zero, ctx, NULL)))
         goto err;
     ERR_clear_error();
 
@@ -1858,12 +2156,12 @@ static int test_badmod()
     ERR_clear_error();
 
     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
-                                  b, ctx, NULL)))
+                                              b, ctx, NULL)))
         goto err;
     ERR_clear_error();
 
     st = 1;
-err:
+ err:
     BN_free(a);
     BN_free(b);
     BN_free(zero);
@@ -1871,7 +2169,7 @@ err:
     return st;
 }
 
-static int test_expmodzero()
+static int test_expmodzero(void)
 {
     BIGNUM *a = NULL, *r = NULL, *zero = NULL;
     int st = 0;
@@ -1883,140 +2181,255 @@ static int test_expmodzero()
     BN_zero(zero);
 
     if (!TEST_true(BN_mod_exp(r, a, zero, BN_value_one(), NULL))
-            || !TEST_true(BN_is_zero(r))
+            || !TEST_BN_eq_zero(r)
             || !TEST_true(BN_mod_exp_mont(r, a, zero, BN_value_one(),
                                           NULL, NULL))
-            || !TEST_true(BN_is_zero(r))
+            || !TEST_BN_eq_zero(r)
             || !TEST_true(BN_mod_exp_mont_consttime(r, a, zero,
                                                     BN_value_one(),
                                                     NULL, NULL))
-            || !TEST_true(BN_is_zero(r))
+            || !TEST_BN_eq_zero(r)
             || !TEST_true(BN_mod_exp_mont_word(r, 42, zero,
                                                BN_value_one(), NULL, NULL))
-            || !TEST_true(BN_is_zero(r)))
+            || !TEST_BN_eq_zero(r))
         goto err;
 
     st = 1;
-err:
+ err:
     BN_free(zero);
     BN_free(a);
     BN_free(r);
     return st;
 }
 
-static int test_smallprime()
+static int test_expmodone(void)
+{
+    int ret = 0, i;
+    BIGNUM *r = BN_new();
+    BIGNUM *a = BN_new();
+    BIGNUM *p = BN_new();
+    BIGNUM *m = BN_new();
+
+    if (!TEST_ptr(r)
+            || !TEST_ptr(a)
+            || !TEST_ptr(p)
+            || !TEST_ptr(p)
+            || !TEST_ptr(m)
+            || !TEST_true(BN_set_word(a, 1))
+            || !TEST_true(BN_set_word(p, 0))
+            || !TEST_true(BN_set_word(m, 1)))
+        goto err;
+
+    /* Calculate r = 1 ^ 0 mod 1, and check the result is always 0 */
+    for (i = 0; i < 2; i++) {
+        if (!TEST_true(BN_mod_exp(r, a, p, m, NULL))
+                || !TEST_BN_eq_zero(r)
+                || !TEST_true(BN_mod_exp_mont(r, a, p, m, NULL, NULL))
+                || !TEST_BN_eq_zero(r)
+                || !TEST_true(BN_mod_exp_mont_consttime(r, a, p, m, NULL, NULL))
+                || !TEST_BN_eq_zero(r)
+                || !TEST_true(BN_mod_exp_mont_word(r, 1, p, m, NULL, NULL))
+                || !TEST_BN_eq_zero(r)
+                || !TEST_true(BN_mod_exp_simple(r, a, p, m, NULL))
+                || !TEST_BN_eq_zero(r)
+                || !TEST_true(BN_mod_exp_recp(r, a, p, m, NULL))
+                || !TEST_BN_eq_zero(r))
+            goto err;
+        /* Repeat for r = 1 ^ 0 mod -1 */
+        if (i == 0)
+            BN_set_negative(m, 1);
+    }
+
+    ret = 1;
+ err:
+    BN_free(r);
+    BN_free(a);
+    BN_free(p);
+    BN_free(m);
+    return ret;
+}
+
+static int test_smallprime(int kBits)
 {
-    static const int kBits = 10;
     BIGNUM *r;
     int st = 0;
 
-    if (!TEST_ptr(r = BN_new())
-            || !TEST_true(BN_generate_prime_ex(r, (int)kBits, 0,
-                                               NULL, NULL, NULL))
-            || !TEST_int_eq(BN_num_bits(r), kBits))
+    if (!TEST_ptr(r = BN_new()))
         goto err;
 
+    if (kBits <= 1) {
+        if (!TEST_false(BN_generate_prime_ex(r, kBits, 0,
+                                             NULL, NULL, NULL)))
+            goto err;
+    } else {
+        if (!TEST_true(BN_generate_prime_ex(r, kBits, 0,
+                                            NULL, NULL, NULL))
+                || !TEST_int_eq(BN_num_bits(r), kBits))
+            goto err;
+    }
+
     st = 1;
-err:
+ err:
     BN_free(r);
     return st;
 }
 
-static int test_3_is_prime()
+static int test_smallsafeprime(int kBits)
+{
+    BIGNUM *r;
+    int st = 0;
+
+    if (!TEST_ptr(r = BN_new()))
+        goto err;
+
+    if (kBits <= 5 && kBits != 3) {
+        if (!TEST_false(BN_generate_prime_ex(r, kBits, 1,
+                                             NULL, NULL, NULL)))
+            goto err;
+    } else {
+        if (!TEST_true(BN_generate_prime_ex(r, kBits, 1,
+                                            NULL, NULL, NULL))
+                || !TEST_int_eq(BN_num_bits(r), kBits))
+            goto err;
+    }
+
+    st = 1;
+ err:
+    BN_free(r);
+    return st;
+}
+
+static int primes[] = { 2, 3, 5, 7, 17863 };
+
+static int test_is_prime(int i)
 {
     int ret = 0;
     BIGNUM *r = NULL;
+    int trial;
 
-    /*
-     * For a long time, small primes were not considered prime when
-     * do_trial_division was set.
-     */
-    if (!TEST_ptr(r = BN_new())
-            || !TEST_true(BN_set_word(r, 3))
-            || !TEST_int_eq(BN_is_prime_fasttest_ex(r, 3 /* nchecks */, ctx,
-                                0 /* do_trial_division */, NULL), 1)
-            || !TEST_int_eq(BN_is_prime_fasttest_ex(r, 3 /* nchecks */, ctx,
-                                1 /* do_trial_division */, NULL), 1))
+    if (!TEST_ptr(r = BN_new()))
         goto err;
 
-    ret = 1;
+    for (trial = 0; trial <= 1; ++trial) {
+        if (!TEST_true(BN_set_word(r, primes[i]))
+                || !TEST_int_eq(BN_check_prime(r, ctx, NULL),
+                                1))
+            goto err;
+    }
 
-err:
+    ret = 1;
+ err:
     BN_free(r);
     return ret;
 }
 
+static int not_primes[] = { -1, 0, 1, 4 };
 
-/* Delete leading and trailing spaces from a string */
-static char *strip_spaces(char *p)
+static int test_not_prime(int i)
 {
-    char *q;
+    int ret = 0;
+    BIGNUM *r = NULL;
+    int trial;
 
-    /* Skip over leading spaces */
-    while (*p && isspace(*p))
-        p++;
-    if (!*p)
-        return NULL;
+    if (!TEST_ptr(r = BN_new()))
+        goto err;
 
-    for (q = p + strlen(p) - 1; q != p && isspace(*q); )
-        *q-- = '\0';
-    return *p ? p : NULL;
+    for (trial = 0; trial <= 1; ++trial) {
+        if (!TEST_true(BN_set_word(r, not_primes[i]))
+                || !TEST_false(BN_check_prime(r, ctx, NULL)))
+            goto err;
+    }
+
+    ret = 1;
+ err:
+    BN_free(r);
+    return ret;
 }
 
-/*
- * Read next test stanza; return 1 if found, 0 on EOF or error.
- */
-static int readstanza(STANZA *s, int *linesread)
+static int test_ctx_set_ct_flag(BN_CTX *c)
 {
-    PAIR *pp = s->pairs;
-    char *p, *equals, *key, *value;
-    char buff[1024];
-
-    while (fgets(buff, sizeof(buff), fp) != NULL) {
-        (*linesread)++;
-        if (!TEST_ptr(p = strchr(buff, '\n'))) {
-            TEST_info("Line %d too long", s->start);
-            return 0;
-        }
-        *p = '\0';
+    int st = 0;
+    size_t i;
+    BIGNUM *b[15];
 
-        /* Blank line marks end of tests. */
-        if (buff[0] == '\0')
-            break;
+    BN_CTX_start(c);
+    for (i = 0; i < OSSL_NELEM(b); i++) {
+        if (!TEST_ptr(b[i] = BN_CTX_get(c)))
+            goto err;
+        if (i % 2 == 1)
+            BN_set_flags(b[i], BN_FLG_CONSTTIME);
+    }
 
-        /* Lines starting with a pound sign are ignored. */
-        if (buff[0] == '#')
-            continue;
+    st = 1;
+ err:
+    BN_CTX_end(c);
+    return st;
+}
 
-        if (!TEST_ptr(equals = strchr(buff, '=')))
-            return 0;
-        *equals++ = '\0';
+static int test_ctx_check_ct_flag(BN_CTX *c)
+{
+    int st = 0;
+    size_t i;
+    BIGNUM *b[30];
 
-        if (!TEST_ptr(key = strip_spaces(buff))
-                || !TEST_ptr(value = strip_spaces(equals))
-                || !TEST_int_lt(s->numpairs++, MAXPAIRS)
-                || !TEST_ptr(pp->key = OPENSSL_strdup(key))
-                || !TEST_ptr(pp->value = OPENSSL_strdup(value)))
-            return 0;
-        pp++;
+    BN_CTX_start(c);
+    for (i = 0; i < OSSL_NELEM(b); i++) {
+        if (!TEST_ptr(b[i] = BN_CTX_get(c)))
+            goto err;
+        if (!TEST_false(BN_get_flags(b[i], BN_FLG_CONSTTIME)))
+            goto err;
     }
 
-    /* If we read anything, return ok. */
-    return 1;
+    st = 1;
+ err:
+    BN_CTX_end(c);
+    return st;
 }
 
-static void clearstanza(STANZA *s)
+static int test_ctx_consttime_flag(void)
 {
-    PAIR *pp = s->pairs;
-    int i = s->numpairs;
-    int start = s->start;
+    /*-
+     * The constant-time flag should not "leak" among BN_CTX frames:
+     *
+     * - test_ctx_set_ct_flag() starts a frame in the given BN_CTX and
+     *   sets the BN_FLG_CONSTTIME flag on some of the BIGNUMs obtained
+     *   from the frame before ending it.
+     * - test_ctx_check_ct_flag() then starts a new frame and gets a
+     *   number of BIGNUMs from it. In absence of leaks, none of the
+     *   BIGNUMs in the new frame should have BN_FLG_CONSTTIME set.
+     *
+     * In actual BN_CTX usage inside libcrypto the leak could happen at
+     * any depth level in the BN_CTX stack, with varying results
+     * depending on the patterns of sibling trees of nested function
+     * calls sharing the same BN_CTX object, and the effect of
+     * unintended BN_FLG_CONSTTIME on the called BN_* functions.
+     *
+     * This simple unit test abstracts away this complexity and verifies
+     * that the leak does not happen between two sibling functions
+     * sharing the same BN_CTX object at the same level of nesting.
+     *
+     */
+    BN_CTX *nctx = NULL;
+    BN_CTX *sctx = NULL;
+    size_t i = 0;
+    int st = 0;
 
-    for ( ; --i >= 0; pp++) {
-        OPENSSL_free(pp->key);
-        OPENSSL_free(pp->value);
+    if (!TEST_ptr(nctx = BN_CTX_new())
+            || !TEST_ptr(sctx = BN_CTX_secure_new()))
+        goto err;
+
+    for (i = 0; i < 2; i++) {
+        BN_CTX *c = i == 0 ? nctx : sctx;
+        if (!TEST_true(test_ctx_set_ct_flag(c))
+                || !TEST_true(test_ctx_check_ct_flag(c)))
+            goto err;
     }
-    memset(s, 0, sizeof(*s));
-    s->start = start;
+
+    st = 1;
+ err:
+    BN_CTX_free(nctx);
+    BN_CTX_free(sctx);
+    return st;
 }
 
 static int file_test_run(STANZA *s)
@@ -2040,86 +2453,129 @@ static int file_test_run(STANZA *s)
     for ( ; --numtests >= 0; tp++) {
         if (findattr(s, tp->name) != NULL) {
             if (!tp->func(s)) {
-                TEST_info("Failed %s test at %d", tp->name, s->start);
+                TEST_info("%s:%d: Failed %s test",
+                          s->test_file, s->start, tp->name);
                 return 0;
             }
             return 1;
         }
     }
-    TEST_info("Unknown test at %d", s->start);
+    TEST_info("%s:%d: Unknown test", s->test_file, s->start);
     return 0;
 }
 
-static int file_tests()
+static int run_file_tests(int i)
 {
-    STANZA s;
-    int linesread = 0, errcnt = 0;
+    STANZA *s = NULL;
+    char *testfile = test_get_argument(i);
+    int c;
+
+    if (!TEST_ptr(s = OPENSSL_zalloc(sizeof(*s))))
+        return 0;
+    if (!test_start_file(s, testfile)) {
+        OPENSSL_free(s);
+        return 0;
+    }
 
     /* Read test file. */
-    memset(&s, 0, sizeof(s));
-    while (!feof(fp) && readstanza(&s, &linesread)) {
-        if (s.numpairs == 0)
+    while (!BIO_eof(s->fp) && test_readstanza(s)) {
+        if (s->numpairs == 0)
             continue;
-        if (!file_test_run(&s)) {
-            errcnt++;
-        }
-        clearstanza(&s);
-        s.start = linesread;
+        if (!file_test_run(s))
+            s->errors++;
+        s->numtests++;
+        test_clearstanza(s);
     }
+    test_end_file(s);
+    c = s->errors;
+    OPENSSL_free(s);
+
+    return c == 0;
+}
+
+typedef enum OPTION_choice {
+    OPT_ERR = -1,
+    OPT_EOF = 0,
+    OPT_STOCHASTIC_TESTS,
+    OPT_TEST_ENUM
+} OPTION_CHOICE;
 
-    return errcnt == 0;
+const OPTIONS *test_get_options(void)
+{
+    static const OPTIONS test_options[] = {
+        OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
+        { "stochastic", OPT_STOCHASTIC_TESTS, '-', "Run stochastic tests" },
+        { OPT_HELP_STR, 1, '-',
+          "file\tFile to run tests on. Normal tests are not run\n" },
+        { NULL }
+    };
+    return test_options;
 }
 
-int test_main(int argc, char *argv[])
+int setup_tests(void)
 {
-    static const char rnd_seed[] =
-        "If not seeded, BN_generate_prime might fail";
-    int result = 0;
+    OPTION_CHOICE o;
+    int n, stochastic = 0;
 
-    if (argc != 2) {
-        TEST_error("%s TEST_FILE", argv[0]);
-        return 0;
+    while ((o = opt_next()) != OPT_EOF) {
+        switch (o) {
+        case OPT_STOCHASTIC_TESTS:
+            stochastic = 1;
+            break;
+        case OPT_TEST_CASES:
+           break;
+        default:
+        case OPT_ERR:
+            return 0;
+        }
     }
+    n  = test_get_argument_count();
+
+    if (!TEST_ptr(ctx = BN_CTX_new()))
+        return 0;
 
-    ADD_TEST(test_sub);
-    ADD_TEST(test_div_recip);
-    ADD_TEST(test_mod);
-    ADD_TEST(test_modexp_mont5);
-    ADD_TEST(test_kronecker);
-    ADD_TEST(test_rand);
-    ADD_TEST(test_bn2padded);
-    ADD_TEST(test_dec2bn);
-    ADD_TEST(test_hex2bn);
-    ADD_TEST(test_asc2bn);
-    ADD_ALL_TESTS(test_mpi, (int)OSSL_NELEM(kMPITests));
-    ADD_TEST(test_negzero);
-    ADD_TEST(test_badmod);
-    ADD_TEST(test_expmodzero);
-    ADD_TEST(test_smallprime);
+    if (n == 0) {
+        ADD_TEST(test_sub);
+        ADD_TEST(test_div_recip);
+        ADD_TEST(test_mod);
+        ADD_TEST(test_modexp_mont5);
+        ADD_TEST(test_kronecker);
+        ADD_TEST(test_rand);
+        ADD_TEST(test_bn2padded);
+        ADD_TEST(test_dec2bn);
+        ADD_TEST(test_hex2bn);
+        ADD_TEST(test_asc2bn);
+        ADD_ALL_TESTS(test_mpi, (int)OSSL_NELEM(kMPITests));
+        ADD_TEST(test_negzero);
+        ADD_TEST(test_badmod);
+        ADD_TEST(test_expmodzero);
+        ADD_TEST(test_expmodone);
+        ADD_ALL_TESTS(test_smallprime, 16);
+        ADD_ALL_TESTS(test_smallsafeprime, 16);
+        ADD_TEST(test_swap);
+        ADD_TEST(test_ctx_consttime_flag);
 #ifndef OPENSSL_NO_EC2M
-    ADD_TEST(test_gf2m_add);
-    ADD_TEST(test_gf2m_mod);
-    ADD_TEST(test_gf2m_mul);
-    ADD_TEST(test_gf2m_sqr);
-    ADD_TEST(test_gf2m_modinv);
-    ADD_TEST(test_gf2m_moddiv);
-    ADD_TEST(test_gf2m_modexp);
-    ADD_TEST(test_gf2m_modsqrt);
-    ADD_TEST(test_gf2m_modsolvequad);
+        ADD_TEST(test_gf2m_add);
+        ADD_TEST(test_gf2m_mod);
+        ADD_TEST(test_gf2m_mul);
+        ADD_TEST(test_gf2m_sqr);
+        ADD_TEST(test_gf2m_modinv);
+        ADD_TEST(test_gf2m_moddiv);
+        ADD_TEST(test_gf2m_modexp);
+        ADD_TEST(test_gf2m_modsqrt);
+        ADD_TEST(test_gf2m_modsolvequad);
 #endif
-    ADD_TEST(test_3_is_prime);
-    ADD_TEST(file_tests);
-
-    RAND_seed(rnd_seed, sizeof rnd_seed);
-    ctx = BN_CTX_new();
-    TEST_check(ctx != NULL);
-
-    if (!TEST_ptr(fp = fopen(argv[1], "r")))
-        goto end;
-    result = run_tests(argv[0]);
-    fclose(fp);
+        ADD_ALL_TESTS(test_is_prime, (int)OSSL_NELEM(primes));
+        ADD_ALL_TESTS(test_not_prime, (int)OSSL_NELEM(not_primes));
+        if (stochastic)
+            ADD_TEST(test_rand_range);
+    } else {
+        ADD_ALL_TESTS(run_file_tests, n);
+    }
+    return 1;
+}
 
-end:
+void cleanup_tests(void)
+{
     BN_CTX_free(ctx);
-    return result;
 }