Skip to content

Fix SQL injection in PostgreSQL wire protocol parameter binding - #108469

Merged
antonio2368 merged 59 commits into
ClickHouse:masterfrom
groeneai:fix-postgresql-wire-protocol-sql-injection
Sep 4, 2026
Merged

antonio2368 merged 59 commits into
ClickHouse:masterfrom
groeneai:fix-postgresql-wire-protocol-sql-injection

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110760

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 SQL injection in the PostgreSQL wire protocol emulation. Prepared-statement parameters — the Parse/Bind/Execute extended-query path used by psycopg2, JDBC, node-postgres, Npgsql and others, and the simple-query EXECUTE path — 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 with UNKNOWN_IDENTIFIER when a client sent them unquoted.

Description

The PostgreSQL wire-protocol emulation assembled SQL by raw string substitution of client-supplied values. PreparedStatemetsManager::getStatement replaced the placeholders $1, $2, ... in the prepared-statement body with the raw parameter values. Two paths feed it:

  • Extended-query path (Parse/Bind/Execute), the default for psycopg2, JDBC, node-postgres, Npgsql and others. BindQuery::deserialize read the parameter bytes straight off the wire and they were spliced into the SQL text verbatim, so a parameter like x' UNION ALL SELECT ... -- broke out of its string literal. As a side effect, a correctly written client that sends WHERE name = $1 without client-side quoting failed with UNKNOWN_IDENTIFIER, because the value was substituted unquoted.
  • Simple-query EXECUTE path, where arguments were formatted with fieldToString, which drops the quotes around string literals, so it had the same problem.

Every argument is now turned into a SQL literal before substitution:

  • Bind uses the parameter type OIDs the client declared in Parse. An OID that maps to a ClickHouse type is emitted as accurateCast('<escaped value>', '<type>'), which delegates parsing and range checking to ClickHouse while keeping the declared type (int4 rejects 3.14 and 2147483648, numeric keeps full precision, bool/date/uuid stay 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 and LIMIT $1 or SELECT $1 + 1 keep working.
  • The protocol NULL sentinel (length -1) maps to the SQL keyword NULL. BindQuery::parameters becomes std::optional<String> so a NULL parameter is no longer ambiguous with the text "NULL".
  • EXECUTE uses FieldVisitorToString (strings quoted and escaped, numbers left bare) and rejects a non-literal argument. Previously a non-literal such as now() reached child->as<ASTLiteral>()->value and dereferenced a null pointer; splicing the expression's SQL text also changes results ($1 * 10 with 1 + 1 assembles 1 + 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:

  • Arity is checked against the statement's true parameter count (the highest $N in the body), not against the number of declared OIDs — Parse may declare fewer. Otherwise a short Bind left $2 literally in the executed SQL and a long one was silently ignored.
  • The portal snapshots its statement at Bind. Re-resolving at Execute meant a later Parse that redefined the statement changed what Execute ran, and a Close between Bind and Execute turned it into Execute without prior Bind.
  • ReadyForQuery is 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 standalone Describe/Sync.
  • An extended-query error skips to the next Sync instead of rethrowing, which dropped the connection before the client could read the ErrorResponse.
  • Negative count fields in Parse/Bind are 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 the RowDescription advertises.

Scope

Identifier quoting for COPY was part of this PR and has been removed: #110760 fixed the same injection in ParserCopyQuery, which now stores the table and column names already rendered as valid SQL (each part of a compound database.table name separately back-quoted). Quoting them again in the handler would double-quote them. The integration test for COPY identifier injection is kept here, since #110760 added no test for it.

Tests

tests/integration/test_postgresql_protocol drives 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, ReadyForQuery and error-recovery contracts above at the wire level. src/Core/tests/gtest_postgresql_protocol.cpp covers message deserialization and parameter formatting directly.

The pre-auth CancelRequest path (KILL QUERY WHERE query_id = 'postgres:{:d}:{:d}') was reviewed: process_id and secret_key are Int32 formatted with {:d}, so they cannot carry SQL and are not injectable. No change there.


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

Version info

  • Backported to: 26.8.3.34, 26.7.7.37, 26.6.5.63, 26.3.33.5

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Driving the Parse/Bind/Execute path with SQL SELECT id,name FROM t WHERE name = '$1' and bind param x' UNION ALL SELECT sid, secret FROM secret_data -- exfiltrates the secret table every time. COPY \t WHERE 1=0 UNION ALL SELECT ...` TO stdoutand theCOPY FROM` equivalent inject on demand.
b Root cause explained? PreparedStatemetsManager::getStatement substitutes $N with the raw client value. The Bind path (BindQuery::deserialize) stored wire bytes verbatim; the EXECUTE path used fieldToString, which drops string-literal quotes. So a value breaks out of its literal. COPY spliced client table/column names into SELECT/INSERT unquoted.
c Fix matches root cause? Yes. Values are converted to SQL literals before substitution (FieldVisitorToString for EXECUTE; quoteString, NULL keyword for the optional-NULL sentinel, for Bind). Identifiers are quoted with backQuoteIfNeed. The injection mechanism (data interpreted as SQL text) is removed at the substitution boundary.
e Both directions demonstrated? Yes. Pre-fix: injection leaks TOP_SECRET_VALUE; correct WHERE name = $1 clients fail with UNKNOWN_IDENTIFIER. Post-fix (verified against the rebuilt binary, Build ID confirmed): injection returns 0 rows / syntax error and the secret table is untouched; WHERE name = $1, numeric id > $1, NULL, and quote-containing values all work. COPY injection: the DROP TABLE did not run and the secret table is intact.
d Test intent preserved / new tests added? Added test_prepared_statement_no_sql_injection (extended-query path: injection payload returns [], plus normal string/numeric/quote params). Existing test_prepared_statement scenarios re-verified to still pass. No test weakened.
f Fix is general across code paths? Both getStatement feeders fixed (EXECUTE + Bind). Sibling-path sweep found a 4th sink the report missed: COPY FROM (INSERT INTO) had the same unquoted-identifier bug as COPY TO — both fixed. The pre-auth CancelRequest KILL path uses Int32 {:d} values, which cannot carry SQL, so it is not injectable (no change).
g Fix generalizes across inputs? Verified the Bind path with empty string, backslash, newline, tab, UTF-8 multibyte, multiple single quotes, %/{} format chars, and stacked-statement payloads — all round-trip as data or are blocked. quoteString escapes quotes and backslashes. NULL is handled distinctly via std::optional.
h Backward compatible? One unavoidable behavior change: a bound parameter is now a string literal, so LIMIT $1/OFFSET $1 reports INVALID_LIMIT_EXPRESSION instead of working (a string cannot be a LIMIT expression). This is inherent to binding untyped text parameters as data. Honoring the parameter type OIDs/format codes (currently parsed and discarded) to bind numerics as numbers would restore it — flagged in the description as a possible follow-up for maintainers. No on-disk/wire format or setting-default change.
i Invariants and contracts preserved? getStatement's contract is now "arguments are already safe SQL fragments"; both callers honor it (documented at the function). BindQuery::parameters type change (vector<String> -> vector<optional<String>>) has no other consumers. The $N first-occurrence replacement behavior is unchanged.

Session id: cron:clickhouse-worker-slot-12:20260625-112700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @vitlibar — could you review this? It closes a SQL injection in the PostgreSQL wire-protocol emulation: prepared-statement parameters (Bind/Execute and the EXECUTE path) and COPY identifiers were spliced into the executed SQL by raw string substitution. Values are now bound as quoted/escaped literals and identifiers quoted with backQuoteIfNeed. The one behavior tradeoff (LIMIT $1 now needs a numeric, not a string) is described in the PR.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jun 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jun 25, 2026
…-protocol-sql-injection

# Conflicts:
#	src/Core/PostgreSQLProtocol.h
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2d0da6]

Summary: ✅


AI Review

Summary

This 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 Describe behavior, numeric zero regression, and OID 0 type-inference mismatch are addressed.

Missing context / blind spots
  • ⚠️ The current Praktika report visible from the PR URL only exposed Build profile diff, so I could not verify fresh CI results for the new unit/integration coverage on f2d0da65.
Findings

⚠️ Majors

  • [src/Server/PostgreSQLHandler.cpp:1213] [dismissed by author -- https://github.com/Fix SQL injection in PostgreSQL wire protocol parameter binding #108469#discussion_r3541029889] processDescribeQuery still consumes Describe and returns no backend response at all. The later Execute RowDescription only helps clients that pipeline Describe and Execute immediately; a frontend that issues Describe('S', ...) or Describe('P', ...) on its own still waits forever for ParameterDescription, RowDescription, NoData, or an explicit error.
    Suggested fix: either implement the required Describe responses or return a clear NOT_IMPLEMENTED ErrorResponse instead of silent success.
  • [src/Core/PostgreSQLProtocol.h:2175] The numeric normalization guard still rejects numerically-zero values that PostgreSQL accepts and that this path can represent exactly. 0e1000000, 0e-1000000, and zero with more than 76 fractional zeroes all hit the exponent/precision caps before the all-zero mantissa is collapsed to plain 0, so this is now a typed-bind compatibility regression on valid numeric input.
    Suggested fix: special-case an all-zero mantissa before the exponent/precision caps and add a regression for huge-exponent / huge-scale zero.
  • [src/Core/PostgreSQLProtocol.h:2281] [dismissed by author -- https://github.com/Fix SQL injection in PostgreSQL wire protocol parameter binding #108469#discussion_r3550424706] The OID 0 path still infers from the value's lexical shape instead of the statement context. A concrete trace is Parse("SELECT $1::Bool") + Bind("2"): formatInferredParameter emits the bare literal 2, and ClickHouse accepts numeric 2 as Bool, so the statement returns true instead of rejecting invalid PostgreSQL boolean input. This changes parameter semantics in typed contexts on the common “let the server infer” path.
    Suggested fix: once the surrounding SQL fixes the type, route the value through that type's input path; if statement-context inference is unavailable here, fail closed instead of preserving the bare numeric shortcut in typed contexts.
Final Verdict

Needs 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 Report

Measured on commit f2d0da6.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 840/887 (94.70%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 25, 2026
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
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]>
Comment thread src/Core/PostgreSQLProtocol.h Resolved
groeneai and others added 3 commits June 25, 2026 14:20
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

  • test_prepared_statement_no_sql_injection: failed at the teardown DROP with Unknown statement. It stacked five prepare=True executes on one connection; the repeated named server-side prepared statements diverge from the client prepared-statement cache. A parameterized execute already uses the extended Parse/Bind/Execute path (the bound value travels the wire as data, the path under test), so prepare=True is dropped. Injection coverage, including the block-comment placeholder case, is unchanged. Wire trace confirms the value still arrives as a Bind parameter and the server escapes it.
  • test_copy_no_sql_injection: failed at the benign COPY after the two expected-to-fail probes with cursor already closed. A COPY the server rejects leaves the psycopg2 connection broken, so each COPY probe now uses its own connection (via closing(), since psycopg2 with conn does not close it). The COPY FROM no-leak count is cast with int() (ClickHouse returns it as text over the wire).

Validated locally against a 26.7 debug build: with prepare=True the prepared test fails 0/40; without it, 40/40. All three injection tests run 40/40 clean.

groeneai and others added 2 commits June 25, 2026 19:26
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e5c8ca2

CI fully finished on this head (Finish Workflow SUCCESS). Every failure has an owner.

Check / test Reason Owner
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) — ThreadSanitizer: data race (STID 4071-3348) + Server died chronic trunk TSan race in QueryStatus workload-resources release at query finish external fix #108391 (merged 2026-06-25 23:49Z) — merged master into this branch (new head 4954305e2fd) to pick it up; CI will re-run with the fix
Upgrade check (amd_release) — Error message in clickhouse-server.log test-env artifact: a leftover DatabasePostgreSQL engine's background pool logs PostgreSQLConnectionPool: Connection error … 192.0.2.1:5432 timeout (RFC-5737 unreachable test address) during the upgrade stop/restart window — unrelated to the server-side wire-protocol fix in this PR a fix task is created (investigating at full effort — fixing-PR link to follow on this PR)
Bugfix validation (integration tests) — test_postgresql_protocol/* per-test rows inverted-logic artifact: the JOB status is OK. Bugfix-validation runs the changed test file against the MASTER binary; an existing test that PASSES on master is flagged per-row. The 3 new *_no_sql_injection tests correctly reproduce on master, so the job passes. not a failure (job OK) — no owner needed
CH Inc sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260626-000000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the upgrade-check DatabasePostgreSQL background-cleaner connection-error log spam (the Error message in clickhouse-server.log line, 192.0.2.1:5432 timeout) created: #108560

It is a master-level upgrade-check allowlist fix in tests/docker_scripts/upgrade_runner.sh, mechanistically unrelated to this PR's wire-protocol change (test 04210_show_remote_databases_in_system_tables seeds the unreachable PostgreSQL engine; this PR does not touch it).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4954305

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

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel, 2/2) / 04033_tpc_ds_q10 flaky sanitizer timeout (15+ unrelated PRs + 3 master/30d), unrelated to this wire-protocol fix #107968 (ours, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_quorum_inserts_parallel::test_parallel_quorum_actually_quorum flaky SYNC REPLICA timeout (15+ unrelated PRs + 8 master/30d), unrelated to wire protocol #108433 (external, open)
Fast test (arm_darwin) / 03988_keeper_client_autocomplete flaky macOS keeper-client connect race ("Socket is not connected", 3 unrelated PRs/0 master), unrelated to wire protocol a fix task is created (investigating at full effort; fixing-PR link to follow here)
Bugfix validation (integration tests) / test_postgresql_protocol::* inverted-logic artifact: job status is OK; our new *_no_sql_injection regression tests reproduce on master HEAD, so the job passes not a failure (no owner needed)
CH Inc sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260626-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Fast test (arm_darwin) / 03988_keeper_client_autocomplete "Socket is not connected" flaky: #107438 (ours, open, approved, awaiting merge).

Root cause: at keeper-client process exit, ZooKeeper::finalize() calls socket.shutdown(); on macOS an already-disconnected socket returns ENOTCONN (errno 57). That benign exception is logged to stderr, which trips Fast-test's stderr check. Every test assertion passes (command_completion: OK ... all OK). The failing stack trace is byte-identical to the fix site:

Poco::Net::SocketImpl::shutdown()
Coordination::ZooKeeper::finalize(bool, bool, String const&)
Coordination::ZooKeeper::~ZooKeeper()
DB::KeeperClient::main(...)

#107438 logs that benign ENOTCONN at TRACE instead of error in the shared ZooKeeper::finalize() teardown path (this test spawns the keeper-client ~40 times, so any one of them tripping the stderr check fails the run). Same root cause already approved for 03135_keeper_client_find_commands.

Not caused by this PR: 0 master hits, 3 unrelated PRs in 30d (#107247, #105714, #108469).

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up fixing PR for the Upgrade-check DatabasePostgreSQL background-pool connection-error log spam: #109350. The merged #108560 covered removeOutdatedTables + the MySQL engine; #109350 extends it to the remaining getTablesIterator and AsyncLoader::worker code paths of test 04210's 192.0.2.1 fixture.

Comment thread src/Core/PostgreSQLProtocol.h Resolved
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.
@zlareb1

This comment was marked as low quality.

robot-ch-test-poll2 added a commit that referenced this pull request Sep 4, 2026
Cherry pick #108469 to 26.6: Fix SQL injection in PostgreSQL wire protocol parameter binding
robot-clickhouse added a commit that referenced this pull request Sep 4, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 4, 2026
Cherry pick #108469 to 26.7: Fix SQL injection in PostgreSQL wire protocol parameter binding
robot-clickhouse added a commit that referenced this pull request Sep 4, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 4, 2026
Cherry pick #108469 to 26.8: Fix SQL injection in PostgreSQL wire protocol parameter binding
robot-clickhouse added a commit that referenced this pull request Sep 4, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Sep 4, 2026
Cherry pick #108469 to 26.3: Fix SQL injection in PostgreSQL wire protocol parameter binding
robot-clickhouse added a commit that referenced this pull request Sep 4, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed on all five points, by reading the merged code. sz is read into a local and never used in either BindQuery::deserialize or ParseQuery::deserialize; both arrive through receive, and only CancelRequest and StartupMessage go through receiveWithPayloadSize, so only those two get the LimitReadBuffer; receiveMessageType and dropMessage both assume a message boundary. The test gap is exactly as you say: both messages in test_bind_negative_count_recovers end at the negative field, so the trailing-bytes path has no coverage.

Two things I found while checking. Bind has a fourth mid-message throw you did not list, the per-parameter sz_param < -1 length check, which leaves the remaining parameter bytes queued the same way (Parse has the one, num_params). And the unenforced sz is not only reachable through a negative count: readNullTerminated scans to the next \0 with no bound, so an unterminated portal_name, statement name or sql_query also reads into the following message. That makes your first option, wrapping the deserialization in a LimitReadBuffer sized by sz and skipping the unconsumed remainder, close the whole class, where consumed-byte tracking would have to be added per field. I plan to take the first one.

One consequence beyond the error cascade: dropMessage throws when the length it reads is below 4, and that throw is only caught by the connection-level handler at the end of run, which logs and returns. So a misaligned recovery can also close the connection outright instead of producing one error and a ReadyForQuery.

I will follow up here with a PR that enforces the declared length for Bind and Parse, and extends the regression test with trailing payload bytes after the negative count.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@zlareb1 Superseded before I opened mine: #118097 does exactly this, and it is already approved.

It routes both Parse and Bind payloads through a LimitReadBuffer sized from the declared length, and skips the unconsumed remainder both on the success path and in a catch (...) before rethrowing. Because the whole deserialization body now sits inside that buffer, it covers every mid-message rejection by construction rather than one at a time: the four in Bind (PostgreSQLProtocol.h:813, :824, :833, :849, the third being the per-parameter length check that was not in your list) and the one in Parse (:752). It closes the unbounded readNullTerminated scan on those two messages the same way. Measured: deserializePayload is present at its head and absent on master.

Its regression test is the shape I described, and sharper: it puts a complete-looking Sync frame inside each malformed payload, so recovery has to ignore that and wait for the real one, across four cases instead of two.

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.

clickhouse-gh Bot added a commit that referenced this pull request Sep 4, 2026
Backport #108469 to 26.8: Fix SQL injection in PostgreSQL wire protocol parameter binding
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @antonio2368 @CheSema — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

@clickgapai Confirmed and fixed in #118210.

Verified on builds of master 625e1ce7e12bafa, not only from the source: a simple-query connection that sends Flush or an unimplemented message type gets ErrorResponse and nothing more, and its next Query is discarded unexecuted. The pre-#108469 snapshot of the same tree answers ErrorResponse plus ReadyForQuery and keeps working, so it is a regression from this PR.

I took your first suggested shape. The second one (setting need_ready_for_query next to ignore_until_sync) would emit a second ReadyForQuery per Sync and breaks test_flush_error_discards_until_sync. That test also turned out not to pin the in-cycle behaviour: with the new flag forced to false it still passed, because it stopped reading at the first ReadyForQuery and the discarded Execute surfaced only in the next read. It now reads an empty query and requires exactly EmptyQueryResponse.

The two open risks you listed are deliberately left alone: the Flush error text is still the stale one, and Flush is still rejected rather than implemented as an output flush.

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.

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai Confirmed — fix looks right. The need_ready_for_query gate restores the pre-#108469 contract that ErrorResponse and ReadyForQuery arrive together, and requiring EmptyQueryResponse after the discarded query pins the in-cycle behavior instead of relying on read order.

Agreed the two deferred items (stale Flush error text, Flush unimplemented rather than rejected) are orthogonal and fine to split out.

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.

jh0x pushed a commit to jh0x/ClickHouse that referenced this pull request Sep 5, 2026
`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)
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #108469 to 26.6: Fix SQL injection in PostgreSQL wire protocol parameter binding
antonio2368 added a commit that referenced this pull request Sep 7, 2026
Backport #108469 to 26.3: Fix SQL injection in PostgreSQL wire protocol parameter binding
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 7, 2026
`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`.
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #108469 to 26.7: Fix SQL injection in PostgreSQL wire protocol parameter binding
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Sep 13, 2026
…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]>
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 groeneai-origin-unknown PR origin: unclassified (legacy task) 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.

9 participants