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