From 9e711f5c9c18db7f0c62cb103d4bb84ead101de2 Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Thu, 4 Jun 2026 09:08:24 +0900 Subject: [PATCH] Add MAX ENTROPY BITS check --- tests/api/test_random.c | 30 ++++++++++++++++++++++++++++++ tests/api/test_random.h | 4 +++- wolfcrypt/src/wolfentropy.c | 2 +- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/tests/api/test_random.c b/tests/api/test_random.c index cdd7e84499..85ce701283 100644 --- a/tests/api/test_random.c +++ b/tests/api/test_random.c @@ -30,6 +30,9 @@ #include #include +#ifdef HAVE_ENTROPY_MEMUSE + #include +#endif #include #include @@ -739,3 +742,30 @@ int test_wc_RNG_HealthTest_SHA512(void) return EXPECT_RESULT(); } +int test_wc_Entropy_Get(void) +{ + EXPECT_DECLS; +#ifdef HAVE_ENTROPY_MEMUSE + byte entropy[WC_SHA3_256_DIGEST_SIZE]; /* 32 bytes */ + + /* bits <= 0: must reject */ + ExpectIntEQ(wc_Entropy_Get(0, entropy, sizeof(entropy)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wc_Entropy_Get(-1, entropy, sizeof(entropy)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + /* bits > MAX_ENTROPY_BITS: must reject (overflow guard) */ + ExpectIntEQ(wc_Entropy_Get(MAX_ENTROPY_BITS + 1, entropy, sizeof(entropy)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wc_Entropy_Get(2049, entropy, sizeof(entropy)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + /* entropy == NULL with len > 0: must reject */ + ExpectIntEQ(wc_Entropy_Get(MAX_ENTROPY_BITS, NULL, sizeof(entropy)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + /* valid call: bits == MAX_ENTROPY_BITS */ + ExpectIntEQ(wc_Entropy_Get(MAX_ENTROPY_BITS, entropy, sizeof(entropy)), 0); +#endif /* HAVE_ENTROPY_MEMUSE */ + return EXPECT_RESULT(); +} diff --git a/tests/api/test_random.h b/tests/api/test_random.h index 0f41b3e04a..07a86e6904 100644 --- a/tests/api/test_random.h +++ b/tests/api/test_random.h @@ -37,6 +37,7 @@ int test_wc_RNG_DRBG_Reseed(void); int test_wc_RNG_TestSeed(void); int test_wc_RNG_HealthTest(void); int test_wc_RNG_HealthTest_SHA512(void); +int test_wc_Entropy_Get(void); #define TEST_RANDOM_DECLS \ TEST_DECL_GROUP("random", test_wc_InitRng), \ @@ -51,6 +52,7 @@ int test_wc_RNG_HealthTest_SHA512(void); TEST_DECL_GROUP("random", test_wc_RNG_DRBG_Reseed), \ TEST_DECL_GROUP("random", test_wc_RNG_TestSeed), \ TEST_DECL_GROUP("random", test_wc_RNG_HealthTest), \ - TEST_DECL_GROUP("random", test_wc_RNG_HealthTest_SHA512) + TEST_DECL_GROUP("random", test_wc_RNG_HealthTest_SHA512), \ + TEST_DECL_GROUP("random", test_wc_Entropy_Get) #endif /* WOLFCRYPT_TEST_RANDOM_H */ diff --git a/wolfcrypt/src/wolfentropy.c b/wolfcrypt/src/wolfentropy.c index a8f42119f6..1d23c7d8c2 100644 --- a/wolfcrypt/src/wolfentropy.c +++ b/wolfcrypt/src/wolfentropy.c @@ -816,7 +816,7 @@ int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len) int noise_len; static byte noise[MAX_NOISE_CNT]; - if (bits <= 0 || (entropy == NULL && len > 0)) { + if (bits <= 0 || bits > MAX_ENTROPY_BITS || (entropy == NULL && len > 0)) { return BAD_FUNC_ARG; }