clia_rustls_mod/msgs/
codec.rs

1use alloc::vec::Vec;
2use core::fmt::Debug;
3use core::mem;
4
5use crate::error::InvalidMessage;
6
7/// Wrapper over a slice of bytes that allows reading chunks from
8/// with the current position state held using a cursor.
9///
10/// A new reader for a sub section of the the buffer can be created
11/// using the `sub` function or a section of a certain length can
12/// be obtained using the `take` function
13pub struct Reader<'a> {
14    /// The underlying buffer storing the readers content
15    buffer: &'a [u8],
16    /// Stores the current reading position for the buffer
17    cursor: usize,
18}
19
20impl<'a> Reader<'a> {
21    /// Creates a new Reader of the provided `bytes` slice with
22    /// the initial cursor position of zero.
23    pub fn init(bytes: &'a [u8]) -> Self {
24        Reader {
25            buffer: bytes,
26            cursor: 0,
27        }
28    }
29
30    /// Attempts to create a new Reader on a sub section of this
31    /// readers bytes by taking a slice of the provided `length`
32    /// will return None if there is not enough bytes
33    pub fn sub(&mut self, length: usize) -> Result<Self, InvalidMessage> {
34        match self.take(length) {
35            Some(bytes) => Ok(Reader::init(bytes)),
36            None => Err(InvalidMessage::MessageTooShort),
37        }
38    }
39
40    /// Borrows a slice of all the remaining bytes
41    /// that appear after the cursor position.
42    ///
43    /// Moves the cursor to the end of the buffer length.
44    pub fn rest(&mut self) -> &'a [u8] {
45        let rest = &self.buffer[self.cursor..];
46        self.cursor = self.buffer.len();
47        rest
48    }
49
50    /// Attempts to borrow a slice of bytes from the current
51    /// cursor position of `length` if there is not enough
52    /// bytes remaining after the cursor to take the length
53    /// then None is returned instead.
54    pub fn take(&mut self, length: usize) -> Option<&'a [u8]> {
55        if self.left() < length {
56            return None;
57        }
58        let current = self.cursor;
59        self.cursor += length;
60        Some(&self.buffer[current..current + length])
61    }
62
63    /// Used to check whether the reader has any content left
64    /// after the cursor (cursor has not reached end of buffer)
65    pub fn any_left(&self) -> bool {
66        self.cursor < self.buffer.len()
67    }
68
69    pub fn expect_empty(&self, name: &'static str) -> Result<(), InvalidMessage> {
70        match self.any_left() {
71            true => Err(InvalidMessage::TrailingData(name)),
72            false => Ok(()),
73        }
74    }
75
76    /// Returns the cursor position which is also the number
77    /// of bytes that have been read from the buffer.
78    pub fn used(&self) -> usize {
79        self.cursor
80    }
81
82    /// Returns the number of bytes that are still able to be
83    /// read (The number of remaining takes)
84    pub fn left(&self) -> usize {
85        self.buffer.len() - self.cursor
86    }
87}
88
89/// A version of [`Reader`] that operates on mutable slices
90pub(crate) struct ReaderMut<'a> {
91    /// The underlying buffer storing the readers content
92    buffer: &'a mut [u8],
93    used: usize,
94}
95
96impl<'a> ReaderMut<'a> {
97    pub(crate) fn init(bytes: &'a mut [u8]) -> Self {
98        Self {
99            buffer: bytes,
100            used: 0,
101        }
102    }
103
104    pub(crate) fn sub(&mut self, length: usize) -> Result<Self, InvalidMessage> {
105        match self.take(length) {
106            Some(bytes) => Ok(ReaderMut::init(bytes)),
107            None => Err(InvalidMessage::MessageTooShort),
108        }
109    }
110
111    pub(crate) fn rest(&mut self) -> &'a mut [u8] {
112        let rest = mem::take(&mut self.buffer);
113        self.used += rest.len();
114        rest
115    }
116
117    pub(crate) fn take(&mut self, length: usize) -> Option<&'a mut [u8]> {
118        if self.left() < length {
119            return None;
120        }
121        let (taken, rest) = mem::take(&mut self.buffer).split_at_mut(length);
122        self.used += taken.len();
123        self.buffer = rest;
124        Some(taken)
125    }
126
127    pub(crate) fn used(&self) -> usize {
128        self.used
129    }
130
131    pub(crate) fn left(&self) -> usize {
132        self.buffer.len()
133    }
134
135    pub(crate) fn as_reader<T>(&mut self, f: impl FnOnce(&mut Reader) -> T) -> T {
136        let mut r = Reader {
137            buffer: self.buffer,
138            cursor: 0,
139        };
140        let ret = f(&mut r);
141        let cursor = r.cursor;
142        self.used += cursor;
143        let (_used, rest) = mem::take(&mut self.buffer).split_at_mut(cursor);
144        self.buffer = rest;
145
146        ret
147    }
148}
149
150/// Trait for implementing encoding and decoding functionality
151/// on something.
152pub trait Codec<'a>: Debug + Sized {
153    /// Function for encoding itself by appending itself to
154    /// the provided vec of bytes.
155    fn encode(&self, bytes: &mut Vec<u8>);
156
157    /// Function for decoding itself from the provided reader
158    /// will return Some if the decoding was successful or
159    /// None if it was not.
160    fn read(_: &mut Reader<'a>) -> Result<Self, InvalidMessage>;
161
162    /// Convenience function for encoding the implementation
163    /// into a vec and returning it
164    fn get_encoding(&self) -> Vec<u8> {
165        let mut bytes = Vec::new();
166        self.encode(&mut bytes);
167        bytes
168    }
169
170    /// Function for wrapping a call to the read function in
171    /// a Reader for the slice of bytes provided
172    fn read_bytes(bytes: &'a [u8]) -> Result<Self, InvalidMessage> {
173        let mut reader = Reader::init(bytes);
174        Self::read(&mut reader)
175    }
176}
177
178impl Codec<'_> for u8 {
179    fn encode(&self, bytes: &mut Vec<u8>) {
180        bytes.push(*self);
181    }
182
183    fn read(r: &mut Reader) -> Result<Self, InvalidMessage> {
184        match r.take(1) {
185            Some(&[byte]) => Ok(byte),
186            _ => Err(InvalidMessage::MissingData("u8")),
187        }
188    }
189}
190
191pub(crate) fn put_u16(v: u16, out: &mut [u8]) {
192    let out: &mut [u8; 2] = (&mut out[..2]).try_into().unwrap();
193    *out = u16::to_be_bytes(v);
194}
195
196impl Codec<'_> for u16 {
197    fn encode(&self, bytes: &mut Vec<u8>) {
198        let mut b16 = [0u8; 2];
199        put_u16(*self, &mut b16);
200        bytes.extend_from_slice(&b16);
201    }
202
203    fn read(r: &mut Reader) -> Result<Self, InvalidMessage> {
204        match r.take(2) {
205            Some(&[b1, b2]) => Ok(Self::from_be_bytes([b1, b2])),
206            _ => Err(InvalidMessage::MissingData("u8")),
207        }
208    }
209}
210
211// Make a distinct type for u24, even though it's a u32 underneath
212#[allow(non_camel_case_types)]
213#[derive(Debug, Copy, Clone)]
214pub struct u24(pub u32);
215
216#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
217impl From<u24> for usize {
218    #[inline]
219    fn from(v: u24) -> Self {
220        v.0 as Self
221    }
222}
223
224impl Codec<'_> for u24 {
225    fn encode(&self, bytes: &mut Vec<u8>) {
226        let be_bytes = u32::to_be_bytes(self.0);
227        bytes.extend_from_slice(&be_bytes[1..]);
228    }
229
230    fn read(r: &mut Reader) -> Result<Self, InvalidMessage> {
231        match r.take(3) {
232            Some(&[a, b, c]) => Ok(Self(u32::from_be_bytes([0, a, b, c]))),
233            _ => Err(InvalidMessage::MissingData("u24")),
234        }
235    }
236}
237
238impl Codec<'_> for u32 {
239    fn encode(&self, bytes: &mut Vec<u8>) {
240        bytes.extend(Self::to_be_bytes(*self));
241    }
242
243    fn read(r: &mut Reader) -> Result<Self, InvalidMessage> {
244        match r.take(4) {
245            Some(&[a, b, c, d]) => Ok(Self::from_be_bytes([a, b, c, d])),
246            _ => Err(InvalidMessage::MissingData("u32")),
247        }
248    }
249}
250
251pub(crate) fn put_u64(v: u64, bytes: &mut [u8]) {
252    let bytes: &mut [u8; 8] = (&mut bytes[..8]).try_into().unwrap();
253    *bytes = u64::to_be_bytes(v);
254}
255
256impl Codec<'_> for u64 {
257    fn encode(&self, bytes: &mut Vec<u8>) {
258        let mut b64 = [0u8; 8];
259        put_u64(*self, &mut b64);
260        bytes.extend_from_slice(&b64);
261    }
262
263    fn read(r: &mut Reader) -> Result<Self, InvalidMessage> {
264        match r.take(8) {
265            Some(&[a, b, c, d, e, f, g, h]) => Ok(Self::from_be_bytes([a, b, c, d, e, f, g, h])),
266            _ => Err(InvalidMessage::MissingData("u64")),
267        }
268    }
269}
270
271/// Implement `Codec` for lists of elements that implement `TlsListElement`.
272///
273/// `TlsListElement` provides the size of the length prefix for the list.
274impl<'a, T: Codec<'a> + TlsListElement + Debug> Codec<'a> for Vec<T> {
275    fn encode(&self, bytes: &mut Vec<u8>) {
276        let nest = LengthPrefixedBuffer::new(T::SIZE_LEN, bytes);
277
278        for i in self {
279            i.encode(nest.buf);
280        }
281    }
282
283    fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> {
284        let len = match T::SIZE_LEN {
285            ListLength::U8 => usize::from(u8::read(r)?),
286            ListLength::U16 => usize::from(u16::read(r)?),
287            ListLength::U24 { max } => Ord::min(usize::from(u24::read(r)?), max),
288        };
289
290        let mut sub = r.sub(len)?;
291        let mut ret = Self::new();
292        while sub.any_left() {
293            ret.push(T::read(&mut sub)?);
294        }
295
296        Ok(ret)
297    }
298}
299
300/// A trait for types that can be encoded and decoded in a list.
301///
302/// This trait is used to implement `Codec` for `Vec<T>`. Lists in the TLS wire format are
303/// prefixed with a length, the size of which depends on the type of the list elements.
304/// As such, the `Codec` implementation for `Vec<T>` requires an implementation of this trait
305/// for its element type `T`.
306pub(crate) trait TlsListElement {
307    const SIZE_LEN: ListLength;
308}
309
310/// The length of the length prefix for a list.
311///
312/// The types that appear in lists are limited to three kinds of length prefixes:
313/// 1, 2, and 3 bytes. For the latter kind, we require a `TlsListElement` implementer
314/// to specify a maximum length.
315pub(crate) enum ListLength {
316    U8,
317    U16,
318    U24 { max: usize },
319}
320
321/// Tracks encoding a length-delimited structure in a single pass.
322pub(crate) struct LengthPrefixedBuffer<'a> {
323    pub(crate) buf: &'a mut Vec<u8>,
324    len_offset: usize,
325    size_len: ListLength,
326}
327
328impl<'a> LengthPrefixedBuffer<'a> {
329    /// Inserts a dummy length into `buf`, and remembers where it went.
330    ///
331    /// After this, the body of the length-delimited structure should be appended to `LengthPrefixedBuffer::buf`.
332    /// The length header is corrected in `LengthPrefixedBuffer::drop`.
333    pub(crate) fn new(size_len: ListLength, buf: &'a mut Vec<u8>) -> Self {
334        let len_offset = buf.len();
335        buf.extend(match size_len {
336            ListLength::U8 => &[0xff][..],
337            ListLength::U16 => &[0xff, 0xff],
338            ListLength::U24 { .. } => &[0xff, 0xff, 0xff],
339        });
340
341        Self {
342            buf,
343            len_offset,
344            size_len,
345        }
346    }
347}
348
349impl<'a> Drop for LengthPrefixedBuffer<'a> {
350    /// Goes back and corrects the length previously inserted at the start of the structure.
351    fn drop(&mut self) {
352        match self.size_len {
353            ListLength::U8 => {
354                let len = self.buf.len() - self.len_offset - 1;
355                debug_assert!(len <= 0xff);
356                self.buf[self.len_offset] = len as u8;
357            }
358            ListLength::U16 => {
359                let len = self.buf.len() - self.len_offset - 2;
360                debug_assert!(len <= 0xffff);
361                let out: &mut [u8; 2] = (&mut self.buf[self.len_offset..self.len_offset + 2])
362                    .try_into()
363                    .unwrap();
364                *out = u16::to_be_bytes(len as u16);
365            }
366            ListLength::U24 { .. } => {
367                let len = self.buf.len() - self.len_offset - 3;
368                debug_assert!(len <= 0xff_ffff);
369                let len_bytes = u32::to_be_bytes(len as u32);
370                let out: &mut [u8; 3] = (&mut self.buf[self.len_offset..self.len_offset + 3])
371                    .try_into()
372                    .unwrap();
373                out.copy_from_slice(&len_bytes[1..]);
374            }
375        }
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use std::prelude::v1::*;
382    use std::vec;
383
384    use super::*;
385
386    #[test]
387    fn interrupted_length_prefixed_buffer_leaves_maximum_length() {
388        let mut buf = Vec::new();
389        let nested = LengthPrefixedBuffer::new(ListLength::U16, &mut buf);
390        nested.buf.push(0xaa);
391        assert_eq!(nested.buf, &vec![0xff, 0xff, 0xaa]);
392        // <- if the buffer is accidentally read here, there is no possiblity
393        //    that the contents of the length-prefixed buffer are interpretted
394        //    as a subsequent encoding (perhaps allowing injection of a different
395        //    extension)
396        drop(nested);
397        assert_eq!(buf, vec![0x00, 0x01, 0xaa]);
398    }
399}