Skip to main content

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