rustls/client/
tls13.rs

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