#3310·rustls

F12: Fragmented vectored writes repeatedly rescan consumed descriptors

Author: djcCreated Sep 30, 2026Updated Sep 30, 2026

F12: Fragmented vectored writes repeatedly rescan consumed descriptors

  • Finding: Quadratic descriptor traversal during vectored writes
  • Affected Software: rustls 0.23.45 and rustls 0.24.0-dev.1 (development snapshot 99f2358cae29).
  • Date: September 2026
  • Discoverer: OpenAI ([email protected])

A fragmented OutboundPlain retains the full original slice array. Each record starts iterating that array again to skip the bytes consumed by preceding records. Highly fragmented application batches therefore take quadratic descriptor-traversal work instead of work proportional to their bytes and descriptors.

Cause and prior work

For N one-byte slices and P plaintext bytes per TLS record, the total skipped prefix is approximately N²/(2P). split_at advances numeric offsets without trimming consumed descriptors, and chunks() restarts Chunks::next from the first descriptor.

#1640 combines chunks to reduce record/copy overhead; it does not address this repeated-prefix cost. #2154 concerns a different receive-side memmove path.

Source: rustls/src/crypto/cipher/messages.rs.

Reproduction

Compare identical plaintext represented by one contiguous slice or one-byte slices. Vary batch size and configured fragment size. Time only encryption, then decrypt every record and check exact equality. The largest case contains 1 MiB and stops after that bounded batch.

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/.

toml
[package]
name = "vectored-complexity-poc"
version = "0.1.0"
edition = "2024"

[workspace]

[dependencies]
rustls = { path = "../rustls/rustls" }
rustls-ring = { path = "../rustls/rustls-ring" }
rust
use rustls::SliceInput;
use rustls::crypto::Identity;
use rustls::crypto::cipher::OutboundPlain;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
use rustls::{
    ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
    VecInput,
};
use std::{sync::Arc, time::Instant};

fn pair(fragment_size: Option<usize>) -> (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 mut client_config = ClientConfig::builder(provider.clone())
        .with_root_certificates(roots)
        .with_no_client_auth()
        .unwrap();
    client_config.max_fragment_size = fragment_size;

    // 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 main() {
    for fragment_size in [None, Some(512), Some(32)] {
        let (mut client, mut server) = pair(fragment_size);
        for len in [16_384, 32_768, 65_536, 131_072, 262_144, 524_288, 1_048_576] {
            let bytes = vec![0x41; len];
            let slices = bytes.chunks(1).collect::<Vec<_>>();

            // Compare the same bytes and connection with only the descriptor representation changed.
            for vectored in [false, true] {
                let payload = if vectored {
                    OutboundPlain::new(&slices)
                } else {
                    bytes.as_slice().into()
                };
                let mut wire = Vec::new();

                // Time the write call, excluding input construction and the peer-side check.
                let start = Instant::now();
                client
                    .write(payload, &mut wire)
                    .expect("encrypt application data");
                let elapsed = start.elapsed();

                // Decrypt the complete output to verify that both representations deliver identical data.
                let wire_len = wire.len();
                let mut received = Vec::new();
                server
                    .read_tls(&mut SliceInput::new(&mut wire), &mut Vec::new())
                    .handle_all(&mut received)
                    .expect("decrypt application data");
                assert_eq!(received, bytes);

                println!(
                    "fragment_size={fragment_size:?}, bytes={len}, vectored={vectored}, wire={wire_len}, time_us={}",
                    elapsed.as_micros()
                );
            }
        }
    }
}
bash
cargo +1.98.1 run --release --manifest-path repro/Cargo.toml

Result

Vectored writes showed superlinear cost while delivering the exact plaintext. With 32-byte local records, doubling a large one-byte-slice batch approximately quadrupled runtime; default record sizing was much less costly. Representative 1 MiB results:

Target Record-size setting Contiguous One-byte slices
macOS aarch64 Default 0.204 ms 10.701 ms
Linux x86_64 Default 0.303 ms 25.522 ms
macOS aarch64 32 bytes 7.911 ms 15,069.292 ms
Linux x86_64 32 bytes 12.463 ms 25,803.415 ms

Exact wall-clock results depend on CPU and concurrent load.

A peer cannot directly choose another process's outgoing slice array or local record size. The strongest case needs an application preserving roughly a million tiny chunks and configuring very small records; no deployed-service attack is established. Release 0.23.45 retains the prefix scan by source comparison, but its writer buffering changes per-call exposure; the timing program targets the development API.

Suggested correction

Carry a progressing descriptor index/intra-chunk offset, or trim consumed descriptors as records are split. Applications can bound descriptor count and coalesce tiny chunks.

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.