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