tlspuffin/tls/rustls/msgs/
deframer.rs

1use std::collections::VecDeque;
2use std::io;
3
4use puffin::codec;
5
6use crate::tls::rustls::msgs::message::{MessageError, OpaqueMessage};
7
8/// This deframer works to reconstruct TLS messages
9/// from arbitrary-sized reads, buffering as necessary.
10/// The input is `read()`, the output is the `frames` deque.
11pub struct MessageDeframer {
12    /// Completed frames for output.
13    pub frames: VecDeque<OpaqueMessage>,
14
15    /// Set to true if the peer is not talking TLS, but some other
16    /// protocol.  The caller should abort the connection, because
17    /// the deframer cannot recover.
18    pub desynced: bool,
19
20    /// A fixed-size buffer containing the currently-accumulating
21    /// TLS message.
22    buf: Box<[u8; OpaqueMessage::MAX_WIRE_SIZE]>,
23
24    /// What size prefix of `buf` is used.
25    used: usize,
26}
27
28enum BufferContents {
29    /// Contains an invalid message as a header.
30    Invalid,
31
32    /// Might contain a valid message if we receive more.
33    /// Perhaps totally empty!
34    Partial,
35
36    /// Contains a valid frame as a prefix.
37    Valid,
38}
39
40impl Default for MessageDeframer {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl MessageDeframer {
47    pub fn new() -> Self {
48        Self {
49            frames: VecDeque::new(),
50            desynced: false,
51            buf: Box::new([0u8; OpaqueMessage::MAX_WIRE_SIZE]),
52            used: 0,
53        }
54    }
55
56    /// Read some bytes from `rd`, and add them to our internal
57    /// buffer.  If this means our internal buffer contains
58    /// full messages, decode them all.
59    pub fn read(&mut self, rd: &mut dyn io::Read) -> io::Result<usize> {
60        // Try to do the largest reads possible.  Note that if
61        // we get a message with a length field out of range here,
62        // we do a zero length read.  That looks like an EOF to
63        // the next layer up, which is fine.
64        debug_assert!(self.used <= OpaqueMessage::MAX_WIRE_SIZE);
65        let new_bytes = rd.read(&mut self.buf[self.used..])?;
66
67        self.used += new_bytes;
68
69        loop {
70            match self.try_deframe_one() {
71                BufferContents::Invalid => {
72                    self.desynced = true;
73                    break;
74                }
75                BufferContents::Valid => continue,
76                BufferContents::Partial => break,
77            }
78        }
79
80        Ok(new_bytes)
81    }
82
83    /// Returns true if we have messages for the caller
84    /// to process, either whole messages in our output
85    /// queue or partial messages in our buffer.
86    pub fn has_pending(&self) -> bool {
87        !self.frames.is_empty() || self.used > 0
88    }
89
90    /// Does our `buf` contain a full message?  It does if it is big enough to
91    /// contain a header, and that header has a length which falls within `buf`.
92    /// If so, deframe it and place the message onto the frames output queue.
93    fn try_deframe_one(&mut self) -> BufferContents {
94        // Try to decode a message off the front of buf.
95        let mut rd = codec::Reader::init(&self.buf[..self.used]);
96
97        match OpaqueMessage::read(&mut rd) {
98            Ok(m) => {
99                let used = rd.used();
100                self.frames.push_back(m);
101                self.buf_consume(used);
102                BufferContents::Valid
103            }
104            Err(MessageError::TooShortForHeader) | Err(MessageError::TooShortForLength) => {
105                BufferContents::Partial
106            }
107            Err(_) => BufferContents::Invalid,
108        }
109    }
110
111    #[allow(clippy::comparison_chain)]
112    fn buf_consume(&mut self, taken: usize) {
113        if taken < self.used {
114            /* Before:
115             * +----------+----------+----------+
116             * | taken    | pending  |xxxxxxxxxx|
117             * +----------+----------+----------+
118             * 0          ^ taken    ^ self.used
119             *
120             * After:
121             * +----------+----------+----------+
122             * | pending  |xxxxxxxxxxxxxxxxxxxxx|
123             * +----------+----------+----------+
124             * 0          ^ self.used
125             */
126
127            self.buf.copy_within(taken..self.used, 0);
128            self.used -= taken;
129        } else if taken == self.used {
130            self.used = 0;
131        }
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use std::io;
138
139    use super::MessageDeframer;
140    use crate::tls::rustls::msgs;
141    use crate::tls::rustls::msgs::message::Message;
142
143    const FIRST_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-test.1.bin");
144    const SECOND_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-test.2.bin");
145
146    const EMPTY_APPLICATIONDATA_MESSAGE: &[u8] =
147        include_bytes!("../testdata/deframer-empty-applicationdata.bin");
148
149    #[allow(dead_code)]
150    const INVALID_EMPTY_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-invalid-empty.bin");
151    #[allow(dead_code)]
152    const INVALID_CONTENTTYPE_MESSAGE: &[u8] =
153        include_bytes!("../testdata/deframer-invalid-contenttype.bin");
154    #[allow(dead_code)]
155    const INVALID_VERSION_MESSAGE: &[u8] =
156        include_bytes!("../testdata/deframer-invalid-version.bin");
157    #[allow(dead_code)]
158    const INVALID_LENGTH_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-invalid-length.bin");
159
160    struct ByteRead<'a> {
161        buf: &'a [u8],
162        offs: usize,
163    }
164
165    impl<'a> ByteRead<'a> {
166        fn new(bytes: &'a [u8]) -> Self {
167            ByteRead {
168                buf: bytes,
169                offs: 0,
170            }
171        }
172    }
173
174    impl<'a> io::Read for ByteRead<'a> {
175        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
176            let mut len = 0;
177
178            while len < buf.len() && len < self.buf.len() - self.offs {
179                buf[len] = self.buf[self.offs + len];
180                len += 1;
181            }
182
183            self.offs += len;
184
185            Ok(len)
186        }
187    }
188
189    fn input_bytes(d: &mut MessageDeframer, bytes: &[u8]) -> io::Result<usize> {
190        let mut rd = ByteRead::new(bytes);
191        d.read(&mut rd)
192    }
193
194    fn input_bytes_concat(
195        d: &mut MessageDeframer,
196        bytes1: &[u8],
197        bytes2: &[u8],
198    ) -> io::Result<usize> {
199        let mut bytes = vec![0u8; bytes1.len() + bytes2.len()];
200        bytes[..bytes1.len()].clone_from_slice(bytes1);
201        bytes[bytes1.len()..].clone_from_slice(bytes2);
202        let mut rd = ByteRead::new(&bytes);
203        d.read(&mut rd)
204    }
205
206    struct ErrorRead {
207        error: Option<io::Error>,
208    }
209
210    impl ErrorRead {
211        fn new(error: io::Error) -> Self {
212            Self { error: Some(error) }
213        }
214    }
215
216    impl io::Read for ErrorRead {
217        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
218            for (i, b) in buf.iter_mut().enumerate() {
219                *b = i as u8;
220            }
221
222            let error = self.error.take().unwrap();
223            Err(error)
224        }
225    }
226
227    fn input_error(d: &mut MessageDeframer) {
228        let error = io::Error::from(io::ErrorKind::TimedOut);
229        let mut rd = ErrorRead::new(error);
230        d.read(&mut rd).expect_err("error not propagated");
231    }
232
233    fn input_whole_incremental(d: &mut MessageDeframer, bytes: &[u8]) {
234        let frames_before = d.frames.len();
235
236        for i in 0..bytes.len() {
237            assert_len(1, input_bytes(d, &bytes[i..i + 1]));
238            assert!(d.has_pending());
239
240            if i < bytes.len() - 1 {
241                assert_eq!(frames_before, d.frames.len());
242            }
243        }
244
245        assert_eq!(frames_before + 1, d.frames.len());
246    }
247
248    fn assert_len(want: usize, got: io::Result<usize>) {
249        if let Ok(gotval) = got {
250            assert_eq!(gotval, want);
251        } else {
252            panic!("read failed, expected {:?} bytes", want);
253        }
254    }
255
256    fn pop_first(d: &mut MessageDeframer) {
257        let m = d.frames.pop_front().unwrap();
258        assert_eq!(m.typ, msgs::enums::ContentType::Handshake);
259        Message::try_from(m.into_plain_message()).unwrap();
260    }
261
262    fn pop_second(d: &mut MessageDeframer) {
263        let m = d.frames.pop_front().unwrap();
264        assert_eq!(m.typ, msgs::enums::ContentType::Alert);
265        Message::try_from(m.into_plain_message()).unwrap();
266    }
267
268    #[test_log::test]
269    fn check_incremental() {
270        let mut d = MessageDeframer::new();
271        assert!(!d.has_pending());
272        input_whole_incremental(&mut d, FIRST_MESSAGE);
273        assert!(d.has_pending());
274        assert_eq!(1, d.frames.len());
275        pop_first(&mut d);
276        assert!(!d.has_pending());
277        assert!(!d.desynced);
278    }
279
280    #[test_log::test]
281    fn check_incremental_2() {
282        let mut d = MessageDeframer::new();
283        assert!(!d.has_pending());
284        input_whole_incremental(&mut d, FIRST_MESSAGE);
285        assert!(d.has_pending());
286        input_whole_incremental(&mut d, SECOND_MESSAGE);
287        assert!(d.has_pending());
288        assert_eq!(2, d.frames.len());
289        pop_first(&mut d);
290        assert!(d.has_pending());
291        pop_second(&mut d);
292        assert!(!d.has_pending());
293        assert!(!d.desynced);
294    }
295
296    #[test_log::test]
297    fn check_whole() {
298        let mut d = MessageDeframer::new();
299        assert!(!d.has_pending());
300        assert_len(FIRST_MESSAGE.len(), input_bytes(&mut d, FIRST_MESSAGE));
301        assert!(d.has_pending());
302        assert_eq!(d.frames.len(), 1);
303        pop_first(&mut d);
304        assert!(!d.has_pending());
305        assert!(!d.desynced);
306    }
307
308    #[test_log::test]
309    fn check_whole_2() {
310        let mut d = MessageDeframer::new();
311        assert!(!d.has_pending());
312        assert_len(FIRST_MESSAGE.len(), input_bytes(&mut d, FIRST_MESSAGE));
313        assert_len(SECOND_MESSAGE.len(), input_bytes(&mut d, SECOND_MESSAGE));
314        assert_eq!(d.frames.len(), 2);
315        pop_first(&mut d);
316        pop_second(&mut d);
317        assert!(!d.has_pending());
318        assert!(!d.desynced);
319    }
320
321    #[test_log::test]
322    fn test_two_in_one_read() {
323        let mut d = MessageDeframer::new();
324        assert!(!d.has_pending());
325        assert_len(
326            FIRST_MESSAGE.len() + SECOND_MESSAGE.len(),
327            input_bytes_concat(&mut d, FIRST_MESSAGE, SECOND_MESSAGE),
328        );
329        assert_eq!(d.frames.len(), 2);
330        pop_first(&mut d);
331        pop_second(&mut d);
332        assert!(!d.has_pending());
333        assert!(!d.desynced);
334    }
335
336    #[test_log::test]
337    fn test_two_in_one_read_shortest_first() {
338        let mut d = MessageDeframer::new();
339        assert!(!d.has_pending());
340        assert_len(
341            FIRST_MESSAGE.len() + SECOND_MESSAGE.len(),
342            input_bytes_concat(&mut d, SECOND_MESSAGE, FIRST_MESSAGE),
343        );
344        assert_eq!(d.frames.len(), 2);
345        pop_second(&mut d);
346        pop_first(&mut d);
347        assert!(!d.has_pending());
348        assert!(!d.desynced);
349    }
350
351    #[test_log::test]
352    fn test_incremental_with_nonfatal_read_error() {
353        let mut d = MessageDeframer::new();
354        assert_len(3, input_bytes(&mut d, &FIRST_MESSAGE[..3]));
355        input_error(&mut d);
356        assert_len(
357            FIRST_MESSAGE.len() - 3,
358            input_bytes(&mut d, &FIRST_MESSAGE[3..]),
359        );
360        assert_eq!(d.frames.len(), 1);
361        pop_first(&mut d);
362        assert!(!d.has_pending());
363        assert!(!d.desynced);
364    }
365
366    #[test_log::test]
367    #[cfg(feature = "enable-guards")]
368    fn test_invalid_contenttype_errors() {
369        let mut d = MessageDeframer::new();
370        assert_len(
371            INVALID_CONTENTTYPE_MESSAGE.len(),
372            input_bytes(&mut d, INVALID_CONTENTTYPE_MESSAGE),
373        );
374        assert!(d.desynced);
375    }
376
377    #[test_log::test]
378    #[cfg(feature = "enable-guards")]
379    fn test_invalid_version_errors() {
380        let mut d = MessageDeframer::new();
381        assert_len(
382            INVALID_VERSION_MESSAGE.len(),
383            input_bytes(&mut d, INVALID_VERSION_MESSAGE),
384        );
385        assert!(d.desynced);
386    }
387
388    #[test_log::test]
389    #[cfg(feature = "enable-guards")]
390    fn test_invalid_length_errors() {
391        let mut d = MessageDeframer::new();
392        assert_len(
393            INVALID_LENGTH_MESSAGE.len(),
394            input_bytes(&mut d, INVALID_LENGTH_MESSAGE),
395        );
396        assert!(d.desynced);
397    }
398
399    #[test_log::test]
400    fn test_empty_applicationdata() {
401        let mut d = MessageDeframer::new();
402        assert_len(
403            EMPTY_APPLICATIONDATA_MESSAGE.len(),
404            input_bytes(&mut d, EMPTY_APPLICATIONDATA_MESSAGE),
405        );
406        let m = d.frames.pop_front().unwrap();
407        assert_eq!(m.typ, msgs::enums::ContentType::ApplicationData);
408        assert_eq!(m.payload.0.len(), 0);
409        assert!(!d.has_pending());
410        assert!(!d.desynced);
411    }
412
413    #[test_log::test]
414    #[cfg(feature = "enable-guards")]
415    fn test_invalid_empty_errors() {
416        let mut d = MessageDeframer::new();
417        assert_len(
418            INVALID_EMPTY_MESSAGE.len(),
419            input_bytes(&mut d, INVALID_EMPTY_MESSAGE),
420        );
421        assert!(d.desynced);
422    }
423}