Repository navigation
Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names - #111516
Conversation
…rals When pushing a WHERE predicate down to a PostgreSQL source, string values inside an IN-list of two or more elements (pushed down as a Tuple literal) were backslash-escaped instead of having their single quotes doubled. Under PostgreSQL's default standard_conforming_strings, `\'` does not escape the quote, so a value containing `'` breaks out of the pushed-down literal and, because PostgreSQLSource ships the query as `COPY (<query>) TO STDOUT` over the libpq simple protocol, allows stacked SQL statements to execute. FieldVisitorToStringPostgreSQL specialized only the scalar String case; every other type, including Array/Tuple/Map, fell through to the regular FieldVisitorToString, whose container methods recurse with themselves, so nested strings used backslash escaping. This completes the incomplete CVE-2025-1520 fix, which covered only scalar strings. Move FieldVisitorToStringPostgreSQL next to its sibling and share the container serialization via templated helpers so both visitors recurse with the same escaping and can no longer drift apart. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [ffdabaf] Summary: ✅
AI ReviewSummaryThis PR finishes the remaining PostgreSQL metadata-query hardening by routing Final Verdict✅ Approve LLVM Coverage Report |
…ay/Tuple/Map Explain that the remaining Field types (Object, CustomType, AggregateFunctionStateData, ...) fall through to the regular backslash-escaping visitor safely, because they cannot appear as a literal in a predicate pushed down to PostgreSQL: there is no Object literal syntax, and a PostgreSQL source exposes no Object/JSON/Map/AggregateFunction columns (json/jsonb map to String). Only a scalar or an IN-list Tuple is pushed down, with Array/Map reachable only nested inside such a Tuple. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Pull request overview
This pull request closes a SQL injection vector in PostgreSQL predicate pushdown by ensuring PostgreSQL-safe string escaping (quote doubling) is applied not only to scalar String literals but also to String values nested inside container literals (Tuple/Array/Map) generated by multi-element IN (...) lists.
Changes:
- Move/centralize
FieldVisitorToStringPostgreSQLintoFieldVisitorToString.{h,cpp}and add container overloads that recurse through the PostgreSQL visitor. - Share container formatting between the regular and PostgreSQL visitors via templated helper functions to prevent future drift.
- Add a regression test asserting that pushed-down
INlists containing a quote use'a''b'(never'a\'b'), including nested tuple/rowINlists.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
src/Storages/tests/gtest_transform_query_for_external_database.cpp |
Adds regression coverage to validate PostgreSQL escaping for multi-element IN lists and nested tuple IN lists. |
src/Parsers/ASTLiteral.cpp |
Removes the local PostgreSQL visitor and uses the shared FieldVisitorToStringPostgreSQL when LiteralEscapingStyle::PostgreSQL is selected. |
src/Common/FieldVisitorToString.h |
Introduces the FieldVisitorToStringPostgreSQL declaration (with container overloads) next to FieldVisitorToString. |
src/Common/FieldVisitorToString.cpp |
Implements PostgreSQL string escaping and container recursion via shared container-formatting helpers. |
Address the review finding on `FieldVisitorToStringPostgreSQL`: string literals pushed down to a PostgreSQL source were emitted as plain `'...'` constants with only the single quote doubled. Under a remote session with `standard_conforming_strings = off`, a backslash escapes the first quote of a doubled pair, letting the second quote terminate the literal early and the remainder execute as SQL - and `Connection::updateConnection` never forces that GUC on. Emit `E'...'` escape-string constants instead, doubling both the single quote (`''`) and the backslash (`\\`). In an `E''` constant PostgreSQL always treats backslash as an escape character irrespective of `standard_conforming_strings`, so the literal is unambiguous on every server. The change is scoped to `FieldVisitorToStringPostgreSQL` (used only for predicate pushdown via `ASTLiteral`), leaving the shared `writeQuotedStringPostgreSQL` - which drives the `Values` output format - untouched. Container overloads recurse through the same visitor and inherit the escaping. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The predicate-pushdown fix made pushed-down literals safe, but the metadata queries in fetchPostgreSQLTableStructure still built SQL with the plain `quoteStringPostgreSQL` (single-quote doubling only) and joined requested column names with `','` without quoting each one. Under a remote session with `standard_conforming_strings = off`, a table/schema/column name containing a backslash-quote still breaks out of the literal, leaving the same SQL-injection class reachable during introspection. Add `writeQuotedStringPostgreSQLLiteral` (an `E'...'` escape-string constant, doubling both the quote and the backslash — safe on every server config) as the single source of PostgreSQL literal escaping, and route both `quoteStringPostgreSQL` and the predicate-pushdown visitor through it so they cannot drift apart. Quote each column name individually instead of `join(columns, "','")`. The PostgreSQL *wire* `writeQuotedStringPostgreSQL` is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 9 out of 9 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (2)
src/IO/WriteHelpers.h:599
- The comment says
writeQuotedStringPostgreSQLis a “wire-format” helper, but it actually produces a plain'...'SQL literal (with quote-doubling and without doubling backslashes). This wording is confusing and may lead to using the wrong function when constructing SQL for PostgreSQL.
/// a query sent to a PostgreSQL server on every server configuration. Use this (not the wire-format
/// `writeQuotedStringPostgreSQL` above) when building SQL for PostgreSQL — a plain `'...'` literal
/// that doubles only the quote is unsafe when `standard_conforming_strings` is off.
src/Common/FieldVisitorToString.h:45
- The doc comment’s examples for PostgreSQL escaping omit the
Eprefix and make the backslash-doubling unclear, but the implementation emitsE'...'escape-string constants (via writeQuotedStringPostgreSQLLiteral). Updating the examples would make the behavior unambiguous.
/** Same as FieldVisitorToString, but escapes string literals for a PostgreSQL source and
* recurses into containers with the same escaping. Strings are emitted as an E'...' escape-string
* constant with both the single quote and the backslash doubled ('a''b', 'a\\b'). This is safe
* irrespective of the remote session's standard_conforming_strings: in an E'' constant PostgreSQL
* always treats backslash as an escape character, so no embedded byte can terminate the literal.
| /// a query sent to a PostgreSQL server on every server configuration. Use this (not the wire-format | ||
| /// `writeQuotedStringPostgreSQL` above) when building SQL for PostgreSQL — a plain `'...'` literal | ||
| /// that doubles only the quote is unsafe when `standard_conforming_strings` is off. | ||
| inline void writeQuotedStringPostgreSQLLiteral(std::string_view ref, WriteBuffer & buf) |
There was a problem hiding this comment.
The new helper makes PostgreSQL literals independent of standard_conforming_strings, but the PostgreSQL dictionary predicate builder still uses the old plain-literal writer. Runtime dictionary keys flow through ExternalQueryBuilder::composeKeyCondition / SerializationString::serializeTextQuoted, which calls writeQuotedStringPostgreSQL: quotes are doubled but backslashes remain unchanged. With standard_conforming_strings = off, a key containing a backslash followed by a quote can still terminate the generated predicate.
Please give PostgreSQL dictionary builders a PostgreSQL-specific literal mode that uses writeQuotedStringPostgreSQLLiteral (or parameters), without changing the shared behavior for Cassandra and other double-quoted-identifier backends.
There was a problem hiding this comment.
Done — added a PostgreSQL-specific literal mode (new escape_string_for_postgresql format setting, selected via LiteralEscapingStyle::PostgreSQL) so PG dictionary predicates emit E'...' via writeQuotedStringPostgreSQLLiteral; Cassandra and other double-quoted-identifier backends keep the '' behavior. (commit 9a91ad2)
…ction paths - checkPostgresTable: quote regclass/schema/tablename via quoteStringPostgreSQL - fetchPostgreSQLTableStructure: quote the empty-schema table identifier - PostgreSQL dictionary predicates: emit E'...' literals (new escape_string_for_postgresql) - MaterializedPostgreSQL: quote publication_name literals in catalog lookups + publication_names - gtest: also exercise the modern analyzer path Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 174/180 (96.67%) · Uncovered code |
| "ORDER BY attnum ASC", generated, where, columns_part); /// Now we use variable `generated` to form query string. End of trick. | ||
|
|
||
| auto postgres_table_with_schema = postgres_schema.empty() ? postgres_table : doubleQuoteString(postgres_schema) + '.' + doubleQuoteString(postgres_table); | ||
| auto postgres_table_with_schema = postgres_schema.empty() ? doubleQuoteString(postgres_table) : doubleQuoteString(postgres_schema) + '.' + doubleQuoteString(postgres_table); |
There was a problem hiding this comment.
The identifier quoting is correct, but it also changes user-visible diagnostics because postgres_table_with_schema is reused in exception messages. Three integration tests now fail consistently across ASan, TSan, MSan, ARM, and coverage builds: test_postgres_array_ndim_error_messges, test_parameters_validation_for_postgresql_function, and test_add_new_table_to_replication.
Please either update those assertions to expect the quoted identifier or keep a separate unquoted display name while retaining this quoted value for SQL construction.
| /// which is safe on every server configuration. Other SQL-standard, double-quoted-identifier backends | ||
| /// (Cassandra, etc.) treat `\` as a literal character, so `''` doubling is enough for them. | ||
| if (literal_escaping_style_ == LiteralEscapingStyle::PostgreSQL) | ||
| format_settings.values.escape_string_for_postgresql = true; |
There was a problem hiding this comment.
Please add focused coverage for this new PostgreSQL mode. The existing gtest_external_query_builder.cpp helper constructs only the default Regular mode, so no test would fail if PostgreSQLDictionarySource stopped selecting this branch or if quote/backslash handling regressed. A small test should pass LiteralEscapingStyle::PostgreSQL and assert E'...' output for a quote, a backslash, and backslash-plus-quote.
|
Un-assigning myself because I'll be out for a few months and I don't want to block the PR |
master absorbed this branch's original subject - container literals in predicates pushed down to PostgreSQL - through ClickHouse#104217, which generalized the escaping to both the PostgreSQL and SQLite dialects: `FieldVisitorToStringForDialect` recurses through the dialect visitor and rejects outright the literals PostgreSQL cannot parse, and `writeQuotedStringPostgreSQLLossless` replaced this branch's `writeQuotedStringPostgreSQLLiteral`. That implementation is the better one, so all four conflicts take it wholesale - `src/IO/WriteHelpers.h`, `src/Parsers/ASTLiteral.cpp`, `src/Parsers/LiteralEscapingStyle.h` and `src/Storages/tests/gtest_transform_query_for_external_database.cpp` - and the duplicate `FieldVisitorToStringPostgreSQL` this branch had in `src/Common/FieldVisitorToString.{h,cpp}` goes with them. What remains is the sinks master still has: SQL literals in the metadata and replication queries. `quoteStringPostgreSQL` now routes through master's lossless helper rather than doubling only the quote, which is what `checkPostgresTable`, the requested column names and the publication name are quoted with. The dictionary-source `E'...'` hardening is dropped as well (`FormatSettings::escape_string_for_postgresql` and the three serializations, `ExternalQueryBuilder`, `PostgreSQLDictionarySource`). master's `ExternalQueryBuilder` already sets `escape_quote_with_quote` for the PostgreSQL quoting style, so that source is safe under the default `standard_conforming_strings`; what was here on top only covered `standard_conforming_strings = off`, at the price of a new `FormatSettings` field and three shared serialization paths, which is not worth carrying on a change that has to be backported. Adds the regression coverage the metadata sinks had none of: a gtest pinning `quoteStringPostgreSQL`, and an integration test asserting that a `schema` payload is not executed by PostgreSQL. The latter is load-bearing - with `DatabasePostgreSQL.cpp` reverted to master it fails on the marker table the payload really does create.
Cherry pick #111516 to 26.3: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
…eries via unescaped schema, column and publication names
Cherry pick #111516 to 26.6: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
…eries via unescaped schema, column and publication names
Cherry pick #111516 to 26.7: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
…eries via unescaped schema, column and publication names
Cherry pick #111516 to 26.8: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
…eries via unescaped schema, column and publication names
|
@tiandiwonder @antonio2368 — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Backport #111516 to 26.6: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
Backport #111516 to 26.8: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
Backport #111516 to 26.3: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
Backport #111516 to 26.7: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
Problem
ClickHouse builds the PostgreSQL metadata queries it uses for introspection by formatting names
into single-quoted SQL literals. Several of those names are user-controlled and were interpolated
without escaping, so a value containing
'closes the literal. Those queries run in apqxx::nontransaction, i.e. over the libpq simple-query protocol, which executes;-separatedstatements, so whatever follows in such a value is executed by the PostgreSQL server as the role
ClickHouse connects with.
The one reachable at pure defaults is the
schemaof thePostgreSQLdatabase engine.schemaisoverridable on a named collection by default, so a user granted only
CREATE DATABASE, use of thecollection and the
POSTGRESsource reaches it with noCREATE TABLEand noINSERT— anarbitrary-SQL channel the engine's sanctioned interface (read-only flat-table mapping) offers at no
grant level. The blast radius is the privileges of the PostgreSQL account stored in the collection.
Root cause
Four sinks composed SQL from an unescaped name:
DatabasePostgreSQL::checkPostgresTableformattedformatTableName(table_name)into'{}'::regclassandtablename = '{}'.formatTableNamewraps the parts withdoubleQuoteString, which escapes"and not', and it prefixesconfiguration.schema, whichis not validated anywhere (only
table_nameis'/\-rejected). The same statement also builtschemaname =withquoteString, whose backslash escaping (\') does not escape the quoteunder the default
standard_conforming_strings, so the'still terminates the literal.fetchPostgreSQLTableStructurebuiltattname IN ('{}')fromboost::algorithm::join(columns, "','"), interpolating every requested column name unquoted.PostgreSQLReplicationHandlerandMaterializedPostgreSQLConsumerformattedpublication_nameinto
pubname = '{}'and into thepublication_namesoption. The publication name is derivedfrom the database, schema and table names.
PostgreSQLReplicationHandler::loadFromSnapshotformatted the snapshot id intoSET TRANSACTION SNAPSHOT '{}'. That is not always PostgreSQL's own id fromCREATE_REPLICATION_SLOT: with a user-managed slot it is thematerialized_postgresql_snapshotsetting verbatim.quoteStringPostgreSQL, the helper the surrounding code already used for the schema and tablenames, only doubled the quote. That is enough under the default
standard_conforming_strings, butwith it off a backslash before the quote escapes the first quote of the
''pair and the literalstill ends early — the same class again, one configuration away.
This completes CVE-2025-1520 (#74144), whose fix introduced PostgreSQL-specific escaping but
applied it to the predicate-pushdown and structure-fetch paths only. The predicate-pushdown half of
that class was finished separately in #104217, which generalized the escaping to both PostgreSQL
and SQLite dialects; this pull request covers the metadata and replication queries it did not
touch.
Solution
quoteStringPostgreSQLthroughwriteQuotedStringPostgreSQLLossless, the helper Fix SQLite WHERE predicate pushdown for strings with special characters #104217added: the value is emitted so PostgreSQL reads back exactly those bytes on every server
configuration — a plain literal with the quote doubled when no byte needs a backslash escape, and
an
E'...'escape-string constant, where the backslash is doubled too, when one does. One helperis now the single source of PostgreSQL literal escaping for both the pushed-down predicates and
the metadata queries, so the two cannot drift apart again. The wire-format
writeQuotedStringPostgreSQL, shared with the PostgreSQL output format, is unchanged.regclassinput, the schema and the table name incheckPostgresTablewith it, insteadof interpolating them into hand-written
'...'literals.fetchPostgreSQLTableStructure(
attname IN ('c1', 'c2')) instead of joining them unquoted. Also double-quote the tableidentifier in the empty-schema branch, the one path that passed it into
FROM {}raw. Whichtables resolve does not change: the branch with a schema has always double-quoted both parts, and
the structure query itself matches
relnameagainst the name as a literal, so the exact case wasalready required.
publication_nameat the four catalog lookups that embedded it as a literal.SET TRANSACTION SNAPSHOT. Unlike the sinks above, an injection here isnot demonstrated: a payload whose first statement succeeds and whose side effect survives the
rollback of the transaction
loadFromSnapshotnever commits still did not execute on an unfixedbuild, apparently because
SET TRANSACTION SNAPSHOThas to be the first statement of itstransaction and its failure aborts the whole batch. So this one is here as the malformed-input fix
it can be shown to be — a quote in the setting now yields an invalid snapshot id rather than a
confusing SQL error — and it comes with no test, since a test that passes unfixed would assert
nothing.
fetchPostgreSQLTableStructureused a single string for both, so double-quoting the identifierwould have changed the error messages that name the relation;
postgres_table_for_messageskeepsthe spelling from before it was quoted.
schemais escaped rather than rejected the waytable_nameis: PostgreSQL identifiers maylegitimately contain a quote, and escaping keeps those usable while removing the sink.
Test
tests/integration/test_postgresql_database_engine/test.py::test_postgresql_database_engine_schema_sql_injection— overrides the collection's
schemawith a value whose payload creates a marker table, thenasserts the marker does not exist in PostgreSQL. The assertion is the absence of a side effect the
unfixed server really produces, so it fails on an unfixed build rather than only observing a
different error message.
src/Common/tests/gtest_quote_string.cpppinsquoteStringPostgreSQL: the quote is alwaysdoubled, a backslash switches to the
E'...'form and is doubled there, and a backslash before aquote cannot escape it.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a SQL injection in the PostgreSQL metadata queries. The
schemaof thePostgreSQLdatabase engine, the requested column names and the publication name were formatted into SQL literals without escaping, so a value containing a quote could execute arbitrary SQL on the connected PostgreSQL server as the role ClickHouse connects with. Reaching it throughschemaneeded onlyCREATE DATABASEplus use of a named collection whoseschemais overridable.Workflow [PR]
Sync PR [sync-upstream/pr/111516]
Version info
26.8.3.70,26.7.7.61,26.6.5.86,26.3.33.25