[kdbx] custos-kdbx: KDBX 3.1/4 reader, KDBX 4 writer, item mapping, KeePassXC test vectors and interop check; v0.8.0

This commit is contained in:
2026-11-03 20:59:40 +01:00
parent 12fd17245b
commit c011463fe5
18 changed files with 3326 additions and 1 deletions
Binary file not shown.
+139
View File
@@ -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]))
+39
View File
@@ -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"
+386
View File
@@ -0,0 +1,386 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<KeePassFile>
<Meta>
<Generator>KeePassXC</Generator>
<DatabaseName>Custos interop</DatabaseName>
<MemoryProtection>
<ProtectTitle>False</ProtectTitle>
<ProtectUserName>False</ProtectUserName>
<ProtectPassword>True</ProtectPassword>
<ProtectURL>False</ProtectURL>
<ProtectNotes>False</ProtectNotes>
</MemoryProtection>
<RecycleBinEnabled>True</RecycleBinEnabled>
<RecycleBinUUID>mZmZmZmZmZmZmZmZmZmZmQ==</RecycleBinUUID>
<HistoryMaxItems>10</HistoryMaxItems>
<HistoryMaxSize>6291456</HistoryMaxSize>
<Binaries>
<Binary ID="0" Compressed="False">QmFja3VwIGNvZGVzOgoxMTExLTIyMjIKMzMzMy00NDQ0Cg==</Binary>
</Binaries>
</Meta>
<Root>
<Group>
<UUID>AQEBAQEBAQEBAQEBAQEBAQ==</UUID>
<Name>Passwords</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>MzMzMzMzMzMzMzMzMzMzMw==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2026-04-01T12:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-04-01T12:00:00Z</LastAccessTime>
<ExpiryTime>2026-04-01T12:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-04-01T12:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>Alarm code</Value>
</String>
<String>
<Key>UserName</Key>
<Value/>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True"/>
</String>
<String>
<Key>URL</Key>
<Value/>
</String>
<String>
<Key>Notes</Key>
<Value>Front door: 4711</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
<Group>
<UUID>AgICAgICAgICAgICAgICAg==</UUID>
<Name>Internet</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>EREREREREREREREREREREQ==</UUID>
<IconID>0</IconID>
<Tags>dev;work</Tags>
<Times>
<LastModificationTime>2026-02-01T09:30:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-02-01T09:30:00Z</LastAccessTime>
<ExpiryTime>2030-01-01T00:00:00Z</ExpiryTime>
<Expires>True</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-02-01T09:30:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>GitHub</Value>
</String>
<String>
<Key>UserName</Key>
<Value>alice</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://github.com</Value>
</String>
<String>
<Key>KP2A_URL</Key>
<Value>https://gist.github.com</Value>
</String>
<String>
<Key>KP2A_URL_1</Key>
<Value>https://api.github.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Hunter3-Current &amp; &lt;ok&gt;</Value>
</String>
<String>
<Key>Notes</Key>
<Value>Line one
Line two &amp; &lt;three&gt;</Value>
</String>
<String>
<Key>otp</Key>
<Value ProtectInMemory="True">otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP&amp;period=30&amp;digits=6&amp;issuer=GitHub</Value>
</String>
<String>
<Key>Recovery codes</Key>
<Value ProtectInMemory="True">Recovery-Secret-123</Value>
</String>
<String>
<Key>Account id</Key>
<Value>42</Value>
</String>
<Binary>
<Key>codes.txt</Key>
<Value Ref="0"/>
</Binary>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence>{USERNAME}{TAB}{PASSWORD}{ENTER}</DefaultSequence>
<Association>
<Window>*GitHub*</Window>
<KeystrokeSequence/>
</Association>
<Association>
<Window>Firefox - GitHub</Window>
<KeystrokeSequence/>
</Association>
</AutoType>
<History>
<Entry>
<UUID>EREREREREREREREREREREQ==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2024-01-01T08:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2024-01-01T08:00:00Z</LastAccessTime>
<ExpiryTime>2024-01-01T08:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2024-01-01T08:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>GitHub</Value>
</String>
<String>
<Key>UserName</Key>
<Value>alice</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://github.com</Value>
</String>
<String>
<Key>KP2A_URL</Key>
<Value>https://gist.github.com</Value>
</String>
<String>
<Key>KP2A_URL_1</Key>
<Value>https://api.github.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Hunter1-Oldest</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
<Entry>
<UUID>EREREREREREREREREREREQ==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2025-01-01T08:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2025-01-01T08:00:00Z</LastAccessTime>
<ExpiryTime>2025-01-01T08:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2025-01-01T08:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>GitHub</Value>
</String>
<String>
<Key>UserName</Key>
<Value>alice</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://github.com</Value>
</String>
<String>
<Key>KP2A_URL</Key>
<Value>https://gist.github.com</Value>
</String>
<String>
<Key>KP2A_URL_1</Key>
<Value>https://api.github.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Hunter2-Old</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
</History>
</Entry>
<Group>
<UUID>AwMDAwMDAwMDAwMDAwMDAw==</UUID>
<Name>Mail</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>IiIiIiIiIiIiIiIiIiIiIg==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2026-03-01T12:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-03-01T12:00:00Z</LastAccessTime>
<ExpiryTime>2026-03-01T12:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-03-01T12:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>Mail</Value>
</String>
<String>
<Key>UserName</Key>
<Value>bob@example.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Mail-Pass-77</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://mail.example.com</Value>
</String>
<String>
<Key>Notes</Key>
<Value/>
</String>
<String>
<Key>TOTP Seed</Key>
<Value ProtectInMemory="True">JBSWY3DPEHPK3PXP</Value>
</String>
<String>
<Key>TOTP Settings</Key>
<Value>60;8</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
</Group>
</Group>
<Group>
<UUID>mZmZmZmZmZmZmZmZmZmZmQ==</UUID>
<Name>Recycle Bin</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>RERERERERERERERERERERA==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2026-04-02T12:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-04-02T12:00:00Z</LastAccessTime>
<ExpiryTime>2026-04-02T12:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-04-02T12:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>Old account</Value>
</String>
<String>
<Key>UserName</Key>
<Value>gone</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Deleted-Pass</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
</Group>
</Group>
<DeletedObjects/>
</Root>
</KeePassFile>