//! The KDBX 4 file format (docs/KDBX.md, "Tests"): round trips, keys, tampering, hostile input. use custos_kdbx::{ AutoType, Cipher, Database, Entry, Error, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times, WriteOptions, read, testing, write, }; use custos_vault::Attachment; use sha2::{Digest, Sha256}; /// Cheap parameters so the tamper tests can run the KDF once per byte. const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } }; fn pw(s: &str) -> SecretString { SecretString::from(s) } fn s(key: &str, value: &str, protected: bool) -> StringField { StringField { key: key.into(), value: value.into(), protected } } pub fn sample() -> Database { let snapshot = Entry { uuid: [2; 16], strings: vec![s("Title", "GitHub", false), s("Password", "Old-Secret-Value", true)], times: Times { created: 1_700_000_000, modified: 1_700_000_100, expires: None }, ..Default::default() }; let login = Entry { uuid: [2; 16], strings: vec![ s("Title", "GitHub & ", false), s("UserName", "alice", false), s("Password", "Hunter2-Secret-Value", true), s("URL", "https://github.com", false), s("Notes", "line one\r\nline \"two\"\n\ttabbed — Česky", false), s("Recovery code", "Protected-Recovery-Code", true), s("Empty protected", "", true), s("Plain", "", false), ], attachments: vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\x01Attached-Key"[..]), }], tags: vec!["dev".into(), "work".into()], times: Times { created: 1_700_000_000, modified: 1_700_000_200, expires: Some(1_800_000_000) }, autotype: AutoType { default_sequence: "{USERNAME}{TAB}{PASSWORD}{ENTER}".into(), windows: vec!["*GitHub*".into()], }, history: vec![snapshot], }; let note = Entry { uuid: [3; 16], strings: vec![s("Title", "Note", false), s("Notes", "just text", false)], times: Times { created: 0, modified: 0, expires: None }, ..Default::default() }; Database { name: "Test database".into(), root: Group { uuid: [1; 16], name: "Root".into(), entries: vec![note], groups: vec![Group { uuid: [4; 16], name: "Internet".into(), entries: vec![login], groups: vec![Group { uuid: [5; 16], name: "Empty".into(), ..Default::default() }], }], }, recycle_bin: None, } } fn key(p: &SecretString) -> Key<'_> { Key { password: Some(p), key_file: None } } #[test] fn write_then_read_is_identical_for_every_cipher_and_kdf() { let db = sample(); let p = pw("correct horse"); for cipher in [Cipher::ChaCha20, Cipher::Aes256] { for kdf in [Kdf::Argon2id { m_kib: 64, t: 1, p: 1 }, Kdf::Argon2d { m_kib: 128, t: 2, p: 2 }, Kdf::Aes { rounds: 100 }] { let bytes = write(&db, &key(&p), WriteOptions { cipher, kdf }).unwrap(); assert_eq!(read(&bytes, &key(&p)).unwrap(), db, "{cipher:?} {kdf:?}"); } } // Every write is fresh: seed, IV, salt and inner stream key. assert_ne!(write(&db, &key(&p), FAST).unwrap(), write(&db, &key(&p), FAST).unwrap()); } #[test] fn the_wrong_password_or_no_key_fails_clearly() { let p = pw("right"); let bytes = write(&sample(), &key(&p), FAST).unwrap(); assert_eq!(read(&bytes, &key(&pw("wrong"))), Err(Error::WrongKey)); assert_eq!(read(&bytes, &Key::default()), Err(Error::NoKey)); // An empty password is no password. assert_eq!(read(&bytes, &key(&pw(""))), Err(Error::NoKey)); let e = read(&bytes, &key(&pw("Typed-Attempt-9"))).unwrap_err().to_string(); assert!(!e.contains("Typed-Attempt-9") && !e.contains("right"), "{e}"); } fn xml_v2(key: &[u8; 32]) -> Vec { let hex: String = key.iter().map(|b| format!("{b:02X}")).collect(); let hash: String = Sha256::digest(key)[..4].iter().map(|b| format!("{b:02X}")).collect(); let (a, b) = hex.split_at(32); format!( "\n\n\t\n\t\t2.0\n\t\n\t\n\t\t\n\t\t\t{a}\n\t\t\t{b}\n\t\t\n\t\n\n" ) .into_bytes() } #[test] fn every_key_file_kind_works_alone_and_with_a_password() { let raw: [u8; 32] = core::array::from_fn(|i| (i * 7 + 3) as u8); let hex: Vec = raw.iter().map(|b| format!("{b:02x}")).collect::().into_bytes(); let v1 = format!( "1.00{}", data_encoding::BASE64.encode(&raw) ) .into_bytes(); // These four are the same 32-byte key written four ways: each opens what another wrote. let same = [raw.to_vec(), hex, xml_v2(&raw), v1]; let p = pw("pw"); for with_pw in [false, true] { fn k<'a>(p: Option<&'a SecretString>, f: &'a [u8]) -> Key<'a> { Key { password: p, key_file: Some(f) } } let p = with_pw.then_some(&p); let bytes = write(&sample(), &k(p, &same[0]), FAST).unwrap(); for f in &same { assert_eq!(read(&bytes, &k(p, f)).unwrap(), sample()); } assert_eq!(read(&bytes, &k(p, b"another file")), Err(Error::WrongKey)); if let Some(p) = p { assert_eq!(read(&bytes, &key(p)), Err(Error::WrongKey), "the key file is needed too"); } } // Any other file is hashed. let photo = b"\x89PNG not really a key file, just some bytes".to_vec(); let bytes = write(&sample(), &Key { password: None, key_file: Some(&photo) }, FAST).unwrap(); assert!(read(&bytes, &Key { password: None, key_file: Some(&photo) }).is_ok()); // A version 2.0 key file with a wrong checksum is refused, not guessed. let mut bad = xml_v2(&raw); let at = bad.windows(6).position(|w| w == b"Hash=\"").unwrap() + 6; bad[at] = if bad[at] == b'0' { b'1' } else { b'0' }; assert_eq!( write(&sample(), &Key { password: None, key_file: Some(&bad) }, FAST), Err(Error::Malformed("key file checksum")) ); } /// Where the parts of a file written with FAST start: header end, then the 64 bytes of hash + HMAC. fn header_len(bytes: &[u8]) -> usize { let mut pos = 12; loop { let id = bytes[pos]; let len = u32::from_le_bytes(bytes[pos + 1..pos + 5].try_into().unwrap()) as usize; pos += 5 + len; if id == 0 { return pos; } } } #[test] fn changing_any_byte_fails_and_never_panics() { let p = pw("pw"); let small = Database { name: "x".into(), ..Default::default() }; let bytes = write(&small, &key(&p), FAST).unwrap(); let h = header_len(&bytes); for i in 0..bytes.len() { let mut b = bytes.clone(); b[i] ^= 0x01; let r = read(&b, &key(&p)); assert!(r.is_err(), "byte {i} of {} changed and the file still opened", bytes.len()); let e = r.unwrap_err(); if (12..h).contains(&i) || (h..h + 32).contains(&i) { // Header or its hash: caught by the hash (or the field structure) before any key work. assert!(matches!(e, Error::Corrupted | Error::Malformed(_) | Error::NotKdbx), "byte {i}: {e:?}"); } else if (h + 32..h + 64).contains(&i) { assert_eq!(e, Error::WrongKey, "byte {i} (header HMAC)"); } else if i >= h + 64 { assert_eq!(e, Error::Corrupted, "byte {i} (blocks)"); } } } #[test] fn truncation_at_any_point_fails() { let p = pw("pw"); let bytes = write(&Database::default(), &key(&p), FAST).unwrap(); for len in 0..bytes.len() { assert!(read(&bytes[..len], &key(&p)).is_err(), "truncated to {len}"); } } #[test] fn not_kdbx_kdbx3_and_future_versions() { let p = pw("pw"); assert_eq!(read(b"", &key(&p)), Err(Error::NotKdbx)); assert_eq!(read(b"PK\x03\x04 a zip file", &key(&p)), Err(Error::NotKdbx)); let mut kdb1 = vec![0x03, 0xD9, 0xA2, 0x9A, 0x65, 0xFB, 0x4B, 0xB5]; kdb1.extend([0; 120]); assert_eq!(read(&kdb1, &key(&p)), Err(Error::NotKdbx)); let good = write(&Database::default(), &key(&p), FAST).unwrap(); let with_version = |minor: u16, major: u16| { let mut b = good.clone(); b[8..10].copy_from_slice(&minor.to_le_bytes()); b[10..12].copy_from_slice(&major.to_le_bytes()); b }; assert_eq!(read(&with_version(1, 2), &key(&p)), Err(Error::UnsupportedVersion(2, 1))); assert_eq!(read(&with_version(0, 5), &key(&p)), Err(Error::UnsupportedVersion(5, 0))); // KDBX 4.1 reads like 4.0 (only the header hash notices the changed version bytes). let v41 = with_version(1, 4); assert_eq!(read(&v41, &key(&p)), Err(Error::Corrupted)); } /// Replaces the cipher id in a file and fixes the header hash, so only the cipher is wrong. fn with_cipher(bytes: &[u8], id: [u8; 16]) -> Vec { let mut b = bytes.to_vec(); assert_eq!(b[12], 2, "the cipher is the first field"); b[17..33].copy_from_slice(&id); let h = header_len(&b); let hash = Sha256::digest(&b[..h]); b[h..h + 32].copy_from_slice(&hash); b } #[test] fn twofish_and_unknown_ciphers_are_refused() { let p = pw("pw"); let bytes = write(&Database::default(), &key(&p), FAST).unwrap(); let twofish = 0xad68f29f_576f_4bb9_a36a_d47af965346cu128.to_be_bytes(); assert_eq!(read(&with_cipher(&bytes, twofish), &key(&p)), Err(Error::UnsupportedCipher)); assert_eq!(read(&with_cipher(&bytes, [0; 16]), &key(&p)), Err(Error::UnsupportedCipher)); } #[test] fn kdf_parameters_out_of_limits_are_refused_before_any_work() { let p = pw("pw"); let inner = testing::inner(3, b""); let t = [0u8; 32]; let start = std::time::Instant::now(); for dict in [ testing::argon2_dict(true, 4 << 30, 1, 1, 0x13), // 4 GiB testing::argon2_dict(true, (64 << 10) + 1, 1, 1, 0x13), // not whole KiB testing::argon2_dict(true, 64 << 10, 1001, 1, 0x13), testing::argon2_dict(true, 64 << 10, 0, 1, 0x13), testing::argon2_dict(false, 64 << 10, 1, 0, 0x13), testing::argon2_dict(false, 64 << 10, 1, 65, 0x13), testing::argon2_dict(false, 64 << 10, 1, 1, 0x10), // Argon2 version 1.0 testing::aes_dict(1 << 31), testing::aes_dict(0), ] { assert_eq!(read(&testing::build(&dict, &t, &inner, true), &key(&p)), Err(Error::UnsupportedKdf)); } assert!(start.elapsed().as_secs() < 5, "the limits are checked before Argon2 or AES-KDF runs"); } /// A file that opens with password "pw" (AES-KDF, 1 round) around this inner XML. fn file_around(xml: &[u8], stream: u32) -> Vec { testing::build(&testing::aes_dict(1), &testing::aes_transformed("pw", 1), &testing::inner(stream, xml), true) } #[test] fn the_test_builder_itself_makes_files_that_open() { let xml = b"AAAAAAAAAAAAAAAAAAAAAA==R"; let db = read(&file_around(xml, 3), &key(&pw("pw"))).unwrap(); assert_eq!(db.root.name, "R"); } #[test] fn doctype_and_entity_tricks_are_refused() { let laughs = br#" ]> &lol2;"#; assert_eq!(read(&file_around(laughs, 3), &key(&pw("pw"))), Err(Error::Malformed("XML with a DOCTYPE"))); let xxe = br#"]>&e;"#; assert_eq!(read(&file_around(xxe, 3), &key(&pw("pw"))), Err(Error::Malformed("XML with a DOCTYPE"))); } #[test] fn deep_nesting_and_broken_xml_are_refused() { let mut deep = b"".to_vec(); for _ in 0..300 { deep.extend_from_slice(b"AAAAAAAAAAAAAAAAAAAAAA=="); } for _ in 0..300 { deep.extend_from_slice(b""); } deep.extend_from_slice(b""); assert_eq!(read(&file_around(&deep, 3), &key(&pw("pw"))), Err(Error::Malformed("groups nested too deeply"))); for bad in [&b""[..], b"not xml", b"\xff\xfe", b""] { assert!(matches!(read(&file_around(bad, 3), &key(&pw("pw"))), Err(Error::Malformed(_)))); } // A protected value that is not base64, and an attachment reference to nothing. let bad_value = b"Password!!"; assert_eq!(read(&file_around(bad_value, 3), &key(&pw("pw"))), Err(Error::Malformed("protected value"))); let bad_ref = b"a"; assert_eq!(read(&file_around(bad_ref, 3), &key(&pw("pw"))), Err(Error::Malformed("attachment"))); } #[test] fn salsa20_inner_stream_is_refused() { let xml = b""; assert_eq!(read(&file_around(xml, 2), &key(&pw("pw"))), Err(Error::UnsupportedStream)); assert_eq!(read(&file_around(xml, 0), &key(&pw("pw"))), Err(Error::UnsupportedStream)); } #[test] fn a_gzip_bomb_stops_at_the_limit() { // 600 MiB of zeros, compressed: a few hundred KiB on disk. use flate2::{Compression, write::GzEncoder}; use std::io::Write; let mut gz = GzEncoder::new(Vec::new(), Compression::fast()); let zeros = vec![0u8; 1 << 20]; gz.write_all(&testing::inner(3, b"")).unwrap(); for _ in 0..600 { gz.write_all(&zeros).unwrap(); } let bomb = gz.finish().unwrap(); assert!(bomb.len() < 4 << 20); let file = testing::build_compressed(&testing::aes_dict(1), &testing::aes_transformed("pw", 1), &bomb); assert_eq!(read(&file, &key(&pw("pw"))), Err(Error::TooLarge)); } #[test] fn no_secret_in_debug_output() { let db = sample(); let p = pw("Master-Password-Here"); let file = [7u8; 32]; let k = Key { password: Some(&p), key_file: Some(&file) }; for out in [format!("{db:?}"), format!("{db:#?}"), format!("{k:?}"), format!("{:?}", Error::WrongKey)] { for leaked in [ "Hunter2-Secret-Value", "Protected-Recovery-Code", "Old-Secret-Value", "Attached-Key", "Master-Password-Here", ] { assert!(!out.contains(leaked), "{leaked} in {out}"); } } assert!(format!("{db:?}").contains("Internet"), "non-secret parts stay readable"); }