Skip to content

Bound an interserver TablesStatusRequest read before authentication - #123422

Open
tiandiwonder wants to merge 10 commits into
masterfrom
bound-interserver-tables-status-request
Open

tiandiwonder wants to merge 10 commits into
masterfrom
bound-interserver-tables-status-request

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

An interserver TablesStatusRequest is deserialized before the peer has proven knowledge of the cluster <secret>. On the signed path (revision DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET_TABLES_STATUS and above) that is by construction: the authentication hash covers the request body, so the body has to be read to recompute the digest before the hash can be validated. Below that revision the peer sends no hash at all, and its request is read whenever it is not refused outright by interserver_tables_status_require_auth.

Two things were unbounded there. The table count was capped only at DEFAULT_MAX_STRING_SIZE, and each name was read with readStringBinary, which resizes the string to the declared size before reading a byte of it — so a peer could declare a 1 GiB name and make the server allocate it while the bytes never arrive. Reaching this needs only a Hello naming an existing cluster that has a <secret>, not knowledge of the secret.

Solution

Read the names with readStringBinaryGrowing, so a declared size never becomes an allocation unless the peer actually sends the bytes. That helper exists for exactly this case — readException uses it because "the sizes of these strings come from the other side, so read them without preallocating the declared size".

Bound the table count for a request arriving on an interserver connection: MAX_TABLES_IN_INTERSERVER_STATUS_REQUEST = 64. ConnectionEstablisher is the only producer of a TablesStatusRequest and it asks about exactly one table, so this leaves ample headroom — including for the request status for joined tables also TODO there — while bounding a hostile request. An ordinary authenticated client keeps the generic bound it has today.

read takes a TablesStatusRequestSource (Client / InterserverPeer) rather than the limit itself, and every interserver path in processTablesStatusRequest converges on one read, so the bound cannot be applied to one path and not another.

Deliberately no bound on how long a name may be. There is none to borrow — IDatabase::checkTableNameLength is a no-op by default and only DatabaseOnDisk overrides it (with a filesystem-derived limit) — and the name here comes from the Distributed engine arguments, so any ceiling could reject a legitimate request from a Distributed table pointing at a long remote name. Beyond the count, an interserver peer has to actually transmit what it declares, bounded as every other pre-authentication string in the protocol is, including the Query text itself.

Related: #99854
Related: #113602

Split out of #113602, which now carries only the change that stops rejecting an unsigned request. Both merge cleanly into master on their own, but they restructure the same part of processTablesStatusRequest, so whichever merges second needs a conflict resolution there.

Changelog category (leave one):

  • Improvement

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

Bound the number of tables in an interserver TablesStatusRequest, and read the table names without preallocating the size the sender declares. The request is deserialized before the sending node has been authenticated with the cluster <secret>.


Workflow [PR]
Sync PR [sync-upstream/pr/123422]

An interserver `TablesStatusRequest` is deserialized before the peer has proven
knowledge of the cluster secret, on every path: the authentication hash covers the
request body, so the body has to be read to recompute the digest, and a peer below
`DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET_TABLES_STATUS` sends no hash at all. Until
now that deserialization was bounded only by the generic limits - up to
`DEFAULT_MAX_STRING_SIZE` (1 GiB) table names, each of which `readStringBinary` reserves
at its declared size before reading a single byte of it.

Bound both the number of tables and the size of each name for a request that arrives on
an interserver connection (`INTERSERVER_TABLES_STATUS_REQUEST_LIMITS`): 1024 tables of
at most 8 KiB each, so 16 MiB worst case, and that allocation is memory-tracked. A
legitimate request asks about the single table behind the `Distributed` table being
read, so this bounds a hostile request, not a real one. An ordinary authenticated client
keeps the generic limits it had.
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c6f676b]

Summary: ✅


AI Review

Summary

This PR hardens pre-authentication TablesStatusRequest handling by capping the interserver table count, switching name reads to readStringBinaryGrowing, and adding unit/integration coverage. However, the central memory-safety contract is still not met: the request is still materialized into QualifiedTableName's plain std::strings before authentication, so the new tracker only counts a duplicate copy and an unauthenticated peer can still push roughly the whole request body into untracked memory before any tracked allocation can throw.

Findings

❌ Blockers

  • [src/Interpreters/TablesStatus.cpp:126] The pre-authentication request body is still stored first in table_name.database / table_name.table, and those fields are still plain std::strings in src/Core/QualifiedTableName.h:15. Appending them into accounted_for_memory_tracker afterward only tracks a second copy; it does not bound the actual request storage. A peer sending very large names can therefore overshoot max_server_memory_usage by roughly the whole request body before MEMORY_LIMIT_EXCEEDED becomes possible, which means the memory-DoS this PR claims to close is still present.
    Suggested fix: make the primary pre-authentication representation memory-tracked, or hash the serialized names incrementally and avoid materializing them twice, instead of storing them first in untracked std::strings and only then copying them into a tracked buffer.
Tests
  • ⚠️ The new tests cover the table-count gate and the “declared huge size but no bytes arrive” path, but they do not verify the material claim that the signed/unsigned pre-authentication read is now bounded by tracked memory. Add a focused regression that proves a large pre-authentication TablesStatusRequest fails via the intended memory-limit path rather than after fully materializing the names in untracked storage.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • change TablesStatusRequest reading so the primary storage or digest path is memory-tracked instead of only a duplicate;
    • add one regression that exercises that memory-limit behavior on the pre-authentication path.

LLVM Coverage Report

Measured on commit c6f676b.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 58/59 (98.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 2, 2026
@tiandiwonder
tiandiwonder marked this pull request as draft October 2, 2026 06:01
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Oct 2, 2026
…-bearing

Review feedback, all three verified against the source:

* `ConnectionEstablisher` is the only producer of a `TablesStatusRequest` and it asks about
  exactly one table, so 1024 x 8 KiB was oversized by orders of magnitude. 64 x 4 KiB still
  leaves ample headroom - including for the "request status for joined tables also" TODO
  there - and brings the parsed request down to 512 KiB.

* The old comment claimed 16 MiB worst case "and that allocation is memory-tracked". Both
  halves were wrong on the signed path: `getAuthDigest` additionally builds a sorted vector
  of encoded entries and a concatenation of them in plain `std::string`s, which allocate
  through `allocNoThrow`, and only the final copy into the caller's
  `StringWithMemoryTracking` is tracked so as to throw. The comment now says so, and the
  smaller bound keeps the real peak small.

* It also claimed the body is deserialized before authentication on every interserver path.
  It is not: an unsigned request is refused before its body is read when
  `interserver_tables_status_require_auth` is on. Pre-authentication deserialization happens
  on the signed path by construction, and on the unsigned path when it is not rejected.

* `test_interserver_request_name_length_is_bounded` declared a 1 GiB name, which an unfixed
  server would also refuse - via the memory tracker - so the test passed without the cap
  existing. It now declares one byte over the cap, which nothing else rejects, and tells a
  connection close apart from the server accepting the length and waiting for bytes that
  never arrive.

Adds `gtest_tables_status_request_read.cpp` to pin both limit profiles directly, which also
covers the signed path's call site: the integration tests can only reach `read` through the
unsigned one.
`read` took the limits as a parameter, so every call site chose them - and nothing failed if
one chose wrong. In particular the signed interserver path, which is the production path and
the one that goes on to the extra `getAuthDigest` allocations, could be switched to the
generous profile and every test would still pass.

It now takes a `TablesStatusRequestSource` (`Client` or `InterserverPeer`) and maps that to
the limits itself, so the mapping lives in one place and a call site would have to
misdescribe its own connection to get the wrong bound. The gtest pins both directions of the
mapping.

Also corrects the integration-test preamble, which still said the body is deserialized before
authentication on every listed path: it is not, an unsigned request is refused before its body
is read when `interserver_tables_status_require_auth` is on, and the third listed path is about
`Data`, not `TablesStatusRequest`.
…ted one

The signed interserver branch has no raw-socket test of its own - the test harness sits at
revision 54449 to stay below `DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS` - so passing it
`TablesStatusRequestSource::Client` by mistake would not have failed anything.

`processTablesStatusRequest` now derives the source once from `is_interserver_mode` and every
`read` in it uses that, instead of each branch naming a source. Getting it wrong therefore
takes the bound off the unsigned branch as well, and
`test_interserver_request_table_count_is_bounded` fails.
… the rest

The previous commit claimed that deriving the source once meant a wrong choice on the signed
branch would be caught by the unsigned branch's test. That was wrong: the branches still had a
`read` each, so replacing the argument on just the signed one would have compiled and left
every test passing.

`processTablesStatusRequest` now does its per-path work *before* the body - taking the hash off
the wire on the new protocol, refusing a request that strict mode will reject anyway - and then
all interserver paths fall through to a single `request.read`. There is one place where the
interserver bound is named, which the unsigned-path tests exercise, so the signed path gets the
same bound by construction rather than by a reviewer noticing.

Behaviour is unchanged on every input class: a signed request still has its hash read before and
validated after the body; strict mode still refuses before the body is read; an authenticated or
opted-out old peer still has its body read without validation; and a build without SSL still
refuses an unauthenticated request. `received_hash` and `request_is_signed` are declared inside
`#if USE_SSL`, so they are not unused when it is off.
Comment thread src/Interpreters/TablesStatus.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c6f676b1c with master a2e4282a1 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

127 translation units recompiled, 1299 s compile time in total, 127 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -88.9 s (-6%) in total before that adjustment.

Job report

The per-name cap of 4 KiB was a compatibility break, as the CI review pointed out:
`IDatabase::checkTableNameLength` is a no-op by default and only `DatabaseOnDisk` overrides it
(with a filesystem-derived limit), so a table in e.g. a `Memory` database can be named
arbitrarily - and the name in a `TablesStatusRequest` comes from the `Distributed` engine
arguments, which are whatever the user wrote. A `Distributed` table pointing at a longer remote
name would have started failing during deserialization, with no version gate.

The names now share one budget, spent down as they are read, so a name is refused only when it
does not fit in what the rest of the request has left. That bounds the same memory without
putting any ceiling on an individual name. The budget is 1 MiB, which is above what a name can
legitimately reach anyway: a `CREATE TABLE` or `Distributed` definition carrying a longer one
does not fit in the default `max_query_size` of 256 KiB.

Tests gain the two properties that distinguish a budget from a cap: one name may use the whole
budget (gtest, plus an end-to-end request naming a table exactly that long, which must still be
answered), and names that each fit but together do not are refused.
Any ceiling on how long a table name may be is a compatibility break, whatever the number: the
name in a `TablesStatusRequest` comes from the `Distributed` engine arguments, and ClickHouse has
no name ceiling of its own to borrow - `IDatabase::checkTableNameLength` is a no-op unless the
database is a `DatabaseOnDisk`. Justifying 1 MiB by the default `max_query_size` did not hold
either, since that setting is configurable and `0` means unlimited.

The real problem was never the length but that `readStringBinary` resizes to the declared size
before reading a byte of it, so a size a peer declares becomes an allocation even when the
payload never follows. `readStringBinaryGrowing` already exists for exactly this - `readException`
uses it because "the sizes of these strings come from the other side" - so use it here and drop
the name bound entirely.

What remains is the table *count*, which a legitimate request cannot push against:
`ConnectionEstablisher` always asks about exactly one table. Beyond that an interserver peer must
actually transmit the bytes, bounded as every other pre-authentication string in the protocol is,
including the Query text itself.

This also restores the ordinary-client path exactly: names keep their own generic string bound
instead of sharing an aggregate one, which the previous commit had tightened by accident.
`INTERSERVER_TABLES_STATUS_REQUEST_LIMITS` no longer exists; the bound is
`MAX_TABLES_IN_INTERSERVER_STATUS_REQUEST`.
Comment on lines +108 to +109
readStringBinaryGrowing(table_name.database, in);
readStringBinaryGrowing(table_name.table, in);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only fixes the “declare a huge size and then send no bytes” case. Once the peer actually streams the bytes, these names still land in QualifiedTableName as plain std::strings, so the pre-auth read path is still unbounded in RSS (unlike TCPHandler::query, which uses StringWithMemoryTracking specifically to avoid that). On the signed path we then copy the whole set again in TablesStatusRequest::getAuthDigest(), so a peer that sends a few genuinely huge names can still push the server past its memory budget before authentication completes.

We still need a real byte bound or a memory-tracked/incremental representation here — for example, track an aggregate name-byte budget while reading, or hash the serialized names incrementally instead of materializing and re-copying arbitrary-size names before the secret check.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — read now keeps one StringWithMemoryTracking alive across the whole loop and appends every name byte to it, so the accumulation is what the tracker sees and the bound is max_server_memory_usage rather than an invented constant; getAuthDigest builds its two duplicates in tracked strings as well.

Accounting each name separately would not have worked, since 64 names each under the limit can exceed it together. (commit c6f676b)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't think this is fixed yet. At src/Interpreters/TablesStatus.cpp:126-src/Interpreters/TablesStatus.cpp:129 the peer-controlled bytes are still read into table_name.database / table_name.table first, and QualifiedTableName still stores those as plain std::strings in src/Core/QualifiedTableName.h:15. The new accounted_for_memory_tracker only sees a second copy after those untracked allocations already succeeded, so it is bounding the duplicate, not the actual request storage.

That is different from the Query path, where the primary buffer itself is StringWithMemoryTracking in src/Server/TCPHandler.h:99. A large pre-authentication request can still push roughly the whole request body into untracked memory before any tracked append can throw, so the original memory-budget issue is still present.

Compare the protocol revision directly where the hash is read and where it is validated, instead
of carrying it in a flag. The comments now state only why the count is bounded, why names are read
growing, and why there is a single `read` for all interserver paths; the rest repeated the
comment at the top of `processTablesStatusRequest`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@tiandiwonder
tiandiwonder marked this pull request as ready for review October 5, 2026 11:09
Reading the names growing only closed the "declare a huge size and send no bytes" case. Once
the peer streams the bytes they land in `QualifiedTableName`'s plain `std::string` fields,
which allocate through `allocNoThrow`, so an interserver peer that has not been authenticated
yet could still grow the server's RSS past `max_server_memory_usage` instead of being refused -
and `getAuthDigest` duplicates the whole set twice more on the signed path.

This is not how the rest of the pre-authentication path behaves: `QueryState::query` is a
`StringWithMemoryTracking` for exactly this reason, as the comment above it says. These names
were the outlier.

`read` now keeps one tracked string alive for the whole loop and appends every name byte to it,
so the bound is `max_server_memory_usage` rather than an invented constant - no name is refused
for its length, so there is nothing to version-gate. Accounting each name on its own would not
work: a peer can send `MAX_TABLES_IN_INTERSERVER_STATUS_REQUEST` names that are each far below
the limit and together far above it. `getAuthDigest` builds its two duplicates in tracked
strings as well.

The costs, both noted in the code: a second copy of the names while `read` runs, so the peak is
a small multiple of what the tracker sees rather than exactly it - the same shape as the query
text, which is tracked and then parsed into an untracked AST - and the digest is still returned
as a plain `std::string`, one copy of something the tracker has already admitted, which keeps
both callers and the unit test untouched.

@tavplubix tavplubix 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.

Can we authenticate the user before reading the potentially huge string?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants