Skip to main content

ssh_encoding/
decode.rs

1//! Decoder-side implementation of the SSH protocol's data type representations
2//! as described in [RFC4251 § 5].
3//!
4//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
5
6use crate::{Decoder, Error, Reader, Result};
7
8#[cfg(feature = "alloc")]
9use alloc::{string::String, vec::Vec};
10
11#[cfg(feature = "bytes")]
12use bytes::Bytes;
13
14/// Decoding trait.
15///
16/// This trait describes how to decode a given type.
17pub trait Decode: Sized {
18    /// Type returned in the event of a decoding error.
19    type Error: From<Error>;
20
21    /// Attempt to decode a value of this type using the provided [`Decoder`].
22    ///
23    /// # Errors
24    /// Returns errors specific to the concrete implementation of this trait.
25    fn decode(reader: &mut Decoder<impl Reader>) -> core::result::Result<Self, Self::Error>;
26}
27
28/// Decode a single `byte` from the input data.
29impl Decode for u8 {
30    type Error = Error;
31
32    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
33        let mut buf = [0];
34        reader.read(&mut buf)?;
35        Ok(buf[0])
36    }
37}
38
39/// Decode a `boolean` as described in [RFC4251 § 5]:
40///
41/// > A boolean value is stored as a single byte.  The value 0
42/// > represents FALSE, and the value 1 represents TRUE.  All non-zero
43/// > values MUST be interpreted as TRUE; however, applications MUST NOT
44/// > store values other than 0 and 1.
45///
46/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
47impl Decode for bool {
48    type Error = Error;
49
50    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
51        let byte = u8::decode(reader)?;
52        match byte {
53            0 => Ok(false),
54            _ => Ok(true),
55        }
56    }
57}
58
59/// Decode a `uint32` as described in [RFC4251 § 5]:
60///
61/// > Represents a 32-bit unsigned integer.  Stored as four bytes in the
62/// > order of decreasing significance (network byte order).
63/// > For example: the value 699921578 (0x29b7f4aa) is stored as 29 b7 f4 aa.
64///
65/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
66impl Decode for u32 {
67    type Error = Error;
68
69    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
70        let mut bytes = [0u8; 4];
71        reader.read(&mut bytes)?;
72        Ok(u32::from_be_bytes(bytes))
73    }
74}
75
76/// Decode a `uint64` as described in [RFC4251 § 5]:
77///
78/// > Represents a 64-bit unsigned integer.  Stored as eight bytes in
79/// > the order of decreasing significance (network byte order).
80///
81/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
82impl Decode for u64 {
83    type Error = Error;
84
85    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
86        let mut bytes = [0u8; 8];
87        reader.read(&mut bytes)?;
88        Ok(u64::from_be_bytes(bytes))
89    }
90}
91
92/// Decode an SSH `uint32` as a `usize`.
93///
94/// Returns [`Error::Overflow`] if the value does not fit in `usize`.
95/// Use [`Decoder::read_prefixed`] to decode a length-prefixed field.
96impl Decode for usize {
97    type Error = Error;
98
99    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
100        Ok(usize::try_from(u32::decode(reader)?)?)
101    }
102}
103
104/// Decodes a byte array from `byte[n]` as described in [RFC4251 § 5]:
105///
106/// > A byte represents an arbitrary 8-bit value (octet).  Fixed length
107/// > data is sometimes represented as an array of bytes, written
108/// > `byte[n]`, where n is the number of bytes in the array.
109///
110/// Note that unlike `string`, this type is encoded without a length prefix,
111/// but instead implicitly obtains its length as `N`.
112///
113/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
114impl<const N: usize> Decode for [u8; N] {
115    type Error = Error;
116
117    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
118        let mut result = [0u8; N];
119        reader.read(&mut result)?;
120        Ok(result)
121    }
122}
123
124/// Decodes `Vec<u8>` from `string` as described in [RFC4251 § 5]:
125///
126/// > Arbitrary length binary string.  Strings are allowed to contain
127/// > arbitrary binary data, including null characters and 8-bit
128/// > characters.  They are stored as a uint32 containing its length
129/// > (number of bytes that follow) and zero (= empty string) or more
130/// > bytes that are the value of the string.  Terminating null
131/// > characters are not used.
132///
133/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
134#[cfg(feature = "alloc")]
135impl Decode for Vec<u8> {
136    type Error = Error;
137
138    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
139        reader.read_prefixed(|reader| {
140            let mut result = crate::vec_zeroed(reader.remaining_len())?;
141            reader.read(&mut result)?;
142            Ok(result)
143        })
144    }
145}
146
147#[cfg(feature = "alloc")]
148impl Decode for String {
149    type Error = Error;
150
151    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
152        String::from_utf8(Vec::decode(reader)?).map_err(|_| Error::CharacterEncoding)
153    }
154}
155
156/// Decodes `Vec<String>` from an SSH `string` containing a sequence of SSH `string` values.
157///
158/// The outer `uint32` length prefix covers all encoded entries, including their individual
159/// length prefixes. Each entry is decoded as UTF-8. This encoding is used for the valid
160/// principals field in OpenSSH certificates.
161///
162/// This differs from the comma-separated `name-list` encoding described in [RFC4251 § 5].
163///
164/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
165#[cfg(feature = "alloc")]
166impl Decode for Vec<String> {
167    type Error = Error;
168
169    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
170        reader.read_prefixed(|reader| {
171            let mut entries = Self::new();
172
173            while !reader.is_finished() {
174                entries.try_reserve(1)?;
175                entries.push(String::decode(reader)?);
176            }
177
178            Ok(entries)
179        })
180    }
181}
182
183/// Decodes `Bytes` from `string` as described in [RFC4251 § 5]:
184///
185/// > Arbitrary length binary string.  Strings are allowed to contain
186/// > arbitrary binary data, including null characters and 8-bit
187/// > characters.  They are stored as a uint32 containing its length
188/// > (number of bytes that follow) and zero (= empty string) or more
189/// > bytes that are the value of the string.  Terminating null
190/// > characters are not used.
191///
192/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
193#[cfg(feature = "bytes")]
194impl Decode for Bytes {
195    type Error = Error;
196
197    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
198        Vec::<u8>::decode(reader).map(Into::into)
199    }
200}