Repository navigation
Add fuzz targets for compression codecs, NativeReader, DataTypes, and WASM - #99653
Conversation
|
Workflow [PR], commit [f6398d6] Summary: ✅
AI ReviewSummaryThis PR adds a broad set of fuzz targets plus the supporting corpus-sync, triage, and packaging glue. A lot of the earlier coverage gaps were fixed, but I still see a few contract-breaking issues in the new harness/tooling: three serialization fuzzers parse their documented 10-byte header through a padded 16-byte C struct, Findings
Final Verdict
LLVM Coverage ReportMeasured on commit f6398d6.
Changed lines: Uncovered code analysis did not run: No coverable C/C++ source files changed (contrib/ is excluded from coverage). Newly covered: +182 lines in 44 files (-103 lines lost coverage) · Details |
Algunenano
left a comment
There was a problem hiding this comment.
Please consider separating the PR into 2:
- The buffer overflow fix with a test (please add one), so that it can be backported easily.
- The addition of new fuzzers
|
changed per comments,Opened PR: #99680 That PR contains:
This fuzzers PR still includes commit |
LLVM Coverage Report
PR changed lines: PR changed-lines coverage: 69.44% (25/36, 0 noise lines excluded) |
|
/recheck |
- `cmake/sanitize.cmake`: add `trace-cmp` to `COVERAGE_FLAGS` and `WITHOUT_COVERAGE_FLAGS` so libFuzzer automatically solves magic-byte comparisons in `BinaryTypeIndex`, `CompressionMethodByte`, protocol version checks and similar switch statements with zero changes to any fuzz target - All `tests/fuzz/*.options`: add `use_value_profile = 1` to every `[libfuzzer]` section to track input-dependent comparison values and help solve multi-byte checks - `src/Interpreters/WebAssembly/WasmTimeRuntime.cpp`: fix integer overflow in `getMemory` where `ptr + size` (both `uint32_t`) could wrap around and bypass the bounds check, allowing host-memory access from WASM guest code. Widen both operands to `uint64_t` before addition so `ptr=0xFFFFFFFF, size=2` correctly throws an exception. Three codecs with complex bit-manipulation and the dangerous `CompressionCodecMultiple` (attacker-controlled codec chaining via `source[0]` = chain length, `source[1..N]` = `CompressionMethodByte`) had no dedicated fuzzers. Added: - `src/Compression/fuzzers/gorilla_decompress_fuzzer.cpp` - `src/Compression/fuzzers/t64_decompress_fuzzer.cpp` - `src/Compression/fuzzers/fpc_decompress_fuzzer.cpp` - `src/Compression/fuzzers/multiple_decompress_fuzzer.cpp` Each follows the `delta_decompress_fuzzer` pattern; Gorilla/T64/FPC use `CompressionCodecFactory::instance().get(method_byte)` since these codecs read their own parameters from the compressed data header, making the construction-time parameters irrelevant for decompression fuzzing. `src/DataTypes/DataTypesBinaryEncoding.cpp` performs recursive type construction from a binary stream with ~55 type indices. Added: - `src/DataTypes/fuzzers/decode_data_type_fuzzer.cpp`: feeds raw bytes to `decodeDataType(ReadBuffer&)` and, on success, exercises the decoded type's default serialization path - `tests/fuzz/dictionaries/binary_types.dict`: all BinaryTypeIndex bytes 0x00-0x36 plus common VarUInt encodings `SerializationLowCardinality` has complex index arithmetic where a dictionary index > dictionary size causes OOB access. Added: - `src/DataTypes/fuzzers/serialization_lowcardinality_fuzzer.cpp`: exercises `deserializeBinaryBulkStatePrefix` + `deserializeBinaryBulkWithMultipleStreams` for both `LowCardinality(String)` and `LowCardinality(Nullable(UInt64))`, toggling `native_format` via the auxiliary header byte - `tests/fuzz/dictionaries/compression.dict`: `CompressionMethodByte` values, data-bytes-size hints, Gorilla/T64/FPC header patterns, and `CompressionCodecMultiple` chain examples - `tests/fuzz/build.sh`: also copy `tests/fuzz/dictionaries/*.dict` to `$OUT/` so the new `.options` files can reference them by name Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
## New fuzz targets ### NativeReader binary protocol fuzzer (P1 Critical) `NativeReader` is the primary binary inter-server and TCP client protocol parser — it reads attacker-controlled `VarUInt` column/row counts and constructs column data from untrusted streams. No dedicated fuzzer existed. - `src/Formats/fuzzers/native_reader_fuzzer.cpp`: toggles `decode_types_in_binary_format` via `data[0]` (0 = text type names with `DBMS_MIN_REVISION_WITH_CLIENT_INFO`, 1 = binary `BinaryTypeIndex` encoding with `DBMS_TCP_PROTOCOL_VERSION`), feeds remaining bytes directly into `NativeReader::read()` and drains the block stream, exercising both the classic and binary type-encoding paths including `SerializationInfo` custom serialization. ### WASM module fuzzer (P1 High) Feeds raw bytes as WASM bytecode to the compile → instantiate → invoke pipeline, covering the `WasmTimeRuntime` and `WasmEdgeRuntime` sandbox boundaries. Uses `data[0]` to select the backend when both are compiled in. Instantiates with 16 MiB guest memory and 1M-instruction fuel limit to prevent infinite loops. Tries `_start` and `main` exports independently. - `src/Interpreters/fuzzers/wasm_fuzzer.cpp` - `tests/fuzz/dictionaries/wasm.dict`: WASM magic, version, section IDs, opcodes, and value type bytes to seed meaningful WASM structure. ### ColumnVariant / ColumnDynamic `insertRangeFrom` fuzzer (P2 Medium) `ColumnVariant::insertRangeFrom` uses a discriminator mapping between source and destination local variant orders; invalid mappings cause OOB access. Exercises three code paths: - A-1: mismatched local-to-global orderings via `insertRangeFrom` - A-2: explicit `global_discriminators_mapping` vector path - A-3: `ColumnDynamic::insertRangeFrom` - `src/Columns/fuzzers/column_variant_fuzzer.cpp` - `src/Columns/CMakeLists.txt`: add `fuzzers/` subdir under `ENABLE_FUZZING` ## Tooling ### Crash triage script (`tests/fuzz/triage.py`) Groups libFuzzer crash files by stack hash (top 5 frames, addresses stripped), classifies severity (CRITICAL: heap-buffer-overflow write / use-after-free write; HIGH: read variants and stack OOB; MEDIUM: UB / assertion / SEGV; LOW: timeout / OOM / leak), and generates a markdown report sorted by severity. Can replay crashes through a fuzzer binary via `--fuzzer-binary` to capture live sanitizer output. ### Corpus cross-pollination (`tests/fuzz/corpus_sync.sh`) Copies corpus entries between related fuzzers using `cp -n`: - `decode_data_type_fuzzer` ↔ `data_type_deserialization_fuzzer` (bidirectional — binary and text type encodings share structure) - `gorilla_decompress_fuzzer`, `t64_decompress_fuzzer`, `delta_decompress_fuzzer` → `multiple_decompress_fuzzer` (codec output from individual fuzzers seeds the chained-codec fuzzer) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Phase 3.1 — `LLVMFuzzerCustomMutator` for `native_reader_fuzzer`:
- New `src/Formats/fuzzers/native_reader_custom_mutator.cpp` with
structure-aware mutations that preserve the mode byte (byte 0) and
inject known-valid ClickHouse type names as VarUInt-length-prefixed
strings to accelerate type-parsing code path discovery.
- Implements `LLVMFuzzerCustomCrossOver` for interleaved parent payloads.
- Linked into `native_reader_fuzzer` by updating `CMakeLists.txt`.
Phase 5.2 — focused WASM bounds-check harness:
- New `src/Interpreters/fuzzers/wasm_memory_fuzzer.cpp` compiles a
static minimal WASM module (1 memory page, exported as `"memory"`)
once in `LLVMFuzzerInitialize`, then for each input parses two
`uint32_t` values (ptr, size) and calls `WasmCompartment::getMemory`.
- Directly exercises the integer-overflow fix in `WasmTimeRuntime.cpp`
(uint32_t wrapping bypass): `ptr=0xFFFFFFFF, size=2` must throw, not
return an out-of-bounds host pointer.
- ASan will catch any real OOB access; the harness is ~1 M exec/sec
since it avoids WASM bytecode compilation per iteration.
- Added `tests/fuzz/wasm_memory_fuzzer.options`.
Fix: normalise compression fuzzer style:
- `gorilla_decompress_fuzzer.cpp`, `t64_decompress_fuzzer.cpp`,
`fpc_decompress_fuzzer.cpp`, `multiple_decompress_fuzzer.cpp` were
using C++ function-try-block syntax and returning `1` from the catch
clause. Converted to the standard ClickHouse pattern: plain
`try { … } catch (…) {}` block, always returns `0`.
- Removed unused `<string>`, `<IO/ReadBufferFromMemory.h>`, and
`<Common/Exception.h>` includes.
- Added missing `<Compression/ICompressionCodec.h>` to
`multiple_decompress_fuzzer.cpp` (needed for the `friend` declaration
that allows calling the protected `doDecompressData`).
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
serialization_variant_fuzzer: - Fuzzes `SerializationVariant::deserializeBinaryBulkStatePrefix` + `deserializeBinaryBulkWithMultipleStreams` with four Variant type shapes: 2-variant, 4-variant, 6-variant (with Nullable), and nested (Array, Tuple variants). - Header byte drives both the Variant shape and flag bits for `native_format` and `use_specialized_prefixes_and_suffixes_substreams`. - Exercises BASIC vs COMPACT discriminator modes naturally since the mode is encoded in the first byte of the VariantDiscriminators stream. serialization_dynamic_fuzzer: - Fuzzes `SerializationDynamic::deserializeBinaryBulkStatePrefix` + `deserializeBinaryBulkWithMultipleStreams` with four `max_dynamic_types` values (1, 4, 16, 255) to cover narrow and wide type fan-out. - Registers aggregate functions to allow `AggregateFunction` values inside Dynamic columns. - Exercises the `FLATTENED` vs standard structure_version code paths since the version is read from the stream prefix. Both fuzzers follow the existing `serialization_lowcardinality_fuzzer` pattern: single shared `ReadBufferFromMemory` returned for all substream paths, `position_independent_encoding = false`, 1 GiB memory limit. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Add `#include <IO/BufferWithOwnMemory.h>` to gorilla, t64, fpc and
multiple decompression fuzzers so that `DB::Memory<>` is defined
(previously relied on a transitive include from `Common/Arena.h`)
- Fix `native_reader_fuzzer`: `Block` has no `operator bool()` — replace
`while ((block = reader.read()))` with an explicit break on
`block.empty()`
- Fix `wasm_fuzzer`: `WasmCompartment::invoke` requires a `StopToken`
third argument — add `#include <Common/StopToken.h>` and pass
`StopToken{}`
- Fix `wasm_memory_fuzzer`: `getMemory()` returns `std::span<uint8_t>`,
not `uint8_t*` — add `#include <Interpreters/WebAssembly/WasmTypes.h>`
and update the probe logic accordingly
…ator `std::mt19937` is banned by ClickHouse style checks. Use `pcg64_fast` from `pcg_random.hpp` seeded with the libFuzzer-provided Seed argument.
… end-of-span bounds check
… std::vector style check in fuzzer
…e name to compileModule - column_variant_fuzzer: ColumnVariant API now requires VectorWithMemoryTracking<Discriminator> for create() and insertRangeFrom(); replace std::vector alias with VectorWithMemoryTracking - wasm_fuzzer/wasm_memory_fuzzer: IWasmEngine::compileModule() now takes (module_name, wasm_code); add missing module_name argument to fix arm_fuzzers build
…nt safety `buildSourceVariantColumn` called `insertIntoVariantFrom(0, *ColumnString::create(), 0)` on a freshly created empty `ColumnString` — reading row 0 from a 0-row column is an out-of-bounds access. The subsequent Field-based inserts already populate the column with the intended String and UInt64 values, so this call was redundant and dangerous. Remove it along with the now-unused `local_string` computation. `triage.py` fixes: - Replace fixed global `ASAN_LOG_PATH = "/tmp/asan_triage.log"` with a per-invocation `tempfile.TemporaryDirectory`, preventing concurrent triage runs from reading each other's sanitizer logs. - `collect_crash_files`: filter out `.log`/`.txt`/`.md` companion files that share the crash/oom/timeout/leak prefix — these should not be treated as fuzzer inputs.
…on test A fuzzed ORC blob whose type tree declares more columns than the stripe footer has ColumnEncoding entries crashed the server (SIGABRT) during schema inference: isDictionaryEncoded -> orc::StripeInformationImpl::getColumnEncoding indexed the stripe footer out of range. Bump contrib/orc to the fix that bounds-checks the column id and throws a ParseError, and add a regression test. Found by the ClickHouse AST fuzzer on PR ClickHouse#99653. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Split flaky check and targeted check into separate roles: Flaky check — runs only new/modified tests from the PR with thread fuzzer enabled. Tests run in parallel with themselves (shared queue) to ensure new tests are parallel-safe under randomized thread ordering. Targeted check — runs previously failed and coverage-relevant tests with per-worker partitioning (--no-self-parallel) so the same test never runs concurrently on multiple workers, avoiding conflicts on shared resources (hardcoded users, roles, settings profiles, etc.). Both use --test-runs 50. Changes: - Add --no-self-parallel flag to clickhouse-test: partitions tests by name hash so all copies go to the same worker - Flaky check: only changed tests, thread fuzzer, shared queue - Targeted check: relevant tests, no thread fuzzer, per-worker queues, 50 runs, single clickhouse-test invocation - Restore original thread fuzzer parameters (reverts reductions from 06c945a and 9790435) - Add amd_binary to flaky check, use AMD_LARGE for targeted debug - Targeted check uses --flaky-check --no-self-parallel PRs affected by tests running in parallel with themselves: ClickHouse#102015 ClickHouse#101093 ClickHouse#99653 ClickHouse#101503 ClickHouse#101108 ClickHouse#101884 ClickHouse#100746 ClickHouse#101447 ClickHouse#100941 ClickHouse#101099 ClickHouse#100203 ClickHouse#96130 ClickHouse#102038
…fuzzer`, seed `QBitWithStride`, wrap FPC seeds for `Multiple` - `decode_data_type_fuzzer.cpp`: the harness called `decodeDataType` with the default `max_complexity = 0` (trusted, unlimited) and left `FormatSettings::binary.max_binary_type_complexity` at `0`, so the rejection branch of `decodeDataTypeImpl` was unreachable for both the top-level type blob and the later `deserializeBinary` call. The first input byte is now a selector: bit 0 picks `1000` (the production default of `input_format_binary_max_type_complexity`) versus `0`, and the same value is propagated into the format settings. - `binary_types.dict`: `BinaryTypeIndex::QBitWithStride` (`0x37`) is live on master but the dictionary stopped at `0x36`; add the token (the reserved `0x33` / `0x35` holes stay out). - `corpus_sync.sh`: `fpc_decompress_fuzzer` shares the 8-byte `AuxiliaryRandomData` header with Gorilla and T64 and `CompressionCodecMultiple` accepts method byte `0x98`, so wrap its seeds for `multiple_decompress_fuzzer` too. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s on the runner disk `Build (arm_fuzzers)` has failed on this branch since 2026-07-21, every time while linking one of the last fuzzers (`fpc_decompress_fuzzer`, `t64_decompress_fuzzer`, `alp_decompress_fuzzer`) with `ld.lld` dying from `Bus error` or `Free space left: 83 MB`. The job log shows the runner going from 11 GB used to 191 GB of 194 GB used: each fuzzer statically links the whole of ClickHouse with its own ASan-instrumented DWARF, about 5 GiB per binary, and this branch adds 12 binaries to the ~20 on master. 26 of them linked before the disk ran out. More than 80% of such a binary is `.debug_*` (3.87 GiB of a 4.65 GiB RelWithDebInfo `clickhouse`), and zlib shrinks those sections about 2.8x, so keep the debug sections compressed in the linked fuzzer binaries with `--compress-debug-sections=zlib`, gated on `lld` and on the existing `COMPRESS_DEBUG_SECTIONS` option (the object files are already `-gz=zlib`, so the toolchain dependency is the same). `llvm-symbolizer`, which ASan and libFuzzer use for reports, reads compressed sections transparently: an ASan heap-buffer-overflow report from a probe linked this way still resolves to `file:line`. ClickHouse's in-process `Dwarf` reader skips compressed sections (`Dwarf::getSection`), which only costs line numbers in ClickHouse's own stack traces inside the fuzzers. Failed job: https://github.com/ClickHouse/ClickHouse/actions/runs/33823992088/job/100979724255 Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99653&sha=f48d37bd48e707cf7ea617a4a1a94f13c47158b2&name_0=PR PR: #99653 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Merged current
Fix: fuzzer executables are now linked with |
… `runner.py` The `.options` files of this PR set `use_value_profile = 1`, but `runner.py` only forwards allow-listed libFuzzer options, so the flag was silently dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er` mutator in binary mode When mode bit 0 selects binary type decoding, `NativeReader` expects raw `encodeDataType` bytes rather than length-prefixed names. The mutator now builds the binary encodings of its known types with the real `encodeDataType` and injects those in binary mode, keeping the text names for text mode. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lizationLowCardinality` A new selector bit sets `data_part_type = Wide`, a `has_uniform_marks_callback` that reports uniform marks, and a `seek_to_start_callback` that rewinds the `ReadBufferFromMemory`, as `MergeTreeReaderWide` does, so the speculative dictionary read and the stream reset in `deserializeBinaryBulkStatePrefix` are fuzzed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/35802062063/job/107080179436 ( |
| { | ||
| uint8_t max_types_selector; | ||
| uint8_t flags; | ||
| uint64_t rows; |
There was a problem hiding this comment.
I locally checked this header shape on the review host: a { uint8_t, uint8_t, uint64_t } struct is 16 bytes and rows starts at offset 8, not byte 2.
Because this harness keys both the size check and the payload split off sizeof(AuxiliaryRandomData), it silently skips bytes 2..7, reads rows from bytes 8..15, and advances the payload by 16 bytes instead of the documented 10. The same padded-header pattern is present in src/DataTypes/fuzzers/serialization_lowcardinality_fuzzer.cpp and src/DataTypes/fuzzers/serialization_variant_fuzzer.cpp, so all three fuzzers are currently mutating a different grammar than their comments describe.
Please parse the header from raw bytes / little-endian helpers instead of reinterpret_casting a padded struct.
| cfg.memory_limit = 16 * 1024 * 1024; /// 16 MiB guest memory | ||
| cfg.fuel_limit = 1'000'000; /// limit guest instructions | ||
|
|
||
| auto compartment = module->instantiate(cfg, StopToken{}); |
There was a problem hiding this comment.
Production does not instantiate arbitrary modules directly: WasmModuleManager first walks module.getImports() and calls module.linkFunction(...) for supported env imports before instantiate.
This harness goes straight from compileModule to instantiate, so any valid module importing supported host functions like clickhouse_* or AssemblyScript env.abort fails during instantiation and never exercises the host-API / guest-memory boundary that this target is supposed to fuzz. Please mirror the normal import-linking step here before calling instantiate.
| # generating a second one. | ||
| cp $SRC/tests/fuzz/*.dict $OUT/ | ||
| cp $SRC/tests/fuzz/*.options $OUT/ | ||
| cp $SRC/tests/fuzz/dictionaries/*.dict $OUT/ |
There was a problem hiding this comment.
Copying tests/fuzz/dictionaries/*.dict into the bundled fuzzers output fixes the aggregate target, but it does not satisfy the source-tree contract used by single-target / OSS-Fuzz builds. CMakeLists.txt explicitly documents that those consumers do cp tests/fuzz/*.dict, i.e. they never look under tests/fuzz/dictionaries/.
The new .options files now reference binary_types.dict, compression.dict, and wasm.dict, but those filenames only exist in that subdirectory, so those targets still start there with missing dictionaries. Please either move the new dictionaries into tests/fuzz/ or widen the source-tree packaging path as well.
| env["MSAN_OPTIONS"] = sanitizer_opts | ||
| env["UBSAN_OPTIONS"] = f"log_path={log_prefix}:halt_on_error=0:exitcode=0" | ||
|
|
||
| result = subprocess.run( |
There was a problem hiding this comment.
Crash replay here always runs binary crash_file with sanitizer env only. A number of fuzzers in this tree need extra fuzzer_arguments / non-default limits from their sibling .options files (create_parser_fuzzer, select_parser_fuzzer, data_type_deserialization_fuzzer, aggregate_function_state_deserialization_fuzzer, ...), so replay in triage.py can take a different parser/memory path or fail to reproduce the sanitizer report at all.
When that happens the script silently falls back to filename-based classification, which loses the stack-based grouping and the more precise severity/type extraction that replay was supposed to provide. Please either parse the sibling .options the same way runner.py does, or let triage.py accept extra arguments/env and plumb them through here.
|
The only blocking row on that run was the dashboard's The fix is already merged: #122782 (2026-09-29) reruns every dashboard blocker once on fresh servers, and only a slowdown that reproduces keeps the check red. 1db8e49 ran on 2026-09-23, before it landed. The current head f6398d6 includes it, and all six So I have no separate PR to open for this one. |
Adds fuzz targets for several subsystems that had no coverage: Gorilla, T64, FPC, and Multiple codec decompressors; the NativeReader binary protocol parser;
decodeDataTyperecursive type decoder; Variant and Dynamic column serialization; LowCardinality serialization; and the WASM sandbox memory interface.A structure-aware custom mutator for
NativeReader(LLVMFuzzerCustomMutator+LLVMFuzzerCustomCrossOver) injects valid ClickHouse type name strings to help libFuzzer reach type-parsing and column-deserialization paths.use_value_profile = 1added to all.optionsfiles.Bounds-check fixes for T64 and Multiple codecs found by the new fuzzers are in #99680 (merged).
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added fuzz targets for the Gorilla, T64, FPC, and Multiple compression codecs, the Native binary protocol reader, the binary type decoder, Variant/Dynamic/LowCardinality serialization, and the WASM sandbox. A structure-aware custom mutator for the Native protocol fuzzer injects valid ClickHouse type names to improve coverage of type-parsing paths.
Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/99653]
Version info
26.10.1.1302-master(included in26.10and later)