Repository navigation
Arrow IPC: fix heap out-of-bounds reads and structural validation gaps in the column reader - #106395
Conversation
The Arrow IPC reader in ArrowColumnToCHColumn trusts schema-declared
sizes and row counts without validating them against the actual bytes
present in the RecordBatch body. A malformed Arrow file can declare
N rows while providing only a few bytes of body data, causing reads of
up to hundreds of megabytes past the allocated buffer. All paths are
reachable by any user with SELECT privilege (via file(), format(), or
table functions over Arrow/ORC/Parquet/ArrowFlight inputs).
Fixed paths (24 total):
Bulk-memcpy readers (checkArrowBuffer / checkedCast* family):
readColumnWithNumericData, readColumnWithDurationData,
readColumnWithFixedStringData, readColumnWithBigIntegerFromFixedBinaryData,
readColumnWithDate32Data (fast path), readColumnWithIndexesDataImpl,
readIPv4ColumnWithInt32Data
Per-element Value() readers (checkedCast validates before the loop):
readColumnWithBooleanData, readColumnWithDate32Data (slow path),
readColumnWithDate64Data, readColumnWithTimestampData,
readColumnWithTimeData (Time32 + Time64), readColumnWithFloat16Data,
readColumnWithDecimalDataImpl, readColumnWithUUIDFromFixedBinaryData
View-struct and offsets-buffer readers:
readColumnWithViewData (view-struct buffer + per-element variadic bounds),
readColumnWithStringData (offsets buffer before per-row data check),
readColumnWithJSONData (offsets buffer + per-row data buffer),
readOffsetsFromArrowListColumn (list offsets array),
getNestedArrowColumn (list/map offsets via Flatten())
Fix approach:
- Introduce checkArrowBuffer(chunk, elem_size, col) — validates
buffers[1]->size() >= elem_size * (offset + length) before any raw
pointer arithmetic.
- Introduce typed wrappers:
checkedCast<T>() — for numeric Arrow arrays (infers elem_size from
value_type); replaces dynamic_cast at all call sites
checkedCastFSB<T>() — for FixedSizeBinary arrays (uses byte_width())
checkedCastBool() — for Boolean (bit-packed, ceiling division)
checkedCastView<T>() — for StringView/BinaryView (16-byte view structs)
checkBinaryOffsetsBuffer() — for BinaryArray offsets buffer (+1 entry)
checkViewStruct() — per-element variadic buffer bounds for view arrays
- Replace all dynamic_cast calls on Arrow array types with the
appropriate checked wrapper; use dynamic_cast only where Arrow
subtypes may appear (BinaryArray, ListArray, MapArray) since
assert_cast requires an exact type match.
Regression tests in 04307/04308/04309_arrow_oob_reads*.sh cover all 24
paths using pyarrow-crafted Arrow IPC files with inflated row counts or
shrunk buffer declarations. Every case produces a clean INCORRECT_DATA
exception on the fixed build; on an unpatched ASan build each triggers
a heap-buffer-overflow.
Related: ClickHouse/clickhouse-private#59620
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
Workflow [PR], commit [eb46d92] Summary: ✅
AI ReviewSummaryThis PR hardens Arrow IPC, ORC, ArrowFlight, and related Arrow-backed conversion paths by validating data buffers, offsets, validity bitmaps, and nested array shapes before raw reads, Final VerdictStatus: ✅ Approve |
`readColumnWithBigNumberFromBinaryData`, `readColumnWithGeoData`, and `readIPv6ColumnFromBinaryData` all called `value_length(i)` or `value_offset(i)` inside a per-row loop before validating the offsets buffer size. The protection was accidental: downstream checks happened to throw `INCORRECT_DATA` for typical PoC inputs because the garbage values read from beyond the buffer failed subsequent comparisons. A crafted Arrow body where the bytes immediately after the offsets buffer look like plausible offset values could bypass those downstream checks. Fix: add `checkBinaryOffsetsBuffer(chunk, column_name)` per chunk before the first `value_offset`/`value_length` call in each of the three functions. This makes the guard explicit and unconditional, not dependent on garbage values. Regression tests added in 04309 (cases 25–27). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
5b6ed0a to
2cfbbe0
Compare
…p redundant static checkViewStruct accepted inline views without rejecting negative size values. size=-1 satisfies is_inline() (-1 ≤ kInlineSize=12), returning cleanly; then static_cast<size_t>(-1) in the accumulation loop wraps to SIZE_MAX, corrupting total_bytes_size and leading to a crash in the subsequent copy pass. readColumnWithBigNumberFromBinaryData and readIPv6ColumnFromBinaryData both had a validated first pass (offsets + value_length checks) but their copy loops called chunk.Value(value_i) without proving value_offset + sizeof(T) ≤ value_data()->size(). A crafted file with a valid offsets buffer but an undersized data buffer could over-read the heap in the copy loop. Fixes: - Add v.size() < 0 rejection before the is_inline() fast-path in checkViewStruct. - Add checkBinaryOffsetsBuffer + per-row data-buffer validation to the copy loops of readColumnWithBigNumberFromBinaryData and readIPv6ColumnFromBinaryData. - Remove redundant static from checkViewStruct (already in anonymous namespace). Regression tests added in 04309 (cases 28–30). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…n tests Issue A (arithmetic overflow): checkArrowBuffer, checkBooleanBuffer, and checkBinaryOffsetsBuffer computed required byte counts with unchecked size_t multiplication. A crafted row count near 2^62 makes elem_size * count wrap to 0 mod 2^64, causing the guard to accept a tiny buffer. Fixed using __builtin_mul_overflow (data buffer) and explicit overflow-safe ceiling division (boolean/offsets). In practice reserve() always rejects the file first (Code 173), so no OOB read was reachable; the fix makes the rejection explicit and deterministic. Issue B (validity bitmap): readByteMapFromArrowColumn and all per-chunk processing paths called IsNull() / IsValid() without validating that buffers[0] (the validity bitmap) is large enough for the declared row count. A file with a valid data buffer but a truncated bitmap (e.g. 1 byte for 64 rows) would let IsNull() read adjacent body data as null flags. Fixed by adding checkValidityBitmap which checks ceil((offset+length)/8) bytes and is called at the end of checkArrowBuffer, checkBooleanBuffer, and checkBinaryOffsetsBuffer (so every data-buffer validation also validates the bitmap), plus explicitly in readByteMapFromArrowColumn. Regression tests in 04310_arrow_oob_reads_arithmetic.sh. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…tive offsets - Initialize `required = 0` in `checkArrowBuffer` and `checkBinaryOffsetsBuffer` before `__builtin_mul_overflow` writes to it, fixing the cppcoreguidelines-init-variables clang-tidy error that failed the arm_tidy build. - Replace `safe_offset + sizeof(T) > data_buf_size` with the two-part check `safe_offset > data_buf_size || sizeof(T) > data_buf_size - safe_offset` in the copy loops of `readColumnWithBigNumberFromBinaryData` and `readIPv6ColumnFromBinaryData`. The single-expression form wraps to a small value when `safe_offset` is cast from a negative `int32_t`, letting a crafted `[-8, 8]` offset pair bypass the guard. Arrow 23's IPC reader already rejects negative per-row offsets during batch loading, so this is defence-in- depth; the format string in the exception now logs the signed offset for clarity. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
`total_size += chunk_length` was inside the per-row validation loop, incrementing by `chunk_length` once per row instead of once per chunk. For a valid chunk with N rows all of the expected width the loop ran N times and added N each time, reserving N² elements before inserting N. Move the increment outside the loop to match the IPv6 path, which already had it in the correct position. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Replace all abbreviations with full names: checkedCastFSB → checkedCastFixedSizeBinary ArrowFSBArray → ArrowFixedSizeBinaryArray Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
getNestedArrowColumn now calls checkValidityBitmap on the parent list (or map) chunk before Flatten(). When null_count > 0, Flatten iterates over each row calling IsValid on the parent array, which reads the validity bitmap (buffers[0]). Without the preflight a crafted file with a truncated parent bitmap but valid offsets and child buffers could silently read past the end of the bitmap allocation. Regression test added as case 31 in 04309_arrow_oob_reads_offsets.sh: 128-row nullable List(Int32) with valid offsets and child data but a 1-byte parent bitmap (instead of the required 16 bytes). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
antaljanosbenjamin
left a comment
There was a problem hiding this comment.
I haven't checked the tests, but the changes looks good in general.
Add explicit guards at the top of `checkValidityBitmap`, `checkArrowBuffer`, `checkBooleanBuffer`, and `checkBinaryOffsetsBuffer` that throw `INCORRECT_DATA` when `chunk.length() < 0` or `chunk.offset() < 0`. The specific gap that motivated this: `checkBinaryOffsetsBuffer` computed `count_plus_one = static_cast<size_t>(-1) + 1 = 0`, so `required = 0` and the buffer-size check passed trivially for a crafted file with `FieldNode.length = -1`. Arrow's IPC reader accepts such a file when `RecordBatch.length` and `FieldNode.length` are consistently negative, which caused the subsequent per-row loop to iterate as if `chunk_length = SIZE_MAX`, reading `offsets[6]` past the end of a 5-row offsets buffer before the per-row bounds check caught the garbage value. The other three check functions (`checkArrowBuffer`, `checkBooleanBuffer`, `checkValidityBitmap`) were already safe via `SIZE_MAX * elem_size` overflow or `SIZE_MAX / 8` exceeding any real buffer, but the explicit guard makes the invariant self-contained and uniform across all helpers. Adds regression test `04326_arrow_oob_neg_length`. Related: ClickHouse#106395
In `readColumnWithBigNumberFromBinaryData` and `readIPv6ColumnFromBinaryData`, the first pass already validates that every `value_length(i) == sizeof(ValueType)` / `sizeof(IPv6)`, so using `chunk.Value(value_i).size()` in the insert is misleading — it implies the size is variable when it has been proven fixed. Use the constant `sizeof(T)` directly. Addresses review comment on ClickHouse#106395
In `readOffsetsFromArrowListColumn`, computing `uint64_t elements = offset - previous_offset` with unsigned arithmetic underflows when Arrow offsets are not monotonically non-decreasing. A crafted offset sequence like [0,32,33,34,35,36,37,38,32] makes the cumulative last offset wrap to exactly `nested.size()`, bypassing the `ColumnArray` constructor check (`data->size() == last_offset`) and constructing a `ColumnArray` whose interior offsets point past the inner-column allocation. Fix: use `int64_t` throughout, check that `first_offset >= 0`, and throw `INCORRECT_DATA` when any offset is less than the previous one. Adds regression test `04327_arrow_list_nonmonotonic_offsets` covering both `List` (int32 offsets) and `LargeList` (int64 offsets). Refs: ClickHouse/clickhouse-private#60305 Related: ClickHouse#106395
Use inner_size=64 (exact Arrow allocation unit, no padding) with offsets [0,64,65,64]. Row 1 starts at inner[64], one byte past the allocation; row 2's underflow wraps last_offset to 64 == inner_size so the ColumnArray constructor accepts it on unpatched code. SELECT arrayElement(arr,2) materialises row 1 and triggers an ASan abort on the unpatched build, confirming this is a critical OOB read, not just corrupt length output.
`ColumnArray::create` skips the `data->size() == last_offset` invariant when the child column is empty (`&& !data->empty()` short-circuit in `ColumnArray.cpp`). A crafted Arrow file with a child `FieldNode.length` patched to 0 could therefore produce a `ColumnArray` whose offsets pointed past the empty inner allocation, causing an OOB heap read. Add an explicit pre-construction check in `readColumnFromArrowColumn`: validate `off.back() == array_data_column->size()` before calling `ColumnArray::create` and `ColumnMap::create`. Regression test added to `04327_arrow_list_nonmonotonic_offsets.sh` covering `FixedSizeList` and `List` with empty child. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Two latent issues in the anonymous-namespace buffer validation helpers: 1. `chunk.offset() + chunk.length()` was computed in signed `int64_t` before being cast to `size_t`, which is UB if both values approach `INT64_MAX`. Cast each operand to `size_t` individually before adding; both are guaranteed non-negative at that point, and their sum fits in `size_t` (at most `2*INT64_MAX = UINT64_MAX-1`). Affects `checkValidityBitmap`, `checkArrowBuffer`, `checkBooleanBuffer`, and `checkBinaryOffsetsBuffer`. 2. `getValidatedBuffer` unconditionally dereferenced `buffers[1]->data()` after `checkArrowBuffer` passed. Arrow allows a null `buffers[1]` when the array is empty (`offset == 0, length == 0`); `checkArrowBuffer` passes in that case because `required == 0`. Guard with a null check and return `nullptr` when the buffer is absent — safe because callers iterate `chunk.length()` rows and the loop body is never entered. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… structural validation gaps in the column reader
Cherry pick #106395 to 25.8: Arrow IPC: fix heap out-of-bounds reads and structural validation gaps in the column reader
… structural validation gaps in the column reader
The native record-batch decoder is now the default reader, so the malformed-input regression tests added by #106395 (`04309`, `04310`, `04327`, `04329`, `04330`) exercise it instead of the Apache Arrow library reader. Several of them reached an oversized allocation (`MEMORY_LIMIT_EXCEEDED` / `CANNOT_ALLOCATE_MEMORY`) or returned a silently-wrong result instead of being rejected as `INCORRECT_DATA`. Harden the decoder to reject the corruption before any allocation: - `requiredBytes`: overflow-safe `count * elem_size` used at every `checkBufferSize` call site. A forged row count near 2^62 otherwise wrapped the product to a small value, passed the buffer-size guard, and then drove a `resize`/`reserve` of the full (huge) row count. - String columns: validate the offsets buffer before `reserve`, so an inflated row count cannot reserve gigabytes before the check fires. - `Struct`: every field's `FieldNode.length` must equal the parent row count; reject unequal-sized fields (a shortened or out-of-range-sliced child), which the library reader's `StructArray::field` silently clamps. - `List`/`LargeList`/`Map`: reject a negative first offset and offsets whose last absolute value points past the decoded child/entries (e.g. `[1,1]` over a zero-length child), which the relative-span check missed. - `decodeField`: validate the validity bitmap against the row count whenever the field declares nulls, even when the column type drops the null map (`Array`/`Tuple`/`Map` cannot be `Nullable`), so a forged-huge null count or a truncated bitmap is rejected before allocating/scanning. - `fixed_size_binary` read as `UUID`: reject any width other than 16 before reserving the UUID column, matching the library reader's `byte_width` check (a narrower width is also a per-row heap over-read). #106522 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Backport #106395 to 25.8: Arrow IPC: fix heap out-of-bounds reads and structural validation gaps in the column reader
Backport #106395 to 26.3: Arrow IPC: fix heap out-of-bounds reads and structural validation gaps in the column reader
Backport #106395 to 26.4: Arrow IPC: fix heap out-of-bounds reads and structural validation gaps in the column reader
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1679 Labels added:
These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels. |
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1895 Labels added:
These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels. |
… reads and structural validation gaps in the column reader
…6395 Backport ClickHouse#106395 to 26.4: Arrow IPC: fix heap out-of-bounds reads and structural validation gaps in the column reader
The native record-batch decoder is now the default reader, so the malformed-input regression tests added by ClickHouse#106395 (`04309`, `04310`, `04327`, `04329`, `04330`) exercise it instead of the Apache Arrow library reader. Several of them reached an oversized allocation (`MEMORY_LIMIT_EXCEEDED` / `CANNOT_ALLOCATE_MEMORY`) or returned a silently-wrong result instead of being rejected as `INCORRECT_DATA`. Harden the decoder to reject the corruption before any allocation: - `requiredBytes`: overflow-safe `count * elem_size` used at every `checkBufferSize` call site. A forged row count near 2^62 otherwise wrapped the product to a small value, passed the buffer-size guard, and then drove a `resize`/`reserve` of the full (huge) row count. - String columns: validate the offsets buffer before `reserve`, so an inflated row count cannot reserve gigabytes before the check fires. - `Struct`: every field's `FieldNode.length` must equal the parent row count; reject unequal-sized fields (a shortened or out-of-range-sliced child), which the library reader's `StructArray::field` silently clamps. - `List`/`LargeList`/`Map`: reject a negative first offset and offsets whose last absolute value points past the decoded child/entries (e.g. `[1,1]` over a zero-length child), which the relative-span check missed. - `decodeField`: validate the validity bitmap against the row count whenever the field declares nulls, even when the column type drops the null map (`Array`/`Tuple`/`Map` cannot be `Nullable`), so a forged-huge null count or a truncated bitmap is rejected before allocating/scanning. - `fixed_size_binary` read as `UUID`: reject any width other than 16 before reserving the UUID column, matching the library reader's `byte_width` check (a narrower width is also a per-row heap over-read). ClickHouse#106522 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
PROTO: malformed Arrow IPC input -> crash (OOB). Effect in the production build a394e92: its upstream test(s) 04307_arrow_oob_reads, 04308_arrow_oob_reads_value, 04309_arrow_oob_reads_offsets, 04310_arrow_oob_reads_arithmetic, 04327_arrow_oob_list_offsets, 04328_arrow_oob_nested_child_length, 04329_arrow_oob_struct_fields, 04330_arrow_oob_declared_length, 04331_arrow_oob_validity_bitmap fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv). Upstream patch unchanged, with its test(s): 04307_arrow_oob_reads,04308_arrow_oob_reads_value,04309_arrow_oob_reads_offsets,04310_arrow_oob_reads_arithmetic,04327_arrow_oob_list_offsets,04328_arrow_oob_nested_child_length,04329_arrow_oob_struct_fields,04330_arrow_oob_declared_length,04331_arrow_oob_validity_bitmap. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Linked issues
Related: https://github.com/ClickHouse/clickhouse-private/issues/59620
Related: https://github.com/ClickHouse/clickhouse-private/issues/60305
Heap out-of-bounds reads and missing structural validation in the Arrow IPC reader
allow any authenticated user to leak heap memory or read past heap allocations by
sending a crafted Arrow file (via
file(),format(), table functions, orArrowFlight). A malformed Arrow IPC file can declare N rows while providing only a
few bytes of body data, declare child arrays whose lengths are inconsistent with
their parent list/struct/map, supply non-monotonic or decreasing list offsets, or
truncate a child validity bitmap. Without validation the readers perform
memcpyor per-element
Value()calls past the end of the allocated buffers, or trustArrow's lazy
null_countscan over a truncated bitmap.What was fixed
Buffer-size validation — new helpers in an anonymous namespace guard every raw
buffer access;
checkedCast*replacesdynamic_castthroughout:checkArrowBuffer/checkValidityBitmap/checkBooleanBuffer/checkBinaryOffsetsBuffervalidate buffer sizes before raw pointer use, withoverflow-safe arithmetic (
__builtin_mul_overflow, ceiling division,offsetand
lengthsummed assize_t)checkedCast<T>/checkedCastFixedSizeBinary<T>/checkedCastBool/checkedCastView<T>perform the typed cast and the buffer check in one call, sothe check cannot be forgotten
checkViewStructenforces per-element variadic-buffer bounds forStringView/BinaryViewand rejects negative view sizes before theis_inline()checkThis covers the bulk-memcpy readers, the per-element
Value()readers, theview-struct readers, and the offsets-buffer readers (string, JSON, geo, big number,
IPv6, list/map offsets). The big-number reader also had an N² reserve fixed.
Structural and consistency validation — buffer sizes alone do not make a column
safe; the shapes must also be consistent:
column size (closes the
ColumnArrayempty-child short-circuit that acceptedoffsets pointing past an empty child)
non-decreasing, in a shared helper called before
Flattenslices the valuesarray (a decreasing pair otherwise failed deep inside Arrow's
ArrayData::Slice)(offset + length) * stridemust not overflow, and the slice must stay within the values array, checked before
Flatten(
arrow::StructArray::field()silentlySlice-clamps a short child, and this alsocovers
Mapkey/value length mismatches)Lazy
null_countscan — Arrow computesnull_countby scanning the validitybitmap; a child produced by
Slice/Flattencarries an unknown count, andarrow::ChunkedArray's constructor sumschunk->null_count(), scanning apossibly-truncated child bitmap before any validation.
checkValidityBitmapis nowscan-free (it validates the buffer whenever a bitmap is present and never calls
null_count) and is applied to each flattened list child and struct field before theChunkedArrayconstructor reads it.Empty-chunk handling — an empty record batch before a non-empty one can leave
buffers[1]null; theDate32numeric-hint branch andreadColumnWithViewDatanowskip zero-length chunks before forming a pointer.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix multiple heap out-of-bounds reads in the Arrow IPC format reader (
ArrowColumnToCHColumn). A malformed Arrow file could declare more rows than its buffers contain, declare list/struct/map child lengths inconsistent with their parent, supply non-monotonic list offsets, or truncate a child validity bitmap, causing reads past the end of heap allocations. This is reachable by any user withSELECTprivilege viafile(),format(), table functions, or ArrowFlight inputs. All data, offsets, view-struct, and validity-bitmap buffers are now validated before any raw pointer access, and list/struct/map shapes and offsets are checked for consistency.Version info
26.6.1.66926.5.3.25,26.4.5.38,26.3.14.29,25.8.25.23