portable_rustls/
conn.rs

1use alloc::boxed::Box;
2use core::fmt::Debug;
3use core::mem;
4use core::ops::{Deref, DerefMut, Range};
5#[cfg(feature = "std")]
6use std::io;
7
8use crate::common_state::{CommonState, Context, IoState, State, DEFAULT_BUFFER_LIMIT};
9use crate::enums::{AlertDescription, ContentType, ProtocolVersion};
10use crate::error::{Error, PeerMisbehaved};
11use crate::log::trace;
12use crate::msgs::deframer::buffers::{BufferProgress, DeframerVecBuffer, Delocator, Locator};
13use crate::msgs::deframer::handshake::HandshakeDeframer;
14use crate::msgs::deframer::DeframerIter;
15use crate::msgs::handshake::Random;
16use crate::msgs::message::{InboundPlainMessage, Message, MessagePayload};
17use crate::record_layer::Decrypted;
18use crate::suites::{ExtractedSecrets, PartiallyExtractedSecrets};
19use crate::vecbuf::ChunkVecBuffer;
20
21pub(crate) mod unbuffered;
22
23#[cfg(feature = "std")]
24mod connection {
25    use alloc::vec::Vec;
26    use core::fmt::Debug;
27    use core::ops::{Deref, DerefMut};
28    use std::io::{self, BufRead, Read};
29
30    use crate::common_state::{CommonState, IoState};
31    use crate::error::Error;
32    use crate::msgs::message::OutboundChunks;
33    use crate::suites::ExtractedSecrets;
34    use crate::vecbuf::ChunkVecBuffer;
35    use crate::ConnectionCommon;
36
37    /// A client or server connection.
38    #[derive(Debug)]
39    pub enum Connection {
40        /// A client connection
41        Client(crate::client::ClientConnection),
42        /// A server connection
43        Server(crate::server::ServerConnection),
44    }
45
46    impl Connection {
47        /// Read TLS content from `rd`.
48        ///
49        /// See [`ConnectionCommon::read_tls()`] for more information.
50        pub fn read_tls(&mut self, rd: &mut dyn Read) -> Result<usize, io::Error> {
51            match self {
52                Self::Client(conn) => conn.read_tls(rd),
53                Self::Server(conn) => conn.read_tls(rd),
54            }
55        }
56
57        /// Writes TLS messages to `wr`.
58        ///
59        /// See [`ConnectionCommon::write_tls()`] for more information.
60        pub fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
61            self.sendable_tls.write_to(wr)
62        }
63
64        /// Returns an object that allows reading plaintext.
65        pub fn reader(&mut self) -> Reader<'_> {
66            match self {
67                Self::Client(conn) => conn.reader(),
68                Self::Server(conn) => conn.reader(),
69            }
70        }
71
72        /// Returns an object that allows writing plaintext.
73        pub fn writer(&mut self) -> Writer<'_> {
74            match self {
75                Self::Client(conn) => Writer::new(&mut **conn),
76                Self::Server(conn) => Writer::new(&mut **conn),
77            }
78        }
79
80        /// Processes any new packets read by a previous call to [`Connection::read_tls`].
81        ///
82        /// See [`ConnectionCommon::process_new_packets()`] for more information.
83        pub fn process_new_packets(&mut self) -> Result<IoState, Error> {
84            match self {
85                Self::Client(conn) => conn.process_new_packets(),
86                Self::Server(conn) => conn.process_new_packets(),
87            }
88        }
89
90        /// Derives key material from the agreed connection secrets.
91        ///
92        /// See [`ConnectionCommon::export_keying_material()`] for more information.
93        pub fn export_keying_material<T: AsMut<[u8]>>(
94            &self,
95            output: T,
96            label: &[u8],
97            context: Option<&[u8]>,
98        ) -> Result<T, Error> {
99            match self {
100                Self::Client(conn) => conn.export_keying_material(output, label, context),
101                Self::Server(conn) => conn.export_keying_material(output, label, context),
102            }
103        }
104
105        /// This function uses `io` to complete any outstanding IO for this connection.
106        ///
107        /// See [`ConnectionCommon::complete_io()`] for more information.
108        pub fn complete_io<T>(&mut self, io: &mut T) -> Result<(usize, usize), io::Error>
109        where
110            Self: Sized,
111            T: Read + io::Write,
112        {
113            match self {
114                Self::Client(conn) => conn.complete_io(io),
115                Self::Server(conn) => conn.complete_io(io),
116            }
117        }
118
119        /// Extract secrets, so they can be used when configuring kTLS, for example.
120        /// Should be used with care as it exposes secret key material.
121        pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
122            match self {
123                Self::Client(client) => client.dangerous_extract_secrets(),
124                Self::Server(server) => server.dangerous_extract_secrets(),
125            }
126        }
127
128        /// Sets a limit on the internal buffers
129        ///
130        /// See [`ConnectionCommon::set_buffer_limit()`] for more information.
131        pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
132            match self {
133                Self::Client(client) => client.set_buffer_limit(limit),
134                Self::Server(server) => server.set_buffer_limit(limit),
135            }
136        }
137
138        /// Sends a TLS1.3 `key_update` message to refresh a connection's keys
139        ///
140        /// See [`ConnectionCommon::refresh_traffic_keys()`] for more information.
141        pub fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
142            match self {
143                Self::Client(client) => client.refresh_traffic_keys(),
144                Self::Server(server) => server.refresh_traffic_keys(),
145            }
146        }
147    }
148
149    impl Deref for Connection {
150        type Target = CommonState;
151
152        fn deref(&self) -> &Self::Target {
153            match self {
154                Self::Client(conn) => &conn.core.common_state,
155                Self::Server(conn) => &conn.core.common_state,
156            }
157        }
158    }
159
160    impl DerefMut for Connection {
161        fn deref_mut(&mut self) -> &mut Self::Target {
162            match self {
163                Self::Client(conn) => &mut conn.core.common_state,
164                Self::Server(conn) => &mut conn.core.common_state,
165            }
166        }
167    }
168
169    /// A structure that implements [`std::io::Read`] for reading plaintext.
170    pub struct Reader<'a> {
171        pub(super) received_plaintext: &'a mut ChunkVecBuffer,
172        pub(super) has_received_close_notify: bool,
173        pub(super) has_seen_eof: bool,
174    }
175
176    impl<'a> Reader<'a> {
177        /// Check the connection's state if no bytes are available for reading.
178        fn check_no_bytes_state(&self) -> io::Result<()> {
179            match (self.has_received_close_notify, self.has_seen_eof) {
180                // cleanly closed; don't care about TCP EOF: express this as Ok(0)
181                (true, _) => Ok(()),
182                // unclean closure
183                (false, true) => Err(io::Error::new(
184                    io::ErrorKind::UnexpectedEof,
185                    UNEXPECTED_EOF_MESSAGE,
186                )),
187                // connection still going, but needs more data: signal `WouldBlock` so that
188                // the caller knows this
189                (false, false) => Err(io::ErrorKind::WouldBlock.into()),
190            }
191        }
192
193        /// Obtain a chunk of plaintext data received from the peer over this TLS connection.
194        ///
195        /// This method consumes `self` so that it can return a slice whose lifetime is bounded by
196        /// the [`ConnectionCommon`] that created this `Reader`.
197        pub fn into_first_chunk(self) -> io::Result<&'a [u8]> {
198            match self.received_plaintext.chunk() {
199                Some(chunk) => Ok(chunk),
200                None => {
201                    self.check_no_bytes_state()?;
202                    Ok(&[])
203                }
204            }
205        }
206    }
207
208    impl Read for Reader<'_> {
209        /// Obtain plaintext data received from the peer over this TLS connection.
210        ///
211        /// If the peer closes the TLS session cleanly, this returns `Ok(0)`  once all
212        /// the pending data has been read. No further data can be received on that
213        /// connection, so the underlying TCP connection should be half-closed too.
214        ///
215        /// If the peer closes the TLS session uncleanly (a TCP EOF without sending a
216        /// `close_notify` alert) this function returns a `std::io::Error` of type
217        /// `ErrorKind::UnexpectedEof` once any pending data has been read.
218        ///
219        /// Note that support for `close_notify` varies in peer TLS libraries: many do not
220        /// support it and uncleanly close the TCP connection (this might be
221        /// vulnerable to truncation attacks depending on the application protocol).
222        /// This means applications using rustls must both handle EOF
223        /// from this function, *and* unexpected EOF of the underlying TCP connection.
224        ///
225        /// If there are no bytes to read, this returns `Err(ErrorKind::WouldBlock.into())`.
226        ///
227        /// You may learn the number of bytes available at any time by inspecting
228        /// the return of [`Connection::process_new_packets`].
229        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
230            let len = self.received_plaintext.read(buf)?;
231            if len > 0 || buf.is_empty() {
232                return Ok(len);
233            }
234
235            self.check_no_bytes_state()
236                .map(|()| len)
237        }
238
239        /// Obtain plaintext data received from the peer over this TLS connection.
240        ///
241        /// If the peer closes the TLS session, this returns `Ok(())` without filling
242        /// any more of the buffer once all the pending data has been read. No further
243        /// data can be received on that connection, so the underlying TCP connection
244        /// should be half-closed too.
245        ///
246        /// If the peer closes the TLS session uncleanly (a TCP EOF without sending a
247        /// `close_notify` alert) this function returns a `std::io::Error` of type
248        /// `ErrorKind::UnexpectedEof` once any pending data has been read.
249        ///
250        /// Note that support for `close_notify` varies in peer TLS libraries: many do not
251        /// support it and uncleanly close the TCP connection (this might be
252        /// vulnerable to truncation attacks depending on the application protocol).
253        /// This means applications using rustls must both handle EOF
254        /// from this function, *and* unexpected EOF of the underlying TCP connection.
255        ///
256        /// If there are no bytes to read, this returns `Err(ErrorKind::WouldBlock.into())`.
257        ///
258        /// You may learn the number of bytes available at any time by inspecting
259        /// the return of [`Connection::process_new_packets`].
260        #[cfg(read_buf)]
261        fn read_buf(&mut self, mut cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> {
262            let before = cursor.written();
263            self.received_plaintext
264                .read_buf(cursor.reborrow())?;
265            let len = cursor.written() - before;
266            if len > 0 || cursor.capacity() == 0 {
267                return Ok(());
268            }
269
270            self.check_no_bytes_state()
271        }
272    }
273
274    impl BufRead for Reader<'_> {
275        /// Obtain a chunk of plaintext data received from the peer over this TLS connection.
276        /// This reads the same data as [`Reader::read()`], but returns a reference instead of
277        /// copying the data.
278        ///
279        /// The caller should call [`Reader::consume()`] afterward to advance the buffer.
280        ///
281        /// See [`Reader::into_first_chunk()`] for a version of this function that returns a
282        /// buffer with a longer lifetime.
283        fn fill_buf(&mut self) -> io::Result<&[u8]> {
284            Reader {
285                // reborrow
286                received_plaintext: self.received_plaintext,
287                ..*self
288            }
289            .into_first_chunk()
290        }
291
292        fn consume(&mut self, amt: usize) {
293            self.received_plaintext
294                .consume_first_chunk(amt)
295        }
296    }
297
298    const UNEXPECTED_EOF_MESSAGE: &str =
299        "peer closed connection without sending TLS close_notify: \
300https://docs.rs/portable-rustls/latest/portable_rustls/manual/_03_howto/index.html#unexpected-eof";
301
302    /// A structure that implements [`std::io::Write`] for writing plaintext.
303    pub struct Writer<'a> {
304        sink: &'a mut dyn PlaintextSink,
305    }
306
307    impl<'a> Writer<'a> {
308        /// Create a new Writer.
309        ///
310        /// This is not an external interface.  Get one of these objects
311        /// from [`Connection::writer`].
312        pub(crate) fn new(sink: &'a mut dyn PlaintextSink) -> Self {
313            Writer { sink }
314        }
315    }
316
317    impl io::Write for Writer<'_> {
318        /// Send the plaintext `buf` to the peer, encrypting
319        /// and authenticating it.  Once this function succeeds
320        /// you should call [`Connection::write_tls`] which will output the
321        /// corresponding TLS records.
322        ///
323        /// This function buffers plaintext sent before the
324        /// TLS handshake completes, and sends it as soon
325        /// as it can.  See [`ConnectionCommon::set_buffer_limit`] to control
326        /// the size of this buffer.
327        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
328            self.sink.write(buf)
329        }
330
331        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
332            self.sink.write_vectored(bufs)
333        }
334
335        fn flush(&mut self) -> io::Result<()> {
336            self.sink.flush()
337        }
338    }
339
340    /// Internal trait implemented by the [`ServerConnection`]/[`ClientConnection`]
341    /// allowing them to be the subject of a [`Writer`].
342    ///
343    /// [`ServerConnection`]: crate::ServerConnection
344    /// [`ClientConnection`]: crate::ClientConnection
345    pub(crate) trait PlaintextSink {
346        fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
347        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize>;
348        fn flush(&mut self) -> io::Result<()>;
349    }
350
351    impl<T> PlaintextSink for ConnectionCommon<T> {
352        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
353            let len = self
354                .core
355                .common_state
356                .buffer_plaintext(buf.into(), &mut self.sendable_plaintext);
357            self.core.maybe_refresh_traffic_keys();
358            Ok(len)
359        }
360
361        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
362            let payload_owner: Vec<&[u8]>;
363            let payload = match bufs.len() {
364                0 => return Ok(0),
365                1 => OutboundChunks::Single(bufs[0].deref()),
366                _ => {
367                    payload_owner = bufs
368                        .iter()
369                        .map(|io_slice| io_slice.deref())
370                        .collect();
371
372                    OutboundChunks::new(&payload_owner)
373                }
374            };
375            let len = self
376                .core
377                .common_state
378                .buffer_plaintext(payload, &mut self.sendable_plaintext);
379            self.core.maybe_refresh_traffic_keys();
380            Ok(len)
381        }
382
383        fn flush(&mut self) -> io::Result<()> {
384            Ok(())
385        }
386    }
387}
388
389#[cfg(feature = "std")]
390pub use connection::{Connection, Reader, Writer};
391
392#[derive(Debug)]
393pub(crate) struct ConnectionRandoms {
394    pub(crate) client: [u8; 32],
395    pub(crate) server: [u8; 32],
396}
397
398impl ConnectionRandoms {
399    pub(crate) fn new(client: Random, server: Random) -> Self {
400        Self {
401            client: client.0,
402            server: server.0,
403        }
404    }
405}
406
407/// Interface shared by client and server connections.
408pub struct ConnectionCommon<Data> {
409    pub(crate) core: ConnectionCore<Data>,
410    deframer_buffer: DeframerVecBuffer,
411    sendable_plaintext: ChunkVecBuffer,
412}
413
414impl<Data> ConnectionCommon<Data> {
415    /// Processes any new packets read by a previous call to
416    /// [`Connection::read_tls`].
417    ///
418    /// Errors from this function relate to TLS protocol errors, and
419    /// are fatal to the connection.  Future calls after an error will do
420    /// no new work and will return the same error. After an error is
421    /// received from [`process_new_packets`], you should not call [`read_tls`]
422    /// any more (it will fill up buffers to no purpose). However, you
423    /// may call the other methods on the connection, including `write`,
424    /// `send_close_notify`, and `write_tls`. Most likely you will want to
425    /// call `write_tls` to send any alerts queued by the error and then
426    /// close the underlying connection.
427    ///
428    /// Success from this function comes with some sundry state data
429    /// about the connection.
430    ///
431    /// [`read_tls`]: Connection::read_tls
432    /// [`process_new_packets`]: Connection::process_new_packets
433    #[inline]
434    pub fn process_new_packets(&mut self) -> Result<IoState, Error> {
435        self.core
436            .process_new_packets(&mut self.deframer_buffer, &mut self.sendable_plaintext)
437    }
438
439    /// Derives key material from the agreed connection secrets.
440    ///
441    /// This function fills in `output` with `output.len()` bytes of key
442    /// material derived from the master session secret using `label`
443    /// and `context` for diversification. Ownership of the buffer is taken
444    /// by the function and returned via the Ok result to ensure no key
445    /// material leaks if the function fails.
446    ///
447    /// See RFC5705 for more details on what this does and is for.
448    ///
449    /// For TLS1.3 connections, this function does not use the
450    /// "early" exporter at any point.
451    ///
452    /// This function fails if called prior to the handshake completing;
453    /// check with [`CommonState::is_handshaking`] first.
454    ///
455    /// This function fails if `output.len()` is zero.
456    #[inline]
457    pub fn export_keying_material<T: AsMut<[u8]>>(
458        &self,
459        output: T,
460        label: &[u8],
461        context: Option<&[u8]>,
462    ) -> Result<T, Error> {
463        self.core
464            .export_keying_material(output, label, context)
465    }
466
467    /// Extract secrets, so they can be used when configuring kTLS, for example.
468    /// Should be used with care as it exposes secret key material.
469    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
470        if !self.enable_secret_extraction {
471            return Err(Error::General("Secret extraction is disabled".into()));
472        }
473
474        let st = self.core.state?;
475
476        let record_layer = self.core.common_state.record_layer;
477        let PartiallyExtractedSecrets { tx, rx } = st.extract_secrets()?;
478        Ok(ExtractedSecrets {
479            tx: (record_layer.write_seq(), tx),
480            rx: (record_layer.read_seq(), rx),
481        })
482    }
483
484    /// Sets a limit on the internal buffers used to buffer
485    /// unsent plaintext (prior to completing the TLS handshake)
486    /// and unsent TLS records.  This limit acts only on application
487    /// data written through [`Connection::writer`].
488    ///
489    /// By default the limit is 64KB.  The limit can be set
490    /// at any time, even if the current buffer use is higher.
491    ///
492    /// [`None`] means no limit applies, and will mean that written
493    /// data is buffered without bound -- it is up to the application
494    /// to appropriately schedule its plaintext and TLS writes to bound
495    /// memory usage.
496    ///
497    /// For illustration: `Some(1)` means a limit of one byte applies:
498    /// [`Connection::writer`] will accept only one byte, encrypt it and
499    /// add a TLS header.  Once this is sent via [`Connection::write_tls`],
500    /// another byte may be sent.
501    ///
502    /// # Internal write-direction buffering
503    /// rustls has two buffers whose size are bounded by this setting:
504    ///
505    /// ## Buffering of unsent plaintext data prior to handshake completion
506    ///
507    /// Calls to [`Connection::writer`] before or during the handshake
508    /// are buffered (up to the limit specified here).  Once the
509    /// handshake completes this data is encrypted and the resulting
510    /// TLS records are added to the outgoing buffer.
511    ///
512    /// ## Buffering of outgoing TLS records
513    ///
514    /// This buffer is used to store TLS records that rustls needs to
515    /// send to the peer.  It is used in these two circumstances:
516    ///
517    /// - by [`Connection::process_new_packets`] when a handshake or alert
518    ///   TLS record needs to be sent.
519    /// - by [`Connection::writer`] post-handshake: the plaintext is
520    ///   encrypted and the resulting TLS record is buffered.
521    ///
522    /// This buffer is emptied by [`Connection::write_tls`].
523    ///
524    /// [`Connection::writer`]: crate::Connection::writer
525    /// [`Connection::write_tls`]: crate::Connection::write_tls
526    /// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
527    pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
528        self.sendable_plaintext.set_limit(limit);
529        self.sendable_tls.set_limit(limit);
530    }
531
532    /// Sends a TLS1.3 `key_update` message to refresh a connection's keys.
533    ///
534    /// This call refreshes our encryption keys. Once the peer receives the message,
535    /// it refreshes _its_ encryption and decryption keys and sends a response.
536    /// Once we receive that response, we refresh our decryption keys to match.
537    /// At the end of this process, keys in both directions have been refreshed.
538    ///
539    /// Note that this process does not happen synchronously: this call just
540    /// arranges that the `key_update` message will be included in the next
541    /// `write_tls` output.
542    ///
543    /// This fails with `Error::HandshakeNotComplete` if called before the initial
544    /// handshake is complete, or if a version prior to TLS1.3 is negotiated.
545    ///
546    /// # Usage advice
547    /// Note that other implementations (including rustls) may enforce limits on
548    /// the number of `key_update` messages allowed on a given connection to prevent
549    /// denial of service.  Therefore, this should be called sparingly.
550    ///
551    /// rustls implicitly and automatically refreshes traffic keys when needed
552    /// according to the selected cipher suite's cryptographic constraints.  There
553    /// is therefore no need to call this manually to avoid cryptographic keys
554    /// "wearing out".
555    ///
556    /// The main reason to call this manually is to roll keys when it is known
557    /// a connection will be idle for a long period.
558    pub fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
559        self.core.refresh_traffic_keys()
560    }
561}
562
563#[cfg(feature = "std")]
564impl<Data> ConnectionCommon<Data> {
565    /// Returns an object that allows reading plaintext.
566    pub fn reader(&mut self) -> Reader<'_> {
567        let common = &mut self.core.common_state;
568        Reader {
569            received_plaintext: &mut common.received_plaintext,
570            // Are we done? i.e., have we processed all received messages, and received a
571            // close_notify to indicate that no new messages will arrive?
572            has_received_close_notify: common.has_received_close_notify,
573            has_seen_eof: common.has_seen_eof,
574        }
575    }
576
577    /// Returns an object that allows writing plaintext.
578    pub fn writer(&mut self) -> Writer<'_> {
579        Writer::new(self)
580    }
581
582    /// This function uses `io` to complete any outstanding IO for
583    /// this connection.
584    ///
585    /// This is a convenience function which solely uses other parts
586    /// of the public API.
587    ///
588    /// What this means depends on the connection  state:
589    ///
590    /// - If the connection [`is_handshaking`], then IO is performed until
591    ///   the handshake is complete.
592    /// - Otherwise, if [`wants_write`] is true, [`write_tls`] is invoked
593    ///   until it is all written.
594    /// - Otherwise, if [`wants_read`] is true, [`read_tls`] is invoked
595    ///   once.
596    ///
597    /// The return value is the number of bytes read from and written
598    /// to `io`, respectively.
599    ///
600    /// This function will block if `io` blocks.
601    ///
602    /// Errors from TLS record handling (i.e., from [`process_new_packets`])
603    /// are wrapped in an `io::ErrorKind::InvalidData`-kind error.
604    ///
605    /// [`is_handshaking`]: CommonState::is_handshaking
606    /// [`wants_read`]: CommonState::wants_read
607    /// [`wants_write`]: CommonState::wants_write
608    /// [`write_tls`]: ConnectionCommon::write_tls
609    /// [`read_tls`]: ConnectionCommon::read_tls
610    /// [`process_new_packets`]: ConnectionCommon::process_new_packets
611    pub fn complete_io<T>(&mut self, io: &mut T) -> Result<(usize, usize), io::Error>
612    where
613        Self: Sized,
614        T: io::Read + io::Write,
615    {
616        let mut eof = false;
617        let mut wrlen = 0;
618        let mut rdlen = 0;
619
620        loop {
621            let until_handshaked = self.is_handshaking();
622
623            if !self.wants_write() && !self.wants_read() {
624                // We will make no further progress.
625                return Ok((rdlen, wrlen));
626            }
627
628            while self.wants_write() {
629                match self.write_tls(io)? {
630                    0 => {
631                        io.flush()?;
632                        return Ok((rdlen, wrlen)); // EOF.
633                    }
634                    n => wrlen += n,
635                }
636            }
637            io.flush()?;
638
639            if !until_handshaked && wrlen > 0 {
640                return Ok((rdlen, wrlen));
641            }
642
643            while !eof && self.wants_read() {
644                let read_size = match self.read_tls(io) {
645                    Ok(0) => {
646                        eof = true;
647                        Some(0)
648                    }
649                    Ok(n) => {
650                        rdlen += n;
651                        Some(n)
652                    }
653                    Err(ref err) if err.kind() == io::ErrorKind::Interrupted => None, // nothing to do
654                    Err(err) => return Err(err),
655                };
656                if read_size.is_some() {
657                    break;
658                }
659            }
660
661            match self.process_new_packets() {
662                Ok(_) => {}
663                Err(e) => {
664                    // In case we have an alert to send describing this error,
665                    // try a last-gasp write -- but don't predate the primary
666                    // error.
667                    let _ignored = self.write_tls(io);
668                    let _ignored = io.flush();
669
670                    return Err(io::Error::new(io::ErrorKind::InvalidData, e));
671                }
672            };
673
674            // if we're doing IO until handshaked, and we believe we've finished handshaking,
675            // but process_new_packets() has queued TLS data to send, loop around again to write
676            // the queued messages.
677            if until_handshaked && !self.is_handshaking() && self.wants_write() {
678                continue;
679            }
680
681            match (eof, until_handshaked, self.is_handshaking()) {
682                (_, true, false) => return Ok((rdlen, wrlen)),
683                (_, false, _) => return Ok((rdlen, wrlen)),
684                (true, true, true) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
685                (..) => {}
686            }
687        }
688    }
689
690    /// Extract the first handshake message.
691    ///
692    /// This is a shortcut to the `process_new_packets()` -> `process_msg()` ->
693    /// `process_handshake_messages()` path, specialized for the first handshake message.
694    pub(crate) fn first_handshake_message(&mut self) -> Result<Option<Message<'static>>, Error> {
695        let mut buffer_progress = self.core.hs_deframer.progress();
696
697        let res = self
698            .core
699            .deframe(
700                None,
701                self.deframer_buffer.filled_mut(),
702                &mut buffer_progress,
703            )
704            .map(|opt| opt.map(|pm| Message::try_from(pm).map(|m| m.into_owned())));
705
706        match res? {
707            Some(Ok(msg)) => {
708                self.deframer_buffer
709                    .discard(buffer_progress.take_discard());
710                Ok(Some(msg))
711            }
712            Some(Err(err)) => Err(self.send_fatal_alert(AlertDescription::DecodeError, err)),
713            None => Ok(None),
714        }
715    }
716
717    pub(crate) fn replace_state(&mut self, new: Box<dyn State<Data>>) {
718        self.core.state = Ok(new);
719    }
720
721    /// Read TLS content from `rd` into the internal buffer.
722    ///
723    /// Due to the internal buffering, `rd` can supply TLS messages in arbitrary-sized chunks (like
724    /// a socket or pipe might).
725    ///
726    /// You should call [`process_new_packets()`] each time a call to this function succeeds in order
727    /// to empty the incoming TLS data buffer.
728    ///
729    /// This function returns `Ok(0)` when the underlying `rd` does so. This typically happens when
730    /// a socket is cleanly closed, or a file is at EOF. Errors may result from the IO done through
731    /// `rd`; additionally, errors of `ErrorKind::Other` are emitted to signal backpressure:
732    ///
733    /// * In order to empty the incoming TLS data buffer, you should call [`process_new_packets()`]
734    ///   each time a call to this function succeeds.
735    /// * In order to empty the incoming plaintext data buffer, you should empty it through
736    ///   the [`reader()`] after the call to [`process_new_packets()`].
737    ///
738    /// This function also returns `Ok(0)` once a `close_notify` alert has been successfully
739    /// received.  No additional data is ever read in this state.
740    ///
741    /// [`process_new_packets()`]: ConnectionCommon::process_new_packets
742    /// [`reader()`]: ConnectionCommon::reader
743    pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
744        if self.received_plaintext.is_full() {
745            return Err(io::Error::new(
746                io::ErrorKind::Other,
747                "received plaintext buffer full",
748            ));
749        }
750
751        if self.has_received_close_notify {
752            return Ok(0);
753        }
754
755        let res = self
756            .deframer_buffer
757            .read(rd, self.core.hs_deframer.is_active());
758        if let Ok(0) = res {
759            self.has_seen_eof = true;
760        }
761        res
762    }
763
764    /// Writes TLS messages to `wr`.
765    ///
766    /// On success, this function returns `Ok(n)` where `n` is a number of bytes written to `wr`
767    /// (after encoding and encryption).
768    ///
769    /// After this function returns, the connection buffer may not yet be fully flushed. The
770    /// [`CommonState::wants_write`] function can be used to check if the output buffer is empty.
771    pub fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
772        self.sendable_tls.write_to(wr)
773    }
774}
775
776impl<'a, Data> From<&'a mut ConnectionCommon<Data>> for Context<'a, Data> {
777    fn from(conn: &'a mut ConnectionCommon<Data>) -> Self {
778        Self {
779            common: &mut conn.core.common_state,
780            data: &mut conn.core.data,
781            sendable_plaintext: Some(&mut conn.sendable_plaintext),
782        }
783    }
784}
785
786impl<T> Deref for ConnectionCommon<T> {
787    type Target = CommonState;
788
789    fn deref(&self) -> &Self::Target {
790        &self.core.common_state
791    }
792}
793
794impl<T> DerefMut for ConnectionCommon<T> {
795    fn deref_mut(&mut self) -> &mut Self::Target {
796        &mut self.core.common_state
797    }
798}
799
800impl<Data> From<ConnectionCore<Data>> for ConnectionCommon<Data> {
801    fn from(core: ConnectionCore<Data>) -> Self {
802        Self {
803            core,
804            deframer_buffer: DeframerVecBuffer::default(),
805            sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
806        }
807    }
808}
809
810/// Interface shared by unbuffered client and server connections.
811pub struct UnbufferedConnectionCommon<Data> {
812    pub(crate) core: ConnectionCore<Data>,
813    wants_write: bool,
814}
815
816impl<Data> From<ConnectionCore<Data>> for UnbufferedConnectionCommon<Data> {
817    fn from(core: ConnectionCore<Data>) -> Self {
818        Self {
819            core,
820            wants_write: false,
821        }
822    }
823}
824
825impl<T> Deref for UnbufferedConnectionCommon<T> {
826    type Target = CommonState;
827
828    fn deref(&self) -> &Self::Target {
829        &self.core.common_state
830    }
831}
832
833pub(crate) struct ConnectionCore<Data> {
834    pub(crate) state: Result<Box<dyn State<Data>>, Error>,
835    pub(crate) data: Data,
836    pub(crate) common_state: CommonState,
837    pub(crate) hs_deframer: HandshakeDeframer,
838
839    /// We limit consecutive empty fragments to avoid a route for the peer to send
840    /// us significant but fruitless traffic.
841    seen_consecutive_empty_fragments: u8,
842}
843
844impl<Data> ConnectionCore<Data> {
845    pub(crate) fn new(state: Box<dyn State<Data>>, data: Data, common_state: CommonState) -> Self {
846        Self {
847            state: Ok(state),
848            data,
849            common_state,
850            hs_deframer: HandshakeDeframer::default(),
851            seen_consecutive_empty_fragments: 0,
852        }
853    }
854
855    pub(crate) fn process_new_packets(
856        &mut self,
857        deframer_buffer: &mut DeframerVecBuffer,
858        sendable_plaintext: &mut ChunkVecBuffer,
859    ) -> Result<IoState, Error> {
860        let mut state = match mem::replace(&mut self.state, Err(Error::HandshakeNotComplete)) {
861            Ok(state) => state,
862            Err(e) => {
863                self.state = Err(e.clone());
864                return Err(e);
865            }
866        };
867
868        let mut buffer_progress = self.hs_deframer.progress();
869
870        loop {
871            let res = self.deframe(
872                Some(&*state),
873                deframer_buffer.filled_mut(),
874                &mut buffer_progress,
875            );
876
877            let opt_msg = match res {
878                Ok(opt_msg) => opt_msg,
879                Err(e) => {
880                    self.state = Err(e.clone());
881                    deframer_buffer.discard(buffer_progress.take_discard());
882                    return Err(e);
883                }
884            };
885
886            let Some(msg) = opt_msg else {
887                break;
888            };
889
890            match self.process_msg(msg, state, Some(sendable_plaintext)) {
891                Ok(new) => state = new,
892                Err(e) => {
893                    self.state = Err(e.clone());
894                    deframer_buffer.discard(buffer_progress.take_discard());
895                    return Err(e);
896                }
897            }
898
899            if self
900                .common_state
901                .has_received_close_notify
902            {
903                // "Any data received after a closure alert has been received MUST be ignored."
904                // -- <https://datatracker.ietf.org/doc/html/rfc8446#section-6.1>
905                // This is data that has already been accepted in `read_tls`.
906                buffer_progress.add_discard(deframer_buffer.filled().len());
907                break;
908            }
909
910            deframer_buffer.discard(buffer_progress.take_discard());
911        }
912
913        deframer_buffer.discard(buffer_progress.take_discard());
914        self.state = Ok(state);
915        Ok(self.common_state.current_io_state())
916    }
917
918    /// Pull a message out of the deframer and send any messages that need to be sent as a result.
919    fn deframe<'b>(
920        &mut self,
921        state: Option<&dyn State<Data>>,
922        buffer: &'b mut [u8],
923        buffer_progress: &mut BufferProgress,
924    ) -> Result<Option<InboundPlainMessage<'b>>, Error> {
925        // before processing any more of `buffer`, return any extant messages from `hs_deframer`
926        if self.hs_deframer.has_message_ready() {
927            Ok(self.take_handshake_message(buffer, buffer_progress))
928        } else {
929            self.process_more_input(state, buffer, buffer_progress)
930        }
931    }
932
933    fn take_handshake_message<'b>(
934        &mut self,
935        buffer: &'b mut [u8],
936        buffer_progress: &mut BufferProgress,
937    ) -> Option<InboundPlainMessage<'b>> {
938        self.hs_deframer
939            .iter(buffer)
940            .next()
941            .map(|(message, discard)| {
942                buffer_progress.add_discard(discard);
943                message
944            })
945    }
946
947    fn process_more_input<'b>(
948        &mut self,
949        state: Option<&dyn State<Data>>,
950        buffer: &'b mut [u8],
951        buffer_progress: &mut BufferProgress,
952    ) -> Result<Option<InboundPlainMessage<'b>>, Error> {
953        let version_is_tls13 = matches!(
954            self.common_state.negotiated_version,
955            Some(ProtocolVersion::TLSv1_3)
956        );
957
958        let locator = Locator::new(buffer);
959
960        loop {
961            let mut iter = DeframerIter::new(&mut buffer[buffer_progress.processed()..]);
962
963            let (message, processed) = loop {
964                let message = match iter.next().transpose() {
965                    Ok(Some(message)) => message,
966                    Ok(None) => return Ok(None),
967                    Err(err) => return Err(self.handle_deframe_error(err, state)),
968                };
969
970                let allowed_plaintext = match message.typ {
971                    // CCS messages are always plaintext.
972                    ContentType::ChangeCipherSpec => true,
973                    // Alerts are allowed to be plaintext if-and-only-if:
974                    // * The negotiated protocol version is TLS 1.3. - In TLS 1.2 it is unambiguous when
975                    //   keying changes based on the CCS message. Only TLS 1.3 requires these heuristics.
976                    // * We have not yet decrypted any messages from the peer - if we have we don't
977                    //   expect any plaintext.
978                    // * The payload size is indicative of a plaintext alert message.
979                    ContentType::Alert
980                        if version_is_tls13
981                            && !self
982                                .common_state
983                                .record_layer
984                                .has_decrypted()
985                            && message.payload.len() <= 2 =>
986                    {
987                        true
988                    }
989                    // In other circumstances, we expect all messages to be encrypted.
990                    _ => false,
991                };
992
993                if allowed_plaintext && !self.hs_deframer.is_active() {
994                    break (message.into_plain_message(), iter.bytes_consumed());
995                }
996
997                let message = match self
998                    .common_state
999                    .record_layer
1000                    .decrypt_incoming(message)
1001                {
1002                    // failed decryption during trial decryption is not allowed to be
1003                    // interleaved with partial handshake data.
1004                    Ok(None) if !self.hs_deframer.is_aligned() => {
1005                        return Err(
1006                            PeerMisbehaved::RejectedEarlyDataInterleavedWithHandshakeMessage.into(),
1007                        )
1008                    }
1009
1010                    // failed decryption during trial decryption.
1011                    Ok(None) => continue,
1012
1013                    Ok(Some(message)) => message,
1014
1015                    Err(err) => return Err(self.handle_deframe_error(err, state)),
1016                };
1017
1018                let Decrypted {
1019                    want_close_before_decrypt,
1020                    plaintext,
1021                } = message;
1022
1023                if want_close_before_decrypt {
1024                    self.common_state.send_close_notify();
1025                }
1026
1027                break (plaintext, iter.bytes_consumed());
1028            };
1029
1030            if !self.hs_deframer.is_aligned() && message.typ != ContentType::Handshake {
1031                // "Handshake messages MUST NOT be interleaved with other record
1032                // types.  That is, if a handshake message is split over two or more
1033                // records, there MUST NOT be any other records between them."
1034                // https://www.rfc-editor.org/rfc/rfc8446#section-5.1
1035                return Err(PeerMisbehaved::MessageInterleavedWithHandshakeMessage.into());
1036            }
1037
1038            match message.payload.len() {
1039                0 => {
1040                    if self.seen_consecutive_empty_fragments
1041                        == ALLOWED_CONSECUTIVE_EMPTY_FRAGMENTS_MAX
1042                    {
1043                        return Err(PeerMisbehaved::TooManyEmptyFragments.into());
1044                    }
1045                    self.seen_consecutive_empty_fragments += 1;
1046                }
1047                _ => {
1048                    self.seen_consecutive_empty_fragments = 0;
1049                }
1050            };
1051
1052            buffer_progress.add_processed(processed);
1053
1054            // do an end-run around the borrow checker, converting `message` (containing
1055            // a borrowed slice) to an unborrowed one (containing a `Range` into the
1056            // same buffer).  the reborrow happens inside the branch that returns the
1057            // message.
1058            //
1059            // is fixed by -Zpolonius
1060            // https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions
1061            let unborrowed = InboundUnborrowedMessage::unborrow(&locator, message);
1062
1063            if unborrowed.typ != ContentType::Handshake {
1064                let message = unborrowed.reborrow(&Delocator::new(buffer));
1065                buffer_progress.add_discard(processed);
1066                return Ok(Some(message));
1067            }
1068
1069            let message = unborrowed.reborrow(&Delocator::new(buffer));
1070            self.hs_deframer
1071                .input_message(message, &locator, buffer_progress.processed());
1072            self.hs_deframer.coalesce(buffer)?;
1073
1074            self.common_state.aligned_handshake = self.hs_deframer.is_aligned();
1075
1076            if self.hs_deframer.has_message_ready() {
1077                // trial decryption finishes with the first handshake message after it started.
1078                self.common_state
1079                    .record_layer
1080                    .finish_trial_decryption();
1081
1082                return Ok(self.take_handshake_message(buffer, buffer_progress));
1083            }
1084        }
1085    }
1086
1087    fn handle_deframe_error(&mut self, error: Error, state: Option<&dyn State<Data>>) -> Error {
1088        match error {
1089            error @ Error::InvalidMessage(_) => {
1090                if self.common_state.is_quic() {
1091                    self.common_state.quic.alert = Some(AlertDescription::DecodeError);
1092                    error
1093                } else {
1094                    self.common_state
1095                        .send_fatal_alert(AlertDescription::DecodeError, error)
1096                }
1097            }
1098            Error::PeerSentOversizedRecord => self
1099                .common_state
1100                .send_fatal_alert(AlertDescription::RecordOverflow, error),
1101            Error::DecryptError => {
1102                if let Some(state) = state {
1103                    state.handle_decrypt_error();
1104                }
1105                self.common_state
1106                    .send_fatal_alert(AlertDescription::BadRecordMac, error)
1107            }
1108
1109            error => error,
1110        }
1111    }
1112
1113    fn process_msg(
1114        &mut self,
1115        msg: InboundPlainMessage<'_>,
1116        state: Box<dyn State<Data>>,
1117        sendable_plaintext: Option<&mut ChunkVecBuffer>,
1118    ) -> Result<Box<dyn State<Data>>, Error> {
1119        // Drop CCS messages during handshake in TLS1.3
1120        if msg.typ == ContentType::ChangeCipherSpec
1121            && !self
1122                .common_state
1123                .may_receive_application_data
1124            && self.common_state.is_tls13()
1125        {
1126            if !msg.is_valid_ccs() {
1127                // "An implementation which receives any other change_cipher_spec value or
1128                //  which receives a protected change_cipher_spec record MUST abort the
1129                //  handshake with an "unexpected_message" alert."
1130                return Err(self.common_state.send_fatal_alert(
1131                    AlertDescription::UnexpectedMessage,
1132                    PeerMisbehaved::IllegalMiddleboxChangeCipherSpec,
1133                ));
1134            }
1135
1136            self.common_state
1137                .received_tls13_change_cipher_spec()?;
1138            trace!("Dropping CCS");
1139            return Ok(state);
1140        }
1141
1142        // Now we can fully parse the message payload.
1143        let msg = match Message::try_from(msg) {
1144            Ok(msg) => msg,
1145            Err(err) => {
1146                return Err(self
1147                    .common_state
1148                    .send_fatal_alert(AlertDescription::DecodeError, err));
1149            }
1150        };
1151
1152        // For alerts, we have separate logic.
1153        if let MessagePayload::Alert(alert) = &msg.payload {
1154            self.common_state.process_alert(alert)?;
1155            return Ok(state);
1156        }
1157
1158        self.common_state
1159            .process_main_protocol(msg, state, &mut self.data, sendable_plaintext)
1160    }
1161
1162    pub(crate) fn export_keying_material<T: AsMut<[u8]>>(
1163        &self,
1164        mut output: T,
1165        label: &[u8],
1166        context: Option<&[u8]>,
1167    ) -> Result<T, Error> {
1168        if output.as_mut().is_empty() {
1169            return Err(Error::General(
1170                "export_keying_material with zero-length output".into(),
1171            ));
1172        }
1173
1174        match self.state.as_ref() {
1175            Ok(st) => st
1176                .export_keying_material(output.as_mut(), label, context)
1177                .map(|_| output),
1178            Err(e) => Err(e.clone()),
1179        }
1180    }
1181
1182    /// Trigger a `refresh_traffic_keys` if required by `CommonState`.
1183    fn maybe_refresh_traffic_keys(&mut self) {
1184        if mem::take(
1185            &mut self
1186                .common_state
1187                .refresh_traffic_keys_pending,
1188        ) {
1189            let _ = self.refresh_traffic_keys();
1190        }
1191    }
1192
1193    fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
1194        match &mut self.state {
1195            Ok(st) => st.send_key_update_request(&mut self.common_state),
1196            Err(e) => Err(e.clone()),
1197        }
1198    }
1199}
1200
1201/// Data specific to the peer's side (client or server).
1202pub trait SideData: Debug {}
1203
1204/// An InboundPlainMessage which does not borrow its payload, but
1205/// references a range that can later be borrowed.
1206struct InboundUnborrowedMessage {
1207    typ: ContentType,
1208    version: ProtocolVersion,
1209    bounds: Range<usize>,
1210}
1211
1212impl InboundUnborrowedMessage {
1213    fn unborrow(locator: &Locator, msg: InboundPlainMessage<'_>) -> Self {
1214        Self {
1215            typ: msg.typ,
1216            version: msg.version,
1217            bounds: locator.locate(msg.payload),
1218        }
1219    }
1220
1221    fn reborrow<'b>(self, delocator: &Delocator<'b>) -> InboundPlainMessage<'b> {
1222        InboundPlainMessage {
1223            typ: self.typ,
1224            version: self.version,
1225            payload: delocator.slice_from_range(&self.bounds),
1226        }
1227    }
1228}
1229
1230/// cf. BoringSSL's `kMaxEmptyRecords`
1231/// <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls_record.cc#L124-L128>
1232const ALLOWED_CONSECUTIVE_EMPTY_FRAGMENTS_MAX: u8 = 32;