Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/asherah.cc
Original file line number Diff line number Diff line change
Expand Up @@ -435,10 +435,9 @@ class Asherah : public Napi::Addon<Asherah> {

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<size_t>(value);
} catch (Napi::Error &e) {
e.ThrowAsJavaScriptException();
Expand Down Expand Up @@ -743,6 +742,13 @@ class Asherah : public Napi::Addon<Asherah> {
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) *
Expand Down
7 changes: 7 additions & 0 deletions src/cobhan_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <sstream> // for std::ostringstream
#include <stdexcept> // for std::runtime_error, std::invalid_argument
#include <string> // for std::string
#include "hints.h" // for unlikely

#ifdef _WIN32
#include <windows.h> // for SecureZeroMemory
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions src/scoped_allocate.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading