Skip to content

Fix security issue to prevent SQL injection in postgresql and sqlite table functions - #74144

Merged
pamarcos merged 13 commits into
masterfrom
sanitize-postgresql-table-function-params
Jan 20, 2025
Merged

pamarcos merged 13 commits into
masterfrom
sanitize-postgresql-table-function-params

Conversation

@pamarcos

@pamarcos pamarcos commented Jan 3, 2025 •

Copy link
Copy Markdown
Member

Fix security issue to prevent SQL injection in postgresql and sqlite table functions

At first I thought we should sanitize and validate the parameters to check whether the database and table names comply with PostgreSQL convention. However, turns out we can fix this in an easier way: properly escaping single quotes for PostgreSQL and SQLite.

Closes https://github.com/ClickHouse/clickhouse-private/issues/21742
Closes #74610

Changelog category (leave one):

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

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

Fix security issue to prevent SQL injection in postgresql and sqlite table functions

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

CI Settings (Only check the boxes if you know what you are doing)

All builds in Builds_1 and Builds_2 stages are always mandatory
and will run independently of the checks below:

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64
  • Exclude: All with release
  • Exclude: All with debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-cloud labels Jan 3, 2025
@robot-ch-test-poll4

robot-ch-test-poll4 commented Jan 3, 2025 •

Copy link
Copy Markdown
Contributor

This is an automated comment for commit 7fb5c9d with description of existing statuses. It's updated for the latest CI running

✅ Click here to open a full report in a separate page

Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
Bugfix validationChecks that either a new test (functional or integration) or there some changed tests that fail with the binary built on master branch✅ success
BuildsThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
BuzzHouse (asan)There's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
BuzzHouse (debug)There's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
BuzzHouse (msan)There's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
BuzzHouse (tsan)There's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
BuzzHouse (ubsan)There's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
ClickBenchRuns ClickBench with instant-attach table✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integration tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors✅ success
Style checkRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success

@kssenii kssenii self-assigned this Jan 3, 2025
@pamarcos
pamarcos marked this pull request as ready for review January 15, 2025 16:34
@pamarcos pamarcos changed the title Fix security issue to prevent SQL injection in postgresql table function Fix security issue to prevent SQL injection in postgresql and sqlite table functions Jan 17, 2025
@pamarcos
pamarcos added this pull request to the merge queue Jan 20, 2025
Merged via the queue into master with commit 0080daf Jan 20, 2025
@pamarcos
pamarcos deleted the sanitize-postgresql-table-function-params branch January 20, 2025 15:08
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jan 20, 2025
robot-clickhouse added a commit that referenced this pull request Jan 20, 2025
…in postgresql and sqlite table functions
robot-clickhouse added a commit that referenced this pull request Jan 20, 2025
… in postgresql and sqlite table functions
robot-clickhouse added a commit that referenced this pull request Jan 20, 2025
… in postgresql and sqlite table functions
robot-clickhouse added a commit that referenced this pull request Jan 20, 2025
… in postgresql and sqlite table functions
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created-cloud deprecated label, NOOP label Jan 20, 2025
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jan 20, 2025
robot-clickhouse-ci-2 added a commit that referenced this pull request Jan 20, 2025
Backport #74144 to 24.12: Fix security issue to prevent SQL injection in postgresql and sqlite table functions
pamarcos added a commit that referenced this pull request Jan 21, 2025
Backport #74144 to 24.11: Fix security issue to prevent SQL injection in postgresql and sqlite table functions
pamarcos added a commit that referenced this pull request Jan 21, 2025
Backport #74144 to 24.10: Fix security issue to prevent SQL injection in postgresql and sqlite table functions
pamarcos added a commit that referenced this pull request Jan 21, 2025
Backport #74144 to 24.8: Fix security issue to prevent SQL injection in postgresql and sqlite table functions
pamarcos added a commit that referenced this pull request Jan 21, 2025
Backport #74144 to 24.3: Fix security issue to prevent SQL injection in postgresql and sqlite table functions
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 2, 2025
alexey-milovidov pushed a commit that referenced this pull request May 17, 2026
`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 #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]>
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Sep 23, 2026
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]>
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-backports-created-cloud deprecated label, NOOP 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.

SQLite table function crash

7 participants