1use alloc::boxed::Box;
2use alloc::vec::Vec;
3
4use pki_types::CertificateDer;
5
6use crate::crypto::SupportedKxGroup;
7use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
8use crate::error::{Error, InvalidMessage, PeerMisbehaved};
9use crate::log::{debug, error, warn};
10use crate::msgs::alert::AlertMessagePayload;
11use crate::msgs::base::Payload;
12use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
13use crate::msgs::fragmenter::MessageFragmenter;
14use crate::msgs::handshake::CertificateChain;
15use crate::msgs::message::{
16 Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
17 PlainMessage,
18};
19use crate::record_layer::PreEncryptAction;
20use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
21#[cfg(feature = "tls12")]
22use crate::tls12::ConnectionSecrets;
23use crate::unbuffered::{EncryptError, InsufficientSizeError};
24use crate::vecbuf::ChunkVecBuffer;
25use crate::{quic, record_layer};
26
27pub struct CommonState {
29 pub(crate) negotiated_version: Option<ProtocolVersion>,
30 pub(crate) handshake_kind: Option<HandshakeKind>,
31 pub(crate) side: Side,
32 pub(crate) record_layer: record_layer::RecordLayer,
33 pub(crate) suite: Option<SupportedCipherSuite>,
34 pub(crate) kx_state: KxState,
35 pub(crate) alpn_protocol: Option<Vec<u8>>,
36 pub(crate) aligned_handshake: bool,
37 pub(crate) may_send_application_data: bool,
38 pub(crate) may_receive_application_data: bool,
39 pub(crate) early_traffic: bool,
40 sent_fatal_alert: bool,
41 pub(crate) has_received_close_notify: bool,
43 #[cfg(feature = "std")]
44 pub(crate) has_seen_eof: bool,
45 pub(crate) peer_certificates: Option<CertificateChain<'static>>,
46 message_fragmenter: MessageFragmenter,
47 pub(crate) received_plaintext: ChunkVecBuffer,
48 pub(crate) sendable_tls: ChunkVecBuffer,
49 queued_key_update_message: Option<Vec<u8>>,
50
51 pub(crate) protocol: Protocol,
53 pub(crate) quic: quic::Quic,
54 pub(crate) enable_secret_extraction: bool,
55 temper_counters: TemperCounters,
56 pub(crate) refresh_traffic_keys_pending: bool,
57}
58
59impl CommonState {
60 pub(crate) fn new(side: Side) -> Self {
61 Self {
62 negotiated_version: None,
63 handshake_kind: None,
64 side,
65 record_layer: record_layer::RecordLayer::new(),
66 suite: None,
67 kx_state: KxState::default(),
68 alpn_protocol: None,
69 aligned_handshake: true,
70 may_send_application_data: false,
71 may_receive_application_data: false,
72 early_traffic: false,
73 sent_fatal_alert: false,
74 has_received_close_notify: false,
75 #[cfg(feature = "std")]
76 has_seen_eof: false,
77 peer_certificates: None,
78 message_fragmenter: MessageFragmenter::default(),
79 received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
80 sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
81 queued_key_update_message: None,
82 protocol: Protocol::Tcp,
83 quic: quic::Quic::default(),
84 enable_secret_extraction: false,
85 temper_counters: TemperCounters::default(),
86 refresh_traffic_keys_pending: false,
87 }
88 }
89
90 pub fn wants_write(&self) -> bool {
94 !self.sendable_tls.is_empty()
95 }
96
97 pub fn is_handshaking(&self) -> bool {
105 !(self.may_send_application_data && self.may_receive_application_data)
106 }
107
108 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
124 self.peer_certificates.as_deref()
125 }
126
127 pub fn alpn_protocol(&self) -> Option<&[u8]> {
133 self.get_alpn_protocol()
134 }
135
136 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
140 self.suite
141 }
142
143 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
153 match self.kx_state {
154 KxState::Complete(group) => Some(group),
155 _ => None,
156 }
157 }
158
159 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
163 self.negotiated_version
164 }
165
166 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
173 self.handshake_kind
174 }
175
176 pub(crate) fn is_tls13(&self) -> bool {
177 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
178 }
179
180 pub(crate) fn process_main_protocol<Data>(
181 &mut self,
182 msg: Message<'_>,
183 mut state: Box<dyn State<Data>>,
184 data: &mut Data,
185 sendable_plaintext: Option<&mut ChunkVecBuffer>,
186 ) -> Result<Box<dyn State<Data>>, Error> {
187 if self.may_receive_application_data && !self.is_tls13() {
190 let reject_ty = match self.side {
191 Side::Client => HandshakeType::HelloRequest,
192 Side::Server => HandshakeType::ClientHello,
193 };
194 if msg.is_handshake_type(reject_ty) {
195 self.temper_counters
196 .received_renegotiation_request()?;
197 self.send_warning_alert(AlertDescription::NoRenegotiation);
198 return Ok(state);
199 }
200 }
201
202 let mut cx = Context {
203 common: self,
204 data,
205 sendable_plaintext,
206 };
207 match state.handle(&mut cx, msg) {
208 Ok(next) => {
209 state = next.into_owned();
210 Ok(state)
211 }
212 Err(e @ Error::InappropriateMessage { .. })
213 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
214 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
215 }
216 Err(e) => Err(e),
217 }
218 }
219
220 pub(crate) fn write_plaintext(
221 &mut self,
222 payload: OutboundChunks<'_>,
223 outgoing_tls: &mut [u8],
224 ) -> Result<usize, EncryptError> {
225 if payload.is_empty() {
226 return Ok(0);
227 }
228
229 let fragments = self
230 .message_fragmenter
231 .fragment_payload(
232 ContentType::ApplicationData,
233 ProtocolVersion::TLSv1_2,
234 payload.clone(),
235 );
236
237 for f in 0..fragments.len() {
238 match self
239 .record_layer
240 .pre_encrypt_action(f as u64)
241 {
242 PreEncryptAction::Nothing => {}
243 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
244 Some(ProtocolVersion::TLSv1_3) => {
245 self.refresh_traffic_keys_pending = true;
247 }
248 _ => {
249 error!("traffic keys exhausted, closing connection to prevent security failure");
250 self.send_close_notify();
251 return Err(EncryptError::EncryptExhausted);
252 }
253 },
254 PreEncryptAction::Refuse => {
255 return Err(EncryptError::EncryptExhausted);
256 }
257 }
258 }
259
260 self.perhaps_write_key_update();
261
262 self.check_required_size(outgoing_tls, fragments)?;
263
264 let fragments = self
265 .message_fragmenter
266 .fragment_payload(
267 ContentType::ApplicationData,
268 ProtocolVersion::TLSv1_2,
269 payload,
270 );
271
272 Ok(self.write_fragments(outgoing_tls, fragments))
273 }
274
275 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
280 if !self.aligned_handshake {
281 Err(self.send_fatal_alert(
282 AlertDescription::UnexpectedMessage,
283 PeerMisbehaved::KeyEpochWithPendingFragment,
284 ))
285 } else {
286 Ok(())
287 }
288 }
289
290 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
293 let iter = self
294 .message_fragmenter
295 .fragment_message(&m);
296 for m in iter {
297 self.send_single_fragment(m);
298 }
299 }
300
301 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
303 let len = match limit {
308 #[cfg(feature = "std")]
309 Limit::Yes => self
310 .sendable_tls
311 .apply_limit(payload.len()),
312 Limit::No => payload.len(),
313 };
314
315 let iter = self
316 .message_fragmenter
317 .fragment_payload(
318 ContentType::ApplicationData,
319 ProtocolVersion::TLSv1_2,
320 payload.split_at(len).0,
321 );
322 for m in iter {
323 self.send_single_fragment(m);
324 }
325
326 len
327 }
328
329 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
330 if m.typ == ContentType::Alert {
331 let em = self.record_layer.encrypt_outgoing(m);
333 self.queue_tls_message(em);
334 return;
335 }
336
337 match self
338 .record_layer
339 .next_pre_encrypt_action()
340 {
341 PreEncryptAction::Nothing => {}
342
343 PreEncryptAction::RefreshOrClose => {
346 match self.negotiated_version {
347 Some(ProtocolVersion::TLSv1_3) => {
348 self.refresh_traffic_keys_pending = true;
350 }
351 _ => {
352 error!("traffic keys exhausted, closing connection to prevent security failure");
353 self.send_close_notify();
354 return;
355 }
356 }
357 }
358
359 PreEncryptAction::Refuse => {
362 return;
363 }
364 };
365
366 let em = self.record_layer.encrypt_outgoing(m);
367 self.queue_tls_message(em);
368 }
369
370 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
371 debug_assert!(self.may_send_application_data);
372 debug_assert!(self.record_layer.is_encrypting());
373
374 if payload.is_empty() {
375 return 0;
377 }
378
379 self.send_appdata_encrypt(payload, limit)
380 }
381
382 pub(crate) fn start_outgoing_traffic(
386 &mut self,
387 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
388 ) {
389 self.may_send_application_data = true;
390 if let Some(sendable_plaintext) = sendable_plaintext {
391 self.flush_plaintext(sendable_plaintext);
392 }
393 }
394
395 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
399 self.may_receive_application_data = true;
400 self.start_outgoing_traffic(sendable_plaintext);
401 }
402
403 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
406 if !self.may_send_application_data {
407 return;
408 }
409
410 while let Some(buf) = sendable_plaintext.pop() {
411 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
412 }
413 }
414
415 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
417 self.perhaps_write_key_update();
418 self.sendable_tls.append(m.encode());
419 }
420
421 pub(crate) fn perhaps_write_key_update(&mut self) {
422 if let Some(message) = self.queued_key_update_message.take() {
423 self.sendable_tls.append(message);
424 }
425 }
426
427 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
429 {
430 if let Protocol::Quic = self.protocol {
431 if let MessagePayload::Alert(alert) = m.payload {
432 self.quic.alert = Some(alert.description);
433 } else {
434 debug_assert!(
435 matches!(m.payload, MessagePayload::Handshake { .. }),
436 "QUIC uses TLS for the cryptographic handshake only"
437 );
438 let mut bytes = Vec::new();
439 m.payload.encode(&mut bytes);
440 self.quic
441 .hs_queue
442 .push_back((must_encrypt, bytes));
443 }
444 return;
445 }
446 }
447 if !must_encrypt {
448 let msg = &m.into();
449 let iter = self
450 .message_fragmenter
451 .fragment_message(msg);
452 for m in iter {
453 self.queue_tls_message(m.to_unencrypted_opaque());
454 }
455 } else {
456 self.send_msg_encrypt(m.into());
457 }
458 }
459
460 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
461 self.received_plaintext
462 .append(bytes.into_vec());
463 }
464
465 #[cfg(feature = "tls12")]
466 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
467 let (dec, enc) = secrets.make_cipher_pair(side);
468 self.record_layer
469 .prepare_message_encrypter(
470 enc,
471 secrets
472 .suite()
473 .common
474 .confidentiality_limit,
475 );
476 self.record_layer
477 .prepare_message_decrypter(dec);
478 }
479
480 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
481 self.send_fatal_alert(AlertDescription::MissingExtension, why)
482 }
483
484 fn send_warning_alert(&mut self, desc: AlertDescription) {
485 warn!("Sending warning alert {:?}", desc);
486 self.send_warning_alert_no_log(desc);
487 }
488
489 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
490 if let AlertLevel::Unknown(_) = alert.level {
492 return Err(self.send_fatal_alert(
493 AlertDescription::IllegalParameter,
494 Error::AlertReceived(alert.description),
495 ));
496 }
497
498 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
501 self.has_received_close_notify = true;
502 return Ok(());
503 }
504
505 let err = Error::AlertReceived(alert.description);
508 if alert.level == AlertLevel::Warning {
509 self.temper_counters
510 .received_warning_alert()?;
511 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
512 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
513 } else {
514 warn!("TLS alert warning received: {:?}", alert);
515 return Ok(());
516 }
517 }
518
519 Err(err)
520 }
521
522 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
523 self.send_fatal_alert(
524 match &err {
525 Error::InvalidCertificate(e) => e.clone().into(),
526 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
527 _ => AlertDescription::HandshakeFailure,
528 },
529 err,
530 )
531 }
532
533 pub(crate) fn send_fatal_alert(
534 &mut self,
535 desc: AlertDescription,
536 err: impl Into<Error>,
537 ) -> Error {
538 debug_assert!(!self.sent_fatal_alert);
539 let m = Message::build_alert(AlertLevel::Fatal, desc);
540 self.send_msg(m, self.record_layer.is_encrypting());
541 self.sent_fatal_alert = true;
542 err.into()
543 }
544
545 pub fn send_close_notify(&mut self) {
553 if self.sent_fatal_alert {
554 return;
555 }
556 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
557 self.sent_fatal_alert = true;
558 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
559 }
560
561 pub(crate) fn eager_send_close_notify(
562 &mut self,
563 outgoing_tls: &mut [u8],
564 ) -> Result<usize, EncryptError> {
565 self.send_close_notify();
566 self.check_required_size(outgoing_tls, [].into_iter())?;
567 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
568 }
569
570 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
571 let m = Message::build_alert(AlertLevel::Warning, desc);
572 self.send_msg(m, self.record_layer.is_encrypting());
573 }
574
575 fn check_required_size<'a>(
576 &self,
577 outgoing_tls: &mut [u8],
578 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
579 ) -> Result<(), EncryptError> {
580 let mut required_size = self.sendable_tls.len();
581
582 for m in fragments {
583 required_size += m.encoded_len(&self.record_layer);
584 }
585
586 if required_size > outgoing_tls.len() {
587 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
588 required_size,
589 }));
590 }
591
592 Ok(())
593 }
594
595 fn write_fragments<'a>(
596 &mut self,
597 outgoing_tls: &mut [u8],
598 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
599 ) -> usize {
600 let mut written = 0;
601
602 while let Some(message) = self.sendable_tls.pop() {
605 let len = message.len();
606 outgoing_tls[written..written + len].copy_from_slice(&message);
607 written += len;
608 }
609
610 for m in fragments {
611 let em = self
612 .record_layer
613 .encrypt_outgoing(m)
614 .encode();
615
616 let len = em.len();
617 outgoing_tls[written..written + len].copy_from_slice(&em);
618 written += len;
619 }
620
621 written
622 }
623
624 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
625 self.message_fragmenter
626 .set_max_fragment_size(new)
627 }
628
629 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
630 self.alpn_protocol
631 .as_ref()
632 .map(AsRef::as_ref)
633 }
634
635 pub fn wants_read(&self) -> bool {
645 self.received_plaintext.is_empty()
652 && !self.has_received_close_notify
653 && (self.may_send_application_data || self.sendable_tls.is_empty())
654 }
655
656 pub(crate) fn current_io_state(&self) -> IoState {
657 IoState {
658 tls_bytes_to_write: self.sendable_tls.len(),
659 plaintext_bytes_to_read: self.received_plaintext.len(),
660 peer_has_closed: self.has_received_close_notify,
661 }
662 }
663
664 pub(crate) fn is_quic(&self) -> bool {
665 self.protocol == Protocol::Quic
666 }
667
668 pub(crate) fn should_update_key(
669 &mut self,
670 key_update_request: &KeyUpdateRequest,
671 ) -> Result<bool, Error> {
672 self.temper_counters
673 .received_key_update_request()?;
674
675 match key_update_request {
676 KeyUpdateRequest::UpdateNotRequested => Ok(false),
677 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
678 _ => Err(self.send_fatal_alert(
679 AlertDescription::IllegalParameter,
680 InvalidMessage::InvalidKeyUpdate,
681 )),
682 }
683 }
684
685 pub(crate) fn enqueue_key_update_notification(&mut self) {
686 let message = PlainMessage::from(Message::build_key_update_notify());
687 self.queued_key_update_message = Some(
688 self.record_layer
689 .encrypt_outgoing(message.borrow_outbound())
690 .encode(),
691 );
692 }
693
694 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
695 self.temper_counters
696 .received_tls13_change_cipher_spec()
697 }
698}
699
700#[cfg(feature = "std")]
701impl CommonState {
702 pub(crate) fn buffer_plaintext(
708 &mut self,
709 payload: OutboundChunks<'_>,
710 sendable_plaintext: &mut ChunkVecBuffer,
711 ) -> usize {
712 self.perhaps_write_key_update();
713 self.send_plain(payload, Limit::Yes, sendable_plaintext)
714 }
715
716 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
717 debug_assert!(self.early_traffic);
718 debug_assert!(self.record_layer.is_encrypting());
719
720 if data.is_empty() {
721 return 0;
723 }
724
725 self.send_appdata_encrypt(data.into(), Limit::Yes)
726 }
727
728 fn send_plain(
734 &mut self,
735 payload: OutboundChunks<'_>,
736 limit: Limit,
737 sendable_plaintext: &mut ChunkVecBuffer,
738 ) -> usize {
739 if !self.may_send_application_data {
740 let len = match limit {
743 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
744 Limit::No => sendable_plaintext.append(payload.to_vec()),
745 };
746 return len;
747 }
748
749 self.send_plain_non_buffering(payload, limit)
750 }
751}
752
753#[derive(Debug, PartialEq, Clone, Copy)]
755pub enum HandshakeKind {
756 Full,
761
762 FullWithHelloRetryRequest,
768
769 Resumed,
775}
776
777#[derive(Debug, Eq, PartialEq)]
782pub struct IoState {
783 tls_bytes_to_write: usize,
784 plaintext_bytes_to_read: usize,
785 peer_has_closed: bool,
786}
787
788impl IoState {
789 pub fn tls_bytes_to_write(&self) -> usize {
794 self.tls_bytes_to_write
795 }
796
797 pub fn plaintext_bytes_to_read(&self) -> usize {
800 self.plaintext_bytes_to_read
801 }
802
803 pub fn peer_has_closed(&self) -> bool {
812 self.peer_has_closed
813 }
814}
815
816pub(crate) trait State<Data>: Send + Sync {
817 fn handle<'m>(
818 self: Box<Self>,
819 cx: &mut Context<'_, Data>,
820 message: Message<'m>,
821 ) -> Result<Box<dyn State<Data> + 'm>, Error>
822 where
823 Self: 'm;
824
825 fn export_keying_material(
826 &self,
827 _output: &mut [u8],
828 _label: &[u8],
829 _context: Option<&[u8]>,
830 ) -> Result<(), Error> {
831 Err(Error::HandshakeNotComplete)
832 }
833
834 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
835 Err(Error::HandshakeNotComplete)
836 }
837
838 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
839 Err(Error::HandshakeNotComplete)
840 }
841
842 fn handle_decrypt_error(&self) {}
843
844 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
845}
846
847pub(crate) struct Context<'a, Data> {
848 pub(crate) common: &'a mut CommonState,
849 pub(crate) data: &'a mut Data,
850 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
853}
854
855#[derive(Clone, Copy, Debug, PartialEq)]
857pub enum Side {
858 Client,
860 Server,
862}
863
864impl Side {
865 pub(crate) fn peer(&self) -> Self {
866 match self {
867 Self::Client => Self::Server,
868 Self::Server => Self::Client,
869 }
870 }
871}
872
873#[derive(Copy, Clone, Eq, PartialEq, Debug)]
874pub(crate) enum Protocol {
875 Tcp,
876 Quic,
877}
878
879enum Limit {
880 #[cfg(feature = "std")]
881 Yes,
882 No,
883}
884
885struct TemperCounters {
888 allowed_warning_alerts: u8,
889 allowed_renegotiation_requests: u8,
890 allowed_key_update_requests: u8,
891 allowed_middlebox_ccs: u8,
892}
893
894impl TemperCounters {
895 fn received_warning_alert(&mut self) -> Result<(), Error> {
896 match self.allowed_warning_alerts {
897 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
898 _ => {
899 self.allowed_warning_alerts -= 1;
900 Ok(())
901 }
902 }
903 }
904
905 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
906 match self.allowed_renegotiation_requests {
907 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
908 _ => {
909 self.allowed_renegotiation_requests -= 1;
910 Ok(())
911 }
912 }
913 }
914
915 fn received_key_update_request(&mut self) -> Result<(), Error> {
916 match self.allowed_key_update_requests {
917 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
918 _ => {
919 self.allowed_key_update_requests -= 1;
920 Ok(())
921 }
922 }
923 }
924
925 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
926 match self.allowed_middlebox_ccs {
927 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
928 _ => {
929 self.allowed_middlebox_ccs -= 1;
930 Ok(())
931 }
932 }
933 }
934}
935
936impl Default for TemperCounters {
937 fn default() -> Self {
938 Self {
939 allowed_warning_alerts: 4,
942
943 allowed_renegotiation_requests: 1,
946
947 allowed_key_update_requests: 32,
950
951 allowed_middlebox_ccs: 2,
956 }
957 }
958}
959
960#[derive(Debug, Default)]
961pub(crate) enum KxState {
962 #[default]
963 None,
964 Start(&'static dyn SupportedKxGroup),
965 Complete(&'static dyn SupportedKxGroup),
966}
967
968impl KxState {
969 pub(crate) fn complete(&mut self) {
970 debug_assert!(matches!(self, Self::Start(_)));
971 if let Self::Start(group) = self {
972 *self = Self::Complete(*group);
973 }
974 }
975}
976
977const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
978pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;