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