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::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::{CertificateChain, HandshakeMessagePayload};
17use crate::msgs::message::{
18 Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
19 PlainMessage,
20};
21use crate::record_layer::PreEncryptAction;
22use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
23#[cfg(feature = "tls12")]
24use crate::tls12::ConnectionSecrets;
25use crate::unbuffered::{EncryptError, InsufficientSizeError};
26use crate::vecbuf::ChunkVecBuffer;
27use crate::{quic, record_layer};
28
29pub struct CommonState {
31 pub(crate) negotiated_version: Option<ProtocolVersion>,
32 pub(crate) handshake_kind: Option<HandshakeKind>,
33 pub(crate) side: Side,
34 pub(crate) record_layer: record_layer::RecordLayer,
35 pub(crate) suite: Option<SupportedCipherSuite>,
36 pub(crate) kx_state: KxState,
37 pub(crate) alpn_protocol: Option<Vec<u8>>,
38 pub(crate) aligned_handshake: bool,
39 pub(crate) may_send_application_data: bool,
40 pub(crate) may_receive_application_data: bool,
41 pub(crate) early_traffic: bool,
42 sent_fatal_alert: bool,
43 pub(crate) has_sent_close_notify: bool,
45 pub(crate) has_received_close_notify: bool,
47 #[cfg(feature = "std")]
48 pub(crate) has_seen_eof: bool,
49 pub(crate) peer_certificates: Option<CertificateChain<'static>>,
50 message_fragmenter: MessageFragmenter,
51 pub(crate) received_plaintext: ChunkVecBuffer,
52 pub(crate) sendable_tls: ChunkVecBuffer,
53 queued_key_update_message: Option<Vec<u8>>,
54
55 pub(crate) protocol: Protocol,
57 pub(crate) quic: quic::Quic,
58 pub(crate) enable_secret_extraction: bool,
59 temper_counters: TemperCounters,
60 pub(crate) refresh_traffic_keys_pending: bool,
61 pub(crate) fips: bool,
62}
63
64impl CommonState {
65 pub(crate) fn new(side: Side) -> Self {
66 Self {
67 negotiated_version: None,
68 handshake_kind: None,
69 side,
70 record_layer: record_layer::RecordLayer::new(),
71 suite: None,
72 kx_state: KxState::default(),
73 alpn_protocol: None,
74 aligned_handshake: true,
75 may_send_application_data: false,
76 may_receive_application_data: false,
77 early_traffic: false,
78 sent_fatal_alert: false,
79 has_sent_close_notify: false,
80 has_received_close_notify: false,
81 #[cfg(feature = "std")]
82 has_seen_eof: false,
83 peer_certificates: None,
84 message_fragmenter: MessageFragmenter::default(),
85 received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
86 sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
87 queued_key_update_message: None,
88 protocol: Protocol::Tcp,
89 quic: quic::Quic::default(),
90 enable_secret_extraction: false,
91 temper_counters: TemperCounters::default(),
92 refresh_traffic_keys_pending: false,
93 fips: false,
94 }
95 }
96
97 pub fn wants_write(&self) -> bool {
101 !self.sendable_tls.is_empty()
102 }
103
104 pub fn is_handshaking(&self) -> bool {
112 !(self.may_send_application_data && self.may_receive_application_data)
113 }
114
115 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
137 self.peer_certificates.as_deref()
138 }
139
140 pub fn alpn_protocol(&self) -> Option<&[u8]> {
146 self.get_alpn_protocol()
147 }
148
149 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
153 self.suite
154 }
155
156 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
166 match self.kx_state {
167 KxState::Complete(group) => Some(group),
168 _ => None,
169 }
170 }
171
172 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
176 self.negotiated_version
177 }
178
179 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
186 self.handshake_kind
187 }
188
189 pub(crate) fn is_tls13(&self) -> bool {
190 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
191 }
192
193 pub(crate) fn process_main_protocol<Data>(
194 &mut self,
195 msg: Message<'_>,
196 mut state: Box<dyn State<Data>>,
197 data: &mut Data,
198 sendable_plaintext: Option<&mut ChunkVecBuffer>,
199 ) -> Result<Box<dyn State<Data>>, Error> {
200 if self.may_receive_application_data && !self.is_tls13() {
203 let reject_ty = match self.side {
204 Side::Client => HandshakeType::HelloRequest,
205 Side::Server => HandshakeType::ClientHello,
206 };
207 if msg.is_handshake_type(reject_ty) {
208 self.temper_counters
209 .received_renegotiation_request()?;
210 self.send_warning_alert(AlertDescription::NoRenegotiation);
211 return Ok(state);
212 }
213 }
214
215 let mut cx = Context {
216 common: self,
217 data,
218 sendable_plaintext,
219 };
220 match state.handle(&mut cx, msg) {
221 Ok(next) => {
222 state = next.into_owned();
223 Ok(state)
224 }
225 Err(e @ Error::InappropriateMessage { .. })
226 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
227 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
228 }
229 Err(e) => Err(e),
230 }
231 }
232
233 pub(crate) fn write_plaintext(
234 &mut self,
235 payload: OutboundChunks<'_>,
236 outgoing_tls: &mut [u8],
237 ) -> Result<usize, EncryptError> {
238 if payload.is_empty() {
239 return Ok(0);
240 }
241
242 let fragments = self
243 .message_fragmenter
244 .fragment_payload(
245 ContentType::ApplicationData,
246 ProtocolVersion::TLSv1_2,
247 payload.clone(),
248 );
249
250 for f in 0..fragments.len() {
251 match self
252 .record_layer
253 .pre_encrypt_action(f as u64)
254 {
255 PreEncryptAction::Nothing => {}
256 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
257 Some(ProtocolVersion::TLSv1_3) => {
258 self.refresh_traffic_keys_pending = true;
260 }
261 _ => {
262 error!(
263 "traffic keys exhausted, closing connection to prevent security failure"
264 );
265 self.send_close_notify();
266 return Err(EncryptError::EncryptExhausted);
267 }
268 },
269 PreEncryptAction::Refuse => {
270 return Err(EncryptError::EncryptExhausted);
271 }
272 }
273 }
274
275 self.perhaps_write_key_update();
276
277 self.check_required_size(outgoing_tls, fragments)?;
278
279 let fragments = self
280 .message_fragmenter
281 .fragment_payload(
282 ContentType::ApplicationData,
283 ProtocolVersion::TLSv1_2,
284 payload,
285 );
286
287 Ok(self.write_fragments(outgoing_tls, fragments))
288 }
289
290 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
295 if !self.aligned_handshake {
296 Err(self.send_fatal_alert(
297 AlertDescription::UnexpectedMessage,
298 PeerMisbehaved::KeyEpochWithPendingFragment,
299 ))
300 } else {
301 Ok(())
302 }
303 }
304
305 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
308 let iter = self
309 .message_fragmenter
310 .fragment_message(&m);
311 for m in iter {
312 self.send_single_fragment(m);
313 }
314 }
315
316 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
318 let len = match limit {
323 #[cfg(feature = "std")]
324 Limit::Yes => self
325 .sendable_tls
326 .apply_limit(payload.len()),
327 Limit::No => payload.len(),
328 };
329
330 let iter = self
331 .message_fragmenter
332 .fragment_payload(
333 ContentType::ApplicationData,
334 ProtocolVersion::TLSv1_2,
335 payload.split_at(len).0,
336 );
337 for m in iter {
338 self.send_single_fragment(m);
339 }
340
341 len
342 }
343
344 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
345 if m.typ == ContentType::Alert {
346 let em = self.record_layer.encrypt_outgoing(m);
348 self.queue_tls_message(em);
349 return;
350 }
351
352 match self
353 .record_layer
354 .next_pre_encrypt_action()
355 {
356 PreEncryptAction::Nothing => {}
357
358 PreEncryptAction::RefreshOrClose => {
361 match self.negotiated_version {
362 Some(ProtocolVersion::TLSv1_3) => {
363 self.refresh_traffic_keys_pending = true;
365 }
366 _ => {
367 error!(
368 "traffic keys exhausted, closing connection to prevent security failure"
369 );
370 self.send_close_notify();
371 return;
372 }
373 }
374 }
375
376 PreEncryptAction::Refuse => {
379 return;
380 }
381 };
382
383 let em = self.record_layer.encrypt_outgoing(m);
384 self.queue_tls_message(em);
385 }
386
387 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
388 debug_assert!(self.may_send_application_data);
389 debug_assert!(self.record_layer.is_encrypting());
390
391 if payload.is_empty() {
392 return 0;
394 }
395
396 self.send_appdata_encrypt(payload, limit)
397 }
398
399 pub(crate) fn start_outgoing_traffic(
403 &mut self,
404 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
405 ) {
406 self.may_send_application_data = true;
407 if let Some(sendable_plaintext) = sendable_plaintext {
408 self.flush_plaintext(sendable_plaintext);
409 }
410 }
411
412 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
416 self.may_receive_application_data = true;
417 self.start_outgoing_traffic(sendable_plaintext);
418 }
419
420 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
423 if !self.may_send_application_data {
424 return;
425 }
426
427 while let Some(buf) = sendable_plaintext.pop() {
428 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
429 }
430 }
431
432 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
434 self.perhaps_write_key_update();
435 self.sendable_tls.append(m.encode());
436 }
437
438 pub(crate) fn perhaps_write_key_update(&mut self) {
439 if let Some(message) = self.queued_key_update_message.take() {
440 self.sendable_tls.append(message);
441 }
442 }
443
444 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
446 {
447 if let Protocol::Quic = self.protocol {
448 if let MessagePayload::Alert(alert) = m.payload {
449 self.quic.alert = Some(alert.description);
450 } else {
451 debug_assert!(
452 matches!(
453 m.payload,
454 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
455 ),
456 "QUIC uses TLS for the cryptographic handshake only"
457 );
458 let mut bytes = Vec::new();
459 m.payload.encode(&mut bytes);
460 self.quic
461 .hs_queue
462 .push_back((must_encrypt, bytes));
463 }
464 return;
465 }
466 }
467 if !must_encrypt {
468 let msg = &m.into();
469 let iter = self
470 .message_fragmenter
471 .fragment_message(msg);
472 for m in iter {
473 self.queue_tls_message(m.to_unencrypted_opaque());
474 }
475 } else {
476 self.send_msg_encrypt(m.into());
477 }
478 }
479
480 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
481 self.received_plaintext
482 .append(bytes.into_vec());
483 }
484
485 #[cfg(feature = "tls12")]
486 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
487 let (dec, enc) = secrets.make_cipher_pair(side);
488 self.record_layer
489 .prepare_message_encrypter(
490 enc,
491 secrets
492 .suite()
493 .common
494 .confidentiality_limit,
495 );
496 self.record_layer
497 .prepare_message_decrypter(dec);
498 }
499
500 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
501 self.send_fatal_alert(AlertDescription::MissingExtension, why)
502 }
503
504 fn send_warning_alert(&mut self, desc: AlertDescription) {
505 warn!("Sending warning alert {:?}", desc);
506 self.send_warning_alert_no_log(desc);
507 }
508
509 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
510 if let AlertLevel::Unknown(_) = alert.level {
512 return Err(self.send_fatal_alert(
513 AlertDescription::IllegalParameter,
514 Error::AlertReceived(alert.description),
515 ));
516 }
517
518 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
521 self.has_received_close_notify = true;
522 return Ok(());
523 }
524
525 let err = Error::AlertReceived(alert.description);
528 if alert.level == AlertLevel::Warning {
529 self.temper_counters
530 .received_warning_alert()?;
531 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
532 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
533 }
534
535 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
538 warn!("TLS alert warning received: {alert:?}");
539 }
540
541 return Ok(());
542 }
543
544 Err(err)
545 }
546
547 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
548 self.send_fatal_alert(
549 match &err {
550 Error::InvalidCertificate(e) => e.clone().into(),
551 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
552 _ => AlertDescription::HandshakeFailure,
553 },
554 err,
555 )
556 }
557
558 pub(crate) fn send_fatal_alert(
559 &mut self,
560 desc: AlertDescription,
561 err: impl Into<Error>,
562 ) -> Error {
563 debug_assert!(!self.sent_fatal_alert);
564 let m = Message::build_alert(AlertLevel::Fatal, desc);
565 self.send_msg(m, self.record_layer.is_encrypting());
566 self.sent_fatal_alert = true;
567 err.into()
568 }
569
570 pub fn send_close_notify(&mut self) {
578 if self.sent_fatal_alert {
579 return;
580 }
581 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
582 self.sent_fatal_alert = true;
583 self.has_sent_close_notify = true;
584 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
585 }
586
587 pub(crate) fn eager_send_close_notify(
588 &mut self,
589 outgoing_tls: &mut [u8],
590 ) -> Result<usize, EncryptError> {
591 self.send_close_notify();
592 self.check_required_size(outgoing_tls, [].into_iter())?;
593 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
594 }
595
596 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
597 let m = Message::build_alert(AlertLevel::Warning, desc);
598 self.send_msg(m, self.record_layer.is_encrypting());
599 }
600
601 fn check_required_size<'a>(
602 &self,
603 outgoing_tls: &mut [u8],
604 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
605 ) -> Result<(), EncryptError> {
606 let mut required_size = self.sendable_tls.len();
607
608 for m in fragments {
609 required_size += m.encoded_len(&self.record_layer);
610 }
611
612 if required_size > outgoing_tls.len() {
613 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
614 required_size,
615 }));
616 }
617
618 Ok(())
619 }
620
621 fn write_fragments<'a>(
622 &mut self,
623 outgoing_tls: &mut [u8],
624 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
625 ) -> usize {
626 let mut written = 0;
627
628 while let Some(message) = self.sendable_tls.pop() {
631 let len = message.len();
632 outgoing_tls[written..written + len].copy_from_slice(&message);
633 written += len;
634 }
635
636 for m in fragments {
637 let em = self
638 .record_layer
639 .encrypt_outgoing(m)
640 .encode();
641
642 let len = em.len();
643 outgoing_tls[written..written + len].copy_from_slice(&em);
644 written += len;
645 }
646
647 written
648 }
649
650 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
651 self.message_fragmenter
652 .set_max_fragment_size(new)
653 }
654
655 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
656 self.alpn_protocol
657 .as_ref()
658 .map(AsRef::as_ref)
659 }
660
661 pub fn wants_read(&self) -> bool {
671 self.received_plaintext.is_empty()
678 && !self.has_received_close_notify
679 && (self.may_send_application_data || self.sendable_tls.is_empty())
680 }
681
682 pub(crate) fn current_io_state(&self) -> IoState {
683 IoState {
684 tls_bytes_to_write: self.sendable_tls.len(),
685 plaintext_bytes_to_read: self.received_plaintext.len(),
686 peer_has_closed: self.has_received_close_notify,
687 }
688 }
689
690 pub(crate) fn is_quic(&self) -> bool {
691 self.protocol == Protocol::Quic
692 }
693
694 pub(crate) fn should_update_key(
695 &mut self,
696 key_update_request: &KeyUpdateRequest,
697 ) -> Result<bool, Error> {
698 self.temper_counters
699 .received_key_update_request()?;
700
701 match key_update_request {
702 KeyUpdateRequest::UpdateNotRequested => Ok(false),
703 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
704 _ => Err(self.send_fatal_alert(
705 AlertDescription::IllegalParameter,
706 InvalidMessage::InvalidKeyUpdate,
707 )),
708 }
709 }
710
711 pub(crate) fn enqueue_key_update_notification(&mut self) {
712 let message = PlainMessage::from(Message::build_key_update_notify());
713 self.queued_key_update_message = Some(
714 self.record_layer
715 .encrypt_outgoing(message.borrow_outbound())
716 .encode(),
717 );
718 }
719
720 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
721 self.temper_counters
722 .received_tls13_change_cipher_spec()
723 }
724}
725
726#[cfg(feature = "std")]
727impl CommonState {
728 pub(crate) fn buffer_plaintext(
734 &mut self,
735 payload: OutboundChunks<'_>,
736 sendable_plaintext: &mut ChunkVecBuffer,
737 ) -> usize {
738 self.perhaps_write_key_update();
739 self.send_plain(payload, Limit::Yes, sendable_plaintext)
740 }
741
742 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
743 debug_assert!(self.early_traffic);
744 debug_assert!(self.record_layer.is_encrypting());
745
746 if data.is_empty() {
747 return 0;
749 }
750
751 self.send_appdata_encrypt(data.into(), Limit::Yes)
752 }
753
754 fn send_plain(
760 &mut self,
761 payload: OutboundChunks<'_>,
762 limit: Limit,
763 sendable_plaintext: &mut ChunkVecBuffer,
764 ) -> usize {
765 if !self.may_send_application_data {
766 let len = match limit {
769 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
770 Limit::No => sendable_plaintext.append(payload.to_vec()),
771 };
772 return len;
773 }
774
775 self.send_plain_non_buffering(payload, limit)
776 }
777}
778
779#[derive(Debug, PartialEq, Clone, Copy)]
781pub enum HandshakeKind {
782 Full,
787
788 FullWithHelloRetryRequest,
794
795 Resumed,
801}
802
803#[derive(Debug, Eq, PartialEq)]
808pub struct IoState {
809 tls_bytes_to_write: usize,
810 plaintext_bytes_to_read: usize,
811 peer_has_closed: bool,
812}
813
814impl IoState {
815 pub fn tls_bytes_to_write(&self) -> usize {
820 self.tls_bytes_to_write
821 }
822
823 pub fn plaintext_bytes_to_read(&self) -> usize {
826 self.plaintext_bytes_to_read
827 }
828
829 pub fn peer_has_closed(&self) -> bool {
838 self.peer_has_closed
839 }
840}
841
842pub(crate) trait State<Data>: Send + Sync {
843 fn handle<'m>(
844 self: Box<Self>,
845 cx: &mut Context<'_, Data>,
846 message: Message<'m>,
847 ) -> Result<Box<dyn State<Data> + 'm>, Error>
848 where
849 Self: 'm;
850
851 fn export_keying_material(
852 &self,
853 _output: &mut [u8],
854 _label: &[u8],
855 _context: Option<&[u8]>,
856 ) -> Result<(), Error> {
857 Err(Error::HandshakeNotComplete)
858 }
859
860 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
861 Err(Error::HandshakeNotComplete)
862 }
863
864 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
865 Err(Error::HandshakeNotComplete)
866 }
867
868 fn handle_decrypt_error(&self) {}
869
870 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
871}
872
873pub(crate) struct Context<'a, Data> {
874 pub(crate) common: &'a mut CommonState,
875 pub(crate) data: &'a mut Data,
876 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
879}
880
881#[derive(Clone, Copy, Debug, PartialEq)]
883pub enum Side {
884 Client,
886 Server,
888}
889
890impl Side {
891 pub(crate) fn peer(&self) -> Self {
892 match self {
893 Self::Client => Self::Server,
894 Self::Server => Self::Client,
895 }
896 }
897}
898
899#[derive(Copy, Clone, Eq, PartialEq, Debug)]
900pub(crate) enum Protocol {
901 Tcp,
902 Quic,
903}
904
905enum Limit {
906 #[cfg(feature = "std")]
907 Yes,
908 No,
909}
910
911struct TemperCounters {
914 allowed_warning_alerts: u8,
915 allowed_renegotiation_requests: u8,
916 allowed_key_update_requests: u8,
917 allowed_middlebox_ccs: u8,
918}
919
920impl TemperCounters {
921 fn received_warning_alert(&mut self) -> Result<(), Error> {
922 match self.allowed_warning_alerts {
923 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
924 _ => {
925 self.allowed_warning_alerts -= 1;
926 Ok(())
927 }
928 }
929 }
930
931 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
932 match self.allowed_renegotiation_requests {
933 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
934 _ => {
935 self.allowed_renegotiation_requests -= 1;
936 Ok(())
937 }
938 }
939 }
940
941 fn received_key_update_request(&mut self) -> Result<(), Error> {
942 match self.allowed_key_update_requests {
943 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
944 _ => {
945 self.allowed_key_update_requests -= 1;
946 Ok(())
947 }
948 }
949 }
950
951 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
952 match self.allowed_middlebox_ccs {
953 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
954 _ => {
955 self.allowed_middlebox_ccs -= 1;
956 Ok(())
957 }
958 }
959 }
960}
961
962impl Default for TemperCounters {
963 fn default() -> Self {
964 Self {
965 allowed_warning_alerts: 4,
968
969 allowed_renegotiation_requests: 1,
972
973 allowed_key_update_requests: 32,
976
977 allowed_middlebox_ccs: 2,
982 }
983 }
984}
985
986#[derive(Debug, Default)]
987pub(crate) enum KxState {
988 #[default]
989 None,
990 Start(&'static dyn SupportedKxGroup),
991 Complete(&'static dyn SupportedKxGroup),
992}
993
994impl KxState {
995 pub(crate) fn complete(&mut self) {
996 debug_assert!(matches!(self, Self::Start(_)));
997 if let Self::Start(group) = self {
998 *self = Self::Complete(*group);
999 }
1000 }
1001}
1002
1003pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
1004 pub(crate) transcript: &'a mut HandshakeHash,
1005 body: Vec<u8>,
1006}
1007
1008impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
1009 pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
1010 Self {
1011 transcript,
1012 body: Vec::new(),
1013 }
1014 }
1015
1016 pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1017 let start_len = self.body.len();
1018 hs.encode(&mut self.body);
1019 self.transcript
1020 .add(&self.body[start_len..]);
1021 }
1022
1023 pub(crate) fn finish(self, common: &mut CommonState) {
1024 common.send_msg(
1025 Message {
1026 version: match TLS13 {
1027 true => ProtocolVersion::TLSv1_3,
1028 false => ProtocolVersion::TLSv1_2,
1029 },
1030 payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1031 },
1032 TLS13,
1033 );
1034 }
1035}
1036
1037#[cfg(feature = "tls12")]
1038pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1039pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1040
1041const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1042pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;