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
24 changes: 12 additions & 12 deletions ssh-encoding/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,12 @@ in [RFC4251].

## Decoding

Convert a reader into a `Decoder` to start decoding SSH data types:
Use `Decoder::from_bytes` to decode binary SSH data.

```rust
use ssh_encoding::{Decode, Reader};
use ssh_encoding::{Decode, Decoder};

let mut decoder = [0, 0, 0, 4, 0, 0, 0, 42]
.as_slice()
.into_decoder()
.expect("input too long");
let mut decoder = Decoder::from_bytes(&[0, 0, 0, 4, 0, 0, 0, 42]).expect("input too long");
let value = decoder.read_prefixed(u32::decode).expect("invalid u32");
assert_eq!(decoder.finish(value).expect("remaining data"), 42);
```
Expand All @@ -34,15 +31,18 @@ handles nested bounds, complete consumption, and failure state. Nested callbacks
the same decoder type and store enclosing bounds on the call stack without allocation.
`Decode` implementations accept `&mut Decoder<impl Reader>`.

Construct a decoder with `Decoder::new(reader)` or `reader.into_decoder()`.
Both return an error if the remaining binary input exceeds 128 MiB, matching
Use `Decoder::from_base64` for contiguous Base64 text or `Decoder::from_pem` for a
PEM document. Both accept borrowed strings or bytes and decode the body incrementally.
The corresponding `base64` and `pem` features also provide the `Base64Decoder<'a>`
and `PemDecoder<'a>` type aliases for use in signatures. A PEM decoder exposes the
document's type label through `pem_label()`. For a type with a known label,
`DecodePem::decode_pem` checks the label before decoding the body.

To supply a reader directly, use `Decoder::new(reader)` or `reader.into_decoder()`.
All constructors return an error if the remaining binary input exceeds 128 MiB, matching
OpenSSH's hard buffer limit. `Decoder::read_prefixed` checks that the declared
body fits in the remaining bytes of the current scope before decoding it.

Raw byte slices implement `Reader`. With the corresponding features enabled,
`Base64Reader` decodes Base64 incrementally, and `DecodePem` wraps a PEM reader in
the same decoder internally.

For Base64 and PEM, the limit applies to the decoded binary length. Applications
must separately bound textual input and file reads before constructing a reader.

Expand Down
3 changes: 3 additions & 0 deletions ssh-encoding/src/base64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ mod writer;

pub use self::{reader::Base64Reader, writer::Base64Writer};
pub use base64ct::{Base64, Base64Unpadded, Encoding, Error};

/// SSH decoder for contiguous Base64 text, constructed with [`Self::from_base64`].
pub type Base64Decoder<'i> = crate::Decoder<Base64Reader<'i>>;
53 changes: 50 additions & 3 deletions ssh-encoding/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@
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`].
///
/// Construct a decoder with [`Decoder::new`] or [`Reader::into_decoder`].
/// 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
Expand All @@ -22,9 +29,9 @@ const MAX_NESTING_DEPTH: u8 = 64;
///
/// # Example
/// ```
/// use ssh_encoding::{Decode, Reader};
/// use ssh_encoding::{Decode, Decoder};
///
/// let mut decoder = [0, 0, 0, 42].as_slice().into_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>(())
Expand All @@ -47,6 +54,46 @@ pub struct Decoder<R> {
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.
///
Expand Down
8 changes: 4 additions & 4 deletions ssh-encoding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
//!
#![cfg_attr(all(feature = "alloc", feature = "derive"), doc = "```")]
#![cfg_attr(not(all(feature = "alloc", feature = "derive")), doc = "```ignore")]
//! use ssh_encoding::{Decode, Encode, Reader};
//! use ssh_encoding::{Decode, Decoder, Encode};
//!
//! #[derive(Debug, PartialEq, Encode, Decode)]
//! #[repr(u8)]
Expand Down Expand Up @@ -172,7 +172,7 @@
//!
//! let encoded = message.encode_vec()?;
//! assert_eq!(&encoded[..13], &[31, 0, 0, 0, 42, 0, 0, 0, 19, 101, 99, 100, 115]);
//! let decoded = Message::decode(&mut encoded.as_slice().into_decoder()?)?;
//! let decoded = Message::decode(&mut Decoder::from_bytes(&encoded)?)?;
//! assert_eq!(message, decoded);
//! # Ok::<(), ssh_encoding::Error>(())
//! ```
Expand Down Expand Up @@ -211,7 +211,7 @@ pub use crate::{
pub use crate::mpint::Mpint;

#[cfg(feature = "base64")]
pub use crate::{base64::Base64Reader, base64::Base64Writer};
pub use crate::base64::{Base64Decoder, Base64Reader, Base64Writer};

#[cfg(feature = "bigint")]
pub use bigint;
Expand All @@ -225,7 +225,7 @@ pub use crate::writer::DigestWriter;
pub use digest;

#[cfg(feature = "pem")]
pub use crate::pem::{DecodePem, EncodePem};
pub use crate::pem::{DecodePem, EncodePem, PemDecoder};

#[cfg(feature = "derive")]
pub use ssh_derive::{Decode, Encode};
Expand Down
5 changes: 4 additions & 1 deletion ssh-encoding/src/pem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ mod encode;
mod reader;
mod writer;

pub use self::{decode::DecodePem, encode::EncodePem};
pub use self::{decode::DecodePem, encode::EncodePem, reader::PemReader};
pub use pem_rfc7468::{Error, LineEnding, PemLabel};

/// SSH decoder for the body of a PEM document, constructed with [`Self::from_pem`].
pub type PemDecoder<'i> = crate::Decoder<PemReader<'i>>;

/// Line width used by the PEM encoding of OpenSSH documents.
const LINE_WIDTH: usize = 70;
22 changes: 18 additions & 4 deletions ssh-encoding/src/pem/reader.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,43 @@
use crate::{Reader, Result};
use core::fmt;

/// Inner PEM decoder.
type Inner<'i> = pem_rfc7468::Decoder<'i>;

/// Constant-time PEM reader.
/// Reader for the Base64 body of a PEM document.
#[derive(Clone)]
pub(crate) struct PemReader<'i> {
pub struct PemReader<'i> {
/// Inner PEM reader.
inner: Inner<'i>,
}

impl<'i> PemReader<'i> {
/// Create a new PEM reader which autodetects the line width of the input.
pub(crate) fn new(pem: &'i [u8]) -> Result<Self> {
///
/// # Errors
/// Returns [`crate::Error::Pem`] on errors parsing the encapsulation or initializing
/// the Base64 decoder.
pub fn new(pem: &'i [u8]) -> Result<Self> {
let inner = Inner::new_detect_wrap(pem)?;

Ok(Self { inner })
}

/// Get the PEM type label for the input document.
pub(crate) fn type_label(&self) -> &'i str {
#[must_use]
pub fn type_label(&self) -> &'i str {
self.inner.type_label()
}
}

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

impl Reader for PemReader<'_> {
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
Ok(self.inner.decode(out)?)
Expand Down
19 changes: 15 additions & 4 deletions ssh-encoding/tests/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,18 @@ fn check_backends<T>(bytes: &[u8], expected: Result<T, Error>)
where
T: Decode<Error = Error> + core::fmt::Debug + Eq,
{
let mut decoder = Decoder::new(bytes).unwrap();
let mut decoder = Decoder::from_bytes(bytes).unwrap();
let result = T::decode(&mut decoder).and_then(|value| decoder.finish(value));
assert_eq!(result, expected);

#[cfg(feature = "base64")]
{
use base64ct::{Base64, Encoding};
use ssh_encoding::Base64Reader;
use ssh_encoding::Base64Decoder;

let mut buffer = [0; 256];
let base64 = Base64::encode(bytes, &mut buffer).expect("test input fits in buffer");
let reader = Base64Reader::new(base64.as_bytes()).expect("valid Base64 test input");
let mut decoder: Decoder<_> = reader.into_decoder().unwrap();
let mut decoder: Base64Decoder<'_> = Decoder::from_base64(base64).unwrap();
let result = T::decode(&mut decoder).and_then(|value| decoder.finish(value));
assert_eq!(result, expected);
}
Expand Down Expand Up @@ -56,6 +55,18 @@ where
}
}

#[cfg(feature = "pem")]
#[test]
fn pem_decoder_reads_label_and_wrapped_body() {
use ssh_encoding::PemDecoder;

let pem = b"-----BEGIN TEST-----\nAAAA\nKg==\n-----END TEST-----\n";
let mut decoder: PemDecoder<'_> = Decoder::from_pem(pem).unwrap();
assert_eq!(decoder.pem_label(), "TEST");
let value = u32::decode(&mut decoder).unwrap();
assert_eq!(decoder.finish(value), Ok(42));
}

#[test]
fn nested_scopes_and_siblings() {
#[derive(Debug, Eq, PartialEq)]
Expand Down
6 changes: 3 additions & 3 deletions ssh-key/src/certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use alloc::{
vec::Vec,
};
use core::str::FromStr;
use encoding::{Base64Reader, CheckedSum, Decode, Decoder, Encode, Reader, Writer};
use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
use signature::Verifier;

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -192,7 +192,7 @@ impl Certificate {
/// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
pub fn from_openssh(certificate_str: &str) -> Result<Self> {
let encapsulation = SshFormat::decode(certificate_str.trim_end().as_bytes())?;
let mut reader = Decoder::new(Base64Reader::new(encapsulation.base64_data)?)?;
let mut reader = Decoder::from_base64(encapsulation.base64_data)?;
let mut cert = Certificate::decode(&mut reader)?;

// Verify that the algorithm in the Base64-encoded data matches the text
Expand All @@ -210,7 +210,7 @@ impl Certificate {
/// - Returns [`Error::Encoding`] in the event of an encoding error.
/// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let mut reader = Decoder::new(bytes)?;
let mut reader = Decoder::from_bytes(bytes)?;
let cert = Certificate::decode(&mut reader)?;
Ok(reader.finish(cert)?)
}
Expand Down
7 changes: 3 additions & 4 deletions ssh-key/src/composite/mldsa44_ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,14 +244,14 @@ mod tests {
/// truncated to the first [`MlDsa44Ed25519PublicKey::BYTE_SIZE`] bytes.
#[test]
fn wrong_encoded_length_is_rejected() {
use encoding::{Decode, Encode, Reader as _};
use encoding::{Decode, Decoder, Encode};

let mut encoded = [0; 4 + KAT_PK.len() + 1];
KAT_PK.encode(&mut encoded.as_mut_slice()).unwrap();

assert!(
MlDsa44Ed25519PublicKey::decode(
&mut encoded[..4 + KAT_PK.len()].into_decoder().unwrap()
&mut Decoder::from_bytes(&encoded[..4 + KAT_PK.len()]).unwrap()
)
.is_ok()
);
Expand All @@ -261,8 +261,7 @@ mod tests {
encoded[..4].copy_from_slice(&len.to_be_bytes());

assert!(
MlDsa44Ed25519PublicKey::decode(&mut encoded.as_slice().into_decoder().unwrap())
.is_err()
MlDsa44Ed25519PublicKey::decode(&mut Decoder::from_bytes(&encoded).unwrap()).is_err()
);
}

Expand Down
2 changes: 1 addition & 1 deletion ssh-key/src/composite/mldsa44_ed25519/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl MlDsa44Ed25519PublicKey {
/// # Errors
/// Returns [`encoding::Error::Length`] if the input has the wrong length.
pub fn new(key: impl AsRef<[u8]>) -> Result<Self> {
Self::decode_bytes(&mut Decoder::new(key.as_ref())?)
Self::decode_bytes(&mut Decoder::from_bytes(key.as_ref())?)
}

/// Get the SSH algorithm for this public key.
Expand Down
4 changes: 2 additions & 2 deletions ssh-key/src/kdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ mod tests {
use super::{Kdf, MAX_BCRYPT_ROUNDS};
use crate::Error;
use alloc::vec::Vec;
use encoding::{Decode, Encode, Reader};
use encoding::{Decode, Decoder, Encode};

#[test]
fn bcrypt_rounds_boundaries() {
Expand Down Expand Up @@ -262,7 +262,7 @@ mod tests {
assert!(output.is_empty());
Err(Error::Crypto)
};
let mut decoder = encoded.as_slice().into_decoder().unwrap();
let mut decoder = Decoder::from_bytes(&encoded).unwrap();
assert_eq!(Kdf::decode(&mut decoder), expected, "rounds: {rounds}");
if valid {
decoder.finish(()).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions ssh-key/src/ppk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ impl PpkContainer {
}

let mut public_key = PublicKey::from_bytes(&public_key)?;
let mut private_key_cursor = Decoder::new(private_key.as_slice())?;
let mut private_key_cursor = Decoder::from_bytes(&private_key)?;
let keypair_data =
decode_private_key_as(&mut private_key_cursor, public_key.clone(), ppk.algorithm)?;

Expand Down Expand Up @@ -648,7 +648,7 @@ mod tests {
let mut encoded = Vec::new();
bytes.as_slice().encode(&mut encoded).unwrap();
let key = decode_private_key_as(
&mut encoded.as_slice().into_decoder().unwrap(),
&mut Decoder::from_bytes(&encoded).unwrap(),
PublicKey::new(public.into(), ""),
Algorithm::Ed25519,
)
Expand Down
4 changes: 2 additions & 2 deletions ssh-key/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ impl PrivateKey {
/// # Errors
/// Returns [`Error::Encoding`] in the event of an encoding error.
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let mut reader = Decoder::new(bytes)?;
let mut reader = Decoder::from_bytes(bytes)?;
let private_key = Self::decode(&mut reader)?;
Ok(reader.finish(private_key)?)
}
Expand Down Expand Up @@ -476,7 +476,7 @@ impl PrivateKey {

#[allow(clippy::arithmetic_side_effects)] // block sizes are constants
Self::decode_privatekey_comment_pair(
&mut (&**buffer).into_decoder()?,
&mut Decoder::from_bytes(&buffer)?,
self.public_key.key_data.clone(),
self.cipher.block_size(),
self.cipher.block_size() - 1,
Expand Down
Loading