unbounded-spsc: Sender::send pointer-as-value transmute causes OOB read + fake-Arc drop
Sender::send transmutes Arc pointer as value, racing with Receiver drop creates synthetic Arc instance that double-decrements refcount on next drop.
Background
unbounded-spsc is a small Rust crate that provides a Single-Producer Single-Consumer channel with unbounded capacity. It wraps bounded-spsc-queue and adds dynamic resizing on the producer side so the sender never blocks. The public API is the familiar let (tx, rx) = unbounded_spsc::channel() shape. Both Sender<T> and Receiver<T> hold an Arc<Inner> to shared state, plus a Producer<T> or Consumer<T> newtype that itself wraps an Arc<Buffer<T>>. The disconnect-aware cleanup path on the sender side is where the bug lives.
Reach is small: two reverse dependencies on crates.io, both owned by the same author (apis and gooey-rs). Roughly 13,000 lifetime downloads. The bug is interesting less for blast radius and more for the precise way the unsafe block goes wrong, which is a textbook "right intent, wrong indirection."
The transmute
The pre-fix Sender::send had a DISCONNECTED arm that ran when the sender observed that the receiver had already dropped. The arm tried to reclaim the in-flight message by transmuting the sender's Producer<T> into a Consumer<T> (so it could try_pop() whatever bytes were already in the buffer) and returning that value to the caller via SendError(t). The unsafe block read:
unsafe {
let consumer: spsc::Consumer<T>
= std::mem::transmute(self.producer.get());
let first = consumer.try_pop();
let second = consumer.try_pop();
assert!(second.is_none());
if let Some(t) = first {
return Err(SendError(t))
}
}
The intent, visible in the surrounding comment block, was a value-level transmute. Producer<T> and Consumer<T> in bounded-spsc-queue are both newtypes around a single Arc<Buffer<T>>, so a value transmute between them is layout-sound. The author's plan was: take the Producer<T> by value, transmute the bytes into a Consumer<T>, drain the queue.
The shipped code is one level of indirection off. self.producer has type UnsafeCell<spsc::Producer<T>>, and UnsafeCell::<X>::get(&self) returns *mut X, a raw pointer eight bytes wide on 64-bit targets. The expression std::mem::transmute(self.producer.get()) reinterprets those eight pointer bytes into the bytes of a Consumer<T>. The resulting Consumer<T>'s internal Arc::ptr field is the address of self.producer inside the Sender<T> struct, not the address of the real ArcInner<Buffer<T>> that lives one indirection deeper.
The fake Consumer<T> walks its Arc::ptr and dereferences fields that lie inside the Sender<T> struct (send_new, inner) or adjacent memory. consumer.try_pop() reads those bytes and surfaces them as a fabricated T value. When the fake Consumer<T> falls out of scope, its Drop runs Arc::drop, decrementing what the type system thinks is a strong_count: AtomicUsize but is actually the bytes of a Sender field. If the count reaches zero, the drop continues into dealloc with a Layout::for_value(...) over an address the allocator never returned. On glibc that is a deterministic abort or a tcache-poisoning primitive; on hardened allocators (jemalloc-secure, mimalloc-secure) it is an immediate abort.
A smoking-gun TODO in the crate's own test suite, near src/lib.rs:975, reads:
// TODO: failures
// - failed with assertion on line 394 in send fn
// assert!(second.is_none())
That is the same assertion site as the transmute block. The author had observed the symptom and misclassified it as a flaky test rather than recognising it as undefined behaviour leaking out.
Race condition
The bug is not reachable single-threaded. Receiver::drop stores connected = false before setting counter = DISCONNECTED, and Sender::send early-returns on connected == false. The actual trigger requires a TOCTOU race: the sender reads connected == true, the receiver flips connected = false and stores DISCONNECTED, and the sender then fetch_adds the counter, observes DISCONNECTED, and dispatches into the buggy arm. The race window is the gap between the connected check and the counter.fetch_add. On modern x86-64 with active contention, the window opens within a few hundred iterations.
Reproducer
Two-thread Rust program that drives the race deterministically:
use std::thread;
use unbounded_spsc::channel;
fn main() {
for trial in 0..500 {
let (tx, rx) = channel::<Box<u64>>();
let started = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let s = started.clone();
let h = thread::spawn(move || {
s.store(true, std::sync::atomic::Ordering::SeqCst);
for _ in 0..10_000 {
let _ = tx.send(Box::new(0xDEAD_BEEF));
}
});
while !started.load(std::sync::atomic::Ordering::SeqCst) {
std::hint::spin_loop();
}
drop(rx);
let _ = h.join();
eprintln!("trial {trial} ok");
}
}
Observed behaviour against unbounded-spsc@0.2.0:
- Release-mode without sanitizer:
Segmentation fault (core dumped)reliably within a few trials. Non-segfaulting trials terminate via aself.send_new.send(...).unwrap()panic, which is a related side-channel defect that surfaces whenreceive_newis dropped at roughly the same time. -Zsanitizer=address -Zbuild-stdon nightly Rust:==PID==ERROR: AddressSanitizer: stack-buffer-overflowon roughly three out of ten iterations. The trace points to the fakeConsumer<T>::try_pop()reading past theSenderstack frame.
Miri does not catch the bug. The single-threaded path is unreachable (it is filtered by the connected == false early-return), and threaded Miri is too slow to drive the iteration count needed to hit the race window.
Impact
The primitive composes three UB classes: an OOB read of bytes adjacent to the Sender<T> struct surfaced through the SendError(t) return value; an OOB write via fake Arc::drop decrementing what it thinks is a refcount; and allocator corruption via fake Arc::drop calling dealloc on a non-allocated address (a confirmed double-free / bucket-poisoning primitive on glibc).
Reachability is from 100% safe Rust through the canonical channel pattern. The two reverse-dependency crates both fit the race profile; gooey-rs in particular uses the crate for an OpenGL / FMOD callback mailbox where scene-graph teardown is a natural rx-drop-during-tx-send moment. The CVSS 3.1 vector AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:H (8.1 High, the reporter's own assessment at the time of the report) reflects the network-reachable case where channel teardown is attacker-induced through a websocket disconnect. For purely local consumers the practical score is closer to 4.5 to 5.0 Medium; the advisory takes the higher number because the worst plausible call site (network-actor mailbox) drives the rating. In absolute Rust-soundness terms this is memory-corruption and unsound regardless of CVSS.
The fix
Shane Pearman's fix-ub branch replaces the pointer-as-value transmute with a value-level read plus transmute, and uses ManuallyDrop to avoid the double-Producer-drop that would otherwise occur when the original UnsafeCell contents are dropped alongside the transmuted consumer:
unsafe {
use core::mem::ManuallyDrop;
// Sound value-level transmute: Producer<T> and Consumer<T> are both newtypes
// around Arc<Buffer<T>>, so the value layouts match. ptr::read takes ownership
// of the Producer's bytes without running Producer's Drop.
let producer_val: spsc::Producer<T> = std::ptr::read(self.producer.get());
let consumer : spsc::Consumer<T> = std::mem::transmute(producer_val);
let first = consumer.try_pop();
let second = consumer.try_pop();
assert!(second.is_none());
if let Some(t) = first {
return Err(SendError(t));
}
let _ = ManuallyDrop::new(consumer);
}
The fix shipped in unbounded-spsc@0.3.0 on 2026-05-15 with a regression test that drives the race shape (500 trial iterations, 10,000 sends per trial). Shane also flagged a secondary issue at the self.send_new.send(new_consumer).unwrap() path that panics when receive_new has been dropped. The same race window can hit that sink too; Shane is handling it as a follow-up rather than rolling it into this advisory.
Timeline
- 2026-05-14 11:56 CEST: PGP-signed disclosure email sent to
spearman@gitlab.comwith the full advisory body and PoC. Mail bounced;spearman@gitlab.comis a dead address. - 2026-05-14 ~12:00 CEST: Public GitHub Issue #4 opened on the repo as fallback, asking the maintainer to enable Private Vulnerability Reporting.
- 2026-05-14 13:55 CEST: Joint RustSec advisory-db PR #2884 (paired with oneringbuf as PR #2883) opened. Dirkjan Ochtman (
@djc) critiqued the disclosure ethics: "Do you have approval from the maintainer to publish this?" Both PRs closed gracefully with a reopen-trigger on maintainer ACK or 2026-06-13. - 2026-05-15: Shane Pearman replied via Issue #4, confirmed the bug, opened the
fix-ubbranch, releasedunbounded-spsc@0.3.0, and accepted GHSA-6m57-8r3p-pqx6. - 2026-05-16: Thanks-comment posted on Issue #4. Advisory closed from the reporter side.
Roughly 28 hours, disclosure to patched release.
Coordination notes
The public-issue fallback after the email bounce worked. A dead spearman@gitlab.com would have stalled the disclosure indefinitely on the email-only path. Opening Issue #4 with a low-noise "please enable Private Vulnerability Reporting" message let the maintainer pick up the thread on his own timetable without spilling the advisory body into public discussion. The pattern (public issue requesting PVR activation, then private advisory once PVR is on) now sits in the playbook for unmaintained-looking repos.
The RustSec etiquette lesson from Dirkjan Ochtman's PR #2884 critique was correct: a RustSec advisory-db PR without a documented maintainer ACK reads as a coordinated-disclosure violation. The right sequence is disclosure email, wait for maintainer response, open advisory-db PR with "Acknowledged by maintainer on YYYY-MM-DD" in the body. If the maintainer is silent past 30 days, the PR proceeds with a "Maintainer contacted YYYY-MM-DD, no response after 30 days" note. Opening the advisory-db PR same-day as the disclosure email was the case the reviewer pushed back on.
Shane Pearman's response was a positive outlier. The bug had been latent for an unknown duration (the TODO suggests months), and he shipped a fix plus regression test in under 24 hours. He asked to handle the second-site finding himself, the right disposition for a maintainer who has internalised the failure mode.
References
- GHSA-6m57-8r3p-pqx6:
https://github.com/spearman/unbounded-spsc/security/advisories/GHSA-6m57-8r3p-pqx6 - Fix branch:
https://github.com/spearman/unbounded-spsc/tree/fix-ub unbounded-spsc@0.3.0on crates.iobounded-spsc-queue@0.4.0source: defines theProducer<T>andConsumer<T>newtypes that the transmute assumed layout-compatible- CWE-843: Access of Resource Using Incompatible Type ("Type Confusion")
- CWE-416: Use After Free
- RustSec category:
memory-corruption, informationalunsound