Skip to content

Do not read the compressed-buffer slack as LZ4 literal data - #116992

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-lz4-uninitialized-slack-read
Sep 5, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-lz4-uninitialized-slack-read

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Closes: https://github.com/ClickHouse/clickhouse-private/issues/71232

The LZ4 decoder is given 64 bytes of slack after the compressed payload so that its unconditional wild copies stay inside allocated memory. The bound on the literal copy was expressed against the end of that slack instead of the end of the payload, so a malformed block could take literal data from it. The slack is not initialized.

Bound the literal by the end of the payload. The new check is stricter than the old one, so the wild-copy over-read stays covered.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed reading uninitialized memory as literal data when decompressing a malformed LZ4-compressed block.


Workflow [PR]
Sync PR [sync-upstream/pr/116992]

Version info

  • Backported to: 26.8.3.48, 26.7.7.34, 26.6.5.59, 26.3.32.12

The LZ4 decoder is given `ADDITIONAL_BYTES_AT_END_OF_BUFFER` (64) bytes of
slack after the compressed payload so that its unconditional wild copies stay
inside allocated memory. That slack is not initialized, and the bound on the
literal copy was expressed against the end of the slack rather than the end of
the payload, so a block declaring a literal longer than the bytes it actually
carries filled the decompressed block from the slack and still reported success.

Bound the literal by the end of the payload instead. The new check is stricter
than the old one, so the wild-copy over-read stays covered, and it no longer
needs to compute the rounded-up copy length.
@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [afce088]

Summary: ✅


AI Review

Summary

The PR hardens the LZ4 decoder against malformed-input slack reads and out-of-range pointer formation, and the current head backs that change with both an end-to-end clickhouse-compressor regression test and forced-variant gtest coverage for all three decoder variants, including the match-side output_end guard. I did not find any remaining correctness, safety, or evidence gaps in the current diff, and the prior bot-raised issues are addressed in the code now.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit afce088.

Metric Baseline Current Δ
Lines 88.80% 88.70% -0.10%
Functions 92.20% 92.10% -0.10%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 137/137 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing afce088af with master cdc26e3bd (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 5 s compile time in total, 7 of them have a recent master baseline.

Job report

The three "at least two more bytes are available" guards in `decompressImpl`
were written as `ip + 1 >= input_end`. `ip` is allowed to be exactly
`input_end` at each of them, and then `ip + 1` is two past the end of the
payload, which is out-of-range pointer arithmetic before the guard gets a
chance to reject the block.

All three states are reachable from malformed input, and two of them need only
a single payload byte: `f0` (a literal length of `0x0F` with no continuation
byte) reaches the first guard, `00` reaches the second one through the
`length == 0` shortcut of the 8-byte variant, and `1f000100` reaches the third
one.

Compare the distance instead. Given the `ip <= input_end` invariant that the
loop already maintains, `input_end - ip < 2` is exactly equivalent to the old
condition, so no block changes its verdict - verified over 3.49e9 crafted
blocks (all payloads up to 4 bytes, plus random longer ones, against all three
`copy_amount` variants): identical accept/reject and identical output bytes.
The distance form also generates one or two instructions less per variant,
because the loop already computes `input_end - ip` for the literal bound.
`copy_end = op + length` was formed before `copy_end > output_end` rejected it,
on both the literal and the match path. `length` comes from
`continue_read_length` and is bounded only by `255 * source_size`, so for a
crafted block the pointer is formed far outside the destination object - a
payload of `f0` followed by n bytes of `0xff` puts it about `255 * n` bytes past
`output_end`, measured 16711655 bytes past for n = 65536. That is the same
out-of-range pointer arithmetic that the input-side guards had, and this
function already avoids it deliberately for `match` (see the comment on the
`offset - 1 >= produced` check).

Compare the distance and form `copy_end` only once it is known to be in range.
`op <= output_end` is an invariant of the loop - `op` only ever becomes a
`copy_end` that was just bounded - so `output_end - op` is non-negative and the
new condition is exactly equivalent to the old one. Verified together with the
input-side guards over 3.49e9 crafted blocks against all three `copy_amount`
variants: identical accept/reject and identical output bytes, 0 mismatches.

This costs throughput, unlike the input-side change. Measured with the real
decoder on synthetic data at three compression ratios, best of 6 interleaved
runs, against the tip of this branch before this commit: `-1.3%` for
`copy_amount == 8` and `-2.2%` for `copy_amount == 16`. Relative to the state
before both commits that nets `-1.0%` and `+0.8%` respectively, because the
input-side change was itself worth `+0.3%` and `+3.0%`. Folding the literal's
output and payload bounds into a single `min` was also tried and came out
slightly worse than this, so the cost looks inherent to not letting the
compiler compute `op + length` before the branch.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Folded the output-side bound in as well (3aaf737), so all four bounds in decompressImpl are now distances and no pointer is formed before it has been validated.

Heads-up on cost — this one is not free, unlike the guard change. Measured with the real decoder (this TU compiled standalone and linked against contrib/lz4's compressor as the data source), synthetic data at three compression ratios plus a 64 KiB block, best of 6 interleaved runs per binary:

copy_amount == 8 copy_amount == 16
f8f20b8 (guards only) vs. a081270 +0.3% +3.0%
3aaf737 (both) vs. f8f20b8 −1.3% −2.2%
3aaf737 (both) vs. a081270 −1.0% +0.8%

The guard change is a small win (it removes 1–2 instructions per variant, because the loop already computes input_end - ip). The output-side bound gives that back and a bit more: it needs output_end - op and op + length, where before only op + length was computed, and it denies the compiler the license to compute copy_end before the branch. I also tried folding the literal's output and payload bounds into one min(...) — one branch instead of two — and it measured slightly worse (−1.3% instead of −1.0% on copy_amount == 8), so the cost looks inherent rather than a codegen accident.

Net effect on copy_amount == 8, which per this file's own comments wins 57% of files: about 1% below the pre-PR baseline.

Verification for both commits: 3.49e9 crafted blocks (all payloads up to 4 bytes across the interesting token values and destination sizes, plus 3e6 random longer ones) run through the old and new formulations of every changed bound, across all three variants — identical accept/reject and identical output bytes, 0 mismatches. The real compiled LZ4::decompress also still rejects the 05048 payload, the three minimal payloads that reach each 2-byte guard with ip == input_end, and an output-overshoot payload, while decoding well-formed blocks unchanged.

@alexey-milovidov — if the ~1% is not a price you want to pay here, say so and I will revert 3aaf737; the reviewer's blocker is fully addressed by f8f20b8 alone, which is a net win on its own. Keeping it closes the whole out-of-range-pointer class in this function, which is why I left it in by default.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Correction to my previous comment — there is no performance degradation. The numbers I posted were measured against this PR's own head (a081270), which had already banked a large win from the core fix. Against pre-PR master — the baseline that actually matters — the whole PR is faster, including the output-side bound. Same harness, best of 6 interleaved runs per binary:

copy_amount == 8 copy_amount == 16 copy_amount == 32
41a6d61 core fix, vs pre-PR master +5.07% +1.33% +0.63%
f8f20b8 +guards, vs pre-PR master +5.24% +3.26% +2.74%
3aaf737 HEAD, vs pre-PR master +3.80% +2.16% +1.46%

The core fix is a win because length > input_end - ip replaced the real_length round-up ((((length >> 3) + 1) * 8) plus ip + real_length >= input_end + ADDITIONAL_BYTES_AT_END_OF_BUFFER) — a stricter check that is also cheaper. Instruction counts per variant confirm HEAD is at or below master: 154/98/129 vs 155/98/129. So the ~1.5% the output bound costs is paid out of a ~5% win, not out of master.

On zero-initializing the padding and letting the copies use it

I looked into this and it cannot replace the payload-end bound, because the padding is not a dedicated allocation in the common case. In CompressedReadBufferBase::readCompressedData:

if (!own_compressed_buffer_header_init
    && compressed_in->available() >= size_compressed_without_checksum - header_size + additional_size_at_the_end_of_buffer)
{
    compressed_buffer = compressed_in->position() - header_size;
    compressed_in->position() += size_compressed_without_checksum - header_size;
}

On this path compressed_buffer points directly into compressed_in's buffer, and the condition guarantees the 64 bytes past the payload are still inside it — those bytes are the next block's checksum, header and payload, not yet consumed. Zeroing them would corrupt the stream. Only the two own_compressed_buffer.resize(...) fallback paths have padding that is genuinely uninitialized heap.

So zero-init would fix the fallback paths and leave the fast path — the one that runs almost always — sourcing literal data from the next compressed block. That is still a disclosure, just of adjacent stream data rather than of arbitrary heap, and the 05048 test's "prime the slack" case is precisely that shape.

Two further reasons to keep the bound:

  • Zero-init is fail-open: a malformed block would decode "successfully" to zeros instead of being rejected. Rejecting is fail-close, and cheaper here.
  • It would add a memset per block on the fallback paths, whereas the bound is free.

Letting the copies use the padding is already what happens and the PR keeps it: wildCopyFromInput still overshoots by less than copy_amount into the padding, which is sound because those bytes land after copy_end, where they are overwritten by the next iteration or fall outside size_decompressed. What the PR stops is the declared literal itself being sourced from the padding.

Zero-initializing the fallback paths' padding is still defensible as defence in depth, but as an addition rather than a replacement, and it would belong in a separate PR against CompressedReadBufferBase. Happy to write it if you want it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Scoping the zero-init follow-up, so it is not lost and so the boundaries are on the record.

Where the compressed-input padding actually comes from. Only CompressedReadBufferBase::readCompressedData produces it, in three shapes:

  1. Fast path (compressed_buffer = compressed_in->position() - header_size): the 64 bytes past the payload are the next block's checksum/header/payload, still inside compressed_in's buffer. Cannot be zeroed — that would corrupt the stream.
  2. Two own_compressed_buffer.resize(...) fallback paths: the buffer is sized to sizeof(Checksum) + size_compressed_without_checksum + additional_size_at_the_end_of_buffer, and readStrict fills exactly the first sizeof(Checksum) + size_compressed_without_checksum bytes. The 64-byte tail is uninitialized PODArray<char> memory. These are zeroable, and both land at the same offset, so one expression covers both:
memset(own_compressed_buffer.data() + sizeof(Checksum) + size_compressed_without_checksum,
       0, additional_size_at_the_end_of_buffer);

Everything else that calls getAdditionalSizeAtTheEndOfBuffer (CompressedReadBuffer, CachedCompressedReadBuffer, the fuzzers) pads the decompressed buffer, which is a write-overshoot allowance, not something the decoder reads as input.

Being straight about the value: with the bound in this PR, that memset is a no-op for LZ4. The literal can no longer reach the padding at all, on either path. So it buys nothing measurable here, and I would not add it to this PR.

Where it is not a no-op is the other codec that requests end-of-buffer slack. getAdditionalSizeAtTheEndOfBuffer is overridden non-zero in exactly two places:

  • CompressionCodecLZ4 — 64, now bounded by this PR.
  • CompressionCodecZXC — 64, and I have not checked whether its decoder bounds its reads against the payload end or against the slack end. CompressionCodecMultiple propagates the value, so it inherits whatever ZXC does.

So the useful follow-up is not really "zero the padding" — it is audit ZXC for the same payload-end-vs-slack-end confusion this PR fixed in LZ4, and zero the two fallback tails as a cheap regression guard while there. I will look at ZXC and open a separate PR against CompressedReadBufferBase (plus ZXC if it turns out to have the same bug); it does not belong in this one.

One thing worth keeping in mind for that audit: because of shape 1 above, a slack-end bound is not merely "reads uninitialized memory" — on the common path it reads the next compressed block, which is live, attacker-adjacent data. That makes it a disclosure bug rather than a hygiene bug, which is what made this PR a Critical Bug Fix.

@thevar1able thevar1able self-assigned this Aug 31, 2026
…riants with a forced-method gtest

`LZ4::decompress` sends every block smaller than 32 KiB to method 0 (`decompressImpl<8>`), so the
functional test `05055_lz4_literal_past_end_of_compressed_block` only ever exercised that variant,
while the new payload-end and output-end bounds are shared by methods 1 (`decompressImpl<16, true>`)
and 2 (`decompressImpl<32>`) as well.

The new `gtest_lz4_decompress_literal_bounds` forces each variant with `LZ4::PerformanceStatistics{method}`
and runs the same crafted blocks through all of them: the literal that declares 40 bytes but carries 8
(the block from the functional test), the one-byte-short boundary, a well-formed literal ending exactly
at the end of the payload for a range of lengths around each copy granularity, a literal that does not
fit into the declared decompressed size, a huge declared literal, a token whose length extension is
missing, and a literal whose match offset is missing. The slack after the payload is filled with a
sentinel so a literal sourced from it can never pass by accident, and every verdict is cross-checked
against the reference `LZ4_decompress_safe`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red on this head, Integration tests (arm_binary, distributed plan, 4/4), is unrelated to this change: test_storage_s3_queue/test_0.py::test_move_after_processing[another_bucket-AzureQueue] failed with assert 0 == (5 * 10) on SELECT sum(rows_processed) FROM system.azure_queue_log. The server log of that run contains no decompression errors at all, and the whole stateless suite is green.

Root cause is a test race, not this PR: ObjectStorageQueueSource::appendLogElement runs from finalizeCommit, after the rows are already committed to the materialized view target, so the test's single SYSTEM FLUSH LOGS can flush an empty queue. Same class of race as #117066, which fixed only the object-count half of it.

Fix submitted separately: #117954

@clickhouse-gh clickhouse-gh Bot added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Sep 4, 2026
alexey-milovidov added a commit that referenced this pull request Sep 4, 2026
…16992

The branch was accidentally started on top of `fix-lz4-uninitialized-slack-read`,
so the `LZ4_decompress_faster.cpp` hardening and its test showed up in this PR.
They belong to #116992 only.

Addresses https://github.com/ClickHouse/ClickHouse/pull/117481/changes#r3903006901

Co-Authored-By: Claude Fable 5.1 <[email protected]>
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 4, 2026
`test_delete_after_processing`, `test_tag_after_processing` and `test_move_after_processing`
wait for the destination materialized view table to reach its final row count, then issue a
single `SYSTEM FLUSH LOGS` and assert on `system.s3queue_log` / `system.azure_queue_log`
and the corresponding metadata cache.

That is racy: `ObjectStorageQueueSource::appendLogElement` is called from `finalizeCommit`,
after the rows have already been committed to the materialized view target, so the log entry
may not have been queued yet when the flush happens, and the flush then flushes nothing.
The assertion then sees `0` instead of `files_num * row_num`.

Replace the one-shot flush and assert with `wait_for_queue_log_rows`, which flushes and polls
until the expected counts are reported, in the same shape as `wait_for_object_counts` added in
ClickHouse#117066 for the object-count race in the same tests.

Observed on ClickHouse#116992 in
`Integration tests (arm_binary, distributed plan, 4/4)`:
`test_move_after_processing[another_bucket-AzureQueue]` failed with
`assert 0 == (5 * 10)` on `SELECT sum(rows_processed) FROM system.azure_queue_log`.
…he forced-variant gtest

The suite pinned the literal-side `output_end` and payload-end checks for methods 0, 1 and 2, but no
committed case reached the match-side `length > output_end - op` check: `RejectsMissingMatchOffset` exits
before the match length is decoded, and `gtest_lz4_decompress_branchless` only covers well-formed matches.

Add crafted blocks of 4 literals, a match with offset 1, and a final literal-only sequence, and run them
through the same `LZ4::PerformanceStatistics{method}` parametrization:
- `AcceptsMatchFittingIntoOutput`: the positive control, a match that fills the output up to the trailing
  literals, for every match length class the variants treat differently, cross-checked against
  `LZ4_decompress_safe`.
- `RejectsMatchPastEndOfOutput`: the same blocks decoded into a destination that is 1 to 7 bytes too small
  for the match (but not for the leading literals, so it is the match that is rejected).
- `RejectsHugeDeclaredMatch`: a ~4 KiB match-length extension into a 40-byte destination.
- `RejectsMissingMatchLengthExtension`: the payload ends right after the offset of a token that promises a
  match-length extension.

The harness now also places a canary after the output slack and asserts that the decoder never writes past
`ADDITIONAL_BYTES_AT_END_OF_BUFFER`, whatever its verdict. Without the match-side check, a match that
overruns the output by a few bytes lands inside the slack, the literal-side check then compares against a
negative distance and passes, and the trailing literals are written wholesale past the slack; the return
value alone does not show this because the decoder still runs out of input afterwards. Verified by compiling
the decoder with the match-side check removed: `RejectsMatchPastEndOfOutput` then fails on all three
variants through the canary, while the unmodified decoder passes all 33 cases.

The trailing literals are 200 bytes so that this spill is observable, and they also satisfy the reference
decoder's rules that a block ends with at least 5 literals and that the last match starts at least 12
bytes before the end of the block, so the positive control agrees with `LZ4_decompress_safe` for every
match length from the minimum of 4.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into master with commit 9872c9f Sep 5, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-lz4-uninitialized-slack-read branch September 5, 2026 11:45
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 5, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 5, 2026
Cherry pick #116992 to 26.3: Do not read the compressed-buffer slack as LZ4 literal data
robot-clickhouse added a commit that referenced this pull request Sep 5, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #116992 to 26.6: Do not read the compressed-buffer slack as LZ4 literal data
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Backport #116992 to 26.3: Do not read the compressed-buffer slack as LZ4 literal data
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #116992 to 26.8: Do not read the compressed-buffer slack as LZ4 literal data
clickhouse-gh Bot added a commit that referenced this pull request Sep 6, 2026
Backport #116992 to 26.7: Do not read the compressed-buffer slack as LZ4 literal data
alexey-milovidov added a commit that referenced this pull request Sep 10, 2026
The previous commit on this branch removed the `LZ4_decompress_faster`
changes that had leaked in from PR #116992, but by then that PR had
already been merged into `master`. Relative to the merge base the
removal therefore reads as a revert of the hardened literal and match
bounds checks in `decompressImpl`, and the merge propagated it.

Restore `src/Compression/LZ4_decompress_faster.cpp` to `master`, so this
pull request is again scoped to `OpenTelemetrySpanLog.cpp` only.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
OTHER: malformed LZ4 block -> wrong (uninitialized memory).
Effect in the production build a394e92: its upstream test(s) 05055_lz4_literal_past_end_of_compressed_block fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 05055_lz4_literal_past_end_of_compressed_block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants