Skip to content

Cherry pick #111516 to 26.8: Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names - #118752

Merged
robot-ch-test-poll2 merged 11 commits into
backport/26.8/111516from
cherrypick/26.8/111516
Sep 8, 2026
Merged

robot-ch-test-poll2 merged 11 commits into
backport/26.8/111516from
cherrypick/26.8/111516

Conversation

@robot-ch-test-poll2

Copy link
Copy Markdown
Contributor

Original pull-request #111516

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-pick locally.
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.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

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:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

tiandiwonder and others added 10 commits July 23, 2026 02:09
…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]>
…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]>
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]>
…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]>
master absorbed this branch's original subject - container literals in
predicates pushed down to PostgreSQL - through #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.
…amed column list

`SET TRANSACTION SNAPSHOT` was the one PostgreSQL literal left built by hand. Its value is not
always PostgreSQL's own snapshot id from `CREATE_REPLICATION_SLOT`: on the user-managed-slot path
it is `materialized_postgresql_snapshot` verbatim, so it goes through `quoteStringPostgreSQL` like
the rest. No test comes with it - one was written and then dropped because it passed on an unfixed
build: with the payload's first statement made to succeed and the side effect chosen to survive the
rollback of the transaction `loadFromSnapshot` never commits, the injected statement still did not
run, so the reachable consequence at this sink looks like a confusing SQL error on a malformed
snapshot id rather than remote SQL execution.

Quoting the table identifier for the empty-schema branch also changed three error messages, because
`fetchPostgreSQLTableStructure` reused one string for both the SQL it sends and the relation name it
shows. Split them: `postgres_table_for_messages` keeps the spelling from before the identifier was
quoted, so `test_postgres_array_ndim_error_messges`,
`test_parameters_validation_for_postgresql_function` and `test_add_new_table_to_replication` see the
diagnostics they assert on.

Build the quoted column list by streaming into a buffer instead of collecting a vector of quoted
copies, which also retires this file's only use of `boost::algorithm::join`.
…-escape

Fix SQL injection in PostgreSQL metadata queries via unescaped schema, column and publication names
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-critical-bugfix labels Sep 8, 2026
…ypick/26.8/111516

# Conflicts:
#	tests/integration/test_postgresql_database_engine/test.py
@robot-ch-test-poll2
robot-ch-test-poll2 merged commit 2550526 into backport/26.8/111516 Sep 8, 2026
1 check passed
@robot-ch-test-poll2
robot-ch-test-poll2 deleted the cherrypick/26.8/111516 branch September 8, 2026 10:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! pr-critical-bugfix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants