rustls/
common_state.rs

1use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
2use crate::error::{Error, InvalidMessage, PeerMisbehaved};
3#[cfg(feature = "logging")]
4use crate::log::{debug, warn};
5use crate::msgs::alert::AlertMessagePayload;
6use crate::msgs::base::Payload;
7use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
8use crate::msgs::fragmenter::MessageFragmenter;
9use crate::msgs::handshake::CertificateChain;
10use crate::msgs::message::MessagePayload;
11use crate::msgs::message::{BorrowedPlainMessage, Message, OpaqueMessage, PlainMessage};
12use crate::quic;
13use crate::record_layer;
14use crate::suites::PartiallyExtractedSecrets;
15use crate::suites::SupportedCipherSuite;
16#[cfg(feature = "tls12")]
17use crate::tls12::ConnectionSecrets;
18use crate::vecbuf::ChunkVecBuffer;
19
20use alloc::boxed::Box;
21use alloc::vec::Vec;
22
23use pki_types::CertificateDer;
24
25/// Connection state common to both client and server connections.
26pub struct CommonState {
27    pub(crate) negotiated_version: Option<ProtocolVersion>,
28    pub(crate) side: Side,
29    pub(crate) record_layer: record_layer::RecordLayer,
30    pub(crate) suite: Option<SupportedCipherSuite>,
31    pub(crate) alpn_protocol: Option<Vec<u8>>,
32    pub(crate) aligned_handshake: bool,
33    pub(crate) may_send_application_data: bool,
34    pub(crate) may_receive_application_data: bool,
35    pub(crate) early_traffic: bool,
36    sent_fatal_alert: bool,
37    /// If the peer has signaled end of stream.
38    pub(crate) has_received_close_notify: bool,
39    pub(crate) has_seen_eof: bool,
40    pub(crate) received_middlebox_ccs: u8,
41    pub(crate) peer_certificates: Option<CertificateChain>,
42    message_fragmenter: MessageFragmenter,
43    pub(crate) received_plaintext: ChunkVecBuffer,
44    sendable_plaintext: ChunkVecBuffer,
45    pub(crate) sendable_tls: ChunkVecBuffer,
46    queued_key_update_message: Option<Vec<u8>>,
47
48    /// Protocol whose key schedule should be used. Unused for TLS < 1.3.
49    pub(crate) protocol: Protocol,
50    pub(crate) quic: quic::Quic,
51    pub(crate) enable_secret_extraction: bool,
52}
53
54impl CommonState {
55    pub(crate) fn new(side: Side) -> Self {
56        Self {
57            negotiated_version: None,
58            side,
59            record_layer: record_layer::RecordLayer::new(),
60            suite: None,
61            alpn_protocol: None,
62            aligned_handshake: true,
63            may_send_application_data: false,
64            may_receive_application_data: false,
65            early_traffic: false,
66            sent_fatal_alert: false,
67            has_received_close_notify: false,
68            has_seen_eof: false,
69            received_middlebox_ccs: 0,
70            peer_certificates: None,
71            message_fragmenter: MessageFragmenter::default(),
72            received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
73            sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
74            sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
75            queued_key_update_message: None,
76            protocol: Protocol::Tcp,
77            quic: quic::Quic::default(),
78            enable_secret_extraction: false,
79        }
80    }
81
82    /// Returns true if the caller should call [`Connection::write_tls`] as soon as possible.
83    ///
84    /// [`Connection::write_tls`]: crate::Connection::write_tls
85    pub fn wants_write(&self) -> bool {
86        !self.sendable_tls.is_empty()
87    }
88
89    /// Returns true if the connection is currently performing the TLS handshake.
90    ///
91    /// During this time plaintext written to the connection is buffered in memory. After
92    /// [`Connection::process_new_packets()`] has been called, this might start to return `false`
93    /// while the final handshake packets still need to be extracted from the connection's buffers.
94    ///
95    /// [`Connection::process_new_packets()`]: crate::Connection::process_new_packets
96    pub fn is_handshaking(&self) -> bool {
97        !(self.may_send_application_data && self.may_receive_application_data)
98    }
99
100    /// Retrieves the certificate chain used by the peer to authenticate.
101    ///
102    /// The order of the certificate chain is as it appears in the TLS
103    /// protocol: the first certificate relates to the peer, the
104    /// second certifies the first, the third certifies the second, and
105    /// so on.
106    ///
107    /// This is made available for both full and resumed handshakes.
108    ///
109    /// For clients, this is the certificate chain of the server.
110    ///
111    /// For servers, this is the certificate chain of the client,
112    /// if client authentication was completed.
113    ///
114    /// The return value is None until this value is available.
115    pub fn peer_certificates(&self) -> Option<&[CertificateDer<'_>]> {
116        self.peer_certificates.as_deref()
117    }
118
119    /// Retrieves the protocol agreed with the peer via ALPN.
120    ///
121    /// A return value of `None` after handshake completion
122    /// means no protocol was agreed (because no protocols
123    /// were offered or accepted by the peer).
124    pub fn alpn_protocol(&self) -> Option<&[u8]> {
125        self.get_alpn_protocol()
126    }
127
128    /// Retrieves the ciphersuite agreed with the peer.
129    ///
130    /// This returns None until the ciphersuite is agreed.
131    pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
132        self.suite
133    }
134
135    /// Retrieves the protocol version agreed with the peer.
136    ///
137    /// This returns `None` until the version is agreed.
138    pub fn protocol_version(&self) -> Option<ProtocolVersion> {
139        self.negotiated_version
140    }
141
142    pub(crate) fn is_tls13(&self) -> bool {
143        matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
144    }
145
146    pub(crate) fn process_main_protocol<Data>(
147        &mut self,
148        msg: Message,
149        mut state: Box<dyn State<Data>>,
150        data: &mut Data,
151    ) -> Result<Box<dyn State<Data>>, Error> {
152        // For TLS1.2, outside of the handshake, send rejection alerts for
153        // renegotiation requests.  These can occur any time.
154        if self.may_receive_application_data && !self.is_tls13() {
155            let reject_ty = match self.side {
156                Side::Client => HandshakeType::HelloRequest,
157                Side::Server => HandshakeType::ClientHello,
158            };
159            if msg.is_handshake_type(reject_ty) {
160                self.send_warning_alert(AlertDescription::NoRenegotiation);
161                return Ok(state);
162            }
163        }
164
165        let mut cx = Context { common: self, data };
166        match state.handle(&mut cx, msg) {
167            Ok(next) => {
168                state = next;
169                Ok(state)
170            }
171            Err(e @ Error::InappropriateMessage { .. })
172            | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
173                Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
174            }
175            Err(e) => Err(e),
176        }
177    }
178
179    /// Send plaintext application data, fragmenting and
180    /// encrypting it as it goes out.
181    ///
182    /// If internal buffers are too small, this function will not accept
183    /// all the data.
184    pub(crate) fn send_some_plaintext(&mut self, data: &[u8]) -> usize {
185        self.perhaps_write_key_update();
186        self.send_plain(data, Limit::Yes)
187    }
188
189    pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
190        debug_assert!(self.early_traffic);
191        debug_assert!(self.record_layer.is_encrypting());
192
193        if data.is_empty() {
194            // Don't send empty fragments.
195            return 0;
196        }
197
198        self.send_appdata_encrypt(data, Limit::Yes)
199    }
200
201    // Changing the keys must not span any fragmented handshake
202    // messages.  Otherwise the defragmented messages will have
203    // been protected with two different record layer protections,
204    // which is illegal.  Not mentioned in RFC.
205    pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
206        if !self.aligned_handshake {
207            Err(self.send_fatal_alert(
208                AlertDescription::UnexpectedMessage,
209                PeerMisbehaved::KeyEpochWithPendingFragment,
210            ))
211        } else {
212            Ok(())
213        }
214    }
215
216    /// Fragment `m`, encrypt the fragments, and then queue
217    /// the encrypted fragments for sending.
218    pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
219        let iter = self
220            .message_fragmenter
221            .fragment_message(&m);
222        for m in iter {
223            self.send_single_fragment(m);
224        }
225    }
226
227    /// Like send_msg_encrypt, but operate on an appdata directly.
228    fn send_appdata_encrypt(&mut self, payload: &[u8], limit: Limit) -> usize {
229        // Here, the limit on sendable_tls applies to encrypted data,
230        // but we're respecting it for plaintext data -- so we'll
231        // be out by whatever the cipher+record overhead is.  That's a
232        // constant and predictable amount, so it's not a terrible issue.
233        let len = match limit {
234            Limit::Yes => self
235                .sendable_tls
236                .apply_limit(payload.len()),
237            Limit::No => payload.len(),
238        };
239
240        let iter = self.message_fragmenter.fragment_slice(
241            ContentType::ApplicationData,
242            ProtocolVersion::TLSv1_2,
243            &payload[..len],
244        );
245        for m in iter {
246            self.send_single_fragment(m);
247        }
248
249        len
250    }
251
252    fn send_single_fragment(&mut self, m: BorrowedPlainMessage) {
253        // Close connection once we start to run out of
254        // sequence space.
255        if self
256            .record_layer
257            .wants_close_before_encrypt()
258        {
259            self.send_close_notify();
260        }
261
262        // Refuse to wrap counter at all costs.  This
263        // is basically untestable unfortunately.
264        if self.record_layer.encrypt_exhausted() {
265            return;
266        }
267
268        let em = self.record_layer.encrypt_outgoing(m);
269        self.queue_tls_message(em);
270    }
271
272    /// Encrypt and send some plaintext `data`.  `limit` controls
273    /// whether the per-connection buffer limits apply.
274    ///
275    /// Returns the number of bytes written from `data`: this might
276    /// be less than `data.len()` if buffer limits were exceeded.
277    fn send_plain(&mut self, data: &[u8], limit: Limit) -> usize {
278        if !self.may_send_application_data {
279            // If we haven't completed handshaking, buffer
280            // plaintext to send once we do.
281            let len = match limit {
282                Limit::Yes => self
283                    .sendable_plaintext
284                    .append_limited_copy(data),
285                Limit::No => self
286                    .sendable_plaintext
287                    .append(data.to_vec()),
288            };
289            return len;
290        }
291
292        debug_assert!(self.record_layer.is_encrypting());
293
294        if data.is_empty() {
295            // Don't send empty fragments.
296            return 0;
297        }
298
299        self.send_appdata_encrypt(data, limit)
300    }
301
302    pub(crate) fn start_outgoing_traffic(&mut self) {
303        self.may_send_application_data = true;
304        self.flush_plaintext();
305    }
306
307    pub(crate) fn start_traffic(&mut self) {
308        self.may_receive_application_data = true;
309        self.start_outgoing_traffic();
310    }
311
312    /// Sets a limit on the internal buffers used to buffer
313    /// unsent plaintext (prior to completing the TLS handshake)
314    /// and unsent TLS records.  This limit acts only on application
315    /// data written through [`Connection::writer`].
316    ///
317    /// By default the limit is 64KB.  The limit can be set
318    /// at any time, even if the current buffer use is higher.
319    ///
320    /// [`None`] means no limit applies, and will mean that written
321    /// data is buffered without bound -- it is up to the application
322    /// to appropriately schedule its plaintext and TLS writes to bound
323    /// memory usage.
324    ///
325    /// For illustration: `Some(1)` means a limit of one byte applies:
326    /// [`Connection::writer`] will accept only one byte, encrypt it and
327    /// add a TLS header.  Once this is sent via [`Connection::write_tls`],
328    /// another byte may be sent.
329    ///
330    /// # Internal write-direction buffering
331    /// rustls has two buffers whose size are bounded by this setting:
332    ///
333    /// ## Buffering of unsent plaintext data prior to handshake completion
334    ///
335    /// Calls to [`Connection::writer`] before or during the handshake
336    /// are buffered (up to the limit specified here).  Once the
337    /// handshake completes this data is encrypted and the resulting
338    /// TLS records are added to the outgoing buffer.
339    ///
340    /// ## Buffering of outgoing TLS records
341    ///
342    /// This buffer is used to store TLS records that rustls needs to
343    /// send to the peer.  It is used in these two circumstances:
344    ///
345    /// - by [`Connection::process_new_packets`] when a handshake or alert
346    ///   TLS record needs to be sent.
347    /// - by [`Connection::writer`] post-handshake: the plaintext is
348    ///   encrypted and the resulting TLS record is buffered.
349    ///
350    /// This buffer is emptied by [`Connection::write_tls`].
351    ///
352    /// [`Connection::writer`]: crate::Connection::writer
353    /// [`Connection::write_tls`]: crate::Connection::write_tls
354    /// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
355    pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
356        self.sendable_plaintext.set_limit(limit);
357        self.sendable_tls.set_limit(limit);
358    }
359
360    /// Send any buffered plaintext.  Plaintext is buffered if
361    /// written during handshake.
362    fn flush_plaintext(&mut self) {
363        if !self.may_send_application_data {
364            return;
365        }
366
367        while let Some(buf) = self.sendable_plaintext.pop() {
368            self.send_plain(&buf, Limit::No);
369        }
370    }
371
372    // Put m into sendable_tls for writing.
373    fn queue_tls_message(&mut self, m: OpaqueMessage) {
374        self.sendable_tls.append(m.encode());
375    }
376
377    /// Send a raw TLS message, fragmenting it if needed.
378    pub(crate) fn send_msg(&mut self, m: Message, must_encrypt: bool) {
379        {
380            if let Protocol::Quic = self.protocol {
381                if let MessagePayload::Alert(alert) = m.payload {
382                    self.quic.alert = Some(alert.description);
383                } else {
384                    debug_assert!(
385                        matches!(m.payload, MessagePayload::Handshake { .. }),
386                        "QUIC uses TLS for the cryptographic handshake only"
387                    );
388                    let mut bytes = Vec::new();
389                    m.payload.encode(&mut bytes);
390                    self.quic
391                        .hs_queue
392                        .push_back((must_encrypt, bytes));
393                }
394                return;
395            }
396        }
397        if !must_encrypt {
398            let msg = &m.into();
399            let iter = self
400                .message_fragmenter
401                .fragment_message(msg);
402            for m in iter {
403                self.queue_tls_message(m.to_unencrypted_opaque());
404            }
405        } else {
406            self.send_msg_encrypt(m.into());
407        }
408    }
409
410    pub(crate) fn take_received_plaintext(&mut self, bytes: Payload) {
411        self.received_plaintext.append(bytes.0);
412    }
413
414    #[cfg(feature = "tls12")]
415    pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
416        let (dec, enc) = secrets.make_cipher_pair(side);
417        self.record_layer
418            .prepare_message_encrypter(enc);
419        self.record_layer
420            .prepare_message_decrypter(dec);
421    }
422
423    pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
424        self.send_fatal_alert(AlertDescription::MissingExtension, why)
425    }
426
427    fn send_warning_alert(&mut self, desc: AlertDescription) {
428        warn!("Sending warning alert {:?}", desc);
429        self.send_warning_alert_no_log(desc);
430    }
431
432    pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
433        // Reject unknown AlertLevels.
434        if let AlertLevel::Unknown(_) = alert.level {
435            return Err(self.send_fatal_alert(
436                AlertDescription::IllegalParameter,
437                Error::AlertReceived(alert.description),
438            ));
439        }
440
441        // If we get a CloseNotify, make a note to declare EOF to our
442        // caller.  But do not treat unauthenticated alerts like this.
443        if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
444            self.has_received_close_notify = true;
445            return Ok(());
446        }
447
448        // Warnings are nonfatal for TLS1.2, but outlawed in TLS1.3
449        // (except, for no good reason, user_cancelled).
450        let err = Error::AlertReceived(alert.description);
451        if alert.level == AlertLevel::Warning {
452            if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
453                return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
454            } else {
455                warn!("TLS alert warning received: {:#?}", alert);
456                return Ok(());
457            }
458        }
459
460        Err(err)
461    }
462
463    pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
464        self.send_fatal_alert(
465            match &err {
466                Error::InvalidCertificate(e) => e.clone().into(),
467                Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
468                _ => AlertDescription::HandshakeFailure,
469            },
470            err,
471        )
472    }
473
474    pub(crate) fn send_fatal_alert(
475        &mut self,
476        desc: AlertDescription,
477        err: impl Into<Error>,
478    ) -> Error {
479        debug_assert!(!self.sent_fatal_alert);
480        let m = Message::build_alert(AlertLevel::Fatal, desc);
481        self.send_msg(m, self.record_layer.is_encrypting());
482        self.sent_fatal_alert = true;
483        err.into()
484    }
485
486    /// Queues a close_notify warning alert to be sent in the next
487    /// [`Connection::write_tls`] call.  This informs the peer that the
488    /// connection is being closed.
489    ///
490    /// [`Connection::write_tls`]: crate::Connection::write_tls
491    pub fn send_close_notify(&mut self) {
492        debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
493        self.send_warning_alert_no_log(AlertDescription::CloseNotify);
494    }
495
496    fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
497        let m = Message::build_alert(AlertLevel::Warning, desc);
498        self.send_msg(m, self.record_layer.is_encrypting());
499    }
500
501    pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
502        self.message_fragmenter
503            .set_max_fragment_size(new)
504    }
505
506    pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
507        self.alpn_protocol
508            .as_ref()
509            .map(AsRef::as_ref)
510    }
511
512    /// Returns true if the caller should call [`Connection::read_tls`] as soon
513    /// as possible.
514    ///
515    /// If there is pending plaintext data to read with [`Connection::reader`],
516    /// this returns false.  If your application respects this mechanism,
517    /// only one full TLS message will be buffered by rustls.
518    ///
519    /// [`Connection::reader`]: crate::Connection::reader
520    /// [`Connection::read_tls`]: crate::Connection::read_tls
521    pub fn wants_read(&self) -> bool {
522        // We want to read more data all the time, except when we have unprocessed plaintext.
523        // This provides back-pressure to the TCP buffers. We also don't want to read more after
524        // the peer has sent us a close notification.
525        //
526        // In the handshake case we don't have readable plaintext before the handshake has
527        // completed, but also don't want to read if we still have sendable tls.
528        self.received_plaintext.is_empty()
529            && !self.has_received_close_notify
530            && (self.may_send_application_data || self.sendable_tls.is_empty())
531    }
532
533    pub(crate) fn current_io_state(&self) -> IoState {
534        IoState {
535            tls_bytes_to_write: self.sendable_tls.len(),
536            plaintext_bytes_to_read: self.received_plaintext.len(),
537            peer_has_closed: self.has_received_close_notify,
538        }
539    }
540
541    pub(crate) fn is_quic(&self) -> bool {
542        self.protocol == Protocol::Quic
543    }
544
545    pub(crate) fn should_update_key(
546        &mut self,
547        key_update_request: &KeyUpdateRequest,
548    ) -> Result<bool, Error> {
549        match key_update_request {
550            KeyUpdateRequest::UpdateNotRequested => Ok(false),
551            KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
552            _ => Err(self.send_fatal_alert(
553                AlertDescription::IllegalParameter,
554                InvalidMessage::InvalidKeyUpdate,
555            )),
556        }
557    }
558
559    pub(crate) fn enqueue_key_update_notification(&mut self) {
560        let message = PlainMessage::from(Message::build_key_update_notify());
561        self.queued_key_update_message = Some(
562            self.record_layer
563                .encrypt_outgoing(message.borrow())
564                .encode(),
565        );
566    }
567
568    pub(crate) fn perhaps_write_key_update(&mut self) {
569        if let Some(message) = self.queued_key_update_message.take() {
570            self.sendable_tls.append(message);
571        }
572    }
573}
574
575/// Values of this structure are returned from [`Connection::process_new_packets`]
576/// and tell the caller the current I/O state of the TLS connection.
577///
578/// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
579#[derive(Debug, Eq, PartialEq)]
580pub struct IoState {
581    tls_bytes_to_write: usize,
582    plaintext_bytes_to_read: usize,
583    peer_has_closed: bool,
584}
585
586impl IoState {
587    /// How many bytes could be written by [`Connection::write_tls`] if called
588    /// right now.  A non-zero value implies [`CommonState::wants_write`].
589    ///
590    /// [`Connection::write_tls`]: crate::Connection::write_tls
591    pub fn tls_bytes_to_write(&self) -> usize {
592        self.tls_bytes_to_write
593    }
594
595    /// How many plaintext bytes could be obtained via [`std::io::Read`]
596    /// without further I/O.
597    pub fn plaintext_bytes_to_read(&self) -> usize {
598        self.plaintext_bytes_to_read
599    }
600
601    /// True if the peer has sent us a close_notify alert.  This is
602    /// the TLS mechanism to securely half-close a TLS connection,
603    /// and signifies that the peer will not send any further data
604    /// on this connection.
605    ///
606    /// This is also signalled via returning `Ok(0)` from
607    /// [`std::io::Read`], after all the received bytes have been
608    /// retrieved.
609    pub fn peer_has_closed(&self) -> bool {
610        self.peer_has_closed
611    }
612}
613
614pub(crate) trait State<Data>: Send + Sync {
615    fn handle(
616        self: Box<Self>,
617        cx: &mut Context<'_, Data>,
618        message: Message,
619    ) -> Result<Box<dyn State<Data>>, Error>;
620
621    fn export_keying_material(
622        &self,
623        _output: &mut [u8],
624        _label: &[u8],
625        _context: Option<&[u8]>,
626    ) -> Result<(), Error> {
627        Err(Error::HandshakeNotComplete)
628    }
629
630    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
631        Err(Error::HandshakeNotComplete)
632    }
633
634    fn handle_decrypt_error(&self) {}
635}
636
637pub(crate) struct Context<'a, Data> {
638    pub(crate) common: &'a mut CommonState,
639    pub(crate) data: &'a mut Data,
640}
641
642/// Side of the connection.
643#[derive(Clone, Copy, Debug, PartialEq)]
644pub enum Side {
645    /// A client initiates the connection.
646    Client,
647    /// A server waits for a client to connect.
648    Server,
649}
650
651impl Side {
652    pub(crate) fn peer(&self) -> Self {
653        match self {
654            Self::Client => Self::Server,
655            Self::Server => Self::Client,
656        }
657    }
658}
659
660#[derive(Copy, Clone, Eq, PartialEq, Debug)]
661pub(crate) enum Protocol {
662    Tcp,
663    Quic,
664}
665
666enum Limit {
667    Yes,
668    No,
669}
670
671const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
672const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;