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