Skip to content

Commit 87fef43

Browse files
authored
fix(hmac): guard against size_t overflow
1 parent 2f0dc3b commit 87fef43

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 {
@@ -123,13 +124,17 @@ namespace hmac {
123124
}
124125

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

132135
// Step 4: Compute final HMAC
136+
if (digest_size > SIZE_MAX - block_size)
137+
throw std::overflow_error("digest_size + block_size overflow");
133138
std::vector<uint8_t> outer_data;
134139
outer_data.reserve(block_size + digest_size);
135140
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
@@ -115,6 +115,15 @@ TEST(HMACTest, InvalidTypeThrows) {
115115
EXPECT_THROW(hmac::get_hmac(key, 3, msg, 3, invalid), std::invalid_argument);
116116
}
117117

118+
TEST(HMACTest, MsgLenOverflowThrows) {
119+
const char key[] = "key";
120+
const char msg[] = "a";
121+
size_t huge_len = std::numeric_limits<size_t>::max() -
122+
hmac_hash::SHA256::SHA224_256_BLOCK_SIZE + 1;
123+
EXPECT_THROW(hmac::get_hmac(key, sizeof(key) - 1, msg, huge_len,
124+
hmac::TypeHash::SHA256), std::overflow_error);
125+
}
126+
118127
TEST(HMACTest, InvalidTypeThrowsString) {
119128
const std::string key = "key";
120129
const std::string msg = "abc";

0 commit comments

Comments
 (0)