Skip to main content

ssh_encoding/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![doc = include_str!("../README.md")]
4#![doc(
5    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
6    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
7)]
8
9//! ## Conventions used in this crate
10//!
11//! This crate uses the following type labels which are described in [RFC4251 § 5], and also lists
12//! types with [`Decode`]/[`Encode`] trait impls which are compatible with this format:
13//!
14//! ### `byte`, `byte[n]`, `byte[]`: arbitrary 8-bit value (octet) or sequence thereof
15//! #### [`Decode`]/[`Encode`] trait impls:
16//! - `byte`: `u8`
17//! - `byte[n]`: `[u8; N]`
18//! - `byte[]`: `Vec<u8>`, `bytes::Bytes` (requires `bytes` crate feature)
19//!
20//! Fixed length data is sometimes represented as an array of bytes, written
21//! `byte[n]` where `n` is the number of bytes in the array.
22//!
23//! `byte[]` is a newer convention from OpenSSH for describing arbitrary
24//! length bytestrings (similar to `string`, see below) but identifies data
25//! which is inherently binary in nature, as opposed to text.
26//!
27//!
28//! ### `boolean`: boolean value stored as a single byte
29//! #### [`Decode`]/[`Encode`] trait impls: `bool`
30//!
31//! The value 0 represents FALSE, and the value 1 represents TRUE.  All non-zero
32//! values MUST be interpreted as TRUE; however, applications MUST NOT
33//! store values other than 0 and 1.
34//!
35//! ### `uint32`: 32-bit unsigned integer
36//! #### [`Decode`]/[`Encode`] trait impls: `u32`, `usize`
37//!
38//! Stored as four bytes in the order of decreasing significance (network byte order).
39//!
40//! For example: the value `699921578` (`0x29b7f4aa`) is stored as
41//! `29 b7 f4 aa`.
42//!
43//! ### `uint64`: 64-bit unsigned integer
44//! #### [`Decode`]/[`Encode`] trait impls: `u64`
45//!
46//! Stored as eight bytes in the order of decreasing significance (network byte order).
47//!
48//! ### `string`: arbitrary length *binary* string
49//! #### [`Decode`]/[`Encode`] trait impls: `Vec<u8>`, `String`, `bytes::Bytes` (requires `bytes` crate feature)
50//!
51//! *NOTE: `string` is effectively equivalent to `byte[]`, however the latter is not defined in
52//! [RFC4251] and so trait impls in this crate for bytestring types like `[u8]` and `Vec<u8>`
53//! are described as being impls of `string`*.
54//!
55//! Strings are allowed to contain arbitrary binary data, including null characters and 8-bit
56//! characters.
57//!
58//! They are stored as a `uint32` containing its length (number of bytes that follow) and
59//! zero (= empty string) or more bytes that are the value of the string.  Terminating null
60//! characters are not used.
61//!
62//! Strings are also used to store text.  In that case, US-ASCII is used for internal names, and
63//! ISO-10646 UTF-8 for text that might be displayed to the user.
64//!
65//! The terminating null character SHOULD  NOT normally be stored in the string.
66//!
67//! For example: the US-ASCII string "testing" is represented as `00 00 00 07 t e s t i n g`.
68//! The UTF-8 mapping does not alter the encoding of US-ASCII characters.
69//!
70//! ### `mpint`: multiple precision integers in two's complement format
71//! #### [`Decode`]/[`Encode`] trait impls: `Mpint`
72//!
73//! Stored as a byte string, 8 bits per byte, MSB first (a.k.a. big endian).
74//!
75//! This crate supports only non-negative values, matching OpenSSH, and enforces a 16384-bit
76//! magnitude limit. Negative wire encodings are rejected. A leading zero byte is added when
77//! the most significant bit is set. Zero is encoded as an empty string.
78//!
79//! Decoding accepts redundant leading zeros like OpenSSH, subject to a 2049-byte wire limit
80//! (the extra byte must be zero). Encoding always produces the canonical representation.
81//! The byte APIs use unsigned magnitudes without sign padding or the length prefix.
82//! Use [`MpintRef`] to encode a borrowed magnitude and [`Decoder::read_mpint_bytes`] to decode
83//! into caller-provided storage.
84//!
85//! By convention, a number that is used in modular computations in
86//! `Z_n` SHOULD be represented in the range `0 <= x < n`.
87//!
88//! #### Examples:
89//!
90//! value (hex)        | representation (hex)
91//! -------------------|---------------------
92//! `0`                | `00 00 00 00`
93//! `9a378f9b2e332a7`  | `00 00 00 08 09 a3 78 f9 b2 e3 32 a7`
94//! `80`               | `00 00 00 02 00 80`
95//!
96//! ### `string` containing a sequence of strings
97//! #### [`Decode`]/[`Encode`] trait impls: `Vec<String>`
98//!
99//! An outer `uint32` length prefix is followed by zero or more SSH `string` values,
100//! each with its own `uint32` length prefix. The outer length covers all encoded entries,
101//! including their individual length prefixes. Each entry is UTF-8 text.
102//!
103//! This encoding is used for the valid principals field in OpenSSH certificates.
104//!
105//! It differs from the `name-list` encoding in [RFC4251 § 5], which stores comma-separated
106//! names within a single SSH `string`. This crate does not currently provide a dedicated
107//! `name-list` type.
108//!
109//! [RFC4251]: https://datatracker.ietf.org/doc/html/rfc4251
110//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
111//!
112//! ## Deriving [`Decode`] and [`Encode`]
113//!
114//! The traits [`Decode`] and [`Encode`] can be derived for any struct or enum where all its fields
115//! implement [`Decode`] and [`Encode`] respectively.
116//!
117//! To use this functionality, enable the `derive` crate feature for `ssh-encoding`.
118//!
119//! ### Example
120//!
121//! Here is an example of how you could define a handful of the SSH message types:
122//!
123#![cfg_attr(all(feature = "alloc", feature = "derive"), doc = "```")]
124#![cfg_attr(not(all(feature = "alloc", feature = "derive")), doc = "```ignore")]
125//! use ssh_encoding::{Decode, Decoder, Encode};
126//!
127//! #[derive(Debug, PartialEq, Encode, Decode)]
128//! #[repr(u8)]
129//! enum Message {
130//!     Disconnect {
131//!         reason_code: u32,
132//!         description: String,
133//!         language_tag: String,
134//!     } = 1,
135//!     EcdhInit {
136//!         client_public_key: Vec<u8>,
137//!     } = 30,
138//!     EcdhReply {
139//!         host_key: HostKey,
140//!         server_public_key: Vec<u8>,
141//!         #[ssh(length_prefixed)]
142//!         host_signature: HostSignature,
143//!     } = 31,
144//! }
145//!
146//! #[derive(Debug, PartialEq, Encode, Decode)]
147//! #[ssh(length_prefixed)]
148//! struct HostKey {
149//!     key_type: String,
150//!     ecdsa_curve_identifier: String,
151//!     ecdsa_public_key: Vec<u8>,
152//! }
153//!
154//! #[derive(Debug, PartialEq, Encode, Decode)]
155//! struct HostSignature {
156//!     signature_type: String,
157//!     signature: Vec<u8>,
158//! }
159//!
160//! let message = Message::EcdhReply {
161//!     host_key: HostKey {
162//!         key_type: "ecdsa-sha2-nistp256".into(),
163//!         ecdsa_curve_identifier: "nistp256".into(),
164//!         ecdsa_public_key: vec![0x01, 0x02, 0x03],
165//!     },
166//!     server_public_key: vec![0x04, 0x05, 0x06],
167//!     host_signature: HostSignature {
168//!         signature_type: "ecdsa-sha2-nistp256".into(),
169//!         signature: vec![0x07, 0x08, 0x09],
170//!     },
171//! };
172//!
173//! let encoded = message.encode_vec()?;
174//! assert_eq!(&encoded[..13], &[31, 0, 0, 0, 42, 0, 0, 0, 19, 101, 99, 100, 115]);
175//! let decoded = Message::decode(&mut Decoder::from_bytes(&encoded)?)?;
176//! assert_eq!(message, decoded);
177//! # Ok::<(), ssh_encoding::Error>(())
178//! ```
179
180#[cfg(feature = "alloc")]
181extern crate alloc;
182
183mod checked;
184mod decode;
185mod decoder;
186mod encode;
187mod error;
188mod label;
189mod mpint;
190mod reader;
191mod writer;
192
193#[cfg(feature = "base64")]
194pub mod base64;
195#[cfg(feature = "pem")]
196pub mod pem;
197
198pub use crate::{
199    checked::CheckedSum,
200    decode::Decode,
201    decoder::Decoder,
202    encode::Encode,
203    error::{Error, Result},
204    label::{Label, LabelError},
205    mpint::MpintRef,
206    reader::Reader,
207    writer::Writer,
208};
209
210#[cfg(feature = "alloc")]
211pub use crate::mpint::Mpint;
212
213#[cfg(feature = "base64")]
214pub use crate::base64::{Base64Decoder, Base64Reader, Base64Writer};
215
216#[cfg(feature = "bigint")]
217pub use bigint;
218
219#[cfg(feature = "bytes")]
220pub use bytes;
221
222#[cfg(feature = "digest")]
223pub use crate::writer::DigestWriter;
224#[cfg(feature = "digest")]
225pub use digest;
226
227#[cfg(feature = "pem")]
228pub use crate::pem::{DecodePem, EncodePem, PemDecoder};
229
230#[cfg(feature = "derive")]
231pub use ssh_derive::{Decode, Encode};
232
233#[cfg(feature = "alloc")]
234use alloc::vec::Vec;
235
236#[cfg(feature = "bigint")]
237pub use bigint::BoxedUint as Uint;
238
239/// Maximum binary input size accepted by [`Decoder`]: 128 MiB.
240///
241/// Matches OpenSSH's [`SSHBUF_SIZE_MAX`]. For Base64 and PEM readers, this bounds the decoded
242/// binary length, excluding textual encapsulation. Nested scopes are bounded by their parent.
243///
244/// [`SSHBUF_SIZE_MAX`]: https://github.com/openssh/openssh-portable/blob/1bf5871aead6d73177d727add15ab0f14c258fdf/sshbuf.h#L39
245const MAX_MSG_SIZE: usize = 0x800_0000;
246
247/// Fallibly allocate an empty byte buffer with the requested capacity.
248#[cfg(feature = "alloc")]
249fn vec_with_reserve(capacity: usize) -> Result<Vec<u8>> {
250    let mut buffer = Vec::new();
251    buffer.try_reserve_exact(capacity)?;
252    Ok(buffer)
253}
254
255/// Fallibly allocate a zero-filled byte buffer.
256#[cfg(feature = "alloc")]
257fn vec_zeroed(len: usize) -> Result<Vec<u8>> {
258    let mut buffer = vec_with_reserve(len)?;
259    buffer.resize(len, 0);
260    Ok(buffer)
261}