fix: fill random buffer in chunks with mbedtls crypto backend (#6379)

* adjust crypto unit test to reproduce the issue

* fill random buffer in chunks with mbedtls crypto backend
This commit is contained in:
Mike Gelfand
2023-12-17 01:21:24 +00:00
committed by GitHub
parent 33c4cd1c44
commit a494da4fea
2 changed files with 42 additions and 9 deletions

View File

@@ -229,6 +229,21 @@ bool tr_rand_buffer_crypto(void* buffer, size_t length)
TR_ASSERT(buffer != nullptr); TR_ASSERT(buffer != nullptr);
auto constexpr ChunkSize = size_t{ MBEDTLS_CTR_DRBG_MAX_REQUEST };
static_assert(ChunkSize > 0U);
auto const lock = std::lock_guard(rng_mutex_); auto const lock = std::lock_guard(rng_mutex_);
return check_result(mbedtls_ctr_drbg_random(get_rng(), static_cast<unsigned char*>(buffer), length));
for (auto offset = size_t{ 0 }; offset < length; offset += ChunkSize)
{
if (!check_result(mbedtls_ctr_drbg_random(
get_rng(),
static_cast<unsigned char*>(buffer) + offset,
std::min(ChunkSize, length - offset))))
{
return false;
}
}
return true;
} }

View File

@@ -249,19 +249,31 @@ TEST(Crypto, random)
} }
} }
TEST(Crypto, randBuf) using CryptoRandBufferTest = ::testing::TestWithParam<size_t>;
{
static auto constexpr Width = 32U;
static auto constexpr Iterations = 100000U;
static auto constexpr Empty = std::array<uint8_t, Width>{};
auto buf = Empty; TEST_P(CryptoRandBufferTest, randBuf)
{
static auto constexpr Iterations = 1000U;
auto const width = GetParam();
auto const empty = std::vector<uint8_t>(width, 0);
auto buf = empty;
for (size_t i = 0; i < Iterations; ++i) for (size_t i = 0; i < Iterations; ++i)
{ {
auto tmp = buf; auto tmp = buf;
tr_rand_buffer(std::data(tmp), std::size(tmp)); tr_rand_buffer(std::data(tmp), std::size(tmp));
EXPECT_NE(tmp, Empty); EXPECT_NE(tmp, empty);
EXPECT_NE(tmp, buf);
buf = tmp;
}
for (size_t i = 0; i < Iterations; ++i)
{
auto tmp = buf;
EXPECT_TRUE(tr_rand_buffer_crypto(std::data(tmp), std::size(tmp)));
EXPECT_NE(tmp, empty);
EXPECT_NE(tmp, buf); EXPECT_NE(tmp, buf);
buf = tmp; buf = tmp;
} }
@@ -270,12 +282,18 @@ TEST(Crypto, randBuf)
{ {
auto tmp = buf; auto tmp = buf;
tr_rand_buffer_std(std::data(tmp), std::size(tmp)); tr_rand_buffer_std(std::data(tmp), std::size(tmp));
EXPECT_NE(tmp, Empty); EXPECT_NE(tmp, empty);
EXPECT_NE(tmp, buf); EXPECT_NE(tmp, buf);
buf = tmp; buf = tmp;
} }
} }
INSTANTIATE_TEST_SUITE_P(
Crypto,
CryptoRandBufferTest,
::testing::Values(32, 100, 1024, 3000),
::testing::PrintToStringParamName{});
TEST(Crypto, base64) TEST(Crypto, base64)
{ {
auto raw = std::string_view{ "YOYO!"sv }; auto raw = std::string_view{ "YOYO!"sv };