rustls/server/config.rs
1use alloc::borrow::Cow;
2use alloc::vec::Vec;
3use core::fmt::Debug;
4use core::marker::PhantomData;
5
6#[cfg(feature = "webpki")]
7use pki_types::PrivateKeyDer;
8use pki_types::{DnsName, FipsStatus, UnixTime};
9
10use super::{ServerSessionKey, handy};
11use crate::builder::{ConfigBuilder, WantsVerifier};
12use crate::common_state::Protocol;
13#[cfg(doc)]
14use crate::crypto;
15use crate::crypto::kx::{NamedGroup, SupportedKxGroup};
16use crate::crypto::{
17 CipherSuite, CryptoProvider, SelectedCredential, SignatureScheme, TicketProducer,
18};
19#[cfg(feature = "webpki")]
20use crate::crypto::{Credentials, Identity, SingleCredential};
21use crate::enums::{ApplicationProtocol, CertificateType, ProtocolVersion};
22use crate::error::{Error, PeerMisbehaved};
23use crate::msgs::{ClientHelloPayload, ClientTicketRequest, ServerNamePayload};
24use crate::suites::Suite;
25use crate::sync::Arc;
26use crate::time_provider::{DefaultTimeProvider, TimeProvider};
27use crate::verify::{ClientVerifier, DistinguishedName, NoClientAuth};
28use crate::{KeyLog, NoKeyLog, Tls12CipherSuite, Tls13CipherSuite, compress};
29
30/// Common configuration for a set of server sessions.
31///
32/// Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots
33/// from the operating system to add to the [`RootCertStore`] passed to a `ClientVerifier`
34/// builder may take on the order of a few hundred milliseconds.
35///
36/// These must be created via the [`ServerConfig::builder()`] or [`ServerConfig::builder_with_details()`]
37/// function.
38///
39/// # Sharing resumption storage between `ServerConfig`s
40///
41/// In a program using many `ServerConfig`s it may improve resumption rates
42/// (which has a significant impact on connection performance) if those
43/// configs share [`ServerConfig::session_storage`] or [`ServerConfig::ticketer`].
44///
45/// However, caution is needed: other fields influence the security of a session
46/// and resumption between them can be surprising. If sharing
47/// [`ServerConfig::session_storage`] or [`ServerConfig::ticketer`] between two
48/// `ServerConfig`s, you should also evaluate the following fields and ensure
49/// they are equivalent:
50///
51/// * `ServerConfig::verifier` -- client authentication requirements,
52/// * [`ServerConfig::cert_resolver`] -- server identities.
53///
54/// To illustrate, imagine two `ServerConfig`s `A` and `B`. `A` requires
55/// client authentication, `B` does not. If `A` and `B` shared a resumption store,
56/// it would be possible for a session originated by `B` (that is, an unauthenticated client)
57/// to be inserted into the store, and then resumed by `A`. This would give a false
58/// impression to the user of `A` that the client was authenticated. This is possible
59/// whether the resumption is performed statefully (via [`ServerConfig::session_storage`])
60/// or statelessly (via [`ServerConfig::ticketer`]).
61///
62/// _Unlike_ `ClientConfig`, rustls does not enforce any policy here.
63///
64/// [`RootCertStore`]: crate::RootCertStore
65/// [`ServerSessionMemoryCache`]: crate::server::handy::ServerSessionMemoryCache
66#[derive(Clone, Debug)]
67pub struct ServerConfig {
68 /// Source of randomness and other crypto.
69 pub(crate) provider: Arc<CryptoProvider>,
70
71 /// How to select a cipher suite to use for a TLS session.
72 ///
73 /// The default is [`PreferClientOrder`].
74 pub cipher_suite_selector: &'static dyn CipherSuiteSelector,
75
76 /// How to select a key exchange group to use for a TLS connection.
77 ///
78 /// The default is [`PreferClientOrder`].
79 pub kx_selector: &'static dyn KeyExchangeSelector,
80
81 /// The maximum size of plaintext input to be emitted in a single TLS record.
82 /// A value of None is equivalent to the [TLS maximum] of 16 kB, and this is
83 /// the default.
84 ///
85 /// rustls enforces an arbitrary minimum of 32 bytes for this field.
86 /// Out of range values are reported as errors from [Connection::new].
87 ///
88 /// Setting this value to a little less than the TCP MSS may improve latency
89 /// for stream-y workloads.
90 ///
91 /// [TLS maximum]: https://datatracker.ietf.org/doc/html/rfc9846#section-5.1
92 /// [Connection::new]: crate::Connection::new
93 pub max_fragment_size: Option<usize>,
94
95 /// How to store client sessions.
96 ///
97 /// The default stores 256 sessions in memory.
98 ///
99 /// See [ServerConfig#sharing-resumption-storage-between-serverconfigs]
100 /// for a warning related to this field.
101 pub session_storage: Arc<dyn StoresServerSessions>,
102
103 /// How to produce tickets.
104 ///
105 /// The default is `None` which means ticket-based resumption in TLS1.2 and stateless resumption
106 /// in TLS1.3 are not available.
107 ///
108 /// See [ServerConfig#sharing-resumption-storage-between-serverconfigs]
109 /// for a warning related to this field.
110 pub ticketer: Option<Arc<dyn TicketProducer>>,
111
112 /// How to choose a server cert and key. This is usually set by
113 /// [ConfigBuilder::with_single_cert] or [ConfigBuilder::with_server_credential_resolver].
114 pub cert_resolver: Arc<dyn ServerCredentialResolver>,
115
116 /// Protocol names we support, most preferred first.
117 ///
118 /// If empty we don't do ALPN at all. This is the default.
119 pub alpn_protocols: Vec<ApplicationProtocol<'static>>,
120
121 /// How to verify client certificates.
122 pub(super) verifier: Arc<dyn ClientVerifier>,
123
124 /// How to output key material for debugging.
125 ///
126 /// The default does nothing and so key material is not logged.
127 ///
128 /// See [RFC 9850](https://datatracker.ietf.org/doc/html/rfc9850) for background.
129 pub key_log: Arc<dyn KeyLog>,
130
131 /// Allows traffic secrets to be extracted after the handshake,
132 /// e.g. for kTLS setup.
133 pub enable_secret_extraction: bool,
134
135 /// Amount of early data to accept for sessions created by
136 /// this config. Specify 0 to disable early data. The
137 /// default is 0.
138 ///
139 /// Read the early data via
140 /// [`MessageHandler::next_early_data()`][crate::conn::MessageHandler::next_early_data()].
141 ///
142 /// The units for this are _both_ plaintext bytes, _and_ ciphertext
143 /// bytes, depending on whether the server accepts a client's early_data
144 /// or not. It is therefore recommended to include some slop in
145 /// this value to account for the unknown amount of ciphertext
146 /// expansion in the latter case.
147 pub max_early_data_size: u32,
148
149 /// Whether the server should send "0.5RTT" data. This means the server
150 /// sends data after its first flight of handshake messages, without
151 /// waiting for the client to complete the handshake.
152 ///
153 /// This can improve TTFB latency for either server-speaks-first protocols,
154 /// or client-speaks-first protocols when paired with "0RTT" data. This
155 /// comes at the cost of a subtle weakening of the normal handshake
156 /// integrity guarantees that TLS provides. Note that the initial
157 /// `ClientHello` is indirectly authenticated because it is included
158 /// in the transcript used to derive the keys used to encrypt the data.
159 ///
160 /// This only applies to TLS1.3 connections. TLS1.2 connections cannot
161 /// do this optimisation and this setting is ignored for them. It is
162 /// also ignored for TLS1.3 connections that even attempt client
163 /// authentication.
164 ///
165 /// This defaults to false. This means the first application data
166 /// sent by the server comes after receiving and validating the client's
167 /// handshake up to the `Finished` message. This is the safest option.
168 pub send_half_rtt_data: bool,
169
170 /// How many TLS1.3 tickets to send immediately after a successful
171 /// handshake.
172 ///
173 /// Because TLS1.3 tickets are single-use, this allows
174 /// a client to perform multiple resumptions.
175 ///
176 /// The default means 2 tickets are sent, with a maximum of 2.
177 ///
178 /// See [`Tls13Tickets`] for the meaning of the default and maximum
179 /// counts.
180 pub send_tls13_tickets: Tls13Tickets,
181
182 /// If set to `true`, requires the client to support the extended
183 /// master secret extraction method defined in [RFC 7627].
184 ///
185 /// The default is `true` if the configured [`CryptoProvider`] is FIPS-compliant,
186 /// false otherwise.
187 ///
188 /// It must be set to `true` to meet FIPS requirement mentioned in section
189 /// **D.Q Transition of the TLS 1.2 KDF to Support the Extended Master
190 /// Secret** from [FIPS 140-3 IG.pdf].
191 ///
192 /// [RFC 7627]: https://datatracker.ietf.org/doc/html/rfc7627
193 /// [FIPS 140-3 IG.pdf]: https://csrc.nist.gov/csrc/media/Projects/cryptographic-module-validation-program/documents/fips%20140-3/FIPS%20140-3%20IG.pdf
194 pub require_ems: bool,
195
196 /// Provides the current system time
197 pub time_provider: Arc<dyn TimeProvider>,
198
199 /// How to compress the server's certificate chain.
200 ///
201 /// If a client supports this extension, and advertises support
202 /// for one of the compression algorithms included here, the
203 /// server certificate will be compressed according to [RFC 8879].
204 ///
205 /// This only applies to TLS1.3 connections. It is ignored for
206 /// TLS1.2 connections.
207 ///
208 /// The default depends on the crate features, see [`compress::default_cert_compressors()`].
209 ///
210 /// [RFC 8879]: https://datatracker.ietf.org/doc/rfc8879/
211 pub cert_compressors: Vec<&'static dyn compress::CertCompressor>,
212
213 /// Caching for compressed certificates.
214 ///
215 /// This is optional: [`compress::CompressionCache::Disabled`] gives
216 /// a cache that does no caching.
217 ///
218 /// The default caches the most recently used 4 compressions.
219 pub cert_compression_cache: Arc<compress::CompressionCache>,
220
221 /// How to decompress the clients's certificate chain.
222 ///
223 /// If this is non-empty, the [RFC 8879] certificate compression
224 /// extension is offered when requesting client authentication,
225 /// and any compressed certificates are transparently decompressed
226 /// during the handshake.
227 ///
228 /// This only applies to TLS1.3 connections. It is ignored for
229 /// TLS1.2 connections.
230 ///
231 /// The default depends on the crate features, see [`compress::default_cert_decompressors()`].
232 ///
233 /// [RFC 8879]: https://datatracker.ietf.org/doc/rfc8879/
234 pub cert_decompressors: Vec<&'static dyn compress::CertDecompressor>,
235
236 /// Policy for how an invalid Server Name Indication (SNI) value from a client is handled.
237 ///
238 /// The default rejects IP addresses in SNI extensions, which is mandated behaviour.
239 pub invalid_sni_policy: InvalidSniPolicy,
240}
241
242impl ServerConfig {
243 /// Create a builder for a server configuration with a specific [`CryptoProvider`].
244 ///
245 /// This will use the provider's configured ciphersuites. This implies which TLS
246 /// protocol versions are enabled.
247 ///
248 /// This function always succeeds. Any internal consistency problems with `provider`
249 /// are reported at the end of the builder process.
250 ///
251 /// For more information, see the [`ConfigBuilder`] documentation.
252 pub fn builder(provider: Arc<CryptoProvider>) -> ConfigBuilder<Self, WantsVerifier> {
253 Self::builder_with_details(provider, Arc::new(DefaultTimeProvider))
254 }
255
256 /// Create a builder for a server configuration with no default implementation details.
257 ///
258 /// This API must be used by `no_std` users.
259 ///
260 /// You must provide a specific [`TimeProvider`].
261 ///
262 /// You must provide a specific [`CryptoProvider`].
263 ///
264 /// This will use the provider's configured ciphersuites. This implies which TLS
265 /// protocol versions are enabled.
266 ///
267 /// This function always succeeds. Any internal consistency problems with `provider`
268 /// are reported at the end of the builder process.
269 ///
270 /// For more information, see the [`ConfigBuilder`] documentation.
271 pub fn builder_with_details(
272 provider: Arc<CryptoProvider>,
273 time_provider: Arc<dyn TimeProvider>,
274 ) -> ConfigBuilder<Self, WantsVerifier> {
275 ConfigBuilder {
276 state: WantsVerifier {
277 client_ech_mode: None,
278 },
279 provider,
280 time_provider,
281 side: PhantomData,
282 }
283 }
284
285 /// Return the FIPS validation status for connections made with this configuration.
286 ///
287 /// This is different from [`CryptoProvider::fips()`]: [`CryptoProvider::fips()`]
288 /// is concerned only with cryptography, whereas this _also_ covers TLS-level
289 /// configuration that NIST recommends.
290 pub fn fips(&self) -> FipsStatus {
291 match self.require_ems {
292 true => self.provider.fips(),
293 false => FipsStatus::Unvalidated,
294 }
295 }
296
297 /// Return the crypto provider used to construct this server configuration.
298 pub fn provider(&self) -> &Arc<CryptoProvider> {
299 &self.provider
300 }
301
302 pub(crate) fn supports_version(&self, v: ProtocolVersion, protocol: Protocol) -> bool {
303 self.provider.supports_version(v) && protocol.supports_version(v)
304 }
305
306 pub(super) fn current_time(&self) -> Result<UnixTime, Error> {
307 self.time_provider
308 .current_time()
309 .ok_or(Error::FailedToGetCurrentTime)
310 }
311}
312
313/// How many TLS 1.3 session tickets the server sends after a handshake.
314#[expect(clippy::exhaustive_structs)]
315#[derive(Clone, Copy, Debug)]
316pub struct Tls13Tickets {
317 /// Tickets sent when the client does not request a specific number.
318 pub default: usize,
319
320 /// Upper bound on the number of tickets sent.
321 pub max: usize,
322}
323
324impl Tls13Tickets {
325 pub(super) fn resolve(&self, requested: Option<&ClientTicketRequest>, resuming: bool) -> usize {
326 let Some(req) = requested else {
327 return self.default;
328 };
329
330 Ord::min(
331 usize::from(match resuming {
332 true => req.resumption_count,
333 false => req.new_session_count,
334 }),
335 self.max,
336 )
337 }
338}
339
340impl Default for Tls13Tickets {
341 fn default() -> Self {
342 Self { default: 2, max: 2 }
343 }
344}
345
346/// A trait for the ability to store server session data.
347///
348/// The keys and values are opaque.
349///
350/// Inserted keys are randomly chosen by the library and have
351/// no internal structure (in other words, you may rely on all
352/// bits being uniformly random). Queried keys are untrusted data.
353///
354/// Both the keys and values should be treated as
355/// **highly sensitive data**, containing enough key material
356/// to break all security of the corresponding sessions.
357///
358/// Implementations can be lossy (in other words, forgetting
359/// key/value pairs) without any negative security consequences.
360///
361/// However, note that `take` **must** reliably delete a returned
362/// value. If it does not, there may be security consequences.
363///
364/// `put` and `take` are mutating operations; this isn't expressed
365/// in the type system to allow implementations freedom in
366/// how to achieve interior mutability. `Mutex` is a common
367/// choice.
368pub trait StoresServerSessions: Debug + Send + Sync {
369 /// Store session secrets encoded in `value` against `key`,
370 /// overwrites any existing value against `key`. Returns `true`
371 /// if the value was stored.
372 fn put(&self, key: ServerSessionKey<'_>, value: Vec<u8>) -> bool;
373
374 /// Find a value with the given `key`. Return it, or None
375 /// if it doesn't exist.
376 fn get(&self, key: ServerSessionKey<'_>) -> Option<Vec<u8>>;
377
378 /// Find a value with the given `key`. Return it and delete it;
379 /// or None if it doesn't exist.
380 fn take(&self, key: ServerSessionKey<'_>) -> Option<Vec<u8>>;
381
382 /// Whether the store can cache another session. This is used to indicate to clients
383 /// whether their session can be resumed; the implementation is not required to remember
384 /// a session even if it returns `true` here.
385 fn can_cache(&self) -> bool;
386}
387
388/// How to choose a certificate chain and signing key for use
389/// in server authentication.
390///
391/// This is suitable when selecting a certificate does not require
392/// I/O or when the application is using blocking I/O anyhow.
393pub trait ServerCredentialResolver: Debug + Send + Sync {
394 /// Choose a certificate chain and matching key given simplified ClientHello information.
395 ///
396 /// The `SelectedCredential` returned from this method contains an identity and a
397 /// one-time-use [`Signer`] wrapping the private key. This is usually obtained via a
398 /// [`Credentials`], on which an implementation can call [`Credentials::signer()`].
399 /// An implementation can either store long-lived [`Credentials`] values, or instantiate
400 /// them as needed using one of its constructors.
401 ///
402 /// Yielding an `Error` will abort the handshake. Some relevant error variants:
403 ///
404 /// * [`PeerIncompatible::NoSignatureSchemesInCommon`]
405 /// * [`PeerIncompatible::NoServerNameProvided`]
406 /// * [`Error::NoSuitableCertificate`]
407 ///
408 /// [`Credentials`]: crate::crypto::Credentials
409 /// [`Credentials::signer()`]: crate::crypto::Credentials::signer
410 /// [`Signer`]: crate::crypto::Signer
411 /// [`PeerIncompatible::NoSignatureSchemesInCommon`]: crate::error::PeerIncompatible::NoSignatureSchemesInCommon
412 /// [`PeerIncompatible::NoServerNameProvided`]: crate::error::PeerIncompatible::NoServerNameProvided
413 fn resolve(&self, client_hello: &ClientHello<'_>) -> Result<SelectedCredential, Error>;
414
415 /// Returns which [`CertificateType`]s this resolver supports.
416 ///
417 /// Returning an empty slice will result in an error. The default implementation signals
418 /// support for X.509 certificates. Implementations should return the same value every time.
419 ///
420 /// See [RFC 7250](https://tools.ietf.org/html/rfc7250) for more information.
421 fn supported_certificate_types(&self) -> &'static [CertificateType] {
422 &[CertificateType::X509]
423 }
424}
425
426/// A struct representing the received Client Hello
427#[derive(Debug)]
428pub struct ClientHello<'a> {
429 pub(super) server_name: Option<Cow<'a, DnsName<'a>>>,
430 pub(super) signature_schemes: &'a [SignatureScheme],
431 pub(super) alpn: Option<&'a Vec<ApplicationProtocol<'a>>>,
432 pub(super) server_cert_types: Option<&'a [CertificateType]>,
433 pub(super) client_cert_types: Option<&'a [CertificateType]>,
434 pub(super) cipher_suites: &'a [CipherSuite],
435 /// The [certificate_authorities] extension, if it was sent by the client.
436 ///
437 /// [certificate_authorities]: https://datatracker.ietf.org/doc/html/rfc9846#section-4.3.4
438 pub(super) certificate_authorities: Option<&'a [DistinguishedName]>,
439 pub(super) named_groups: Option<&'a [NamedGroup]>,
440}
441
442impl<'a> ClientHello<'a> {
443 #[cfg(test)]
444 pub(super) fn empty() -> Self {
445 Self {
446 server_name: None,
447 signature_schemes: &[],
448 alpn: None,
449 server_cert_types: None,
450 client_cert_types: None,
451 cipher_suites: &[],
452 certificate_authorities: None,
453 named_groups: None,
454 }
455 }
456
457 pub(super) fn new(
458 payload: &'a ClientHelloPayload,
459 signature_schemes: Option<&'a [SignatureScheme]>,
460 server_name: Option<Cow<'a, DnsName<'a>>>,
461 version: Option<ProtocolVersion>,
462 ) -> Self {
463 Self {
464 server_name,
465 signature_schemes: signature_schemes.unwrap_or_else(|| {
466 payload
467 .signature_schemes
468 .as_deref()
469 .unwrap_or_default()
470 }),
471 alpn: payload.protocols.as_ref(),
472 server_cert_types: payload
473 .server_certificate_types
474 .as_deref(),
475 client_cert_types: payload
476 .client_certificate_types
477 .as_deref(),
478 cipher_suites: &payload.cipher_suites,
479 // We adhere to the TLS 1.2 RFC by not exposing this to the cert resolver if TLS version is 1.2
480 certificate_authorities: match version {
481 Some(ProtocolVersion::TLSv1_2) => None,
482 _ => payload
483 .certificate_authority_names
484 .as_deref(),
485 },
486 named_groups: payload.named_groups.as_deref(),
487 }
488 }
489
490 /// Get the server name indicator.
491 ///
492 /// Returns `None` if the client did not supply a SNI.
493 pub fn server_name(&self) -> Option<&DnsName<'_>> {
494 self.server_name.as_deref()
495 }
496
497 /// Get the compatible signature schemes.
498 ///
499 /// Returns standard-specified default if the client omitted this extension.
500 pub fn signature_schemes(&self) -> &[SignatureScheme] {
501 self.signature_schemes
502 }
503
504 /// Get the ALPN protocol identifiers submitted by the client.
505 ///
506 /// Returns `None` if the client did not include an ALPN extension.
507 ///
508 /// Application Layer Protocol Negotiation (ALPN) is a TLS extension that lets a client
509 /// submit a set of identifiers that each a represent an application-layer protocol.
510 /// The server will then pick its preferred protocol from the set submitted by the client.
511 /// Each identifier is represented as a byte array, although common values are often ASCII-encoded.
512 /// See the official RFC-7301 specifications at <https://datatracker.ietf.org/doc/html/rfc7301>
513 /// for more information on ALPN.
514 ///
515 /// For example, a HTTP client might specify "http/1.1" and/or "h2". Other well-known values
516 /// are listed in the at IANA registry at
517 /// <https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids>.
518 ///
519 /// The server can specify supported ALPN protocols by setting [`ServerConfig::alpn_protocols`].
520 /// During the handshake, the server will select the first protocol configured that the client supports.
521 pub fn alpn(&self) -> Option<impl Iterator<Item = &'a [u8]> + use<'a>> {
522 self.alpn.map(|protocols| {
523 protocols
524 .iter()
525 .map(|proto| proto.as_ref())
526 })
527 }
528
529 /// Get cipher suites.
530 pub fn cipher_suites(&self) -> &[CipherSuite] {
531 self.cipher_suites
532 }
533
534 /// Get the server certificate types offered in the ClientHello.
535 ///
536 /// Returns `None` if the client did not include a certificate type extension.
537 pub fn server_cert_types(&self) -> Option<&'a [CertificateType]> {
538 self.server_cert_types
539 }
540
541 /// Get the client certificate types offered in the ClientHello.
542 ///
543 /// Returns `None` if the client did not include a certificate type extension.
544 pub fn client_cert_types(&self) -> Option<&'a [CertificateType]> {
545 self.client_cert_types
546 }
547
548 /// Get the [certificate_authorities] extension sent by the client.
549 ///
550 /// Returns `None` if the client did not send this extension.
551 ///
552 /// [certificate_authorities]: https://datatracker.ietf.org/doc/html/rfc9846#section-4.3.4
553 pub fn certificate_authorities(&self) -> Option<&'a [DistinguishedName]> {
554 self.certificate_authorities
555 }
556
557 /// Get the [`named_groups`] extension sent by the client.
558 ///
559 /// This means different things in different versions of TLS:
560 ///
561 /// Originally it was introduced as the "[`elliptic_curves`]" extension for TLS1.2.
562 /// It described the elliptic curves supported by a client for all purposes: key
563 /// exchange, signature verification (for server authentication), and signing (for
564 /// client auth). Later [RFC 7919] extended this to include FFDHE "named groups",
565 /// but FFDHE groups in this context only relate to key exchange.
566 ///
567 /// In TLS1.3 it was renamed to "[`named_groups`]" and now describes all types
568 /// of key exchange mechanisms, and does not relate at all to elliptic curves
569 /// used for signatures.
570 ///
571 /// [`elliptic_curves`]: https://datatracker.ietf.org/doc/html/rfc4492#section-5.1.1
572 /// [RFC 7919]: https://datatracker.ietf.org/doc/html/rfc7919#section-2
573 /// [`named_groups`]:https://datatracker.ietf.org/doc/html/rfc9846#section-4.3.7
574 pub fn named_groups(&self) -> Option<&'a [NamedGroup]> {
575 self.named_groups
576 }
577}
578
579/// A policy describing how an invalid Server Name Indication (SNI) value from a client is handled by the server.
580///
581/// The only valid form of SNI according to relevant RFCs ([RFC 6066], [RFC 1035]) is
582/// non-IP-address host name, however some misconfigured clients may send a bare IP address, or
583/// another invalid value. Some servers may wish to ignore these invalid values instead of producing
584/// an error.
585///
586/// By default, Rustls will ignore invalid values that are an IP address (the most common misconfiguration)
587/// and error for all other invalid values.
588///
589/// When an SNI value is ignored, Rustls treats the client as if it sent no SNI at all.
590///
591/// [RFC 1035]: https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1
592/// [RFC 6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
593#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
594#[non_exhaustive]
595pub enum InvalidSniPolicy {
596 /// Reject all ClientHello messages that contain an invalid SNI value.
597 RejectAll,
598 /// Ignore an invalid SNI value in ClientHello messages if the value is an IP address.
599 ///
600 /// "Ignoring SNI" means accepting the ClientHello message, but acting as if the client sent no SNI.
601 #[default]
602 IgnoreIpAddresses,
603 /// Ignore all invalid SNI in ClientHello messages.
604 ///
605 /// "Ignoring SNI" means accepting the ClientHello message, but acting as if the client sent no SNI.
606 IgnoreAll,
607}
608
609impl InvalidSniPolicy {
610 /// Returns the valid SNI value, or ignores the invalid SNI value if allowed by this policy; otherwise returns
611 /// an error.
612 pub(super) fn accept(
613 &self,
614 payload: Option<&ServerNamePayload<'_>>,
615 ) -> Result<Option<DnsName<'static>>, Error> {
616 let Some(payload) = payload else {
617 return Ok(None);
618 };
619 if let Some(server_name) = payload.to_dns_name_normalized() {
620 return Ok(Some(server_name));
621 }
622 match (self, payload) {
623 (Self::IgnoreAll, _) => Ok(None),
624 (Self::IgnoreIpAddresses, ServerNamePayload::IpAddress) => Ok(None),
625 _ => Err(Error::PeerMisbehaved(
626 PeerMisbehaved::ServerNameMustContainOneHostName,
627 )),
628 }
629 }
630}
631
632impl ConfigBuilder<ServerConfig, WantsVerifier> {
633 /// Choose how to verify client certificates.
634 pub fn with_client_cert_verifier(
635 self,
636 client_cert_verifier: Arc<dyn ClientVerifier>,
637 ) -> ConfigBuilder<ServerConfig, WantsServerCert> {
638 ConfigBuilder {
639 state: WantsServerCert {
640 verifier: client_cert_verifier,
641 },
642 provider: self.provider,
643 time_provider: self.time_provider,
644 side: PhantomData,
645 }
646 }
647
648 /// Disable client authentication.
649 pub fn with_no_client_auth(self) -> ConfigBuilder<ServerConfig, WantsServerCert> {
650 self.with_client_cert_verifier(Arc::new(NoClientAuth))
651 }
652}
653
654/// A config builder state where the caller must supply how to provide a server certificate to
655/// the connecting peer.
656///
657/// For more information, see the [`ConfigBuilder`] documentation.
658#[derive(Clone, Debug)]
659pub struct WantsServerCert {
660 verifier: Arc<dyn ClientVerifier>,
661}
662
663impl ConfigBuilder<ServerConfig, WantsServerCert> {
664 /// Sets a single [`Identity`] and matching private key.
665 ///
666 /// This identity and key is used for all subsequent connections, irrespective of
667 /// things like SNI hostname.
668 ///
669 /// Note that the end-entity certificate must have the
670 /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
671 /// extension to describe, e.g., the valid DNS name. The `commonName` field is
672 /// disregarded.
673 ///
674 /// - `identity` is the [`Identity`], typically containing a certificate chain.
675 /// - `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. Supported key
676 /// formats and types depends on the configured provider.
677 ///
678 /// This function fails if `key_der` is invalid, or if the `SubjectPublicKeyInfo` from
679 /// the private key does not match the public key from the `identity`.
680 #[cfg(feature = "webpki")]
681 pub fn with_single_cert(
682 self,
683 identity: Arc<Identity<'static>>,
684 key_der: PrivateKeyDer<'static>,
685 ) -> Result<ServerConfig, Error> {
686 let credentials = Credentials::from_der(identity, key_der, self.provider())?;
687 self.with_server_credential_resolver(Arc::new(SingleCredential::from(credentials)))
688 }
689
690 /// Sets a single [`Identity`], matching private key, and stapled OCSP response.
691 ///
692 /// This identity and key is used for all subsequent connections, irrespective of
693 /// things like SNI hostname.
694 ///
695 /// Note that the end-entity certificate must have the
696 /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
697 /// extension to describe, e.g., the valid DNS name. The `commonName` field is
698 /// disregarded.
699 ///
700 /// - `identity` is the [`Identity`], typically containing a certificate chain.
701 /// - `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. Supported key
702 /// formats and types depends on the configured provider.
703 /// - `ocsp` is a DER-encoded OCSP response. It is ignored if zero length but it is
704 /// not validated otherwise.
705 ///
706 /// This function fails if `key_der` is invalid, or if the `SubjectPublicKeyInfo` from
707 /// the private key does not match the public key from the `identity`.
708 #[cfg(feature = "webpki")]
709 pub fn with_single_cert_with_ocsp(
710 self,
711 identity: Arc<Identity<'static>>,
712 key_der: PrivateKeyDer<'static>,
713 ocsp: Arc<[u8]>,
714 ) -> Result<ServerConfig, Error> {
715 let mut credentials = Credentials::from_der(identity, key_der, self.provider())?;
716 if !ocsp.is_empty() {
717 credentials.ocsp = Some(ocsp);
718 }
719 self.with_server_credential_resolver(Arc::new(SingleCredential::from(credentials)))
720 }
721
722 /// Sets a custom [`ServerCredentialResolver`].
723 pub fn with_server_credential_resolver(
724 self,
725 cert_resolver: Arc<dyn ServerCredentialResolver>,
726 ) -> Result<ServerConfig, Error> {
727 self.provider.consistency_check()?;
728 let require_ems = !matches!(self.provider.fips(), FipsStatus::Unvalidated);
729 Ok(ServerConfig {
730 provider: self.provider,
731 cipher_suite_selector: &PreferClientOrder,
732 kx_selector: &PreferClientOrder,
733 max_fragment_size: None,
734 session_storage: handy::ServerSessionMemoryCache::new(256),
735 ticketer: None,
736 cert_resolver,
737 alpn_protocols: Vec::new(),
738 verifier: self.state.verifier,
739 key_log: Arc::new(NoKeyLog {}),
740 enable_secret_extraction: false,
741 max_early_data_size: 0,
742 send_half_rtt_data: false,
743 send_tls13_tickets: Tls13Tickets::default(),
744 require_ems,
745 time_provider: self.time_provider,
746 cert_compressors: compress::default_cert_compressors().to_vec(),
747 cert_compression_cache: Arc::new(compress::CompressionCache::default()),
748 cert_decompressors: compress::default_cert_decompressors().to_vec(),
749 invalid_sni_policy: InvalidSniPolicy::default(),
750 })
751 }
752}
753
754/// A [`KeyExchangeSelector`]/[`CipherSuiteSelector`] implementation that prioritizes client order.
755#[expect(clippy::exhaustive_structs)]
756#[derive(Debug)]
757pub struct PreferClientOrder;
758
759impl KeyExchangeSelector for PreferClientOrder {
760 fn select_key_exchange(
761 &self,
762 client: &mut dyn Iterator<Item = OfferedKxGroup>,
763 _server: &[&'static dyn SupportedKxGroup],
764 ) -> Option<&'static dyn SupportedKxGroup> {
765 client.next().map(|c| c.group)
766 }
767}
768
769impl CipherSuiteSelector for PreferClientOrder {
770 fn select_tls12_cipher_suite(
771 &self,
772 client: &mut dyn Iterator<Item = &'static Tls12CipherSuite>,
773 server: &[&'static Tls12CipherSuite],
774 ) -> Option<&'static Tls12CipherSuite> {
775 self.select(client, server)
776 }
777
778 fn select_tls13_cipher_suite(
779 &self,
780 client: &mut dyn Iterator<Item = &'static Tls13CipherSuite>,
781 server: &[&'static Tls13CipherSuite],
782 ) -> Option<&'static Tls13CipherSuite> {
783 self.select(client, server)
784 }
785}
786
787impl PreferClientOrder {
788 fn select<T: Suite>(
789 &self,
790 client: &mut dyn Iterator<Item = &'static T>,
791 _server: &[&'static T],
792 ) -> Option<&'static T> {
793 client.next()
794 }
795}
796
797/// A [`KeyExchangeSelector`]/[`CipherSuiteSelector`] implementation that prioritizes server order.
798#[expect(clippy::exhaustive_structs)]
799#[derive(Debug)]
800pub struct PreferServerOrder;
801
802impl KeyExchangeSelector for PreferServerOrder {
803 fn select_key_exchange(
804 &self,
805 client: &mut dyn Iterator<Item = OfferedKxGroup>,
806 server: &[&'static dyn SupportedKxGroup],
807 ) -> Option<&'static dyn SupportedKxGroup> {
808 client
809 .filter_map(|offered| {
810 server
811 .iter()
812 .position(|ss| ss.name() == offered.group.name())
813 .map(|pos| (pos, offered.group))
814 })
815 .min_by_key(|&(pos, _)| pos)
816 .map(|(_, group)| group)
817 }
818}
819
820impl CipherSuiteSelector for PreferServerOrder {
821 fn select_tls12_cipher_suite(
822 &self,
823 client: &mut dyn Iterator<Item = &'static Tls12CipherSuite>,
824 server: &[&'static Tls12CipherSuite],
825 ) -> Option<&'static Tls12CipherSuite> {
826 client
827 .filter_map(|cs| {
828 server
829 .iter()
830 .position(|&ss| ss == cs)
831 .map(|pos| (pos, cs))
832 })
833 .min_by_key(|&(pos, _)| pos)
834 .map(|(_, cs)| cs)
835 }
836
837 fn select_tls13_cipher_suite(
838 &self,
839 client: &mut dyn Iterator<Item = &'static Tls13CipherSuite>,
840 server: &[&'static Tls13CipherSuite],
841 ) -> Option<&'static Tls13CipherSuite> {
842 client
843 .filter_map(|cs| {
844 server
845 .iter()
846 .position(|&ss| ss == cs)
847 .map(|pos| (pos, cs))
848 })
849 .min_by_key(|&(pos, _)| pos)
850 .map(|(_, cs)| cs)
851 }
852}
853
854impl<T: CipherSuiteSelector + ?Sized> VersionSuiteSelector<Tls12CipherSuite> for T {
855 fn select(
856 &self,
857 client: &mut dyn Iterator<Item = &'static Tls12CipherSuite>,
858 server: &[&'static Tls12CipherSuite],
859 ) -> Option<&'static Tls12CipherSuite> {
860 self.select_tls12_cipher_suite(client, server)
861 }
862}
863
864impl<T: CipherSuiteSelector + ?Sized> VersionSuiteSelector<Tls13CipherSuite> for T {
865 fn select(
866 &self,
867 client: &mut dyn Iterator<Item = &'static Tls13CipherSuite>,
868 server: &[&'static Tls13CipherSuite],
869 ) -> Option<&'static Tls13CipherSuite> {
870 self.select_tls13_cipher_suite(client, server)
871 }
872}
873
874pub(super) trait VersionSuiteSelector<T> {
875 fn select(
876 &self,
877 client: &mut dyn Iterator<Item = &'static T>,
878 server: &[&'static T],
879 ) -> Option<&'static T>;
880}
881
882/// A filter that chooses the cipher suite to use for a TLS session.
883pub trait CipherSuiteSelector: Debug + Send + Sync {
884 /// Choose a cipher suite, given the client's and server's options, in preference order.
885 ///
886 /// The `client` list is generated in order from the [`CipherSuite`] values received in the
887 /// `ClientHello`, filtered to only contain suites that the server supports. The `server`
888 /// list comes from the [`ServerConfig`]'s [`CryptoProvider`].
889 ///
890 /// Yields the chosen cipher suite supported by both sides, or `None` to indicate that no
891 /// mutually supported cipher suite could be agreed on.
892 fn select_tls12_cipher_suite(
893 &self,
894 client: &mut dyn Iterator<Item = &'static Tls12CipherSuite>,
895 server: &[&'static Tls12CipherSuite],
896 ) -> Option<&'static Tls12CipherSuite>;
897
898 /// Choose a cipher suite, given the client's and server's options, in preference order.
899 ///
900 /// The `client` list is generated in order from the [`CipherSuite`] values received in the
901 /// `ClientHello`, filtered to only contain suites that the server supports. The `server`
902 /// list comes from the [`ServerConfig`]'s [`CryptoProvider`].
903 ///
904 /// Yields the chosen cipher suite supported by both sides, or `None` to indicate that no
905 /// mutually supported cipher suite could be agreed on.
906 fn select_tls13_cipher_suite(
907 &self,
908 client: &mut dyn Iterator<Item = &'static Tls13CipherSuite>,
909 server: &[&'static Tls13CipherSuite],
910 ) -> Option<&'static Tls13CipherSuite>;
911}
912
913/// Chooses the key exchange group for a TLS connection.
914pub trait KeyExchangeSelector: Debug + Send + Sync {
915 /// Choose a key exchange group, given the client's and server's options.
916 ///
917 /// `client` holds the groups from the client's `supported_groups` extension, in the
918 /// client's order, filtered to those the server supports and that suit the protocol
919 /// version and the selected cipher suite. `server` is the [`CryptoProvider`]'s
920 /// `kx_groups`, in preference order.
921 ///
922 /// If the chosen group has no key share (see [`OfferedKxGroup::has_key_share`]),
923 /// a TLS 1.3 server sends a HelloRetryRequest for it.
924 ///
925 /// Returns `None` if no acceptable group is offered. The result must come from
926 /// `client`.
927 fn select_key_exchange(
928 &self,
929 client: &mut dyn Iterator<Item = OfferedKxGroup>,
930 server: &[&'static dyn SupportedKxGroup],
931 ) -> Option<&'static dyn SupportedKxGroup>;
932}
933
934/// A key exchange group offered by the client.
935#[non_exhaustive]
936#[derive(Clone, Copy, Debug)]
937pub struct OfferedKxGroup {
938 /// The group, as implemented by the server's provider.
939 pub group: &'static dyn SupportedKxGroup,
940
941 /// Whether the client sent a key share for this group.
942 ///
943 /// Always `false` for TLS 1.2.
944 pub has_key_share: bool,
945}
946
947impl OfferedKxGroup {
948 /// Creates a new [`OfferedKxGroup`]
949 pub const fn new(group: &'static dyn SupportedKxGroup, has_key_share: bool) -> Self {
950 Self {
951 group,
952 has_key_share,
953 }
954 }
955}