Repository navigation
Bound PostgreSQL protocol messages by their declared size - #116998
Conversation
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.
|
Workflow [PR], commit [79e9773] Summary: ✅
AI ReviewSummaryThis 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 Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 79e9773.
Changed lines: Changed C/C++ lines covered: 122/129 (94.57%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+27.45 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units11 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. |
…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.
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`.
…ol-message-size-limit
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]>
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.
…ol-message-size-limit
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) |
There was a problem hiding this comment.
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.
Cherry pick #116998 to 26.3: Bound PostgreSQL protocol messages by their declared size
Backport #116998 to 26.3: Bound PostgreSQL protocol messages by their declared size
…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]>
Cherry pick #116998 to 26.7: Bound PostgreSQL protocol messages by their declared size
Cherry pick #116998 to 26.8: Bound PostgreSQL protocol messages by their declared size
Backport #116998 to 26.8: Bound PostgreSQL protocol messages by their declared size
Backport #116998 to 26.7: Bound PostgreSQL protocol messages by their declared size
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,
masterhas made the declared length an exact frame boundary for the extended-protocol messages, throughFrontMessage::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:Bindparameters and theSASLInitialResponsemechanism were still sized from the wire, andCopyDatareserved its declared payload size and then read it one byte at a time.PasswordMessage,SASLInitialResponse,SASLResponse- andTerminate,CopyDatago throughdeserializePayloadas 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.SASLInitialResponseandSASLResponseno longer read the message type byte insidedeserialize;ScrambleSHA256Authreads and checks it throughreceiveMessageType, as every other frontend message does.Changelog category (leave one):
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
26.9.1.1476(included in26.9and later)26.8.9.4,26.7.13.7,26.3.33.112