rustls/server/server_conn.rs
1use crate::builder::ConfigBuilder;
2use crate::common_state::{CommonState, Context, Protocol, Side, State};
3use crate::conn::{ConnectionCommon, ConnectionCore};
4use crate::crypto::CryptoProvider;
5use crate::enums::{CipherSuite, ProtocolVersion, SignatureScheme};
6use crate::error::Error;
7#[cfg(feature = "logging")]
8use crate::log::trace;
9use crate::msgs::base::Payload;
10use crate::msgs::handshake::{ClientHelloPayload, ProtocolName, ServerExtension};
11use crate::msgs::message::Message;
12use crate::suites::ExtractedSecrets;
13use crate::vecbuf::ChunkVecBuffer;
14use crate::verify;
15use crate::versions;
16use crate::KeyLog;
17#[cfg(feature = "ring")]
18use crate::WantsVerifier;
19use crate::{sign, WantsVersions};
20
21use super::hs;
22
23use pki_types::DnsName;
24
25use alloc::boxed::Box;
26use alloc::sync::Arc;
27use alloc::vec::Vec;
28use core::fmt;
29use core::fmt::{Debug, Formatter};
30use core::marker::PhantomData;
31use core::ops::{Deref, DerefMut};
32use std::io;
33
34#[cfg(doc)]
35use crate::crypto;
36
37/// A trait for the ability to store server session data.
38///
39/// The keys and values are opaque.
40///
41/// Both the keys and values should be treated as
42/// **highly sensitive data**, containing enough key material
43/// to break all security of the corresponding sessions.
44///
45/// Implementations can be lossy (in other words, forgetting
46/// key/value pairs) without any negative security consequences.
47///
48/// However, note that `take` **must** reliably delete a returned
49/// value. If it does not, there may be security consequences.
50///
51/// `put` and `take` are mutating operations; this isn't expressed
52/// in the type system to allow implementations freedom in
53/// how to achieve interior mutability. `Mutex` is a common
54/// choice.
55pub trait StoresServerSessions: Debug + Send + Sync {
56 /// Store session secrets encoded in `value` against `key`,
57 /// overwrites any existing value against `key`. Returns `true`
58 /// if the value was stored.
59 fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool;
60
61 /// Find a value with the given `key`. Return it, or None
62 /// if it doesn't exist.
63 fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
64
65 /// Find a value with the given `key`. Return it and delete it;
66 /// or None if it doesn't exist.
67 fn take(&self, key: &[u8]) -> Option<Vec<u8>>;
68
69 /// Whether the store can cache another session. This is used to indicate to clients
70 /// whether their session can be resumed; the implementation is not required to remember
71 /// a session even if it returns `true` here.
72 fn can_cache(&self) -> bool;
73}
74
75/// A trait for the ability to encrypt and decrypt tickets.
76pub trait ProducesTickets: Debug + Send + Sync {
77 /// Returns true if this implementation will encrypt/decrypt
78 /// tickets. Should return false if this is a dummy
79 /// implementation: the server will not send the SessionTicket
80 /// extension and will not call the other functions.
81 fn enabled(&self) -> bool;
82
83 /// Returns the lifetime in seconds of tickets produced now.
84 /// The lifetime is provided as a hint to clients that the
85 /// ticket will not be useful after the given time.
86 ///
87 /// This lifetime must be implemented by key rolling and
88 /// erasure, *not* by storing a lifetime in the ticket.
89 ///
90 /// The objective is to limit damage to forward secrecy caused
91 /// by tickets, not just limiting their lifetime.
92 fn lifetime(&self) -> u32;
93
94 /// Encrypt and authenticate `plain`, returning the resulting
95 /// ticket. Return None if `plain` cannot be encrypted for
96 /// some reason: an empty ticket will be sent and the connection
97 /// will continue.
98 fn encrypt(&self, plain: &[u8]) -> Option<Vec<u8>>;
99
100 /// Decrypt `cipher`, validating its authenticity protection
101 /// and recovering the plaintext. `cipher` is fully attacker
102 /// controlled, so this decryption must be side-channel free,
103 /// panic-proof, and otherwise bullet-proof. If the decryption
104 /// fails, return None.
105 fn decrypt(&self, cipher: &[u8]) -> Option<Vec<u8>>;
106}
107
108/// How to choose a certificate chain and signing key for use
109/// in server authentication.
110///
111/// This is suitable when selecting a certificate does not require
112/// I/O or when the application is using blocking I/O anyhow.
113///
114/// For applications that use async I/O and need to do I/O to choose
115/// a certificate (for instance, fetching a certificate from a data store),
116/// the [`Acceptor`] interface is more suitable.
117pub trait ResolvesServerCert: Debug + Send + Sync {
118 /// Choose a certificate chain and matching key given simplified
119 /// ClientHello information.
120 ///
121 /// Return `None` to abort the handshake.
122 fn resolve(&self, client_hello: ClientHello) -> Option<Arc<sign::CertifiedKey>>;
123}
124
125/// A struct representing the received Client Hello
126pub struct ClientHello<'a> {
127 server_name: &'a Option<DnsName<'a>>,
128 signature_schemes: &'a [SignatureScheme],
129 alpn: Option<&'a Vec<ProtocolName>>,
130 cipher_suites: &'a [CipherSuite],
131}
132
133impl<'a> ClientHello<'a> {
134 /// Creates a new ClientHello
135 pub(super) fn new(
136 server_name: &'a Option<DnsName>,
137 signature_schemes: &'a [SignatureScheme],
138 alpn: Option<&'a Vec<ProtocolName>>,
139 cipher_suites: &'a [CipherSuite],
140 ) -> Self {
141 trace!("sni {:?}", server_name);
142 trace!("sig schemes {:?}", signature_schemes);
143 trace!("alpn protocols {:?}", alpn);
144 trace!("cipher suites {:?}", cipher_suites);
145
146 ClientHello {
147 server_name,
148 signature_schemes,
149 alpn,
150 cipher_suites,
151 }
152 }
153
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
201/// Common configuration for a set of server sessions.
202///
203/// Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots
204/// from the operating system to add to the [`RootCertStore`] passed to a `ClientCertVerifier`
205/// builder may take on the order of a few hundred milliseconds.
206///
207/// These must be created via the [`ServerConfig::builder()`] or [`ServerConfig::builder_with_provider()`]
208/// function.
209///
210/// # Defaults
211///
212/// * [`ServerConfig::max_fragment_size`]: the default is `None` (meaning 16kB).
213/// * [`ServerConfig::session_storage`]: the default stores 256 sessions in memory.
214/// * [`ServerConfig::alpn_protocols`]: the default is empty -- no ALPN protocol is negotiated.
215/// * [`ServerConfig::key_log`]: key material is not logged.
216/// * [`ServerConfig::send_tls13_tickets`]: 4 tickets are sent.
217///
218/// [`RootCertStore`]: crate::RootCertStore
219#[derive(Debug)]
220pub struct ServerConfig {
221 /// Source of randomness and other crypto.
222 pub(super) provider: Arc<CryptoProvider>,
223
224 /// Ignore the client's ciphersuite order. Instead,
225 /// choose the top ciphersuite in the server list
226 /// which is supported by the client.
227 pub ignore_client_order: bool,
228
229 /// The maximum size of plaintext input to be emitted in a single TLS record.
230 /// A value of None is equivalent to the [TLS maximum] of 16 kB.
231 ///
232 /// rustls enforces an arbitrary minimum of 32 bytes for this field.
233 /// Out of range values are reported as errors from [ServerConnection::new].
234 ///
235 /// Setting this value to a little less than the TCP MSS may improve latency
236 /// for stream-y workloads.
237 ///
238 /// [TLS maximum]: https://datatracker.ietf.org/doc/html/rfc8446#section-5.1
239 /// [ServerConnection::new]: crate::server::ServerConnection::new
240 pub max_fragment_size: Option<usize>,
241
242 /// How to store client sessions.
243 pub session_storage: Arc<dyn StoresServerSessions + Send + Sync>,
244
245 /// How to produce tickets.
246 pub ticketer: Arc<dyn ProducesTickets>,
247
248 /// How to choose a server cert and key. This is usually set by
249 /// [ConfigBuilder::with_single_cert] or [ConfigBuilder::with_cert_resolver].
250 /// For async applications, see also [Acceptor].
251 pub cert_resolver: Arc<dyn ResolvesServerCert>,
252
253 /// Protocol names we support, most preferred first.
254 /// If empty we don't do ALPN at all.
255 pub alpn_protocols: Vec<Vec<u8>>,
256
257 /// Supported protocol versions, in no particular order.
258 /// The default is all supported versions.
259 pub(super) versions: versions::EnabledVersions,
260
261 /// How to verify client certificates.
262 pub(super) verifier: Arc<dyn verify::ClientCertVerifier>,
263
264 /// How to output key material for debugging. The default
265 /// does nothing.
266 pub key_log: Arc<dyn KeyLog>,
267
268 /// Allows traffic secrets to be extracted after the handshake,
269 /// e.g. for kTLS setup.
270 pub enable_secret_extraction: bool,
271
272 /// Amount of early data to accept for sessions created by
273 /// this config. Specify 0 to disable early data. The
274 /// default is 0.
275 ///
276 /// Read the early data via [`ServerConnection::early_data`].
277 ///
278 /// The units for this are _both_ plaintext bytes, _and_ ciphertext
279 /// bytes, depending on whether the server accepts a client's early_data
280 /// or not. It is therefore recommended to include some slop in
281 /// this value to account for the unknown amount of ciphertext
282 /// expansion in the latter case.
283 pub max_early_data_size: u32,
284
285 /// Whether the server should send "0.5RTT" data. This means the server
286 /// sends data after its first flight of handshake messages, without
287 /// waiting for the client to complete the handshake.
288 ///
289 /// This can improve TTFB latency for either server-speaks-first protocols,
290 /// or client-speaks-first protocols when paired with "0RTT" data. This
291 /// comes at the cost of a subtle weakening of the normal handshake
292 /// integrity guarantees that TLS provides. Note that the initial
293 /// `ClientHello` is indirectly authenticated because it is included
294 /// in the transcript used to derive the keys used to encrypt the data.
295 ///
296 /// This only applies to TLS1.3 connections. TLS1.2 connections cannot
297 /// do this optimisation and this setting is ignored for them. It is
298 /// also ignored for TLS1.3 connections that even attempt client
299 /// authentication.
300 ///
301 /// This defaults to false. This means the first application data
302 /// sent by the server comes after receiving and validating the client's
303 /// handshake up to the `Finished` message. This is the safest option.
304 pub send_half_rtt_data: bool,
305
306 /// How many TLS1.3 tickets to send immediately after a successful
307 /// handshake.
308 ///
309 /// Because TLS1.3 tickets are single-use, this allows
310 /// a client to perform multiple resumptions.
311 ///
312 /// The default is 4.
313 ///
314 /// If this is 0, no tickets are sent and clients will not be able to
315 /// do any resumption.
316 pub send_tls13_tickets: usize,
317}
318
319// Avoid a `Clone` bound on `C`.
320impl Clone for ServerConfig {
321 fn clone(&self) -> Self {
322 Self {
323 provider: Arc::<CryptoProvider>::clone(&self.provider),
324 ignore_client_order: self.ignore_client_order,
325 max_fragment_size: self.max_fragment_size,
326 session_storage: Arc::clone(&self.session_storage),
327 ticketer: Arc::clone(&self.ticketer),
328 cert_resolver: Arc::clone(&self.cert_resolver),
329 alpn_protocols: self.alpn_protocols.clone(),
330 versions: self.versions,
331 verifier: Arc::clone(&self.verifier),
332 key_log: Arc::clone(&self.key_log),
333 enable_secret_extraction: self.enable_secret_extraction,
334 max_early_data_size: self.max_early_data_size,
335 send_half_rtt_data: self.send_half_rtt_data,
336 send_tls13_tickets: self.send_tls13_tickets,
337 }
338 }
339}
340
341impl ServerConfig {
342 /// Create a builder for a server configuration with the default
343 /// [`CryptoProvider`]: [`crypto::ring::default_provider`] and safe ciphersuite and protocol
344 /// defaults.
345 ///
346 /// For more information, see the [`ConfigBuilder`] documentation.
347 #[cfg(feature = "ring")]
348 pub fn builder() -> ConfigBuilder<Self, WantsVerifier> {
349 // Safety: we know the *ring* provider's ciphersuites are compatible with the safe default protocol versions.
350 Self::builder_with_provider(crate::crypto::ring::default_provider().into())
351 .with_safe_default_protocol_versions()
352 .unwrap()
353 }
354
355 /// Create a builder for a server configuration with the default
356 /// [`CryptoProvider`]: [`crypto::ring::default_provider`], safe ciphersuite defaults and
357 /// the provided protocol versions.
358 ///
359 /// Panics if provided an empty slice of supported versions.
360 ///
361 /// For more information, see the [`ConfigBuilder`] documentation.
362 #[cfg(feature = "ring")]
363 pub fn builder_with_protocol_versions(
364 versions: &[&'static versions::SupportedProtocolVersion],
365 ) -> ConfigBuilder<Self, WantsVerifier> {
366 // Safety: we know the *ring* provider's ciphersuites are compatible with all protocol version choices.
367 Self::builder_with_provider(crate::crypto::ring::default_provider().into())
368 .with_protocol_versions(versions)
369 .unwrap()
370 }
371
372 /// Create a builder for a server configuration with a specific [`CryptoProvider`].
373 ///
374 /// This will use the provider's configured ciphersuites. You must additionally choose
375 /// which protocol versions to enable, using `with_protocol_versions` or
376 /// `with_safe_default_protocol_versions` and handling the `Result` in case a protocol
377 /// version is not supported by the provider's ciphersuites.
378 ///
379 /// For more information, see the [`ConfigBuilder`] documentation.
380 pub fn builder_with_provider(
381 provider: Arc<CryptoProvider>,
382 ) -> ConfigBuilder<Self, WantsVersions> {
383 ConfigBuilder {
384 state: WantsVersions { provider },
385 side: PhantomData,
386 }
387 }
388
389 /// We support a given TLS version if it's quoted in the configured
390 /// versions *and* at least one ciphersuite for this version is
391 /// also configured.
392 pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool {
393 self.versions.contains(v)
394 && self
395 .provider
396 .cipher_suites
397 .iter()
398 .any(|cs| cs.version().version == v)
399 }
400
401 pub(crate) fn supports_protocol(&self, proto: Protocol) -> bool {
402 self.provider
403 .cipher_suites
404 .iter()
405 .any(|cs| cs.usable_for_protocol(proto))
406 }
407}
408
409/// Allows reading of early data in resumed TLS1.3 connections.
410///
411/// "Early data" is also known as "0-RTT data".
412///
413/// This structure implements [`std::io::Read`].
414pub struct ReadEarlyData<'a> {
415 early_data: &'a mut EarlyDataState,
416}
417
418impl<'a> ReadEarlyData<'a> {
419 fn new(early_data: &'a mut EarlyDataState) -> Self {
420 ReadEarlyData { early_data }
421 }
422}
423
424impl<'a> io::Read for ReadEarlyData<'a> {
425 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
426 self.early_data.read(buf)
427 }
428
429 #[cfg(read_buf)]
430 fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> {
431 self.early_data.read_buf(cursor)
432 }
433}
434
435/// This represents a single TLS server connection.
436///
437/// Send TLS-protected data to the peer using the `io::Write` trait implementation.
438/// Read data from the peer using the `io::Read` trait implementation.
439pub struct ServerConnection {
440 inner: ConnectionCommon<ServerConnectionData>,
441}
442
443impl ServerConnection {
444 /// Make a new ServerConnection. `config` controls how
445 /// we behave in the TLS protocol.
446 pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
447 let mut common = CommonState::new(Side::Server);
448 common.set_max_fragment_size(config.max_fragment_size)?;
449 common.enable_secret_extraction = config.enable_secret_extraction;
450 Ok(Self {
451 inner: ConnectionCommon::from(ConnectionCore::for_server(config, Vec::new())?),
452 })
453 }
454
455 /// Retrieves the server name, if any, used to select the certificate and
456 /// private key.
457 ///
458 /// This returns `None` until some time after the client's server name indication
459 /// (SNI) extension value is processed during the handshake. It will never be
460 /// `None` when the connection is ready to send or process application data,
461 /// unless the client does not support SNI.
462 ///
463 /// This is useful for application protocols that need to enforce that the
464 /// server name matches an application layer protocol hostname. For
465 /// example, HTTP/1.1 servers commonly expect the `Host:` header field of
466 /// every request on a connection to match the hostname in the SNI extension
467 /// when the client provides the SNI extension.
468 ///
469 /// The server name is also used to match sessions during session resumption.
470 pub fn server_name(&self) -> Option<&str> {
471 self.inner.core.get_sni_str()
472 }
473
474 /// Application-controlled portion of the resumption ticket supplied by the client, if any.
475 ///
476 /// Recovered from the prior session's `set_resumption_data`. Integrity is guaranteed by rustls.
477 ///
478 /// Returns `Some` iff a valid resumption ticket has been received from the client.
479 pub fn received_resumption_data(&self) -> Option<&[u8]> {
480 self.inner
481 .core
482 .data
483 .received_resumption_data
484 .as_ref()
485 .map(|x| &x[..])
486 }
487
488 /// Set the resumption data to embed in future resumption tickets supplied to the client.
489 ///
490 /// Defaults to the empty byte string. Must be less than 2^15 bytes to allow room for other
491 /// data. Should be called while `is_handshaking` returns true to ensure all transmitted
492 /// resumption tickets are affected.
493 ///
494 /// Integrity will be assured by rustls, but the data will be visible to the client. If secrecy
495 /// from the client is desired, encrypt the data separately.
496 pub fn set_resumption_data(&mut self, data: &[u8]) {
497 assert!(data.len() < 2usize.pow(15));
498 self.inner.core.data.resumption_data = data.into();
499 }
500
501 /// Explicitly discard early data, notifying the client
502 ///
503 /// Useful if invariants encoded in `received_resumption_data()` cannot be respected.
504 ///
505 /// Must be called while `is_handshaking` is true.
506 pub fn reject_early_data(&mut self) {
507 self.inner.core.reject_early_data()
508 }
509
510 /// Returns an `io::Read` implementer you can read bytes from that are
511 /// received from a client as TLS1.3 0RTT/"early" data, during the handshake.
512 ///
513 /// This returns `None` in many circumstances, such as :
514 ///
515 /// - Early data is disabled if [`ServerConfig::max_early_data_size`] is zero (the default).
516 /// - The session negotiated with the client is not TLS1.3.
517 /// - The client just doesn't support early data.
518 /// - The connection doesn't resume an existing session.
519 /// - The client hasn't sent a full ClientHello yet.
520 pub fn early_data(&mut self) -> Option<ReadEarlyData> {
521 let data = &mut self.inner.core.data;
522 if data.early_data.was_accepted() {
523 Some(ReadEarlyData::new(&mut data.early_data))
524 } else {
525 None
526 }
527 }
528
529 /// Extract secrets, so they can be used when configuring kTLS, for example.
530 /// Should be used with care as it exposes secret key material.
531 pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
532 self.inner.dangerous_extract_secrets()
533 }
534}
535
536impl Debug for ServerConnection {
537 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
538 f.debug_struct("ServerConnection")
539 .finish()
540 }
541}
542
543impl Deref for ServerConnection {
544 type Target = ConnectionCommon<ServerConnectionData>;
545
546 fn deref(&self) -> &Self::Target {
547 &self.inner
548 }
549}
550
551impl DerefMut for ServerConnection {
552 fn deref_mut(&mut self) -> &mut Self::Target {
553 &mut self.inner
554 }
555}
556
557impl From<ServerConnection> for crate::Connection {
558 fn from(conn: ServerConnection) -> Self {
559 Self::Server(conn)
560 }
561}
562
563/// Handle a server-side connection before configuration is available.
564///
565/// `Acceptor` allows the caller to choose a [`ServerConfig`] after reading
566/// the [`ClientHello`] of an incoming connection. This is useful for servers
567/// that choose different certificates or cipher suites based on the
568/// characteristics of the `ClientHello`. In particular it is useful for
569/// servers that need to do some I/O to load a certificate and its private key
570/// and don't want to use the blocking interface provided by
571/// [`ResolvesServerCert`].
572///
573/// Create an Acceptor with [`Acceptor::default()`].
574///
575/// # Example
576///
577/// ```no_run
578/// # #[cfg(feature = "ring")] {
579/// # fn choose_server_config(
580/// # _: rustls::server::ClientHello,
581/// # ) -> std::sync::Arc<rustls::ServerConfig> {
582/// # unimplemented!();
583/// # }
584/// # #[allow(unused_variables)]
585/// # fn main() {
586/// use rustls::server::{Acceptor, ServerConfig};
587/// let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
588/// for stream in listener.incoming() {
589/// let mut stream = stream.unwrap();
590/// let mut acceptor = Acceptor::default();
591/// let accepted = loop {
592/// acceptor.read_tls(&mut stream).unwrap();
593/// if let Some(accepted) = acceptor.accept().unwrap() {
594/// break accepted;
595/// }
596/// };
597///
598/// // For some user-defined choose_server_config:
599/// let config = choose_server_config(accepted.client_hello());
600/// let conn = accepted
601/// .into_connection(config)
602/// .unwrap();
603
604/// // Proceed with handling the ServerConnection.
605/// }
606/// # }
607/// # }
608/// ```
609pub struct Acceptor {
610 inner: Option<ConnectionCommon<ServerConnectionData>>,
611}
612
613impl Default for Acceptor {
614 /// Return an empty Acceptor, ready to receive bytes from a new client connection.
615 fn default() -> Self {
616 Self {
617 inner: Some(
618 ConnectionCore::new(
619 Box::new(Accepting),
620 ServerConnectionData::default(),
621 CommonState::new(Side::Server),
622 )
623 .into(),
624 ),
625 }
626 }
627}
628
629impl Acceptor {
630 /// Read TLS content from `rd`.
631 ///
632 /// Returns an error if this `Acceptor` has already yielded an [`Accepted`]. For more details,
633 /// refer to [`Connection::read_tls()`].
634 ///
635 /// [`Connection::read_tls()`]: crate::Connection::read_tls
636 pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
637 match &mut self.inner {
638 Some(conn) => conn.read_tls(rd),
639 None => Err(io::Error::new(
640 io::ErrorKind::Other,
641 "acceptor cannot read after successful acceptance",
642 )),
643 }
644 }
645
646 /// Check if a `ClientHello` message has been received.
647 ///
648 /// Returns `Ok(None)` if the complete `ClientHello` has not yet been received.
649 /// Do more I/O and then call this function again.
650 ///
651 /// Returns `Ok(Some(accepted))` if the connection has been accepted. Call
652 /// `accepted.into_connection()` to continue. Do not call this function again.
653 ///
654 /// Returns `Err(err)` if an error occurred. Do not call this function again.
655 pub fn accept(&mut self) -> Result<Option<Accepted>, Error> {
656 let mut connection = match self.inner.take() {
657 Some(conn) => conn,
658 None => {
659 return Err(Error::General("Acceptor polled after completion".into()));
660 }
661 };
662
663 let message = match connection.first_handshake_message()? {
664 Some(msg) => msg,
665 None => {
666 self.inner = Some(connection);
667 return Ok(None);
668 }
669 };
670
671 let (_, sig_schemes) =
672 hs::process_client_hello(&message, false, &mut Context::from(&mut connection))?;
673
674 Ok(Some(Accepted {
675 connection,
676 message,
677 sig_schemes,
678 }))
679 }
680}
681
682/// Represents a `ClientHello` message received through the [`Acceptor`].
683///
684/// Contains the state required to resume the connection through [`Accepted::into_connection()`].
685pub struct Accepted {
686 connection: ConnectionCommon<ServerConnectionData>,
687 message: Message,
688 sig_schemes: Vec<SignatureScheme>,
689}
690
691impl Accepted {
692 /// Get the [`ClientHello`] for this connection.
693 pub fn client_hello(&self) -> ClientHello<'_> {
694 let payload = Self::client_hello_payload(&self.message);
695 ClientHello::new(
696 &self.connection.core.data.sni,
697 &self.sig_schemes,
698 payload.get_alpn_extension(),
699 &payload.cipher_suites,
700 )
701 }
702
703 /// Convert the [`Accepted`] into a [`ServerConnection`].
704 ///
705 /// Takes the state returned from [`Acceptor::accept()`] as well as the [`ServerConfig`] and
706 /// [`sign::CertifiedKey`] that should be used for the session. Returns an error if
707 /// configuration-dependent validation of the received `ClientHello` message fails.
708 pub fn into_connection(mut self, config: Arc<ServerConfig>) -> Result<ServerConnection, Error> {
709 self.connection
710 .set_max_fragment_size(config.max_fragment_size)?;
711
712 self.connection.enable_secret_extraction = config.enable_secret_extraction;
713
714 let state = hs::ExpectClientHello::new(config, Vec::new());
715 let mut cx = hs::ServerContext::from(&mut self.connection);
716
717 let new = state.with_certified_key(
718 self.sig_schemes,
719 Self::client_hello_payload(&self.message),
720 &self.message,
721 &mut cx,
722 )?;
723
724 self.connection.replace_state(new);
725 Ok(ServerConnection {
726 inner: self.connection,
727 })
728 }
729
730 fn client_hello_payload(message: &Message) -> &ClientHelloPayload {
731 match &message.payload {
732 crate::msgs::message::MessagePayload::Handshake { parsed, .. } => match &parsed.payload
733 {
734 crate::msgs::handshake::HandshakePayload::ClientHello(ch) => ch,
735 _ => unreachable!(),
736 },
737 _ => unreachable!(),
738 }
739 }
740}
741
742struct Accepting;
743
744impl State<ServerConnectionData> for Accepting {
745 fn handle(
746 self: Box<Self>,
747 _cx: &mut hs::ServerContext<'_>,
748 _m: Message,
749 ) -> Result<Box<dyn State<ServerConnectionData>>, Error> {
750 Err(Error::General("unreachable state".into()))
751 }
752}
753
754pub(super) enum EarlyDataState {
755 New,
756 Accepted(ChunkVecBuffer),
757 Rejected,
758}
759
760impl Default for EarlyDataState {
761 fn default() -> Self {
762 Self::New
763 }
764}
765
766impl EarlyDataState {
767 pub(super) fn reject(&mut self) {
768 *self = Self::Rejected;
769 }
770
771 pub(super) fn accept(&mut self, max_size: usize) {
772 *self = Self::Accepted(ChunkVecBuffer::new(Some(max_size)));
773 }
774
775 fn was_accepted(&self) -> bool {
776 matches!(self, Self::Accepted(_))
777 }
778
779 pub(super) fn was_rejected(&self) -> bool {
780 matches!(self, Self::Rejected)
781 }
782
783 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
784 match self {
785 Self::Accepted(ref mut received) => received.read(buf),
786 _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)),
787 }
788 }
789
790 #[cfg(read_buf)]
791 fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> {
792 match self {
793 Self::Accepted(ref mut received) => received.read_buf(cursor),
794 _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)),
795 }
796 }
797
798 pub(super) fn take_received_plaintext(&mut self, bytes: Payload) -> bool {
799 let available = bytes.0.len();
800 match self {
801 Self::Accepted(ref mut received) if received.apply_limit(available) == available => {
802 received.append(bytes.0);
803 true
804 }
805 _ => false,
806 }
807 }
808}
809
810impl Debug for EarlyDataState {
811 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
812 match self {
813 Self::New => write!(f, "EarlyDataState::New"),
814 Self::Accepted(buf) => write!(f, "EarlyDataState::Accepted({})", buf.len()),
815 Self::Rejected => write!(f, "EarlyDataState::Rejected"),
816 }
817 }
818}
819
820impl ConnectionCore<ServerConnectionData> {
821 pub(crate) fn for_server(
822 config: Arc<ServerConfig>,
823 extra_exts: Vec<ServerExtension>,
824 ) -> Result<Self, Error> {
825 let mut common = CommonState::new(Side::Server);
826 common.set_max_fragment_size(config.max_fragment_size)?;
827 common.enable_secret_extraction = config.enable_secret_extraction;
828 Ok(Self::new(
829 Box::new(hs::ExpectClientHello::new(config, extra_exts)),
830 ServerConnectionData::default(),
831 common,
832 ))
833 }
834
835 pub(crate) fn reject_early_data(&mut self) {
836 assert!(
837 self.common_state.is_handshaking(),
838 "cannot retroactively reject early data"
839 );
840 self.data.early_data.reject();
841 }
842
843 pub(crate) fn get_sni_str(&self) -> Option<&str> {
844 self.data.get_sni_str()
845 }
846}
847
848/// State associated with a server connection.
849#[derive(Default, Debug)]
850pub struct ServerConnectionData {
851 pub(super) sni: Option<DnsName<'static>>,
852 pub(super) received_resumption_data: Option<Vec<u8>>,
853 pub(super) resumption_data: Vec<u8>,
854 pub(super) early_data: EarlyDataState,
855}
856
857impl ServerConnectionData {
858 pub(super) fn get_sni_str(&self) -> Option<&str> {
859 self.sni.as_ref().map(AsRef::as_ref)
860 }
861}
862
863impl crate::conn::SideData for ServerConnectionData {}
864
865#[cfg(test)]
866mod tests {
867 use super::*;
868 use std::format;
869
870 // these branches not reachable externally, unless something else goes wrong.
871 #[test]
872 fn test_read_in_new_state() {
873 assert_eq!(
874 format!("{:?}", EarlyDataState::default().read(&mut [0u8; 5])),
875 "Err(Kind(BrokenPipe))"
876 );
877 }
878
879 #[cfg(read_buf)]
880 #[test]
881 fn test_read_buf_in_new_state() {
882 use core::io::BorrowedBuf;
883
884 let mut buf = [0u8; 5];
885 let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into();
886 assert_eq!(
887 format!("{:?}", EarlyDataState::default().read_buf(buf.unfilled())),
888 "Err(Kind(BrokenPipe))"
889 );
890 }
891}