rustls/
common_state.rs

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