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, ProtocolName};
18use crate::msgs::message::{
19    Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
20    PlainMessage,
21};
22use crate::record_layer::PreEncryptAction;
23use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
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<ProtocolName>,
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    /// Protocol whose key schedule should be used. Unused for TLS < 1.3.
56    pub(crate) protocol: Protocol,
57    pub(crate) quic: quic::Quic,
58    pub(crate) enable_secret_extraction: bool,
59    temper_counters: TemperCounters,
60    pub(crate) refresh_traffic_keys_pending: bool,
61    pub(crate) fips: bool,
62    pub(crate) tls13_tickets_received: u32,
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            tls13_tickets_received: 0,
96        }
97    }
98
99    /// Returns true if the caller should call [`Connection::write_tls`] as soon as possible.
100    ///
101    /// [`Connection::write_tls`]: crate::Connection::write_tls
102    pub fn wants_write(&self) -> bool {
103        !self.sendable_tls.is_empty()
104    }
105
106    /// Returns true if the connection is currently performing the TLS handshake.
107    ///
108    /// During this time plaintext written to the connection is buffered in memory. After
109    /// [`Connection::process_new_packets()`] has been called, this might start to return `false`
110    /// while the final handshake packets still need to be extracted from the connection's buffers.
111    ///
112    /// [`Connection::process_new_packets()`]: crate::Connection::process_new_packets
113    pub fn is_handshaking(&self) -> bool {
114        !(self.may_send_application_data && self.may_receive_application_data)
115    }
116
117    /// Retrieves the certificate chain or the raw public key used by the peer to authenticate.
118    ///
119    /// The order of the certificate chain is as it appears in the TLS
120    /// protocol: the first certificate relates to the peer, the
121    /// second certifies the first, the third certifies the second, and
122    /// so on.
123    ///
124    /// When using raw public keys, the first and only element is the raw public key.
125    ///
126    /// This is made available for both full and resumed handshakes.
127    ///
128    /// For clients, this is the certificate chain or the raw public key of the server.
129    ///
130    /// For servers, this is the certificate chain or the raw public key of the client,
131    /// if client authentication was completed.
132    ///
133    /// The return value is None until this value is available.
134    ///
135    /// Note: the return type of the 'certificate', when using raw public keys is `CertificateDer<'static>`
136    /// even though this should technically be a `SubjectPublicKeyInfoDer<'static>`.
137    /// This choice simplifies the API and ensures backwards compatibility.
138    pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
139        self.peer_certificates.as_deref()
140    }
141
142    /// Retrieves the protocol agreed with the peer via ALPN.
143    ///
144    /// A return value of `None` after handshake completion
145    /// means no protocol was agreed (because no protocols
146    /// were offered or accepted by the peer).
147    pub fn alpn_protocol(&self) -> Option<&[u8]> {
148        self.get_alpn_protocol()
149    }
150
151    /// Retrieves the ciphersuite agreed with the peer.
152    ///
153    /// This returns None until the ciphersuite is agreed.
154    pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
155        self.suite
156    }
157
158    /// Retrieves the key exchange group agreed with the peer.
159    ///
160    /// This function may return `None` depending on the state of the connection,
161    /// the type of handshake, and the protocol version.
162    ///
163    /// If [`CommonState::is_handshaking()`] is true this function will return `None`.
164    /// Similarly, if the [`CommonState::handshake_kind()`] is [`HandshakeKind::Resumed`]
165    /// and the [`CommonState::protocol_version()`] is TLS 1.2, then no key exchange will have
166    /// occurred and this function will return `None`.
167    pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
168        match self.kx_state {
169            KxState::Complete(group) => Some(group),
170            _ => None,
171        }
172    }
173
174    /// Retrieves the protocol version agreed with the peer.
175    ///
176    /// This returns `None` until the version is agreed.
177    pub fn protocol_version(&self) -> Option<ProtocolVersion> {
178        self.negotiated_version
179    }
180
181    /// Which kind of handshake was performed.
182    ///
183    /// This tells you whether the handshake was a resumption or not.
184    ///
185    /// This will return `None` before it is known which sort of
186    /// handshake occurred.
187    pub fn handshake_kind(&self) -> Option<HandshakeKind> {
188        self.handshake_kind
189    }
190
191    pub(crate) fn is_tls13(&self) -> bool {
192        matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
193    }
194
195    pub(crate) fn process_main_protocol<Data>(
196        &mut self,
197        msg: Message<'_>,
198        mut state: Box<dyn State<Data>>,
199        data: &mut Data,
200        sendable_plaintext: Option<&mut ChunkVecBuffer>,
201    ) -> Result<Box<dyn State<Data>>, Error> {
202        // For TLS1.2, outside of the handshake, send rejection alerts for
203        // renegotiation requests.  These can occur any time.
204        if self.may_receive_application_data && !self.is_tls13() {
205            let reject_ty = match self.side {
206                Side::Client => HandshakeType::HelloRequest,
207                Side::Server => HandshakeType::ClientHello,
208            };
209            if msg.is_handshake_type(reject_ty) {
210                self.temper_counters
211                    .received_renegotiation_request()?;
212                self.send_warning_alert(AlertDescription::NoRenegotiation);
213                return Ok(state);
214            }
215        }
216
217        let mut cx = Context {
218            common: self,
219            data,
220            sendable_plaintext,
221        };
222        match state.handle(&mut cx, msg) {
223            Ok(next) => {
224                state = next.into_owned();
225                Ok(state)
226            }
227            Err(e @ Error::InappropriateMessage { .. })
228            | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
229                Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
230            }
231            Err(e) => Err(e),
232        }
233    }
234
235    pub(crate) fn write_plaintext(
236        &mut self,
237        payload: OutboundChunks<'_>,
238        outgoing_tls: &mut [u8],
239    ) -> Result<usize, EncryptError> {
240        if payload.is_empty() {
241            return Ok(0);
242        }
243
244        let fragments = self
245            .message_fragmenter
246            .fragment_payload(
247                ContentType::ApplicationData,
248                ProtocolVersion::TLSv1_2,
249                payload.clone(),
250            );
251
252        for f in 0..fragments.len() {
253            match self
254                .record_layer
255                .pre_encrypt_action(f as u64)
256            {
257                PreEncryptAction::Nothing => {}
258                PreEncryptAction::RefreshOrClose => match self.negotiated_version {
259                    Some(ProtocolVersion::TLSv1_3) => {
260                        // driven by caller, as we don't have the `State` here
261                        self.refresh_traffic_keys_pending = true;
262                    }
263                    _ => {
264                        error!(
265                            "traffic keys exhausted, closing connection to prevent security failure"
266                        );
267                        self.send_close_notify();
268                        return Err(EncryptError::EncryptExhausted);
269                    }
270                },
271                PreEncryptAction::Refuse => {
272                    return Err(EncryptError::EncryptExhausted);
273                }
274            }
275        }
276
277        self.perhaps_write_key_update();
278
279        self.check_required_size(outgoing_tls, fragments)?;
280
281        let fragments = self
282            .message_fragmenter
283            .fragment_payload(
284                ContentType::ApplicationData,
285                ProtocolVersion::TLSv1_2,
286                payload,
287            );
288
289        Ok(self.write_fragments(outgoing_tls, fragments))
290    }
291
292    // Changing the keys must not span any fragmented handshake
293    // messages.  Otherwise the defragmented messages will have
294    // been protected with two different record layer protections,
295    // which is illegal.  Not mentioned in RFC.
296    pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
297        if !self.aligned_handshake {
298            Err(self.send_fatal_alert(
299                AlertDescription::UnexpectedMessage,
300                PeerMisbehaved::KeyEpochWithPendingFragment,
301            ))
302        } else {
303            Ok(())
304        }
305    }
306
307    /// Fragment `m`, encrypt the fragments, and then queue
308    /// the encrypted fragments for sending.
309    pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
310        let iter = self
311            .message_fragmenter
312            .fragment_message(&m);
313        for m in iter {
314            self.send_single_fragment(m);
315        }
316    }
317
318    /// Like send_msg_encrypt, but operate on an appdata directly.
319    fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
320        // Here, the limit on sendable_tls applies to encrypted data,
321        // but we're respecting it for plaintext data -- so we'll
322        // be out by whatever the cipher+record overhead is.  That's a
323        // constant and predictable amount, so it's not a terrible issue.
324        let len = match limit {
325            #[cfg(feature = "std")]
326            Limit::Yes => self
327                .sendable_tls
328                .apply_limit(payload.len()),
329            Limit::No => payload.len(),
330        };
331
332        let iter = self
333            .message_fragmenter
334            .fragment_payload(
335                ContentType::ApplicationData,
336                ProtocolVersion::TLSv1_2,
337                payload.split_at(len).0,
338            );
339        for m in iter {
340            self.send_single_fragment(m);
341        }
342
343        len
344    }
345
346    fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
347        if m.typ == ContentType::Alert {
348            // Alerts are always sendable -- never quashed by a PreEncryptAction.
349            let em = self.record_layer.encrypt_outgoing(m);
350            self.queue_tls_message(em);
351            return;
352        }
353
354        match self
355            .record_layer
356            .next_pre_encrypt_action()
357        {
358            PreEncryptAction::Nothing => {}
359
360            // Close connection once we start to run out of
361            // sequence space.
362            PreEncryptAction::RefreshOrClose => {
363                match self.negotiated_version {
364                    Some(ProtocolVersion::TLSv1_3) => {
365                        // driven by caller, as we don't have the `State` here
366                        self.refresh_traffic_keys_pending = true;
367                    }
368                    _ => {
369                        error!(
370                            "traffic keys exhausted, closing connection to prevent security failure"
371                        );
372                        self.send_close_notify();
373                        return;
374                    }
375                }
376            }
377
378            // Refuse to wrap counter at all costs.  This
379            // is basically untestable unfortunately.
380            PreEncryptAction::Refuse => {
381                return;
382            }
383        };
384
385        let em = self.record_layer.encrypt_outgoing(m);
386        self.queue_tls_message(em);
387    }
388
389    fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
390        debug_assert!(self.may_send_application_data);
391        debug_assert!(self.record_layer.is_encrypting());
392
393        if payload.is_empty() {
394            // Don't send empty fragments.
395            return 0;
396        }
397
398        self.send_appdata_encrypt(payload, limit)
399    }
400
401    /// Mark the connection as ready to send application data.
402    ///
403    /// Also flush `sendable_plaintext` if it is `Some`.
404    pub(crate) fn start_outgoing_traffic(
405        &mut self,
406        sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
407    ) {
408        self.may_send_application_data = true;
409        if let Some(sendable_plaintext) = sendable_plaintext {
410            self.flush_plaintext(sendable_plaintext);
411        }
412    }
413
414    /// Mark the connection as ready to send and receive application data.
415    ///
416    /// Also flush `sendable_plaintext` if it is `Some`.
417    pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
418        self.may_receive_application_data = true;
419        self.start_outgoing_traffic(sendable_plaintext);
420    }
421
422    /// Send any buffered plaintext.  Plaintext is buffered if
423    /// written during handshake.
424    fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
425        if !self.may_send_application_data {
426            return;
427        }
428
429        while let Some(buf) = sendable_plaintext.pop() {
430            self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
431        }
432    }
433
434    // Put m into sendable_tls for writing.
435    fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
436        self.perhaps_write_key_update();
437        self.sendable_tls.append(m.encode());
438    }
439
440    pub(crate) fn perhaps_write_key_update(&mut self) {
441        if let Some(message) = self.queued_key_update_message.take() {
442            self.sendable_tls.append(message);
443        }
444    }
445
446    /// Send a raw TLS message, fragmenting it if needed.
447    pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
448        {
449            if let Protocol::Quic = self.protocol {
450                if let MessagePayload::Alert(alert) = m.payload {
451                    self.quic.alert = Some(alert.description);
452                } else {
453                    debug_assert!(
454                        matches!(
455                            m.payload,
456                            MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
457                        ),
458                        "QUIC uses TLS for the cryptographic handshake only"
459                    );
460                    let mut bytes = Vec::new();
461                    m.payload.encode(&mut bytes);
462                    self.quic
463                        .hs_queue
464                        .push_back((must_encrypt, bytes));
465                }
466                return;
467            }
468        }
469        if !must_encrypt {
470            let msg = &m.into();
471            let iter = self
472                .message_fragmenter
473                .fragment_message(msg);
474            for m in iter {
475                self.queue_tls_message(m.to_unencrypted_opaque());
476            }
477        } else {
478            self.send_msg_encrypt(m.into());
479        }
480    }
481
482    pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
483        self.received_plaintext
484            .append(bytes.into_vec());
485    }
486
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)]
782#[non_exhaustive]
783pub enum HandshakeKind {
784    /// A full handshake.
785    ///
786    /// This is the typical TLS connection initiation process when resumption is
787    /// not yet unavailable, and the initial `ClientHello` was accepted by the server.
788    Full,
789
790    /// A full TLS1.3 handshake, with an extra round-trip for a `HelloRetryRequest`.
791    ///
792    /// The server can respond with a `HelloRetryRequest` if the initial `ClientHello`
793    /// is unacceptable for several reasons, the most likely if no supported key
794    /// shares were offered by the client.
795    FullWithHelloRetryRequest,
796
797    /// A resumed handshake.
798    ///
799    /// Resumed handshakes involve fewer round trips and less cryptography than
800    /// full ones, but can only happen when the peers have previously done a full
801    /// handshake together, and then remember data about it.
802    Resumed,
803}
804
805/// Values of this structure are returned from [`Connection::process_new_packets`]
806/// and tell the caller the current I/O state of the TLS connection.
807///
808/// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
809#[derive(Debug, Eq, PartialEq)]
810pub struct IoState {
811    tls_bytes_to_write: usize,
812    plaintext_bytes_to_read: usize,
813    peer_has_closed: bool,
814}
815
816impl IoState {
817    /// How many bytes could be written by [`Connection::write_tls`] if called
818    /// right now.  A non-zero value implies [`CommonState::wants_write`].
819    ///
820    /// [`Connection::write_tls`]: crate::Connection::write_tls
821    pub fn tls_bytes_to_write(&self) -> usize {
822        self.tls_bytes_to_write
823    }
824
825    /// How many plaintext bytes could be obtained via [`std::io::Read`]
826    /// without further I/O.
827    pub fn plaintext_bytes_to_read(&self) -> usize {
828        self.plaintext_bytes_to_read
829    }
830
831    /// True if the peer has sent us a close_notify alert.  This is
832    /// the TLS mechanism to securely half-close a TLS connection,
833    /// and signifies that the peer will not send any further data
834    /// on this connection.
835    ///
836    /// This is also signalled via returning `Ok(0)` from
837    /// [`std::io::Read`], after all the received bytes have been
838    /// retrieved.
839    pub fn peer_has_closed(&self) -> bool {
840        self.peer_has_closed
841    }
842}
843
844pub(crate) trait State<Data>: Send + Sync {
845    fn handle<'m>(
846        self: Box<Self>,
847        cx: &mut Context<'_, Data>,
848        message: Message<'m>,
849    ) -> Result<Box<dyn State<Data> + 'm>, Error>
850    where
851        Self: 'm;
852
853    fn export_keying_material(
854        &self,
855        _output: &mut [u8],
856        _label: &[u8],
857        _context: Option<&[u8]>,
858    ) -> Result<(), Error> {
859        Err(Error::HandshakeNotComplete)
860    }
861
862    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
863        Err(Error::HandshakeNotComplete)
864    }
865
866    fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
867        Err(Error::HandshakeNotComplete)
868    }
869
870    fn handle_decrypt_error(&self) {}
871
872    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
873        Err(Error::HandshakeNotComplete)
874    }
875
876    fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
877}
878
879pub(crate) struct Context<'a, Data> {
880    pub(crate) common: &'a mut CommonState,
881    pub(crate) data: &'a mut Data,
882    /// Buffered plaintext. This is `Some` if any plaintext was written during handshake and `None`
883    /// otherwise.
884    pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
885}
886
887/// Side of the connection.
888#[allow(clippy::exhaustive_enums)]
889#[derive(Clone, Copy, Debug, PartialEq)]
890pub enum Side {
891    /// A client initiates the connection.
892    Client,
893    /// A server waits for a client to connect.
894    Server,
895}
896
897impl Side {
898    pub(crate) fn peer(&self) -> Self {
899        match self {
900            Self::Client => Self::Server,
901            Self::Server => Self::Client,
902        }
903    }
904}
905
906#[derive(Copy, Clone, Eq, PartialEq, Debug)]
907pub(crate) enum Protocol {
908    Tcp,
909    Quic,
910}
911
912enum Limit {
913    #[cfg(feature = "std")]
914    Yes,
915    No,
916}
917
918/// Tracking technically-allowed protocol actions
919/// that we limit to avoid denial-of-service vectors.
920struct TemperCounters {
921    allowed_warning_alerts: u8,
922    allowed_renegotiation_requests: u8,
923    allowed_key_update_requests: u8,
924    allowed_middlebox_ccs: u8,
925}
926
927impl TemperCounters {
928    fn received_warning_alert(&mut self) -> Result<(), Error> {
929        match self.allowed_warning_alerts {
930            0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
931            _ => {
932                self.allowed_warning_alerts -= 1;
933                Ok(())
934            }
935        }
936    }
937
938    fn received_renegotiation_request(&mut self) -> Result<(), Error> {
939        match self.allowed_renegotiation_requests {
940            0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
941            _ => {
942                self.allowed_renegotiation_requests -= 1;
943                Ok(())
944            }
945        }
946    }
947
948    fn received_key_update_request(&mut self) -> Result<(), Error> {
949        match self.allowed_key_update_requests {
950            0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
951            _ => {
952                self.allowed_key_update_requests -= 1;
953                Ok(())
954            }
955        }
956    }
957
958    fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
959        match self.allowed_middlebox_ccs {
960            0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
961            _ => {
962                self.allowed_middlebox_ccs -= 1;
963                Ok(())
964            }
965        }
966    }
967}
968
969impl Default for TemperCounters {
970    fn default() -> Self {
971        Self {
972            // cf. BoringSSL `kMaxWarningAlerts`
973            // <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls_record.cc#L137-L139>
974            allowed_warning_alerts: 4,
975
976            // we rebuff renegotiation requests with a `NoRenegotiation` warning alerts.
977            // a second request after this is fatal.
978            allowed_renegotiation_requests: 1,
979
980            // cf. BoringSSL `kMaxKeyUpdates`
981            // <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls13_both.cc#L35-L38>
982            allowed_key_update_requests: 32,
983
984            // At most two CCS are allowed: one after each ClientHello (recall a second
985            // ClientHello happens after a HelloRetryRequest).
986            //
987            // note BoringSSL allows up to 32.
988            allowed_middlebox_ccs: 2,
989        }
990    }
991}
992
993#[derive(Debug, Default)]
994pub(crate) enum KxState {
995    #[default]
996    None,
997    Start(&'static dyn SupportedKxGroup),
998    Complete(&'static dyn SupportedKxGroup),
999}
1000
1001impl KxState {
1002    pub(crate) fn complete(&mut self) {
1003        debug_assert!(matches!(self, Self::Start(_)));
1004        if let Self::Start(group) = self {
1005            *self = Self::Complete(*group);
1006        }
1007    }
1008}
1009
1010pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
1011    pub(crate) transcript: &'a mut HandshakeHash,
1012    body: Vec<u8>,
1013}
1014
1015impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
1016    pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
1017        Self {
1018            transcript,
1019            body: Vec::new(),
1020        }
1021    }
1022
1023    pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1024        let start_len = self.body.len();
1025        hs.encode(&mut self.body);
1026        self.transcript
1027            .add(&self.body[start_len..]);
1028    }
1029
1030    pub(crate) fn finish(self, common: &mut CommonState) {
1031        common.send_msg(
1032            Message {
1033                version: match TLS13 {
1034                    true => ProtocolVersion::TLSv1_3,
1035                    false => ProtocolVersion::TLSv1_2,
1036                },
1037                payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1038            },
1039            TLS13,
1040        );
1041    }
1042}
1043
1044pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1045pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1046
1047const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1048pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;