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