Skip to content

fix: cap ZLIB/GZIP decompressed size in DecodeCompressed op - #123846

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
prasanna8585:fix/decode-compressed-zlib-gzip-size-cap
Oct 28, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
prasanna8585:fix/decode-compressed-zlib-gzip-size-cap

Conversation

@prasanna8585

@prasanna8585 prasanna8585 commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

tensorflow/core/kernels/decode_compressed_op.cc implements the public DecodeCompressed op (tf.io.decode_compressed), which takes an arbitrary string tensor of attacker-controlled bytes and decompresses it using ZLIB, GZIP, or ZSTD.

Commit ce1bdcb added a hard 1GB cap to the ZSTD branch of DecompressOne(), 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 to INT_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 kMaxDecompressedBytes class constant. Since ZLIB/GZIP (unlike ZSTD) exposes no trustworthy declared size up front, the cap is enforced by reading kMaxDecompressedBytes + 1 bytes: ReadNBytes returning OutOfRange means the true size is ≤ 1GB (accept), returning OkStatus means exactly the requested limit + 1 bytes were read, meaning the stream exceeds 1GB (reject with InvalidArgumentError, 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=1 to keep CPU time reasonable for 1GB payloads; test size bumped to medium accordingly.

@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Jul 23, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@prasanna8585
prasanna8585 force-pushed the fix/decode-compressed-zlib-gzip-size-cap branch from 521f883 to 34dab78 Compare July 23, 2026 13:30
@nithyak0204
nithyak0204 requested a review from a team July 24, 2026 04:01
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 24, 2026
@nithyak0204 nithyak0204 added the comp:core issues related to core part of tensorflow label Jul 24, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Jul 24, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Jul 27, 2026
…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.
@prasanna8585
prasanna8585 requested a review from dmiltr3 July 27, 2026 14:32
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Jul 28, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Jul 28, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Jul 28, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Jul 28, 2026
@prasanna8585

Copy link
Copy Markdown
Contributor Author

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!

@prasanna8585

Copy link
Copy Markdown
Contributor Author

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!

@prasanna8585

Copy link
Copy Markdown
Contributor Author

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.

@nithyak0204

Copy link
Copy Markdown

Hi @prasanna8585, Sorry for the delay, this PR is waiting for internal approvals. We are working on it. Thank you!

@prasanna8585

prasanna8585 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @dmiltr3 @nithyak0204 ,

Just following up to check if this is ready to be merged.

@prasanna8585

Copy link
Copy Markdown
Contributor Author

Hi @dmiltr3 @nithyak0204 ,
Are we ready to merge?

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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) and gzip.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/BUILD to 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!

@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Sep 27, 2026
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 27, 2026
@prasanna8585

Copy link
Copy Markdown
Contributor Author

Hi @dmiltr3,

Thanks for the detailed follow-up. Addressed all four items:

  1. kMaxDecompressedBytes is now a shared static constexpr class constant, reused by both the ZLIB/GZIP and ZSTD branches.

  2. output.clear() added before returning the error, so the oversized buffer is freed rather than held until the op call unwinds.

  3. Added testDecompressGzipAtLimitIsAccepted (mirroring the ZLIB boundary test), switched all three 1GB-payload tests to level=1/compresslevel=1 for faster CI runs, and bumped the test target to medium.

  4. Updated the PR description to reflect the final implementation.

Let me know if anything else is needed.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 27, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 28, 2026
@nithyak0204 nithyak0204 added ready to pull PR ready for merge process and removed ready to pull PR ready for merge process labels Oct 13, 2026
@nithyak0204 nithyak0204 added ready to pull PR ready for merge process and removed ready to pull PR ready for merge process labels Oct 28, 2026
@copybara-service
copybara-service Bot merged commit 50f613a into tensorflow:master Oct 28, 2026
21 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

5 participants