rustls/client/
tls13.rs

1use alloc::boxed::Box;
2use alloc::vec;
3use alloc::vec::Vec;
4
5use pki_types::ServerName;
6use subtle::ConstantTimeEq;
7
8use super::client_conn::ClientConnectionData;
9use super::hs::{ClientContext, ClientHelloInput, ClientSessionValue};
10use crate::check::inappropriate_handshake_message;
11use crate::client::common::{ClientAuthDetails, ClientHelloDetails, ServerCertDetails};
12use crate::client::ech::{self, EchState, EchStatus};
13use crate::client::{ClientConfig, ClientSessionStore, hs};
14use crate::common_state::{
15    CommonState, HandshakeFlightTls13, HandshakeKind, KxState, Protocol, Side, State,
16};
17use crate::conn::ConnectionRandoms;
18use crate::conn::kernel::{Direction, KernelContext, KernelState};
19use crate::crypto::hash::Hash;
20use crate::crypto::{ActiveKeyExchange, SharedSecret};
21use crate::enums::{
22    AlertDescription, ContentType, HandshakeType, ProtocolVersion, SignatureScheme,
23};
24use crate::error::{Error, InvalidMessage, PeerIncompatible, PeerMisbehaved};
25use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
26use crate::log::{debug, trace, warn};
27use crate::msgs::base::{Payload, PayloadU8};
28use crate::msgs::ccs::ChangeCipherSpecPayload;
29use crate::msgs::codec::{Codec, Reader};
30use crate::msgs::enums::{ExtensionType, KeyUpdateRequest};
31use crate::msgs::handshake::{
32    CERTIFICATE_MAX_SIZE_LIMIT, CertificatePayloadTls13, ClientExtensions, EchConfigPayload,
33    HandshakeMessagePayload, HandshakePayload, KeyShareEntry, NewSessionTicketPayloadTls13,
34    PresharedKeyBinder, PresharedKeyIdentity, PresharedKeyOffer, ServerExtensions,
35    ServerHelloPayload,
36};
37use crate::msgs::message::{Message, MessagePayload};
38use crate::msgs::persist::{self, Retrieved};
39use crate::sign::{CertifiedKey, Signer};
40use crate::suites::PartiallyExtractedSecrets;
41use crate::sync::Arc;
42use crate::tls13::key_schedule::{
43    KeyScheduleEarly, KeyScheduleHandshake, KeySchedulePreHandshake, KeyScheduleResumption,
44    KeyScheduleTraffic,
45};
46use crate::tls13::{
47    Tls13CipherSuite, construct_client_verify_message, construct_server_verify_message,
48};
49use crate::verify::{self, DigitallySignedStruct};
50use crate::{ConnectionTrafficSecrets, KeyLog, compress, crypto};
51
52// Extensions we expect in plaintext in the ServerHello.
53static ALLOWED_PLAINTEXT_EXTS: &[ExtensionType] = &[
54    ExtensionType::KeyShare,
55    ExtensionType::PreSharedKey,
56    ExtensionType::SupportedVersions,
57];
58
59// Only the intersection of things we offer, and those disallowed
60// in TLS1.3
61static DISALLOWED_TLS13_EXTS: &[ExtensionType] = &[
62    ExtensionType::ECPointFormats,
63    ExtensionType::SessionTicket,
64    ExtensionType::RenegotiationInfo,
65    ExtensionType::ExtendedMasterSecret,
66];
67
68/// `early_data_key_schedule` is `Some` if we sent the
69/// "early_data" extension to the server.
70pub(super) fn handle_server_hello(
71    cx: &mut ClientContext<'_>,
72    server_hello: &ServerHelloPayload,
73    mut randoms: ConnectionRandoms,
74    suite: &'static Tls13CipherSuite,
75    mut transcript: HandshakeHash,
76    early_data_key_schedule: Option<KeyScheduleEarly>,
77    our_key_share: Box<dyn ActiveKeyExchange>,
78    server_hello_msg: &Message<'_>,
79    ech_state: Option<EchState>,
80    input: ClientHelloInput,
81) -> hs::NextStateOrError<'static> {
82    validate_server_hello(cx.common, server_hello)?;
83
84    let their_key_share = server_hello
85        .key_share
86        .as_ref()
87        .ok_or_else(|| {
88            cx.common.send_fatal_alert(
89                AlertDescription::MissingExtension,
90                PeerMisbehaved::MissingKeyShare,
91            )
92        })?;
93
94    let ClientHelloInput {
95        config,
96        resuming,
97        mut sent_tls13_fake_ccs,
98        mut hello,
99        server_name,
100        ..
101    } = input;
102
103    let mut resuming_session = match resuming {
104        Some(Retrieved {
105            value: ClientSessionValue::Tls13(value),
106            ..
107        }) => Some(value),
108        _ => None,
109    };
110
111    let our_key_share = KeyExchangeChoice::new(&config, cx, our_key_share, their_key_share)
112        .map_err(|_| {
113            cx.common.send_fatal_alert(
114                AlertDescription::IllegalParameter,
115                PeerMisbehaved::WrongGroupForKeyShare,
116            )
117        })?;
118
119    let key_schedule_pre_handshake = match (server_hello.preshared_key, early_data_key_schedule) {
120        (Some(selected_psk), Some(early_key_schedule)) => {
121            match &resuming_session {
122                Some(resuming) => {
123                    let Some(resuming_suite) = suite.can_resume_from(resuming.suite()) else {
124                        return Err({
125                            cx.common.send_fatal_alert(
126                                AlertDescription::IllegalParameter,
127                                PeerMisbehaved::ResumptionOfferedWithIncompatibleCipherSuite,
128                            )
129                        });
130                    };
131
132                    // If the server varies the suite here, we will have encrypted early data with
133                    // the wrong suite.
134                    if cx.data.early_data.is_enabled() && resuming_suite != suite {
135                        return Err({
136                            cx.common.send_fatal_alert(
137                                AlertDescription::IllegalParameter,
138                                PeerMisbehaved::EarlyDataOfferedWithVariedCipherSuite,
139                            )
140                        });
141                    }
142
143                    if selected_psk != 0 {
144                        return Err({
145                            cx.common.send_fatal_alert(
146                                AlertDescription::IllegalParameter,
147                                PeerMisbehaved::SelectedInvalidPsk,
148                            )
149                        });
150                    }
151
152                    debug!("Resuming using PSK");
153                    // The key schedule has been initialized and set in fill_in_psk_binder()
154                }
155                _ => {
156                    return Err(PeerMisbehaved::SelectedUnofferedPsk.into());
157                }
158            }
159            KeySchedulePreHandshake::from(early_key_schedule)
160        }
161        _ => {
162            debug!("Not resuming");
163            // Discard the early data key schedule.
164            cx.data.early_data.rejected();
165            cx.common.early_traffic = false;
166            resuming_session.take();
167            KeySchedulePreHandshake::new(suite)
168        }
169    };
170
171    cx.common.kx_state.complete();
172    let shared_secret = our_key_share
173        .complete(&their_key_share.payload.0)
174        .map_err(|err| {
175            cx.common
176                .send_fatal_alert(AlertDescription::IllegalParameter, err)
177        })?;
178
179    let mut key_schedule = key_schedule_pre_handshake.into_handshake(shared_secret);
180
181    // If we have ECH state, check that the server accepted our offer.
182    if let Some(ech_state) = ech_state {
183        let Message {
184            payload:
185                MessagePayload::Handshake {
186                    encoded: server_hello_encoded,
187                    ..
188                },
189            ..
190        } = &server_hello_msg
191        else {
192            unreachable!("ServerHello is a handshake message");
193        };
194        cx.data.ech_status = match ech_state.confirm_acceptance(
195            &mut key_schedule,
196            server_hello,
197            server_hello_encoded,
198            suite.common.hash_provider,
199        )? {
200            // The server accepted our ECH offer, so complete the inner transcript with the
201            // server hello message, and switch the relevant state to the copies for the
202            // inner client hello.
203            Some(mut accepted) => {
204                accepted
205                    .transcript
206                    .add_message(server_hello_msg);
207                transcript = accepted.transcript;
208                randoms.client = accepted.random.0;
209                hello.sent_extensions = accepted.sent_extensions;
210                EchStatus::Accepted
211            }
212            // The server rejected our ECH offer.
213            None => EchStatus::Rejected,
214        };
215    }
216
217    // Remember what KX group the server liked for next time.
218    config
219        .resumption
220        .store
221        .set_kx_hint(server_name.clone(), their_key_share.group);
222
223    // If we change keying when a subsequent handshake message is being joined,
224    // the two halves will have different record layer protections.  Disallow this.
225    cx.common.check_aligned_handshake()?;
226
227    let hash_at_client_recvd_server_hello = transcript.current_hash();
228    let key_schedule = key_schedule.derive_client_handshake_secrets(
229        cx.data.early_data.is_enabled(),
230        hash_at_client_recvd_server_hello,
231        suite,
232        &*config.key_log,
233        &randoms.client,
234        cx.common,
235    );
236
237    emit_fake_ccs(&mut sent_tls13_fake_ccs, cx.common);
238
239    Ok(Box::new(ExpectEncryptedExtensions {
240        config,
241        resuming_session,
242        server_name,
243        randoms,
244        suite,
245        transcript,
246        key_schedule,
247        hello,
248    }))
249}
250
251enum KeyExchangeChoice {
252    Whole(Box<dyn ActiveKeyExchange>),
253    Component(Box<dyn ActiveKeyExchange>),
254}
255
256impl KeyExchangeChoice {
257    /// Decide between `our_key_share` or `our_key_share.hybrid_component()`
258    /// based on the selection of the server expressed in `their_key_share`.
259    fn new(
260        config: &Arc<ClientConfig>,
261        cx: &mut ClientContext<'_>,
262        our_key_share: Box<dyn ActiveKeyExchange>,
263        their_key_share: &KeyShareEntry,
264    ) -> Result<Self, ()> {
265        if our_key_share.group() == their_key_share.group {
266            return Ok(Self::Whole(our_key_share));
267        }
268
269        let (component_group, _) = our_key_share
270            .hybrid_component()
271            .ok_or(())?;
272
273        if component_group != their_key_share.group {
274            return Err(());
275        }
276
277        // correct the record for the benefit of accuracy of
278        // `negotiated_key_exchange_group()`
279        let actual_skxg = config
280            .find_kx_group(component_group, ProtocolVersion::TLSv1_3)
281            .ok_or(())?;
282        cx.common.kx_state = KxState::Start(actual_skxg);
283
284        Ok(Self::Component(our_key_share))
285    }
286
287    fn complete(self, peer_pub_key: &[u8]) -> Result<SharedSecret, Error> {
288        match self {
289            Self::Whole(akx) => akx.complete(peer_pub_key),
290            Self::Component(akx) => akx.complete_hybrid_component(peer_pub_key),
291        }
292    }
293}
294
295fn validate_server_hello(
296    common: &mut CommonState,
297    server_hello: &ServerHelloPayload,
298) -> Result<(), Error> {
299    if !server_hello.only_contains(ALLOWED_PLAINTEXT_EXTS) {
300        return Err(common.send_fatal_alert(
301            AlertDescription::UnsupportedExtension,
302            PeerMisbehaved::UnexpectedCleartextExtension,
303        ));
304    }
305
306    Ok(())
307}
308
309pub(super) fn initial_key_share(
310    config: &ClientConfig,
311    server_name: &ServerName<'_>,
312    kx_state: &mut KxState,
313) -> Result<Box<dyn ActiveKeyExchange>, Error> {
314    let group = config
315        .resumption
316        .store
317        .kx_hint(server_name)
318        .and_then(|group_name| config.find_kx_group(group_name, ProtocolVersion::TLSv1_3))
319        .unwrap_or_else(|| {
320            config
321                .provider
322                .kx_groups
323                .iter()
324                .copied()
325                .next()
326                .expect("No kx groups configured")
327        });
328
329    *kx_state = KxState::Start(group);
330    group.start()
331}
332
333/// This implements the horrifying TLS1.3 hack where PSK binders have a
334/// data dependency on the message they are contained within.
335pub(super) fn fill_in_psk_binder(
336    resuming: &persist::Tls13ClientSessionValue,
337    transcript: &HandshakeHashBuffer,
338    hmp: &mut HandshakeMessagePayload<'_>,
339) -> KeyScheduleEarly {
340    // We need to know the hash function of the suite we're trying to resume into.
341    let suite = resuming.suite();
342    let suite_hash = suite.common.hash_provider;
343
344    // The binder is calculated over the clienthello, but doesn't include itself or its
345    // length, or the length of its container.
346    let binder_plaintext = hmp.encoding_for_binder_signing();
347    let handshake_hash = transcript.hash_given(suite_hash, &binder_plaintext);
348
349    // Run a fake key_schedule to simulate what the server will do if it chooses
350    // to resume.
351    let key_schedule = KeyScheduleEarly::new(suite, resuming.secret());
352    let real_binder = key_schedule.resumption_psk_binder_key_and_sign_verify_data(&handshake_hash);
353
354    if let HandshakePayload::ClientHello(ch) = &mut hmp.0 {
355        if let Some(PresharedKeyOffer {
356            binders,
357            identities,
358        }) = &mut ch.preshared_key_offer
359        {
360            // the caller of this function must have set up the desired identity, and a
361            // matching (dummy) binder; or else the binder we compute here will be incorrect.
362            // See `prepare_resumption()`.
363            debug_assert_eq!(identities.len(), 1);
364            debug_assert_eq!(binders.len(), 1);
365            debug_assert_eq!(binders[0].as_ref().len(), real_binder.as_ref().len());
366            binders[0] = PresharedKeyBinder::from(real_binder.as_ref().to_vec());
367        }
368    };
369
370    key_schedule
371}
372
373pub(super) fn prepare_resumption(
374    config: &ClientConfig,
375    cx: &mut ClientContext<'_>,
376    resuming_session: &Retrieved<&persist::Tls13ClientSessionValue>,
377    exts: &mut ClientExtensions<'_>,
378    doing_retry: bool,
379) {
380    let resuming_suite = resuming_session.suite();
381    cx.common.suite = Some(resuming_suite.into());
382    // The EarlyData extension MUST be supplied together with the
383    // PreSharedKey extension.
384    let max_early_data_size = resuming_session.max_early_data_size();
385    if config.enable_early_data && max_early_data_size > 0 && !doing_retry {
386        cx.data
387            .early_data
388            .enable(max_early_data_size as usize);
389        exts.early_data_request = Some(());
390    }
391
392    // Finally, and only for TLS1.3 with a ticket resumption, include a binder
393    // for our ticket.  This must go last.
394    //
395    // Include an empty binder. It gets filled in below because it depends on
396    // the message it's contained in (!!!).
397    let obfuscated_ticket_age = resuming_session.obfuscated_ticket_age();
398
399    let binder_len = resuming_suite
400        .common
401        .hash_provider
402        .output_len();
403    let binder = vec![0u8; binder_len];
404
405    let psk_identity =
406        PresharedKeyIdentity::new(resuming_session.ticket().to_vec(), obfuscated_ticket_age);
407    let psk_offer = PresharedKeyOffer::new(psk_identity, binder);
408    exts.preshared_key_offer = Some(psk_offer);
409}
410
411pub(super) fn derive_early_traffic_secret(
412    key_log: &dyn KeyLog,
413    cx: &mut ClientContext<'_>,
414    hash_alg: &'static dyn Hash,
415    early_key_schedule: &KeyScheduleEarly,
416    sent_tls13_fake_ccs: &mut bool,
417    transcript_buffer: &HandshakeHashBuffer,
418    client_random: &[u8; 32],
419) {
420    // For middlebox compatibility
421    emit_fake_ccs(sent_tls13_fake_ccs, cx.common);
422
423    let client_hello_hash = transcript_buffer.hash_given(hash_alg, &[]);
424    early_key_schedule.client_early_traffic_secret(
425        &client_hello_hash,
426        key_log,
427        client_random,
428        cx.common,
429    );
430
431    // Now the client can send encrypted early data
432    cx.common.early_traffic = true;
433    trace!("Starting early data traffic");
434}
435
436pub(super) fn emit_fake_ccs(sent_tls13_fake_ccs: &mut bool, common: &mut CommonState) {
437    if common.is_quic() {
438        return;
439    }
440
441    if core::mem::replace(sent_tls13_fake_ccs, true) {
442        return;
443    }
444
445    let m = Message {
446        version: ProtocolVersion::TLSv1_2,
447        payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload {}),
448    };
449    common.send_msg(m, false);
450}
451
452fn validate_encrypted_extensions(
453    common: &mut CommonState,
454    hello: &ClientHelloDetails,
455    exts: &ServerExtensions<'_>,
456) -> Result<(), Error> {
457    if hello.server_sent_unsolicited_extensions(exts, &[]) {
458        return Err(common.send_fatal_alert(
459            AlertDescription::UnsupportedExtension,
460            PeerMisbehaved::UnsolicitedEncryptedExtension,
461        ));
462    }
463
464    if exts.contains_any(ALLOWED_PLAINTEXT_EXTS) || exts.contains_any(DISALLOWED_TLS13_EXTS) {
465        return Err(common.send_fatal_alert(
466            AlertDescription::UnsupportedExtension,
467            PeerMisbehaved::DisallowedEncryptedExtension,
468        ));
469    }
470
471    Ok(())
472}
473
474struct ExpectEncryptedExtensions {
475    config: Arc<ClientConfig>,
476    resuming_session: Option<persist::Tls13ClientSessionValue>,
477    server_name: ServerName<'static>,
478    randoms: ConnectionRandoms,
479    suite: &'static Tls13CipherSuite,
480    transcript: HandshakeHash,
481    key_schedule: KeyScheduleHandshake,
482    hello: ClientHelloDetails,
483}
484
485impl State<ClientConnectionData> for ExpectEncryptedExtensions {
486    fn handle<'m>(
487        mut self: Box<Self>,
488        cx: &mut ClientContext<'_>,
489        m: Message<'m>,
490    ) -> hs::NextStateOrError<'m>
491    where
492        Self: 'm,
493    {
494        let exts = require_handshake_msg!(
495            m,
496            HandshakeType::EncryptedExtensions,
497            HandshakePayload::EncryptedExtensions
498        )?;
499        debug!("TLS1.3 encrypted extensions: {exts:?}");
500        self.transcript.add_message(&m);
501
502        validate_encrypted_extensions(cx.common, &self.hello, exts)?;
503        hs::process_alpn_protocol(
504            cx.common,
505            &self.hello.alpn_protocols,
506            exts.selected_protocol
507                .as_ref()
508                .map(|protocol| protocol.as_ref()),
509            self.config.check_selected_alpn,
510        )?;
511        hs::process_client_cert_type_extension(
512            cx.common,
513            &self.config,
514            exts.client_certificate_type.as_ref(),
515        )?;
516        hs::process_server_cert_type_extension(
517            cx.common,
518            &self.config,
519            exts.server_certificate_type.as_ref(),
520        )?;
521
522        let ech_retry_configs = match (cx.data.ech_status, &exts.encrypted_client_hello_ack) {
523            // If we didn't offer ECH, or ECH was accepted, but the server sent an ECH encrypted
524            // extension with retry configs, we must error.
525            (EchStatus::NotOffered | EchStatus::Accepted, Some(_)) => {
526                return Err(cx.common.send_fatal_alert(
527                    AlertDescription::UnsupportedExtension,
528                    PeerMisbehaved::UnsolicitedEchExtension,
529                ));
530            }
531            // If we offered ECH, and it was rejected, store the retry configs (if any) from
532            // the server's ECH extension. We will return them in an error produced at the end
533            // of the handshake.
534            (EchStatus::Rejected, ext) => ext
535                .as_ref()
536                .map(|ext| ext.retry_configs.to_vec()),
537            _ => None,
538        };
539
540        // QUIC transport parameters
541        if cx.common.is_quic() {
542            match exts
543                .transport_parameters
544                .as_ref()
545                .or(exts.transport_parameters_draft.as_ref())
546            {
547                Some(params) => cx.common.quic.params = Some(params.clone().into_vec()),
548                None => {
549                    return Err(cx
550                        .common
551                        .missing_extension(PeerMisbehaved::MissingQuicTransportParameters));
552                }
553            }
554        }
555
556        match self.resuming_session {
557            Some(resuming_session) => {
558                let was_early_traffic = cx.common.early_traffic;
559                if was_early_traffic {
560                    match exts.early_data_ack {
561                        Some(()) => cx.data.early_data.accepted(),
562                        None => {
563                            cx.data.early_data.rejected();
564                            cx.common.early_traffic = false;
565                        }
566                    }
567                }
568
569                if was_early_traffic && !cx.common.early_traffic {
570                    // If no early traffic, set the encryption key for handshakes
571                    self.key_schedule
572                        .set_handshake_encrypter(cx.common);
573                }
574
575                cx.common.peer_certificates = Some(
576                    resuming_session
577                        .server_cert_chain()
578                        .clone(),
579                );
580                cx.common.handshake_kind = Some(HandshakeKind::Resumed);
581
582                // We *don't* reverify the certificate chain here: resumption is a
583                // continuation of the previous session in terms of security policy.
584                let cert_verified = verify::ServerCertVerified::assertion();
585                let sig_verified = verify::HandshakeSignatureValid::assertion();
586                Ok(Box::new(ExpectFinished {
587                    config: self.config,
588                    server_name: self.server_name,
589                    randoms: self.randoms,
590                    suite: self.suite,
591                    transcript: self.transcript,
592                    key_schedule: self.key_schedule,
593                    client_auth: None,
594                    cert_verified,
595                    sig_verified,
596                    ech_retry_configs,
597                }))
598            }
599            _ => {
600                if exts.early_data_ack.is_some() {
601                    return Err(PeerMisbehaved::EarlyDataExtensionWithoutResumption.into());
602                }
603                cx.common
604                    .handshake_kind
605                    .get_or_insert(HandshakeKind::Full);
606
607                Ok(if self.hello.offered_cert_compression {
608                    Box::new(ExpectCertificateOrCompressedCertificateOrCertReq {
609                        config: self.config,
610                        server_name: self.server_name,
611                        randoms: self.randoms,
612                        suite: self.suite,
613                        transcript: self.transcript,
614                        key_schedule: self.key_schedule,
615                        ech_retry_configs,
616                    })
617                } else {
618                    Box::new(ExpectCertificateOrCertReq {
619                        config: self.config,
620                        server_name: self.server_name,
621                        randoms: self.randoms,
622                        suite: self.suite,
623                        transcript: self.transcript,
624                        key_schedule: self.key_schedule,
625                        ech_retry_configs,
626                    })
627                })
628            }
629        }
630    }
631
632    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
633        self
634    }
635}
636
637struct ExpectCertificateOrCompressedCertificateOrCertReq {
638    config: Arc<ClientConfig>,
639    server_name: ServerName<'static>,
640    randoms: ConnectionRandoms,
641    suite: &'static Tls13CipherSuite,
642    transcript: HandshakeHash,
643    key_schedule: KeyScheduleHandshake,
644    ech_retry_configs: Option<Vec<EchConfigPayload>>,
645}
646
647impl State<ClientConnectionData> for ExpectCertificateOrCompressedCertificateOrCertReq {
648    fn handle<'m>(
649        self: Box<Self>,
650        cx: &mut ClientContext<'_>,
651        m: Message<'m>,
652    ) -> hs::NextStateOrError<'m>
653    where
654        Self: 'm,
655    {
656        match m.payload {
657            MessagePayload::Handshake {
658                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
659                ..
660            } => Box::new(ExpectCertificate {
661                config: self.config,
662                server_name: self.server_name,
663                randoms: self.randoms,
664                suite: self.suite,
665                transcript: self.transcript,
666                key_schedule: self.key_schedule,
667                client_auth: None,
668                message_already_in_transcript: false,
669                ech_retry_configs: self.ech_retry_configs,
670            })
671            .handle(cx, m),
672            MessagePayload::Handshake {
673                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
674                ..
675            } => Box::new(ExpectCompressedCertificate {
676                config: self.config,
677                server_name: self.server_name,
678                randoms: self.randoms,
679                suite: self.suite,
680                transcript: self.transcript,
681                key_schedule: self.key_schedule,
682                client_auth: None,
683                ech_retry_configs: self.ech_retry_configs,
684            })
685            .handle(cx, m),
686            MessagePayload::Handshake {
687                parsed: HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(..)),
688                ..
689            } => Box::new(ExpectCertificateRequest {
690                config: self.config,
691                server_name: self.server_name,
692                randoms: self.randoms,
693                suite: self.suite,
694                transcript: self.transcript,
695                key_schedule: self.key_schedule,
696                offered_cert_compression: true,
697                ech_retry_configs: self.ech_retry_configs,
698            })
699            .handle(cx, m),
700            payload => Err(inappropriate_handshake_message(
701                &payload,
702                &[ContentType::Handshake],
703                &[
704                    HandshakeType::Certificate,
705                    HandshakeType::CertificateRequest,
706                    HandshakeType::CompressedCertificate,
707                ],
708            )),
709        }
710    }
711
712    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
713        self
714    }
715}
716
717struct ExpectCertificateOrCompressedCertificate {
718    config: Arc<ClientConfig>,
719    server_name: ServerName<'static>,
720    randoms: ConnectionRandoms,
721    suite: &'static Tls13CipherSuite,
722    transcript: HandshakeHash,
723    key_schedule: KeyScheduleHandshake,
724    client_auth: Option<ClientAuthDetails>,
725    ech_retry_configs: Option<Vec<EchConfigPayload>>,
726}
727
728impl State<ClientConnectionData> for ExpectCertificateOrCompressedCertificate {
729    fn handle<'m>(
730        self: Box<Self>,
731        cx: &mut ClientContext<'_>,
732        m: Message<'m>,
733    ) -> hs::NextStateOrError<'m>
734    where
735        Self: 'm,
736    {
737        match m.payload {
738            MessagePayload::Handshake {
739                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
740                ..
741            } => Box::new(ExpectCertificate {
742                config: self.config,
743                server_name: self.server_name,
744                randoms: self.randoms,
745                suite: self.suite,
746                transcript: self.transcript,
747                key_schedule: self.key_schedule,
748                client_auth: self.client_auth,
749                message_already_in_transcript: false,
750                ech_retry_configs: self.ech_retry_configs,
751            })
752            .handle(cx, m),
753            MessagePayload::Handshake {
754                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
755                ..
756            } => Box::new(ExpectCompressedCertificate {
757                config: self.config,
758                server_name: self.server_name,
759                randoms: self.randoms,
760                suite: self.suite,
761                transcript: self.transcript,
762                key_schedule: self.key_schedule,
763                client_auth: self.client_auth,
764                ech_retry_configs: self.ech_retry_configs,
765            })
766            .handle(cx, m),
767            payload => Err(inappropriate_handshake_message(
768                &payload,
769                &[ContentType::Handshake],
770                &[
771                    HandshakeType::Certificate,
772                    HandshakeType::CompressedCertificate,
773                ],
774            )),
775        }
776    }
777
778    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
779        self
780    }
781}
782
783struct ExpectCertificateOrCertReq {
784    config: Arc<ClientConfig>,
785    server_name: ServerName<'static>,
786    randoms: ConnectionRandoms,
787    suite: &'static Tls13CipherSuite,
788    transcript: HandshakeHash,
789    key_schedule: KeyScheduleHandshake,
790    ech_retry_configs: Option<Vec<EchConfigPayload>>,
791}
792
793impl State<ClientConnectionData> for ExpectCertificateOrCertReq {
794    fn handle<'m>(
795        self: Box<Self>,
796        cx: &mut ClientContext<'_>,
797        m: Message<'m>,
798    ) -> hs::NextStateOrError<'m>
799    where
800        Self: 'm,
801    {
802        match m.payload {
803            MessagePayload::Handshake {
804                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
805                ..
806            } => Box::new(ExpectCertificate {
807                config: self.config,
808                server_name: self.server_name,
809                randoms: self.randoms,
810                suite: self.suite,
811                transcript: self.transcript,
812                key_schedule: self.key_schedule,
813                client_auth: None,
814                message_already_in_transcript: false,
815                ech_retry_configs: self.ech_retry_configs,
816            })
817            .handle(cx, m),
818            MessagePayload::Handshake {
819                parsed: HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(..)),
820                ..
821            } => Box::new(ExpectCertificateRequest {
822                config: self.config,
823                server_name: self.server_name,
824                randoms: self.randoms,
825                suite: self.suite,
826                transcript: self.transcript,
827                key_schedule: self.key_schedule,
828                offered_cert_compression: false,
829                ech_retry_configs: self.ech_retry_configs,
830            })
831            .handle(cx, m),
832            payload => Err(inappropriate_handshake_message(
833                &payload,
834                &[ContentType::Handshake],
835                &[
836                    HandshakeType::Certificate,
837                    HandshakeType::CertificateRequest,
838                ],
839            )),
840        }
841    }
842
843    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
844        self
845    }
846}
847
848// TLS1.3 version of CertificateRequest handling.  We then move to expecting the server
849// Certificate. Unfortunately the CertificateRequest type changed in an annoying way
850// in TLS1.3.
851struct ExpectCertificateRequest {
852    config: Arc<ClientConfig>,
853    server_name: ServerName<'static>,
854    randoms: ConnectionRandoms,
855    suite: &'static Tls13CipherSuite,
856    transcript: HandshakeHash,
857    key_schedule: KeyScheduleHandshake,
858    offered_cert_compression: bool,
859    ech_retry_configs: Option<Vec<EchConfigPayload>>,
860}
861
862impl State<ClientConnectionData> for ExpectCertificateRequest {
863    fn handle<'m>(
864        mut self: Box<Self>,
865        cx: &mut ClientContext<'_>,
866        m: Message<'m>,
867    ) -> hs::NextStateOrError<'m>
868    where
869        Self: 'm,
870    {
871        let certreq = &require_handshake_msg!(
872            m,
873            HandshakeType::CertificateRequest,
874            HandshakePayload::CertificateRequestTls13
875        )?;
876        self.transcript.add_message(&m);
877        debug!("Got CertificateRequest {certreq:?}");
878
879        // Fortunately the problems here in TLS1.2 and prior are corrected in
880        // TLS1.3.
881
882        // Must be empty during handshake.
883        if !certreq.context.0.is_empty() {
884            warn!("Server sent non-empty certreq context");
885            return Err(cx.common.send_fatal_alert(
886                AlertDescription::DecodeError,
887                InvalidMessage::InvalidCertRequest,
888            ));
889        }
890
891        let compat_sigschemes = certreq
892            .extensions
893            .signature_algorithms
894            .as_deref()
895            .unwrap_or_default()
896            .iter()
897            .cloned()
898            .filter(SignatureScheme::supported_in_tls13)
899            .collect::<Vec<SignatureScheme>>();
900
901        if compat_sigschemes.is_empty() {
902            return Err(cx.common.send_fatal_alert(
903                AlertDescription::HandshakeFailure,
904                PeerIncompatible::NoCertificateRequestSignatureSchemesInCommon,
905            ));
906        }
907
908        let compat_compressor = certreq
909            .extensions
910            .certificate_compression_algorithms
911            .as_deref()
912            .and_then(|offered| {
913                self.config
914                    .cert_compressors
915                    .iter()
916                    .find(|compressor| offered.contains(&compressor.algorithm()))
917            })
918            .cloned();
919
920        let client_auth = ClientAuthDetails::resolve(
921            self.config
922                .client_auth_cert_resolver
923                .as_ref(),
924            certreq
925                .extensions
926                .authority_names
927                .as_deref(),
928            &compat_sigschemes,
929            Some(certreq.context.0.clone()),
930            compat_compressor,
931        );
932
933        Ok(if self.offered_cert_compression {
934            Box::new(ExpectCertificateOrCompressedCertificate {
935                config: self.config,
936                server_name: self.server_name,
937                randoms: self.randoms,
938                suite: self.suite,
939                transcript: self.transcript,
940                key_schedule: self.key_schedule,
941                client_auth: Some(client_auth),
942                ech_retry_configs: self.ech_retry_configs,
943            })
944        } else {
945            Box::new(ExpectCertificate {
946                config: self.config,
947                server_name: self.server_name,
948                randoms: self.randoms,
949                suite: self.suite,
950                transcript: self.transcript,
951                key_schedule: self.key_schedule,
952                client_auth: Some(client_auth),
953                message_already_in_transcript: false,
954                ech_retry_configs: self.ech_retry_configs,
955            })
956        })
957    }
958
959    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
960        self
961    }
962}
963
964struct ExpectCompressedCertificate {
965    config: Arc<ClientConfig>,
966    server_name: ServerName<'static>,
967    randoms: ConnectionRandoms,
968    suite: &'static Tls13CipherSuite,
969    transcript: HandshakeHash,
970    key_schedule: KeyScheduleHandshake,
971    client_auth: Option<ClientAuthDetails>,
972    ech_retry_configs: Option<Vec<EchConfigPayload>>,
973}
974
975impl State<ClientConnectionData> for ExpectCompressedCertificate {
976    fn handle<'m>(
977        mut self: Box<Self>,
978        cx: &mut ClientContext<'_>,
979        m: Message<'m>,
980    ) -> hs::NextStateOrError<'m>
981    where
982        Self: 'm,
983    {
984        self.transcript.add_message(&m);
985        let compressed_cert = require_handshake_msg_move!(
986            m,
987            HandshakeType::CompressedCertificate,
988            HandshakePayload::CompressedCertificate
989        )?;
990
991        let selected_decompressor = self
992            .config
993            .cert_decompressors
994            .iter()
995            .find(|item| item.algorithm() == compressed_cert.alg);
996
997        let Some(decompressor) = selected_decompressor else {
998            return Err(cx.common.send_fatal_alert(
999                AlertDescription::BadCertificate,
1000                PeerMisbehaved::SelectedUnofferedCertCompression,
1001            ));
1002        };
1003
1004        if compressed_cert.uncompressed_len as usize > CERTIFICATE_MAX_SIZE_LIMIT {
1005            return Err(cx.common.send_fatal_alert(
1006                AlertDescription::BadCertificate,
1007                InvalidMessage::MessageTooLarge,
1008            ));
1009        }
1010
1011        let mut decompress_buffer = vec![0u8; compressed_cert.uncompressed_len as usize];
1012        if let Err(compress::DecompressionFailed) =
1013            decompressor.decompress(compressed_cert.compressed.0.bytes(), &mut decompress_buffer)
1014        {
1015            return Err(cx.common.send_fatal_alert(
1016                AlertDescription::BadCertificate,
1017                PeerMisbehaved::InvalidCertCompression,
1018            ));
1019        }
1020
1021        let cert_payload =
1022            match CertificatePayloadTls13::read(&mut Reader::init(&decompress_buffer)) {
1023                Ok(cm) => cm,
1024                Err(err) => {
1025                    return Err(cx
1026                        .common
1027                        .send_fatal_alert(AlertDescription::BadCertificate, err));
1028                }
1029            };
1030        trace!(
1031            "Server certificate decompressed using {:?} ({} bytes -> {})",
1032            compressed_cert.alg,
1033            compressed_cert
1034                .compressed
1035                .0
1036                .bytes()
1037                .len(),
1038            compressed_cert.uncompressed_len,
1039        );
1040
1041        let m = Message {
1042            version: ProtocolVersion::TLSv1_3,
1043            payload: MessagePayload::handshake(HandshakeMessagePayload(
1044                HandshakePayload::CertificateTls13(cert_payload.into_owned()),
1045            )),
1046        };
1047
1048        Box::new(ExpectCertificate {
1049            config: self.config,
1050            server_name: self.server_name,
1051            randoms: self.randoms,
1052            suite: self.suite,
1053            transcript: self.transcript,
1054            key_schedule: self.key_schedule,
1055            client_auth: self.client_auth,
1056            message_already_in_transcript: true,
1057            ech_retry_configs: self.ech_retry_configs,
1058        })
1059        .handle(cx, m)
1060    }
1061
1062    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1063        self
1064    }
1065}
1066
1067struct ExpectCertificate {
1068    config: Arc<ClientConfig>,
1069    server_name: ServerName<'static>,
1070    randoms: ConnectionRandoms,
1071    suite: &'static Tls13CipherSuite,
1072    transcript: HandshakeHash,
1073    key_schedule: KeyScheduleHandshake,
1074    client_auth: Option<ClientAuthDetails>,
1075    message_already_in_transcript: bool,
1076    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1077}
1078
1079impl State<ClientConnectionData> for ExpectCertificate {
1080    fn handle<'m>(
1081        mut self: Box<Self>,
1082        cx: &mut ClientContext<'_>,
1083        m: Message<'m>,
1084    ) -> hs::NextStateOrError<'m>
1085    where
1086        Self: 'm,
1087    {
1088        if !self.message_already_in_transcript {
1089            self.transcript.add_message(&m);
1090        }
1091        let cert_chain = require_handshake_msg_move!(
1092            m,
1093            HandshakeType::Certificate,
1094            HandshakePayload::CertificateTls13
1095        )?;
1096
1097        // This is only non-empty for client auth.
1098        if !cert_chain.context.0.is_empty() {
1099            return Err(cx.common.send_fatal_alert(
1100                AlertDescription::DecodeError,
1101                InvalidMessage::InvalidCertRequest,
1102            ));
1103        }
1104
1105        let end_entity_ocsp = cert_chain.end_entity_ocsp().to_vec();
1106        let server_cert = ServerCertDetails::new(
1107            cert_chain
1108                .into_certificate_chain()
1109                .into_owned(),
1110            end_entity_ocsp,
1111        );
1112
1113        Ok(Box::new(ExpectCertificateVerify {
1114            config: self.config,
1115            server_name: self.server_name,
1116            randoms: self.randoms,
1117            suite: self.suite,
1118            transcript: self.transcript,
1119            key_schedule: self.key_schedule,
1120            server_cert,
1121            client_auth: self.client_auth,
1122            ech_retry_configs: self.ech_retry_configs,
1123        }))
1124    }
1125
1126    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1127        self
1128    }
1129}
1130
1131// --- TLS1.3 CertificateVerify ---
1132struct ExpectCertificateVerify<'a> {
1133    config: Arc<ClientConfig>,
1134    server_name: ServerName<'static>,
1135    randoms: ConnectionRandoms,
1136    suite: &'static Tls13CipherSuite,
1137    transcript: HandshakeHash,
1138    key_schedule: KeyScheduleHandshake,
1139    server_cert: ServerCertDetails<'a>,
1140    client_auth: Option<ClientAuthDetails>,
1141    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1142}
1143
1144impl State<ClientConnectionData> for ExpectCertificateVerify<'_> {
1145    fn handle<'m>(
1146        mut self: Box<Self>,
1147        cx: &mut ClientContext<'_>,
1148        m: Message<'m>,
1149    ) -> hs::NextStateOrError<'m>
1150    where
1151        Self: 'm,
1152    {
1153        let cert_verify = require_handshake_msg!(
1154            m,
1155            HandshakeType::CertificateVerify,
1156            HandshakePayload::CertificateVerify
1157        )?;
1158
1159        trace!("Server cert is {:?}", self.server_cert.cert_chain);
1160
1161        // 1. Verify the certificate chain.
1162        let (end_entity, intermediates) = self
1163            .server_cert
1164            .cert_chain
1165            .split_first()
1166            .ok_or(Error::NoCertificatesPresented)?;
1167
1168        let now = self.config.current_time()?;
1169
1170        let cert_verified = self
1171            .config
1172            .verifier
1173            .verify_server_cert(
1174                end_entity,
1175                intermediates,
1176                &self.server_name,
1177                &self.server_cert.ocsp_response,
1178                now,
1179            )
1180            .map_err(|err| {
1181                cx.common
1182                    .send_cert_verify_error_alert(err)
1183            })?;
1184
1185        // 2. Verify their signature on the handshake.
1186        let handshake_hash = self.transcript.current_hash();
1187        let sig_verified = self
1188            .config
1189            .verifier
1190            .verify_tls13_signature(
1191                construct_server_verify_message(&handshake_hash).as_ref(),
1192                end_entity,
1193                cert_verify,
1194            )
1195            .map_err(|err| {
1196                cx.common
1197                    .send_cert_verify_error_alert(err)
1198            })?;
1199
1200        cx.common.peer_certificates = Some(self.server_cert.cert_chain.into_owned());
1201        self.transcript.add_message(&m);
1202
1203        Ok(Box::new(ExpectFinished {
1204            config: self.config,
1205            server_name: self.server_name,
1206            randoms: self.randoms,
1207            suite: self.suite,
1208            transcript: self.transcript,
1209            key_schedule: self.key_schedule,
1210            client_auth: self.client_auth,
1211            cert_verified,
1212            sig_verified,
1213            ech_retry_configs: self.ech_retry_configs,
1214        }))
1215    }
1216
1217    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1218        Box::new(ExpectCertificateVerify {
1219            config: self.config,
1220            server_name: self.server_name,
1221            randoms: self.randoms,
1222            suite: self.suite,
1223            transcript: self.transcript,
1224            key_schedule: self.key_schedule,
1225            server_cert: self.server_cert.into_owned(),
1226            client_auth: self.client_auth,
1227            ech_retry_configs: self.ech_retry_configs,
1228        })
1229    }
1230}
1231
1232fn emit_compressed_certificate_tls13(
1233    flight: &mut HandshakeFlightTls13<'_>,
1234    certkey: &CertifiedKey,
1235    auth_context: Option<Vec<u8>>,
1236    compressor: &dyn compress::CertCompressor,
1237    config: &ClientConfig,
1238) {
1239    let mut cert_payload = CertificatePayloadTls13::new(certkey.cert.iter(), None);
1240    cert_payload.context = PayloadU8::new(auth_context.clone().unwrap_or_default());
1241
1242    let Ok(compressed) = config
1243        .cert_compression_cache
1244        .compression_for(compressor, &cert_payload)
1245    else {
1246        return emit_certificate_tls13(flight, Some(certkey), auth_context);
1247    };
1248
1249    flight.add(HandshakeMessagePayload(
1250        HandshakePayload::CompressedCertificate(compressed.compressed_cert_payload()),
1251    ));
1252}
1253
1254fn emit_certificate_tls13(
1255    flight: &mut HandshakeFlightTls13<'_>,
1256    certkey: Option<&CertifiedKey>,
1257    auth_context: Option<Vec<u8>>,
1258) {
1259    let certs = certkey
1260        .map(|ck| ck.cert.as_ref())
1261        .unwrap_or(&[][..]);
1262    let mut cert_payload = CertificatePayloadTls13::new(certs.iter(), None);
1263    cert_payload.context = PayloadU8::new(auth_context.unwrap_or_default());
1264
1265    flight.add(HandshakeMessagePayload(HandshakePayload::CertificateTls13(
1266        cert_payload,
1267    )));
1268}
1269
1270fn emit_certverify_tls13(
1271    flight: &mut HandshakeFlightTls13<'_>,
1272    signer: &dyn Signer,
1273) -> Result<(), Error> {
1274    let message = construct_client_verify_message(&flight.transcript.current_hash());
1275
1276    let scheme = signer.scheme();
1277    let sig = signer.sign(message.as_ref())?;
1278    let dss = DigitallySignedStruct::new(scheme, sig);
1279
1280    flight.add(HandshakeMessagePayload(
1281        HandshakePayload::CertificateVerify(dss),
1282    ));
1283    Ok(())
1284}
1285
1286fn emit_finished_tls13(flight: &mut HandshakeFlightTls13<'_>, verify_data: &crypto::hmac::Tag) {
1287    let verify_data_payload = Payload::new(verify_data.as_ref());
1288
1289    flight.add(HandshakeMessagePayload(HandshakePayload::Finished(
1290        verify_data_payload,
1291    )));
1292}
1293
1294fn emit_end_of_early_data_tls13(transcript: &mut HandshakeHash, common: &mut CommonState) {
1295    if common.is_quic() {
1296        return;
1297    }
1298
1299    let m = Message {
1300        version: ProtocolVersion::TLSv1_3,
1301        payload: MessagePayload::handshake(HandshakeMessagePayload(
1302            HandshakePayload::EndOfEarlyData,
1303        )),
1304    };
1305
1306    transcript.add_message(&m);
1307    common.send_msg(m, true);
1308}
1309
1310struct ExpectFinished {
1311    config: Arc<ClientConfig>,
1312    server_name: ServerName<'static>,
1313    randoms: ConnectionRandoms,
1314    suite: &'static Tls13CipherSuite,
1315    transcript: HandshakeHash,
1316    key_schedule: KeyScheduleHandshake,
1317    client_auth: Option<ClientAuthDetails>,
1318    cert_verified: verify::ServerCertVerified,
1319    sig_verified: verify::HandshakeSignatureValid,
1320    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1321}
1322
1323impl State<ClientConnectionData> for ExpectFinished {
1324    fn handle<'m>(
1325        self: Box<Self>,
1326        cx: &mut ClientContext<'_>,
1327        m: Message<'m>,
1328    ) -> hs::NextStateOrError<'m>
1329    where
1330        Self: 'm,
1331    {
1332        let mut st = *self;
1333        let finished =
1334            require_handshake_msg!(m, HandshakeType::Finished, HandshakePayload::Finished)?;
1335
1336        let handshake_hash = st.transcript.current_hash();
1337        let expect_verify_data = st
1338            .key_schedule
1339            .sign_server_finish(&handshake_hash);
1340
1341        let fin = match ConstantTimeEq::ct_eq(expect_verify_data.as_ref(), finished.bytes()).into()
1342        {
1343            true => verify::FinishedMessageVerified::assertion(),
1344            false => {
1345                return Err(cx
1346                    .common
1347                    .send_fatal_alert(AlertDescription::DecryptError, Error::DecryptError));
1348            }
1349        };
1350
1351        st.transcript.add_message(&m);
1352
1353        let hash_after_handshake = st.transcript.current_hash();
1354        /* The EndOfEarlyData message to server is still encrypted with early data keys,
1355         * but appears in the transcript after the server Finished. */
1356        if cx.common.early_traffic {
1357            emit_end_of_early_data_tls13(&mut st.transcript, cx.common);
1358            cx.common.early_traffic = false;
1359            cx.data.early_data.finished();
1360            st.key_schedule
1361                .set_handshake_encrypter(cx.common);
1362        }
1363
1364        let mut flight = HandshakeFlightTls13::new(&mut st.transcript);
1365
1366        /* Send our authentication/finished messages.  These are still encrypted
1367         * with our handshake keys. */
1368        if let Some(client_auth) = st.client_auth {
1369            match client_auth {
1370                ClientAuthDetails::Empty {
1371                    auth_context_tls13: auth_context,
1372                } => {
1373                    emit_certificate_tls13(&mut flight, None, auth_context);
1374                }
1375                ClientAuthDetails::Verify {
1376                    auth_context_tls13: auth_context,
1377                    ..
1378                } if cx.data.ech_status == EchStatus::Rejected => {
1379                    // If ECH was offered, and rejected, we MUST respond with
1380                    // an empty certificate message.
1381                    emit_certificate_tls13(&mut flight, None, auth_context);
1382                }
1383                ClientAuthDetails::Verify {
1384                    certkey,
1385                    signer,
1386                    auth_context_tls13: auth_context,
1387                    compressor,
1388                } => {
1389                    if let Some(compressor) = compressor {
1390                        emit_compressed_certificate_tls13(
1391                            &mut flight,
1392                            &certkey,
1393                            auth_context,
1394                            compressor,
1395                            &st.config,
1396                        );
1397                    } else {
1398                        emit_certificate_tls13(&mut flight, Some(&certkey), auth_context);
1399                    }
1400                    emit_certverify_tls13(&mut flight, signer.as_ref())?;
1401                }
1402            }
1403        }
1404
1405        let (key_schedule_pre_finished, verify_data) = st
1406            .key_schedule
1407            .into_pre_finished_client_traffic(
1408                hash_after_handshake,
1409                flight.transcript.current_hash(),
1410                &*st.config.key_log,
1411                &st.randoms.client,
1412            );
1413
1414        emit_finished_tls13(&mut flight, &verify_data);
1415        flight.finish(cx.common);
1416
1417        /* We're now sure this server supports TLS1.3.  But if we run out of TLS1.3 tickets
1418         * when connecting to it again, we definitely don't want to attempt a TLS1.2 resumption. */
1419        st.config
1420            .resumption
1421            .store
1422            .remove_tls12_session(&st.server_name);
1423
1424        /* Now move to our application traffic keys. */
1425        cx.common.check_aligned_handshake()?;
1426        let (key_schedule, resumption) =
1427            key_schedule_pre_finished.into_traffic(cx.common, st.transcript.current_hash());
1428        cx.common
1429            .start_traffic(&mut cx.sendable_plaintext);
1430
1431        // Now that we've reached the end of the normal handshake we must enforce ECH acceptance by
1432        // sending an alert and returning an error (potentially with retry configs) if the server
1433        // did not accept our ECH offer.
1434        if cx.data.ech_status == EchStatus::Rejected {
1435            return Err(ech::fatal_alert_required(st.ech_retry_configs, cx.common));
1436        }
1437
1438        let st = ExpectTraffic {
1439            config: st.config.clone(),
1440            session_storage: st.config.resumption.store.clone(),
1441            server_name: st.server_name,
1442            suite: st.suite,
1443            key_schedule,
1444            resumption,
1445            _cert_verified: st.cert_verified,
1446            _sig_verified: st.sig_verified,
1447            _fin_verified: fin,
1448        };
1449
1450        Ok(match cx.common.is_quic() {
1451            true => Box::new(ExpectQuicTraffic(st)),
1452            false => Box::new(st),
1453        })
1454    }
1455
1456    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1457        self
1458    }
1459}
1460
1461// -- Traffic transit state (TLS1.3) --
1462// In this state we can be sent tickets, key updates,
1463// and application data.
1464struct ExpectTraffic {
1465    config: Arc<ClientConfig>,
1466    session_storage: Arc<dyn ClientSessionStore>,
1467    server_name: ServerName<'static>,
1468    suite: &'static Tls13CipherSuite,
1469    key_schedule: KeyScheduleTraffic,
1470    resumption: KeyScheduleResumption,
1471    _cert_verified: verify::ServerCertVerified,
1472    _sig_verified: verify::HandshakeSignatureValid,
1473    _fin_verified: verify::FinishedMessageVerified,
1474}
1475
1476impl ExpectTraffic {
1477    fn handle_new_ticket_impl(
1478        &mut self,
1479        cx: &mut KernelContext<'_>,
1480        nst: &NewSessionTicketPayloadTls13,
1481    ) -> Result<(), Error> {
1482        let secret = self
1483            .resumption
1484            .derive_ticket_psk(&nst.nonce.0);
1485
1486        let now = self.config.current_time()?;
1487
1488        #[allow(unused_mut)]
1489        let mut value = persist::Tls13ClientSessionValue::new(
1490            self.suite,
1491            nst.ticket.clone(),
1492            secret.as_ref(),
1493            cx.peer_certificates
1494                .cloned()
1495                .unwrap_or_default(),
1496            &self.config.verifier,
1497            &self.config.client_auth_cert_resolver,
1498            now,
1499            nst.lifetime,
1500            nst.age_add,
1501            nst.extensions
1502                .max_early_data_size
1503                .unwrap_or_default(),
1504        );
1505
1506        if cx.is_quic() {
1507            if let Some(sz) = nst.extensions.max_early_data_size {
1508                if sz != 0 && sz != 0xffff_ffff {
1509                    return Err(PeerMisbehaved::InvalidMaxEarlyDataSize.into());
1510                }
1511            }
1512
1513            if let Some(quic_params) = &cx.quic.params {
1514                value.set_quic_params(quic_params);
1515            }
1516        }
1517
1518        self.session_storage
1519            .insert_tls13_ticket(self.server_name.clone(), value);
1520        Ok(())
1521    }
1522
1523    fn handle_new_ticket_tls13(
1524        &mut self,
1525        cx: &mut ClientContext<'_>,
1526        nst: &NewSessionTicketPayloadTls13,
1527    ) -> Result<(), Error> {
1528        let mut kcx = KernelContext {
1529            peer_certificates: cx.common.peer_certificates.as_ref(),
1530            protocol: cx.common.protocol,
1531            quic: &cx.common.quic,
1532        };
1533        cx.common.tls13_tickets_received = cx
1534            .common
1535            .tls13_tickets_received
1536            .saturating_add(1);
1537        self.handle_new_ticket_impl(&mut kcx, nst)
1538    }
1539
1540    fn handle_key_update(
1541        &mut self,
1542        common: &mut CommonState,
1543        key_update_request: &KeyUpdateRequest,
1544    ) -> Result<(), Error> {
1545        if let Protocol::Quic = common.protocol {
1546            return Err(common.send_fatal_alert(
1547                AlertDescription::UnexpectedMessage,
1548                PeerMisbehaved::KeyUpdateReceivedInQuicConnection,
1549            ));
1550        }
1551
1552        // Mustn't be interleaved with other handshake messages.
1553        common.check_aligned_handshake()?;
1554
1555        if common.should_update_key(key_update_request)? {
1556            self.key_schedule
1557                .update_encrypter_and_notify(common);
1558        }
1559
1560        // Update our read-side keys.
1561        self.key_schedule
1562            .update_decrypter(common);
1563        Ok(())
1564    }
1565}
1566
1567impl State<ClientConnectionData> for ExpectTraffic {
1568    fn handle<'m>(
1569        mut self: Box<Self>,
1570        cx: &mut ClientContext<'_>,
1571        m: Message<'m>,
1572    ) -> hs::NextStateOrError<'m>
1573    where
1574        Self: 'm,
1575    {
1576        match m.payload {
1577            MessagePayload::ApplicationData(payload) => cx
1578                .common
1579                .take_received_plaintext(payload),
1580            MessagePayload::Handshake {
1581                parsed: HandshakeMessagePayload(HandshakePayload::NewSessionTicketTls13(new_ticket)),
1582                ..
1583            } => self.handle_new_ticket_tls13(cx, &new_ticket)?,
1584            MessagePayload::Handshake {
1585                parsed: HandshakeMessagePayload(HandshakePayload::KeyUpdate(key_update)),
1586                ..
1587            } => self.handle_key_update(cx.common, &key_update)?,
1588            payload => {
1589                return Err(inappropriate_handshake_message(
1590                    &payload,
1591                    &[ContentType::ApplicationData, ContentType::Handshake],
1592                    &[HandshakeType::NewSessionTicket, HandshakeType::KeyUpdate],
1593                ));
1594            }
1595        }
1596
1597        Ok(self)
1598    }
1599
1600    fn send_key_update_request(&mut self, common: &mut CommonState) -> Result<(), Error> {
1601        self.key_schedule
1602            .request_key_update_and_update_encrypter(common)
1603    }
1604
1605    fn export_keying_material(
1606        &self,
1607        output: &mut [u8],
1608        label: &[u8],
1609        context: Option<&[u8]>,
1610    ) -> Result<(), Error> {
1611        self.key_schedule
1612            .export_keying_material(output, label, context)
1613    }
1614
1615    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
1616        self.key_schedule
1617            .extract_secrets(Side::Client)
1618    }
1619
1620    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1621        Ok(self)
1622    }
1623
1624    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1625        self
1626    }
1627}
1628
1629impl KernelState for ExpectTraffic {
1630    fn update_secrets(&mut self, dir: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1631        self.key_schedule
1632            .refresh_traffic_secret(match dir {
1633                Direction::Transmit => Side::Client,
1634                Direction::Receive => Side::Server,
1635            })
1636    }
1637
1638    fn handle_new_session_ticket(
1639        &mut self,
1640        cx: &mut KernelContext<'_>,
1641        message: &NewSessionTicketPayloadTls13,
1642    ) -> Result<(), Error> {
1643        self.handle_new_ticket_impl(cx, message)
1644    }
1645}
1646
1647struct ExpectQuicTraffic(ExpectTraffic);
1648
1649impl State<ClientConnectionData> for ExpectQuicTraffic {
1650    fn handle<'m>(
1651        mut self: Box<Self>,
1652        cx: &mut ClientContext<'_>,
1653        m: Message<'m>,
1654    ) -> hs::NextStateOrError<'m>
1655    where
1656        Self: 'm,
1657    {
1658        let nst = require_handshake_msg!(
1659            m,
1660            HandshakeType::NewSessionTicket,
1661            HandshakePayload::NewSessionTicketTls13
1662        )?;
1663        self.0
1664            .handle_new_ticket_tls13(cx, nst)?;
1665        Ok(self)
1666    }
1667
1668    fn export_keying_material(
1669        &self,
1670        output: &mut [u8],
1671        label: &[u8],
1672        context: Option<&[u8]>,
1673    ) -> Result<(), Error> {
1674        self.0
1675            .export_keying_material(output, label, context)
1676    }
1677
1678    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1679        Ok(self)
1680    }
1681
1682    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1683        self
1684    }
1685}
1686
1687impl KernelState for ExpectQuicTraffic {
1688    fn update_secrets(&mut self, _: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1689        Err(Error::General(
1690            "KeyUpdate is not supported for QUIC connections".into(),
1691        ))
1692    }
1693
1694    fn handle_new_session_ticket(
1695        &mut self,
1696        cx: &mut KernelContext<'_>,
1697        nst: &NewSessionTicketPayloadTls13,
1698    ) -> Result<(), Error> {
1699        self.0.handle_new_ticket_impl(cx, nst)
1700    }
1701}