rustls/client/client_conn.rs
1use alloc::vec::Vec;
2use core::marker::PhantomData;
3use core::ops::{Deref, DerefMut};
4use core::{fmt, mem};
5
6use pki_types::{ServerName, UnixTime};
7
8use super::handy::NoClientSessionStorage;
9use super::hs::{self, ClientHelloInput};
10#[cfg(feature = "std")]
11use crate::WantsVerifier;
12use crate::builder::ConfigBuilder;
13use crate::client::{EchMode, EchStatus};
14use crate::common_state::{CommonState, Protocol, Side};
15use crate::conn::{ConnectionCore, UnbufferedConnectionCommon};
16use crate::crypto::{CryptoProvider, SupportedKxGroup};
17use crate::enums::{CipherSuite, ProtocolVersion, SignatureScheme};
18use crate::error::Error;
19use crate::kernel::KernelConnection;
20use crate::log::trace;
21use crate::msgs::enums::NamedGroup;
22use crate::msgs::handshake::ClientExtensionsInput;
23use crate::msgs::persist;
24use crate::suites::{ExtractedSecrets, SupportedCipherSuite};
25use crate::sync::Arc;
26#[cfg(feature = "std")]
27use crate::time_provider::DefaultTimeProvider;
28use crate::time_provider::TimeProvider;
29use crate::unbuffered::{EncryptError, TransmitTlsData};
30#[cfg(doc)]
31use crate::{DistinguishedName, crypto};
32use crate::{KeyLog, WantsVersions, compress, sign, verify, versions};
33
34/// A trait for the ability to store client session data, so that sessions
35/// can be resumed in future connections.
36///
37/// Generally all data in this interface should be treated as
38/// **highly sensitive**, containing enough key material to break all security
39/// of the corresponding session.
40///
41/// `set_`, `insert_`, `remove_` and `take_` operations are mutating; this isn't
42/// expressed in the type system to allow implementations freedom in
43/// how to achieve interior mutability. `Mutex` is a common choice.
44pub trait ClientSessionStore: fmt::Debug + Send + Sync {
45 /// Remember what `NamedGroup` the given server chose.
46 fn set_kx_hint(&self, server_name: ServerName<'static>, group: NamedGroup);
47
48 /// This should return the value most recently passed to `set_kx_hint`
49 /// for the given `server_name`.
50 ///
51 /// If `None` is returned, the caller chooses the first configured group,
52 /// and an extra round trip might happen if that choice is unsatisfactory
53 /// to the server.
54 fn kx_hint(&self, server_name: &ServerName<'_>) -> Option<NamedGroup>;
55
56 /// Remember a TLS1.2 session.
57 ///
58 /// At most one of these can be remembered at a time, per `server_name`.
59 fn set_tls12_session(
60 &self,
61 server_name: ServerName<'static>,
62 value: persist::Tls12ClientSessionValue,
63 );
64
65 /// Get the most recently saved TLS1.2 session for `server_name` provided to `set_tls12_session`.
66 fn tls12_session(
67 &self,
68 server_name: &ServerName<'_>,
69 ) -> Option<persist::Tls12ClientSessionValue>;
70
71 /// Remove and forget any saved TLS1.2 session for `server_name`.
72 fn remove_tls12_session(&self, server_name: &ServerName<'static>);
73
74 /// Remember a TLS1.3 ticket that might be retrieved later from `take_tls13_ticket`, allowing
75 /// resumption of this session.
76 ///
77 /// This can be called multiple times for a given session, allowing multiple independent tickets
78 /// to be valid at once. The number of times this is called is controlled by the server, so
79 /// implementations of this trait should apply a reasonable bound of how many items are stored
80 /// simultaneously.
81 fn insert_tls13_ticket(
82 &self,
83 server_name: ServerName<'static>,
84 value: persist::Tls13ClientSessionValue,
85 );
86
87 /// Return a TLS1.3 ticket previously provided to `add_tls13_ticket`.
88 ///
89 /// Implementations of this trait must return each value provided to `add_tls13_ticket` _at most once_.
90 fn take_tls13_ticket(
91 &self,
92 server_name: &ServerName<'static>,
93 ) -> Option<persist::Tls13ClientSessionValue>;
94}
95
96/// A trait for the ability to choose a certificate chain and
97/// private key for the purposes of client authentication.
98pub trait ResolvesClientCert: fmt::Debug + Send + Sync {
99 /// Resolve a client certificate chain/private key to use as the client's
100 /// identity.
101 ///
102 /// `root_hint_subjects` is an optional list of certificate authority
103 /// subject distinguished names that the client can use to help
104 /// decide on a client certificate the server is likely to accept. If
105 /// the list is empty, the client should send whatever certificate it
106 /// has. The hints are expected to be DER-encoded X.500 distinguished names,
107 /// per [RFC 5280 A.1]. See [`DistinguishedName`] for more information
108 /// on decoding with external crates like `x509-parser`.
109 ///
110 /// `sigschemes` is the list of the [`SignatureScheme`]s the server
111 /// supports.
112 ///
113 /// Return `None` to continue the handshake without any client
114 /// authentication. The server may reject the handshake later
115 /// if it requires authentication.
116 ///
117 /// [RFC 5280 A.1]: https://www.rfc-editor.org/rfc/rfc5280#appendix-A.1
118 fn resolve(
119 &self,
120 root_hint_subjects: &[&[u8]],
121 sigschemes: &[SignatureScheme],
122 ) -> Option<Arc<sign::CertifiedKey>>;
123
124 /// Return true if the client only supports raw public keys.
125 ///
126 /// See [RFC 7250](https://www.rfc-editor.org/rfc/rfc7250).
127 fn only_raw_public_keys(&self) -> bool {
128 false
129 }
130
131 /// Return true if any certificates at all are available.
132 fn has_certs(&self) -> bool;
133}
134
135/// Common configuration for (typically) all connections made by a program.
136///
137/// Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots
138/// from the operating system to add to the [`RootCertStore`] passed to `with_root_certificates()`
139/// (the rustls-native-certs crate is often used for this) may take on the order of a few hundred
140/// milliseconds.
141///
142/// These must be created via the [`ClientConfig::builder()`] or [`ClientConfig::builder_with_provider()`]
143/// function.
144///
145/// Note that using [`ConfigBuilder<ClientConfig, WantsVersions>::with_ech()`] will produce a common
146/// configuration specific to the provided [`crate::client::EchConfig`] that may not be appropriate
147/// for all connections made by the program. In this case the configuration should only be shared
148/// by connections intended for domains that offer the provided [`crate::client::EchConfig`] in
149/// their DNS zone.
150///
151/// # Defaults
152///
153/// * [`ClientConfig::max_fragment_size`]: the default is `None` (meaning 16kB).
154/// * [`ClientConfig::resumption`]: supports resumption with up to 256 server names, using session
155/// ids or tickets, with a max of eight tickets per server.
156/// * [`ClientConfig::alpn_protocols`]: the default is empty -- no ALPN protocol is negotiated.
157/// * [`ClientConfig::key_log`]: key material is not logged.
158/// * [`ClientConfig::cert_decompressors`]: depends on the crate features, see [`compress::default_cert_decompressors()`].
159/// * [`ClientConfig::cert_compressors`]: depends on the crate features, see [`compress::default_cert_compressors()`].
160/// * [`ClientConfig::cert_compression_cache`]: caches the most recently used 4 compressions
161///
162/// [`RootCertStore`]: crate::RootCertStore
163#[derive(Clone, Debug)]
164pub struct ClientConfig {
165 /// Which ALPN protocols we include in our client hello.
166 /// If empty, no ALPN extension is sent.
167 pub alpn_protocols: Vec<Vec<u8>>,
168
169 /// Whether to check the selected ALPN was offered.
170 ///
171 /// The default is true.
172 pub check_selected_alpn: bool,
173
174 /// How and when the client can resume a previous session.
175 ///
176 /// # Sharing `resumption` between `ClientConfig`s
177 /// In a program using many `ClientConfig`s it may improve resumption rates
178 /// (which has a significant impact on connection performance) if those
179 /// configs share a single `Resumption`.
180 ///
181 /// However, resumption is only allowed between two `ClientConfig`s if their
182 /// `client_auth_cert_resolver` (ie, potential client authentication credentials)
183 /// and `verifier` (ie, server certificate verification settings) are
184 /// the same (according to `Arc::ptr_eq`).
185 ///
186 /// To illustrate, imagine two `ClientConfig`s `A` and `B`. `A` fully validates
187 /// the server certificate, `B` does not. If `A` and `B` shared a resumption store,
188 /// it would be possible for a session originated by `B` to be inserted into the
189 /// store, and then resumed by `A`. This would give a false impression to the user
190 /// of `A` that the server certificate is fully validated.
191 pub resumption: Resumption,
192
193 /// The maximum size of plaintext input to be emitted in a single TLS record.
194 /// A value of None is equivalent to the [TLS maximum] of 16 kB.
195 ///
196 /// rustls enforces an arbitrary minimum of 32 bytes for this field.
197 /// Out of range values are reported as errors from [ClientConnection::new].
198 ///
199 /// Setting this value to a little less than the TCP MSS may improve latency
200 /// for stream-y workloads.
201 ///
202 /// [TLS maximum]: https://datatracker.ietf.org/doc/html/rfc8446#section-5.1
203 /// [ClientConnection::new]: crate::client::ClientConnection::new
204 pub max_fragment_size: Option<usize>,
205
206 /// How to decide what client auth certificate/keys to use.
207 pub client_auth_cert_resolver: Arc<dyn ResolvesClientCert>,
208
209 /// Whether to send the Server Name Indication (SNI) extension
210 /// during the client handshake.
211 ///
212 /// The default is true.
213 pub enable_sni: bool,
214
215 /// How to output key material for debugging. The default
216 /// does nothing.
217 pub key_log: Arc<dyn KeyLog>,
218
219 /// Allows traffic secrets to be extracted after the handshake,
220 /// e.g. for kTLS setup.
221 pub enable_secret_extraction: bool,
222
223 /// Whether to send data on the first flight ("early data") in
224 /// TLS 1.3 handshakes.
225 ///
226 /// The default is false.
227 pub enable_early_data: bool,
228
229 /// If set to `true`, requires the server to support the extended
230 /// master secret extraction method defined in [RFC 7627].
231 ///
232 /// The default is `true` if the `fips` crate feature is enabled,
233 /// `false` otherwise.
234 ///
235 /// It must be set to `true` to meet FIPS requirement mentioned in section
236 /// **D.Q Transition of the TLS 1.2 KDF to Support the Extended Master
237 /// Secret** from [FIPS 140-3 IG.pdf].
238 ///
239 /// [RFC 7627]: https://datatracker.ietf.org/doc/html/rfc7627
240 /// [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
241 #[cfg(feature = "tls12")]
242 pub require_ems: bool,
243
244 /// Provides the current system time
245 pub time_provider: Arc<dyn TimeProvider>,
246
247 /// Source of randomness and other crypto.
248 pub(super) provider: Arc<CryptoProvider>,
249
250 /// Supported versions, in no particular order. The default
251 /// is all supported versions.
252 pub(super) versions: versions::EnabledVersions,
253
254 /// How to verify the server certificate chain.
255 pub(super) verifier: Arc<dyn verify::ServerCertVerifier>,
256
257 /// How to decompress the server's certificate chain.
258 ///
259 /// If this is non-empty, the [RFC8779] certificate compression
260 /// extension is offered, and any compressed certificates are
261 /// transparently decompressed during the handshake.
262 ///
263 /// This only applies to TLS1.3 connections. It is ignored for
264 /// TLS1.2 connections.
265 ///
266 /// [RFC8779]: https://datatracker.ietf.org/doc/rfc8879/
267 pub cert_decompressors: Vec<&'static dyn compress::CertDecompressor>,
268
269 /// How to compress the client's certificate chain.
270 ///
271 /// If a server supports this extension, and advertises support
272 /// for one of the compression algorithms included here, the
273 /// client certificate will be compressed according to [RFC8779].
274 ///
275 /// This only applies to TLS1.3 connections. It is ignored for
276 /// TLS1.2 connections.
277 ///
278 /// [RFC8779]: https://datatracker.ietf.org/doc/rfc8879/
279 pub cert_compressors: Vec<&'static dyn compress::CertCompressor>,
280
281 /// Caching for compressed certificates.
282 ///
283 /// This is optional: [`compress::CompressionCache::Disabled`] gives
284 /// a cache that does no caching.
285 pub cert_compression_cache: Arc<compress::CompressionCache>,
286
287 /// How to offer Encrypted Client Hello (ECH). The default is to not offer ECH.
288 pub(super) ech_mode: Option<EchMode>,
289}
290
291impl ClientConfig {
292 /// Create a builder for a client configuration with
293 /// [the process-default `CryptoProvider`][CryptoProvider#using-the-per-process-default-cryptoprovider]
294 /// and safe protocol version defaults.
295 ///
296 /// For more information, see the [`ConfigBuilder`] documentation.
297 #[cfg(feature = "std")]
298 pub fn builder() -> ConfigBuilder<Self, WantsVerifier> {
299 Self::builder_with_protocol_versions(versions::DEFAULT_VERSIONS)
300 }
301
302 /// Create a builder for a client configuration with
303 /// [the process-default `CryptoProvider`][CryptoProvider#using-the-per-process-default-cryptoprovider]
304 /// and the provided protocol versions.
305 ///
306 /// Panics if
307 /// - the supported versions are not compatible with the provider (eg.
308 /// the combination of ciphersuites supported by the provider and supported
309 /// versions lead to zero cipher suites being usable),
310 /// - if a `CryptoProvider` cannot be resolved using a combination of
311 /// the crate features and process default.
312 ///
313 /// For more information, see the [`ConfigBuilder`] documentation.
314 #[cfg(feature = "std")]
315 pub fn builder_with_protocol_versions(
316 versions: &[&'static versions::SupportedProtocolVersion],
317 ) -> ConfigBuilder<Self, WantsVerifier> {
318 // Safety assumptions:
319 // 1. that the provider has been installed (explicitly or implicitly)
320 // 2. that the process-level default provider is usable with the supplied protocol versions.
321 Self::builder_with_provider(
322 CryptoProvider::get_default_or_install_from_crate_features().clone(),
323 )
324 .with_protocol_versions(versions)
325 .unwrap()
326 }
327
328 /// Create a builder for a client configuration with a specific [`CryptoProvider`].
329 ///
330 /// This will use the provider's configured ciphersuites. You must additionally choose
331 /// which protocol versions to enable, using `with_protocol_versions` or
332 /// `with_safe_default_protocol_versions` and handling the `Result` in case a protocol
333 /// version is not supported by the provider's ciphersuites.
334 ///
335 /// For more information, see the [`ConfigBuilder`] documentation.
336 #[cfg(feature = "std")]
337 pub fn builder_with_provider(
338 provider: Arc<CryptoProvider>,
339 ) -> ConfigBuilder<Self, WantsVersions> {
340 ConfigBuilder {
341 state: WantsVersions {},
342 provider,
343 time_provider: Arc::new(DefaultTimeProvider),
344 side: PhantomData,
345 }
346 }
347 /// Create a builder for a client configuration with no default implementation details.
348 ///
349 /// This API must be used by `no_std` users.
350 ///
351 /// You must provide a specific [`TimeProvider`].
352 ///
353 /// You must provide a specific [`CryptoProvider`].
354 ///
355 /// This will use the provider's configured ciphersuites. You must additionally choose
356 /// which protocol versions to enable, using `with_protocol_versions` or
357 /// `with_safe_default_protocol_versions` and handling the `Result` in case a protocol
358 /// version is not supported by the provider's ciphersuites.
359 ///
360 /// For more information, see the [`ConfigBuilder`] documentation.
361 pub fn builder_with_details(
362 provider: Arc<CryptoProvider>,
363 time_provider: Arc<dyn TimeProvider>,
364 ) -> ConfigBuilder<Self, WantsVersions> {
365 ConfigBuilder {
366 state: WantsVersions {},
367 provider,
368 time_provider,
369 side: PhantomData,
370 }
371 }
372
373 /// Return true if connections made with this `ClientConfig` will
374 /// operate in FIPS mode.
375 ///
376 /// This is different from [`CryptoProvider::fips()`]: [`CryptoProvider::fips()`]
377 /// is concerned only with cryptography, whereas this _also_ covers TLS-level
378 /// configuration that NIST recommends, as well as ECH HPKE suites if applicable.
379 pub fn fips(&self) -> bool {
380 let mut is_fips = self.provider.fips();
381
382 #[cfg(feature = "tls12")]
383 {
384 is_fips = is_fips && self.require_ems
385 }
386
387 if let Some(ech_mode) = &self.ech_mode {
388 is_fips = is_fips && ech_mode.fips();
389 }
390
391 is_fips
392 }
393
394 /// Return the crypto provider used to construct this client configuration.
395 pub fn crypto_provider(&self) -> &Arc<CryptoProvider> {
396 &self.provider
397 }
398
399 /// Access configuration options whose use is dangerous and requires
400 /// extra care.
401 pub fn dangerous(&mut self) -> danger::DangerousClientConfig<'_> {
402 danger::DangerousClientConfig { cfg: self }
403 }
404
405 pub(super) fn needs_key_share(&self) -> bool {
406 self.supports_version(ProtocolVersion::TLSv1_3)
407 }
408
409 /// We support a given TLS version if it's quoted in the configured
410 /// versions *and* at least one ciphersuite for this version is
411 /// also configured.
412 pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool {
413 self.versions.contains(v)
414 && self
415 .provider
416 .cipher_suites
417 .iter()
418 .any(|cs| cs.version().version == v)
419 }
420
421 #[cfg(feature = "std")]
422 pub(crate) fn supports_protocol(&self, proto: Protocol) -> bool {
423 self.provider
424 .cipher_suites
425 .iter()
426 .any(|cs| cs.usable_for_protocol(proto))
427 }
428
429 pub(super) fn find_cipher_suite(&self, suite: CipherSuite) -> Option<SupportedCipherSuite> {
430 self.provider
431 .cipher_suites
432 .iter()
433 .copied()
434 .find(|&scs| scs.suite() == suite)
435 }
436
437 pub(super) fn find_kx_group(
438 &self,
439 group: NamedGroup,
440 version: ProtocolVersion,
441 ) -> Option<&'static dyn SupportedKxGroup> {
442 self.provider
443 .kx_groups
444 .iter()
445 .copied()
446 .find(|skxg| skxg.usable_for_version(version) && skxg.name() == group)
447 }
448
449 pub(super) fn current_time(&self) -> Result<UnixTime, Error> {
450 self.time_provider
451 .current_time()
452 .ok_or(Error::FailedToGetCurrentTime)
453 }
454}
455
456/// Configuration for how/when a client is allowed to resume a previous session.
457#[derive(Clone, Debug)]
458pub struct Resumption {
459 /// How we store session data or tickets. The default is to use an in-memory
460 /// [super::handy::ClientSessionMemoryCache].
461 pub(super) store: Arc<dyn ClientSessionStore>,
462
463 /// What mechanism is used for resuming a TLS 1.2 session.
464 pub(super) tls12_resumption: Tls12Resumption,
465}
466
467impl Resumption {
468 /// Create a new `Resumption` that stores data for the given number of sessions in memory.
469 ///
470 /// This is the default `Resumption` choice, and enables resuming a TLS 1.2 session with
471 /// a session id or RFC 5077 ticket.
472 #[cfg(feature = "std")]
473 pub fn in_memory_sessions(num: usize) -> Self {
474 Self {
475 store: Arc::new(super::handy::ClientSessionMemoryCache::new(num)),
476 tls12_resumption: Tls12Resumption::SessionIdOrTickets,
477 }
478 }
479
480 /// Use a custom [`ClientSessionStore`] implementation to store sessions.
481 ///
482 /// By default, enables resuming a TLS 1.2 session with a session id or RFC 5077 ticket.
483 pub fn store(store: Arc<dyn ClientSessionStore>) -> Self {
484 Self {
485 store,
486 tls12_resumption: Tls12Resumption::SessionIdOrTickets,
487 }
488 }
489
490 /// Disable all use of session resumption.
491 pub fn disabled() -> Self {
492 Self {
493 store: Arc::new(NoClientSessionStorage),
494 tls12_resumption: Tls12Resumption::Disabled,
495 }
496 }
497
498 /// Configure whether TLS 1.2 sessions may be resumed, and by what mechanism.
499 ///
500 /// This is meaningless if you've disabled resumption entirely, which is the case in `no-std`
501 /// contexts.
502 pub fn tls12_resumption(mut self, tls12: Tls12Resumption) -> Self {
503 self.tls12_resumption = tls12;
504 self
505 }
506}
507
508impl Default for Resumption {
509 /// Create an in-memory session store resumption with up to 256 server names, allowing
510 /// a TLS 1.2 session to resume with a session id or RFC 5077 ticket.
511 fn default() -> Self {
512 #[cfg(feature = "std")]
513 let ret = Self::in_memory_sessions(256);
514
515 #[cfg(not(feature = "std"))]
516 let ret = Self::disabled();
517
518 ret
519 }
520}
521
522/// What mechanisms to support for resuming a TLS 1.2 session.
523#[derive(Clone, Copy, Debug, PartialEq)]
524pub enum Tls12Resumption {
525 /// Disable 1.2 resumption.
526 Disabled,
527 /// Support 1.2 resumption using session ids only.
528 SessionIdOnly,
529 /// Support 1.2 resumption using session ids or RFC 5077 tickets.
530 ///
531 /// See[^1] for why you might like to disable RFC 5077 by instead choosing the `SessionIdOnly`
532 /// option. Note that TLS 1.3 tickets do not have those issues.
533 ///
534 /// [^1]: <https://words.filippo.io/we-need-to-talk-about-session-tickets/>
535 SessionIdOrTickets,
536}
537
538/// Container for unsafe APIs
539pub(super) mod danger {
540 use super::ClientConfig;
541 use super::verify::ServerCertVerifier;
542 use crate::sync::Arc;
543
544 /// Accessor for dangerous configuration options.
545 #[derive(Debug)]
546 pub struct DangerousClientConfig<'a> {
547 /// The underlying ClientConfig
548 pub cfg: &'a mut ClientConfig,
549 }
550
551 impl DangerousClientConfig<'_> {
552 /// Overrides the default `ServerCertVerifier` with something else.
553 pub fn set_certificate_verifier(&mut self, verifier: Arc<dyn ServerCertVerifier>) {
554 self.cfg.verifier = verifier;
555 }
556 }
557}
558
559#[derive(Debug, PartialEq)]
560enum EarlyDataState {
561 Disabled,
562 Ready,
563 Accepted,
564 AcceptedFinished,
565 Rejected,
566}
567
568#[derive(Debug)]
569pub(super) struct EarlyData {
570 state: EarlyDataState,
571 left: usize,
572}
573
574impl EarlyData {
575 fn new() -> Self {
576 Self {
577 left: 0,
578 state: EarlyDataState::Disabled,
579 }
580 }
581
582 pub(super) fn is_enabled(&self) -> bool {
583 matches!(self.state, EarlyDataState::Ready | EarlyDataState::Accepted)
584 }
585
586 #[cfg(feature = "std")]
587 fn is_accepted(&self) -> bool {
588 matches!(
589 self.state,
590 EarlyDataState::Accepted | EarlyDataState::AcceptedFinished
591 )
592 }
593
594 pub(super) fn enable(&mut self, max_data: usize) {
595 assert_eq!(self.state, EarlyDataState::Disabled);
596 self.state = EarlyDataState::Ready;
597 self.left = max_data;
598 }
599
600 pub(super) fn rejected(&mut self) {
601 trace!("EarlyData rejected");
602 self.state = EarlyDataState::Rejected;
603 }
604
605 pub(super) fn accepted(&mut self) {
606 trace!("EarlyData accepted");
607 assert_eq!(self.state, EarlyDataState::Ready);
608 self.state = EarlyDataState::Accepted;
609 }
610
611 pub(super) fn finished(&mut self) {
612 trace!("EarlyData finished");
613 self.state = match self.state {
614 EarlyDataState::Accepted => EarlyDataState::AcceptedFinished,
615 _ => panic!("bad EarlyData state"),
616 }
617 }
618
619 fn check_write_opt(&mut self, sz: usize) -> Option<usize> {
620 match self.state {
621 EarlyDataState::Disabled => unreachable!(),
622 EarlyDataState::Ready | EarlyDataState::Accepted => {
623 let take = if self.left < sz {
624 mem::replace(&mut self.left, 0)
625 } else {
626 self.left -= sz;
627 sz
628 };
629
630 Some(take)
631 }
632 EarlyDataState::Rejected | EarlyDataState::AcceptedFinished => None,
633 }
634 }
635}
636
637#[cfg(feature = "std")]
638mod connection {
639 use alloc::vec::Vec;
640 use core::fmt;
641 use core::ops::{Deref, DerefMut};
642 use std::io;
643
644 use pki_types::ServerName;
645
646 use super::{ClientConnectionData, ClientExtensionsInput};
647 use crate::ClientConfig;
648 use crate::client::EchStatus;
649 use crate::common_state::Protocol;
650 use crate::conn::{ConnectionCommon, ConnectionCore};
651 use crate::error::Error;
652 use crate::suites::ExtractedSecrets;
653 use crate::sync::Arc;
654
655 /// Stub that implements io::Write and dispatches to `write_early_data`.
656 pub struct WriteEarlyData<'a> {
657 sess: &'a mut ClientConnection,
658 }
659
660 impl<'a> WriteEarlyData<'a> {
661 fn new(sess: &'a mut ClientConnection) -> Self {
662 WriteEarlyData { sess }
663 }
664
665 /// How many bytes you may send. Writes will become short
666 /// once this reaches zero.
667 pub fn bytes_left(&self) -> usize {
668 self.sess
669 .inner
670 .core
671 .data
672 .early_data
673 .bytes_left()
674 }
675 }
676
677 impl io::Write for WriteEarlyData<'_> {
678 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
679 self.sess.write_early_data(buf)
680 }
681
682 fn flush(&mut self) -> io::Result<()> {
683 Ok(())
684 }
685 }
686
687 impl super::EarlyData {
688 fn check_write(&mut self, sz: usize) -> io::Result<usize> {
689 self.check_write_opt(sz)
690 .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))
691 }
692
693 fn bytes_left(&self) -> usize {
694 self.left
695 }
696 }
697
698 /// This represents a single TLS client connection.
699 pub struct ClientConnection {
700 inner: ConnectionCommon<ClientConnectionData>,
701 }
702
703 impl fmt::Debug for ClientConnection {
704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705 f.debug_struct("ClientConnection")
706 .finish()
707 }
708 }
709
710 impl ClientConnection {
711 /// Make a new ClientConnection. `config` controls how
712 /// we behave in the TLS protocol, `name` is the
713 /// name of the server we want to talk to.
714 pub fn new(config: Arc<ClientConfig>, name: ServerName<'static>) -> Result<Self, Error> {
715 Self::new_with_alpn(config.clone(), name, config.alpn_protocols.clone())
716 }
717
718 /// Make a new ClientConnection with custom ALPN protocols.
719 pub fn new_with_alpn(
720 config: Arc<ClientConfig>,
721 name: ServerName<'static>,
722 alpn_protocols: Vec<Vec<u8>>,
723 ) -> Result<Self, Error> {
724 Ok(Self {
725 inner: ConnectionCommon::from(ConnectionCore::for_client(
726 config,
727 name,
728 ClientExtensionsInput::from_alpn(alpn_protocols),
729 Protocol::Tcp,
730 )?),
731 })
732 }
733 /// Returns an `io::Write` implementer you can write bytes to
734 /// to send TLS1.3 early data (a.k.a. "0-RTT data") to the server.
735 ///
736 /// This returns None in many circumstances when the capability to
737 /// send early data is not available, including but not limited to:
738 ///
739 /// - The server hasn't been talked to previously.
740 /// - The server does not support resumption.
741 /// - The server does not support early data.
742 /// - The resumption data for the server has expired.
743 ///
744 /// The server specifies a maximum amount of early data. You can
745 /// learn this limit through the returned object, and writes through
746 /// it will process only this many bytes.
747 ///
748 /// The server can choose not to accept any sent early data --
749 /// in this case the data is lost but the connection continues. You
750 /// can tell this happened using `is_early_data_accepted`.
751 pub fn early_data(&mut self) -> Option<WriteEarlyData<'_>> {
752 if self
753 .inner
754 .core
755 .data
756 .early_data
757 .is_enabled()
758 {
759 Some(WriteEarlyData::new(self))
760 } else {
761 None
762 }
763 }
764
765 /// Returns True if the server signalled it will process early data.
766 ///
767 /// If you sent early data and this returns false at the end of the
768 /// handshake then the server will not process the data. This
769 /// is not an error, but you may wish to resend the data.
770 pub fn is_early_data_accepted(&self) -> bool {
771 self.inner.core.is_early_data_accepted()
772 }
773
774 /// Extract secrets, so they can be used when configuring kTLS, for example.
775 /// Should be used with care as it exposes secret key material.
776 pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
777 self.inner.dangerous_extract_secrets()
778 }
779
780 /// Return the connection's Encrypted Client Hello (ECH) status.
781 pub fn ech_status(&self) -> EchStatus {
782 self.inner.core.data.ech_status
783 }
784
785 /// Returns the number of TLS1.3 tickets that have been received.
786 pub fn tls13_tickets_received(&self) -> u32 {
787 self.inner.tls13_tickets_received
788 }
789
790 /// Return true if the connection was made with a `ClientConfig` that is FIPS compatible.
791 ///
792 /// This is different from [`crate::crypto::CryptoProvider::fips()`]:
793 /// it is concerned only with cryptography, whereas this _also_ covers TLS-level
794 /// configuration that NIST recommends, as well as ECH HPKE suites if applicable.
795 pub fn fips(&self) -> bool {
796 self.inner.core.common_state.fips
797 }
798
799 fn write_early_data(&mut self, data: &[u8]) -> io::Result<usize> {
800 self.inner
801 .core
802 .data
803 .early_data
804 .check_write(data.len())
805 .map(|sz| {
806 self.inner
807 .send_early_plaintext(&data[..sz])
808 })
809 }
810 }
811
812 impl Deref for ClientConnection {
813 type Target = ConnectionCommon<ClientConnectionData>;
814
815 fn deref(&self) -> &Self::Target {
816 &self.inner
817 }
818 }
819
820 impl DerefMut for ClientConnection {
821 fn deref_mut(&mut self) -> &mut Self::Target {
822 &mut self.inner
823 }
824 }
825
826 #[doc(hidden)]
827 impl<'a> TryFrom<&'a mut crate::Connection> for &'a mut ClientConnection {
828 type Error = ();
829
830 fn try_from(value: &'a mut crate::Connection) -> Result<Self, Self::Error> {
831 use crate::Connection::*;
832 match value {
833 Client(conn) => Ok(conn),
834 Server(_) => Err(()),
835 }
836 }
837 }
838
839 impl From<ClientConnection> for crate::Connection {
840 fn from(conn: ClientConnection) -> Self {
841 Self::Client(conn)
842 }
843 }
844}
845#[cfg(feature = "std")]
846pub use connection::{ClientConnection, WriteEarlyData};
847
848impl ConnectionCore<ClientConnectionData> {
849 pub(crate) fn for_client(
850 config: Arc<ClientConfig>,
851 name: ServerName<'static>,
852 extra_exts: ClientExtensionsInput<'static>,
853 proto: Protocol,
854 ) -> Result<Self, Error> {
855 let mut common_state = CommonState::new(Side::Client);
856 common_state.set_max_fragment_size(config.max_fragment_size)?;
857 common_state.protocol = proto;
858 common_state.enable_secret_extraction = config.enable_secret_extraction;
859 common_state.fips = config.fips();
860 let mut data = ClientConnectionData::new();
861
862 let mut cx = hs::ClientContext {
863 common: &mut common_state,
864 data: &mut data,
865 // `start_handshake` won't produce plaintext
866 sendable_plaintext: None,
867 };
868
869 let input = ClientHelloInput::new(name, &extra_exts, &mut cx, config)?;
870 let state = input.start_handshake(extra_exts, &mut cx)?;
871 Ok(Self::new(state, data, common_state))
872 }
873
874 #[cfg(feature = "std")]
875 pub(crate) fn is_early_data_accepted(&self) -> bool {
876 self.data.early_data.is_accepted()
877 }
878}
879
880/// Unbuffered version of `ClientConnection`
881///
882/// See the [`crate::unbuffered`] module docs for more details
883pub struct UnbufferedClientConnection {
884 inner: UnbufferedConnectionCommon<ClientConnectionData>,
885}
886
887impl UnbufferedClientConnection {
888 /// Make a new ClientConnection. `config` controls how we behave in the TLS protocol, `name` is
889 /// the name of the server we want to talk to.
890 pub fn new(config: Arc<ClientConfig>, name: ServerName<'static>) -> Result<Self, Error> {
891 Self::new_with_extensions(
892 config.clone(),
893 name,
894 ClientExtensionsInput::from_alpn(config.alpn_protocols.clone()),
895 )
896 }
897
898 /// Make a new UnbufferedClientConnection with custom ALPN protocols.
899 pub fn new_with_alpn(
900 config: Arc<ClientConfig>,
901 name: ServerName<'static>,
902 alpn_protocols: Vec<Vec<u8>>,
903 ) -> Result<Self, Error> {
904 Self::new_with_extensions(
905 config,
906 name,
907 ClientExtensionsInput::from_alpn(alpn_protocols),
908 )
909 }
910
911 fn new_with_extensions(
912 config: Arc<ClientConfig>,
913 name: ServerName<'static>,
914 extensions: ClientExtensionsInput<'static>,
915 ) -> Result<Self, Error> {
916 Ok(Self {
917 inner: UnbufferedConnectionCommon::from(ConnectionCore::for_client(
918 config,
919 name,
920 extensions,
921 Protocol::Tcp,
922 )?),
923 })
924 }
925
926 /// Extract secrets, so they can be used when configuring kTLS, for example.
927 /// Should be used with care as it exposes secret key material.
928 #[deprecated = "dangerous_extract_secrets() does not support session tickets or \
929 key updates, use dangerous_into_kernel_connection() instead"]
930 pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
931 self.inner.dangerous_extract_secrets()
932 }
933
934 /// Extract secrets and a [`KernelConnection`] object.
935 ///
936 /// This allows you use rustls to manage keys and then manage encryption and
937 /// decryption yourself (e.g. for kTLS).
938 ///
939 /// Should be used with care as it exposes secret key material.
940 ///
941 /// See the [`crate::kernel`] documentations for details on prerequisites
942 /// for calling this method.
943 pub fn dangerous_into_kernel_connection(
944 self,
945 ) -> Result<(ExtractedSecrets, KernelConnection<ClientConnectionData>), Error> {
946 self.inner
947 .core
948 .dangerous_into_kernel_connection()
949 }
950
951 /// Returns the number of TLS1.3 tickets that have been received.
952 pub fn tls13_tickets_received(&self) -> u32 {
953 self.inner.tls13_tickets_received
954 }
955}
956
957impl Deref for UnbufferedClientConnection {
958 type Target = UnbufferedConnectionCommon<ClientConnectionData>;
959
960 fn deref(&self) -> &Self::Target {
961 &self.inner
962 }
963}
964
965impl DerefMut for UnbufferedClientConnection {
966 fn deref_mut(&mut self) -> &mut Self::Target {
967 &mut self.inner
968 }
969}
970
971impl TransmitTlsData<'_, ClientConnectionData> {
972 /// returns an adapter that allows encrypting early (RTT-0) data before transmitting the
973 /// already encoded TLS data
974 ///
975 /// IF allowed by the protocol
976 pub fn may_encrypt_early_data(&mut self) -> Option<MayEncryptEarlyData<'_>> {
977 if self
978 .conn
979 .core
980 .data
981 .early_data
982 .is_enabled()
983 {
984 Some(MayEncryptEarlyData { conn: self.conn })
985 } else {
986 None
987 }
988 }
989}
990
991/// Allows encrypting early (RTT-0) data
992pub struct MayEncryptEarlyData<'c> {
993 conn: &'c mut UnbufferedConnectionCommon<ClientConnectionData>,
994}
995
996impl MayEncryptEarlyData<'_> {
997 /// Encrypts `application_data` into the `outgoing_tls` buffer
998 ///
999 /// returns the number of bytes that were written into `outgoing_tls`, or an error if
1000 /// the provided buffer was too small. In the error case, `outgoing_tls` is not modified
1001 pub fn encrypt(
1002 &mut self,
1003 early_data: &[u8],
1004 outgoing_tls: &mut [u8],
1005 ) -> Result<usize, EarlyDataError> {
1006 let Some(allowed) = self
1007 .conn
1008 .core
1009 .data
1010 .early_data
1011 .check_write_opt(early_data.len())
1012 else {
1013 return Err(EarlyDataError::ExceededAllowedEarlyData);
1014 };
1015
1016 self.conn
1017 .core
1018 .common_state
1019 .write_plaintext(early_data[..allowed].into(), outgoing_tls)
1020 .map_err(|e| e.into())
1021 }
1022}
1023
1024/// Errors that may arise when encrypting early (RTT-0) data
1025#[derive(Debug)]
1026pub enum EarlyDataError {
1027 /// Cannot encrypt more early data due to imposed limits
1028 ExceededAllowedEarlyData,
1029 /// Encryption error
1030 Encrypt(EncryptError),
1031}
1032
1033impl From<EncryptError> for EarlyDataError {
1034 fn from(v: EncryptError) -> Self {
1035 Self::Encrypt(v)
1036 }
1037}
1038
1039impl fmt::Display for EarlyDataError {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041 match self {
1042 Self::ExceededAllowedEarlyData => f.write_str("cannot send any more early data"),
1043 Self::Encrypt(e) => fmt::Display::fmt(e, f),
1044 }
1045 }
1046}
1047
1048#[cfg(feature = "std")]
1049impl std::error::Error for EarlyDataError {}
1050
1051/// State associated with a client connection.
1052#[derive(Debug)]
1053pub struct ClientConnectionData {
1054 pub(super) early_data: EarlyData,
1055 pub(super) ech_status: EchStatus,
1056}
1057
1058impl ClientConnectionData {
1059 fn new() -> Self {
1060 Self {
1061 early_data: EarlyData::new(),
1062 ech_status: EchStatus::NotOffered,
1063 }
1064 }
1065}
1066
1067impl crate::conn::SideData for ClientConnectionData {}