Repository navigation
Do not read the compressed-buffer slack as LZ4 literal data - #116992
Conversation
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.
|
Workflow [PR], commit [afce088] Summary: ✅
AI ReviewSummaryThe PR hardens the Final Verdict
LLVM Coverage ReportMeasured on commit afce088.
Changed lines: Changed C/C++ lines covered: 137/137 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 5 s compile time in total, 7 of them have a recent master baseline. |
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.
|
🕵 Folded the output-side bound in as well (3aaf737), so all four bounds in 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
The guard change is a small win (it removes 1–2 instructions per variant, because the loop already computes Net effect on 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 @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. |
|
🕵 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:
The core fix is a win because On zero-initializing the padding and letting the copies use itI looked into this and it cannot replace the payload-end bound, because the padding is not a dedicated allocation in the common case. In 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 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:
Letting the copies use the padding is already what happens and the PR keeps it: 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 |
|
🕵 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
memset(own_compressed_buffer.data() + sizeof(Checksum) + size_compressed_without_checksum,
0, additional_size_at_the_end_of_buffer);Everything else that calls Being straight about the value: with the bound in this PR, that Where it is not a no-op is the other codec that requests end-of-buffer slack.
So the useful follow-up is not really "zero the padding" — it is audit 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. |
…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`.
|
🕵 The only red on this head, Root cause is a test race, not this PR: Fix submitted separately: #117954 |
…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]>
`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]>
Cherry pick #116992 to 26.3: Do not read the compressed-buffer slack as LZ4 literal data
Backport #116992 to 26.6: Do not read the compressed-buffer slack as LZ4 literal data
Backport #116992 to 26.3: Do not read the compressed-buffer slack as LZ4 literal data
Backport #116992 to 26.8: Do not read the compressed-buffer slack as LZ4 literal data
Backport #116992 to 26.7: Do not read the compressed-buffer slack as LZ4 literal data
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]>
… slack as LZ4 literal data
… slack as LZ4 literal data
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]>
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):
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
26.8.3.48,26.7.7.34,26.6.5.59,26.3.32.12