Skip to content

Do not allocate from sizes a peer declares in the Native protocol - #117011

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-client-native-protocol-allocations
Aug 30, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-client-native-protocol-allocations

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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

A client allocates from sizes that the server puts on the wire, before the corresponding payload arrives, and the client has no memory limit to stop it.

  • The strings of an exception, which is the first thing a client can receive during the handshake, were resized to their declared size before the text arrived. They are now read as the bytes arrive.
  • The decompressed size of a compressed block was not bounded, while the compressed size was. It is bounded the same way now.
  • The row count of a block was only checked against a limit of a thousand billion rows, and the bulk deserialization resizes the column to it before reading. The limit is now a billion rows, which is still far above anything ClickHouse produces, and the columns are no longer preallocated from a row count that no data has backed yet.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Sizes declared by a server in the Native protocol no longer make the client allocate memory for data that has not arrived: exception strings are read as they arrive, the decompressed size of a block is bounded, and the maximum number of rows in a Native block is now a billion.


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

Version info

  • Backported to: 26.8.1.2041, 26.7.7.47, 26.6.4.50, 26.3.27.3

A client allocates from sizes that the server puts on the wire, and the client
has no memory limit to stop it, so a small packet could make it allocate
gigabytes:

- The strings of an exception, which is the first thing a client can receive
  during the handshake, were resized to their declared size before the text
  arrived. Read them as the bytes arrive instead.
- The decompressed size of a compressed block was not bounded, while the
  compressed size was. Bound it the same way.
- The row count of a block was only checked against a limit of a thousand
  billion rows, and the bulk deserialization resizes the column to it before
  reading. Lower the limit to a billion rows, which is already far above
  anything ClickHouse produces, and stop preallocating the columns from a row
  count that has not been backed by any data yet.
@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 [fb3a21b]

Summary: ✅


AI Review

Summary

This PR hardens a few client-side Native/compressed-input allocation paths by reading exception strings incrementally, capping declared decompressed block sizes, and reducing the accepted Native row-count limit. The direction is right, but the accepted boundary values still drive the same large allocations from peer-controlled headers, and the new shared decompressed-size cap also rejects compressed data that current writers can still produce.

Findings

❌ Blockers

  • [src/Compression/CompressionInfo.h:14] DBMS_MAX_DECOMPRESSED_SIZE = 1 GiB still allows a peer-controlled block header to trigger a ~1 GiB allocation before payload validation, because CompressedReadBuffer::nextImpl / CompressedReadBufferFromFile::nextImpl immediately resize the destination buffer to size_decompressed.
  • [src/Core/Defines.h:171] DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS = 1'000'000'000ULL still lets a tiny Native header force multi-gigabyte allocations; NativeReader::readData forwards rows to bulk deserializers, and SerializationNumber<T>::deserializeBinaryBulk starts with x.resize(initial_size + limit), so a single UInt64 column at the new limit still allocates about 8 GiB before data arrives.
  • [src/Compression/CompressedReadBufferBase.cpp:167] Enforcing the 1 GiB decompressed-size cap in the generic compressed-reader path breaks backward compatibility for data current writers can emit (CompressedWriteBuffer accepts up to INT_MAX, StorageLog passes through max_compress_block_size, and clickhouse-compressor --block-size is unconstrained), so previously readable compressed files can start failing after upgrade.
Final Verdict
  • Status: ❌ Block
    Minimum required actions:
  • Make the compressed-block hardening actually prevent header-only large allocations at the accepted boundary.
  • Make the Native row-count hardening stop bulk deserializers from pre-sizing multi-gigabyte columns from peer-controlled rows.
  • Avoid introducing an unconditional incompatibility for existing compressed files, or gate/document it with an explicit compatibility story.

LLVM Coverage Report

Measured on commit fb3a21b.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 36/40 (90.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 29, 2026
* declares a huge decompressed size makes the reader allocate that much from a tiny payload.
* Blocks are written with `max_compress_block_size`, which is 1 MB by default.
*/
constexpr uint64_t DBMS_MAX_DECOMPRESSED_SIZE = 0x40000000ULL; /// 1GB

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.

This still leaves the original allocation bug in place at the new boundary. CompressedReadBuffer::nextImpl and CompressedReadBufferFromFile::nextImpl both call memory.resize(size_decompressed + ...) immediately after readCompressedData, so a block that declares exactly 0x40000000 bytes here still forces a ~1 GiB allocation before any real payload is validated. That only moves the cliff from 4 GiB to 1 GiB; it does not satisfy the PR contract that a peer-declared size should not become an allocation on its own.

I think this needs either a much smaller byte budget that matches supported writers, or a decompression path that does not pre-size the destination buffer from the header alone.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's ok.

Comment thread src/Core/Defines.h
/// Not `uz`: the value does not fit into `size_t` on 32-bit platforms, and it is compared against
/// a row count read from the wire as `UInt64`.
static constexpr auto DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS = 1'000'000'000'000ULL;
static constexpr auto DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS = 1'000'000'000ULL;

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.

Lowering the cap to 1'000'000'000 does not actually close the NativeReader side of the bug. NativeReader::readData still forwards rows into deserializeBinaryBulkWithMultipleStreams, and SerializationNumber<T>::deserializeBinaryBulk starts with x.resize(initial_size + limit) in src/DataTypes/Serializations/SerializationNumber.cpp. So a Native block that declares exactly 1e9 rows for a single UInt64 column still allocates about 8 GiB before any column bytes are read. The new test only exercises 1e12, but the header/payload asymmetry remains at the new boundary.

This probably needs a byte-budget-based cap, or the bulk deserializers need to grow from bytes actually read instead of trusting rows.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's ok.

throw Exception(ErrorCodes::TOO_LARGE_SIZE_COMPRESSED, "Too large size_compressed_without_checksum: {}. "
"Most likely corrupted data.", size_compressed_without_checksum);

if (size_decompressed > DBMS_MAX_DECOMPRESSED_SIZE)

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.

Putting this cap in the shared compressed-reader path is a backward-compatibility break: current writers still allow blocks larger than 1 GiB. CompressedWriteBuffer::nextImpl accepts any offset() <= INT_MAX, StorageLog passes max_compress_block_size through without clamping, and clickhouse-compressor --block-size is also an unconstrained size_t. That means previously readable compressed data can start failing after upgrade even though the format itself did not change.

If the goal is to harden untrusted Native or network reads, I think the tighter bound has to live on those untrusted entrypoints, or this needs a compatibility knob or migration story for generic compressed files.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's ok.

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fb3a21b5c with master 194df773e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c0938b0c2; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 710.13 MiB 707.08 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

3967 translation units recompiled, 18580 s compile time in total, 3966 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Aug 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into master with commit 41ee389 Aug 30, 2026
180 of 181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-client-native-protocol-allocations branch August 30, 2026 00:35
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 30, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 30, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 30, 2026
Backport #117011 to 26.8: Do not allocate from sizes a peer declares in the Native protocol
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 30, 2026
Cherry pick #117011 to 26.3: Do not allocate from sizes a peer declares in the Native protocol
robot-clickhouse added a commit that referenced this pull request Aug 30, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 30, 2026
Cherry pick #117011 to 26.6: Do not allocate from sizes a peer declares in the Native protocol
robot-clickhouse added a commit that referenced this pull request Aug 30, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 30, 2026
Cherry pick #117011 to 26.7: Do not allocate from sizes a peer declares in the Native protocol
robot-clickhouse added a commit that referenced this pull request Aug 30, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 30, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 30, 2026
Backport #117011 to 26.6: Do not allocate from sizes a peer declares in the Native protocol
alexey-milovidov added a commit that referenced this pull request Aug 30, 2026
Backport #117011 to 26.3: Do not allocate from sizes a peer declares in the Native protocol
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 8, 2026
Backport #117011 to 26.7: Do not allocate from sizes a peer declares in the Native protocol
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 8, 2026
Two backports left the per-file `ErrorCodes` declarations inconsistent, so
`check_cpp.sh` fails branch-wide:

- Backport #117011 added a `TOO_LARGE_STRING_SIZE` throw to
  `src/IO/ReadHelpers.cpp` without declaring the code in that file (it
  compiles only because `ReadHelpers.h` declares it, which the check does
  not follow). `master` declares it in the `.cpp` too.
- Backport #117003 kept the `SYNTAX_ERROR` declaration in
  `src/Server/MySQLHandler.cpp` but not the code that uses it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 15, 2026
…ckHouse#117011

Master bounds size_decompressed in the compressed frame header
unconditionally (ClickHouse#117011, already backported to 26.8, 26.6 and 26.3). This
branch carried the same bound behind a per-call-site flag. Master's check runs
first, so the resolution takes master's line verbatim and drops the flag from
the header parser's signature and from both of its call sites.

The check this branch adds, that a codec storing data verbatim has a body
length equal to its declared decompressed length, is kept, after the existing
header-size check.

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 15, 2026
…ter-side frame cap

ClickHouse#117011 bounds size_decompressed in the compressed frame header
unconditionally, and its check runs before the gated one this branch added, so
allowUnboundedDecompressedSize and its 20 call sites across 14 reader files
were unreachable. Both the accessor and the call sites are removed, and all 15
files return to what master has.

The writer-side frame cap is withdrawn as well, for two reasons that hold
independently of any frame-size policy.

A cap can only subtract the worst-case expansion a codec reports, and two
codecs compute that figure in wrapping 32-bit arithmetic. For a 480000000-byte
one-byte block CompressionCodecGorilla reports a reserve of 483129106 against a
true 1020000009 plus the 9-byte header; CompressionCodecDoubleDelta wraps the
same way. A cap derived from that number cannot be correct, and a
reserve < size test does not detect this case, because the wrapped value is
still larger than its own input.

A codec-independent cap at the limit instead breaches the sibling bounds. An
expanding codec pushes size_compressed past DBMS_MAX_COMPRESSED_SIZE, and an
expanding nested codec pushes the nested frame past the stricter nested bound:
CompressionCodecDelta reports uncompressed_size + 2, so a CODEC(Delta, LZ4)
chain over a buffer capped at 1 GiB declares a nested frame of 1 GiB + 11 and
CompressionCodecMultiple.cpp:161 rejects it, while the outer frame sits inside
both top-level limits. Such a cap would make a common codec chain unreadable.

Capping the writer therefore needs two earlier changes: the codec reserve
arithmetic repaired, and the four frame bounds harmonised. The two top-level
checks in CompressedReadBufferBase.cpp admit exactly 1 GiB; the two nested ones
in CompressionCodecMultiple.cpp reject it, against a hardcoded literal rather
than the named constant. Both are separate PRs.

This withdraws the substance of b32f102, which plumbed the cap through
master's adaptive-buffer helpers. That commit stays in the branch history.

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 15, 2026
…g inside `Multiple`

A compressed frame header carries two independently declared 32-bit sizes, and ClickHouse#117011 bounded
the magnitude of one of them without validating their relationship. For a method byte whose
codec stores the body verbatim, `NONE` and `Quantized`, the only two overriding `isNone`, the
body length and the declared decompressed length describe the same bytes and must be equal.
Nothing checked that at either layer.

The nested layer is the sharper half, and a complete bypass of the top-level check:
`CompressionCodecMultiple::doDecompressData` parses each nested header itself and never calls
`readHeaderAndGetCodecAndSize`. There it bounds the declared size at 1 GiB and then sizes
`uncompressed_buf` from it, so a tiny nested `NONE` body wrapped in `Multiple` made the reader
allocate up to just under a gigabyte before codec `NONE`'s own length check refused the frame.
A bound is not a validation, and a rejection that follows the allocation does not address it.

Both checks now run before any buffer is sized from a declaration. Such a frame is reachable at
default settings over any transport that accepts a compressed frame, because the checksum is an
unkeyed `CityHash128` over bytes the sender chose and can therefore be recomputed by the sender.
The allocation is virtual and decoding fails immediately after it, so the effect is
amplification rather than memory corruption.

`03003_codec_multiple_buffer_overflow` already carried such a frame: its second arm declares
33686018 bytes behind a 278-byte nested `NONE` body, and until now the only thing between that
frame and the allocation was a check that ran after it. The frame is still refused, so no arm is
removed or relaxed; the arm's expectation moves from codec `NONE`'s message to the earlier one.

`docs/reference/interfaces/specs/NativeFormat.mdx` now describes what the reader enforces at
both layers, and makes no writer-side claim.

Co-Authored-By: Claude Opus 5 <[email protected]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
PROTO: client reading Native blocks with large declared sizes -> DoS.
Effect in the production build a394e92: its upstream test(s) 05052_client_untrusted_server_allocations 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): 05052_client_untrusted_server_allocations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
m7kss1 pushed a commit to m7kss1/ClickHouse that referenced this pull request Nov 20, 2026
…rrive

When a compressed block is not fully available in the input buffer, both copy
branches of CompressedReadBufferBase::readCompressedData resized
own_compressed_buffer to sizeof(Checksum) + size_compressed + codec padding
before readStrict could find out that the bytes are not there. The header check
accepts size_compressed up to DBMS_MAX_COMPRESSED_SIZE (1 GiB), and PODArray's
power-of-two growth turns 1 GiB plus the checksum and LZ4 padding into a 2 GiB
request, made from a 25-byte header. The nightly mergetree_checksum_fuzzer hit
it as `out-of-memory (malloc(2147483648))` on a 63-byte input; the same path
serves every CompressedReadBuffer* user (HTTP decompress=1, the Native protocol
in both directions, MergeTree, Keeper snapshots).

Copy the block in the chunks the input already holds, growing the buffer as the
bytes arrive, then add the codec padding. Each branch copies exactly the bytes
its readStrict read before, so the final layout [checksum][header][data][padding]
and capacity are unchanged, and a truncated block fails with the same
CANNOT_READ_ALL_DATA "Bytes read / Bytes expected" message. The buffer keeps its
capacity across blocks, so a warm buffer costs one O(1) resize per chunk.

ClickHouse#117011 bounded the decompressed size in the same function; this completes it
for the compressed size. A harness-only memory limit (what
compressed_buffer_fuzzer has) would only hide it from the fuzzer.

The test sends a truncated LZ4 block declaring 1 GiB over HTTP decompress=1,
after a first frame larger than max_query_size so that the block is read inside
the INSERT pipeline, where max_memory_usage applies: master returns
MEMORY_LIMIT_EXCEEDED, the fix CANNOT_READ_ALL_DATA. A second case loads blocks
larger than the 1 MiB HTTP read buffer.

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

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants