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