rustls/
common_state.rs

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