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