Project

General

Profile

Actions

Bug #77334

closed
NH

Zstd decompression lacks error handling

Bug #77334: Zstd decompression lacks error handling

Added by Niklas Hambuechen 6 months ago. Updated 20 days ago.

Status:
Resolved
Priority:
Normal
Assignee:
-
Category:
-
Target version:
-
Due date:
% Done:

0%

Source:
Community (user)
Backport:
Regression:
No
Severity:
3 - minor
Reviewed:
Affected Versions:
ceph-qa-suite:
Pull request ID:
Crash signature (v1):
Crash signature (v2):
Tags (freeform):
Fixed In:
v22.0.0-821-gce17991f65
Released In:
Upkeep Timestamp:
2026-11-13T02:49:01+00:00

Description

We're looking to use zstd compression.

Scared of the past Ceph lz4 corruption bug #39525 (Bug of the year 2020 video), we thought it would be smart to have a quick look at the code, and unfortunately found some concerns immediately.

Code: https://github.com/ceph/ceph/blob/v20.2.1/src/compressor/zstd/ZstdCompressor.h

It was added 9 years ago in https://github.com/ceph/ceph/pull/13075

Out of interest, my colleague chpatrick ran the just-released Claude Fable/Mythos 5 LLM on it with prompt Could you review the zstd compression code?. Provided is its output below, followed by my analysis.

LLM output

Overall the compress path (recently modernized in 4cc10e7aa8b) is in good shape -- proper error checks, correct streaming over non-contiguous bufferlists, ZSTD_compressBound guarantees the single output buffer is large enough so the final ZSTD_e_end flush can't stall. The problems are concentrated in decompress(), which looks like it was never given the same treatment.

Bugs in decompress() (ZstdCompressor.h:88-121)

  1. ZSTD_decompressStream's return value is ignored (line 114). If the input is corrupt, zstd returns an error code, but the loop keeps feeding chunks and the function returns 0 with whatever partial output accumulated. Callers (BlueStore, RGW, OSD message decompression) get silently truncated/garbage data with a success status. This is the most serious issue -- every other error path in this file returns a failure code, and the lz4/snappy decompressors do check their library's return.
  2. Unconsumed input is silently dropped. The loop decrements compressed_len -= inbuf.size and the iterator advances by the full chunk, regardless of inbuf.pos. If zstd stops consuming input -- most plausibly because outbuf is full when the encoded dst_len prefix is smaller than the real decompressed size -- the remaining bytes are skipped and the function again returns 0 with truncated output. After the loop, there's no check that outbuf.pos == dst_len or that the frame actually ended.
  3. No NULL check on ZSTD_createDStream() (line 104), and ZSTD_initDStream's return isn't checked either. Compare with compress(), which checks ZSTD_createCCtx() and returns -ENOMEM. On allocation failure this dereferences NULL inside zstd.
  4. dst_len is trusted blindly (line 96-99). A corrupt 4-byte prefix of 0xffffffff makes ceph::buffer::ptr dstptr(dst_len) attempt a 4 GiB allocation, which throws std::bad_alloc and takes down the daemon -- an unhandled-corruption crash rather than an -EINVAL. A cheap sanity check (e.g. against ZSTD_getFrameContentSize on the first chunk, or just an upper bound relative to compressed_len * max ratio) would turn that into a clean error. Relatedly, ceph::decode(dst_len, p) can throw buffer::end_of_buffer if the caller's compressed_len overstates the available data; the function isn't exception-safe (the DStream would leak if a throw happened after creation, though currently decode happens before).
  5. Returns -1 on error instead of a proper errno like the -EINVAL/-ENOMEM used in compress(). Callers mostly just test < 0, but it's inconsistent.

Minor / quality

  • Context churn in compress(): a ZSTD_CCtx is created and freed on every call. zstd contexts are explicitly designed for reuse, and per-call creation is measurable overhead at BlueStore blob sizes (typically 4-64 KiB). A thread-local context (as the QAT path and many other zstd users do) would help. Also, the ZSTD_CCtx_reset at line 35 is a no-op on a freshly created context and could go away -- it only earns its keep if the context becomes reusable.
  • Buffer over-retention (line 79): dst.append(outptr, 0, outbuf.pos) shares the underlying raw buffer rather than copying, so the full ZSTD_compressBound-sized, page-aligned allocation stays alive while only outbuf.pos bytes are used. For well-compressing data that's most of the allocation wasted for the bufferlist's lifetime. Whether that matters depends on how long callers hold the result; BlueStore writes it out promptly, so this is minor.
  • CompressionPluginZstd::factory does an unsynchronized check-then-assign on compressor, but this matches every other compression plugin and is serialized by PluginRegistry's lock, so it's fine as-is.
  • The (const char**)&inbuf.src cast (lines 64, 113) type-puns a const void* through const char**. It works on every platform Ceph targets and is the established pattern here, just not strictly clean.

Human analysis

  1. True: Indeed the ZSTD_decompressStream return value check is missing, not implementing the Streaming decompression - HowTo instructions on error handling (code link).
    Further, as per code:
    "when an operation returns with an error code, the zds state may be left in undefined state. It's UB to invoke ZSTD_decompressStream() on such a state."
  2. True: The HowTo clearly states that one needs to check the updated inbuf.pos to learn how much of the input has been consumed, but the code assumes that always the full inbuf.size has been consumed (via compressed_len -= inbuf.size;).
    Also true is the "After the loop, there's no check that outbuf.pos == dst_len or that the frame actually ended".
  3. True: Missing NULL check for ZSTD_createDStream().
  4. Seems exaggerated. I don't know what Ceph's policy is regarding checking values stored on disk for corruption. A 4 GiB allocation definitely doesn't have to result in std::bad_alloc on today's machines. But a "cheap sanity check" definitely sounds like a good idea. But not as important as the other points.
  5. Fair point but minor.

Regarding the quality points:

  • Context churn: I cannot judge that, haven't analysed yet what higher-level Ceph code calls compress(). Probably deserves a comment in the Ceph code.
  • Buffer over-retention: Maybe deserves a comment in the Ceph code.
  • unsynchronized check-then-assign: No idea.
  • Type-pun: Probably good to fix.

Adding one of my own:

  • It seems ugly that decompress() takes size_t compressed_len but then internally assumes that it, and the uint32_t dst_len decompressed from it, will never exceed the uint32_t range. This invariant is not checked in the code. In compress(), the (uint32_t)src.length() would silently overflow if it was larger. From reading around in callers, it doesn't seem to be larget today, but why not add an actual overflow check to avoid this doubt?

Additional help:

Missed by Mythos/Fable 5:

  • It fails to point out an obvious memory leak in the decompress function (ZSTD_freeDStream(s); not being called if the return -1; early return happens).

LS Updated by Lumir Sliva 6 months ago Actions #1

  • Status changed from New to In Progress
  • Assignee set to Lumir Sliva

LS Updated by Lumir Sliva 6 months ago Actions #2

  • Pull request ID set to 69584

LS Updated by Lumir Sliva 5 months ago Actions #3

  • Status changed from In Progress to New
  • Assignee deleted (Lumir Sliva)
  • Pull request ID changed from 69584 to 69733

Closed my #69584 in favor of #69733 (more complete, reporter's own team). Clearing self-assignment, PR field set to 69733.

NH Updated by Niklas Hambuechen 5 months ago Actions #4

Lumir Sliva wrote in #note-3:

Closed my #69584 in favor of #69733 (more complete, reporter's own team). Clearing self-assignment, PR field set to 69733.

These links don't work because the numbers are actually Github PR numbers, linking them here for convenience:

NH Updated by Niklas Hambuechen 5 months ago Actions #5

@Lumir Sliva Thanks for also looking into this, would be great to have you as an additional reviewer on the PR!

UB Updated by Upkeep Bot 20 days ago Actions #6

  • Status changed from New to Resolved
  • Merge Commit set to ce17991f65b4aea0340a01cacbaadbd4a92dca57
  • Fixed In set to v22.0.0-821-gce17991f65
  • Upkeep Timestamp set to 2026-11-13T02:49:01+00:00
Actions

Also available in: PDF Atom