Skip to content

fix: add overflow check in ReadBlock block size arithmetic#1312

Open
Tulgaaaaaaaa wants to merge 2 commits intogoogle:mainfrom
Tulgaaaaaaaa:fix/integer-overflow-readblock
Open

fix: add overflow check in ReadBlock block size arithmetic#1312
Tulgaaaaaaaa wants to merge 2 commits intogoogle:mainfrom
Tulgaaaaaaaa:fix/integer-overflow-readblock

Conversation

@Tulgaaaaaaaa
Copy link
Copy Markdown

@Tulgaaaaaaaa Tulgaaaaaaaa commented Mar 23, 2026

Problem

ReadBlock() in table/format.cc computes n + kBlockTrailerSize (where kBlockTrailerSize = 5) without checking for arithmetic overflow. The value n comes from BlockHandle::size() which is decoded from SSTable file data via GetVarint64 with no range validation.

When n is near SIZE_MAX, the addition wraps around, causing:

  • An undersized heap allocation (new char[wrapped_value])
  • Subsequent out-of-bounds memory access at offsets derived from the original large n

Additionally, handle.size() returns uint64_t which is silently truncated to size_t on 32-bit platforms.

Fix

Added two guards before the allocation:

  1. Truncation check: verify static_cast<size_t> did not lose bits from the uint64_t source
  2. Overflow check: verify n + kBlockTrailerSize does not wrap size_t

Both return Status::Corruption on failure.

Tests added

  • ReadBlockTest.SizeOverflow -- verifies rejection of block handles with sizes near SIZE_MAX
  • ReadBlockTest.TruncatedBlock -- verifies handling of blocks larger than the backing file

ReadBlock() passes handle.size() + kBlockTrailerSize to operator new
without checking for arithmetic overflow. A crafted SSTable with a
near-SIZE_MAX block handle size causes the addition to wrap around,
allocating a tiny buffer while subsequent accesses use the original
large offset.

Add checks for both size_t truncation (relevant on 32-bit) and
addition overflow before the allocation.

Bug: CWE-190 (Integer Overflow), CWE-122 (Heap Buffer Overflow)
@google-cla
Copy link
Copy Markdown

google-cla bot commented Mar 23, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

Verify that ReadBlock rejects block handles with sizes near SIZE_MAX
(overflow check) and handles truncated block reads gracefully.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants