Repository navigation
Fix SQL injection in PostgreSQL wire protocol parameter binding - #108469
antonio2368 merged 59 commits into
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-12:20260625-112700 |
|
cc @yakov-olkhovskiy @vitlibar — could you review this? It closes a SQL injection in the PostgreSQL wire-protocol emulation: prepared-statement parameters ( |
…-protocol-sql-injection # Conflicts: # src/Core/PostgreSQLProtocol.h
|
Workflow [PR], commit [f2d0da6] Summary: ✅
AI ReviewSummaryThis PR closes the raw-string SQL injection sinks in the PostgreSQL wire protocol and fixes several real extended-query contract bugs, but the current head still leaves a few PostgreSQL-compatibility problems in the same area. I would keep the review open until the remaining Missing context / blind spots
Findings
Final VerdictNeeds changes before merge: the injection fix itself looks sound, but the remaining protocol semantics above are still user-visible correctness and compatibility gaps in the same code path. LLVM Coverage ReportMeasured on commit f2d0da6.
Changed lines: Changed C/C++ lines covered: 840/887 (94.70%) · Uncovered code |
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]>
|
Pushed 8fcf469: made the two new injection tests deterministic (the flaky integration check was failing them intermittently). Both failures were connection-state artifacts, not security-assertion failures.
Validated locally against a 26.7 debug build: with |
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
CI finish ledger — e5c8ca2CI fully finished on this head (Finish Workflow SUCCESS). Every failure has an owner.
Session id: cron:our-pr-ci-monitor:20260626-000000 |
|
Fixing PR for the upgrade-check It is a master-level upgrade-check allowlist fix in |
CI finish ledger — 4954305Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260626-050000 |
|
Fixing PR for the Root cause: at keeper-client process exit, #107438 logs that benign ENOTCONN at Not caused by this PR: 0 master hits, 3 unrelated PRs in 30d (#107247, #105714, #108469). |
|
Follow-up fixing PR for the Upgrade-check |
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.
This comment was marked as low quality.
This comment was marked as low quality.
Cherry pick #108469 to 26.6: Fix SQL injection in PostgreSQL wire protocol parameter binding
Cherry pick #108469 to 26.7: Fix SQL injection in PostgreSQL wire protocol parameter binding
Cherry pick #108469 to 26.8: Fix SQL injection in PostgreSQL wire protocol parameter binding
Cherry pick #108469 to 26.3: Fix SQL injection in PostgreSQL wire protocol parameter binding
|
Confirmed on all five points, by reading the merged code. Two things I found while checking. One consequence beyond the error cascade: I will follow up here with a PR that enforces the declared length for |
|
@zlareb1 Superseded before I opened mine: #118097 does exactly this, and it is already approved. It routes both Its regression test is the shape I described, and sharper: it puts a complete-looking That is the first of your two options, so nothing diverges from what I said I would take, and I am not opening a competing PR. |
Backport #108469 to 26.8: Fix SQL injection in PostgreSQL wire protocol parameter binding
|
@groeneai @antonio2368 @CheSema — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
@clickgapai Confirmed and fixed in #118210. Verified on builds of master I took your first suggested shape. The second one (setting The two open risks you listed are deliberately left alone: the For whoever owns the backport wave: the regression is already on 26.8 through the merged backport of this PR, and reaches 26.3, 26.6 and 26.7 when theirs merge. |
|
@groeneai Confirmed — fix looks right. The Agreed the two deferred items (stale Backport scope noted: 26.8+ is affected now, 26.3–26.7 once their backports land — relevant for any PostgreSQL wire client on those versions. |
`Parse` and `Bind` errors could leave bytes from the declared payload in the connection buffer. The recovery loop then treated those bytes as new frontend messages before it reached the real `Sync`. Read both message payloads through an exact-size `LimitReadBuffer` and consume the declared remainder before propagating an exception. Extend the socket and unit coverage with an embedded fake `Sync` frame. Review: ClickHouse#108469 (comment)
Backport #108469 to 26.6: Fix SQL injection in PostgreSQL wire protocol parameter binding
Backport #108469 to 26.3: Fix SQL injection in PostgreSQL wire protocol parameter binding
`Sync` and a simple `Query` both end an extended-query cycle, and this handler
now treats them as equivalent boundaries, but only `Sync` cleared the cycle's
objects. After `Parse("")`, `Bind("")`, `Query(...)`, a bare `Execute("")` still
ran the portal bound before the simple query, and a `Bind("")` after it still
resolved the unnamed prepared statement. PostgreSQL rejects both cases
(`exec_simple_query` calls `drop_unnamed_stmt()` and recreates the unnamed
portal), so stale extended-query state stayed executable across a boundary that
should have destroyed it.
Measured on 7152cbb: `Execute("")` after the simple query returned the stale
portal's row instead of an error; it now answers `Execute without prior Bind`,
and a later `Bind("")` answers `Unknown statement`. Named statements are
unaffected, as is the SQL-level `PREPARE`/`EXECUTE` path.
The defect predates ClickHouse#108469: `resetBindQuery()` is called only from
`processSyncQuery` and `Close('P')` on master and at that PR's base alike. It is
fixed here because this PR is what makes the simple `Query` a cycle-ending
boundary.
Reported by the AI reviewer on ClickHouse#118210.
The `Parse` comment claiming a cycle ends only at `Sync` contradicted that, so it
now names both boundaries.
`test_out_of_cycle_rejection_keeps_connection_usable` also now sends the rejected
message as the connection's first message. Every other case opens and ends a cycle
first, so a handler that started out believing a cycle was in progress kept the
whole suite green while a fresh simple-query connection went deaf on its first
`Flush`.
Backport #108469 to 26.7: Fix SQL injection in PostgreSQL wire protocol parameter binding
…mat but carries no parameters `BindQuery::deserialize` reads the parameter-format-code array before the parameter-value count, because that is the wire order, and it armed the message-level `has_binary_format_param` flag for any non-zero code at that point, with no reference to `num_params`. The flag therefore recorded "a non-text format code appeared somewhere in this message", while its only consumer, `attachBindQuery`, needs "a parameter value in this message must be decoded from a non-text format". Those two propositions differ exactly when the message carries no values. The protocol lets the format-code count be one, in which case that single code applies to all parameters, including when there are none; the reference implementation only rejects `numPFormats > 1 && numPFormats != numParams` (postgres `src/backend/tcop/postgres.c`). A wire-legal `Bind` with one binary format code and zero parameter values was therefore answered with NOT_IMPLEMENTED "Binary format parameters are not supported in Bind messages", and `attachBindQuery` threw before it even resolved the statement, so nothing downstream could rescue the case. Accumulate the observation in a local while the codes are consumed (the loop must keep consuming all of them, which is what keeps the stream aligned), then assign the member once `num_params` has been read and validated. Binary parameter values are still rejected, and the malformed-count guards still fire first. Related: ClickHouse#108469 Co-Authored-By: Claude Opus 5 <[email protected]>
Related: #110760
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed SQL injection in the PostgreSQL wire protocol emulation. Prepared-statement parameters — the
Parse/Bind/Executeextended-query path used bypsycopg2, JDBC,node-postgres, Npgsql and others, and the simple-queryEXECUTEpath — were substituted into the executed SQL by raw string splicing, so a crafted parameter could break out of its value position and inject SQL. Parameters are now bound as data. This also fixes string parameters that previously failed withUNKNOWN_IDENTIFIERwhen a client sent them unquoted.Description
The PostgreSQL wire-protocol emulation assembled SQL by raw string substitution of client-supplied values.
PreparedStatemetsManager::getStatementreplaced the placeholders$1,$2, ... in the prepared-statement body with the raw parameter values. Two paths feed it:Parse/Bind/Execute), the default forpsycopg2, JDBC,node-postgres, Npgsql and others.BindQuery::deserializeread the parameter bytes straight off the wire and they were spliced into the SQL text verbatim, so a parameter likex' UNION ALL SELECT ... --broke out of its string literal. As a side effect, a correctly written client that sendsWHERE name = $1without client-side quoting failed withUNKNOWN_IDENTIFIER, because the value was substituted unquoted.EXECUTEpath, where arguments were formatted withfieldToString, which drops the quotes around string literals, so it had the same problem.Every argument is now turned into a SQL literal before substitution:
Binduses the parameter type OIDs the client declared inParse. An OID that maps to a ClickHouse type is emitted asaccurateCast('<escaped value>', '<type>'), which delegates parsing and range checking to ClickHouse while keeping the declared type (int4rejects3.14and2147483648,numerickeeps full precision,bool/date/uuidstay their declared type). Any other OID becomes a quoted and escaped string literal. Both forms keep the value inside a quoted literal, so it cannot break out of the value position. Because the declared type is honoured, a numeric parameter stays numeric andLIMIT $1orSELECT $1 + 1keep working.NULL.BindQuery::parametersbecomesstd::optional<String>so a NULL parameter is no longer ambiguous with the text"NULL".EXECUTEusesFieldVisitorToString(strings quoted and escaped, numbers left bare) and rejects a non-literal argument. Previously a non-literal such asnow()reachedchild->as<ASTLiteral>()->valueand dereferenced a null pointer; splicing the expression's SQL text also changes results ($1 * 10with1 + 1assembles1 + 1 * 10= 11, not 20).Binding values as data exposed several protocol contracts that the emulation did not keep, each of which is needed for the fix to be usable by real clients:
$Nin the body), not against the number of declared OIDs —Parsemay declare fewer. Otherwise a shortBindleft$2literally in the executed SQL and a long one was silently ignored.Bind. Re-resolving atExecutemeant a laterParsethat redefined the statement changed whatExecuteran, and aClosebetweenBindandExecuteturned it intoExecute without prior Bind.ReadyForQueryis emitted once per protocol boundary (startup, a completed simple query,Sync) instead of at the top of every idle loop iteration, which used to emit it twice around a standaloneDescribe/Sync.Syncinstead of rethrowing, which dropped the connection before the client could read theErrorResponse.Parse/Bindare rejected; binary-format parameters are rejected after the message is fully consumed (so the stream stays aligned); binary result format requests are accepted and answered with text, which is what theRowDescriptionadvertises.Scope
Identifier quoting for
COPYwas part of this PR and has been removed: #110760 fixed the same injection inParserCopyQuery, which now stores the table and column names already rendered as valid SQL (each part of a compounddatabase.tablename separately back-quoted). Quoting them again in the handler would double-quote them. The integration test forCOPYidentifier injection is kept here, since #110760 added no test for it.Tests
tests/integration/test_postgresql_protocoldrives the extended-query path with injection payloads and asserts the parameter is treated as data (the targeted secret table is never read), while normal string, numeric, quote-containing and NULL parameters keep working; it also covers the arity, portal-snapshot,ReadyForQueryand error-recovery contracts above at the wire level.src/Core/tests/gtest_postgresql_protocol.cppcovers message deserialization and parameter formatting directly.The pre-auth
CancelRequestpath (KILL QUERY WHERE query_id = 'postgres:{:d}:{:d}') was reviewed:process_idandsecret_keyareInt32formatted with{:d}, so they cannot carry SQL and are not injectable. No change there.Workflow [PR]
Sync PR [sync-upstream/pr/108469]
Version info
26.8.3.34,26.7.7.37,26.6.5.63,26.3.33.5