Skip to main content

keepass_ng/
config.rs

1//! Configuration options for how to compress and encrypt databases
2use hex_literal::hex;
3
4use std::convert::TryFrom;
5
6pub use crate::format::DatabaseVersion;
7
8#[cfg(feature = "save_kdbx4")]
9use crate::crypt::ciphers::Cipher;
10
11use crate::{
12    compression,
13    crypt::{ciphers, kdf},
14    error::{CryptographyError, VariantDictionaryError},
15    format::{KDBX4_CURRENT_MINOR_VERSION, variant_dictionary::VariantDictionary},
16};
17
18const _CIPHERSUITE_AES128: [u8; 16] = hex!("61ab05a1946441c38d743a563df8dd35");
19const CIPHERSUITE_AES256: [u8; 16] = hex!("31c1f2e6bf714350be5805216afc5aff");
20const CIPHERSUITE_TWOFISH: [u8; 16] = hex!("ad68f29f576f4bb9a36ad47af965346c");
21const CIPHERSUITE_CHACHA20: [u8; 16] = hex!("d6038a2b8b6f4cb5a524339a31dbb59a");
22
23// Internal IDs for the ciphers
24const PLAIN: u32 = 0;
25const SALSA_20: u32 = 2;
26const CHA_CHA_20: u32 = 3;
27
28/// Configuration of how a database should be stored
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
31pub struct DatabaseConfig {
32    /// Version of the outer database file
33    pub version: DatabaseVersion,
34
35    /// What encryption to use for the outer encryption
36    pub outer_cipher_config: OuterCipherConfig,
37
38    /// What algorithm to use to compress the inner data
39    pub compression_config: CompressionConfig,
40
41    /// What encryption to use for protected fields inside the database
42    pub inner_cipher_config: InnerCipherConfig,
43
44    /// Settings for the Key Derivation Function (KDF)
45    pub kdf_config: KdfConfig,
46
47    /// Custom data of plugins/ports.
48    pub public_custom_data: Option<VariantDictionary>,
49}
50
51/// Sensible default configuration for new databases
52impl Default for DatabaseConfig {
53    fn default() -> Self {
54        Self {
55            version: DatabaseVersion::KDB4(KDBX4_CURRENT_MINOR_VERSION),
56            outer_cipher_config: OuterCipherConfig::AES256,
57            compression_config: CompressionConfig::GZip,
58            inner_cipher_config: InnerCipherConfig::ChaCha20,
59            kdf_config: KdfConfig::Argon2 {
60                iterations: 50,
61                memory: 1024 * 1024,
62                parallelism: 4,
63                version: argon2::Version::Version13,
64            },
65            public_custom_data: None,
66        }
67    }
68}
69
70/// Choices for outer encryption
71#[derive(Debug, Clone, PartialEq, Eq)]
72#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
73pub enum OuterCipherConfig {
74    AES256,
75    Twofish,
76    ChaCha20,
77}
78
79/// Errors with the configuration of the outer encryption.
80#[derive(Debug, thiserror::Error)]
81pub enum OuterCipherConfigError {
82    #[error(transparent)]
83    Cryptography(#[from] CryptographyError),
84
85    #[error("Invalid outer cipher ID: {:?}", cid)]
86    InvalidOuterCipherID { cid: Vec<u8> },
87}
88
89impl OuterCipherConfig {
90    pub(crate) fn get_cipher(&self, key: &[u8], iv: &[u8]) -> Result<Box<dyn ciphers::Cipher>, CryptographyError> {
91        match self {
92            OuterCipherConfig::AES256 => Ok(Box::new(ciphers::AES256Cipher::new(key, iv))),
93            OuterCipherConfig::Twofish => Ok(Box::new(ciphers::TwofishCipher::new(key, iv))),
94            OuterCipherConfig::ChaCha20 => Ok(Box::new(ciphers::ChaCha20Cipher::new_key_iv(key, iv)?)),
95        }
96    }
97
98    #[cfg(feature = "save_kdbx4")]
99    pub(crate) fn get_iv_size(&self) -> usize {
100        match self {
101            OuterCipherConfig::AES256 => ciphers::AES256Cipher::iv_size(),
102            OuterCipherConfig::Twofish => ciphers::TwofishCipher::iv_size(),
103            OuterCipherConfig::ChaCha20 => ciphers::ChaCha20Cipher::iv_size(),
104        }
105    }
106
107    #[cfg(feature = "save_kdbx4")]
108    pub(crate) fn dump(&self) -> [u8; 16] {
109        match self {
110            OuterCipherConfig::AES256 => CIPHERSUITE_AES256,
111            OuterCipherConfig::Twofish => CIPHERSUITE_TWOFISH,
112            OuterCipherConfig::ChaCha20 => CIPHERSUITE_CHACHA20,
113        }
114    }
115}
116
117impl TryFrom<&[u8]> for OuterCipherConfig {
118    type Error = OuterCipherConfigError;
119    fn try_from(v: &[u8]) -> Result<OuterCipherConfig, Self::Error> {
120        if v == CIPHERSUITE_AES256 {
121            Ok(OuterCipherConfig::AES256)
122        } else if v == CIPHERSUITE_TWOFISH {
123            Ok(OuterCipherConfig::Twofish)
124        } else if v == CIPHERSUITE_CHACHA20 {
125            Ok(OuterCipherConfig::ChaCha20)
126        } else {
127            Err(OuterCipherConfigError::InvalidOuterCipherID { cid: v.to_vec() })
128        }
129    }
130}
131
132/// Choices for encrypting protected values inside of databases
133#[derive(Debug, Clone, PartialEq, Eq)]
134#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
135pub enum InnerCipherConfig {
136    Plain,
137    Salsa20,
138    ChaCha20,
139}
140
141/// Errors with the configuration of the inner encryption.
142#[derive(Debug, thiserror::Error)]
143pub enum InnerCipherConfigError {
144    #[error(transparent)]
145    Cryptography(#[from] CryptographyError),
146
147    #[error("Invalid inner cipher ID: {}", cid)]
148    InvalidInnerCipherID { cid: u32 },
149}
150
151impl InnerCipherConfig {
152    pub(crate) fn get_cipher(&self, protected_stream_key: &[u8]) -> Result<Box<dyn ciphers::Cipher>, CryptographyError> {
153        match self {
154            InnerCipherConfig::Plain => Ok(Box::new(ciphers::PlainCipher::new(protected_stream_key))),
155            InnerCipherConfig::Salsa20 => Ok(Box::new(ciphers::Salsa20Cipher::new(protected_stream_key))),
156            InnerCipherConfig::ChaCha20 => Ok(Box::new(ciphers::ChaCha20Cipher::new(protected_stream_key)?)),
157        }
158    }
159
160    #[cfg(feature = "save_kdbx4")]
161    pub(crate) fn dump(&self) -> u32 {
162        match self {
163            InnerCipherConfig::Plain => PLAIN,
164            InnerCipherConfig::Salsa20 => SALSA_20,
165            InnerCipherConfig::ChaCha20 => CHA_CHA_20,
166        }
167    }
168
169    #[cfg(feature = "save_kdbx4")]
170    pub(crate) fn get_key_size(&self) -> usize {
171        match self {
172            InnerCipherConfig::Plain => ciphers::PlainCipher::key_size(),
173            InnerCipherConfig::Salsa20 => ciphers::Salsa20Cipher::key_size(),
174            InnerCipherConfig::ChaCha20 => ciphers::ChaCha20Cipher::key_size(),
175        }
176    }
177}
178
179impl TryFrom<u32> for InnerCipherConfig {
180    type Error = InnerCipherConfigError;
181
182    fn try_from(v: u32) -> Result<InnerCipherConfig, Self::Error> {
183        match v {
184            PLAIN => Ok(InnerCipherConfig::Plain),
185            SALSA_20 => Ok(InnerCipherConfig::Salsa20),
186            CHA_CHA_20 => Ok(InnerCipherConfig::ChaCha20),
187            _ => Err(InnerCipherConfigError::InvalidInnerCipherID { cid: v }),
188        }
189    }
190}
191
192// Name of the KDF fields in the variant dictionaries.
193const KDF_ID: &str = "$UUID";
194// KDF fields used by Argon2.
195const KDF_MEMORY: &str = "M";
196const KDF_SALT: &str = "S";
197const KDF_ITERATIONS: &str = "I";
198const KDF_PARALLELISM: &str = "P";
199const KDF_VERSION: &str = "V";
200// KDF fields used by AES.
201const KDF_SEED: &str = "S";
202const KDF_ROUNDS: &str = "R";
203
204/// Choices for Key Derivation Functions (KDFs)
205#[derive(Debug, Clone, PartialEq, Eq)]
206#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
207pub enum KdfConfig {
208    /// Derive keys with repeated AES encryption
209    Aes { rounds: u64 },
210    /// Derive keys with Argon2d
211    Argon2 {
212        iterations: u64,
213        memory: u64,
214        parallelism: u32,
215
216        #[cfg_attr(feature = "serialization", serde(serialize_with = "serialize_argon2_version"))]
217        version: argon2::Version,
218    },
219    /// Derive keys with Argon2id
220    Argon2id {
221        iterations: u64,
222        memory: u64,
223        parallelism: u32,
224
225        #[cfg_attr(feature = "serialization", serde(serialize_with = "serialize_argon2_version"))]
226        version: argon2::Version,
227    },
228}
229
230/// Errors with the configuration of the key derivation function.
231#[derive(Debug, thiserror::Error)]
232pub enum KdfConfigError {
233    #[error("Invalid KDF version: {}", version)]
234    InvalidKDFVersion { version: u32 },
235
236    #[error("Invalid KDF UUID: {:?}", uuid)]
237    InvalidKDFUUID { uuid: Vec<u8> },
238
239    #[error(transparent)]
240    VariantDictionary(#[from] VariantDictionaryError),
241}
242
243#[cfg(feature = "serialization")]
244fn serialize_argon2_version<S: serde::Serializer>(
245    version: &argon2::Version,
246    serializer: S,
247) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> {
248    serializer.serialize_u32(version.as_u32())
249}
250
251impl KdfConfig {
252    #[cfg(feature = "save_kdbx4")]
253    fn seed_size(&self) -> usize {
254        match self {
255            KdfConfig::Aes { .. } => 32,
256            KdfConfig::Argon2 { .. } => 32,
257            KdfConfig::Argon2id { .. } => 32,
258        }
259    }
260
261    /// For writing out a database, generate a new KDF seed from the config and return the KDF
262    /// and the generated seed
263    #[cfg(feature = "save_kdbx4")]
264    pub(crate) fn get_kdf_and_seed(&self) -> Result<(Box<dyn kdf::Kdf>, Vec<u8>), getrandom::Error> {
265        let mut kdf_seed = vec![0; self.seed_size()];
266        getrandom::fill(&mut kdf_seed)?;
267
268        let kdf = self.get_kdf_seeded(&kdf_seed);
269
270        Ok((kdf, kdf_seed))
271    }
272
273    /// For reading a database, generate a KDF from the KDF config and a provided seed
274    pub(crate) fn get_kdf_seeded(&self, seed: &[u8]) -> Box<dyn kdf::Kdf> {
275        match self {
276            KdfConfig::Aes { rounds } => Box::new(kdf::AesKdf {
277                seed: seed.to_vec(),
278                rounds: *rounds,
279            }),
280            KdfConfig::Argon2 {
281                memory,
282                iterations,
283                parallelism,
284                version,
285            } => Box::new(kdf::Argon2Kdf {
286                memory: *memory,
287                salt: seed.to_vec(),
288                iterations: *iterations,
289                parallelism: *parallelism,
290                version: *version,
291                variant: argon2::Variant::Argon2d,
292            }),
293            KdfConfig::Argon2id {
294                memory,
295                iterations,
296                parallelism,
297                version,
298            } => Box::new(kdf::Argon2Kdf {
299                memory: *memory,
300                salt: seed.to_vec(),
301                iterations: *iterations,
302                parallelism: *parallelism,
303                version: *version,
304                variant: argon2::Variant::Argon2id,
305            }),
306        }
307    }
308
309    #[cfg(feature = "save_kdbx4")]
310    pub(crate) fn to_variant_dictionary(&self, seed: &[u8]) -> VariantDictionary {
311        let mut vd = VariantDictionary::new();
312
313        match self {
314            KdfConfig::Aes { rounds } => {
315                vd.set(KDF_ID, KDF_AES_KDBX3.to_vec());
316                vd.set(KDF_ROUNDS, *rounds);
317                vd.set(KDF_SEED, seed.to_vec());
318            }
319            KdfConfig::Argon2 {
320                memory,
321                iterations,
322                parallelism,
323                version,
324            } => {
325                vd.set(KDF_ID, KDF_ARGON2.to_vec());
326                vd.set(KDF_MEMORY, *memory);
327                vd.set(KDF_SALT, seed.to_vec());
328                vd.set(KDF_ITERATIONS, *iterations);
329                vd.set(KDF_PARALLELISM, *parallelism);
330                vd.set(KDF_VERSION, version.as_u32());
331            }
332            KdfConfig::Argon2id {
333                memory,
334                iterations,
335                parallelism,
336                version,
337            } => {
338                vd.set(KDF_ID, KDF_ARGON2ID.to_vec());
339                vd.set(KDF_MEMORY, *memory);
340                vd.set(KDF_SALT, seed.to_vec());
341                vd.set(KDF_ITERATIONS, *iterations);
342                vd.set(KDF_PARALLELISM, *parallelism);
343                vd.set(KDF_VERSION, version.as_u32());
344            }
345        }
346
347        vd
348    }
349}
350
351const KDF_AES_KDBX3: [u8; 16] = hex!("c9d9f39a628a4460bf740d08c18a4fea");
352const KDF_AES_KDBX4: [u8; 16] = hex!("7c02bb8279a74ac0927d114a00648238");
353const KDF_ARGON2: [u8; 16] = hex!("ef636ddf8c29444b91f7a9a403e30a0c");
354const KDF_ARGON2ID: [u8; 16] = hex!("9e298b1956db4773b23dfc3ec6f0a1e6");
355
356impl TryFrom<VariantDictionary> for (KdfConfig, Vec<u8>) {
357    type Error = KdfConfigError;
358
359    fn try_from(vd: VariantDictionary) -> Result<(KdfConfig, Vec<u8>), Self::Error> {
360        let uuid = vd.get::<Vec<u8>>(KDF_ID)?;
361
362        if uuid == &KDF_ARGON2ID {
363            let memory: u64 = *vd.get(KDF_MEMORY)?;
364            let salt: Vec<u8> = vd.get::<Vec<u8>>(KDF_SALT)?.clone();
365            let iterations: u64 = *vd.get(KDF_ITERATIONS)?;
366            let parallelism: u32 = *vd.get(KDF_PARALLELISM)?;
367            let version: u32 = *vd.get(KDF_VERSION)?;
368
369            let version = match version {
370                0x10 => argon2::Version::Version10,
371                0x13 => argon2::Version::Version13,
372                _ => return Err(KdfConfigError::InvalidKDFVersion { version }),
373            };
374
375            Ok((
376                KdfConfig::Argon2id {
377                    memory,
378                    iterations,
379                    parallelism,
380                    version,
381                },
382                salt,
383            ))
384        } else if uuid == &KDF_ARGON2 {
385            let memory: u64 = *vd.get(KDF_MEMORY)?;
386            let salt: Vec<u8> = vd.get::<Vec<u8>>(KDF_SALT)?.clone();
387            let iterations: u64 = *vd.get(KDF_ITERATIONS)?;
388            let parallelism: u32 = *vd.get(KDF_PARALLELISM)?;
389            let version: u32 = *vd.get(KDF_VERSION)?;
390
391            let version = match version {
392                0x10 => argon2::Version::Version10,
393                0x13 => argon2::Version::Version13,
394                _ => return Err(KdfConfigError::InvalidKDFVersion { version }),
395            };
396
397            Ok((
398                KdfConfig::Argon2 {
399                    memory,
400                    iterations,
401                    parallelism,
402                    version,
403                },
404                salt,
405            ))
406        } else if uuid == &KDF_AES_KDBX4 || uuid == &KDF_AES_KDBX3 {
407            let rounds: u64 = *vd.get(KDF_ROUNDS)?;
408            let seed: Vec<u8> = vd.get::<Vec<u8>>(KDF_SEED)?.clone();
409
410            Ok((KdfConfig::Aes { rounds }, seed))
411        } else {
412            Err(KdfConfigError::InvalidKDFUUID { uuid: uuid.clone() })
413        }
414    }
415}
416
417/// Choices of compression algorithm
418#[derive(Debug, Clone, PartialEq, Eq)]
419#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
420pub enum CompressionConfig {
421    None,
422    GZip,
423}
424
425/// Errors with the configuration of the compression algorithm.
426#[derive(Debug, thiserror::Error)]
427pub enum CompressionConfigError {
428    #[error("Invalid compression algorithm: {}", cid)]
429    InvalidCompressionSuite { cid: u32 },
430}
431
432impl CompressionConfig {
433    pub(crate) fn get_compression(&self) -> Box<dyn compression::Compression> {
434        match self {
435            CompressionConfig::None => Box::new(compression::NoCompression),
436            CompressionConfig::GZip => Box::new(compression::GZipCompression),
437        }
438    }
439
440    #[cfg(feature = "save_kdbx4")]
441    pub(crate) fn dump(&self) -> [u8; 4] {
442        match self {
443            CompressionConfig::None => [0, 0, 0, 0],
444            CompressionConfig::GZip => [1, 0, 0, 0],
445        }
446    }
447}
448
449impl TryFrom<u32> for CompressionConfig {
450    type Error = CompressionConfigError;
451
452    fn try_from(v: u32) -> Result<CompressionConfig, Self::Error> {
453        match v {
454            0 => Ok(CompressionConfig::None),
455            1 => Ok(CompressionConfig::GZip),
456            _ => Err(CompressionConfigError::InvalidCompressionSuite { cid: v }),
457        }
458    }
459}