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