Skip to content

Commit 1eea010

Browse files
committed
fix(hmac): guard against size_t overflow
1 parent d416ceb commit 1eea010

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

hmac.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include <algorithm>
22
#include <stdexcept>
3+
#include <cstdint>
34
#include "hmac.hpp"
45

56
namespace hmac {
@@ -122,13 +123,17 @@ namespace hmac {
122123
}
123124

124125
// Step 3: Compute inner hash
126+
if (msg_len > SIZE_MAX - block_size)
127+
throw std::overflow_error("msg_len + block_size overflow");
125128
std::vector<uint8_t> inner_data;
126129
inner_data.reserve(block_size + msg_len);
127130
inner_data.insert(inner_data.end(), ikeypad.begin(), ikeypad.end());
128131
inner_data.insert(inner_data.end(), reinterpret_cast<const uint8_t*>(msg_ptr), reinterpret_cast<const uint8_t*>(msg_ptr) + msg_len);
129132
std::vector<uint8_t> inner_hash = get_hash(inner_data.data(), inner_data.size(), type);
130133

131134
// Step 4: Compute final HMAC
135+
if (digest_size > SIZE_MAX - block_size)
136+
throw std::overflow_error("digest_size + block_size overflow");
132137
std::vector<uint8_t> outer_data;
133138
outer_data.reserve(block_size + digest_size);
134139
outer_data.insert(outer_data.end(), okeypad.begin(), okeypad.end());

test_all.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,15 @@ TEST(HMACTest, InvalidTypeThrows) {
9393
EXPECT_THROW(hmac::get_hmac(key, 3, msg, 3, invalid), std::invalid_argument);
9494
}
9595

96+
TEST(HMACTest, MsgLenOverflowThrows) {
97+
const char key[] = "key";
98+
const char msg[] = "a";
99+
size_t huge_len = std::numeric_limits<size_t>::max() -
100+
hmac_hash::SHA256::SHA224_256_BLOCK_SIZE + 1;
101+
EXPECT_THROW(hmac::get_hmac(key, sizeof(key) - 1, msg, huge_len,
102+
hmac::TypeHash::SHA256), std::overflow_error);
103+
}
104+
96105
TEST(TOTPTest, AtTime) {
97106
const std::string totp_key = "12345678901234567890";
98107
uint64_t test_time = 1234567890;

0 commit comments

Comments
 (0)