Skip to main content

rustls/server/
server_conn.rs

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