Repository navigation
fix: cap ZLIB/GZIP decompressed size in DecodeCompressed op - #123846
copybara-service[bot] merged 3 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a 1GB cap on the decompressed output size for the Zlib stream in DecodeCompressedOp to mitigate decompression bomb vulnerabilities. The review feedback points out an edge case where a valid stream of exactly 1GB would be incorrectly rejected with a ResourceExhaustedError. To resolve this, the reviewer suggests attempting to read 1GB + 1 bytes to accurately distinguish between a stream that is exactly 1GB and one that exceeds the limit.
DecodeCompressed's ZLIB/GZIP branch called
zlib_stream.ReadNBytes(INT_MAX, &output) with no compression-ratio or
absolute-size check, allowing a small, highly-compressible attacker
input (a decompression bomb) to force decompression up to ~2GiB with a
single op call.
Commit ce1bdcb ('Validate ZSTD decompressed size does not exceed 1GB
...') just added an equivalent cap to the ZSTD branch of the same
function. The ZLIB/GZIP branch was not covered by that fix and remains
vulnerable to the identical pattern.
Fix: cap the ZLIB/GZIP branch at the same 1GB limit used for ZSTD,
returning absl::ResourceExhaustedError when the decompressed output
reaches the cap rather than continuing to decompress up to INT_MAX.
521f883 to
34dab78
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for this fix! Mitigating decompression bomb vulnerabilities in DecodeCompressed is important.
I have reviewed the PR and have a few suggestions to ensure it is fully ready for merging and consistent with other parts of the codebase.
1. Boundary Condition Handling (Exactly 1 GB vs > 1 GB)
The existing ZSTD implementation allows files that decompress to exactly 1 GB (1,073,741,824 bytes). We should ensure ZLIB/GZIP behaves the same way.
If you use zlib_stream.ReadNBytes(kMaxDecompressedBytes, &output), and the stream is exactly 1 GB, ReadNBytes will fill the buffer and return absl::OkStatus(). If your check rejects on result.ok() && output.size() >= kMaxDecompressedBytes, it will incorrectly reject streams that are exactly 1 GB.
Recommendation:
Update ReadNBytes to try reading kMaxDecompressedBytes + 1 bytes:
constexpr int64_t kMaxDecompressedBytes = 1024LL * 1024 * 1024; // 1GB
absl::Status result = zlib_stream.ReadNBytes(kMaxDecompressedBytes + 1, &output);
if (absl::IsOutOfRange(result)) {
// Stream ended before or exactly at the limit.
// ReadNBytes swallowed EOF if it read up to requested, but here it failed to read limit + 1.
// So size is <= 1GB.
return absl::OkStatus();
}
if (result.ok()) {
// Read exactly limit + 1 bytes, meaning the stream is larger than 1GB.
return absl::InvalidArgumentError("Decompressed size exceeds 1GB limit");
}
return result;This correctly allows streams that are exactly 1 GB while rejecting those that exceed it.
2. Error Code Consistency
The ZSTD branch in decode_compressed_op.cc returns absl::InvalidArgumentError when the limit is exceeded. For consistency, we recommend using absl::InvalidArgumentError for the ZLIB/GZIP path as well (instead of absl::ResourceExhaustedError).
3. Unit Tests
We should add unit tests to verify these boundary cases. You can use zlib's compression objects to create highly compressible data efficiently without excessive memory usage in the test setup.
Here is a test case you can add to decode_compressed_op_test.py:
def testDecompressLargeZlibSize(self):
# Construct a highly compressible ZLIB stream that decompresses to > 1GB.
import zlib
compressor = zlib.compressobj()
compressed = b""
# 1 GB = 1024 MB
for _ in range(1024):
compressed += compressor.compress(b"\x00" * (1024 * 1024))
compressed += compressor.compress(b"\x00") # +1 byte
compressed += compressor.flush()
with self.cached_session():
# Use errors.ResourceExhaustedError if you decide to keep it,
# but errors.InvalidArgumentError is recommended for consistency.
with self.assertRaisesRegex(
errors.InvalidArgumentError, "Decompressed size exceeds 1GB limit"
):
self.evaluate(
parsing_ops.decode_compressed(
compressed, compression_type="ZLIB"
)
)You can add a similar test for GZIP if needed.
…ency, add tests - Restructure the ZLIB/GZIP size check to branch on ReadNBytes's status code directly, per review. - Use absl::InvalidArgumentError instead of absl::ResourceExhaustedError, consistent with the ZSTD branch. - Add boundary tests for both the accept (exactly 1GB) and reject (>1GB, ZLIB and GZIP) cases.
|
Hi Team, Just following up to check if any additional changes or steps are needed on my end, or if this is ready to be merged. Thanks! |
|
Hi @dmiltr3 , Just following up to check if any additional changes or steps are needed on my end, or if this is ready to be merged. Thanks! |
|
Hi @dmiltr3 , Just following up to check if any additional changes or steps are needed on my end, or if this is ready to be merged. |
|
Hi @prasanna8585, Sorry for the delay, this PR is waiting for internal approvals. We are working on it. Thank you! |
|
Hi @dmiltr3 @nithyak0204 , Just following up to check if this is ready to be merged. |
|
Hi @dmiltr3 @nithyak0204 , |
dmiltr3
left a comment
There was a problem hiding this comment.
Hi @prasanna8585, thank you for this hardening fix. We integrated it and verified it internally, and the kMaxDecompressedBytes + 1 approach is correct. A few small follow-ups are needed before merging. We prototyped all of them locally and the test suite passes.
1. Share one limit constant between ZLIB/GZIP and ZSTD (decode_compressed_op.cc)
Please make kMaxDecompressedBytes a private class constant, and reuse it in the ZSTD branch instead of the separate 1024 * 1024 * 1024 literal:
private:
enum { kBufferSize = 256 << 10 /* 256 kB */ };
// Maximum decompressed size accepted for every compression type.
static constexpr int64_t kMaxDecompressedBytes = 1024LL * 1024 * 1024; // 1GB if (max_decompressed_size > kMaxDecompressedBytes) {(and remove the local constexpr in the ZLIB/GZIP branch).
2. Free the oversized buffer before returning the error
When ReadNBytes succeeds, output holds 1 GB + 1 byte. Please release it right away:
if (result.ok()) {
// Read exactly limit + 1 bytes, meaning the stream is larger than
// 1GB. Free the oversized buffer before propagating the error.
output.clear();
return absl::InvalidArgumentError(
"Decompressed size exceeds 1GB limit");
}3. Tests (decode_compressed_op_test.py and BUILD)
-
Add a GZIP acceptance test for exactly 1 GB, matching
testDecompressZlibAtLimitIsAccepted:def testDecompressGzipAtLimitIsAccepted(self): # A GZIP stream that decompresses to EXACTLY 1GB must be accepted. kOneGb = 1024 * 1024 * 1024 chunk = b"\x00" * (1024 * 1024) # 1 MB out = io.BytesIO() with gzip.GzipFile(fileobj=out, mode="wb", compresslevel=1) as f: for _ in range(1024): # 1024 * 1MB = 1GB f.write(chunk) compressed = out.getvalue() with self.cached_session(): result = self.evaluate( parsing_ops.decode_compressed(compressed, compression_type="GZIP") ) self.assertLen(result, kOneGb)
-
In the 1 GB tests, use the fastest compression level:
zlib.compressobj(level=1)andgzip.GzipFile(..., compresslevel=1). Compressing 1 GB of zeros at the default level takes several seconds of CPU per test. -
These tests decompress 1 GB payloads, so please bump the test size in
tensorflow/python/kernel_tests/image_ops/BUILDto avoid timeouts, especially under sanitizers:tf_py_strict_test( name = "decode_compressed_op_test", - size = "small", + size = "medium",
4. Update the PR description
The ## Fix section still shows the first draft (ReadNBytes(kMaxDecompressedBytes, ...) and ResourceExhaustedError). Please update it to describe the final implementation: read kMaxDecompressedBytes + 1 bytes and return InvalidArgumentError. The PR description becomes the commit message.
Thanks again!
… GZIP boundary test
|
Hi @dmiltr3, Thanks for the detailed follow-up. Addressed all four items:
Let me know if anything else is needed. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the fix! This addresses the security vulnerability perfectly. The changes compile cleanly and pass all internal presubmit tests as well as the newly added unit tests.
LGTM.
Problem
tensorflow/core/kernels/decode_compressed_op.ccimplements the publicDecodeCompressedop (tf.io.decode_compressed), which takes an arbitrary string tensor of attacker-controlled bytes and decompresses it using ZLIB, GZIP, or ZSTD.Commit
ce1bdcbadded a hard 1GB cap to the ZSTD branch ofDecompressOne(), checked against the frame's declared decompressed size before any allocation or decompression occurs. The sibling ZLIB/GZIP branch of the exact same function had no equivalent limit, decompressing in 256 KB chunks up toINT_MAX(~2 GiB) with no compression-ratio or absolute-size check.Impact
A small, highly-compressible (~1000:1 ratio) attacker-supplied byte string forced an essentially uncapped in-memory decompression, up to ~2 GiB per input element, reachable from a standard public TF op with no authentication or preconditions beyond invoking the op.
Fix
Caps the ZLIB/GZIP branch at the same 1GB limit as ZSTD, now shared via a single
kMaxDecompressedBytesclass constant. Since ZLIB/GZIP (unlike ZSTD) exposes no trustworthy declared size up front, the cap is enforced by readingkMaxDecompressedBytes + 1bytes:ReadNBytesreturningOutOfRangemeans the true size is ≤ 1GB (accept), returningOkStatusmeans exactly the requestedlimit + 1bytes were read, meaning the stream exceeds 1GB (reject withInvalidArgumentError, after freeing the oversized buffer).Tests
Boundary tests for both ZLIB and GZIP confirm a stream decompressing to exactly 1GB is accepted, and one byte over is rejected. Compression uses
level=1to keep CPU time reasonable for 1GB payloads; test size bumped tomediumaccordingly.