Skip to main content

rtci_dtls/
config.rs

1//! Handshake configuration.
2//!
3//! [`ConfigBuilder`] is what a caller supplies: certificates, the client/server role, which cipher
4//! suites and curves to offer, the SRTP protection profiles to negotiate through `use_srtp`,
5//! and how strictly to require the extended master secret
6//! ([`ExtendedMasterSecretType`]).
7//!
8//! WebRTC authenticates peers by comparing the certificate fingerprint against the one
9//! signalled in SDP, not against a CA chain — so certificates here are normally self-signed
10//! (see [`gen_self_signed_root_cert`]) and the check is implemented by supplying a
11//! [`VerifyPeerCertificateFn`].
12//!
13//! [`HandshakeConfig`] is the resolved form the handshake
14//! actually runs with, produced by [`ConfigBuilder::build`](crate::config::ConfigBuilder::build).
15
16#[cfg(test)]
17mod config_test;
18
19use crate::cipher_suite::*;
20use crate::conn::{
21    DEFAULT_MAXIMUM_RETRANSMIT_NUMBER, DEFAULT_REPLAY_PROTECTION_WINDOW, INITIAL_TICKER_INTERVAL,
22    MAXIMUM_RETRANSMIT_INTERVAL, MINIMUM_MTU, MINIMUM_REPLAY_PROTECTION_WINDOW,
23};
24use crate::crypto::*;
25use crate::curve::named_curve::NamedCurve;
26use crate::extension::extension_use_srtp::SrtpProtectionProfile;
27use crate::record_layer::record_layer_header::{
28    PROTOCOL_VERSION1_0, PROTOCOL_VERSION1_2, ProtocolVersion,
29};
30use crate::signature_hash_algorithm::{
31    SignatureHashAlgorithm, SignatureScheme, parse_signature_schemes,
32};
33use crypto::RTCCryptoProvider;
34use log::warn;
35use shared::error::*;
36use std::collections::HashMap;
37use std::fmt;
38use std::net::SocketAddr;
39use std::sync::Arc;
40use std::time::Duration;
41
42use rustls::client::danger::ServerCertVerifier;
43use rustls::pki_types::CertificateDer;
44use rustls::server::danger::ClientCertVerifier;
45
46/// Explicit rustls/webpki backend used only for CA-chain and hostname verification.
47///
48/// This policy adapter is separate from [`RTCCryptoProvider`]. Applications authenticating with
49/// SDP fingerprints do not need it, while applications enabling WebPKI validation can select its
50/// backend without changing their primitive RTC provider.
51#[derive(Clone)]
52pub struct RustlsVerifierAdapter {
53    provider: Arc<rustls::crypto::CryptoProvider>,
54}
55
56impl RustlsVerifierAdapter {
57    /// Wraps a rustls crypto provider for WebPKI verification.
58    #[must_use]
59    pub fn new(provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
60        Self { provider }
61    }
62
63    /// Uses rustls's ring verification backend.
64    #[cfg(feature = "crypto-ring")]
65    #[must_use]
66    pub fn ring() -> Self {
67        Self::new(Arc::new(rustls::crypto::ring::default_provider()))
68    }
69
70    /// Uses rustls's AWS-LC-RS verification backend.
71    #[cfg(feature = "crypto-aws-lc-rs")]
72    #[must_use]
73    pub fn aws_lc_rs() -> Self {
74        Self::new(Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
75    }
76}
77
78fn default_verifier_adapter() -> Option<RustlsVerifierAdapter> {
79    #[cfg(feature = "crypto-ring")]
80    {
81        Some(RustlsVerifierAdapter::ring())
82    }
83    #[cfg(all(not(feature = "crypto-ring"), feature = "crypto-aws-lc-rs"))]
84    {
85        Some(RustlsVerifierAdapter::aws_lc_rs())
86    }
87    #[cfg(not(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs")))]
88    {
89        None
90    }
91}
92
93/// Builds the default server-certificate verifier, with an explicit provider where we have one.
94///
95/// # Errors
96///
97/// Fails if the root store holds no usable trust anchors.
98fn server_cert_verifier(
99    roots: std::sync::Arc<rustls::RootCertStore>,
100    adapter: &RustlsVerifierAdapter,
101) -> Result<std::sync::Arc<dyn ServerCertVerifier>> {
102    let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
103        roots,
104        adapter.provider.clone(),
105    )
106    .build()
107    .map_err(|err| Error::Other(format!("rustls server cert verifier: {err}")))?;
108    Ok(verifier)
109}
110
111/// Config is used to configure a DTLS client or server.
112/// After a Config is passed to a DTLS function it must not be modified.
113///
114/// # Session resumption and forward secrecy
115///
116/// Nothing is resumed unless the application configures it: a server issues tickets with
117/// [`Self::with_session_tickets`] (or shared keys, [`Self::with_session_ticket_issuer`]) and
118/// keeps DTLS 1.2 sessions with [`Self::with_session_cache`]; a client keeps what it is given
119/// with [`Self::with_session_store`]. Once any of these is set, **both** protocol versions
120/// resume by default, and they do not cost the same:
121///
122/// - **DTLS 1.3** resumes with `psk_dhe_ke` (RFC 8446 section 4.2.9): the ticket's PSK is
123///   combined with a new (EC)DHE exchange, so every association still has keys of its own
124///   and forward secrecy is kept. (`psk_ke`, which gives that up, is a separate opt-in:
125///   [`Self::with_psk_without_key_exchange`].)
126/// - **DTLS 1.2** resumes with the abbreviated handshake (RFC 5246 section 7.3, RFC 5077):
127///   **no key exchange is run**. The resumed association's keys come from the master secret
128///   of the association the session was made in and two public randoms. So there is **no
129///   forward secrecy against whatever holds that master secret**: the server's session
130///   cache, the client's store, and, with tickets, the server's ticket key, because an RFC
131///   5077 ticket is the master secret sealed under that key and it crosses the network in
132///   the clear part of the handshake. Whoever later obtains the ticket key (it lives as long
133///   as the configuration; a key is replaced every ticket lifetime and kept one lifetime
134///   more) and has recorded the traffic decrypts the association that got the ticket and
135///   every association resumed from it. Without resumption each DTLS 1.2 certificate
136///   handshake of this crate runs its own ephemeral ECDHE exchange and has none of this.
137///
138/// [`Self::with_dtls12_resumption`]`(false)` keeps DTLS 1.3 resumption and takes DTLS 1.2
139/// out of it; an application that turns tickets or a store on for DTLS 1.3 and does not need
140/// DTLS 1.2 resumption should set it. It is `true` by default for the applications that
141/// configured resumption before the switch existed. (The peer connection of the `rtci` crate
142/// sets it to `false` in every configuration.)
143#[derive(Clone)]
144pub struct ConfigBuilder {
145    crypto_provider: Option<Arc<dyn RTCCryptoProvider>>,
146    certificates: Vec<Certificate>,
147    cipher_suites: Vec<CipherSuiteId>,
148    signature_schemes: Vec<SignatureScheme>,
149    srtp_protection_profiles: Vec<SrtpProtectionProfile>,
150    use_srtp_optional: bool,
151    alpn_protocols: Vec<String>,
152    use_srtp_required: bool,
153    client_auth: ClientAuthType,
154    bad_certificate_for_a_missing_client_certificate: bool,
155    extended_master_secret: ExtendedMasterSecretType,
156    flight_interval: Duration,
157    maximum_flight_interval: Duration,
158    handshake_timeout: Option<Duration>,
159    cookie_exchange: bool,
160    hello_verify_request_version: ProtocolVersion,
161    early_data_retransmit: bool,
162    min_version: DtlsVersion,
163    max_version: DtlsVersion,
164    connection_id: Option<usize>,
165    connection_id_migration: bool,
166    invalid_record_limit: Option<u64>,
167    post_quantum_key_share: bool,
168    psk: Option<PskCallback>,
169    psk_identity_hint: Option<Vec<u8>>,
170    session_tickets: u8,
171    session_ticket_issuer: Option<crate::session::SessionTicketIssuer>,
172    session_ticket_lifetime: Duration,
173    session_store: Option<Arc<dyn crate::session::SessionStore>>,
174    session_cache: Option<Arc<dyn crate::session::SessionCache>>,
175    dtls12_resumption: bool,
176    external_psks: Vec<crate::session::ExternalPsk>,
177    psk_without_key_exchange: bool,
178    post_handshake_auth: bool,
179    max_early_data: u32,
180    insecure_skip_verify: bool,
181    insecure_hashes: bool,
182    insecure_verification: bool,
183    verify_peer_certificate: Option<VerifyPeerCertificateFn>,
184    roots_cas: rustls::RootCertStore,
185    client_cas: rustls::RootCertStore,
186    verifier_adapter: Option<RustlsVerifierAdapter>,
187    /// A client's verifier of the server's chain and name, used instead of `roots_cas`.
188    server_cert_verifier: Option<Arc<dyn ServerCertVerifier>>,
189    server_name: String,
190    mtu: usize,
191    replay_protection_window: usize,
192}
193
194impl Default for ConfigBuilder {
195    fn default() -> Self {
196        Self {
197            crypto_provider: None,
198            certificates: vec![],
199            cipher_suites: vec![],
200            signature_schemes: vec![],
201            srtp_protection_profiles: vec![],
202            use_srtp_optional: false,
203            alpn_protocols: vec![],
204            use_srtp_required: false,
205            client_auth: ClientAuthType::default(),
206            bad_certificate_for_a_missing_client_certificate: false,
207            extended_master_secret: ExtendedMasterSecretType::default(),
208            flight_interval: Duration::default(),
209            maximum_flight_interval: MAXIMUM_RETRANSMIT_INTERVAL,
210            handshake_timeout: None,
211            cookie_exchange: true,
212            hello_verify_request_version: PROTOCOL_VERSION1_2,
213            early_data_retransmit: true,
214            min_version: DtlsVersion::Dtls1_2,
215            max_version: DtlsVersion::Dtls1_3,
216            connection_id: Some(0),
217            connection_id_migration: false,
218            invalid_record_limit: None,
219            post_quantum_key_share: true,
220            psk: None,
221            psk_identity_hint: None,
222            session_tickets: 0,
223            session_ticket_issuer: None,
224            session_ticket_lifetime: crate::dtls13::psk::DEFAULT_TICKET_LIFETIME,
225            session_store: None,
226            session_cache: None,
227            dtls12_resumption: true,
228            external_psks: vec![],
229            psk_without_key_exchange: false,
230            post_handshake_auth: false,
231            max_early_data: 0,
232            insecure_skip_verify: false,
233            insecure_hashes: false,
234            insecure_verification: false,
235            verify_peer_certificate: None,
236            roots_cas: rustls::RootCertStore::empty(),
237            client_cas: rustls::RootCertStore::empty(),
238            verifier_adapter: default_verifier_adapter(),
239            server_cert_verifier: None,
240            server_name: String::default(),
241            mtu: 0,
242            replay_protection_window: 0,
243        }
244    }
245}
246
247impl ConfigBuilder {
248    /// Selects the cryptography and CSPRNG implementation for this DTLS association.
249    ///
250    /// The provider is resolved while building the handshake configuration and is reused for the
251    /// entire handshake and record lifetime. No global registration is required.
252    pub fn with_crypto_provider(mut self, provider: Arc<dyn RTCCryptoProvider>) -> Self {
253        self.crypto_provider = Some(provider);
254        self
255    }
256
257    /// certificates contains certificate chain to present to the other side of the connection.
258    /// Server MUST set this if psk is nil, and MAY set it alongside a psk to serve both families
259    /// Client SHOULD set this so CertificateRequests can be handled, and MUST NOT set it with a psk
260    pub fn with_certificates(mut self, certificates: Vec<Certificate>) -> Self {
261        self.certificates = certificates;
262        self
263    }
264
265    /// cipher_suites is a list of supported cipher suites.
266    /// If cipher_suites is nil, a default list is used
267    ///
268    /// The list is exact, and with it the versions: the TLS 1.3 suites in it
269    /// (`Tls_Aes_128_Gcm_Sha256` and the others of that family) are what DTLS 1.3 is
270    /// negotiated with, the rest what DTLS 1.2 is. A list without a TLS 1.3 suite therefore
271    /// negotiates DTLS 1.2 only, and one with nothing else DTLS 1.3 only. The default list
272    /// has both.
273    pub fn with_cipher_suites(mut self, cipher_suites: Vec<CipherSuiteId>) -> Self {
274        self.cipher_suites = cipher_suites;
275        self
276    }
277
278    /// signature_schemes contains the signature and hash schemes that the peer requests to verify.
279    pub fn with_signature_schemes(mut self, signature_schemes: Vec<SignatureScheme>) -> Self {
280        self.signature_schemes = signature_schemes;
281        self
282    }
283
284    /// srtp_protection_profiles are the supported protection profiles
285    /// Clients will send this via use_srtp and assert that the server properly responds
286    /// Servers will assert that clients send one of these profiles and will respond as needed
287    pub fn with_srtp_protection_profiles(
288        mut self,
289        srtp_protection_profiles: Vec<SrtpProtectionProfile>,
290    ) -> Self {
291        self.srtp_protection_profiles = srtp_protection_profiles;
292        self
293    }
294
295    /// Lets a client that offers `use_srtp` go on when the server's ServerHello carries no
296    /// `use_srtp` extension (RFC 5764 section 4.1.1: a server that does not take the extension
297    /// leaves it out). The association then has no SRTP profile
298    /// ([`SrtpProtectionProfile::Unsupported`]) and carries DTLS application data only: the
299    /// caller decides whether that is enough. `false` (the default) aborts such a handshake with
300    /// a fatal alert.
301    pub fn with_use_srtp_optional(mut self, use_srtp_optional: bool) -> Self {
302        self.use_srtp_optional = use_srtp_optional;
303        self
304    }
305
306    /// The application protocols of Application-Layer Protocol Negotiation (RFC 7301), most
307    /// preferred first; empty (the default) uses no ALPN. A client offers them in its
308    /// ClientHello and takes the one the server selects, which must be one of them; a server
309    /// selects the first of its own that the client offered, refuses a client that offered
310    /// ALPN but none of them (`no_application_protocol`), and answers a client without the
311    /// extension without it. DTLS 1.2 (ServerHello) and DTLS 1.3 (EncryptedExtensions).
312    /// [`State::application_protocol`](crate::state::State::application_protocol) gives the
313    /// result. Each name is 1 to 255 bytes.
314    pub fn with_alpn_protocols(mut self, protocols: Vec<String>) -> Self {
315        self.alpn_protocols = protocols;
316        self
317    }
318
319    /// Makes a server refuse a client whose `use_srtp` shares no profile with it, with a fatal
320    /// insufficient_security alert. RFC 5764 section 4.1.1: with no shared profile "the server
321    /// SHOULD NOT return the use_srtp extension at which point the connection falls back to
322    /// the negotiated DTLS cipher suite. If that is not acceptable, the server SHOULD return
323    /// an appropriate DTLS alert". `false` (the default) falls back; set `true` when the
324    /// association is of no use without SRTP.
325    pub fn with_use_srtp_required(mut self, use_srtp_required: bool) -> Self {
326        self.use_srtp_required = use_srtp_required;
327        self
328    }
329
330    /// client_auth determines the server's policy for
331    /// TLS Client Authentication. The default is NoClientCert.
332    pub fn with_client_auth(mut self, client_auth: ClientAuthType) -> Self {
333        self.client_auth = client_auth;
334        self
335    }
336
337    /// The alert a server that requires a client certificate
338    /// ([`ClientAuthType::RequireAnyClientCert`], [`ClientAuthType::RequireAndVerifyClientCert`])
339    /// ends the handshake with when the client sends none. `false` (the default):
340    /// `handshake_failure` (RFC 5246 section 7.4.6), `certificate_required` under DTLS 1.3 (RFC
341    /// 8446 section 4.4.2.4). `true`: `bad_certificate`, which RFC 8122 section 6.2 requires of
342    /// an endpoint of the SDP offer/answer model ("if the client does not provide one ... the
343    /// server endpoint MUST terminate the media connection with a bad_certificate error");
344    /// the WebRTC peer connection sets it.
345    pub fn with_bad_certificate_for_a_missing_client_certificate(mut self, bad: bool) -> Self {
346        self.bad_certificate_for_a_missing_client_certificate = bad;
347        self
348    }
349
350    /// extended_master_secret determines if the "Extended Master Secret" extension
351    /// should be disabled, requested, or required (default requested).
352    pub fn with_extended_master_secret(
353        mut self,
354        extended_master_secret: ExtendedMasterSecretType,
355    ) -> Self {
356        self.extended_master_secret = extended_master_secret;
357        self
358    }
359
360    /// The initial value of the handshake retransmission timer: how long a flight waits for
361    /// its answer before it is sent again. The timer doubles at each retransmission, up to
362    /// [`Self::with_maximum_flight_interval`], and keeps its value until a flight is answered
363    /// without loss (RFC 6347 4.2.4.1). Defaults to one second.
364    pub fn with_flight_interval(mut self, flight_interval: Duration) -> Self {
365        self.flight_interval = flight_interval;
366        self
367    }
368
369    /// The value the handshake retransmission timer doubles up to. Defaults to 60 seconds, the
370    /// least RFC 6347 4.2.4.1 allows as a maximum; a value below the initial interval is
371    /// raised to it.
372    pub fn with_maximum_flight_interval(mut self, maximum_flight_interval: Duration) -> Self {
373        self.maximum_flight_interval = maximum_flight_interval;
374        self
375    }
376
377    /// How long a handshake may take, from the first flight sent or received, before the
378    /// association fails with `ErrHandshakeTimeout`. `None`, the default, never gives up:
379    /// the flight is retransmitted, at the timer that doubles up to
380    /// [`Self::with_maximum_flight_interval`], for as long as the association exists.
381    ///
382    /// RFC 6347 section 4.2.4 and RFC 9147 section 5.8 define the retransmission timer and
383    /// set no total limit, so by default none is set here either: what ends a handshake is
384    /// the transport under it (in a peer connection, ICE: consent expiry or the failure of
385    /// every candidate pair, RFC 7675), a fatal alert, or the application closing the
386    /// association. An application that runs DTLS over a transport that cannot tell it that
387    /// the peer is gone sets a limit here. A server endpoint drops an association it made
388    /// for an address the client has not verified after a fixed time whatever this says
389    /// (the cookie exchange of a fragmented DTLS 1.3 ClientHello).
390    pub fn with_handshake_timeout(mut self, handshake_timeout: Option<Duration>) -> Self {
391        self.handshake_timeout = handshake_timeout;
392        self
393    }
394
395    /// Whether a server [`Endpoint`](crate::endpoint::Endpoint) answers a ClientHello that
396    /// carries no valid cookie with a HelloVerifyRequest (RFC 6347 4.2.1). On by default, as
397    /// the RFC asks: until a client echoes the cookie the server keeps no state for it and
398    /// sends it nothing larger than what it received.
399    ///
400    /// Off, the first ClientHello gets an association and the server's whole first flight. That
401    /// saves a round trip where something else has already shown that the client receives at
402    /// its address (ICE connectivity checks do, for WebRTC), and makes the server an
403    /// amplifier and a holder of state for spoofed addresses where nothing has.
404    pub fn with_cookie_exchange(mut self, cookie_exchange: bool) -> Self {
405        self.cookie_exchange = cookie_exchange;
406        self
407    }
408
409    /// The server_version a server writes into its HelloVerifyRequest. The default is DTLS 1.2
410    /// ([`PROTOCOL_VERSION1_2`]), the version its ServerHello carries: RFC 6347 4.2.1, "The
411    /// server MUST use the same version number in the HelloVerifyRequest that it would use when
412    /// sending a ServerHello" (this server never negotiates DTLS 1.0: a ClientHello offering
413    /// nothing later is refused). [`PROTOCOL_VERSION1_0`] writes DTLS 1.0 whatever follows, the
414    /// same section's SHOULD ("DTLS 1.2 server implementations SHOULD use DTLS version 1.0
415    /// regardless of the version of TLS that is expected to be negotiated") and what OpenSSL
416    /// sends; the MUST governs where the two contradict (RFC 2119: a MUST is an absolute
417    /// requirement, a SHOULD admits exceptions; recorded 2026-11-29). A client is
418    /// required to ignore the field, and this one does, so the setting changes nothing but that
419    /// field.
420    ///
421    /// [`Self::build`] refuses any other version.
422    pub fn with_hello_verify_request_version(mut self, version: ProtocolVersion) -> Self {
423        self.hello_verify_request_version = version;
424        self
425    }
426
427    /// Whether a client that receives protected application data while it still waits for the
428    /// server's Finished sends its final flight again at once, instead of when its timer fires
429    /// (RFC 6347 4.2.4, a MAY: such data means the server has its keys and its Finished was
430    /// lost or is late). On by default. Only a record that authenticates under the negotiated
431    /// keys counts, and a flight is sent again for this reason once at most.
432    pub fn with_early_data_retransmit(mut self, early_data_retransmit: bool) -> Self {
433        self.early_data_retransmit = early_data_retransmit;
434        self
435    }
436
437    /// The DTLS versions to negotiate: the lowest and the highest, both included. The default
438    /// is DTLS 1.2 to DTLS 1.3, with 1.3 preferred: a client offers both in
439    /// `supported_versions`, a server takes 1.3 from a client that offers it and 1.2 from one
440    /// that does not (RFC 9147 section 5.3, RFC 8446 section 4.2.1), and each end checks the
441    /// downgrade sentinel of RFC 8446 section 4.1.3.
442    ///
443    /// DTLS 1.3 authenticates with certificates here; a configuration with a pre-shared key
444    /// negotiates DTLS 1.2 (its PSK cipher suites), and [`Self::build`] refuses one that asks
445    /// for DTLS 1.3 as the minimum. It also refuses a minimum above the maximum.
446    pub fn with_protocol_versions(mut self, min: DtlsVersion, max: DtlsVersion) -> Self {
447        self.min_version = min;
448        self.max_version = max;
449        self
450    }
451
452    /// Whether, and how, this side uses connection ids (RFC 9147 section 9, on RFC 9146's
453    /// `connection_id` extension): `Some(n)` sends the extension and asks the peer to put a
454    /// connection id of `n` random bytes in every protected record it sends, `Some(0)` sends
455    /// it and asks for none (the peer may still ask for one in the other direction), `None`
456    /// does not use the extension. Negotiated when both sides send it. The default is
457    /// `Some(0)`, as RFC 9147 section 5.1 asks of a client that wants no connection id.
458    ///
459    /// Both versions: DTLS 1.2 uses RFC 9146 (`tls12_cid` records), DTLS 1.3 its own record
460    /// header. A ClientHello that offers both carries the extension once, for both (RFC 9147
461    /// section 5.1).
462    pub fn with_connection_id(mut self, length: Option<usize>) -> Self {
463        self.connection_id = length;
464        self
465    }
466
467    /// Whether a server [`Endpoint`](crate::endpoint::Endpoint) follows an association to a
468    /// new address when a record under one of its connection ids arrives from there, is
469    /// authentic and is newer than any before it (RFC 9146 section 6). Off by default: the
470    /// RFC also requires a strategy that shows the new address receives, and none is run
471    /// here. An application that has one (ICE has: consent and connectivity checks on the
472    /// new pair) turns this on; under ICE the engine addresses an association by the
473    /// selected pair anyway.
474    pub fn with_connection_id_migration(mut self, migration: bool) -> Self {
475        self.connection_id_migration = migration;
476        self
477    }
478
479    /// Whether DTLS 1.3 offers and accepts the hybrid post-quantum group X25519MLKEM768
480    /// (draft-ietf-tls-ecdhe-mlkem, code point 0x11EC), preferred over the curves. On by
481    /// default; it takes effect only with a crypto provider that has ML-KEM (the built-in
482    /// aws-lc-rs one; ring has none). Its key share is 1216 bytes, so a ClientHello that
483    /// carries it does not fit one datagram and is sent as two fragments.
484    pub fn with_post_quantum_key_share(mut self, post_quantum_key_share: bool) -> Self {
485        self.post_quantum_key_share = post_quantum_key_share;
486        self
487    }
488
489    /// How many invalid records (malformed, or failing authentication) an association takes
490    /// before it gives its peer up as persistently misbehaving and fails, without an alert
491    /// (RFC 9147 section 5.10 for DTLS 1.3; RFC 6347 section 4.2.7 for DTLS 1.2, which counts
492    /// the protected records that fail authentication). `None`, the default, never does: over UDP
493    /// anyone who knows the addresses can send such records, and a limit lets them end the
494    /// association. A limit suits a transport where only the peer can send (under ICE, a
495    /// selected pair with consent checks narrows it to on-path senders).
496    pub fn with_invalid_record_limit(mut self, limit: Option<u64>) -> Self {
497        self.invalid_record_limit = limit;
498        self
499    }
500
501    /// Server: how many tickets (NewSessionTicket messages, RFC 8446 section 4.6.1) a DTLS 1.3
502    /// server sends after each handshake, for the client to resume with. 0, the default, sends
503    /// none and accepts none. Tickets are sealed under a key the configuration makes at
504    /// random when it is built, and each is accepted once: see [`crate::session`].
505    ///
506    /// Any count above 0 also makes a DTLS 1.2 server issue and accept RFC 5077 session
507    /// tickets, one per handshake to a client that asks for one, for sessions made with the
508    /// extended master secret. That costs forward secrecy, which DTLS 1.3 tickets do not: a
509    /// DTLS 1.2 ticket is the association's master secret sealed under this server's ticket
510    /// key and sent in the clear part of the handshake, and a resumed DTLS 1.2 association
511    /// runs no key exchange, so whoever later obtains the ticket key decrypts the recorded
512    /// association the ticket came from and every one resumed from it (see
513    /// [the type's notes](Self#session-resumption-and-forward-secrecy)).
514    /// [`Self::with_dtls12_resumption`]`(false)` issues DTLS 1.3 tickets only.
515    ///
516    /// A server that also has a [peer-certificate check](Self::with_verify_peer_certificate)
517    /// runs it again on the client certificates a ticket carries. A ticket that carries none
518    /// is resumed only when the server asks its clients for no certificate
519    /// ([`ClientAuthType::NoClientCert`]: the first handshake had none to check either); a
520    /// server that asks for one runs a full handshake instead, and asks again.
521    pub fn with_session_tickets(mut self, count: u8) -> Self {
522        self.session_tickets = count;
523        self
524    }
525
526    /// Server: the keys to seal and open tickets with, shared with other configurations: a
527    /// ticket one of them issued is accepted (once) by any other. It takes the place of
528    /// [`Self::with_session_tickets`] and [`Self::with_session_ticket_lifetime`], whose count
529    /// and lifetime are the issuer's own. `None`, the default, has the configuration make keys
530    /// of its own when tickets are on. A client ignores it.
531    pub fn with_session_ticket_issuer(
532        mut self,
533        issuer: Option<crate::session::SessionTicketIssuer>,
534    ) -> Self {
535        self.session_ticket_issuer = issuer;
536        self
537    }
538
539    /// Server: how long a ticket it issues may be used for (`ticket_lifetime`), and how long a
540    /// DTLS 1.2 session it keeps in its session cache may be resumed. Two hours by default; at
541    /// most seven days (RFC 8446 section 4.6.1).
542    pub fn with_session_ticket_lifetime(mut self, lifetime: Duration) -> Self {
543        self.session_ticket_lifetime = lifetime;
544        self
545    }
546
547    /// Client: where to keep the tickets servers send, and take one from for the next
548    /// handshake with the same server name. Without a store (the default) a client offers no
549    /// PSK and drops the tickets it is sent.
550    ///
551    /// A DTLS 1.2 client keeps its sessions there too (RFC 5246 section 7.3: by session id,
552    /// or RFC 5077: by ticket, and it asks for a ticket in every ClientHello), when they were
553    /// made with the extended master secret (RFC 7627 section 5.3), and offers the most recent
554    /// one again. A resumed DTLS 1.2 association runs no key exchange: its keys come from
555    /// the stored master secret, so what is in the store (and, for a ticket, the server's
556    /// ticket key) opens every association of that session, recorded ones included (see
557    /// [the type's notes](Self#session-resumption-and-forward-secrecy)).
558    /// [`Self::with_dtls12_resumption`]`(false)` keeps DTLS 1.3 tickets only.
559    pub fn with_session_store(
560        mut self,
561        store: Option<Arc<dyn crate::session::SessionStore>>,
562    ) -> Self {
563        self.session_store = store;
564        self
565    }
566
567    /// DTLS 1.2 server: where to keep the sessions it may resume by session id (RFC 5246
568    /// sections 7.3 and 7.4.1.3). With one, each full handshake that used the extended master
569    /// secret makes a session with a new 32-byte session id, valid for
570    /// [`Self::with_session_ticket_lifetime`]; a ClientHello that offers it gets the
571    /// abbreviated handshake. `None`, the default, gives no session id and resumes by
572    /// session id nothing. The cache holds master secrets, and a resumed association runs no
573    /// key exchange: there is no forward secrecy against the cache's contents for the
574    /// associations of a cached session (see
575    /// [the type's notes](Self#session-resumption-and-forward-secrecy)).
576    pub fn with_session_cache(
577        mut self,
578        cache: Option<Arc<dyn crate::session::SessionCache>>,
579    ) -> Self {
580        self.session_cache = cache;
581        self
582    }
583
584    /// Whether DTLS 1.2 associations resume sessions at all (RFC 5246 section 7.3 by session
585    /// id, RFC 5077 by ticket). `true`, the default, has a client with a
586    /// [session store](Self::with_session_store) ask for a ticket and offer its sessions, and
587    /// a server with a [session cache](Self::with_session_cache) or
588    /// [tickets](Self::with_session_tickets) give session ids and tickets and resume them.
589    /// `false` leaves DTLS 1.3 resumption as configured and takes DTLS 1.2 out of it: a
590    /// client asks for no ticket, offers no session id or ticket and keeps no DTLS 1.2
591    /// session; a server gives no session id, issues no ticket and resumes nothing, so every
592    /// DTLS 1.2 handshake is a full one with its own (EC)DHE exchange.
593    ///
594    /// What `true` costs, once tickets, a cache or a store are configured: a resumed DTLS
595    /// 1.2 association runs no key exchange, and a DTLS 1.2 ticket is the master secret of
596    /// the association it came from, sealed under the server's ticket key and sent in the
597    /// clear part of the handshake. There is then no forward secrecy against the ticket key,
598    /// the session cache or the client's store: any of them, obtained later, decrypts the
599    /// recorded associations of the session. DTLS 1.3 resumption (`psk_dhe_ke`) has no such
600    /// cost. The default is `true` only so that configurations made before this switch
601    /// existed behave as they did; set `false` unless DTLS 1.2 resumption is wanted (see
602    /// [the type's notes](Self#session-resumption-and-forward-secrecy)).
603    pub fn with_dtls12_resumption(mut self, resumption: bool) -> Self {
604        self.dtls12_resumption = resumption;
605        self
606    }
607
608    /// DTLS 1.3: external pre-shared keys (RFC 8446 section 2.2). A client offers each of
609    /// them; a server accepts one whose identity it has in place of a certificate exchange.
610    /// The DTLS 1.2 PSK suites are configured with [`Self::with_psk`] instead.
611    ///
612    /// An external PSK authenticates both sides by possession of the key (RFC 8446 sections
613    /// 2.2 and 4.2.11): no certificate is sent in either direction, the association reports
614    /// no peer certificates, and a [peer-certificate check](Self::with_verify_peer_certificate)
615    /// is **not called** for that handshake, on a client or on a server, whatever the
616    /// server's [`Self::with_client_auth`] says. A configuration may have both: the check
617    /// then covers the handshakes that carry certificates (and resumptions of them), and the
618    /// PSK the ones made with it. An application that identifies its peer by certificate
619    /// alone must not configure an external PSK for that peer.
620    pub fn with_external_psks(mut self, psks: Vec<crate::session::ExternalPsk>) -> Self {
621        self.external_psks = psks;
622        self
623    }
624
625    /// DTLS 1.3: whether a PSK may also be used alone, without an (EC)DHE exchange (the
626    /// `psk_ke` mode of RFC 8446 section 4.2.9). Off by default: `psk_dhe_ke` only, which
627    /// keeps forward secrecy (RFC 8446 section E.1).
628    pub fn with_psk_without_key_exchange(mut self, allowed: bool) -> Self {
629        self.psk_without_key_exchange = allowed;
630        self
631    }
632
633    /// DTLS 1.3 client: offer post-handshake authentication (the `post_handshake_auth`
634    /// extension, RFC 8446 section 4.2.6), so that the server may ask for this client's
635    /// certificate at any time after the handshake ([`DTLSConn::request_client_certificate`](crate::conn::DTLSConn::request_client_certificate)).
636    /// It is answered at once, with the configured certificate if the request allows it and
637    /// with an empty Certificate otherwise. Off by default.
638    pub fn with_post_handshake_auth(mut self, offer: bool) -> Self {
639        self.post_handshake_auth = offer;
640        self
641    }
642
643    /// DTLS 1.3 server: take up to `size` bytes of 0-RTT data (RFC 8446 section 4.2.10)
644    /// with the tickets it issues ([`Self::with_session_tickets`]). 0, the default, takes
645    /// none. 0-RTT data can be replayed by anyone who saw it: each ticket is accepted once
646    /// (RFC 8446 section 8.1), and the ticket's age has to agree with the server's within ten
647    /// seconds (section 8.3), but the application decides what is safe to do before the
648    /// handshake is complete ([`EndpointEvent::EarlyData`](crate::endpoint::EndpointEvent::EarlyData)).
649    /// A ClientHello answered with a HelloRetryRequest has no 0-RTT, so this takes effect
650    /// only with the cookie exchange off ([`Self::with_cookie_exchange`]).
651    pub fn with_max_early_data(mut self, size: u32) -> Self {
652        self.max_early_data = size;
653        self
654    }
655
656    /// psk sets the pre-shared key used by this DTLS connection
657    /// A client with a psk offers only psk cipher_suites; a server that also holds certificates
658    /// offers both families and lets the negotiated suite decide which credential it uses
659    pub fn with_psk(mut self, psk: Option<PskCallback>) -> Self {
660        self.psk = psk;
661        self
662    }
663
664    /// psk_identity_hint sets the pre-shared key hint
665    pub fn with_psk_identity_hint(mut self, psk_identity_hint: Option<Vec<u8>>) -> Self {
666        self.psk_identity_hint = psk_identity_hint;
667        self
668    }
669
670    /// insecure_skip_verify controls whether a client verifies the
671    /// server's certificate chain and host name.
672    /// If insecure_skip_verify is true, TLS accepts any certificate
673    /// presented by the server and any host name in that certificate.
674    /// In this mode, TLS is susceptible to man-in-the-middle attacks.
675    /// This should be used only for testing.
676    pub fn with_insecure_skip_verify(mut self, insecure_skip_verify: bool) -> Self {
677        self.insecure_skip_verify = insecure_skip_verify;
678        self
679    }
680
681    /// insecure_hashes allows the use of hashing algorithms that are known
682    /// to be vulnerable.
683    pub fn with_insecure_hashes(mut self, insecure_hashes: bool) -> Self {
684        self.insecure_hashes = insecure_hashes;
685        self
686    }
687
688    /// insecure_verification allows the use of verification algorithms that are
689    /// known to be vulnerable or deprecated
690    pub fn with_insecure_verification(mut self, insecure_verification: bool) -> Self {
691        self.insecure_verification = insecure_verification;
692        self
693    }
694
695    /// VerifyPeerCertificate, if not nil, is called after normal
696    /// certificate verification by either a client or server. It
697    /// receives the certificate provided by the peer and also a flag
698    /// that tells if normal verification has succeeded. If it returns a
699    /// non-nil error, the handshake is aborted and that error results.
700    ///
701    /// If normal verification fails then the handshake will abort before
702    /// considering this callback. If normal verification is disabled by
703    /// setting insecure_skip_verify, or (for a server) when client_auth is
704    /// RequestClientCert or RequireAnyClientCert, then this callback will
705    /// be considered but the verifiedChains will always be nil.
706    ///
707    /// What it covers. The check is called with the certificates the peer presents in a
708    /// handshake, and it is called only when there are certificates:
709    ///
710    /// - A full handshake: on the server's chain (a client), on the client's chain (a
711    ///   server). A server is not called for a client that sends no certificate: one it
712    ///   never asks ([`ClientAuthType::NoClientCert`]) or one that answers a request with
713    ///   none where that is allowed (`RequestClientCert`, `VerifyClientCertIfGiven`).
714    /// - A resumption (a DTLS 1.3 ticket, a DTLS 1.2 session id or ticket): no certificate
715    ///   is sent, and the check runs again on the certificates stored with the ticket or
716    ///   session, those of the handshake that made it (with no verified chains). It fails
717    ///   closed where a certificate should be there: a client fails a resumption whose
718    ///   ticket or session carries none (`bad_certificate`), and a server that asks its
719    ///   clients for a certificate resumes no ticket or session without one (a full
720    ///   handshake runs instead). A server that asks for none resumes, without the check:
721    ///   the first handshake had no client certificate either.
722    /// - An external PSK handshake ([`Self::with_external_psks`], RFC 8446 sections 2.2 and
723    ///   4.2.11): **not called**. No certificate exists; the peer is authenticated by
724    ///   possession of the key, and by nothing this check sees.
725    pub fn with_verify_peer_certificate(
726        mut self,
727        verify_peer_certificate: Option<VerifyPeerCertificateFn>,
728    ) -> Self {
729        self.verify_peer_certificate = verify_peer_certificate;
730        self
731    }
732
733    /// roots_cas defines the set of root certificate authorities
734    /// that one peer uses when verifying the other peer's certificates.
735    /// If RootCAs is nil, TLS uses the host's root CA set.
736    /// Used by Client to verify server's certificate
737    pub fn with_roots_cas(mut self, roots_cas: rustls::RootCertStore) -> Self {
738        self.roots_cas = roots_cas;
739        self
740    }
741
742    /// client_cas defines the set of root certificate authorities
743    /// that servers use if required to verify a client certificate
744    /// by the policy in client_auth.
745    /// Used by Server to verify client's certificate
746    pub fn with_client_cas(mut self, client_cas: rustls::RootCertStore) -> Self {
747        self.client_cas = client_cas;
748        self
749    }
750
751    /// Selects the rustls/webpki adapter used for optional CA-chain and hostname verification.
752    pub fn with_rustls_verifier_adapter(mut self, adapter: RustlsVerifierAdapter) -> Self {
753        self.verifier_adapter = Some(adapter);
754        self
755    }
756
757    /// A client verifies the server's certificate chain and name with `verifier` (a rustls
758    /// [`ServerCertVerifier`] of the application's) instead of the roots of
759    /// [`Self::with_roots_cas`]. As with the roots, the handshake's CertificateVerify is still
760    /// checked by the DTLS layer itself; `insecure_skip_verify` skips this verifier too.
761    pub fn with_server_cert_verifier(mut self, verifier: Arc<dyn ServerCertVerifier>) -> Self {
762        self.server_cert_verifier = Some(verifier);
763        self
764    }
765
766    /// server_name is used to verify the hostname on the returned
767    /// certificates unless insecure_skip_verify is given, and a client sends it as SNI
768    /// (RFC 6066 section 3) unless it is an IP address.
769    ///
770    /// A client with no server name takes the remote address `build` is given. With neither,
771    /// a client that verifies nothing by name (`with_insecure_skip_verify(true)` or a PSK)
772    /// sends no server_name extension (in 0.2.0 it sent "localhost"); for one that verifies
773    /// the certificate by name `build` returns an error, as there is no name to verify against
774    /// (in 0.2.0 it verified against "localhost", with a warning). A WebRTC peer connection
775    /// verifies the certificate by its fingerprint in the session description (RFC 8122,
776    /// RFC 8827) and sends none.
777    pub fn with_server_name(mut self, server_name: String) -> Self {
778        self.server_name = server_name;
779        self
780    }
781
782    /// mtu is the length at which handshake messages will be fragmented to
783    /// fit within the maximum transmission unit (default is 1200 bytes)
784    pub fn with_mtu(mut self, mtu: usize) -> Self {
785        self.mtu = mtu;
786        self
787    }
788
789    /// replay_protection_window is the size of the replay attack protection window.
790    /// Duplication of the sequence number is checked in this window size.
791    /// Packet with sequence number older than this value compared to the latest
792    /// accepted packet will be discarded. (default is 64)
793    ///
794    /// RFC 6347 4.1.2.6 requires a window of at least 32: a smaller value is raised to 32.
795    pub fn with_replay_protection_window(mut self, replay_protection_window: usize) -> Self {
796        self.replay_protection_window = replay_protection_window;
797        self
798    }
799}
800
801pub(crate) const DEFAULT_MTU: usize = 1200; // bytes
802
803/// A version of DTLS this crate negotiates.
804#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
805#[non_exhaustive]
806pub enum DtlsVersion {
807    /// DTLS 1.2 (RFC 6347), `{254, 253}` on the wire.
808    Dtls1_2,
809    /// DTLS 1.3 (RFC 9147), `{254, 252}` on the wire.
810    Dtls1_3,
811}
812
813impl DtlsVersion {
814    /// The version as a [`ProtocolVersion`]: what `supported_versions` carries, and the two
815    /// bytes webrtc-stats' `tlsVersion` is the hex of (`FEFD`, `FEFC`).
816    pub fn protocol_version(self) -> ProtocolVersion {
817        match self {
818            DtlsVersion::Dtls1_2 => PROTOCOL_VERSION1_2,
819            DtlsVersion::Dtls1_3 => ProtocolVersion {
820                major: 254,
821                minor: 252,
822            },
823        }
824    }
825}
826
827/// PSKCallback is called once we have the remote's psk_identity_hint.
828/// If the remote provided none it will be nil
829pub(crate) type PskCallback = Arc<dyn (Fn(&[u8]) -> Result<Vec<u8>>) + Send + Sync>;
830
831/// ClientAuthType declares the policy the server will follow for
832/// TLS Client Authentication.
833#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
834#[non_exhaustive]
835pub enum ClientAuthType {
836    #[default]
837    /// `NO_CLIENT_CERT` (`0`).
838    NoClientCert = 0,
839    /// `REQUEST_CLIENT_CERT` (`1`).
840    RequestClientCert = 1,
841    /// `REQUIRE_ANY_CLIENT_CERT` (`2`).
842    RequireAnyClientCert = 2,
843    /// `VERIFY_CLIENT_CERT_IF_GIVEN` (`3`).
844    VerifyClientCertIfGiven = 3,
845    /// `REQUIRE_AND_VERIFY_CLIENT_CERT` (`4`).
846    RequireAndVerifyClientCert = 4,
847}
848
849// ExtendedMasterSecretType declares the policy the client and server
850// will follow for the Extended Master Secret extension
851#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
852/// How strictly to require the extended master secret extension ([RFC 7627]).
853pub enum ExtendedMasterSecretType {
854    #[default]
855    /// `REQUEST` (`0`).
856    Request = 0,
857    /// `REQUIRE` (`1`).
858    Require = 1,
859    /// `DISABLE` (`2`).
860    Disable = 2,
861}
862
863impl ConfigBuilder {
864    fn offered_cipher_suites(&self, is_client: bool) -> Result<Vec<Box<dyn CipherSuite>>> {
865        let legacy_suites = self.configured_suites(false);
866        // a client offers one family or the other, while a server can only offer them if
867        // it actually holds a certificate.
868        let exclude_certificate = if is_client {
869            self.psk.is_some()
870        } else {
871            self.certificates.is_empty()
872        };
873
874        parse_cipher_suites(&legacy_suites, self.psk.is_none(), exclude_certificate)
875    }
876
877    /// The cipher suites of the configured list that belong to one family: the TLS 1.3
878    /// suites, or the others.
879    fn configured_suites(&self, tls13: bool) -> Vec<CipherSuiteId> {
880        self.cipher_suites
881            .iter()
882            .copied()
883            .filter(|suite| suite.is_tls13() == tls13)
884            .collect()
885    }
886
887    fn validate(&self, is_client: bool) -> Result<()> {
888        if self.min_version > self.max_version {
889            return Err(Error::ErrUnsupportedProtocolVersion);
890        }
891        // A pre-shared key means the DTLS 1.2 PSK suites: a client with one offers nothing
892        // else, and a server with nothing else has no certificate for DTLS 1.3.
893        let psk_only = self.psk.is_some() && (is_client || self.certificates.is_empty());
894        if psk_only && self.min_version == DtlsVersion::Dtls1_3 {
895            return Err(Error::ErrUnsupportedProtocolVersion);
896        }
897
898        if is_client && self.psk.is_some() && self.psk_identity_hint.is_none() {
899            return Err(Error::ErrPskAndIdentityMustBeSetForClient);
900        }
901
902        if !is_client && self.psk.is_none() && self.certificates.is_empty() {
903            return Err(Error::ErrServerMustHaveCertificate);
904        }
905
906        // A server may hold both and let each handshake pick
907        if is_client && !self.certificates.is_empty() && self.psk.is_some() {
908            return Err(Error::ErrPskAndCertificate);
909        }
910
911        if self.psk_identity_hint.is_some() && self.psk.is_none() {
912            return Err(Error::ErrIdentityNoPsk);
913        }
914
915        self.offered_cipher_suites(is_client)?;
916
917        Ok(())
918    }
919
920    /// build handshake config
921    pub fn build(
922        mut self,
923        is_client: bool,
924        remote_addr: Option<SocketAddr>,
925    ) -> Result<HandshakeConfig> {
926        // The caller supplies the provider; this crate never resolves a default. An application
927        // that wants the feature-selected built-in passes `crypto::default_provider()?`.
928        let crypto_provider = self.crypto_provider.take().ok_or_else(|| {
929            Error::Crypto(
930                "no crypto provider configured: call ConfigBuilder::with_crypto_provider"
931                    .to_owned(),
932            )
933        })?;
934        self.validate(is_client)?;
935
936        // Each id is paired with the suite's own `is_psk`, so the checks below can tell the two
937        // families apart without a second definition of which suites are psk.
938        let mut local_cipher_suites: Vec<(CipherSuiteId, bool)> = self
939            .offered_cipher_suites(is_client)?
940            .iter()
941            .map(|cs| (cs.id(), cs.is_psk()))
942            .filter(|(id, _)| id.supported_by(crypto_provider.crypto()))
943            .collect();
944        if local_cipher_suites.is_empty() {
945            return Err(Error::ErrNoAvailableCipherSuites);
946        }
947
948        let sigs: Vec<u16> = self.signature_schemes.iter().map(|x| *x as u16).collect();
949        let local_signature_schemes: Vec<_> = parse_signature_schemes(&sigs, self.insecure_hashes)?
950            .into_iter()
951            .filter(|algorithm| {
952                algorithm.crypto_scheme().is_ok_and(|scheme| {
953                    crypto_provider
954                        .crypto()
955                        .supports(crypto::CryptoAlgorithm::Signature(scheme))
956                })
957            })
958            .collect();
959
960        let has_non_psk_suites = local_cipher_suites.iter().any(|(_, is_psk)| !is_psk);
961        if has_non_psk_suites && local_signature_schemes.is_empty() {
962            return Err(Error::ErrNoAvailableSignatureSchemes);
963        }
964
965        let local_named_curves: Vec<_> = [NamedCurve::P256, NamedCurve::X25519, NamedCurve::P384]
966            .into_iter()
967            .filter(|curve| {
968                curve.crypto_algorithm().is_ok_and(|algorithm| {
969                    crypto_provider
970                        .crypto()
971                        .supports(crypto::CryptoAlgorithm::KeyExchange(algorithm))
972                })
973            })
974            .collect();
975        if has_non_psk_suites && local_named_curves.is_empty() {
976            return Err(Error::ErrNoAvailableCipherSuites);
977        }
978
979        if !is_client && has_non_psk_suites {
980            let signing_key = &self.certificates[0].private_key.signing_key;
981            local_cipher_suites.retain(|(id, is_psk)| {
982                *is_psk
983                    || local_signature_schemes.iter().any(|algorithm| {
984                        let signature_family_matches = match id {
985                            CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256
986                            | CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_256_Cbc_Sha
987                            | CipherSuiteId::Tls_Ecdhe_Rsa_With_ChaCha20_Poly1305_Sha256 => {
988                                algorithm.signature.is_rsa()
989                            }
990                            // RFC 8422 5.1.1, 5.2: an ECDHE_ECDSA suite takes a
991                            // certificate with an ECDSA- or EdDSA-capable key.
992                            _ => matches!(
993                                algorithm.signature,
994                                crate::signature_hash_algorithm::SignatureAlgorithm::Ecdsa
995                                    | crate::signature_hash_algorithm::SignatureAlgorithm::Ed25519
996                            ),
997                        };
998                        signature_family_matches
999                            && algorithm
1000                                .crypto_scheme()
1001                                .is_ok_and(|scheme| signing_key.supports(scheme))
1002                    })
1003            });
1004            // A mixed config keeps its psk suites either way, so being left with only those
1005            // means the certificate can sign none of the suites offered alongside them.
1006            let only_psk_suites_left = local_cipher_suites.iter().all(|(_, is_psk)| *is_psk);
1007            if only_psk_suites_left {
1008                return Err(Error::ErrNoAvailableCipherSuites);
1009            }
1010        }
1011
1012        let local_cipher_suites: Vec<CipherSuiteId> =
1013            local_cipher_suites.into_iter().map(|(id, _)| id).collect();
1014
1015        // DTLS 1.3: its own suites (the configured ones of that family, or the defaults),
1016        // certificates only. Without a usable suite, group or signature scheme the highest
1017        // version is DTLS 1.2.
1018        let psk_only = self.psk.is_some() && (is_client || self.certificates.is_empty());
1019        let mut max_version = self.max_version;
1020        let mut local_tls13_cipher_suites = vec![];
1021        if max_version == DtlsVersion::Dtls1_3 && !psk_only {
1022            // A configured list is exact: without a TLS 1.3 suite in it there is no
1023            // DTLS 1.3.
1024            local_tls13_cipher_suites = if self.cipher_suites.is_empty() {
1025                crate::dtls13::suite::DEFAULT_SUITES.to_vec()
1026            } else {
1027                self.configured_suites(true)
1028            };
1029            local_tls13_cipher_suites.retain(|suite| suite.supported_by(crypto_provider.crypto()));
1030            let signs = local_signature_schemes.iter().any(|scheme| {
1031                scheme.is_tls13_signature()
1032                    && (is_client
1033                        || self
1034                            .certificates
1035                            .first()
1036                            .is_some_and(|c| scheme.is_compatible(&c.private_key)))
1037            });
1038            if local_tls13_cipher_suites.is_empty() || local_named_curves.is_empty() || !signs {
1039                local_tls13_cipher_suites.clear();
1040            }
1041        }
1042        if local_tls13_cipher_suites.is_empty() {
1043            if self.min_version == DtlsVersion::Dtls1_3 {
1044                return Err(Error::ErrNoAvailableCipherSuites);
1045            }
1046            max_version = DtlsVersion::Dtls1_2;
1047        }
1048        // The groups of DTLS 1.3: the hybrid with ML-KEM first where the provider has it
1049        // (and the configuration does not switch it off), then the curves.
1050        let mut local_tls13_groups = vec![];
1051        if self.post_quantum_key_share && hybrid_key_share_works(crypto_provider.crypto()) {
1052            local_tls13_groups.push(NamedCurve::X25519MlKem768);
1053        }
1054        local_tls13_groups.extend_from_slice(&local_named_curves);
1055
1056        // A list with TLS 1.3 suites only leaves nothing to negotiate DTLS 1.2 with.
1057        let min_version = if max_version == DtlsVersion::Dtls1_3
1058            && !self.cipher_suites.is_empty()
1059            && self.configured_suites(false).is_empty()
1060        {
1061            DtlsVersion::Dtls1_3
1062        } else {
1063            self.min_version
1064        };
1065
1066        let retransmit_interval = if self.flight_interval != Duration::from_secs(0) {
1067            self.flight_interval
1068        } else {
1069            INITIAL_TICKER_INTERVAL
1070        };
1071
1072        let maximum_transmission_unit = if self.mtu == 0 { DEFAULT_MTU } else { self.mtu };
1073        if self
1074            .alpn_protocols
1075            .iter()
1076            .any(|protocol| protocol.is_empty() || protocol.len() > 255)
1077        {
1078            return Err(Error::Other(
1079                "an ALPN protocol name is 1 to 255 bytes".to_owned(),
1080            ));
1081        }
1082        if self.connection_id.is_some_and(|length| length > 255) {
1083            return Err(Error::Other(
1084                "a connection id is at most 255 bytes".to_owned(),
1085            ));
1086        }
1087        if maximum_transmission_unit < MINIMUM_MTU {
1088            return Err(Error::Other(format!(
1089                "mtu {maximum_transmission_unit} is below the minimum of {MINIMUM_MTU}"
1090            )));
1091        }
1092        let maximum_retransmit_interval = self.maximum_flight_interval.max(retransmit_interval);
1093        if self.hello_verify_request_version != PROTOCOL_VERSION1_0
1094            && self.hello_verify_request_version != PROTOCOL_VERSION1_2
1095        {
1096            return Err(Error::ErrUnsupportedProtocolVersion);
1097        }
1098
1099        // `..Default::default()` used to supply this; when P7 replaced that with an explicit
1100        // field list it wrote `0`, which means *no retransmits are permitted at all*. The very
1101        // first firing of the retransmit timer then takes the handshake straight to `Errored`
1102        // (see `handshaker::handshake_timeout`), so a single reply arriving later than one
1103        // `retransmit_interval` kills the handshake instead of being retried.
1104        //
1105        // That is exactly what a loaded CI machine produces: under `-Cinstrument-coverage` on a
1106        // two-vCPU runner, a round trip between two in-process peers can easily exceed the 1 s
1107        // interval, and the connection dies with the misleading `ErrInvalidFsmTransition`.
1108        let maximum_retransmit_number = DEFAULT_MAXIMUM_RETRANSMIT_NUMBER;
1109
1110        let replay_protection_window = if self.replay_protection_window == 0 {
1111            DEFAULT_REPLAY_PROTECTION_WINDOW
1112        } else if self.replay_protection_window < MINIMUM_REPLAY_PROTECTION_WINDOW {
1113            warn!(
1114                "replay protection window {} raised to the minimum of {}",
1115                self.replay_protection_window, MINIMUM_REPLAY_PROTECTION_WINDOW
1116            );
1117            MINIMUM_REPLAY_PROTECTION_WINDOW
1118        } else {
1119            self.replay_protection_window
1120        };
1121
1122        let mut server_name = self.server_name.clone();
1123
1124        // A client given no server name takes the remote address's (an address is used to
1125        // verify the certificate and never sent as SNI, RFC 6066 section 3). A client that
1126        // verifies nothing by name (insecure_skip_verify, or a PSK) and has neither keeps no
1127        // name: it sends no server_name extension (the extension is a MAY, and its HostName
1128        // is "the fully qualified DNS hostname of the server, as understood by the client",
1129        // which this client does not know). A WebRTC peer connection is such a client: it
1130        // checks the certificate by its fingerprint. A client that verifies by name and has
1131        // neither has nothing to verify against and is refused (0.2.0 used "localhost").
1132        if is_client && server_name.is_empty() {
1133            if let Some(remote_addr) = remote_addr {
1134                server_name = remote_addr.ip().to_string();
1135            } else if !self.insecure_skip_verify && self.psk.is_none() {
1136                return Err(Error::Other(
1137                    "a client that verifies the server's certificate needs a server name \
1138                     (with_server_name) or a remote address"
1139                        .to_owned(),
1140                ));
1141            }
1142        }
1143
1144        let server_cert_verifier = if self.insecure_skip_verify {
1145            None
1146        } else if let Some(verifier) = self.server_cert_verifier.take() {
1147            Some(verifier)
1148        } else {
1149            let adapter = self.verifier_adapter.as_ref().ok_or_else(|| {
1150                Error::Crypto("CA-chain verification requires a RustlsVerifierAdapter".to_owned())
1151            })?;
1152            let roots = if self.roots_cas.is_empty() {
1153                gen_self_signed_root_cert()
1154            } else {
1155                self.roots_cas.clone()
1156            };
1157            Some(server_cert_verifier(Arc::new(roots), adapter)?)
1158        };
1159
1160        let client_cert_verifier = if self.client_auth as u8
1161            >= ClientAuthType::VerifyClientCertIfGiven as u8
1162        {
1163            let adapter = self.verifier_adapter.as_ref().ok_or_else(|| {
1164                Error::Crypto(
1165                    "client-certificate verification requires a RustlsVerifierAdapter".to_owned(),
1166                )
1167            })?;
1168            Some(
1169                rustls::server::WebPkiClientVerifier::builder_with_provider(
1170                    Arc::new(self.client_cas.clone()),
1171                    adapter.provider.clone(),
1172                )
1173                .build()
1174                .map_err(|err| Error::Other(format!("rustls client cert verifier: {err}")))?
1175                    as Arc<dyn ClientCertVerifier>,
1176            )
1177        } else {
1178            None
1179        };
1180
1181        // DTLS 1.3 pre-shared keys: a server's tickets, and the external PSKs (RFC 8446
1182        // section 4.2.11: an identity of at least one byte).
1183        let ticket_issuer = if is_client {
1184            None
1185        } else if let Some(shared) = self.session_ticket_issuer.take() {
1186            Some(shared.0)
1187        } else if self.session_tickets > 0 {
1188            Some(Arc::new(crate::dtls13::psk::TicketIssuer::new(
1189                crypto_provider.as_ref(),
1190                self.session_tickets,
1191                self.session_ticket_lifetime,
1192            )?))
1193        } else {
1194            None
1195        };
1196        let external_psks = std::mem::take(&mut self.external_psks);
1197        if external_psks.iter().any(|psk| {
1198            psk.identity.is_empty() || psk.identity.len() > 0xffff || psk.secret.is_empty()
1199        }) {
1200            return Err(Error::Other(
1201                "an external PSK has an identity of 1 to 65535 bytes and a secret".to_owned(),
1202            ));
1203        }
1204
1205        // Fields not derived from the builder come from `HandshakeConfig::new`, which also
1206        // supplies `crypto_provider`.
1207        Ok(HandshakeConfig {
1208            crypto_provider,
1209            local_psk_callback: self.psk.take(),
1210            local_psk_identity_hint: self.psk_identity_hint.take(),
1211            local_cipher_suites,
1212            local_named_curves,
1213            local_signature_schemes,
1214            extended_master_secret: self.extended_master_secret,
1215            local_srtp_protection_profiles: self.srtp_protection_profiles,
1216            use_srtp_optional: self.use_srtp_optional,
1217            alpn_protocols: self.alpn_protocols.clone(),
1218            use_srtp_required: self.use_srtp_required,
1219            server_name,
1220            client_auth: self.client_auth,
1221            bad_certificate_for_a_missing_client_certificate: self
1222                .bad_certificate_for_a_missing_client_certificate,
1223            local_certificates: self.certificates,
1224            name_to_certificate: Default::default(),
1225            insecure_skip_verify: self.insecure_skip_verify,
1226            insecure_verification: self.insecure_verification,
1227            verify_peer_certificate: self.verify_peer_certificate.take(),
1228            roots_cas: self.roots_cas,
1229            server_cert_verifier,
1230            client_cert_verifier,
1231            retransmit_interval,
1232            maximum_retransmit_interval,
1233            handshake_timeout: self.handshake_timeout,
1234            cookie_exchange: self.cookie_exchange,
1235            hello_verify_request_version: self.hello_verify_request_version,
1236            early_data_retransmit: self.early_data_retransmit,
1237            min_version,
1238            max_version,
1239            local_tls13_cipher_suites,
1240            local_tls13_groups,
1241            // The extension belongs to both versions (RFC 9146 for DTLS 1.2, RFC 9147
1242            // section 9 for 1.3). A hello carries it even when no connection id is asked for
1243            // (RFC 9147 section 5.1: so that the peer can ask for one), unless that is
1244            // switched off.
1245            connection_id: self.connection_id,
1246            connection_id_migration: self.connection_id_migration,
1247            invalid_record_limit: self.invalid_record_limit,
1248            ticket_issuer,
1249            session_store: if is_client {
1250                self.session_store.take()
1251            } else {
1252                None
1253            },
1254            session_cache: if is_client {
1255                None
1256            } else {
1257                self.session_cache.take()
1258            },
1259            session_lifetime: self
1260                .session_ticket_lifetime
1261                .min(crate::session::MAX_TICKET_LIFETIME),
1262            dtls12_resumption: self.dtls12_resumption,
1263            external_psks,
1264            psk_without_key_exchange: self.psk_without_key_exchange,
1265            post_handshake_auth: is_client && self.post_handshake_auth,
1266            max_early_data: if is_client { 0 } else { self.max_early_data },
1267            #[cfg(test)]
1268            psk_modes_for_test: None,
1269            initial_epoch: 0,
1270            maximum_transmission_unit,
1271            maximum_retransmit_number,
1272            replay_protection_window,
1273        })
1274    }
1275}
1276
1277/// A callback that decides whether a peer's certificate chain is acceptable.
1278///
1279/// WebRTC verifies the fingerprint from SDP instead of a CA chain, so this is where that check
1280/// goes.
1281pub type VerifyPeerCertificateFn =
1282    Arc<dyn (Fn(&[Vec<u8>], &[CertificateDer<'static>]) -> Result<()>) + Send + Sync>;
1283
1284/// Generates a self-signed certificate, as WebRTC endpoints use.
1285pub fn gen_self_signed_root_cert() -> rustls::RootCertStore {
1286    #[cfg(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
1287    {
1288        let mut certs = rustls::RootCertStore::empty();
1289        certs
1290            .add(
1291                rcgen::generate_simple_self_signed(vec![])
1292                    .unwrap()
1293                    .cert
1294                    .der()
1295                    .to_owned(),
1296            )
1297            .unwrap();
1298        certs
1299    }
1300    #[cfg(not(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs")))]
1301    {
1302        rustls::RootCertStore::empty()
1303    }
1304}
1305
1306#[derive(Clone)]
1307/// The resolved configuration a handshake runs with, produced by [`ConfigBuilder::build`].
1308pub struct HandshakeConfig {
1309    pub(crate) crypto_provider: Arc<dyn RTCCryptoProvider>,
1310    pub(crate) local_psk_callback: Option<PskCallback>,
1311    pub(crate) local_psk_identity_hint: Option<Vec<u8>>,
1312    pub(crate) local_cipher_suites: Vec<CipherSuiteId>, // Available CipherSuites
1313    pub(crate) local_named_curves: Vec<NamedCurve>,
1314    pub(crate) local_signature_schemes: Vec<SignatureHashAlgorithm>, // Available signature schemes
1315    pub(crate) extended_master_secret: ExtendedMasterSecretType, // Policy for the Extended Master Support extension
1316    pub(crate) local_srtp_protection_profiles: Vec<SrtpProtectionProfile>, // Available SRTPProtectionProfiles, if empty no SRTP support
1317    pub(crate) use_srtp_optional: bool, // A client goes on when the server leaves use_srtp out
1318    /// The ALPN protocols (RFC 7301), most preferred first; empty without ALPN.
1319    pub(crate) alpn_protocols: Vec<String>,
1320    pub(crate) use_srtp_required: bool, // A server refuses a client it shares no SRTP profile with
1321    pub(crate) server_name: String,
1322    pub(crate) client_auth: ClientAuthType, // If we are a client should we request a client certificate
1323    /// RFC 8122 section 6.2: bad_certificate for a missing required client certificate.
1324    pub(crate) bad_certificate_for_a_missing_client_certificate: bool,
1325    pub(crate) local_certificates: Vec<Certificate>,
1326    pub(crate) name_to_certificate: HashMap<String, Certificate>,
1327    pub(crate) insecure_skip_verify: bool,
1328    pub(crate) insecure_verification: bool,
1329    pub(crate) verify_peer_certificate: Option<VerifyPeerCertificateFn>,
1330    pub(crate) roots_cas: rustls::RootCertStore,
1331    pub(crate) server_cert_verifier: Option<Arc<dyn ServerCertVerifier>>,
1332    pub(crate) client_cert_verifier: Option<Arc<dyn ClientCertVerifier>>,
1333    pub(crate) retransmit_interval: Duration,
1334    pub(crate) maximum_retransmit_interval: Duration,
1335    pub(crate) handshake_timeout: Option<Duration>,
1336    pub(crate) cookie_exchange: bool,
1337    pub(crate) hello_verify_request_version: ProtocolVersion,
1338    pub(crate) early_data_retransmit: bool,
1339    /// The lowest version negotiated.
1340    pub(crate) min_version: DtlsVersion,
1341    /// The highest version negotiated: DTLS 1.3 only when there is something to negotiate it
1342    /// with (`local_tls13_cipher_suites`).
1343    pub(crate) max_version: DtlsVersion,
1344    /// The TLS 1.3 cipher suites, for DTLS 1.3. Empty when DTLS 1.3 is not negotiated.
1345    pub(crate) local_tls13_cipher_suites: Vec<CipherSuiteId>,
1346    /// The key exchange groups of DTLS 1.3, most preferred first: `local_named_curves`,
1347    /// with X25519MLKEM768 in front where the provider has it.
1348    pub(crate) local_tls13_groups: Vec<NamedCurve>,
1349    /// The length of the connection ids this side asks its peer to send, if it uses the
1350    /// connection_id extension at all.
1351    pub(crate) connection_id: Option<usize>,
1352    pub(crate) connection_id_migration: bool,
1353    pub(crate) invalid_record_limit: Option<u64>,
1354    /// DTLS 1.3 server: the tickets it issues and has accepted, if it issues any.
1355    pub(crate) ticket_issuer: Option<Arc<crate::dtls13::psk::TicketIssuer>>,
1356    /// Client: where it keeps tickets and DTLS 1.2 sessions, if it resumes.
1357    pub(crate) session_store: Option<Arc<dyn crate::session::SessionStore>>,
1358    /// DTLS 1.2 server: the sessions it resumes by session id, if it keeps any.
1359    pub(crate) session_cache: Option<Arc<dyn crate::session::SessionCache>>,
1360    /// How long a DTLS 1.2 session in `session_cache` may be resumed.
1361    pub(crate) session_lifetime: Duration,
1362    /// DTLS 1.2 sessions are resumed (`ConfigBuilder::with_dtls12_resumption`).
1363    pub(crate) dtls12_resumption: bool,
1364    pub(crate) external_psks: Vec<crate::session::ExternalPsk>,
1365    pub(crate) psk_without_key_exchange: bool,
1366    /// DTLS 1.3 client: it offers post-handshake authentication.
1367    pub(crate) post_handshake_auth: bool,
1368    /// DTLS 1.3 server: the most 0-RTT data it takes with a ticket.
1369    pub(crate) max_early_data: u32,
1370    /// The PSK key exchange modes a client offers, in place of the configured ones: for the
1371    /// tests of a peer that offers psk_ke alone.
1372    #[cfg(test)]
1373    pub(crate) psk_modes_for_test: Option<Vec<u8>>,
1374    pub(crate) initial_epoch: u16,
1375    pub(crate) maximum_transmission_unit: usize,
1376    pub(crate) maximum_retransmit_number: usize,
1377    pub(crate) replay_protection_window: usize,
1378}
1379
1380impl fmt::Debug for HandshakeConfig {
1381    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1382        fmt.debug_struct("HandshakeConfig<T>")
1383            .field("crypto_provider", &self.crypto_provider.name())
1384            .field("local_psk_identity_hint", &self.local_psk_identity_hint)
1385            .field("local_cipher_suites", &self.local_cipher_suites)
1386            .field("local_named_curves", &self.local_named_curves)
1387            .field("local_signature_schemes", &self.local_signature_schemes)
1388            .field("extended_master_secret", &self.extended_master_secret)
1389            .field(
1390                "local_srtp_protection_profiles",
1391                &self.local_srtp_protection_profiles,
1392            )
1393            .field("server_name", &self.server_name)
1394            .field("client_auth", &self.client_auth)
1395            .field("local_certificates", &self.local_certificates)
1396            .field("name_to_certificate", &self.name_to_certificate)
1397            .field("insecure_skip_verify", &self.insecure_skip_verify)
1398            .field("insecure_verification", &self.insecure_verification)
1399            .field("roots_cas", &self.roots_cas)
1400            .field("retransmit_interval", &self.retransmit_interval)
1401            .field("initial_epoch", &self.initial_epoch)
1402            .field("maximum_transmission_unit", &self.maximum_transmission_unit)
1403            .field("maximum_retransmit_number", &self.maximum_retransmit_number)
1404            .field("replay_protection_window", &self.replay_protection_window)
1405            .finish()
1406    }
1407}
1408
1409impl HandshakeConfig {
1410    /// Whether a missing required client certificate ends the handshake with
1411    /// `bad_certificate` (RFC 8122 section 6.2); see
1412    /// [`ConfigBuilder::with_bad_certificate_for_a_missing_client_certificate`].
1413    pub fn bad_certificate_for_a_missing_client_certificate(&self) -> bool {
1414        self.bad_certificate_for_a_missing_client_certificate
1415    }
1416
1417    pub(crate) fn new(crypto_provider: Arc<dyn RTCCryptoProvider>) -> Self {
1418        Self {
1419            crypto_provider,
1420            local_psk_callback: None,
1421            local_psk_identity_hint: None,
1422            local_cipher_suites: vec![],
1423            local_named_curves: vec![],
1424            local_signature_schemes: vec![],
1425            extended_master_secret: ExtendedMasterSecretType::Disable,
1426            local_srtp_protection_profiles: vec![],
1427            use_srtp_optional: false,
1428            alpn_protocols: vec![],
1429            use_srtp_required: false,
1430            server_name: String::new(),
1431            client_auth: ClientAuthType::NoClientCert,
1432            bad_certificate_for_a_missing_client_certificate: false,
1433            local_certificates: vec![],
1434            name_to_certificate: HashMap::new(),
1435            insecure_skip_verify: false,
1436            insecure_verification: false,
1437            verify_peer_certificate: None,
1438            roots_cas: rustls::RootCertStore::empty(),
1439            server_cert_verifier: default_verifier_adapter().and_then(|adapter| {
1440                server_cert_verifier(Arc::new(gen_self_signed_root_cert()), &adapter).ok()
1441            }),
1442            client_cert_verifier: None,
1443            retransmit_interval: std::time::Duration::from_secs(0),
1444            maximum_retransmit_interval: MAXIMUM_RETRANSMIT_INTERVAL,
1445            handshake_timeout: None,
1446            cookie_exchange: true,
1447            hello_verify_request_version: PROTOCOL_VERSION1_2,
1448            early_data_retransmit: true,
1449            min_version: DtlsVersion::Dtls1_2,
1450            max_version: DtlsVersion::Dtls1_2,
1451            local_tls13_cipher_suites: vec![],
1452            local_tls13_groups: vec![],
1453            connection_id: None,
1454            connection_id_migration: false,
1455            invalid_record_limit: None,
1456            ticket_issuer: None,
1457            session_store: None,
1458            session_cache: None,
1459            session_lifetime: crate::dtls13::psk::DEFAULT_TICKET_LIFETIME,
1460            dtls12_resumption: true,
1461            external_psks: vec![],
1462            psk_without_key_exchange: false,
1463            post_handshake_auth: false,
1464            max_early_data: 0,
1465            #[cfg(test)]
1466            psk_modes_for_test: None,
1467            initial_epoch: 0,
1468            maximum_transmission_unit: DEFAULT_MTU,
1469            maximum_retransmit_number: DEFAULT_MAXIMUM_RETRANSMIT_NUMBER,
1470            replay_protection_window: DEFAULT_REPLAY_PROTECTION_WINDOW,
1471        }
1472    }
1473
1474    /// This configuration with another initial value for the handshake retransmission
1475    /// timer: for a caller that learns the round trip time of the path after the
1476    /// configuration was built (ICE does), and sets the timer to 1.5 times it as RFC 9147
1477    /// section 5.8.2 asks. The maximum the timer doubles to is raised to it if need be.
1478    pub fn with_flight_interval(&self, flight_interval: std::time::Duration) -> Self {
1479        let mut config = self.clone();
1480        if !flight_interval.is_zero() {
1481            config.retransmit_interval = flight_interval;
1482            config.maximum_retransmit_interval =
1483                config.maximum_retransmit_interval.max(flight_interval);
1484        }
1485        config
1486    }
1487
1488    /// The initial value of the handshake retransmission timer.
1489    pub fn flight_interval(&self) -> std::time::Duration {
1490        self.retransmit_interval
1491    }
1492
1493    pub(crate) fn provider(&self) -> &Arc<dyn RTCCryptoProvider> {
1494        &self.crypto_provider
1495    }
1496
1497    /// Whether DTLS 1.3 is negotiated at all: the configuration allows it and has a DTLS 1.3
1498    /// cipher suite, group and signature scheme to run it with.
1499    pub fn supports_dtls13(&self) -> bool {
1500        self.max_version == DtlsVersion::Dtls1_3
1501    }
1502
1503    /// Whether DTLS 1.2 is negotiated at all.
1504    pub(crate) fn supports_dtls12(&self) -> bool {
1505        self.min_version == DtlsVersion::Dtls1_2
1506    }
1507
1508    /// A server's answer to a ClientHello's ALPN extension offering `offered` (RFC 7301
1509    /// section 3.2): `None` when this server uses no ALPN (the extension is ignored), the
1510    /// first of its protocols the client offered, or an error when there is none, which is
1511    /// a `no_application_protocol` alert.
1512    pub(crate) fn select_alpn(&self, offered: &[String]) -> Option<Result<String>> {
1513        if self.alpn_protocols.is_empty() {
1514            return None;
1515        }
1516        Some(
1517            self.alpn_protocols
1518                .iter()
1519                .find(|protocol| offered.contains(protocol))
1520                .cloned()
1521                .ok_or_else(|| {
1522                    Error::Other("no application protocol in common (RFC 7301)".to_owned())
1523                }),
1524        )
1525    }
1526
1527    /// The connection id a hello of this side carries, if it uses the extension: random
1528    /// bytes of the configured length, none for a length of zero.
1529    pub(crate) fn connection_id_offer(&self) -> Option<Vec<u8>> {
1530        let length = self.connection_id?;
1531        let mut connection_id = vec![0u8; length];
1532        self.crypto_provider
1533            .random()
1534            .fill(&mut connection_id)
1535            .ok()?;
1536        Some(connection_id)
1537    }
1538
1539    pub(crate) fn get_certificate(&self, server_name: &str) -> Result<Certificate> {
1540        if self.local_certificates.is_empty() {
1541            return Err(Error::ErrNoCertificates);
1542        }
1543
1544        if self.local_certificates.len() == 1 {
1545            // There's only one choice, so no point doing any work.
1546            return Ok(self.local_certificates[0].clone());
1547        }
1548
1549        if server_name.is_empty() {
1550            return Ok(self.local_certificates[0].clone());
1551        }
1552
1553        let lower = server_name.to_lowercase();
1554        let name = lower.trim_end_matches('.');
1555
1556        if let Some(cert) = self.name_to_certificate.get(name) {
1557            return Ok(cert.clone());
1558        }
1559
1560        // try replacing labels in the name with wildcards until we get a
1561        // match.
1562        let mut labels: Vec<&str> = name.split_terminator('.').collect();
1563        for i in 0..labels.len() {
1564            labels[i] = "*";
1565            let candidate = labels.join(".");
1566            if let Some(cert) = self.name_to_certificate.get(&candidate) {
1567                return Ok(cert.clone());
1568            }
1569        }
1570
1571        // If nothing matches, return the first certificate.
1572        Ok(self.local_certificates[0].clone())
1573    }
1574}
1575
1576/// Whether `crypto` can do both ends of the X25519MLKEM768 exchange: it says so, and one
1577/// exchange made at once with it (a client share, the server's answer by encapsulation, the
1578/// client's decapsulation) gives both sides the same secret. A provider that wraps another
1579/// and passes `supports` through while leaving `key_exchange_respond` at its Diffie-Hellman
1580/// default says yes and cannot answer a hybrid share; such a provider is not offered the
1581/// group, rather than failing every handshake that picks it.
1582fn hybrid_key_share_works(crypto: &dyn crypto::RTCCrypto) -> bool {
1583    let algorithm = crypto::KeyExchangeAlgorithm::X25519MlKem768;
1584    if !crypto.supports(crypto::CryptoAlgorithm::KeyExchange(algorithm)) {
1585        return false;
1586    }
1587    let Ok(client) = crypto.start_key_exchange(algorithm) else {
1588        return false;
1589    };
1590    let Ok((share, server_secret)) = crypto.key_exchange_respond(algorithm, client.public_key())
1591    else {
1592        return false;
1593    };
1594    client
1595        .complete(&share)
1596        .is_ok_and(|client_secret| client_secret.as_ref() == server_secret.as_ref())
1597}