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.0 {
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: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
611                ..
612            } => Box::new(ExpectCertificate {
613                config: self.config,
614                server_name: self.server_name,
615                randoms: self.randoms,
616                suite: self.suite,
617                transcript: self.transcript,
618                key_schedule: self.key_schedule,
619                client_auth: None,
620                message_already_in_transcript: false,
621                ech_retry_configs: self.ech_retry_configs,
622            })
623            .handle(cx, m),
624            MessagePayload::Handshake {
625                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
626                ..
627            } => Box::new(ExpectCompressedCertificate {
628                config: self.config,
629                server_name: self.server_name,
630                randoms: self.randoms,
631                suite: self.suite,
632                transcript: self.transcript,
633                key_schedule: self.key_schedule,
634                client_auth: None,
635                ech_retry_configs: self.ech_retry_configs,
636            })
637            .handle(cx, m),
638            MessagePayload::Handshake {
639                parsed: HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(..)),
640                ..
641            } => Box::new(ExpectCertificateRequest {
642                config: self.config,
643                server_name: self.server_name,
644                randoms: self.randoms,
645                suite: self.suite,
646                transcript: self.transcript,
647                key_schedule: self.key_schedule,
648                offered_cert_compression: true,
649                ech_retry_configs: self.ech_retry_configs,
650            })
651            .handle(cx, m),
652            payload => Err(inappropriate_handshake_message(
653                &payload,
654                &[ContentType::Handshake],
655                &[
656                    HandshakeType::Certificate,
657                    HandshakeType::CertificateRequest,
658                    HandshakeType::CompressedCertificate,
659                ],
660            )),
661        }
662    }
663
664    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
665        self
666    }
667}
668
669struct ExpectCertificateOrCompressedCertificate {
670    config: Arc<ClientConfig>,
671    server_name: ServerName<'static>,
672    randoms: ConnectionRandoms,
673    suite: &'static Tls13CipherSuite,
674    transcript: HandshakeHash,
675    key_schedule: KeyScheduleHandshake,
676    client_auth: Option<ClientAuthDetails>,
677    ech_retry_configs: Option<Vec<EchConfigPayload>>,
678}
679
680impl State<ClientConnectionData> for ExpectCertificateOrCompressedCertificate {
681    fn handle<'m>(
682        self: Box<Self>,
683        cx: &mut ClientContext<'_>,
684        m: Message<'m>,
685    ) -> hs::NextStateOrError<'m>
686    where
687        Self: 'm,
688    {
689        match m.payload {
690            MessagePayload::Handshake {
691                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
692                ..
693            } => Box::new(ExpectCertificate {
694                config: self.config,
695                server_name: self.server_name,
696                randoms: self.randoms,
697                suite: self.suite,
698                transcript: self.transcript,
699                key_schedule: self.key_schedule,
700                client_auth: self.client_auth,
701                message_already_in_transcript: false,
702                ech_retry_configs: self.ech_retry_configs,
703            })
704            .handle(cx, m),
705            MessagePayload::Handshake {
706                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
707                ..
708            } => Box::new(ExpectCompressedCertificate {
709                config: self.config,
710                server_name: self.server_name,
711                randoms: self.randoms,
712                suite: self.suite,
713                transcript: self.transcript,
714                key_schedule: self.key_schedule,
715                client_auth: self.client_auth,
716                ech_retry_configs: self.ech_retry_configs,
717            })
718            .handle(cx, m),
719            payload => Err(inappropriate_handshake_message(
720                &payload,
721                &[ContentType::Handshake],
722                &[
723                    HandshakeType::Certificate,
724                    HandshakeType::CompressedCertificate,
725                ],
726            )),
727        }
728    }
729
730    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
731        self
732    }
733}
734
735struct ExpectCertificateOrCertReq {
736    config: Arc<ClientConfig>,
737    server_name: ServerName<'static>,
738    randoms: ConnectionRandoms,
739    suite: &'static Tls13CipherSuite,
740    transcript: HandshakeHash,
741    key_schedule: KeyScheduleHandshake,
742    ech_retry_configs: Option<Vec<EchConfigPayload>>,
743}
744
745impl State<ClientConnectionData> for ExpectCertificateOrCertReq {
746    fn handle<'m>(
747        self: Box<Self>,
748        cx: &mut ClientContext<'_>,
749        m: Message<'m>,
750    ) -> hs::NextStateOrError<'m>
751    where
752        Self: 'm,
753    {
754        match m.payload {
755            MessagePayload::Handshake {
756                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
757                ..
758            } => Box::new(ExpectCertificate {
759                config: self.config,
760                server_name: self.server_name,
761                randoms: self.randoms,
762                suite: self.suite,
763                transcript: self.transcript,
764                key_schedule: self.key_schedule,
765                client_auth: None,
766                message_already_in_transcript: false,
767                ech_retry_configs: self.ech_retry_configs,
768            })
769            .handle(cx, m),
770            MessagePayload::Handshake {
771                parsed: HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(..)),
772                ..
773            } => Box::new(ExpectCertificateRequest {
774                config: self.config,
775                server_name: self.server_name,
776                randoms: self.randoms,
777                suite: self.suite,
778                transcript: self.transcript,
779                key_schedule: self.key_schedule,
780                offered_cert_compression: false,
781                ech_retry_configs: self.ech_retry_configs,
782            })
783            .handle(cx, m),
784            payload => Err(inappropriate_handshake_message(
785                &payload,
786                &[ContentType::Handshake],
787                &[
788                    HandshakeType::Certificate,
789                    HandshakeType::CertificateRequest,
790                ],
791            )),
792        }
793    }
794
795    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
796        self
797    }
798}
799
800// TLS1.3 version of CertificateRequest handling.  We then move to expecting the server
801// Certificate. Unfortunately the CertificateRequest type changed in an annoying way
802// in TLS1.3.
803struct ExpectCertificateRequest {
804    config: Arc<ClientConfig>,
805    server_name: ServerName<'static>,
806    randoms: ConnectionRandoms,
807    suite: &'static Tls13CipherSuite,
808    transcript: HandshakeHash,
809    key_schedule: KeyScheduleHandshake,
810    offered_cert_compression: bool,
811    ech_retry_configs: Option<Vec<EchConfigPayload>>,
812}
813
814impl State<ClientConnectionData> for ExpectCertificateRequest {
815    fn handle<'m>(
816        mut self: Box<Self>,
817        cx: &mut ClientContext<'_>,
818        m: Message<'m>,
819    ) -> hs::NextStateOrError<'m>
820    where
821        Self: 'm,
822    {
823        let certreq = &require_handshake_msg!(
824            m,
825            HandshakeType::CertificateRequest,
826            HandshakePayload::CertificateRequestTls13
827        )?;
828        self.transcript.add_message(&m);
829        debug!("Got CertificateRequest {certreq:?}");
830
831        // Fortunately the problems here in TLS1.2 and prior are corrected in
832        // TLS1.3.
833
834        // Must be empty during handshake.
835        if !certreq.context.0.is_empty() {
836            warn!("Server sent non-empty certreq context");
837            return Err(cx.common.send_fatal_alert(
838                AlertDescription::DecodeError,
839                InvalidMessage::InvalidCertRequest,
840            ));
841        }
842
843        let no_sigschemes = Vec::new();
844        let compat_sigschemes = certreq
845            .sigalgs_extension()
846            .unwrap_or(&no_sigschemes)
847            .iter()
848            .cloned()
849            .filter(SignatureScheme::supported_in_tls13)
850            .collect::<Vec<SignatureScheme>>();
851
852        if compat_sigschemes.is_empty() {
853            return Err(cx.common.send_fatal_alert(
854                AlertDescription::HandshakeFailure,
855                PeerIncompatible::NoCertificateRequestSignatureSchemesInCommon,
856            ));
857        }
858
859        let compat_compressor = certreq
860            .certificate_compression_extension()
861            .and_then(|offered| {
862                self.config
863                    .cert_compressors
864                    .iter()
865                    .find(|compressor| offered.contains(&compressor.algorithm()))
866            })
867            .cloned();
868
869        let client_auth = ClientAuthDetails::resolve(
870            self.config
871                .client_auth_cert_resolver
872                .as_ref(),
873            certreq.authorities_extension(),
874            &compat_sigschemes,
875            Some(certreq.context.0.clone()),
876            compat_compressor,
877        );
878
879        Ok(if self.offered_cert_compression {
880            Box::new(ExpectCertificateOrCompressedCertificate {
881                config: self.config,
882                server_name: self.server_name,
883                randoms: self.randoms,
884                suite: self.suite,
885                transcript: self.transcript,
886                key_schedule: self.key_schedule,
887                client_auth: Some(client_auth),
888                ech_retry_configs: self.ech_retry_configs,
889            })
890        } else {
891            Box::new(ExpectCertificate {
892                config: self.config,
893                server_name: self.server_name,
894                randoms: self.randoms,
895                suite: self.suite,
896                transcript: self.transcript,
897                key_schedule: self.key_schedule,
898                client_auth: Some(client_auth),
899                message_already_in_transcript: false,
900                ech_retry_configs: self.ech_retry_configs,
901            })
902        })
903    }
904
905    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
906        self
907    }
908}
909
910struct ExpectCompressedCertificate {
911    config: Arc<ClientConfig>,
912    server_name: ServerName<'static>,
913    randoms: ConnectionRandoms,
914    suite: &'static Tls13CipherSuite,
915    transcript: HandshakeHash,
916    key_schedule: KeyScheduleHandshake,
917    client_auth: Option<ClientAuthDetails>,
918    ech_retry_configs: Option<Vec<EchConfigPayload>>,
919}
920
921impl State<ClientConnectionData> for ExpectCompressedCertificate {
922    fn handle<'m>(
923        mut self: Box<Self>,
924        cx: &mut ClientContext<'_>,
925        m: Message<'m>,
926    ) -> hs::NextStateOrError<'m>
927    where
928        Self: 'm,
929    {
930        self.transcript.add_message(&m);
931        let compressed_cert = require_handshake_msg_move!(
932            m,
933            HandshakeType::CompressedCertificate,
934            HandshakePayload::CompressedCertificate
935        )?;
936
937        let selected_decompressor = self
938            .config
939            .cert_decompressors
940            .iter()
941            .find(|item| item.algorithm() == compressed_cert.alg);
942
943        let Some(decompressor) = selected_decompressor else {
944            return Err(cx.common.send_fatal_alert(
945                AlertDescription::BadCertificate,
946                PeerMisbehaved::SelectedUnofferedCertCompression,
947            ));
948        };
949
950        if compressed_cert.uncompressed_len as usize > CERTIFICATE_MAX_SIZE_LIMIT {
951            return Err(cx.common.send_fatal_alert(
952                AlertDescription::BadCertificate,
953                InvalidMessage::MessageTooLarge,
954            ));
955        }
956
957        let mut decompress_buffer = vec![0u8; compressed_cert.uncompressed_len as usize];
958        if let Err(compress::DecompressionFailed) =
959            decompressor.decompress(compressed_cert.compressed.0.bytes(), &mut decompress_buffer)
960        {
961            return Err(cx.common.send_fatal_alert(
962                AlertDescription::BadCertificate,
963                PeerMisbehaved::InvalidCertCompression,
964            ));
965        }
966
967        let cert_payload =
968            match CertificatePayloadTls13::read(&mut Reader::init(&decompress_buffer)) {
969                Ok(cm) => cm,
970                Err(err) => {
971                    return Err(cx
972                        .common
973                        .send_fatal_alert(AlertDescription::BadCertificate, err));
974                }
975            };
976        trace!(
977            "Server certificate decompressed using {:?} ({} bytes -> {})",
978            compressed_cert.alg,
979            compressed_cert
980                .compressed
981                .0
982                .bytes()
983                .len(),
984            compressed_cert.uncompressed_len,
985        );
986
987        let m = Message {
988            version: ProtocolVersion::TLSv1_3,
989            payload: MessagePayload::handshake(HandshakeMessagePayload(
990                HandshakePayload::CertificateTls13(cert_payload.into_owned()),
991            )),
992        };
993
994        Box::new(ExpectCertificate {
995            config: self.config,
996            server_name: self.server_name,
997            randoms: self.randoms,
998            suite: self.suite,
999            transcript: self.transcript,
1000            key_schedule: self.key_schedule,
1001            client_auth: self.client_auth,
1002            message_already_in_transcript: true,
1003            ech_retry_configs: self.ech_retry_configs,
1004        })
1005        .handle(cx, m)
1006    }
1007
1008    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1009        self
1010    }
1011}
1012
1013struct ExpectCertificate {
1014    config: Arc<ClientConfig>,
1015    server_name: ServerName<'static>,
1016    randoms: ConnectionRandoms,
1017    suite: &'static Tls13CipherSuite,
1018    transcript: HandshakeHash,
1019    key_schedule: KeyScheduleHandshake,
1020    client_auth: Option<ClientAuthDetails>,
1021    message_already_in_transcript: bool,
1022    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1023}
1024
1025impl State<ClientConnectionData> for ExpectCertificate {
1026    fn handle<'m>(
1027        mut self: Box<Self>,
1028        cx: &mut ClientContext<'_>,
1029        m: Message<'m>,
1030    ) -> hs::NextStateOrError<'m>
1031    where
1032        Self: 'm,
1033    {
1034        if !self.message_already_in_transcript {
1035            self.transcript.add_message(&m);
1036        }
1037        let cert_chain = require_handshake_msg_move!(
1038            m,
1039            HandshakeType::Certificate,
1040            HandshakePayload::CertificateTls13
1041        )?;
1042
1043        // This is only non-empty for client auth.
1044        if !cert_chain.context.0.is_empty() {
1045            return Err(cx.common.send_fatal_alert(
1046                AlertDescription::DecodeError,
1047                InvalidMessage::InvalidCertRequest,
1048            ));
1049        }
1050
1051        if cert_chain.any_entry_has_duplicate_extension()
1052            || cert_chain.any_entry_has_unknown_extension()
1053        {
1054            return Err(cx.common.send_fatal_alert(
1055                AlertDescription::UnsupportedExtension,
1056                PeerMisbehaved::BadCertChainExtensions,
1057            ));
1058        }
1059        let end_entity_ocsp = cert_chain.end_entity_ocsp().to_vec();
1060        let server_cert = ServerCertDetails::new(
1061            cert_chain
1062                .into_certificate_chain()
1063                .into_owned(),
1064            end_entity_ocsp,
1065        );
1066
1067        Ok(Box::new(ExpectCertificateVerify {
1068            config: self.config,
1069            server_name: self.server_name,
1070            randoms: self.randoms,
1071            suite: self.suite,
1072            transcript: self.transcript,
1073            key_schedule: self.key_schedule,
1074            server_cert,
1075            client_auth: self.client_auth,
1076            ech_retry_configs: self.ech_retry_configs,
1077        }))
1078    }
1079
1080    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1081        self
1082    }
1083}
1084
1085// --- TLS1.3 CertificateVerify ---
1086struct ExpectCertificateVerify<'a> {
1087    config: Arc<ClientConfig>,
1088    server_name: ServerName<'static>,
1089    randoms: ConnectionRandoms,
1090    suite: &'static Tls13CipherSuite,
1091    transcript: HandshakeHash,
1092    key_schedule: KeyScheduleHandshake,
1093    server_cert: ServerCertDetails<'a>,
1094    client_auth: Option<ClientAuthDetails>,
1095    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1096}
1097
1098impl State<ClientConnectionData> for ExpectCertificateVerify<'_> {
1099    fn handle<'m>(
1100        mut self: Box<Self>,
1101        cx: &mut ClientContext<'_>,
1102        m: Message<'m>,
1103    ) -> hs::NextStateOrError<'m>
1104    where
1105        Self: 'm,
1106    {
1107        let cert_verify = require_handshake_msg!(
1108            m,
1109            HandshakeType::CertificateVerify,
1110            HandshakePayload::CertificateVerify
1111        )?;
1112
1113        trace!("Server cert is {:?}", self.server_cert.cert_chain);
1114
1115        // 1. Verify the certificate chain.
1116        let (end_entity, intermediates) = self
1117            .server_cert
1118            .cert_chain
1119            .split_first()
1120            .ok_or(Error::NoCertificatesPresented)?;
1121
1122        let now = self.config.current_time()?;
1123
1124        let cert_verified = self
1125            .config
1126            .verifier
1127            .verify_server_cert(
1128                end_entity,
1129                intermediates,
1130                &self.server_name,
1131                &self.server_cert.ocsp_response,
1132                now,
1133            )
1134            .map_err(|err| {
1135                cx.common
1136                    .send_cert_verify_error_alert(err)
1137            })?;
1138
1139        // 2. Verify their signature on the handshake.
1140        let handshake_hash = self.transcript.current_hash();
1141        let sig_verified = self
1142            .config
1143            .verifier
1144            .verify_tls13_signature(
1145                construct_server_verify_message(&handshake_hash).as_ref(),
1146                end_entity,
1147                cert_verify,
1148            )
1149            .map_err(|err| {
1150                cx.common
1151                    .send_cert_verify_error_alert(err)
1152            })?;
1153
1154        cx.common.peer_certificates = Some(self.server_cert.cert_chain.into_owned());
1155        self.transcript.add_message(&m);
1156
1157        Ok(Box::new(ExpectFinished {
1158            config: self.config,
1159            server_name: self.server_name,
1160            randoms: self.randoms,
1161            suite: self.suite,
1162            transcript: self.transcript,
1163            key_schedule: self.key_schedule,
1164            client_auth: self.client_auth,
1165            cert_verified,
1166            sig_verified,
1167            ech_retry_configs: self.ech_retry_configs,
1168        }))
1169    }
1170
1171    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1172        Box::new(ExpectCertificateVerify {
1173            config: self.config,
1174            server_name: self.server_name,
1175            randoms: self.randoms,
1176            suite: self.suite,
1177            transcript: self.transcript,
1178            key_schedule: self.key_schedule,
1179            server_cert: self.server_cert.into_owned(),
1180            client_auth: self.client_auth,
1181            ech_retry_configs: self.ech_retry_configs,
1182        })
1183    }
1184}
1185
1186fn emit_compressed_certificate_tls13(
1187    flight: &mut HandshakeFlightTls13<'_>,
1188    certkey: &CertifiedKey,
1189    auth_context: Option<Vec<u8>>,
1190    compressor: &dyn compress::CertCompressor,
1191    config: &ClientConfig,
1192) {
1193    let mut cert_payload = CertificatePayloadTls13::new(certkey.cert.iter(), None);
1194    cert_payload.context = PayloadU8::new(auth_context.clone().unwrap_or_default());
1195
1196    let Ok(compressed) = config
1197        .cert_compression_cache
1198        .compression_for(compressor, &cert_payload)
1199    else {
1200        return emit_certificate_tls13(flight, Some(certkey), auth_context);
1201    };
1202
1203    flight.add(HandshakeMessagePayload(
1204        HandshakePayload::CompressedCertificate(compressed.compressed_cert_payload()),
1205    ));
1206}
1207
1208fn emit_certificate_tls13(
1209    flight: &mut HandshakeFlightTls13<'_>,
1210    certkey: Option<&CertifiedKey>,
1211    auth_context: Option<Vec<u8>>,
1212) {
1213    let certs = certkey
1214        .map(|ck| ck.cert.as_ref())
1215        .unwrap_or(&[][..]);
1216    let mut cert_payload = CertificatePayloadTls13::new(certs.iter(), None);
1217    cert_payload.context = PayloadU8::new(auth_context.unwrap_or_default());
1218
1219    flight.add(HandshakeMessagePayload(HandshakePayload::CertificateTls13(
1220        cert_payload,
1221    )));
1222}
1223
1224fn emit_certverify_tls13(
1225    flight: &mut HandshakeFlightTls13<'_>,
1226    signer: &dyn Signer,
1227) -> Result<(), Error> {
1228    let message = construct_client_verify_message(&flight.transcript.current_hash());
1229
1230    let scheme = signer.scheme();
1231    let sig = signer.sign(message.as_ref())?;
1232    let dss = DigitallySignedStruct::new(scheme, sig);
1233
1234    flight.add(HandshakeMessagePayload(
1235        HandshakePayload::CertificateVerify(dss),
1236    ));
1237    Ok(())
1238}
1239
1240fn emit_finished_tls13(flight: &mut HandshakeFlightTls13<'_>, verify_data: &crypto::hmac::Tag) {
1241    let verify_data_payload = Payload::new(verify_data.as_ref());
1242
1243    flight.add(HandshakeMessagePayload(HandshakePayload::Finished(
1244        verify_data_payload,
1245    )));
1246}
1247
1248fn emit_end_of_early_data_tls13(transcript: &mut HandshakeHash, common: &mut CommonState) {
1249    if common.is_quic() {
1250        return;
1251    }
1252
1253    let m = Message {
1254        version: ProtocolVersion::TLSv1_3,
1255        payload: MessagePayload::handshake(HandshakeMessagePayload(
1256            HandshakePayload::EndOfEarlyData,
1257        )),
1258    };
1259
1260    transcript.add_message(&m);
1261    common.send_msg(m, true);
1262}
1263
1264struct ExpectFinished {
1265    config: Arc<ClientConfig>,
1266    server_name: ServerName<'static>,
1267    randoms: ConnectionRandoms,
1268    suite: &'static Tls13CipherSuite,
1269    transcript: HandshakeHash,
1270    key_schedule: KeyScheduleHandshake,
1271    client_auth: Option<ClientAuthDetails>,
1272    cert_verified: verify::ServerCertVerified,
1273    sig_verified: verify::HandshakeSignatureValid,
1274    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1275}
1276
1277impl State<ClientConnectionData> for ExpectFinished {
1278    fn handle<'m>(
1279        self: Box<Self>,
1280        cx: &mut ClientContext<'_>,
1281        m: Message<'m>,
1282    ) -> hs::NextStateOrError<'m>
1283    where
1284        Self: 'm,
1285    {
1286        let mut st = *self;
1287        let finished =
1288            require_handshake_msg!(m, HandshakeType::Finished, HandshakePayload::Finished)?;
1289
1290        let handshake_hash = st.transcript.current_hash();
1291        let expect_verify_data = st
1292            .key_schedule
1293            .sign_server_finish(&handshake_hash);
1294
1295        let fin = match ConstantTimeEq::ct_eq(expect_verify_data.as_ref(), finished.bytes()).into()
1296        {
1297            true => verify::FinishedMessageVerified::assertion(),
1298            false => {
1299                return Err(cx
1300                    .common
1301                    .send_fatal_alert(AlertDescription::DecryptError, Error::DecryptError));
1302            }
1303        };
1304
1305        st.transcript.add_message(&m);
1306
1307        let hash_after_handshake = st.transcript.current_hash();
1308        /* The EndOfEarlyData message to server is still encrypted with early data keys,
1309         * but appears in the transcript after the server Finished. */
1310        if cx.common.early_traffic {
1311            emit_end_of_early_data_tls13(&mut st.transcript, cx.common);
1312            cx.common.early_traffic = false;
1313            cx.data.early_data.finished();
1314            st.key_schedule
1315                .set_handshake_encrypter(cx.common);
1316        }
1317
1318        let mut flight = HandshakeFlightTls13::new(&mut st.transcript);
1319
1320        /* Send our authentication/finished messages.  These are still encrypted
1321         * with our handshake keys. */
1322        if let Some(client_auth) = st.client_auth {
1323            match client_auth {
1324                ClientAuthDetails::Empty {
1325                    auth_context_tls13: auth_context,
1326                } => {
1327                    emit_certificate_tls13(&mut flight, None, auth_context);
1328                }
1329                ClientAuthDetails::Verify {
1330                    auth_context_tls13: auth_context,
1331                    ..
1332                } if cx.data.ech_status == EchStatus::Rejected => {
1333                    // If ECH was offered, and rejected, we MUST respond with
1334                    // an empty certificate message.
1335                    emit_certificate_tls13(&mut flight, None, auth_context);
1336                }
1337                ClientAuthDetails::Verify {
1338                    certkey,
1339                    signer,
1340                    auth_context_tls13: auth_context,
1341                    compressor,
1342                } => {
1343                    if let Some(compressor) = compressor {
1344                        emit_compressed_certificate_tls13(
1345                            &mut flight,
1346                            &certkey,
1347                            auth_context,
1348                            compressor,
1349                            &st.config,
1350                        );
1351                    } else {
1352                        emit_certificate_tls13(&mut flight, Some(&certkey), auth_context);
1353                    }
1354                    emit_certverify_tls13(&mut flight, signer.as_ref())?;
1355                }
1356            }
1357        }
1358
1359        let (key_schedule_pre_finished, verify_data) = st
1360            .key_schedule
1361            .into_pre_finished_client_traffic(
1362                hash_after_handshake,
1363                flight.transcript.current_hash(),
1364                &*st.config.key_log,
1365                &st.randoms.client,
1366            );
1367
1368        emit_finished_tls13(&mut flight, &verify_data);
1369        flight.finish(cx.common);
1370
1371        /* We're now sure this server supports TLS1.3.  But if we run out of TLS1.3 tickets
1372         * when connecting to it again, we definitely don't want to attempt a TLS1.2 resumption. */
1373        st.config
1374            .resumption
1375            .store
1376            .remove_tls12_session(&st.server_name);
1377
1378        /* Now move to our application traffic keys. */
1379        cx.common.check_aligned_handshake()?;
1380        let key_schedule_traffic = key_schedule_pre_finished.into_traffic(cx.common);
1381        cx.common
1382            .start_traffic(&mut cx.sendable_plaintext);
1383
1384        // Now that we've reached the end of the normal handshake we must enforce ECH acceptance by
1385        // sending an alert and returning an error (potentially with retry configs) if the server
1386        // did not accept our ECH offer.
1387        if cx.data.ech_status == EchStatus::Rejected {
1388            return Err(ech::fatal_alert_required(st.ech_retry_configs, cx.common));
1389        }
1390
1391        let st = ExpectTraffic {
1392            config: st.config.clone(),
1393            session_storage: st.config.resumption.store.clone(),
1394            server_name: st.server_name,
1395            suite: st.suite,
1396            transcript: st.transcript,
1397            key_schedule: key_schedule_traffic,
1398            _cert_verified: st.cert_verified,
1399            _sig_verified: st.sig_verified,
1400            _fin_verified: fin,
1401        };
1402
1403        Ok(match cx.common.is_quic() {
1404            true => Box::new(ExpectQuicTraffic(st)),
1405            false => Box::new(st),
1406        })
1407    }
1408
1409    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1410        self
1411    }
1412}
1413
1414// -- Traffic transit state (TLS1.3) --
1415// In this state we can be sent tickets, key updates,
1416// and application data.
1417struct ExpectTraffic {
1418    config: Arc<ClientConfig>,
1419    session_storage: Arc<dyn ClientSessionStore>,
1420    server_name: ServerName<'static>,
1421    suite: &'static Tls13CipherSuite,
1422    transcript: HandshakeHash,
1423    key_schedule: KeyScheduleTraffic,
1424    _cert_verified: verify::ServerCertVerified,
1425    _sig_verified: verify::HandshakeSignatureValid,
1426    _fin_verified: verify::FinishedMessageVerified,
1427}
1428
1429impl ExpectTraffic {
1430    fn handle_new_ticket_impl(
1431        &mut self,
1432        cx: &mut KernelContext<'_>,
1433        nst: &NewSessionTicketPayloadTls13,
1434    ) -> Result<(), Error> {
1435        if nst.has_duplicate_extension() {
1436            return Err(PeerMisbehaved::DuplicateNewSessionTicketExtensions.into());
1437        }
1438
1439        let handshake_hash = self.transcript.current_hash();
1440        let secret = ResumptionSecret::new(&self.key_schedule, &handshake_hash)
1441            .derive_ticket_psk(&nst.nonce.0);
1442
1443        let now = self.config.current_time()?;
1444
1445        #[allow(unused_mut)]
1446        let mut value = persist::Tls13ClientSessionValue::new(
1447            self.suite,
1448            nst.ticket.clone(),
1449            secret.as_ref(),
1450            cx.peer_certificates
1451                .cloned()
1452                .unwrap_or_default(),
1453            &self.config.verifier,
1454            &self.config.client_auth_cert_resolver,
1455            now,
1456            nst.lifetime,
1457            nst.age_add,
1458            nst.max_early_data_size()
1459                .unwrap_or_default(),
1460        );
1461
1462        if cx.is_quic() {
1463            if let Some(sz) = nst.max_early_data_size() {
1464                if sz != 0 && sz != 0xffff_ffff {
1465                    return Err(PeerMisbehaved::InvalidMaxEarlyDataSize.into());
1466                }
1467            }
1468
1469            if let Some(quic_params) = &cx.quic.params {
1470                value.set_quic_params(quic_params);
1471            }
1472        }
1473
1474        self.session_storage
1475            .insert_tls13_ticket(self.server_name.clone(), value);
1476        Ok(())
1477    }
1478
1479    fn handle_new_ticket_tls13(
1480        &mut self,
1481        cx: &mut ClientContext<'_>,
1482        nst: &NewSessionTicketPayloadTls13,
1483    ) -> Result<(), Error> {
1484        if nst.has_duplicate_extension() {
1485            return Err(cx.common.send_fatal_alert(
1486                AlertDescription::IllegalParameter,
1487                PeerMisbehaved::DuplicateNewSessionTicketExtensions,
1488            ));
1489        }
1490
1491        let mut kcx = KernelContext {
1492            peer_certificates: cx.common.peer_certificates.as_ref(),
1493            protocol: cx.common.protocol,
1494            quic: &cx.common.quic,
1495        };
1496        cx.common.tls13_tickets_received = cx
1497            .common
1498            .tls13_tickets_received
1499            .saturating_add(1);
1500        self.handle_new_ticket_impl(&mut kcx, nst)
1501    }
1502
1503    fn handle_key_update(
1504        &mut self,
1505        common: &mut CommonState,
1506        key_update_request: &KeyUpdateRequest,
1507    ) -> Result<(), Error> {
1508        if let Protocol::Quic = common.protocol {
1509            return Err(common.send_fatal_alert(
1510                AlertDescription::UnexpectedMessage,
1511                PeerMisbehaved::KeyUpdateReceivedInQuicConnection,
1512            ));
1513        }
1514
1515        // Mustn't be interleaved with other handshake messages.
1516        common.check_aligned_handshake()?;
1517
1518        if common.should_update_key(key_update_request)? {
1519            self.key_schedule
1520                .update_encrypter_and_notify(common);
1521        }
1522
1523        // Update our read-side keys.
1524        self.key_schedule
1525            .update_decrypter(common);
1526        Ok(())
1527    }
1528}
1529
1530impl State<ClientConnectionData> for ExpectTraffic {
1531    fn handle<'m>(
1532        mut self: Box<Self>,
1533        cx: &mut ClientContext<'_>,
1534        m: Message<'m>,
1535    ) -> hs::NextStateOrError<'m>
1536    where
1537        Self: 'm,
1538    {
1539        match m.payload {
1540            MessagePayload::ApplicationData(payload) => cx
1541                .common
1542                .take_received_plaintext(payload),
1543            MessagePayload::Handshake {
1544                parsed: HandshakeMessagePayload(HandshakePayload::NewSessionTicketTls13(new_ticket)),
1545                ..
1546            } => self.handle_new_ticket_tls13(cx, &new_ticket)?,
1547            MessagePayload::Handshake {
1548                parsed: HandshakeMessagePayload(HandshakePayload::KeyUpdate(key_update)),
1549                ..
1550            } => self.handle_key_update(cx.common, &key_update)?,
1551            payload => {
1552                return Err(inappropriate_handshake_message(
1553                    &payload,
1554                    &[ContentType::ApplicationData, ContentType::Handshake],
1555                    &[HandshakeType::NewSessionTicket, HandshakeType::KeyUpdate],
1556                ));
1557            }
1558        }
1559
1560        Ok(self)
1561    }
1562
1563    fn send_key_update_request(&mut self, common: &mut CommonState) -> Result<(), Error> {
1564        self.key_schedule
1565            .request_key_update_and_update_encrypter(common)
1566    }
1567
1568    fn export_keying_material(
1569        &self,
1570        output: &mut [u8],
1571        label: &[u8],
1572        context: Option<&[u8]>,
1573    ) -> Result<(), Error> {
1574        self.key_schedule
1575            .export_keying_material(output, label, context)
1576    }
1577
1578    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
1579        self.key_schedule
1580            .extract_secrets(Side::Client)
1581    }
1582
1583    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1584        Ok(self)
1585    }
1586
1587    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1588        self
1589    }
1590}
1591
1592impl KernelState for ExpectTraffic {
1593    fn update_secrets(&mut self, dir: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1594        self.key_schedule
1595            .refresh_traffic_secret(match dir {
1596                Direction::Transmit => Side::Client,
1597                Direction::Receive => Side::Server,
1598            })
1599    }
1600
1601    fn handle_new_session_ticket(
1602        &mut self,
1603        cx: &mut KernelContext<'_>,
1604        message: &NewSessionTicketPayloadTls13,
1605    ) -> Result<(), Error> {
1606        self.handle_new_ticket_impl(cx, message)
1607    }
1608}
1609
1610struct ExpectQuicTraffic(ExpectTraffic);
1611
1612impl State<ClientConnectionData> for ExpectQuicTraffic {
1613    fn handle<'m>(
1614        mut self: Box<Self>,
1615        cx: &mut ClientContext<'_>,
1616        m: Message<'m>,
1617    ) -> hs::NextStateOrError<'m>
1618    where
1619        Self: 'm,
1620    {
1621        let nst = require_handshake_msg!(
1622            m,
1623            HandshakeType::NewSessionTicket,
1624            HandshakePayload::NewSessionTicketTls13
1625        )?;
1626        self.0
1627            .handle_new_ticket_tls13(cx, nst)?;
1628        Ok(self)
1629    }
1630
1631    fn export_keying_material(
1632        &self,
1633        output: &mut [u8],
1634        label: &[u8],
1635        context: Option<&[u8]>,
1636    ) -> Result<(), Error> {
1637        self.0
1638            .export_keying_material(output, label, context)
1639    }
1640
1641    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1642        Ok(self)
1643    }
1644
1645    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1646        self
1647    }
1648}
1649
1650impl KernelState for ExpectQuicTraffic {
1651    fn update_secrets(&mut self, _: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1652        Err(Error::General(
1653            "KeyUpdate is not supported for QUIC connections".into(),
1654        ))
1655    }
1656
1657    fn handle_new_session_ticket(
1658        &mut self,
1659        cx: &mut KernelContext<'_>,
1660        nst: &NewSessionTicketPayloadTls13,
1661    ) -> Result<(), Error> {
1662        self.0.handle_new_ticket_impl(cx, nst)
1663    }
1664}