rustls 0.24.0-dev.0

Rustls is a modern TLS library written in Rust.
Documentation
use alloc::vec::Vec;
use core::ops::Deref;
use core::time::Duration;

use pki_types::UnixTime;
use zeroize::Zeroizing;

use crate::crypto::cipher::Payload;
use crate::crypto::{Identity, SelectedCredential, SignatureScheme};
use crate::enums::{ApplicationProtocol, CertificateType};
use crate::log::{debug, trace};
use crate::msgs::{
    CertificateChain, ClientSessionCommon, ExtensionType, MaybeEmpty, ServerExtensions, SessionId,
    SizedPayload,
};
use crate::sync::Arc;
use crate::verify::DistinguishedName;
#[cfg(feature = "webpki")]
pub use crate::webpki::{
    ServerVerifierBuilder, VerifierBuilderError, WebPkiServerVerifier,
    verify_identity_signed_by_trust_anchor, verify_server_name,
};
use crate::{Tls12CipherSuite, Tls13CipherSuite, compress};

mod config;
pub use config::{
    ClientConfig, ClientCredentialResolver, ClientSessionKey, ClientSessionStore,
    CredentialRequest, Resumption, Tls12Resumption, WantsClientCert,
};

mod connection;
#[cfg(feature = "std")]
pub use connection::{ClientConnection, WriteEarlyData};
pub use connection::{
    ClientConnectionData, EarlyDataError, MayEncryptEarlyData, UnbufferedClientConnection,
};

mod ech;
pub use ech::{EchConfig, EchGreaseConfig, EchMode, EchStatus};

mod handy;
#[cfg(any(feature = "std", feature = "hashbrown"))]
pub use handy::ClientSessionMemoryCache;

mod hs;
pub(crate) use hs::ClientHandler;

mod tls12;
pub(crate) use tls12::TLS12_HANDLER;

mod tls13;
pub(crate) use tls13::TLS13_HANDLER;

/// Dangerous configuration that should be audited and used with extreme care.
pub mod danger {
    pub use super::config::danger::{DangerousClientConfig, DangerousClientConfigBuilder};
    pub use crate::verify::{
        HandshakeSignatureValid, PeerVerified, ServerIdentity, ServerVerifier,
        SignatureVerificationInput,
    };
}

#[cfg(test)]
mod test;

/// A stored TLS 1.3 client session value.
#[derive(Debug)]
pub struct Tls13ClientSessionValue {
    suite: &'static Tls13CipherSuite,
    secret: Zeroizing<SizedPayload<'static, u8>>,
    pub(crate) age_add: u32,
    max_early_data_size: u32,
    pub(crate) common: ClientSessionCommon,
    quic_params: SizedPayload<'static, u16, MaybeEmpty>,
}

impl Tls13ClientSessionValue {
    pub(crate) fn new(
        input: Tls13ClientSessionInput,
        ticket: Arc<SizedPayload<'static, u16, MaybeEmpty>>,
        secret: &[u8],
        time_now: UnixTime,
        lifetime: Duration,
        age_add: u32,
        max_early_data_size: u32,
    ) -> Self {
        Self {
            suite: input.suite,
            secret: Zeroizing::new(secret.to_vec().into()),
            age_add,
            max_early_data_size,
            common: ClientSessionCommon::new(ticket, time_now, lifetime, input.peer_identity),
            quic_params: input
                .quic_params
                .unwrap_or_else(|| SizedPayload::from(Payload::new(Vec::new()))),
        }
    }

    pub(crate) fn secret(&self) -> &[u8] {
        self.secret.bytes()
    }

    /// Maximum early data size supported by the server.
    pub fn max_early_data_size(&self) -> u32 {
        self.max_early_data_size
    }

    /// The TLS 1.3 cipher suite used in this session.
    pub fn suite(&self) -> &'static Tls13CipherSuite {
        self.suite
    }

    /// Test only: rewind epoch by `delta` seconds.
    #[doc(hidden)]
    pub fn rewind_epoch(&mut self, delta: u32) {
        self.common.epoch -= delta as u64;
    }

    /// Test only: replace `max_early_data_size` with `new`
    #[doc(hidden)]
    pub fn _private_set_max_early_data_size(&mut self, new: u32) {
        self.max_early_data_size = new;
    }

    /// QUIC transport parameters provided by the server.
    pub fn quic_params(&self) -> Vec<u8> {
        self.quic_params.to_vec()
    }
}

impl Deref for Tls13ClientSessionValue {
    type Target = ClientSessionCommon;

    fn deref(&self) -> &Self::Target {
        &self.common
    }
}

/// A "template" for future TLS1.3 client session values.
#[derive(Clone)]
pub(crate) struct Tls13ClientSessionInput {
    pub(crate) suite: &'static Tls13CipherSuite,
    pub(crate) peer_identity: Identity<'static>,
    pub(crate) quic_params: Option<SizedPayload<'static, u16, MaybeEmpty>>,
}

/// A stored TLS 1.2 client session value.
#[derive(Debug, Clone)]
pub struct Tls12ClientSessionValue {
    suite: &'static Tls12CipherSuite,
    pub(crate) session_id: SessionId,
    master_secret: Zeroizing<[u8; 48]>,
    extended_ms: bool,
    #[doc(hidden)]
    pub(crate) common: ClientSessionCommon,
}

impl Tls12ClientSessionValue {
    pub(crate) fn new(
        suite: &'static Tls12CipherSuite,
        session_id: SessionId,
        ticket: Arc<SizedPayload<'static, u16, MaybeEmpty>>,
        master_secret: &[u8; 48],
        peer_identity: Identity<'static>,
        time_now: UnixTime,
        lifetime: Duration,
        extended_ms: bool,
    ) -> Self {
        Self {
            suite,
            session_id,
            master_secret: Zeroizing::new(*master_secret),
            extended_ms,
            common: ClientSessionCommon::new(ticket, time_now, lifetime, peer_identity),
        }
    }

    pub(crate) fn master_secret(&self) -> &[u8; 48] {
        &self.master_secret
    }

    pub(crate) fn ticket(&self) -> Arc<SizedPayload<'static, u16, MaybeEmpty>> {
        self.common.ticket.clone()
    }

    pub(crate) fn extended_ms(&self) -> bool {
        self.extended_ms
    }

    pub(crate) fn suite(&self) -> &'static Tls12CipherSuite {
        self.suite
    }

    /// Test only: rewind epoch by `delta` seconds.
    #[doc(hidden)]
    pub fn rewind_epoch(&mut self, delta: u32) {
        self.common.epoch -= delta as u64;
    }
}

impl Deref for Tls12ClientSessionValue {
    type Target = ClientSessionCommon;

    fn deref(&self) -> &Self::Target {
        &self.common
    }
}

#[derive(Debug)]
struct ServerCertDetails {
    cert_chain: CertificateChain<'static>,
    ocsp_response: Vec<u8>,
}

impl ServerCertDetails {
    fn new(cert_chain: CertificateChain<'static>, ocsp_response: Vec<u8>) -> Self {
        Self {
            cert_chain,
            ocsp_response,
        }
    }
}

struct ClientHelloDetails {
    alpn_protocols: Vec<ApplicationProtocol<'static>>,
    sent_extensions: Vec<ExtensionType>,
    extension_order_seed: u16,
    offered_cert_compression: bool,
}

impl ClientHelloDetails {
    fn new(alpn_protocols: Vec<ApplicationProtocol<'static>>, extension_order_seed: u16) -> Self {
        Self {
            alpn_protocols,
            sent_extensions: Vec::new(),
            extension_order_seed,
            offered_cert_compression: false,
        }
    }

    fn server_sent_unsolicited_extensions(
        &self,
        received_exts: &ServerExtensions<'_>,
        allowed_unsolicited: &[ExtensionType],
    ) -> bool {
        let mut extensions = received_exts.collect_used();
        extensions.extend(
            received_exts
                .unknown_extensions
                .iter()
                .map(|ext| ExtensionType::from(*ext)),
        );
        for ext_type in extensions {
            if !self.sent_extensions.contains(&ext_type) && !allowed_unsolicited.contains(&ext_type)
            {
                trace!("Unsolicited extension {ext_type:?}");
                return true;
            }
        }

        false
    }
}

enum ClientAuthDetails {
    /// Send an empty `Certificate` and no `CertificateVerify`.
    Empty { auth_context_tls13: Option<Vec<u8>> },
    /// Send a non-empty `Certificate` and a `CertificateVerify`.
    Verify {
        credentials: SelectedCredential,
        auth_context_tls13: Option<Vec<u8>>,
        compressor: Option<&'static dyn compress::CertCompressor>,
    },
}

impl ClientAuthDetails {
    fn resolve(
        negotiated_type: CertificateType,
        resolver: &dyn ClientCredentialResolver,
        root_hint_subjects: Option<&[DistinguishedName]>,
        signature_schemes: &[SignatureScheme],
        auth_context_tls13: Option<Vec<u8>>,
        compressor: Option<&'static dyn compress::CertCompressor>,
    ) -> Self {
        let server_hello = CredentialRequest {
            negotiated_type,
            root_hint_subjects: root_hint_subjects.unwrap_or_default(),
            signature_schemes,
        };

        if let Some(credentials) = resolver.resolve(&server_hello) {
            debug!("Attempting client auth");
            return Self::Verify {
                credentials,
                auth_context_tls13,
                compressor,
            };
        }

        debug!("Client auth requested but no cert/sigscheme available");
        Self::Empty { auth_context_tls13 }
    }
}