Skip to content

Commit a962606

Browse files
gyscosclaude
andcommitted
zstd-safe: refuse to use a Seekable until an init succeeded
zstd only allocates the seek table when an initialization succeeds, and ZSTD_seekable_decompress() / offsetToFrameIndex() read it unconditionally, so a fresh Seekable, or one whose init_buff() failed, made them dereference NULL from safe code. A failed re-initialization also left the old table in place while the source had already switched to the refused buffer. Track the result of the last initialization with the existing Poison helper and guard the methods that reach the table on it. While here, also guard frame_decompressed_size() (on Seekable and SeekTable) against frame_index == num_frames(): zstd only rejects frame_index > num_frames() and otherwise reads one entry past the end of the seek table. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-VFQMVXJX. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MxSMUdwqoQ3qm6UF82MgZD
1 parent 80506be commit a962606

2 files changed

Lines changed: 113 additions & 5 deletions

File tree

‎zstd-safe/src/seekable.rs‎

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,22 @@
66
use core::{marker::PhantomData, ptr::NonNull};
77

88
use crate::{
9-
parse_code, ptr_mut, ptr_void, CompressionLevel, InBuffer, OutBuffer,
10-
SafeResult, WriteBuf, SEEKABLE_FRAMEINDEX_TOOLARGE,
9+
parse_code, ptr_mut, ptr_void, CompressionLevel, ErrorCode, InBuffer,
10+
OutBuffer, Poison, SafeResult, WriteBuf, SEEKABLE_FRAMEINDEX_TOOLARGE,
1111
};
1212

13+
/// The error code zstd itself uses for a context that should have been
14+
/// initialized first (`-ZSTD_error_init_missing` as a `size_t`).
15+
const INIT_MISSING_ERROR: ErrorCode =
16+
(zstd_sys::ZSTD_ErrorCode::ZSTD_error_init_missing as usize)
17+
.wrapping_neg();
18+
19+
/// The error code zstd itself returns for a frame index past the last frame
20+
/// (`-ZSTD_error_frameIndex_tooLarge` as a `size_t`).
21+
const FRAMEINDEX_TOOLARGE_ERROR: ErrorCode =
22+
(zstd_sys::ZSTD_ErrorCode::ZSTD_error_frameIndex_tooLarge as usize)
23+
.wrapping_neg();
24+
1325
/// Indicates that the passed frame index is too large.
1426
///
1527
/// This happens when `frame_index > num_frames()`.
@@ -262,7 +274,16 @@ impl Drop for FrameLog {
262274
/// A seekable decompression object.
263275
///
264276
/// The lifetime references the potential buffer that holds the data of this seekable.
265-
pub struct Seekable<'a>(NonNull<zstd_sys::ZSTD_seekable>, PhantomData<&'a ()>);
277+
///
278+
/// It needs to be initialized, with `init_buff()` or `init_advanced()`, before it can be used.
279+
// zstd only allocates the seek table when an initialization succeeds, and then
280+
// reads it without checking that it is there. So this starts out poisoned, and
281+
// stays so until an initialization succeeds.
282+
pub struct Seekable<'a>(
283+
NonNull<zstd_sys::ZSTD_seekable>,
284+
PhantomData<&'a ()>,
285+
Poison,
286+
);
266287

267288
// Safety: as for `SeekableCStream`. Note the decompression methods, which do
268289
// drive the C context, all take `&mut self`.
@@ -284,6 +305,7 @@ impl<'a> Seekable<'a> {
284305
Some(Seekable(
285306
NonNull::new(unsafe { zstd_sys::ZSTD_seekable_create() })?,
286307
PhantomData,
308+
Poison(Some(INIT_MISSING_ERROR)),
287309
))
288310
}
289311

@@ -312,7 +334,10 @@ impl<'a> Seekable<'a> {
312334
)
313335
};
314336

315-
parse_code(code)
337+
// Only the last initialization counts: a failed one has already
338+
// replaced the source, whatever seek table was there before.
339+
self.2.clear();
340+
self.2.record(parse_code(code))
316341
}
317342

318343
/// Decompresses the length of `dst` at decompressed offset `offset`.
@@ -329,6 +354,7 @@ impl<'a> Seekable<'a> {
329354
dst: &mut C,
330355
offset: u64,
331356
) -> SafeResult {
357+
self.2.guard()?;
332358
// `ZSTD_seekable_decompress()` does cut the length down to what is left
333359
// of the data, but with unchecked arithmetic: for an `offset` past the
334360
// end it wraps around and either claims to have written bytes it did
@@ -389,6 +415,7 @@ impl<'a> Seekable<'a> {
389415
dst: &mut C,
390416
frame_index: u32,
391417
) -> SafeResult {
418+
self.2.guard()?;
392419
unsafe {
393420
dst.write_from(|buffer, capacity| {
394421
parse_code(zstd_sys::ZSTD_seekable_decompressFrame(
@@ -468,6 +495,12 @@ impl<'a> Seekable<'a> {
468495
///
469496
/// Returns an error if `frame_index` is out of range.
470497
pub fn frame_decompressed_size(&self, frame_index: u32) -> SafeResult {
498+
self.2.guard()?;
499+
// zstd only rejects `frame_index > num_frames()`, and reads past the
500+
// end of the seek table for `frame_index == num_frames()`.
501+
if frame_index >= self.num_frames() {
502+
return Err(FRAMEINDEX_TOOLARGE_ERROR);
503+
}
471504
let code = unsafe {
472505
zstd_sys::ZSTD_seekable_getFrameDecompressedSize(
473506
self.0.as_ptr(),
@@ -479,7 +512,12 @@ impl<'a> Seekable<'a> {
479512
}
480513

481514
/// Get the frame at the given offset.
515+
///
516+
/// Returns `0` if the seekable is not initialized.
482517
pub fn offset_to_frame_index(&self, offset: u64) -> u32 {
518+
if self.2.guard().is_err() {
519+
return 0;
520+
}
483521
unsafe {
484522
zstd_sys::ZSTD_seekable_offsetToFrameIndex(self.0.as_ptr(), offset)
485523
}
@@ -570,7 +608,7 @@ impl<'a> Seekable<'a> {
570608
#[cfg(feature = "std")]
571609
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "std")))]
572610
pub fn init_advanced<F>(
573-
self,
611+
mut self,
574612
src: std::boxed::Box<F>,
575613
) -> Result<AdvancedSeekable<'a, F>, crate::ErrorCode>
576614
where
@@ -598,6 +636,7 @@ impl<'a> Seekable<'a> {
598636
return Err(code);
599637
}
600638

639+
self.2.clear();
601640
Ok(AdvancedSeekable {
602641
inner: self,
603642
src: opaque,
@@ -770,6 +809,10 @@ impl SeekTable {
770809
///
771810
/// Returns an error if `frame_index` is out of range.
772811
pub fn frame_decompressed_size(&self, frame_index: u32) -> SafeResult {
812+
// See `Seekable::frame_decompressed_size()`.
813+
if frame_index >= self.num_frames() {
814+
return Err(FRAMEINDEX_TOOLARGE_ERROR);
815+
}
773816
// Safety: Just FFI
774817
let code = unsafe {
775818
zstd_sys::ZSTD_seekTable_getFrameDecompressedSize(

‎zstd-safe/src/tests.rs‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,13 @@ fn test_seekable_seek_table() {
255255
seek_table.frame_decompressed_size(2).unwrap()
256256
);
257257

258+
// zstd itself would read past the end of the seek table here.
259+
let last = seekable.num_frames();
260+
assert!(seekable.frame_decompressed_size(last).is_err());
261+
assert!(seek_table.frame_decompressed_size(last).is_err());
262+
assert!(seekable.frame_compressed_size(last).is_err());
263+
assert!(seek_table.frame_compressed_size(last).is_err());
264+
258265
// Trigger FrameIndexTooLargeError
259266
let frame_index = seekable.num_frames() + 1;
260267
assert_eq!(
@@ -263,6 +270,64 @@ fn test_seekable_seek_table() {
263270
);
264271
}
265272

273+
/// A seekable has no seek table until it is successfully initialized, and zstd
274+
/// dereferences a null pointer looking for it.
275+
#[cfg(feature = "seekable")]
276+
#[test]
277+
fn test_seekable_uninitialized() {
278+
use crate::seekable::Seekable;
279+
280+
fn check(seekable: &mut Seekable<'_>, error: &str) {
281+
let mut buffer = std::vec![0u8; 64];
282+
assert_eq!(
283+
seekable
284+
.decompress(&mut buffer[..], 0)
285+
.map_err(zstd_safe::get_error_name),
286+
Err(error)
287+
);
288+
assert_eq!(
289+
seekable
290+
.decompress_frame(&mut buffer[..], 0)
291+
.map_err(zstd_safe::get_error_name),
292+
Err(error)
293+
);
294+
assert_eq!(
295+
seekable
296+
.frame_decompressed_size(0)
297+
.map_err(zstd_safe::get_error_name),
298+
Err(error)
299+
);
300+
assert_eq!(seekable.offset_to_frame_index(0), 0);
301+
}
302+
303+
let seekable_archive = new_seekable_archive(INPUT);
304+
let mut seekable = Seekable::create();
305+
check(&mut seekable, "Context should be init first");
306+
307+
// A failed initialization does not make it usable.
308+
let error = seekable
309+
.init_buff(b"this is not a seekable archive")
310+
.map_err(zstd_safe::get_error_name)
311+
.unwrap_err();
312+
check(&mut seekable, error);
313+
314+
// A successful one does...
315+
seekable
316+
.init_buff(&seekable_archive)
317+
.map_err(zstd_safe::get_error_name)
318+
.unwrap();
319+
check_seekable_decompression(|dst, offset| {
320+
seekable.decompress(dst, offset)
321+
});
322+
323+
// ... until the next failure.
324+
let error = seekable
325+
.init_buff(b"this is not a seekable archive")
326+
.map_err(zstd_safe::get_error_name)
327+
.unwrap_err();
328+
check(&mut seekable, error);
329+
}
330+
266331
#[cfg(all(feature = "std", feature = "seekable"))]
267332
#[test]
268333
fn test_seekable_advanced_cycle() {

0 commit comments

Comments
 (0)