diff --git a/src/ssl.c b/src/ssl.c index 3d26a38b1..c081086c2 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -50833,7 +50833,7 @@ int wolfSSL_mask_bits(WOLFSSL_BIGNUM* bn, int n) int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) { int ret = 0; - int len = bits / 8; + int len; int initTmpRng = 0; WC_RNG* rng = NULL; #ifdef WOLFSSL_SMALL_STACK @@ -50848,9 +50848,19 @@ int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) (void)bottom; WOLFSSL_MSG("wolfSSL_BN_rand"); + if (bits <= 0) { + return WOLFSSL_FAILURE; + } + + len = bits / 8; if (bits % 8) len++; + /* has to be a length of at least 1 since we set buf[0] and buf[len-1] */ + if (len < 1) { + return WOLFSSL_FAILURE; + } + #ifdef WOLFSSL_SMALL_STACK buff = (byte*)XMALLOC(1024, NULL, DYNAMIC_TYPE_TMP_BUFFER); tmpRNG = (WC_RNG*) XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); @@ -50906,7 +50916,7 @@ int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) int wolfSSL_BN_pseudo_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) { int ret = 0; - int len = bits / 8; + int len; int initTmpRng = 0; WC_RNG* rng = NULL; #ifdef WOLFSSL_SMALL_STACK @@ -50917,11 +50927,23 @@ int wolfSSL_BN_pseudo_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) byte buff[1024]; #endif - WOLFSSL_MSG("wolfSSL_BN_rand"); + WOLFSSL_MSG("wolfSSL_BN_pseudo_rand"); + if (bits <= 0) { + return WOLFSSL_FAILURE; + } + + len = bits / 8; if (bits % 8) len++; + /* has to be a length of at least 1 since we set buf[0] and buf[len-1] */ + if (top == 1 || top == 0 || bottom == 1) { + if (len < 1) { + return WOLFSSL_FAILURE; + } + } + #ifdef WOLFSSL_SMALL_STACK buff = (byte*)XMALLOC(1024, NULL, DYNAMIC_TYPE_TMP_BUFFER); tmpRNG = (WC_RNG*) XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/tests/api.c b/tests/api.c index 56e5efd7a..a0a015387 100644 --- a/tests/api.c +++ b/tests/api.c @@ -30458,6 +30458,29 @@ static void test_wolfSSL_RAND_bytes(void) #endif } +static void test_wolfSSL_BN_rand(void) +{ + #if defined(OPENSSL_EXTRA) + BIGNUM* bn; + + printf(testingFmt, "wolfSSL_BN_rand()"); + + AssertNotNull(bn = BN_new()); + AssertIntNE(BN_rand(bn, 0, 0, 0), SSL_SUCCESS); + BN_free(bn); + + AssertNotNull(bn = BN_new()); + AssertIntEQ(BN_rand(bn, 8, 0, 0), SSL_SUCCESS); + BN_free(bn); + + AssertNotNull(bn = BN_new()); + AssertIntEQ(BN_rand(bn, 64, 0, 0), SSL_SUCCESS); + BN_free(bn); + + printf(resultFmt, passed); + #endif +} + static void test_wolfSSL_pseudo_rand(void) { #if defined(OPENSSL_EXTRA) @@ -41550,6 +41573,7 @@ void ApiTest(void) test_wolfSSL_CTX_set_ecdh_auto(); test_wolfSSL_THREADID_hash(); test_wolfSSL_RAND_bytes(); + test_wolfSSL_BN_rand(); test_wolfSSL_pseudo_rand(); test_wolfSSL_PKCS8_Compat(); test_wolfSSL_PKCS8_d2i();