[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:
@@ -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]))
|
||||
Reference in New Issue
Block a user