Bug #77334
closedZstd decompression lacks error handling
0%
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.
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_compressBoundguarantees the single output buffer is large enough so the finalZSTD_e_endflush can't stall. The problems are concentrated indecompress(), which looks like it was never given the same treatment.
Bugs in
decompress()(ZstdCompressor.h:88-121)
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.- Unconsumed input is silently dropped. The loop decrements
compressed_len -= inbuf.sizeand the iterator advances by the full chunk, regardless ofinbuf.pos. If zstd stops consuming input -- most plausibly because outbuf is full when the encodeddst_lenprefix 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 thatoutbuf.pos == dst_lenor that the frame actually ended.- No
NULLcheck onZSTD_createDStream()(line 104), andZSTD_initDStream's return isn't checked either. Compare withcompress(), which checksZSTD_createCCtx()and returns-ENOMEM. On allocation failure this dereferencesNULLinside zstd.dst_lenis trusted blindly (line 96-99). A corrupt 4-byte prefix of0xffffffffmakesceph::buffer::ptr dstptr(dst_len)attempt a 4 GiB allocation, which throwsstd::bad_allocand takes down the daemon -- an unhandled-corruption crash rather than an-EINVAL. A cheap sanity check (e.g. againstZSTD_getFrameContentSizeon the first chunk, or just an upper bound relative tocompressed_len* max ratio) would turn that into a clean error. Relatedly,ceph::decode(dst_len, p)can throwbuffer::end_of_bufferif the caller'scompressed_lenoverstates the available data; the function isn't exception-safe (the DStream would leak if a throw happened after creation, though currently decode happens before).- Returns
-1on error instead of a proper errno like the-EINVAL/-ENOMEMused incompress(). Callers mostly just test< 0, but it's inconsistent.
Minor / quality
- Context churn in
compress(): aZSTD_CCtxis 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, theZSTD_CCtx_resetat 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 fullZSTD_compressBound-sized, page-aligned allocation stays alive while onlyoutbuf.posbytes 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::factorydoes an unsynchronized check-then-assign oncompressor, but this matches every other compression plugin and is serialized by PluginRegistry's lock, so it's fine as-is.- The
(const char**)&inbuf.srccast (lines 64, 113) type-puns aconst void*throughconst char**. It works on every platform Ceph targets and is the established pattern here, just not strictly clean.
Human analysis¶
- True: Indeed the
ZSTD_decompressStreamreturn 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, thezdsstate may be left in undefined state. It's UB to invokeZSTD_decompressStream()on such a state." - True: The HowTo clearly states that one needs to check the updated
inbuf.posto learn how much of the input has been consumed, but the code assumes that always the fullinbuf.sizehas been consumed (viacompressed_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". - True: Missing
NULLcheck forZSTD_createDStream(). - 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_allocon today's machines. But a "cheap sanity check" definitely sounds like a good idea. But not as important as the other points. - 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()takessize_t compressed_lenbut then internally assumes that it, and theuint32_t dst_lendecompressed from it, will never exceed theuint32_trange. This invariant is not checked in the code. Incompress(), 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:
- The zstd
examples/streaming_decompression.chas some more proper error handling examples.
Missed by Mythos/Fable 5:
- It fails to point out an obvious memory leak in the
decompressfunction (ZSTD_freeDStream(s);not being called if thereturn -1;early return happens).
LS Updated by Lumir Sliva 6 months ago
- Status changed from New to In Progress
- Assignee set to Lumir Sliva
LS Updated by Lumir Sliva 6 months ago
- Pull request ID set to 69584
LS Updated by Lumir Sliva 5 months ago
NH Updated by Niklas Hambuechen 5 months ago
NH Updated by Niklas Hambuechen 5 months ago
@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
- 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