Skip to content

Cherry pick #108474 to 26.3: Fix SQL injection in MySQL wire protocol replacement queries - #119981

Merged
CheSema merged 4 commits into
backport/26.3/108474from
cherrypick/26.3/108474
Sep 15, 2026
Merged

CheSema merged 4 commits into
backport/26.3/108474from
cherrypick/26.3/108474

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #108474

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

groeneai and others added 3 commits June 25, 2026 20:21
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]>
…ery-injection

Fix SQL injection in MySQL wire protocol replacement queries
@robot-ch-test-poll robot-ch-test-poll 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-bugfix Pull request with bugfix, not backported by default labels Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The conflict here is one file, src/Server/MySQLHandler.cpp, and one 3-line add/add hunk in namespace ErrorCodes: the merge base declares neither line, the cherry-pick side adds SYNTAX_ERROR, and the 26.3 side adds SYNTAX_ERROR plus UNKNOWN_PACKET_FROM_CLIENT. Both declarations are load-bearing, SYNTAX_ERROR for the ported literal parsing and UNKNOWN_PACKET_FROM_CLIENT for 26.3's existing packet handling, so the resolution is their union. The resolution touches nothing else in the file, and tests/integration/test_mysql_protocol/test.py auto-merges clean. Against backport/26.3/108474 the merge changes exactly those two files and nothing else.

I verified the resolved merge on the 26.3 tree rather than just making it merge. It builds with clang-21, the toolset 26.3 pins, and the ported test_mysql_protocol/test.py::test_mysql_replacement_query_injection fails on a binary built without the port:

AssertionError: SHOW TABLE STATUS LIKE injection leaked system.users: ['default', 'user_with_double_sha1', 'user_with_empty_password', 'user_with_sha256']

and passes with it, 3 runs each way, with ::test_mysql_replacement_query green in both directions.

@CheSema, I hold pull and triage on this repository but not push, so I cannot move cherrypick/26.3/108474 myself. The merge is on my fork and its first parent is d7582838d3cb888d6fa59a6dbe5efff13a550bcd, this PR's head, so applying it is a fast-forward and resolves nothing by hand:

git fetch https://github.com/groeneai/ClickHouse.git groeneai/resolve-26.3-cherrypick-108474
git push origin FETCH_HEAD:cherrypick/26.3/108474

cherry_pick.py merges this PR once it reports mergeable and then opens the 26.3 backport PR itself.

The 26.6 arm, #119982, is the same shape and I am handling it separately.

The `ErrorCodes` block in `MySQLHandler.cpp` conflicted: the fix appends
`SYNTAX_ERROR`, while the release branch declares both `SYNTAX_ERROR`
and `UNKNOWN_PACKET_FROM_CLIENT`, the latter dropped on master. Keep the
branch block unchanged, because it already provides what the fix needs.
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-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants