Skip to content

Commit 682b8b2

Browse files
gyscosclaude
andcommitted
zstd-safe: refuse CCtx::try_clone once NbWorkers was set
ZSTD_copyCCtx() trusts stage == ZSTDcs_init to mean that appliedParams, hashLog3 and the workspace tables come from the same reset. The multithreaded branch of ZSTD_CCtx_init_compressStream2() overwrites appliedParams with the workers' parameters while leaving the outer context's stage and tables as an abandoned single-threaded frame left them, so try_clone() then copied tables of mismatched sizes: up to 512 KiB past the clone's workspace, or 16 MiB past the source's. The applied parameters cannot be queried, so remember whether NbWorkers was ever set to a non-zero value, and from then on refuse try_clone() and the (unsafe) compress_block() with ZSTD_error_stage_wrong. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-XGF4B4VN. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MxSMUdwqoQ3qm6UF82MgZD
1 parent cee6529 commit 682b8b2

2 files changed

Lines changed: 91 additions & 4 deletions

File tree

‎zstd-safe/src/lib.rs‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,14 @@ impl Poison {
305305
///
306306
/// It is recommended to allocate a single context per thread and re-use it
307307
/// for many compression operations.
308-
pub struct CCtx<'a>(NonNull<zstd_sys::ZSTD_CCtx>, PhantomData<&'a ()>, Poison);
308+
pub struct CCtx<'a>(
309+
NonNull<zstd_sys::ZSTD_CCtx>,
310+
PhantomData<&'a ()>,
311+
Poison,
312+
/// Whether `NbWorkers` was ever set to a non-zero value, see
313+
/// `guard_own_tables`.
314+
bool,
315+
);
309316

310317
impl Default for CCtx<'_> {
311318
fn default() -> Self {
@@ -334,7 +341,12 @@ impl<'a> CCtx<'a> {
334341
// Safety: zstd returns a newly owned context or null.
335342
let context = unsafe { zstd_sys::ZSTD_createCCtx() };
336343

337-
Some(Self(NonNull::new(context)?, PhantomData, Poison::default()))
344+
Some(Self(
345+
NonNull::new(context)?,
346+
PhantomData,
347+
Poison::default(),
348+
false,
349+
))
338350
}
339351

340352
/// Wrap `ZSTD_createCCtx`
@@ -839,9 +851,13 @@ impl<'a> CCtx<'a> {
839851
};
840852

841853
// Safety: Just FFI
842-
parse_code(unsafe {
854+
let res = parse_code(unsafe {
843855
zstd_sys::ZSTD_CCtx_setParameter(self.0.as_ptr(), param, value)
844-
})
856+
});
857+
if res.is_ok() && matches!(param, ZSTD_c_nbWorkers) && value != 0 {
858+
self.3 = true;
859+
}
860+
res
845861
}
846862

847863
/// Guarantee that the input size will be this value.
@@ -865,11 +881,32 @@ impl<'a> CCtx<'a> {
865881
})
866882
}
867883

884+
/// Fails if the tables of this context may not be the ones its applied
885+
/// parameters describe.
886+
///
887+
/// Starting a multi-threaded frame overwrites the applied parameters with
888+
/// those of the workers, but leaves the context's own stage and workspace
889+
/// as the last single-threaded frame left them. If that frame was
890+
/// abandoned before its first block, zstd still accepts the calls that
891+
/// work on this context directly, and overruns a workspace that was sized
892+
/// for other parameters. The applied parameters cannot be queried, so
893+
/// refuse these calls as soon as a multi-threaded frame could have been
894+
/// started.
895+
#[cfg(feature = "experimental")]
896+
fn guard_own_tables(&self) -> Result<(), ErrorCode> {
897+
if self.3 {
898+
return Err(STAGE_WRONG_ERROR);
899+
}
900+
Ok(())
901+
}
902+
868903
/// Creates a copy of this context.
869904
///
870905
/// This only works before any data has been compressed. An error will be
871906
/// returned otherwise.
872907
/// A poisoned context cannot be cloned until its session is reset.
908+
/// A context on which `NbWorkers` was ever set to a non-zero value cannot
909+
/// be cloned anymore.
873910
#[cfg(feature = "experimental")]
874911
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
875912
#[deprecated(
@@ -881,6 +918,7 @@ impl<'a> CCtx<'a> {
881918
) -> Result<Self, ErrorCode> {
882919
// An error may leave the C context undefined; do not copy it.
883920
self.2.guard()?;
921+
self.guard_own_tables()?;
884922
// zstd copies the allocator callbacks from `self` into the new
885923
// context, so both must be created the same way; `try_create` always
886924
// picks the same allocator within a build.
@@ -911,6 +949,9 @@ impl<'a> CCtx<'a> {
911949

912950
/// Wraps the `ZSTD_compressBlock()` function.
913951
///
952+
/// Returns an error once `NbWorkers` was set to a non-zero value on this
953+
/// context.
954+
///
914955
/// # Safety
915956
///
916957
/// `src` becomes this context's history window, so it must stay allocated and unmodified until
@@ -926,6 +967,7 @@ impl<'a> CCtx<'a> {
926967
dst: &mut C,
927968
src: &[u8],
928969
) -> SafeResult {
970+
self.guard_own_tables()?;
929971
// Safety: ZSTD_compressBlock returns the number of bytes written.
930972
unsafe {
931973
dst.write_from(|buffer, capacity| {

‎zstd-safe/src/tests.rs‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -880,6 +880,51 @@ fn test_cloning_decompression_context_keeps_streaming_parameters() {
880880
assert!(cloned.sizeof() < 1 << 20);
881881
}
882882

883+
#[cfg(all(feature = "std", feature = "experimental", feature = "zstdmt"))]
884+
#[test]
885+
#[allow(deprecated)] // Exercises the deprecated copy and block APIs.
886+
fn test_multithreaded_context_refuses_copy_and_block_apis() {
887+
use crate::{CCtx, CParameter, InBuffer, OutBuffer, ResetDirective};
888+
889+
let mut output = [0; 1024];
890+
let mut start_frame = |cctx: &mut CCtx<'_>| {
891+
cctx.compress_stream(
892+
&mut OutBuffer::around(&mut output[..]),
893+
&mut InBuffer::around(b"abc"),
894+
)
895+
.unwrap();
896+
};
897+
898+
// Abandon a frame in its initial stage, with a workspace sized for it.
899+
let mut cctx = CCtx::create();
900+
cctx.set_parameter(CParameter::CompressionLevel(19)).unwrap();
901+
start_frame(&mut cctx);
902+
assert!(cctx.try_clone(Some(1000)).is_ok());
903+
cctx.reset(ResetDirective::SessionAndParameters).unwrap();
904+
905+
// The workers' parameters now describe tables of other sizes, but the
906+
// context's own stage and workspace are still those of the first frame.
907+
cctx.set_parameter(CParameter::NbWorkers(1)).unwrap();
908+
start_frame(&mut cctx);
909+
assert!(cctx.try_clone(Some(1000)).is_err());
910+
let block = std::vec![0u8; cctx.get_block_size()];
911+
let mut compressed = Vec::with_capacity(block.len());
912+
assert!(unsafe { cctx.compress_block(&mut compressed, &block) }.is_err());
913+
914+
// Resetting the requested parameters does not touch the applied ones.
915+
cctx.reset(ResetDirective::SessionAndParameters).unwrap();
916+
assert!(cctx.try_clone(Some(1000)).is_err());
917+
918+
// The other way round, the copy reads past the source's workspace.
919+
let mut cctx = CCtx::create();
920+
start_frame(&mut cctx);
921+
cctx.reset(ResetDirective::SessionAndParameters).unwrap();
922+
cctx.set_parameter(CParameter::CompressionLevel(19)).unwrap();
923+
cctx.set_parameter(CParameter::NbWorkers(1)).unwrap();
924+
start_frame(&mut cctx);
925+
assert!(cctx.try_clone(None).is_err());
926+
}
927+
883928
#[cfg(all(feature = "std", feature = "with-rust-allocator"))]
884929
#[test]
885930
fn test_custom_allocator_dictionaries_interoperate_with_c_dictionaries() {

0 commit comments

Comments
 (0)