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