
Safely Validate Rust Buffer Positions Before C FFI Calls
A Rust slice is safe to read only within its bounds, but passing a public position field to C can bypass that guarantee if the wrapper does not validate it. In zstd-safe, an out-of-range InBuffer::pos reached ZSTD_seekable_compressStream unchecked; that C function could read beyond the input slice and include adjacent memory in compressed output. Validate pos <= src.len() immediately before every FFI call, and upgrade affected releases to a patched version: 7.4.0 or later in the 7.x line, or 8.2.0 or later in the 8.x line.
This guide focuses on the specific failure tracked as RUSTSEC-2026-0405, not on FFI in general. The key engineering lesson is that a safe Rust wrapper must re-establish every invariant required by the native function at the call boundary—even when its input struct is public and callers can construct invalid states using safe Rust.
Environment and baseline
The affected crate is zstd-safe, which wraps the Zstandard C library. The advisory identifies SeekableCStream::compress_stream as affected in versions >=7.2.2, <7.4.0 and >=8.0.0, <8.2.0. It lists versions <7.2.2 as unaffected by this specific issue, and patches the vulnerable ranges in 7.4.0 and 8.2.0.
For a new or updated application, use a patched version and pin your supported range deliberately:
[dependencies]
# Choose a patched release compatible with your application.
zstd-safe = "7.4"
For an application already using the 8.x API, select 8.2.0 or later instead. Check the resolved version—not just the manifest constraint—with cargo tree -i zstd-safe. Also check whether a lockfile or workspace dependency is holding an affected version in place.
The examples below target Rust 1.82+ (Edition 2021) and describe the boundary invariant independently of minor API-signature differences across zstd-safe releases. Keep the crate’s public API in sync with the version in your lockfile.
The vulnerable pattern: public position sent unchecked to C
InBuffer exposes both its input slice and its current position. Safe Rust can therefore create a value whose position is outside that slice:
let input = b"short input";
let mut in_buffer = zstd_safe::InBuffer {
src: input,
pos: input.len() + 1, // Safe Rust can construct this invalid state.
};
// Vulnerable pattern: forwarding the public position to the seekable C API
// without first checking it.
stream.compress_stream(&mut out_buffer, &mut in_buffer)?;
The problem is not that slices permit out-of-bounds indexing; they do not. The problem is that the wrapper forwards metadata derived from the public pos field to a native API. The advisory reports that ZSTD_seekable_compressStream, unlike the other streaming functions, does not validate this position. It can consequently read past the end of src, by up to a frame’s size, and compress the bytes it reads into the output.
That turns an invalid cursor into a memory-safety and data-exposure issue. The compressed output may contain bytes that were never part of the caller’s input. The Rust type alone does not protect the C call because the type permits the invalid state.
Production fix: validate at the FFI boundary
The required invariant is simple:
0 <= input.pos <= input.src.len()
Check it immediately before every call that passes this buffer to C. Do not rely only on constructors, earlier validation, or assumptions about how the buffer was created: public fields allow safe callers to modify pos after construction.
A small helper makes the condition explicit:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidInputPosition {
pub position: usize,
pub input_len: usize,
}
pub fn validate_input_position(
src: &[u8],
pos: usize,
) -> Result<(), InvalidInputPosition> {
if pos <= src.len() {
Ok(())
} else {
Err(InvalidInputPosition {
position: pos,
input_len: src.len(),
})
}
}
At the call site, reject invalid state before calling the native-backed method:
validate_input_position(in_buffer.src, in_buffer.pos)
.map_err(|_| AppError::InvalidCompressionInput)?;
stream.compress_stream(&mut out_buffer, &mut in_buffer)?;
AppError here represents the application’s error type. Map the validation error into the project’s normal error model, but do not replace rejection with clamping. Changing an invalid position to src.len() silently changes the caller’s requested input state and can hide a bug; passing the original value to C preserves the vulnerability.
Validate every call, not just the first one
Streaming APIs are stateful. A buffer’s pos may change between calls, and public fields can be modified by safe code at any time. Validation belongs directly before each unsafe/native boundary:
loop {
validate_input_position(in_buffer.src, in_buffer.pos)
.map_err(|_| AppError::InvalidCompressionInput)?;
stream.compress_stream(&mut out_buffer, &mut in_buffer)?;
if stream_has_finished_work() {
break;
}
}
This application-side guard is useful when integrating with a version that cannot yet be upgraded, or when another wrapper exposes the same unsafe boundary. It does not replace upgrading a vulnerable dependency: the library itself should enforce its contract for every caller.
The patched zstd-safe implementation follows the same essential rule: check the position before each call into the C library. That placement matters. Validation only in an initial constructor is insufficient if the buffer remains mutable; validation in an unrelated streaming function is insufficient if the seekable function has a different C-level contract.
Prefer APIs that make invalid positions harder to express
If you own a higher-level wrapper, keep cursor state private and expose operations that preserve the invariant:
pub struct CheckedInput<'a> {
src: &'a [u8],
pos: usize,
}
impl<'a> CheckedInput<'a> {
pub fn new(src: &'a [u8]) -> Self {
Self { src, pos: 0 }
}
pub fn position(&self) -> usize {
self.pos
}
pub fn remaining(&self) -> &'a [u8] {
&self.src[self.pos..]
}
pub fn advance(&mut self, amount: usize) -> Result<(), InvalidInputPosition> {
let next = self.pos.checked_add(amount).ok_or(InvalidInputPosition {
position: usize::MAX,
input_len: self.src.len(),
})?;
if next > self.src.len() {
return Err(InvalidInputPosition {
position: next,
input_len: self.src.len(),
});
}
self.pos = next;
Ok(())
}
}
This wrapper prevents ordinary users of CheckedInput from setting the cursor directly, and checked_add avoids integer overflow while advancing. But a checked abstraction is defense in depth, not permission to skip validation immediately before FFI. For broader API-design context, see Rust Type-State Pattern: Encoding Valid Object Lifecycles in the Type System and Advanced Rust: Exploring Traits and Generics in Depth.
Trade-offs
| Approach | Runtime cost | Rejects invalid pos at FFI boundary? | Assessment |
|---|---|---|---|
Forward public pos unchecked | No Rust-side check | No | Vulnerable in the affected seekable path |
| Validate only when constructing a buffer | One check at construction | Not necessarily | Insufficient when fields can later change |
Check pos <= src.len() before every native call | One integer comparison per call | Yes | Direct, low-cost mitigation |
Use a patched zstd-safe release | Library performs the boundary check | Yes | Recommended primary fix |
Clamp an invalid pos | One comparison and assignment | No; changes input state | Avoid; can conceal caller defects |
The comparison is constant-time, O(1), and does not allocate. In a streaming loop, it adds one bounds comparison per call. That cost is usually negligible relative to compression and crossing the FFI boundary; more importantly, omitting it can disclose memory that was not part of the input.
Production pitfalls and differential verification
Do not assume all streaming functions share the same checks. The advisory specifically distinguishes ZSTD_seekable_compressStream from other streaming functions. Review the exact call path used by your application rather than inferring safety from a neighboring API.
Test boundary values, not just normal input. A focused test should cover pos == 0, pos == src.len(), and pos > src.len(). The first two satisfy the invariant; the third must be rejected before the native method is called. Also test a zero-length slice: its only valid position is zero.
Check the position again after any operation that can change it. Do not validate, call unrelated mutable code, and then pass the buffer to C under the assumption that its fields are unchanged. Keeping validation adjacent to the call makes the invariant auditable.
Do not treat output checks as a substitute. Checking the compressed output’s length or validity after the call cannot undo an out-of-bounds native read. Reject bad input state before entering C.
A practical dependency audit and test workflow is:
# Confirm the actual resolved dependency.
cargo tree -i zstd-safe
# Update within the compatible release line, then inspect the lockfile diff.
cargo update -p zstd-safe
# Run normal tests and lint checks.
cargo test --all-targets
cargo clippy --all-targets --all-features -- -D warnings
For a library that supports more than one zstd-safe release line, run the same boundary tests against each supported dependency configuration. Ensure that each CI job actually resolves the intended patched version; a broad manifest requirement alone does not prove which version was tested. Where a local unsafe wrapper exists, add tests asserting invalid positions are rejected before its native call, and run them under Miri as a supplementary check:
cargo +nightly miri test
Miri is useful for detecting certain classes of Rust undefined behavior in code it can interpret, but it does not establish that an external C library validates its inputs. The decisive mitigation is the boundary check plus a patched dependency; test those properties directly.
For adjacent memory-layout concerns, Rust std::mem::size_of and align_of: Understanding Layout for FFI, Performance, and Unsafe Code provides related context. Layout knowledge does not replace validating pointer-associated lengths and positions.
Frequently Asked Questions (FAQ)
Which zstd-safe versions are affected by RUSTSEC-2026-0405?
The advisory lists zstd-safe versions >=7.2.2, <7.4.0 and >=8.0.0, <8.2.0 as affected for SeekableCStream::compress_stream. Upgrade to 7.4.0 or later in the 7.x line, or 8.2.0 or later in the 8.x line.
Why can a public InBuffer position cause an out-of-bounds read?
Safe Rust can set the public InBuffer::pos field to a value greater than src.len(). In the affected path, that value reached ZSTD_seekable_compressStream without validation, and the C function did not perform the necessary bounds check.
Is checking InBuffer::pos only at construction sufficient?
No. Public fields can be changed after construction, and streaming code may make repeated native calls. Validate pos <= src.len() immediately before every call that passes the buffer to the FFI boundary.