Skip to content

Validate Npy format shape dimensions to prevent DoS from crafted files - #100625

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
Algunenano:npy-large-shape-validation
Mar 25, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
Algunenano:npy-large-shape-validation

Conversation

@Algunenano

@Algunenano Algunenano commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #99812 which fixed negative shape dimensions. This addresses the
remaining attack surface with large non-negative dimensions
(comment).

A crafted .npy file can claim arbitrarily large shape dimensions in its header
while containing little or no actual data. Without validation, this leads to
unbounded loops, excessive memory allocation, or integer overflow in the format
parser. For multi-dimensional arrays, all inner-dimension processing happens
inside a single readRow call, which means max_execution_time cannot interrupt
it — the time check only runs between rows.

Changes:

  • Validate that the product of all shape dimensions does not overflow size_t
  • Validate claimed data size against actual file size (when known)
  • Cap per-row memory footprint (data + array offset overhead) to 2 GiB, which
    also protects non-file sources (pipes, HTTP) where file size is unavailable
  • Cap individual element size to 2 GiB (prevents |S<huge> allocation DoS)
  • Add overflow check in NumpyDataTypeUnicode constructor (size * 4 wrap)
  • Reject empty shape to prevent out-of-bounds access on shape[0]
  • Add periodic isCancelled check in the inner readValue loop so
    max_execution_time is respected for single-row large arrays
  • Widen shape type from int to size_t for correctness (NumPy allows
    dimensions larger than INT_MAX)
  • Remove dead declarations (readData, readRows)

Closes #99585

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):

Validate Npy format shape dimensions against file size and overflow limits to prevent denial of service from crafted .npy files with unreasonably large dimensions. Also reject empty shapes and cap per-row memory to 2 GiB.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.262

Follow-up to ClickHouse#99812 which fixed negative shape dimensions. This addresses
the remaining attack surface with large non-negative dimensions:

- Validate that the product of all shape dimensions does not overflow `size_t`
- Validate that claimed data size matches the actual file size (when known)
- Cap per-row memory footprint (data + array offset overhead) to 2 GiB
- Cap individual element size to 2 GiB (prevents `|S<huge>` DoS)
- Add overflow check in `NumpyDataTypeUnicode` constructor (`size * 4`)
- Reject empty shape (prevents OOB access on `shape[0]`)
- Add periodic `isCancelled` check in the inner `readValue` loop so
  `max_execution_time` is respected even for single-row large arrays
- Widen shape dimensions from `int` to `size_t` for correctness
- Remove dead declarations (`readData`, `readRows`)

Closes ClickHouse#99585

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e052e8]

Summary: ❌

job_name test_name status info comment
Unit tests (asan_ubsan) error IGNORED

AI Review

Summary

This PR strengthens Npy input validation against malformed shapes, overflow, and uninterruptible large-row parsing DoS scenarios, and adds focused stateless tests. I found one backward-compatibility issue: a new hardcoded per-row 2 GiB rejection threshold can fail previously valid imports without a compatibility/setting escape hatch.

Findings

❌ Blockers

  • [src/Processors/Formats/Impl/NpyRowInputFormat.cpp:273] New hardcoded max_bytes_per_row = 2 GiB changes accepted behavior for valid large rows, but is not gated by a setting or compatibility. Per ClickHouse rules, new enforcement affecting existing data/workloads must be configurable to preserve prior behavior.
    • Suggested fix: make this threshold a format/setting value (or compatibility-dependent), and wire it into SettingsChangesHistory.cpp.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ❌ Hardcoded 2 GiB limit in Npy parser should be a setting.
Backward compatibility ❌ New strict per-row cap can reject previously accepted valid .npy inputs with no compatibility switch.
SettingsChangesHistory.cpp ⚠️ A compatibility-impacting validation was added without corresponding compatibility-setting integration.
PR metadata quality ✅
Safe rollout ⚠️ Rollout risk due to immediate hard limit without configurable fallback.
Compilation time ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Make the per-row Npy size cap configurable (or compatibility-gated) instead of hardcoded.
    • Add compatibility plumbing/update (SettingsChangesHistory.cpp) so existing workloads can preserve prior behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 24, 2026
- Use range-based for loop in shape dimension validation (clang-tidy
  modernize-loop-convert)
- Skip file-size check for compressed read buffers:
  `tryGetFileSizeFromReadBuffer` unwraps `CompressedReadBufferWrapper`
  and returns the compressed source size, which would cause false
  `INCORRECT_DATA` rejections for valid compressed `.npy` inputs

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
if (element_size == 0)
throw Exception(ErrorCodes::INCORRECT_DATA, "Npy element size is zero");

static constexpr size_t max_bytes_per_row = 2ULL * 1024 * 1024 * 1024; /// 2 GiB

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This introduces a hard 2 GiB per-row cap for Npy imports (data + offsets) and fails otherwise. That is a behavior change for valid .npy data that previously could be read, so it is a backward-incompatibility unless it is gated behind a setting (or tied to compatibility) and documented in SettingsChangesHistory.cpp.

Could you expose this threshold as a format setting (with compatibility-controlled default), instead of a fixed constant in code?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No without a really good reason.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Mar 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.90% 84.10% +0.20%
Functions 24.50% 24.50% +0.00%
Branches 76.50% 76.60% +0.10%

PR changed lines: PR changed-lines coverage: 87.70% (107/122, 0 noise lines excluded)
Diff coverage report
Uncovered code

@Algunenano
Algunenano added this pull request to the merge queue Mar 25, 2026
Merged via the queue into ClickHouse:master with commit 6c73494 Mar 25, 2026
148 of 149 checks passed
@Algunenano
Algunenano deleted the npy-large-shape-validation branch March 25, 2026 16:09
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 25, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Mar 29, 2026
@ClickHouse ClickHouse deleted a comment from clickgapai Mar 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @Algunenano @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Npy format: negative shape dimension causes infinite loop

4 participants