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