1use crate::check::inappropriate_handshake_message;
2#[cfg(feature = "quic")]
3use crate::common_state::Protocol;
4#[cfg(feature = "secret_extraction")]
5use crate::common_state::Side;
6use crate::common_state::{CommonState, State};
7use crate::conn::ConnectionRandoms;
8use crate::enums::{
9 AlertDescription, ContentType, HandshakeType, ProtocolVersion, SignatureScheme,
10};
11use crate::error::{Error, InvalidMessage, PeerIncompatible, PeerMisbehaved};
12use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
13use crate::kx;
14#[cfg(feature = "logging")]
15use crate::log::{debug, trace, warn};
16use crate::msgs::base::{Payload, PayloadU8};
17use crate::msgs::ccs::ChangeCipherSpecPayload;
18use crate::msgs::enums::ExtensionType;
19use crate::msgs::enums::KeyUpdateRequest;
20use crate::msgs::handshake::NewSessionTicketPayloadTLS13;
21use crate::msgs::handshake::{CertificateEntry, CertificatePayloadTLS13};
22use crate::msgs::handshake::{ClientExtension, ServerExtension};
23use crate::msgs::handshake::{HandshakeMessagePayload, HandshakePayload};
24use crate::msgs::handshake::{HasServerExtensions, ServerHelloPayload};
25use crate::msgs::handshake::{PresharedKeyIdentity, PresharedKeyOffer};
26use crate::msgs::message::{Message, MessagePayload};
27use crate::msgs::persist;
28#[cfg(feature = "secret_extraction")]
29use crate::suites::PartiallyExtractedSecrets;
30use crate::tls13::key_schedule::{
31 KeyScheduleEarly, KeyScheduleHandshake, KeySchedulePreHandshake, KeyScheduleTraffic,
32};
33use crate::tls13::Tls13CipherSuite;
34use crate::verify::{self, DigitallySignedStruct};
35use crate::{sign, KeyLog};
36
37use super::client_conn::ClientConnectionData;
38use super::hs::ClientContext;
39use crate::client::common::ServerCertDetails;
40use crate::client::common::{ClientAuthDetails, ClientHelloDetails};
41use crate::client::{hs, ClientConfig, ClientSessionStore, ServerName};
42
43use crate::ticketer::TimeBase;
44use ring::constant_time;
45
46use crate::sign::{CertifiedKey, Signer};
47use std::sync::Arc;
48
49static ALLOWED_PLAINTEXT_EXTS: &[ExtensionType] = &[
51 ExtensionType::KeyShare,
52 ExtensionType::PreSharedKey,
53 ExtensionType::SupportedVersions,
54];
55
56static DISALLOWED_TLS13_EXTS: &[ExtensionType] = &[
59 ExtensionType::ECPointFormats,
60 ExtensionType::SessionTicket,
61 ExtensionType::RenegotiationInfo,
62 ExtensionType::ExtendedMasterSecret,
63];
64
65pub(super) fn handle_server_hello(
66 config: Arc<ClientConfig>,
67 cx: &mut ClientContext,
68 server_hello: &ServerHelloPayload,
69 mut resuming_session: Option<persist::Tls13ClientSessionValue>,
70 server_name: ServerName,
71 randoms: ConnectionRandoms,
72 suite: &'static Tls13CipherSuite,
73 transcript: HandshakeHash,
74 early_key_schedule: Option<KeyScheduleEarly>,
75 hello: ClientHelloDetails,
76 our_key_share: kx::KeyExchange,
77 mut sent_tls13_fake_ccs: bool,
78) -> hs::NextStateOrError {
79 validate_server_hello(cx.common, server_hello)?;
80
81 let their_key_share = server_hello
82 .get_key_share()
83 .ok_or_else(|| {
84 cx.common.send_fatal_alert(
85 AlertDescription::MissingExtension,
86 PeerMisbehaved::MissingKeyShare,
87 )
88 })?;
89
90 if our_key_share.group() != their_key_share.group {
91 return Err({
92 cx.common.send_fatal_alert(
93 AlertDescription::IllegalParameter,
94 PeerMisbehaved::WrongGroupForKeyShare,
95 )
96 });
97 }
98
99 let key_schedule_pre_handshake = if let (Some(selected_psk), Some(early_key_schedule)) =
100 (server_hello.get_psk_index(), early_key_schedule)
101 {
102 if let Some(ref resuming) = resuming_session {
103 let resuming_suite = match suite.can_resume_from(resuming.suite()) {
104 Some(resuming) => resuming,
105 None => {
106 return Err({
107 cx.common.send_fatal_alert(
108 AlertDescription::IllegalParameter,
109 PeerMisbehaved::ResumptionOfferedWithIncompatibleCipherSuite,
110 )
111 });
112 }
113 };
114
115 if cx.data.early_data.is_enabled() && resuming_suite != suite {
118 return Err({
119 cx.common.send_fatal_alert(
120 AlertDescription::IllegalParameter,
121 PeerMisbehaved::EarlyDataOfferedWithVariedCipherSuite,
122 )
123 });
124 }
125
126 if selected_psk != 0 {
127 return Err({
128 cx.common.send_fatal_alert(
129 AlertDescription::IllegalParameter,
130 PeerMisbehaved::SelectedInvalidPsk,
131 )
132 });
133 }
134
135 debug!("Resuming using PSK");
136 } else {
138 return Err(PeerMisbehaved::SelectedUnofferedPsk.into());
139 }
140 KeySchedulePreHandshake::from(early_key_schedule)
141 } else {
142 debug!("Not resuming");
143 cx.data.early_data.rejected();
145 cx.common.early_traffic = false;
146 resuming_session.take();
147 KeySchedulePreHandshake::new(suite)
148 };
149
150 let key_schedule = our_key_share.complete(&their_key_share.payload.0, |secret| {
151 key_schedule_pre_handshake.into_handshake(secret)
152 })?;
153
154 config
156 .resumption
157 .store
158 .set_kx_hint(&server_name, their_key_share.group);
159
160 cx.common.check_aligned_handshake()?;
163
164 let hash_at_client_recvd_server_hello = transcript.get_current_hash();
165 let key_schedule = key_schedule.derive_client_handshake_secrets(
166 cx.data.early_data.is_enabled(),
167 hash_at_client_recvd_server_hello,
168 suite,
169 &*config.key_log,
170 &randoms.client,
171 cx.common,
172 );
173
174 emit_fake_ccs(&mut sent_tls13_fake_ccs, cx.common);
175
176 Ok(Box::new(ExpectEncryptedExtensions {
177 config,
178 resuming_session,
179 server_name,
180 randoms,
181 suite,
182 transcript,
183 key_schedule,
184 hello,
185 }))
186}
187
188fn validate_server_hello(
189 common: &mut CommonState,
190 server_hello: &ServerHelloPayload,
191) -> Result<(), Error> {
192 for ext in &server_hello.extensions {
193 if !ALLOWED_PLAINTEXT_EXTS.contains(&ext.get_type()) {
194 return Err(common.send_fatal_alert(
195 AlertDescription::UnsupportedExtension,
196 PeerMisbehaved::UnexpectedCleartextExtension,
197 ));
198 }
199 }
200
201 Ok(())
202}
203
204pub(super) fn initial_key_share(
205 config: &ClientConfig,
206 server_name: &ServerName,
207) -> Result<kx::KeyExchange, Error> {
208 let group = config
209 .resumption
210 .store
211 .kx_hint(server_name)
212 .and_then(|group| kx::KeyExchange::choose(group, &config.kx_groups))
213 .unwrap_or_else(|| {
214 config
215 .kx_groups
216 .first()
217 .expect("No kx groups configured")
218 });
219
220 kx::KeyExchange::start(group).ok_or(Error::FailedToGetRandomBytes)
221}
222
223pub(super) fn fill_in_psk_binder(
226 resuming: &persist::Tls13ClientSessionValue,
227 transcript: &HandshakeHashBuffer,
228 hmp: &mut HandshakeMessagePayload,
229) -> KeyScheduleEarly {
230 let suite = resuming.suite();
232 let suite_hash = suite.hash_algorithm();
233
234 let binder_plaintext = hmp.get_encoding_for_binder_signing();
237 let handshake_hash = transcript.get_hash_given(suite_hash, &binder_plaintext);
238
239 let key_schedule = KeyScheduleEarly::new(suite, resuming.secret());
242 let real_binder = key_schedule.resumption_psk_binder_key_and_sign_verify_data(&handshake_hash);
243
244 if let HandshakePayload::ClientHello(ref mut ch) = hmp.payload {
245 ch.set_psk_binder(real_binder.as_ref());
246 };
247
248 key_schedule
249}
250
251pub(super) fn prepare_resumption(
252 config: &ClientConfig,
253 cx: &mut ClientContext<'_>,
254 resuming_session: &persist::Retrieved<&persist::Tls13ClientSessionValue>,
255 exts: &mut Vec<ClientExtension>,
256 doing_retry: bool,
257) {
258 let resuming_suite = resuming_session.suite();
259 cx.common.suite = Some(resuming_suite.into());
260 cx.data.resumption_ciphersuite = Some(resuming_suite.into());
261 let max_early_data_size = resuming_session.max_early_data_size();
264 if config.enable_early_data && max_early_data_size > 0 && !doing_retry {
265 cx.data
266 .early_data
267 .enable(max_early_data_size as usize);
268 exts.push(ClientExtension::EarlyData);
269 }
270
271 let obfuscated_ticket_age = resuming_session.obfuscated_ticket_age();
277
278 let binder_len = resuming_suite
279 .hash_algorithm()
280 .output_len();
281 let binder = vec![0u8; binder_len];
282
283 let psk_identity =
284 PresharedKeyIdentity::new(resuming_session.ticket().to_vec(), obfuscated_ticket_age);
285 let psk_ext = PresharedKeyOffer::new(psk_identity, binder);
286 exts.push(ClientExtension::PresharedKey(psk_ext));
287}
288
289pub(super) fn derive_early_traffic_secret(
290 key_log: &dyn KeyLog,
291 cx: &mut ClientContext<'_>,
292 resuming_suite: &'static Tls13CipherSuite,
293 early_key_schedule: &KeyScheduleEarly,
294 sent_tls13_fake_ccs: &mut bool,
295 transcript_buffer: &HandshakeHashBuffer,
296 client_random: &[u8; 32],
297) {
298 emit_fake_ccs(sent_tls13_fake_ccs, cx.common);
300
301 let client_hello_hash = transcript_buffer.get_hash_given(resuming_suite.hash_algorithm(), &[]);
302 early_key_schedule.client_early_traffic_secret(
303 &client_hello_hash,
304 key_log,
305 client_random,
306 cx.common,
307 );
308
309 cx.common.early_traffic = true;
311 trace!("Starting early data traffic");
312}
313
314pub(super) fn emit_fake_ccs(sent_tls13_fake_ccs: &mut bool, common: &mut CommonState) {
315 if common.is_quic() {
316 return;
317 }
318
319 if std::mem::replace(sent_tls13_fake_ccs, true) {
320 return;
321 }
322
323 let m = Message {
324 version: ProtocolVersion::TLSv1_2,
325 payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload {}),
326 };
327 common.send_msg(m, false);
328}
329
330fn validate_encrypted_extensions(
331 common: &mut CommonState,
332 hello: &ClientHelloDetails,
333 exts: &Vec<ServerExtension>,
334) -> Result<(), Error> {
335 if exts.has_duplicate_extension() {
336 return Err(common.send_fatal_alert(
337 AlertDescription::DecodeError,
338 PeerMisbehaved::DuplicateEncryptedExtensions,
339 ));
340 }
341
342 if hello.server_sent_unsolicited_extensions(exts, &[]) {
343 return Err(common.send_fatal_alert(
344 AlertDescription::UnsupportedExtension,
345 PeerMisbehaved::UnsolicitedEncryptedExtension,
346 ));
347 }
348
349 for ext in exts {
350 if ALLOWED_PLAINTEXT_EXTS.contains(&ext.get_type())
351 || DISALLOWED_TLS13_EXTS.contains(&ext.get_type())
352 {
353 return Err(common.send_fatal_alert(
354 AlertDescription::UnsupportedExtension,
355 PeerMisbehaved::DisallowedEncryptedExtension,
356 ));
357 }
358 }
359
360 Ok(())
361}
362
363struct ExpectEncryptedExtensions {
364 config: Arc<ClientConfig>,
365 resuming_session: Option<persist::Tls13ClientSessionValue>,
366 server_name: ServerName,
367 randoms: ConnectionRandoms,
368 suite: &'static Tls13CipherSuite,
369 transcript: HandshakeHash,
370 key_schedule: KeyScheduleHandshake,
371 hello: ClientHelloDetails,
372}
373
374impl State<ClientConnectionData> for ExpectEncryptedExtensions {
375 fn handle(mut self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
376 let exts = require_handshake_msg!(
377 m,
378 HandshakeType::EncryptedExtensions,
379 HandshakePayload::EncryptedExtensions
380 )?;
381 debug!("TLS1.3 encrypted extensions: {:?}", exts);
382 self.transcript.add_message(&m);
383
384 validate_encrypted_extensions(cx.common, &self.hello, exts)?;
385 hs::process_alpn_protocol(cx.common, &self.config, exts.get_alpn_protocol())?;
386
387 #[cfg(feature = "quic")]
388 {
389 if cx.common.is_quic() {
391 match exts.get_quic_params_extension() {
392 Some(params) => cx.common.quic.params = Some(params),
393 None => {
394 return Err(cx
395 .common
396 .missing_extension(PeerMisbehaved::MissingQuicTransportParameters));
397 }
398 }
399 }
400 }
401
402 if let Some(resuming_session) = self.resuming_session {
403 let was_early_traffic = cx.common.early_traffic;
404 if was_early_traffic {
405 if exts.early_data_extension_offered() {
406 cx.data.early_data.accepted();
407 } else {
408 cx.data.early_data.rejected();
409 cx.common.early_traffic = false;
410 }
411 }
412
413 if was_early_traffic && !cx.common.early_traffic {
414 self.key_schedule
416 .set_handshake_encrypter(cx.common);
417 }
418
419 cx.common.peer_certificates = Some(
420 resuming_session
421 .server_cert_chain()
422 .to_vec(),
423 );
424
425 let cert_verified = verify::ServerCertVerified::assertion();
428 let sig_verified = verify::HandshakeSignatureValid::assertion();
429 Ok(Box::new(ExpectFinished {
430 config: self.config,
431 server_name: self.server_name,
432 randoms: self.randoms,
433 suite: self.suite,
434 transcript: self.transcript,
435 key_schedule: self.key_schedule,
436 client_auth: None,
437 cert_verified,
438 sig_verified,
439 }))
440 } else {
441 if exts.early_data_extension_offered() {
442 return Err(PeerMisbehaved::EarlyDataExtensionWithoutResumption.into());
443 }
444 Ok(Box::new(ExpectCertificateOrCertReq {
445 config: self.config,
446 server_name: self.server_name,
447 randoms: self.randoms,
448 suite: self.suite,
449 transcript: self.transcript,
450 key_schedule: self.key_schedule,
451 may_send_sct_list: self.hello.server_may_send_sct_list(),
452 }))
453 }
454 }
455}
456
457struct ExpectCertificateOrCertReq {
458 config: Arc<ClientConfig>,
459 server_name: ServerName,
460 randoms: ConnectionRandoms,
461 suite: &'static Tls13CipherSuite,
462 transcript: HandshakeHash,
463 key_schedule: KeyScheduleHandshake,
464 may_send_sct_list: bool,
465}
466
467impl State<ClientConnectionData> for ExpectCertificateOrCertReq {
468 fn handle(self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
469 match m.payload {
470 MessagePayload::Handshake {
471 parsed:
472 HandshakeMessagePayload {
473 payload: HandshakePayload::CertificateTLS13(..),
474 ..
475 },
476 ..
477 } => Box::new(ExpectCertificate {
478 config: self.config,
479 server_name: self.server_name,
480 randoms: self.randoms,
481 suite: self.suite,
482 transcript: self.transcript,
483 key_schedule: self.key_schedule,
484 may_send_sct_list: self.may_send_sct_list,
485 client_auth: None,
486 })
487 .handle(cx, m),
488 MessagePayload::Handshake {
489 parsed:
490 HandshakeMessagePayload {
491 payload: HandshakePayload::CertificateRequestTLS13(..),
492 ..
493 },
494 ..
495 } => Box::new(ExpectCertificateRequest {
496 config: self.config,
497 server_name: self.server_name,
498 randoms: self.randoms,
499 suite: self.suite,
500 transcript: self.transcript,
501 key_schedule: self.key_schedule,
502 may_send_sct_list: self.may_send_sct_list,
503 })
504 .handle(cx, m),
505 payload => Err(inappropriate_handshake_message(
506 &payload,
507 &[ContentType::Handshake],
508 &[
509 HandshakeType::Certificate,
510 HandshakeType::CertificateRequest,
511 ],
512 )),
513 }
514 }
515}
516
517struct ExpectCertificateRequest {
521 config: Arc<ClientConfig>,
522 server_name: ServerName,
523 randoms: ConnectionRandoms,
524 suite: &'static Tls13CipherSuite,
525 transcript: HandshakeHash,
526 key_schedule: KeyScheduleHandshake,
527 may_send_sct_list: bool,
528}
529
530impl State<ClientConnectionData> for ExpectCertificateRequest {
531 fn handle(mut self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
532 let certreq = &require_handshake_msg!(
533 m,
534 HandshakeType::CertificateRequest,
535 HandshakePayload::CertificateRequestTLS13
536 )?;
537 self.transcript.add_message(&m);
538 debug!("Got CertificateRequest {:?}", certreq);
539
540 if !certreq.context.0.is_empty() {
545 warn!("Server sent non-empty certreq context");
546 return Err(cx.common.send_fatal_alert(
547 AlertDescription::DecodeError,
548 InvalidMessage::InvalidCertRequest,
549 ));
550 }
551
552 let tls13_sign_schemes = sign::supported_sign_tls13();
553 let no_sigschemes = Vec::new();
554 let compat_sigschemes = certreq
555 .get_sigalgs_extension()
556 .unwrap_or(&no_sigschemes)
557 .iter()
558 .cloned()
559 .filter(|scheme| tls13_sign_schemes.contains(scheme))
560 .collect::<Vec<SignatureScheme>>();
561
562 if compat_sigschemes.is_empty() {
563 return Err(cx.common.send_fatal_alert(
564 AlertDescription::HandshakeFailure,
565 PeerIncompatible::NoCertificateRequestSignatureSchemesInCommon,
566 ));
567 }
568
569 let client_auth = ClientAuthDetails::resolve(
570 self.config
571 .client_auth_cert_resolver
572 .as_ref(),
573 certreq.get_authorities_extension(),
574 &compat_sigschemes,
575 Some(certreq.context.0.clone()),
576 );
577
578 Ok(Box::new(ExpectCertificate {
579 config: self.config,
580 server_name: self.server_name,
581 randoms: self.randoms,
582 suite: self.suite,
583 transcript: self.transcript,
584 key_schedule: self.key_schedule,
585 may_send_sct_list: self.may_send_sct_list,
586 client_auth: Some(client_auth),
587 }))
588 }
589}
590
591struct ExpectCertificate {
592 config: Arc<ClientConfig>,
593 server_name: ServerName,
594 randoms: ConnectionRandoms,
595 suite: &'static Tls13CipherSuite,
596 transcript: HandshakeHash,
597 key_schedule: KeyScheduleHandshake,
598 may_send_sct_list: bool,
599 client_auth: Option<ClientAuthDetails>,
600}
601
602impl State<ClientConnectionData> for ExpectCertificate {
603 fn handle(mut self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
604 let cert_chain = require_handshake_msg!(
605 m,
606 HandshakeType::Certificate,
607 HandshakePayload::CertificateTLS13
608 )?;
609 self.transcript.add_message(&m);
610
611 if !cert_chain.context.0.is_empty() {
613 return Err(cx.common.send_fatal_alert(
614 AlertDescription::DecodeError,
615 InvalidMessage::InvalidCertRequest,
616 ));
617 }
618
619 if cert_chain.any_entry_has_duplicate_extension()
620 || cert_chain.any_entry_has_unknown_extension()
621 {
622 return Err(cx.common.send_fatal_alert(
623 AlertDescription::UnsupportedExtension,
624 PeerMisbehaved::BadCertChainExtensions,
625 ));
626 }
627
628 let server_cert = ServerCertDetails::new(
629 cert_chain.convert(),
630 cert_chain.get_end_entity_ocsp(),
631 cert_chain
632 .get_end_entity_scts()
633 .map(|scts| scts.to_vec()),
634 );
635
636 if let Some(sct_list) = server_cert.scts.as_ref() {
637 if hs::sct_list_is_invalid(sct_list) {
638 return Err(PeerMisbehaved::InvalidSctList.into());
639 }
640
641 if !self.may_send_sct_list {
642 return Err(PeerMisbehaved::UnsolicitedSctList.into());
643 }
644 }
645
646 Ok(Box::new(ExpectCertificateVerify {
647 config: self.config,
648 server_name: self.server_name,
649 randoms: self.randoms,
650 suite: self.suite,
651 transcript: self.transcript,
652 key_schedule: self.key_schedule,
653 server_cert,
654 client_auth: self.client_auth,
655 }))
656 }
657}
658
659struct ExpectCertificateVerify {
661 config: Arc<ClientConfig>,
662 server_name: ServerName,
663 randoms: ConnectionRandoms,
664 suite: &'static Tls13CipherSuite,
665 transcript: HandshakeHash,
666 key_schedule: KeyScheduleHandshake,
667 server_cert: ServerCertDetails,
668 client_auth: Option<ClientAuthDetails>,
669}
670
671impl State<ClientConnectionData> for ExpectCertificateVerify {
672 fn handle(mut self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
673 let cert_verify = require_handshake_msg!(
674 m,
675 HandshakeType::CertificateVerify,
676 HandshakePayload::CertificateVerify
677 )?;
678
679 trace!("Server cert is {:?}", self.server_cert.cert_chain);
680
681 let (end_entity, intermediates) = self
683 .server_cert
684 .cert_chain
685 .split_first()
686 .ok_or(Error::NoCertificatesPresented)?;
687 let now = std::time::SystemTime::now();
688 let cert_verified = self
689 .config
690 .verifier
691 .verify_server_cert(
692 end_entity,
693 intermediates,
694 &self.server_name,
695 &mut self.server_cert.scts(),
696 &self.server_cert.ocsp_response,
697 now,
698 )
699 .map_err(|err| {
700 cx.common
701 .send_cert_verify_error_alert(err)
702 })?;
703
704 let handshake_hash = self.transcript.get_current_hash();
706 let sig_verified = self
707 .config
708 .verifier
709 .verify_tls13_signature(
710 &verify::construct_tls13_server_verify_message(&handshake_hash),
711 &self.server_cert.cert_chain[0],
712 cert_verify,
713 )
714 .map_err(|err| {
715 cx.common
716 .send_cert_verify_error_alert(err)
717 })?;
718
719 cx.common.peer_certificates = Some(self.server_cert.cert_chain);
720 self.transcript.add_message(&m);
721
722 Ok(Box::new(ExpectFinished {
723 config: self.config,
724 server_name: self.server_name,
725 randoms: self.randoms,
726 suite: self.suite,
727 transcript: self.transcript,
728 key_schedule: self.key_schedule,
729 client_auth: self.client_auth,
730 cert_verified,
731 sig_verified,
732 }))
733 }
734}
735
736fn emit_certificate_tls13(
737 transcript: &mut HandshakeHash,
738 certkey: Option<&CertifiedKey>,
739 auth_context: Option<Vec<u8>>,
740 common: &mut CommonState,
741) {
742 let context = auth_context.unwrap_or_default();
743
744 let mut cert_payload = CertificatePayloadTLS13 {
745 context: PayloadU8::new(context),
746 entries: Vec::new(),
747 };
748
749 if let Some(certkey) = certkey {
750 for cert in &certkey.cert {
751 cert_payload
752 .entries
753 .push(CertificateEntry::new(cert.clone()));
754 }
755 }
756
757 let m = Message {
758 version: ProtocolVersion::TLSv1_3,
759 payload: MessagePayload::handshake(HandshakeMessagePayload {
760 typ: HandshakeType::Certificate,
761 payload: HandshakePayload::CertificateTLS13(cert_payload),
762 }),
763 };
764 transcript.add_message(&m);
765 common.send_msg(m, true);
766}
767
768fn emit_certverify_tls13(
769 transcript: &mut HandshakeHash,
770 signer: &dyn Signer,
771 common: &mut CommonState,
772) -> Result<(), Error> {
773 let message = verify::construct_tls13_client_verify_message(&transcript.get_current_hash());
774
775 let scheme = signer.scheme();
776 let sig = signer.sign(&message)?;
777 let dss = DigitallySignedStruct::new(scheme, sig);
778
779 let m = Message {
780 version: ProtocolVersion::TLSv1_3,
781 payload: MessagePayload::handshake(HandshakeMessagePayload {
782 typ: HandshakeType::CertificateVerify,
783 payload: HandshakePayload::CertificateVerify(dss),
784 }),
785 };
786
787 transcript.add_message(&m);
788 common.send_msg(m, true);
789 Ok(())
790}
791
792fn emit_finished_tls13(
793 transcript: &mut HandshakeHash,
794 verify_data: ring::hmac::Tag,
795 common: &mut CommonState,
796) {
797 let verify_data_payload = Payload::new(verify_data.as_ref());
798
799 let m = Message {
800 version: ProtocolVersion::TLSv1_3,
801 payload: MessagePayload::handshake(HandshakeMessagePayload {
802 typ: HandshakeType::Finished,
803 payload: HandshakePayload::Finished(verify_data_payload),
804 }),
805 };
806
807 transcript.add_message(&m);
808 common.send_msg(m, true);
809}
810
811fn emit_end_of_early_data_tls13(transcript: &mut HandshakeHash, common: &mut CommonState) {
812 if common.is_quic() {
813 return;
814 }
815
816 let m = Message {
817 version: ProtocolVersion::TLSv1_3,
818 payload: MessagePayload::handshake(HandshakeMessagePayload {
819 typ: HandshakeType::EndOfEarlyData,
820 payload: HandshakePayload::EndOfEarlyData,
821 }),
822 };
823
824 transcript.add_message(&m);
825 common.send_msg(m, true);
826}
827
828struct ExpectFinished {
829 config: Arc<ClientConfig>,
830 server_name: ServerName,
831 randoms: ConnectionRandoms,
832 suite: &'static Tls13CipherSuite,
833 transcript: HandshakeHash,
834 key_schedule: KeyScheduleHandshake,
835 client_auth: Option<ClientAuthDetails>,
836 cert_verified: verify::ServerCertVerified,
837 sig_verified: verify::HandshakeSignatureValid,
838}
839
840impl State<ClientConnectionData> for ExpectFinished {
841 fn handle(self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
842 let mut st = *self;
843 let finished =
844 require_handshake_msg!(m, HandshakeType::Finished, HandshakePayload::Finished)?;
845
846 let handshake_hash = st.transcript.get_current_hash();
847 let expect_verify_data = st
848 .key_schedule
849 .sign_server_finish(&handshake_hash);
850
851 let fin = constant_time::verify_slices_are_equal(expect_verify_data.as_ref(), &finished.0)
852 .map_err(|_| {
853 cx.common
854 .send_fatal_alert(AlertDescription::DecryptError, Error::DecryptError)
855 })
856 .map(|_| verify::FinishedMessageVerified::assertion())?;
857
858 st.transcript.add_message(&m);
859
860 let hash_after_handshake = st.transcript.get_current_hash();
861 if cx.common.early_traffic {
864 emit_end_of_early_data_tls13(&mut st.transcript, cx.common);
865 cx.common.early_traffic = false;
866 cx.data.early_data.finished();
867 st.key_schedule
868 .set_handshake_encrypter(cx.common);
869 }
870
871 if let Some(client_auth) = st.client_auth {
874 match client_auth {
875 ClientAuthDetails::Empty {
876 auth_context_tls13: auth_context,
877 } => {
878 emit_certificate_tls13(&mut st.transcript, None, auth_context, cx.common);
879 }
880 ClientAuthDetails::Verify {
881 certkey,
882 signer,
883 auth_context_tls13: auth_context,
884 } => {
885 emit_certificate_tls13(
886 &mut st.transcript,
887 Some(&certkey),
888 auth_context,
889 cx.common,
890 );
891 emit_certverify_tls13(&mut st.transcript, signer.as_ref(), cx.common)?;
892 }
893 }
894 }
895
896 let (key_schedule_pre_finished, verify_data) = st
897 .key_schedule
898 .into_pre_finished_client_traffic(
899 hash_after_handshake,
900 st.transcript.get_current_hash(),
901 &*st.config.key_log,
902 &st.randoms.client,
903 );
904
905 emit_finished_tls13(&mut st.transcript, verify_data, cx.common);
906
907 st.config
910 .resumption
911 .store
912 .remove_tls12_session(&st.server_name);
913
914 cx.common.check_aligned_handshake()?;
916 let key_schedule_traffic = key_schedule_pre_finished.into_traffic(cx.common);
917 cx.common.start_traffic();
918
919 let st = ExpectTraffic {
920 session_storage: Arc::clone(&st.config.resumption.store),
921 server_name: st.server_name,
922 suite: st.suite,
923 transcript: st.transcript,
924 key_schedule: key_schedule_traffic,
925 _cert_verified: st.cert_verified,
926 _sig_verified: st.sig_verified,
927 _fin_verified: fin,
928 };
929
930 #[cfg(feature = "quic")]
931 if cx.common.is_quic() {
932 return Ok(Box::new(ExpectQuicTraffic(st)));
933 }
934
935 Ok(Box::new(st))
936 }
937}
938
939struct ExpectTraffic {
943 session_storage: Arc<dyn ClientSessionStore>,
944 server_name: ServerName,
945 suite: &'static Tls13CipherSuite,
946 transcript: HandshakeHash,
947 key_schedule: KeyScheduleTraffic,
948 _cert_verified: verify::ServerCertVerified,
949 _sig_verified: verify::HandshakeSignatureValid,
950 _fin_verified: verify::FinishedMessageVerified,
951}
952
953impl ExpectTraffic {
954 #[allow(clippy::unnecessary_wraps)] fn handle_new_ticket_tls13(
956 &mut self,
957 cx: &mut ClientContext<'_>,
958 nst: &NewSessionTicketPayloadTLS13,
959 ) -> Result<(), Error> {
960 if nst.has_duplicate_extension() {
961 return Err(cx.common.send_fatal_alert(
962 AlertDescription::IllegalParameter,
963 PeerMisbehaved::DuplicateNewSessionTicketExtensions,
964 ));
965 }
966
967 let handshake_hash = self.transcript.get_current_hash();
968 let secret = self
969 .key_schedule
970 .resumption_master_secret_and_derive_ticket_psk(&handshake_hash, &nst.nonce.0);
971
972 let time_now = match TimeBase::now() {
973 Ok(t) => t,
974 #[allow(unused_variables)]
975 Err(e) => {
976 debug!("Session not saved: {}", e);
977 return Ok(());
978 }
979 };
980
981 #[allow(unused_mut)]
982 let mut value = persist::Tls13ClientSessionValue::new(
983 self.suite,
984 nst.ticket.0.clone(),
985 secret,
986 cx.common
987 .peer_certificates
988 .clone()
989 .unwrap_or_default(),
990 time_now,
991 nst.lifetime,
992 nst.age_add,
993 nst.get_max_early_data_size()
994 .unwrap_or_default(),
995 );
996
997 #[cfg(feature = "quic")]
998 if cx.common.is_quic() {
999 if let Some(sz) = nst.get_max_early_data_size() {
1000 if sz != 0 && sz != 0xffff_ffff {
1001 return Err(PeerMisbehaved::InvalidMaxEarlyDataSize.into());
1002 }
1003 }
1004
1005 if let Some(ref quic_params) = &cx.common.quic.params {
1006 value.set_quic_params(quic_params);
1007 }
1008 }
1009
1010 self.session_storage
1011 .insert_tls13_ticket(&self.server_name, value);
1012 Ok(())
1013 }
1014
1015 fn handle_key_update(
1016 &mut self,
1017 common: &mut CommonState,
1018 key_update_request: &KeyUpdateRequest,
1019 ) -> Result<(), Error> {
1020 #[cfg(feature = "quic")]
1021 {
1022 if let Protocol::Quic = common.protocol {
1023 return Err(common.send_fatal_alert(
1024 AlertDescription::UnexpectedMessage,
1025 PeerMisbehaved::KeyUpdateReceivedInQuicConnection,
1026 ));
1027 }
1028 }
1029
1030 common.check_aligned_handshake()?;
1032
1033 if common.should_update_key(key_update_request)? {
1034 self.key_schedule
1035 .update_encrypter_and_notify(common);
1036 }
1037
1038 self.key_schedule
1040 .update_decrypter(common);
1041 Ok(())
1042 }
1043}
1044
1045impl State<ClientConnectionData> for ExpectTraffic {
1046 fn handle(mut self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
1047 match m.payload {
1048 MessagePayload::ApplicationData(payload) => cx
1049 .common
1050 .take_received_plaintext(payload),
1051 MessagePayload::Handshake {
1052 parsed:
1053 HandshakeMessagePayload {
1054 payload: HandshakePayload::NewSessionTicketTLS13(ref new_ticket),
1055 ..
1056 },
1057 ..
1058 } => self.handle_new_ticket_tls13(cx, new_ticket)?,
1059 MessagePayload::Handshake {
1060 parsed:
1061 HandshakeMessagePayload {
1062 payload: HandshakePayload::KeyUpdate(ref key_update),
1063 ..
1064 },
1065 ..
1066 } => self.handle_key_update(cx.common, key_update)?,
1067 payload => {
1068 return Err(inappropriate_handshake_message(
1069 &payload,
1070 &[ContentType::ApplicationData, ContentType::Handshake],
1071 &[HandshakeType::NewSessionTicket, HandshakeType::KeyUpdate],
1072 ));
1073 }
1074 }
1075
1076 Ok(self)
1077 }
1078
1079 fn export_keying_material(
1080 &self,
1081 output: &mut [u8],
1082 label: &[u8],
1083 context: Option<&[u8]>,
1084 ) -> Result<(), Error> {
1085 self.key_schedule
1086 .export_keying_material(output, label, context)
1087 }
1088
1089 #[cfg(feature = "secret_extraction")]
1090 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
1091 self.key_schedule
1092 .extract_secrets(Side::Client)
1093 }
1094}
1095
1096#[cfg(feature = "quic")]
1097struct ExpectQuicTraffic(ExpectTraffic);
1098
1099#[cfg(feature = "quic")]
1100impl State<ClientConnectionData> for ExpectQuicTraffic {
1101 fn handle(mut self: Box<Self>, cx: &mut ClientContext<'_>, m: Message) -> hs::NextStateOrError {
1102 let nst = require_handshake_msg!(
1103 m,
1104 HandshakeType::NewSessionTicket,
1105 HandshakePayload::NewSessionTicketTLS13
1106 )?;
1107 self.0
1108 .handle_new_ticket_tls13(cx, nst)?;
1109 Ok(self)
1110 }
1111
1112 fn export_keying_material(
1113 &self,
1114 output: &mut [u8],
1115 label: &[u8],
1116 context: Option<&[u8]>,
1117 ) -> Result<(), Error> {
1118 self.0
1119 .export_keying_material(output, label, context)
1120 }
1121}