Skip to main content

ssh_encoding/
decoder.rs

1//! Shared decoder for SSH protocol data types.
2
3use crate::{Decode, Error, MAX_MSG_SIZE, MpintRef, Reader, Result};
4use core::{fmt, str};
5
6/// Maximum number of simultaneously active nested decoding scopes.
7const MAX_NESTING_DEPTH: u8 = 64;
8
9/// Decoder for SSH protocol data types over a byte [`Reader`].
10///
11/// Construct a decoder with [`Decoder::new`] or [`Reader::into_decoder`].
12///
13/// All nested decoding uses the same decoder type, with enclosing bounds stored on the call
14/// stack. A decoder permits up to 64 active nested scopes. Neither nesting nor decoding from
15/// Base64 or PEM requires a heap allocation.
16///
17/// A failed read or nested decoding operation invalidates the decoder. Subsequent reads and
18/// completion checks return [`Error::Failed`]. The underlying reader is not rewound on errors.
19///
20/// # Example
21/// ```
22/// use ssh_encoding::{Decode, Reader};
23///
24/// let mut decoder = [0, 0, 0, 42].as_slice().into_decoder()?;
25/// let value = u32::decode(&mut decoder)?;
26/// assert_eq!(decoder.finish(value)?, 42);
27/// # Ok::<(), ssh_encoding::Error>(())
28/// ```
29pub struct Decoder<R> {
30    /// Underlying byte reader.
31    reader: R,
32
33    /// Position in the decoded input.
34    position: usize,
35
36    /// End of the currently active decoding scope.
37    end: usize,
38
39    /// Number of active nested scopes.
40    depth: u8,
41
42    /// Whether a read or nested decoding operation failed.
43    failed: bool,
44}
45
46impl<R: Reader> Decoder<R> {
47    /// Create a decoder which owns the given reader.
48    ///
49    /// # Errors
50    /// Returns [`Error::Length`] if the remaining decoded input exceeds `MAX_MSG_SIZE`.
51    pub fn new(reader: R) -> Result<Self> {
52        let end = reader.remaining_len();
53        if end > MAX_MSG_SIZE {
54            return Err(Error::Length);
55        }
56
57        Ok(Self {
58            reader,
59            position: 0,
60            end,
61            depth: 0,
62            failed: false,
63        })
64    }
65
66    /// Read enough bytes to exactly fill `out`, without crossing the active scope's boundary.
67    ///
68    /// # Errors
69    /// - Returns [`Error::Failed`] if the decoder has already failed.
70    /// - Returns [`Error::Length`] if `out` exceeds the remaining length.
71    /// - Propagates errors returned from [`Reader::read`].
72    pub fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
73        if self.failed {
74            return Err(Error::Failed);
75        }
76
77        if out.len() > self.remaining_len() {
78            self.failed = true;
79            return Err(Error::Length);
80        }
81
82        // Avoid calling streaming decoders for empty reads.
83        if out.is_empty() {
84            return Ok(out);
85        }
86
87        let len = out.len();
88        match self.reader.read(out) {
89            Ok(bytes) => {
90                self.position += len;
91                Ok(bytes)
92            }
93            Err(err) => {
94                self.failed = true;
95                Err(err)
96            }
97        }
98    }
99
100    /// Get the number of decoded bytes remaining in the active scope.
101    #[must_use]
102    pub fn remaining_len(&self) -> usize {
103        self.end - self.position
104    }
105
106    /// Have all bytes in the active scope been consumed?
107    #[must_use]
108    pub fn is_finished(&self) -> bool {
109        self.remaining_len() == 0
110    }
111
112    /// Decode exactly `len` bytes within a nested scope.
113    ///
114    /// The callback receives the same decoder type with its bounds temporarily narrowed.
115    /// It must consume the entire scope before returning successfully. Enclosing bounds are
116    /// restored on success, error, or unwinding, without rewinding the underlying reader.
117    ///
118    /// # Errors
119    /// - Returns [`Error::Failed`] if the decoder has already failed.
120    /// - Returns [`Error::Length`] if `len` exceeds the remaining length.
121    /// - Returns [`Error::NestingDepth`] if the decoder already has 64 active nested scopes.
122    /// - Returns [`Error::TrailingData`] if the callback leaves unread bytes.
123    /// - Propagates errors returned from the callback.
124    pub fn read_nested<T, E, F>(&mut self, len: usize, f: F) -> core::result::Result<T, E>
125    where
126        E: From<Error>,
127        F: FnOnce(&mut Self) -> core::result::Result<T, E>,
128    {
129        let mut scope = self.enter_nested(len)?;
130        let value = f(scope.decoder)?;
131        scope.decoder.ensure_finished()?;
132        scope.completed = true;
133        Ok(value)
134    }
135
136    /// Decode a `uint32` length prefix, then decode its body in a nested scope.
137    ///
138    /// # Errors
139    /// Propagates errors decoding the prefix or returned by [`Decoder::read_nested`].
140    pub fn read_prefixed<T, E, F>(&mut self, f: F) -> core::result::Result<T, E>
141    where
142        E: From<Error>,
143        F: FnOnce(&mut Self) -> core::result::Result<T, E>,
144    {
145        let len = usize::decode(self).inspect_err(|_| self.failed = true)?;
146        self.read_nested(len, f)
147    }
148
149    /// Decode an SSH binary `string` into `out` and return the filled portion.
150    ///
151    /// The `uint32` length prefix gives the number of payload bytes to read ([RFC4251 §5]).
152    /// To decode to a `str`, use [`Decoder::read_string`].
153    ///
154    /// The [`Decode`] impl on `Vec<u8>` can be used to allocate a buffer for the result.
155    ///
156    /// [RFC4251 §5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
157    ///
158    /// # Errors
159    /// - Returns [`Error::Length`] if the payload is larger than `out`.
160    /// - Propagates errors returned from [`Decoder::read_prefixed`] or [`Decoder::read`].
161    pub fn read_string_bytes<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
162        self.read_prefixed(|reader| {
163            let slice = out.get_mut(..reader.remaining_len()).ok_or(Error::Length)?;
164            reader.read(slice)?;
165            Ok(&*slice)
166        })
167    }
168
169    /// Decode an SSH `string` into `buf` and return the filled portion as a `&str` ([RFC4251 § 5]).
170    ///
171    /// > Arbitrary length binary string.  Strings are allowed to contain
172    /// > arbitrary binary data, including null characters and 8-bit
173    /// > characters.  They are stored as a uint32 containing its length
174    /// > (number of bytes that follow) and zero (= empty string) or more
175    /// > bytes that are the value of the string.  Terminating null
176    /// > characters are not used.
177    /// >
178    /// > Strings are also used to store text.  In that case, US-ASCII is
179    /// > used for internal names, and ISO-10646 UTF-8 for text that might
180    /// > be displayed to the user.  The terminating null character SHOULD
181    /// > NOT normally be stored in the string.  For example: the US-ASCII
182    /// > string "testing" is represented as 00 00 00 07 t e s t i n g.  The
183    /// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
184    ///
185    /// Storage for the string data must be provided as mutable byte slice in order to accommodate
186    /// `no_alloc` use cases.
187    ///
188    /// The [`Decode`] impl on `String` can be used to allocate a buffer for the result.
189    ///
190    /// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
191    ///
192    /// # Errors
193    /// - Propagates errors returned from [`Decoder::read_string_bytes`].
194    /// - Returns [`Error::CharacterEncoding`] if the data is not valid UTF-8.
195    pub fn read_string<'o>(&mut self, buf: &'o mut [u8]) -> Result<&'o str> {
196        Ok(str::from_utf8(self.read_string_bytes(buf)?)?)
197    }
198
199    /// Decode an SSH `mpint`, left-padding its unsigned big-endian magnitude with zeros to fill `out`.
200    ///
201    /// Returns the significant bytes in `out`, or an empty slice for zero. Redundant leading
202    /// zeros are accepted up to the 2049-byte wire limit. Decoding is variable-time.
203    ///
204    /// # Errors
205    /// Returns [`Error::MpintEncoding`] for a negative encoding or [`Error::Length`] if
206    /// the encoding exceeds the wire limit or the magnitude does not fit in `out`.
207    /// Propagates errors from the reader.
208    pub fn read_mpint_bytes<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
209        self.read_prefixed(|reader| {
210            let Some(first) = reader.read_mpint_prefix()? else {
211                out.fill(0);
212                return Ok(&out[out.len()..]);
213            };
214
215            let len = reader.remaining_len() + 1;
216            let offset = out.len().checked_sub(len).ok_or(Error::Length)?;
217            let (padding, magnitude) = out.split_at_mut(offset);
218            padding.fill(0);
219            magnitude[0] = first;
220            reader.read(&mut magnitude[1..])?;
221            Ok(&*magnitude)
222        })
223    }
224
225    /// Read the first significant byte in a length-delimited mpint body, or `None` for zero.
226    pub(crate) fn read_mpint_prefix(&mut self) -> Result<Option<u8>> {
227        let len = self.remaining_len();
228        if len > MpintRef::MAX_SIZE + 1 {
229            return Err(Error::Length);
230        }
231        if len == 0 {
232            return Ok(None);
233        }
234
235        let mut first = u8::decode(self)?;
236        if first >= 0x80 {
237            return Err(Error::MpintEncoding);
238        }
239        if first != 0 && len > MpintRef::MAX_SIZE {
240            return Err(Error::Length);
241        }
242
243        while first == 0 {
244            if self.is_finished() {
245                return Ok(None);
246            }
247            first = u8::decode(self)?;
248        }
249        Ok(Some(first))
250    }
251
252    /// Drain the given number of bytes from the reader, discarding them.
253    ///
254    /// # Errors
255    /// Propagates errors returned from [`Decoder::read`].
256    pub fn drain(&mut self, n_bytes: usize) -> Result<()> {
257        let mut byte = [0];
258        for _ in 0..n_bytes {
259            self.read(&mut byte)?;
260        }
261        Ok(())
262    }
263
264    /// Decode a `u32` length prefix, and then drain the length of the body.
265    ///
266    /// Upon success, returns the number of bytes drained sans the length of the `u32` length prefix
267    /// (4-bytes).
268    ///
269    /// # Errors
270    /// - Propagates errors returned from [`Decoder::read_prefixed`].
271    /// - Propagates errors returned from [`Decoder::drain`].
272    pub fn drain_prefixed(&mut self) -> Result<usize> {
273        self.read_prefixed(|reader| {
274            let len = reader.remaining_len();
275            reader.drain(len)?;
276            Ok(len)
277        })
278    }
279
280    /// Ensure that decoding is finished.
281    ///
282    /// # Errors
283    /// - Returns [`Error::Failed`] if the decoder has already failed.
284    /// - Returns [`Error::TrailingData`] if there is data remaining in the decoder.
285    pub fn ensure_finished(&self) -> Result<()> {
286        if self.failed {
287            Err(Error::Failed)
288        } else if self.is_finished() {
289            Ok(())
290        } else {
291            Err(Error::TrailingData {
292                remaining: self.remaining_len(),
293            })
294        }
295    }
296
297    /// Finish decoding, returning the given value if there is no remaining data.
298    ///
299    /// # Errors
300    /// - Returns [`Error::Failed`] if the decoder has already failed.
301    /// - Returns [`Error::TrailingData`] if there is data remaining in the decoder.
302    pub fn finish<T>(self, value: T) -> Result<T> {
303        self.ensure_finished()?;
304        Ok(value)
305    }
306
307    /// Enter a nested scope, keeping setup independent of the callback type.
308    fn enter_nested(&mut self, len: usize) -> Result<NestedScope<'_, R>> {
309        if self.failed {
310            return Err(Error::Failed);
311        }
312
313        if len > self.remaining_len() {
314            self.failed = true;
315            return Err(Error::Length);
316        }
317
318        let outer_depth = self.depth;
319        if outer_depth >= MAX_NESTING_DEPTH {
320            self.failed = true;
321            return Err(Error::NestingDepth);
322        }
323
324        let outer_end = self.end;
325        self.end = self.position + len;
326        self.depth = outer_depth + 1;
327        Ok(NestedScope {
328            decoder: self,
329            outer_end,
330            outer_depth,
331            completed: false,
332        })
333    }
334}
335
336impl<R: Reader> fmt::Debug for Decoder<R> {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        f.debug_struct("Decoder")
339            .field("position", &self.position)
340            .field("remaining_len", &self.remaining_len())
341            .field("depth", &self.depth)
342            .field("failed", &self.failed)
343            .finish_non_exhaustive()
344    }
345}
346
347/// Restores enclosing bounds on every exit path without introducing another reader type.
348struct NestedScope<'a, R> {
349    decoder: &'a mut Decoder<R>,
350    outer_end: usize,
351    outer_depth: u8,
352    completed: bool,
353}
354
355impl<R> Drop for NestedScope<'_, R> {
356    fn drop(&mut self) {
357        self.decoder.end = self.outer_end;
358        self.decoder.depth = self.outer_depth;
359        if !self.completed {
360            self.decoder.failed = true;
361        }
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use crate::{Error, MAX_MSG_SIZE, Reader};
368
369    #[test]
370    fn input_size_limit_before_reading() {
371        // Exercise the actual limit without allocating a large input buffer.
372        struct Unreadable(usize);
373
374        impl Reader for Unreadable {
375            fn read<'o>(&mut self, _: &'o mut [u8]) -> Result<&'o [u8], Error> {
376                panic!("construction must not read input");
377            }
378
379            fn remaining_len(&self) -> usize {
380                self.0
381            }
382        }
383
384        for len in [0, MAX_MSG_SIZE - 1, MAX_MSG_SIZE] {
385            let decoder = Unreadable(len).into_decoder().unwrap();
386            assert_eq!(decoder.remaining_len(), len);
387        }
388
389        for len in [MAX_MSG_SIZE + 1, usize::MAX] {
390            assert_eq!(Unreadable(len).into_decoder().err(), Some(Error::Length));
391        }
392    }
393}