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