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