rustls/server/
server_conn.rs

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