F07: Stream flush succeeds with pending ciphertext or unflushed transport bytes
F07: Stream flush succeeds with pending ciphertext or unflushed transport bytes
- Finding: False flush success and data loss
- Affected Software: rustls 0.23.45 (
StreamOwned); rustls-util development snapshot99f2358cae29(StreamandStreamOwned). - Date: September 2026
- Discoverer: OpenAI ([email protected])
flush() can succeed after a short transport write leaves TLS ciphertext buffered. It can also succeed without retrying an underlying buffered transport's failed flush after Rustls's own output becomes empty. Dropping the stream after that success loses accepted data.
Cause and prior work
complete_prior_io calls complete_io once when TLS output is nonempty; partial progress is not complete drainage. Once TLS output is empty, it skips the transport's flush entirely. #1273 addressed final handshake output, and #1542 established transport flushing before blocking for input. Neither covers these post-handshake completion/retry conditions.
Source: rustls-util/src/stream.rs; rustls-util/src/lib.rs.
Reproduction
Use a transport that lawfully alternates a one-byte write and WouldBlock. Then use a buffered transport whose first flush returns Interrupted and whose second would succeed. The latter control calls the transport directly and drains its bytes. A final real nonblocking Unix socket with an unread peer confirms incomplete successful flushing without a synthetic transport.
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 = "util-stream-check"
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, Read, Write},
sync::Arc,
};
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();
}
#[derive(Debug, Default)]
struct PartialNonblocking {
writes: usize,
reads: usize,
sent: Vec<u8>,
}
impl Write for PartialNonblocking {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.writes += 1;
// Model a nonblocking socket with one byte of send capacity each time
// it is retried following WouldBlock. Both outcomes are valid Write behavior.
if self.writes.is_multiple_of(2) {
return Err(io::ErrorKind::WouldBlock.into());
}
let len = buf.len().min(1);
self.sent.extend_from_slice(&buf[..len]);
Ok(len)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Read for PartialNonblocking {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
self.reads += 1;
Err(io::ErrorKind::WouldBlock.into())
}
}
#[derive(Debug, Default)]
struct BufferedTransport {
pending: Vec<u8>,
delivered: Vec<u8>,
flushes: usize,
}
impl Write for BufferedTransport {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.pending.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.flushes += 1;
if self.flushes == 1 {
return Err(io::ErrorKind::Interrupted.into());
}
self.delivered.append(&mut self.pending);
Ok(())
}
}
impl Read for BufferedTransport {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Err(io::ErrorKind::WouldBlock.into())
}
}
fn main() {
// Queue ciphertext before testing a transport that allows only partial progress.
let (mut client, _server) = pair();
let mut output = Vec::new();
client
.write(
b"request with more than two bytes"
.as_slice()
.into(),
&mut output,
)
.unwrap();
let original_len = output.len();
let mut stream = StreamOwned::new(client, PartialNonblocking::default(), output);
let result = stream.flush();
println!(
"partial transport flush: result={result:?}, pending={}, initial={original_len}",
stream.output.len()
);
assert!(result.is_ok());
assert!(!stream.output.is_empty());
// A separate transport accepts bytes but interrupts its first flush.
{
let (client, _server) = pair();
let mut stream = StreamOwned::new(client, BufferedTransport::default(), Vec::new());
assert_eq!(
stream
.write(b"buffered transport payload")
.unwrap(),
26
);
// Retry through the wrapper after the first underlying flush was interrupted.
let result = stream.flush();
println!(
"retry underlying buffered flush: result={result:?}, tls_pending={}, transport_pending={}, delivered={}, flush_calls={}",
stream.output.len(),
stream.sock.pending.len(),
stream.sock.delivered.len(),
stream.sock.flushes
);
assert!(result.is_ok());
assert_eq!(stream.sock.flushes, 1);
assert!(!stream.sock.pending.is_empty());
assert!(stream.sock.delivered.is_empty());
// The transport itself recovers immediately if its flush is retried.
stream.sock.flush().unwrap();
assert!(stream.sock.pending.is_empty());
assert!(!stream.sock.delivered.is_empty());
}
// Confirm incomplete success with a real nonblocking socket and an unread peer.
#[cfg(unix)]
{
let (mut client, _server) = pair();
let mut output = Vec::new();
client
.write(
vec![b'x'; 4 * 1024 * 1024]
.as_slice()
.into(),
&mut output,
)
.unwrap();
let initial = output.len();
let (socket, _peer_not_reading) = std::os::unix::net::UnixStream::pair().unwrap();
socket.set_nonblocking(true).unwrap();
let mut stream = StreamOwned::new(client, socket, output);
// Try flushing while the unread peer limits the real socket's capacity.
let result = stream.flush();
println!(
"real nonblocking UnixStream flush: result={result:?}, pending={}, initial={initial}",
stream.output.len()
);
assert!(result.is_ok());
assert!(stream.output.len() < initial);
assert!(!stream.output.is_empty());
}
}cargo +1.98.1 run --release --manifest-path repro/Cargo.tomlResult
Partial flush returned Ok(()) with 53 of 54 TLS bytes pending. After the interrupted buffered flush, the wrapper reported success with 48 transport bytes pending and only one transport-flush call; calling the transport again delivered them. The real socket also returned success with most of a 4 MiB payload still queued; exact counts differ with kernel socket capacity.
The defect is false success, not failure to retry Interrupted internally. Successful flush does not guarantee remote application delivery, but it must not leave these intermediate buffers unflushed.
The 0.23.45 StreamOwned control also showed both failures: successful partial flush with wants_write() == true, and successful retry with 48 bytes still in the buffered transport.
Suggested correction
Drain TLS output or return an error such as WouldBlock/WriteZero. Flush the underlying transport even when Rustls's output is already empty, including after a previous flush failed.
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