ssh-key 0.7.0

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
//! Elliptic Curve Digital Signature Algorithm (ECDSA) private keys.

use crate::{Algorithm, EcdsaCurve, Error, Result, public::EcdsaPublicKey};
use core::fmt;
use ctutils::{Choice, CtEq};
use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
use sec1::consts::{U32, U48, U66};
use zeroize::Zeroize;

#[cfg(feature = "rand_core")]
use rand_core::CryptoRng;

#[cfg(all(
    feature = "rand_core",
    any(feature = "p256", feature = "p384", feature = "p521")
))]
use cipher::cipher::common::Generate;

/// Elliptic Curve Digital Signature Algorithm (ECDSA) private key.
#[derive(Clone)]
pub struct EcdsaPrivateKey<const SIZE: usize> {
    /// Byte array containing serialized big endian private scalar.
    bytes: [u8; SIZE],
}

impl<const SIZE: usize> EcdsaPrivateKey<SIZE> {
    /// Minimum allowed size of a private scalar for ECDSA: 192-bits.
    // NOTE: this matches `elliptic_curve::SecretKey::MIN_SIZE` while avoiding a hard dependency
    pub const MIN_SIZE: usize = 24;

    /// Borrow the inner byte array as a slice.
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        self.bytes.as_ref()
    }

    /// Convert to the inner byte array.
    #[must_use]
    pub fn into_bytes(self) -> [u8; SIZE] {
        self.bytes
    }

    /// Does this private key need to be prefixed with a leading zero?
    fn needs_leading_zero(&self) -> bool {
        self.bytes[0] >= 0x80
    }
}

impl<const SIZE: usize> Decode for EcdsaPrivateKey<SIZE> {
    type Error = Error;

    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
        reader.read_prefixed(|reader| {
            // Bound the wire length before stripping any leading zeros.
            match reader.remaining_len().checked_sub(1) {
                Some(len) if len <= SIZE => (),
                _ => return Err(encoding::Error::Length.into()),
            }

            let mut first = u8::decode(reader)?;
            if first >= 0x80 {
                return Err(Error::FormatEncoding);
            }

            // Accept redundant leading zeros
            while first == 0 {
                if reader.is_finished() {
                    return Err(encoding::Error::Length.into());
                }
                first = u8::decode(reader)?;
            }

            let len = reader
                .remaining_len()
                .checked_add(1)
                .ok_or(encoding::Error::Length)?;

            if len < Self::MIN_SIZE || len > SIZE {
                return Err(encoding::Error::Length.into());
            }

            // Add leading zeros if the encoded key is smaller than `SIZE`.
            // The resulting value is big endian and needs leading zero padding.
            let leading_zeros = SIZE.checked_sub(len).ok_or(encoding::Error::Length)?;

            let mut bytes = [0u8; SIZE];
            let (first_byte, remaining) = bytes[leading_zeros..]
                .split_first_mut()
                .ok_or(encoding::Error::Length)?;

            *first_byte = first;
            reader.read(remaining)?;
            Ok(Self { bytes })
        })
    }
}

impl<const SIZE: usize> Encode for EcdsaPrivateKey<SIZE> {
    fn encoded_len(&self) -> encoding::Result<usize> {
        [4, self.needs_leading_zero().into(), SIZE].checked_sum()
    }

    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        [self.needs_leading_zero().into(), SIZE]
            .checked_sum()?
            .encode(writer)?;

        if self.needs_leading_zero() {
            writer.write(&[0])?;
        }

        writer.write(&self.bytes)?;
        Ok(())
    }
}

impl<const SIZE: usize> From<[u8; SIZE]> for EcdsaPrivateKey<SIZE> {
    fn from(bytes: [u8; SIZE]) -> Self {
        Self { bytes }
    }
}

impl<const SIZE: usize> AsRef<[u8; SIZE]> for EcdsaPrivateKey<SIZE> {
    fn as_ref(&self) -> &[u8; SIZE] {
        &self.bytes
    }
}

impl<const SIZE: usize> CtEq for EcdsaPrivateKey<SIZE> {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.as_ref().ct_eq(other.as_ref())
    }
}

impl<const SIZE: usize> PartialEq for EcdsaPrivateKey<SIZE> {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

impl<const SIZE: usize> Eq for EcdsaPrivateKey<SIZE> {}

impl<const SIZE: usize> fmt::Debug for EcdsaPrivateKey<SIZE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EcdsaPrivateKey").finish_non_exhaustive()
    }
}

impl<const SIZE: usize> fmt::LowerHex for EcdsaPrivateKey<SIZE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.as_ref() {
            write!(f, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl<const SIZE: usize> fmt::UpperHex for EcdsaPrivateKey<SIZE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.as_ref() {
            write!(f, "{byte:02X}")?;
        }
        Ok(())
    }
}

impl<const SIZE: usize> Drop for EcdsaPrivateKey<SIZE> {
    fn drop(&mut self) {
        self.bytes.zeroize();
    }
}

#[cfg(feature = "p256")]
impl From<p256::SecretKey> for EcdsaPrivateKey<32> {
    fn from(sk: p256::SecretKey) -> EcdsaPrivateKey<32> {
        EcdsaPrivateKey {
            bytes: sk.to_bytes().into(),
        }
    }
}

#[cfg(feature = "p384")]
impl From<p384::SecretKey> for EcdsaPrivateKey<48> {
    fn from(sk: p384::SecretKey) -> EcdsaPrivateKey<48> {
        EcdsaPrivateKey {
            bytes: sk.to_bytes().into(),
        }
    }
}

#[cfg(feature = "p521")]
impl From<p521::SecretKey> for EcdsaPrivateKey<66> {
    fn from(sk: p521::SecretKey) -> EcdsaPrivateKey<66> {
        // TODO(tarcieri): clean this up when migrating to hybrid-array
        let mut bytes = [0u8; 66];
        bytes.copy_from_slice(&sk.to_bytes());
        EcdsaPrivateKey { bytes }
    }
}

/// Elliptic Curve Digital Signature Algorithm (ECDSA) private/public keypair.
#[derive(Clone, Debug)]
pub enum EcdsaKeypair {
    /// NIST P-256 ECDSA keypair.
    NistP256 {
        /// Public key.
        public: sec1::EncodedPoint<U32>,

        /// Private key.
        private: EcdsaPrivateKey<32>,
    },

    /// NIST P-384 ECDSA keypair.
    NistP384 {
        /// Public key.
        public: sec1::EncodedPoint<U48>,

        /// Private key.
        private: EcdsaPrivateKey<48>,
    },

    /// NIST P-521 ECDSA keypair.
    NistP521 {
        /// Public key.
        public: sec1::EncodedPoint<U66>,

        /// Private key.
        private: EcdsaPrivateKey<66>,
    },
}

impl EcdsaKeypair {
    /// Generate a random ECDSA private key.
    ///
    /// # Errors
    /// Returns [`Error::AlgorithmUnsupported`] if support has not been enabled for the given
    /// elliptic curve, e.g. the `p256`, `p384`, or `p521` crate feature has not been enabled.
    #[cfg(feature = "rand_core")]
    #[allow(unused_variables)]
    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, curve: EcdsaCurve) -> Result<Self> {
        match curve {
            #[cfg(feature = "p256")]
            EcdsaCurve::NistP256 => {
                let private = p256::SecretKey::generate_from_rng(rng);
                let public = private.public_key();
                Ok(EcdsaKeypair::NistP256 {
                    private: private.into(),
                    public: public.into(),
                })
            }
            #[cfg(feature = "p384")]
            EcdsaCurve::NistP384 => {
                let private = p384::SecretKey::generate_from_rng(rng);
                let public = private.public_key();
                Ok(EcdsaKeypair::NistP384 {
                    private: private.into(),
                    public: public.into(),
                })
            }
            #[cfg(feature = "p521")]
            EcdsaCurve::NistP521 => {
                let private = p521::SecretKey::generate_from_rng(rng);
                let public = private.public_key();
                Ok(EcdsaKeypair::NistP521 {
                    private: private.into(),
                    public: public.into(),
                })
            }
            #[cfg(not(all(feature = "p256", feature = "p384", feature = "p521")))]
            _ => Err(Error::AlgorithmUnsupported {
                algorithm: curve.into(),
            }),
        }
    }

    /// Get the [`Algorithm`] for this public key type.
    #[must_use]
    pub fn algorithm(&self) -> Algorithm {
        Algorithm::Ecdsa {
            curve: self.curve(),
        }
    }

    /// Get the [`EcdsaCurve`] for this key.
    #[must_use]
    pub fn curve(&self) -> EcdsaCurve {
        match self {
            Self::NistP256 { .. } => EcdsaCurve::NistP256,
            Self::NistP384 { .. } => EcdsaCurve::NistP384,
            Self::NistP521 { .. } => EcdsaCurve::NistP521,
        }
    }

    /// Get the bytes representing the public key.
    #[must_use]
    pub fn public_key_bytes(&self) -> &[u8] {
        match self {
            Self::NistP256 { public, .. } => public.as_ref(),
            Self::NistP384 { public, .. } => public.as_ref(),
            Self::NistP521 { public, .. } => public.as_ref(),
        }
    }

    /// Get the bytes representing the private key.
    #[must_use]
    pub fn private_key_bytes(&self) -> &[u8] {
        match self {
            Self::NistP256 { private, .. } => private.as_ref(),
            Self::NistP384 { private, .. } => private.as_ref(),
            Self::NistP521 { private, .. } => private.as_ref(),
        }
    }
}

impl CtEq for EcdsaKeypair {
    fn ct_eq(&self, other: &Self) -> Choice {
        let public_eq = Choice::from(u8::from(
            EcdsaPublicKey::from(self) == EcdsaPublicKey::from(other),
        ));

        let private_key_a = match self {
            Self::NistP256 { private, .. } => private.as_slice(),
            Self::NistP384 { private, .. } => private.as_slice(),
            Self::NistP521 { private, .. } => private.as_slice(),
        };

        let private_key_b = match other {
            Self::NistP256 { private, .. } => private.as_slice(),
            Self::NistP384 { private, .. } => private.as_slice(),
            Self::NistP521 { private, .. } => private.as_slice(),
        };

        public_eq & private_key_a.ct_eq(private_key_b)
    }
}

impl Eq for EcdsaKeypair {}

impl PartialEq for EcdsaKeypair {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

impl Decode for EcdsaKeypair {
    type Error = Error;

    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
        match EcdsaPublicKey::decode(reader)? {
            EcdsaPublicKey::NistP256(public) => {
                let private = EcdsaPrivateKey::<32>::decode(reader)?;
                Ok(Self::NistP256 { public, private })
            }
            EcdsaPublicKey::NistP384(public) => {
                let private = EcdsaPrivateKey::<48>::decode(reader)?;
                Ok(Self::NistP384 { public, private })
            }
            EcdsaPublicKey::NistP521(public) => {
                let private = EcdsaPrivateKey::<66>::decode(reader)?;
                Ok(Self::NistP521 { public, private })
            }
        }
    }
}

impl Encode for EcdsaKeypair {
    fn encoded_len(&self) -> encoding::Result<usize> {
        let public_len = EcdsaPublicKey::from(self).encoded_len()?;

        let private_len = match self {
            Self::NistP256 { private, .. } => private.encoded_len()?,
            Self::NistP384 { private, .. } => private.encoded_len()?,
            Self::NistP521 { private, .. } => private.encoded_len()?,
        };

        [public_len, private_len].checked_sum()
    }

    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        EcdsaPublicKey::from(self).encode(writer)?;

        match self {
            Self::NistP256 { private, .. } => private.encode(writer)?,
            Self::NistP384 { private, .. } => private.encode(writer)?,
            Self::NistP521 { private, .. } => private.encode(writer)?,
        }

        Ok(())
    }
}

impl From<EcdsaKeypair> for EcdsaPublicKey {
    fn from(keypair: EcdsaKeypair) -> EcdsaPublicKey {
        EcdsaPublicKey::from(&keypair)
    }
}

impl From<&EcdsaKeypair> for EcdsaPublicKey {
    fn from(keypair: &EcdsaKeypair) -> EcdsaPublicKey {
        match keypair {
            EcdsaKeypair::NistP256 { public, .. } => EcdsaPublicKey::NistP256(*public),
            EcdsaKeypair::NistP384 { public, .. } => EcdsaPublicKey::NistP384(*public),
            EcdsaKeypair::NistP521 { public, .. } => EcdsaPublicKey::NistP521(*public),
        }
    }
}