ssh-key 0.7.0-rc.13

Pure Rust implementation of SSH key file format decoders/encoders as described in RFC4251/RFC4253 and OpenSSH key formats, as well as "sshsig" signatures and certificates (including certificate validation and certificate authority support), with further support for the `authorized_keys` and `known_hosts` file formats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Public key data.

use super::{Ed25519PublicKey, SkEd25519};
use crate::{Algorithm, Error, Result};
use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};

#[cfg(feature = "alloc")]
use {
    super::{DsaPublicKey, OpaquePublicKey, RsaPublicKey},
    crate::Certificate,
    alloc::boxed::Box,
};

#[cfg(feature = "ecdsa")]
use super::{EcdsaPublicKey, SkEcdsaSha2NistP256};

#[cfg(all(feature = "mldsa", feature = "ed25519"))]
use super::MlDsa44Ed25519PublicKey;
#[cfg(all(feature = "mldsa", feature = "p384"))]
use super::MlDsa87P384PublicKey;

#[cfg(feature = "sha2")]
use crate::{Fingerprint, HashAlg};

/// Public key data.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum KeyData {
    /// Digital Signature Algorithm (DSA) public key data.
    #[cfg(feature = "alloc")]
    Dsa(DsaPublicKey),

    /// Elliptic Curve Digital Signature Algorithm (ECDSA) public key data.
    #[cfg(feature = "ecdsa")]
    Ecdsa(EcdsaPublicKey),

    /// Ed25519 public key data.
    Ed25519(Ed25519PublicKey),

    /// RSA public key data.
    #[cfg(feature = "alloc")]
    Rsa(RsaPublicKey),

    /// MLDSA44-Ed25519 public key data.
    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
    MlDsa44Ed25519(MlDsa44Ed25519PublicKey),

    /// MLDSA87-P384 public key data.
    #[cfg(all(feature = "mldsa", feature = "p384"))]
    MlDsa87P384(MlDsa87P384PublicKey),

    /// Security Key (FIDO/U2F) using ECDSA/NIST P-256 as specified in [PROTOCOL.u2f].
    ///
    /// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
    #[cfg(feature = "ecdsa")]
    SkEcdsaSha2NistP256(SkEcdsaSha2NistP256),

    /// Security Key (FIDO/U2F) using Ed25519 as specified in [PROTOCOL.u2f].
    ///
    /// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
    SkEd25519(SkEd25519),

    /// Certificate key as specified in [draft-ietf-sshm-cert].
    ///
    /// [draft-ietf-sshm-cert]: https://www.ietf.org/archive/id/draft-ietf-sshm-cert-01.html
    #[cfg(feature = "alloc")]
    Certificate(Box<Certificate>),

    /// Opaque public key data.
    #[cfg(feature = "alloc")]
    Other(OpaquePublicKey),
}

impl KeyData {
    /// Get the [`Algorithm`] for this public key.
    #[must_use]
    pub fn algorithm(&self) -> Algorithm {
        match self {
            #[cfg(feature = "alloc")]
            Self::Dsa(_) => Algorithm::Dsa,
            #[cfg(feature = "ecdsa")]
            Self::Ecdsa(key) => key.algorithm(),
            Self::Ed25519(_) => Algorithm::Ed25519,
            #[cfg(feature = "alloc")]
            Self::Rsa(_) => Algorithm::Rsa { hash: None },
            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
            Self::MlDsa44Ed25519(key) => key.algorithm(),
            #[cfg(all(feature = "mldsa", feature = "p384"))]
            Self::MlDsa87P384(key) => key.algorithm(),
            #[cfg(feature = "ecdsa")]
            Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
            Self::SkEd25519(_) => Algorithm::SkEd25519,
            #[cfg(feature = "alloc")]
            Self::Certificate(cert) => cert.algorithm(),
            #[cfg(feature = "alloc")]
            Self::Other(key) => key.algorithm(),
        }
    }

    /// Get DSA public key if this key is the correct type.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn dsa(&self) -> Option<&DsaPublicKey> {
        match self {
            Self::Dsa(key) => Some(key),
            _ => None,
        }
    }

    /// Get ECDSA public key if this key is the correct type.
    #[cfg(feature = "ecdsa")]
    #[must_use]
    pub fn ecdsa(&self) -> Option<&EcdsaPublicKey> {
        match self {
            Self::Ecdsa(key) => Some(key),
            _ => None,
        }
    }

    /// Get Ed25519 public key if this key is the correct type.
    #[must_use]
    pub fn ed25519(&self) -> Option<&Ed25519PublicKey> {
        match self {
            Self::Ed25519(key) => Some(key),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }

    /// Compute key fingerprint.
    ///
    /// Use [`Default::default()`] to use the default hash function (SHA-256).
    #[cfg(feature = "sha2")]
    #[must_use]
    pub fn fingerprint(&self, hash_alg: HashAlg) -> Fingerprint {
        Fingerprint::new(hash_alg, self)
    }

    /// Get RSA public key if this key is the correct type.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn rsa(&self) -> Option<&RsaPublicKey> {
        match self {
            Self::Rsa(key) => Some(key),
            _ => None,
        }
    }

    /// Get MLDSA44-Ed25519 public key if this key is the correct type.
    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
    #[must_use]
    pub fn mldsa44_ed25519(&self) -> Option<&MlDsa44Ed25519PublicKey> {
        match self {
            Self::MlDsa44Ed25519(key) => Some(key),
            _ => None,
        }
    }

    /// Get MLDSA87-P384 public key if this key is the correct type.
    #[cfg(all(feature = "mldsa", feature = "p384"))]
    #[must_use]
    pub fn mldsa87_p384(&self) -> Option<&MlDsa87P384PublicKey> {
        match self {
            Self::MlDsa87P384(key) => Some(key),
            _ => None,
        }
    }

    /// Get FIDO/U2F ECDSA/NIST P-256 public key if this key is the correct type.
    #[cfg(feature = "ecdsa")]
    #[must_use]
    pub fn sk_ecdsa_p256(&self) -> Option<&SkEcdsaSha2NistP256> {
        match self {
            Self::SkEcdsaSha2NistP256(sk) => Some(sk),
            _ => None,
        }
    }

    /// Get FIDO/U2F Ed25519 public key if this key is the correct type.
    #[must_use]
    pub fn sk_ed25519(&self) -> Option<&SkEd25519> {
        match self {
            Self::SkEd25519(sk) => Some(sk),
            _ => None,
        }
    }

    /// Get the custom, opaque public key if this key is the correct type.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn other(&self) -> Option<&OpaquePublicKey> {
        match self {
            Self::Other(key) => Some(key),
            _ => None,
        }
    }

    /// Get the certificate if this key is the correct type.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn certificate(&self) -> Option<&Certificate> {
        match self {
            Self::Certificate(certificate) => Some(certificate.as_ref()),
            _ => None,
        }
    }

    /// Get the certificate, consuming the [`KeyData`], if this key is the correct type.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn into_certificate(self) -> Option<Certificate> {
        match self {
            Self::Certificate(certificate) => Some(*certificate),
            _ => None,
        }
    }

    /// Is this key a DSA key?
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn is_dsa(&self) -> bool {
        matches!(self, Self::Dsa(_))
    }

    /// Is this key an ECDSA key?
    #[cfg(feature = "ecdsa")]
    #[must_use]
    pub fn is_ecdsa(&self) -> bool {
        matches!(self, Self::Ecdsa(_))
    }

    /// Is this key an Ed25519 key?
    #[must_use]
    pub fn is_ed25519(&self) -> bool {
        matches!(self, Self::Ed25519(_))
    }

    /// Is this key an RSA key?
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn is_rsa(&self) -> bool {
        matches!(self, Self::Rsa(_))
    }

    /// Is this key an ML-DSA key?
    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
    #[must_use]
    pub fn is_mldsa44_ed25519(&self) -> bool {
        matches!(self, Self::MlDsa44Ed25519(_))
    }

    /// Is this key an ML-DSA-87/P-384 composite key?
    #[cfg(all(feature = "mldsa", feature = "p384"))]
    #[must_use]
    pub fn is_mldsa87_p384(&self) -> bool {
        matches!(self, Self::MlDsa87P384(_))
    }

    /// Is this key a FIDO/U2F ECDSA/NIST P-256 key?
    #[cfg(feature = "ecdsa")]
    #[must_use]
    pub fn is_sk_ecdsa_p256(&self) -> bool {
        matches!(self, Self::SkEcdsaSha2NistP256(_))
    }

    /// Is this key a FIDO/U2F Ed25519 key?
    #[must_use]
    pub fn is_sk_ed25519(&self) -> bool {
        matches!(self, Self::SkEd25519(_))
    }

    /// Is this a key with a custom algorithm?
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn is_other(&self) -> bool {
        matches!(self, Self::Other(_))
    }

    /// Is this a certificate?
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn is_certificate(&self) -> bool {
        matches!(self, Self::Certificate(_))
    }

    /// Decode [`KeyData`] for the specified algorithm.
    ///
    /// # Errors
    /// - Returns [`Error::AlgorithmUnknown`] if the provided `algorithm` is unknown or unsupported
    ///   by this library.
    /// - Returns [`Error::Encoding`] in the event of an encoding error.
    pub fn decode_as(reader: &mut Decoder<impl Reader>, algorithm: Algorithm) -> Result<Self> {
        match algorithm {
            #[cfg(feature = "alloc")]
            Algorithm::Dsa => DsaPublicKey::decode(reader).map(Self::Dsa),
            #[cfg(feature = "ecdsa")]
            Algorithm::Ecdsa { curve } => match EcdsaPublicKey::decode(reader)? {
                key if key.curve() == curve => Ok(Self::Ecdsa(key)),
                _ => Err(Error::AlgorithmUnknown),
            },
            Algorithm::Ed25519 => Ed25519PublicKey::decode(reader).map(Self::Ed25519),
            #[cfg(feature = "alloc")]
            Algorithm::Rsa { .. } => RsaPublicKey::decode(reader).map(Self::Rsa),
            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
            Algorithm::MlDsa44Ed25519 => {
                MlDsa44Ed25519PublicKey::decode(reader).map(Self::MlDsa44Ed25519)
            }
            #[cfg(all(feature = "mldsa", feature = "p384"))]
            Algorithm::MlDsa87P384 => MlDsa87P384PublicKey::decode(reader).map(Self::MlDsa87P384),
            #[cfg(feature = "ecdsa")]
            Algorithm::SkEcdsaSha2NistP256 => {
                SkEcdsaSha2NistP256::decode(reader).map(Self::SkEcdsaSha2NistP256)
            }
            Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
            #[cfg(feature = "alloc")]
            Algorithm::Other(_) => OpaquePublicKey::decode_as(reader, algorithm).map(Self::Other),
            #[allow(unreachable_patterns)]
            _ => Err(Error::AlgorithmUnknown),
        }
    }

    /// Decode [`KeyData`] as a certificate with the specified algorithm.
    ///
    /// # Errors
    /// Propagates errors from [`Certificate::decode_as`].
    #[cfg(feature = "alloc")]
    pub fn decode_as_certificate(
        reader: &mut Decoder<impl Reader>,
        algorithm: Algorithm,
    ) -> Result<Self> {
        Certificate::decode_as(reader, algorithm).map(|cert| Self::Certificate(Box::new(cert)))
    }

    /// Get the encoded length of this key data without a leading algorithm
    /// identifier.
    pub(crate) fn encoded_key_data_len(&self) -> encoding::Result<usize> {
        match self {
            #[cfg(feature = "alloc")]
            Self::Dsa(key) => key.encoded_len(),
            #[cfg(feature = "ecdsa")]
            Self::Ecdsa(key) => key.encoded_len(),
            Self::Ed25519(key) => key.encoded_len(),
            #[cfg(feature = "alloc")]
            Self::Rsa(key) => key.encoded_len(),
            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
            Self::MlDsa44Ed25519(key) => key.encoded_len(),
            #[cfg(all(feature = "mldsa", feature = "p384"))]
            Self::MlDsa87P384(key) => key.encoded_len(),
            #[cfg(feature = "ecdsa")]
            Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len(),
            Self::SkEd25519(sk) => sk.encoded_len(),
            #[cfg(feature = "alloc")]
            Self::Certificate(cert) => cert.encoded_len(),
            #[cfg(feature = "alloc")]
            Self::Other(other) => other.key.encoded_len(),
        }
    }

    /// Encode the key data without a leading algorithm identifier.
    pub(crate) fn encode_key_data(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        match self {
            #[cfg(feature = "alloc")]
            Self::Dsa(key) => key.encode(writer),
            #[cfg(feature = "ecdsa")]
            Self::Ecdsa(key) => key.encode(writer),
            Self::Ed25519(key) => key.encode(writer),
            #[cfg(feature = "alloc")]
            Self::Rsa(key) => key.encode(writer),
            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
            Self::MlDsa44Ed25519(key) => key.encode(writer),
            #[cfg(all(feature = "mldsa", feature = "p384"))]
            Self::MlDsa87P384(key) => key.encode(writer),
            #[cfg(feature = "ecdsa")]
            Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer),
            Self::SkEd25519(sk) => sk.encode(writer),
            #[cfg(feature = "alloc")]
            Self::Certificate(cert) => cert.encode(writer),
            #[cfg(feature = "alloc")]
            Self::Other(other) => other.key.encode(writer),
        }
    }
}

impl Decode for KeyData {
    type Error = Error;

    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
        let algorithm = Algorithm::decode(reader)?;
        #[cfg(feature = "alloc")]
        if let Algorithm::Other(name) = &algorithm {
            if let Ok(certificate_algorithm) = Algorithm::new_certificate(name.as_str()) {
                return Self::decode_as_certificate(reader, certificate_algorithm);
            }
        }
        Self::decode_as(reader, algorithm)
    }
}

impl Encode for KeyData {
    fn encoded_len(&self) -> encoding::Result<usize> {
        #[cfg(feature = "alloc")]
        if self.is_certificate() {
            // Certificate encodes its own Algorithm
            return self.encoded_key_data_len();
        }

        [
            self.algorithm().encoded_len()?,
            self.encoded_key_data_len()?,
        ]
        .checked_sum()
    }

    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        #[cfg(feature = "alloc")]
        if self.is_certificate() {
            // Certificate encodes its own Algorithm
            return self.encode_key_data(writer);
        }

        self.algorithm().encode(writer)?;
        self.encode_key_data(writer)
    }
}

#[cfg(feature = "alloc")]
impl From<DsaPublicKey> for KeyData {
    fn from(public_key: DsaPublicKey) -> KeyData {
        Self::Dsa(public_key)
    }
}

#[cfg(feature = "ecdsa")]
impl From<EcdsaPublicKey> for KeyData {
    fn from(public_key: EcdsaPublicKey) -> KeyData {
        Self::Ecdsa(public_key)
    }
}

impl From<Ed25519PublicKey> for KeyData {
    fn from(public_key: Ed25519PublicKey) -> KeyData {
        Self::Ed25519(public_key)
    }
}

#[cfg(feature = "alloc")]
impl From<RsaPublicKey> for KeyData {
    fn from(public_key: RsaPublicKey) -> KeyData {
        Self::Rsa(public_key)
    }
}

#[cfg(all(feature = "mldsa", feature = "ed25519"))]
impl From<MlDsa44Ed25519PublicKey> for KeyData {
    fn from(public_key: MlDsa44Ed25519PublicKey) -> KeyData {
        Self::MlDsa44Ed25519(public_key)
    }
}

#[cfg(all(feature = "mldsa", feature = "p384"))]
impl From<MlDsa87P384PublicKey> for KeyData {
    fn from(public_key: MlDsa87P384PublicKey) -> KeyData {
        Self::MlDsa87P384(public_key)
    }
}

#[cfg(feature = "ecdsa")]
impl From<SkEcdsaSha2NistP256> for KeyData {
    fn from(public_key: SkEcdsaSha2NistP256) -> KeyData {
        Self::SkEcdsaSha2NistP256(public_key)
    }
}

impl From<SkEd25519> for KeyData {
    fn from(public_key: SkEd25519) -> KeyData {
        Self::SkEd25519(public_key)
    }
}

#[cfg(feature = "alloc")]
impl From<Certificate> for KeyData {
    fn from(certificate: Certificate) -> KeyData {
        Self::Certificate(Box::new(certificate))
    }
}