rustls/server/config.rs
1use alloc::borrow::Cow;
2use alloc::vec::Vec;
3use core::fmt::Debug;
4use core::marker::PhantomData;
5
6use pki_types::{DnsName, PrivateKeyDer, UnixTime};
7
8use super::handy;
9use super::hs::ClientHelloInput;
10use crate::builder::{ConfigBuilder, WantsVerifier};
11#[cfg(doc)]
12use crate::crypto;
13use crate::crypto::kx::NamedGroup;
14use crate::crypto::{
15 CipherSuite, Credentials, CryptoProvider, Identity, SelectedCredential, SignatureScheme,
16 SingleCredential, TicketProducer,
17};
18use crate::enums::{CertificateType, ProtocolVersion};
19use crate::error::{Error, PeerMisbehaved};
20use crate::msgs::handshake::{ProtocolName, ServerNamePayload};
21use crate::sync::Arc;
22#[cfg(feature = "std")]
23use crate::time_provider::DefaultTimeProvider;
24use crate::time_provider::TimeProvider;
25use crate::verify::{ClientVerifier, DistinguishedName, NoClientAuth};
26use crate::{KeyLog, NoKeyLog, compress};
27
28/// Common configuration for a set of server sessions.
29///
30/// Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots
31/// from the operating system to add to the [`RootCertStore`] passed to a `ClientVerifier`
32/// builder may take on the order of a few hundred milliseconds.
33///
34/// These must be created via the [`ServerConfig::builder()`] or [`ServerConfig::builder()`]
35/// function.
36///
37/// # Defaults
38///
39/// * [`ServerConfig::max_fragment_size`]: the default is `None` (meaning 16kB).
40/// * [`ServerConfig::session_storage`]: if the `std` feature is enabled, the default stores 256
41/// sessions in memory. If the `std` feature is not enabled, the default is to not store any
42/// sessions. In a no-std context, by enabling the `hashbrown` feature you may provide your
43/// own `session_storage` using [`ServerSessionMemoryCache`] and a `crate::lock::MakeMutex`
44/// implementation.
45/// * [`ServerConfig::alpn_protocols`]: the default is empty -- no ALPN protocol is negotiated.
46/// * [`ServerConfig::key_log`]: key material is not logged.
47/// * [`ServerConfig::send_tls13_tickets`]: 2 tickets are sent.
48/// * [`ServerConfig::cert_compressors`]: depends on the crate features, see [`compress::default_cert_compressors()`].
49/// * [`ServerConfig::cert_compression_cache`]: caches the most recently used 4 compressions
50/// * [`ServerConfig::cert_decompressors`]: depends on the crate features, see [`compress::default_cert_decompressors()`].
51///
52/// # Sharing resumption storage between `ServerConfig`s
53///
54/// In a program using many `ServerConfig`s it may improve resumption rates
55/// (which has a significant impact on connection performance) if those
56/// configs share [`ServerConfig::session_storage`] or [`ServerConfig::ticketer`].
57///
58/// However, caution is needed: other fields influence the security of a session
59/// and resumption between them can be surprising. If sharing
60/// [`ServerConfig::session_storage`] or [`ServerConfig::ticketer`] between two
61/// `ServerConfig`s, you should also evaluate the following fields and ensure
62/// they are equivalent:
63///
64/// * `ServerConfig::verifier` -- client authentication requirements,
65/// * [`ServerConfig::cert_resolver`] -- server identities.
66///
67/// To illustrate, imagine two `ServerConfig`s `A` and `B`. `A` requires
68/// client authentication, `B` does not. If `A` and `B` shared a resumption store,
69/// it would be possible for a session originated by `B` (that is, an unauthenticated client)
70/// to be inserted into the store, and then resumed by `A`. This would give a false
71/// impression to the user of `A` that the client was authenticated. This is possible
72/// whether the resumption is performed statefully (via [`ServerConfig::session_storage`])
73/// or statelessly (via [`ServerConfig::ticketer`]).
74///
75/// _Unlike_ `ClientConfig`, rustls does not enforce any policy here.
76///
77/// [`RootCertStore`]: crate::RootCertStore
78/// [`ServerSessionMemoryCache`]: crate::server::handy::ServerSessionMemoryCache
79#[derive(Clone, Debug)]
80pub struct ServerConfig {
81 /// Source of randomness and other crypto.
82 pub(crate) provider: Arc<CryptoProvider>,
83
84 /// Ignore the client's ciphersuite order. Instead,
85 /// choose the top ciphersuite in the server list
86 /// which is supported by the client.
87 pub ignore_client_order: bool,
88
89 /// The maximum size of plaintext input to be emitted in a single TLS record.
90 /// A value of None is equivalent to the [TLS maximum] of 16 kB.
91 ///
92 /// rustls enforces an arbitrary minimum of 32 bytes for this field.
93 /// Out of range values are reported as errors from [ServerConnection::new].
94 ///
95 /// Setting this value to a little less than the TCP MSS may improve latency
96 /// for stream-y workloads.
97 ///
98 /// [TLS maximum]: https://datatracker.ietf.org/doc/html/rfc8446#section-5.1
99 /// [ServerConnection::new]: crate::server::ServerConnection::new
100 pub max_fragment_size: Option<usize>,
101
102 /// How to store client sessions.
103 ///
104 /// See [ServerConfig#sharing-resumption-storage-between-serverconfigs]
105 /// for a warning related to this field.
106 pub session_storage: Arc<dyn StoresServerSessions>,
107
108 /// How to produce tickets.
109 ///
110 /// See [ServerConfig#sharing-resumption-storage-between-serverconfigs]
111 /// for a warning related to this field.
112 pub ticketer: Option<Arc<dyn TicketProducer>>,
113
114 /// How to choose a server cert and key. This is usually set by
115 /// [ConfigBuilder::with_single_cert] or [ConfigBuilder::with_server_credential_resolver].
116 /// For async applications, see also [`Acceptor`][super::Acceptor].
117 pub cert_resolver: Arc<dyn ServerCredentialResolver>,
118
119 /// Protocol names we support, most preferred first.
120 /// If empty we don't do ALPN at all.
121 pub alpn_protocols: Vec<Vec<u8>>,
122
123 /// How to verify client certificates.
124 pub(super) verifier: Arc<dyn ClientVerifier>,
125
126 /// How to output key material for debugging. The default
127 /// does nothing.
128 pub key_log: Arc<dyn KeyLog>,
129
130 /// Allows traffic secrets to be extracted after the handshake,
131 /// e.g. for kTLS setup.
132 pub enable_secret_extraction: bool,
133
134 /// Amount of early data to accept for sessions created by
135 /// this config. Specify 0 to disable early data. The
136 /// default is 0.
137 ///
138 /// Read the early data via
139 /// [`ServerConnection::early_data()`][super::ServerConnection::early_data()].
140 ///
141 /// The units for this are _both_ plaintext bytes, _and_ ciphertext
142 /// bytes, depending on whether the server accepts a client's early_data
143 /// or not. It is therefore recommended to include some slop in
144 /// this value to account for the unknown amount of ciphertext
145 /// expansion in the latter case.
146 pub max_early_data_size: u32,
147
148 /// Whether the server should send "0.5RTT" data. This means the server
149 /// sends data after its first flight of handshake messages, without
150 /// waiting for the client to complete the handshake.
151 ///
152 /// This can improve TTFB latency for either server-speaks-first protocols,
153 /// or client-speaks-first protocols when paired with "0RTT" data. This
154 /// comes at the cost of a subtle weakening of the normal handshake
155 /// integrity guarantees that TLS provides. Note that the initial
156 /// `ClientHello` is indirectly authenticated because it is included
157 /// in the transcript used to derive the keys used to encrypt the data.
158 ///
159 /// This only applies to TLS1.3 connections. TLS1.2 connections cannot
160 /// do this optimisation and this setting is ignored for them. It is
161 /// also ignored for TLS1.3 connections that even attempt client
162 /// authentication.
163 ///
164 /// This defaults to false. This means the first application data
165 /// sent by the server comes after receiving and validating the client's
166 /// handshake up to the `Finished` message. This is the safest option.
167 pub send_half_rtt_data: bool,
168
169 /// How many TLS1.3 tickets to send immediately after a successful
170 /// handshake.
171 ///
172 /// Because TLS1.3 tickets are single-use, this allows
173 /// a client to perform multiple resumptions.
174 ///
175 /// The default is 2.
176 ///
177 /// If this is 0, no tickets are sent and clients will not be able to
178 /// do any resumption.
179 pub send_tls13_tickets: usize,
180
181 /// If set to `true`, requires the client to support the extended
182 /// master secret extraction method defined in [RFC 7627].
183 ///
184 /// The default is `true` if the "fips" crate feature is enabled,
185 /// `false` otherwise.
186 ///
187 /// It must be set to `true` to meet FIPS requirement mentioned in section
188 /// **D.Q Transition of the TLS 1.2 KDF to Support the Extended Master
189 /// Secret** from [FIPS 140-3 IG.pdf].
190 ///
191 /// [RFC 7627]: https://datatracker.ietf.org/doc/html/rfc7627
192 /// [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
193 pub require_ems: bool,
194
195 /// Provides the current system time
196 pub time_provider: Arc<dyn TimeProvider>,
197
198 /// How to compress the server's certificate chain.
199 ///
200 /// If a client supports this extension, and advertises support
201 /// for one of the compression algorithms included here, the
202 /// server certificate will be compressed according to [RFC8779].
203 ///
204 /// This only applies to TLS1.3 connections. It is ignored for
205 /// TLS1.2 connections.
206 ///
207 /// [RFC8779]: https://datatracker.ietf.org/doc/rfc8879/
208 pub cert_compressors: Vec<&'static dyn compress::CertCompressor>,
209
210 /// Caching for compressed certificates.
211 ///
212 /// This is optional: [`compress::CompressionCache::Disabled`] gives
213 /// a cache that does no caching.
214 pub cert_compression_cache: Arc<compress::CompressionCache>,
215
216 /// How to decompress the clients's certificate chain.
217 ///
218 /// If this is non-empty, the [RFC8779] certificate compression
219 /// extension is offered when requesting client authentication,
220 /// and any compressed certificates are transparently decompressed
221 /// during the handshake.
222 ///
223 /// This only applies to TLS1.3 connections. It is ignored for
224 /// TLS1.2 connections.
225 ///
226 /// [RFC8779]: https://datatracker.ietf.org/doc/rfc8879/
227 pub cert_decompressors: Vec<&'static dyn compress::CertDecompressor>,
228
229 /// Policy for how an invalid Server Name Indication (SNI) value from a client is handled.
230 pub invalid_sni_policy: InvalidSniPolicy,
231}
232
233impl ServerConfig {
234 /// Create a builder for a server configuration with a specific [`CryptoProvider`].
235 ///
236 /// This will use the provider's configured ciphersuites. This implies which TLS
237 /// protocol versions are enabled.
238 ///
239 /// This function always succeeds. Any internal consistency problems with `provider`
240 /// are reported at the end of the builder process.
241 ///
242 /// For more information, see the [`ConfigBuilder`] documentation.
243 #[cfg(feature = "std")]
244 pub fn builder(provider: Arc<CryptoProvider>) -> ConfigBuilder<Self, WantsVerifier> {
245 Self::builder_with_details(provider, Arc::new(DefaultTimeProvider))
246 }
247
248 /// Create a builder for a server configuration with no default implementation details.
249 ///
250 /// This API must be used by `no_std` users.
251 ///
252 /// You must provide a specific [`TimeProvider`].
253 ///
254 /// You must provide a specific [`CryptoProvider`].
255 ///
256 /// This will use the provider's configured ciphersuites. This implies which TLS
257 /// protocol versions are enabled.
258 ///
259 /// This function always succeeds. Any internal consistency problems with `provider`
260 /// are reported at the end of the builder process.
261 ///
262 /// For more information, see the [`ConfigBuilder`] documentation.
263 pub fn builder_with_details(
264 provider: Arc<CryptoProvider>,
265 time_provider: Arc<dyn TimeProvider>,
266 ) -> ConfigBuilder<Self, WantsVerifier> {
267 ConfigBuilder {
268 state: WantsVerifier {
269 client_ech_mode: None,
270 },
271 provider,
272 time_provider,
273 side: PhantomData,
274 }
275 }
276
277 /// Return `true` if connections made with this `ServerConfig` will
278 /// operate in FIPS mode.
279 ///
280 /// This is different from [`CryptoProvider::fips()`]: [`CryptoProvider::fips()`]
281 /// is concerned only with cryptography, whereas this _also_ covers TLS-level
282 /// configuration that NIST recommends.
283 pub fn fips(&self) -> bool {
284 self.provider.fips() && self.require_ems
285 }
286
287 /// Return the crypto provider used to construct this client configuration.
288 pub fn crypto_provider(&self) -> &Arc<CryptoProvider> {
289 &self.provider
290 }
291
292 pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool {
293 self.provider.supports_version(v)
294 }
295
296 pub(super) fn current_time(&self) -> Result<UnixTime, Error> {
297 self.time_provider
298 .current_time()
299 .ok_or(Error::FailedToGetCurrentTime)
300 }
301}
302
303/// A trait for the ability to store server session data.
304///
305/// The keys and values are opaque.
306///
307/// Inserted keys are randomly chosen by the library and have
308/// no internal structure (in other words, you may rely on all
309/// bits being uniformly random). Queried keys are untrusted data.
310///
311/// Both the keys and values should be treated as
312/// **highly sensitive data**, containing enough key material
313/// to break all security of the corresponding sessions.
314///
315/// Implementations can be lossy (in other words, forgetting
316/// key/value pairs) without any negative security consequences.
317///
318/// However, note that `take` **must** reliably delete a returned
319/// value. If it does not, there may be security consequences.
320///
321/// `put` and `take` are mutating operations; this isn't expressed
322/// in the type system to allow implementations freedom in
323/// how to achieve interior mutability. `Mutex` is a common
324/// choice.
325pub trait StoresServerSessions: Debug + Send + Sync {
326 /// Store session secrets encoded in `value` against `key`,
327 /// overwrites any existing value against `key`. Returns `true`
328 /// if the value was stored.
329 fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool;
330
331 /// Find a value with the given `key`. Return it, or None
332 /// if it doesn't exist.
333 fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
334
335 /// Find a value with the given `key`. Return it and delete it;
336 /// or None if it doesn't exist.
337 fn take(&self, key: &[u8]) -> Option<Vec<u8>>;
338
339 /// Whether the store can cache another session. This is used to indicate to clients
340 /// whether their session can be resumed; the implementation is not required to remember
341 /// a session even if it returns `true` here.
342 fn can_cache(&self) -> bool;
343}
344
345/// How to choose a certificate chain and signing key for use
346/// in server authentication.
347///
348/// This is suitable when selecting a certificate does not require
349/// I/O or when the application is using blocking I/O anyhow.
350///
351/// For applications that use async I/O and need to do I/O to choose
352/// a certificate (for instance, fetching a certificate from a data store),
353/// the [`Acceptor`][super::Acceptor] interface is more suitable.
354pub trait ServerCredentialResolver: Debug + Send + Sync {
355 /// Choose a certificate chain and matching key given simplified ClientHello information.
356 ///
357 /// The `SelectedCredential` returned from this method contains an identity and a
358 /// one-time-use [`Signer`] wrapping the private key. This is usually obtained via a
359 /// [`Credentials`], on which an implementation can call [`Credentials::signer()`].
360 /// An implementation can either store long-lived [`Credentials`] values, or instantiate
361 /// them as needed using one of its constructors.
362 ///
363 /// Yielding an `Error` will abort the handshake. Some relevant error variants:
364 ///
365 /// * [`PeerIncompatible::NoSignatureSchemesInCommon`]
366 /// * [`PeerIncompatible::NoServerNameProvided`]
367 /// * [`Error::NoSuitableCertificate`]
368 ///
369 /// [`Credentials`]: crate::crypto::Credentials
370 /// [`Credentials::signer()`]: crate::crypto::Credentials::signer
371 /// [`Signer`]: crate::crypto::Signer
372 /// [`PeerIncompatible::NoSignatureSchemesInCommon`]: crate::error::PeerIncompatible::NoSignatureSchemesInCommon
373 /// [`PeerIncompatible::NoServerNameProvided`]: crate::error::PeerIncompatible::NoServerNameProvided
374 fn resolve(&self, client_hello: &ClientHello<'_>) -> Result<SelectedCredential, Error>;
375
376 /// Returns which [`CertificateType`]s this resolver supports.
377 ///
378 /// Returning an empty slice will result in an error. The default implementation signals
379 /// support for X.509 certificates. Implementations should return the same value every time.
380 ///
381 /// See [RFC 7250](https://tools.ietf.org/html/rfc7250) for more information.
382 fn supported_certificate_types(&self) -> &'static [CertificateType] {
383 &[CertificateType::X509]
384 }
385}
386
387/// A struct representing the received Client Hello
388#[derive(Debug)]
389pub struct ClientHello<'a> {
390 pub(super) server_name: Option<Cow<'a, DnsName<'a>>>,
391 pub(super) signature_schemes: &'a [SignatureScheme],
392 pub(super) alpn: Option<&'a Vec<ProtocolName>>,
393 pub(super) server_cert_types: Option<&'a [CertificateType]>,
394 pub(super) client_cert_types: Option<&'a [CertificateType]>,
395 pub(super) cipher_suites: &'a [CipherSuite],
396 /// The [certificate_authorities] extension, if it was sent by the client.
397 ///
398 /// [certificate_authorities]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
399 pub(super) certificate_authorities: Option<&'a [DistinguishedName]>,
400 pub(super) named_groups: Option<&'a [NamedGroup]>,
401}
402
403impl<'a> ClientHello<'a> {
404 pub(super) fn new(
405 input: &'a ClientHelloInput<'a>,
406 sni: Option<&'a DnsName<'static>>,
407 version: ProtocolVersion,
408 ) -> Self {
409 Self {
410 server_name: sni.map(Cow::Borrowed),
411 signature_schemes: &input.sig_schemes,
412 alpn: input.client_hello.protocols.as_ref(),
413 client_cert_types: input
414 .client_hello
415 .client_certificate_types
416 .as_deref(),
417 server_cert_types: input
418 .client_hello
419 .server_certificate_types
420 .as_deref(),
421 cipher_suites: &input.client_hello.cipher_suites,
422 // We adhere to the TLS 1.2 RFC by not exposing this to the cert resolver if TLS version is 1.2
423 certificate_authorities: match version {
424 ProtocolVersion::TLSv1_2 => None,
425 _ => input
426 .client_hello
427 .certificate_authority_names
428 .as_deref(),
429 },
430 named_groups: input
431 .client_hello
432 .named_groups
433 .as_deref(),
434 }
435 }
436
437 /// Get the server name indicator.
438 ///
439 /// Returns `None` if the client did not supply a SNI.
440 pub fn server_name(&self) -> Option<&DnsName<'_>> {
441 self.server_name.as_deref()
442 }
443
444 /// Get the compatible signature schemes.
445 ///
446 /// Returns standard-specified default if the client omitted this extension.
447 pub fn signature_schemes(&self) -> &[SignatureScheme] {
448 self.signature_schemes
449 }
450
451 /// Get the ALPN protocol identifiers submitted by the client.
452 ///
453 /// Returns `None` if the client did not include an ALPN extension.
454 ///
455 /// Application Layer Protocol Negotiation (ALPN) is a TLS extension that lets a client
456 /// submit a set of identifiers that each a represent an application-layer protocol.
457 /// The server will then pick its preferred protocol from the set submitted by the client.
458 /// Each identifier is represented as a byte array, although common values are often ASCII-encoded.
459 /// See the official RFC-7301 specifications at <https://datatracker.ietf.org/doc/html/rfc7301>
460 /// for more information on ALPN.
461 ///
462 /// For example, a HTTP client might specify "http/1.1" and/or "h2". Other well-known values
463 /// are listed in the at IANA registry at
464 /// <https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids>.
465 ///
466 /// The server can specify supported ALPN protocols by setting [`ServerConfig::alpn_protocols`].
467 /// During the handshake, the server will select the first protocol configured that the client supports.
468 pub fn alpn(&self) -> Option<impl Iterator<Item = &'a [u8]>> {
469 self.alpn.map(|protocols| {
470 protocols
471 .iter()
472 .map(|proto| proto.as_ref())
473 })
474 }
475
476 /// Get cipher suites.
477 pub fn cipher_suites(&self) -> &[CipherSuite] {
478 self.cipher_suites
479 }
480
481 /// Get the server certificate types offered in the ClientHello.
482 ///
483 /// Returns `None` if the client did not include a certificate type extension.
484 pub fn server_cert_types(&self) -> Option<&'a [CertificateType]> {
485 self.server_cert_types
486 }
487
488 /// Get the client certificate types offered in the ClientHello.
489 ///
490 /// Returns `None` if the client did not include a certificate type extension.
491 pub fn client_cert_types(&self) -> Option<&'a [CertificateType]> {
492 self.client_cert_types
493 }
494
495 /// Get the [certificate_authorities] extension sent by the client.
496 ///
497 /// Returns `None` if the client did not send this extension.
498 ///
499 /// [certificate_authorities]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
500 pub fn certificate_authorities(&self) -> Option<&'a [DistinguishedName]> {
501 self.certificate_authorities
502 }
503
504 /// Get the [`named_groups`] extension sent by the client.
505 ///
506 /// This means different things in different versions of TLS:
507 ///
508 /// Originally it was introduced as the "[`elliptic_curves`]" extension for TLS1.2.
509 /// It described the elliptic curves supported by a client for all purposes: key
510 /// exchange, signature verification (for server authentication), and signing (for
511 /// client auth). Later [RFC7919] extended this to include FFDHE "named groups",
512 /// but FFDHE groups in this context only relate to key exchange.
513 ///
514 /// In TLS1.3 it was renamed to "[`named_groups`]" and now describes all types
515 /// of key exchange mechanisms, and does not relate at all to elliptic curves
516 /// used for signatures.
517 ///
518 /// [`elliptic_curves`]: https://datatracker.ietf.org/doc/html/rfc4492#section-5.1.1
519 /// [RFC7919]: https://datatracker.ietf.org/doc/html/rfc7919#section-2
520 /// [`named_groups`]:https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.7
521 pub fn named_groups(&self) -> Option<&'a [NamedGroup]> {
522 self.named_groups
523 }
524}
525
526/// A policy describing how an invalid Server Name Indication (SNI) value from a client is handled by the server.
527///
528/// The only valid form of SNI according to relevant RFCs ([RFC6066], [RFC1035]) is
529/// non-IP-address host name, however some misconfigured clients may send a bare IP address, or
530/// another invalid value. Some servers may wish to ignore these invalid values instead of producing
531/// an error.
532///
533/// By default, Rustls will ignore invalid values that are an IP address (the most common misconfiguration)
534/// and error for all other invalid values.
535///
536/// When an SNI value is ignored, Rustls treats the client as if it sent no SNI at all.
537///
538/// [RFC1035]: https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1
539/// [RFC6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
540#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
541#[non_exhaustive]
542pub enum InvalidSniPolicy {
543 /// Reject all ClientHello messages that contain an invalid SNI value.
544 RejectAll,
545 /// Ignore an invalid SNI value in ClientHello messages if the value is an IP address.
546 ///
547 /// "Ignoring SNI" means accepting the ClientHello message, but acting as if the client sent no SNI.
548 #[default]
549 IgnoreIpAddresses,
550 /// Ignore all invalid SNI in ClientHello messages.
551 ///
552 /// "Ignoring SNI" means accepting the ClientHello message, but acting as if the client sent no SNI.
553 IgnoreAll,
554}
555
556impl InvalidSniPolicy {
557 /// Returns the valid SNI value, or ignores the invalid SNI value if allowed by this policy; otherwise returns
558 /// an error.
559 pub(super) fn accept(
560 &self,
561 payload: Option<&ServerNamePayload<'_>>,
562 ) -> Result<Option<DnsName<'static>>, Error> {
563 let Some(payload) = payload else {
564 return Ok(None);
565 };
566 if let Some(server_name) = payload.to_dns_name_normalized() {
567 return Ok(Some(server_name));
568 }
569 match (self, payload) {
570 (Self::IgnoreAll, _) => Ok(None),
571 (Self::IgnoreIpAddresses, ServerNamePayload::IpAddress) => Ok(None),
572 _ => Err(Error::PeerMisbehaved(
573 PeerMisbehaved::ServerNameMustContainOneHostName,
574 )),
575 }
576 }
577}
578
579impl ConfigBuilder<ServerConfig, WantsVerifier> {
580 /// Choose how to verify client certificates.
581 pub fn with_client_cert_verifier(
582 self,
583 client_cert_verifier: Arc<dyn ClientVerifier>,
584 ) -> ConfigBuilder<ServerConfig, WantsServerCert> {
585 ConfigBuilder {
586 state: WantsServerCert {
587 verifier: client_cert_verifier,
588 },
589 provider: self.provider,
590 time_provider: self.time_provider,
591 side: PhantomData,
592 }
593 }
594
595 /// Disable client authentication.
596 pub fn with_no_client_auth(self) -> ConfigBuilder<ServerConfig, WantsServerCert> {
597 self.with_client_cert_verifier(Arc::new(NoClientAuth))
598 }
599}
600
601/// A config builder state where the caller must supply how to provide a server certificate to
602/// the connecting peer.
603///
604/// For more information, see the [`ConfigBuilder`] documentation.
605#[derive(Clone, Debug)]
606pub struct WantsServerCert {
607 verifier: Arc<dyn ClientVerifier>,
608}
609
610impl ConfigBuilder<ServerConfig, WantsServerCert> {
611 /// Sets a single certificate chain and matching private key. This
612 /// certificate and key is used for all subsequent connections,
613 /// irrespective of things like SNI hostname.
614 ///
615 /// Note that the end-entity certificate must have the
616 /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
617 /// extension to describe, e.g., the valid DNS name. The `commonName` field is
618 /// disregarded.
619 ///
620 /// `cert_chain` is a vector of DER-encoded certificates.
621 /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
622 /// `aws-lc-rs` and `ring` [`CryptoProvider`]s support
623 /// all three encodings, but other `CryptoProvider`s may not.
624 ///
625 /// This function fails if `key_der` is invalid, or if the
626 /// `SubjectPublicKeyInfo` from the private key does not match the public
627 /// key for the end-entity certificate from the `cert_chain`.
628 pub fn with_single_cert(
629 self,
630 identity: Arc<Identity<'static>>,
631 key_der: PrivateKeyDer<'static>,
632 ) -> Result<ServerConfig, Error> {
633 let credentials = Credentials::from_der(identity, key_der, self.crypto_provider())?;
634 self.with_server_credential_resolver(Arc::new(SingleCredential::from(credentials)))
635 }
636
637 /// Sets a single certificate chain, matching private key and optional OCSP
638 /// response. This certificate and key is used for all
639 /// subsequent connections, irrespective of things like SNI hostname.
640 ///
641 /// `cert_chain` is a vector of DER-encoded certificates.
642 /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
643 /// `aws-lc-rs` and `ring` [`CryptoProvider`]s support
644 /// all three encodings, but other `CryptoProvider`s may not.
645 /// `ocsp` is a DER-encoded OCSP response. Ignored if zero length.
646 ///
647 /// This function fails if `key_der` is invalid, or if the
648 /// `SubjectPublicKeyInfo` from the private key does not match the public
649 /// key for the end-entity certificate from the `cert_chain`.
650 pub fn with_single_cert_with_ocsp(
651 self,
652 identity: Arc<Identity<'static>>,
653 key_der: PrivateKeyDer<'static>,
654 ocsp: Arc<[u8]>,
655 ) -> Result<ServerConfig, Error> {
656 let mut credentials = Credentials::from_der(identity, key_der, self.crypto_provider())?;
657 if !ocsp.is_empty() {
658 credentials.ocsp = Some(ocsp);
659 }
660 self.with_server_credential_resolver(Arc::new(SingleCredential::from(credentials)))
661 }
662
663 /// Sets a custom [`ServerCredentialResolver`].
664 pub fn with_server_credential_resolver(
665 self,
666 cert_resolver: Arc<dyn ServerCredentialResolver>,
667 ) -> Result<ServerConfig, Error> {
668 self.provider.consistency_check()?;
669 Ok(ServerConfig {
670 provider: self.provider,
671 verifier: self.state.verifier,
672 cert_resolver,
673 ignore_client_order: false,
674 max_fragment_size: None,
675 #[cfg(feature = "std")]
676 session_storage: handy::ServerSessionMemoryCache::new(256),
677 #[cfg(not(feature = "std"))]
678 session_storage: Arc::new(handy::NoServerSessionStorage {}),
679 ticketer: None,
680 alpn_protocols: Vec::new(),
681 key_log: Arc::new(NoKeyLog {}),
682 enable_secret_extraction: false,
683 max_early_data_size: 0,
684 send_half_rtt_data: false,
685 send_tls13_tickets: 2,
686 require_ems: cfg!(feature = "fips"),
687 time_provider: self.time_provider,
688 cert_compressors: compress::default_cert_compressors().to_vec(),
689 cert_compression_cache: Arc::new(compress::CompressionCache::default()),
690 cert_decompressors: compress::default_cert_decompressors().to_vec(),
691 invalid_sni_policy: InvalidSniPolicy::default(),
692 })
693 }
694}