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 request_key_update_for(&mut self, payload: OutboundChunks<'_>) {
241 let records = self
242 .message_fragmenter
243 .fragment_payload(
244 ContentType::ApplicationData,
245 ProtocolVersion::TLSv1_2,
246 payload,
247 )
248 .len();
249
250 if records > 0
251 && self.negotiated_version == Some(ProtocolVersion::TLSv1_3)
252 && self.record_layer.write_seq() > 0
253 && self
254 .record_layer
255 .pre_encrypt_action(records as u64)
256 != PreEncryptAction::Nothing
257 {
258 self.refresh_traffic_keys_pending = true;
260 }
261 }
262
263 pub(crate) fn write_plaintext(
264 &mut self,
265 payload: OutboundChunks<'_>,
266 outgoing_tls: &mut [u8],
267 ) -> Result<usize, EncryptError> {
268 if payload.is_empty() {
269 return Ok(0);
270 }
271
272 let fragments = self
273 .message_fragmenter
274 .fragment_payload(
275 ContentType::ApplicationData,
276 ProtocolVersion::TLSv1_2,
277 payload.clone(),
278 );
279
280 for f in 0..fragments.len() {
281 match self
282 .record_layer
283 .pre_encrypt_action(f as u64)
284 {
285 PreEncryptAction::Nothing => {}
286 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
287 Some(ProtocolVersion::TLSv1_3) => {
288 self.refresh_traffic_keys_pending = true;
290 }
291 _ => {
292 error!(
293 "traffic keys exhausted, closing connection to prevent security failure"
294 );
295 self.send_close_notify();
296 return Err(EncryptError::EncryptExhausted);
297 }
298 },
299 PreEncryptAction::Refuse => {
300 return Err(EncryptError::EncryptExhausted);
301 }
302 }
303 }
304
305 self.perhaps_write_key_update();
306
307 self.check_required_size(outgoing_tls, fragments)?;
308
309 let fragments = self
310 .message_fragmenter
311 .fragment_payload(
312 ContentType::ApplicationData,
313 ProtocolVersion::TLSv1_2,
314 payload,
315 );
316
317 Ok(self.write_fragments(outgoing_tls, fragments))
318 }
319
320 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
325 if !self.aligned_handshake {
326 Err(self.send_fatal_alert(
327 AlertDescription::UnexpectedMessage,
328 PeerMisbehaved::KeyEpochWithPendingFragment,
329 ))
330 } else {
331 Ok(())
332 }
333 }
334
335 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
338 let iter = self
339 .message_fragmenter
340 .fragment_message(&m);
341 for m in iter {
342 self.send_single_fragment(m);
343 }
344 }
345
346 fn send_appdata_encrypt(
353 &mut self,
354 payload: OutboundChunks<'_>,
355 limit: Limit,
356 stop_for_key_update: bool,
357 ) -> usize {
358 let len = match limit {
363 #[cfg(feature = "std")]
364 Limit::Yes => self
365 .sendable_tls
366 .apply_limit(payload.len()),
367 Limit::No => payload.len(),
368 };
369
370 let iter = self
371 .message_fragmenter
372 .fragment_payload(
373 ContentType::ApplicationData,
374 ProtocolVersion::TLSv1_2,
375 payload.split_at(len).0,
376 );
377
378 if let Some(last) = (iter.len() as u64).checked_sub(1) {
381 if !self.check_pre_encrypt_action(last) {
382 return len;
383 }
384 }
385
386 let mut sent = 0;
387 for m in iter {
388 if stop_for_key_update
391 && self.negotiated_version == Some(ProtocolVersion::TLSv1_3)
392 && self.record_layer.write_seq() > 0
393 && self.record_layer.pre_encrypt_action(1) != PreEncryptAction::Nothing
394 {
395 self.refresh_traffic_keys_pending = true;
397 return sent;
398 }
399
400 sent += m.payload.len();
401 self.send_single_fragment(m);
402 }
403
404 len
405 }
406
407 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
408 if m.typ == ContentType::Alert {
409 let em = self.record_layer.encrypt_outgoing(m);
411 self.queue_tls_message(em);
412 return;
413 }
414
415 if !self.check_pre_encrypt_action(0) {
416 return;
417 }
418
419 let em = self.record_layer.encrypt_outgoing(m);
420 self.queue_tls_message(em);
421 }
422
423 fn check_pre_encrypt_action(&mut self, add: u64) -> bool {
427 match self
428 .record_layer
429 .pre_encrypt_action(add)
430 {
431 PreEncryptAction::Nothing => true,
432
433 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
436 Some(ProtocolVersion::TLSv1_3) => {
437 self.refresh_traffic_keys_pending = true;
439 true
440 }
441 _ => {
442 error!(
443 "traffic keys exhausted, closing connection to prevent security failure"
444 );
445 self.send_close_notify();
446 false
447 }
448 },
449
450 PreEncryptAction::Refuse => false,
453 }
454 }
455
456 fn send_plain_non_buffering(
457 &mut self,
458 payload: OutboundChunks<'_>,
459 limit: Limit,
460 stop_for_key_update: bool,
461 ) -> usize {
462 debug_assert!(self.may_send_application_data);
463 debug_assert!(self.record_layer.is_encrypting());
464
465 if payload.is_empty() {
466 return 0;
468 }
469
470 self.send_appdata_encrypt(payload, limit, stop_for_key_update)
471 }
472
473 pub(crate) fn start_outgoing_traffic(
477 &mut self,
478 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
479 ) {
480 self.may_send_application_data = true;
481 if let Some(sendable_plaintext) = sendable_plaintext {
482 self.flush_plaintext(sendable_plaintext);
483 }
484 }
485
486 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
490 self.may_receive_application_data = true;
491 self.start_outgoing_traffic(sendable_plaintext);
492 }
493
494 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
497 if !self.may_send_application_data {
498 return;
499 }
500
501 while let Some(buf) = sendable_plaintext.pop() {
502 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No, false);
503 }
504 }
505
506 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
508 self.perhaps_write_key_update();
509 self.sendable_tls.append(m.encode());
510 }
511
512 pub(crate) fn perhaps_write_key_update(&mut self) {
513 if let Some(message) = self.queued_key_update_message.take() {
514 self.sendable_tls.append(message);
515 }
516 }
517
518 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
520 {
521 if let Protocol::Quic = self.protocol {
522 if let MessagePayload::Alert(alert) = m.payload {
523 self.quic.alert = Some(alert.description);
524 } else {
525 debug_assert!(
526 matches!(
527 m.payload,
528 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
529 ),
530 "QUIC uses TLS for the cryptographic handshake only"
531 );
532 let mut bytes = Vec::new();
533 m.payload.encode(&mut bytes);
534 self.quic
535 .hs_queue
536 .push_back((must_encrypt, bytes));
537 }
538 return;
539 }
540 }
541 if !must_encrypt {
542 let msg = &m.into();
543 let iter = self
544 .message_fragmenter
545 .fragment_message(msg);
546 for m in iter {
547 self.queue_tls_message(m.to_unencrypted_opaque());
548 }
549 } else {
550 self.send_msg_encrypt(m.into());
551 }
552 }
553
554 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
555 self.temper_counters.received_app_data();
556 self.received_plaintext
557 .append(bytes.into_vec());
558 }
559
560 #[cfg(feature = "tls12")]
561 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
562 let (dec, enc) = secrets.make_cipher_pair(side);
563 self.record_layer
564 .prepare_message_encrypter(
565 enc,
566 secrets
567 .suite()
568 .common
569 .confidentiality_limit,
570 );
571 self.record_layer
572 .prepare_message_decrypter(dec);
573 }
574
575 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
576 self.send_fatal_alert(AlertDescription::MissingExtension, why)
577 }
578
579 fn send_warning_alert(&mut self, desc: AlertDescription) {
580 warn!("Sending warning alert {desc:?}");
581 self.send_warning_alert_no_log(desc);
582 }
583
584 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
585 if let AlertLevel::Unknown(_) = alert.level {
587 return Err(self.send_fatal_alert(
588 AlertDescription::IllegalParameter,
589 Error::AlertReceived(alert.description),
590 ));
591 }
592
593 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
596 self.has_received_close_notify = true;
597 return Ok(());
598 }
599
600 let err = Error::AlertReceived(alert.description);
603 if alert.level == AlertLevel::Warning {
604 self.temper_counters
605 .received_warning_alert()?;
606 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
607 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
608 }
609
610 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
613 warn!("TLS alert warning received: {alert:?}");
614 }
615
616 return Ok(());
617 }
618
619 Err(err)
620 }
621
622 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
623 self.send_fatal_alert(
624 match &err {
625 Error::InvalidCertificate(e) => e.clone().into(),
626 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
627 _ => AlertDescription::HandshakeFailure,
628 },
629 err,
630 )
631 }
632
633 pub(crate) fn send_fatal_alert(
634 &mut self,
635 desc: AlertDescription,
636 err: impl Into<Error>,
637 ) -> Error {
638 debug_assert!(!self.sent_fatal_alert);
639 let m = Message::build_alert(AlertLevel::Fatal, desc);
640 self.send_msg(m, self.record_layer.is_encrypting());
641 self.sent_fatal_alert = true;
642 err.into()
643 }
644
645 pub fn send_close_notify(&mut self) {
653 if self.sent_fatal_alert {
654 return;
655 }
656 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
657 self.sent_fatal_alert = true;
658 self.has_sent_close_notify = true;
659 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
660 }
661
662 pub(crate) fn eager_send_close_notify(
663 &mut self,
664 outgoing_tls: &mut [u8],
665 ) -> Result<usize, EncryptError> {
666 self.send_close_notify();
667 self.check_required_size(outgoing_tls, [].into_iter())?;
668 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
669 }
670
671 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
672 let m = Message::build_alert(AlertLevel::Warning, desc);
673 self.send_msg(m, self.record_layer.is_encrypting());
674 }
675
676 fn check_required_size<'a>(
677 &self,
678 outgoing_tls: &mut [u8],
679 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
680 ) -> Result<(), EncryptError> {
681 let mut required_size = self.sendable_tls.len();
682
683 for m in fragments {
684 required_size += m.encoded_len(&self.record_layer);
685 }
686
687 if required_size > outgoing_tls.len() {
688 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
689 required_size,
690 }));
691 }
692
693 Ok(())
694 }
695
696 fn write_fragments<'a>(
697 &mut self,
698 outgoing_tls: &mut [u8],
699 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
700 ) -> usize {
701 let mut written = 0;
702
703 while let Some(message) = self.sendable_tls.pop() {
706 let len = message.len();
707 outgoing_tls[written..written + len].copy_from_slice(&message);
708 written += len;
709 }
710
711 for m in fragments {
712 let em = self
713 .record_layer
714 .encrypt_outgoing(m)
715 .encode();
716
717 let len = em.len();
718 outgoing_tls[written..written + len].copy_from_slice(&em);
719 written += len;
720 }
721
722 written
723 }
724
725 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
726 self.message_fragmenter
727 .set_max_fragment_size(new)
728 }
729
730 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
731 self.alpn_protocol
732 .as_ref()
733 .map(AsRef::as_ref)
734 }
735
736 pub fn wants_read(&self) -> bool {
746 self.received_plaintext.is_empty()
753 && !self.has_received_close_notify
754 && (self.may_send_application_data || self.sendable_tls.is_empty())
755 }
756
757 pub(crate) fn current_io_state(&self) -> IoState {
758 IoState {
759 tls_bytes_to_write: self.sendable_tls.len(),
760 plaintext_bytes_to_read: self.received_plaintext.len(),
761 peer_has_closed: self.has_received_close_notify,
762 }
763 }
764
765 pub(crate) fn is_quic(&self) -> bool {
766 self.protocol == Protocol::Quic
767 }
768
769 pub(crate) fn should_update_key(
770 &mut self,
771 key_update_request: &KeyUpdateRequest,
772 ) -> Result<bool, Error> {
773 self.temper_counters
774 .received_key_update_request()?;
775
776 match key_update_request {
777 KeyUpdateRequest::UpdateNotRequested => Ok(false),
778 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
779 _ => Err(self.send_fatal_alert(
780 AlertDescription::IllegalParameter,
781 InvalidMessage::InvalidKeyUpdate,
782 )),
783 }
784 }
785
786 pub(crate) fn enqueue_key_update_notification(&mut self) {
787 let message = PlainMessage::from(Message::build_key_update_notify());
788 self.queued_key_update_message = Some(
789 self.record_layer
790 .encrypt_outgoing(message.borrow_outbound())
791 .encode(),
792 );
793 }
794
795 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
796 self.temper_counters
797 .received_tls13_change_cipher_spec()
798 }
799}
800
801#[cfg(feature = "std")]
802impl CommonState {
803 pub(crate) fn buffer_plaintext(
809 &mut self,
810 payload: OutboundChunks<'_>,
811 sendable_plaintext: &mut ChunkVecBuffer,
812 ) -> usize {
813 self.perhaps_write_key_update();
814 self.send_plain(payload, Limit::Yes, sendable_plaintext)
815 }
816
817 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
818 debug_assert!(self.early_traffic);
819 debug_assert!(self.record_layer.is_encrypting());
820
821 if data.is_empty() {
822 return 0;
824 }
825
826 self.send_appdata_encrypt(data.into(), Limit::Yes, false)
827 }
828
829 fn send_plain(
835 &mut self,
836 payload: OutboundChunks<'_>,
837 limit: Limit,
838 sendable_plaintext: &mut ChunkVecBuffer,
839 ) -> usize {
840 if !self.may_send_application_data {
841 let len = match limit {
844 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
845 Limit::No => sendable_plaintext.append(payload.to_vec()),
846 };
847 return len;
848 }
849
850 self.send_plain_non_buffering(payload, limit, true)
851 }
852}
853
854#[derive(Debug, PartialEq, Clone, Copy)]
856pub enum HandshakeKind {
857 Full,
862
863 FullWithHelloRetryRequest,
869
870 Resumed,
876}
877
878#[derive(Debug, Eq, PartialEq)]
883pub struct IoState {
884 tls_bytes_to_write: usize,
885 plaintext_bytes_to_read: usize,
886 peer_has_closed: bool,
887}
888
889impl IoState {
890 pub fn tls_bytes_to_write(&self) -> usize {
895 self.tls_bytes_to_write
896 }
897
898 pub fn plaintext_bytes_to_read(&self) -> usize {
901 self.plaintext_bytes_to_read
902 }
903
904 pub fn peer_has_closed(&self) -> bool {
913 self.peer_has_closed
914 }
915}
916
917pub(crate) trait State<Data>: Send + Sync {
918 fn handle<'m>(
919 self: Box<Self>,
920 cx: &mut Context<'_, Data>,
921 message: Message<'m>,
922 ) -> Result<Box<dyn State<Data> + 'm>, Error>
923 where
924 Self: 'm;
925
926 fn export_keying_material(
927 &self,
928 _output: &mut [u8],
929 _label: &[u8],
930 _context: Option<&[u8]>,
931 ) -> Result<(), Error> {
932 Err(Error::HandshakeNotComplete)
933 }
934
935 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
936 Err(Error::HandshakeNotComplete)
937 }
938
939 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
940 Err(Error::HandshakeNotComplete)
941 }
942
943 fn handle_decrypt_error(&self) {}
944
945 fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
946 Err(Error::HandshakeNotComplete)
947 }
948
949 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
950}
951
952pub(crate) struct Context<'a, Data> {
953 pub(crate) common: &'a mut CommonState,
954 pub(crate) data: &'a mut Data,
955 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
958}
959
960#[derive(Clone, Copy, Debug, PartialEq)]
962pub enum Side {
963 Client,
965 Server,
967}
968
969impl Side {
970 pub(crate) fn peer(&self) -> Self {
971 match self {
972 Self::Client => Self::Server,
973 Self::Server => Self::Client,
974 }
975 }
976}
977
978#[derive(Copy, Clone, Eq, PartialEq, Debug)]
979pub(crate) enum Protocol {
980 Tcp,
981 Quic,
982}
983
984impl Protocol {
985 pub(crate) fn supports_version(&self, version: ProtocolVersion) -> bool {
986 match self {
987 Self::Quic => version == ProtocolVersion::TLSv1_3,
988 Self::Tcp => true,
989 }
990 }
991}
992
993enum Limit {
994 #[cfg(feature = "std")]
995 Yes,
996 No,
997}
998
999struct TemperCounters {
1002 allowed_warning_alerts: u8,
1003 allowed_renegotiation_requests: u8,
1004 allowed_key_update_requests: u8,
1005 allowed_middlebox_ccs: u8,
1006}
1007
1008impl TemperCounters {
1009 fn received_warning_alert(&mut self) -> Result<(), Error> {
1010 match self.allowed_warning_alerts {
1011 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
1012 _ => {
1013 self.allowed_warning_alerts -= 1;
1014 Ok(())
1015 }
1016 }
1017 }
1018
1019 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
1020 match self.allowed_renegotiation_requests {
1021 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
1022 _ => {
1023 self.allowed_renegotiation_requests -= 1;
1024 Ok(())
1025 }
1026 }
1027 }
1028
1029 fn received_key_update_request(&mut self) -> Result<(), Error> {
1030 match self.allowed_key_update_requests {
1031 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
1032 _ => {
1033 self.allowed_key_update_requests -= 1;
1034 Ok(())
1035 }
1036 }
1037 }
1038
1039 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
1040 match self.allowed_middlebox_ccs {
1041 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
1042 _ => {
1043 self.allowed_middlebox_ccs -= 1;
1044 Ok(())
1045 }
1046 }
1047 }
1048
1049 fn received_app_data(&mut self) {
1050 self.allowed_key_update_requests = Self::INITIAL_KEY_UPDATE_REQUESTS;
1051 }
1052
1053 const INITIAL_KEY_UPDATE_REQUESTS: u8 = 32;
1056}
1057
1058impl Default for TemperCounters {
1059 fn default() -> Self {
1060 Self {
1061 allowed_warning_alerts: 4,
1064
1065 allowed_renegotiation_requests: 1,
1068
1069 allowed_key_update_requests: Self::INITIAL_KEY_UPDATE_REQUESTS,
1070
1071 allowed_middlebox_ccs: 2,
1076 }
1077 }
1078}
1079
1080#[derive(Debug, Default)]
1081pub(crate) enum KxState {
1082 #[default]
1083 None,
1084 Start(&'static dyn SupportedKxGroup),
1085 Complete(&'static dyn SupportedKxGroup),
1086}
1087
1088impl KxState {
1089 pub(crate) fn complete(&mut self) {
1090 debug_assert!(matches!(self, Self::Start(_)));
1091 if let Self::Start(group) = self {
1092 *self = Self::Complete(*group);
1093 }
1094 }
1095}
1096
1097pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
1098 pub(crate) transcript: &'a mut HandshakeHash,
1099 body: Vec<u8>,
1100}
1101
1102impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
1103 pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
1104 Self {
1105 transcript,
1106 body: Vec::new(),
1107 }
1108 }
1109
1110 pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1111 let start_len = self.body.len();
1112 hs.encode(&mut self.body);
1113 self.transcript
1114 .add(&self.body[start_len..]);
1115 }
1116
1117 pub(crate) fn finish(self, common: &mut CommonState) {
1118 common.send_msg(
1119 Message {
1120 version: match TLS13 {
1121 true => ProtocolVersion::TLSv1_3,
1122 false => ProtocolVersion::TLSv1_2,
1123 },
1124 payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1125 },
1126 TLS13,
1127 );
1128 }
1129}
1130
1131#[cfg(feature = "tls12")]
1132pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1133pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1134
1135const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1136pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;