Repository navigation
Cherry pick #108469 to 26.7: Fix SQL injection in PostgreSQL wire protocol parameter binding - #118054
Merged
robot-ch-test-poll2 merged 61 commits intoSep 4, 2026
Merged
Conversation
ClickHouse's PostgreSQL wire-protocol emulation built SQL by raw string substitution of client-supplied values, allowing SQL injection. PreparedStatemetsManager::getStatement substituted the prepared-statement placeholders $1, $2, ... with the raw parameter values. Two paths feed it: - The extended-query path (Parse/Bind/Execute), used by default by psycopg2, JDBC, node-postgres, Npgsql, etc. BindQuery::deserialize read the parameter bytes straight off the wire and they were spliced into the SQL text as-is. A parameter such as "x' UNION ALL SELECT ... --" broke out of its string literal. As a side effect, a correctly written client that sends "WHERE name = $1" (no client-side quoting) failed with UNKNOWN_IDENTIFIER, because the value was substituted unquoted. - The simple-query EXECUTE path formatted arguments with fieldToString, which drops the quotes around string literals, so it had the same problem. Now each argument is turned into a proper SQL literal before substitution: the EXECUTE path uses FieldVisitorToString (strings quoted and escaped, numbers left bare) and the Bind path quotes each value with quoteString and maps the protocol NULL sentinel to the SQL keyword NULL. BindQuery::parameters is changed to std::vector<std::optional<String>> so a NULL parameter is no longer ambiguous with the text "NULL". The COPY command built its SELECT/INSERT by splicing the client-supplied table and column names verbatim, so a table name like "t WHERE 1=0 UNION ALL SELECT ..." injected SQL on both COPY TO and COPY FROM. The identifiers are now quoted with backQuoteIfNeed. Note: a bound parameter is now always a string literal, so using one directly as a LIMIT/OFFSET expression (LIMIT $1) now reports INVALID_LIMIT_EXPRESSION instead of working. This is unavoidable when binding untyped text parameters as data rather than splicing them into the SQL. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…-protocol-sql-injection # Conflicts: # src/Core/PostgreSQLProtocol.h
The Bind path already had injection coverage; add focused cases for the two other sinks the fix touches: the simple-query PREPARE/EXECUTE path (ParserExecute argument substitution) and the COPY table/column identifier path (PostgreSQLHandler). Each asserts a malicious payload is treated as a literal/identifier and normal queries still work. Co-Authored-By: Claude Opus 4.8 <[email protected]>
WHERE name = '$1' is the realistic vulnerable pattern: the prepared body quotes the placeholder, so an unescaped argument with a doubled quote breaks out and leaks the secret table. Verified this shape leaks on the pre-fix binary and is blocked after the fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ries The previous getStatement substituted $N with std::string::find/replace, which matched a placeholder anywhere in the text, including inside comments, string literals and quoted identifiers, and matched $1 against the prefix of $10. A $N inside a block comment was still substituted with the (quoted) value, so a Bind value beginning with "*/ ... --" closed the comment and the rest became executable SQL ahead of the real placeholder. Quoting the value alone does not help, because in a comment the quotes are not syntactic. Now the body is tokenized with the lexer and only a $N that is its own BareWord token is replaced; comments, string literals, quoted identifiers and heredocs are emitted verbatim, and a whole token must match so $1 is not taken for the start of $10. Also fix the unit test that still expected the protocol NULL sentinel to decode to the literal text "NULL"; it maps to a disengaged optional now. Add regression coverage: a $1 inside a leading block comment (extended path) and a malicious COPY FROM column identifier (INSERT INTO sink). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The two new injection regression tests in test_postgresql_protocol were flaky in the flaky integration check (each passed most repeats but failed a few). Neither failure was a security-assertion failure; both were connection-state artifacts from how the tests drove the clients. test_prepared_statement_no_sql_injection failed intermittently at the teardown DROP with "Unknown statement". It stacked five prepare=True executes on one connection; the repeated named server-side prepared statements interact badly with the client's prepared-statement cache. A parameterized execute already uses the extended Parse/Bind/Execute path (the bound value travels the wire as data, which is the path under test), so prepare=True is dropped. Injection coverage, including the block-comment placeholder case, is unchanged. test_copy_no_sql_injection failed at the benign COPY after the two expected-to-fail COPY probes with "cursor already closed". A COPY the server rejects leaves the psycopg2 connection broken, so the next COPY on the same connection fails regardless of the security check. Each COPY probe now uses its own connection (wrapped in closing(), since psycopg2's with-statement does not close the connection). The COPY FROM no-leak count is also cast with int(), since ClickHouse returns it over the wire as text. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The previous EXECUTE injection case prepared `WHERE name = '$1'`, but getStatement skips a `$N` inside a string-literal token, so the `$1` was left as literal text and the payload was never substituted. The assertion would have passed even if ParserExecute went back to splicing raw string values. Use a bare `$N` placeholder in a numeric comparison (`WHERE id = $1`) with a string EXECUTE argument, so the argument is actually substituted: with the fix it is a quoted literal that fails Int32 coercion (no leak), without the fix the raw value splices a UNION and leaks the secret table. Also add a `SELECT $1` echo case that round-trips the same payload as a single string value. The coercion error drops the connection, so the injection probe uses its own. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…-protocol-sql-injection
The extended-query Bind message carries a per-parameter format code (0 = text, 1 = binary). deserialize() read these codes and discarded them, so a binary payload flowed to getStatmentFromBind() and was literalized by quoteString() as a raw byte string instead of being decoded by its declared type. Standards-compliant binary prepared statements were therefore silently misbound rather than rejected. This handler only supports the text format, so fail fast on any non-text format code (and on a negative format-code count) in deserialize(). Add a gtest covering both directions and an integration test driving a binary-format Bind via libpq.
The extended-query Parse message declares a type OID per parameter, but ParseQuery::deserialize read and discarded them, so every Bind value was force-quoted as a String literal. That fixed injection but reinterpreted a standards-compliant typed bind as a string: SELECT $1 + 1 became SELECT '1' + 1 and LIMIT $1 became LIMIT '1' (which ClickHouse rejects), a wire-protocol compatibility regression for typed prepared statements. Thread the declared OIDs from Parse through the prepared statement to Bind formatting. A parameter whose declared type is numeric (int2/int4/int8, oid, float4/float8, numeric) is emitted as a bare numeric literal after validating it contains only numeric characters; any other type (including an unspecified OID) stays a quoted+escaped string literal. Numeric validation keeps the emission injection-safe: a payload such as 1 UNION ALL SELECT ... is rejected rather than spliced into the body. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The numeric Bind branch validated the value with a per-character check (only chars in [0-9+-.eE]). That accepts values that are not a single numeric literal: 1-- opens a Lexer line comment that drops the rest of the query, and 1+2 / 1-2 splice an expression where a bound value is expected. Replace it with a strict grammar check that requires the whole string to parse as exactly one decimal literal ([sign] digits [. digits] [ (e|E) [sign] digits ]) before emitting it unquoted. Add gtest and integration regressions for 1--, 1+2, 1-2. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eclared type
The numeric branch previously accepted any single decimal literal for every
numeric OID and emitted it unquoted. That let a value be spliced with the wrong
type (an int4 accepting 3.14) and lost precision for numeric/1700 (a bare
literal is reparsed as Float64, since ClickHouse SQL has no Decimal literal).
Validate each value against its declared type's grammar and re-serialize it as a
type-preserving fragment: integer types require an integer literal, oid requires
an unsigned integer, float types keep a bare literal, and numeric is emitted as
CAST('<value>', 'Decimal256(scale)') so the exact value and Decimal type survive.
Values exceeding Decimal256 precision are rejected rather than rounded. All
branches remain injection-safe.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Emit a Bind value declared with a mapped type OID as
accurateCast('<escaped value>', '<ClickHouse type>') instead of a bare
literal. This delegates parsing, range/width checking and rejection to
ClickHouse's own parser (accurateCast rejects out-of-range input rather
than wrapping like CAST), so the declared type is preserved and invalid
input for it is rejected: int4 rejects 3.14 and 2147483648, int2 rejects
32768, oid rejects -1, and bool/date/timestamp/uuid keep their declared
type instead of being downgraded to a String literal. The value is always
quoted+escaped inside the cast, so injection payloads such as 1--, 1+2 or
1 UNION ALL SELECT ... stay in the value position and can never break out.
numeric (OID 1700) is still validated and normalized to an exact Decimal
(ClickHouse SQL has no Decimal literal), avoiding a Float64 reparse.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
… numeric-exponent DoS and timestamptz OID Complete the extended-query fixes on top of the injection/type-preservation work in this PR. 1. Keep the connection alive after an extended-query error. The Parse/Bind/ Describe/Execute/Close handlers sent an ErrorResponse and then re-threw, which propagated to run()'s outer catch and closed the socket. libpq's exec_params pipelines Parse+Bind+Describe+Execute+Sync, so the first error (a rejected binary format code or an out-of-range typed value) tore the connection down and the client saw "server closed the connection unexpectedly" instead of the error, breaking every subsequent request on that connection. The PostgreSQL protocol instead requires the server to send one ErrorResponse, ignore all messages until the next Sync, then send ReadyForQuery, keeping the connection usable. The run loop now enters a skip-until-Sync recovery state for the extended-query messages while the simple-query (Query) path keeps its previous behaviour. The binary-format rejection in BindQuery::deserialize is deferred until the whole message has been consumed so the read buffer sits at a clean message boundary for the drop-until-Sync resync. 2. Bound the exponent when normalizing a numeric (OID 1700) parameter. A value like 1e1000000 passes the lexical numeric check; the normalizer then parsed the exponent into a signed Int64 (overflow) and materialized zeros before the Decimal256 precision guard ran (O(exponent) CPU/memory). The exponent is now capped well beyond Decimal256 precision, so such values are rejected promptly and the accumulator cannot overflow. 3. Map timestamptz (OID 1184) to DateTime64(6, 'UTC') instead of the bare DateTime64(6) used for plain timestamp, matching how PostgreSQL timestamptz is treated elsewhere in the repo; the timezone is part of the type. The cast type name is now emitted via quoteString so a mapping that contains a quote of its own stays well-formed SQL. Extends the gtest and integration tests accordingly.
…typed Bind Keep the connection alive after an extended-query error (Parse/Bind/Execute/ Close): send ErrorResponse, discard messages until Sync, then ReadyForQuery, per the PostgreSQL protocol, instead of rethrowing and dropping the socket. Rejecting a bad typed Bind value (added for type preservation) must not close the connection, otherwise the client never receives the error. Move the binary-format Bind rejection out of deserialize (it now records a flag and fully consumes the message so the byte stream stays aligned for the skip-until-Sync path) into attachBindQuery. Reject an oversize decimal exponent for a numeric (OID 1700) Bind before any exponent arithmetic or zero-padding, closing the O(exponent) DoS and the signed-Int64 overflow on values like 1e1000000 / 1e99999999999999999999. Map timestamptz (OID 1184) to DateTime64(6, 'UTC') instead of bare DateTime64(6), and quote the cast target type so a type name containing a quote stays a well-formed SQL literal. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nd Describe no-op Mark DESCRIBE, CLOSE and EXECUTE as in-progress like PARSE/BIND, so a standalone Describe/Sync or Close/Sync no longer emits a mid-cycle ReadyForQuery before the Sync is read. ReadyForQuery is now sent exactly once per Sync, as strict extended-protocol clients require. Describe was a silent no-op: on success the backend sent none of ParameterDescription/RowDescription/NoData, so a client issuing Describe hung until timeout. It now fails fast with a clear NOT_IMPLEMENTED error, followed by the existing skip-until-Sync recovery so the connection stays alive. Adds a raw-wire integration regression asserting one ReadyForQuery per Sync for Close/Sync, Describe/Sync and Parse/Bind/Describe/Execute/Sync, that Describe returns an error instead of hanging, and that a rejected 1-- typed Bind still recovers on the same connection. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…statements The previous change made Describe fail fast with NOT_IMPLEMENTED, but that aborts the whole extended-query cycle: the skip-until-Sync recovery discards the Execute that a client pipelines after Describe, so a standard prepared statement (for example psycopg execute(..., prepare=True), which sends Parse/Bind/Describe/Execute/Sync in one flush) fails with 'Describe is not supported' instead of running. The row layout is not known until the query runs, and the RowDescription is emitted at Execute time by PostgreSQLOutputFormat, which pipelining clients read together with the Describe. So Describe is consumed as a no-op and the Execute produces the RowDescription. The ReadyForQuery-per-Sync contract fix (marking Describe/Close/Execute in-progress) is kept. Adjust the extended-query regression test accordingly: Describe/Sync is a silent no-op with exactly one ReadyForQuery, and Parse/Bind/Describe/Execute/ Sync runs the Execute (RowDescription + DataRow + CommandComplete) with one ReadyForQuery. Co-Authored-By: Claude Opus 4.8 <[email protected]>
A malformed Bind carrying num_params < 0 skipped the parameter loop and left the parameter payload unread, so the following bytes were misread as the result-format-code count and the rest of the Bind body stayed unconsumed. That desynchronized the skip-until-Sync error-recovery path introduced for typed Bind validation. Reject num_params < 0 (mirroring the existing num_format_params guard) and add the same guard to num_format_params_result, which was likewise unchecked. Regressions cover both counts at the gtest and integration layers. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…LUSH and unsupported-message errors Bind's requested result-format codes were parsed then dropped, so a binary result request (resultFormat = 1) silently returned text rows. Record a has_binary_result_format_param flag during deserialize (keeping the stream aligned for skip-until-Sync recovery) and reject it in attachBindQuery, matching the binary parameter-format rejection. The FLUSH and unsupported-message branches emitted an ErrorResponse but left ignore_until_sync = false, so a pipeline like Parse; Bind; FLUSH; Execute; Sync still ran the Execute after the error. Route both branches through the same discard-until-Sync recovery as Parse/Bind/Execute/Close. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ives redefine/close
Bind now resolves the prepared statement and snapshots its body/param types
into the portal (and validates arity), instead of Execute re-resolving it from
the live statements map. Per the extended-query contract, once BindComplete is
sent the portal owns its statement: a later Parse that redefines it, or a Close
that deallocates it, must not change what Execute runs. Close('S') no longer
touches the bound portal.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…orQuery per Sync Bind arity: check the value count against the statement's true parameter count (highest $N placeholder in the body), not the declared parameter type count. Parse may declare fewer OIDs than there are placeholders, so the old check let SELECT $1, $2 bound with one value through (leaving $2 in the SQL at Execute) and silently dropped extra bound values. ReadyForQuery: emit it only at explicit protocol boundaries (startup, simple query, Sync) via a need_ready_for_query flag, instead of speculatively at the top of every idle loop iteration. A bare standalone Sync issued while idle now yields exactly one ReadyForQuery instead of two. Co-Authored-By: Claude Opus 4.8 <[email protected]>
attachBindQuery returns void; the bindN test helper had `return manager.attachBindQuery(...)`, rejected by arm_tidy WERROR. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… text test_dotnet_client (Npgsql) regressed: the .NET driver requests binary result format by default, and the earlier hard rejection of binary result format codes in Bind broke it with "Binary result format is not supported". Binary result format is an output-encoding concern, orthogonal to the SQL injection fix (which is about input parameter values). Master's long-standing behavior was to accept the request and return text rows: RowDescription honestly advertises FormatCode::TEXT for every column, so a client that asked for binary reads text and adapts. Restore that: consume the result-format codes to keep the byte stream aligned, then ignore them. The binary parameter-value rejection and all injection defenses (per-OID accurateCast, arity check, negative-count and length guards, one ReadyForQuery per Sync, FLUSH/error skip-until-Sync recovery) are unchanged. Tests updated: the gtest now asserts the result-format codes are consumed and the stream stays aligned; the integration test asserts a binary result request completes normally (RowDescription/DataRow/CommandComplete, one ReadyForQuery) instead of erroring. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ameters An OID of 0 (or an omitted trailing OID) in a Parse message means the server infers the parameter type from the statement, not text. Coercing such values to a String literal regressed standards-compliant frontends: SELECT $1 + 1 became '41' + 1 (type error) and LIMIT $1 became LIMIT '1' (rejected). For an unspecified-OID slot, a value that is a single numeric literal is now emitted as a parenthesized numeric literal so ClickHouse infers its numeric type exactly as an inline literal would; any other value stays a quoted+escaped string. This is injection-safe by construction: isSingleNumericLiteral accepts only one optionally-signed decimal/exponent literal, so payloads like 1--, 1+2 or 1 UNION ... fall through to the quoted-string branch, and the wrapping parentheses block token-adjacency (a body 5-$1 with value -5 becomes 5-(-5), never the comment-truncating 5--5).
…ded literal
The parenthesized form (value) for an unspecified (OID 0) Bind parameter
broke the typed cast path: SELECT $1::Int32 assembled (42)::Int32, which
parses as CAST('(42)', 'Int32') (a parenthesized literal before :: is taken
as a string) and fails with a parse error, regressing the whole
test_postgresql_protocol suite.
Emit the validated numeric literal bare and space-padded ( value ) instead.
It keeps type inference (SELECT $1 + 1, LIMIT $1, $1::Int32 all work), and
the single space on each side blocks token-adjacency (a body 5-$1 with value
-5 becomes 5- -5, never the comment-truncating 5--5). Injection safety is
unchanged: only a single optionally-signed decimal/exponent literal
(isSingleNumericLiteral) takes this path; everything else stays a
quoted+escaped string.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ce-before-comma style check The space-padded OID-0 inference emit produces the expected value "SELECT 1 , 2 ". Splitting the literal at the comma (compile-time concatenated, value unchanged) avoids the style check matching whitespace-before-comma inside the string literal. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eral The space-padded OID-0 inference value "SELECT 1 , 2 " tripped check_style.py DOUBLE_WS_AFTER_COMMA (comma followed by two spaces) even after the earlier split. Isolate the comma in its own adjacent string literal so the source has no ", " or "\w ," sequence; compile-time concatenation keeps the asserted value byte-identical. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pick up revert PR #109851 (reverts #108988) which fixes the ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup unit test regression that was failing on our pre-revert build head. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…pecified-OID binds
Simple PREPARE/EXECUTE path (getStatement) now enforces the same exact-arity
invariant as the extended Bind path: EXECUTE must supply one argument per $N
placeholder. Without it, EXECUTE s(1,2) on PREPARE s AS SELECT $1 silently
dropped the extra argument and EXECUTE s(1) on PREPARE s AS SELECT $1,$2 left
$2 in the executed SQL.
Unspecified/OID-0 Bind params: a boolean keyword (true/false, case-insensitive)
now infers as Bool alongside the existing numeric-literal inference, so
Parse("SELECT NOT $1") + Bind("true") assembles NOT true instead of NOT
'true' (which fails). Any other value stays a quoted+escaped string literal.
Injection safety unchanged: only isSingleNumericLiteral / isBooleanLiteral
validated values take the bare space-padded form; everything else is quoted.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Related: ClickHouse/clickhouse-private#53764 Related: ClickHouse/clickhouse-private#70135 Related: #112940
…-protocol-sql-injection # Conflicts: # src/Core/tests/gtest_postgresql_protocol.cpp
Use a CSPRNG for PostgreSQL `CancelRequest` secrets and preserve all 32 bits. Shorten branch comments and fix the ClickHouse spelling check. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108469&sha=da8b614bff5298fb4e05965290ecdf4103d9a7bf&name_0=PR&name_1=Style%20check PR: #108469
…-protocol-sql-injection
Store the return value from `close` in the non-OpenSSL cancellation-key path, matching the existing checked-close style. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108469&sha=03deb99e4acd5f219882978197d6f977c13bff60&name_0=PR&name_1=Style%20check PR: #108469
…-protocol-sql-injection
Initialize `secret_key` before filling it with secure random bytes to satisfy `cppcoreguidelines-init-variables`. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108469&sha=210604a664fedc0a9f3aa55b5a71e86f764612eb&name_0=PR PR: #108469
`CancelRequest` arrives on its own unauthenticated connection and carries only the `BackendKeyData` pair, so the secret is the whole credential for it. The query ID was `postgres:<connection id>:<secret key>`, and `system.processes` and `system.query_log` publish query IDs verbatim, so a principal able to read those could take another user's secret and cancel that user's query while holding no `KILL QUERY` privilege. The query ID is now `postgres:<connection id>`. The secret is registered in `ProcessList` for as long as the connection is open, and `sendCancelToPostgreSQLQuery` compares it there, so cancellation still requires the exact pair from `BackendKeyData`. Two regression cases that were missing are added with it: a live PostgreSQL query with the right process ID and a wrong secret must keep running, and a `COPY FROM` table name carrying a backquote must not inject SQL.
The connection ID is the query ID of every statement of its connection, and the ID a `CancelRequest` resolves to now that the secret is no longer carried in the query ID. The counter was a member of `PostgreSQLHandlerFactory`, and one factory is created per listener, so two connections arriving on two endpoints both received ID 0: one query ID for two live statements, and one cancellation slot that the later connection overwrote. Measured on a server with `postgresql_port` plus a second `postgres` protocol endpoint: with a counter per factory both listeners hand out `BackendKeyData` process ID 0, with a server-wide counter they hand out 3 and 4.
`substitute` appended the argument text with no separation, and `EXECUTE` arguments reach it straight from the parser, so `PREPARE s AS SELECT 5-$1 AS v` executed with `-1` assembled `SELECT 5--1 AS v`, where `--` starts a comment and the rest of the statement disappears. Measured before this change: `EXECUTE s(-1)` returned 5 rather than 6, and with a trailing `, 'tail' AS t` the second column was gone as well. Spaces now surround every substituted argument, which is where the `Bind` path already put them for inferred values, so `formatInferredParameter` no longer adds its own.
…pair Keying it on the query ID alone let a connection that reuses a connection ID displace a live one: the later registration replaced the earlier connection's secret under the shared ID, so the newcomer's own secret could cancel the older connection's query, and either teardown removed the entry both were using. Connection IDs come from one server wide counter, so this needs the counter to wrap, and nothing bounds how long a connection stays open. Two live connections practically never hold the same secret, so the pair identifies a connection by itself. `sendCancelToPostgreSQLQuery` takes the pair and reads the query ID out of the registry instead of rebuilding it.
The interface check and the registry entry going away at teardown both make the CancelRequest in that case a no-op, so it cannot attribute the outcome to either one. Telling them apart would need the same PostgreSQL connection id handed out twice, which needs the server wide counter to wrap, so the docstring now states the limit instead of claiming the stronger property.
The random component of `postgres:<connection id>:<...>` was doing three jobs at once: authenticating `CancelRequest`, keeping query IDs unique, and keeping them unpredictable. Removing it to stop publishing the secret kept the first and lost the other two. A query ID of `postgres:<connection id>` alone repeats once the connection counter wraps, which two live connections cannot survive because a query ID identifies a running query; and it is small enough to guess, so a client on another interface can hold it and keep a PostgreSQL statement from starting. The ID now carries a random token that is generated per connection and is not the secret, so it is unique and unguessable while the credential stays in `ProcessList`. That restores the shape the stateless test already asserted, and the integration case now checks the stronger property directly: the secret does not appear in the query ID that `system.query_log` publishes. Because the token is not predictable, the cases that need a connection's query ID read it back from `system.query_log`, and the wrong-secret case polls `system.processes` by statement text.
The control sent the genuine secret and then allowed 30 seconds for the statement to leave `system.processes`, while the statement sleeps for about 18 and would have left on its own inside that window, so a cancellation that did nothing satisfied it. The window is 8 seconds now, and the case also requires the `ErrorResponse` the client is owed. Measured on a local server: the statement disappears 0.3 seconds after the request and the connection receives `E` then `Z`.
Surrounding every substituted argument with spaces also padded the values that already carry
their own delimiters, so the `Bind` paths started emitting `SELECT accurateCast('41', 'Int32')
+ 1` and `SELECT 'hi' `. Eight `PostgreSQLProtocol` unit tests pin that text and failed on
`Unit tests (asan_ubsan)`.
Only a bare literal can merge with the token beside it, and the two places that produce one are
`formatInferredParameter` for OID 0 and the simple `EXECUTE` path, so the separation belongs
there rather than at the substitution site. `formatInferredParameter` keeps the spaces it had
before, `EXECUTE` arguments now get them, and an `accurateCast` call or a quoted string is
substituted unchanged.
Measured with `clickhouse local` on the text this now emits: `SELECT 5- -1 AS v, 'tail' AS t`
returns 6 and both columns, while the previous `SELECT 5--1 AS v, 'tail' AS t` returns 5 and
drops the second column. `ExecuteArgumentStaysASeparateToken` covers it, and removing the
`EXECUTE` separation alone fails that case and no other.
The `whitespace_check` leg of `Style check` rejects a comma followed by two
or three spaces (`,( {2,3})[^ /]` in `ci/jobs/check_style.py`), and it looks
inside string literals as well as code. The simple `EXECUTE` path pads each
bare argument with spaces so that it cannot merge with an adjacent token, so
the body `SELECT $1 AS a, $2 AS b` renders as `SELECT 1 AS a, 2 AS b`
and the expected literal carried `, 2`.
Assert on a comma-free two-placeholder body instead, matching the
repeated-placeholder block below it. The property under test is unchanged:
exact arity is accepted, and each argument is substituted at its own
placeholder, which the distinct values still pin by position.
Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108469&sha=7115f03255555356764c2a12857cf9839099c6aa&name_0=PR&name_1=Style%20check&name_1=Style%20check
Related: #108469
A query ID may be held by only one query at a time across the whole server, and `system.processes` and `system.query_log` publish PostgreSQL query IDs verbatim while the secret from `BackendKeyData` stays server side. The public random token was drawn once per connection, so `postgres:<connection id>:<token>` covered every statement of that session. A principal who read one such ID could take it on another interface, and the connection's next statement was then refused with `Query with id = postgres:... is already running.` before it entered the process list, without holding `KILL QUERY`. Draw the token as each statement starts, and re-point the connection's cancellation entry at the new ID so `CancelRequest` still resolves to the statement that is running. Measured on the debug build in three arms. Without the change the second statement is refused while the learned ID is held. With it the statement runs and the two IDs differ. With the new token but without the re-registration the ID is no longer reusable, but a genuine `CancelRequest` stops cancelling, which is the property `test_cancel_request_with_wrong_secret_key_does_not_cancel` already covers.
…-sql-injection Fix SQL injection in PostgreSQL wire protocol parameter binding
…ypick/26.7/108469 # Conflicts: # src/Core/PostgreSQLProtocol.h # src/Core/tests/gtest_postgresql_protocol.cpp # src/Server/PostgreSQLHandler.cpp # src/Server/PostgreSQLHandler.h # src/Server/PostgreSQLHandlerFactory.h # tests/integration/test_postgresql_protocol/test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #108469
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job