Skip to main content

ssh_key/
kdf.rs

1//! Key Derivation Functions.
2//!
3//! These are used for deriving an encryption key from a password.
4
5use crate::{Error, KdfAlg, Result};
6use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
7
8#[cfg(feature = "alloc")]
9use alloc::vec::Vec;
10
11#[cfg(feature = "encryption")]
12use {crate::Cipher, bcrypt_pbkdf::bcrypt_pbkdf, rand_core::TryCryptoRng, zeroize::Zeroizing};
13
14/// Default number of rounds to use for bcrypt-pbkdf. Matches OpenSSH's `DEFAULT_ROUNDS`.
15// https://github.com/openssh/openssh-portable/commit/f938c78d490cb7556aa8ca1625e9b9bd1f963ed3
16#[cfg(feature = "encryption")]
17const DEFAULT_BCRYPT_ROUNDS: u32 = 32;
18
19/// Maximum number of rounds for bcrypt-pbkdf. Matches OpenSSH's `MAX_KDF_ROUNDS`.
20// https://github.com/openssh/openssh-portable/commit/f938c78d490cb7556aa8ca1625e9b9bd1f963ed3
21#[cfg(feature = "alloc")]
22const MAX_BCRYPT_ROUNDS: u32 = 1 << 20;
23
24/// Default salt size. Matches OpenSSH.
25#[cfg(feature = "encryption")]
26const DEFAULT_SALT_SIZE: usize = 16;
27
28/// Key Derivation Functions (KDF).
29#[derive(Clone, Debug, Eq, PartialEq)]
30#[non_exhaustive]
31#[derive(Default)]
32pub enum Kdf {
33    /// No KDF.
34    #[default]
35    None,
36
37    /// bcrypt-pbkdf options.
38    #[cfg(feature = "alloc")]
39    Bcrypt {
40        /// Salt: recommended 16-bytes and random.
41        salt: Vec<u8>,
42
43        /// Rounds: must be within `1..=1_048_576`.
44        rounds: u32,
45    },
46}
47
48impl Kdf {
49    /// Initialize KDF configuration for the given algorithm.
50    ///
51    /// # Errors
52    /// Returns [`Error::RngFailure`] on RNG errors.
53    #[cfg(feature = "encryption")]
54    pub fn new<R: TryCryptoRng + ?Sized>(algorithm: KdfAlg, rng: &mut R) -> Result<Self> {
55        let mut salt = vec![0u8; DEFAULT_SALT_SIZE];
56        rng.try_fill_bytes(&mut salt)
57            .map_err(|_| Error::RngFailure)?;
58
59        match algorithm {
60            KdfAlg::None => {
61                // Disallow explicit initialization with a `none` algorithm
62                Err(Error::AlgorithmUnknown)
63            }
64            KdfAlg::Bcrypt => Ok(Kdf::Bcrypt {
65                salt,
66                rounds: DEFAULT_BCRYPT_ROUNDS,
67            }),
68        }
69    }
70
71    /// Get the KDF algorithm.
72    #[must_use]
73    pub fn algorithm(&self) -> KdfAlg {
74        match self {
75            Self::None => KdfAlg::None,
76            #[cfg(feature = "alloc")]
77            Self::Bcrypt { .. } => KdfAlg::Bcrypt,
78        }
79    }
80
81    /// Derive an encryption key from the given password.
82    ///
83    /// # Errors
84    /// Returns [`Error::Crypto`] if the bcrypt round count is zero or exceeds 1,048,576, or if the
85    /// underlying password hashing primitive returns an error.
86    #[cfg(feature = "encryption")]
87    pub fn derive(&self, password: impl AsRef<[u8]>, output: &mut [u8]) -> Result<()> {
88        match self {
89            Kdf::None => Err(Error::Decrypted),
90            Kdf::Bcrypt { salt, rounds } => {
91                validate_bcrypt_rounds(*rounds)?;
92                bcrypt_pbkdf(password, salt, *rounds, output).map_err(|_| Error::Crypto)?;
93                Ok(())
94            }
95        }
96    }
97
98    /// Derive key and IV for the given [`Cipher`].
99    ///
100    /// Returns two byte vectors containing the key and IV respectively.
101    ///
102    /// # Errors
103    /// - Returns [`Error::Decrypted`] if `cipher` is [`Cipher::None`].
104    /// - Returns [`Error::Encoding`] in the event of a length error.
105    /// - Propagates errors returned from [`Self::derive`].
106    #[cfg(feature = "encryption")]
107    pub fn derive_key_and_iv(
108        &self,
109        cipher: Cipher,
110        password: impl AsRef<[u8]>,
111    ) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
112        let (key_size, iv_size) = cipher.key_and_iv_size().ok_or(Error::Decrypted)?;
113
114        let okm_size = key_size
115            .checked_add(iv_size)
116            .ok_or(encoding::Error::Length)?;
117
118        let mut okm = Zeroizing::new(vec![0u8; okm_size]);
119        self.derive(password, &mut okm)?;
120        let mut iv = okm.split_off(key_size);
121
122        // For whatever reason `chacha20-poly1305@openssh.com` uses a nonce of all zeros for private
123        // key encryption, relying on a unique salt used in the password-based encryption key
124        // derivation to ensure that each encryption key is only used once.
125        if cipher == Cipher::ChaCha20Poly1305 {
126            iv.copy_from_slice(&cipher::ChaChaNonce::default());
127        }
128
129        Ok((okm, iv))
130    }
131
132    /// Is the KDF configured as `none`?
133    #[must_use]
134    pub fn is_none(&self) -> bool {
135        self == &Self::None
136    }
137
138    /// Is the KDF configured as anything other than `none`?
139    #[must_use]
140    pub fn is_some(&self) -> bool {
141        !self.is_none()
142    }
143
144    /// Is the KDF configured as `bcrypt` (i.e. bcrypt-pbkdf)?
145    #[cfg(feature = "alloc")]
146    #[must_use]
147    pub fn is_bcrypt(&self) -> bool {
148        matches!(self, Self::Bcrypt { .. })
149    }
150}
151
152impl Decode for Kdf {
153    type Error = Error;
154
155    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
156        match KdfAlg::decode(reader)? {
157            KdfAlg::None => {
158                if usize::decode(reader)? == 0 {
159                    Ok(Self::None)
160                } else {
161                    Err(Error::AlgorithmUnknown)
162                }
163            }
164            KdfAlg::Bcrypt => {
165                #[cfg(not(feature = "alloc"))]
166                return Err(Error::AlgorithmUnknown);
167
168                #[cfg(feature = "alloc")]
169                reader.read_prefixed(|reader| {
170                    let salt = Vec::decode(reader)?;
171                    let rounds = u32::decode(reader)?;
172                    validate_bcrypt_rounds(rounds)?;
173                    Ok(Self::Bcrypt { salt, rounds })
174                })
175            }
176        }
177    }
178}
179
180impl Encode for Kdf {
181    fn encoded_len(&self) -> encoding::Result<usize> {
182        let kdfopts_prefixed_len = match self {
183            Self::None => 4,
184            #[cfg(feature = "alloc")]
185            Self::Bcrypt { salt, rounds } => {
186                validate_bcrypt_rounds(*rounds).map_err(|_| encoding::Error::Overflow)?;
187                [12, salt.len()].checked_sum()?
188            }
189        };
190
191        [self.algorithm().encoded_len()?, kdfopts_prefixed_len].checked_sum()
192    }
193
194    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
195        // Validate before writing any part of the KDF.
196        self.encoded_len()?;
197        self.algorithm().encode(writer)?;
198
199        match self {
200            Self::None => 0usize.encode(writer)?,
201            #[cfg(feature = "alloc")]
202            Self::Bcrypt { salt, rounds } => {
203                [8, salt.len()].checked_sum()?.encode(writer)?;
204                salt.encode(writer)?;
205                rounds.encode(writer)?;
206            }
207        }
208
209        Ok(())
210    }
211}
212
213/// Check the bcrypt round count before encoding, decoding, or key derivation.
214#[cfg(feature = "alloc")]
215fn validate_bcrypt_rounds(rounds: u32) -> Result<()> {
216    if !(1..=MAX_BCRYPT_ROUNDS).contains(&rounds) {
217        return Err(Error::Crypto);
218    }
219    Ok(())
220}
221
222#[cfg(all(test, feature = "alloc"))]
223mod tests {
224    use super::{Kdf, MAX_BCRYPT_ROUNDS};
225    use crate::Error;
226    use alloc::vec::Vec;
227    use encoding::{Decode, Encode, Reader};
228
229    #[test]
230    fn bcrypt_rounds_boundaries() {
231        let mut encoded = Kdf::Bcrypt {
232            salt: b"salt".to_vec(),
233            rounds: 1,
234        }
235        .encode_vec()
236        .unwrap();
237
238        for (rounds, valid) in [
239            (0, false),
240            (1, true),
241            (MAX_BCRYPT_ROUNDS, true),
242            (MAX_BCRYPT_ROUNDS + 1, false),
243            (u32::MAX, false),
244        ] {
245            let kdf = Kdf::Bcrypt {
246                salt: b"salt".to_vec(),
247                rounds,
248            };
249            // Modify the wire encoding so invalid rounds can still be tested on decode.
250            let offset = encoded.len() - 4;
251            encoded[offset..].copy_from_slice(&rounds.to_be_bytes());
252
253            let mut output = Vec::new();
254            let expected = if valid {
255                assert_eq!(kdf.encoded_len(), Ok(encoded.len()));
256                kdf.encode(&mut output).unwrap();
257                assert_eq!(output, encoded);
258                Ok(kdf)
259            } else {
260                assert_eq!(kdf.encoded_len(), Err(encoding::Error::Overflow));
261                assert_eq!(kdf.encode(&mut output), Err(encoding::Error::Overflow));
262                assert!(output.is_empty());
263                Err(Error::Crypto)
264            };
265            let mut decoder = encoded.as_slice().into_decoder().unwrap();
266            assert_eq!(Kdf::decode(&mut decoder), expected, "rounds: {rounds}");
267            if valid {
268                decoder.finish(()).unwrap();
269            }
270        }
271    }
272
273    #[cfg(feature = "encryption")]
274    #[test]
275    fn derive_bcrypt_invalid_rounds() {
276        // Fail immediately if invalid rounds reach bcrypt instead of running an expensive KDF.
277        struct UnreadPassword;
278
279        impl AsRef<[u8]> for UnreadPassword {
280            fn as_ref(&self) -> &[u8] {
281                panic!("invalid rounds must be rejected before accessing the password");
282            }
283        }
284
285        for rounds in [0, MAX_BCRYPT_ROUNDS + 1, u32::MAX] {
286            let kdf = Kdf::Bcrypt {
287                salt: b"salt".to_vec(),
288                rounds,
289            };
290            let mut output = [0xa5; 32];
291            assert_eq!(kdf.derive(UnreadPassword, &mut output), Err(Error::Crypto));
292            assert_eq!(output, [0xa5; 32]);
293        }
294    }
295}