diff --git a/CLAUDE.md b/CLAUDE.md index 8a0bc41..3eda70b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,6 +14,7 @@ crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app' crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs +crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code) docs/FACTORS.md version 2: any two factors open the vault; the machine store docs/KEYS.md secret keys, API keys and key pairs @@ -21,6 +22,7 @@ docs/SEAL.md sealed boxes and the match code docs/SHARE.md the share blob and link format (versioned like FORMAT.md) docs/THREAT_MODEL.md what is and is not protected docs/IDENTITY.md the Domi identity: the root key in the vault, the mnemonic order, signing certs +docs/KDBX.md KeePass files: reading, writing, limits, the item mapping and what does not survive ``` ## Commands @@ -41,7 +43,8 @@ On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: - No binaries in git. - **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `hkdf`, `zeroize`, `rand` with `SysRng`; for key pairs `ssh-key`, `p256`, `rsa` and `ed25519-dalek`, RustCrypto's Ed25519 - backend; `x25519-dalek` for sealed boxes). Randomness from the OS CSPRNG only. + backend; `x25519-dalek` for sealed boxes; for KeePass files `aes`, `cbc`, `chacha20`, `salsa20`, `hmac`, + `sha2`). Randomness from the OS CSPRNG only. - **Secrets never in logs, panics, error messages, `Debug`/`Display` output or test snapshots.** Secret-holding types print `[redacted]`; there is a test for each one. - Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md` diff --git a/README.md b/README.md index 2f64dfb..8112f2b 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ password and secret manager: everything that touches plaintext or keys. | `custos-qr` | QR payloads: Wi-Fi join codes (escaped), plain secrets | | `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) | | `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) | +| `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) | Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md) for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md). diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 7bfd47a..8c74b88 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -121,6 +121,11 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: - Readers ignore JSON members they do not know, so later versions can add them. - `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later. +- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path, + docs/KDBX.md). Absent or empty = no folder. +- `attachments` (optional item member, core 0.8.0): `[{"name": "id_rsa", "data": ""}]`, files kept with + the item (imported from KeePass). The data counts as secret: it is never logged or printed. + An older Custos drops `folder` and `attachments` when it saves. ### Item types and their fields (v1) @@ -137,34 +142,9 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: `notes` is secret for every type (it is shown only on reveal). -## Planned KDBX 4 mapping (export comes in v1.2) +## KDBX 4 (KeePass) -KeePassXC-compatible: standard strings where KeePass has them, custom strings otherwise. Secret fields -become *protected* strings. - -| Custos | KDBX 4 entry | -|:--|:--| -| `title` | `Title` | -| `username` (web-login, local-app) | `UserName` | -| `password`* (web-login, local-app, wifi) | `Password` (protected) | -| first `url` | `URL` | -| 2nd, 3rd … `url` | `KP2A_URL_1`, `KP2A_URL_2`, … (KeePassXC reads these) | -| `notes` | `Notes` | -| `totp` | `otp` (protected), as an `otpauth://` URI (KeePassXC's format) | -| `autotype-sequence` | `AutoType/DefaultSequence` | -| `autotype-match` | `AutoType/Association/Window` | -| `type` | custom string `custos-type` | -| `api-credential`: `service`, `key-id`, `endpoint`, `expires` | custom strings `service`, `key-id`, `endpoint`; `expires` → entry `Times/Expires` + `ExpiryTime` | -| `api-credential`: `secret`* | `Password` (protected) | -| `local-app`: `target` | custom string `target` | -| `wifi`: `ssid`, `security`, `hidden` | `UserName` = ssid, custom strings `security`, `hidden` | -| `card`: `number`* | `Password` (protected) | -| `card`: `cardholder`, `expiry` | `UserName` = cardholder, custom string `expiry` | -| `card`: `cvv`*, `pin`* | protected custom strings `cvv`, `pin` | -| other custom fields | custom strings of the same name, protected when secret | -| `tags` | `Tags` (`;`-separated) | -| `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` | -| `history` entries | `History` entries (one per change, with that old password) | +Import and export, with the full field mapping and what does not survive: docs/KDBX.md. ## Device key wrap (not part of the file) diff --git a/docs/KDBX.md b/docs/KDBX.md new file mode 100644 index 0000000..041c59f --- /dev/null +++ b/docs/KDBX.md @@ -0,0 +1,128 @@ +# KeePass import and export (`custos-kdbx`) + +Custos reads KeePass's KDBX 3.1 and KDBX 4 files (4.0 and 4.1) and writes KDBX 4.0, so a vault can move in from +KeePassXC or KeePass 2 and back out to them. KeePassXC 2.7 still writes 3.1 for a database with AES-KDF (its +command line does by default); its app writes 4.0 with Argon2d. The crate has two layers: + +1. **The file format** (`read`, `write`): bytes and a key in, a KDBX database model out, and back. It knows + groups, entries, strings, attachments, times, auto-type and history. It does not know Custos items. +2. **The mapping** (`to_items`, `from_items`): KDBX entries to Custos items and back (the table below). + +No custom crypto: AES-256 (`aes`, `cbc`), ChaCha20 (`chacha20`), SHA-256/512 (`sha2`), HMAC-SHA-256 (`hmac`), +Argon2d/id (`argon2`), all RustCrypto. Compression is gzip (`flate2`), XML is `quick-xml` events. + +## Reading + +| Step | What | +|:--|:--| +| Signature | `03 D9 A2 9A`, `67 FB 4B B5`, then minor/major version (u16 LE each). Major 4 here; major 3 is read as below ("KDBX 3.1"); anything else is `UnsupportedVersion` | +| Outer header | TLV fields: id (u8), length (u32 LE), data, until id 0. Cipher, compression, master seed (32 bytes), IV, KDF parameters (a VariantDictionary) | +| Header checks | SHA-256 of the header (mismatch: `Corrupted`), then HMAC-SHA-256 of the header with the block key for index 2⁶⁴−1 (mismatch: `WrongKey`) | +| Key | composite = SHA-256(SHA-256(password) ‖ key-file key); with only one of the two, only that one goes in | +| KDF | Argon2d or Argon2id (`S`, `P`, `M` bytes, `I`, `V` = 0x13; a non-empty secret `K` or data `A` is refused), or AES-KDF (`R` rounds of AES-256-ECB keyed with `S` over both halves, then SHA-256) | +| Keys | cipher key = SHA-256(master seed ‖ transformed); HMAC base = SHA-512(master seed ‖ transformed ‖ 0x01); block *i* key = SHA-512(u64 LE *i* ‖ HMAC base) | +| Blocks | HMAC (32) ‖ length (u32 LE) ‖ data, each checked: HMAC-SHA-256(block key, u64 LE index ‖ u32 LE length ‖ data). A zero-length block ends the stream. A failed block: `Corrupted` | +| Payload | AES-256-CBC (PKCS#7) or ChaCha20 (96-bit IV) decryption, then gunzip if the compression flag is 1 | +| Inner header | TLV: inner stream id (3 = ChaCha20; Salsa20 = 2 is refused), inner stream key (64 bytes), binaries (flag byte ‖ data, in pool order), end | +| XML | protected values are XORed with the inner stream, key = SHA-512(stream key)[0..32], nonce = [32..44], in document order | + +### KDBX 3.1 + +The same key, cipher and XML, with these differences: header field lengths are u16; the KDF is always AES-KDF +from the header (`TransformSeed`, `TransformRounds`); there is no header HMAC: after decryption the first 32 +bytes must equal the header's `StreamStartBytes` (otherwise `WrongKey`); the payload is SHA-256 hashed blocks +(index u32, hash, length u32, data; a changed block is `Corrupted`); the inner stream is Salsa20 (key = +SHA-256 of `ProtectedStreamKey`, KeePass's fixed nonce `E8 30 09 4B 97 20 5D 2A`), and its id and key are in the +outer header; attachments are in `Meta/Binaries` (base64, gzipped when `Compressed="True"`), referenced by ID. + +**Key files** (`Key::key_file`): KeePass XML 2.0 (`` hex, the hash is checked), XML 1.0 (base64), +exactly 32 bytes (used as is), exactly 64 hex digits (decoded), anything else: SHA-256 of the file. + +### Limits (checked before any expensive work) + +| What | Limit | Error | +|:--|:--|:--| +| File size | 512 MiB | `TooLarge` | +| A header field | 64 KiB (a binary in the inner header: 256 MiB) | `Malformed` | +| Argon2 | `M` ≤ 2 GiB, `I` 1 ..= 1000, `P` 1 ..= 64, `V` = 0x13 | `UnsupportedKdf` | +| AES-KDF | `R` 1 ..= 2³⁰ | `UnsupportedKdf` | +| Decompressed payload | 512 MiB | `TooLarge` | +| XML | no `` (entities are never expanded), element depth ≤ 256 | `Malformed` | +| Unknown cipher (Twofish) | | `UnsupportedCipher` | +| Inner stream other than ChaCha20 (and Salsa20 in 3.1) | | `UnsupportedStream` | + +No error carries any part of the password, the key or a value. A panic on any input is a bug. + +## Writing + +KDBX 4.0: ChaCha20, gzip, Argon2id (`M` = 64 MiB, `I` = 20, `P` = 1 by default: the vault's own defaults), +ChaCha20 inner stream with a fresh 64-byte key, a fresh master seed, IV and salt from the OS CSPRNG. Every +`Password` and every string Custos keeps secret is written protected. Blocks are 1 MiB. AES-256 and AES-KDF +can be chosen (`WriteOptions`) so the reader is tested against both. + +The export is protected **by its own password only** (and optionally a key file). It is meant for moving to +KeePassXC or for an offline backup; the app says so before it writes one. + +## Mapping: KeePass entry ↔ Custos item + +Entry UUID ↔ item `id` (16 bytes ↔ 32 hex digits), so importing the same file again finds the items it +already imported. + +| KDBX entry | Custos item | +|:--|:--| +| group path below the root group | `folder` (list of group names; the root itself is not included) | +| `Title` | `title` | +| `UserName` | `username` (web-login, local-app, and any type without its own), `ssid` (wifi), `cardholder` (card) | +| `Password` (protected) | `password` (web-login, local-app, wifi, and others), `secret` (api-credential), `number` (card) | +| `URL`, then `KP2A_URL`, `KP2A_URL_1`, … (exactly those names) | `url`, repeated in that order | +| `Notes` | `notes` | +| `otp` (KeePassXC) | `totp` | +| `TOTP Seed` + `TOTP Settings` (KeePass 2 / older KeePassXC) | `totp`, as an `otpauth://` URI when the settings are not 30 s / 6 digits | +| `custos-type` | the item type (written by Custos; other files are guessed: no user name, password or URL → secure-note, otherwise web-login) | +| any other string | a field with the same name; secret when protected. A Custos field whose name KeePass reserves (`Title`, `custos-type`, `KP2A_URL`, …) or that is already taken is written as `name (2)`, `name (3)`, … | +| `Tags` (`;` or `,` separated) | `tags` | +| `Times/CreationTime`, `LastModificationTime` | `created`, `modified` (seconds; milliseconds are dropped on export) | +| `Times/Expires` + `ExpiryTime` | field `expires`: `YYYY-MM-DD` at midnight UTC, else `YYYY-MM-DDTHH:MM:SSZ` | +| `Binary` (attachments) | `attachments` (name and bytes) | +| `AutoType/DefaultSequence` | `autotype-sequence` | +| each `AutoType/Association/Window` | `autotype-match`, repeated | +| `History` | `history`: for each snapshot, each secret field (the password, every protected string) whose value differs in the next version: `{field, value, changed: the snapshot's modification time}`, newest 20 kept. On export, one snapshot per distinct change time, with the values just before that change | + +On export, an empty field from the item's template is left out; every other field is written, even when +empty. `custos-type` is written only when the type differs from what the guess above would give, so a plain +KeePass entry comes back without it. The root group is named after the export (default "Custos"); folders +become groups under it. Imported items come back folder by folder: extra fields after the template's ones. + +### What does not survive + +Said plainly, so nobody expects it: + +- **Icons, colours, custom icons, `OverrideURL`**, an entry's or group's `CustomData`, group notes and settings. +- **History of non-secret fields**: KeePass snapshots hold every field; Custos keeps old values of secret + fields only, at most 20 per item (KeePassXC keeps 10 snapshots by default). +- **Auto-type**: a per-window keystroke sequence and the "auto-type disabled" switch. +- **The recycle bin**: entries in it are not imported. Deleted-object records are not kept. +- **Database settings** (`Meta`): name, description, history limits, KDF and cipher. The export uses its own. +- Sub-second times. + +Custos items that have nothing in KeePass go out as custom strings (`custos-type`, the template fields such as +`key-id` or `cvv`) and come back the same. Version 2 vault factors and the Domi identity are never exported. + +## Tests (`crates/custos-kdbx/tests/`) + +- `format.rs`: write → read is identical for every cipher and KDF; wrong password, no key, each key-file kind + (four spellings of one key open each other's files); a changed byte anywhere (header and hash: `Corrupted`, + header HMAC: `WrongKey`, blocks: `Corrupted`); truncation at every length; out-of-limit KDF parameters refused + in well under a second; DOCTYPE (billion laughs, XXE), deep nesting, broken XML, a gzip bomb, a Salsa20 inner + stream in KDBX 4, Twofish and unknown versions refused; no secret in any `Debug` output. +- `keepassxc.rs`: two files KeePassXC 2.7.12 wrote from `tools/kdbx/sample.xml` (base64 test vectors in + `tests/data/`, password `custos-test`): KDBX 3.1 from `import`, KDBX 4.0 from `merge` into a Custos file. Both + open with the expected folders, fields, protected strings, extra URLs, both TOTP forms, expiry, auto-type, + history and attachment; the 3.1 file's recycle bin is skipped; a wrong password is `WrongKey`. +- `mapping.rs`: every item type through `from_items` → write → read → `to_items` is unchanged, field by field; + what the export looks like to KeePassXC; a KeePass-style database maps as the table says; reserved names are + renamed, ids survive. +- `tools/kdbx/interop.sh` (WSL + Nix with `keepassxc-cli`, not part of `cargo test`): KeePassXC makes a 3.1 and a + 4.0 file from `sample.xml`; Custos reads each, maps it to items and back, and writes KDBX 4; KeePassXC opens + that, `compare.py` checks both XML exports entry by entry (leaving out only what "What does not survive" + lists), `attachment-export` compares the attachment bytes, and `show --totp` gives the 8-digit code. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index e2376d0..b8b7e45 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -21,6 +21,8 @@ just as plainly, what it does not. | Someone who gets a share link | The link (chat history, a forwarded mail) | The secret, if the share still has views left; with a password share, also one Argon2id evaluation (19 MiB) per password guess | That is what a link is. Use 1 view (the default): once it is opened, it is gone, and the sender learns about interception when the recipient finds it used. | | Link-preview bot | The link, fetched by a chat app | Nothing; the view is not used | The page asks for a click on *Reveal* before it fetches the share. | | Someone who crashes the machine mid-save | — | Nothing | Atomic save: temp file, fsync, rename; the previous version is kept as `.bak`. | +| Someone with a KeePass export | A `.kdbx` file Custos exported (docs/KDBX.md) | Everything in it, with its one password (or key file): one Argon2id evaluation per guess | An export leaves the two-factor protection behind on purpose, to move to KeePassXC or as an offline backup. The app says so before it writes one. Factors and the Domi identity are never in it. | +| A hostile `.kdbx` file | An import the user starts | A refusal | Size, header, KDF and decompression limits are checked before any work; the XML parser takes no DTD; a panic on any input is a bug (docs/KDBX.md, "Limits"). | ## What is NOT protected