ssh-encoding 0.4.0

Pure Rust implementation of SSH data type decoders/encoders as described in RFC4251
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Shared decoder for SSH protocol data types.

use crate::{Decode, Error, MAX_MSG_SIZE, MpintRef, Reader, Result};
use core::{fmt, str};

#[cfg(feature = "base64")]
use crate::Base64Reader;
#[cfg(feature = "pem")]
use crate::pem::PemReader;

/// Maximum number of simultaneously active nested decoding scopes.
const MAX_NESTING_DEPTH: u8 = 64;

/// Decoder for SSH protocol data types over a byte [`Reader`].
///
/// Use [`Decoder::from_bytes`] for binary input, `Decoder::from_base64` with the `base64`
/// feature, or `Decoder::from_pem` with the `pem` feature. For a custom reader, use
/// [`Decoder::new`] or [`Reader::into_decoder`].
///
/// All nested decoding uses the same decoder type, with enclosing bounds stored on the call
/// stack. A decoder permits up to 64 active nested scopes. Neither nesting nor decoding from
/// Base64 or PEM requires a heap allocation.
///
/// A failed read or nested decoding operation invalidates the decoder. Subsequent reads and
/// completion checks return [`Error::Failed`]. The underlying reader is not rewound on errors.
///
/// A clone has an independent read position and retains the current scope, nesting depth,
/// and failure state.
///
/// # Example
/// ```
/// use ssh_encoding::{Decode, Decoder};
///
/// let mut decoder = Decoder::from_bytes(&[0, 0, 0, 42])?;
/// let value = u32::decode(&mut decoder)?;
/// assert_eq!(decoder.finish(value)?, 42);
/// # Ok::<(), ssh_encoding::Error>(())
/// ```
#[derive(Clone)]
pub struct Decoder<R> {
    /// Underlying byte reader.
    reader: R,

    /// Position in the decoded input.
    position: usize,

    /// End of the currently active decoding scope.
    end: usize,

    /// Number of active nested scopes.
    depth: u8,

    /// Whether a read or nested decoding operation failed.
    failed: bool,
}

impl<'i> Decoder<&'i [u8]> {
    /// Create a decoder over binary SSH data.
    ///
    /// # Errors
    /// Returns [`Error::Length`] if the input exceeds 128 MiB.
    pub fn from_bytes(bytes: &'i [u8]) -> Result<Self> {
        Self::new(bytes)
    }
}

#[cfg(feature = "base64")]
impl<'i> Decoder<Base64Reader<'i>> {
    /// Create a decoder over contiguous Base64 text.
    ///
    /// # Errors
    /// Propagates errors from [`Base64Reader::new`] or [`Decoder::new`].
    pub fn from_base64(base64: &'i (impl AsRef<[u8]> + ?Sized)) -> Result<Self> {
        Self::new(Base64Reader::new(base64.as_ref())?)
    }
}

#[cfg(feature = "pem")]
impl<'i> Decoder<PemReader<'i>> {
    /// Create a decoder over the body of a PEM document, detecting its line width.
    ///
    /// Use [`Self::pem_label`] to check the document type before decoding its body.
    ///
    /// # Errors
    /// Propagates errors from [`PemReader::new`] or [`Decoder::new`].
    pub fn from_pem(pem: &'i (impl AsRef<[u8]> + ?Sized)) -> Result<Self> {
        Self::new(PemReader::new(pem.as_ref())?)
    }

    /// Get the PEM type label from the encapsulation boundaries.
    #[must_use]
    pub fn pem_label(&self) -> &'i str {
        self.reader.type_label()
    }
}

impl<R: Reader> Decoder<R> {
    /// Create a decoder which owns the given reader.
    ///
    /// # Errors
    /// Returns [`Error::Length`] if the remaining decoded input exceeds `MAX_MSG_SIZE`.
    pub fn new(reader: R) -> Result<Self> {
        let end = reader.remaining_len();
        if end > MAX_MSG_SIZE {
            return Err(Error::Length);
        }

        Ok(Self {
            reader,
            position: 0,
            end,
            depth: 0,
            failed: false,
        })
    }

    /// Read enough bytes to exactly fill `out`, without crossing the active scope's boundary.
    ///
    /// # Errors
    /// - Returns [`Error::Failed`] if the decoder has already failed.
    /// - Returns [`Error::Length`] if `out` exceeds the remaining length.
    /// - Propagates errors returned from [`Reader::read`].
    pub fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
        if self.failed {
            return Err(Error::Failed);
        }

        if out.len() > self.remaining_len() {
            self.failed = true;
            return Err(Error::Length);
        }

        // Avoid calling streaming decoders for empty reads.
        if out.is_empty() {
            return Ok(out);
        }

        let len = out.len();
        match self.reader.read(out) {
            Ok(bytes) => {
                self.position += len;
                Ok(bytes)
            }
            Err(err) => {
                self.failed = true;
                Err(err)
            }
        }
    }

    /// Get the number of decoded bytes remaining in the active scope.
    #[must_use]
    pub fn remaining_len(&self) -> usize {
        self.end - self.position
    }

    /// Have all bytes in the active scope been consumed?
    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.remaining_len() == 0
    }

    /// Decode exactly `len` bytes within a nested scope.
    ///
    /// The callback receives the same decoder type with its bounds temporarily narrowed.
    /// It must consume the entire scope before returning successfully. Enclosing bounds are
    /// restored on success, error, or unwinding, without rewinding the underlying reader.
    ///
    /// # Errors
    /// - Returns [`Error::Failed`] if the decoder has already failed.
    /// - Returns [`Error::Length`] if `len` exceeds the remaining length.
    /// - Returns [`Error::NestingDepth`] if the decoder already has 64 active nested scopes.
    /// - Returns [`Error::TrailingData`] if the callback leaves unread bytes.
    /// - Propagates errors returned from the callback.
    pub fn read_nested<T, E, F>(&mut self, len: usize, f: F) -> core::result::Result<T, E>
    where
        E: From<Error>,
        F: FnOnce(&mut Self) -> core::result::Result<T, E>,
    {
        let mut scope = self.enter_nested(len)?;
        let value = f(scope.decoder)?;
        scope.decoder.ensure_finished()?;
        scope.completed = true;
        Ok(value)
    }

    /// Decode a `uint32` length prefix, then decode its body in a nested scope.
    ///
    /// # Errors
    /// Propagates errors decoding the prefix or returned by [`Decoder::read_nested`].
    pub fn read_prefixed<T, E, F>(&mut self, f: F) -> core::result::Result<T, E>
    where
        E: From<Error>,
        F: FnOnce(&mut Self) -> core::result::Result<T, E>,
    {
        let len = usize::decode(self).inspect_err(|_| self.failed = true)?;
        self.read_nested(len, f)
    }

    /// Decode an SSH binary `string` into `out` and return the filled portion.
    ///
    /// The `uint32` length prefix gives the number of payload bytes to read ([RFC4251 §5]).
    /// To decode to a `str`, use [`Decoder::read_string`].
    ///
    /// The [`Decode`] impl on `Vec<u8>` can be used to allocate a buffer for the result.
    ///
    /// [RFC4251 §5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
    ///
    /// # Errors
    /// - Returns [`Error::Length`] if the payload is larger than `out`.
    /// - Propagates errors returned from [`Decoder::read_prefixed`] or [`Decoder::read`].
    pub fn read_string_bytes<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
        self.read_prefixed(|reader| {
            let slice = out.get_mut(..reader.remaining_len()).ok_or(Error::Length)?;
            reader.read(slice)?;
            Ok(&*slice)
        })
    }

    /// Decode an SSH `string` into `buf` and return the filled portion as a `&str` ([RFC4251 § 5]).
    ///
    /// > Arbitrary length binary string.  Strings are allowed to contain
    /// > arbitrary binary data, including null characters and 8-bit
    /// > characters.  They are stored as a uint32 containing its length
    /// > (number of bytes that follow) and zero (= empty string) or more
    /// > bytes that are the value of the string.  Terminating null
    /// > characters are not used.
    /// >
    /// > Strings are also used to store text.  In that case, US-ASCII is
    /// > used for internal names, and ISO-10646 UTF-8 for text that might
    /// > be displayed to the user.  The terminating null character SHOULD
    /// > NOT normally be stored in the string.  For example: the US-ASCII
    /// > string "testing" is represented as 00 00 00 07 t e s t i n g.  The
    /// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
    ///
    /// Storage for the string data must be provided as mutable byte slice in order to accommodate
    /// `no_alloc` use cases.
    ///
    /// The [`Decode`] impl on `String` can be used to allocate a buffer for the result.
    ///
    /// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
    ///
    /// # Errors
    /// - Propagates errors returned from [`Decoder::read_string_bytes`].
    /// - Returns [`Error::CharacterEncoding`] if the data is not valid UTF-8.
    pub fn read_string<'o>(&mut self, buf: &'o mut [u8]) -> Result<&'o str> {
        Ok(str::from_utf8(self.read_string_bytes(buf)?)?)
    }

    /// Decode an SSH `mpint`, left-padding its unsigned big-endian magnitude with zeros to fill `out`.
    ///
    /// Returns the significant bytes in `out`, or an empty slice for zero. Redundant leading
    /// zeros are accepted up to the 2049-byte wire limit. Decoding is variable-time.
    ///
    /// # Errors
    /// Returns [`Error::MpintEncoding`] for a negative encoding or [`Error::Length`] if
    /// the encoding exceeds the wire limit or the magnitude does not fit in `out`.
    /// Propagates errors from the reader.
    pub fn read_mpint_bytes<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
        self.read_prefixed(|reader| {
            let Some(first) = reader.read_mpint_prefix()? else {
                out.fill(0);
                return Ok(&out[out.len()..]);
            };

            let len = reader.remaining_len() + 1;
            let offset = out.len().checked_sub(len).ok_or(Error::Length)?;
            let (padding, magnitude) = out.split_at_mut(offset);
            padding.fill(0);
            magnitude[0] = first;
            reader.read(&mut magnitude[1..])?;
            Ok(&*magnitude)
        })
    }

    /// Read the first significant byte in a length-delimited mpint body, or `None` for zero.
    pub(crate) fn read_mpint_prefix(&mut self) -> Result<Option<u8>> {
        let len = self.remaining_len();
        if len > MpintRef::MAX_SIZE + 1 {
            return Err(Error::Length);
        }
        if len == 0 {
            return Ok(None);
        }

        let mut first = u8::decode(self)?;
        if first >= 0x80 {
            return Err(Error::MpintEncoding);
        }
        if first != 0 && len > MpintRef::MAX_SIZE {
            return Err(Error::Length);
        }

        while first == 0 {
            if self.is_finished() {
                return Ok(None);
            }
            first = u8::decode(self)?;
        }
        Ok(Some(first))
    }

    /// Drain the given number of bytes from the reader, discarding them.
    ///
    /// # Errors
    /// Propagates errors returned from [`Decoder::read`].
    pub fn drain(&mut self, n_bytes: usize) -> Result<()> {
        let mut byte = [0];
        for _ in 0..n_bytes {
            self.read(&mut byte)?;
        }
        Ok(())
    }

    /// Decode a `u32` length prefix, and then drain the length of the body.
    ///
    /// Upon success, returns the number of bytes drained sans the length of the `u32` length prefix
    /// (4-bytes).
    ///
    /// # Errors
    /// - Propagates errors returned from [`Decoder::read_prefixed`].
    /// - Propagates errors returned from [`Decoder::drain`].
    pub fn drain_prefixed(&mut self) -> Result<usize> {
        self.read_prefixed(|reader| {
            let len = reader.remaining_len();
            reader.drain(len)?;
            Ok(len)
        })
    }

    /// Ensure that decoding is finished.
    ///
    /// # Errors
    /// - Returns [`Error::Failed`] if the decoder has already failed.
    /// - Returns [`Error::TrailingData`] if there is data remaining in the decoder.
    pub fn ensure_finished(&self) -> Result<()> {
        if self.failed {
            Err(Error::Failed)
        } else if self.is_finished() {
            Ok(())
        } else {
            Err(Error::TrailingData {
                remaining: self.remaining_len(),
            })
        }
    }

    /// Finish decoding, returning the given value if there is no remaining data.
    ///
    /// # Errors
    /// - Returns [`Error::Failed`] if the decoder has already failed.
    /// - Returns [`Error::TrailingData`] if there is data remaining in the decoder.
    pub fn finish<T>(self, value: T) -> Result<T> {
        self.ensure_finished()?;
        Ok(value)
    }

    /// Enter a nested scope, keeping setup independent of the callback type.
    fn enter_nested(&mut self, len: usize) -> Result<NestedScope<'_, R>> {
        if self.failed {
            return Err(Error::Failed);
        }

        if len > self.remaining_len() {
            self.failed = true;
            return Err(Error::Length);
        }

        let outer_depth = self.depth;
        if outer_depth >= MAX_NESTING_DEPTH {
            self.failed = true;
            return Err(Error::NestingDepth);
        }

        let outer_end = self.end;
        self.end = self.position + len;
        self.depth = outer_depth + 1;
        Ok(NestedScope {
            decoder: self,
            outer_end,
            outer_depth,
            completed: false,
        })
    }
}

impl<R: Reader> fmt::Debug for Decoder<R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Decoder")
            .field("position", &self.position)
            .field("remaining_len", &self.remaining_len())
            .field("depth", &self.depth)
            .field("failed", &self.failed)
            .finish_non_exhaustive()
    }
}

/// Restores enclosing bounds on every exit path without introducing another reader type.
struct NestedScope<'a, R> {
    decoder: &'a mut Decoder<R>,
    outer_end: usize,
    outer_depth: u8,
    completed: bool,
}

impl<R> Drop for NestedScope<'_, R> {
    fn drop(&mut self) {
        self.decoder.end = self.outer_end;
        self.decoder.depth = self.outer_depth;
        if !self.completed {
            self.decoder.failed = true;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{Error, MAX_MSG_SIZE, Reader};

    #[test]
    fn input_size_limit_before_reading() {
        // Exercise the actual limit without allocating a large input buffer.
        #[derive(Clone)]
        struct Unreadable(usize);

        impl Reader for Unreadable {
            fn read<'o>(&mut self, _: &'o mut [u8]) -> Result<&'o [u8], Error> {
                panic!("construction must not read input");
            }

            fn remaining_len(&self) -> usize {
                self.0
            }
        }

        for len in [0, MAX_MSG_SIZE - 1, MAX_MSG_SIZE] {
            let decoder = Unreadable(len).into_decoder().unwrap();
            assert_eq!(decoder.remaining_len(), len);
        }

        for len in [MAX_MSG_SIZE + 1, usize::MAX] {
            assert_eq!(Unreadable(len).into_decoder().err(), Some(Error::Length));
        }
    }
}