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