1use 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
27const PLAIN: u32 = 0;
29const SALSA_20: u32 = 2;
30const CHA_CHA_20: u32 = 3;
31
32#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
34#[non_exhaustive]
35pub struct DatabaseConfig {
36 pub version: DatabaseVersion,
38
39 pub outer_cipher_config: OuterCipherConfig,
41
42 pub compression_config: CompressionConfig,
44
45 pub inner_cipher_config: InnerCipherConfig,
47
48 pub kdf_config: KdfConfig,
50
51 pub public_custom_data: Option<VariantDictionary>,
53}
54
55impl 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#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
71#[non_exhaustive]
72pub enum OuterCipherConfig {
73 AES256,
75
76 Twofish,
78
79 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#[derive(Debug, Error)]
126#[non_exhaustive]
127pub enum OuterCipherConfigError {
128 #[error(transparent)]
130 Cryptography(#[from] CryptographyError),
131
132 #[error("Invalid outer cipher ID: {:?}", cid)]
134 InvalidOuterCipherID {
135 cid: Vec<u8>,
137 },
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
142#[non_exhaustive]
143pub enum InnerCipherConfig {
144 Plain,
146
147 Salsa20,
149
150 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#[derive(Debug, Error)]
195#[non_exhaustive]
196pub enum InnerCipherConfigError {
197 #[error(transparent)]
199 Cryptography(#[from] CryptographyError),
200
201 #[error("Invalid inner cipher ID: {}", cid)]
203 InvalidInnerCipherID {
204 cid: u32,
206 },
207}
208
209const KDF_ID: &str = "$UUID";
211const KDF_MEMORY: &str = "M";
213const KDF_SALT: &str = "S";
214const KDF_ITERATIONS: &str = "I";
215const KDF_PARALLELISM: &str = "P";
216const KDF_VERSION: &str = "V";
217const KDF_SEED: &str = "S";
219const KDF_ROUNDS: &str = "R";
220
221#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
223#[non_exhaustive]
224pub enum KdfConfig {
225 Aes {
227 rounds: u64,
229 },
230 Argon2 {
232 iterations: u64,
234
235 memory: u64,
240
241 parallelism: u32,
243
244 #[serde(serialize_with = "serialize_argon2_version")]
246 version: argon2::Version,
247 },
248
249 Argon2id {
251 iterations: u64,
253
254 memory: u64,
259
260 parallelism: u32,
262
263 #[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 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 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 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#[derive(Debug, Error)]
400#[non_exhaustive]
401pub enum KdfConfigError {
402 #[error("Invalid KDF version: {}", version)]
404 InvalidKDFVersion {
405 version: u32,
407 },
408
409 #[error("Invalid KDF UUID: {:?}", uuid)]
411 InvalidKDFUUID {
412 uuid: Vec<u8>,
414 },
415
416 #[error(transparent)]
418 VariantDictionary(#[from] VariantDictionaryError),
419}
420
421#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
423#[non_exhaustive]
424pub enum CompressionConfig {
425 None,
427
428 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#[derive(Debug, Error)]
462#[non_exhaustive]
463pub enum CompressionConfigError {
464 #[error("Invalid compression algorithm: {}", cid)]
466 InvalidCompressionSuite {
467 cid: u32,
469 },
470}