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//! If you import `ssh-encoding` under another name, specify its path on the type,
119//! e.g. `#[ssh(crate = encoding)]`. Both derives use this path.
120//!
121//! ### Example
122//!
123//! Here is an example of how you could define a handful of the SSH message types:
124//!
125#![cfg_attr(all(feature = "alloc", feature = "derive"), doc = "```")]
126#![cfg_attr(not(all(feature = "alloc", feature = "derive")), doc = "```ignore")]
127//! use ssh_encoding::{Decode, Decoder, Encode};
128//!
129//! #[derive(Debug, PartialEq, Encode, Decode)]
130//! #[repr(u8)]
131//! enum Message {
132//!     Disconnect {
133//!         reason_code: u32,
134//!         description: String,
135//!         language_tag: String,
136//!     } = 1,
137//!     EcdhInit {
138//!         client_public_key: Vec<u8>,
139//!     } = 30,
140//!     EcdhReply {
141//!         host_key: HostKey,
142//!         server_public_key: Vec<u8>,
143//!         #[ssh(length_prefixed)]
144//!         host_signature: HostSignature,
145//!     } = 31,
146//! }
147//!
148//! #[derive(Debug, PartialEq, Encode, Decode)]
149//! #[ssh(length_prefixed)]
150//! struct HostKey {
151//!     key_type: String,
152//!     ecdsa_curve_identifier: String,
153//!     ecdsa_public_key: Vec<u8>,
154//! }
155//!
156//! #[derive(Debug, PartialEq, Encode, Decode)]
157//! struct HostSignature {
158//!     signature_type: String,
159//!     signature: Vec<u8>,
160//! }
161//!
162//! let message = Message::EcdhReply {
163//!     host_key: HostKey {
164//!         key_type: "ecdsa-sha2-nistp256".into(),
165//!         ecdsa_curve_identifier: "nistp256".into(),
166//!         ecdsa_public_key: vec![0x01, 0x02, 0x03],
167//!     },
168//!     server_public_key: vec![0x04, 0x05, 0x06],
169//!     host_signature: HostSignature {
170//!         signature_type: "ecdsa-sha2-nistp256".into(),
171//!         signature: vec![0x07, 0x08, 0x09],
172//!     },
173//! };
174//!
175//! let encoded = message.encode_vec()?;
176//! assert_eq!(&encoded[..13], &[31, 0, 0, 0, 42, 0, 0, 0, 19, 101, 99, 100, 115]);
177//! let decoded = Message::decode(&mut Decoder::from_bytes(&encoded)?)?;
178//! assert_eq!(message, decoded);
179//! # Ok::<(), ssh_encoding::Error>(())
180//! ```
181
182#[cfg(feature = "alloc")]
183extern crate alloc;
184
185mod checked;
186mod decode;
187mod decoder;
188mod encode;
189mod error;
190mod label;
191mod mpint;
192mod reader;
193mod writer;
194
195#[cfg(feature = "base64")]
196pub mod base64;
197#[cfg(feature = "pem")]
198pub mod pem;
199
200pub use crate::{
201    checked::CheckedSum,
202    decode::Decode,
203    decoder::Decoder,
204    encode::Encode,
205    error::{Error, Result},
206    label::{Label, LabelError},
207    mpint::MpintRef,
208    reader::Reader,
209    writer::Writer,
210};
211
212#[cfg(feature = "alloc")]
213pub use crate::mpint::Mpint;
214
215#[cfg(feature = "base64")]
216pub use crate::base64::{Base64Decoder, Base64Reader, Base64Writer};
217
218#[cfg(feature = "bigint")]
219pub use bigint;
220
221#[cfg(feature = "bytes")]
222pub use bytes;
223
224#[cfg(feature = "digest")]
225pub use crate::writer::DigestWriter;
226#[cfg(feature = "digest")]
227pub use digest;
228
229#[cfg(feature = "pem")]
230pub use crate::pem::{DecodePem, EncodePem, PemDecoder};
231
232#[cfg(feature = "derive")]
233pub use ssh_derive::{Decode, Encode};
234
235#[cfg(feature = "alloc")]
236use alloc::vec::Vec;
237
238#[cfg(feature = "bigint")]
239pub use bigint::BoxedUint as Uint;
240
241/// Maximum binary input size accepted by [`Decoder`]: 128 MiB.
242///
243/// Matches OpenSSH's [`SSHBUF_SIZE_MAX`]. For Base64 and PEM readers, this bounds the decoded
244/// binary length, excluding textual encapsulation. Nested scopes are bounded by their parent.
245///
246/// [`SSHBUF_SIZE_MAX`]: https://github.com/openssh/openssh-portable/blob/1bf5871aead6d73177d727add15ab0f14c258fdf/sshbuf.h#L39
247const MAX_MSG_SIZE: usize = 0x800_0000;
248
249/// Fallibly allocate an empty byte buffer with the requested capacity.
250#[cfg(feature = "alloc")]
251fn vec_with_reserve(capacity: usize) -> Result<Vec<u8>> {
252    let mut buffer = Vec::new();
253    buffer.try_reserve_exact(capacity)?;
254    Ok(buffer)
255}
256
257/// Fallibly allocate a zero-filled byte buffer.
258#[cfg(feature = "alloc")]
259fn vec_zeroed(len: usize) -> Result<Vec<u8>> {
260    let mut buffer = vec_with_reserve(len)?;
261    buffer.resize(len, 0);
262    Ok(buffer)
263}
264
265#[cfg(all(test, feature = "derive"))]
266mod tests {
267    use crate as wire;
268    use wire::{Decode, Decoder, Encode};
269
270    #[test]
271    fn derive_with_crate_alias() -> wire::Result<()> {
272        #[derive(Debug, Decode, Encode, PartialEq)]
273        #[repr(u8)]
274        #[ssh(crate = wire, length_prefixed)]
275        enum Message {
276            Data(#[ssh(length_prefixed)] u8) = 1,
277        }
278
279        let mut buf = [0; 10];
280        let value = Message::Data(42);
281        assert_eq!(value.encoded_len()?, buf.len());
282        value.encode(&mut buf.as_mut_slice())?;
283        assert_eq!(buf, [0, 0, 0, 6, 1, 0, 0, 0, 1, 42]);
284        assert_eq!(Message::decode(&mut Decoder::from_bytes(&buf)?)?, value);
285        Ok(())
286    }
287}