Skip to main content

agentmux_srv_core/backend/vault/import/
kdbx.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! KeePass `.kdbx` databases (KeePass, KeePassXC, KeePassDX, KeeWeb, Strongbox;
5//! KDBX 3.1 and 4), opened with the person's master password (spec §8.4).
6//!
7//! A database chooses its own key-stretching cost, and opening it spends that
8//! cost before anything is known about the file. So the header is read first, by
9//! hand, and a database asking for more than [`MAX_ARGON_MEMORY`],
10//! [`MAX_ARGON_ITERATIONS`] or [`MAX_AES_ROUNDS`] is refused before the password is
11//! ever tried (§8.7).
12
13use std::collections::BTreeMap;
14
15use keepass::db::GroupRef;
16use keepass::{Database, DatabaseKey};
17
18use super::super::{kdbx_names, kinds, linked, source_link};
19use super::{Imported, Incoming, ReadError, Source, MAX_ITEMS};
20
21pub const MAGIC: [u8; 4] = [0x03, 0xD9, 0xA2, 0x9A];
22/// The second signature of KDBX 2 and later; the original `.kdb` has another.
23const SIGNATURE_2: [u8; 4] = [0x67, 0xFB, 0x4B, 0xB5];
24const SIGNATURE_2_KDB: [u8; 4] = [0x65, 0xFB, 0x4B, 0xB5];
25
26/// Argon2 memory a database may ask for: 1 GiB.
27pub const MAX_ARGON_MEMORY: u64 = 1 << 30;
28pub const MAX_ARGON_ITERATIONS: u64 = 100;
29pub const MAX_ARGON_PARALLELISM: u64 = 64;
30/// AES-KDF rounds: a few seconds on a current machine.
31pub const MAX_AES_ROUNDS: u64 = 150_000_000;
32
33const KDF_ARGON2D: [u8; 16] = [0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B, 0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C];
34const KDF_ARGON2ID: [u8; 16] = [0x9E, 0x29, 0x8B, 0x19, 0x56, 0xDB, 0x47, 0x73, 0xB2, 0x3D, 0xFC, 0x3E, 0xC6, 0xF0, 0xA1, 0xE6];
35
36const DAMAGED: &str = "this KeePass database is damaged or isn't one";
37
38/// A cursor over the header's bytes that never reads past the end.
39struct Bytes<'a>(&'a [u8]);
40
41impl<'a> Bytes<'a> {
42    fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
43        if self.0.len() < n {
44            return Err(DAMAGED.to_string());
45        }
46        let (head, rest) = self.0.split_at(n);
47        self.0 = rest;
48        Ok(head)
49    }
50
51    fn u8(&mut self) -> Result<u8, String> {
52        Ok(self.take(1)?[0])
53    }
54
55    fn u16(&mut self) -> Result<u16, String> {
56        Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
57    }
58
59    fn u32(&mut self) -> Result<u32, String> {
60        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
61    }
62}
63
64fn le_u64(b: &[u8]) -> Result<u64, String> {
65    match b.len() {
66        4 => Ok(u32::from_le_bytes(b.try_into().unwrap()) as u64),
67        8 => Ok(u64::from_le_bytes(b.try_into().unwrap())),
68        _ => Err(DAMAGED.to_string()),
69    }
70}
71
72fn too_heavy(what: &str) -> String {
73    format!("this KeePass database asks for more {what} to open than AgentMux will spend; open it in KeePassXC and export a CSV instead")
74}
75
76/// Refuses a database whose key-stretching is heavier than the caps, or whose
77/// header doesn't parse. Reads nothing secret.
78pub fn check_header(bytes: &[u8]) -> Result<(), String> {
79    let mut b = Bytes(bytes);
80    if b.take(4)? != MAGIC {
81        return Err(DAMAGED.to_string());
82    }
83    let second = b.take(4)?;
84    if second == SIGNATURE_2_KDB {
85        return Err("this is a KeePass 1.x (.kdb) database, which AgentMux can't open; export it from KeePass as a CSV".to_string());
86    }
87    if second != SIGNATURE_2 {
88        return Err(DAMAGED.to_string());
89    }
90    let _minor = b.u16()?;
91    let major = b.u16()?;
92    match major {
93        3 => {
94            // Fields: id (1), size (2), data.
95            loop {
96                let id = b.u8()?;
97                let size = b.u16()? as usize;
98                let data = b.take(size)?;
99                match id {
100                    0 => return Ok(()),
101                    // TransformRounds
102                    6 if le_u64(data)? > MAX_AES_ROUNDS => return Err(too_heavy("key-stretching")),
103                    _ => {}
104                }
105            }
106        }
107        4 => {
108            // Fields: id (1), size (4), data.
109            loop {
110                let id = b.u8()?;
111                let size = b.u32()? as usize;
112                let data = b.take(size)?;
113                match id {
114                    0 => return Ok(()),
115                    // KdfParameters, a variant dictionary.
116                    11 => return check_kdf(data),
117                    _ => {}
118                }
119            }
120        }
121        _ => Err("this KeePass database is a version AgentMux doesn't know".to_string()),
122    }
123}
124
125/// The KDF variant dictionary of a KDBX 4 header.
126fn check_kdf(data: &[u8]) -> Result<(), String> {
127    let mut b = Bytes(data);
128    let _version = b.u16()?;
129    let mut uuid: Option<Vec<u8>> = None;
130    let mut numbers: BTreeMap<String, u64> = BTreeMap::new();
131    loop {
132        let kind = b.u8()?;
133        if kind == 0 {
134            break;
135        }
136        let key_len = b.u32()? as usize;
137        let key = String::from_utf8_lossy(b.take(key_len)?).into_owned();
138        let value_len = b.u32()? as usize;
139        let value = b.take(value_len)?;
140        match (kind, key.as_str()) {
141            (0x42, "$UUID") => uuid = Some(value.to_vec()),
142            // UInt32, UInt64, Int32, Int64
143            (0x04 | 0x05 | 0x0C | 0x0D, _) => {
144                numbers.insert(key, le_u64(value)?);
145            }
146            _ => {}
147        }
148    }
149    let uuid = uuid.ok_or_else(|| DAMAGED.to_string())?;
150    if uuid == KDF_ARGON2D || uuid == KDF_ARGON2ID {
151        let get = |k: &str| numbers.get(k).copied().ok_or_else(|| DAMAGED.to_string());
152        if get("M")? > MAX_ARGON_MEMORY {
153            return Err(too_heavy("memory"));
154        }
155        if get("I")? > MAX_ARGON_ITERATIONS || get("P")? > MAX_ARGON_PARALLELISM {
156            return Err(too_heavy("key-stretching"));
157        }
158    } else if numbers.get("R").copied().unwrap_or(0) > MAX_AES_ROUNDS {
159        return Err(too_heavy("key-stretching"));
160    }
161    Ok(())
162}
163
164/// The field names KeePass itself uses; any other field is the person's own.
165const STANDARD: &[&str] = &["Title", "UserName", "Password", "URL", "Notes", "otp"];
166
167/// The most a key file may be: KeePass's own are a few hundred bytes (an XML file, or 32 random ones).
168pub const MAX_KEY_FILE: usize = 1024 * 1024;
169
170pub fn read(bytes: &[u8], passphrase: &str, keyfile: Option<&[u8]>) -> Result<Imported, ReadError> {
171    check_header(bytes)?;
172    if passphrase.is_empty() && keyfile.is_none() {
173        return Err(ReadError::NeedsPassphrase);
174    }
175    // A database may be opened by its password, its key file, or both.
176    let mut key = DatabaseKey::new();
177    if !passphrase.is_empty() {
178        key = key.with_password(passphrase);
179    }
180    if let Some(file) = keyfile {
181        if file.len() > MAX_KEY_FILE {
182            return Err("that key file is too large to be a KeePass key file".into());
183        }
184        key = key.with_keyfile(&mut std::io::Cursor::new(file)).map_err(|_| ReadError::from("that isn't a KeePass key file"))?;
185    }
186    let (what, wrong) = match keyfile {
187        Some(_) => ("that password and key file", "the password or the key file is wrong"),
188        None => ("that password", "the password is wrong, or the database also needs a key file: choose it too"),
189    };
190    let db = Database::parse(bytes, key).map_err(|e| {
191        use keepass::db::DatabaseOpenError as E;
192        match e {
193            E::Key(keepass::error::DatabaseKeyError::IncorrectKey) => ReadError::from(format!("{what} didn't open the database ({wrong})")),
194            E::Key(keepass::error::DatabaseKeyError::InvalidKeyFile | keepass::error::DatabaseKeyError::Xml(_)) => ReadError::from("that isn't a KeePass key file"),
195            E::Key(_) => ReadError::from(format!("{what} didn't open the database")),
196            // A KDBX 3 file has no check of the key before it decrypts: a wrong password comes out as
197            // garbage that fails to unpad, the same as a damaged file does.
198            E::Cryptography(_) => ReadError::from(format!("{what} didn't open the database, or the file is damaged")),
199            // The XML inside didn't parse. The crate's detail can quote the file, so it is not passed on.
200            E::Format(_) => ReadError::from(
201                "this KeePass database couldn't be read: it is damaged, or was written by a tool that lays its entries out differently from KeePass (files from KeePass and KeePassXC read fine)",
202            ),
203            _ => ReadError::from(DAMAGED),
204        }
205    })?;
206    let recycle = db.recycle_bin().map(|g| g.id());
207    let mut entries = Vec::new();
208    let mut skipped = Vec::new();
209    walk(db.root(), &[], recycle, &mut entries, &mut skipped)?;
210    Ok(Imported { source: Source::KeePass, entries, skipped, plaintext: false })
211}
212
213fn walk(group: GroupRef<'_>, path: &[String], recycle: Option<keepass::db::GroupId>, entries: &mut Vec<Incoming>, skipped: &mut Vec<(String, String)>) -> Result<(), ReadError> {
214    if recycle == Some(group.id()) {
215        return Ok(());
216    }
217    // The root group's own name ("Root", "Database") says nothing; below it, the path does.
218    let mut here = path.to_vec();
219    if !path.is_empty() || group.parent().is_some() {
220        here.push(group.name.clone());
221    }
222    let tag = here.join("/");
223    for entry in group.entries() {
224        if entries.len() + skipped.len() >= MAX_ITEMS {
225            return Err(format!("this database has more than {MAX_ITEMS} entries, more than the Vault imports").into());
226        }
227        entry_into(&entry, &tag, entries, skipped);
228    }
229    for child in group.groups() {
230        walk(child, &here, recycle, entries, skipped)?;
231    }
232    Ok(())
233}
234
235fn entry_into(e: &keepass::db::Entry, tag: &str, entries: &mut Vec<Incoming>, skipped: &mut Vec<(String, String)>) {
236    let get = |k: &str| e.get(k).map(str::trim).unwrap_or("");
237    let site = get("URL");
238    let label = match get("Title") {
239        "" if !site.is_empty() => site.to_string(),
240        "" => get("UserName").to_string(),
241        t => t.to_string(),
242    };
243    let label = if label.is_empty() { "(unnamed)".to_string() } else { label };
244    let mut made = Vec::new();
245    // A password is kept exactly as saved, spaces and all.
246    let password = e.get("Password").unwrap_or("");
247    if !password.is_empty() {
248        let mut login = Incoming::new("login", &label).part("password", password).field("site", site).field("username", get("UserName"));
249        // KeePassXC's `otp` field, or KeePass's own TimeOtp fields.
250        let totp = e.get_raw_otp_value().map(str::trim).filter(|v| !v.is_empty());
251        if let Some(t) = totp {
252            login = login.part("totp", t);
253        }
254        made.push(login);
255    }
256    // Custom fields: one named like a kind's secret (SSN, Card number, API key, …) makes an entry of
257    // that kind, with the fields that belong to it (a card's expiry, an owner); the rest are kept
258    // sealed in a note, since a custom field is often a recovery code or a PIN.
259    let custom = custom_fields(e);
260    let (mut used, mut link, marked) = link_fields(&custom);
261    let mut typed: Vec<Incoming> = Vec::new();
262    for primary in kdbx_names::PRIMARY {
263        let Some(i) = custom.iter().position(|(n, _)| kdbx_names::matches(primary.aliases, n)) else { continue };
264        if used[i] {
265            continue;
266        }
267        used[i] = true;
268        let mut entry = Incoming::new(primary.kind, &label).part(primary.part, &custom[i].1);
269        for c in kdbx_names::COMPANIONS.iter().filter(|c| c.kind == primary.kind) {
270            if let Some(j) = custom.iter().position(|(n, _)| kdbx_names::matches(c.aliases, n)).filter(|j| !used[*j]) {
271                used[j] = true;
272                entry = entry.part(c.part, &custom[j].1);
273            }
274        }
275        typed.push(entry);
276    }
277    match marked.filter(|_| typed.is_empty() && password.is_empty()) {
278        Some(i) => typed.push(linked_entry(&custom[i].1, &label, site, get("UserName"))),
279        None => date_stays_text(&custom, &mut used, &mut link),
280    }
281    // The details (an owner, a bank, an expiry) go to the entries that take them.
282    for detail in kdbx_names::DETAILS {
283        let Some(j) = custom.iter().position(|(n, _)| kdbx_names::matches(detail.aliases, n) || n.trim().eq_ignore_ascii_case(detail.title)).filter(|j| !used[*j]) else { continue };
284        let mut taken = false;
285        for t in typed.iter_mut() {
286            if kinds::kind(&t.kind).is_some_and(|k| k.fields.contains(&detail.name)) {
287                *t = std::mem::take(t).field(detail.name, &custom[j].1);
288                taken = true;
289            }
290        }
291        if taken {
292            used[j] = true;
293        }
294    }
295    // An entry that is nothing but one typed secret keeps its own title; one with a password too (or
296    // several secrets) names each by what it holds.
297    if typed.len() == 1 && password.is_empty() {
298        typed[0].label = label.clone();
299    } else {
300        for t in typed.iter_mut() {
301            let what = kdbx_names::primary_for(&t.kind).map(|p| p.title).unwrap_or("secret");
302            t.label = format!("{label} ({what})");
303        }
304    }
305    made.extend(typed);
306    let mut extra = String::new();
307    for (i, (name, value)) in custom.iter().enumerate() {
308        if used[i] {
309            continue;
310        }
311        if !extra.is_empty() {
312            extra.push('\n');
313        }
314        extra.push_str(&format!("{name}: {value}"));
315    }
316    // A one-time-code seed with no password to go with it (a 2FA-only entry) has no
317    // login to ride on, so it is kept in the sealed note rather than dropped.
318    if password.is_empty() {
319        if let Some(t) = e.get_raw_otp_value().map(str::trim).filter(|v| !v.is_empty()) {
320            if !extra.is_empty() {
321                extra.push('\n');
322            }
323            extra.push_str(&format!("otp: {t}"));
324        }
325    }
326    // Notes and the remaining custom fields, kept together and sealed.
327    let notes = get("Notes");
328    let text = match (notes.is_empty(), extra.is_empty()) {
329        (true, _) => extra,
330        (false, true) => notes.to_string(),
331        (false, false) => format!("{notes}
332{extra}"),
333    };
334    if !text.is_empty() {
335        // An entry with no password of its own is just a note.
336        let name = if made.is_empty() { label.clone() } else { format!("{label} (notes)") };
337        made.push(Incoming::new("note", &name).part("text", &text));
338    }
339    if made.is_empty() {
340        skipped.push((label, "it has no password, note or secret field".to_string()));
341        return;
342    }
343    entries.extend(with_link(made, link).into_iter().map(|m| m.tag(tag)));
344}
345
346/// The entry's custom fields that hold something, by name: not the standard ones, nor another app's own.
347fn custom_fields(e: &keepass::db::Entry) -> Vec<(String, String)> {
348    let mut custom: Vec<(String, String)> = e
349        .fields
350        .keys()
351        .filter(|k| !STANDARD.contains(&k.as_str()) && !k.starts_with("TimeOtp-") && !k.starts_with("KPH: ") && !k.starts_with("_etm_"))
352        .filter_map(|k| {
353            let v = e.get(k).map(str::trim).unwrap_or("");
354            (!v.is_empty()).then(|| (k.clone(), v.to_string()))
355        })
356        .collect();
357    custom.sort();
358    custom
359}
360
361/// A linked entry, as an export from the Vault writes one: no secret, and a field that says its kind (`said`). It
362/// comes back as a link of that kind, an API key when the kind isn't one the Vault has.
363fn linked_entry(said: &str, label: &str, site: &str, username: &str) -> Incoming {
364    let kind = kinds::kind(said.trim()).map(|k| k.name).unwrap_or("api-key");
365    let entry = Incoming::new(kind, label).field(linked::LINK, linked::ONLY);
366    if kind == "login" {
367        return entry.field("site", site).field("username", username);
368    }
369    entry
370}
371
372/// An entry that is not a linked one (it never was, or it has since been given a password or a secret field) holds
373/// a value, and the date a key last changed is a linked entry's own: the Vault's history dates a value it holds. The
374/// date goes back among the custom fields kept as text in the entry's note.
375fn date_stays_text(custom: &[(String, String)], used: &mut [bool], link: &mut Vec<(&'static str, String)>) {
376    link.retain(|(name, _)| *name != linked::ROTATED);
377    let titled = linked::TITLES.iter().find(|(name, _)| *name == linked::ROTATED).map_or("", |(_, title)| *title);
378    if let Some(i) = custom.iter().position(|(n, _)| n.trim().eq_ignore_ascii_case(titled)) {
379        used[i] = false;
380    }
381}
382
383/// Which custom fields say where the entry's machine copy is and what is said of the key there (who reads it, when
384/// it last changed, where else it is kept), as an export from the Vault writes them: they come back as plain fields,
385/// not note text. What is said of the key is read only from an entry the Vault wrote (one that marks a link or
386/// names a place): another app's field called "Read by" stays text in the note. Returns which of `custom` are used
387/// up, the fields, and which field marks a linked entry.
388fn link_fields(custom: &[(String, String)]) -> (Vec<bool>, Vec<(&'static str, String)>, Option<usize>) {
389    let mut used = vec![false; custom.len()];
390    let mut link = Vec::new();
391    let marked = custom.iter().position(|(n, _)| n.trim().eq_ignore_ascii_case(linked::KIND_TITLE));
392    if let Some(i) = marked {
393        used[i] = true;
394    }
395    let mut take = |titles: &[(&'static str, &'static str)], link: &mut Vec<(&'static str, String)>| {
396        for (name, title) in titles {
397            if let Some(i) = custom.iter().position(|(n, _)| n.trim().eq_ignore_ascii_case(title)) {
398                used[i] = true;
399                link.push((*name, custom[i].1.clone()));
400            }
401        }
402    };
403    take(&source_link::TITLES, &mut link);
404    if marked.is_some() || !link.is_empty() {
405        take(&linked::TITLES, &mut link);
406    }
407    (used, link, marked)
408}
409
410/// `made` with the link on its first entry: the one the KeePass entry is about.
411fn with_link(mut made: Vec<Incoming>, link: Vec<(&'static str, String)>) -> Vec<Incoming> {
412    if let Some(first) = made.first_mut() {
413        for (name, value) in &link {
414            *first = std::mem::take(first).field(name, value);
415        }
416    }
417    made
418}
419
420#[cfg(test)]
421#[path = "kdbx_tests.rs"]
422mod tests;