Skip to content

Fix SQL injection in MySQL wire protocol replacement queries - #108474

Merged
CheSema merged 2 commits into
ClickHouse:masterfrom
groeneai:mysql-handler-replacement-query-injection
Jul 7, 2026
Merged

CheSema merged 2 commits into
ClickHouse:masterfrom
groeneai:mysql-handler-replacement-query-injection

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 MySQL wire protocol: the SHOW TABLE STATUS LIKE argument and the SET <mysql_setting> value sent over the MySQL interface (port 9004) are now parsed and re-quoted instead of being concatenated verbatim into the rewritten query. Also fixed KILL QUERY <id> over the MySQL interface silently ignoring multi-digit connection ids.

Description

MySQLHandler rewrites a few MySQL-wire client commands into ClickHouse SQL. The rewrites concatenated the raw client-supplied suffix into the generated query with no parsing or escaping, so an authenticated MySQL-wire client could inject SQL. The injection runs under the caller's own grants (no privilege escalation), but it bypasses the intended read scope of these helpers.

showTableStatusReplacementQuery appended the SHOW TABLE STATUS LIKE argument directly after ... WHERE name LIKE . This let a client inject an arbitrary tail and read any table instead of the intended system.tables-only lookup, e.g.:

SHOW TABLE STATUS LIKE '' UNION ALL SELECT name, ... FROM system.users --

returned rows from system.users. The argument is now parsed as a single string literal and re-quoted with quoteString(); anything that is not exactly one string literal matches nothing.

setSettingReplacementQuery concatenated the SET value tail, so SET SQL_SELECT_LIMIT=1, max_threads=42 became SET limit=1, max_threads=42 and set unrelated settings. The value is now parsed (= <literal|DEFAULT>) and re-serialized; once the SET <mysql_setting> prefix matches, the handler always emits a sanitized replacement and never executes the raw client text.

killConnectionIdReplacementQuery used ^[0-9] with RE2::FullMatch, which required the whole id to match a single digit, so every multi-digit connection id (e.g. KILL QUERY 12) was silently not translated. Tightened to ^[0-9]+$, which accepts multi-digit ids and still rejects any non-numeric tail.

A regression test (tests/integration/test_mysql_protocol/test.py::test_mysql_replacement_query_injection) is added: it fails on the previous behavior (leaks system.users) and passes with this fix, while the benign SHOW TABLE STATUS LIKE, SET, and KILL QUERY paths keep working.

Version info

  • Merged into: 26.7.1.580 (included in 26.7 and later)
  • Backported to: 26.6.8.6, 26.3.33.93

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a clean build with <mysql_port>9004</mysql_port>, SHOW TABLE STATUS LIKE '' UNION ALL SELECT name,... FROM system.users over the MySQL wire returns system.users rows every time; SET SQL_SELECT_LIMIT=1, max_threads=42 sets max_threads=42 every time; KILL QUERY 12 errors with SYNTAX_ERROR every time.
b Root cause explained? The replacement helpers in MySQLHandler.cpp build ClickHouse SQL by concatenating the raw client suffix. showTableStatusReplacementQuery appends the LIKE arg after WHERE name LIKE , so a '' UNION SELECT ... tail becomes part of the executed query. setSettingReplacementQuery appends the SET value tail verbatim, so extra , setting=value assignments execute. killConnectionIdReplacementQuery's ^[0-9] under FullMatch only matches a single digit, dropping multi-digit ids.
c Fix matches root cause? Yes. Each site now parses the client argument (single string literal for LIKE; = <literal|DEFAULT> for the setting value) and re-serializes it with quoteString() / FieldVisitorToString, so client text can never reach the executed query unquoted. The KILL regex is anchored to ^[0-9]+$.
d Test intent preserved / new tests added? New regression test test_mysql_replacement_query_injection added; the existing test_mysql_replacement_query is unchanged and still passes. The new test asserts no system.users leak, no unrelated-setting injection, and that benign SHOW/SET/KILL still work.
e Both directions demonstrated? Yes, via the integration test. On the unmodified binary it FAILS: AssertionError: SHOW TABLE STATUS LIKE injection leaked system.users: ['default', 'user_with_double_sha1', ...]. On the fixed binary it PASSES (test_mysql_replacement_query + test_mysql_replacement_query_injection, 2 passed).
f Fix is general across code paths? Yes. All three replacement helpers that concatenated raw client input are fixed. The other replacement functions (showWarnings, showCountWarnings, selectEmpty, showCollations) return constant queries and ignore client input, so they were never injectable.
g Fix generalizes across inputs? Yes. The LIKE fix handles plain, escaped-quote (a\'b), empty, and wildcard literals, and rejects non-literals (matches nothing). The SET fix handles integer/string/DEFAULT values (incl. max UInt64 that connectors send) and resets only the mapped setting on malformed input. The KILL fix handles single- and multi-digit ids and rejects any non-numeric tail.
h Backward compatible? Yes. Benign client commands behave identically (verified: SET NET_WRITE_TIMEOUT=77 -> send_timeout=77; SET SQL_SELECT_LIMIT=DEFAULT/numeric OK; SHOW TABLE STATUS LIKE 'tbl' unchanged). The only behavior change is that malformed/injecting input is now rejected. No settings, formats, or on-disk data are affected.
i Invariants and contracts preserved? Yes. The helpers still return a single valid ClickHouse query string; IParserBase::parse restores the token position on failure, so failed parse attempts do not leave a half-consumed stream. Parser objects are stack-local with no shared state. The MySQL session/grant model is unchanged.

Session id: cron:clickhouse-worker-slot-3:20260625-113800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @yakov-olkhovskiy — could you review this? It fixes SQL injection in the MySQL-wire replacement queries (MySQLHandler.cpp): the SHOW TABLE STATUS LIKE argument and the SET <mysql_setting> value were concatenated into the rewritten query verbatim; they are now parsed and re-quoted with quoteString()/FieldVisitorToString. Also tightens KILL QUERY <id> (^[0-9] -> ^[0-9]+$) so multi-digit ids translate. Runs under the caller's grants (no privilege escalation). Regression test included.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [da02224]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Stress test (arm_debug) FAIL
Cannot start clickhouse-server FAIL cidb
Logical error: 'Unexpected exception in refresh scheduling' (STID: 2508-34af) FAIL cidb
Check failed FAIL cidb

AI Review

Summary
  • The PR fixes SQL injection in MySQL wire replacement queries by parsing and re-quoting the client-controlled SHOW TABLE STATUS LIKE pattern and mapped SET values, and it fixes multi-digit KILL QUERY connection ids. The added integration coverage exercises the original injection paths, malformed tails, optional single-statement terminators, setting-name boundaries, and missing-separator cases. I did not find any remaining blocker or major issue in the current diff; the prior bot review threads are addressed by the current code.
Final Verdict
  • Status: ✅ Approve

@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/MySQLHandler.cpp Resolved
@groeneai
groeneai force-pushed the mysql-handler-replacement-query-injection branch from 7ec66d7 to 6d9415a Compare June 25, 2026 14:14
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 6d9415a. setSettingReplacementQuery now verifies a word boundary after the mapped setting name before producing any replacement: if the next character continues an identifier (isWordCharASCII), the query is left untranslated and falls through to normal execution, where it errors as an unknown setting. The malformed-value fallback now only applies to the exact mapped setting.

So SET SQL_SELECT_LIMITED=1 no longer touches limit. Confirmed both directions on a local debug build: without the boundary check it accepts SQL_SELECT_LIMITED and resets limit (changed 1 to 0); with it, limit stays untouched and the variable is rejected. Added an SQL_SELECT_LIMITED case to test_mysql_replacement_query_injection covering this; the integration test passes.

Comment thread src/Server/MySQLHandler.cpp Resolved
@groeneai
groeneai force-pushed the mysql-handler-replacement-query-injection branch from 6d9415a to c15d4b5 Compare June 25, 2026 15:01
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both sanitized parsers now accept one optional trailing TokenType::Semicolon before end-of-stream, so SHOW TABLE STATUS LIKE 'one'; returns the table and SET SQL_SELECT_LIMIT=2; sets limit to 2. A second statement after the ; still leaves the parser before end-of-stream, so it is rejected and the injection protection is intact.

Added pymysql regression cases in test_mysql_replacement_query_injection: the terminator is accepted for both SHOW TABLE STATUS LIKE 'one'; and SET SQL_SELECT_LIMIT=2;, plus negative cases proving SHOW TABLE STATUS LIKE '' ; UNION ... FROM system.users and SET SQL_SELECT_LIMIT=1, max_threads=42; are still blocked. Verified both directions on a local debug build (the previous strict end-of-stream check turned LIKE 'one'; into an empty pattern and SET SQL_SELECT_LIMIT=2; into SET limit = DEFAULT).

Comment thread src/Server/MySQLHandler.cpp Resolved
Comment thread src/Server/MySQLHandler.cpp Resolved
@groeneai
groeneai force-pushed the mysql-handler-replacement-query-injection branch from c15d4b5 to 4b6aa2b Compare June 25, 2026 19:22
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both addressed in 4b6aa2b44e9:

  • setSettingReplacementQuery no longer has a state-changing fallback. It throws a syntax error unless the full tail is exactly = <literal|DEFAULT> plus an optional single trailing ;, so a rejected input (e.g. SET SQL_SELECT_LIMIT=1, max_threads=42) never resets limit and the raw tail is never executed.
  • killConnectionIdReplacementQuery now matches ^\s*([0-9]+)\s*;?\s*$ and substitutes only the captured digits, so KILL QUERY 12; translates while a non-numeric tail or a second statement still fails the match.

Regression cases added in test_mysql_replacement_query_injection: the injected SET tail (with and without trailing ;) is rejected and leaves both limit and max_threads unchanged, KILL QUERY 12; translates, and KILL QUERY 12; SELECT 1 is rejected. Verified the rejected-SET-resets-limit and KILL QUERY 12;-syntax-error behaviors reproduce on the pre-fix binary and are gone after. test_mysql_replacement_query and test_mysql_replacement_query_injection both pass.

Comment thread src/Server/MySQLHandler.cpp Resolved
The MySQL handler rewrites a few client commands into ClickHouse SQL by
concatenating the raw client-supplied suffix into the replacement query
without parsing or escaping it. An authenticated MySQL-wire client could
inject SQL:

- showTableStatusReplacementQuery concatenated the SHOW TABLE STATUS LIKE
  argument after "WHERE name LIKE ", so "" UNION SELECT ... FROM system.users
  read arbitrary tables instead of the intended system.tables-only lookup.
- setSettingReplacementQuery concatenated the SET value tail, so
  "SET SQL_SELECT_LIMIT=1, max_threads=42" set unrelated settings.

Both now parse the client argument (a single string literal for the LIKE
pattern; "= <literal|DEFAULT>" for the setting value) and re-serialize it
with quoteString()/FieldVisitorToString instead of concatenating raw input.
The injection runs under the caller's own grants, so there is no privilege
escalation, but it bypasses the intended read scope.

checkShouldReplaceQuery is only a byte-prefix check, so the setting name in
setSettingReplacementQuery is now checked for a word boundary before the
sanitized replacement is produced. Otherwise a longer variable that merely
starts with a mapped name (e.g. "SET SQL_SELECT_LIMITED=1" vs the mapped
"SET SQL_SELECT_LIMIT") would be translated and silently reset the unrelated
"limit" setting; it now passes through untranslated and errors as an unknown
setting.

The sanitized parsers accept one optional trailing ';' followed by
end-of-stream. executeQuery treats ';' as end-of-query, so a benign
programmatic client may send "SHOW TABLE STATUS LIKE 'one';" or
"SET SQL_SELECT_LIMIT=2;" (the mysql CLI strips the terminator, but other
clients pass it through). Requiring a strict end-of-stream broke those
benign inputs. A second statement after the ';' still leaves the parser
before end-of-stream and is rejected, so the injection protection is intact.

setSettingReplacementQuery no longer has a state-changing fallback on a
malformed value. The previous "reset the mapped setting to DEFAULT" fallback
silently changed the caller's session setting (and reported success) when the
tail was not exactly "= <literal|DEFAULT>" with an optional single ';' (for
example "SET SQL_SELECT_LIMIT=1, max_threads=42" parses the "1", stops at the
comma, and reset "limit"). It now throws a syntax error in that case, so the
session setting is never changed as a side effect of a rejected input and the
raw tail is never executed.

killConnectionIdReplacementQuery used the regex "^[0-9]+$", which rejected a
benign single-statement terminator: "KILL QUERY 12;" left the suffix "12;",
failed the match, and fell through to the raw "KILL QUERY 12;" that ClickHouse
does not support. The connection id is now captured with "^\s*([0-9]+)\s*;?\s*$"
(one optional trailing ';' and surrounding whitespace) and only the captured
digits are substituted, so multi-digit ids and a trailing terminator work while
any non-numeric tail or a second statement still fails the match.

The dispatcher matches the registered keys "KILL QUERY" and
"SHOW TABLE STATUS LIKE" without their trailing separator, but the helpers
slice the suffix at prefix.length() which includes the space. A malformed
command would skip the byte at the separator position and be coerced into a
valid command: "KILL QUERY;12" and "KILL QUERYx12" reached the digit regex as
"12" (cancelling query id 12), and "SHOW TABLE STATUS LIKEx'a'" became a lookup
of 'a'. Both helpers now require the byte at the separator position to be
whitespace before slicing, so a missing or non-space separator is rejected
(KILL QUERY passes through and errors; SHOW TABLE STATUS matches nothing).

Added a regression test (test_mysql_replacement_query_injection) that fails
on the previous behavior and passes with this fix, covering the
SQL_SELECT_LIMITED boundary case, the trailing-semicolon terminator for
SHOW TABLE STATUS / SET / KILL QUERY, the rejection of an injected SET tail
(without changing "limit" or "max_threads"), the rejection of a second
statement after ';', and the missing-separator cases for KILL QUERY and
SHOW TABLE STATUS LIKE.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the mysql-handler-replacement-query-injection branch from 4b6aa2b to cef6b4b Compare June 25, 2026 20:22
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in cef6b4b. Both killConnectionIdReplacementQuery and showTableStatusReplacementQuery now require the byte at the separator position (query[prefix.size() - 1], the space) to be whitespace before slicing the suffix, so KILL QUERY;12, KILL QUERYx12, KILL QUERY12 and SHOW TABLE STATUS LIKEx'a' are no longer coerced: KILL QUERY passes through and errors, SHOW TABLE STATUS matches nothing. Regression cases added to test_mysql_replacement_query_injection. Verified both directions on a local MySQL-port build: the malformed cases were accepted (cancel / lookup) before the change and are rejected after.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cef6b4b

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
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found deadlock (chronic; 457 PRs + 329 master rows / 30d, no causal link to MySQLHandler) #101680 / #105905 (ours, open)
Bugfix validation (integration tests) / test_mysql_protocol::* expected (validation passes overall: regression fails on master, passes on PR) check conclusion SUCCESS, no owner needed
PR / Mergeable Check / Style check aggregator rollup reflects the above
CH Inc sync — CH Inc sync (private, not actionable)

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

@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 66/69 (95.65%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — da02224

CI fully finished (Finish Workflow pass). The Bugfix validation (integration tests) MySQL-protocol job PASSES at the job level (the inner test_mysql_* FAILs are the expected pre-invert result: the regression tests correctly fail on master and pass on this PR). The remaining reds are chronic trunk Stress-test families, none PR-caused.

Check / test Reason Owner / fixing PR
Bugfix validation (integration tests) / test_mysql_protocol::* expected invert (regression tests fail-on-master / pass-on-PR; job verdict = pass) PR-caused → N/A (this IS the fix; job green)
Stress test (amd_tsan) / Hung check deadlock (chronic hung-check family) #108212 (ours, merged) / #105905 (ours, merged)
Stress test (arm_debug) / "Unexpected exception in refresh scheduling" (STID 2508-34af) + Cannot start server crash (chronic RefreshTask-scheduling trunk family: 136 PRs, 14 master/30d) a fix task is moved to pending (RefreshTask family — investigating at full effort; fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260703-053000

@CheSema CheSema self-assigned this Jul 7, 2026
@CheSema
CheSema added this pull request to the merge queue Jul 7, 2026
Merged via the queue into ClickHouse:master with commit d758283 Jul 7, 2026
172 of 175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…acement-query-injection

Fix SQL injection in MySQL wire protocol replacement queries
@rschu1ze rschu1ze added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 14, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
CheSema added a commit that referenced this pull request Sep 15, 2026
Cherry pick #108474 to 26.6: Fix SQL injection in MySQL wire protocol replacement queries
CheSema added a commit that referenced this pull request Sep 15, 2026
Cherry pick #108474 to 26.3: Fix SQL injection in MySQL wire protocol replacement queries
robot-clickhouse added a commit that referenced this pull request Sep 15, 2026
robot-clickhouse added a commit that referenced this pull request Sep 15, 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 Sep 15, 2026
CheSema added a commit that referenced this pull request Sep 15, 2026
Cherry pick #108474 to 26.3: Fix SQL injection in MySQL wire protocol replacement queries
CheSema added a commit that referenced this pull request Sep 15, 2026
Cherry pick #108474 to 26.6: Fix SQL injection in MySQL wire protocol replacement queries
CheSema added a commit that referenced this pull request Sep 15, 2026
CheSema added a commit that referenced this pull request Sep 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #108474 to 26.6: Fix SQL injection in MySQL wire protocol replacement queries
CheSema added a commit that referenced this pull request Sep 16, 2026
Backport #108474 to 26.3: Fix SQL injection in MySQL wire protocol replacement queries
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 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.

8 participants