//! 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() }