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) chosen_psk_identity: Option<Vec<u8>>,
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<Vec<u8>>,
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(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}
64
65impl CommonState {
66 pub(crate) fn new(side: Side) -> Self {
67 Self {
68 negotiated_version: None,
69 chosen_psk_identity: 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 aligned_handshake: true,
77 may_send_application_data: false,
78 may_receive_application_data: false,
79 early_traffic: false,
80 sent_fatal_alert: false,
81 has_sent_close_notify: false,
82 has_received_close_notify: false,
83 #[cfg(feature = "std")]
84 has_seen_eof: false,
85 peer_certificates: None,
86 message_fragmenter: MessageFragmenter::default(),
87 received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
88 sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
89 queued_key_update_message: None,
90 protocol: Protocol::Tcp,
91 quic: quic::Quic::default(),
92 enable_secret_extraction: false,
93 temper_counters: TemperCounters::default(),
94 refresh_traffic_keys_pending: false,
95 fips: false,
96 }
97 }
98
99 pub fn wants_write(&self) -> bool {
103 !self.sendable_tls.is_empty()
104 }
105
106 pub fn is_handshaking(&self) -> bool {
114 !(self.may_send_application_data && self.may_receive_application_data)
115 }
116
117 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
139 self.peer_certificates.as_deref()
140 }
141
142 pub fn alpn_protocol(&self) -> Option<&[u8]> {
148 self.get_alpn_protocol()
149 }
150
151 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
155 self.suite
156 }
157
158 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
168 match self.kx_state {
169 KxState::Complete(group) => Some(group),
170 _ => None,
171 }
172 }
173
174 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
178 self.negotiated_version
179 }
180
181 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
188 self.handshake_kind
189 }
190
191 pub fn chosen_psk_identity(&self) -> Option<&[u8]> {
197 self.chosen_psk_identity.as_deref()
198 }
199
200 pub(crate) fn is_tls13(&self) -> bool {
201 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
202 }
203
204 pub(crate) fn process_main_protocol<Data>(
205 &mut self,
206 msg: Message<'_>,
207 mut state: Box<dyn State<Data>>,
208 data: &mut Data,
209 sendable_plaintext: Option<&mut ChunkVecBuffer>,
210 ) -> Result<Box<dyn State<Data>>, Error> {
211 if self.may_receive_application_data && !self.is_tls13() {
214 let reject_ty = match self.side {
215 Side::Client => HandshakeType::HelloRequest,
216 Side::Server => HandshakeType::ClientHello,
217 };
218 if msg.is_handshake_type(reject_ty) {
219 self.temper_counters
220 .received_renegotiation_request()?;
221 self.send_warning_alert(AlertDescription::NoRenegotiation);
222 return Ok(state);
223 }
224 }
225
226 let mut cx = Context {
227 common: self,
228 data,
229 sendable_plaintext,
230 };
231 match state.handle(&mut cx, msg) {
232 Ok(next) => {
233 state = next.into_owned();
234 Ok(state)
235 }
236 Err(e @ Error::InappropriateMessage { .. })
237 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
238 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
239 }
240 Err(e) => Err(e),
241 }
242 }
243
244 pub(crate) fn write_plaintext(
245 &mut self,
246 payload: OutboundChunks<'_>,
247 outgoing_tls: &mut [u8],
248 ) -> Result<usize, EncryptError> {
249 if payload.is_empty() {
250 return Ok(0);
251 }
252
253 let fragments = self
254 .message_fragmenter
255 .fragment_payload(
256 ContentType::ApplicationData,
257 ProtocolVersion::TLSv1_2,
258 payload.clone(),
259 );
260
261 for f in 0..fragments.len() {
262 match self
263 .record_layer
264 .pre_encrypt_action(f as u64)
265 {
266 PreEncryptAction::Nothing => {}
267 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
268 Some(ProtocolVersion::TLSv1_3) => {
269 self.refresh_traffic_keys_pending = true;
271 }
272 _ => {
273 error!(
274 "traffic keys exhausted, closing connection to prevent security failure"
275 );
276 self.send_close_notify();
277 return Err(EncryptError::EncryptExhausted);
278 }
279 },
280 PreEncryptAction::Refuse => {
281 return Err(EncryptError::EncryptExhausted);
282 }
283 }
284 }
285
286 self.perhaps_write_key_update();
287
288 self.check_required_size(outgoing_tls, fragments)?;
289
290 let fragments = self
291 .message_fragmenter
292 .fragment_payload(
293 ContentType::ApplicationData,
294 ProtocolVersion::TLSv1_2,
295 payload,
296 );
297
298 Ok(self.write_fragments(outgoing_tls, fragments))
299 }
300
301 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
306 if !self.aligned_handshake {
307 Err(self.send_fatal_alert(
308 AlertDescription::UnexpectedMessage,
309 PeerMisbehaved::KeyEpochWithPendingFragment,
310 ))
311 } else {
312 Ok(())
313 }
314 }
315
316 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
319 let iter = self
320 .message_fragmenter
321 .fragment_message(&m);
322 for m in iter {
323 self.send_single_fragment(m);
324 }
325 }
326
327 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
329 let len = match limit {
334 #[cfg(feature = "std")]
335 Limit::Yes => self
336 .sendable_tls
337 .apply_limit(payload.len()),
338 Limit::No => payload.len(),
339 };
340
341 let iter = self
342 .message_fragmenter
343 .fragment_payload(
344 ContentType::ApplicationData,
345 ProtocolVersion::TLSv1_2,
346 payload.split_at(len).0,
347 );
348 for m in iter {
349 self.send_single_fragment(m);
350 }
351
352 len
353 }
354
355 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
356 if m.typ == ContentType::Alert {
357 let em = self.record_layer.encrypt_outgoing(m);
359 self.queue_tls_message(em);
360 return;
361 }
362
363 match self
364 .record_layer
365 .next_pre_encrypt_action()
366 {
367 PreEncryptAction::Nothing => {}
368
369 PreEncryptAction::RefreshOrClose => {
372 match self.negotiated_version {
373 Some(ProtocolVersion::TLSv1_3) => {
374 self.refresh_traffic_keys_pending = true;
376 }
377 _ => {
378 error!(
379 "traffic keys exhausted, closing connection to prevent security failure"
380 );
381 self.send_close_notify();
382 return;
383 }
384 }
385 }
386
387 PreEncryptAction::Refuse => {
390 return;
391 }
392 };
393
394 let em = self.record_layer.encrypt_outgoing(m);
395 self.queue_tls_message(em);
396 }
397
398 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
399 debug_assert!(self.may_send_application_data);
400 debug_assert!(self.record_layer.is_encrypting());
401
402 if payload.is_empty() {
403 return 0;
405 }
406
407 self.send_appdata_encrypt(payload, limit)
408 }
409
410 pub(crate) fn start_outgoing_traffic(
414 &mut self,
415 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
416 ) {
417 self.may_send_application_data = true;
418 if let Some(sendable_plaintext) = sendable_plaintext {
419 self.flush_plaintext(sendable_plaintext);
420 }
421 }
422
423 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
427 self.may_receive_application_data = true;
428 self.start_outgoing_traffic(sendable_plaintext);
429 }
430
431 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
434 if !self.may_send_application_data {
435 return;
436 }
437
438 while let Some(buf) = sendable_plaintext.pop() {
439 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
440 }
441 }
442
443 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
445 self.perhaps_write_key_update();
446 self.sendable_tls.append(m.encode());
447 }
448
449 pub(crate) fn perhaps_write_key_update(&mut self) {
450 if let Some(message) = self.queued_key_update_message.take() {
451 self.sendable_tls.append(message);
452 }
453 }
454
455 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
457 {
458 if let Protocol::Quic = self.protocol {
459 if let MessagePayload::Alert(alert) = m.payload {
460 self.quic.alert = Some(alert.description);
461 } else {
462 debug_assert!(
463 matches!(
464 m.payload,
465 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
466 ),
467 "QUIC uses TLS for the cryptographic handshake only"
468 );
469 let mut bytes = Vec::new();
470 m.payload.encode(&mut bytes);
471 self.quic
472 .hs_queue
473 .push_back((must_encrypt, bytes));
474 }
475 return;
476 }
477 }
478 if !must_encrypt {
479 let msg = &m.into();
480 let iter = self
481 .message_fragmenter
482 .fragment_message(msg);
483 for m in iter {
484 self.queue_tls_message(m.to_unencrypted_opaque());
485 }
486 } else {
487 self.send_msg_encrypt(m.into());
488 }
489 }
490
491 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
492 self.received_plaintext
493 .append(bytes.into_vec());
494 }
495
496 #[cfg(feature = "tls12")]
497 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
498 let (dec, enc) = secrets.make_cipher_pair(side);
499 self.record_layer
500 .prepare_message_encrypter(
501 enc,
502 secrets
503 .suite()
504 .common
505 .confidentiality_limit,
506 );
507 self.record_layer
508 .prepare_message_decrypter(dec);
509 }
510
511 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
512 self.send_fatal_alert(AlertDescription::MissingExtension, why)
513 }
514
515 fn send_warning_alert(&mut self, desc: AlertDescription) {
516 warn!("Sending warning alert {:?}", desc);
517 self.send_warning_alert_no_log(desc);
518 }
519
520 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
521 if let AlertLevel::Unknown(_) = alert.level {
523 return Err(self.send_fatal_alert(
524 AlertDescription::IllegalParameter,
525 Error::AlertReceived(alert.description),
526 ));
527 }
528
529 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
532 self.has_received_close_notify = true;
533 return Ok(());
534 }
535
536 let err = Error::AlertReceived(alert.description);
539 if alert.level == AlertLevel::Warning {
540 self.temper_counters
541 .received_warning_alert()?;
542 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
543 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
544 }
545
546 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
549 warn!("TLS alert warning received: {alert:?}");
550 }
551
552 return Ok(());
553 }
554
555 Err(err)
556 }
557
558 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
559 self.send_fatal_alert(
560 match &err {
561 Error::InvalidCertificate(e) => e.clone().into(),
562 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
563 _ => AlertDescription::HandshakeFailure,
564 },
565 err,
566 )
567 }
568
569 pub(crate) fn send_fatal_alert(
570 &mut self,
571 desc: AlertDescription,
572 err: impl Into<Error>,
573 ) -> Error {
574 debug_assert!(!self.sent_fatal_alert);
575 let m = Message::build_alert(AlertLevel::Fatal, desc);
576 self.send_msg(m, self.record_layer.is_encrypting());
577 self.sent_fatal_alert = true;
578 err.into()
579 }
580
581 pub fn send_close_notify(&mut self) {
589 if self.sent_fatal_alert {
590 return;
591 }
592 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
593 self.sent_fatal_alert = true;
594 self.has_sent_close_notify = true;
595 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
596 }
597
598 pub(crate) fn eager_send_close_notify(
599 &mut self,
600 outgoing_tls: &mut [u8],
601 ) -> Result<usize, EncryptError> {
602 self.send_close_notify();
603 self.check_required_size(outgoing_tls, [].into_iter())?;
604 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
605 }
606
607 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
608 let m = Message::build_alert(AlertLevel::Warning, desc);
609 self.send_msg(m, self.record_layer.is_encrypting());
610 }
611
612 fn check_required_size<'a>(
613 &self,
614 outgoing_tls: &mut [u8],
615 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
616 ) -> Result<(), EncryptError> {
617 let mut required_size = self.sendable_tls.len();
618
619 for m in fragments {
620 required_size += m.encoded_len(&self.record_layer);
621 }
622
623 if required_size > outgoing_tls.len() {
624 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
625 required_size,
626 }));
627 }
628
629 Ok(())
630 }
631
632 fn write_fragments<'a>(
633 &mut self,
634 outgoing_tls: &mut [u8],
635 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
636 ) -> usize {
637 let mut written = 0;
638
639 while let Some(message) = self.sendable_tls.pop() {
642 let len = message.len();
643 outgoing_tls[written..written + len].copy_from_slice(&message);
644 written += len;
645 }
646
647 for m in fragments {
648 let em = self
649 .record_layer
650 .encrypt_outgoing(m)
651 .encode();
652
653 let len = em.len();
654 outgoing_tls[written..written + len].copy_from_slice(&em);
655 written += len;
656 }
657
658 written
659 }
660
661 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
662 self.message_fragmenter
663 .set_max_fragment_size(new)
664 }
665
666 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
667 self.alpn_protocol
668 .as_ref()
669 .map(AsRef::as_ref)
670 }
671
672 pub fn wants_read(&self) -> bool {
682 self.received_plaintext.is_empty()
689 && !self.has_received_close_notify
690 && (self.may_send_application_data || self.sendable_tls.is_empty())
691 }
692
693 pub(crate) fn current_io_state(&self) -> IoState {
694 IoState {
695 tls_bytes_to_write: self.sendable_tls.len(),
696 plaintext_bytes_to_read: self.received_plaintext.len(),
697 peer_has_closed: self.has_received_close_notify,
698 }
699 }
700
701 pub(crate) fn is_quic(&self) -> bool {
702 self.protocol == Protocol::Quic
703 }
704
705 pub(crate) fn should_update_key(
706 &mut self,
707 key_update_request: &KeyUpdateRequest,
708 ) -> Result<bool, Error> {
709 self.temper_counters
710 .received_key_update_request()?;
711
712 match key_update_request {
713 KeyUpdateRequest::UpdateNotRequested => Ok(false),
714 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
715 _ => Err(self.send_fatal_alert(
716 AlertDescription::IllegalParameter,
717 InvalidMessage::InvalidKeyUpdate,
718 )),
719 }
720 }
721
722 pub(crate) fn enqueue_key_update_notification(&mut self) {
723 let message = PlainMessage::from(Message::build_key_update_notify());
724 self.queued_key_update_message = Some(
725 self.record_layer
726 .encrypt_outgoing(message.borrow_outbound())
727 .encode(),
728 );
729 }
730
731 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
732 self.temper_counters
733 .received_tls13_change_cipher_spec()
734 }
735}
736
737#[cfg(feature = "std")]
738impl CommonState {
739 pub(crate) fn buffer_plaintext(
745 &mut self,
746 payload: OutboundChunks<'_>,
747 sendable_plaintext: &mut ChunkVecBuffer,
748 ) -> usize {
749 self.perhaps_write_key_update();
750 self.send_plain(payload, Limit::Yes, sendable_plaintext)
751 }
752
753 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
754 debug_assert!(self.early_traffic);
755 debug_assert!(self.record_layer.is_encrypting());
756
757 if data.is_empty() {
758 return 0;
760 }
761
762 self.send_appdata_encrypt(data.into(), Limit::Yes)
763 }
764
765 fn send_plain(
771 &mut self,
772 payload: OutboundChunks<'_>,
773 limit: Limit,
774 sendable_plaintext: &mut ChunkVecBuffer,
775 ) -> usize {
776 if !self.may_send_application_data {
777 let len = match limit {
780 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
781 Limit::No => sendable_plaintext.append(payload.to_vec()),
782 };
783 return len;
784 }
785
786 self.send_plain_non_buffering(payload, limit)
787 }
788}
789
790#[derive(Debug, PartialEq, Clone, Copy)]
792pub enum HandshakeKind {
793 Full,
798
799 FullWithHelloRetryRequest,
805
806 Resumed,
812
813 Psk,
815}
816
817#[derive(Debug, Eq, PartialEq)]
822pub struct IoState {
823 tls_bytes_to_write: usize,
824 plaintext_bytes_to_read: usize,
825 peer_has_closed: bool,
826}
827
828impl IoState {
829 pub fn tls_bytes_to_write(&self) -> usize {
834 self.tls_bytes_to_write
835 }
836
837 pub fn plaintext_bytes_to_read(&self) -> usize {
840 self.plaintext_bytes_to_read
841 }
842
843 pub fn peer_has_closed(&self) -> bool {
852 self.peer_has_closed
853 }
854}
855
856pub(crate) trait State<Data>: Send + Sync {
857 fn handle<'m>(
858 self: Box<Self>,
859 cx: &mut Context<'_, Data>,
860 message: Message<'m>,
861 ) -> Result<Box<dyn State<Data> + 'm>, Error>
862 where
863 Self: 'm;
864
865 fn export_keying_material(
866 &self,
867 _output: &mut [u8],
868 _label: &[u8],
869 _context: Option<&[u8]>,
870 ) -> Result<(), Error> {
871 Err(Error::HandshakeNotComplete)
872 }
873
874 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
875 Err(Error::HandshakeNotComplete)
876 }
877
878 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
879 Err(Error::HandshakeNotComplete)
880 }
881
882 fn handle_decrypt_error(&self) {}
883
884 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
885}
886
887pub(crate) struct Context<'a, Data> {
888 pub(crate) common: &'a mut CommonState,
889 pub(crate) data: &'a mut Data,
890 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
893}
894
895#[derive(Clone, Copy, Debug, PartialEq)]
897pub enum Side {
898 Client,
900 Server,
902}
903
904impl Side {
905 pub(crate) fn peer(&self) -> Self {
906 match self {
907 Self::Client => Self::Server,
908 Self::Server => Self::Client,
909 }
910 }
911}
912
913#[derive(Copy, Clone, Eq, PartialEq, Debug)]
914pub(crate) enum Protocol {
915 Tcp,
916 Quic,
917}
918
919enum Limit {
920 #[cfg(feature = "std")]
921 Yes,
922 No,
923}
924
925struct TemperCounters {
928 allowed_warning_alerts: u8,
929 allowed_renegotiation_requests: u8,
930 allowed_key_update_requests: u8,
931 allowed_middlebox_ccs: u8,
932}
933
934impl TemperCounters {
935 fn received_warning_alert(&mut self) -> Result<(), Error> {
936 match self.allowed_warning_alerts {
937 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
938 _ => {
939 self.allowed_warning_alerts -= 1;
940 Ok(())
941 }
942 }
943 }
944
945 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
946 match self.allowed_renegotiation_requests {
947 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
948 _ => {
949 self.allowed_renegotiation_requests -= 1;
950 Ok(())
951 }
952 }
953 }
954
955 fn received_key_update_request(&mut self) -> Result<(), Error> {
956 match self.allowed_key_update_requests {
957 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
958 _ => {
959 self.allowed_key_update_requests -= 1;
960 Ok(())
961 }
962 }
963 }
964
965 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
966 match self.allowed_middlebox_ccs {
967 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
968 _ => {
969 self.allowed_middlebox_ccs -= 1;
970 Ok(())
971 }
972 }
973 }
974}
975
976impl Default for TemperCounters {
977 fn default() -> Self {
978 Self {
979 allowed_warning_alerts: 4,
982
983 allowed_renegotiation_requests: 1,
986
987 allowed_key_update_requests: 32,
990
991 allowed_middlebox_ccs: 2,
996 }
997 }
998}
999
1000#[derive(Debug, Default)]
1001pub(crate) enum KxState {
1002 #[default]
1003 None,
1004 Start(&'static dyn SupportedKxGroup),
1005 Complete(&'static dyn SupportedKxGroup),
1006}
1007
1008impl KxState {
1009 pub(crate) fn complete(&mut self) {
1010 debug_assert!(matches!(self, Self::Start(_)));
1011 if let Self::Start(group) = self {
1012 *self = Self::Complete(*group);
1013 }
1014 }
1015}
1016
1017pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
1018 pub(crate) transcript: &'a mut HandshakeHash,
1019 body: Vec<u8>,
1020}
1021
1022impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
1023 pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
1024 Self {
1025 transcript,
1026 body: Vec::new(),
1027 }
1028 }
1029
1030 pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1031 let start_len = self.body.len();
1032 hs.encode(&mut self.body);
1033 self.transcript
1034 .add(&self.body[start_len..]);
1035 }
1036
1037 pub(crate) fn finish(self, common: &mut CommonState) {
1038 common.send_msg(
1039 Message {
1040 version: match TLS13 {
1041 true => ProtocolVersion::TLSv1_3,
1042 false => ProtocolVersion::TLSv1_2,
1043 },
1044 payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1045 },
1046 TLS13,
1047 );
1048 }
1049}
1050
1051#[cfg(feature = "tls12")]
1052pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1053pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1054
1055const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1056pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;