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