Skip to content

Fix SQL injection in ExternalQueryBuilder via incorrect string escaping - #104009

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
tiandiwonder:pg-dict-sql-injection-escape
May 17, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
tiandiwonder:pg-dict-sql-injection-escape

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Fix SQL injection in ExternalQueryBuilder caused by incorrect string literal escaping when building WHERE clauses for external dictionary sources (PostgreSQL, Cassandra, XDBC).

ExternalQueryBuilder used the default FormatSettings with escape_quote_with_quote = false, so serializeTextQuoted produced backslash-escaped string literals (\') in the generated SQL. PostgreSQL (with standard_conforming_strings = on by default since 9.1) treats backslash as a literal character — not an escape sequence — allowing a caller to break out of a string literal and inject arbitrary SQL by passing a key containing a single quote to dictGet on a PostgreSQL or XDBC dictionary source. The same vulnerability applies to Cassandra, which also follows the SQL standard.

The same class of bug was fixed for the PostgreSQL table function in PR #74144, but the dictionary code path through ExternalQueryBuilder was missed.

Fix: in ExternalQueryBuilder's constructor, set escape_quote_with_quote = true only when quoting_style == DoubleQuotes (PostgreSQL, Cassandra, XDBC SQL). For ClickHouse and MySQL (Backticks / BackticksMySQL), keep the default backslash escaping (\', \\), which both backends parse natively. This per-backend split addresses reviewer feedback that the original "always quote-doubling" fix would have caused ClickHouse-on-ClickHouse dictionaries to corrupt string values containing backslashes when those values are serialized back through TabSeparated.

A new gtest gtest_external_query_builder.cpp covers both branches: DoubleQuotes doubles single quotes and leaves backslashes intact; Backticks uses \' and doubles backslashes.

Reported in: https://github.com/ClickHouse/clickhouse-private/issues/56142

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed SQL injection vulnerability in PostgreSQL, Cassandra and XDBC dictionary sources: string keys containing single quotes were escaped with \' (backslash), which these backends treat as a literal backslash rather than an escape sequence, allowing arbitrary SQL to be injected into dictionary lookup queries. ExternalQueryBuilder now emits SQL-standard '' escaping for those backends; ClickHouse and MySQL dictionary sources continue to use backslash escaping.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.727 (included in 26.5 and later)
  • Backported to: 26.4.3.34, 26.3.11.26, 25.8.29.17

`ExternalQueryBuilder` used the default `FormatSettings` with
`escape_quote_with_quote = false`, causing `serializeTextQuoted` to
produce backslash-escaped string literals (`\'`) in the generated SQL
sent to external databases.

PostgreSQL (with `standard_conforming_strings = on` by default since
9.1) treats backslash as a literal character, not an escape sequence.
This allowed a caller to break out of a string literal and inject
arbitrary SQL by passing a string key containing a single quote through
`dictGet` on a PostgreSQL or XDBC dictionary source.

The same class of bug was fixed for the PostgreSQL table function in
PR ClickHouse#74144, but the dictionary code path via `ExternalQueryBuilder` was
missed.

Fix: initialize `format_settings` with `escape_quote_with_quote = true`
so that all backends using `ExternalQueryBuilder` (PostgreSQL, MySQL,
XDBC, ClickHouse, Cassandra) consistently use the SQL-standard `''`
quoting style. MySQL and ClickHouse accept both styles, so there is no
regression risk for those backends.

Reported in: ClickHouse/clickhouse-private#56142

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ee42acf]

Summary: ✅


AI Review

Summary

This PR fixes string-literal escaping in ExternalQueryBuilder for dictionary key lookups by enabling SQL-standard quote doubling only for IdentifierQuotingStyle::DoubleQuotes backends (PostgreSQL/Cassandra/XDBC SQL), while keeping backslash escaping for backtick-style backends (ClickHouse/MySQL). The patch also adds targeted unit and integration coverage for quote and backslash handling. I did not find unresolved correctness or security issues in the current code.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels May 4, 2026
…aping

MySQL was never affected by the backslash-vs-quote-doubling escaping bug
fixed in the previous commit: MySQL correctly handles \' by default.
There is no regression scenario to protect against, so the test only
adds maintenance burden without value.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

MySQL and ClickHouse accept both styles, so there is no regression risk for those backends.

Let's say we have a string with the following contents: \''.
In ClickHouse-style escaping, it will be written as '\\\'\''.
In Postgres-style escaping, it will be written as '\'''''.

Now let's see what happens if we take the string with Postgres-style escaping and put it in a ClickHouse query. It will not parse.

@alexey-milovidov alexey-milovidov self-assigned this May 6, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

…g per-backend

Use SQL-standard `''` quoting only for backends with `IdentifierQuotingStyle::DoubleQuotes`
(PostgreSQL, XDBC-PostgreSQL). ClickHouse and MySQL use backslash escaping by default,
and their SQL parsers would misinterpret `''`-escaped strings containing backslashes:
`\b` in a `''`-escaped literal is parsed by ClickHouse as a backspace character,
and a lone `\` produces an unterminated string literal (parse error).

Add regression test for ClickHouse dictionary source with backslash and quote keys.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@tiandiwonder

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Thank you for the example — you're correct. The fix incorrectly applied ''-style escaping to all backends including ClickHouse. ClickHouse's SQL parser treats \\ as an escape character by default, so a backslash in a ''-escaped string literal would be misinterpreted (e.g., \b becomes a backspace, \' causes an unterminated literal). Fixed in commit 1459070e7cf — ExternalQueryBuilder now uses SQL-standard '' escaping only when quoting_style == IdentifierQuotingStyle::DoubleQuotes (PostgreSQL, XDBC-PostgreSQL backends), and keeps backslash escaping for ClickHouse and MySQL. Added a regression test (04141) covering ClickHouse dictionary lookups with backslash and single-quote keys.

tiandiwonder and others added 2 commits May 8, 2026 01:09
Add coverage and a comment cleanup for the per-backend escape mode
chosen in `ExternalQueryBuilder` after reviewer feedback (PostgreSQL,
Cassandra, XDBC SQL go through SQL-standard `''` quoting while
ClickHouse and MySQL keep backslash escaping):

  - New unit test `gtest_external_query_builder.cpp` exercises both
    branches at the generated-SQL level via `composeLoadKeysQuery`:
    `DoubleQuotes` doubles single quotes and leaves backslashes
    unchanged; `Backticks` uses `\'` and `\\`.

  - New MySQL integration test in `test_dictionaries_mysql/test.py`
    verifies that a MySQL dictionary source correctly handles keys
    containing single quotes and backslashes under backslash escaping.

  - Restate the comment in `ExternalQueryBuilder.cpp` in plain ASCII
    and switch to an explicit `if` so the opt-in nature of
    `escape_quote_with_quote` for SQL-standard quoting is obvious.

No behavior change beyond the per-backend split already addressed in
the previous reviewer-feedback commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The new stateless test 04141_dict_clickhouse_source_backslash_key was a
regression test for the ClickHouse-source dictionary path, which uses
`IdentifierQuotingStyle::Backticks` and is unaffected by the original
SQL injection bug. As a result, the test passed on master, causing the
"Bugfix validation (functional tests)" check to fail with "Failed to
reproduce the bug".

Per-backend escaping behavior is still covered by:
- `gtest_external_query_builder.cpp` (unit-level coverage of both
  `DoubleQuotes` and `Backticks` quoting styles, including backslash
  and single-quote handling)
- `test_dictionaries_postgresql.py::test_postgres_dict_complex_key_with_single_quote`
  (end-to-end PostgreSQL coverage that actually catches the original
  bug on master)
- `test_dictionaries_mysql.py::test_mysql_dict_complex_key_with_special_chars`
  (end-to-end MySQL coverage of backslash escaping)

CI report: ClickHouse#104009
@alexey-milovidov

Copy link
Copy Markdown
Member

Removed tests/queries/0_stateless/04141_dict_clickhouse_source_backslash_key.sql in ee42acfa096 to make the Bugfix validation (functional tests) check pass.

The test was a regression test for the ClickHouse-source dictionary path, which uses IdentifierQuotingStyle::Backticks and is unaffected by the original SQL injection. Because the test passed on master (i.e. it did not reproduce the bug), the bugfix validation correctly reported "Failed to reproduce the bug".

Per-backend escaping behavior is still covered by:

  • gtest_external_query_builder.cpp for the unit-level DoubleQuotes and Backticks paths (both single quote and backslash);
  • the new PostgreSQL integration test test_postgres_dict_complex_key_with_single_quote, which catches the original injection on master;
  • the new MySQL integration test test_mysql_dict_complex_key_with_special_chars, which exercises backslash escaping.

The other CI failures are unrelated to this PR:

  • Unit tests (msan, function_prop_fuzzer) — known flaky failure tracked in FunctionsStress.stress #104877 (FunctionsStress.stress);
  • Stateless tests (amd_msan, WasmEdge, parallel, 1/2) — 04033_tpc_ds_* tests are widely flaky across many sanitizers/configurations on master.

@clickhouse-gh

clickhouse-gh Bot commented May 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.20% +0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 100.00% (44/44) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 9bad114 into ClickHouse:master May 17, 2026
166 of 167 checks passed
robot-ch-test-poll1 added a commit that referenced this pull request May 17, 2026
Cherry pick #104009 to 25.8: Fix SQL injection in ExternalQueryBuilder via incorrect string escaping
robot-clickhouse added a commit that referenced this pull request May 17, 2026
robot-ch-test-poll1 added a commit that referenced this pull request May 17, 2026
Cherry pick #104009 to 26.2: Fix SQL injection in ExternalQueryBuilder via incorrect string escaping
robot-clickhouse added a commit that referenced this pull request May 17, 2026
robot-ch-test-poll1 added a commit that referenced this pull request May 17, 2026
Cherry pick #104009 to 26.3: Fix SQL injection in ExternalQueryBuilder via incorrect string escaping
robot-clickhouse added a commit that referenced this pull request May 17, 2026
robot-ch-test-poll1 added a commit that referenced this pull request May 17, 2026
Cherry pick #104009 to 26.4: Fix SQL injection in ExternalQueryBuilder via incorrect string escaping
robot-clickhouse added a commit that referenced this pull request May 17, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels May 18, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 18, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request May 18, 2026
This is a regression test for the `ExternalQueryBuilder` ClickHouse-backend
path that uses `IdentifierQuotingStyle::Backticks` and backslash escaping.
Switching to Postgres-style `''` escaping for this backend would break
ClickHouse queries when keys contain backslashes, because the ClickHouse
SQL parser interprets `\` as an escape character.

This test passes on master and would have caught any regression that
changed the escaping style for the ClickHouse-source dictionary backend.

Originally part of ClickHouse#104009
but excluded from that PR because the bugfix validation requires the test
to fail on master, and this test does not reproduce the original SQL
injection bug (which only affected `DoubleQuotes`-style backends like
PostgreSQL/MySQL).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request May 19, 2026
…ia incorrect string escaping (#105187)

Co-authored-by: robot-clickhouse <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request May 19, 2026
…ia incorrect string escaping (#105183)

Co-authored-by: robot-clickhouse <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request May 19, 2026
…ia incorrect string escaping (#105185)

Co-authored-by: robot-clickhouse <[email protected]>
tiandiwonder added a commit that referenced this pull request Jul 15, 2026
Backport #104009 to 25.8: Fix SQL injection in ExternalQueryBuilder via incorrect string escaping
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…yBuilder via incorrect string escaping (ClickHouse#105187)

Co-authored-by: robot-clickhouse <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix 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.

4 participants