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
55 changes: 54 additions & 1 deletion ssh-encoding/src/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Shared decoder for SSH protocol data types.

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

/// Maximum number of simultaneously active nested decoding scopes.
Expand Down Expand Up @@ -196,6 +196,59 @@ impl<R: Reader> Decoder<R> {
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
Expand Down
2 changes: 0 additions & 2 deletions ssh-encoding/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ pub enum Error {
Length,

/// `mpint` encoding errors.
#[cfg(feature = "alloc")]
MpintEncoding,

/// Maximum decoding nesting depth exceeded.
Expand Down Expand Up @@ -79,7 +78,6 @@ impl fmt::Display for Error {
Error::Failed => write!(f, "decoder previously failed"),
Error::Label(err) => write!(f, "{}", err),
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"),
Expand Down
4 changes: 3 additions & 1 deletion ssh-encoding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@
//! Decoding accepts redundant leading zeros like OpenSSH, subject to a 2049-byte wire limit
//! (the extra byte must be zero). Encoding always produces the canonical representation.
//! The byte APIs use unsigned magnitudes without sign padding or the length prefix.
//! Use [`MpintRef`] to encode a borrowed magnitude and [`Decoder::read_mpint_bytes`] to decode
//! into caller-provided storage.
//!
//! By convention, a number that is used in modular computations in
//! `Z_n` SHOULD be represented in the range `0 <= x < n`.
Expand Down Expand Up @@ -184,7 +186,6 @@ mod decoder;
mod encode;
mod error;
mod label;
#[cfg(feature = "alloc")]
mod mpint;
mod reader;
mod writer;
Expand All @@ -201,6 +202,7 @@ pub use crate::{
encode::Encode,
error::{Error, Result},
label::{Label, LabelError},
mpint::MpintRef,
reader::Reader,
writer::Writer,
};
Expand Down
Loading