rustls/
common_state.rs

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