diff --git a/Cargo.lock b/Cargo.lock index cec391d..8f96149 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aead" version = "0.6.1" @@ -12,6 +18,17 @@ dependencies = [ "inout 0.2.5", ] +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -112,6 +129,24 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -181,6 +216,12 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -199,6 +240,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + [[package]] name = "crypto-bigint" version = "0.5.5" @@ -280,6 +330,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "custos-kdbx" +version = "0.7.0" +dependencies = [ + "aes", + "argon2", + "cbc", + "chacha20", + "custos-vault", + "data-encoding", + "flate2", + "hmac 0.13.0", + "rand 0.10.3", + "roxmltree", + "salsa20", + "serde_json", + "sha2 0.11.1", + "thiserror", + "zeroize", +] + [[package]] name = "custos-keys" version = "0.7.0" @@ -508,6 +579,16 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + [[package]] name = "generic-array" version = "0.14.9" @@ -613,6 +694,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f" dependencies = [ + "block-padding", "hybrid-array", ] @@ -655,6 +737,16 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -942,6 +1034,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rsa" version = "0.9.10" @@ -985,6 +1086,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "salsa20" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" +dependencies = [ + "cfg-if", + "cipher 0.5.2", +] + [[package]] name = "sec1" version = "0.7.3" @@ -1091,6 +1202,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "smallvec" version = "1.16.4" diff --git a/Cargo.toml b/Cargo.toml index 1ff9052..1c48dac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.7.0" +version = "0.8.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-kdbx/Cargo.toml b/crates/custos-kdbx/Cargo.toml new file mode 100644 index 0000000..1cc5cc4 --- /dev/null +++ b/crates/custos-kdbx/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "custos-kdbx" +description = "KeePass KDBX 4 import and export for Custos: the file format and the item mapping" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +custos-vault = { path = "../custos-vault" } +aes = "0.9" +cbc = { version = "0.2", features = ["alloc", "block-padding"] } +chacha20 = "0.10" +salsa20 = "0.11" +argon2.workspace = true +hmac.workspace = true +sha2.workspace = true +zeroize.workspace = true +rand.workspace = true +thiserror.workspace = true +data-encoding.workspace = true +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +roxmltree = { version = "0.21", default-features = false, features = ["std"] } + +[dev-dependencies] +serde_json.workspace = true diff --git a/crates/custos-kdbx/examples/kdbx_tool.rs b/crates/custos-kdbx/examples/kdbx_tool.rs new file mode 100644 index 0000000..d6438f2 --- /dev/null +++ b/crates/custos-kdbx/examples/kdbx_tool.rs @@ -0,0 +1,41 @@ +//! A dev tool for the KeePassXC interop check (tools/kdbx/interop.sh). The password comes from +//! `KDBX_PASSWORD`, never from the command line. +//! +//! ```text +//! kdbx_tool new OUT [fast] an empty KDBX 4 database (fast: Argon2id 1 MiB, 2 passes) +//! kdbx_tool roundtrip IN OUT IN → Custos items → OUT, as the app's import and export do +//! kdbx_tool items IN the Custos items IN maps to, as JSON (test databases only: it prints secrets) +//! ``` + +use custos_kdbx::{Database, Kdf, Key, SecretString, WriteOptions, from_items, read, to_items, write}; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let password = SecretString::new(std::env::var("KDBX_PASSWORD").expect("set KDBX_PASSWORD")); + let key = Key { password: Some(&password), key_file: None }; + let open = |path: &str| read(&std::fs::read(path).expect("read"), &key).unwrap_or_else(|e| panic!("{path}: {e}")); + match args.iter().map(String::as_str).collect::>()[..] { + ["new", out, ref rest @ ..] => { + let mut opts = WriteOptions::default(); + if rest == ["fast"] { + opts.kdf = Kdf::Argon2id { m_kib: 1024, t: 2, p: 1 }; + } + let db = Database { name: "Interop".into(), ..Default::default() }; + std::fs::write(out, write(&db, &key, opts).expect("write")).expect("write file"); + } + ["roundtrip", input, out] => { + let db = open(input); + let items = to_items(&db); + let back = from_items(&items, &db.name); + std::fs::write(out, write(&back, &key, WriteOptions::default()).expect("write")).expect("write file"); + eprintln!("{} items", items.len()); + } + ["items", input] => { + println!("{}", serde_json::to_string_pretty(&to_items(&open(input))).expect("json")); + } + _ => { + eprintln!("usage: kdbx_tool new OUT [fast] | roundtrip IN OUT | items IN"); + std::process::exit(2); + } + } +} diff --git a/crates/custos-kdbx/src/crypto.rs b/crates/custos-kdbx/src/crypto.rs new file mode 100644 index 0000000..9dc7c66 --- /dev/null +++ b/crates/custos-kdbx/src/crypto.rs @@ -0,0 +1,220 @@ +//! The only module that calls the cryptographic crates: the composite key, key files, the KDFs, the +//! outer ciphers, the HMAC block keys and the inner stream (docs/KDBX.md, "Reading"). + +use crate::{Error, Key}; +use aes::Aes256; +use aes::cipher::{BlockCipherEncrypt, BlockModeDecrypt, BlockModeEncrypt, KeyInit, KeyIvInit, StreamCipher}; +use cbc::cipher::block_padding::Pkcs7; +use chacha20::ChaCha20; +use hmac::{Hmac, Mac}; +use rand::Rng; +use rand::rand_core::UnwrapErr; +use rand::rngs::SysRng; +use sha2::{Digest, Sha256, Sha512}; +use zeroize::Zeroizing; + +pub(crate) type K32 = Zeroizing<[u8; 32]>; +pub(crate) type K64 = Zeroizing<[u8; 64]>; + +pub(crate) fn fill_random(buf: &mut [u8]) { + UnwrapErr(SysRng).fill_bytes(buf); +} + +pub(crate) fn sha256(parts: &[&[u8]]) -> K32 { + let mut h = Sha256::new(); + for p in parts { + h.update(p); + } + Zeroizing::new(h.finalize().into()) +} + +pub(crate) fn sha512(parts: &[&[u8]]) -> K64 { + let mut h = Sha512::new(); + for p in parts { + h.update(p); + } + Zeroizing::new(h.finalize().into()) +} + +/// SHA-256 over each key part's 32-byte form, concatenated (KeePass's composite key). +pub(crate) fn composite(key: &Key) -> Result { + let mut parts: Vec = Vec::new(); + if let Some(p) = key.password.filter(|p| !p.is_empty()) { + parts.push(sha256(&[p.expose().as_bytes()])); + } + if let Some(f) = key.key_file { + parts.push(key_file(f)?); + } + if parts.is_empty() { + return Err(Error::NoKey); + } + let refs: Vec<&[u8]> = parts.iter().map(|p| p.as_slice()).collect(); + Ok(sha256(&refs)) +} + +/// A key file's 32-byte key: KeePass XML 2.0 or 1.0, 32 raw bytes, 64 hex digits, or SHA-256 of the file. +pub(crate) fn key_file(f: &[u8]) -> Result { + let head = &f[..f.len().min(256)]; + if head.windows(8).any(|w| w == b" Result { + const BAD: Error = Error::Malformed("key file"); + let text = std::str::from_utf8(f).map_err(|_| BAD)?; + let doc = roxmltree::Document::parse_with_options( + text, + roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1000, ..Default::default() }, + ) + .map_err(|_| BAD)?; + let find = |name: &str| doc.descendants().find(|n| n.has_tag_name(name)); + let version = find("Version").and_then(|n| n.text()).unwrap_or("").trim().to_owned(); + let data = find("Data").ok_or(BAD)?; + let body: Zeroizing = Zeroizing::new(data.text().unwrap_or("").split_whitespace().collect()); + let bytes = Zeroizing::new(if version.starts_with("2.") { + let b = data_encoding::HEXUPPER_PERMISSIVE.decode(body.as_bytes()).map_err(|_| BAD)?; + if let Some(hash) = data.attribute("Hash") { + let want = data_encoding::HEXUPPER_PERMISSIVE.decode(hash.trim().as_bytes()).map_err(|_| BAD)?; + if sha256(&[&b])[..4] != want[..] { + return Err(Error::Malformed("key file checksum")); + } + } + b + } else if version.starts_with("1.") { + data_encoding::BASE64.decode(body.as_bytes()).map_err(|_| BAD)? + } else { + return Err(Error::Malformed("key file version")); + }); + let k: [u8; 32] = bytes.as_slice().try_into().map_err(|_| BAD)?; + Ok(Zeroizing::new(k)) +} + +/// Argon2d or Argon2id. The caller has checked the parameters against the limits. +pub(crate) fn argon2(composite: &[u8], id: bool, salt: &[u8], m_kib: u32, t: u32, p: u32) -> Result { + use argon2::{Algorithm, Argon2, Params, Version}; + let params = Params::new(m_kib, t, p, Some(32)).map_err(|_| Error::UnsupportedKdf)?; + let alg = if id { Algorithm::Argon2id } else { Algorithm::Argon2d }; + let mut out = Zeroizing::new([0u8; 32]); + Argon2::new(alg, Version::V0x13, params) + .hash_password_into(composite, salt, out.as_mut()) + .map_err(|_| Error::UnsupportedKdf)?; + Ok(out) +} + +/// AES-KDF: `rounds` AES-256-ECB encryptions of both halves keyed with `seed`, then SHA-256. +pub(crate) fn aes_kdf(composite: &[u8], seed: &[u8; 32], rounds: u64) -> K32 { + let cipher = Aes256::new(seed.into()); + let mut blocks = Zeroizing::new([[0u8; 16]; 2]); + blocks[0].copy_from_slice(&composite[..16]); + blocks[1].copy_from_slice(&composite[16..32]); + for _ in 0..rounds { + for b in blocks.iter_mut() { + cipher.encrypt_block(b.into()); + } + } + sha256(&[&blocks[0], &blocks[1]]) +} + +pub(crate) struct Keys { + pub cipher: K32, + hmac_base: K64, +} + +impl Keys { + pub(crate) fn new(master_seed: &[u8], transformed: &[u8]) -> Self { + Keys { cipher: sha256(&[master_seed, transformed]), hmac_base: sha512(&[master_seed, transformed, &[1]]) } + } + + fn block_key(&self, index: u64) -> K64 { + sha512(&[&index.to_le_bytes(), self.hmac_base.as_slice()]) + } + + pub(crate) fn header_hmac(&self, header: &[u8]) -> [u8; 32] { + mac(self.block_key(u64::MAX).as_slice(), &[header]) + } + + pub(crate) fn block_hmac(&self, index: u64, data: &[u8]) -> [u8; 32] { + mac(self.block_key(index).as_slice(), &[&index.to_le_bytes(), &(data.len() as u32).to_le_bytes(), data]) + } +} + +fn mac(key: &[u8], parts: &[&[u8]]) -> [u8; 32] { + let mut m = >::new_from_slice(key).expect("HMAC takes any key length"); + for p in parts { + m.update(p); + } + m.finalize().into_bytes().into() +} + +/// Constant-time comparison of two MACs. +pub(crate) fn same(a: &[u8; 32], b: &[u8]) -> bool { + b.len() == 32 && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +pub(crate) fn chacha20(key: &[u8; 32], nonce: &[u8; 12], data: &mut [u8]) { + ChaCha20::new(key.into(), nonce.into()).apply_keystream(data); +} + +pub(crate) fn aes_cbc_decrypt(key: &[u8; 32], iv: &[u8; 16], data: &mut Vec) -> Result<(), Error> { + let n = cbc::Decryptor::::new(key.into(), iv.into()) + .decrypt_padded::(data) + .map_err(|_| Error::Corrupted)? + .len(); + data.truncate(n); + Ok(()) +} + +pub(crate) fn aes_cbc_encrypt(key: &[u8; 32], iv: &[u8; 16], data: &mut Vec) { + let len = data.len(); + data.resize(len + 16 - len % 16, 0); + let n = cbc::Encryptor::::new(key.into(), iv.into()) + .encrypt_padded::(data, len) + .expect("room for the padding") + .len(); + data.truncate(n); +} + +/// The inner stream that hides protected values. +pub(crate) enum InnerStream { + /// KDBX 4: ChaCha20 keyed from SHA-512 of the stream key. + ChaCha20(ChaCha20), + /// KDBX 3.1: Salsa20 keyed with SHA-256 of the stream key and KeePass's fixed nonce. + Salsa20(salsa20::Salsa20), +} + +impl InnerStream { + pub(crate) fn chacha20(stream_key: &[u8]) -> Self { + let h = sha512(&[stream_key]); + let key = Zeroizing::new(<[u8; 32]>::try_from(&h[..32]).expect("32 bytes")); + let nonce: [u8; 12] = h[32..44].try_into().expect("12 bytes"); + InnerStream::ChaCha20(ChaCha20::new((&*key).into(), (&nonce).into())) + } + + pub(crate) fn salsa20(stream_key: &[u8]) -> Self { + const NONCE: [u8; 8] = [0xE8, 0x30, 0x09, 0x4B, 0x97, 0x20, 0x5D, 0x2A]; + let key = sha256(&[stream_key]); + InnerStream::Salsa20(salsa20::Salsa20::new((&*key).into(), (&NONCE).into())) + } + + pub(crate) fn apply(&mut self, data: &mut [u8]) { + match self { + InnerStream::ChaCha20(c) => c.apply_keystream(data), + InnerStream::Salsa20(c) => c.apply_keystream(data), + } + } +} diff --git a/crates/custos-kdbx/src/format.rs b/crates/custos-kdbx/src/format.rs new file mode 100644 index 0000000..b7f3f22 --- /dev/null +++ b/crates/custos-kdbx/src/format.rs @@ -0,0 +1,568 @@ +//! The outer KDBX 4 file: header, KDF parameters, HMAC blocks, payload cipher, gzip, inner header +//! (docs/KDBX.md, "Reading" and "Writing"). + +use crate::crypto::{self, InnerStream, K32, Keys}; +use crate::{Database, Error, Key, xml}; +use custos_vault::SecretBytes; +use std::io::{Read, Write}; +use zeroize::Zeroizing; + +const SIG1: [u8; 4] = [0x03, 0xD9, 0xA2, 0x9A]; +const SIG2: [u8; 4] = [0x67, 0xFB, 0x4B, 0xB5]; + +const CIPHER_AES256: [u8; 16] = uuid(0x31c1f2e6_bf71_4350_be58_05216afc5aff); +const CIPHER_CHACHA20: [u8; 16] = uuid(0xd6038a2b_8b6f_4cb5_a524_339a31dbb59a); +const KDF_AES: [u8; 16] = uuid(0xc9d9f39a_628a_4460_bf74_0d08c18a4fea); +const KDF_ARGON2D: [u8; 16] = uuid(0xef636ddf_8c29_444b_91f7_a9a403e30a0c); +const KDF_ARGON2ID: [u8; 16] = uuid(0x9e298b19_56db_4773_b23d_fc3ec6f0a1e6); + +const fn uuid(v: u128) -> [u8; 16] { + v.to_be_bytes() +} + +const MAX_FILE: usize = 512 << 20; +const MAX_FIELD: usize = 64 << 10; +const MAX_PAYLOAD: u64 = 512 << 20; +const MAX_ARGON2_BYTES: u64 = 2 << 30; +const MAX_AES_ROUNDS: u64 = 1 << 30; +const BLOCK: usize = 1 << 20; +const STREAM_CHACHA20: u32 = 3; + +/// The outer cipher an export uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cipher { + Aes256, + ChaCha20, +} + +/// The key derivation an export uses. `m_kib` is Argon2's memory in KiB. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kdf { + Argon2d { m_kib: u32, t: u32, p: u32 }, + Argon2id { m_kib: u32, t: u32, p: u32 }, + Aes { rounds: u64 }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WriteOptions { + pub cipher: Cipher, + pub kdf: Kdf, +} + +impl Default for WriteOptions { + /// ChaCha20 and Argon2id with the vault's own defaults (64 MiB, 20 passes, 1 lane). + fn default() -> Self { + WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 65_536, t: 20, p: 1 } } + } +} + +struct Cur<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Cur<'a> { + fn take(&mut self, n: usize, e: Error) -> Result<&'a [u8], Error> { + let end = self.pos.checked_add(n).filter(|&end| end <= self.b.len()).ok_or(e)?; + let s = &self.b[self.pos..end]; + self.pos = end; + Ok(s) + } + + fn u8(&mut self, e: Error) -> Result { + Ok(self.take(1, e)?[0]) + } + + fn u32(&mut self, e: Error) -> Result { + Ok(u32::from_le_bytes(self.take(4, e)?.try_into().expect("4 bytes"))) + } +} + +/// Opens a KDBX 4 file. +pub fn read(bytes: &[u8], key: &Key) -> Result { + if bytes.len() > MAX_FILE { + return Err(Error::TooLarge); + } + if bytes.len() < 12 || bytes[..4] != SIG1 || bytes[4..8] != SIG2 { + return Err(Error::NotKdbx); + } + let minor = u16::from_le_bytes([bytes[8], bytes[9]]); + let major = u16::from_le_bytes([bytes[10], bytes[11]]); + match major { + 4 => {} + 3 => return read3(bytes, key), + _ => return Err(Error::UnsupportedVersion(major, minor)), + } + + // The outer header. + let mut c = Cur { b: bytes, pos: 12 }; + let (mut cipher, mut compression, mut seed, mut iv, mut kdf) = (None, None, None, None, None); + loop { + let id = c.u8(Error::Corrupted)?; + let len = c.u32(Error::Corrupted)? as usize; + if len > MAX_FIELD { + return Err(Error::Malformed("header field too long")); + } + let data = c.take(len, Error::Corrupted)?; + match id { + 0 => break, + 2 => cipher = Some(data), + 3 => compression = Some(u32::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("compression"))?)), + 4 => seed = Some(data), + 7 => iv = Some(data), + 11 => kdf = Some(data), + _ => {} // public custom data, and KDBX 3 fields that mean nothing here + } + } + let header = &bytes[..c.pos]; + let hash = c.take(32, Error::Corrupted)?; + let hmac = c.take(32, Error::Corrupted)?; + if crypto::sha256(&[header])[..] != hash[..] { + return Err(Error::Corrupted); + } + let cipher = match cipher.ok_or(Error::Malformed("no cipher"))? { + c if c == CIPHER_AES256 => Cipher::Aes256, + c if c == CIPHER_CHACHA20 => Cipher::ChaCha20, + _ => return Err(Error::UnsupportedCipher), + }; + let seed = seed.filter(|s| s.len() == 32).ok_or(Error::Malformed("master seed"))?; + let (kdf, salt) = parse_kdf(kdf.ok_or(Error::Malformed("no KDF parameters"))?)?; + + // The key, checked against the header before anything is decrypted. + let transformed = transform(&crypto::composite(key)?, kdf, &salt)?; + let keys = Keys::new(seed, transformed.as_slice()); + if !crypto::same(&keys.header_hmac(header), hmac) { + return Err(Error::WrongKey); + } + + // HMAC blocks. + let mut payload = Vec::new(); + for index in 0u64.. { + let mac = c.take(32, Error::Corrupted)?; + let len = c.u32(Error::Corrupted)? as usize; + let data = c.take(len, Error::Corrupted)?; + if !crypto::same(&keys.block_hmac(index, data), mac) { + return Err(Error::Corrupted); + } + if len == 0 { + break; + } + payload.extend_from_slice(data); + } + + let mut plain = Zeroizing::new(payload); + let iv = iv.ok_or(Error::Malformed("no IV"))?; + match cipher { + Cipher::Aes256 => { + let iv: &[u8; 16] = iv.try_into().map_err(|_| Error::Malformed("IV"))?; + crypto::aes_cbc_decrypt(&keys.cipher, iv, &mut plain)?; + } + Cipher::ChaCha20 => { + let iv: &[u8; 12] = iv.try_into().map_err(|_| Error::Malformed("IV"))?; + crypto::chacha20(&keys.cipher, iv, &mut plain); + } + } + let inner = match compression { + Some(0) => plain, + Some(1) => gunzip(&plain)?, + _ => return Err(Error::Malformed("compression")), + }; + + // The inner header. + let mut c = Cur { b: &inner, pos: 0 }; + let (mut stream_id, mut stream_key) = (None, None); + let mut pool = Vec::new(); + loop { + let id = c.u8(Error::Malformed("inner header"))?; + let len = c.u32(Error::Malformed("inner header"))? as usize; + let data = c.take(len, Error::Malformed("inner header"))?; + match id { + 0 => break, + 1 => stream_id = Some(u32::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("inner stream"))?)), + 2 => stream_key = Some(data), + 3 => { + let (_flags, content) = data.split_first().ok_or(Error::Malformed("attachment"))?; + pool.push(SecretBytes::from(content)); + } + _ => {} + } + } + let stream_key = stream_key.filter(|k| !k.is_empty()).ok_or(Error::Malformed("inner stream"))?; + let mut stream = match stream_id { + Some(STREAM_CHACHA20) => InnerStream::chacha20(stream_key), + _ => return Err(Error::UnsupportedStream), + }; + xml::parse(&inner[c.pos..], &mut stream, &pool) +} + +/// KDBX 3.1: 16-bit header field lengths, AES-KDF from the header, no header HMAC (the first 32 bytes of the +/// payload must equal `StreamStartBytes` instead), SHA-256 hashed blocks, a Salsa20 inner stream, and the +/// attachments in `Meta/Binaries` (docs/KDBX.md, "KDBX 3.1"). +fn read3(bytes: &[u8], key: &Key) -> Result { + let mut c = Cur { b: bytes, pos: 12 }; + let (mut cipher, mut compression, mut seed, mut iv) = (None, None, None, None); + let (mut tseed, mut rounds, mut stream_key, mut start, mut stream_id) = (None, None, None, None, None); + let u32_ = |d: &[u8]| d.try_into().map(u32::from_le_bytes).map_err(|_| Error::Malformed("header field")); + loop { + let id = c.u8(Error::Corrupted)?; + let len = u16::from_le_bytes(c.take(2, Error::Corrupted)?.try_into().expect("2 bytes")) as usize; + let data = c.take(len, Error::Corrupted)?; + match id { + 0 => break, + 2 => cipher = Some(data), + 3 => compression = Some(u32_(data)?), + 4 => seed = Some(data), + 5 => tseed = Some(data), + 6 => rounds = Some(u64::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("rounds"))?)), + 7 => iv = Some(data), + 8 => stream_key = Some(data), + 9 => start = Some(data), + 10 => stream_id = Some(u32_(data)?), + _ => {} + } + } + let cipher = match cipher.ok_or(Error::Malformed("no cipher"))? { + c if c == CIPHER_AES256 => Cipher::Aes256, + c if c == CIPHER_CHACHA20 => Cipher::ChaCha20, + _ => return Err(Error::UnsupportedCipher), + }; + let seed = seed.filter(|s| s.len() == 32).ok_or(Error::Malformed("master seed"))?; + let tseed: &[u8; 32] = tseed.and_then(|s| s.try_into().ok()).ok_or(Error::UnsupportedKdf)?; + let kdf = Kdf::Aes { rounds: rounds.ok_or(Error::UnsupportedKdf)? }; + check_kdf(kdf)?; + let start: &[u8; 32] = start.and_then(|s| s.try_into().ok()).ok_or(Error::Malformed("stream start bytes"))?; + let stream_key = stream_key.filter(|k| !k.is_empty()).ok_or(Error::Malformed("inner stream"))?; + let mut stream = match stream_id { + Some(2) => InnerStream::salsa20(stream_key), + Some(STREAM_CHACHA20) => InnerStream::chacha20(stream_key), + _ => return Err(Error::UnsupportedStream), + }; + + let transformed = transform(&crypto::composite(key)?, kdf, tseed)?; + let keys = Keys::new(seed, transformed.as_slice()); + let mut plain = Zeroizing::new(bytes[c.pos..].to_vec()); + let iv = iv.ok_or(Error::Malformed("no IV"))?; + match cipher { + Cipher::Aes256 => { + let iv: &[u8; 16] = iv.try_into().map_err(|_| Error::Malformed("IV"))?; + // A wrong key gives garbage, usually with broken padding: that is a wrong key, not damage. + crypto::aes_cbc_decrypt(&keys.cipher, iv, &mut plain).map_err(|_| Error::WrongKey)?; + } + Cipher::ChaCha20 => { + let iv: &[u8; 12] = iv.try_into().map_err(|_| Error::Malformed("IV"))?; + crypto::chacha20(&keys.cipher, iv, &mut plain); + } + } + if plain.len() < 32 || !crypto::same(start, &plain[..32]) { + return Err(Error::WrongKey); + } + + // Hashed blocks: index (u32), SHA-256 (32), length (u32), data; a zero length ends them. + let mut c = Cur { b: &plain, pos: 32 }; + let mut payload = Zeroizing::new(Vec::new()); + for index in 0u32.. { + if c.u32(Error::Corrupted)? != index { + return Err(Error::Corrupted); + } + let hash = c.take(32, Error::Corrupted)?; + let len = c.u32(Error::Corrupted)? as usize; + if len == 0 { + if hash.iter().any(|&b| b != 0) { + return Err(Error::Corrupted); + } + break; + } + let data = c.take(len, Error::Corrupted)?; + if crypto::sha256(&[data])[..] != hash[..] { + return Err(Error::Corrupted); + } + payload.extend_from_slice(data); + } + let xml_bytes = match compression { + Some(0) => payload, + Some(1) => gunzip(&payload)?, + _ => return Err(Error::Malformed("compression")), + }; + xml::parse(&xml_bytes, &mut stream, &[]) +} + +/// Writes a KDBX 4.0 file (docs/KDBX.md, "Writing"). +pub fn write(db: &Database, key: &Key, opts: WriteOptions) -> Result, Error> { + let composite = crypto::composite(key)?; + let mut seed = [0u8; 32]; + let mut salt = [0u8; 32]; + let mut stream_key = Zeroizing::new([0u8; 64]); + crypto::fill_random(&mut seed); + crypto::fill_random(&mut salt); + crypto::fill_random(stream_key.as_mut()); + let mut iv = vec![0u8; if opts.cipher == Cipher::Aes256 { 16 } else { 12 }]; + crypto::fill_random(&mut iv); + + check_kdf(opts.kdf)?; + let transformed = transform(&composite, opts.kdf, &salt)?; + let keys = Keys::new(&seed, transformed.as_slice()); + + let mut out = Vec::new(); + out.extend_from_slice(&SIG1); + out.extend_from_slice(&SIG2); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&4u16.to_le_bytes()); + let cipher_id = if opts.cipher == Cipher::Aes256 { CIPHER_AES256 } else { CIPHER_CHACHA20 }; + field(&mut out, 2, &cipher_id); + field(&mut out, 3, &1u32.to_le_bytes()); + field(&mut out, 4, &seed); + field(&mut out, 7, &iv); + field(&mut out, 11, &kdf_dict(opts.kdf, &salt)); + field(&mut out, 0, b"\r\n\r\n"); + let hash = crypto::sha256(&[&out]); + let hmac = keys.header_hmac(&out); + out.extend_from_slice(hash.as_slice()); + out.extend_from_slice(&hmac); + + let mut stream = InnerStream::chacha20(stream_key.as_slice()); + let mut pool: Vec<&SecretBytes> = Vec::new(); + let body = xml::write(db, &mut stream, &mut pool); + let mut inner = Zeroizing::new(Vec::with_capacity(body.len() + 128)); + field(&mut inner, 1, &STREAM_CHACHA20.to_le_bytes()); + field(&mut inner, 2, stream_key.as_slice()); + for a in pool { + let mut b = Zeroizing::new(Vec::with_capacity(a.len() + 1)); + b.push(0); + b.extend_from_slice(a.expose()); + field(&mut inner, 3, &b); + } + field(&mut inner, 0, &[]); + inner.extend_from_slice(body.as_bytes()); + + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gz.write_all(&inner).expect("writing to memory"); + let mut payload = gz.finish().expect("writing to memory"); + match opts.cipher { + Cipher::Aes256 => crypto::aes_cbc_encrypt(&keys.cipher, iv.as_slice().try_into().expect("16"), &mut payload), + Cipher::ChaCha20 => crypto::chacha20(&keys.cipher, iv.as_slice().try_into().expect("12"), &mut payload), + } + let mut index = 0u64; + for chunk in payload.chunks(BLOCK).chain(std::iter::once(&[][..])) { + out.extend_from_slice(&keys.block_hmac(index, chunk)); + out.extend_from_slice(&(chunk.len() as u32).to_le_bytes()); + out.extend_from_slice(chunk); + index += 1; + } + Ok(out) +} + +fn field(out: &mut Vec, id: u8, data: &[u8]) { + out.push(id); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(data); +} + +pub(crate) fn gunzip(data: &[u8]) -> Result>, Error> { + let mut out = Zeroizing::new(Vec::new()); + flate2::read::GzDecoder::new(data).take(MAX_PAYLOAD + 1).read_to_end(&mut out).map_err(|_| Error::Corrupted)?; + if out.len() as u64 > MAX_PAYLOAD { + return Err(Error::TooLarge); + } + Ok(out) +} + +fn transform(composite: &K32, kdf: Kdf, salt: &[u8]) -> Result { + match kdf { + Kdf::Argon2d { m_kib, t, p } => crypto::argon2(composite.as_slice(), false, salt, m_kib, t, p), + Kdf::Argon2id { m_kib, t, p } => crypto::argon2(composite.as_slice(), true, salt, m_kib, t, p), + Kdf::Aes { rounds } => { + let seed: &[u8; 32] = salt.try_into().map_err(|_| Error::UnsupportedKdf)?; + Ok(crypto::aes_kdf(composite.as_slice(), seed, rounds)) + } + } +} + +fn check_kdf(kdf: Kdf) -> Result<(), Error> { + let ok = match kdf { + Kdf::Argon2d { m_kib, t, p } | Kdf::Argon2id { m_kib, t, p } => { + (1..=64).contains(&p) + && (1..=1000).contains(&t) + && u64::from(m_kib) * 1024 <= MAX_ARGON2_BYTES + && m_kib >= 8 * p + } + Kdf::Aes { rounds } => (1..=MAX_AES_ROUNDS).contains(&rounds), + }; + if ok { Ok(()) } else { Err(Error::UnsupportedKdf) } +} + +// VariantDictionary value types. +const VD_U32: u8 = 0x04; +const VD_U64: u8 = 0x05; +const VD_BYTES: u8 = 0x42; + +/// The KDF and its salt (Argon2 `S`) or seed (AES-KDF `S`), checked against the limits. +fn parse_kdf(d: &[u8]) -> Result<(Kdf, Vec), Error> { + const BAD: Error = Error::Malformed("KDF parameters"); + let mut c = Cur { b: d, pos: 0 }; + let version = u16::from_le_bytes(c.take(2, BAD)?.try_into().expect("2 bytes")); + if version & 0xFF00 != 0x0100 { + return Err(BAD); + } + let mut map: Vec<(&[u8], u8, &[u8])> = Vec::new(); + loop { + let kind = c.u8(BAD)?; + if kind == 0 { + break; + } + let klen = c.u32(BAD)? as usize; + let k = c.take(klen, BAD)?; + let vlen = c.u32(BAD)? as usize; + let v = c.take(vlen, BAD)?; + map.push((k, kind, v)); + } + let get = |name: &str, kind: u8| map.iter().find(|(k, t, _)| *k == name.as_bytes() && *t == kind).map(|e| e.2); + let u32_ = |name| get(name, VD_U32).and_then(|v| v.try_into().ok()).map(u32::from_le_bytes); + let u64_ = |name| get(name, VD_U64).and_then(|v| v.try_into().ok()).map(u64::from_le_bytes); + let id = get("$UUID", VD_BYTES).ok_or(BAD)?; + let salt = get("S", VD_BYTES).ok_or(Error::UnsupportedKdf)?.to_vec(); + let kdf = if id == KDF_AES { + if salt.len() != 32 { + return Err(Error::UnsupportedKdf); + } + Kdf::Aes { rounds: u64_("R").ok_or(Error::UnsupportedKdf)? } + } else if id == KDF_ARGON2D || id == KDF_ARGON2ID { + let m = u64_("M").ok_or(Error::UnsupportedKdf)?; + let t = u64_("I").ok_or(Error::UnsupportedKdf)?; + let p = u32_("P").ok_or(Error::UnsupportedKdf)?; + let extra = |n| get(n, VD_BYTES).is_some_and(|v| !v.is_empty()); + if u32_("V") != Some(0x13) || extra("K") || extra("A") || !(8..=64).contains(&salt.len()) { + return Err(Error::UnsupportedKdf); + } + if m % 1024 != 0 || m > MAX_ARGON2_BYTES || t > 1000 { + return Err(Error::UnsupportedKdf); + } + let (m_kib, t) = ((m / 1024) as u32, t as u32); + if id == KDF_ARGON2D { Kdf::Argon2d { m_kib, t, p } } else { Kdf::Argon2id { m_kib, t, p } } + } else { + return Err(Error::UnsupportedKdf); + }; + check_kdf(kdf)?; + Ok((kdf, salt)) +} + +fn kdf_dict(kdf: Kdf, salt: &[u8; 32]) -> Vec { + let mut d = 0x0100u16.to_le_bytes().to_vec(); + let mut item = |kind: u8, k: &str, v: &[u8]| { + d.push(kind); + d.extend_from_slice(&(k.len() as u32).to_le_bytes()); + d.extend_from_slice(k.as_bytes()); + d.extend_from_slice(&(v.len() as u32).to_le_bytes()); + d.extend_from_slice(v); + }; + match kdf { + Kdf::Argon2d { m_kib, t, p } | Kdf::Argon2id { m_kib, t, p } => { + let id = if matches!(kdf, Kdf::Argon2d { .. }) { KDF_ARGON2D } else { KDF_ARGON2ID }; + item(VD_BYTES, "$UUID", &id); + item(VD_BYTES, "S", salt); + item(VD_U32, "P", &p.to_le_bytes()); + item(VD_U64, "M", &(u64::from(m_kib) * 1024).to_le_bytes()); + item(VD_U64, "I", &u64::from(t).to_le_bytes()); + item(VD_U32, "V", &0x13u32.to_le_bytes()); + } + Kdf::Aes { rounds } => { + item(VD_BYTES, "$UUID", &KDF_AES); + item(VD_U64, "R", &rounds.to_le_bytes()); + item(VD_BYTES, "S", salt); + } + } + d.push(0); + d +} + +/// Test hooks: build files with chosen KDF parameters, inner streams or payloads, to check the reader refuses them. +#[doc(hidden)] +pub mod testing { + use super::*; + + /// A valid file around `inner` (inner header + XML, before gzip) with the given KDF dictionary bytes, + /// keyed with `transformed` directly (no KDF runs). + pub fn build(kdf_dict_bytes: &[u8], transformed: &[u8; 32], inner: &[u8], gzip: bool) -> Vec { + let payload = if gzip { + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); + gz.write_all(inner).unwrap(); + gz.finish().unwrap() + } else { + inner.to_vec() + }; + assemble(kdf_dict_bytes, transformed, payload, gzip) + } + + /// The same around a payload that is already gzipped. + pub fn build_compressed(kdf_dict_bytes: &[u8], transformed: &[u8; 32], gz: &[u8]) -> Vec { + assemble(kdf_dict_bytes, transformed, gz.to_vec(), true) + } + + fn assemble(kdf_dict_bytes: &[u8], transformed: &[u8; 32], mut payload: Vec, gzip: bool) -> Vec { + let seed = [7u8; 32]; + let iv = [9u8; 12]; + let keys = Keys::new(&seed, transformed); + let mut out = Vec::new(); + out.extend_from_slice(&SIG1); + out.extend_from_slice(&SIG2); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&4u16.to_le_bytes()); + field(&mut out, 2, &CIPHER_CHACHA20); + field(&mut out, 3, &u32::from(gzip).to_le_bytes()); + field(&mut out, 4, &seed); + field(&mut out, 7, &iv); + field(&mut out, 11, kdf_dict_bytes); + field(&mut out, 0, b"\r\n\r\n"); + let hash = crypto::sha256(&[&out]); + let hmac = keys.header_hmac(&out); + out.extend_from_slice(hash.as_slice()); + out.extend_from_slice(&hmac); + crypto::chacha20(&keys.cipher, &iv, &mut payload); + for (index, chunk) in payload.chunks(BLOCK).chain(std::iter::once(&[][..])).enumerate() { + out.extend_from_slice(&keys.block_hmac(index as u64, chunk)); + out.extend_from_slice(&(chunk.len() as u32).to_le_bytes()); + out.extend_from_slice(chunk); + } + out + } + + /// A KDF dictionary for AES-KDF with `rounds` (and a fixed seed), or raw entries. + pub fn aes_dict(rounds: u64) -> Vec { + kdf_dict(Kdf::Aes { rounds }, &[3u8; 32]) + } + + /// An Argon2 dictionary with the given raw values (memory in bytes), unchecked. + pub fn argon2_dict(id: bool, m_bytes: u64, t: u64, p: u32, version: u32) -> Vec { + let mut d = 0x0100u16.to_le_bytes().to_vec(); + let mut item = |kind: u8, k: &str, v: &[u8]| { + d.push(kind); + d.extend_from_slice(&(k.len() as u32).to_le_bytes()); + d.extend_from_slice(k.as_bytes()); + d.extend_from_slice(&(v.len() as u32).to_le_bytes()); + d.extend_from_slice(v); + }; + item(VD_BYTES, "$UUID", if id { &KDF_ARGON2ID } else { &KDF_ARGON2D }); + item(VD_BYTES, "S", &[5u8; 32]); + item(VD_U32, "P", &p.to_le_bytes()); + item(VD_U64, "M", &m_bytes.to_le_bytes()); + item(VD_U64, "I", &t.to_le_bytes()); + item(VD_U32, "V", &version.to_le_bytes()); + d.push(0); + d + } + + /// The transformed key AES-KDF gives for a password and `aes_dict(rounds)`. + pub fn aes_transformed(password: &str, rounds: u64) -> [u8; 32] { + let composite = crypto::sha256(&[crypto::sha256(&[password.as_bytes()]).as_slice()]); + *crypto::aes_kdf(composite.as_slice(), &[3u8; 32], rounds) + } + + /// An inner header: stream id, a 64-byte stream key of 1s, then `xml`. + pub fn inner(stream_id: u32, xml: &[u8]) -> Vec { + let mut v = Vec::new(); + field(&mut v, 1, &stream_id.to_le_bytes()); + field(&mut v, 2, &[1u8; 64]); + field(&mut v, 0, &[]); + v.extend_from_slice(xml); + v + } +} diff --git a/crates/custos-kdbx/src/lib.rs b/crates/custos-kdbx/src/lib.rs new file mode 100644 index 0000000..f7a9621 --- /dev/null +++ b/crates/custos-kdbx/src/lib.rs @@ -0,0 +1,121 @@ +//! KeePass KDBX import (3.1 and 4) and export (4) (docs/KDBX.md). +//! +//! Two layers: [`read`] / [`write`] turn bytes and a [`Key`] into a [`Database`] and back; +//! [`to_items`] / [`from_items`] map KeePass entries to Custos items and back. + +mod crypto; +mod format; +mod map; +mod time; +mod xml; + +pub use custos_vault::{SecretBytes, SecretString}; +#[doc(hidden)] +pub use format::testing; +pub use format::{Cipher, Kdf, WriteOptions, read, write}; +pub use map::{from_items, to_items}; +pub use time::{format_iso, parse_iso}; + +/// A whole KDBX database, as far as Custos keeps it (docs/KDBX.md, "What does not survive"). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Database { + /// `Meta/DatabaseName`. + pub name: String, + pub root: Group, + /// The recycle bin group, when the file has one switched on. Its entries are not imported. + pub recycle_bin: Option<[u8; 16]>, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Group { + pub uuid: [u8; 16], + pub name: String, + pub groups: Vec, + pub entries: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Entry { + pub uuid: [u8; 16], + /// In file order. Keys are unique within an entry. + pub strings: Vec, + pub attachments: Vec, + pub tags: Vec, + pub times: Times, + pub autotype: AutoType, + /// Older versions of this entry, oldest first (KeePass order). Their own history is empty. + pub history: Vec, +} + +impl Entry { + /// The value of the string called `key`. + pub fn get(&self, key: &str) -> Option<&SecretString> { + self.strings.iter().find(|s| s.key == key).map(|s| &s.value) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StringField { + pub key: String, + pub value: SecretString, + /// Written XORed with the inner stream (KeePass's "protect in memory"). + pub protected: bool, +} + +/// Unix seconds (UTC). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Times { + pub created: i64, + pub modified: i64, + /// `ExpiryTime` when `Expires` is true. + pub expires: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AutoType { + pub default_sequence: String, + /// The `Window` of each association, in order. + pub windows: Vec, +} + +/// What opens a KDBX file: a password, a key file, or both. +#[derive(Clone, Copy, Default)] +pub struct Key<'a> { + /// An empty password counts as no password (as in KeePassXC). + pub password: Option<&'a SecretString>, + /// The key file's whole content. + pub key_file: Option<&'a [u8]>, +} + +impl std::fmt::Debug for Key<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Key") + .field("password", &self.password.is_some()) + .field("key_file", &self.key_file.is_some()) + .finish() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + #[error("this is not a KeePass database")] + NotKdbx, + #[error("unsupported KDBX version {0}.{1}")] + UnsupportedVersion(u16, u16), + #[error("a password or a key file is needed")] + NoKey, + #[error("wrong password or key file")] + WrongKey, + #[error("the file is damaged")] + Corrupted, + #[error("unsupported cipher: only AES-256 and ChaCha20 are supported")] + UnsupportedCipher, + #[error("unsupported key derivation settings")] + UnsupportedKdf, + #[error("unsupported inner stream: only ChaCha20 and Salsa20 are supported")] + UnsupportedStream, + #[error("the file is too large")] + TooLarge, + #[error("malformed KDBX file: {0}")] + Malformed(&'static str), +} diff --git a/crates/custos-kdbx/src/map.rs b/crates/custos-kdbx/src/map.rs new file mode 100644 index 0000000..a1da5f9 --- /dev/null +++ b/crates/custos-kdbx/src/map.rs @@ -0,0 +1,410 @@ +//! KeePass entries ↔ Custos items (docs/KDBX.md, "Mapping"). + +use crate::{AutoType, Database, Entry, Group, StringField, Times, crypto, time}; +use custos_vault::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, SecretString}; + +const TYPE_KEY: &str = "custos-type"; +const URL_EXTRA: &str = "KP2A_URL"; + +fn kind_name(k: ItemType) -> &'static str { + match k { + ItemType::WebLogin => "web-login", + ItemType::ApiCredential => "api-credential", + ItemType::LocalApp => "local-app", + ItemType::Wifi => "wifi", + ItemType::SecureNote => "secure-note", + ItemType::Card => "card", + ItemType::KeyPair => "key-pair", + } +} + +/// The Custos field KeePass's `UserName` stands for. +fn user_field(k: ItemType) -> &'static str { + match k { + ItemType::Wifi => "ssid", + ItemType::Card => "cardholder", + _ => "username", + } +} + +/// The Custos field KeePass's `Password` stands for. +fn pass_field(k: ItemType) -> &'static str { + match k { + ItemType::ApiCredential => "secret", + ItemType::Card => "number", + _ => "password", + } +} + +fn in_template(k: ItemType, name: &str) -> Option { + k.template().iter().find(|(n, _)| *n == name).map(|&(_, s)| s) +} + +/// A file from elsewhere has no `custos-type`: no user name, password or URL makes it a note. +fn guess(e: &Entry) -> ItemType { + let has = |k| e.get(k).is_some_and(|v| !v.is_empty()); + if has("UserName") || has("Password") || has("URL") { ItemType::WebLogin } else { ItemType::SecureNote } +} + +/// `KP2A_URL` or `KP2A_URL_`: KeePassXC's extra URLs. Its number, `KP2A_URL` itself being 0. +fn extra_url(key: &str) -> Option { + let rest = key.strip_prefix(URL_EXTRA)?; + if rest.is_empty() { + return Some(0); + } + rest.strip_prefix('_').filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))?.parse().ok() +} + +fn hex(b: &[u8; 16]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +fn ms(secs: i64) -> i64 { + secs.saturating_mul(1000) +} + +// ---- KeePass → Custos ---- + +/// Every entry outside the recycle bin, as a Custos item. The root group is not part of `folder`. +pub fn to_items(db: &Database) -> Vec { + let mut out = Vec::new(); + collect(&db.root, &mut Vec::new(), db.recycle_bin, &mut out); + out +} + +fn collect(g: &Group, path: &mut Vec, bin: Option<[u8; 16]>, out: &mut Vec) { + for e in &g.entries { + out.push(entry_to_item(e, path)); + } + for sub in &g.groups { + if Some(sub.uuid) == bin { + continue; + } + path.push(sub.name.clone()); + collect(sub, path, bin, out); + path.pop(); + } +} + +/// One mapped value: the Custos field name, the value, and whether KeePass protected it. +struct Mapped { + name: String, + value: SecretString, + protected: bool, + /// From `UserName`, `Password` or `URL`: an empty one is only a template slot, never a field of its own. + standard: bool, +} + +/// An entry's strings as Custos fields, in file order (extra URLs in their numeric order). +fn mapped(e: &Entry, kind: ItemType) -> Vec { + let mut out = Vec::new(); + let mut extra_urls: Vec<(u32, &StringField)> = Vec::new(); + let mut urls_at = None; + let mut primary_url = None; + let totp_seed = e.get("TOTP Seed").filter(|_| e.get("otp").is_none()); + for s in &e.strings { + let m = + |name: &str, protected, standard| Mapped { name: name.into(), value: s.value.clone(), protected, standard }; + match s.key.as_str() { + "Title" | "Notes" | TYPE_KEY | "TOTP Settings" => {} + "UserName" => out.push(m(user_field(kind), false, true)), + "Password" => out.push(m(pass_field(kind), true, true)), + "URL" => { + urls_at.get_or_insert(out.len()); + primary_url = Some(m("url", false, true)); + } + "otp" => out.push(m("totp", true, false)), + "TOTP Seed" if totp_seed.is_some() => out.push(Mapped { + name: "totp".into(), + value: totp_uri(e, s.value.expose()), + protected: true, + standard: false, + }), + k if let Some(n) = extra_url(k) => { + urls_at.get_or_insert(out.len()); + extra_urls.push((n, s)); + } + k => out.push(m(k, s.protected, false)), + } + } + extra_urls.sort_by_key(|(n, _)| *n); + let urls = extra_urls.into_iter().map(|(_, s)| Mapped { + name: "url".into(), + value: s.value.clone(), + protected: false, + standard: false, + }); + // `URL` first, then the extra ones in their numeric order, wherever the first of them was in the file + // (KeePassXC sorts keys, so `KP2A_URL` comes before `URL` there). + let at = urls_at.unwrap_or(out.len()); + out.splice(at..at, primary_url.into_iter().chain(urls)); + out +} + +/// KeePass 2's `TOTP Seed` (base32) with `TOTP Settings` ("period;digits"), as Custos keeps it: the bare +/// seed for 30 s / 6 digits, otherwise an otpauth:// URI. +fn totp_uri(e: &Entry, seed: &str) -> SecretString { + let settings = e.get("TOTP Settings").map(|s| s.expose().to_owned()).unwrap_or_default(); + let mut parts = settings.split(';'); + let period = parts.next().and_then(|p| p.trim().parse::().ok()).unwrap_or(30); + let digits = parts.next().and_then(|d| d.trim().parse::().ok()).unwrap_or(6); + let seed: String = seed.chars().filter(|c| !c.is_whitespace()).collect(); + if period == 30 && digits == 6 { + return SecretString::new(seed); + } + let label: String = e + .get("Title") + .map(|t| t.expose()) + .unwrap_or("") + .bytes() + .map(|b| if b.is_ascii_alphanumeric() { (b as char).to_string() } else { format!("%{b:02X}") }) + .collect(); + SecretString::new(format!("otpauth://totp/{label}?secret={seed}&period={period}&digits={digits}")) +} + +/// Puts a value into the first unfilled template slot with that name, or appends it as a field. +fn put(item: &mut Item, filled: &mut Vec, name: &str, value: SecretString, secret: bool, standard: bool) { + let template = in_template(item.kind, name); + if let Some(i) = item.fields.iter().enumerate().position(|(i, f)| f.name == name && !filled[i]) { + item.fields[i].value = value; + item.fields[i].secret |= secret; + filled[i] = true; + } else if !(standard && value.is_empty()) { + item.fields.push(Field { name: name.into(), value, secret: secret || template == Some(true) }); + filled.push(true); + } +} + +fn entry_to_item(e: &Entry, folder: &[String]) -> Item { + let kind = e + .get(TYPE_KEY) + .and_then(|t| ItemType::ALL.into_iter().find(|k| kind_name(*k) == t.expose())) + .unwrap_or_else(|| guess(e)); + let title = e.get("Title").map(|t| t.expose()).unwrap_or(""); + let mut item = Item::new(kind, title, ms(e.times.created)); + item.id = hex(&e.uuid); + item.modified = ms(e.times.modified); + item.notes = e.get("Notes").cloned().unwrap_or_default(); + item.tags = e.tags.clone(); + item.folder = folder.to_vec(); + item.attachments = e.attachments.clone(); + let mut filled = vec![false; item.fields.len()]; + for m in mapped(e, kind) { + put(&mut item, &mut filled, &m.name, m.value, m.protected, m.standard); + } + if let Some(x) = e.times.expires { + put(&mut item, &mut filled, "expires", SecretString::new(time::format_iso(x)), false, false); + } + if !e.autotype.default_sequence.is_empty() { + put(&mut item, &mut filled, "autotype-sequence", e.autotype.default_sequence.as_str().into(), false, false); + } + for w in &e.autotype.windows { + put(&mut item, &mut filled, "autotype-match", w.as_str().into(), false, false); + } + item.history = history(e, kind); + item +} + +/// For every snapshot, each secret field whose value differs in the next version (docs/KDBX.md). +fn history(e: &Entry, kind: ItemType) -> Vec { + let secrets = |v: &Entry| -> Vec<(String, SecretString)> { + let mut seen: Vec<(String, SecretString)> = Vec::new(); + for m in mapped(v, kind) { + let secret = m.protected || in_template(kind, &m.name) == Some(true); + if secret && !seen.iter().any(|(n, _)| *n == m.name) { + seen.push((m.name, m.value)); + } + } + seen + }; + let mut out = Vec::new(); + let versions: Vec<&Entry> = e.history.iter().chain(std::iter::once(e)).collect(); + for pair in versions.windows(2) { + let next = secrets(pair[1]); + for (name, old) in secrets(pair[0]) { + let now = next.iter().find(|(n, _)| *n == name).map(|(_, v)| v.expose()).unwrap_or(""); + if !old.is_empty() && old.expose() != now { + out.push(HistoryEntry { field: name, value: old, changed: ms(pair[0].times.modified) }); + } + } + } + let excess = out.len().saturating_sub(HISTORY_LIMIT); + out.drain(..excess); + out +} + +// ---- Custos → KeePass ---- + +/// A database with one group per folder under a root group called `name`. Factors and the Domi identity +/// are not items, so they never get here. +pub fn from_items(items: &[Item], name: &str) -> Database { + let mut root = Group { uuid: random_uuid(), name: name.into(), ..Default::default() }; + for item in items { + let mut g = &mut root; + for part in &item.folder { + let i = match g.groups.iter().position(|s| s.name == *part) { + Some(i) => i, + None => { + g.groups.push(Group { uuid: random_uuid(), name: part.clone(), ..Default::default() }); + g.groups.len() - 1 + } + }; + g = &mut g.groups[i]; + } + g.entries.push(item_to_entry(item)); + } + Database { name: name.into(), root, recycle_bin: None } +} + +fn random_uuid() -> [u8; 16] { + let mut u = [0u8; 16]; + crypto::fill_random(&mut u); + u +} + +/// The KeePass key a Custos field goes to, given which standard slots are already taken. +fn key_for(kind: ItemType, name: &str, used: &[String], urls: &mut u32) -> String { + let standard = match name { + n if n == user_field(kind) => Some("UserName"), + n if n == pass_field(kind) => Some("Password"), + "url" => Some("URL"), + "totp" => Some("otp"), + _ => None, + }; + if let Some(k) = standard.filter(|k| !used.iter().any(|u| u == k)) { + return k.into(); + } + if name == "url" { + let k = if *urls == 0 { URL_EXTRA.to_owned() } else { format!("{URL_EXTRA}_{urls}") }; + *urls += 1; + return k; + } + // Never collide with a key KeePass gives a meaning to, or with one already written. + let reserved = |k: &str| { + ["Title", "UserName", "Password", "URL", "Notes", "otp", TYPE_KEY, "TOTP Seed", "TOTP Settings"].contains(&k) + || extra_url(k).is_some() + || used.iter().any(|u| u == k) + }; + let mut k = name.to_owned(); + let mut n = 2; + while reserved(&k) { + k = format!("{name} ({n})"); + n += 1; + } + k +} + +fn item_to_entry(item: &Item) -> Entry { + let kind = item.kind; + let uuid = data_encoding::HEXLOWER_PERMISSIVE + .decode(item.id.as_bytes()) + .ok() + .and_then(|b| <[u8; 16]>::try_from(b).ok()) + .unwrap_or_else(random_uuid); + let mut e = Entry { + uuid, + tags: item.tags.clone(), + attachments: item.attachments.clone(), + times: Times { + created: item.created.div_euclid(1000), + modified: item.modified.div_euclid(1000), + expires: None, + }, + ..Default::default() + }; + let first = |name: &str| item.field(name).map(|f| f.value.clone()).unwrap_or_default(); + e.strings = vec![ + StringField { key: "Title".into(), value: item.title.as_str().into(), protected: false }, + StringField { key: "UserName".into(), value: first(user_field(kind)), protected: false }, + StringField { key: "Password".into(), value: first(pass_field(kind)), protected: true }, + StringField { key: "URL".into(), value: first("url"), protected: false }, + StringField { key: "Notes".into(), value: item.notes.clone(), protected: false }, + ]; + let mut used: Vec = e.strings.iter().map(|s| s.key.clone()).collect(); + let (mut seen_user, mut seen_pass, mut seen_url) = (false, false, false); + let (mut seen_seq, mut seen_exp) = (false, false); + let mut urls = 0; + for f in &item.fields { + let first_of = |seen: &mut bool| !std::mem::replace(seen, true); + if f.name == user_field(kind) && first_of(&mut seen_user) + || f.name == pass_field(kind) && first_of(&mut seen_pass) + || f.name == "url" && first_of(&mut seen_url) + { + continue; // already in a standard string + } + if f.name == "autotype-sequence" && first_of(&mut seen_seq) { + e.autotype.default_sequence = f.value.expose().to_owned(); + continue; + } + if f.name == "autotype-match" { + if !f.value.is_empty() { + e.autotype.windows.push(f.value.expose().to_owned()); + } + continue; + } + if f.name == "expires" + && !seen_exp + && let Some(x) = time::parse_iso(f.value.expose()) + { + seen_exp = true; + e.times.expires = Some(x); + continue; + } + if f.value.is_empty() && in_template(kind, &f.name).is_some() { + continue; + } + let key = key_for(kind, &f.name, &used, &mut urls); + let protected = f.secret || key == "otp"; + used.push(key.clone()); + e.strings.push(StringField { key, value: f.value.clone(), protected }); + } + if guess(&e) != kind { + e.strings.push(StringField { key: TYPE_KEY.into(), value: kind_name(kind).into(), protected: false }); + } + e.history = snapshots(item, &e); + e +} + +/// KeePass snapshots from Custos's per-field history: one per distinct change time, each with the values +/// as they were just before that change. +fn snapshots(item: &Item, current: &Entry) -> Vec { + let mut hist: Vec<&HistoryEntry> = item.history.iter().collect(); + hist.sort_by_key(|h| h.changed); + let mut times: Vec = hist.iter().map(|h| h.changed).collect(); + times.dedup(); + // A field's key in the current entry: the standard ones, otherwise its own name. + let key_of = |field: &str| -> String { + match field { + n if n == user_field(item.kind) => "UserName".into(), + n if n == pass_field(item.kind) => "Password".into(), + "totp" => "otp".into(), + n => n.to_owned(), + } + }; + times + .iter() + .map(|&t| { + let mut s = Entry { + uuid: current.uuid, + strings: current.strings.clone(), + tags: current.tags.clone(), + times: Times { modified: t.div_euclid(1000), ..current.times }, + autotype: AutoType::default(), + ..Default::default() + }; + let mut done: Vec<&str> = Vec::new(); + for h in hist.iter().filter(|h| h.changed >= t) { + if done.contains(&h.field.as_str()) { + continue; + } + done.push(&h.field); + let key = key_of(&h.field); + match s.strings.iter_mut().find(|x| x.key == key) { + Some(x) => x.value = h.value.clone(), + None => s.strings.push(StringField { key, value: h.value.clone(), protected: true }), + } + } + s + }) + .collect() +} diff --git a/crates/custos-kdbx/src/time.rs b/crates/custos-kdbx/src/time.rs new file mode 100644 index 0000000..0511885 --- /dev/null +++ b/crates/custos-kdbx/src/time.rs @@ -0,0 +1,111 @@ +//! KDBX times: base64 of an i64 LE count of seconds since 0001-01-01 (KDBX 4), or ISO 8601 (KeePass XML). + +/// Seconds from 0001-01-01T00:00:00Z to the Unix epoch. +const EPOCH_OFFSET: i64 = 62_135_596_800; + +pub(crate) fn from_kdbx(text: &str) -> Option { + let t = text.trim(); + if let Ok(b) = data_encoding::BASE64.decode(t.as_bytes()) + && let Ok(b) = <[u8; 8]>::try_from(b.as_slice()) + { + return i64::from_le_bytes(b).checked_sub(EPOCH_OFFSET); + } + parse_iso(t) +} + +pub(crate) fn to_kdbx(unix: i64) -> String { + data_encoding::BASE64.encode(&unix.saturating_add(EPOCH_OFFSET).to_le_bytes()) +} + +/// `YYYY-MM-DD` (midnight UTC) or `YYYY-MM-DDTHH:MM:SS` with an optional `Z` → Unix seconds. +pub fn parse_iso(s: &str) -> Option { + let s = s.trim(); + let s = s.strip_suffix('Z').unwrap_or(s); + let (date, time) = match s.split_once('T') { + Some((d, t)) => (d, Some(t)), + None => (s, None), + }; + let mut d = date.splitn(3, '-'); + let y: i64 = num(d.next()?, 4)?; + let m: u32 = num(d.next()?, 2)? as u32; + let day: u32 = num(d.next()?, 2)? as u32; + if !(1..=12).contains(&m) || day == 0 || day > days_in_month(y, m) { + return None; + } + let mut secs = 0; + if let Some(t) = time { + let mut p = t.splitn(3, ':'); + let (h, mi, se) = (num(p.next()?, 2)?, num(p.next()?, 2)?, num(p.next()?, 2)?); + if h > 23 || mi > 59 || se > 59 { + return None; + } + secs = h * 3600 + mi * 60 + se; + } + Some(days_from_civil(y, m, day) * 86_400 + secs) +} + +/// Unix seconds → `YYYY-MM-DD` when it is midnight UTC, otherwise `YYYY-MM-DDTHH:MM:SSZ`. +pub fn format_iso(unix: i64) -> String { + let (days, secs) = (unix.div_euclid(86_400), unix.rem_euclid(86_400)); + let (y, m, d) = civil_from_days(days); + if secs == 0 { + format!("{y:04}-{m:02}-{d:02}") + } else { + format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", secs / 3600, secs / 60 % 60, secs % 60) + } +} + +fn num(s: &str, len: usize) -> Option { + (s.len() == len && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten() +} + +fn days_in_month(y: i64, m: u32) -> u32 { + match m { + 2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + } +} + +// Howard Hinnant's civil-date algorithms. +fn days_from_civil(y: i64, m: u32, d: u32) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (i64::from(m) + 9) % 12; + let doy = (153 * mp + 2) / 5 + i64::from(d) - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (yoe + era * 400 + i64::from(m <= 2), m, d) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_round_trips_and_refuses_nonsense() { + assert_eq!(parse_iso("1970-01-01"), Some(0)); + assert_eq!(parse_iso("2026-11-03T19:26:49Z"), Some(1_793_734_009)); + assert_eq!(format_iso(1_793_734_009), "2026-11-03T19:26:49Z"); + assert_eq!(format_iso(parse_iso("2024-02-29").unwrap()), "2024-02-29"); + assert_eq!(format_iso(parse_iso("0001-01-01").unwrap()), "0001-01-01"); + for bad in ["", "2023-02-29", "2026-13-01", "26-01-01", "2026-01-01T24:00:00Z", "next year", "2026-1-1"] { + assert_eq!(parse_iso(bad), None, "{bad}"); + } + assert_eq!(from_kdbx(&to_kdbx(1_793_734_009)), Some(1_793_734_009)); + assert_eq!(from_kdbx("2026-11-03T19:26:49Z"), Some(1_793_734_009)); + } +} diff --git a/crates/custos-kdbx/src/xml.rs b/crates/custos-kdbx/src/xml.rs new file mode 100644 index 0000000..12cbe17 --- /dev/null +++ b/crates/custos-kdbx/src/xml.rs @@ -0,0 +1,348 @@ +//! The inner XML: parsed with roxmltree (no DTD, so no entity tricks), written by hand. + +use crate::crypto::InnerStream; +use crate::{AutoType, Database, Entry, Error, Group, StringField, Times, time}; +use custos_vault::{Attachment, SecretBytes, SecretString}; +use roxmltree::{Node, NodeId}; +use std::collections::HashMap; +use std::fmt::Write as _; +use zeroize::Zeroizing; + +const MAX_DEPTH: usize = 256; + +pub(crate) fn parse(xml: &[u8], stream: &mut InnerStream, pool: &[SecretBytes]) -> Result { + let xml = xml.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(xml); + let body = std::str::from_utf8(xml).map_err(|_| Error::Malformed("XML is not UTF-8"))?; + let doc = roxmltree::Document::parse_with_options( + body, + roxmltree::ParsingOptions { allow_dtd: false, ..Default::default() }, + ) + .map_err(|e| match e { + roxmltree::Error::DtdDetected => Error::Malformed("XML with a DOCTYPE"), + _ => Error::Malformed("XML"), + })?; + + // Protected values, unmasked in document order: every one consumes the stream, used or not. + let mut protected: HashMap>> = HashMap::new(); + for n in doc.descendants().filter(|n| n.is_element()) { + if n.attribute("Protected").is_some_and(|v| v.eq_ignore_ascii_case("true")) { + let mut bytes = Zeroizing::new( + data_encoding::BASE64.decode(n_text(n).as_bytes()).map_err(|_| Error::Malformed("protected value"))?, + ); + stream.apply(&mut bytes); + protected.insert(n.id(), bytes); + } + } + + let root = doc.root_element(); + if !root.has_tag_name("KeePassFile") { + return Err(Error::Malformed("not a KeePass XML document")); + } + let meta = child(root, "Meta"); + let name = meta.and_then(|m| child(m, "DatabaseName")).map(text).unwrap_or_default(); + let recycle_bin = meta + .filter(|m| child(*m, "RecycleBinEnabled").is_some_and(|n| text(n).eq_ignore_ascii_case("true"))) + .and_then(|m| child(m, "RecycleBinUUID")) + .and_then(|n| uuid(n).ok()) + .filter(|u| *u != [0; 16]); + let group = child(root, "Root").and_then(|r| child(r, "Group")).ok_or(Error::Malformed("no root group"))?; + + // Attachments: KDBX 4 keeps them in the inner header (by index), KDBX 3.1 in Meta/Binaries (by ID). + let mut binaries: HashMap = + pool.iter().enumerate().map(|(i, b)| (i.to_string(), b.clone())).collect(); + for b in meta.and_then(|m| child(m, "Binaries")).into_iter().flat_map(|bs| bs.children()) { + if !b.has_tag_name("Binary") { + continue; + } + let id = b.attribute("ID").ok_or(Error::Malformed("attachment"))?.to_owned(); + let raw = match protected.get(&b.id()) { + Some(bytes) => bytes.clone(), + None => Zeroizing::new( + data_encoding::BASE64.decode(n_text(b).as_bytes()).map_err(|_| Error::Malformed("attachment"))?, + ), + }; + let data = if b.attribute("Compressed").is_some_and(|v| v.eq_ignore_ascii_case("true")) { + crate::format::gunzip(&raw)? + } else { + raw + }; + binaries.insert(id, SecretBytes::new(data.to_vec())); + } + let ctx = Ctx { protected: &protected, binaries: &binaries }; + Ok(Database { name, root: ctx.group(group, 0)?, recycle_bin }) +} + +struct Ctx<'a> { + protected: &'a HashMap>>, + binaries: &'a HashMap, +} + +impl Ctx<'_> { + fn group(&self, n: Node, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(Error::Malformed("groups nested too deeply")); + } + let mut g = Group { + uuid: child(n, "UUID").map(uuid).transpose()?.unwrap_or_default(), + name: child(n, "Name").map(text).unwrap_or_default(), + ..Default::default() + }; + for c in n.children().filter(|c| c.is_element()) { + match c.tag_name().name() { + "Entry" => g.entries.push(self.entry(c, true)?), + "Group" => g.groups.push(self.group(c, depth + 1)?), + _ => {} + } + } + Ok(g) + } + + fn entry(&self, n: Node, with_history: bool) -> Result { + let mut e = Entry { uuid: child(n, "UUID").map(uuid).transpose()?.unwrap_or_default(), ..Default::default() }; + for c in n.children().filter(|c| c.is_element()) { + match c.tag_name().name() { + "Tags" => { + e.tags = + text(c).split([';', ',']).map(str::trim).filter(|t| !t.is_empty()).map(Into::into).collect() + } + "Times" => e.times = times(c), + "String" => { + let key = child(c, "Key").map(text).unwrap_or_default(); + let v = child(c, "Value"); + let (value, protected) = match v.and_then(|v| self.protected.get(&v.id())) { + Some(b) => { + let s = String::from_utf8(b.to_vec()).map_err(|_| Error::Malformed("protected value"))?; + (SecretString::new(s), true) + } + None => (SecretString::new(v.map(text).unwrap_or_default()), false), + }; + if !e.strings.iter().any(|s| s.key == key) { + e.strings.push(StringField { key, value, protected }); + } + } + "Binary" => { + let name = child(c, "Key").map(text).unwrap_or_default(); + let r = child(c, "Value").and_then(|v| v.attribute("Ref")).ok_or(Error::Malformed("attachment"))?; + let data = self.binaries.get(r).ok_or(Error::Malformed("attachment"))?; + e.attachments.push(Attachment { name, data: data.clone() }); + } + "AutoType" => { + e.autotype = AutoType { + default_sequence: child(c, "DefaultSequence").map(text).unwrap_or_default(), + windows: c + .children() + .filter(|a| a.has_tag_name("Association")) + .map(|a| child(a, "Window").map(text).unwrap_or_default()) + .collect(), + } + } + "History" if with_history => { + for h in c.children().filter(|h| h.has_tag_name("Entry")) { + e.history.push(self.entry(h, false)?); + } + } + _ => {} + } + } + Ok(e) + } +} + +fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option> { + n.children().find(|c| c.has_tag_name(name)) +} + +/// Base64 text without its whitespace. +fn n_text(n: Node) -> Zeroizing { + Zeroizing::new(n.text().unwrap_or("").split_whitespace().collect()) +} + +fn text(n: Node) -> String { + n.text().unwrap_or("").to_owned() +} + +fn uuid(n: Node) -> Result<[u8; 16], Error> { + let t = n.text().unwrap_or("").trim(); + data_encoding::BASE64.decode(t.as_bytes()).ok().and_then(|b| b.try_into().ok()).ok_or(Error::Malformed("UUID")) +} + +fn times(n: Node) -> Times { + let get = |name| child(n, name).and_then(|c| time::from_kdbx(c.text().unwrap_or(""))); + let expires = child(n, "Expires").is_some_and(|c| text(c).trim().eq_ignore_ascii_case("true")); + Times { + created: get("CreationTime").unwrap_or(0), + modified: get("LastModificationTime").unwrap_or(0), + expires: if expires { get("ExpiryTime") } else { None }, + } +} + +/// The XML, protected values masked with `stream` in document order; attachments go to `pool` in the +/// order their `Ref`s are written. +pub(crate) fn write<'d>( + db: &'d Database, + stream: &mut InnerStream, + pool: &mut Vec<&'d SecretBytes>, +) -> Zeroizing { + let mut w = W { out: Zeroizing::new(String::new()), stream, pool }; + w.raw("\n\n\t\n"); + w.el(2, "Generator", "Custos"); + w.el(2, "DatabaseName", &db.name); + w.raw("\t\t\n"); + for (k, v) in [("ProtectTitle", "False"), ("ProtectUserName", "False"), ("ProtectPassword", "True")] { + w.el(3, k, v); + } + for (k, v) in [("ProtectURL", "False"), ("ProtectNotes", "False")] { + w.el(3, k, v); + } + w.raw("\t\t\n"); + w.el(2, "RecycleBinEnabled", "False"); + w.el(2, "HistoryMaxItems", "20"); + w.el(2, "HistoryMaxSize", "6291456"); + w.raw("\t\n\t\n"); + w.group(&db.root, 2); + w.raw("\t\t\n\t\n\n"); + w.out +} + +struct W<'s, 'd> { + out: Zeroizing, + stream: &'s mut InnerStream, + pool: &'s mut Vec<&'d SecretBytes>, +} + +impl<'d> W<'_, 'd> { + fn raw(&mut self, s: &str) { + self.out.push_str(s); + } + + fn indent(&mut self, n: usize) { + for _ in 0..n { + self.out.push('\t'); + } + } + + fn el(&mut self, depth: usize, name: &str, value: &str) { + self.indent(depth); + if value.is_empty() { + let _ = writeln!(self.out, "<{name}/>"); + } else { + let _ = write!(self.out, "<{name}>"); + escape(&mut self.out, value); + let _ = writeln!(self.out, ""); + } + } + + fn times(&mut self, d: usize, t: &Times) { + self.indent(d); + self.raw("\n"); + let m = time::to_kdbx(t.modified); + self.el(d + 1, "LastModificationTime", &m); + self.el(d + 1, "CreationTime", &time::to_kdbx(t.created)); + self.el(d + 1, "LastAccessTime", &m); + self.el(d + 1, "ExpiryTime", &time::to_kdbx(t.expires.unwrap_or(t.modified))); + self.el(d + 1, "Expires", if t.expires.is_some() { "True" } else { "False" }); + self.el(d + 1, "UsageCount", "0"); + self.el(d + 1, "LocationChanged", &m); + self.indent(d); + self.raw("\n"); + } + + fn group(&mut self, g: &'d Group, d: usize) { + self.indent(d); + self.raw("\n"); + self.el(d + 1, "UUID", &data_encoding::BASE64.encode(&g.uuid)); + self.el(d + 1, "Name", &g.name); + self.el(d + 1, "IconID", "48"); + self.el(d + 1, "IsExpanded", "True"); + for e in &g.entries { + self.entry(e, d + 1, true); + } + for sub in &g.groups { + self.group(sub, d + 1); + } + self.indent(d); + self.raw("\n"); + } + + fn entry(&mut self, e: &'d Entry, d: usize, with_history: bool) { + self.indent(d); + self.raw("\n"); + self.el(d + 1, "UUID", &data_encoding::BASE64.encode(&e.uuid)); + self.el(d + 1, "IconID", "0"); + self.el(d + 1, "Tags", &e.tags.join(";")); + self.times(d + 1, &e.times); + for s in &e.strings { + self.indent(d + 1); + self.raw("\n"); + self.el(d + 2, "Key", &s.key); + self.indent(d + 2); + if s.protected { + let mut b = Zeroizing::new(s.value.expose().as_bytes().to_vec()); + self.stream.apply(&mut b); + let _ = writeln!(self.out, "{}", data_encoding::BASE64.encode(&b)); + } else if s.value.is_empty() { + self.raw("\n"); + } else { + self.raw(""); + escape(&mut self.out, s.value.expose()); + self.raw("\n"); + } + self.indent(d + 1); + self.raw("\n"); + } + for a in &e.attachments { + let r = self.pool.len(); + self.pool.push(&a.data); + self.indent(d + 1); + self.raw("\n"); + self.el(d + 2, "Key", &a.name); + self.indent(d + 2); + let _ = writeln!(self.out, ""); + self.indent(d + 1); + self.raw("\n"); + } + self.indent(d + 1); + self.raw("\n"); + self.el(d + 2, "Enabled", "True"); + self.el(d + 2, "DataTransferObfuscation", "0"); + self.el(d + 2, "DefaultSequence", &e.autotype.default_sequence); + for win in &e.autotype.windows { + self.indent(d + 2); + self.raw("\n"); + self.el(d + 3, "Window", win); + self.el(d + 3, "KeystrokeSequence", ""); + self.indent(d + 2); + self.raw("\n"); + } + self.indent(d + 1); + self.raw("\n"); + if with_history && !e.history.is_empty() { + self.indent(d + 1); + self.raw("\n"); + for h in &e.history { + self.entry(h, d + 2, false); + } + self.indent(d + 1); + self.raw("\n"); + } + self.indent(d); + self.raw("\n"); + } +} + +/// XML text escaping. `\r` is written as a character reference so a parser's line-end normalization keeps +/// it; characters XML 1.0 cannot carry at all (other C0 controls) are dropped. +fn escape(out: &mut String, s: &str) { + for ch in s.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\r' => out.push_str(" "), + '\t' | '\n' => out.push(ch), + c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {} + c => out.push(c), + } + } +} diff --git a/crates/custos-kdbx/tests/data/keepassxc_files.rs b/crates/custos-kdbx/tests/data/keepassxc_files.rs new file mode 100644 index 0000000..03a0528 --- /dev/null +++ b/crates/custos-kdbx/tests/data/keepassxc_files.rs @@ -0,0 +1,97 @@ +// Files written by KeePassXC 2.7.12 (keepassxc-cli), from tools/kdbx/sample.xml, password "custos-test": +// V3 by `import` (KDBX 3.1, AES-KDF, AES-256, a recycle bin), V4 by `merge` of V3 into an empty KDBX 4 +// file Custos wrote (KDBX 4.0, Argon2id 1 MiB, ChaCha20; KeePassXC keeps a file's format when it saves). +// These are test vectors: the first two steps of tools/kdbx/interop.sh make new ones +// (scratch script: base64 of each file, 100 characters per line). + +const V3: &str = " +A9mimmf7S7UBAAMAAhAAMcHy5r9xQ1C+WAUhavxa/wMEAAEAAAAEIABxP6+yGbKtLFUqLZSBYUCDYrbP08dc4XTSSqHBRDGfewUg +AFDZzHIfvtxlCIOFQuMhnUD+NylHzyQm9bamu47pm/UrBggAgmVhAAAAAAAHEAA6M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4muuj +7UaKV6sxHsPdWU5IMe9qGi5qSWp0Q21KLZ89DBWT56vwkySR0QjZTTbb/wmUYT57S9MCrmhF/ncbJM7A14xrjl0y/0K65N7Y8UgD +7Fol550Yl+rhTYWM/egpIJr9wmz6FHuHw86DZv/RHJyKPgfIPlZvy+Z3eaSwGz8jeTa+NaSY9+v0TpVTHDBTyeZ17t8L0cW0RU0v +Olwh939wYrYVE6SzQFv85nllEmRN0J/O3lzm/LaCydqzEpezAg1Xxd3VxXEMZAgc3B14O4rzDTigTHdi1/6yk3lQnxYVOCaFgEbC +n3SWMHJMnT31P/sWIOs/Cn57A2IZ4i1JsqoGORyo8NXSOcRrOusTTewH9MJiRkEelYlRrEV1xWl1ZGt1jcjbkkOdunvio3JM/xpe +C/aBgU7zc28doM9AdKq51ZEYx3JU3VqKE/+quCgeEmz5vE7OSya7jSE+v0jTD7JOKTs/hwJWslKCr93R/mspG38Pv5Lq/ksNRLwz +m9fIgtGblTCK/O/oz6iSSNvhJL54Uu+8C9X2k+rUcHDGi7SkqRdrpmdudgfGHQuOwLOA7lQlh1yKuDy5pEeVmyrgUFqehpa37vDS +CswLKbmv3UA3Op95mptfwdj6b+Jqy4/V9bSW9KbBgAmYhFoQM29QLbL+c3bCjPmPxxe9ff/on/KPR5tHRBeeIlywWbZh+CMWoYkt +NqnfihsZJgT0EECsY7tPNPK5BphIPstuKTjxPPDXG5XhVpF7NLC2/yhvMmOu1X0Hzp4jKf3C8zvlZOPK5UBIbfB7EQOzMZdqtHzq +BHdA9FSFNSUm2fVRCA1YDtUAOqF6AF/j0btxILsn/C5jANRGZPcVWzoowmd6//xYMHCqJqW8Df2yAAAAAA== +"; diff --git a/crates/custos-kdbx/tests/format.rs b/crates/custos-kdbx/tests/format.rs new file mode 100644 index 0000000..04a675e --- /dev/null +++ b/crates/custos-kdbx/tests/format.rs @@ -0,0 +1,353 @@ +//! 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"); +} diff --git a/crates/custos-kdbx/tests/keepassxc.rs b/crates/custos-kdbx/tests/keepassxc.rs new file mode 100644 index 0000000..5dcfdd4 --- /dev/null +++ b/crates/custos-kdbx/tests/keepassxc.rs @@ -0,0 +1,87 @@ +//! Files KeePassXC wrote open with what tools/kdbx/sample.xml put in them (docs/KDBX.md, "Tests"). + +use custos_kdbx::{Error, Key, SecretString, read, to_items}; +use custos_vault::{Item, ItemType}; + +include!("data/keepassxc_files.rs"); + +fn bytes(b64: &str) -> Vec { + let clean: String = b64.split_whitespace().collect(); + data_encoding::BASE64.decode(clean.as_bytes()).unwrap() +} + +fn open(b64: &str) -> custos_kdbx::Database { + let p = SecretString::from("custos-test"); + read(&bytes(b64), &Key { password: Some(&p), key_file: None }).unwrap() +} + +fn field<'a>(item: &'a Item, name: &str) -> Vec<&'a str> { + item.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect() +} + +fn check(items: &[Item]) { + let by = |title: &str| items.iter().find(|i| i.title == title).unwrap_or_else(|| panic!("no {title}")); + + let gh = by("GitHub"); + assert_eq!(gh.id, "11".repeat(16)); + assert_eq!(gh.kind, ItemType::WebLogin); + assert_eq!(gh.folder, ["Internet"]); + assert_eq!(field(gh, "username"), ["alice"]); + assert_eq!(field(gh, "password"), ["Hunter3-Current & "]); + assert_eq!(field(gh, "url"), ["https://github.com", "https://gist.github.com", "https://api.github.com"]); + assert!(field(gh, "totp")[0].starts_with("otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP")); + assert_eq!(field(gh, "Recovery codes"), ["Recovery-Secret-123"]); + assert!(gh.field("Recovery codes").unwrap().secret, "protected in KeePass, secret in Custos"); + assert_eq!(field(gh, "Account id"), ["42"]); + assert!(!gh.field("Account id").unwrap().secret); + assert_eq!(field(gh, "expires"), ["2030-01-01"]); + assert_eq!(field(gh, "autotype-sequence"), ["{USERNAME}{TAB}{PASSWORD}{ENTER}"]); + assert_eq!(field(gh, "autotype-match"), ["*GitHub*", "Firefox - GitHub"]); + assert_eq!(gh.notes.expose(), "Line one\nLine two & "); + assert_eq!(gh.tags, ["dev", "work"]); + assert_eq!(gh.created, 1_682_935_200_000); // 2023-05-01T10:00:00Z + assert_eq!(gh.modified, 1_769_938_200_000); // 2026-02-01T09:30:00Z + let history: Vec<(&str, i64)> = gh.history.iter().map(|h| (h.value.expose(), h.changed)).collect(); + assert_eq!(history, [("Hunter1-Oldest", 1_704_096_000_000), ("Hunter2-Old", 1_735_718_400_000)]); + assert!(gh.history.iter().all(|h| h.field == "password")); + assert_eq!(gh.attachments.len(), 1); + assert_eq!(gh.attachments[0].name, "codes.txt"); + assert_eq!(gh.attachments[0].data.expose(), b"Backup codes:\n1111-2222\n3333-4444\n"); + + let mail = by("Mail"); + assert_eq!(mail.folder, ["Internet", "Mail"]); + assert_eq!(field(mail, "totp"), ["otpauth://totp/Mail?secret=JBSWY3DPEHPK3PXP&period=60&digits=8"]); + + let note = by("Alarm code"); + assert_eq!(note.kind, ItemType::SecureNote, "no user name, password or URL"); + assert!(note.folder.is_empty()); + assert_eq!(note.notes.expose(), "Front door: 4711"); +} + +#[test] +fn keepassxc_kdbx_3_1_with_a_recycle_bin() { + let db = open(V3); + assert_eq!(db.name, "Custos interop"); + assert!(db.recycle_bin.is_some()); + let items = to_items(&db); + check(&items); + assert_eq!(items.len(), 3, "the recycle bin's entry is not imported"); + assert!(items.iter().all(|i| i.title != "Old account")); +} + +#[test] +fn keepassxc_kdbx_4() { + let db = open(V4); + let items = to_items(&db); + check(&items); + // This file's recycle bin is switched off, so the merged "Recycle Bin" is an ordinary group. + assert!(items.iter().any(|i| i.title == "Old account" && i.folder == ["Recycle Bin"])); +} + +#[test] +fn keepassxc_files_refuse_the_wrong_password() { + let wrong = SecretString::from("custos-test "); + for f in [V3, V4] { + assert_eq!(read(&bytes(f), &Key { password: Some(&wrong), key_file: None }), Err(Error::WrongKey)); + } +} diff --git a/crates/custos-kdbx/tests/mapping.rs b/crates/custos-kdbx/tests/mapping.rs new file mode 100644 index 0000000..4b00999 --- /dev/null +++ b/crates/custos-kdbx/tests/mapping.rs @@ -0,0 +1,262 @@ +//! Custos items ↔ KeePass entries (docs/KDBX.md, "Mapping"). + +use custos_kdbx::{ + AutoType, Cipher, Database, Entry, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times, WriteOptions, + from_items, read, to_items, write, +}; +use custos_vault::{Attachment, Field, Item, ItemType}; + +const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } }; +const T: i64 = 1_790_000_000_000; // whole seconds: KeePass keeps seconds + +fn through_a_file(items: &[Item]) -> Vec { + let p = SecretString::from("pw"); + let key = Key { password: Some(&p), key_file: None }; + let bytes = write(&from_items(items, "Custos"), &key, FAST).unwrap(); + to_items(&read(&bytes, &key).unwrap()) +} + +fn every_type() -> Vec { + let mut login = Item::new(ItemType::WebLogin, "GitHub", T); + login.set("username", "alice", T); + login.set("password", "First-Pass-1", T); + login.set("password", "Second-Pass-2", T + 1000); + login.set("password", "Current-Pass-3", T + 2000); + login.set("url", "https://github.com", T); + login.set("totp", "JBSWY3DPEHPK3PXP", T); + login.set("autotype-match", "*GitHub*", T); + login.set("autotype-sequence", "{USERNAME}{TAB}{PASSWORD}{ENTER}", T); + login.add_field(Field::text("url", "https://gist.github.com")); + login.add_field(Field::text("url", "https://api.github.com")); + login.add_field(Field::secret("Recovery code", "Recovery-1234")); + login.add_field(Field::text("Account", "")); + login.add_field(Field::text("expires", "2031-06-30T12:00:00Z")); + login.add_field(Field::text("autotype-match", "Firefox - GitHub")); + login.tags = vec!["dev".into(), "work".into()]; + login.notes = "line one\r\nline & \"three\"".into(); + login.folder = vec!["Internet".into(), "Code".into()]; + login.modified = T + 2000; + + let mut api = Item::new(ItemType::ApiCredential, "Stripe", T); + for (k, v) in + [("service", "Stripe"), ("key-id", "pk_live_1"), ("secret", "sk-Old"), ("endpoint", "https://api.stripe.com")] + { + api.set(k, v, T); + } + api.set("secret", "sk-New", T + 5000); + api.set("expires", "2027-01-31", T); + + let mut app = Item::new(ItemType::LocalApp, "Backup tool", T); + for (k, v) in [("target", "restic"), ("username", "backup"), ("password", "Restic-Pass")] { + app.set(k, v, T); + } + + let mut wifi = Item::new(ItemType::Wifi, "Home", T); + for (k, v) in [("ssid", "Domi"), ("password", "Wifi-Pass"), ("security", "WPA"), ("hidden", "false")] { + wifi.set(k, v, T); + } + + let mut note = Item::new(ItemType::SecureNote, "Keys", T); + note.notes = "the spare key is with the neighbours".into(); + note.attachments = + vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\xffkey bytes"[..]) }]; + note.folder = vec!["Home".into()]; + + let mut card = Item::new(ItemType::Card, "Visa", T); + for (k, v) in [ + ("cardholder", "A N Other"), + ("number", "4111111111111111"), + ("expiry", "12/29"), + ("cvv", "123"), + ("pin", "0000"), + ] { + card.set(k, v, T); + } + // Two secret fields changed at the same moment: one KeePass snapshot. + card.set("number", "4000000000000002", T + 9000); + card.set("cvv", "456", T + 9000); + + let mut pair = Item::new(ItemType::KeyPair, "Signing key", T); + for (k, v) in [ + ("algorithm", "ed25519"), + ("public-key", "ssh-ed25519 AAAA… me"), + ("private-key", "-----BEGIN PRIVATE KEY-----\nMC4…\n-----END PRIVATE KEY-----\n"), + ] { + pair.set(k, v, T); + } + + let empty: Vec = ItemType::ALL.into_iter().map(|k| Item::new(k, &format!("empty {k:?}"), T)).collect(); + [vec![login, api, app, wifi, note, card, pair], empty].concat() +} + +#[test] +fn every_item_type_survives_export_and_import() { + let items = every_type(); + let back = through_a_file(&items); + assert_eq!(back.len(), items.len()); + // Items come back folder by folder (root first), so match them by id. + for a in &items { + let b = back.iter().find(|b| b.id == a.id).unwrap_or_else(|| panic!("{} is missing", a.title)); + assert_eq!(a, b, "{}", a.title); + for (fa, fb) in a.fields.iter().zip(&b.fields) { + assert_eq!(fa.value, fb.value, "{} / {}", a.title, fa.name); + } + assert_eq!(a.notes, b.notes, "{}", a.title); + } +} + +#[test] +fn the_export_looks_like_keepass_to_keepassxc() { + let db = from_items(&every_type(), "Custos"); + let internet = db.root.groups.iter().find(|g| g.name == "Internet").unwrap(); + let gh = &internet.groups[0].entries[0]; + assert_eq!(internet.groups[0].name, "Code"); + let get = |e: &Entry, k: &str| e.get(k).map(|v| v.expose().to_owned()); + assert_eq!(get(gh, "UserName").as_deref(), Some("alice")); + assert_eq!(get(gh, "URL").as_deref(), Some("https://github.com")); + assert_eq!(get(gh, "KP2A_URL").as_deref(), Some("https://gist.github.com")); + assert_eq!(get(gh, "KP2A_URL_1").as_deref(), Some("https://api.github.com")); + assert_eq!(get(gh, "otp").as_deref(), Some("JBSWY3DPEHPK3PXP")); + assert!(gh.strings.iter().find(|s| s.key == "Password").unwrap().protected); + assert!(gh.strings.iter().find(|s| s.key == "Recovery code").unwrap().protected); + assert!(gh.get("custos-type").is_none(), "a login looks like a login without help"); + assert_eq!(gh.times.expires, custos_kdbx::parse_iso("2031-06-30T12:00:00Z")); + assert_eq!(gh.autotype.windows, ["*GitHub*", "Firefox - GitHub"]); + // Two password changes: two snapshots, oldest first, each with the password it had then. + let old: Vec = gh.history.iter().map(|h| h.get("Password").unwrap().expose().to_owned()).collect(); + assert_eq!(old, ["First-Pass-1", "Second-Pass-2"]); + + let entry = |title: &str| { + fn find<'a>(g: &'a Group, t: &str) -> Option<&'a Entry> { + g.entries + .iter() + .find(|e| e.get("Title").unwrap().expose() == t) + .or_else(|| g.groups.iter().find_map(|s| find(s, t))) + } + find(&db.root, title).unwrap() + }; + let api = entry("Stripe"); + assert_eq!(api.get("custos-type").unwrap().expose(), "api-credential"); + assert_eq!(api.get("Password").unwrap().expose(), "sk-New"); + assert_eq!(api.times.expires, custos_kdbx::parse_iso("2027-01-31")); + let card = entry("Visa"); + assert_eq!(card.get("UserName").unwrap().expose(), "A N Other"); + assert_eq!(card.get("Password").unwrap().expose(), "4000000000000002"); + assert!(card.strings.iter().find(|s| s.key == "cvv").unwrap().protected); + assert_eq!(card.history.len(), 1, "both changes in one snapshot"); + assert_eq!(card.history[0].get("cvv").unwrap().expose(), "123"); + assert_eq!(card.history[0].get("Password").unwrap().expose(), "4111111111111111"); + assert_eq!(entry("Home").get("UserName").unwrap().expose(), "Domi", "Wi-Fi: SSID as the user name"); + assert!(entry("Keys").get("custos-type").is_none(), "a note looks like a note"); + // Empty template fields stay out; Custos's own type and template names come back as custom strings. + assert!(entry("empty ApiCredential").get("key-id").is_none()); +} + +fn s(key: &str, value: &str, protected: bool) -> StringField { + StringField { key: key.into(), value: value.into(), protected } +} + +#[test] +fn a_keepass_database_maps_as_the_table_says() { + let entry = |n: u8, strings: Vec| Entry { + uuid: [n; 16], + strings, + times: Times { created: 1_700_000_000, modified: 1_700_000_500, expires: None }, + ..Default::default() + }; + let mut login = entry( + 1, + vec![ + s("Notes", "n", false), + s("KP2A_URL_2", "https://three.example", false), + s("KP2A_URL", "https://two.example", false), + s("Password", "Now-1", true), + s("PIN", "9999", true), + s("Title", "Bank", false), + s("TOTP Seed", "JBSW Y3DP EHPK 3PXP", true), + s("URL", "https://one.example", false), + s("UserName", "me", false), + ], + ); + login.tags = vec!["money".into(), "important".into()]; + login.autotype = AutoType { default_sequence: "{PASSWORD}{ENTER}".into(), windows: vec![] }; + // Snapshots: the PIN changed first, then the password; the last one changed nothing secret. + login.history = vec![ + entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "1111", true)]), + entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "9999", true)]), + entry(1, vec![s("Title", "Bank renamed", false), s("Password", "Now-1", true), s("PIN", "9999", true)]), + ]; + for (i, h) in login.history.iter_mut().enumerate() { + h.times.modified = 1_700_000_100 + i as i64 * 100; + } + let only_custom = entry(2, vec![s("Title", "Licence", false), s("Licence key", "ABCD-EFGH", true)]); + let binned = entry(3, vec![s("Title", "Deleted", false), s("Password", "x", true)]); + let db = Database { + name: "KeePass".into(), + root: Group { + uuid: [9; 16], + name: "Root".into(), + entries: vec![only_custom], + groups: vec![ + Group { uuid: [8; 16], name: "Banking".into(), entries: vec![login], groups: vec![] }, + Group { uuid: [7; 16], name: "Recycle Bin".into(), entries: vec![binned], groups: vec![] }, + ], + }, + recycle_bin: Some([7; 16]), + }; + let items = to_items(&db); + assert_eq!(items.len(), 2, "nothing from the recycle bin"); + + let licence = &items[0]; + assert_eq!(licence.kind, ItemType::SecureNote); + assert_eq!(licence.fields, [Field::secret("Licence key", "ABCD-EFGH")]); + + let bank = &items[1]; + assert_eq!(bank.kind, ItemType::WebLogin); + assert_eq!(bank.id, "01".repeat(16)); + assert_eq!(bank.folder, ["Banking"]); + assert_eq!(bank.tags, ["money", "important"]); + let f = |name: &str| bank.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect::>(); + assert_eq!(f("url"), ["https://one.example", "https://two.example", "https://three.example"]); + assert_eq!(f("totp"), ["JBSWY3DPEHPK3PXP"], "default settings: the bare seed, spaces removed"); + assert_eq!(f("PIN"), ["9999"]); + assert_eq!(f("autotype-sequence"), ["{PASSWORD}{ENTER}"]); + let h: Vec<(&str, &str, i64)> = + bank.history.iter().map(|h| (h.field.as_str(), h.value.expose(), h.changed)).collect(); + assert_eq!(h, [("PIN", "1111", 1_700_000_100_000), ("password", "Old-1", 1_700_000_200_000)]); + assert_eq!(bank.created, 1_700_000_000_000); + assert_eq!(bank.modified, 1_700_000_500_000); +} + +#[test] +fn field_names_keepass_reserves_are_renamed_not_lost() { + let mut item = Item::new(ItemType::WebLogin, "Odd", T); + item.add_field(Field::text("Title", "a field called Title")); + item.add_field(Field::secret("custos-type", "not a type")); + item.add_field(Field::text("KP2A_URL", "not a URL")); + let db = from_items(&[item], "x"); + let e = &db.root.entries[0]; + assert_eq!(e.get("Title").unwrap().expose(), "Odd"); + assert_eq!(e.get("Title (2)").unwrap().expose(), "a field called Title"); + assert_eq!(e.get("custos-type (2)").unwrap().expose(), "not a type"); + assert_eq!(e.get("KP2A_URL (2)").unwrap().expose(), "not a URL"); + let keys: Vec<&str> = e.strings.iter().map(|s| s.key.as_str()).collect(); + let mut unique = keys.clone(); + unique.sort(); + unique.dedup(); + assert_eq!(keys.len(), unique.len(), "keys are unique: {keys:?}"); +} + +#[test] +fn ids_survive_and_bad_ids_get_a_fresh_uuid() { + let mut a = Item::new(ItemType::SecureNote, "a", T); + a.id = "00112233445566778899aabbccddeeff".into(); + let mut b = Item::new(ItemType::SecureNote, "b", T); + b.id = "not hex".into(); + let db = from_items(&[a, b], "x"); + assert_eq!( + db.root.entries[0].uuid, + [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff] + ); + assert_ne!(db.root.entries[1].uuid, [0; 16]); +} diff --git a/tools/kdbx/__pycache__/compare.cpython-310.pyc b/tools/kdbx/__pycache__/compare.cpython-310.pyc new file mode 100644 index 0000000..589ee92 Binary files /dev/null and b/tools/kdbx/__pycache__/compare.cpython-310.pyc differ diff --git a/tools/kdbx/compare.py b/tools/kdbx/compare.py new file mode 100644 index 0000000..ae1fda1 --- /dev/null +++ b/tools/kdbx/compare.py @@ -0,0 +1,139 @@ +"""Compares two KeePassXC XML exports entry by entry (docs/KDBX.md, "Tests"). + + python3 compare.py before.xml after.xml + +Leaves out exactly what docs/KDBX.md says does not survive: icons, colours, custom data, group settings, +history beyond the secret fields, per-window auto-type sequences, the recycle bin, sub-second times. +A KeePass 2 `TOTP Seed` + `TOTP Settings` pair counts as equal to the `otp` URI Custos writes for it. +Exit status 1 and a list of differences when anything else changed. Prints no values, only keys. +""" + +import base64 +import gzip +import sys +import xml.etree.ElementTree as ET +from datetime import datetime, timezone +from urllib.parse import parse_qs, urlparse + +EPOCH_OFFSET = 62_135_596_800 + + +def when(text): + text = (text or "").strip() + try: + raw = base64.b64decode(text, validate=True) + if len(raw) == 8: + return int.from_bytes(raw, "little", signed=True) - EPOCH_OFFSET + except ValueError: + pass + return int(datetime.strptime(text.rstrip("Z"), "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc).timestamp()) + + +def binaries(root): + out = {} + for b in root.findall("./Meta/Binaries/Binary"): + data = base64.b64decode(b.text or "") + if b.get("Compressed", "").lower() == "true": + data = gzip.decompress(data) + out[b.get("ID")] = data + return out + + +def totp(strings): + """(secret, period, digits) from `otp` or from `TOTP Seed` + `TOTP Settings`.""" + if "otp" in strings: + v = strings["otp"] + if v.startswith("otpauth://"): + q = parse_qs(urlparse(v).query) + return (q["secret"][0].upper(), int(q.get("period", ["30"])[0]), int(q.get("digits", ["6"])[0])) + return (v.replace(" ", "").upper(), 30, 6) + if "TOTP Seed" in strings: + parts = (strings.get("TOTP Settings") or "30;6").split(";") + return (strings["TOTP Seed"].replace(" ", "").upper(), int(parts[0]), int(parts[1])) + return None + + +def entry(e, bins, with_history=True): + strings = {} + for s in e.findall("String"): + strings[s.findtext("Key")] = s.findtext("Value") or "" + t = totp(strings) + for k in ("otp", "TOTP Seed", "TOTP Settings", "custos-type"): + strings.pop(k, None) + times = e.find("Times") + expires = times.findtext("Expires", "False").lower() == "true" + out = { + "strings": strings, + "totp": t, + "attachments": {b.findtext("Key"): bins.get(b.find("Value").get("Ref")) for b in e.findall("Binary")}, + "tags": sorted(x.strip() for x in (e.findtext("Tags") or "").replace(",", ";").split(";") if x.strip()), + "created": when(times.findtext("CreationTime")), + "modified": when(times.findtext("LastModificationTime")), + "expires": when(times.findtext("ExpiryTime")) if expires else None, + "autotype": ( + e.findtext("AutoType/DefaultSequence") or "", + [a.findtext("Window") or "" for a in e.findall("AutoType/Association")], + ), + } + if with_history: + versions = [entry(h, bins, False) for h in e.findall("History/Entry")] + [out] + changes = [] + for old, new in zip(versions, versions[1:]): + # Custos keeps the old values of secret fields: the password is the one every file has. + if old["strings"].get("Password", "") not in ("", new["strings"].get("Password", "")): + changes.append((old["modified"], old["strings"]["Password"])) + out["history"] = changes + return out + + +def entries(path): + root = ET.parse(path).getroot() + bins = binaries(root) + meta = root.find("Meta") + bin_uuid = meta.findtext("RecycleBinUUID") if meta.findtext("RecycleBinEnabled", "").lower() == "true" else None + out = {} + + def walk(g, folder): + for e in g.findall("Entry"): + out[e.findtext("UUID")] = (folder, entry(e, bins)) + for sub in g.findall("Group"): + if sub.findtext("UUID") != bin_uuid: + walk(sub, folder + [sub.findtext("Name")]) + + walk(root.find("Root/Group"), []) + return out + + +def main(before, after): + a, b = entries(before), entries(after) + problems = [] + for uuid in sorted(set(a) | set(b)): + if uuid not in b: + problems.append(f"{uuid}: missing after the round trip") + continue + if uuid not in a: + problems.append(f"{uuid}: new after the round trip") + continue + (fa, ea), (fb, eb) = a[uuid], b[uuid] + if fa != fb: + problems.append(f"{uuid}: folder {fa} became {fb}") + for k in ea: + if k == "strings": + for key in sorted(set(ea[k]) | set(eb[k])): + if ea[k].get(key) != eb[k].get(key): + problems.append(f"{uuid}: string {key!r} differs") + elif k == "attachments" and None in [*ea[k].values(), *eb[k].values()]: + # KeePassXC's XML export of a KDBX 4 database leaves the attachment data out: compare names + # here; interop.sh compares the content with `attachment-export`. + if sorted(ea[k]) != sorted(eb[k]): + problems.append(f"{uuid}: attachment names differ") + elif ea[k] != eb[k]: + problems.append(f"{uuid}: {k} differs") + print(f"{len(a)} entries before, {len(b)} after, {len(problems)} differences") + for p in problems: + print(" " + p) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:3])) diff --git a/tools/kdbx/interop.sh b/tools/kdbx/interop.sh new file mode 100644 index 0000000..73720c3 --- /dev/null +++ b/tools/kdbx/interop.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# KeePassXC interop check (docs/KDBX.md, "Tests"). Needs keepassxc-cli (2.7), cargo and python3; on the dev +# machine run it in WSL inside `nix shell nixpkgs#keepassxc nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc +# nixpkgs#python3`. Works in a fresh temporary folder; the test password is not a secret. +# +# 1. KeePassXC imports sample.xml (every feature in the mapping table) → KDBX 3.1 with a recycle bin. +# 2. Custos writes an empty KDBX 4 file; KeePassXC merges (1) into it and saves it → KDBX 4 written by KeePassXC. +# 3. Custos reads (1) and (2), maps them to items and back, and writes KDBX 4 again. +# 4. KeePassXC opens what Custos wrote; compare.py checks the XML exports and attachment-export the bytes. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../.." && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +export KDBX_PASSWORD=custos-test +K=${KEEPASSXC_CLI:-keepassxc-cli} +pw() { printf '%s\n' "$KDBX_PASSWORD"; } + +cargo build -q --release --manifest-path "$repo/Cargo.toml" -p custos-kdbx --example kdbx_tool \ + --target-dir "${CARGO_TARGET_DIR:-$work/target}" +tool="${CARGO_TARGET_DIR:-$work/target}/release/examples/kdbx_tool" + +cd "$work" +{ pw; pw; } | $K import -q -p "$here/sample.xml" v3.kdbx +"$tool" new v4.kdbx fast +{ pw; pw; } | $K merge -q v4.kdbx v3.kdbx +for v in v3 v4; do + printf 'KDBX version of %s: ' "$v"; od -A n -t u2 -j 8 -N 4 "$v.kdbx" | awk '{print $2 "." $1}' + pw | $K export -q -f xml "$v.kdbx" > "$v.xml" + "$tool" roundtrip "$v.kdbx" "$v-custos.kdbx" + pw | $K export -q -f xml "$v-custos.kdbx" > "$v-custos.xml" + python3 "$here/compare.py" "$v.xml" "$v-custos.xml" + for db in "$v.kdbx" "$v-custos.kdbx"; do + pw | $K attachment-export -q --stdout "$db" Internet/GitHub codes.txt | sha256sum + done | uniq | wc -l | grep -qx 1 || { echo "$v: the attachment changed"; exit 1; } + pw | $K show -q --totp "$v-custos.kdbx" Internet/Mail/Mail | grep -qE '^[0-9]{8}$' \ + || { echo "$v: no 8-digit TOTP after the round trip"; exit 1; } +done +echo "interop: ok" diff --git a/tools/kdbx/sample.xml b/tools/kdbx/sample.xml new file mode 100644 index 0000000..6f71936 --- /dev/null +++ b/tools/kdbx/sample.xml @@ -0,0 +1,386 @@ + + + +KeePassXC +Custos interop + +False +False +True +False +False + +True +mZmZmZmZmZmZmZmZmZmZmQ== +10 +6291456 + +QmFja3VwIGNvZGVzOgoxMTExLTIyMjIKMzMzMy00NDQ0Cg== + + + + +AQEBAQEBAQEBAQEBAQEBAQ== +Passwords + +48 + +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +False +0 +2023-05-01T10:00:00Z + +True + +null +null +AAAAAAAAAAAAAAAAAAAAAA== + +MzMzMzMzMzMzMzMzMzMzMw== +0 + + + +2026-04-01T12:00:00Z +2023-05-01T10:00:00Z +2026-04-01T12:00:00Z +2026-04-01T12:00:00Z +False +0 +2026-04-01T12:00:00Z + + +Title +Alarm code + + +UserName + + + +Password + + + +URL + + + +Notes +Front door: 4711 + + +True +0 + + + + +AgICAgICAgICAgICAgICAg== +Internet + +48 + +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +False +0 +2023-05-01T10:00:00Z + +True + +null +null +AAAAAAAAAAAAAAAAAAAAAA== + +EREREREREREREREREREREQ== +0 +dev;work + +2026-02-01T09:30:00Z +2023-05-01T10:00:00Z +2026-02-01T09:30:00Z +2030-01-01T00:00:00Z +True +0 +2026-02-01T09:30:00Z + + +Title +GitHub + + +UserName +alice + + +URL +https://github.com + + +KP2A_URL +https://gist.github.com + + +KP2A_URL_1 +https://api.github.com + + +Password +Hunter3-Current & <ok> + + +Notes +Line one +Line two & <three> + + +otp +otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP&period=30&digits=6&issuer=GitHub + + +Recovery codes +Recovery-Secret-123 + + +Account id +42 + + +codes.txt + + + +True +0 +{USERNAME}{TAB}{PASSWORD}{ENTER} + +*GitHub* + + + +Firefox - GitHub + + + + + +EREREREREREREREREREREQ== +0 + + + +2024-01-01T08:00:00Z +2023-05-01T10:00:00Z +2024-01-01T08:00:00Z +2024-01-01T08:00:00Z +False +0 +2024-01-01T08:00:00Z + + +Title +GitHub + + +UserName +alice + + +URL +https://github.com + + +KP2A_URL +https://gist.github.com + + +KP2A_URL_1 +https://api.github.com + + +Password +Hunter1-Oldest + + +True +0 + + + + +EREREREREREREREREREREQ== +0 + + + +2025-01-01T08:00:00Z +2023-05-01T10:00:00Z +2025-01-01T08:00:00Z +2025-01-01T08:00:00Z +False +0 +2025-01-01T08:00:00Z + + +Title +GitHub + + +UserName +alice + + +URL +https://github.com + + +KP2A_URL +https://gist.github.com + + +KP2A_URL_1 +https://api.github.com + + +Password +Hunter2-Old + + +True +0 + + + + + + +AwMDAwMDAwMDAwMDAwMDAw== +Mail + +48 + +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +False +0 +2023-05-01T10:00:00Z + +True + +null +null +AAAAAAAAAAAAAAAAAAAAAA== + +IiIiIiIiIiIiIiIiIiIiIg== +0 + + + +2026-03-01T12:00:00Z +2023-05-01T10:00:00Z +2026-03-01T12:00:00Z +2026-03-01T12:00:00Z +False +0 +2026-03-01T12:00:00Z + + +Title +Mail + + +UserName +bob@example.com + + +Password +Mail-Pass-77 + + +URL +https://mail.example.com + + +Notes + + + +TOTP Seed +JBSWY3DPEHPK3PXP + + +TOTP Settings +60;8 + + +True +0 + + + + + + +mZmZmZmZmZmZmZmZmZmZmQ== +Recycle Bin + +48 + +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +2023-05-01T10:00:00Z +False +0 +2023-05-01T10:00:00Z + +True + +null +null +AAAAAAAAAAAAAAAAAAAAAA== + +RERERERERERERERERERERA== +0 + + + +2026-04-02T12:00:00Z +2023-05-01T10:00:00Z +2026-04-02T12:00:00Z +2026-04-02T12:00:00Z +False +0 +2026-04-02T12:00:00Z + + +Title +Old account + + +UserName +gone + + +Password +Deleted-Pass + + +True +0 + + + + + + + +