Skip to main content

ssh_key/
sshsig.rs

1//! `sshsig` implementation.
2
3use crate::{Algorithm, AssociatedHashAlg, Error, HashAlg, Result, Signature, SigningKey, public};
4use alloc::{string::String, string::ToString, vec::Vec};
5use core::str::FromStr;
6use encoding::{
7    CheckedSum, Decode, DecodePem, Decoder, Encode, EncodePem, Reader, Writer,
8    digest::Digest,
9    pem::{LineEnding, PemLabel},
10};
11use signature::Verifier;
12
13#[cfg(doc)]
14use crate::{PrivateKey, PublicKey};
15
16type Version = u32;
17
18#[cfg(feature = "serde")]
19use serde::{Deserialize, Serialize, de, ser};
20
21/// `sshsig` provides a general-purpose signature format based on SSH keys and
22/// wire formats.
23///
24/// These signatures can be produced using `ssh-keygen -Y sign`. They're
25/// encoded as PEM and begin with the following:
26///
27/// ```text
28/// -----BEGIN SSH SIGNATURE-----
29/// ```
30///
31/// See [PROTOCOL.sshsig] for more information.
32///
33/// # Usage
34///
35/// See [`PrivateKey::sign`] and [`PublicKey::verify`] for usage information.
36///
37/// [PROTOCOL.sshsig]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.sshsig?annotate=HEAD
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct SshSig {
40    version: Version,
41    public_key: public::KeyData,
42    namespace: String,
43    reserved: Vec<u8>,
44    hash_alg: HashAlg,
45    signature: Signature,
46}
47
48impl SshSig {
49    /// Supported version.
50    pub const VERSION: Version = 1;
51
52    /// The preamble is the six-byte sequence "SSHSIG".
53    ///
54    /// It is included to ensure that manual signatures can never be confused with any message
55    /// signed during SSH user or host authentication.
56    const MAGIC_PREAMBLE: &'static [u8] = b"SSHSIG";
57
58    /// Create a new signature with the given public key, namespace, hash algorithm, and signature.
59    ///
60    /// # Errors
61    /// Returns [`Error::Namespace`] if the namespace is empty.
62    pub fn new(
63        public_key: public::KeyData,
64        namespace: impl Into<String>,
65        hash_alg: HashAlg,
66        signature: Signature,
67    ) -> Result<Self> {
68        let version = Self::VERSION;
69        let namespace = namespace.into();
70        let reserved = Vec::new();
71
72        if namespace.is_empty() {
73            return Err(Error::Namespace);
74        }
75
76        Ok(Self {
77            version,
78            public_key,
79            namespace,
80            reserved,
81            hash_alg,
82            signature,
83        })
84    }
85
86    /// Decode signature from PEM which begins with the following:
87    ///
88    /// ```text
89    /// -----BEGIN SSH SIGNATURE-----
90    /// ```
91    ///
92    /// # Errors
93    /// Returns [`Error::Encoding`] in the event of an encoding error.
94    pub fn from_pem(pem: impl AsRef<[u8]>) -> Result<Self> {
95        Self::decode_pem(pem)
96    }
97
98    /// Encode signature as PEM which begins with the following:
99    ///
100    /// ```text
101    /// -----BEGIN SSH SIGNATURE-----
102    /// ```
103    ///
104    /// # Errors
105    /// Returns [`Error::Encoding`] in the event of an encoding error.
106    pub fn to_pem(&self, line_ending: LineEnding) -> Result<String> {
107        Ok(self.encode_pem_string(line_ending)?)
108    }
109
110    /// Sign the given message with the provided signing key.
111    ///
112    /// See also: [`PrivateKey::sign`].
113    ///
114    /// # Errors
115    /// - Returns [`Error::AlgorithmUnsupported`] if this signing key's algorithm is unsupported
116    ///   by this library with its enabled features.
117    /// - Returns [`Error::Crypto`] in the event of an error occurring in the cryptographic
118    ///   implementation.
119    /// - Returns [`Error::Namespace`] if the namespace is empty.
120    #[cfg(feature = "sha2")]
121    pub fn sign<S: SigningKey>(
122        signing_key: &S,
123        namespace: &str,
124        hash_alg: HashAlg,
125        msg: &[u8],
126    ) -> Result<Self> {
127        Self::sign_prehash(
128            signing_key,
129            namespace,
130            hash_alg,
131            hash_alg.digest(msg).as_slice(),
132        )
133    }
134
135    /// Sign the given message digest with the provided signing key.
136    ///
137    /// # Errors
138    /// - Returns [`Error::AlgorithmUnsupported`] if this signing key's algorithm is unsupported
139    ///   by this library with its enabled features.
140    /// - Returns [`Error::Crypto`] in the event of an error occurring in the cryptographic
141    ///   implementation.
142    /// - Returns [`Error::Namespace`] if the namespace is empty.
143    pub fn sign_digest<S, D>(signing_key: &S, namespace: &str, digest: D) -> Result<Self>
144    where
145        S: SigningKey,
146        D: AssociatedHashAlg + Digest,
147    {
148        Self::sign_prehash(
149            signing_key,
150            namespace,
151            D::HASH_ALG,
152            digest.finalize().as_slice(),
153        )
154    }
155
156    /// Sign the given prehashed message digest with the provided signing key.
157    ///
158    /// # Errors
159    /// - Returns [`Error::AlgorithmUnsupported`] if this signing key's algorithm is unsupported
160    ///   by this library with its enabled features.
161    /// - Returns [`Error::Crypto`] in the event of an error occurring in the cryptographic
162    ///   implementation.
163    /// - Returns [`Error::Namespace`] if the namespace is empty.
164    pub fn sign_prehash<S: SigningKey>(
165        signing_key: &S,
166        namespace: &str,
167        hash_alg: HashAlg,
168        prehash: &[u8],
169    ) -> Result<Self> {
170        if namespace.is_empty() {
171            return Err(Error::Namespace);
172        }
173
174        if signing_key.public_key().is_sk_ed25519() {
175            return Err(Algorithm::SkEd25519.unsupported_error());
176        }
177
178        #[cfg(feature = "ecdsa")]
179        if signing_key.public_key().is_sk_ecdsa_p256() {
180            return Err(Algorithm::SkEcdsaSha2NistP256.unsupported_error());
181        }
182
183        let signed_data = Self::signed_data_for_prehash(namespace, hash_alg, prehash)?;
184        let signature = signing_key.try_sign(&signed_data)?;
185        Self::new(signing_key.public_key(), namespace, hash_alg, signature)
186    }
187
188    /// Get the raw "enveloped" message over which the signature for a given input message is
189    /// computed.
190    ///
191    /// This is a low-level function intended for uses cases which can't be expressed using
192    /// [`SshSig::sign`], such as if the [`SigningKey`] trait can't be used for some reason.
193    ///
194    /// Once a [`Signature`] has been computed over the returned byte vector, [`SshSig::new`] can be
195    /// used to construct the final signature.
196    ///
197    /// # Errors
198    /// Returns [`Error::Namespace`] if the namespace is empty.
199    #[cfg(feature = "sha2")]
200    pub fn signed_data(namespace: &str, hash_alg: HashAlg, msg: &[u8]) -> Result<Vec<u8>> {
201        Self::signed_data_for_prehash(namespace, hash_alg, hash_alg.digest(msg).as_slice())
202    }
203
204    /// Get the raw message over which the signature for a given message digest (passed as the
205    /// `prehash` parameter) is computed.
206    ///
207    /// # Errors
208    /// - Returns [`Error::HashSize`] if `prehash` is not the right length for `hash_alg`.
209    /// - Returns [`Error::Namespace`] if the namespace is empty.
210    pub fn signed_data_for_prehash(
211        namespace: &str,
212        hash_alg: HashAlg,
213        prehash: &[u8],
214    ) -> Result<Vec<u8>> {
215        if prehash.len() != hash_alg.digest_size() {
216            return Err(Error::HashSize);
217        }
218
219        if namespace.is_empty() {
220            return Err(Error::Namespace);
221        }
222
223        SignedData {
224            namespace,
225            reserved: &[],
226            hash_alg,
227            hash: prehash,
228        }
229        .to_bytes()
230    }
231
232    /// Verify the given prehashed message digest against this signature.
233    ///
234    /// Note that this method does not verify the public key or namespace are correct and thus is
235    /// crate-private so as to ensure these parameters are always authenticated by users of the
236    /// public API.
237    pub(crate) fn verify_prehash(&self, prehash: &[u8]) -> Result<()> {
238        if prehash.len() != self.hash_alg.digest_size() {
239            return Err(Error::HashSize);
240        }
241
242        let signed_data = SignedData {
243            namespace: self.namespace.as_str(),
244            reserved: self.reserved.as_slice(),
245            hash_alg: self.hash_alg,
246            hash: prehash,
247        }
248        .to_bytes()?;
249
250        Ok(self.public_key.verify(&signed_data, &self.signature)?)
251    }
252
253    /// Get the signature algorithm.
254    #[must_use]
255    pub fn algorithm(&self) -> Algorithm {
256        self.signature.algorithm()
257    }
258
259    /// Get version number for this signature.
260    ///
261    /// Verifiers MUST reject signatures with versions greater than those
262    /// they support.
263    #[must_use]
264    pub fn version(&self) -> Version {
265        self.version
266    }
267
268    /// Get public key which corresponds to the signing key that produced
269    /// this signature.
270    #[must_use]
271    pub fn public_key(&self) -> &public::KeyData {
272        &self.public_key
273    }
274
275    /// Get the namespace (i.e. domain identifier) for this signature.
276    ///
277    /// The purpose of the namespace value is to specify a unambiguous
278    /// interpretation domain for the signature, e.g. file signing.
279    /// This prevents cross-protocol attacks caused by signatures
280    /// intended for one intended domain being accepted in another.
281    /// The namespace value MUST NOT be the empty string.
282    #[must_use]
283    pub fn namespace(&self) -> &str {
284        &self.namespace
285    }
286
287    /// Get reserved data associated with this signature. Typically empty.
288    ///
289    /// The reserved value is present to encode future information
290    /// (e.g. tags) into the signature. Implementations should ignore
291    /// the reserved field if it is not empty.
292    #[must_use]
293    pub fn reserved(&self) -> &[u8] {
294        &self.reserved
295    }
296
297    /// Get the hash algorithm used to produce this signature.
298    ///
299    /// Data to be signed is first hashed with the specified `hash_alg`.
300    /// This is done to limit the amount of data presented to the signature
301    /// operation, which may be of concern if the signing key is held in limited
302    /// or slow hardware or on a remote ssh-agent. The supported hash algorithms
303    /// are "sha256" and "sha512".
304    #[must_use]
305    pub fn hash_alg(&self) -> HashAlg {
306        self.hash_alg
307    }
308
309    /// Get the structured signature over the given message.
310    #[must_use]
311    pub fn signature(&self) -> &Signature {
312        &self.signature
313    }
314
315    /// Get the bytes which comprise the serialized signature.
316    #[must_use]
317    pub fn signature_bytes(&self) -> &[u8] {
318        self.signature.as_bytes()
319    }
320}
321
322impl Decode for SshSig {
323    type Error = Error;
324
325    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
326        let mut magic_preamble = [0u8; Self::MAGIC_PREAMBLE.len()];
327        reader.read(&mut magic_preamble)?;
328
329        if magic_preamble != Self::MAGIC_PREAMBLE {
330            return Err(Error::FormatEncoding);
331        }
332
333        let version = Version::decode(reader)?;
334
335        if version > Self::VERSION {
336            return Err(Error::Version { number: version });
337        }
338
339        let public_key = reader.read_prefixed(public::KeyData::decode)?;
340        let namespace = String::decode(reader)?;
341
342        if namespace.is_empty() {
343            return Err(Error::Namespace);
344        }
345
346        let reserved = Vec::decode(reader)?;
347        let hash_alg = HashAlg::decode(reader)?;
348        let signature = reader.read_prefixed(Signature::decode)?;
349
350        Ok(Self {
351            version,
352            public_key,
353            namespace,
354            reserved,
355            hash_alg,
356            signature,
357        })
358    }
359}
360
361impl Encode for SshSig {
362    fn encoded_len(&self) -> encoding::Result<usize> {
363        [
364            Self::MAGIC_PREAMBLE.len(),
365            self.version.encoded_len()?,
366            self.public_key.encoded_len_prefixed()?,
367            self.namespace.encoded_len()?,
368            self.reserved.encoded_len()?,
369            self.hash_alg.encoded_len()?,
370            self.signature.encoded_len_prefixed()?,
371        ]
372        .checked_sum()
373    }
374
375    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
376        writer.write(Self::MAGIC_PREAMBLE)?;
377        self.version.encode(writer)?;
378        self.public_key.encode_prefixed(writer)?;
379        self.namespace.encode(writer)?;
380        self.reserved.encode(writer)?;
381        self.hash_alg.encode(writer)?;
382        self.signature.encode_prefixed(writer)?;
383        Ok(())
384    }
385}
386
387impl FromStr for SshSig {
388    type Err = Error;
389
390    fn from_str(s: &str) -> Result<Self> {
391        Self::from_pem(s)
392    }
393}
394
395impl PemLabel for SshSig {
396    const PEM_LABEL: &'static str = "SSH SIGNATURE";
397}
398
399#[allow(clippy::to_string_trait_impl)]
400impl ToString for SshSig {
401    fn to_string(&self) -> String {
402        self.to_pem(LineEnding::default())
403            .expect("SSH signature encoding error")
404    }
405}
406
407/// Data to be signed.
408#[derive(Clone, Copy, Debug, Eq, PartialEq)]
409struct SignedData<'a> {
410    namespace: &'a str,
411    reserved: &'a [u8],
412    hash_alg: HashAlg,
413    hash: &'a [u8],
414}
415
416impl SignedData<'_> {
417    fn to_bytes(self) -> Result<Vec<u8>> {
418        let mut signed_bytes = Vec::with_capacity(self.encoded_len()?);
419        self.encode(&mut signed_bytes)?;
420        Ok(signed_bytes)
421    }
422}
423
424impl Encode for SignedData<'_> {
425    fn encoded_len(&self) -> encoding::Result<usize> {
426        [
427            SshSig::MAGIC_PREAMBLE.len(),
428            self.namespace.encoded_len()?,
429            self.reserved.encoded_len()?,
430            self.hash_alg.encoded_len()?,
431            self.hash.encoded_len()?,
432        ]
433        .checked_sum()
434    }
435
436    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
437        writer.write(SshSig::MAGIC_PREAMBLE)?;
438        self.namespace.encode(writer)?;
439        self.reserved.encode(writer)?;
440        self.hash_alg.encode(writer)?;
441        self.hash.encode(writer)?;
442        Ok(())
443    }
444}
445
446#[cfg(feature = "serde")]
447impl<'de> Deserialize<'de> for SshSig {
448    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
449    where
450        D: de::Deserializer<'de>,
451    {
452        if deserializer.is_human_readable() {
453            let string = String::deserialize(deserializer)?;
454            string.parse::<SshSig>().map_err(de::Error::custom)
455        } else {
456            let bytes = Vec::<u8>::deserialize(deserializer)?;
457            let mut decoder = bytes.as_slice().into_decoder().map_err(de::Error::custom)?;
458            let sshsig = Self::decode(&mut decoder).map_err(de::Error::custom)?;
459            decoder.finish(sshsig).map_err(de::Error::custom)
460        }
461    }
462}
463
464#[cfg(feature = "serde")]
465impl Serialize for SshSig {
466    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
467    where
468        S: ser::Serializer,
469    {
470        if serializer.is_human_readable() {
471            self.to_pem(LineEnding::LF)
472                .map_err(ser::Error::custom)?
473                .serialize(serializer)
474        } else {
475            let bytes = self.encode_vec().map_err(ser::Error::custom)?;
476            bytes.serialize(serializer)
477        }
478    }
479}