rustls/
conn.rs

1use crate::common_state::{CommonState, Context, IoState, State};
2use crate::enums::{AlertDescription, ContentType};
3use crate::error::{Error, PeerMisbehaved};
4#[cfg(feature = "logging")]
5use crate::log::trace;
6use crate::msgs::deframer::{Deframed, MessageDeframer};
7use crate::msgs::handshake::Random;
8use crate::msgs::message::{Message, MessagePayload, PlainMessage};
9use crate::suites::{ExtractedSecrets, PartiallyExtractedSecrets};
10use crate::vecbuf::ChunkVecBuffer;
11
12use alloc::boxed::Box;
13use core::fmt::Debug;
14use core::mem;
15use core::ops::{Deref, DerefMut};
16use std::io;
17
18/// A client or server connection.
19#[derive(Debug)]
20pub enum Connection {
21    /// A client connection
22    Client(crate::client::ClientConnection),
23    /// A server connection
24    Server(crate::server::ServerConnection),
25}
26
27impl Connection {
28    /// Read TLS content from `rd`.
29    ///
30    /// See [`ConnectionCommon::read_tls()`] for more information.
31    pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
32        match self {
33            Self::Client(conn) => conn.read_tls(rd),
34            Self::Server(conn) => conn.read_tls(rd),
35        }
36    }
37
38    /// Writes TLS messages to `wr`.
39    ///
40    /// See [`ConnectionCommon::write_tls()`] for more information.
41    pub fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
42        self.sendable_tls.write_to(wr)
43    }
44
45    /// Returns an object that allows reading plaintext.
46    pub fn reader(&mut self) -> Reader {
47        match self {
48            Self::Client(conn) => conn.reader(),
49            Self::Server(conn) => conn.reader(),
50        }
51    }
52
53    /// Returns an object that allows writing plaintext.
54    pub fn writer(&mut self) -> Writer {
55        match self {
56            Self::Client(conn) => Writer::new(&mut **conn),
57            Self::Server(conn) => Writer::new(&mut **conn),
58        }
59    }
60
61    /// Processes any new packets read by a previous call to [`Connection::read_tls`].
62    ///
63    /// See [`ConnectionCommon::process_new_packets()`] for more information.
64    pub fn process_new_packets(&mut self) -> Result<IoState, Error> {
65        match self {
66            Self::Client(conn) => conn.process_new_packets(),
67            Self::Server(conn) => conn.process_new_packets(),
68        }
69    }
70
71    /// Derives key material from the agreed connection secrets.
72    ///
73    /// See [`ConnectionCommon::export_keying_material()`] for more information.
74    pub fn export_keying_material<T: AsMut<[u8]>>(
75        &self,
76        output: T,
77        label: &[u8],
78        context: Option<&[u8]>,
79    ) -> Result<T, Error> {
80        match self {
81            Self::Client(conn) => conn.export_keying_material(output, label, context),
82            Self::Server(conn) => conn.export_keying_material(output, label, context),
83        }
84    }
85
86    /// This function uses `io` to complete any outstanding IO for this connection.
87    ///
88    /// See [`ConnectionCommon::complete_io()`] for more information.
89    pub fn complete_io<T>(&mut self, io: &mut T) -> Result<(usize, usize), io::Error>
90    where
91        Self: Sized,
92        T: io::Read + io::Write,
93    {
94        match self {
95            Self::Client(conn) => conn.complete_io(io),
96            Self::Server(conn) => conn.complete_io(io),
97        }
98    }
99
100    /// Extract secrets, so they can be used when configuring kTLS, for example.
101    /// Should be used with care as it exposes secret key material.
102    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
103        match self {
104            Self::Client(client) => client.dangerous_extract_secrets(),
105            Self::Server(server) => server.dangerous_extract_secrets(),
106        }
107    }
108}
109
110impl Deref for Connection {
111    type Target = CommonState;
112
113    fn deref(&self) -> &Self::Target {
114        match self {
115            Self::Client(conn) => &conn.core.common_state,
116            Self::Server(conn) => &conn.core.common_state,
117        }
118    }
119}
120
121impl DerefMut for Connection {
122    fn deref_mut(&mut self) -> &mut Self::Target {
123        match self {
124            Self::Client(conn) => &mut conn.core.common_state,
125            Self::Server(conn) => &mut conn.core.common_state,
126        }
127    }
128}
129
130/// A structure that implements [`std::io::Read`] for reading plaintext.
131pub struct Reader<'a> {
132    received_plaintext: &'a mut ChunkVecBuffer,
133    peer_cleanly_closed: bool,
134    has_seen_eof: bool,
135}
136
137impl<'a> io::Read for Reader<'a> {
138    /// Obtain plaintext data received from the peer over this TLS connection.
139    ///
140    /// If the peer closes the TLS session cleanly, this returns `Ok(0)`  once all
141    /// the pending data has been read. No further data can be received on that
142    /// connection, so the underlying TCP connection should be half-closed too.
143    ///
144    /// If the peer closes the TLS session uncleanly (a TCP EOF without sending a
145    /// `close_notify` alert) this function returns a `std::io::Error` of type
146    /// `ErrorKind::UnexpectedEof` once any pending data has been read.
147    ///
148    /// Note that support for `close_notify` varies in peer TLS libraries: many do not
149    /// support it and uncleanly close the TCP connection (this might be
150    /// vulnerable to truncation attacks depending on the application protocol).
151    /// This means applications using rustls must both handle EOF
152    /// from this function, *and* unexpected EOF of the underlying TCP connection.
153    ///
154    /// If there are no bytes to read, this returns `Err(ErrorKind::WouldBlock.into())`.
155    ///
156    /// You may learn the number of bytes available at any time by inspecting
157    /// the return of [`Connection::process_new_packets`].
158    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
159        let len = self.received_plaintext.read(buf)?;
160
161        if len == 0 && !buf.is_empty() {
162            // No bytes available:
163            match (self.peer_cleanly_closed, self.has_seen_eof) {
164                // cleanly closed; don't care about TCP EOF: express this as Ok(0)
165                (true, _) => {}
166                // unclean closure
167                (false, true) => {
168                    return Err(io::Error::new(
169                        io::ErrorKind::UnexpectedEof,
170                        UNEXPECTED_EOF_MESSAGE,
171                    ))
172                }
173                // connection still going, but needs more data: signal `WouldBlock` so that
174                // the caller knows this
175                (false, false) => return Err(io::ErrorKind::WouldBlock.into()),
176            }
177        }
178
179        Ok(len)
180    }
181
182    /// Obtain plaintext data received from the peer over this TLS connection.
183    ///
184    /// If the peer closes the TLS session, this returns `Ok(())` without filling
185    /// any more of the buffer once all the pending data has been read. No further
186    /// data can be received on that connection, so the underlying TCP connection
187    /// should be half-closed too.
188    ///
189    /// If the peer closes the TLS session uncleanly (a TCP EOF without sending a
190    /// `close_notify` alert) this function returns a `std::io::Error` of type
191    /// `ErrorKind::UnexpectedEof` once any pending data has been read.
192    ///
193    /// Note that support for `close_notify` varies in peer TLS libraries: many do not
194    /// support it and uncleanly close the TCP connection (this might be
195    /// vulnerable to truncation attacks depending on the application protocol).
196    /// This means applications using rustls must both handle EOF
197    /// from this function, *and* unexpected EOF of the underlying TCP connection.
198    ///
199    /// If there are no bytes to read, this returns `Err(ErrorKind::WouldBlock.into())`.
200    ///
201    /// You may learn the number of bytes available at any time by inspecting
202    /// the return of [`Connection::process_new_packets`].
203    #[cfg(read_buf)]
204    fn read_buf(&mut self, mut cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> {
205        let before = cursor.written();
206        self.received_plaintext
207            .read_buf(cursor.reborrow())?;
208        let len = cursor.written() - before;
209
210        if len == 0 && cursor.capacity() > 0 {
211            // No bytes available:
212            match (self.peer_cleanly_closed, self.has_seen_eof) {
213                // cleanly closed; don't care about TCP EOF: express this as Ok(0)
214                (true, _) => {}
215                // unclean closure
216                (false, true) => {
217                    return Err(io::Error::new(
218                        io::ErrorKind::UnexpectedEof,
219                        UNEXPECTED_EOF_MESSAGE,
220                    ));
221                }
222                // connection still going, but need more data: signal `WouldBlock` so that
223                // the caller knows this
224                (false, false) => return Err(io::ErrorKind::WouldBlock.into()),
225            }
226        }
227
228        Ok(())
229    }
230}
231
232/// Internal trait implemented by the [`ServerConnection`]/[`ClientConnection`]
233/// allowing them to be the subject of a [`Writer`].
234///
235/// [`ServerConnection`]: crate::ServerConnection
236/// [`ClientConnection`]: crate::ClientConnection
237pub(crate) trait PlaintextSink {
238    fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
239    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize>;
240    fn flush(&mut self) -> io::Result<()>;
241}
242
243impl<T> PlaintextSink for ConnectionCommon<T> {
244    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
245        Ok(self.send_some_plaintext(buf))
246    }
247
248    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
249        let mut sz = 0;
250        for buf in bufs {
251            sz += self.send_some_plaintext(buf);
252        }
253        Ok(sz)
254    }
255
256    fn flush(&mut self) -> io::Result<()> {
257        Ok(())
258    }
259}
260
261/// A structure that implements [`std::io::Write`] for writing plaintext.
262pub struct Writer<'a> {
263    sink: &'a mut dyn PlaintextSink,
264}
265
266impl<'a> Writer<'a> {
267    /// Create a new Writer.
268    ///
269    /// This is not an external interface.  Get one of these objects
270    /// from [`Connection::writer`].
271    pub(crate) fn new(sink: &'a mut dyn PlaintextSink) -> Writer<'a> {
272        Writer { sink }
273    }
274}
275
276impl<'a> io::Write for Writer<'a> {
277    /// Send the plaintext `buf` to the peer, encrypting
278    /// and authenticating it.  Once this function succeeds
279    /// you should call [`Connection::write_tls`] which will output the
280    /// corresponding TLS records.
281    ///
282    /// This function buffers plaintext sent before the
283    /// TLS handshake completes, and sends it as soon
284    /// as it can.  See [`CommonState::set_buffer_limit`] to control
285    /// the size of this buffer.
286    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
287        self.sink.write(buf)
288    }
289
290    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
291        self.sink.write_vectored(bufs)
292    }
293
294    fn flush(&mut self) -> io::Result<()> {
295        self.sink.flush()
296    }
297}
298
299#[derive(Debug)]
300pub(crate) struct ConnectionRandoms {
301    pub(crate) client: [u8; 32],
302    pub(crate) server: [u8; 32],
303}
304
305/// How many ChangeCipherSpec messages we accept and drop in TLS1.3 handshakes.
306/// The spec says 1, but implementations (namely the boringssl test suite) get
307/// this wrong.  BoringSSL itself accepts up to 32.
308static TLS13_MAX_DROPPED_CCS: u8 = 2u8;
309
310impl ConnectionRandoms {
311    pub(crate) fn new(client: Random, server: Random) -> Self {
312        Self {
313            client: client.0,
314            server: server.0,
315        }
316    }
317}
318
319// --- Common (to client and server) connection functions ---
320
321fn is_valid_ccs(msg: &PlainMessage) -> bool {
322    // We passthrough ChangeCipherSpec messages in the deframer without decrypting them.
323    // Note: this is prior to the record layer, so is unencrypted. See
324    // third paragraph of section 5 in RFC8446.
325    msg.typ == ContentType::ChangeCipherSpec && msg.payload.0 == [0x01]
326}
327
328/// Interface shared by client and server connections.
329pub struct ConnectionCommon<Data> {
330    pub(crate) core: ConnectionCore<Data>,
331}
332
333impl<Data> ConnectionCommon<Data> {
334    /// Returns an object that allows reading plaintext.
335    pub fn reader(&mut self) -> Reader {
336        let common = &mut self.core.common_state;
337        Reader {
338            received_plaintext: &mut common.received_plaintext,
339            // Are we done? i.e., have we processed all received messages, and received a
340            // close_notify to indicate that no new messages will arrive?
341            peer_cleanly_closed: common.has_received_close_notify
342                && !self.core.message_deframer.has_pending(),
343            has_seen_eof: common.has_seen_eof,
344        }
345    }
346
347    /// Returns an object that allows writing plaintext.
348    pub fn writer(&mut self) -> Writer {
349        Writer::new(self)
350    }
351
352    /// This function uses `io` to complete any outstanding IO for
353    /// this connection.
354    ///
355    /// This is a convenience function which solely uses other parts
356    /// of the public API.
357    ///
358    /// What this means depends on the connection  state:
359    ///
360    /// - If the connection [`is_handshaking`], then IO is performed until
361    ///   the handshake is complete.
362    /// - Otherwise, if [`wants_write`] is true, [`write_tls`] is invoked
363    ///   until it is all written.
364    /// - Otherwise, if [`wants_read`] is true, [`read_tls`] is invoked
365    ///   once.
366    ///
367    /// The return value is the number of bytes read from and written
368    /// to `io`, respectively.
369    ///
370    /// This function will block if `io` blocks.
371    ///
372    /// Errors from TLS record handling (i.e., from [`process_new_packets`])
373    /// are wrapped in an `io::ErrorKind::InvalidData`-kind error.
374    ///
375    /// [`is_handshaking`]: CommonState::is_handshaking
376    /// [`wants_read`]: CommonState::wants_read
377    /// [`wants_write`]: CommonState::wants_write
378    /// [`write_tls`]: ConnectionCommon::write_tls
379    /// [`read_tls`]: ConnectionCommon::read_tls
380    /// [`process_new_packets`]: ConnectionCommon::process_new_packets
381    pub fn complete_io<T>(&mut self, io: &mut T) -> Result<(usize, usize), io::Error>
382    where
383        Self: Sized,
384        T: io::Read + io::Write,
385    {
386        let mut eof = false;
387        let mut wrlen = 0;
388        let mut rdlen = 0;
389
390        loop {
391            let until_handshaked = self.is_handshaking();
392
393            while self.wants_write() {
394                wrlen += self.write_tls(io)?;
395            }
396            io.flush()?;
397
398            if !until_handshaked && wrlen > 0 {
399                return Ok((rdlen, wrlen));
400            }
401
402            while !eof && self.wants_read() {
403                let read_size = match self.read_tls(io) {
404                    Ok(0) => {
405                        eof = true;
406                        Some(0)
407                    }
408                    Ok(n) => {
409                        rdlen += n;
410                        Some(n)
411                    }
412                    Err(ref err) if err.kind() == io::ErrorKind::Interrupted => None, // nothing to do
413                    Err(err) => return Err(err),
414                };
415                if read_size.is_some() {
416                    break;
417                }
418            }
419
420            match self.process_new_packets() {
421                Ok(_) => {}
422                Err(e) => {
423                    // In case we have an alert to send describing this error,
424                    // try a last-gasp write -- but don't predate the primary
425                    // error.
426                    let _ignored = self.write_tls(io);
427                    let _ignored = io.flush();
428
429                    return Err(io::Error::new(io::ErrorKind::InvalidData, e));
430                }
431            };
432
433            // if we're doing IO until handshaked, and we believe we've finished handshaking,
434            // but process_new_packets() has queued TLS data to send, loop around again to write
435            // the queued messages.
436            if until_handshaked && !self.is_handshaking() && self.wants_write() {
437                continue;
438            }
439
440            match (eof, until_handshaked, self.is_handshaking()) {
441                (_, true, false) => return Ok((rdlen, wrlen)),
442                (_, false, _) => return Ok((rdlen, wrlen)),
443                (true, true, true) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
444                (..) => {}
445            }
446        }
447    }
448
449    /// Extract the first handshake message.
450    ///
451    /// This is a shortcut to the `process_new_packets()` -> `process_msg()` ->
452    /// `process_handshake_messages()` path, specialized for the first handshake message.
453    pub(crate) fn first_handshake_message(&mut self) -> Result<Option<Message>, Error> {
454        match self
455            .core
456            .deframe()?
457            .map(Message::try_from)
458        {
459            Some(Ok(msg)) => Ok(Some(msg)),
460            Some(Err(err)) => Err(self.send_fatal_alert(AlertDescription::DecodeError, err)),
461            None => Ok(None),
462        }
463    }
464
465    pub(crate) fn replace_state(&mut self, new: Box<dyn State<Data>>) {
466        self.core.state = Ok(new);
467    }
468
469    /// Processes any new packets read by a previous call to
470    /// [`Connection::read_tls`].
471    ///
472    /// Errors from this function relate to TLS protocol errors, and
473    /// are fatal to the connection.  Future calls after an error will do
474    /// no new work and will return the same error. After an error is
475    /// received from [`process_new_packets`], you should not call [`read_tls`]
476    /// any more (it will fill up buffers to no purpose). However, you
477    /// may call the other methods on the connection, including `write`,
478    /// `send_close_notify`, and `write_tls`. Most likely you will want to
479    /// call `write_tls` to send any alerts queued by the error and then
480    /// close the underlying connection.
481    ///
482    /// Success from this function comes with some sundry state data
483    /// about the connection.
484    ///
485    /// [`read_tls`]: Connection::read_tls
486    /// [`process_new_packets`]: Connection::process_new_packets
487    #[inline]
488    pub fn process_new_packets(&mut self) -> Result<IoState, Error> {
489        self.core.process_new_packets()
490    }
491
492    /// Read TLS content from `rd` into the internal buffer.
493    ///
494    /// Due to the internal buffering, `rd` can supply TLS messages in arbitrary-sized chunks (like
495    /// a socket or pipe might).
496    ///
497    /// You should call [`process_new_packets()`] each time a call to this function succeeds in order
498    /// to empty the incoming TLS data buffer.
499    ///
500    /// This function returns `Ok(0)` when the underlying `rd` does so. This typically happens when
501    /// a socket is cleanly closed, or a file is at EOF. Errors may result from the IO done through
502    /// `rd`; additionally, errors of `ErrorKind::Other` are emitted to signal backpressure:
503    ///
504    /// * In order to empty the incoming TLS data buffer, you should call [`process_new_packets()`]
505    ///   each time a call to this function succeeds.
506    /// * In order to empty the incoming plaintext data buffer, you should empty it through
507    ///   the [`reader()`] after the call to [`process_new_packets()`].
508    ///
509    /// [`process_new_packets()`]: ConnectionCommon::process_new_packets
510    /// [`reader()`]: ConnectionCommon::reader
511    pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
512        if self.received_plaintext.is_full() {
513            return Err(io::Error::new(
514                io::ErrorKind::Other,
515                "received plaintext buffer full",
516            ));
517        }
518
519        let res = self.core.message_deframer.read(rd);
520        if let Ok(0) = res {
521            self.has_seen_eof = true;
522        }
523        res
524    }
525
526    /// Writes TLS messages to `wr`.
527    ///
528    /// On success, this function returns `Ok(n)` where `n` is a number of bytes written to `wr`
529    /// (after encoding and encryption).
530    ///
531    /// After this function returns, the connection buffer may not yet be fully flushed. The
532    /// [`CommonState::wants_write`] function can be used to check if the output buffer is empty.
533    pub fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
534        self.sendable_tls.write_to(wr)
535    }
536
537    /// Derives key material from the agreed connection secrets.
538    ///
539    /// This function fills in `output` with `output.len()` bytes of key
540    /// material derived from the master session secret using `label`
541    /// and `context` for diversification. Ownership of the buffer is taken
542    /// by the function and returned via the Ok result to ensure no key
543    /// material leaks if the function fails.
544    ///
545    /// See RFC5705 for more details on what this does and is for.
546    ///
547    /// For TLS1.3 connections, this function does not use the
548    /// "early" exporter at any point.
549    ///
550    /// This function fails if called prior to the handshake completing;
551    /// check with [`CommonState::is_handshaking`] first.
552    ///
553    /// This function fails if `output.len()` is zero.
554    #[inline]
555    pub fn export_keying_material<T: AsMut<[u8]>>(
556        &self,
557        output: T,
558        label: &[u8],
559        context: Option<&[u8]>,
560    ) -> Result<T, Error> {
561        self.core
562            .export_keying_material(output, label, context)
563    }
564
565    /// Extract secrets, so they can be used when configuring kTLS, for example.
566    /// Should be used with care as it exposes secret key material.
567    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
568        if !self.enable_secret_extraction {
569            return Err(Error::General("Secret extraction is disabled".into()));
570        }
571
572        let st = self.core.state?;
573
574        let record_layer = self.core.common_state.record_layer;
575        let PartiallyExtractedSecrets { tx, rx } = st.extract_secrets()?;
576        Ok(ExtractedSecrets {
577            tx: (record_layer.write_seq(), tx),
578            rx: (record_layer.read_seq(), rx),
579        })
580    }
581}
582
583impl<'a, Data> From<&'a mut ConnectionCommon<Data>> for Context<'a, Data> {
584    fn from(conn: &'a mut ConnectionCommon<Data>) -> Self {
585        Self {
586            common: &mut conn.core.common_state,
587            data: &mut conn.core.data,
588        }
589    }
590}
591
592impl<T> Deref for ConnectionCommon<T> {
593    type Target = CommonState;
594
595    fn deref(&self) -> &Self::Target {
596        &self.core.common_state
597    }
598}
599
600impl<T> DerefMut for ConnectionCommon<T> {
601    fn deref_mut(&mut self) -> &mut Self::Target {
602        &mut self.core.common_state
603    }
604}
605
606impl<Data> From<ConnectionCore<Data>> for ConnectionCommon<Data> {
607    fn from(core: ConnectionCore<Data>) -> Self {
608        Self { core }
609    }
610}
611
612pub(crate) struct ConnectionCore<Data> {
613    pub(crate) state: Result<Box<dyn State<Data>>, Error>,
614    pub(crate) data: Data,
615    pub(crate) common_state: CommonState,
616    pub(crate) message_deframer: MessageDeframer,
617}
618
619impl<Data> ConnectionCore<Data> {
620    pub(crate) fn new(state: Box<dyn State<Data>>, data: Data, common_state: CommonState) -> Self {
621        Self {
622            state: Ok(state),
623            data,
624            common_state,
625            message_deframer: MessageDeframer::default(),
626        }
627    }
628
629    pub(crate) fn process_new_packets(&mut self) -> Result<IoState, Error> {
630        let mut state = match mem::replace(&mut self.state, Err(Error::HandshakeNotComplete)) {
631            Ok(state) => state,
632            Err(e) => {
633                self.state = Err(e.clone());
634                return Err(e);
635            }
636        };
637
638        while let Some(msg) = self.deframe()? {
639            match self.process_msg(msg, state) {
640                Ok(new) => state = new,
641                Err(e) => {
642                    self.state = Err(e.clone());
643                    return Err(e);
644                }
645            }
646        }
647
648        self.state = Ok(state);
649        Ok(self.common_state.current_io_state())
650    }
651
652    /// Pull a message out of the deframer and send any messages that need to be sent as a result.
653    fn deframe(&mut self) -> Result<Option<PlainMessage>, Error> {
654        match self.message_deframer.pop(
655            &mut self.common_state.record_layer,
656            self.common_state.negotiated_version,
657        ) {
658            Ok(Some(Deframed {
659                want_close_before_decrypt,
660                aligned,
661                trial_decryption_finished,
662                message,
663            })) => {
664                if want_close_before_decrypt {
665                    self.common_state.send_close_notify();
666                }
667
668                if trial_decryption_finished {
669                    self.common_state
670                        .record_layer
671                        .finish_trial_decryption();
672                }
673
674                self.common_state.aligned_handshake = aligned;
675                Ok(Some(message))
676            }
677            Ok(None) => Ok(None),
678            Err(err @ Error::InvalidMessage(_)) => {
679                if self.common_state.is_quic() {
680                    self.common_state.quic.alert = Some(AlertDescription::DecodeError);
681                }
682
683                Err(if !self.common_state.is_quic() {
684                    self.common_state
685                        .send_fatal_alert(AlertDescription::DecodeError, err)
686                } else {
687                    err
688                })
689            }
690            Err(err @ Error::PeerSentOversizedRecord) => Err(self
691                .common_state
692                .send_fatal_alert(AlertDescription::RecordOverflow, err)),
693            Err(err @ Error::DecryptError) => Err(self
694                .common_state
695                .send_fatal_alert(AlertDescription::BadRecordMac, err)),
696            Err(e) => Err(e),
697        }
698    }
699
700    fn process_msg(
701        &mut self,
702        msg: PlainMessage,
703        state: Box<dyn State<Data>>,
704    ) -> Result<Box<dyn State<Data>>, Error> {
705        // Drop CCS messages during handshake in TLS1.3
706        if msg.typ == ContentType::ChangeCipherSpec
707            && !self
708                .common_state
709                .may_receive_application_data
710            && self.common_state.is_tls13()
711        {
712            if !is_valid_ccs(&msg)
713                || self.common_state.received_middlebox_ccs > TLS13_MAX_DROPPED_CCS
714            {
715                // "An implementation which receives any other change_cipher_spec value or
716                //  which receives a protected change_cipher_spec record MUST abort the
717                //  handshake with an "unexpected_message" alert."
718                return Err(self.common_state.send_fatal_alert(
719                    AlertDescription::UnexpectedMessage,
720                    PeerMisbehaved::IllegalMiddleboxChangeCipherSpec,
721                ));
722            } else {
723                self.common_state.received_middlebox_ccs += 1;
724                trace!("Dropping CCS");
725                return Ok(state);
726            }
727        }
728
729        // Now we can fully parse the message payload.
730        let msg = match Message::try_from(msg) {
731            Ok(msg) => msg,
732            Err(err) => {
733                return Err(self
734                    .common_state
735                    .send_fatal_alert(AlertDescription::DecodeError, err));
736            }
737        };
738
739        // For alerts, we have separate logic.
740        if let MessagePayload::Alert(alert) = &msg.payload {
741            self.common_state.process_alert(alert)?;
742            return Ok(state);
743        }
744
745        self.common_state
746            .process_main_protocol(msg, state, &mut self.data)
747    }
748
749    pub(crate) fn export_keying_material<T: AsMut<[u8]>>(
750        &self,
751        mut output: T,
752        label: &[u8],
753        context: Option<&[u8]>,
754    ) -> Result<T, Error> {
755        if output.as_mut().is_empty() {
756            return Err(Error::General(
757                "export_keying_material with zero-length output".into(),
758            ));
759        }
760
761        match self.state.as_ref() {
762            Ok(st) => st
763                .export_keying_material(output.as_mut(), label, context)
764                .map(|_| output),
765            Err(e) => Err(e.clone()),
766        }
767    }
768}
769
770/// Data specific to the peer's side (client or server).
771pub trait SideData: Debug {}
772
773const UNEXPECTED_EOF_MESSAGE: &str = "peer closed connection without sending TLS close_notify: \
774https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof";