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//!
83//! By convention, a number that is used in modular computations in
84//! `Z_n` SHOULD be represented in the range `0 <= x < n`.
85//!
86//! #### Examples:
87//!
88//! value (hex) | representation (hex)
89//! -------------------|---------------------
90//! `0` | `00 00 00 00`
91//! `9a378f9b2e332a7` | `00 00 00 08 09 a3 78 f9 b2 e3 32 a7`
92//! `80` | `00 00 00 02 00 80`
93//!
94//! ### `string` containing a sequence of strings
95//! #### [`Decode`]/[`Encode`] trait impls: `Vec<String>`
96//!
97//! An outer `uint32` length prefix is followed by zero or more SSH `string` values,
98//! each with its own `uint32` length prefix. The outer length covers all encoded entries,
99//! including their individual length prefixes. Each entry is UTF-8 text.
100//!
101//! This encoding is used for the valid principals field in OpenSSH certificates.
102//!
103//! It differs from the `name-list` encoding in [RFC4251 § 5], which stores comma-separated
104//! names within a single SSH `string`. This crate does not currently provide a dedicated
105//! `name-list` type.
106//!
107//! [RFC4251]: https://datatracker.ietf.org/doc/html/rfc4251
108//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
109//!
110//! ## Deriving [`Decode`] and [`Encode`]
111//!
112//! The traits [`Decode`] and [`Encode`] can be derived for any struct or enum where all its fields
113//! implement [`Decode`] and [`Encode`] respectively.
114//!
115//! To use this functionality, enable the `derive` crate feature for `ssh-encoding`.
116//!
117//! ### Example
118//!
119//! Here is an example of how you could define a handful of the SSH message types:
120//!
121#![cfg_attr(all(feature = "alloc", feature = "derive"), doc = "```")]
122#![cfg_attr(not(all(feature = "alloc", feature = "derive")), doc = "```ignore")]
123//! use ssh_encoding::{Decode, Encode, Reader};
124//!
125//! #[derive(Debug, PartialEq, Encode, Decode)]
126//! #[repr(u8)]
127//! enum Message {
128//! Disconnect {
129//! reason_code: u32,
130//! description: String,
131//! language_tag: String,
132//! } = 1,
133//! EcdhInit {
134//! client_public_key: Vec<u8>,
135//! } = 30,
136//! EcdhReply {
137//! host_key: HostKey,
138//! server_public_key: Vec<u8>,
139//! #[ssh(length_prefixed)]
140//! host_signature: HostSignature,
141//! } = 31,
142//! }
143//!
144//! #[derive(Debug, PartialEq, Encode, Decode)]
145//! #[ssh(length_prefixed)]
146//! struct HostKey {
147//! key_type: String,
148//! ecdsa_curve_identifier: String,
149//! ecdsa_public_key: Vec<u8>,
150//! }
151//!
152//! #[derive(Debug, PartialEq, Encode, Decode)]
153//! struct HostSignature {
154//! signature_type: String,
155//! signature: Vec<u8>,
156//! }
157//!
158//! let message = Message::EcdhReply {
159//! host_key: HostKey {
160//! key_type: "ecdsa-sha2-nistp256".into(),
161//! ecdsa_curve_identifier: "nistp256".into(),
162//! ecdsa_public_key: vec![0x01, 0x02, 0x03],
163//! },
164//! server_public_key: vec![0x04, 0x05, 0x06],
165//! host_signature: HostSignature {
166//! signature_type: "ecdsa-sha2-nistp256".into(),
167//! signature: vec![0x07, 0x08, 0x09],
168//! },
169//! };
170//!
171//! let encoded = message.encode_vec()?;
172//! assert_eq!(&encoded[..13], &[31, 0, 0, 0, 42, 0, 0, 0, 19, 101, 99, 100, 115]);
173//! let decoded = Message::decode(&mut encoded.as_slice().into_decoder()?)?;
174//! assert_eq!(message, decoded);
175//! # Ok::<(), ssh_encoding::Error>(())
176//! ```
177
178#[cfg(feature = "alloc")]
179extern crate alloc;
180
181mod checked;
182mod decode;
183mod decoder;
184mod encode;
185mod error;
186mod label;
187#[cfg(feature = "alloc")]
188mod mpint;
189mod reader;
190mod writer;
191
192#[cfg(feature = "base64")]
193pub mod base64;
194#[cfg(feature = "pem")]
195pub mod pem;
196
197pub use crate::{
198 checked::CheckedSum,
199 decode::Decode,
200 decoder::Decoder,
201 encode::Encode,
202 error::{Error, Result},
203 label::{Label, LabelError},
204 reader::Reader,
205 writer::Writer,
206};
207
208#[cfg(feature = "alloc")]
209pub use crate::mpint::Mpint;
210
211#[cfg(feature = "base64")]
212pub use crate::{base64::Base64Reader, base64::Base64Writer};
213
214#[cfg(feature = "bigint")]
215pub use bigint;
216
217#[cfg(feature = "bytes")]
218pub use bytes;
219
220#[cfg(feature = "digest")]
221pub use crate::writer::DigestWriter;
222#[cfg(feature = "digest")]
223pub use digest;
224
225#[cfg(feature = "pem")]
226pub use crate::pem::{DecodePem, EncodePem};
227
228#[cfg(feature = "derive")]
229pub use ssh_derive::{Decode, Encode};
230
231#[cfg(feature = "alloc")]
232use alloc::vec::Vec;
233
234#[cfg(feature = "bigint")]
235pub use bigint::BoxedUint as Uint;
236
237/// Maximum binary input size accepted by [`Decoder`]: 128 MiB.
238///
239/// Matches OpenSSH's [`SSHBUF_SIZE_MAX`]. For Base64 and PEM readers, this bounds the decoded
240/// binary length, excluding textual encapsulation. Nested scopes are bounded by their parent.
241///
242/// [`SSHBUF_SIZE_MAX`]: https://github.com/openssh/openssh-portable/blob/1bf5871aead6d73177d727add15ab0f14c258fdf/sshbuf.h#L39
243const MAX_MSG_SIZE: usize = 0x800_0000;
244
245/// Fallibly allocate an empty byte buffer with the requested capacity.
246#[cfg(feature = "alloc")]
247fn vec_with_reserve(capacity: usize) -> Result<Vec<u8>> {
248 let mut buffer = Vec::new();
249 buffer.try_reserve_exact(capacity)?;
250 Ok(buffer)
251}
252
253/// Fallibly allocate a zero-filled byte buffer.
254#[cfg(feature = "alloc")]
255fn vec_zeroed(len: usize) -> Result<Vec<u8>> {
256 let mut buffer = vec_with_reserve(len)?;
257 buffer.resize(len, 0);
258 Ok(buffer)
259}