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