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