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