Repository navigation
Fix integer overflow in String deserialization - #115702
Conversation
|
Workflow [PR], commit [7e5309e] Summary: ❌
AI ReviewSummaryThis PR hardens several binary PR Metadata
Findings
Tests
Final VerdictStatus: Minimum required actions:
LLVM Coverage ReportMeasured on commit 7e5309e.
Changed lines: Changed C/C++ lines covered: 112/113 (99.12%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 11 s compile time in total, 8 of them have a recent master baseline. |
…n every deserialization path `SerializationString::deserializeBinary` for a `Field` had no hard upper bound of its own, and that path is reachable for the values of the paths that go into the shared data of a `JSON` column, so a malformed nested string could still be passed to `std::string::resize` when `format_binary_max_string_size` is disabled. Both overloads now share `checkStringSize`, which enforces the setting and `SerializationString::MAX_STRING_SIZE`. `SerializationDynamic::deserializeBinary` and `SerializationObject::deserializeBinary` for a column also recurse into each other on the main column-building path of `RowBinary` and `Native`, so the `checkStackSize` call is now made there as well and not only in the `Field` overloads.
…e redundant stack checks The list of types of a flattened `Dynamic` column is now checked for duplicates while it is read, instead of in a second pass over the list, and a test for a list with a duplicate type is added. `SerializationObject::deserializeBinary` does not recurse into itself: every nested value goes through `SerializationDynamic::deserializeBinary`, the only place where the type of a nested value comes from the data. So the check of the stack size there bounds the whole mutual recursion, and the checks in `SerializationObject` are removed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… a per-row cost The skipped prefix of a seeked read (`rows_offset > 0`) summed the sizes from the sizes stream into `bytes_to_skip` without any check, so a corrupted stream could wrap the sum around and make the read start from a wrong byte boundary in the data stream instead of rejecting the part. The prefix now goes through the same validation as the sizes of the materialized rows, and both cases are covered by unit tests over hand-crafted sizes streams. The per-row checks that the previous commits added to `appendStringSizesToColumnStringOffsets` slowed reading of short strings down by 15-55% (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115702&sha=5ba92a1a90a0c126424a7d9c8fbcb2f82c750c25&name_0=PR, https://performance.ci.clickhouse.com/runs?q=115702), because the accumulation of the offsets is one of the hot loops of reading a `String` column. The loop now OR-folds the sizes into a single value that bounds each of them from above and checks it once per chunk sized so that a chunk of validated sizes cannot wrap `UInt64`; in the astronomically rare case when the OR exceeds the limit (which can also combine the bits of legitimate sizes), the accumulation is rolled back and redone with the exact per-size validation. In a microbenchmark the OR-folding loop matches the unchecked one (0.63 ns/row), while the per-row-checked one takes 0.94 ns/row.
…ization-overflow # Conflicts: # src/DataTypes/Serializations/SerializationString.cpp
…lization A typed path of a `JSON` type recurses back into `SerializationObject::deserializeBinary` directly, without passing through `SerializationDynamic`, and the nesting depth of such a type comes from the data (the binary encoding of a `Dynamic` value starts with the encoding of its type). So the stack size checks in `SerializationObject::deserializeBinary` were not redundant after all: they are restored, and `05033_row_binary_huge_string_size` now covers a `Dynamic` value with a deeply nested typed-path `JSON` type, which has to be rejected with `TOO_DEEP_RECURSION` instead of exhausting the stack. Also adapt the new tests to the current master: `rows_offset` was removed from the deserialization API in #115731, which makes the skipped-prefix validation and its unit test moot. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115702&sha=latest&name_0=PR Co-Authored-By: Claude Fable 5 <[email protected]>
| offsets.reserve(offsets.size() + rows); | ||
|
|
||
| for (size_t i = 0; i < rows; ++i) | ||
| /// The sizes come from a separate stream, so they are not implicitly bounded by the amount of data |
There was a problem hiding this comment.
This only hardens the position-independent size stream. The position_independent_encoding = false branch in deserializeStringOffsetsAndGetDataSize is still the Native/absolute-offset carrier (src/Formats/NativeReader.cpp sets it at false), and that branch only checks that the cumulative offsets are monotonic. A payload with one offset of SerializationString::MAX_STRING_SIZE + 1 is monotonic, keeps bytes_to_read well below MAX_TOTAL_STRING_SIZE, and still makes the reader materialize an oversized single string, so the new hard cap is still bypassable on Native input.
Could we validate the per-row deltas on the absolute-offset path too (or otherwise compare consecutive offsets against MAX_STRING_SIZE) and add a focused NativeStringSizeStream regression for that case?
There was a problem hiding this comment.
🕵 Right, the cumulative offsets that Native carries were only checked for monotonicity. Fixed in 60a826a: the difference between two consecutive offsets is the size of a string, so it is checked against MAX_STRING_SIZE there as well, which also subsumes the monotonicity check (the difference of a non-monotonic pair wraps around and lands far above the limit). The difference between the last offset already in the column and the first one of the stream is now covered too - it was outside the range that std::adjacent_find scanned. StringSerialization.OffsetsStreamHugeSizeIsRejected covers the position_independent_encoding = false path with a single offset of MAX_STRING_SIZE + 1, a huge difference in the middle of the stream, and the non-monotonic case.
There was a problem hiding this comment.
This looks reintroduced on the current head. deserializeStringOffsetsAndGetDataSize now only checks that the cumulative offsets are monotonic at src/DataTypes/Serializations/SerializationString.cpp:813-826, and appendStringSizesToColumnStringOffsets only checks the total column size at src/DataTypes/Serializations/SerializationString.cpp:672-687. A Native offsets stream like [SerializationString::MAX_STRING_SIZE + 1] is still monotonic and stays well below MAX_TOTAL_STRING_SIZE, so deserializeBinaryBulkWithSizeStream reaches data.resize(...) at src/DataTypes/Serializations/SerializationString.cpp:887-893 instead of rejecting the single oversized string with TOO_LARGE_STRING_SIZE.
There was a problem hiding this comment.
🕵 This is not a reintroduction — it is the state that @Avogar deliberately established in e534e8e7de22 and 2fcfc07be4a6, and I agree with it (see his comment #115702 (comment) and my reply above).
Both streams now enforce one invariant instead of two overlapping ones: the total size of the batch is bounded by MAX_TOTAL_STRING_SIZE, and the offsets are monotonic, so no offset can address memory outside the block that the bound already allows. The sizes stream accumulates in unsigned __int128, so the sum cannot wrap and one check of the total is exact; the Native offsets stream carries the cumulative offsets directly, so std::adjacent_find for monotonicity plus the same total check in deserializeBinaryBulkWithSizeStream gives the same guarantee — exactly the way SerializationArray validates its offsets.
The per-difference MAX_STRING_SIZE check that this thread asks to restore does not add safety on top of that: with a bounded total, a single string is bounded too. It only changes which error code a corrupted stream produces (TOO_LARGE_STRING_SIZE instead of INCORRECT_DATA) and costs a comparison per row on every Native and every wide-part read; the measurement in the comment linked above puts the per-element variant at 0.47 ns/row against 0.33 for the checked bulk form and 0.30 for the unchecked one.
The overflow this pull request fixes — a sizes stream whose sum wraps the 64-bit offsets and yields a bytes_to_read far smaller than the offsets the column ends up carrying — is what the 128-bit accumulation and the total check close, and 05060_row_binary_huge_string_size covers it.
`deserializeStringOffsetsAndGetDataSize` reads the size stream in two layouts. The `position_independent_encoding` one carries per-row sizes and now rejects a size above `SerializationString::MAX_STRING_SIZE`, but the other one - the cumulative byte offsets that `Native` carries (`NativeReader` sets `position_independent_encoding` to `false`) - only checked that the offsets increase monotonically. A monotonically increasing stream can still put a single string above the limit while the total stays below the limit on the size of the whole column, so the hard cap was bypassable there. The difference between two consecutive offsets is the size of a string, so it is checked against the same limit, which also subsumes the monotonicity check: the difference of a non-monotonic pair wraps around and lands far above it. The difference between the last offset of the column and the first one of the stream is now covered as well; it was outside the range that `std::adjacent_find` scanned.
…the containers The type of a `Dynamic` value comes from the data, and after `decodeDataType` returns it the value is read by `field_type->getDefaultSerialization()->deserializeBinary(...)`, which recurses through `SerializationArray`, `SerializationTuple` and `SerializationMap` for a nested container type. Those did not check the stack, so the guard added to `SerializationDynamic` and `SerializationObject` only covered the types that pass through `Dynamic` or `JSON` again. In practice the depth was already bounded: `decodeDataTypeImpl` and `IDataType::getDefaultSerialization` check the stack on the way in, and their frames are larger than the ones of the value deserialization, so they throw first. That is a property of the generated code rather than of the contract, so the containers now check the stack themselves. The check is a thread-local load and two comparisons, once per container value.
…offsets validation The offsets of a `String` column in the `Native` format are now validated not only for monotonicity but also for the size of every string being within `MAX_STRING_SIZE`, so the corrupted pair `[0xfffffffffffffff0, 0x20]` of the test is rejected with `TOO_LARGE_STRING_SIZE` on the very first offset, before the pair is found to be non-monotonic. Split the test into three payloads so that both rejections stay covered: a non-monotonic pair, an offset far past the data, and a monotonic pair whose difference is above the limit.
…formed size stream is rejected The new validation appends offsets to the destination column before the batch is known to be valid, so a rejection could leave `offsets.back() > chars.size()` behind for a caller that catches the exception and reuses the column. Add a rollback guard in `deserializeBinaryBulkWithSizeStream` that restores both `offsets` and `chars` to their pre-call sizes on every exception path, and a gtest for it.
|
🕵 @groeneai, investigate the failure: This is unrelated to this pull request, which only touches binary The other red, |
|
This is a memcg OOM kill of the test's own server, not a parallel replicas defect. From that job's
So this is the Which cgroup breached is not recoverable from this run: Breadth: 3 hits in 30 days, all on Your reading of the |
…ding and the rollback `appendStringSizesToColumnStringOffsets` accumulates the offsets in 128 bits, which cannot overflow, so the total is checked once at the end instead of bounding every size on the way. Below a total within `MAX_TOTAL_STRING_SIZE` every offset is exact, so a valid stream is accumulated exactly as before. This replaces the chunked OR-folding of the sizes and the rollback that redid the accumulation with the exact per-size validation, at the same speed: on short strings the loop takes 0.33 ns/row against 0.33 ns/row for the OR-folded one and 0.30 ns/row for the unchecked one, while the per-size validation takes 0.47 ns/row. The `Native` path, which carries cumulative offsets instead of sizes, checks that they increase monotonically with `std::adjacent_find`, the way `SerializationArray` does. The total of a monotonic stream of offsets is already checked by the caller, so the sizes it describes are bounded as well and the OR-folding of the differences is not needed there either. `ColumnStringRollbackGuard` is removed: `deserializeBinaryBulk*` does not restore the destination column, a caller that needs it intact uses `ColumnCheckpoint`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rom the data A type that nests deeply has to be decoded before any value of it is read, and `decodeDataTypeImpl` checks the stack while decoding it, so the guards in `SerializationArray`, `SerializationTuple`, `SerializationMap` and `SerializationObject` cannot be reached: the decoding throws first. They are removed, together with their cost of a thread-local load and two comparisons per container value. `SerializationDynamic::deserializeBinary` keeps its check. There the depth comes from the number of values rather than from one deep type: every nested value carries its own type tag, so nothing bounds the recursion but the size of the input. The tests of the two recursion cases are unchanged and still pass: the deeply nested `JSON` value is rejected by the check in `SerializationDynamic`, and the deeply nested type of a typed path by the one in `decodeDataTypeImpl`, both with `TOO_DEEP_RECURSION`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
I pushed two commits that simplify the validation added in the last rounds. My concern was that each round added a new mechanism on top of the previous one, and the result Sizes streamThe accumulation now runs in A 128-bit accumulator cannot overflow, and below a total within the limit every offset is exact, This is not a performance concession. I measured the loop for short strings, and the 128-bit
The per-element check really does cost what the earlier report showed, so the OR fold was the Offsets stream (
|
Backport #115702 to 26.8: Fix integer overflow in String deserialization
Resolve the cherry-pick conflicts of #115702 for 26.6: - `SerializationString.cpp`: 26.6 has no offsets-stream carrier and no `MAX_TOTAL_STRING_SIZE` constant, so the constant is introduced here and the `deserializeStringOffsetsAndGetDataSize` hunk is dropped; the `checkStringSize` helper and the 128-bit accumulator in `appendStringSizesToColumnStringOffsets` are ported as is. - `SerializationDynamic.cpp`: the `checkStackSize` guards are added around the 26.6 `decodeDataType(istr)` calls. - `gtest_string_serialization.cpp`: the `OffsetsStreamHugeSizeIsRejected` test is dropped (no offsets stream on 26.6). - `gtest_native_string_size_stream.cpp` does not exist on 26.6; its hunk is dropped.
Resolve the conflicts of the cherry-pick of #115702 against 26.3: - `SerializationDynamic.cpp`: keep the 26.3 `decodeDataType(istr)` call and add the `checkStackSize` guards. - `SerializationString.cpp`: 26.3 has no `MAX_TOTAL_STRING_SIZE` and no Native offsets stream (`deserializeStringOffsetsAndGetDataSize`), so add the constant, the `checkStringSize` helper and the 128-bit accumulator in `appendStringSizesToColumnStringOffsets`; the offsets-stream hunk does not apply. - `gtest_string_serialization.cpp`: port `WithSizeStreamHugeSizeIsRejected` to the 26.3 signatures (`ColumnPtr &`, `rows_offset`), drop the offsets-stream test. - `src/Formats/tests/gtest_native_string_size_stream.cpp` does not exist on 26.3: dropped.
Resolve the conflicts of the cherry-pick of #115702 against 26.7: - `SerializationString.cpp`: 26.7 has no cumulative-offsets carrier for the size stream (`deserializeStringOffsetsAndGetDataSize` does not exist there) and no `MAX_TOTAL_STRING_SIZE` constant yet, so the constant is added, the `checkStringSize` helper and the 128-bit accumulator in `appendStringSizesToColumnStringOffsets` are applied on top of the 26.7 code, and the monotonicity hunk for the offsets stream is dropped. 26.7 still has `rows_offset`, so the sum of the skipped prefix is bounded the same way. - `gtest_string_serialization.cpp`: adapted to the `rows_offset` signature, the offsets-stream test is dropped, and a test for the skipped prefix is added. - `gtest_native_string_size_stream.cpp` does not exist on 26.7; the hunk is dropped.
Cherry pick #115702 to 26.3: Fix integer overflow in String deserialization
Cherry pick #115702 to 26.6: Fix integer overflow in String deserialization
Cherry pick #115702 to 26.7: Fix integer overflow in String deserialization
Backport #115702 to 26.7: Fix integer overflow in String deserialization
Backport #115702 to 26.3: Fix integer overflow in String deserialization
Backport #115702 to 26.6: Fix integer overflow in String deserialization
`result_column_stats` is an `unordered_map`, so serializing it in iteration order made the bytes of one plan vary between runs. It is emitted sorted by column name now, which is also the order the Cascades identity encoding of the same members uses. The local in `deserialize` is renamed to `step`, matching the two other open pull requests that add a field to that function, so resolving the overlap between them is a one-line pick. The header comment above these members read "Runtime info, do not serialize", which stopped being true for them. It now describes the group it still applies to, and the note in `serialize` states the property the new block exists for. That note also drops a claim from the previous commit's message: `right_hash_table_cache_key` is not the output of the plan cache key hashing. A `JoinStepLogical`'s contribution to a cache key is computed by `calculateJoinStepCacheKeyContribution`, never by its `serialize`. The block is still left out of a cache key, for the other reason given there: `optimized` and the estimates differ between the single-node and the parallel-replicas plan build, and those two builds have to hash alike. Both tests pin the randomized settings their case depends on. Four settings each independently remove the divergence and the test runner draws two of them half the time, so without the pins the new case in `04649_pr_plan_based_join_distributed` would have been vacuous on roughly three CI runs in four. `04511_cascades_replicated_subplan_join` pins `use_hash_table_stats_for_join_reordering`: it is a full pinned-text `EXPLAIN PLAN` that pins every other plan-shaping randomized setting, and join reordering otherwise takes a leaf row estimate from the process-global hash table statistics, which any join that ran earlier in the same server fills in. That already fails it one run in five on master under concurrency; with the pin it passes five of five on master and five of five with this change, and its reference file is unchanged. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115702&sha=7e5309e6c513d335a722af6a869b2945818a27a7&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 Seen on ClickHouse#115702 Related: ClickHouse#110518 Co-Authored-By: Claude Opus 5 <[email protected]>
… 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
The size of a string is read from the data in two places where adding it to the current size of the
column can overflow:
SerializationString::deserializeBinary(the single-value path used byRowBinaryand the otherbinary formats) had no upper bound of its own; the limit was only the
format_binary_max_string_sizesetting, which is documented to be disabled when it is set to
0. With it disabled, a size closeto
2^64wrapped the offset around, the column was resized to the wrapped value and the data wasthen copied past the end of it.
appendStringSizesToColumnStringOffsets(the path that reads the sizes of the strings from aseparate stream) accumulated the sizes without checking them, and the offsets could wrap around
as well, after which the spans computed from them pointed outside the data of the column.
The single-value path now rejects a size above
SerializationString::MAX_STRING_SIZE, the hard limitthat is always enforced, next to the user-facing setting that can be disabled. The size stream
accumulates in
unsigned __int128, which cannot wrap, and the total is checked once againstMAX_TOTAL_STRING_SIZE: below that bound every offset it wrote is exact. The other layout of thesize stream, the cumulative byte offsets that
Nativecarries, is checked for monotonicity the waySerializationArraychecks its own offsets, and its total is bounded by the same limit in the caller,so both carriers end up enforcing one and the same invariant.
SerializationDynamic::deserializeBinaryrecurses into itself, driven by the type tags in the data,with nothing but the size of the input bounding the depth, so it now checks the stack size the way the
rest of the recursive code in ClickHouse does. The containers it can recurse through do not need a
check of their own: a deeply nested type has to be decoded before any value of it can be read, and
decodeDataTypeImplchecks the stack while decoding it.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix an integer overflow in the deserialization of
Stringvalues in the binary formats, and bound the recursion of the binary deserialization ofDynamicandJSONvalues.Workflow [PR]
Sync PR [sync-upstream/pr/115702]
Version info
26.9.1.702(included in26.9and later)26.8.3.41,26.7.7.30,26.6.5.55,26.3.32.8