Skip to main content

ssh_key/private/
keypair.rs

1//! Private key pairs.
2
3use super::ed25519::Ed25519Keypair;
4use crate::{Algorithm, Error, Result, public};
5use ctutils::{Choice, CtEq};
6use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
7
8#[cfg(feature = "alloc")]
9use {
10    super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
11    alloc::vec::Vec,
12};
13
14#[cfg(all(feature = "mldsa", feature = "ed25519"))]
15use super::MlDsa44Ed25519Keypair;
16#[cfg(all(feature = "mldsa", feature = "p384"))]
17use super::MlDsa87P384Keypair;
18
19#[cfg(feature = "ecdsa")]
20use super::EcdsaKeypair;
21
22#[cfg(all(feature = "alloc", feature = "ecdsa"))]
23use super::SkEcdsaSha2NistP256;
24
25/// Private key data: digital signature key pairs.
26///
27/// SSH private keys contain pairs of public and private keys for various
28/// supported digital signature algorithms.
29// TODO(tarcieri): pseudo-private keys for FIDO/U2F security keys
30#[derive(Clone, Debug)]
31#[non_exhaustive]
32pub enum KeypairData {
33    /// Digital Signature Algorithm (DSA) keypair.
34    #[cfg(feature = "alloc")]
35    Dsa(DsaKeypair),
36
37    /// ECDSA keypair.
38    #[cfg(feature = "ecdsa")]
39    Ecdsa(EcdsaKeypair),
40
41    /// Ed25519 keypair.
42    Ed25519(Ed25519Keypair),
43
44    /// Encrypted private key (ciphertext).
45    #[cfg(feature = "alloc")]
46    Encrypted(Vec<u8>),
47
48    /// RSA keypair.
49    #[cfg(feature = "alloc")]
50    Rsa(RsaKeypair),
51
52    /// MLDSA44-Ed25519 keypair
53    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
54    MlDsa44Ed25519(MlDsa44Ed25519Keypair),
55
56    /// MLDSA87-P384 keypair
57    #[cfg(all(feature = "mldsa", feature = "p384"))]
58    MlDsa87P384(MlDsa87P384Keypair),
59
60    /// Security Key (FIDO/U2F) using ECDSA/NIST P-256 as specified in [PROTOCOL.u2f].
61    ///
62    /// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
63    #[cfg(all(feature = "alloc", feature = "ecdsa"))]
64    SkEcdsaSha2NistP256(SkEcdsaSha2NistP256),
65
66    /// Security Key (FIDO/U2F) using Ed25519 as specified in [PROTOCOL.u2f].
67    ///
68    /// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
69    #[cfg(feature = "alloc")]
70    SkEd25519(SkEd25519),
71
72    /// Opaque keypair.
73    #[cfg(feature = "alloc")]
74    Other(OpaqueKeypair),
75}
76
77impl KeypairData {
78    /// Get the [`Algorithm`] for this private key.
79    ///
80    /// # Errors
81    /// Returns [`Error::Encrypted`] if the private key is encrypted.
82    pub fn algorithm(&self) -> Result<Algorithm> {
83        Ok(match self {
84            #[cfg(feature = "alloc")]
85            Self::Dsa(_) => Algorithm::Dsa,
86            #[cfg(feature = "ecdsa")]
87            Self::Ecdsa(key) => key.algorithm(),
88            Self::Ed25519(_) => Algorithm::Ed25519,
89            #[cfg(feature = "alloc")]
90            Self::Encrypted(_) => return Err(Error::Encrypted),
91            #[cfg(feature = "alloc")]
92            Self::Rsa(_) => Algorithm::Rsa { hash: None },
93            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
94            Self::MlDsa44Ed25519(key) => key.algorithm(),
95            #[cfg(all(feature = "mldsa", feature = "p384"))]
96            Self::MlDsa87P384(key) => key.algorithm(),
97            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
98            Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
99            #[cfg(feature = "alloc")]
100            Self::SkEd25519(_) => Algorithm::SkEd25519,
101            #[cfg(feature = "alloc")]
102            Self::Other(key) => key.algorithm(),
103        })
104    }
105
106    /// Get DSA keypair if this key is the correct type.
107    #[cfg(feature = "alloc")]
108    #[must_use]
109    pub fn dsa(&self) -> Option<&DsaKeypair> {
110        match self {
111            Self::Dsa(key) => Some(key),
112            _ => None,
113        }
114    }
115
116    /// Get ECDSA private key if this key is the correct type.
117    #[cfg(feature = "ecdsa")]
118    #[must_use]
119    pub fn ecdsa(&self) -> Option<&EcdsaKeypair> {
120        match self {
121            Self::Ecdsa(keypair) => Some(keypair),
122            _ => None,
123        }
124    }
125
126    /// Get Ed25519 private key if this key is the correct type.
127    #[must_use]
128    pub fn ed25519(&self) -> Option<&Ed25519Keypair> {
129        match self {
130            Self::Ed25519(key) => Some(key),
131            #[allow(unreachable_patterns)]
132            _ => None,
133        }
134    }
135
136    /// Get the encrypted ciphertext if this key is encrypted.
137    #[cfg(feature = "alloc")]
138    #[must_use]
139    pub fn encrypted(&self) -> Option<&[u8]> {
140        match self {
141            Self::Encrypted(ciphertext) => Some(ciphertext),
142            _ => None,
143        }
144    }
145
146    /// Get RSA keypair if this key is the correct type.
147    #[cfg(feature = "alloc")]
148    #[must_use]
149    pub fn rsa(&self) -> Option<&RsaKeypair> {
150        match self {
151            Self::Rsa(key) => Some(key),
152            _ => None,
153        }
154    }
155
156    /// Get MLDSA44-Ed25519 keypair if this key is the correct type.
157    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
158    #[must_use]
159    pub fn mldsa44_ed25519(&self) -> Option<&MlDsa44Ed25519Keypair> {
160        match self {
161            Self::MlDsa44Ed25519(key) => Some(key),
162            _ => None,
163        }
164    }
165
166    /// Get MLDSA87-P384 keypair if this key is the correct type.
167    #[cfg(all(feature = "mldsa", feature = "p384"))]
168    #[must_use]
169    pub fn mldsa87_p384(&self) -> Option<&MlDsa87P384Keypair> {
170        match self {
171            Self::MlDsa87P384(key) => Some(key),
172            _ => None,
173        }
174    }
175
176    /// Get FIDO/U2F ECDSA/NIST P-256 private key if this key is the correct type.
177    #[cfg(all(feature = "alloc", feature = "ecdsa"))]
178    #[must_use]
179    pub fn sk_ecdsa_p256(&self) -> Option<&SkEcdsaSha2NistP256> {
180        match self {
181            Self::SkEcdsaSha2NistP256(sk) => Some(sk),
182            _ => None,
183        }
184    }
185
186    /// Get FIDO/U2F Ed25519 private key if this key is the correct type.
187    #[cfg(feature = "alloc")]
188    #[must_use]
189    pub fn sk_ed25519(&self) -> Option<&SkEd25519> {
190        match self {
191            Self::SkEd25519(sk) => Some(sk),
192            _ => None,
193        }
194    }
195
196    /// Get the custom, opaque private key if this key is the correct type.
197    #[cfg(feature = "alloc")]
198    #[must_use]
199    pub fn other(&self) -> Option<&OpaqueKeypair> {
200        match self {
201            Self::Other(key) => Some(key),
202            _ => None,
203        }
204    }
205
206    /// Is this key a DSA key?
207    #[cfg(feature = "alloc")]
208    #[must_use]
209    pub fn is_dsa(&self) -> bool {
210        matches!(self, Self::Dsa(_))
211    }
212
213    /// Is this key an ECDSA key?
214    #[cfg(feature = "ecdsa")]
215    #[must_use]
216    pub fn is_ecdsa(&self) -> bool {
217        matches!(self, Self::Ecdsa(_))
218    }
219
220    /// Is this key an Ed25519 key?
221    #[must_use]
222    pub fn is_ed25519(&self) -> bool {
223        matches!(self, Self::Ed25519(_))
224    }
225
226    /// Is this key encrypted?
227    #[cfg(not(feature = "alloc"))]
228    #[must_use]
229    pub fn is_encrypted(&self) -> bool {
230        false
231    }
232
233    /// Is this key encrypted?
234    #[cfg(feature = "alloc")]
235    #[must_use]
236    pub fn is_encrypted(&self) -> bool {
237        matches!(self, Self::Encrypted(_))
238    }
239
240    /// Is this key an RSA key?
241    #[cfg(feature = "alloc")]
242    #[must_use]
243    pub fn is_rsa(&self) -> bool {
244        matches!(self, Self::Rsa(_))
245    }
246
247    /// Is this key an ML-DSA-44-Ed25519 composite key?
248    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
249    #[must_use]
250    pub fn is_mldsa44_ed25519(&self) -> bool {
251        matches!(self, Self::MlDsa44Ed25519(_))
252    }
253
254    /// Is this key an ML-DSA-87/P-384 composite key?
255    #[cfg(all(feature = "mldsa", feature = "p384"))]
256    #[must_use]
257    pub fn is_mldsa87_p384(&self) -> bool {
258        matches!(self, Self::MlDsa87P384(_))
259    }
260
261    /// Is this key a FIDO/U2F ECDSA/NIST P-256 key?
262    #[cfg(all(feature = "alloc", feature = "ecdsa"))]
263    #[must_use]
264    pub fn is_sk_ecdsa_p256(&self) -> bool {
265        matches!(self, Self::SkEcdsaSha2NistP256(_))
266    }
267
268    /// Is this key a FIDO/U2F Ed25519 key?
269    #[cfg(feature = "alloc")]
270    #[must_use]
271    pub fn is_sk_ed25519(&self) -> bool {
272        matches!(self, Self::SkEd25519(_))
273    }
274
275    /// Is this a key with a custom algorithm?
276    #[cfg(feature = "alloc")]
277    #[must_use]
278    pub fn is_other(&self) -> bool {
279        matches!(self, Self::Other(_))
280    }
281
282    /// Compute a deterministic "checkint" for this private key.
283    ///
284    /// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
285    // TODO(tarcieri): true randomness or a better algorithm?
286    pub(super) fn checkint(&self) -> u32 {
287        let bytes = match self {
288            #[cfg(feature = "alloc")]
289            Self::Dsa(dsa) => dsa.private().as_bytes(),
290            #[cfg(feature = "ecdsa")]
291            Self::Ecdsa(ecdsa) => ecdsa.private_key_bytes(),
292            Self::Ed25519(ed25519) => ed25519.private.as_ref(),
293            #[cfg(feature = "alloc")]
294            Self::Encrypted(ciphertext) => ciphertext.as_ref(),
295            #[cfg(feature = "alloc")]
296            Self::Rsa(rsa) => rsa.private().d().as_bytes(),
297            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
298            Self::MlDsa44Ed25519(mldsa) => mldsa.private.checkint_bytes(),
299            #[cfg(all(feature = "mldsa", feature = "p384"))]
300            Self::MlDsa87P384(mldsa) => mldsa.private().checkint_bytes(),
301            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
302            Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
303            #[cfg(feature = "alloc")]
304            Self::SkEd25519(sk) => sk.key_handle(),
305            #[cfg(feature = "alloc")]
306            Self::Other(key) => key.private.as_ref(),
307        };
308
309        let mut n = 0u32;
310
311        for chunk in bytes.chunks_exact(4) {
312            n ^= u32::from_be_bytes(chunk.try_into().expect("not 4 bytes"));
313        }
314
315        n
316    }
317
318    /// Decode [`KeypairData`] for the specified algorithm.
319    ///
320    /// # Errors
321    /// - Returns [`Error::AlgorithmUnknown`] if the provided `algorithm` is unknown or unsupported
322    ///   by this library.
323    /// - Returns [`Error::Encoding`] in the event of an encoding error.
324    pub fn decode_as(reader: &mut Decoder<impl Reader>, algorithm: Algorithm) -> Result<Self> {
325        match algorithm {
326            #[cfg(feature = "alloc")]
327            Algorithm::Dsa => DsaKeypair::decode(reader).map(Self::Dsa),
328            #[cfg(feature = "ecdsa")]
329            Algorithm::Ecdsa { curve } => match EcdsaKeypair::decode(reader)? {
330                keypair if keypair.curve() == curve => Ok(Self::Ecdsa(keypair)),
331                _ => Err(Error::AlgorithmUnknown),
332            },
333            Algorithm::Ed25519 => Ed25519Keypair::decode(reader).map(Self::Ed25519),
334            #[cfg(feature = "alloc")]
335            Algorithm::Rsa { .. } => RsaKeypair::decode(reader).map(Self::Rsa),
336            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
337            Algorithm::MlDsa44Ed25519 => {
338                MlDsa44Ed25519Keypair::decode(reader).map(Self::MlDsa44Ed25519)
339            }
340            #[cfg(all(feature = "mldsa", feature = "p384"))]
341            Algorithm::MlDsa87P384 => MlDsa87P384Keypair::decode(reader).map(Self::MlDsa87P384),
342            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
343            Algorithm::SkEcdsaSha2NistP256 => {
344                SkEcdsaSha2NistP256::decode(reader).map(Self::SkEcdsaSha2NistP256)
345            }
346            #[cfg(feature = "alloc")]
347            Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
348            #[cfg(feature = "alloc")]
349            algorithm @ Algorithm::Other(_) => {
350                OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
351            }
352            #[allow(unreachable_patterns)]
353            _ => Err(Error::AlgorithmUnknown),
354        }
355    }
356}
357
358impl CtEq for KeypairData {
359    fn ct_eq(&self, other: &Self) -> Choice {
360        // Note: constant-time with respect to key *data* comparisons, not algorithms
361        match (self, other) {
362            #[cfg(feature = "alloc")]
363            (Self::Dsa(a), Self::Dsa(b)) => a.ct_eq(b),
364            #[cfg(feature = "ecdsa")]
365            (Self::Ecdsa(a), Self::Ecdsa(b)) => a.ct_eq(b),
366            (Self::Ed25519(a), Self::Ed25519(b)) => a.ct_eq(b),
367            #[cfg(feature = "alloc")]
368            (Self::Encrypted(a), Self::Encrypted(b)) => a.ct_eq(b),
369            #[cfg(feature = "alloc")]
370            (Self::Rsa(a), Self::Rsa(b)) => a.ct_eq(b),
371            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
372            (Self::MlDsa44Ed25519(a), Self::MlDsa44Ed25519(b)) => a.ct_eq(b),
373            #[cfg(all(feature = "mldsa", feature = "p384"))]
374            (Self::MlDsa87P384(a), Self::MlDsa87P384(b)) => a.ct_eq(b),
375            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
376            (Self::SkEcdsaSha2NistP256(a), Self::SkEcdsaSha2NistP256(b)) => {
377                // Security Keys store the actual private key in hardware.
378                // The key structs contain all public data.
379                Choice::from(u8::from(a == b))
380            }
381            #[cfg(feature = "alloc")]
382            (Self::SkEd25519(a), Self::SkEd25519(b)) => {
383                // Security Keys store the actual private key in hardware.
384                // The key structs contain all public data.
385                Choice::from(u8::from(a == b))
386            }
387            #[cfg(feature = "alloc")]
388            (Self::Other(a), Self::Other(b)) => a.ct_eq(b),
389            #[allow(unreachable_patterns)]
390            _ => Choice::from(0),
391        }
392    }
393}
394
395impl Eq for KeypairData {}
396
397impl PartialEq for KeypairData {
398    fn eq(&self, other: &Self) -> bool {
399        self.ct_eq(other).into()
400    }
401}
402
403impl Decode for KeypairData {
404    type Error = Error;
405
406    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
407        let algorithm = Algorithm::decode(reader)?;
408        Self::decode_as(reader, algorithm)
409    }
410}
411
412impl Encode for KeypairData {
413    fn encoded_len(&self) -> encoding::Result<usize> {
414        let alg_len = self
415            .algorithm()
416            .ok()
417            .map(|alg| alg.encoded_len())
418            .transpose()?
419            .unwrap_or(0);
420
421        let key_len = match self {
422            #[cfg(feature = "alloc")]
423            Self::Dsa(key) => key.encoded_len()?,
424            #[cfg(feature = "ecdsa")]
425            Self::Ecdsa(key) => key.encoded_len()?,
426            Self::Ed25519(key) => key.encoded_len()?,
427            #[cfg(feature = "alloc")]
428            Self::Encrypted(ciphertext) => return Ok(ciphertext.len()),
429            #[cfg(feature = "alloc")]
430            Self::Rsa(key) => key.encoded_len()?,
431            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
432            Self::MlDsa44Ed25519(key) => key.encoded_len()?,
433            #[cfg(all(feature = "mldsa", feature = "p384"))]
434            Self::MlDsa87P384(key) => key.encoded_len()?,
435            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
436            Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
437            #[cfg(feature = "alloc")]
438            Self::SkEd25519(sk) => sk.encoded_len()?,
439            #[cfg(feature = "alloc")]
440            Self::Other(key) => key.encoded_len()?,
441        };
442
443        [alg_len, key_len].checked_sum()
444    }
445
446    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
447        if let Ok(alg) = self.algorithm() {
448            alg.encode(writer)?;
449        }
450
451        match self {
452            #[cfg(feature = "alloc")]
453            Self::Dsa(key) => key.encode(writer)?,
454            #[cfg(feature = "ecdsa")]
455            Self::Ecdsa(key) => key.encode(writer)?,
456            Self::Ed25519(key) => key.encode(writer)?,
457            #[cfg(feature = "alloc")]
458            Self::Encrypted(ciphertext) => writer.write(ciphertext)?,
459            #[cfg(feature = "alloc")]
460            Self::Rsa(key) => key.encode(writer)?,
461            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
462            Self::MlDsa44Ed25519(key) => key.encode(writer)?,
463            #[cfg(all(feature = "mldsa", feature = "p384"))]
464            Self::MlDsa87P384(key) => key.encode(writer)?,
465            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
466            Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
467            #[cfg(feature = "alloc")]
468            Self::SkEd25519(sk) => sk.encode(writer)?,
469            #[cfg(feature = "alloc")]
470            Self::Other(key) => key.encode(writer)?,
471        }
472
473        Ok(())
474    }
475}
476
477impl TryFrom<&KeypairData> for public::KeyData {
478    type Error = Error;
479
480    fn try_from(keypair_data: &KeypairData) -> Result<public::KeyData> {
481        Ok(match keypair_data {
482            #[cfg(feature = "alloc")]
483            KeypairData::Dsa(dsa) => public::KeyData::Dsa(dsa.into()),
484            #[cfg(feature = "ecdsa")]
485            KeypairData::Ecdsa(ecdsa) => public::KeyData::Ecdsa(ecdsa.into()),
486            KeypairData::Ed25519(ed25519) => public::KeyData::Ed25519(ed25519.into()),
487            #[cfg(feature = "alloc")]
488            KeypairData::Encrypted(_) => return Err(Error::Encrypted),
489            #[cfg(feature = "alloc")]
490            KeypairData::Rsa(rsa) => public::KeyData::Rsa(rsa.into()),
491            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
492            KeypairData::MlDsa44Ed25519(mldsa) => public::KeyData::MlDsa44Ed25519(mldsa.into()),
493            #[cfg(all(feature = "mldsa", feature = "p384"))]
494            KeypairData::MlDsa87P384(mldsa) => public::KeyData::MlDsa87P384(mldsa.into()),
495            #[cfg(all(feature = "alloc", feature = "ecdsa"))]
496            KeypairData::SkEcdsaSha2NistP256(sk) => {
497                public::KeyData::SkEcdsaSha2NistP256(sk.public().clone())
498            }
499            #[cfg(feature = "alloc")]
500            KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
501            #[cfg(feature = "alloc")]
502            KeypairData::Other(key) => public::KeyData::Other(key.into()),
503        })
504    }
505}
506
507#[cfg(feature = "alloc")]
508impl From<DsaKeypair> for KeypairData {
509    fn from(keypair: DsaKeypair) -> KeypairData {
510        Self::Dsa(keypair)
511    }
512}
513
514#[cfg(feature = "ecdsa")]
515impl From<EcdsaKeypair> for KeypairData {
516    fn from(keypair: EcdsaKeypair) -> KeypairData {
517        Self::Ecdsa(keypair)
518    }
519}
520
521impl From<Ed25519Keypair> for KeypairData {
522    fn from(keypair: Ed25519Keypair) -> KeypairData {
523        Self::Ed25519(keypair)
524    }
525}
526
527#[cfg(feature = "alloc")]
528impl From<RsaKeypair> for KeypairData {
529    fn from(keypair: RsaKeypair) -> KeypairData {
530        Self::Rsa(keypair)
531    }
532}
533
534#[cfg(all(feature = "mldsa", feature = "ed25519"))]
535impl From<MlDsa44Ed25519Keypair> for KeypairData {
536    fn from(keypair: MlDsa44Ed25519Keypair) -> KeypairData {
537        Self::MlDsa44Ed25519(keypair)
538    }
539}
540
541#[cfg(all(feature = "mldsa", feature = "p384"))]
542impl From<MlDsa87P384Keypair> for KeypairData {
543    fn from(keypair: MlDsa87P384Keypair) -> KeypairData {
544        Self::MlDsa87P384(keypair)
545    }
546}
547
548#[cfg(all(feature = "alloc", feature = "ecdsa"))]
549impl From<SkEcdsaSha2NistP256> for KeypairData {
550    fn from(keypair: SkEcdsaSha2NistP256) -> KeypairData {
551        Self::SkEcdsaSha2NistP256(keypair)
552    }
553}
554
555#[cfg(feature = "alloc")]
556impl From<SkEd25519> for KeypairData {
557    fn from(keypair: SkEd25519) -> KeypairData {
558        Self::SkEd25519(keypair)
559    }
560}