Repository navigation
Do not allocate from peer-declared sizes when reading settings from the Native protocol - #118612
Conversation
`readStringBinaryGrowing` was added in fb3a21b as a file-local helper for the three handshake exception strings. The settings wire needs the same primitive, so give it external linkage: drop `static`, declare it in ReadHelpers.h next to `skipStringBinary`, and move its explanatory comment onto the declaration. The default argument moves with the declaration, since a default may appear only once per translation unit. No behaviour change: its three existing callers in `readException` are untouched.
`BaseSettingsHelpers::readString` is the single funnel for every string on the settings section of the Native protocol: the setting name at the head of the loop, all three value branches, the discarded value of an unknown setting, and both strings of `readQueryParameters`. It used `readStringBinary` at the default 1 GiB bound, and that primitive resizes its destination to the declared size before reading any payload, so a length prefix alone was the allocation. About five bytes of varint on the wire committed up to 1 GiB of resident memory with nothing backing it, and each connection could do it again: I measured 1024 MiB of RSS growth for one connection and 3072 MiB for three concurrent connections, persisting for as long as the sockets stayed open. Nothing refuses that on a default-configured server. The allocation is counted, because ClickHouse intercepts the global operator new, but enforcement on that path requires `min_allocation_size_to_throw_on_memory_limit`, which defaults to 0, meaning never enforce. Counted but not enforced is the state src/Common/VectorWithMemoryTracking.h describes as the precondition for an OOM kill, not a mitigation. Both callers reach the loop before the peer is trusted. `TCPHandler::processQuery` reads the settings section 98 lines before it compares the interserver secret hash, so on that path the loop consumes unverified peer input, and the ordinary post-authentication path is open to any user including `readonly`. `Connection::receiveHello` decodes server-supplied settings in the client, which has no memory limit at all; every other read in that function is already bounded by DBMS_MAX_HELLO_STRING_SIZE, so this was the one unguarded read left there, and no server-side change reaches it. Use `readStringBinaryGrowing` at all twelve string carriers instead: the shared helper, the seven leaf readers that the legacy `SettingsWriteFormat::BINARY` branch reaches through `accessor.readBinary`, and the four string carriers of the generic binary `Field` decoder that a `Map` setting reaches through `SettingFieldMap::readBinary`. That decoder accepts any recursive tag before it validates shape, so fixing only its bare `String` case would leave the invariant false. I did not add a bound instead. A setting value is open-ended user data, for instance a long `log_comment`, a SQL fragment in `additional_result_filter`, or an arbitrary custom payload, so any cap risks rejecting a configuration that works today. The wire format, the setting names and the defaults are unchanged, as is the `TOO_LARGE_STRING_SIZE` refusal at the same 1 GiB bound. One error code does change: a truncated payload now raises `ATTEMPT_TO_READ_AFTER_EOF` from the growing loop, where `readStrict` raised `CANNOT_READ_ALL_DATA` (`src/IO/ReadBuffer.cpp:62-68`). No test or documented contract depends on either code. The cost is that a genuinely large, fully backed value now grows geometrically rather than being resized once; both that tradeoff and the error-code substitution are ones this project already accepted for the handshake strings in `fb3a21b5c2a7`. The regression test drives six of the twelve carriers, one per distinct decoder this commit changes, with a declared length of 64 MiB and no payload; the other six are the identical one-line swap in sibling `SettingField*::readBinary` leaf readers and in the line following `Field.cpp:472`. Each entry fails before the change and passes after, on the debug and the `asan_ubsan` build alike. Afterwards every entry raises `ATTEMPT_TO_READ_AFTER_EOF`. Before, the debug build refuses the 64 MiB allocation under a clamped global limit (`MEMORY_LIMIT_EXCEEDED`), while `asan_ubsan` has no `operator new` interception, so there the resize succeeds and the short read surfaces as `CANNOT_READ_ALL_DATA`. A second case reads a well-formed settings block under the same clamp, so the clamp itself is not what produces the first outcome, and the empty string end marker still terminates the loop.
Internal second-model reviewThree independent passes over this diff (my own cold read each round, plus a second model), adjudicated against the recorded validation evidence. ❌ Fixed before publishing: two inaccurate claims about my own change. A truncated payload now raises
|
|
cc @CheSema @vitlibar, could you review this? |
|
Workflow [PR], commit [ad1e8c1] Summary: ✅
AI ReviewSummaryThis PR switches settings and parameter string decoding away from sizing destinations from the peer-declared length before payload bytes arrive, which is the right direction for the memory-amplification bug it targets. I did not find a C++ correctness regression in the implementation itself, but the PR still leaves the native protocol spec stale for third-party implementations. Findings
Final VerdictRequest changes until the native protocol spec is updated to describe the new resource-safe decoding rule for settings and parameters. LLVM Coverage ReportMeasured on commit ad1e8c1.
Changed lines: Changed C/C++ lines covered: 115/128 (89.84%) · Uncovered code |
CI finish ledger - 6ac97a5Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260907-233055 |
|
Fixing-PR link-back for the The logs-cluster user switch that addresses the |
| { | ||
| String str; | ||
| readStringBinary(str, in); | ||
| readStringBinaryGrowing(str, in); |
There was a problem hiding this comment.
The protocol hardening is in the C++ decoder now, but the corresponding contract is still missing from docs/reference/interfaces/specs/NativeProtocol.mdx. The Setting / Parameter sections currently describe only the wire bytes, so a third-party native client implementing from the spec can still preallocate from the declared string length and keep the same amplification bug on truncated Query / ServerHello payloads. That spec already includes receiver-side resource-safety requirements for password_complexity_rules, so this settings/parameters decode rule should be documented in the same PR.
There was a problem hiding this comment.
Verified the premise before acting on it, and it holds: the spec does carry one receiver-side resource note, on password_complexity_rules under ServerHello ("cap the decoded count at 256 entries and each pattern and message String at 4096 bytes"). I am still not adding a Setting/Parameter decode rule here.
-
That text is already being written, in Bound the collections read from the Native protocol #117015, whose new "Receiver-side size limits" section documents this exact surface, including a row for the number of
SettingandParameterentries in aQuery. It also already edits two of the files this PR changes (src/Core/BaseSettings.cpp,src/IO/ReadHelpers.h), so a second version of that section here would only add a docs collision. -
Nothing the spec states today stops being true.
TOO_LARGE_STRING_SIZE,1 GiB,allocateandpreallocathave 0 hits inNativeProtocol.mdxon master, and this PR leaves the encoding and the accepted-input set byte for byte identical:readStringBinaryGrowingkeeps the sameDEFAULT_MAX_STRING_SIZE = 1_GiBdefault and the sameTOO_LARGE_STRING_SIZErejection asreadStringBinary(src/IO/ReadHelpers.h:39,:154,:176). Thepassword_complexity_rulesnote bounds what a client should reject, and this PR moves no limit. -
The in-tree rule that would compel the edit (
.claude/CLAUDE.md:15) triggers on theNativeformat and namesNativeFormat.mdx; this change is in the protocol's settings decoder. Its own "if unsure whether the spec needs updating, flag it" tie-breaker is what this reply is.
Worth flagging for whoever merges second: #117015's new section opens with "a receiver allocates for the declared size before the data behind it arrives", which stops being true of the settings strings once this lands.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units1902 translation units recompiled, 11200 s compile time in total, 1902 of them have a recent master baseline. |
|
Fixing-PR link-back for the It splits the two column censuses in |
CI finish ledger - ad1e8c1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260908-113133 |
b18ca9e
|
It broke clang-tidy. Resubmitted. |
|
Thanks for catching it, and sorry for the breakage. The duplicate was not in this PR's diff: #118610 and this PR each added #120931's tree carries exactly one copy of the include, so the duplicate cannot come back. I had a one-line deletion ready and dropped it once your revert landed; I am not opening a competing fix. |
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md. Changelog-revert: 120763 120477 Revert "Remove stale entries from `parallel_replicas_blacklist.txt`" Changelog-revert: 120801 120767 Revert "CI: give revert pull requests a green light at once" Changelog-revert: 120930 118612 Revert "Do not allocate from peer-declared sizes when reading settings from the Native protocol" Changelog-deleted-entry: 118612 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Reading settings from the Native protocol no longer sizes a string from the length a peer declares before the payload arrives, so a Query packet or a server hello can no longer turn a few bytes on the wire into a large memory allocation. This covers `BaseSettings::read`, `BaseSettings::readBinary` and `readQueryParameters`, on the server and in the client. [#118612](#118612) ([Groene AI](https://github.com/groeneai)). Changelog-deleted-entry: 120767 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * CI: give revert pull requests a green light at once. [#120767](#120767) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reading settings from the Native protocol no longer sizes a string from the length a peer declares before the payload arrives, so a Query packet or a server hello can no longer turn a few bytes on the wire into a large memory allocation. This covers
BaseSettings::read,BaseSettings::readBinaryandreadQueryParameters, on the server and in the client.Description
Requested by @ rschu1ze.
BaseSettingsHelpers::readStringis the single funnel for every string on the settings wire. It usedreadStringBinary, which resizes its destination to the declared size before any payload arrives, so five varint bytes committed up to 1 GiB. I measured +1024 MiB RSS for one connection, +3072 MiB for three. Nothing refuses it: the allocation is counted, but enforcement needsmin_allocation_size_to_throw_on_memory_limit, which defaults to never.Both callers reach the loop before the peer is trusted:
TCPHandler::processQueryreads settings 98 lines before comparing the interserver secret hash, and the post-authentication path is open to any user.Connection::receiveHellodecodes server-supplied settings in the client, which has no memory limit and where every other string read is already bounded byDBMS_MAX_HELLO_STRING_SIZE; no server-side fix reaches it.This applies #117011's remedy for the same class,
readStringBinaryGrowing, to the twelve carriers here. I did not add a bound: a setting value is open-ended user data, so a cap risks rejecting a working configuration. The wire format, setting names and defaults are unchanged. Two observable changes: a truncated payload now raisesATTEMPT_TO_READ_AFTER_EOFrather thanCANNOT_READ_ALL_DATA, and a large fully backed value grows geometrically instead of being resized once, as in #117011. #117015 bounds the pair count; this bounds each string.Two gtest cases cover six of the twelve, one per decoding shape; the other six repeat two of them. Each declares 64 MiB, sends no payload, fails before the change and passes after, on debug and
asan_ubsan. A unit test, not a stateless one: the property is that the allocation never happens, which needs an in-process clamp; a socket probe sees only the error code.Raised separately, not fixed here:
SettingFieldNumber<T>::readBinary's signed-integral branch (src/Core/SettingsFields.cpp:263) assigns from its own member instead of the value just read, so a signed setting's wire value is discarded.Workflow [PR]
Sync PR [sync-upstream/pr/118612]
Version info
26.10.1.117(included in26.10and later)