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