Skip to content

Do not deserialize a Data packet that arrives before any query - #118588

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:interserver-preauth-data-packet-unread
Sep 12, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:interserver-preauth-data-packet-unread

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #99854

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):

Fixed the server deserializing the payload of a Data packet that arrives on a connection before any query. In interserver mode the connection is not authenticated until the Query packet is processed, so such a packet was rejected only after its Native block had been read, which let an unauthenticated peer choose the column type the server constructed. The packet is now rejected before its payload is touched.

Description

TCPHandler::receivePacketsExpectQuery() handles packets arriving before any Query. Its Data/Scalar case called processUnexpectedData() and only then threw UNEXPECTED_PACKET_FROM_CLIENT. That call reads a block through a headerless NativeReader, so the column type name goes off the wire into DataTypeFactory::get().

Entering interserver mode requires only the name of a cluster with a non-empty <secret>, never the secret itself; the connection is authenticated only inside processQuery(). So an unauthenticated peer chose which deserializer ran.

The read had no consumer for any peer: its result was discarded, and the exception that follows is caught where if (!query_state) return; exits runImpl, so nothing is sent and no further byte is read. runImpl's exception handler already states that policy ("unneeded exposure to unauthenticated connections"); the parse it forbids had already happened. The adjacent case of this switch, processObsoleteIgnoredPartUUIDs(), was given this shape in #99398.

Removing the call is the fix, and no setting is added: unlike the TablesStatusRequest path in #99854, which was served and needed an opt-out (#113602), Data before Query has always thrown, so there is no working flow to preserve and nothing a legitimate client observes changes. The protocol spec's READY row now records this rejection.

Requested by @ nikitamikhaylov (relayed privately, so there is no public issue to link).

Validation: a new integration test completes an accepted interserver handshake, then sends a Data packet declaring a nonexistent type. Without this change the server logs Unknown data type family: ..., proving a wire-supplied type name reached DataTypeFactory pre-authentication; with it the packet is rejected unread. 30/30 repeats green.

Two adjacent surfaces stay untouched. processUnexpectedHello() also drains its packet, but every field is capped by MAX_HELLO_STRING_SIZE and none reaches a factory. processQuery() deserializes client_info and Settings before the hash check, which the protocol requires: the hash covers the query text.


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

Version info

  • Merged into: 26.9.1.1316 (included in 26.9 and later)
  • Backported to: 26.8.3.103, 26.7.7.91, 26.6.5.120, 26.3.33.69

groeneai and others added 5 commits September 7, 2026 12:38
TCPHandler::receivePacketsExpectQuery() handles the packets that arrive
before any Query has been received. Its Data/Scalar case called
processUnexpectedData() and only then threw UNEXPECTED_PACKET_FROM_CLIENT.
That call builds a headerless NativeReader and reads a block, so the
column type name comes off the wire and is handed to DataTypeFactory.

Entering interserver mode requires only the name of a cluster that has a
non-empty <secret>, never the secret itself, and the secret is verified
only inside processQuery(), which this loop never reaches. So an
unauthenticated peer decided which type the server constructed and which
deserializer ran.

The read had no consumer for any peer either: its return value was
discarded, and the exception thrown right after is caught where
"if (!query_state) return;" exits runImpl, so the exception is never
sent, the connection is closed, and no further byte is read from the
socket. runImpl's exception handler already documents that policy ("the
server should not try to skip (parse, decompress) the remaining packets
sent by the client, as it will lead to additional work and unneeded
exposure to unauthenticated connections"); the parse it forbids had
already happened one frame earlier. The adjacent case of the same
switch, processObsoleteIgnoredPartUUIDs(), was given exactly this shape
in ClickHouse#99398.

No setting gates the rejection, deliberately. The TablesStatusRequest
path needed an operator opt-out when it was hardened in ClickHouse#99854 because
it was a served path, and rejecting it broke rolling upgrades (ClickHouse#113602).
Data before Query has always thrown, so there is no working flow to
preserve, and nothing a client can observe changes: the connection
closes with nothing written back, before and after.

The regression test completes an accepted interserver handshake over a
raw socket and then sends a Data packet declaring a column type that
does not exist. Without this change the server logs "Unknown data type
family: NoSuchTypeGroeneAI", which is the proof that a wire-supplied
type name reached DataTypeFactory before authentication. It is extended
into the existing pre-authentication interserver test module rather than
added as a new one, because that module already provides the cluster
with a <secret> and a handshake pinned below the chunked-packets
revision, which is what makes a hand-built packet feasible.

Requested by @ nikitamikhaylov, relayed via OranjeAI.

Co-Authored-By: Claude Opus 5 <[email protected]>
The regression test sent the complete Data packet and then asserted only
that no data type had been constructed. That is a subset of what the
change claims: a handler that read the external table name and only then
threw would touch peer-supplied payload bytes and still pass the test.

The test function now opens a second connection that sends the Data
packet type alone, one byte, and shuts down its write side. On a server
without the fix the external-table-name length varint inside
processUnexpectedData() hits end of stream, so UNEXPECTED_PACKET_FROM_CLIENT
is never constructed and the rejection is never logged; measured, that
arm fails with "Attempt to read after eof" raised from readStringBinary
one frame below processUnexpectedData(). With the fix the rejection is
immediate, because no payload byte is required.

The handshake and the bounded log barrier are factored into helpers so
the second connection reuses them; both are used by the new test only,
and the two pre-existing tests keep their own inlined handshake
unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
The native protocol spec describes READY as the state where the client
may send Ping, Query or close, and, unlike the handshake, ping and query
phases, it gives no outcome for anything else. A client author reading it
cannot learn what happens if they send a Data packet there, which is
precisely the packet this change stops the server from decoding.

State the three facts: it is a protocol violation and the connection is
terminated, no Exception packet is sent first so the client observes a
silent close, and the body is not decoded. The silent close is general
rather than interserver-specific: query_state is always null in the loop
that reads pre-query packets, so runImpl's handler returns before any
send for every peer.

Scalar is named alongside Data because both share the same case label.
The sentence is deliberately not written as "anything other than Ping or
Query", which would be wrong: TablesStatusRequest is served from READY
and Cancel is accepted and ignored.

Co-Authored-By: Claude Opus 5 <[email protected]>
The module comment stated that a packet arriving before the Query must
neither disclose anything nor have its payload deserialized. Two
pre-query paths contradict that by design, not by omission:
processTablesStatusRequest reads the request body before validating the
hash, because the hash is computed over that body, and Ping is answered
with Pong. A reader who takes the sentence as the module's invariant
concludes the hardened TablesStatusRequest path is buggy.

Scope the claim to the packets the server rejects. The legitimately
served pre-query packets are not enumerated here; the protocol spec
carries that.

Co-Authored-By: Claude Opus 5 <[email protected]>
The module comment claimed that a packet the server rejects before the
Query must disclose nothing and must not have its payload deserialized.
The second half is false for two pre-query paths, one of which this very
comment enumerates: processTablesStatusRequest() deserializes the request
body at TCPHandler.cpp:1711 before comparing digests at :1738, because
the digest binds request.getAuthDigest(), so a wrong-secret request is
rejected only after its payload has been read. processUnexpectedHello()
likewise drains seven bounded fields and then throws. A reader who checks
the module's second bullet, a TablesStatusRequest signed with the wrong
cluster secret, against the sentence above it finds them contradictory.

Only a rejected Data or Scalar packet leaves its payload untouched, so
the payload clause now names Data. The disclosure clause holds for every
rejected packet and is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed the resulting code and I adjudicated its findings against the
implementation evidence. Three were accepted and fixed:

  • ⚠️ The regression test proved that no data type was constructed, which is weaker than the
    contract stated here (the body is not read at all). The test now also sends the packet type
    alone and withholds the body, so it fails if any payload byte is required.
  • ⚠️ NativeProtocol.mdx did not say what happens to a Data/Scalar packet in the READY
    state. The spec now records that it terminates the connection, without an Exception packet
    and without its body being decoded.
  • 💡 A test comment stated the no-payload-read rule for every pre-Query packet, then for every
    rejected pre-Query packet. Both are false by design: a wrong-secret TablesStatusRequest
    is rejected but its body is deserialized first, because the hash is computed over it, and an
    unexpected Hello drains a bounded body. The claim now names the Data packet.

One question for a maintainer: the sibling defect in this same file, #99854, shipped as
Critical Bug Fix (crash, data loss, RBAC). I have not self-assigned that category, so this is
Bug Fix. Should it match #99854? Critical Bug Fix also auto-applies pr-must-backport, so
the call is yours rather than mine.

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a5e177d]

Summary: ✅


AI Review

Summary

This PR hardens TCPHandler::receivePacketsExpectQuery so a pre-query Data/Scalar packet is rejected on the packet type alone instead of deserializing a headerless Native block, adds an integration test that proves both "no payload deserialized" and "no payload byte required", and updates NativeProtocol.mdx to document the READY-state behavior. I reviewed the current diff together with the full prior discussion and do not see any remaining correctness, authentication, or spec-sync issues in the current head.

Final Verdict

✅ Approved. No remaining findings.

LLVM Coverage Report

Measured on commit a5e177d.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 7/7 (100.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 Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @nikitamikhaylov, could you review this? In interserver mode the cluster secret is only verified while the Query packet is processed, but the Data/Scalar case of the pre-query packet loop called processUnexpectedData() before throwing, so an unauthenticated peer chose which type name reached DataTypeFactory; that read had no consumer for any peer (its result was discarded and query_state is still null, so the exception is never sent), which is why I deleted the call instead of gating it. Nikita, this is the public patch you asked for via OranjeAI.

@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2ddbe6e

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra: the job exits 1 before any comparison, on Code: 497 ACCESS_DENIED for default.binary_sizes in the CI logs cluster (has_pr_data, build_profile_diff_job.py:721); reproduced on unrelated PRs by other authors a fix task is created (investigating at full effort, fixing PR link to follow here)
CH Inc sync reported tests failed (1 new, 1 known) in the private mirror CH Inc sync (private, not actionable by me)

Coverage, so the ledger is not certifying an untested head: 150 of 174 checks passed, 21 skipped,
0 dropped. Config Workflow, Fast test, Style check (0/15), Finish Workflow and
Mergeable Check are all green. The PR check is the workflow rollup and is red only because of
the rows above. The Bugfix validation (integration tests, *) jobs are green on both arches;
their inverted per-test rows are a property of that check's status inversion, not failures.

Session id: cron:our-pr-ci-monitor:20260907-213102

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Build profile diff row in the CI finish ledger above: #118685 fixes the repo-side defect that failure exposed, namely that a failing first cluster read left an earlier commit's comparison pinned to the pull request, presenting an older revision as the current one.

The logs-cluster user switch that addresses the ACCESS_DENIED trigger itself is linked from that PR's description. CIDB still shows Build profile diff as error on all 7 runs started after that switch merged, with no success rows in the window, so this row's check may stay red until the cluster side is provisioned.

The READY row of the protocol spec said the client "observes a silent
close". The server rejects the packet without reading its body, so
unconsumed bytes can still be queued when the socket closes and the client
can see a TCP reset instead. The sibling reject-before-read path behaves
the same way on master, which is why its test accepts ConnectionResetError.

Stating the reset outcome keeps a client author from treating it as a
protocol bug.
Both comments said the cluster secret is only verified while the Query
packet is processed. That is not true: a new-protocol TablesStatusRequest
validates a secret-derived hash of its own before any Query, which the
module's wrong-secret test exercises. What stays unauthenticated until the
Query packet is the connection, which is what is_interserver_authenticated
tracks and what makes an early Data packet peer-controlled input.
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a5e177d7e with master b75d29e7d (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.

Object file sizes

10 object files changed (+28.94 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/Utils.cpp.o 278.30 KiB 306.51 KiB +28.21 KiB (+10.14%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6de6981

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky: the job's own reproducibility check re-ran it and it passed 3 of 3 reruns; 49 pull requests and 9 true-master runs carry the same failure in 30 days #118417 (external, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, co-fails in the same run (expected server error 439, got 1000); also 0 of 3 reruns reproduced, with 57 pull requests and 14 true-master runs in 30 days #118390 (mine, open)
Stress test (arm_msan) / Hung check failed, possible deadlock found a cancelled INSERT keeps writing: is_cancelled = 1 with elapsed = 1316 s, and the hung leaf is MergeTreeDataPartWriterWide::writeColumn (SerializationObject::enumerateStreams under MSan shadow poisoning), i.e. the write path never observes the cancellation #108357 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR aggregators reflecting the two failing jobs above #118417, #118390, #108357 (the owners of the rows above)

Nothing here is attributable to this pull request: its diff touches TCPHandler::processUnexpectedData
(the pre-query packet path), while the failing leaves are distributed-plan error reporting and the
MergeTree write path, and all three signatures are live on master independently of this branch.

Session id: cron:our-pr-ci-monitor:20260908-123042

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai merge master.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (af30b32ef31e1153ea3887257d46544d543dec33); the branch head is now 751d10e3cea014f. Clean merge, and the diff against master is unchanged: src/Server/TCPHandler.cpp, one row in NativeProtocol.mdx, and the integration test. CI has restarted.

…ation failure

Not reading the payload is the point of the previous commit, but throwing
`UNEXPECTED_PACKET_FROM_CLIENT` for it also renames the case: an interserver
connection that has not reached its `Query` packet is unauthenticated, and
`runImpl` has a dedicated answer for `AUTHENTICATION_FAILED` in interserver
mode. Throw that instead, and keep `UNEXPECTED_PACKET_FROM_CLIENT` for an
ordinary client.

`CH Inc sync` found this: a test there asserts the guard's log line for exactly
this shape, and it stopped appearing once the packet was rejected earlier.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A Data packet arriving before any Query on an unauthenticated interserver
connection is now reported as AUTHENTICATION_FAILED, so "Unexpected packet
Data received from client" is no longer logged on the path this test drives:
both log barriers waited out their 60s timeout and the test failed even with
the guard working. Measured here, the old needle never appears at all
(assert 0 > 0 after 84s); the new one appears within the barrier, and the
test passes 50/50.

Matching the interserver wording rather than a signal shared by both
exception codes keeps the assertion tied to the unauthenticated case: a
connection that stopped reaching interserver mode would otherwise still
satisfy it. With src/Server/TCPHandler.cpp reverted to master the test still
reddens on the deserialization assertion (assert 1 == 0), so the oracle is
no weaker than before.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7fb4d61f-97cb-40b7-940d-8705d1ab41e9
  • MIRAI run: b763bbcd-5d25-4d05-b9f1-659fedf36fa0
  • PR check IDs:
    • clickbench_151454_1788996203
    • clickbench_151467_1788996204
    • clickbench_151473_1788996203
    • tpch_adapted_1_official_151484_1788996203
    • tpch_adapted_1_official_151510_1788996203
    • tpch_adapted_1_official_151524_1788996204

@alexey-milovidov alexey-milovidov added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 035fc82 Sep 12, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #118588 to 26.7: Do not deserialize a Data packet that arrives before any query
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #118588 to 26.8: Do not deserialize a Data packet that arrives before any query
robot-ch-test-poll3 added a commit that referenced this pull request Sep 13, 2026
Cherry pick #118588 to 26.3: Do not deserialize a Data packet that arrives before any query
robot-clickhouse added a commit that referenced this pull request Sep 13, 2026
alexey-milovidov added a commit that referenced this pull request Sep 13, 2026
Resolve the cherry-pick of #118588 onto 26.6.

The `TCPHandler.cpp` hunk and the `NativeProtocol` spec change merged cleanly
(git followed the docs page rename to `docs/en/interfaces/specs/NativeProtocol.md`).

`tests/integration/test_interserver_tables_status_auth` does not exist on 26.6:
its `TablesStatusRequest` cases depend on `interserver_tables_status_require_auth`,
which was introduced after the branch was cut. The module is therefore carried as a
26.6-local variant containing only the `Data`-before-`Query` regression test that
#118588 added, with a single-node cluster config providing the `mismatch` secret.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 13, 2026
Cherry pick #118588 to 26.6: Do not deserialize a Data packet that arrives before any query
robot-clickhouse added a commit that referenced this pull request Sep 13, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #118588 to 26.6: Do not deserialize a Data packet that arrives before any query
PedroTadim added a commit that referenced this pull request Sep 13, 2026
Backport #118588 to 26.3: Do not deserialize a Data packet that arrives before any query
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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-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