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