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