Skip to content

Implement overflow check in MaxCompressedLength function#242

Open
yusmer96-maker wants to merge 3 commits into
google:mainfrom
yusmer96-maker:yusmer96-maker-patch-1
Open

Implement overflow check in MaxCompressedLength function#242
yusmer96-maker wants to merge 3 commits into
google:mainfrom
yusmer96-maker:yusmer96-maker-patch-1

Conversation

@yusmer96-maker
Copy link
Copy Markdown

Summary

Add integer overflow check in MaxCompressedLength() to prevent
heap buffer overflow vulnerabilities.

Problem

The expression 32 + source_bytes + source_bytes / 6 can overflow
when source_bytes is very large, resulting in a small return value.
Callers use this value to allocate buffers, so an overflow leads to
undersized allocations and subsequent heap buffer overflows during
compression.

Fix

Added a bounds check before the calculation. If source_bytes exceeds
the safe threshold (SIZE_MAX - 32) / 7 * 6, the function returns
SIZE_MAX, which forces a controlled allocation failure instead of
silent memory corruption.

Add overflow check for buffer allocation in MaxCompressedLength
Comment thread snappy.cc Outdated
size_t MaxCompressedLength(size_t source_bytes) {
// Avoid integer overflow that could cause undersized buffer allocations.
// Return SIZE_MAX to force a controlled allocation failure.
if (source_bytes > (SIZE_MAX - 32) / 7 * 6) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Can you use std::numeric_limits<size_t>::max() ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! I initially used SIZE_MAX because I didn't notice was included transitively through snappy-stubs-internal.h. Now that I see it's available, I'll update to std::numeric_limits<size_t>::max(). Thanks for the suggestion.

Updated the overflow check to use std::numeric_limits<size_t>::max() for clarity.
Comment thread snappy.cc
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <memory>
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's have #include <limits> here as well

Copy link
Copy Markdown
Author

@yusmer96-maker yusmer96-maker Jun 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, added #include <limits>

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