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