Skip to main content

keepass/
config.rs

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