diff --git a/src/asherah.cc b/src/asherah.cc index 7e57eea..8fe5abd 100644 --- a/src/asherah.cc +++ b/src/asherah.cc @@ -435,10 +435,9 @@ class Asherah : public Napi::Addon { Napi::Number item_size = info[0].ToNumber(); int32_t value = item_size.Int32Value(); - if (value < 0) { - NapiUtils::ThrowException(env, - "set_max_stack_alloc_item_size: value must be non-negative"); - } + // Clamp to reasonable range without branching + constexpr int32_t MAX_STACK_SIZE = 1048576; // 1MB max + value = std::max(0, std::min(value, MAX_STACK_SIZE)); maximum_stack_alloc_size = static_cast(value); } catch (Napi::Error &e) { e.ThrowAsJavaScriptException(); @@ -743,6 +742,13 @@ class Asherah : public Napi::Addon { const size_t est_envelope_overhead = 185; const double base64_overhead = 1.34; + // Only check for overflow if suspiciously large (> 1TB) + if (unlikely(data_byte_len > 1099511627776ULL)) { + if (data_byte_len > SIZE_MAX / 2) { + throw std::invalid_argument("Data size too large for encryption"); + } + } + // Add one rather than using std::ceil to round up size_t est_data_byte_len = size_t(double(data_byte_len + est_encryption_overhead) * diff --git a/src/cobhan_buffer.h b/src/cobhan_buffer.h index 623494c..802656b 100644 --- a/src/cobhan_buffer.h +++ b/src/cobhan_buffer.h @@ -8,6 +8,7 @@ #include // for std::ostringstream #include // for std::runtime_error, std::invalid_argument #include // for std::string +#include "hints.h" // for unlikely #ifdef _WIN32 #include // for SecureZeroMemory @@ -119,6 +120,12 @@ class CobhanBuffer { } static size_t AllocationSizeToMaxDataSize(size_t allocation_len_bytes) { + // Check for buffer underflow with unlikely hint + constexpr size_t min_size = cobhan_header_size_bytes + canary_size_bytes + safety_padding_bytes; + if (unlikely(allocation_len_bytes < min_size)) { + throw std::invalid_argument("Buffer allocation size too small"); + } + size_t data_len_bytes = allocation_len_bytes - cobhan_header_size_bytes - canary_size_bytes - safety_padding_bytes; if (data_len_bytes > max_int32_size) { diff --git a/src/scoped_allocate.h b/src/scoped_allocate.h index ce94cfe..73aef82 100644 --- a/src/scoped_allocate.h +++ b/src/scoped_allocate.h @@ -3,6 +3,8 @@ #ifdef USE_SCOPED_ALLOCATE_BUFFER +#include "hints.h" // for unlikely macro + /* This macro allows us to allocate a buffer either on the stack or on the heap. If the requested buffer size is less than max_stack_alloc_size, we create the