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