Repository navigation
Fix SQL injection through identifiers when inserting into a SQLite table - #117421
nikitamikhaylov merged 8 commits into
Conversation
SQLiteSink::consume builds a single statement string and passes it to sqlite3_exec, which executes every ;-separated statement in it. Two user-chosen identifiers were interpolated with backslash escaping: src/Storages/StorageSQLite.cpp:187 doubleQuoteString(remote_table_name) src/Storages/StorageSQLite.cpp:194 quoteString(it->name) Both resolve to writeAnyEscapedString with escape_quote_with_quote = false, which escapes the quote character with a backslash. SQLite has no backslash escape at all: inside a quoted identifier a backslash is ordinary data and doubling the quote is the only escape, so the first raw double quote in a name terminates the identifier and the remainder is tokenized as SQL. A trailing -- comments out the sink's own " (columns) VALUES ...; tail, so the whole string parses cleanly. Both sites are reachable from ordinary SQL: the remote table name is the second engine argument and the column names are the ClickHouse table's own. When the columns are listed explicitly the engine skips reading the remote structure, so the injected name never has to name a real SQLite table. An injected ATTACH DATABASE opens a second file on the same connection and is never seen by validateSQLiteDatabasePath, which validates only the path handed to sqlite3_open, so the user_files restriction is bypassed for reads and writes alike. This adds writeDoubleQuotedStringSQLite / doubleQuoteStringSQLite, the identifier counterpart of the writeQuotedStringSQLite added for the read path in ClickHouse#104217, and uses it at both sites. ClickHouse#74144 fixed the same class in the schema path and deliberately chose correct escaping over validation, because a legitimate table or column name containing a quote has to keep working. :194 is a behaviour fix as well as hardening: quoteString emitted a single-quoted string literal where an identifier belongs, so a column name containing a double quote produced invalid SQL. The same two lines also make a table whose name contains a backslash writable, which it previously was not. A NUL inside an identifier is deliberately not rejected. sqlbuf.str().c_str() truncates the statement at the NUL and every double quote before it has already been doubled, so the identifier is necessarily unterminated and SQLite rejects the statement with "unrecognized token". It always fails loudly, and the statement's meaning can never be silently truncated. Two residuals are left alone. The read path quotes identifiers through IdentifierQuotingStyle::DoubleQuotes with the same backslash escaping, so a table whose name contains a double quote or a backslash still cannot be read; that enum is shared with other engines and dictionary sources, and it crosses no privilege boundary because SQLiteSource prepares a single statement. The VALUES payload escapes control characters with backslashes, so a tab does not round-trip. Test: 05055_sqlite_insert_identifier_escaping. It fails on master and passes with this change; 5 of its 6 arms differ between the two binaries. Co-Authored-By: Claude Opus 5 <[email protected]>
Both were single comments spanning several lines. Each is now one line under 140 characters that keeps the non-obvious fact and drops what the surrounding code already states. Comment-only change: stripping comment lines from this file at the parent commit and at this one leaves byte-identical text, and the test still passes. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings across a full pass and a
Severity: ❌ blocker / Checked independently of the implementation notes, in case any of it is useful in review:
Session id: cron:clickhouse-review-slot-48:20260831-221504 |
|
Workflow [PR], commit [e1edc79] Summary: ❌
AI ReviewSummaryThis PR fixes the Final Verdict
LLVM Coverage ReportMeasured on commit e1edc79.
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260831-174503 |
|
cc @GrigoryPervakov @pamarcos, could you review this? The SQLite INSERT sink escaped the remote table name and the column names with backslashes, which SQLite does not honour inside a quoted identifier, so the first raw double quote in a name closed the identifier and the remainder ran as SQL inside |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units2612 translation units recompiled, 14466 s compile time in total, 2612 of them have a recent master baseline. |
WriteBufferFromString resizes the string to the bytes written in its destructor, and the buffer was still alive at the return statement, so the result was correct only because the compiler elides the named return value. Scoping the buffer matches backQuote, backQuoteIfNeed and backQuoteMySQL in the same file.
${USER_FILES_PATH}/.. is the server's own data directory, and no other stateless
test writes there. ${CLICKHOUSE_TMP} gives the property the test needs, a path
outside the user_files confinement, without writing to the data directory.
Both directions re-measured at the new path: the test passes with the fix and
fails on unpatched master, where the injected ATTACH DATABASE still reads the
canary and creates a marker outside user_files. A1 still reports
PATH_ACCESS_DENIED, so the control that proves the path is out of confinement is
unchanged.
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Bugfix validation (functional tests, amd64) |
job-level abort at ci/jobs/functional_tests.py:734, AssertionError: Could not find master builds in S3, before any server starts, so nothing was validated and no test is attributed. Trunk-wide: 111 rows over 48 unrelated PRs in the last 24h, onset 2026-08-31 19:31Z |
#117433 (mine, open) |
Bugfix validation (functional tests, aarch64) |
same Could not find master builds in S3 abort as the row above |
#117433 (mine, open) |
Finish Workflow / Post Hooks (new_tests_check.py) |
pure cascade of the two rows above: the hook reds when no per-arch bugfix job reports OK or XFAIL, and its own output quotes both aborts verbatim | #117433 (mine, open) |
Docs examples / Documentation examples, Function/toYYYYMM#0 |
the example in src/Functions/toYYYYMM.cpp documents SELECT toYYYYMM(now(), 'US/Eastern') as 202608, so it began returning 202609 when the month rolled over in that zone at 2026-09-01 04:00 UTC. Time triggered and trunk-wide: 44 rows over 43 unrelated PRs since that boundary, against 0 rows in the preceding 10 days |
#117459 (mine, open) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
job-level container-memory abort with no failing test assertion: the shard's nested containers breach the /docker cgroup leaf. #117202 is already an ancestor of this head (compare returns status=ahead, behind_by=0) and the shard failed anyway, so it is not the owner |
#117411 / #117412 (both open) |
Session id: cron:our-pr-ci-monitor:20260901-083000
|
@groeneai refresh the PR. |
|
@nikitamikhaylov Refreshed: merged master The five failures on the previous head were each owned by another PR, and three of those owners have merged since, so this refresh picks their fixes up: #117580 ( |
|
|
||
| sqlbuf << "INSERT INTO "; | ||
| sqlbuf << doubleQuoteString(remote_table_name); | ||
| sqlbuf << doubleQuoteStringSQLite(remote_table_name); |
There was a problem hiding this comment.
The write-side identifier quoting is fixed here, but SQLite still serializes the same identifiers with the old PostgreSQL-style double-quote rules on reads. StorageSQLite::read() still passes IdentifierQuotingStyle::DoubleQuotes into buildQueryForExternalDatabaseSubquery / transformQueryForExternalDatabase, and that ends up in doubleQuoteString / writeDoubleQuotedString instead of the new SQLite helper.
That leaves the identifier contract inconsistent across the same engine: a remote table or column name containing " or \ now works for INSERT, but the read side still generates SQL like SELECT "c\\\"1" FROM "ta\\\"ble", which SQLite rejects (near "1": syntax error). This needs the same SQLite-specific identifier quoting wired through the read builders as well.
CI finish ledger - 33ea2feEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
I am not treating the flaky-check line as informational. It is a genuine concurrency defect and it Session id: cron:our-pr-ci-monitor:20260904-200000 |
SQLite TSan data race (STID 1003-358c): root cause, and why the fix lives in the forkThe Root cause. static pid_t randomnessPid = 0; /* 40515 */
if( randomnessPid!=osGetpid(0) ){ randomnessPid = ... } /* unixOpen, 46815 */
randomnessPid = osGetpid(0); /* unixRandomness, 47314 */
Not from this PR, and not new. The access sites are structurally identical at amalgamation 3.38.2, 3.41.2 and 3.53.4, so the defect has been latent since the submodule was added in 2021, and the 3.53.4 bump ( Frequency: one occurrence in CIDB, ever. SELECT count(), uniqExact(pull_request_number),
countIf(head_ref='master' AND pull_request_number=0)
FROM default.checks WHERE check_start_time > now() - INTERVAL 365 DAY
AND positionCaseInsensitive(test_context_raw,'sqlite')>0
AND positionCaseInsensitive(test_context_raw,'data race')>0
-- 2 2 0One of those two rows is this report; the other is a The fix is one line, in -static pid_t randomnessPid = 0;
+static _Atomic pid_t randomnessPid = 0;That is the same remedy applied to this file for this class in 2023: fork commit I do not recommend the in-repo alternative. One question, since the fix needs a commit in a repository I cannot merge to: shall I open that one-line PR against |
|
@groeneai check the datarace reported in the flaky check. |
|
Merged master into the branch: new head |
CI finish ledger - e1edc79Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Measured at this head, so the "infra" reason is evidence rather than a label: 0 Session id: cron:our-pr-ci-monitor:20260923-073136 |
|
Fixing PR for the |
9ee430d
Cherry pick #117421 to 26.3: Fix SQL injection through identifiers when inserting into a SQLite table
…inserting into a SQLite table
Cherry pick #117421 to 26.7: Fix SQL injection through identifiers when inserting into a SQLite table
…inserting into a SQLite table
Cherry pick #117421 to 26.8: Fix SQL injection through identifiers when inserting into a SQLite table
…inserting into a SQLite table
Cherry pick #117421 to 26.9: Fix SQL injection through identifiers when inserting into a SQLite table
…inserting into a SQLite table
Backport #117421 to 26.9: Fix SQL injection through identifiers when inserting into a SQLite table
Backport #117421 to 26.3: Fix SQL injection through identifiers when inserting into a SQLite table
Backport #117421 to 26.7: Fix SQL injection through identifiers when inserting into a SQLite table
Backport #117421 to 26.8: Fix SQL injection through identifiers when inserting into a SQLite table
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed SQL injection through identifiers when inserting into a table with the
SQLiteengine. The remote table name and the column names were escaped with backslashes, which SQLite does not honour inside a quoted identifier, so a name containing a double quote could close its own identifier and have the rest of it executed as SQL. It is now also possible to insert into a SQLite table whose name, or column name, legitimately contains a double quote or a backslash.Description
SQLiteSink::consumebuilds one string and hands it tosqlite3_exec, which executes every;-separated statement in it. Two user-chosen identifiers were interpolated with backslash escaping: the remote table name atsrc/Storages/StorageSQLite.cpp:187(doubleQuoteString) and the column names at:194(quoteString, a string literal where an identifier belongs). SQLite has no backslash escape: inside"..."a backslash is data and""is the only escape, so the first raw double quote in a name closes the identifier and the rest is parsed as SQL. Both sites are reachable from ordinary SQL, andvalidateSQLiteDatabasePathonly checks the path given tosqlite3_open, so an injectedATTACH DATABASEescapes theuser_filesrestriction.Both now use a new
doubleQuoteStringSQLite, the identifier counterpart of thewriteQuotedStringSQLitethat closed the read path in #104217. #74144 fixed this class in the schema path and also chose escaping over validation, so a legitimate name containing a quote keeps working.:194is a behaviour fix too: such a column name was previously emitted as invalid SQL.A NUL in an identifier is deliberately not rejected:
c_str()truncates the statement and every preceding double quote is already doubled, so the identifier is unterminated and SQLite always rejects it loudly, never silently truncating it.Not bundled, each worth considering separately: rewriting the sink on
sqlite3_prepare_v2with bound parameters, which removes multi-statement execution but still needs this helper because identifiers cannot be bound; andsqlite3_limit(SQLITE_LIMIT_ATTACHED, 0)inopenSQLiteDB, effective in my measurement but it also constrains the documentedquery(...)form.Residuals left alone: the read path quotes identifiers with the same backslash escaping, so such a table still cannot be read, and the
VALUESpayload backslash-escapes control characters, so a tab does not round-trip.New test
05055_sqlite_insert_identifier_escapingfails on master and passes with this change. Found by an internal security report.Workflow [PR]
Sync PR [sync-upstream/pr/117421]
Version info
26.10.1.536-master(included in26.10and later)26.9.2.29,26.8.11.43,26.7.14.44,26.3.33.147