rustls/server/
server_conn.rs

1use alloc::borrow::Cow;
2use alloc::boxed::Box;
3use alloc::vec::Vec;
4use core::fmt;
5use core::fmt::{Debug, Formatter};
6use core::marker::PhantomData;
7use core::ops::{Deref, DerefMut};
8#[cfg(feature = "std")]
9use std::io;
10
11use pki_types::{DnsName, UnixTime};
12
13use super::hs;
14use crate::builder::ConfigBuilder;
15#[cfg(feature = "std")]
16use crate::common_state::State;
17use crate::common_state::{CommonState, Side};
18#[cfg(feature = "std")]
19use crate::conn::ConnectionCommon;
20use crate::conn::{ConnectionCore, UnbufferedConnectionCommon};
21#[cfg(doc)]
22use crate::crypto;
23use crate::crypto::{CryptoProvider, SelectedCredential};
24use crate::enums::{CertificateType, CipherSuite, ProtocolVersion, SignatureScheme};
25use crate::error::{Error, PeerMisbehaved};
26use crate::kernel::KernelConnection;
27#[cfg(feature = "std")]
28use crate::log::trace;
29use crate::msgs::base::Payload;
30#[cfg(feature = "std")]
31use crate::msgs::handshake::ClientHelloPayload;
32use crate::msgs::handshake::{ProtocolName, ServerExtensionsInput, ServerNamePayload};
33#[cfg(feature = "std")]
34use crate::msgs::message::Message;
35use crate::server::hs::ClientHelloInput;
36use crate::suites::ExtractedSecrets;
37use crate::sync::Arc;
38#[cfg(feature = "std")]
39use crate::time_provider::DefaultTimeProvider;
40use crate::time_provider::TimeProvider;
41use crate::vecbuf::ChunkVecBuffer;
42use crate::{DistinguishedName, KeyLog, NamedGroup, WantsVerifier, compress, verify};
43
44/// A trait for the ability to store server session data.
45///
46/// The keys and values are opaque.
47///
48/// Inserted keys are randomly chosen by the library and have
49/// no internal structure (in other words, you may rely on all
50/// bits being uniformly random).  Queried keys are untrusted data.
51///
52/// Both the keys and values should be treated as
53/// **highly sensitive data**, containing enough key material
54/// to break all security of the corresponding sessions.
55///
56/// Implementations can be lossy (in other words, forgetting
57/// key/value pairs) without any negative security consequences.
58///
59/// However, note that `take` **must** reliably delete a returned
60/// value.  If it does not, there may be security consequences.
61///
62/// `put` and `take` are mutating operations; this isn't expressed
63/// in the type system to allow implementations freedom in
64/// how to achieve interior mutability.  `Mutex` is a common
65/// choice.
66pub trait StoresServerSessions: Debug + Send + Sync {
67    /// Store session secrets encoded in `value` against `key`,
68    /// overwrites any existing value against `key`.  Returns `true`
69    /// if the value was stored.
70    fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool;
71
72    /// Find a value with the given `key`.  Return it, or None
73    /// if it doesn't exist.
74    fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
75
76    /// Find a value with the given `key`.  Return it and delete it;
77    /// or None if it doesn't exist.
78    fn take(&self, key: &[u8]) -> Option<Vec<u8>>;
79
80    /// Whether the store can cache another session. This is used to indicate to clients
81    /// whether their session can be resumed; the implementation is not required to remember
82    /// a session even if it returns `true` here.
83    fn can_cache(&self) -> bool;
84}
85
86/// A trait for the ability to encrypt and decrypt tickets.
87pub trait ProducesTickets: Debug + Send + Sync {
88    /// Returns true if this implementation will encrypt/decrypt
89    /// tickets.  Should return false if this is a dummy
90    /// implementation: the server will not send the SessionTicket
91    /// extension and will not call the other functions.
92    fn enabled(&self) -> bool;
93
94    /// Returns the lifetime in seconds of tickets produced now.
95    /// The lifetime is provided as a hint to clients that the
96    /// ticket will not be useful after the given time.
97    ///
98    /// This lifetime must be implemented by key rolling and
99    /// erasure, *not* by storing a lifetime in the ticket.
100    ///
101    /// The objective is to limit damage to forward secrecy caused
102    /// by tickets, not just limiting their lifetime.
103    fn lifetime(&self) -> u32;
104
105    /// Encrypt and authenticate `plain`, returning the resulting
106    /// ticket.  Return None if `plain` cannot be encrypted for
107    /// some reason: an empty ticket will be sent and the connection
108    /// will continue.
109    fn encrypt(&self, plain: &[u8]) -> Option<Vec<u8>>;
110
111    /// Decrypt `cipher`, validating its authenticity protection
112    /// and recovering the plaintext.  `cipher` is fully attacker
113    /// controlled, so this decryption must be side-channel free,
114    /// panic-proof, and otherwise bullet-proof.  If the decryption
115    /// fails, return None.
116    fn decrypt(&self, cipher: &[u8]) -> Option<Vec<u8>>;
117}
118
119/// How to choose a certificate chain and signing key for use
120/// in server authentication.
121///
122/// This is suitable when selecting a certificate does not require
123/// I/O or when the application is using blocking I/O anyhow.
124///
125/// For applications that use async I/O and need to do I/O to choose
126/// a certificate (for instance, fetching a certificate from a data store),
127/// the [`Acceptor`] interface is more suitable.
128pub trait ServerCredentialResolver: Debug + Send + Sync {
129    /// Choose a certificate chain and matching key given simplified ClientHello information.
130    ///
131    /// The `SelectedCredential` returned from this method contains an identity and a
132    /// one-time-use [`Signer`] wrapping the private key. This is usually obtained via a
133    /// [`Credentials`], on which an implementation can call [`Credentials::signer()`].
134    /// An implementation can either store long-lived [`Credentials`] values, or instantiate
135    /// them as needed using one of its constructors.
136    ///
137    /// Yielding an `Error` will abort the handshake. Some relevant error variants:
138    ///
139    /// * [`PeerIncompatible::NoSignatureSchemesInCommon`]
140    /// * [`PeerIncompatible::NoServerNameProvided`]
141    /// * [`Error::NoSuitableCertificate`]
142    ///
143    /// [`Credentials`]: crate::crypto::Credentials
144    /// [`Credentials::signer()`]: crate::crypto::Credentials::signer
145    /// [`Signer`]: crate::crypto::Signer
146    /// [`PeerIncompatible::NoSignatureSchemesInCommon`]: crate::error::PeerIncompatible::NoSignatureSchemesInCommon
147    /// [`PeerIncompatible::NoServerNameProvided`]: crate::error::PeerIncompatible::NoServerNameProvided
148    fn resolve(&self, client_hello: &ClientHello<'_>) -> Result<SelectedCredential, Error>;
149
150    /// Returns which [`CertificateType`]s this resolver supports.
151    ///
152    /// Returning an empty slice will result in an error. The default implementation signals
153    /// support for X.509 certificates. Implementations should return the same value every time.
154    ///
155    /// See [RFC 7250](https://tools.ietf.org/html/rfc7250) for more information.
156    fn supported_certificate_types(&self) -> &'static [CertificateType] {
157        &[CertificateType::X509]
158    }
159}
160
161/// A struct representing the received Client Hello
162#[derive(Debug)]
163pub struct ClientHello<'a> {
164    pub(super) server_name: Option<Cow<'a, DnsName<'a>>>,
165    pub(super) signature_schemes: &'a [SignatureScheme],
166    pub(super) alpn: Option<&'a Vec<ProtocolName>>,
167    pub(super) server_cert_types: Option<&'a [CertificateType]>,
168    pub(super) client_cert_types: Option<&'a [CertificateType]>,
169    pub(super) cipher_suites: &'a [CipherSuite],
170    /// The [certificate_authorities] extension, if it was sent by the client.
171    ///
172    /// [certificate_authorities]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
173    pub(super) certificate_authorities: Option<&'a [DistinguishedName]>,
174    pub(super) named_groups: Option<&'a [NamedGroup]>,
175}
176
177impl<'a> ClientHello<'a> {
178    pub(super) fn new(
179        input: &'a ClientHelloInput<'a>,
180        sni: Option<&'a DnsName<'static>>,
181        version: ProtocolVersion,
182    ) -> Self {
183        Self {
184            server_name: sni.map(Cow::Borrowed),
185            signature_schemes: &input.sig_schemes,
186            alpn: input.client_hello.protocols.as_ref(),
187            client_cert_types: input
188                .client_hello
189                .client_certificate_types
190                .as_deref(),
191            server_cert_types: input
192                .client_hello
193                .server_certificate_types
194                .as_deref(),
195            cipher_suites: &input.client_hello.cipher_suites,
196            // We adhere to the TLS 1.2 RFC by not exposing this to the cert resolver if TLS version is 1.2
197            certificate_authorities: match version {
198                ProtocolVersion::TLSv1_2 => None,
199                _ => input
200                    .client_hello
201                    .certificate_authority_names
202                    .as_deref(),
203            },
204            named_groups: input
205                .client_hello
206                .named_groups
207                .as_deref(),
208        }
209    }
210
211    /// Get the server name indicator.
212    ///
213    /// Returns `None` if the client did not supply a SNI.
214    pub fn server_name(&self) -> Option<&DnsName<'_>> {
215        self.server_name.as_deref()
216    }
217
218    /// Get the compatible signature schemes.
219    ///
220    /// Returns standard-specified default if the client omitted this extension.
221    pub fn signature_schemes(&self) -> &[SignatureScheme] {
222        self.signature_schemes
223    }
224
225    /// Get the ALPN protocol identifiers submitted by the client.
226    ///
227    /// Returns `None` if the client did not include an ALPN extension.
228    ///
229    /// Application Layer Protocol Negotiation (ALPN) is a TLS extension that lets a client
230    /// submit a set of identifiers that each a represent an application-layer protocol.
231    /// The server will then pick its preferred protocol from the set submitted by the client.
232    /// Each identifier is represented as a byte array, although common values are often ASCII-encoded.
233    /// See the official RFC-7301 specifications at <https://datatracker.ietf.org/doc/html/rfc7301>
234    /// for more information on ALPN.
235    ///
236    /// For example, a HTTP client might specify "http/1.1" and/or "h2". Other well-known values
237    /// are listed in the at IANA registry at
238    /// <https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids>.
239    ///
240    /// The server can specify supported ALPN protocols by setting [`ServerConfig::alpn_protocols`].
241    /// During the handshake, the server will select the first protocol configured that the client supports.
242    pub fn alpn(&self) -> Option<impl Iterator<Item = &'a [u8]>> {
243        self.alpn.map(|protocols| {
244            protocols
245                .iter()
246                .map(|proto| proto.as_ref())
247        })
248    }
249
250    /// Get cipher suites.
251    pub fn cipher_suites(&self) -> &[CipherSuite] {
252        self.cipher_suites
253    }
254
255    /// Get the server certificate types offered in the ClientHello.
256    ///
257    /// Returns `None` if the client did not include a certificate type extension.
258    pub fn server_cert_types(&self) -> Option<&'a [CertificateType]> {
259        self.server_cert_types
260    }
261
262    /// Get the client certificate types offered in the ClientHello.
263    ///
264    /// Returns `None` if the client did not include a certificate type extension.
265    pub fn client_cert_types(&self) -> Option<&'a [CertificateType]> {
266        self.client_cert_types
267    }
268
269    /// Get the [certificate_authorities] extension sent by the client.
270    ///
271    /// Returns `None` if the client did not send this extension.
272    ///
273    /// [certificate_authorities]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
274    pub fn certificate_authorities(&self) -> Option<&'a [DistinguishedName]> {
275        self.certificate_authorities
276    }
277
278    /// Get the [`named_groups`] extension sent by the client.
279    ///
280    /// This means different things in different versions of TLS:
281    ///
282    /// Originally it was introduced as the "[`elliptic_curves`]" extension for TLS1.2.
283    /// It described the elliptic curves supported by a client for all purposes: key
284    /// exchange, signature verification (for server authentication), and signing (for
285    /// client auth).  Later [RFC7919] extended this to include FFDHE "named groups",
286    /// but FFDHE groups in this context only relate to key exchange.
287    ///
288    /// In TLS1.3 it was renamed to "[`named_groups`]" and now describes all types
289    /// of key exchange mechanisms, and does not relate at all to elliptic curves
290    /// used for signatures.
291    ///
292    /// [`elliptic_curves`]: https://datatracker.ietf.org/doc/html/rfc4492#section-5.1.1
293    /// [RFC7919]: https://datatracker.ietf.org/doc/html/rfc7919#section-2
294    /// [`named_groups`]:https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.7
295    pub fn named_groups(&self) -> Option<&'a [NamedGroup]> {
296        self.named_groups
297    }
298}
299
300/// Common configuration for a set of server sessions.
301///
302/// Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots
303/// from the operating system to add to the [`RootCertStore`] passed to a `ClientVerifier`
304/// builder may take on the order of a few hundred milliseconds.
305///
306/// These must be created via the [`ServerConfig::builder()`] or [`ServerConfig::builder_with_provider()`]
307/// function.
308///
309/// # Defaults
310///
311/// * [`ServerConfig::max_fragment_size`]: the default is `None` (meaning 16kB).
312/// * [`ServerConfig::session_storage`]: if the `std` feature is enabled, the default stores 256
313///   sessions in memory. If the `std` feature is not enabled, the default is to not store any
314///   sessions. In a no-std context, by enabling the `hashbrown` feature you may provide your
315///   own `session_storage` using [`ServerSessionMemoryCache`] and a `crate::lock::MakeMutex`
316///   implementation.
317/// * [`ServerConfig::alpn_protocols`]: the default is empty -- no ALPN protocol is negotiated.
318/// * [`ServerConfig::key_log`]: key material is not logged.
319/// * [`ServerConfig::send_tls13_tickets`]: 2 tickets are sent.
320/// * [`ServerConfig::cert_compressors`]: depends on the crate features, see [`compress::default_cert_compressors()`].
321/// * [`ServerConfig::cert_compression_cache`]: caches the most recently used 4 compressions
322/// * [`ServerConfig::cert_decompressors`]: depends on the crate features, see [`compress::default_cert_decompressors()`].
323///
324/// # Sharing resumption storage between `ServerConfig`s
325///
326/// In a program using many `ServerConfig`s it may improve resumption rates
327/// (which has a significant impact on connection performance) if those
328/// configs share [`ServerConfig::session_storage`] or [`ServerConfig::ticketer`].
329///
330/// However, caution is needed: other fields influence the security of a session
331/// and resumption between them can be surprising.  If sharing
332/// [`ServerConfig::session_storage`] or [`ServerConfig::ticketer`] between two
333/// `ServerConfig`s, you should also evaluate the following fields and ensure
334/// they are equivalent:
335///
336/// * `ServerConfig::verifier` -- client authentication requirements,
337/// * [`ServerConfig::cert_resolver`] -- server identities.
338///
339/// To illustrate, imagine two `ServerConfig`s `A` and `B`.  `A` requires
340/// client authentication, `B` does not.  If `A` and `B` shared a resumption store,
341/// it would be possible for a session originated by `B` (that is, an unauthenticated client)
342/// to be inserted into the store, and then resumed by `A`.  This would give a false
343/// impression to the user of `A` that the client was authenticated.  This is possible
344/// whether the resumption is performed statefully (via [`ServerConfig::session_storage`])
345/// or statelessly (via [`ServerConfig::ticketer`]).
346///
347/// _Unlike_ `ClientConfig`, rustls does not enforce any policy here.
348///
349/// [`RootCertStore`]: crate::RootCertStore
350/// [`ServerSessionMemoryCache`]: crate::server::handy::ServerSessionMemoryCache
351#[derive(Clone, Debug)]
352pub struct ServerConfig {
353    /// Source of randomness and other crypto.
354    pub(crate) provider: Arc<CryptoProvider>,
355
356    /// Ignore the client's ciphersuite order. Instead,
357    /// choose the top ciphersuite in the server list
358    /// which is supported by the client.
359    pub ignore_client_order: bool,
360
361    /// The maximum size of plaintext input to be emitted in a single TLS record.
362    /// A value of None is equivalent to the [TLS maximum] of 16 kB.
363    ///
364    /// rustls enforces an arbitrary minimum of 32 bytes for this field.
365    /// Out of range values are reported as errors from [ServerConnection::new].
366    ///
367    /// Setting this value to a little less than the TCP MSS may improve latency
368    /// for stream-y workloads.
369    ///
370    /// [TLS maximum]: https://datatracker.ietf.org/doc/html/rfc8446#section-5.1
371    /// [ServerConnection::new]: crate::server::ServerConnection::new
372    pub max_fragment_size: Option<usize>,
373
374    /// How to store client sessions.
375    ///
376    /// See [ServerConfig#sharing-resumption-storage-between-serverconfigs]
377    /// for a warning related to this field.
378    pub session_storage: Arc<dyn StoresServerSessions>,
379
380    /// How to produce tickets.
381    ///
382    /// See [ServerConfig#sharing-resumption-storage-between-serverconfigs]
383    /// for a warning related to this field.
384    pub ticketer: Arc<dyn ProducesTickets>,
385
386    /// How to choose a server cert and key. This is usually set by
387    /// [ConfigBuilder::with_single_cert] or [ConfigBuilder::with_server_credential_resolver].
388    /// For async applications, see also [Acceptor].
389    pub cert_resolver: Arc<dyn ServerCredentialResolver>,
390
391    /// Protocol names we support, most preferred first.
392    /// If empty we don't do ALPN at all.
393    pub alpn_protocols: Vec<Vec<u8>>,
394
395    /// How to verify client certificates.
396    pub(super) verifier: Arc<dyn verify::ClientVerifier>,
397
398    /// How to output key material for debugging.  The default
399    /// does nothing.
400    pub key_log: Arc<dyn KeyLog>,
401
402    /// Allows traffic secrets to be extracted after the handshake,
403    /// e.g. for kTLS setup.
404    pub enable_secret_extraction: bool,
405
406    /// Amount of early data to accept for sessions created by
407    /// this config.  Specify 0 to disable early data.  The
408    /// default is 0.
409    ///
410    /// Read the early data via [`ServerConnection::early_data`].
411    ///
412    /// The units for this are _both_ plaintext bytes, _and_ ciphertext
413    /// bytes, depending on whether the server accepts a client's early_data
414    /// or not.  It is therefore recommended to include some slop in
415    /// this value to account for the unknown amount of ciphertext
416    /// expansion in the latter case.
417    pub max_early_data_size: u32,
418
419    /// Whether the server should send "0.5RTT" data.  This means the server
420    /// sends data after its first flight of handshake messages, without
421    /// waiting for the client to complete the handshake.
422    ///
423    /// This can improve TTFB latency for either server-speaks-first protocols,
424    /// or client-speaks-first protocols when paired with "0RTT" data.  This
425    /// comes at the cost of a subtle weakening of the normal handshake
426    /// integrity guarantees that TLS provides.  Note that the initial
427    /// `ClientHello` is indirectly authenticated because it is included
428    /// in the transcript used to derive the keys used to encrypt the data.
429    ///
430    /// This only applies to TLS1.3 connections.  TLS1.2 connections cannot
431    /// do this optimisation and this setting is ignored for them.  It is
432    /// also ignored for TLS1.3 connections that even attempt client
433    /// authentication.
434    ///
435    /// This defaults to false.  This means the first application data
436    /// sent by the server comes after receiving and validating the client's
437    /// handshake up to the `Finished` message.  This is the safest option.
438    pub send_half_rtt_data: bool,
439
440    /// How many TLS1.3 tickets to send immediately after a successful
441    /// handshake.
442    ///
443    /// Because TLS1.3 tickets are single-use, this allows
444    /// a client to perform multiple resumptions.
445    ///
446    /// The default is 2.
447    ///
448    /// If this is 0, no tickets are sent and clients will not be able to
449    /// do any resumption.
450    pub send_tls13_tickets: usize,
451
452    /// If set to `true`, requires the client to support the extended
453    /// master secret extraction method defined in [RFC 7627].
454    ///
455    /// The default is `true` if the "fips" crate feature is enabled,
456    /// `false` otherwise.
457    ///
458    /// It must be set to `true` to meet FIPS requirement mentioned in section
459    /// **D.Q Transition of the TLS 1.2 KDF to Support the Extended Master
460    /// Secret** from [FIPS 140-3 IG.pdf].
461    ///
462    /// [RFC 7627]: https://datatracker.ietf.org/doc/html/rfc7627
463    /// [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
464    pub require_ems: bool,
465
466    /// Provides the current system time
467    pub time_provider: Arc<dyn TimeProvider>,
468
469    /// How to compress the server's certificate chain.
470    ///
471    /// If a client supports this extension, and advertises support
472    /// for one of the compression algorithms included here, the
473    /// server certificate will be compressed according to [RFC8779].
474    ///
475    /// This only applies to TLS1.3 connections.  It is ignored for
476    /// TLS1.2 connections.
477    ///
478    /// [RFC8779]: https://datatracker.ietf.org/doc/rfc8879/
479    pub cert_compressors: Vec<&'static dyn compress::CertCompressor>,
480
481    /// Caching for compressed certificates.
482    ///
483    /// This is optional: [`compress::CompressionCache::Disabled`] gives
484    /// a cache that does no caching.
485    pub cert_compression_cache: Arc<compress::CompressionCache>,
486
487    /// How to decompress the clients's certificate chain.
488    ///
489    /// If this is non-empty, the [RFC8779] certificate compression
490    /// extension is offered when requesting client authentication,
491    /// and any compressed certificates are transparently decompressed
492    /// during the handshake.
493    ///
494    /// This only applies to TLS1.3 connections.  It is ignored for
495    /// TLS1.2 connections.
496    ///
497    /// [RFC8779]: https://datatracker.ietf.org/doc/rfc8879/
498    pub cert_decompressors: Vec<&'static dyn compress::CertDecompressor>,
499
500    /// Policy for how an invalid Server Name Indication (SNI) value from a client is handled.
501    pub invalid_sni_policy: InvalidSniPolicy,
502}
503
504impl ServerConfig {
505    /// Create a builder for a server configuration with
506    /// [the process-default `CryptoProvider`][CryptoProvider#using-the-per-process-default-cryptoprovider].
507    ///
508    /// This will use the provider's configured ciphersuites.  This implies which TLS
509    /// protocol versions are enabled.
510    ///
511    /// This function always succeeds.  Any internal consistency problems with `provider`
512    /// are reported at the end of the builder process.
513    ///
514    /// For more information, see the [`ConfigBuilder`] documentation.
515    #[cfg(feature = "std")]
516    pub fn builder() -> ConfigBuilder<Self, WantsVerifier> {
517        Self::builder_with_provider(
518            CryptoProvider::get_default_or_install_from_crate_features().clone(),
519        )
520    }
521
522    /// Create a builder for a server configuration with a specific [`CryptoProvider`].
523    ///
524    /// This will use the provider's configured ciphersuites.  This implies which TLS
525    /// protocol versions are enabled.
526    ///
527    /// This function always succeeds.  Any internal consistency problems with `provider`
528    /// are reported at the end of the builder process.
529    ///
530    /// For more information, see the [`ConfigBuilder`] documentation.
531    #[cfg(feature = "std")]
532    pub fn builder_with_provider(
533        provider: Arc<CryptoProvider>,
534    ) -> ConfigBuilder<Self, WantsVerifier> {
535        Self::builder_with_details(provider, Arc::new(DefaultTimeProvider))
536    }
537
538    /// Create a builder for a server configuration with no default implementation details.
539    ///
540    /// This API must be used by `no_std` users.
541    ///
542    /// You must provide a specific [`TimeProvider`].
543    ///
544    /// You must provide a specific [`CryptoProvider`].
545    ///
546    /// This will use the provider's configured ciphersuites.  This implies which TLS
547    /// protocol versions are enabled.
548    ///
549    /// This function always succeeds.  Any internal consistency problems with `provider`
550    /// are reported at the end of the builder process.
551    ///
552    /// For more information, see the [`ConfigBuilder`] documentation.
553    pub fn builder_with_details(
554        provider: Arc<CryptoProvider>,
555        time_provider: Arc<dyn TimeProvider>,
556    ) -> ConfigBuilder<Self, WantsVerifier> {
557        ConfigBuilder {
558            state: WantsVerifier {
559                client_ech_mode: None,
560            },
561            provider,
562            time_provider,
563            side: PhantomData,
564        }
565    }
566
567    /// Return `true` if connections made with this `ServerConfig` will
568    /// operate in FIPS mode.
569    ///
570    /// This is different from [`CryptoProvider::fips()`]: [`CryptoProvider::fips()`]
571    /// is concerned only with cryptography, whereas this _also_ covers TLS-level
572    /// configuration that NIST recommends.
573    pub fn fips(&self) -> bool {
574        self.provider.fips() && self.require_ems
575    }
576
577    /// Return the crypto provider used to construct this client configuration.
578    pub fn crypto_provider(&self) -> &Arc<CryptoProvider> {
579        &self.provider
580    }
581
582    pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool {
583        self.provider.supports_version(v)
584    }
585
586    pub(super) fn current_time(&self) -> Result<UnixTime, Error> {
587        self.time_provider
588            .current_time()
589            .ok_or(Error::FailedToGetCurrentTime)
590    }
591}
592
593/// A policy describing how an invalid Server Name Indication (SNI) value from a client is handled by the server.
594///
595/// The only valid form of SNI according to relevant RFCs ([RFC6066], [RFC1035]) is
596/// non-IP-address host name, however some misconfigured clients may send a bare IP address, or
597/// another invalid value. Some servers may wish to ignore these invalid values instead of producing
598/// an error.
599///
600/// By default, Rustls will ignore invalid values that are an IP address (the most common misconfiguration)
601/// and error for all other invalid values.
602///
603/// When an SNI value is ignored, Rustls treats the client as if it sent no SNI at all.
604///
605/// [RFC1035]: https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1
606/// [RFC6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
607#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
608#[non_exhaustive]
609pub enum InvalidSniPolicy {
610    /// Reject all ClientHello messages that contain an invalid SNI value.
611    RejectAll,
612    /// Ignore an invalid SNI value in ClientHello messages if the value is an IP address.
613    ///
614    /// "Ignoring SNI" means accepting the ClientHello message, but acting as if the client sent no SNI.
615    #[default]
616    IgnoreIpAddresses,
617    /// Ignore all invalid SNI in ClientHello messages.
618    ///
619    /// "Ignoring SNI" means accepting the ClientHello message, but acting as if the client sent no SNI.
620    IgnoreAll,
621}
622
623impl InvalidSniPolicy {
624    /// Returns the valid SNI value, or ignores the invalid SNI value if allowed by this policy; otherwise returns
625    /// an error.
626    pub(super) fn accept(
627        &self,
628        payload: Option<&ServerNamePayload<'_>>,
629    ) -> Result<Option<DnsName<'static>>, Error> {
630        let Some(payload) = payload else {
631            return Ok(None);
632        };
633        if let Some(server_name) = payload.to_dns_name_normalized() {
634            return Ok(Some(server_name));
635        }
636        match (self, payload) {
637            (Self::IgnoreAll, _) => Ok(None),
638            (Self::IgnoreIpAddresses, ServerNamePayload::IpAddress) => Ok(None),
639            _ => Err(Error::PeerMisbehaved(
640                PeerMisbehaved::ServerNameMustContainOneHostName,
641            )),
642        }
643    }
644}
645
646#[cfg(feature = "std")]
647mod connection {
648    use alloc::boxed::Box;
649    use core::fmt;
650    use core::fmt::{Debug, Formatter};
651    use core::ops::{Deref, DerefMut};
652    use std::io;
653
654    use pki_types::DnsName;
655
656    use super::{Accepted, Accepting, ServerConfig, ServerConnectionData, ServerExtensionsInput};
657    use crate::KeyingMaterialExporter;
658    use crate::common_state::{CommonState, Context, Side};
659    use crate::conn::{ConnectionCommon, ConnectionCore};
660    use crate::error::{ApiMisuse, Error};
661    use crate::server::hs::ClientHelloInput;
662    use crate::suites::ExtractedSecrets;
663    use crate::sync::Arc;
664    use crate::vecbuf::ChunkVecBuffer;
665
666    /// Allows reading of early data in resumed TLS1.3 connections.
667    ///
668    /// "Early data" is also known as "0-RTT data".
669    ///
670    /// This type implements [`io::Read`].
671    pub struct ReadEarlyData<'a> {
672        common: &'a mut ConnectionCommon<ServerConnectionData>,
673    }
674
675    impl<'a> ReadEarlyData<'a> {
676        fn new(common: &'a mut ConnectionCommon<ServerConnectionData>) -> Self {
677            ReadEarlyData { common }
678        }
679
680        /// Returns the "early" exporter that can derive key material for use in early data
681        ///
682        /// See [RFC5705][] for general details on what exporters are, and [RFC8446 S7.5][] for
683        /// specific details on the "early" exporter.
684        ///
685        /// **Beware** that the early exporter requires care, as it is subject to the same
686        /// potential for replay as early data itself.  See [RFC8446 appendix E.5.1][] for
687        /// more detail.
688        ///
689        /// This function can be called at most once per connection. This function will error:
690        /// if called more than once per connection.
691        ///
692        /// If you are looking for the normal exporter, this is available from
693        /// [`ConnectionCommon::exporter()`].
694        ///
695        /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
696        /// [RFC8446 S7.5]: https://datatracker.ietf.org/doc/html/rfc8446#section-7.5
697        /// [RFC8446 appendix E.5.1]: https://datatracker.ietf.org/doc/html/rfc8446#appendix-E.5.1
698        /// [`ConnectionCommon::exporter()`]: crate::conn::ConnectionCommon::exporter()
699        pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
700            self.common.core.early_exporter()
701        }
702    }
703
704    impl io::Read for ReadEarlyData<'_> {
705        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
706            self.common
707                .core
708                .side
709                .early_data
710                .read(buf)
711        }
712    }
713
714    /// This represents a single TLS server connection.
715    ///
716    /// Send TLS-protected data to the peer using the `io::Write` trait implementation.
717    /// Read data from the peer using the `io::Read` trait implementation.
718    pub struct ServerConnection {
719        pub(super) inner: ConnectionCommon<ServerConnectionData>,
720    }
721
722    impl ServerConnection {
723        /// Make a new ServerConnection.  `config` controls how
724        /// we behave in the TLS protocol.
725        pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
726            Ok(Self {
727                inner: ConnectionCommon::from(ConnectionCore::for_server(
728                    config,
729                    ServerExtensionsInput::default(),
730                )?),
731            })
732        }
733
734        /// Retrieves the server name, if any, used to select the certificate and
735        /// private key.
736        ///
737        /// This returns `None` until some time after the client's server name indication
738        /// (SNI) extension value is processed during the handshake. It will never be
739        /// `None` when the connection is ready to send or process application data,
740        /// unless the client does not support SNI.
741        ///
742        /// This is useful for application protocols that need to enforce that the
743        /// server name matches an application layer protocol hostname. For
744        /// example, HTTP/1.1 servers commonly expect the `Host:` header field of
745        /// every request on a connection to match the hostname in the SNI extension
746        /// when the client provides the SNI extension.
747        ///
748        /// The server name is also used to match sessions during session resumption.
749        pub fn server_name(&self) -> Option<&DnsName<'_>> {
750            self.inner.core.side.sni.as_ref()
751        }
752
753        /// Application-controlled portion of the resumption ticket supplied by the client, if any.
754        ///
755        /// Recovered from the prior session's `set_resumption_data`. Integrity is guaranteed by rustls.
756        ///
757        /// Returns `Some` if and only if a valid resumption ticket has been received from the client.
758        pub fn received_resumption_data(&self) -> Option<&[u8]> {
759            self.inner
760                .core
761                .side
762                .received_resumption_data
763                .as_ref()
764                .map(|x| &x[..])
765        }
766
767        /// Set the resumption data to embed in future resumption tickets supplied to the client.
768        ///
769        /// Defaults to the empty byte string. Must be less than 2^15 bytes to allow room for other
770        /// data. Should be called while `is_handshaking` returns true to ensure all transmitted
771        /// resumption tickets are affected.
772        ///
773        /// Integrity will be assured by rustls, but the data will be visible to the client. If secrecy
774        /// from the client is desired, encrypt the data separately.
775        pub fn set_resumption_data(&mut self, data: &[u8]) {
776            assert!(data.len() < 2usize.pow(15));
777            self.inner.core.side.resumption_data = data.into();
778        }
779
780        /// Explicitly discard early data, notifying the client
781        ///
782        /// Useful if invariants encoded in `received_resumption_data()` cannot be respected.
783        ///
784        /// Must be called while `is_handshaking` is true.
785        pub fn reject_early_data(&mut self) {
786            self.inner.core.reject_early_data()
787        }
788
789        /// Returns an `io::Read` implementer you can read bytes from that are
790        /// received from a client as TLS1.3 0RTT/"early" data, during the handshake.
791        ///
792        /// This returns `None` in many circumstances, such as :
793        ///
794        /// - Early data is disabled if [`ServerConfig::max_early_data_size`] is zero (the default).
795        /// - The session negotiated with the client is not TLS1.3.
796        /// - The client just doesn't support early data.
797        /// - The connection doesn't resume an existing session.
798        /// - The client hasn't sent a full ClientHello yet.
799        pub fn early_data(&mut self) -> Option<ReadEarlyData<'_>> {
800            if self
801                .inner
802                .core
803                .side
804                .early_data
805                .was_accepted()
806            {
807                Some(ReadEarlyData::new(&mut self.inner))
808            } else {
809                None
810            }
811        }
812
813        /// Return true if the connection was made with a `ServerConfig` that is FIPS compatible.
814        ///
815        /// This is different from [`crate::crypto::CryptoProvider::fips()`]:
816        /// it is concerned only with cryptography, whereas this _also_ covers TLS-level
817        /// configuration that NIST recommends, as well as ECH HPKE suites if applicable.
818        pub fn fips(&self) -> bool {
819            self.inner.core.common_state.fips
820        }
821
822        /// Extract secrets, so they can be used when configuring kTLS, for example.
823        /// Should be used with care as it exposes secret key material.
824        pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
825            self.inner.dangerous_extract_secrets()
826        }
827    }
828
829    impl Debug for ServerConnection {
830        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
831            f.debug_struct("ServerConnection")
832                .finish()
833        }
834    }
835
836    impl Deref for ServerConnection {
837        type Target = ConnectionCommon<ServerConnectionData>;
838
839        fn deref(&self) -> &Self::Target {
840            &self.inner
841        }
842    }
843
844    impl DerefMut for ServerConnection {
845        fn deref_mut(&mut self) -> &mut Self::Target {
846            &mut self.inner
847        }
848    }
849
850    impl From<ServerConnection> for crate::Connection {
851        fn from(conn: ServerConnection) -> Self {
852            Self::Server(conn)
853        }
854    }
855
856    /// Handle a server-side connection before configuration is available.
857    ///
858    /// `Acceptor` allows the caller to choose a [`ServerConfig`] after reading
859    /// the [`super::ClientHello`] of an incoming connection. This is useful for servers
860    /// that choose different certificates or cipher suites based on the
861    /// characteristics of the `ClientHello`. In particular it is useful for
862    /// servers that need to do some I/O to load a certificate and its private key
863    /// and don't want to use the blocking interface provided by
864    /// [`super::ServerCredentialResolver`].
865    ///
866    /// Create an Acceptor with [`Acceptor::default()`].
867    ///
868    /// # Example
869    ///
870    /// ```no_run
871    /// # #[cfg(feature = "aws-lc-rs")] {
872    /// # fn choose_server_config(
873    /// #     _: rustls::server::ClientHello,
874    /// # ) -> std::sync::Arc<rustls::ServerConfig> {
875    /// #     unimplemented!();
876    /// # }
877    /// # #[allow(unused_variables)]
878    /// # fn main() {
879    /// use rustls::server::{Acceptor, ServerConfig};
880    /// let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
881    /// for stream in listener.incoming() {
882    ///     let mut stream = stream.unwrap();
883    ///     let mut acceptor = Acceptor::default();
884    ///     let accepted = loop {
885    ///         acceptor.read_tls(&mut stream).unwrap();
886    ///         if let Some(accepted) = acceptor.accept().unwrap() {
887    ///             break accepted;
888    ///         }
889    ///     };
890    ///
891    ///     // For some user-defined choose_server_config:
892    ///     let config = choose_server_config(accepted.client_hello());
893    ///     let conn = accepted
894    ///         .into_connection(config)
895    ///         .unwrap();
896    ///
897    ///     // Proceed with handling the ServerConnection.
898    /// }
899    /// # }
900    /// # }
901    /// ```
902    pub struct Acceptor {
903        inner: Option<ConnectionCommon<ServerConnectionData>>,
904    }
905
906    impl Default for Acceptor {
907        /// Return an empty Acceptor, ready to receive bytes from a new client connection.
908        fn default() -> Self {
909            Self {
910                inner: Some(
911                    ConnectionCore::new(
912                        Box::new(Accepting),
913                        ServerConnectionData::default(),
914                        CommonState::new(Side::Server),
915                    )
916                    .into(),
917                ),
918            }
919        }
920    }
921
922    impl Acceptor {
923        /// Read TLS content from `rd`.
924        ///
925        /// Returns an error if this `Acceptor` has already yielded an [`Accepted`]. For more details,
926        /// refer to [`Connection::read_tls()`].
927        ///
928        /// [`Connection::read_tls()`]: crate::Connection::read_tls
929        pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
930            match &mut self.inner {
931                Some(conn) => conn.read_tls(rd),
932                None => Err(io::Error::other(
933                    "acceptor cannot read after successful acceptance",
934                )),
935            }
936        }
937
938        /// Check if a `ClientHello` message has been received.
939        ///
940        /// Returns `Ok(None)` if the complete `ClientHello` has not yet been received.
941        /// Do more I/O and then call this function again.
942        ///
943        /// Returns `Ok(Some(accepted))` if the connection has been accepted. Call
944        /// `accepted.into_connection()` to continue. Do not call this function again.
945        ///
946        /// Returns `Err((err, alert))` if an error occurred. If an alert is returned, the
947        /// application should call `alert.write()` to send the alert to the client. It should
948        /// not call `accept()` again.
949        pub fn accept(&mut self) -> Result<Option<Accepted>, (Error, AcceptedAlert)> {
950            let Some(mut connection) = self.inner.take() else {
951                return Err((
952                    ApiMisuse::AcceptorPolledAfterCompletion.into(),
953                    AcceptedAlert::empty(),
954                ));
955            };
956
957            let message = match connection.first_handshake_message() {
958                Ok(Some(msg)) => msg,
959                Ok(None) => {
960                    self.inner = Some(connection);
961                    return Ok(None);
962                }
963                Err(err) => return Err((err, AcceptedAlert::from(connection))),
964            };
965
966            let mut cx = Context::from(&mut connection);
967            let sig_schemes = match ClientHelloInput::from_message(&message, false, &mut cx) {
968                Ok(ClientHelloInput { sig_schemes, .. }) => sig_schemes,
969                Err(err) => {
970                    return Err((err, AcceptedAlert::from(connection)));
971                }
972            };
973
974            Ok(Some(Accepted {
975                connection,
976                message,
977                sig_schemes,
978            }))
979        }
980    }
981
982    /// Represents a TLS alert resulting from handling the client's `ClientHello` message.
983    ///
984    /// When [`Acceptor::accept()`] returns an error, it yields an `AcceptedAlert` such that the
985    /// application can communicate failure to the client via [`AcceptedAlert::write()`].
986    pub struct AcceptedAlert(ChunkVecBuffer);
987
988    impl AcceptedAlert {
989        pub(super) fn empty() -> Self {
990            Self(ChunkVecBuffer::new(None))
991        }
992
993        /// Send the alert to the client.
994        ///
995        /// To account for short writes this function should be called repeatedly until it
996        /// returns `Ok(0)` or an error.
997        pub fn write(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
998            self.0.write_to(wr)
999        }
1000
1001        /// Send the alert to the client.
1002        ///
1003        /// This function will invoke the writer until the buffer is empty.
1004        pub fn write_all(&mut self, wr: &mut dyn io::Write) -> Result<(), io::Error> {
1005            while self.write(wr)? != 0 {}
1006            Ok(())
1007        }
1008    }
1009
1010    impl From<ConnectionCommon<ServerConnectionData>> for AcceptedAlert {
1011        fn from(conn: ConnectionCommon<ServerConnectionData>) -> Self {
1012            Self(conn.core.common_state.sendable_tls)
1013        }
1014    }
1015
1016    impl Debug for AcceptedAlert {
1017        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1018            f.debug_struct("AcceptedAlert").finish()
1019        }
1020    }
1021}
1022
1023#[cfg(feature = "std")]
1024pub use connection::{AcceptedAlert, Acceptor, ReadEarlyData, ServerConnection};
1025
1026/// Unbuffered version of `ServerConnection`
1027///
1028/// See the [`crate::unbuffered`] module docs for more details
1029pub struct UnbufferedServerConnection {
1030    inner: UnbufferedConnectionCommon<ServerConnectionData>,
1031}
1032
1033impl UnbufferedServerConnection {
1034    /// Make a new ServerConnection. `config` controls how we behave in the TLS protocol.
1035    pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
1036        Ok(Self {
1037            inner: UnbufferedConnectionCommon::from(ConnectionCore::for_server(
1038                config,
1039                ServerExtensionsInput::default(),
1040            )?),
1041        })
1042    }
1043
1044    /// Extract secrets, so they can be used when configuring kTLS, for example.
1045    /// Should be used with care as it exposes secret key material.
1046    #[deprecated = "dangerous_extract_secrets() does not support session tickets or \
1047                    key updates, use dangerous_into_kernel_connection() instead"]
1048    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
1049        self.inner.dangerous_extract_secrets()
1050    }
1051
1052    /// Extract secrets and an [`KernelConnection`] object.
1053    ///
1054    /// This allows you use rustls to manage keys and then manage encryption and
1055    /// decryption yourself (e.g. for kTLS).
1056    ///
1057    /// Should be used with care as it exposes secret key material.
1058    ///
1059    /// See the [`crate::kernel`] documentations for details on prerequisites
1060    /// for calling this method.
1061    pub fn dangerous_into_kernel_connection(
1062        self,
1063    ) -> Result<(ExtractedSecrets, KernelConnection<ServerConnectionData>), Error> {
1064        self.inner
1065            .core
1066            .dangerous_into_kernel_connection()
1067    }
1068}
1069
1070impl Deref for UnbufferedServerConnection {
1071    type Target = UnbufferedConnectionCommon<ServerConnectionData>;
1072
1073    fn deref(&self) -> &Self::Target {
1074        &self.inner
1075    }
1076}
1077
1078impl DerefMut for UnbufferedServerConnection {
1079    fn deref_mut(&mut self) -> &mut Self::Target {
1080        &mut self.inner
1081    }
1082}
1083
1084impl UnbufferedConnectionCommon<ServerConnectionData> {
1085    pub(crate) fn pop_early_data(&mut self) -> Option<Vec<u8>> {
1086        self.core.side.early_data.pop()
1087    }
1088
1089    pub(crate) fn peek_early_data(&self) -> Option<&[u8]> {
1090        self.core.side.early_data.peek()
1091    }
1092}
1093
1094/// Represents a `ClientHello` message received through the [`Acceptor`].
1095///
1096/// Contains the state required to resume the connection through [`Accepted::into_connection()`].
1097#[cfg(feature = "std")]
1098pub struct Accepted {
1099    connection: ConnectionCommon<ServerConnectionData>,
1100    message: Message<'static>,
1101    sig_schemes: Vec<SignatureScheme>,
1102}
1103
1104#[cfg(feature = "std")]
1105impl Accepted {
1106    /// Get the [`ClientHello`] for this connection.
1107    pub fn client_hello(&self) -> ClientHello<'_> {
1108        let payload = Self::client_hello_payload(&self.message);
1109        let server_name = payload
1110            .server_name
1111            .as_ref()
1112            .and_then(ServerNamePayload::to_dns_name_normalized)
1113            .map(Cow::Owned);
1114        let ch = ClientHello {
1115            server_name,
1116            signature_schemes: &self.sig_schemes,
1117            alpn: payload.protocols.as_ref(),
1118            server_cert_types: payload
1119                .server_certificate_types
1120                .as_deref(),
1121            client_cert_types: payload
1122                .client_certificate_types
1123                .as_deref(),
1124            cipher_suites: &payload.cipher_suites,
1125            certificate_authorities: payload
1126                .certificate_authority_names
1127                .as_deref(),
1128            named_groups: payload.named_groups.as_deref(),
1129        };
1130
1131        trace!("Accepted::client_hello(): {ch:#?}");
1132        ch
1133    }
1134
1135    /// Convert the [`Accepted`] into a [`ServerConnection`].
1136    ///
1137    /// Takes the state returned from [`Acceptor::accept()`] as well as the [`ServerConfig`] that
1138    /// should be used for the session. Returns an error if configuration-dependent validation of
1139    /// the received `ClientHello` message fails.
1140    pub fn into_connection(
1141        mut self,
1142        config: Arc<ServerConfig>,
1143    ) -> Result<ServerConnection, (Error, AcceptedAlert)> {
1144        if let Err(err) = self
1145            .connection
1146            .set_max_fragment_size(config.max_fragment_size)
1147        {
1148            // We have a connection here, but it won't contain an alert since the error
1149            // is with the fragment size configured in the `ServerConfig`.
1150            return Err((err, AcceptedAlert::empty()));
1151        }
1152
1153        self.connection.enable_secret_extraction = config.enable_secret_extraction;
1154
1155        let state = hs::ExpectClientHello::new(config, ServerExtensionsInput::default());
1156        let mut cx = hs::ServerContext::from(&mut self.connection);
1157
1158        let input = ClientHelloInput {
1159            client_hello: Self::client_hello_payload(&self.message),
1160            message: &self.message,
1161            sig_schemes: self.sig_schemes,
1162        };
1163
1164        let new = match state.with_input(input, &mut cx) {
1165            Ok(new) => new,
1166            Err(err) => return Err((err, AcceptedAlert::from(self.connection))),
1167        };
1168
1169        self.connection.replace_state(new);
1170        Ok(ServerConnection {
1171            inner: self.connection,
1172        })
1173    }
1174
1175    fn client_hello_payload<'a>(message: &'a Message<'_>) -> &'a ClientHelloPayload {
1176        match &message.payload {
1177            crate::msgs::message::MessagePayload::Handshake { parsed, .. } => match &parsed.0 {
1178                crate::msgs::handshake::HandshakePayload::ClientHello(ch) => ch,
1179                _ => unreachable!(),
1180            },
1181            _ => unreachable!(),
1182        }
1183    }
1184}
1185
1186#[cfg(feature = "std")]
1187impl Debug for Accepted {
1188    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1189        f.debug_struct("Accepted").finish()
1190    }
1191}
1192
1193#[cfg(feature = "std")]
1194struct Accepting;
1195
1196#[cfg(feature = "std")]
1197impl State<ServerConnectionData> for Accepting {
1198    #[cfg_attr(coverage_nightly, coverage(off))]
1199    fn handle<'m>(
1200        self: Box<Self>,
1201        _cx: &mut hs::ServerContext<'_>,
1202        _m: Message<'m>,
1203    ) -> Result<Box<dyn State<ServerConnectionData>>, Error> {
1204        Err(Error::Unreachable("unreachable state"))
1205    }
1206}
1207
1208pub(super) enum EarlyDataState {
1209    New,
1210    Accepted {
1211        received: ChunkVecBuffer,
1212        left: usize,
1213    },
1214    Rejected,
1215}
1216
1217impl Default for EarlyDataState {
1218    fn default() -> Self {
1219        Self::New
1220    }
1221}
1222
1223impl EarlyDataState {
1224    pub(super) fn reject(&mut self) {
1225        *self = Self::Rejected;
1226    }
1227
1228    pub(super) fn accept(&mut self, max_size: usize) {
1229        *self = Self::Accepted {
1230            received: ChunkVecBuffer::new(Some(max_size)),
1231            left: max_size,
1232        };
1233    }
1234
1235    #[cfg(feature = "std")]
1236    fn was_accepted(&self) -> bool {
1237        matches!(self, Self::Accepted { .. })
1238    }
1239
1240    pub(super) fn was_rejected(&self) -> bool {
1241        matches!(self, Self::Rejected)
1242    }
1243
1244    fn peek(&self) -> Option<&[u8]> {
1245        match self {
1246            Self::Accepted { received, .. } => received.peek(),
1247            _ => None,
1248        }
1249    }
1250
1251    fn pop(&mut self) -> Option<Vec<u8>> {
1252        match self {
1253            Self::Accepted { received, .. } => received.pop(),
1254            _ => None,
1255        }
1256    }
1257
1258    #[cfg(feature = "std")]
1259    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1260        match self {
1261            Self::Accepted { received, .. } => received.read(buf),
1262            _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)),
1263        }
1264    }
1265
1266    pub(super) fn take_received_plaintext(&mut self, bytes: Payload<'_>) -> bool {
1267        let available = bytes.bytes().len();
1268        let Self::Accepted { received, left } = self else {
1269            return false;
1270        };
1271
1272        if received.apply_limit(available) != available || available > *left {
1273            return false;
1274        }
1275
1276        received.append(bytes.into_vec());
1277        *left -= available;
1278        true
1279    }
1280}
1281
1282impl Debug for EarlyDataState {
1283    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1284        match self {
1285            Self::New => write!(f, "EarlyDataState::New"),
1286            Self::Accepted { received, left } => write!(
1287                f,
1288                "EarlyDataState::Accepted {{ received: {}, left: {} }}",
1289                received.len(),
1290                left
1291            ),
1292            Self::Rejected => write!(f, "EarlyDataState::Rejected"),
1293        }
1294    }
1295}
1296
1297impl ConnectionCore<ServerConnectionData> {
1298    pub(crate) fn for_server(
1299        config: Arc<ServerConfig>,
1300        extra_exts: ServerExtensionsInput<'static>,
1301    ) -> Result<Self, Error> {
1302        let mut common = CommonState::new(Side::Server);
1303        common.set_max_fragment_size(config.max_fragment_size)?;
1304        common.enable_secret_extraction = config.enable_secret_extraction;
1305        common.fips = config.fips();
1306        Ok(Self::new(
1307            Box::new(hs::ExpectClientHello::new(config, extra_exts)),
1308            ServerConnectionData::default(),
1309            common,
1310        ))
1311    }
1312
1313    #[cfg(feature = "std")]
1314    pub(crate) fn reject_early_data(&mut self) {
1315        assert!(
1316            self.common_state.is_handshaking(),
1317            "cannot retroactively reject early data"
1318        );
1319        self.side.early_data.reject();
1320    }
1321}
1322
1323/// State associated with a server connection.
1324#[derive(Default, Debug)]
1325pub struct ServerConnectionData {
1326    pub(crate) sni: Option<DnsName<'static>>,
1327    pub(crate) received_resumption_data: Option<Vec<u8>>,
1328    pub(crate) resumption_data: Vec<u8>,
1329    pub(super) early_data: EarlyDataState,
1330}
1331
1332impl crate::conn::SideData for ServerConnectionData {}
1333
1334#[cfg(feature = "std")]
1335#[cfg(test)]
1336mod tests {
1337    use std::format;
1338
1339    use super::*;
1340
1341    // these branches not reachable externally, unless something else goes wrong.
1342    #[test]
1343    fn test_read_in_new_state() {
1344        assert_eq!(
1345            format!("{:?}", EarlyDataState::default().read(&mut [0u8; 5])),
1346            "Err(Kind(BrokenPipe))"
1347        );
1348    }
1349}