Skip to content

Bound PostgreSQL protocol messages by their declared size - #116998

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-postgres-protocol-message-size-limit
Sep 14, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-postgres-protocol-message-size-limit

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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

Only the startup message and the cancel request were parsed through a buffer limited to the declared payload size. Every other message was parsed straight from the socket, so a field could be sized from the wire and allocated before any payload arrived, and a string without its terminator could grow past the end of the message. Authentication messages are parsed before the client is authenticated.

Since this pull request was opened, master has made the declared length an exact frame boundary for the extended-protocol messages, through FrontMessage::deserializePayload: the payload is parsed from a buffer that ends at the boundary, a frame that ends before it is an error rather than a message parsed from whatever arrived, and whatever the parser leaves unread is rejected instead of being taken for the beginning of the next message. This pull request now builds on that instead of enforcing the same contract centrally, and covers what is left:

  • Fields that carry an explicit length grow as the bytes arrive instead of being resized to the declared size up front. This is the allocation the issue is about: Bind parameters and the SASLInitialResponse mechanism were still sized from the wire, and CopyData reserved its declared payload size and then read it one byte at a time.
  • The authentication messages - PasswordMessage, SASLInitialResponse, SASLResponse - and Terminate, CopyData go through deserializePayload as well, so the declared length is a real frame boundary for the messages that are parsed before the client is authenticated, not only for the extended-protocol ones.
  • SASLInitialResponse and SASLResponse no longer read the message type byte inside deserialize; ScrambleSHA256Auth reads and checks it through receiveMessageType, as every other frontend message does.

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

Messages of the PostgreSQL wire protocol are now parsed within their declared size, so a malformed message can no longer make the server allocate memory for a payload that never arrives.


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

Version info

  • Merged into: 26.9.1.1476 (included in 26.9 and later)
  • Backported to: 26.8.9.4, 26.7.13.7, 26.3.33.112

Only the startup message and the cancel request were parsed through a buffer
limited to the declared payload size. Every other message was parsed straight
from the socket, so a field could be sized from the wire and allocated before
any payload arrived, and a string without its terminator could grow past the end
of the message. Authentication messages are parsed before the client is
authenticated, so this was reachable without credentials.

`MessageTransport::receive` now reads the message length itself and parses the
message from a buffer limited to it, and the fields that carry an explicit
length grow as the bytes arrive instead of being resized to the declared size up
front. The two SASL messages of the SCRAM exchange no longer read their own type
byte: it is read and checked by the caller, like every other message type.
@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 [79e9773]

Summary: ✅


AI Review

Summary

This PR finishes moving the PostgreSQL frontend parsers onto exact per-message payload boundaries and stops pre-sizing explicit-length fields from wire values alone. The protocol-side changes look correct on the current head, but the new stateless regression test still relies on a single recv(4096) as if it consumed one backend message, which makes the coverage racy on normal TCP packetization.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh:78] The new test drains AuthenticationSASL / AuthenticationCleartextPassword with one raw recv(4096) in several places. TCP does not preserve message boundaries, so a partial read leaves backend bytes queued; outcome then starts with that leftover auth frame and reports UNEXPECTED REPLY even when the server correctly rejects the malformed client packet. Replace those one-shot receives with a helper that reads one complete backend frame (type + 4-byte length + payload).
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make the new stateless test consume a complete backend auth frame before it sends the malformed frontend message.

LLVM Coverage Report

Measured on commit 79e9773.

Metric Baseline Current Δ
Lines 89.00% 89.10% +0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.50% +0.10%

Changed lines: Changed C/C++ lines covered: 122/129 (94.57%) · 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
Comment thread src/Core/PostgreSQLProtocol.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79e9773c2 with master a5efd3a38 (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

5 object files changed (+27.45 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Server/PostgreSQLHandlerFactory.cpp.o 149.24 KiB 172.12 KiB +22.89 KiB (+15.34%)

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

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

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +2.8 s (+6%) in total before that adjustment.

Job report

…ol-message-size-limit

# Conflicts:
#	src/Core/PostgreSQLProtocol.h
`MessageTransport::receive` limited parsing to the declared message length, but the
length was only an upper bound: whatever `deserialize` left unread stayed in the
socket and was then read as the next message. For a message whose parser reads
nothing, such as `Sync`, the whole payload was smuggled past the protocol state
machine, and the same held for a `Query` or `PasswordMessage` terminated early.

`receive` now skips the rest of the frame on both success and failure, and rejects a
message that carries more bytes than its parser consumed. Every `deserialize` of a
frontend message consumes its whole frame for a well-formed message, so the check
does not reject anything a client legitimately sends.

`gtest_postgresql_protocol` exercised the message length through `deserialize`, which
no longer reads it, so its cases are moved to `receive` and extended with the frame
boundary. The functional test gets the smuggled-tail case, and is renumbered to
`05054` because `05050` is taken on master.
@thevar1able thevar1able self-assigned this Aug 31, 2026
alexey-milovidov and others added 5 commits September 3, 2026 02:50
The previous commit on this branch was supposed to carry this change, but only the test
rename ended up in it, so `MessageTransport::receive` still treated the declared length as
a mere upper bound: whatever `deserialize` left unread stayed in the socket and was then
read as the next message. For a message whose parser reads nothing, such as `Sync`, the
whole payload was smuggled past the protocol state machine, and the same held for a `Query`
or `PasswordMessage` terminated early.

`receive` now skips the rest of the frame on both success and failure, so a malformed
message realigns the stream instead of desynchronizing the connection, and rejects a
message that carries more bytes than its parser consumed. Every `deserialize` of a frontend
message consumes its whole frame for a well-formed message, so the check does not reject
anything a client legitimately sends.

`gtest_postgresql_protocol` exercised the message length through `deserialize`, which no
longer reads it, so its cases are moved to `receive` and extended with the frame boundary.
The functional test gets a `Query` smuggling a second `Query` in its tail and an oversized
`Sync`.
The server rejects the message but keeps the connection open when nothing has been sent for
the statement yet, so draining until the connection closes only hit the read timeout.

Verified locally against a private server with `postgresql_port` enabled: all five cases of
`05054_postgresql_protocol_message_size.sh` match the reference, and the nine
`PostgreSQLProtocol` unit tests pass.
… failures

`MessageTransport::receive` treated the declared message length as an upper
bound in one direction only. The `LimitReadBuffer` it parsed the message from
was configured with `read_no_more` alone, and `LimitReadBuffer::nextImpl`
returns `false` on EOF whenever `read_no_less` is zero, so a frame that ended
before its declared length was accepted as if it had ended exactly on the
boundary: a `Query` declaring 1000 bytes but sending only `SELECT 1` before
closing its write side was executed, and the post-parse check for unparsed
bytes never fired because `ignoreAll` returned `0`.

The limiter is now exact - `read_no_less` and `read_no_more` are both the
declared payload size - so a frame that ends early fails on the read instead
of being parsed from whatever arrived.

The drain of the rest of the frame is no longer wrapped in `SCOPE_EXIT_SAFE`,
which logged and suppressed a timeout or socket error and let the message
through as if the frame had been consumed. On the success path the drain is a
plain call, so its failure propagates. Realigning the stream after a failed
`deserialize` still has to be best-effort - it cannot report its own failure
without discarding the parsing error, which is the more informative one - so
only there is a failure logged and the original exception rethrown.

Tests: `ReceiveRejectsFrameShorterThanDeclared` covers a truncated frame for
`Query`, `PasswordMessage` and `SASLResponse` (the parser that reads to the
end of the frame), and `05054_postgresql_protocol_message_size.sh` gets a
`Query` that declares more bytes than it sends and then closes its write side,
which must be answered with an error instead of being executed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 4, 2026
Master has since landed `FrontMessage::deserializePayload`, which parses each
extended-protocol message inside an exact-length `LimitReadBuffer`, realigns the
stream after a parse error and rejects trailing payload bytes. That is the same
frame-boundary contract this branch was enforcing centrally in
`MessageTransport::receive`, so the resolution keeps master's per-message
structure and re-applies only what is still missing from it:

- `readStringOfDeclaredSize` grows a field as its bytes arrive instead of
  resizing it to the size the client declared, so a tiny packet declaring a huge
  field no longer makes the server allocate that much up front. It is used for
  the `SASLInitialResponse` mechanism and for `Bind` parameters.
- `PasswordMessage`, `SASLInitialResponse`, `SASLResponse`, `Terminate`,
  `CopyInData` and `CopyDataQuery` now go through `deserializePayload` too, so
  the declared length is a frame boundary for the authentication messages as
  well, not only for the extended-protocol ones.
- `SASLInitialResponse` and `SASLResponse` no longer read the message type byte
  themselves; `ScrambleSHA256Auth::expectPasswordMessage` reads and checks it,
  as every other frontend message does through `receiveMessageType`.

`CopyInData` also stops reserving the declared payload size and reading it one
byte at a time.
alexey-milovidov and others added 2 commits September 14, 2026 00:36
When the client closes the connection before sending all bytes of the declared
frame, `LimitReadBuffer::nextImpl` throws `CANNOT_READ_ALL_DATA` and
`ReadBuffer::next` cancels the buffer. The `catch` block then called `ignore` on
that canceled buffer to keep the stream aligned, which is a logical error
(`ReadBuffer is canceled. Can't read from it.`) and aborted the debug and
sanitizer unit test jobs in `PostgreSQLProtocol.MessagesRejectFrameShorterThanDeclared`.
A canceled buffer has nothing left to align, so skip the drain and rethrow.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116998&sha=8620afedfa94e0e6b25084e76e8b2a6ff7baba1f&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%29
PR: #116998

Co-Authored-By: Claude Fable 5.1 <[email protected]>
# A SASL initial response that declares a two-gigabyte mechanism in a thirty-byte message.
sock = connect()
startup(sock, user_scram)
sock.recv(4096)

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.

recv(4096) is not a protocol read here. The first backend auth reply is a length-prefixed frame, and TCP can split it across reads. If this call consumes only part of AuthenticationSASL / AuthenticationCleartextPassword, the later outcome call starts with leftover auth bytes instead of the server's error response and the test reports UNEXPECTED REPLY, so the coverage flakes on packetization rather than the parser behavior under test.

Please replace these one-shot drains (the same pattern appears in the later auth cases too) with a helper that reads one complete backend frame: 1 byte type, 4-byte length, then exactly length - 4 payload bytes.

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 14, 2026
Merged via the queue into master with commit 0642d3d Sep 14, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-postgres-protocol-message-size-limit branch September 14, 2026 16:25
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
@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 Sep 14, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 18, 2026
Cherry pick #116998 to 26.3: Bound PostgreSQL protocol messages by their declared size
robot-clickhouse added a commit that referenced this pull request Sep 18, 2026
PedroTadim added a commit that referenced this pull request Sep 18, 2026
Backport #116998 to 26.3: Bound PostgreSQL protocol messages by their declared size
alexey-milovidov added a commit that referenced this pull request Sep 19, 2026
…ypick/26.7/116998

Resolve the cherry-pick of #116998 onto 26.7.

Conflicts:
	src/Core/PostgreSQLProtocol.h
	src/Core/tests/gtest_postgresql_protocol.cpp

26.7 does not have the `deserializePayload` helper that master gained in
`Keep PostgreSQL messages aligned after parse errors`, and the fix being
backported is only meaningful when the frontend messages are actually read
through it. The resolution therefore brings in the helper together with the
message conversions it enables (`Terminate`, `SASLInitialResponse`,
`SASLResponse`, `PasswordMessage`, `Query`, `Sync`, both `CopyData` variants)
and the `readStringOfDeclaredSize` reader, i.e. exactly the resolution that was
already merged for 26.3 in #120824.

26.7-only differences are kept: the memory-tracking containers
(`UnorderedMapWithMemoryTracking`, `VectorWithMemoryTracking`) and the
explicitly initialized members outside the rewritten blocks. Master-only
changes unrelated to this fix - the `scram_sha256_password` salt selection in
`ScrambleSHA256Auth` - are not pulled in; only `expectPasswordMessage` and its
two call sites, which belong to this fix, are.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Sep 19, 2026
Cherry pick #116998 to 26.7: Bound PostgreSQL protocol messages by their declared size
robot-clickhouse added a commit that referenced this pull request Sep 19, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Sep 19, 2026
Cherry pick #116998 to 26.8: Bound PostgreSQL protocol messages by their declared size
robot-clickhouse added a commit that referenced this pull request Sep 19, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 19, 2026
Backport #116998 to 26.8: Bound PostgreSQL protocol messages by their declared size
clickhouse-gh Bot added a commit that referenced this pull request Sep 19, 2026
Backport #116998 to 26.7: Bound PostgreSQL protocol messages by their declared size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... 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.

5 participants