Repository navigation
Do not allocate from sizes a peer declares in the Native protocol - #117011
Conversation
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.
|
Workflow [PR], commit [fb3a21b] Summary: ✅
AI ReviewSummaryThis PR hardens a few client-side Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit fb3a21b.
Changed lines: Changed C/C++ lines covered: 36/40 (90.00%) · Uncovered code |
| * 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 |
There was a problem hiding this comment.
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.
| /// 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; |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units3967 translation units recompiled, 18580 s compile time in total, 3966 of them have a recent master baseline. |
Backport #117011 to 26.8: Do not allocate from sizes a peer declares in the Native protocol
Cherry pick #117011 to 26.3: Do not allocate from sizes a peer declares in the Native protocol
…in the Native protocol
Cherry pick #117011 to 26.6: Do not allocate from sizes a peer declares in the Native protocol
…in the Native protocol
Cherry pick #117011 to 26.7: Do not allocate from sizes a peer declares in the Native protocol
…in the Native protocol
Backport #117011 to 26.6: Do not allocate from sizes a peer declares in the Native protocol
Backport #117011 to 26.3: Do not allocate from sizes a peer declares in the Native protocol
… declares in the Native protocol
Backport #117011 to 26.7: Do not allocate from sizes a peer declares in the Native protocol
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]>
…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]>
…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]>
…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]>
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]>
…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]>
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.
Changelog category (leave one):
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
Nativeblock is now a billion.Workflow [PR]
Sync PR [sync-upstream/pr/117011]
Version info
26.8.1.2041,26.7.7.47,26.6.4.50,26.3.27.3