ssh-encoding 0.4.0-rc.1

Pure Rust implementation of SSH data type decoders/encoders as described in RFC4251
Documentation
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]

//! ## Conventions used in this crate
//!
//! This crate uses the following type labels which are described in [RFC4251 § 5], and also lists
//! types with [`Decode`]/[`Encode`] trait impls which are compatible with this format:
//!
//! ### `byte`, `byte[n]`, `byte[]`: arbitrary 8-bit value (octet) or sequence thereof
//! #### [`Decode`]/[`Encode`] trait impls:
//! - `byte`: `u8`
//! - `byte[n]`: `[u8; N]`
//! - `byte[]`: `Vec<u8>`, `bytes::Bytes` (requires `bytes` crate feature)
//!
//! Fixed length data is sometimes represented as an array of bytes, written
//! `byte[n]` where `n` is the number of bytes in the array.
//!
//! `byte[]` is a newer convention from OpenSSH for describing arbitrary
//! length bytestrings (similar to `string`, see below) but identifies data
//! which is inherently binary in nature, as opposed to text.
//!
//!
//! ### `boolean`: boolean value stored as a single byte
//! #### [`Decode`]/[`Encode`] trait impls: `bool`
//!
//! The value 0 represents FALSE, and the value 1 represents TRUE.  All non-zero
//! values MUST be interpreted as TRUE; however, applications MUST NOT
//! store values other than 0 and 1.
//!
//! ### `uint32`: 32-bit unsigned integer
//! #### [`Decode`]/[`Encode`] trait impls: `u32`, `usize`
//!
//! Stored as four bytes in the order of decreasing significance (network byte order).
//!
//! For example: the value `699921578` (`0x29b7f4aa`) is stored as
//! `29 b7 f4 aa`.
//!
//! ### `uint64`: 64-bit unsigned integer
//! #### [`Decode`]/[`Encode`] trait impls: `u64`
//!
//! Stored as eight bytes in the order of decreasing significance (network byte order).
//!
//! ### `string`: arbitrary length *binary* string
//! #### [`Decode`]/[`Encode`] trait impls: `Vec<u8>`, `String`, `bytes::Bytes` (requires `bytes` crate feature)
//!
//! *NOTE: `string` is effectively equivalent to `byte[]`, however the latter is not defined in
//! [RFC4251] and so trait impls in this crate for bytestring types like `[u8]` and `Vec<u8>`
//! are described as being impls of `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.
//!
//! ### `mpint`: multiple precision integers in two's complement format
//! #### [`Decode`]/[`Encode`] trait impls: `Mpint`
//!
//! Stored as a byte string, 8 bits per byte, MSB first (a.k.a. big endian).
//!
//! This crate supports only non-negative values, matching OpenSSH, and enforces a 16384-bit
//! magnitude limit. Negative wire encodings are rejected. A leading zero byte is added when
//! the most significant bit is set. Zero is encoded as an empty string.
//!
//! 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`.
//!
//! #### Examples:
//!
//! value (hex)        | representation (hex)
//! -------------------|---------------------
//! `0`                | `00 00 00 00`
//! `9a378f9b2e332a7`  | `00 00 00 08 09 a3 78 f9 b2 e3 32 a7`
//! `80`               | `00 00 00 02 00 80`
//!
//! ### `string` containing a sequence of strings
//! #### [`Decode`]/[`Encode`] trait impls: `Vec<String>`
//!
//! An outer `uint32` length prefix is followed by zero or more SSH `string` values,
//! each with its own `uint32` length prefix. The outer length covers all encoded entries,
//! including their individual length prefixes. Each entry is UTF-8 text.
//!
//! This encoding is used for the valid principals field in OpenSSH certificates.
//!
//! It differs from the `name-list` encoding in [RFC4251 § 5], which stores comma-separated
//! names within a single SSH `string`. This crate does not currently provide a dedicated
//! `name-list` type.
//!
//! [RFC4251]: https://datatracker.ietf.org/doc/html/rfc4251
//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
//!
//! ## Deriving [`Decode`] and [`Encode`]
//!
//! The traits [`Decode`] and [`Encode`] can be derived for any struct or enum where all its fields
//! implement [`Decode`] and [`Encode`] respectively.
//!
//! To use this functionality, enable the `derive` crate feature for `ssh-encoding`.
//!
//! ### Example
//!
//! Here is an example of how you could define a handful of the SSH message types:
//!
#![cfg_attr(all(feature = "alloc", feature = "derive"), doc = "```")]
#![cfg_attr(not(all(feature = "alloc", feature = "derive")), doc = "```ignore")]
//! use ssh_encoding::{Decode, Encode, Reader};
//!
//! #[derive(Debug, PartialEq, Encode, Decode)]
//! #[repr(u8)]
//! enum Message {
//!     Disconnect {
//!         reason_code: u32,
//!         description: String,
//!         language_tag: String,
//!     } = 1,
//!     EcdhInit {
//!         client_public_key: Vec<u8>,
//!     } = 30,
//!     EcdhReply {
//!         host_key: HostKey,
//!         server_public_key: Vec<u8>,
//!         #[ssh(length_prefixed)]
//!         host_signature: HostSignature,
//!     } = 31,
//! }
//!
//! #[derive(Debug, PartialEq, Encode, Decode)]
//! #[ssh(length_prefixed)]
//! struct HostKey {
//!     key_type: String,
//!     ecdsa_curve_identifier: String,
//!     ecdsa_public_key: Vec<u8>,
//! }
//!
//! #[derive(Debug, PartialEq, Encode, Decode)]
//! struct HostSignature {
//!     signature_type: String,
//!     signature: Vec<u8>,
//! }
//!
//! let message = Message::EcdhReply {
//!     host_key: HostKey {
//!         key_type: "ecdsa-sha2-nistp256".into(),
//!         ecdsa_curve_identifier: "nistp256".into(),
//!         ecdsa_public_key: vec![0x01, 0x02, 0x03],
//!     },
//!     server_public_key: vec![0x04, 0x05, 0x06],
//!     host_signature: HostSignature {
//!         signature_type: "ecdsa-sha2-nistp256".into(),
//!         signature: vec![0x07, 0x08, 0x09],
//!     },
//! };
//!
//! 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()?)?;
//! assert_eq!(message, decoded);
//! # Ok::<(), ssh_encoding::Error>(())
//! ```

#[cfg(feature = "alloc")]
extern crate alloc;

mod checked;
mod decode;
mod decoder;
mod encode;
mod error;
mod label;
mod mpint;
mod reader;
mod writer;

#[cfg(feature = "base64")]
pub mod base64;
#[cfg(feature = "pem")]
pub mod pem;

pub use crate::{
    checked::CheckedSum,
    decode::Decode,
    decoder::Decoder,
    encode::Encode,
    error::{Error, Result},
    label::{Label, LabelError},
    mpint::MpintRef,
    reader::Reader,
    writer::Writer,
};

#[cfg(feature = "alloc")]
pub use crate::mpint::Mpint;

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

#[cfg(feature = "bigint")]
pub use bigint;

#[cfg(feature = "bytes")]
pub use bytes;

#[cfg(feature = "digest")]
pub use crate::writer::DigestWriter;
#[cfg(feature = "digest")]
pub use digest;

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

#[cfg(feature = "derive")]
pub use ssh_derive::{Decode, Encode};

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "bigint")]
pub use bigint::BoxedUint as Uint;

/// Maximum binary input size accepted by [`Decoder`]: 128 MiB.
///
/// Matches OpenSSH's [`SSHBUF_SIZE_MAX`]. For Base64 and PEM readers, this bounds the decoded
/// binary length, excluding textual encapsulation. Nested scopes are bounded by their parent.
///
/// [`SSHBUF_SIZE_MAX`]: https://github.com/openssh/openssh-portable/blob/1bf5871aead6d73177d727add15ab0f14c258fdf/sshbuf.h#L39
const MAX_MSG_SIZE: usize = 0x800_0000;

/// Fallibly allocate an empty byte buffer with the requested capacity.
#[cfg(feature = "alloc")]
fn vec_with_reserve(capacity: usize) -> Result<Vec<u8>> {
    let mut buffer = Vec::new();
    buffer.try_reserve_exact(capacity)?;
    Ok(buffer)
}

/// Fallibly allocate a zero-filled byte buffer.
#[cfg(feature = "alloc")]
fn vec_zeroed(len: usize) -> Result<Vec<u8>> {
    let mut buffer = vec_with_reserve(len)?;
    buffer.resize(len, 0);
    Ok(buffer)
}