Skip to content

Fix server crash from recursive Avro schema - #102853

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/avro-recursive-schema-crash
Apr 21, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/avro-recursive-schema-crash

Conversation

@groeneai

@groeneai groeneai commented Apr 15, 2026 •

Copy link
Copy Markdown
Collaborator

A crafted .avro file with a mutually recursive schema (e.g. TypeA → TypeB → TypeA) causes avroNodeToDataType(), createDeserializeFn(), and createAction() to recurse infinitely through AVRO_SYMBOLIC nodes, overflowing the stack and crashing the server with SIGSEGV. Any query reading such a file (from S3, HTTP, or local path) triggers the crash — no authentication required.

The fix adds explicit cycle detection to all three vulnerable code paths using name-tracking sets that detect back-references immediately (on the first re-entry, not after thousands of stack frames). Non-recursive re-use of named types is unaffected — verified with existing test 02592_avro_records_with_same_names.

createSkipFn() was already protected via symbolic_skip_fn_map — the same defensive pattern.

Complementary to #102417 which adds generic checkStackSize() guards (catches all deep nesting including non-recursive). This PR specifically detects logical cycles with an immediate, targeted error message.

Reproduction:

-- With the crafted malicious.avro from #102809:
SELECT * FROM file('malicious.avro', 'Avro');  -- SIGSEGV before fix, clean error after

After fix:

Code: 36. Recursive Avro schema is not supported: type 'TypeB' references itself. (BAD_ARGUMENTS)

Closes #102809

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix server crash (SIGSEGV) when reading Avro files with recursive schemas containing cyclic symbolic type references. Now such schemas are detected and rejected with a clear error message instead of crashing.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.1106

A crafted .avro file with a mutually recursive schema (e.g. TypeA -> TypeB -> TypeA)
causes avroNodeToDataType(), createDeserializeFn(), and createAction() to recurse
infinitely through AVRO_SYMBOLIC nodes, overflowing the stack and crashing the server
with SIGSEGV. Any query reading such a file (from S3, HTTP, or local path) triggers the
crash without authentication.

The fix adds explicit cycle detection to all three vulnerable code paths:
- avroNodeToDataType(): tracks record names on the recursion stack via seen_names set
- createDeserializeFn(): tracks symbolic names via symbolic_deserialize_guard member
- createAction(): shares the same guard as createDeserializeFn

createSkipFn() was already protected via symbolic_skip_fn_map (same pattern).

Non-recursive re-use of named types (e.g. TypeB used in two different fields of TypeA)
is unaffected — the name is removed from the set when leaving the record scope.

Closes ClickHouse#102809
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @nikitamikhaylov — could you review this? It adds explicit cycle detection for recursive Avro schemas (the vulnerability from #102809). Complementary to #102417 — this catches logical cycles immediately with a targeted error message, while #102417's checkStackSize() catches all deep nesting generically. Both can coexist.

Session: cron:clickhouse-ci-task-worker:20260415-184500

Pre-PR validation:

  • (a) Deterministic repro: clickhouse local -q "SELECT * FROM file('malicious.avro', 'Avro')" → SIGSEGV (exit 139) without fix, clean error with fix
  • (b) Root cause: AVRO_SYMBOLIC resolution creates pointer cycle; avroNodeToDataType/createDeserializeFn/createAction recurse infinitely; createSkipFn already had protection via symbolic_skip_fn_map
  • (c) Fix matches cause: name-tracking sets detect cycles on first re-entry
  • (d) New test: 04101_avro_recursive_schema_crash crafts the exact attack vector; existing 02592_avro_records_with_same_names verifies no false positives
  • (e) Both directions confirmed: SIGSEGV without → clean error with
  • (f) All 3 vulnerable paths fixed; createSkipFn already protected

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9199392]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, 3/3) FAIL
03373_named_session_try_recreate_before_timeout FAIL cidb, issue ISSUE CREATED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR fixes an actual server exception vector in Avro parsing by rejecting cyclic symbolic schema references in avroNodeToDataType, createDeserializeFn, and the recursive branch of createAction, while preserving safe skip behavior for non-traversed recursive branches. I found no correctness, safety, or performance regressions in the patched paths, and the added regression test matches the reported failure mode.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 15, 2026
@Avogar Avogar self-assigned this Apr 16, 2026
@Avogar

Avogar commented Apr 20, 2026

Copy link
Copy Markdown
Member

@groeneai test 01060_avro fails in the CI with:

2026-04-15 23:07:27 Reason: return code:  36
2026-04-15 23:07:27 Code: 36. DB::Exception: Recursive Avro schema is not supported: type 'sub1' references itself: (while reading header): (in file/uri (fd = 0)): While executing AvroRowInputFormat: While executing File. (BAD_ARGUMENTS)

Does it mean we tested Avro file with recursive schema and parsed it successfully?

Fixes regression introduced by the initial cycle-detection patch in this PR
that broke test `01060_avro` on legitimately recursive Avro schemas such as
the `sub1` linked-list-like record in `nested_complex.avsc` (`sub1` has a
`b4_null_sub1` field whose type is `union(null, sub1)`).

Root cause: in `AvroDeserializer::createAction`, the guard was inserted on
every visit to an `AVRO_SYMBOLIC` node, *before* checking `keep_going`.
When the user only needs columns at a finite depth and the deeper
occurrence of the symbolic reference would have been handled by the safe
skip path (`createSkipFn`, which already avoids infinite recursion via the
lazy `symbolic_skip_fn_map`), the eager insert still triggered the guard
and rejected the schema.

Fix: defer the guard to the actually-recursive branch. Take the safe skip
path first when `keep_going` is false. Only insert into the path stack
when we genuinely recurse into the resolved node, preserving back-edge
detection for the case where the user wants to deserialize a column whose
path requires infinite unrolling.

The regression test `04101_avro_recursive_schema_crash` still catches the
original SIGSEGV (checked via `avroNodeToDataTypeImpl` for schema inference
and via `createDeserializeFn` on the deserialize path).

Verified locally:
- `01060_avro`: FAIL -> PASS (same error as reported by @Avogar in CI).
- `04101_avro_recursive_schema_crash`: PASS (regression test).
- `02592_avro_records_with_same_names`: PASS (no false-positive regression).
- 10 consecutive runs of all three tests: 30/30 passed.

CI report (failure that motivated this commit):
ClickHouse#102853
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar thanks for catching that — the failing 01060_avro is NOT a legitimate recursive-schema read, it was my cycle-detection being too aggressive. Fixed in 9199392 ("Allow safe skip of cyclic symbolic references in createAction").

What was happening

tests/queries/0_stateless/data_avro/nested_complex.avsc has a truly recursive schema:

{
  "type": "record", "name": "main",
  "fields": [
    {"name": "a", "type": "long"},
    {"name": "b", "type": {
      "type": "record", "name": "sub1",
      "fields": [
        ...
        {"name": "b4_null_sub1", "type": ["null", "sub1"]}   // <- self-reference
      ]
    }}
  ]
}

The test reads column b.b4_null_sub1.sub1.b2_null_str (goes through the recursive sub1 link one level, reads a leaf field).

Traversal in createAction:

  1. main (record) -> iterate fields
  2. b (record sub1) -> iterate fields
  3. b.b4_null_sub1 (union [null, SYMBOLIC sub1]) -> iterate branches
  4. SYMBOLIC sub1 at path b.b4_null_sub1.sub1, keep_going=true -> recurse into resolved sub1 record
  5. Inside, b.b4_null_sub1.sub1.b4_null_sub1 is another union with SYMBOLIC sub1
  6. That second SYMBOLIC sub1 is at path b.b4_null_sub1.sub1.b4_null_sub1.sub1. The requested column does not start with this path, so keep_going=false and the old code took the safe createSkipFn path (which already handles cycles via symbolic_skip_fn_map).

My original patch inserted into symbolic_deserialize_guard before the keep_going check, so the second occurrence of "sub1" was flagged as a cycle even though we'd never actually recurse into it. That's the BAD_ARGUMENTS you saw.

The fix (9199392)

if (node->type() == avro::AVRO_SYMBOLIC)
{
    auto keep_going = std::any_of(header.begin(), header.end(), ...);
    auto resolved_node = avro::resolveSymbol(node);

    // Safe skip path handles cycles via symbolic_skip_fn_map — no guard needed.
    if (!keep_going)
        return AvroDeserializer::Action(createSkipFn(resolved_node));

    // Only guard the genuinely-recursive path.
    const auto & sym_name = node->name().fullname();
    if (!symbolic_deserialize_guard.insert(sym_name).second)
        throw Exception(..., "Recursive Avro schema is not supported: type '{}' references itself", sym_name);
    Action result = createAction(header, resolved_node, current_path);
    symbolic_deserialize_guard.erase(sym_name);
    return result;
}

So: schemas that are truly recursive remain readable as long as the requested column paths are finite. Only the case where the user does want to descend into a cycle (which would require infinite unrolling) still errors out. The 04101_avro_recursive_schema_crash regression test still catches the original SIGSEGV — that path goes through avroNodeToDataTypeImpl (schema inference, DESCRIBE / SELECT *) and through createDeserializeFn when the target type itself is recursive, both of which keep the unconditional guard.

Verified locally

  • 01060_avro: FAIL -> PASS (confirmed the exact Code: 36 error without the patch, exactly as you pasted, and PASS with it).
  • 04101_avro_recursive_schema_crash: PASS (regression test still catches the malicious file).
  • 02592_avro_records_with_same_names: PASS (no false positives for records with reused field names).
  • 10 consecutive runs of all three: 30/30 passed.

Session id: cron:clickhouse-ci-task-worker:20260420-184500

@clickhouse-gh

clickhouse-gh Bot commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 76.56% (49/64) · Uncovered code

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Apr 21, 2026
Merged via the queue into ClickHouse:master with commit 251ab53 Apr 21, 2026
158 of 161 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 21, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

Affected code: AvroSchemaReader::avroNodeToDataType, AvroDeserializer::createDeserializeFn, AvroDeserializer::createAction — core code present in all supported branches.

Why: SIGSEGV crash from crafted Avro input is a security vulnerability (no authentication required). The Avro format support and AVRO_SYMBOLIC handling have existed since at least 2019, predating all supported branches. All supported branches are affected.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Oct 9, 2026
`AvroSchemaReader::avroNodeToDataTypeImpl` follows named type references,
so its recursion depth is the length of the reference chain, not the JSON
nesting that contrib/avro bounds with `MAX_AVRO_SCHEMA_DEPTH`. A valid file
whose schema chains 100000 named records, each defined in its own array
field, made `DESC file(..., Avro)` recurse ~200000 frames and overflow the
stack (SIGSEGV on 26.8.18.2 server and on master, after ~35 s and 13 GB).

The per-level `checkStackSize()` added by ClickHouse#102417 ended up in the
non-recursive wrapper `avroNodeToDataType` when ClickHouse#102853 split the
recursion into `avroNodeToDataTypeImpl`, so it ran once per root column.

Count the recursion depth against `max_parser_depth` (0 = unlimited) and
throw `TOO_DEEP_RECURSION`, as ClickHouse#107341 does for MsgPack, BSON, ORC, Parquet
and JSON schema inference, and keep `checkStackSize()` per level as a
backstop for a raised or unlimited limit. The limit is passed by all three
callers (schema inference, the Variant read path and the Iceberg manifest
reader), and `max_parser_depth` is added to the Avro/AvroConfluent schema
cache key, so a schema inferred under a higher limit is not served to a
query with a lower one (same as a839800 did for ORC).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default 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.

Vulnerabilities exploitable by an attacker who controls data that ClickHouse reads

5 participants