1use alloc::boxed::Box;
2use alloc::vec::Vec;
3
4use crate::conn::Exporter;
5use crate::conn::kernel::KernelState;
6use crate::crypto::{Identity, SupportedKxGroup};
7use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
8use crate::error::{Error, InvalidMessage, PeerMisbehaved};
9use crate::hash_hs::HandshakeHash;
10use crate::log::{debug, error, warn};
11use crate::msgs::alert::AlertMessagePayload;
12use crate::msgs::base::Payload;
13use crate::msgs::codec::Codec;
14use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
15use crate::msgs::fragmenter::MessageFragmenter;
16use crate::msgs::handshake::{HandshakeMessagePayload, ProtocolName};
17use crate::msgs::message::{
18 Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
19 PlainMessage,
20};
21use crate::record_layer::PreEncryptAction;
22use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
23use crate::tls12::ConnectionSecrets;
24use crate::unbuffered::{EncryptError, InsufficientSizeError};
25use crate::vecbuf::ChunkVecBuffer;
26use crate::{quic, record_layer};
27
28pub struct CommonState {
30 pub(crate) negotiated_version: Option<ProtocolVersion>,
31 pub(crate) handshake_kind: Option<HandshakeKind>,
32 pub(crate) side: Side,
33 pub(crate) record_layer: record_layer::RecordLayer,
34 pub(crate) suite: Option<SupportedCipherSuite>,
35 pub(crate) kx_state: KxState,
36 pub(crate) alpn_protocol: Option<ProtocolName>,
37 pub(crate) exporter: Option<Box<dyn Exporter>>,
38 pub(crate) early_exporter: Option<Box<dyn Exporter>>,
39 pub(crate) aligned_handshake: bool,
40 pub(crate) may_send_application_data: bool,
41 pub(crate) may_receive_application_data: bool,
42 pub(crate) early_traffic: bool,
43 sent_fatal_alert: bool,
44 pub(crate) has_sent_close_notify: bool,
46 pub(crate) has_received_close_notify: bool,
48 #[cfg(feature = "std")]
49 pub(crate) has_seen_eof: bool,
50 pub(crate) peer_identity: Option<Identity<'static>>,
51 message_fragmenter: MessageFragmenter,
52 pub(crate) received_plaintext: ChunkVecBuffer,
53 pub(crate) sendable_tls: ChunkVecBuffer,
54 queued_key_update_message: Option<Vec<u8>>,
55
56 pub(crate) protocol: Protocol,
58 pub(crate) quic: quic::Quic,
59 pub(crate) enable_secret_extraction: bool,
60 temper_counters: TemperCounters,
61 pub(crate) refresh_traffic_keys_pending: bool,
62 pub(crate) fips: bool,
63 pub(crate) tls13_tickets_received: u32,
64}
65
66impl CommonState {
67 pub(crate) fn new(side: Side) -> Self {
68 Self {
69 negotiated_version: None,
70 handshake_kind: None,
71 side,
72 record_layer: record_layer::RecordLayer::new(),
73 suite: None,
74 kx_state: KxState::default(),
75 alpn_protocol: None,
76 exporter: None,
77 early_exporter: None,
78 aligned_handshake: true,
79 may_send_application_data: false,
80 may_receive_application_data: false,
81 early_traffic: false,
82 sent_fatal_alert: false,
83 has_sent_close_notify: false,
84 has_received_close_notify: false,
85 #[cfg(feature = "std")]
86 has_seen_eof: false,
87 peer_identity: None,
88 message_fragmenter: MessageFragmenter::default(),
89 received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
90 sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
91 queued_key_update_message: None,
92 protocol: Protocol::Tcp,
93 quic: quic::Quic::default(),
94 enable_secret_extraction: false,
95 temper_counters: TemperCounters::default(),
96 refresh_traffic_keys_pending: false,
97 fips: false,
98 tls13_tickets_received: 0,
99 }
100 }
101
102 pub fn wants_write(&self) -> bool {
106 !self.sendable_tls.is_empty()
107 }
108
109 pub fn is_handshaking(&self) -> bool {
117 !(self.may_send_application_data && self.may_receive_application_data)
118 }
119
120 pub fn peer_identity(&self) -> Option<&Identity<'static>> {
129 self.peer_identity.as_ref()
130 }
131
132 pub fn alpn_protocol(&self) -> Option<&[u8]> {
138 self.get_alpn_protocol()
139 }
140
141 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
145 self.suite
146 }
147
148 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
158 match self.kx_state {
159 KxState::Complete(group) => Some(group),
160 _ => None,
161 }
162 }
163
164 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
168 self.negotiated_version
169 }
170
171 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
178 self.handshake_kind
179 }
180
181 pub(crate) fn is_tls13(&self) -> bool {
182 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
183 }
184
185 pub(crate) fn process_main_protocol<Data>(
186 &mut self,
187 msg: Message<'_>,
188 state: Box<dyn State<Data>>,
189 data: &mut Data,
190 sendable_plaintext: Option<&mut ChunkVecBuffer>,
191 ) -> Result<Box<dyn State<Data>>, Error> {
192 if self.may_receive_application_data && !self.is_tls13() {
195 let reject_ty = match self.side {
196 Side::Client => HandshakeType::HelloRequest,
197 Side::Server => HandshakeType::ClientHello,
198 };
199 if msg.is_handshake_type(reject_ty) {
200 self.temper_counters
201 .received_renegotiation_request()?;
202 self.send_warning_alert(AlertDescription::NoRenegotiation);
203 return Ok(state);
204 }
205 }
206
207 let mut cx = Context {
208 common: self,
209 data,
210 sendable_plaintext,
211 };
212 match state.handle(&mut cx, msg) {
213 Ok(next) => Ok(next),
214 Err(e @ Error::InappropriateMessage { .. })
215 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
216 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
217 }
218 Err(e) => Err(e),
219 }
220 }
221
222 pub(crate) fn write_plaintext(
223 &mut self,
224 payload: OutboundChunks<'_>,
225 outgoing_tls: &mut [u8],
226 ) -> Result<usize, EncryptError> {
227 if payload.is_empty() {
228 return Ok(0);
229 }
230
231 let fragments = self
232 .message_fragmenter
233 .fragment_payload(
234 ContentType::ApplicationData,
235 ProtocolVersion::TLSv1_2,
236 payload.clone(),
237 );
238
239 for f in 0..fragments.len() {
240 match self
241 .record_layer
242 .pre_encrypt_action(f as u64)
243 {
244 PreEncryptAction::Nothing => {}
245 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
246 Some(ProtocolVersion::TLSv1_3) => {
247 self.refresh_traffic_keys_pending = true;
249 }
250 _ => {
251 error!(
252 "traffic keys exhausted, closing connection to prevent security failure"
253 );
254 self.send_close_notify();
255 return Err(EncryptError::EncryptExhausted);
256 }
257 },
258 PreEncryptAction::Refuse => {
259 return Err(EncryptError::EncryptExhausted);
260 }
261 }
262 }
263
264 self.perhaps_write_key_update();
265
266 self.check_required_size(outgoing_tls, fragments)?;
267
268 let fragments = self
269 .message_fragmenter
270 .fragment_payload(
271 ContentType::ApplicationData,
272 ProtocolVersion::TLSv1_2,
273 payload,
274 );
275
276 Ok(self.write_fragments(outgoing_tls, fragments))
277 }
278
279 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
284 if !self.aligned_handshake {
285 Err(self.send_fatal_alert(
286 AlertDescription::UnexpectedMessage,
287 PeerMisbehaved::KeyEpochWithPendingFragment,
288 ))
289 } else {
290 Ok(())
291 }
292 }
293
294 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
297 let iter = self
298 .message_fragmenter
299 .fragment_message(&m);
300 for m in iter {
301 self.send_single_fragment(m);
302 }
303 }
304
305 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
307 let len = match limit {
312 #[cfg(feature = "std")]
313 Limit::Yes => self
314 .sendable_tls
315 .apply_limit(payload.len()),
316 Limit::No => payload.len(),
317 };
318
319 let iter = self
320 .message_fragmenter
321 .fragment_payload(
322 ContentType::ApplicationData,
323 ProtocolVersion::TLSv1_2,
324 payload.split_at(len).0,
325 );
326 for m in iter {
327 self.send_single_fragment(m);
328 }
329
330 len
331 }
332
333 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
334 if m.typ == ContentType::Alert {
335 let em = self.record_layer.encrypt_outgoing(m);
337 self.queue_tls_message(em);
338 return;
339 }
340
341 match self
342 .record_layer
343 .next_pre_encrypt_action()
344 {
345 PreEncryptAction::Nothing => {}
346
347 PreEncryptAction::RefreshOrClose => {
350 match self.negotiated_version {
351 Some(ProtocolVersion::TLSv1_3) => {
352 self.refresh_traffic_keys_pending = true;
354 }
355 _ => {
356 error!(
357 "traffic keys exhausted, closing connection to prevent security failure"
358 );
359 self.send_close_notify();
360 return;
361 }
362 }
363 }
364
365 PreEncryptAction::Refuse => {
368 return;
369 }
370 };
371
372 let em = self.record_layer.encrypt_outgoing(m);
373 self.queue_tls_message(em);
374 }
375
376 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
377 debug_assert!(self.may_send_application_data);
378 debug_assert!(self.record_layer.is_encrypting());
379
380 if payload.is_empty() {
381 return 0;
383 }
384
385 self.send_appdata_encrypt(payload, limit)
386 }
387
388 pub(crate) fn start_outgoing_traffic(
392 &mut self,
393 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
394 ) {
395 self.may_send_application_data = true;
396 if let Some(sendable_plaintext) = sendable_plaintext {
397 self.flush_plaintext(sendable_plaintext);
398 }
399 }
400
401 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
405 self.may_receive_application_data = true;
406 self.start_outgoing_traffic(sendable_plaintext);
407 }
408
409 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
412 if !self.may_send_application_data {
413 return;
414 }
415
416 while let Some(buf) = sendable_plaintext.pop() {
417 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
418 }
419 }
420
421 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
423 self.perhaps_write_key_update();
424 self.sendable_tls.append(m.encode());
425 }
426
427 pub(crate) fn perhaps_write_key_update(&mut self) {
428 if let Some(message) = self.queued_key_update_message.take() {
429 self.sendable_tls.append(message);
430 }
431 }
432
433 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
435 {
436 if let Protocol::Quic = self.protocol {
437 if let MessagePayload::Alert(alert) = m.payload {
438 self.quic.alert = Some(alert.description);
439 } else {
440 debug_assert!(
441 matches!(
442 m.payload,
443 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
444 ),
445 "QUIC uses TLS for the cryptographic handshake only"
446 );
447 let mut bytes = Vec::new();
448 m.payload.encode(&mut bytes);
449 self.quic
450 .hs_queue
451 .push_back((must_encrypt, bytes));
452 }
453 return;
454 }
455 }
456 if !must_encrypt {
457 let msg = &m.into();
458 let iter = self
459 .message_fragmenter
460 .fragment_message(msg);
461 for m in iter {
462 self.queue_tls_message(m.to_unencrypted_opaque());
463 }
464 } else {
465 self.send_msg_encrypt(m.into());
466 }
467 }
468
469 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
470 self.temper_counters.received_app_data();
471 self.received_plaintext
472 .append(bytes.into_vec());
473 }
474
475 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
476 let (dec, enc) = secrets.make_cipher_pair(side);
477 self.record_layer
478 .prepare_message_encrypter(
479 enc,
480 secrets
481 .suite()
482 .common
483 .confidentiality_limit,
484 );
485 self.record_layer
486 .prepare_message_decrypter(dec);
487 }
488
489 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
490 self.send_fatal_alert(AlertDescription::MissingExtension, why)
491 }
492
493 fn send_warning_alert(&mut self, desc: AlertDescription) {
494 warn!("Sending warning alert {desc:?}");
495 self.send_warning_alert_no_log(desc);
496 }
497
498 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
499 if let AlertLevel::Unknown(_) = alert.level {
501 return Err(self.send_fatal_alert(
502 AlertDescription::IllegalParameter,
503 Error::AlertReceived(alert.description),
504 ));
505 }
506
507 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
510 self.has_received_close_notify = true;
511 return Ok(());
512 }
513
514 let err = Error::AlertReceived(alert.description);
517 if alert.level == AlertLevel::Warning {
518 self.temper_counters
519 .received_warning_alert()?;
520 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
521 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
522 }
523
524 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
527 warn!("TLS alert warning received: {alert:?}");
528 }
529
530 return Ok(());
531 }
532
533 Err(err)
534 }
535
536 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
537 self.send_fatal_alert(
538 match &err {
539 Error::InvalidCertificate(e) => e.clone().into(),
540 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
541 _ => AlertDescription::HandshakeFailure,
542 },
543 err,
544 )
545 }
546
547 pub(crate) fn send_fatal_alert(
548 &mut self,
549 desc: AlertDescription,
550 err: impl Into<Error>,
551 ) -> Error {
552 debug_assert!(!self.sent_fatal_alert);
553 let m = Message::build_alert(AlertLevel::Fatal, desc);
554 self.send_msg(m, self.record_layer.is_encrypting());
555 self.sent_fatal_alert = true;
556 err.into()
557 }
558
559 pub fn send_close_notify(&mut self) {
567 if self.sent_fatal_alert {
568 return;
569 }
570 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
571 self.sent_fatal_alert = true;
572 self.has_sent_close_notify = true;
573 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
574 }
575
576 pub(crate) fn eager_send_close_notify(
577 &mut self,
578 outgoing_tls: &mut [u8],
579 ) -> Result<usize, EncryptError> {
580 self.send_close_notify();
581 self.check_required_size(outgoing_tls, [].into_iter())?;
582 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
583 }
584
585 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
586 let m = Message::build_alert(AlertLevel::Warning, desc);
587 self.send_msg(m, self.record_layer.is_encrypting());
588 }
589
590 fn check_required_size<'a>(
591 &self,
592 outgoing_tls: &mut [u8],
593 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
594 ) -> Result<(), EncryptError> {
595 let mut required_size = self.sendable_tls.len();
596
597 for m in fragments {
598 required_size += m.encoded_len(&self.record_layer);
599 }
600
601 if required_size > outgoing_tls.len() {
602 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
603 required_size,
604 }));
605 }
606
607 Ok(())
608 }
609
610 fn write_fragments<'a>(
611 &mut self,
612 outgoing_tls: &mut [u8],
613 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
614 ) -> usize {
615 let mut written = 0;
616
617 while let Some(message) = self.sendable_tls.pop() {
620 let len = message.len();
621 outgoing_tls[written..written + len].copy_from_slice(&message);
622 written += len;
623 }
624
625 for m in fragments {
626 let em = self
627 .record_layer
628 .encrypt_outgoing(m)
629 .encode();
630
631 let len = em.len();
632 outgoing_tls[written..written + len].copy_from_slice(&em);
633 written += len;
634 }
635
636 written
637 }
638
639 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
640 self.message_fragmenter
641 .set_max_fragment_size(new)
642 }
643
644 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
645 self.alpn_protocol
646 .as_ref()
647 .map(AsRef::as_ref)
648 }
649
650 pub fn wants_read(&self) -> bool {
660 self.received_plaintext.is_empty()
667 && !self.has_received_close_notify
668 && (self.may_send_application_data || self.sendable_tls.is_empty())
669 }
670
671 pub(crate) fn current_io_state(&self) -> IoState {
672 IoState {
673 tls_bytes_to_write: self.sendable_tls.len(),
674 plaintext_bytes_to_read: self.received_plaintext.len(),
675 peer_has_closed: self.has_received_close_notify,
676 }
677 }
678
679 pub(crate) fn is_quic(&self) -> bool {
680 self.protocol == Protocol::Quic
681 }
682
683 pub(crate) fn should_update_key(
684 &mut self,
685 key_update_request: &KeyUpdateRequest,
686 ) -> Result<bool, Error> {
687 self.temper_counters
688 .received_key_update_request()?;
689
690 match key_update_request {
691 KeyUpdateRequest::UpdateNotRequested => Ok(false),
692 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
693 _ => Err(self.send_fatal_alert(
694 AlertDescription::IllegalParameter,
695 InvalidMessage::InvalidKeyUpdate,
696 )),
697 }
698 }
699
700 pub(crate) fn enqueue_key_update_notification(&mut self) {
701 let message = PlainMessage::from(Message::build_key_update_notify());
702 self.queued_key_update_message = Some(
703 self.record_layer
704 .encrypt_outgoing(message.borrow_outbound())
705 .encode(),
706 );
707 }
708
709 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
710 self.temper_counters
711 .received_tls13_change_cipher_spec()
712 }
713}
714
715#[cfg(feature = "std")]
716impl CommonState {
717 pub(crate) fn buffer_plaintext(
723 &mut self,
724 payload: OutboundChunks<'_>,
725 sendable_plaintext: &mut ChunkVecBuffer,
726 ) -> usize {
727 self.perhaps_write_key_update();
728 self.send_plain(payload, Limit::Yes, sendable_plaintext)
729 }
730
731 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
732 debug_assert!(self.early_traffic);
733 debug_assert!(self.record_layer.is_encrypting());
734
735 if data.is_empty() {
736 return 0;
738 }
739
740 self.send_appdata_encrypt(data.into(), Limit::Yes)
741 }
742
743 fn send_plain(
749 &mut self,
750 payload: OutboundChunks<'_>,
751 limit: Limit,
752 sendable_plaintext: &mut ChunkVecBuffer,
753 ) -> usize {
754 if !self.may_send_application_data {
755 let len = match limit {
758 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
759 Limit::No => sendable_plaintext.append(payload.to_vec()),
760 };
761 return len;
762 }
763
764 self.send_plain_non_buffering(payload, limit)
765 }
766}
767
768#[derive(Debug, PartialEq, Clone, Copy)]
770#[non_exhaustive]
771pub enum HandshakeKind {
772 Full,
777
778 FullWithHelloRetryRequest,
784
785 Resumed,
791}
792
793#[derive(Debug, Eq, PartialEq)]
798pub struct IoState {
799 tls_bytes_to_write: usize,
800 plaintext_bytes_to_read: usize,
801 peer_has_closed: bool,
802}
803
804impl IoState {
805 pub fn tls_bytes_to_write(&self) -> usize {
810 self.tls_bytes_to_write
811 }
812
813 pub fn plaintext_bytes_to_read(&self) -> usize {
816 self.plaintext_bytes_to_read
817 }
818
819 pub fn peer_has_closed(&self) -> bool {
828 self.peer_has_closed
829 }
830}
831
832pub(crate) trait State<Side>: Send + Sync {
833 fn handle<'m>(
834 self: Box<Self>,
835 cx: &mut Context<'_, Side>,
836 message: Message<'m>,
837 ) -> Result<Box<dyn State<Side>>, Error>;
838
839 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
840 Err(Error::HandshakeNotComplete)
841 }
842
843 fn handle_decrypt_error(&self) {}
844
845 fn into_external_state(
846 self: Box<Self>,
847 ) -> Result<(PartiallyExtractedSecrets, Box<dyn KernelState + 'static>), Error> {
848 Err(Error::HandshakeNotComplete)
849 }
850}
851
852pub(crate) struct Context<'a, Data> {
853 pub(crate) common: &'a mut CommonState,
854 pub(crate) data: &'a mut Data,
855 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
858}
859
860#[allow(clippy::exhaustive_enums)]
862#[derive(Clone, Copy, Debug, PartialEq)]
863pub enum Side {
864 Client,
866 Server,
868}
869
870impl Side {
871 pub(crate) fn peer(&self) -> Self {
872 match self {
873 Self::Client => Self::Server,
874 Self::Server => Self::Client,
875 }
876 }
877}
878
879#[derive(Copy, Clone, Eq, PartialEq, Debug)]
880pub(crate) enum Protocol {
881 Tcp,
882 Quic,
883}
884
885enum Limit {
886 #[cfg(feature = "std")]
887 Yes,
888 No,
889}
890
891struct TemperCounters {
894 allowed_warning_alerts: u8,
895 allowed_renegotiation_requests: u8,
896 allowed_key_update_requests: u8,
897 allowed_middlebox_ccs: u8,
898}
899
900impl TemperCounters {
901 fn received_warning_alert(&mut self) -> Result<(), Error> {
902 match self.allowed_warning_alerts {
903 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
904 _ => {
905 self.allowed_warning_alerts -= 1;
906 Ok(())
907 }
908 }
909 }
910
911 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
912 match self.allowed_renegotiation_requests {
913 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
914 _ => {
915 self.allowed_renegotiation_requests -= 1;
916 Ok(())
917 }
918 }
919 }
920
921 fn received_key_update_request(&mut self) -> Result<(), Error> {
922 match self.allowed_key_update_requests {
923 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
924 _ => {
925 self.allowed_key_update_requests -= 1;
926 Ok(())
927 }
928 }
929 }
930
931 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
932 match self.allowed_middlebox_ccs {
933 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
934 _ => {
935 self.allowed_middlebox_ccs -= 1;
936 Ok(())
937 }
938 }
939 }
940
941 fn received_app_data(&mut self) {
942 self.allowed_key_update_requests = Self::INITIAL_KEY_UPDATE_REQUESTS;
943 }
944
945 const INITIAL_KEY_UPDATE_REQUESTS: u8 = 32;
948}
949
950impl Default for TemperCounters {
951 fn default() -> Self {
952 Self {
953 allowed_warning_alerts: 4,
956
957 allowed_renegotiation_requests: 1,
960
961 allowed_key_update_requests: Self::INITIAL_KEY_UPDATE_REQUESTS,
962
963 allowed_middlebox_ccs: 2,
968 }
969 }
970}
971
972#[derive(Debug, Default)]
973pub(crate) enum KxState {
974 #[default]
975 None,
976 Start(&'static dyn SupportedKxGroup),
977 Complete(&'static dyn SupportedKxGroup),
978}
979
980impl KxState {
981 pub(crate) fn complete(&mut self) {
982 debug_assert!(matches!(self, Self::Start(_)));
983 if let Self::Start(group) = self {
984 *self = Self::Complete(*group);
985 }
986 }
987}
988
989pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
990 pub(crate) transcript: &'a mut HandshakeHash,
991 body: Vec<u8>,
992}
993
994impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
995 pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
996 Self {
997 transcript,
998 body: Vec::new(),
999 }
1000 }
1001
1002 pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1003 let start_len = self.body.len();
1004 hs.encode(&mut self.body);
1005 self.transcript
1006 .add(&self.body[start_len..]);
1007 }
1008
1009 pub(crate) fn finish(self, common: &mut CommonState) {
1010 common.send_msg(
1011 Message {
1012 version: match TLS13 {
1013 true => ProtocolVersion::TLSv1_3,
1014 false => ProtocolVersion::TLSv1_2,
1015 },
1016 payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1017 },
1018 TLS13,
1019 );
1020 }
1021}
1022
1023pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1024pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1025
1026const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1027pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;