Skip to main content

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