Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion ssh-encoding/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@
use crate::{Decode, Error, MAX_MSG_SIZE, Reader, Result};
use core::{fmt, str};

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

/// Decoder for SSH protocol data types over a byte [`Reader`].
///
/// Construct a decoder with [`Decoder::new`] or [`Reader::into_decoder`].
///
/// All nested decoding uses the same decoder type, with enclosing bounds stored on the call
/// stack. Neither nesting nor decoding from Base64 or PEM requires a heap allocation.
/// 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.
Expand All @@ -32,6 +36,9 @@ pub struct Decoder<R> {
/// 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,
}
Expand All @@ -51,6 +58,7 @@ impl<R: Reader> Decoder<R> {
reader,
position: 0,
end,
depth: 0,
failed: false,
})
}
Expand Down Expand Up @@ -110,6 +118,7 @@ impl<R: Reader> Decoder<R> {
/// # 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>
Expand Down Expand Up @@ -257,11 +266,19 @@ impl<R: Reader> Decoder<R> {
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,
})
}
Expand All @@ -272,6 +289,7 @@ impl<R: Reader> fmt::Debug for Decoder<R> {
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()
}
Expand All @@ -281,12 +299,14 @@ impl<R: Reader> fmt::Debug for Decoder<R> {
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;
}
Expand Down
4 changes: 4 additions & 0 deletions ssh-encoding/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ pub enum Error {
#[cfg(feature = "alloc")]
MpintEncoding,

/// Maximum decoding nesting depth exceeded.
NestingDepth,

/// Overflow errors.
Overflow,

Expand Down Expand Up @@ -78,6 +81,7 @@ impl fmt::Display for Error {
Error::Length => write!(f, "length invalid"),
#[cfg(feature = "alloc")]
Error::MpintEncoding => write!(f, "`mpint` encoding invalid"),
Error::NestingDepth => write!(f, "maximum nesting depth exceeded"),
Error::Overflow => write!(f, "internal overflow error"),
#[cfg(feature = "pem")]
Error::Pem(err) => write!(f, "{err}"),
Expand Down
23 changes: 23 additions & 0 deletions ssh-encoding/tests/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,29 @@ fn recursive_decoding_keeps_the_same_reader_type() {
check_backends(&hex!("00000009 00000005 00000001 42"), Ok(Depth(3)));
}

#[test]
fn nesting_depth_limit() {
fn descend(decoder: &mut Decoder<impl Reader>, levels: u8) -> Result<(), Error> {
if levels == 0 {
return Ok(());
}
decoder.read_nested(0, |decoder| descend(decoder, levels - 1))
}

// Each empty prefixed string occupies one scope while its callback runs.
let mut decoder = Decoder::new([0; 12].as_slice()).unwrap();
for _ in 0..2 {
decoder
.read_prefixed(|decoder| descend(decoder, 63))
.unwrap();
}
assert_eq!(
decoder.read_prefixed(|decoder| descend(decoder, 64)),
Err(Error::NestingDepth)
);
assert_eq!(decoder.finish(()), Err(Error::Failed));
}

#[test]
fn callback_error_restores_scope_and_invalidates_decoder() {
#[derive(Debug, Eq, PartialEq)]
Expand Down
Loading