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(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 pub(crate) tls13_tickets_received: u32,
64}
65
66impl CommonState {
67 pub(crate) fn new(side: Side) -> Self {
68 Self {
69 negotiated_version: 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 tls13_tickets_received: 0,
97 }
98 }
99
100 pub fn wants_write(&self) -> bool {
104 !self.sendable_tls.is_empty()
105 }
106
107 pub fn is_handshaking(&self) -> bool {
115 !(self.may_send_application_data && self.may_receive_application_data)
116 }
117
118 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
140 self.peer_certificates.as_deref()
141 }
142
143 pub fn alpn_protocol(&self) -> Option<&[u8]> {
149 self.get_alpn_protocol()
150 }
151
152 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
156 self.suite
157 }
158
159 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
169 match self.kx_state {
170 KxState::Complete(group) => Some(group),
171 _ => None,
172 }
173 }
174
175 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
179 self.negotiated_version
180 }
181
182 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
189 self.handshake_kind
190 }
191
192 pub(crate) fn is_tls13(&self) -> bool {
193 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
194 }
195
196 pub(crate) fn process_main_protocol<Data>(
197 &mut self,
198 msg: Message<'_>,
199 mut state: Box<dyn State<Data>>,
200 data: &mut Data,
201 sendable_plaintext: Option<&mut ChunkVecBuffer>,
202 ) -> Result<Box<dyn State<Data>>, Error> {
203 if self.may_receive_application_data && !self.is_tls13() {
206 let reject_ty = match self.side {
207 Side::Client => HandshakeType::HelloRequest,
208 Side::Server => HandshakeType::ClientHello,
209 };
210 if msg.is_handshake_type(reject_ty) {
211 self.temper_counters
212 .received_renegotiation_request()?;
213 self.send_warning_alert(AlertDescription::NoRenegotiation);
214 return Ok(state);
215 }
216 }
217
218 let mut cx = Context {
219 common: self,
220 data,
221 sendable_plaintext,
222 };
223 match state.handle(&mut cx, msg) {
224 Ok(next) => {
225 state = next.into_owned();
226 Ok(state)
227 }
228 Err(e @ Error::InappropriateMessage { .. })
229 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
230 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
231 }
232 Err(e) => Err(e),
233 }
234 }
235
236 pub(crate) fn write_plaintext(
237 &mut self,
238 payload: OutboundChunks<'_>,
239 outgoing_tls: &mut [u8],
240 ) -> Result<usize, EncryptError> {
241 if payload.is_empty() {
242 return Ok(0);
243 }
244
245 let fragments = self
246 .message_fragmenter
247 .fragment_payload(
248 ContentType::ApplicationData,
249 ProtocolVersion::TLSv1_2,
250 payload.clone(),
251 );
252
253 for f in 0..fragments.len() {
254 match self
255 .record_layer
256 .pre_encrypt_action(f as u64)
257 {
258 PreEncryptAction::Nothing => {}
259 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
260 Some(ProtocolVersion::TLSv1_3) => {
261 self.refresh_traffic_keys_pending = true;
263 }
264 _ => {
265 error!(
266 "traffic keys exhausted, closing connection to prevent security failure"
267 );
268 self.send_close_notify();
269 return Err(EncryptError::EncryptExhausted);
270 }
271 },
272 PreEncryptAction::Refuse => {
273 return Err(EncryptError::EncryptExhausted);
274 }
275 }
276 }
277
278 self.perhaps_write_key_update();
279
280 self.check_required_size(outgoing_tls, fragments)?;
281
282 let fragments = self
283 .message_fragmenter
284 .fragment_payload(
285 ContentType::ApplicationData,
286 ProtocolVersion::TLSv1_2,
287 payload,
288 );
289
290 Ok(self.write_fragments(outgoing_tls, fragments))
291 }
292
293 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
298 if !self.aligned_handshake {
299 Err(self.send_fatal_alert(
300 AlertDescription::UnexpectedMessage,
301 PeerMisbehaved::KeyEpochWithPendingFragment,
302 ))
303 } else {
304 Ok(())
305 }
306 }
307
308 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
311 let iter = self
312 .message_fragmenter
313 .fragment_message(&m);
314 for m in iter {
315 self.send_single_fragment(m);
316 }
317 }
318
319 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
321 let len = match limit {
326 #[cfg(feature = "std")]
327 Limit::Yes => self
328 .sendable_tls
329 .apply_limit(payload.len()),
330 Limit::No => payload.len(),
331 };
332
333 let iter = self
334 .message_fragmenter
335 .fragment_payload(
336 ContentType::ApplicationData,
337 ProtocolVersion::TLSv1_2,
338 payload.split_at(len).0,
339 );
340 for m in iter {
341 self.send_single_fragment(m);
342 }
343
344 len
345 }
346
347 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
348 if m.typ == ContentType::Alert {
349 let em = self.record_layer.encrypt_outgoing(m);
351 self.queue_tls_message(em);
352 return;
353 }
354
355 match self
356 .record_layer
357 .next_pre_encrypt_action()
358 {
359 PreEncryptAction::Nothing => {}
360
361 PreEncryptAction::RefreshOrClose => {
364 match self.negotiated_version {
365 Some(ProtocolVersion::TLSv1_3) => {
366 self.refresh_traffic_keys_pending = true;
368 }
369 _ => {
370 error!(
371 "traffic keys exhausted, closing connection to prevent security failure"
372 );
373 self.send_close_notify();
374 return;
375 }
376 }
377 }
378
379 PreEncryptAction::Refuse => {
382 return;
383 }
384 };
385
386 let em = self.record_layer.encrypt_outgoing(m);
387 self.queue_tls_message(em);
388 }
389
390 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
391 debug_assert!(self.may_send_application_data);
392 debug_assert!(self.record_layer.is_encrypting());
393
394 if payload.is_empty() {
395 return 0;
397 }
398
399 self.send_appdata_encrypt(payload, limit)
400 }
401
402 pub(crate) fn start_outgoing_traffic(
406 &mut self,
407 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
408 ) {
409 self.may_send_application_data = true;
410 if let Some(sendable_plaintext) = sendable_plaintext {
411 self.flush_plaintext(sendable_plaintext);
412 }
413 }
414
415 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
419 self.may_receive_application_data = true;
420 self.start_outgoing_traffic(sendable_plaintext);
421 }
422
423 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
426 if !self.may_send_application_data {
427 return;
428 }
429
430 while let Some(buf) = sendable_plaintext.pop() {
431 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
432 }
433 }
434
435 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
437 self.perhaps_write_key_update();
438 self.sendable_tls.append(m.encode());
439 }
440
441 pub(crate) fn perhaps_write_key_update(&mut self) {
442 if let Some(message) = self.queued_key_update_message.take() {
443 self.sendable_tls.append(message);
444 }
445 }
446
447 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
449 {
450 if let Protocol::Quic = self.protocol {
451 if let MessagePayload::Alert(alert) = m.payload {
452 self.quic.alert = Some(alert.description);
453 } else {
454 debug_assert!(
455 matches!(
456 m.payload,
457 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
458 ),
459 "QUIC uses TLS for the cryptographic handshake only"
460 );
461 let mut bytes = Vec::new();
462 m.payload.encode(&mut bytes);
463 self.quic
464 .hs_queue
465 .push_back((must_encrypt, bytes));
466 }
467 return;
468 }
469 }
470 if !must_encrypt {
471 let msg = &m.into();
472 let iter = self
473 .message_fragmenter
474 .fragment_message(msg);
475 for m in iter {
476 self.queue_tls_message(m.to_unencrypted_opaque());
477 }
478 } else {
479 self.send_msg_encrypt(m.into());
480 }
481 }
482
483 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
484 self.temper_counters.received_app_data();
485 self.received_plaintext
486 .append(bytes.into_vec());
487 }
488
489 #[cfg(feature = "tls12")]
490 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
491 let (dec, enc) = secrets.make_cipher_pair(side);
492 self.record_layer
493 .prepare_message_encrypter(
494 enc,
495 secrets
496 .suite()
497 .common
498 .confidentiality_limit,
499 );
500 self.record_layer
501 .prepare_message_decrypter(dec);
502 }
503
504 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
505 self.send_fatal_alert(AlertDescription::MissingExtension, why)
506 }
507
508 fn send_warning_alert(&mut self, desc: AlertDescription) {
509 warn!("Sending warning alert {desc:?}");
510 self.send_warning_alert_no_log(desc);
511 }
512
513 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
514 if let AlertLevel::Unknown(_) = alert.level {
516 return Err(self.send_fatal_alert(
517 AlertDescription::IllegalParameter,
518 Error::AlertReceived(alert.description),
519 ));
520 }
521
522 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
525 self.has_received_close_notify = true;
526 return Ok(());
527 }
528
529 let err = Error::AlertReceived(alert.description);
532 if alert.level == AlertLevel::Warning {
533 self.temper_counters
534 .received_warning_alert()?;
535 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
536 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
537 }
538
539 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
542 warn!("TLS alert warning received: {alert:?}");
543 }
544
545 return Ok(());
546 }
547
548 Err(err)
549 }
550
551 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
552 self.send_fatal_alert(
553 match &err {
554 Error::InvalidCertificate(e) => e.clone().into(),
555 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
556 _ => AlertDescription::HandshakeFailure,
557 },
558 err,
559 )
560 }
561
562 pub(crate) fn send_fatal_alert(
563 &mut self,
564 desc: AlertDescription,
565 err: impl Into<Error>,
566 ) -> Error {
567 debug_assert!(!self.sent_fatal_alert);
568 let m = Message::build_alert(AlertLevel::Fatal, desc);
569 self.send_msg(m, self.record_layer.is_encrypting());
570 self.sent_fatal_alert = true;
571 err.into()
572 }
573
574 pub fn send_close_notify(&mut self) {
582 if self.sent_fatal_alert {
583 return;
584 }
585 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
586 self.sent_fatal_alert = true;
587 self.has_sent_close_notify = true;
588 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
589 }
590
591 pub(crate) fn eager_send_close_notify(
592 &mut self,
593 outgoing_tls: &mut [u8],
594 ) -> Result<usize, EncryptError> {
595 self.send_close_notify();
596 self.check_required_size(outgoing_tls, [].into_iter())?;
597 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
598 }
599
600 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
601 let m = Message::build_alert(AlertLevel::Warning, desc);
602 self.send_msg(m, self.record_layer.is_encrypting());
603 }
604
605 fn check_required_size<'a>(
606 &self,
607 outgoing_tls: &mut [u8],
608 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
609 ) -> Result<(), EncryptError> {
610 let mut required_size = self.sendable_tls.len();
611
612 for m in fragments {
613 required_size += m.encoded_len(&self.record_layer);
614 }
615
616 if required_size > outgoing_tls.len() {
617 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
618 required_size,
619 }));
620 }
621
622 Ok(())
623 }
624
625 fn write_fragments<'a>(
626 &mut self,
627 outgoing_tls: &mut [u8],
628 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
629 ) -> usize {
630 let mut written = 0;
631
632 while let Some(message) = self.sendable_tls.pop() {
635 let len = message.len();
636 outgoing_tls[written..written + len].copy_from_slice(&message);
637 written += len;
638 }
639
640 for m in fragments {
641 let em = self
642 .record_layer
643 .encrypt_outgoing(m)
644 .encode();
645
646 let len = em.len();
647 outgoing_tls[written..written + len].copy_from_slice(&em);
648 written += len;
649 }
650
651 written
652 }
653
654 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
655 self.message_fragmenter
656 .set_max_fragment_size(new)
657 }
658
659 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
660 self.alpn_protocol
661 .as_ref()
662 .map(AsRef::as_ref)
663 }
664
665 pub fn wants_read(&self) -> bool {
675 self.received_plaintext.is_empty()
682 && !self.has_received_close_notify
683 && (self.may_send_application_data || self.sendable_tls.is_empty())
684 }
685
686 pub(crate) fn current_io_state(&self) -> IoState {
687 IoState {
688 tls_bytes_to_write: self.sendable_tls.len(),
689 plaintext_bytes_to_read: self.received_plaintext.len(),
690 peer_has_closed: self.has_received_close_notify,
691 }
692 }
693
694 pub(crate) fn is_quic(&self) -> bool {
695 self.protocol == Protocol::Quic
696 }
697
698 pub(crate) fn should_update_key(
699 &mut self,
700 key_update_request: &KeyUpdateRequest,
701 ) -> Result<bool, Error> {
702 self.temper_counters
703 .received_key_update_request()?;
704
705 match key_update_request {
706 KeyUpdateRequest::UpdateNotRequested => Ok(false),
707 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
708 _ => Err(self.send_fatal_alert(
709 AlertDescription::IllegalParameter,
710 InvalidMessage::InvalidKeyUpdate,
711 )),
712 }
713 }
714
715 pub(crate) fn enqueue_key_update_notification(&mut self) {
716 let message = PlainMessage::from(Message::build_key_update_notify());
717 self.queued_key_update_message = Some(
718 self.record_layer
719 .encrypt_outgoing(message.borrow_outbound())
720 .encode(),
721 );
722 }
723
724 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
725 self.temper_counters
726 .received_tls13_change_cipher_spec()
727 }
728}
729
730#[cfg(feature = "std")]
731impl CommonState {
732 pub(crate) fn buffer_plaintext(
738 &mut self,
739 payload: OutboundChunks<'_>,
740 sendable_plaintext: &mut ChunkVecBuffer,
741 ) -> usize {
742 self.perhaps_write_key_update();
743 self.send_plain(payload, Limit::Yes, sendable_plaintext)
744 }
745
746 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
747 debug_assert!(self.early_traffic);
748 debug_assert!(self.record_layer.is_encrypting());
749
750 if data.is_empty() {
751 return 0;
753 }
754
755 self.send_appdata_encrypt(data.into(), Limit::Yes)
756 }
757
758 fn send_plain(
764 &mut self,
765 payload: OutboundChunks<'_>,
766 limit: Limit,
767 sendable_plaintext: &mut ChunkVecBuffer,
768 ) -> usize {
769 if !self.may_send_application_data {
770 let len = match limit {
773 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
774 Limit::No => sendable_plaintext.append(payload.to_vec()),
775 };
776 return len;
777 }
778
779 self.send_plain_non_buffering(payload, limit)
780 }
781}
782
783#[derive(Debug, PartialEq, Clone, Copy)]
785pub enum HandshakeKind {
786 Full,
791
792 FullWithHelloRetryRequest,
798
799 Resumed,
805}
806
807#[derive(Debug, Eq, PartialEq)]
812pub struct IoState {
813 tls_bytes_to_write: usize,
814 plaintext_bytes_to_read: usize,
815 peer_has_closed: bool,
816}
817
818impl IoState {
819 pub fn tls_bytes_to_write(&self) -> usize {
824 self.tls_bytes_to_write
825 }
826
827 pub fn plaintext_bytes_to_read(&self) -> usize {
830 self.plaintext_bytes_to_read
831 }
832
833 pub fn peer_has_closed(&self) -> bool {
842 self.peer_has_closed
843 }
844}
845
846pub(crate) trait State<Data>: Send + Sync {
847 fn handle<'m>(
848 self: Box<Self>,
849 cx: &mut Context<'_, Data>,
850 message: Message<'m>,
851 ) -> Result<Box<dyn State<Data> + 'm>, Error>
852 where
853 Self: 'm;
854
855 fn export_keying_material(
856 &self,
857 _output: &mut [u8],
858 _label: &[u8],
859 _context: Option<&[u8]>,
860 ) -> Result<(), Error> {
861 Err(Error::HandshakeNotComplete)
862 }
863
864 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
865 Err(Error::HandshakeNotComplete)
866 }
867
868 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
869 Err(Error::HandshakeNotComplete)
870 }
871
872 fn handle_decrypt_error(&self) {}
873
874 fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
875 Err(Error::HandshakeNotComplete)
876 }
877
878 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
879}
880
881pub(crate) struct Context<'a, Data> {
882 pub(crate) common: &'a mut CommonState,
883 pub(crate) data: &'a mut Data,
884 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
887}
888
889#[derive(Clone, Copy, Debug, PartialEq)]
891pub enum Side {
892 Client,
894 Server,
896}
897
898impl Side {
899 pub(crate) fn peer(&self) -> Self {
900 match self {
901 Self::Client => Self::Server,
902 Self::Server => Self::Client,
903 }
904 }
905}
906
907#[derive(Copy, Clone, Eq, PartialEq, Debug)]
908pub(crate) enum Protocol {
909 Tcp,
910 Quic,
911}
912
913enum Limit {
914 #[cfg(feature = "std")]
915 Yes,
916 No,
917}
918
919struct TemperCounters {
922 allowed_warning_alerts: u8,
923 allowed_renegotiation_requests: u8,
924 allowed_key_update_requests: u8,
925 allowed_middlebox_ccs: u8,
926}
927
928impl TemperCounters {
929 fn received_warning_alert(&mut self) -> Result<(), Error> {
930 match self.allowed_warning_alerts {
931 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
932 _ => {
933 self.allowed_warning_alerts -= 1;
934 Ok(())
935 }
936 }
937 }
938
939 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
940 match self.allowed_renegotiation_requests {
941 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
942 _ => {
943 self.allowed_renegotiation_requests -= 1;
944 Ok(())
945 }
946 }
947 }
948
949 fn received_key_update_request(&mut self) -> Result<(), Error> {
950 match self.allowed_key_update_requests {
951 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
952 _ => {
953 self.allowed_key_update_requests -= 1;
954 Ok(())
955 }
956 }
957 }
958
959 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
960 match self.allowed_middlebox_ccs {
961 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
962 _ => {
963 self.allowed_middlebox_ccs -= 1;
964 Ok(())
965 }
966 }
967 }
968
969 fn received_app_data(&mut self) {
970 self.allowed_key_update_requests = Self::INITIAL_KEY_UPDATE_REQUESTS;
971 }
972
973 const INITIAL_KEY_UPDATE_REQUESTS: u8 = 32;
976}
977
978impl Default for TemperCounters {
979 fn default() -> Self {
980 Self {
981 allowed_warning_alerts: 4,
984
985 allowed_renegotiation_requests: 1,
988
989 allowed_key_update_requests: Self::INITIAL_KEY_UPDATE_REQUESTS,
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;