rustls/
common_state.rs

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::log::{debug, error, warn};
10use crate::msgs::alert::AlertMessagePayload;
11use crate::msgs::base::Payload;
12use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
13use crate::msgs::fragmenter::MessageFragmenter;
14use crate::msgs::handshake::CertificateChain;
15use crate::msgs::message::{
16    Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
17    PlainMessage,
18};
19use crate::record_layer::PreEncryptAction;
20use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
21#[cfg(feature = "tls12")]
22use crate::tls12::ConnectionSecrets;
23use crate::unbuffered::{EncryptError, InsufficientSizeError};
24use crate::vecbuf::ChunkVecBuffer;
25use crate::{quic, record_layer};
26
27/// Connection state common to both client and server connections.
28pub struct CommonState {
29    pub(crate) negotiated_version: Option<ProtocolVersion>,
30    pub(crate) handshake_kind: Option<HandshakeKind>,
31    pub(crate) side: Side,
32    pub(crate) record_layer: record_layer::RecordLayer,
33    pub(crate) suite: Option<SupportedCipherSuite>,
34    pub(crate) kx_state: KxState,
35    pub(crate) alpn_protocol: Option<Vec<u8>>,
36    pub(crate) aligned_handshake: bool,
37    pub(crate) may_send_application_data: bool,
38    pub(crate) may_receive_application_data: bool,
39    pub(crate) early_traffic: bool,
40    sent_fatal_alert: bool,
41    /// If the peer has signaled end of stream.
42    pub(crate) has_received_close_notify: bool,
43    #[cfg(feature = "std")]
44    pub(crate) has_seen_eof: bool,
45    pub(crate) peer_certificates: Option<CertificateChain<'static>>,
46    message_fragmenter: MessageFragmenter,
47    pub(crate) received_plaintext: ChunkVecBuffer,
48    pub(crate) sendable_tls: ChunkVecBuffer,
49    queued_key_update_message: Option<Vec<u8>>,
50
51    /// Protocol whose key schedule should be used. Unused for TLS < 1.3.
52    pub(crate) protocol: Protocol,
53    pub(crate) quic: quic::Quic,
54    pub(crate) enable_secret_extraction: bool,
55    temper_counters: TemperCounters,
56    pub(crate) refresh_traffic_keys_pending: bool,
57}
58
59impl CommonState {
60    pub(crate) fn new(side: Side) -> Self {
61        Self {
62            negotiated_version: None,
63            handshake_kind: None,
64            side,
65            record_layer: record_layer::RecordLayer::new(),
66            suite: None,
67            kx_state: KxState::default(),
68            alpn_protocol: None,
69            aligned_handshake: true,
70            may_send_application_data: false,
71            may_receive_application_data: false,
72            early_traffic: false,
73            sent_fatal_alert: false,
74            has_received_close_notify: false,
75            #[cfg(feature = "std")]
76            has_seen_eof: false,
77            peer_certificates: None,
78            message_fragmenter: MessageFragmenter::default(),
79            received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
80            sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
81            queued_key_update_message: None,
82            protocol: Protocol::Tcp,
83            quic: quic::Quic::default(),
84            enable_secret_extraction: false,
85            temper_counters: TemperCounters::default(),
86            refresh_traffic_keys_pending: false,
87        }
88    }
89
90    /// Returns true if the caller should call [`Connection::write_tls`] as soon as possible.
91    ///
92    /// [`Connection::write_tls`]: crate::Connection::write_tls
93    pub fn wants_write(&self) -> bool {
94        !self.sendable_tls.is_empty()
95    }
96
97    /// Returns true if the connection is currently performing the TLS handshake.
98    ///
99    /// During this time plaintext written to the connection is buffered in memory. After
100    /// [`Connection::process_new_packets()`] has been called, this might start to return `false`
101    /// while the final handshake packets still need to be extracted from the connection's buffers.
102    ///
103    /// [`Connection::process_new_packets()`]: crate::Connection::process_new_packets
104    pub fn is_handshaking(&self) -> bool {
105        !(self.may_send_application_data && self.may_receive_application_data)
106    }
107
108    /// Retrieves the certificate chain used by the peer to authenticate.
109    ///
110    /// The order of the certificate chain is as it appears in the TLS
111    /// protocol: the first certificate relates to the peer, the
112    /// second certifies the first, the third certifies the second, and
113    /// so on.
114    ///
115    /// This is made available for both full and resumed handshakes.
116    ///
117    /// For clients, this is the certificate chain of the server.
118    ///
119    /// For servers, this is the certificate chain of the client,
120    /// if client authentication was completed.
121    ///
122    /// The return value is None until this value is available.
123    pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
124        self.peer_certificates.as_deref()
125    }
126
127    /// Retrieves the protocol agreed with the peer via ALPN.
128    ///
129    /// A return value of `None` after handshake completion
130    /// means no protocol was agreed (because no protocols
131    /// were offered or accepted by the peer).
132    pub fn alpn_protocol(&self) -> Option<&[u8]> {
133        self.get_alpn_protocol()
134    }
135
136    /// Retrieves the ciphersuite agreed with the peer.
137    ///
138    /// This returns None until the ciphersuite is agreed.
139    pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
140        self.suite
141    }
142
143    /// Retrieves the key exchange group agreed with the peer.
144    ///
145    /// This function may return `None` depending on the state of the connection,
146    /// the type of handshake, and the protocol version.
147    ///
148    /// If [`CommonState::is_handshaking()`] is true this function will return `None`.
149    /// Similarly, if the [`CommonState::handshake_kind()`] is [`HandshakeKind::Resumed`]
150    /// and the [`CommonState::protocol_version()`] is TLS 1.2, then no key exchange will have
151    /// occurred and this function will return `None`.
152    pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
153        match self.kx_state {
154            KxState::Complete(group) => Some(group),
155            _ => None,
156        }
157    }
158
159    /// Retrieves the protocol version agreed with the peer.
160    ///
161    /// This returns `None` until the version is agreed.
162    pub fn protocol_version(&self) -> Option<ProtocolVersion> {
163        self.negotiated_version
164    }
165
166    /// Which kind of handshake was performed.
167    ///
168    /// This tells you whether the handshake was a resumption or not.
169    ///
170    /// This will return `None` before it is known which sort of
171    /// handshake occurred.
172    pub fn handshake_kind(&self) -> Option<HandshakeKind> {
173        self.handshake_kind
174    }
175
176    pub(crate) fn is_tls13(&self) -> bool {
177        matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
178    }
179
180    pub(crate) fn process_main_protocol<Data>(
181        &mut self,
182        msg: Message<'_>,
183        mut state: Box<dyn State<Data>>,
184        data: &mut Data,
185        sendable_plaintext: Option<&mut ChunkVecBuffer>,
186    ) -> Result<Box<dyn State<Data>>, Error> {
187        // For TLS1.2, outside of the handshake, send rejection alerts for
188        // renegotiation requests.  These can occur any time.
189        if self.may_receive_application_data && !self.is_tls13() {
190            let reject_ty = match self.side {
191                Side::Client => HandshakeType::HelloRequest,
192                Side::Server => HandshakeType::ClientHello,
193            };
194            if msg.is_handshake_type(reject_ty) {
195                self.temper_counters
196                    .received_renegotiation_request()?;
197                self.send_warning_alert(AlertDescription::NoRenegotiation);
198                return Ok(state);
199            }
200        }
201
202        let mut cx = Context {
203            common: self,
204            data,
205            sendable_plaintext,
206        };
207        match state.handle(&mut cx, msg) {
208            Ok(next) => {
209                state = next.into_owned();
210                Ok(state)
211            }
212            Err(e @ Error::InappropriateMessage { .. })
213            | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
214                Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
215            }
216            Err(e) => Err(e),
217        }
218    }
219
220    pub(crate) fn write_plaintext(
221        &mut self,
222        payload: OutboundChunks<'_>,
223        outgoing_tls: &mut [u8],
224    ) -> Result<usize, EncryptError> {
225        if payload.is_empty() {
226            return Ok(0);
227        }
228
229        let fragments = self
230            .message_fragmenter
231            .fragment_payload(
232                ContentType::ApplicationData,
233                ProtocolVersion::TLSv1_2,
234                payload.clone(),
235            );
236
237        for f in 0..fragments.len() {
238            match self
239                .record_layer
240                .pre_encrypt_action(f as u64)
241            {
242                PreEncryptAction::Nothing => {}
243                PreEncryptAction::RefreshOrClose => match self.negotiated_version {
244                    Some(ProtocolVersion::TLSv1_3) => {
245                        // driven by caller, as we don't have the `State` here
246                        self.refresh_traffic_keys_pending = true;
247                    }
248                    _ => {
249                        error!("traffic keys exhausted, closing connection to prevent security failure");
250                        self.send_close_notify();
251                        return Err(EncryptError::EncryptExhausted);
252                    }
253                },
254                PreEncryptAction::Refuse => {
255                    return Err(EncryptError::EncryptExhausted);
256                }
257            }
258        }
259
260        self.perhaps_write_key_update();
261
262        self.check_required_size(outgoing_tls, fragments)?;
263
264        let fragments = self
265            .message_fragmenter
266            .fragment_payload(
267                ContentType::ApplicationData,
268                ProtocolVersion::TLSv1_2,
269                payload,
270            );
271
272        Ok(self.write_fragments(outgoing_tls, fragments))
273    }
274
275    // Changing the keys must not span any fragmented handshake
276    // messages.  Otherwise the defragmented messages will have
277    // been protected with two different record layer protections,
278    // which is illegal.  Not mentioned in RFC.
279    pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
280        if !self.aligned_handshake {
281            Err(self.send_fatal_alert(
282                AlertDescription::UnexpectedMessage,
283                PeerMisbehaved::KeyEpochWithPendingFragment,
284            ))
285        } else {
286            Ok(())
287        }
288    }
289
290    /// Fragment `m`, encrypt the fragments, and then queue
291    /// the encrypted fragments for sending.
292    pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
293        let iter = self
294            .message_fragmenter
295            .fragment_message(&m);
296        for m in iter {
297            self.send_single_fragment(m);
298        }
299    }
300
301    /// Like send_msg_encrypt, but operate on an appdata directly.
302    fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
303        // Here, the limit on sendable_tls applies to encrypted data,
304        // but we're respecting it for plaintext data -- so we'll
305        // be out by whatever the cipher+record overhead is.  That's a
306        // constant and predictable amount, so it's not a terrible issue.
307        let len = match limit {
308            #[cfg(feature = "std")]
309            Limit::Yes => self
310                .sendable_tls
311                .apply_limit(payload.len()),
312            Limit::No => payload.len(),
313        };
314
315        let iter = self
316            .message_fragmenter
317            .fragment_payload(
318                ContentType::ApplicationData,
319                ProtocolVersion::TLSv1_2,
320                payload.split_at(len).0,
321            );
322        for m in iter {
323            self.send_single_fragment(m);
324        }
325
326        len
327    }
328
329    fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
330        if m.typ == ContentType::Alert {
331            // Alerts are always sendable -- never quashed by a PreEncryptAction.
332            let em = self.record_layer.encrypt_outgoing(m);
333            self.queue_tls_message(em);
334            return;
335        }
336
337        match self
338            .record_layer
339            .next_pre_encrypt_action()
340        {
341            PreEncryptAction::Nothing => {}
342
343            // Close connection once we start to run out of
344            // sequence space.
345            PreEncryptAction::RefreshOrClose => {
346                match self.negotiated_version {
347                    Some(ProtocolVersion::TLSv1_3) => {
348                        // driven by caller, as we don't have the `State` here
349                        self.refresh_traffic_keys_pending = true;
350                    }
351                    _ => {
352                        error!("traffic keys exhausted, closing connection to prevent security failure");
353                        self.send_close_notify();
354                        return;
355                    }
356                }
357            }
358
359            // Refuse to wrap counter at all costs.  This
360            // is basically untestable unfortunately.
361            PreEncryptAction::Refuse => {
362                return;
363            }
364        };
365
366        let em = self.record_layer.encrypt_outgoing(m);
367        self.queue_tls_message(em);
368    }
369
370    fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
371        debug_assert!(self.may_send_application_data);
372        debug_assert!(self.record_layer.is_encrypting());
373
374        if payload.is_empty() {
375            // Don't send empty fragments.
376            return 0;
377        }
378
379        self.send_appdata_encrypt(payload, limit)
380    }
381
382    /// Mark the connection as ready to send application data.
383    ///
384    /// Also flush `sendable_plaintext` if it is `Some`.
385    pub(crate) fn start_outgoing_traffic(
386        &mut self,
387        sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
388    ) {
389        self.may_send_application_data = true;
390        if let Some(sendable_plaintext) = sendable_plaintext {
391            self.flush_plaintext(sendable_plaintext);
392        }
393    }
394
395    /// Mark the connection as ready to send and receive application data.
396    ///
397    /// Also flush `sendable_plaintext` if it is `Some`.
398    pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
399        self.may_receive_application_data = true;
400        self.start_outgoing_traffic(sendable_plaintext);
401    }
402
403    /// Send any buffered plaintext.  Plaintext is buffered if
404    /// written during handshake.
405    fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
406        if !self.may_send_application_data {
407            return;
408        }
409
410        while let Some(buf) = sendable_plaintext.pop() {
411            self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
412        }
413    }
414
415    // Put m into sendable_tls for writing.
416    fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
417        self.perhaps_write_key_update();
418        self.sendable_tls.append(m.encode());
419    }
420
421    pub(crate) fn perhaps_write_key_update(&mut self) {
422        if let Some(message) = self.queued_key_update_message.take() {
423            self.sendable_tls.append(message);
424        }
425    }
426
427    /// Send a raw TLS message, fragmenting it if needed.
428    pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
429        {
430            if let Protocol::Quic = self.protocol {
431                if let MessagePayload::Alert(alert) = m.payload {
432                    self.quic.alert = Some(alert.description);
433                } else {
434                    debug_assert!(
435                        matches!(m.payload, MessagePayload::Handshake { .. }),
436                        "QUIC uses TLS for the cryptographic handshake only"
437                    );
438                    let mut bytes = Vec::new();
439                    m.payload.encode(&mut bytes);
440                    self.quic
441                        .hs_queue
442                        .push_back((must_encrypt, bytes));
443                }
444                return;
445            }
446        }
447        if !must_encrypt {
448            let msg = &m.into();
449            let iter = self
450                .message_fragmenter
451                .fragment_message(msg);
452            for m in iter {
453                self.queue_tls_message(m.to_unencrypted_opaque());
454            }
455        } else {
456            self.send_msg_encrypt(m.into());
457        }
458    }
459
460    pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
461        self.received_plaintext
462            .append(bytes.into_vec());
463    }
464
465    #[cfg(feature = "tls12")]
466    pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
467        let (dec, enc) = secrets.make_cipher_pair(side);
468        self.record_layer
469            .prepare_message_encrypter(
470                enc,
471                secrets
472                    .suite()
473                    .common
474                    .confidentiality_limit,
475            );
476        self.record_layer
477            .prepare_message_decrypter(dec);
478    }
479
480    pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
481        self.send_fatal_alert(AlertDescription::MissingExtension, why)
482    }
483
484    fn send_warning_alert(&mut self, desc: AlertDescription) {
485        warn!("Sending warning alert {:?}", desc);
486        self.send_warning_alert_no_log(desc);
487    }
488
489    pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
490        // Reject unknown AlertLevels.
491        if let AlertLevel::Unknown(_) = alert.level {
492            return Err(self.send_fatal_alert(
493                AlertDescription::IllegalParameter,
494                Error::AlertReceived(alert.description),
495            ));
496        }
497
498        // If we get a CloseNotify, make a note to declare EOF to our
499        // caller.  But do not treat unauthenticated alerts like this.
500        if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
501            self.has_received_close_notify = true;
502            return Ok(());
503        }
504
505        // Warnings are nonfatal for TLS1.2, but outlawed in TLS1.3
506        // (except, for no good reason, user_cancelled).
507        let err = Error::AlertReceived(alert.description);
508        if alert.level == AlertLevel::Warning {
509            self.temper_counters
510                .received_warning_alert()?;
511            if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
512                return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
513            } else {
514                warn!("TLS alert warning received: {:?}", alert);
515                return Ok(());
516            }
517        }
518
519        Err(err)
520    }
521
522    pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
523        self.send_fatal_alert(
524            match &err {
525                Error::InvalidCertificate(e) => e.clone().into(),
526                Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
527                _ => AlertDescription::HandshakeFailure,
528            },
529            err,
530        )
531    }
532
533    pub(crate) fn send_fatal_alert(
534        &mut self,
535        desc: AlertDescription,
536        err: impl Into<Error>,
537    ) -> Error {
538        debug_assert!(!self.sent_fatal_alert);
539        let m = Message::build_alert(AlertLevel::Fatal, desc);
540        self.send_msg(m, self.record_layer.is_encrypting());
541        self.sent_fatal_alert = true;
542        err.into()
543    }
544
545    /// Queues a `close_notify` warning alert to be sent in the next
546    /// [`Connection::write_tls`] call.  This informs the peer that the
547    /// connection is being closed.
548    ///
549    /// Does nothing if any `close_notify` or fatal alert was already sent.
550    ///
551    /// [`Connection::write_tls`]: crate::Connection::write_tls
552    pub fn send_close_notify(&mut self) {
553        if self.sent_fatal_alert {
554            return;
555        }
556        debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
557        self.sent_fatal_alert = true;
558        self.send_warning_alert_no_log(AlertDescription::CloseNotify);
559    }
560
561    pub(crate) fn eager_send_close_notify(
562        &mut self,
563        outgoing_tls: &mut [u8],
564    ) -> Result<usize, EncryptError> {
565        self.send_close_notify();
566        self.check_required_size(outgoing_tls, [].into_iter())?;
567        Ok(self.write_fragments(outgoing_tls, [].into_iter()))
568    }
569
570    fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
571        let m = Message::build_alert(AlertLevel::Warning, desc);
572        self.send_msg(m, self.record_layer.is_encrypting());
573    }
574
575    fn check_required_size<'a>(
576        &self,
577        outgoing_tls: &mut [u8],
578        fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
579    ) -> Result<(), EncryptError> {
580        let mut required_size = self.sendable_tls.len();
581
582        for m in fragments {
583            required_size += m.encoded_len(&self.record_layer);
584        }
585
586        if required_size > outgoing_tls.len() {
587            return Err(EncryptError::InsufficientSize(InsufficientSizeError {
588                required_size,
589            }));
590        }
591
592        Ok(())
593    }
594
595    fn write_fragments<'a>(
596        &mut self,
597        outgoing_tls: &mut [u8],
598        fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
599    ) -> usize {
600        let mut written = 0;
601
602        // Any pre-existing encrypted messages in `sendable_tls` must
603        // be output before encrypting any of the `fragments`.
604        while let Some(message) = self.sendable_tls.pop() {
605            let len = message.len();
606            outgoing_tls[written..written + len].copy_from_slice(&message);
607            written += len;
608        }
609
610        for m in fragments {
611            let em = self
612                .record_layer
613                .encrypt_outgoing(m)
614                .encode();
615
616            let len = em.len();
617            outgoing_tls[written..written + len].copy_from_slice(&em);
618            written += len;
619        }
620
621        written
622    }
623
624    pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
625        self.message_fragmenter
626            .set_max_fragment_size(new)
627    }
628
629    pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
630        self.alpn_protocol
631            .as_ref()
632            .map(AsRef::as_ref)
633    }
634
635    /// Returns true if the caller should call [`Connection::read_tls`] as soon
636    /// as possible.
637    ///
638    /// If there is pending plaintext data to read with [`Connection::reader`],
639    /// this returns false.  If your application respects this mechanism,
640    /// only one full TLS message will be buffered by rustls.
641    ///
642    /// [`Connection::reader`]: crate::Connection::reader
643    /// [`Connection::read_tls`]: crate::Connection::read_tls
644    pub fn wants_read(&self) -> bool {
645        // We want to read more data all the time, except when we have unprocessed plaintext.
646        // This provides back-pressure to the TCP buffers. We also don't want to read more after
647        // the peer has sent us a close notification.
648        //
649        // In the handshake case we don't have readable plaintext before the handshake has
650        // completed, but also don't want to read if we still have sendable tls.
651        self.received_plaintext.is_empty()
652            && !self.has_received_close_notify
653            && (self.may_send_application_data || self.sendable_tls.is_empty())
654    }
655
656    pub(crate) fn current_io_state(&self) -> IoState {
657        IoState {
658            tls_bytes_to_write: self.sendable_tls.len(),
659            plaintext_bytes_to_read: self.received_plaintext.len(),
660            peer_has_closed: self.has_received_close_notify,
661        }
662    }
663
664    pub(crate) fn is_quic(&self) -> bool {
665        self.protocol == Protocol::Quic
666    }
667
668    pub(crate) fn should_update_key(
669        &mut self,
670        key_update_request: &KeyUpdateRequest,
671    ) -> Result<bool, Error> {
672        self.temper_counters
673            .received_key_update_request()?;
674
675        match key_update_request {
676            KeyUpdateRequest::UpdateNotRequested => Ok(false),
677            KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
678            _ => Err(self.send_fatal_alert(
679                AlertDescription::IllegalParameter,
680                InvalidMessage::InvalidKeyUpdate,
681            )),
682        }
683    }
684
685    pub(crate) fn enqueue_key_update_notification(&mut self) {
686        let message = PlainMessage::from(Message::build_key_update_notify());
687        self.queued_key_update_message = Some(
688            self.record_layer
689                .encrypt_outgoing(message.borrow_outbound())
690                .encode(),
691        );
692    }
693
694    pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
695        self.temper_counters
696            .received_tls13_change_cipher_spec()
697    }
698}
699
700#[cfg(feature = "std")]
701impl CommonState {
702    /// Send plaintext application data, fragmenting and
703    /// encrypting it as it goes out.
704    ///
705    /// If internal buffers are too small, this function will not accept
706    /// all the data.
707    pub(crate) fn buffer_plaintext(
708        &mut self,
709        payload: OutboundChunks<'_>,
710        sendable_plaintext: &mut ChunkVecBuffer,
711    ) -> usize {
712        self.perhaps_write_key_update();
713        self.send_plain(payload, Limit::Yes, sendable_plaintext)
714    }
715
716    pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
717        debug_assert!(self.early_traffic);
718        debug_assert!(self.record_layer.is_encrypting());
719
720        if data.is_empty() {
721            // Don't send empty fragments.
722            return 0;
723        }
724
725        self.send_appdata_encrypt(data.into(), Limit::Yes)
726    }
727
728    /// Encrypt and send some plaintext `data`.  `limit` controls
729    /// whether the per-connection buffer limits apply.
730    ///
731    /// Returns the number of bytes written from `data`: this might
732    /// be less than `data.len()` if buffer limits were exceeded.
733    fn send_plain(
734        &mut self,
735        payload: OutboundChunks<'_>,
736        limit: Limit,
737        sendable_plaintext: &mut ChunkVecBuffer,
738    ) -> usize {
739        if !self.may_send_application_data {
740            // If we haven't completed handshaking, buffer
741            // plaintext to send once we do.
742            let len = match limit {
743                Limit::Yes => sendable_plaintext.append_limited_copy(payload),
744                Limit::No => sendable_plaintext.append(payload.to_vec()),
745            };
746            return len;
747        }
748
749        self.send_plain_non_buffering(payload, limit)
750    }
751}
752
753/// Describes which sort of handshake happened.
754#[derive(Debug, PartialEq, Clone, Copy)]
755pub enum HandshakeKind {
756    /// A full handshake.
757    ///
758    /// This is the typical TLS connection initiation process when resumption is
759    /// not yet unavailable, and the initial `ClientHello` was accepted by the server.
760    Full,
761
762    /// A full TLS1.3 handshake, with an extra round-trip for a `HelloRetryRequest`.
763    ///
764    /// The server can respond with a `HelloRetryRequest` if the initial `ClientHello`
765    /// is unacceptable for several reasons, the most likely if no supported key
766    /// shares were offered by the client.
767    FullWithHelloRetryRequest,
768
769    /// A resumed handshake.
770    ///
771    /// Resumed handshakes involve fewer round trips and less cryptography than
772    /// full ones, but can only happen when the peers have previously done a full
773    /// handshake together, and then remember data about it.
774    Resumed,
775}
776
777/// Values of this structure are returned from [`Connection::process_new_packets`]
778/// and tell the caller the current I/O state of the TLS connection.
779///
780/// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
781#[derive(Debug, Eq, PartialEq)]
782pub struct IoState {
783    tls_bytes_to_write: usize,
784    plaintext_bytes_to_read: usize,
785    peer_has_closed: bool,
786}
787
788impl IoState {
789    /// How many bytes could be written by [`Connection::write_tls`] if called
790    /// right now.  A non-zero value implies [`CommonState::wants_write`].
791    ///
792    /// [`Connection::write_tls`]: crate::Connection::write_tls
793    pub fn tls_bytes_to_write(&self) -> usize {
794        self.tls_bytes_to_write
795    }
796
797    /// How many plaintext bytes could be obtained via [`std::io::Read`]
798    /// without further I/O.
799    pub fn plaintext_bytes_to_read(&self) -> usize {
800        self.plaintext_bytes_to_read
801    }
802
803    /// True if the peer has sent us a close_notify alert.  This is
804    /// the TLS mechanism to securely half-close a TLS connection,
805    /// and signifies that the peer will not send any further data
806    /// on this connection.
807    ///
808    /// This is also signalled via returning `Ok(0)` from
809    /// [`std::io::Read`], after all the received bytes have been
810    /// retrieved.
811    pub fn peer_has_closed(&self) -> bool {
812        self.peer_has_closed
813    }
814}
815
816pub(crate) trait State<Data>: Send + Sync {
817    fn handle<'m>(
818        self: Box<Self>,
819        cx: &mut Context<'_, Data>,
820        message: Message<'m>,
821    ) -> Result<Box<dyn State<Data> + 'm>, Error>
822    where
823        Self: 'm;
824
825    fn export_keying_material(
826        &self,
827        _output: &mut [u8],
828        _label: &[u8],
829        _context: Option<&[u8]>,
830    ) -> Result<(), Error> {
831        Err(Error::HandshakeNotComplete)
832    }
833
834    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
835        Err(Error::HandshakeNotComplete)
836    }
837
838    fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
839        Err(Error::HandshakeNotComplete)
840    }
841
842    fn handle_decrypt_error(&self) {}
843
844    fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
845}
846
847pub(crate) struct Context<'a, Data> {
848    pub(crate) common: &'a mut CommonState,
849    pub(crate) data: &'a mut Data,
850    /// Buffered plaintext. This is `Some` if any plaintext was written during handshake and `None`
851    /// otherwise.
852    pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
853}
854
855/// Side of the connection.
856#[derive(Clone, Copy, Debug, PartialEq)]
857pub enum Side {
858    /// A client initiates the connection.
859    Client,
860    /// A server waits for a client to connect.
861    Server,
862}
863
864impl Side {
865    pub(crate) fn peer(&self) -> Self {
866        match self {
867            Self::Client => Self::Server,
868            Self::Server => Self::Client,
869        }
870    }
871}
872
873#[derive(Copy, Clone, Eq, PartialEq, Debug)]
874pub(crate) enum Protocol {
875    Tcp,
876    Quic,
877}
878
879enum Limit {
880    #[cfg(feature = "std")]
881    Yes,
882    No,
883}
884
885/// Tracking technically-allowed protocol actions
886/// that we limit to avoid denial-of-service vectors.
887struct TemperCounters {
888    allowed_warning_alerts: u8,
889    allowed_renegotiation_requests: u8,
890    allowed_key_update_requests: u8,
891    allowed_middlebox_ccs: u8,
892}
893
894impl TemperCounters {
895    fn received_warning_alert(&mut self) -> Result<(), Error> {
896        match self.allowed_warning_alerts {
897            0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
898            _ => {
899                self.allowed_warning_alerts -= 1;
900                Ok(())
901            }
902        }
903    }
904
905    fn received_renegotiation_request(&mut self) -> Result<(), Error> {
906        match self.allowed_renegotiation_requests {
907            0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
908            _ => {
909                self.allowed_renegotiation_requests -= 1;
910                Ok(())
911            }
912        }
913    }
914
915    fn received_key_update_request(&mut self) -> Result<(), Error> {
916        match self.allowed_key_update_requests {
917            0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
918            _ => {
919                self.allowed_key_update_requests -= 1;
920                Ok(())
921            }
922        }
923    }
924
925    fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
926        match self.allowed_middlebox_ccs {
927            0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
928            _ => {
929                self.allowed_middlebox_ccs -= 1;
930                Ok(())
931            }
932        }
933    }
934}
935
936impl Default for TemperCounters {
937    fn default() -> Self {
938        Self {
939            // cf. BoringSSL `kMaxWarningAlerts`
940            // <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls_record.cc#L137-L139>
941            allowed_warning_alerts: 4,
942
943            // we rebuff renegotiation requests with a `NoRenegotiation` warning alerts.
944            // a second request after this is fatal.
945            allowed_renegotiation_requests: 1,
946
947            // cf. BoringSSL `kMaxKeyUpdates`
948            // <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls13_both.cc#L35-L38>
949            allowed_key_update_requests: 32,
950
951            // At most two CCS are allowed: one after each ClientHello (recall a second
952            // ClientHello happens after a HelloRetryRequest).
953            //
954            // note BoringSSL allows up to 32.
955            allowed_middlebox_ccs: 2,
956        }
957    }
958}
959
960#[derive(Debug, Default)]
961pub(crate) enum KxState {
962    #[default]
963    None,
964    Start(&'static dyn SupportedKxGroup),
965    Complete(&'static dyn SupportedKxGroup),
966}
967
968impl KxState {
969    pub(crate) fn complete(&mut self) {
970        debug_assert!(matches!(self, Self::Start(_)));
971        if let Self::Start(group) = self {
972            *self = Self::Complete(*group);
973        }
974    }
975}
976
977const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
978pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;