Skip to content

Guard the constant-to-literal walks with checkStackSize - #120885

Merged
Avogar merged 7 commits into
masterfrom
security-fix-5
Oct 8, 2026
Merged

Avogar merged 7 commits into
masterfrom
security-fix-5

Conversation

@Avogar

@Avogar Avogar commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Turning a constant into an AST literal walks the value recursively. For Dynamic/JSON the nesting is part of the value rather than of the query text, so no parser limit bounds it: a JSON path holding a Dynamic holding a JSON costs three stack frames per level, and the depth comes straight from the binary value. A deeply nested constant therefore ran past the stack guard page and terminated the server process instead of failing the query.

checkStackSize in getFieldFromColumnForASTLiteralImpl and columnConstantToExactLiteralASTImpl turns this into TOO_DEEP_RECURSION, matching what the Field visitors already report for the same data.

Changelog category (leave one):

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

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

Fixed a crash on a query with a deeply nested Dynamic or JSON constant.


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

Version info

  • Merged into: 26.10.1.1859-master (included in 26.10 and later)
  • Backported to: 26.9.17.8, 26.8.25.14, 26.7.28.14, 26.3.50.5

Turning a constant into an AST literal walks the value recursively, and for
`Dynamic`/`JSON` the nesting is part of the value rather than of the query
text, so no parser limit bounds it: a `JSON` path holding a `Dynamic` holding
a `JSON` costs three stack frames per level, and the depth comes straight from
the binary value. A deeply nested value therefore ran past the stack guard
page and killed the process instead of failing the query.

Add `checkStackSize` to `getFieldFromColumnForASTLiteralImpl` and
`columnConstantToExactLiteralASTImpl`, which turns this into
`TOO_DEEP_RECURSION`, matching what the `Field` visitors already report for
the same data.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 18, 2026
@vdimir vdimir self-assigned this Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [861edf3]

Summary: ✅


AI Review

Summary

This PR adds checkStackSize() to the recursive constant-to-literal walkers in src/Analyzer/Utils.cpp and to ColumnObject::operator[], so deeply nested Dynamic/JSON constants now fail with TOO_DEEP_RECURSION instead of overrunning the native stack. I re-checked the previously reported ReadFromRemote top-level JSON path against current code and it is now covered by the new ColumnObject::operator[] guard, so I do not see remaining blocking or major issues in the current diff.

Missing context / blind spots
  • ⚠️ I did not run tests/queries/0_stateless/05218_dynamic_json_constant_deep_recursion.sql locally because this checkout has no prebuilt build_* directory or clickhouse binary. A local stateless run or green CI would close that gap.
Final Verdict

✅ Looks good to merge.

LLVM Coverage Report

Measured on commit 861edf3.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.80% 79.70% -0.10%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 21, 2026
Comment thread src/Analyzer/Utils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 861edf388 with master e95690ab4 (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

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

Job report

alexey-milovidov and others added 4 commits September 23, 2026 02:26
Reading a value as a `Field` walks the column recursively, and a `JSON` path
holding a `Dynamic` holding a `JSON` cycles between `ColumnObject`,
`ColumnDynamic` and `ColumnVariant` once per nesting level. The nesting is
part of the value rather than of the query text, so no parser limit bounds
it, and a deeply nested value ran past the stack guard page and killed the
process.

Add `checkStackSize` to `ColumnObject::operator[]` and `ColumnDynamic::get`,
the two entry points of that cycle, so it reports `TOO_DEEP_RECURSION`
instead. Found by the AST fuzzer, which mutated the constant from the test
added here into `if(<deeply nested Dynamic>, 1, 2)`: constant folding reads
the condition as a `Field` and enters the walk.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Oct 5, 2026
… value

A Dynamic value can hold a JSON object, a JSON object's dynamic path is a
Dynamic, and JSON/Object is a legal Variant member (checkAllowedInsideVariant
forbids only Nullable, LowCardinality(Nullable), a nested Variant and a direct
Dynamic). So one value can nest Object -> Dynamic -> Variant -> Object to any
depth, and that depth comes from the data: the declared type here is just
Dynamic, and each level's small type is decoded separately, so no type
complexity or parser limit bounds it.

Reading one row of such a value recurses once per level through five frames:

  ColumnObject::operator[]      (ColumnObject.cpp:305)
    -> ColumnDynamic::operator[] (ColumnDynamic.cpp:318)
    -> ColumnDynamic::get        (ColumnDynamic.cpp:328)
    -> ColumnVariant::get        (ColumnVariant.cpp:428)
    -> ColumnObject::get         (ColumnObject.cpp:327)
    -> ColumnObject::operator[]  ... repeats

at about 2.8 KB of stack per level. The one checkStackSize() that path already
reaches sits inside convertFieldToType, called at ColumnDynamic.cpp:330 after
variant_col.get(n, res) has returned, so it runs only once the descent has
completed and cannot stop the descent that overflows. Measured on a debug build
with an 8 MB stack: 1500 and 2000 levels report TOO_DEEP_RECURSION from that
call, while 3000 and 4000 levels take SIGSEGV on the way down. An -O2 build
behaves the same (these frames are dominated by Field, String and Object
temporaries rather than spills, so optimisation does not shrink them), and the
official 26.8.10.6-lts build dies the same way at default settings.

Checking the stack at the top of ColumnDynamic::get moves the check onto the way
down, once per level. Every data-driven level of this nesting passes through a
ColumnDynamic per-value method, because a JSON object's dynamic paths are
ColumnDynamic columns and its shared-data values are decoded by
SerializationDynamic, which is already guarded.

ColumnObject and ColumnVariant are deliberately left unguarded. Their nested
types come from the declared type, and DataTypeFactory.cpp:128-130 caps a
declared type's parse depth at 150 (debug) / 300, two orders of magnitude below
the depths that overflow; a probe confirms a deep JSON(a JSON(...)) is rejected
with "Maximum parse depth (150) exceeded" and the server survives. Adding a
guard there would also re-litigate 2fcfc07, which removed exactly that
construct one layer down in ClickHouse#115702 for its per-container-value cost.

About twenty further per-value methods on these three columns (insert*,
compareAt, computeHashInto, updateHashWithValue, serializeValueIntoArena,
compress, byteSizeAt, ...) recurse identically, with no observed overflow and no
reproducer; the reproducers for updateHashWithValue and getValueNameImpl are
pre-empted on this base by the analyzer recursion that ClickHouse#120885 guards, so they
are not covered here.

Alternatives rejected: guarding the entry points (eight-plus sites for one arm,
and it guards the symptom); bounding the nesting depth when the value is built
(a behaviour change that rejects values accepted today, and it cannot protect a
read of data an older server already wrote); guarding the operator[] alias as
well as get (operator[] is get, so it would double-check).

The regression test uses 4000 levels, the depth CI found and a depth measured to
overflow both a debug and an -O2 build. It should not be raised much above that:
from about 8000 levels the type-side guard in IDataType::getDefaultSerialization
fires first and returns the same error code without the column recursion ever
running deep.

Found by the AST fuzzer, STID 4709-36d5:
https://github.com/ClickHouse/ClickHouse/actions/runs/35623644754/job/106452545848
robot-clickhouse added a commit that referenced this pull request Oct 12, 2026
robot-clickhouse added a commit that referenced this pull request Oct 12, 2026
robot-clickhouse added a commit that referenced this pull request Oct 12, 2026
robot-clickhouse added a commit that referenced this pull request Oct 12, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #120885 to 26.9: Guard the constant-to-literal walks with checkStackSize
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #120885 to 26.8: Guard the constant-to-literal walks with checkStackSize
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #120885 to 26.7: Guard the constant-to-literal walks with checkStackSize
PedroTadim added a commit that referenced this pull request Oct 12, 2026
Backport #120885 to 26.3: Guard the constant-to-literal walks with checkStackSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore 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.

6 participants