Repository navigation
Fix out-of-bounds reads when reading malformed JSON and Dynamic columns - #117765
Conversation
…format The FLATTENED branch of `SerializationObject::deserializeBinaryBulkWithMultipleStreams` unflattens `limit` rows out of the path columns without checking that the streams produced that many rows, so a truncated Native block made `unflattenAndInsertPaths` read past the end of a deserialized column. Nothing downstream catches it: `ColumnObject::size()` is the size of shared data, which unflattening fills to exactly `limit` regardless of the paths. Two shapes reached it. A short indexes stream of a flattened `Dynamic` stays self-consistent, because the per-type limits are derived from the indexes that were actually read and a run of NULL markers demands no values at all, so the existing per-type check passed and the shortened column was then read for `limit` rows. A short typed path stream was accepted outright and only failed later, when the resulting column was read. Validate both: every typed and flattened path column must advance by exactly `limit` rows before unflattening, and the indexes column of a flattened `Dynamic` must hold `limit` rows. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [290252f] Summary: ✅
AI ReviewSummaryThis PR hardens Findings
Tests
Final VerdictChanges requested: the core out-of-bounds fixes are valuable, but validation is still incomplete on subcolumn readers and corrupted-part paths still raise LLVM Coverage Report |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+72.48 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units106 translation units recompiled, 884 s compile time in total, 106 of them have a recent master baseline. |
Algunenano
left a comment
There was a problem hiding this comment.
Left some comments in the original issue
… format A follow-up review of the same code found more ways to make the reader of a JSON or Dynamic column read out of bounds, or to escape as an internal error instead of a data error. `NativeWriter` writes only the `V1`, `V2`, `STRING` and `FLATTENED` serialization versions, and MergeTree only `V1`, `V2` and `V3`, but the reader accepted every version on both channels. Over Native that opened the whole shared data machinery of `V3` -- buckets, granules, stream marks -- to a hand-built block, and a block that declared more granules in one bucket than in bucket 0 aborted a release server on the first request. Each version is now rejected on the channel it is never written to. In the list of types of a flattened `Dynamic` column, two equal types map onto the same variant discriminator, and `fillDynamicColumn` then replaces the variant column a second time while the offsets still refer to the first, larger one -- an out-of-bounds read from a complete, self-consistent payload. `Nothing` is dropped by `DataTypeVariant`, so such a type has no discriminator to unflatten into and escaped as `std::out_of_range`. Both are rejected now. The check for duplicates is moved here from #115702, because this change is the one that gets backported. In the list of paths of an Object column, a repeated path, or a path that the type of the column declares as a typed path, is stored in the column twice, once as a dynamic path and once in shared data. Such a block was written into a part without a complaint and every later read of the column failed with `LOGICAL_ERROR`, or, for the typed collision, returned a JSON value with a duplicated key. On the part side, which is reachable with bytes the user chooses through `RESTORE` of a user-managed backup, a `web`/`s3_plain` disk or `ATTACH PART`, the reader of the shared data paths indexes stopped silently at the end of the stream, leaving the paths column shorter than the offsets say. Reading such a part segfaulted a release server. It now fails as a read error, and the checks of the sizes of the buckets, of the granule layout across buckets and of the values column are added next to it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…is pull request The check and its test are already in #117765, in the same place and in a stricter form: that pull request also rejects `Nothing` in the list of types and a structure version that does not belong to the format being read. Keeping both would only conflict, and this pull request is about the deserialization of `String`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The readers of the ADVANCED shared data serialization take the granule layout from bucket 0 and then index every other bucket with it, so a bucket with fewer or shorter granules is read out of bounds. The check added for the reader of the whole shared data column covered only that one reader, and the same layout is used by the sub-object reader (`json.^a`) and by the distinct paths reader, where bucket 0's offset and limit are also used to index the Dynamic columns of the other buckets. The check now lives in one place and is called by all three, and it compares the offset of the granule as well. The MAP_WITH_BUCKETS branch of the distinct paths reader takes the number of rows of the result from bucket 0 while it appends the paths of all buckets, and it ends with `insertManyDefaults(num_new_rows - 1)`, so a bucket 0 that read no rows turned into an insert of SIZE_MAX values. Every bucket has to have the number of rows of the first one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The granule layout of the ADVANCED shared data serialization and the sizes stream describe the same rows, but they are read independently, and nothing compared them. A structure stream that ends early leaves a layout that covers fewer rows than the sizes stream provides, and reading such a part segfaulted: the check across buckets added before does not catch it, because a part where every bucket is equally short is consistent with itself. The number of rows of the layout is compared with the number of rows read from the sizes stream now, which is the same corruption that `SerializationArray` reports as `CANNOT_READ_ALL_DATA`, so it is reported the same way and can be tested. `deserializePathsData` returned the column of a path without checking that it holds the rows of the granule, and the wide branch dereferenced the stream of the values without checking it for null while the compact branch above it does. Neither is reachable today -- a short path column is caught by the size checks of `Variant`, and a part without the values stream is detached as broken before it is read -- but both are one refactoring away from being. `SerializationSubObject` read every typed path, dynamic path and shared data with the same limit and never checked that they agree, unlike `SerializationObject`. A shared data stream that ends early silently dropped rows from a sub-object read. The duplicate check of the flattened paths kept string views into the vector of the paths while it was still being filled. The reserve of that vector is capped, so a block with more than a million paths reallocates it in the middle of the loop, and short paths are stored inside the string object, so every view already in the set pointed into the freed buffer (ASan: heap-use-after-free, reported by Raúl Marín). The paths are read first and the duplicates are looked for afterwards, when the vector no longer moves. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Algunenano
left a comment
There was a problem hiding this comment.
LGTM. The new code is easy to understand, and it covers many corner cases. My only concern is evolving this and not breaking all the invariants, but this is the nature of serialization code when you need to handle external writers.
The AI bot still complains about a couple of cases, but those are handled via LOGICAL_ERROR exceptions and do not produce OOB.
…nitizers Both tests spent all of their time starting processes: 05055 started a client for each of the 114 truncations of its payloads, and 05056 a `clickhouse-local` for each of its 9 blocks. A process start costs ~2.3 s in the build with ASan and ~37 s in the one with MSan, so the tests took 286 s and 332 s there and were failed by the 180 s limit of the reruns, while locally they take seconds. The blocks are sent over HTTP now, which keeps the same coverage -- the same payloads, the same step of the sweep -- and moves the work to the server that is already running. 05056 gained the row counts of its tables, so that a block that is accepted does not go unnoticed, and it no longer reads the blocks through schema inference, whose error wrapped the one being checked. 05055 is skipped with the old analyzer: the queries that build its payloads read JSON and Dynamic subcolumns, which it cannot resolve (`Unknown column: json.a` for the Dynamic payload, `Missing columns: 'x.a'` for the array one), while what the test checks is the deserialization of the Native format. Reruns of the tests in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117765&sha=latest&name_0=PR Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Inserting the blocks over HTTP appends `: While executing Native` to the message of the exception, which the reference of the test does not have, because the messages were collected while the blocks were read through `clickhouse-local`. The reference states why a block is rejected, not where it happened, so the context is cut off instead of being added to it. Fast test in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117765&sha=3f8f086f73b7c500ec34f81e40b2304552eaf8a6&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…d data The reader of the distinct paths of a JSON column builds one row with all the paths and fills the rest of the requested rows with empty ones, and it counted the rest as `num_new_rows - 1`. The streams are allowed to return fewer rows than the limit, down to none at all, and then that count is `SIZE_MAX`. Nothing is inserted when no rows were read now. The test of a part with a truncated stream took the directory of the part from a glob over `all_1_2_1` and spelled out the names of the streams, and both were wrong on the runner with macOS, where it found neither of the two streams it truncates. The directory comes from `system.parts` now and the names are matched, so the test no longer depends on the layout of the part, and the listing of the part is printed when a stream is missing, so that a failure names its own cause. Fast test (arm_darwin) in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117765&sha=86a2c1842ba7c98bf33b52e7b705f7cd1730221d&name_0=PR Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…n-native-oob-read # Conflicts: # src/DataTypes/Serializations/SerializationObjectDistinctPaths.cpp # src/DataTypes/Serializations/SerializationObjectSharedData.cpp # src/DataTypes/Serializations/SerializationObjectSharedData.h # src/DataTypes/Serializations/SerializationSubObjectSharedData.cpp
The page listed the shared data serialization versions of an `Object` column and how to validate the count of its buckets, but that sub-version is read only in `V3`, which this change rejects in a `Native` stream, and `V1` and `V2` always use `MAP` without buckets. None of it can reach a decoder of the format, and the layouts it describes belong to a part rather than to a block. The rows of `V3` itself are kept, because the values are assigned and must not be reused, and a decoder that meets one should know what it is rejecting. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every block of the test declares version 4 of the Object structure, which is written into MergeTree parts only and is refused in a Native stream now, so the guard the test was written for is no longer reachable from there and the blocks are rejected before the count is read. Three of the four cases even kept passing, because the refusal raises `INCORRECT_DATA` as well, which is what they expect. The guard itself stays: it is what rejects the count of a corrupted part, and the refusal of version 4 is covered by `05056_json_dynamic_native_malformed_structure`. Fast test in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117765&sha=8c6ad24be00c431f0e1c436db290aa491e79ec9c&name_0=PR Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…attened-json-native-oob-read
| /// Verify that all typed paths, dynamic paths and shared data has consistent sizes | ||
| size_t expected_size = column_object.getSharedDataPtr()->size(); | ||
| for (const auto & [path, path_column] : typed_paths) | ||
| { | ||
| if (path_column->size() != expected_size) | ||
| throw Exception(settings.native_format ? ErrorCodes::INCORRECT_DATA : ErrorCodes::LOGICAL_ERROR, "Unexpected size of typed path {}: {}. Expected size {}", path, path_column->size(), expected_size); | ||
| } | ||
|
|
||
| for (const auto & [path, path_column] : dynamic_paths) | ||
| { | ||
| if (path_column->size() != expected_size) | ||
| throw Exception(settings.native_format ? ErrorCodes::INCORRECT_DATA : ErrorCodes::LOGICAL_ERROR, "Unexpected size of dynamic path {}: {}. Expected size {}", path, path_column->size(), expected_size); |
There was a problem hiding this comment.
These new consistency checks still map malformed MergeTree-part bytes to LOGICAL_ERROR when settings.native_format is false. SerializationSubObject is the json.^... entrypoint, so a truncated or corrupted part now aborts debug/ASan builds here instead of surfacing the read error this PR promises for part-backed corruption. Please use a data/read error (CANNOT_READ_ALL_DATA or INCORRECT_DATA) on the part path as well, and add a regression on the sub-object reader; 05057_json_part_truncated_shared_data.sh only exercises whole-column SELECT json.
| /// All buckets store the same rows, and the number of rows of the first one is used as | ||
| /// the number of rows of the result. | ||
| else if (bucket_shared_data_paths_column->size() != num_new_rows) | ||
| throw Exception( | ||
| ErrorCodes::LOGICAL_ERROR, | ||
| "Bucket {} of Object shared data has {} rows, but bucket 0 has {} rows", |
There was a problem hiding this comment.
This bucket-row-count guard is also validating externally supplied part bytes, but it still throws LOGICAL_ERROR. SerializationObjectDistinctPaths backs JSONAllPaths / distinct-path subcolumns, so a malformed MAP_WITH_BUCKETS part can still abort debug/ASan builds on this entrypoint instead of returning a corruption/read error. Please use CANNOT_READ_ALL_DATA or INCORRECT_DATA here too, and extend the malformed-part coverage beyond the whole-column reader.
Backport #117765 to 26.9: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
…ing malformed JSON and Dynamic columns
Cherry pick #117765 to 26.3: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
Cherry pick #117765 to 26.7: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
Cherry pick #117765 to 26.8: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
…med JSON and Dynamic columns
…med JSON and Dynamic columns
…med JSON and Dynamic columns
Backport #117765 to 26.7: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
Backport #117765 to 26.8: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
Backport #117765 to 26.3: Fix out-of-bounds reads when reading malformed JSON and Dynamic columns
The FLATTENED branch of
SerializationObject::deserializeBinaryBulkWithMultipleStreamsunflattens the row count declared in theNativeblock header out of the path columns without checking that the streams produced that many rows. A truncated block madeunflattenAndInsertPathsread past the end of a deserialized column, crashing the server or copying unrelated heap contents into the inserted data.NativeReadercannot catch it, becauseColumnObject::size()is the size of shared data, which unflattening fills to exactly the declared row count. Any user who can sendINSERT ... FORMAT Nativeinto a table with aJSONcolumn can reach it — the serialization version comes from the stream.A short typed path stream was accepted outright. A short indexes stream of a flattened
Dynamicalso passed the existing per-type check, because the per-type limits are derived from the indexes that were actually read, and a run of NULL markers demands no value bytes at all. Now every typed and flattened path column must advance by exactlylimitrows before unflattening, and the indexes column of a flattenedDynamicmust holdlimitrows.A follow-up review found more ways to read the same columns out of bounds, most of them nothing to do with truncation, so the rest of the structure prefix is validated too:
NativeWriterwrites onlyV1,V2,STRINGandFLATTENED, and MergeTree onlyV1,V2andV3, but the reader accepted every version on both channels. Over Native that exposed the shared data machinery ofV3— buckets, granules, stream marks — to a hand-built block, where a bucket declaring more granules than bucket 0 aborted a release server on the first request. Each version is now rejected on the channel it is never written to.Dynamiccolumn map onto one variant discriminator, and the variant column is then replaced a second time while the offsets still refer to the first, larger one.Nothingis dropped byDataTypeVariant, so it has no discriminator to unflatten into and escaped asstd::out_of_range.RESTOREof a user-managed backup, aweb/s3_plaindisk orATTACH PART— the reader of the shared data paths indexes stopped silently at the end of the stream, leaving the paths column shorter than the offsets say, and reading such a part segfaulted. It fails as a read error now, and the sizes of the buckets, the granule layout across buckets and the size of the values column are checked next to it.Related: #115702 — the check for duplicate types in a flattened
Dynamiccolumn is moved here from it, since this change is the one that gets backported.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed out-of-bounds reads when reading a
JSONorDynamiccolumn from a malformedNativeblock or a corrupted data part. A truncated stream, a duplicate type in a flattenedDynamiccolumn, a duplicate or typed-colliding path in aJSONcolumn, and a serialization version that is only ever written into a data part but sent over the wire, all made the server read past the end of a deserialized column, which could crash it or store unrelated heap contents in the inserted data. All of them are now rejected.Workflow [PR]
Sync PR [sync-upstream/pr/117765]
Version info
26.10.1.997-master(included in26.10and later)26.9.6.8,26.8.16.27,26.7.20.16,26.3.39.13