From 1eea010a0ec121959a2d8e43e6401e2984c87bef Mon Sep 17 00:00:00 2001 From: Aster Seker Date: Thu, 4 Sep 2025 02:22:38 +0300 Subject: [PATCH] fix(hmac): guard against size_t overflow --- hmac.cpp | 5 +++++ test_all.cpp | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/hmac.cpp b/hmac.cpp index eec053e..0ed7a0a 100644 --- a/hmac.cpp +++ b/hmac.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "hmac.hpp" namespace hmac { @@ -122,6 +123,8 @@ namespace hmac { } // Step 3: Compute inner hash + if (msg_len > SIZE_MAX - block_size) + throw std::overflow_error("msg_len + block_size overflow"); std::vector inner_data; inner_data.reserve(block_size + msg_len); inner_data.insert(inner_data.end(), ikeypad.begin(), ikeypad.end()); @@ -129,6 +132,8 @@ namespace hmac { std::vector inner_hash = get_hash(inner_data.data(), inner_data.size(), type); // Step 4: Compute final HMAC + if (digest_size > SIZE_MAX - block_size) + throw std::overflow_error("digest_size + block_size overflow"); std::vector outer_data; outer_data.reserve(block_size + digest_size); outer_data.insert(outer_data.end(), okeypad.begin(), okeypad.end()); diff --git a/test_all.cpp b/test_all.cpp index d070c29..f6386fe 100644 --- a/test_all.cpp +++ b/test_all.cpp @@ -93,6 +93,15 @@ TEST(HMACTest, InvalidTypeThrows) { EXPECT_THROW(hmac::get_hmac(key, 3, msg, 3, invalid), std::invalid_argument); } +TEST(HMACTest, MsgLenOverflowThrows) { + const char key[] = "key"; + const char msg[] = "a"; + size_t huge_len = std::numeric_limits::max() - + hmac_hash::SHA256::SHA224_256_BLOCK_SIZE + 1; + EXPECT_THROW(hmac::get_hmac(key, sizeof(key) - 1, msg, huge_len, + hmac::TypeHash::SHA256), std::overflow_error); +} + TEST(TOTPTest, AtTime) { const std::string totp_key = "12345678901234567890"; uint64_t test_time = 1234567890;