1use alloc::boxed::Box;
2use alloc::vec::Vec;
3
4use pki_types::CertificateDer;
5
6use crate::conn::kernel::KernelState;
7use crate::crypto::SupportedKxGroup;
8use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
9use crate::error::{Error, InvalidMessage, PeerMisbehaved};
10use crate::hash_hs::HandshakeHash;
11use crate::log::{debug, error, warn};
12use crate::msgs::alert::AlertMessagePayload;
13use crate::msgs::base::Payload;
14use crate::msgs::codec::Codec;
15use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
16use crate::msgs::fragmenter::MessageFragmenter;
17use crate::msgs::handshake::{CertificateChain, HandshakeMessagePayload, ProtocolName};
18use crate::msgs::message::{
19 Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
20 PlainMessage,
21};
22use crate::record_layer::PreEncryptAction;
23use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
24#[cfg(feature = "tls12")]
25use crate::tls12::ConnectionSecrets;
26use crate::unbuffered::{EncryptError, InsufficientSizeError};
27use crate::vecbuf::ChunkVecBuffer;
28use crate::{quic, record_layer};
29
30pub struct CommonState {
32 pub(crate) negotiated_version: Option<ProtocolVersion>,
33 pub(crate) handshake_kind: Option<HandshakeKind>,
34 pub(crate) side: Side,
35 pub(crate) record_layer: record_layer::RecordLayer,
36 pub(crate) suite: Option<SupportedCipherSuite>,
37 pub(crate) kx_state: KxState,
38 pub(crate) alpn_protocol: Option<ProtocolName>,
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_certificates: Option<CertificateChain<'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 jls_authed: crate::jls::JlsState,
58 pub(crate) protocol: Protocol,
60 pub(crate) quic: quic::Quic,
61 pub(crate) enable_secret_extraction: bool,
62 temper_counters: TemperCounters,
63 pub(crate) refresh_traffic_keys_pending: bool,
64 pub(crate) fips: bool,
65 pub(crate) tls13_tickets_received: u32,
66}
67
68impl CommonState {
69 pub(crate) fn new(side: Side) -> Self {
70 Self {
71 negotiated_version: None,
72 handshake_kind: None,
73 side,
74 record_layer: record_layer::RecordLayer::new(),
75 suite: None,
76 kx_state: KxState::default(),
77 alpn_protocol: 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_certificates: 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 jls_authed: Default::default(),
93
94 protocol: Protocol::Tcp,
95 quic: quic::Quic::default(),
96 enable_secret_extraction: false,
97 temper_counters: TemperCounters::default(),
98 refresh_traffic_keys_pending: false,
99 fips: false,
100 tls13_tickets_received: 0,
101 }
102 }
103
104 pub fn wants_write(&self) -> bool {
108 !self.sendable_tls.is_empty()
109 }
110
111 pub fn is_handshaking(&self) -> bool {
119 !(self.may_send_application_data && self.may_receive_application_data)
120 }
121
122 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
144 self.peer_certificates.as_deref()
145 }
146
147 pub fn alpn_protocol(&self) -> Option<&[u8]> {
153 self.get_alpn_protocol()
154 }
155
156 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
160 self.suite
161 }
162
163 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
173 match self.kx_state {
174 KxState::Complete(group) => Some(group),
175 _ => None,
176 }
177 }
178
179 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
183 self.negotiated_version
184 }
185
186 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
193 self.handshake_kind
194 }
195
196 pub(crate) fn is_tls13(&self) -> bool {
197 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
198 }
199
200 pub(crate) fn process_main_protocol<Data>(
201 &mut self,
202 msg: Message<'_>,
203 mut state: Box<dyn State<Data>>,
204 data: &mut Data,
205 sendable_plaintext: Option<&mut ChunkVecBuffer>,
206 ) -> Result<Box<dyn State<Data>>, Error> {
207 if self.may_receive_application_data && !self.is_tls13() {
210 let reject_ty = match self.side {
211 Side::Client => HandshakeType::HelloRequest,
212 Side::Server => HandshakeType::ClientHello,
213 };
214 if msg.is_handshake_type(reject_ty) {
215 self.temper_counters
216 .received_renegotiation_request()?;
217 self.send_warning_alert(AlertDescription::NoRenegotiation);
218 return Ok(state);
219 }
220 }
221
222 let mut cx = Context {
223 common: self,
224 data,
225 sendable_plaintext,
226 };
227 match state.handle(&mut cx, msg) {
228 Ok(next) => {
229 state = next.into_owned();
230 Ok(state)
231 }
232 Err(e @ Error::InappropriateMessage { .. })
233 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
234 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
235 }
236 Err(e) => Err(e),
237 }
238 }
239
240 pub(crate) fn write_plaintext(
241 &mut self,
242 payload: OutboundChunks<'_>,
243 outgoing_tls: &mut [u8],
244 ) -> Result<usize, EncryptError> {
245 if payload.is_empty() {
246 return Ok(0);
247 }
248
249 let fragments = self
250 .message_fragmenter
251 .fragment_payload(
252 ContentType::ApplicationData,
253 ProtocolVersion::TLSv1_2,
254 payload.clone(),
255 );
256
257 for f in 0..fragments.len() {
258 match self
259 .record_layer
260 .pre_encrypt_action(f as u64)
261 {
262 PreEncryptAction::Nothing => {}
263 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
264 Some(ProtocolVersion::TLSv1_3) => {
265 self.refresh_traffic_keys_pending = true;
267 }
268 _ => {
269 error!(
270 "traffic keys exhausted, closing connection to prevent security failure"
271 );
272 self.send_close_notify();
273 return Err(EncryptError::EncryptExhausted);
274 }
275 },
276 PreEncryptAction::Refuse => {
277 return Err(EncryptError::EncryptExhausted);
278 }
279 }
280 }
281
282 self.perhaps_write_key_update();
283
284 self.check_required_size(outgoing_tls, fragments)?;
285
286 let fragments = self
287 .message_fragmenter
288 .fragment_payload(
289 ContentType::ApplicationData,
290 ProtocolVersion::TLSv1_2,
291 payload,
292 );
293
294 Ok(self.write_fragments(outgoing_tls, fragments))
295 }
296
297 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
302 if !self.aligned_handshake {
303 Err(self.send_fatal_alert(
304 AlertDescription::UnexpectedMessage,
305 PeerMisbehaved::KeyEpochWithPendingFragment,
306 ))
307 } else {
308 Ok(())
309 }
310 }
311
312 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
315 let iter = self
316 .message_fragmenter
317 .fragment_message(&m);
318 for m in iter {
319 self.send_single_fragment(m);
320 }
321 }
322
323 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
325 let len = match limit {
330 #[cfg(feature = "std")]
331 Limit::Yes => self
332 .sendable_tls
333 .apply_limit(payload.len()),
334 Limit::No => payload.len(),
335 };
336
337 let iter = self
338 .message_fragmenter
339 .fragment_payload(
340 ContentType::ApplicationData,
341 ProtocolVersion::TLSv1_2,
342 payload.split_at(len).0,
343 );
344 for m in iter {
345 self.send_single_fragment(m);
346 }
347
348 len
349 }
350
351 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
352 if m.typ == ContentType::Alert {
353 let em = self.record_layer.encrypt_outgoing(m);
355 self.queue_tls_message(em);
356 return;
357 }
358
359 match self
360 .record_layer
361 .next_pre_encrypt_action()
362 {
363 PreEncryptAction::Nothing => {}
364
365 PreEncryptAction::RefreshOrClose => {
368 match self.negotiated_version {
369 Some(ProtocolVersion::TLSv1_3) => {
370 self.refresh_traffic_keys_pending = true;
372 }
373 _ => {
374 error!(
375 "traffic keys exhausted, closing connection to prevent security failure"
376 );
377 self.send_close_notify();
378 return;
379 }
380 }
381 }
382
383 PreEncryptAction::Refuse => {
386 return;
387 }
388 };
389
390 let em = self.record_layer.encrypt_outgoing(m);
391 self.queue_tls_message(em);
392 }
393
394 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
395 debug_assert!(self.may_send_application_data);
396 debug_assert!(self.record_layer.is_encrypting());
397
398 if payload.is_empty() {
399 return 0;
401 }
402
403 self.send_appdata_encrypt(payload, limit)
404 }
405
406 pub(crate) fn start_outgoing_traffic(
410 &mut self,
411 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
412 ) {
413 self.may_send_application_data = true;
414 if let Some(sendable_plaintext) = sendable_plaintext {
415 self.flush_plaintext(sendable_plaintext);
416 }
417 }
418
419 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
423 self.may_receive_application_data = true;
424 self.start_outgoing_traffic(sendable_plaintext);
425 }
426
427 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
430 if !self.may_send_application_data {
431 return;
432 }
433
434 while let Some(buf) = sendable_plaintext.pop() {
435 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
436 }
437 }
438
439 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
441 self.perhaps_write_key_update();
442 self.sendable_tls.append(m.encode());
443 }
444
445 pub(crate) fn perhaps_write_key_update(&mut self) {
446 if let Some(message) = self.queued_key_update_message.take() {
447 self.sendable_tls.append(message);
448 }
449 }
450
451 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
453 {
454 if let Protocol::Quic = self.protocol {
455 if let MessagePayload::Alert(alert) = m.payload {
456 self.quic.alert = Some(alert.description);
457 } else {
458 debug_assert!(
459 matches!(
460 m.payload,
461 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
462 ),
463 "QUIC uses TLS for the cryptographic handshake only"
464 );
465 let mut bytes = Vec::new();
466 m.payload.encode(&mut bytes);
467 self.quic
468 .hs_queue
469 .push_back((must_encrypt, bytes));
470 }
471 return;
472 }
473 }
474 if !must_encrypt {
475 let msg = &m.into();
476 let iter = self
477 .message_fragmenter
478 .fragment_message(msg);
479 for m in iter {
480 self.queue_tls_message(m.to_unencrypted_opaque());
481 }
482 } else {
483 self.send_msg_encrypt(m.into());
484 }
485 }
486
487 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
488 self.temper_counters.received_app_data();
489 self.received_plaintext
490 .append(bytes.into_vec());
491 }
492
493 #[cfg(feature = "tls12")]
494 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
495 let (dec, enc) = secrets.make_cipher_pair(side);
496 self.record_layer
497 .prepare_message_encrypter(
498 enc,
499 secrets
500 .suite()
501 .common
502 .confidentiality_limit,
503 );
504 self.record_layer
505 .prepare_message_decrypter(dec);
506 }
507
508 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
509 self.send_fatal_alert(AlertDescription::MissingExtension, why)
510 }
511
512 fn send_warning_alert(&mut self, desc: AlertDescription) {
513 warn!("Sending warning alert {desc:?}");
514 self.send_warning_alert_no_log(desc);
515 }
516
517 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
518 if let AlertLevel::Unknown(_) = alert.level {
520 return Err(self.send_fatal_alert(
521 AlertDescription::IllegalParameter,
522 Error::AlertReceived(alert.description),
523 ));
524 }
525
526 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
529 self.has_received_close_notify = true;
530 return Ok(());
531 }
532
533 let err = Error::AlertReceived(alert.description);
536 if alert.level == AlertLevel::Warning {
537 self.temper_counters
538 .received_warning_alert()?;
539 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
540 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
541 }
542
543 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
546 warn!("TLS alert warning received: {alert:?}");
547 }
548
549 return Ok(());
550 }
551
552 Err(err)
553 }
554
555 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
556 self.send_fatal_alert(
557 match &err {
558 Error::InvalidCertificate(e) => e.clone().into(),
559 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
560 _ => AlertDescription::HandshakeFailure,
561 },
562 err,
563 )
564 }
565
566 pub(crate) fn send_fatal_alert(
567 &mut self,
568 desc: AlertDescription,
569 err: impl Into<Error>,
570 ) -> Error {
571 debug_assert!(!self.sent_fatal_alert);
572 let m = Message::build_alert(AlertLevel::Fatal, desc);
573 self.send_msg(m, self.record_layer.is_encrypting());
574 self.sent_fatal_alert = true;
575 err.into()
576 }
577
578 pub fn send_close_notify(&mut self) {
586 if self.sent_fatal_alert {
587 return;
588 }
589 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
590 self.sent_fatal_alert = true;
591 self.has_sent_close_notify = true;
592 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
593 }
594
595 pub(crate) fn eager_send_close_notify(
596 &mut self,
597 outgoing_tls: &mut [u8],
598 ) -> Result<usize, EncryptError> {
599 self.send_close_notify();
600 self.check_required_size(outgoing_tls, [].into_iter())?;
601 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
602 }
603
604 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
605 let m = Message::build_alert(AlertLevel::Warning, desc);
606 self.send_msg(m, self.record_layer.is_encrypting());
607 }
608
609 fn check_required_size<'a>(
610 &self,
611 outgoing_tls: &mut [u8],
612 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
613 ) -> Result<(), EncryptError> {
614 let mut required_size = self.sendable_tls.len();
615
616 for m in fragments {
617 required_size += m.encoded_len(&self.record_layer);
618 }
619
620 if required_size > outgoing_tls.len() {
621 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
622 required_size,
623 }));
624 }
625
626 Ok(())
627 }
628
629 fn write_fragments<'a>(
630 &mut self,
631 outgoing_tls: &mut [u8],
632 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
633 ) -> usize {
634 let mut written = 0;
635
636 while let Some(message) = self.sendable_tls.pop() {
639 let len = message.len();
640 outgoing_tls[written..written + len].copy_from_slice(&message);
641 written += len;
642 }
643
644 for m in fragments {
645 let em = self
646 .record_layer
647 .encrypt_outgoing(m)
648 .encode();
649
650 let len = em.len();
651 outgoing_tls[written..written + len].copy_from_slice(&em);
652 written += len;
653 }
654
655 written
656 }
657
658 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
659 self.message_fragmenter
660 .set_max_fragment_size(new)
661 }
662
663 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
664 self.alpn_protocol
665 .as_ref()
666 .map(AsRef::as_ref)
667 }
668
669 pub fn wants_read(&self) -> bool {
679 self.received_plaintext.is_empty()
686 && !self.has_received_close_notify
687 && (self.may_send_application_data || self.sendable_tls.is_empty())
688 }
689
690 pub(crate) fn current_io_state(&self) -> IoState {
691 IoState {
692 tls_bytes_to_write: self.sendable_tls.len(),
693 plaintext_bytes_to_read: self.received_plaintext.len(),
694 peer_has_closed: self.has_received_close_notify,
695 }
696 }
697
698 pub(crate) fn is_quic(&self) -> bool {
699 self.protocol == Protocol::Quic
700 }
701
702 pub(crate) fn should_update_key(
703 &mut self,
704 key_update_request: &KeyUpdateRequest,
705 ) -> Result<bool, Error> {
706 self.temper_counters
707 .received_key_update_request()?;
708
709 match key_update_request {
710 KeyUpdateRequest::UpdateNotRequested => Ok(false),
711 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
712 _ => Err(self.send_fatal_alert(
713 AlertDescription::IllegalParameter,
714 InvalidMessage::InvalidKeyUpdate,
715 )),
716 }
717 }
718
719 pub(crate) fn enqueue_key_update_notification(&mut self) {
720 let message = PlainMessage::from(Message::build_key_update_notify());
721 self.queued_key_update_message = Some(
722 self.record_layer
723 .encrypt_outgoing(message.borrow_outbound())
724 .encode(),
725 );
726 }
727
728 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
729 self.temper_counters
730 .received_tls13_change_cipher_spec()
731 }
732}
733
734#[cfg(feature = "std")]
735impl CommonState {
736 pub(crate) fn buffer_plaintext(
742 &mut self,
743 payload: OutboundChunks<'_>,
744 sendable_plaintext: &mut ChunkVecBuffer,
745 ) -> usize {
746 self.perhaps_write_key_update();
747 self.send_plain(payload, Limit::Yes, sendable_plaintext)
748 }
749
750 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
751 debug_assert!(self.early_traffic);
752 debug_assert!(self.record_layer.is_encrypting());
753
754 if data.is_empty() {
755 return 0;
757 }
758
759 self.send_appdata_encrypt(data.into(), Limit::Yes)
760 }
761
762 fn send_plain(
768 &mut self,
769 payload: OutboundChunks<'_>,
770 limit: Limit,
771 sendable_plaintext: &mut ChunkVecBuffer,
772 ) -> usize {
773 if !self.may_send_application_data {
774 let len = match limit {
777 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
778 Limit::No => sendable_plaintext.append(payload.to_vec()),
779 };
780 return len;
781 }
782
783 self.send_plain_non_buffering(payload, limit)
784 }
785}
786
787#[derive(Debug, PartialEq, Clone, Copy)]
789pub enum HandshakeKind {
790 Full,
795
796 FullWithHelloRetryRequest,
802
803 Resumed,
809}
810
811#[derive(Debug, Eq, PartialEq)]
816pub struct IoState {
817 tls_bytes_to_write: usize,
818 plaintext_bytes_to_read: usize,
819 peer_has_closed: bool,
820}
821
822impl IoState {
823 pub fn tls_bytes_to_write(&self) -> usize {
828 self.tls_bytes_to_write
829 }
830
831 pub fn plaintext_bytes_to_read(&self) -> usize {
834 self.plaintext_bytes_to_read
835 }
836
837 pub fn peer_has_closed(&self) -> bool {
846 self.peer_has_closed
847 }
848}
849
850pub(crate) trait State<Data>: Send + Sync {
851 fn handle<'m>(
852 self: Box<Self>,
853 cx: &mut Context<'_, Data>,
854 message: Message<'m>,
855 ) -> Result<Box<dyn State<Data> + 'm>, Error>
856 where
857 Self: 'm;
858
859 fn export_keying_material(
860 &self,
861 _output: &mut [u8],
862 _label: &[u8],
863 _context: Option<&[u8]>,
864 ) -> Result<(), Error> {
865 Err(Error::HandshakeNotComplete)
866 }
867
868 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
869 Err(Error::HandshakeNotComplete)
870 }
871
872 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
873 Err(Error::HandshakeNotComplete)
874 }
875
876 fn handle_decrypt_error(&self) {}
877
878 fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
879 Err(Error::HandshakeNotComplete)
880 }
881
882 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
883}
884
885pub(crate) struct Context<'a, Data> {
886 pub(crate) common: &'a mut CommonState,
887 pub(crate) data: &'a mut Data,
888 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
891}
892
893#[derive(Clone, Copy, Debug, PartialEq)]
895pub enum Side {
896 Client,
898 Server,
900}
901
902impl Side {
903 pub(crate) fn peer(&self) -> Self {
904 match self {
905 Self::Client => Self::Server,
906 Self::Server => Self::Client,
907 }
908 }
909}
910
911#[derive(Copy, Clone, Eq, PartialEq, Debug)]
912pub(crate) enum Protocol {
913 Tcp,
914 Quic,
915}
916
917enum Limit {
918 #[cfg(feature = "std")]
919 Yes,
920 No,
921}
922
923struct TemperCounters {
926 allowed_warning_alerts: u8,
927 allowed_renegotiation_requests: u8,
928 allowed_key_update_requests: u8,
929 allowed_middlebox_ccs: u8,
930}
931
932impl TemperCounters {
933 fn received_warning_alert(&mut self) -> Result<(), Error> {
934 match self.allowed_warning_alerts {
935 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
936 _ => {
937 self.allowed_warning_alerts -= 1;
938 Ok(())
939 }
940 }
941 }
942
943 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
944 match self.allowed_renegotiation_requests {
945 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
946 _ => {
947 self.allowed_renegotiation_requests -= 1;
948 Ok(())
949 }
950 }
951 }
952
953 fn received_key_update_request(&mut self) -> Result<(), Error> {
954 match self.allowed_key_update_requests {
955 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
956 _ => {
957 self.allowed_key_update_requests -= 1;
958 Ok(())
959 }
960 }
961 }
962
963 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
964 match self.allowed_middlebox_ccs {
965 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
966 _ => {
967 self.allowed_middlebox_ccs -= 1;
968 Ok(())
969 }
970 }
971 }
972
973 fn received_app_data(&mut self) {
974 self.allowed_key_update_requests = Self::INITIAL_KEY_UPDATE_REQUESTS;
975 }
976
977 const INITIAL_KEY_UPDATE_REQUESTS: u8 = 32;
980}
981
982impl Default for TemperCounters {
983 fn default() -> Self {
984 Self {
985 allowed_warning_alerts: 4,
988
989 allowed_renegotiation_requests: 1,
992
993 allowed_key_update_requests: Self::INITIAL_KEY_UPDATE_REQUESTS,
994
995 allowed_middlebox_ccs: 2,
1000 }
1001 }
1002}
1003
1004#[derive(Debug, Default)]
1005pub(crate) enum KxState {
1006 #[default]
1007 None,
1008 Start(&'static dyn SupportedKxGroup),
1009 Complete(&'static dyn SupportedKxGroup),
1010}
1011
1012impl KxState {
1013 pub(crate) fn complete(&mut self) {
1014 debug_assert!(matches!(self, Self::Start(_)));
1015 if let Self::Start(group) = self {
1016 *self = Self::Complete(*group);
1017 }
1018 }
1019}
1020
1021pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
1022 pub(crate) transcript: &'a mut HandshakeHash,
1023 body: Vec<u8>,
1024}
1025
1026impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
1027 pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
1028 Self {
1029 transcript,
1030 body: Vec::new(),
1031 }
1032 }
1033
1034 pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1035 let start_len = self.body.len();
1036 hs.encode(&mut self.body);
1037 self.transcript
1038 .add(&self.body[start_len..]);
1039 }
1040
1041 pub(crate) fn finish(self, common: &mut CommonState) {
1042 common.send_msg(
1043 Message {
1044 version: match TLS13 {
1045 true => ProtocolVersion::TLSv1_3,
1046 false => ProtocolVersion::TLSv1_2,
1047 },
1048 payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1049 },
1050 TLS13,
1051 );
1052 }
1053}
1054
1055#[cfg(feature = "tls12")]
1056pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1057pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1058
1059const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1060pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;