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