Compare commits

..

63 Commits

Author SHA1 Message Date
mnovak f622bd283c [repo] Merge: feature/licence (Domi licences: the domi-licence key, the strict payload parser, the licence grant; 0.21.0; PR #29) 2026-11-30 07:17:13 +01:00
mnovak 022b5da454 [repo] Lockfile: the workspace at 0.21.0 2026-11-30 07:16:41 +01:00
mnovak 553f13b265 [vault] Licences: the domi-licence key, the strict payload parser, the licence grant (0.21.0)
The key that signs Domi licences and revocation lists (Fundamentum docs/LICENCE.md, licence v1): Ed25519 under
the reserved id domi-licence, no scope, refused by every other signing path, signing plain Ed25519 over the exact
payload. The payload is parsed first, as the spec's strict parser does (section 2.4 steps 1-4 and 7, section 4.1),
and a malformed one is refused with the spec's code and no card. The licence grant (Mark's click) signs a licence
from licence-issue whose apps are on the allowlist, within 50 a day, without a card; anything else that is well
formed asks on a card, a revocation list always. Refused outright: a licence dated more than a day from this clock,
a licence id signed before (replay), a seq not above the highest signed (rollback), any other caller. The grant and
the log live in signing.licence, which older cores ignore; the key is an ordinary Ed25519 entry every core reads.

Not compiled or tested yet: the PC is over Mark's 90 % rule.
2026-11-28 21:47:14 +01:00
mnovak bf5becdc32 [repo] Merge: repo/cpal-1.0 (CPAL-1.0 from v0.20.0, MPL-2.0 before; PR #27) 2026-11-23 00:44:10 +01:00
mnovak 44452e3815 [extension] Licence: hold the popup credit for now (Mark's rule: a credit only where the app's own repo is public; asked of him)
This reverts commit 987d49c.
2026-11-23 00:30:40 +01:00
mnovak 987d49c116 [extension] Licence: the Exhibit B credit in the popup's foot (CPAL-1.0 §14), exactly as DOMI_ATTRIBUTION_TEXT 2026-11-23 00:25:06 +01:00
mnovak b942c24077 [repo] Licence: CPAL-1.0 from v0.20.0, with the Exhibit B credit; versions before stay MPL-2.0
Mark's decision of 2026-11-23 for every public Domi repository. LICENSE is domi-licence's template with only
{ORIGINAL_CODE} = CustosPublic; the workspace licence is CPAL-1.0; the README says versions up to v0.19.1 stay
available under MPL-2.0 to those who received them and that redistributors show the credit. The EFF wordlist keeps
CC BY 3.0 US.
2026-11-23 00:06:03 +01:00
mnovak a3b3a32745 [repo] Merge: fix/android-grant-compat (a key the Android grant makes is standing-granted; v0.19.1, PR #26) 2026-11-21 09:07:02 +01:00
mnovak 0eee7632ae [vault] Signing: a key the Android grant makes is standing-granted, a value older cores read; v0.19.1
0.19.0 wrote a new security action, android-key-made, which every older core refuses. The phone app and the
web vault open the same vault with their own pinned core, so a vault in which the grant made a key would stop
opening there. The key's creation is now standing-granted with 'Android grant made <id> for <repo> pipeline
release'; the grant itself is a member older cores ignore.
2026-11-21 09:06:35 +01:00
mnovak 6588461438 [repo] Merge: feature/android-grant (the Android grant: every Domi app's release APK and its key on first use; v0.19.0, PR #25) 2026-11-21 08:58:25 +01:00
mnovak e533a38883 [vault] Signing: the Android grant, one answer for every Domi app's release APK and its key on first use; v0.19.0
signing.android: patterns owner/name or owner/*, the certificate's O and C, uses, last used and the keys it
made. A request fits when it is an apk from this PC's pipe with a run, pipeline release, a covered repository,
and that repository's own app key (<name>-android, scoped to exactly it and release, role release), while
card-signing is not ticked; a key's first signature fits. android_grant_make_key makes that key for a covered
repository (android-key-made in the security audit). Granting and revoking write standing-granted and
standing-revoked. A vault whose grant made a key needs core 0.19.0; older cores drop the grant itself.
2026-11-21 08:57:48 +01:00
mnovak 47146a6ea2 [repo] Merge: fix/team-review (deployment ticket on target.request, unknown author under others, refuse after sign; v0.18.1, PR #24) 2026-11-17 12:45:27 +01:00
mnovak 98d56f4673 [team] Review fixes: a deployment ticket and a MAC on target.request, an unknown author is unsatisfiable under others, a signed request cannot be refused afterwards; TEAM.md limits; v0.18.1 2026-11-17 12:44:54 +01:00
mnovak f95c768bfa [repo] Merge: feature/team-vault (team vaults, policies, sign.request, proofs, cosign and Tauri envelopes; v0.18.0, PR #23) 2026-11-17 12:21:44 +01:00
mnovak 3bb05bf6f1 [team] Team vaults: rustfmt on the files this change touches 2026-11-17 12:15:18 +01:00
mnovak e3ede760bd [team] Team vaults: member keys, member slots (kind 6), policies per environment, the canonical sign.request, approval statements, policy proofs; cosign and Tauri updater envelopes; v0.18.0 2026-11-17 11:38:41 +01:00
mnovak 9b40c834dd [repo] Merge: feature/approval-25h (a deploy approval may expire up to 25 hours ahead; v0.17.1, PR #22) 2026-11-14 17:51:37 +01:00
mnovak f84ac575bd [sign] Approval: a deploy approval may expire up to 25 hours ahead (was an hour), so a release's day-long card can still be signed; v0.17.1 2026-11-14 17:12:20 +01:00
mnovak ff14c8902f [repo] Merge: feature/recovery-key (the recovery key: one per two-factor vault, taken only by Vault::recover; v0.17.0, PR #21) 2026-11-12 23:09:31 +01:00
mnovak 2b4a78644b [vault] The recovery key is printed as 8 groups of 8 2026-11-12 23:09:02 +01:00
mnovak 8d5d08afcb [vault] The recovery key: one per two-factor vault, returned once, taken only by Vault::recover, which replaces every factor and the key (slot kind 5, three audit actions); v0.17.0 2026-11-12 13:24:00 +01:00
mnovak 61b98ee9b0 [repo] Merge: fix/standing-count (a standing approval's use count saturates; v0.16.1, PR #20) 2026-11-11 16:19:54 +01:00
mnovak 2c2d56b856 [vault] Standing approvals: a rule's use count saturates instead of overflowing (a stored count at its end made the next standing signature panic in debug builds); v0.16.1 2026-11-11 16:19:35 +01:00
mnovak 95613f4ed0 [repo] Merge: feature/standing-approval (standing approvals: always allow for one repository, key, kind, pipeline and origin; the outcome standing; v0.16.0, PR #19) 2026-11-11 16:13:04 +01:00
mnovak 2d04f32f57 [vault] Standing approvals: a rule Mark grants from a card (repository, key, kind, pipeline, origin; an approval's targets), signed without asking as outcome standing, counted, revocable, paused by card-signing; never a key's first signature or a mailbox release signature; v0.16.0 2026-11-11 16:02:14 +01:00
mnovak 1292c09d02 [repo] Merge: feature/browser-ext-v2 (autofill for Edge and Chrome: custos-browser, custos-native, the MV3 extension, docs/BROWSER.md; v0.15.0, PR #18) 2026-11-10 21:50:00 +01:00
mnovak a45d1054f0 [browser] Docs: docs/BROWSER.md (the pieces, which login goes where, the messages, registration, threat model); v0.15.0 2026-11-09 08:55:55 +01:00
mnovak 4e8fb6a8f5 [browser] Autofill for Edge and Chrome: custos-browser (which login fits which page, native messaging frames), custos-native (the host), the MV3 extension 2026-11-09 08:54:08 +01:00
mnovak aa5b692651 [repo] Merge: fix/android-sets (an Android key never counts as the release or test set; v0.14.1, PR #17) 2026-11-08 00:56:35 +01:00
mnovak 6f4075f7e3 [vault] Android: an Android key never counts as the release or test set (signing_create, signing_add_approve); v0.14.1 2026-11-08 00:56:18 +01:00
mnovak 54ce09ce61 [repo] Merge: feature/apk-signing (the android key kind and the apk sign kind for Postea's APKs; v0.14.0, PR #16) 2026-11-08 00:33:11 +01:00
mnovak 045f1f5d00 [vault] Android: the android key kind (RSA-4096, self-signed, 100 years) and the apk sign kind (1-4 SHA-512 digests, PKCS#1 v1.5), never unattended; v0.14.0 2026-11-08 00:27:47 +01:00
mnovak 82698bd9e5 [repo] Merge: feature/hands-off (take over a machine-key vault, the hands-off items, notes and rules; v0.13.0, PR #15) 2026-11-05 11:02:15 +01:00
mnovak 68a1f1344d [vault] Hands off: take_over a machine-key vault, the no-auto-connect, no-unattended and card-signing items, notes with a detail, the unattended rules; v0.13.0 2026-11-05 11:01:35 +01:00
mnovak ac69cf4638 [repo] Merge: feature/runs-core (deploy approvals with domi-approve, the security member, display offers; v0.12.0, PR #14) 2026-11-04 21:09:17 +01:00
mnovak 65c87186d6 [repo] Version: 0.12.0 (deploy approvals with domi-approve, the security member, display offers) 2026-11-04 20:56:49 +01:00
mnovak 7f90f952f0 [vault] Security: the security body member (Setup window, checklist, kept scope, append-only audit of 5 000; level and card rules); docs/FORMAT.md with the values older cores refuse 2026-11-04 20:55:47 +01:00
mnovak 12a5ba31d8 [vault] Provision: display offers (store display, outcome confirmed; display stores nothing, confirmed only for a display offer) 2026-11-04 20:55:46 +01:00
mnovak 8a10c695c5 [vault] Approval: sign kind approval only by domi-approve (made with the release keys, signing_add_approve for older vaults), run on requests and in the audit, context version, signing_check_at; docs/SIGNING.md 2026-11-04 20:50:49 +01:00
mnovak 6739423f4d [sign] Approval: canonical deploy approvals (parse, rewrite, byte-compare; run, names, commit, targets, expiry within an hour) signed as prehashed minisign approval-<run>.json 2026-11-04 20:45:08 +01:00
mnovak 8660b887c1 [repo] Merge: feature/provisio-core (Provisio: a kept seal recipient, the provision audit; v0.11.0, PR #13) 2026-11-04 14:01:58 +01:00
mnovak 23a8878f32 [repo] Version: 0.11.0 (Provisio: a kept seal recipient, the provision audit) 2026-11-04 14:00:28 +01:00
mnovak 37634f0d26 [vault] Provision: the provision audit body member (checked entries, no value member, append-only, newest 5 000; docs/FORMAT.md) 2026-11-04 14:00:28 +01:00
mnovak 76a94b0d11 [seal] Recipient: a kept key (from_secret refuses a known key, secret_bytes for DPAPI storage), Debug redacted; docs/SEAL.md 2026-11-04 13:55:47 +01:00
mnovak 4e386e8113 [repo] Merge: feature/domi-revoke (Domi identity: restore, revocation signing, backup secret; v0.10.0, PR #12) 2026-11-04 09:22:31 +01:00
mnovak 92ab8a0d63 [vault] Identity: restore from the 24 words, revocation signing for revoked keys only, the backup secret (docs/IDENTITY.md; v0.10.0) 2026-11-04 09:21:11 +01:00
mnovak bf661a7338 [repo] Merge: feature/signing (signing keys for Artifex: custos-sign, the signing body member, the audit log; v0.9.0, PR #11) 2026-11-04 00:45:11 +01:00
mnovak 510d5eecd1 [repo] Undo cargo fmt churn in files this branch does not change; CLAUDE.md: the trap 2026-11-04 00:27:37 +01:00
mnovak 06410ab3be [vault] Signing: the signing body member (release and test key sets, scope, sign-only API, append-only audit log); custos-sign draws from SysRng; the wasm build links getrandom 0.2 to the browser CSPRNG 2026-11-04 00:26:11 +01:00
mnovak cd2963392d [vault] Signing: mandatory tests for scope, refusals and the audit log through a reopen 2026-11-04 00:26:11 +01:00
mnovak 59fdfa26ef [sign] custos-sign: minisign (prehashed), SHA256SUMS, Authenticode digests, the household CA; tools/signing/interop.ps1 2026-11-04 00:15:33 +01:00
mnovak 6c6ffd33c0 [sign] Tests: known answers from the real minisign 0.12 and openssl, the household CA, canonical manifests 2026-11-04 00:15:33 +01:00
mnovak 2a146f342d [vault] Signing: docs/SIGNING.md (keys, signature kinds, audit log) and the FORMAT.md member, before the code 2026-11-04 00:09:05 +01:00
mnovak 38c458d21b [repo] Merge: feature/kdbx (KeePass import and export: custos-kdbx, KDBX 3.1/4 read, KDBX 4 write; v0.8.0, PR #10) 2026-11-03 23:11:50 +01:00
mnovak 2c333390c5 [repo] Git: shell scripts keep LF line endings 2026-11-03 20:59:44 +01:00
mnovak c011463fe5 [kdbx] custos-kdbx: KDBX 3.1/4 reader, KDBX 4 writer, item mapping, KeePassXC test vectors and interop check; v0.8.0 2026-11-03 20:59:40 +01:00
mnovak 12fd17245b [vault] Items: optional folder and attachments (SecretBytes), for KeePass groups and files 2026-11-03 20:59:39 +01:00
mnovak 05ac32dfc3 [kdbx] Docs: KeePass import (KDBX 3.1, 4) and export (KDBX 4), the item mapping, limits, what does not survive 2026-11-03 20:59:39 +01:00
mnovak 73d9de2304 [repo] Merge: feature/domi-identity (the Domi identity's root key in the vault, domi_pair, PR #9) 2026-11-03 19:04:24 +01:00
mnovak 6c696ba3a6 [wasm] Domi pairing: seal a phone's device key and label to the waiting PC; v0.7.0 2026-11-03 18:54:09 +01:00
mnovak 1c4bf4b373 [vault] Identity: the Domi root key in the vault, mnemonic typestate, signs only certs 2026-11-03 18:52:10 +01:00
mnovak 680b66cff7 [vault] Identity: docs/IDENTITY.md and the mandatory tests, before the code 2026-11-03 18:52:01 +01:00
mnovak 6e4da02351 [repo] Merge: feature/web-factors (two factors in the browser, phone pairing, factors apart, PR #8) 2026-11-03 15:28:30 +01:00
103 changed files with 18711 additions and 411 deletions
+2
View File
@@ -1,2 +1,4 @@
# Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md).
crates/custos-gen/wordlists/eff_large_wordlist.txt -text
*.sh text eol=lf
crates/custos-sign/tests/fixtures/** -text
+17 -2
View File
@@ -1,7 +1,7 @@
# Custos Domi — core (public)
Custos (Latin: guardian) is a local-first password and secret manager in the Domi ecosystem.
This repository is the **public, MPL-2.0 core**: everything that touches plaintext or keys.
This repository is the **public, CPAL-1.0 core** (MPL-2.0 before v0.20.0): everything that touches plaintext or keys.
The Windows app lives in the private `Custos` repo and depends on this one by git tag.
## Layout
@@ -12,14 +12,24 @@ crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS#
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing
crates/custos-team team vaults' pure parts: member keys, policy evaluation, sign.request, approval statements, proofs
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
crates/custos-browser which login belongs on which page (origins, no fuzzy matching), native messaging frames
crates/custos-native the browser extension's native messaging host: three ops, rebuilt, to custos.exe's pipe only
extension/ the MV3 extension for Edge and Chrome (fixed id jchkapmceepdnlhagfppeckggaecdcmn)
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
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
docs/BROWSER.md the browser extension: pieces, matching rule, messages, registration, threat model
docs/SIGNING.md release signing keys, kinds, standing approvals, the audit log
docs/TEAM.md team vaults (member slots, kind 6), policies, sign.request, proofs, cosign and Tauri envelopes
```
## Commands
@@ -40,10 +50,15 @@ 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`
first, then a test, then the code.
- Branch → PR on Gitea (token in `$GITEA_TOKEN`, never echoed) → self-review in the PR body → merge `--no-ff`
→ push → `git rev-parse HEAD origin/main` → tag `vX.Y.Z` (the private app pins tags).
## Known traps
- `cargo fmt --all` reformats files that are not rustfmt-clean on `main` (custos-keys, custos-seal, custos-wasm and
some tests): run `rustfmt --edition 2024 <file>` on the files you changed, so a PR carries no unrelated churn.
Generated
+309 -10
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aead"
version = "0.6.1"
@@ -12,6 +18,17 @@ dependencies = [
"inout 0.2.5",
]
[[package]]
name = "aes"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
dependencies = [
"cipher 0.5.2",
"cpubits",
"cpufeatures 0.3.1",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -28,12 +45,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
dependencies = [
"base64ct",
"blake2",
"blake2 0.11.0",
"cpufeatures 0.3.1",
"password-hash",
"zeroize",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -52,12 +75,42 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bip39"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
dependencies = [
"bitcoin_hashes",
"serde",
"unicode-normalization",
"zeroize",
]
[[package]]
name = "bitcoin_hashes"
version = "0.14.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bca4c7abb40c8817d77403c880988cfd484f23ab2365726afb2f798363e2c4a2"
dependencies = [
"hex-conservative",
]
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "blake2"
version = "0.11.0"
@@ -85,6 +138,24 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "block-padding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
dependencies = [
"hybrid-array",
]
[[package]]
name = "cbc"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
dependencies = [
"cipher 0.5.2",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -154,6 +225,12 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -172,6 +249,15 @@ dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-bigint"
version = "0.5.5"
@@ -241,9 +327,16 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "custos-browser"
version = "0.21.0"
dependencies = [
"zeroize",
]
[[package]]
name = "custos-gen"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -253,9 +346,30 @@ dependencies = [
"zeroize",
]
[[package]]
name = "custos-kdbx"
version = "0.21.0"
dependencies = [
"aes",
"argon2",
"cbc",
"chacha20",
"custos-vault",
"data-encoding",
"flate2",
"hmac 0.13.0",
"rand 0.10.3",
"roxmltree",
"salsa20",
"serde_json",
"sha2 0.11.1",
"thiserror",
"zeroize",
]
[[package]]
name = "custos-keys"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"custos-vault",
"ed25519-dalek",
@@ -266,13 +380,23 @@ dependencies = [
"thiserror",
]
[[package]]
name = "custos-native"
version = "0.21.0"
dependencies = [
"custos-browser",
"serde_json",
"windows-sys",
"zeroize",
]
[[package]]
name = "custos-qr"
version = "0.6.0"
version = "0.21.0"
[[package]]
name = "custos-seal"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"chacha20poly1305",
"hkdf",
@@ -285,7 +409,7 @@ dependencies = [
[[package]]
name = "custos-share"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"argon2",
"chacha20poly1305",
@@ -300,38 +424,86 @@ dependencies = [
"zeroize",
]
[[package]]
name = "custos-sign"
version = "0.21.0"
dependencies = [
"blake2 0.10.6",
"data-encoding",
"ed25519-dalek",
"minisign-verify",
"p256",
"rand 0.10.3",
"rand_core 0.6.4",
"rsa",
"serde",
"serde_json",
"sha2 0.10.9",
"thiserror",
"x509-cert",
"zeroize",
]
[[package]]
name = "custos-team"
version = "0.21.0"
dependencies = [
"custos-seal",
"custos-sign",
"data-encoding",
"ed25519-dalek",
"hmac 0.13.0",
"minisign-verify",
"rand 0.10.3",
"serde",
"serde_json",
"sha2 0.11.1",
"thiserror",
"zeroize",
]
[[package]]
name = "custos-totp"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"custos-vault",
"data-encoding",
"hmac 0.13.0",
"percent-encoding",
"sha1",
"sha1 0.11.0",
"sha2 0.11.1",
"zeroize",
]
[[package]]
name = "custos-vault"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"argon2",
"bip39",
"chacha20poly1305",
"custos-seal",
"custos-sign",
"custos-team",
"data-encoding",
"ed25519-dalek",
"hkdf",
"minisign-verify",
"rand 0.10.3",
"rsa",
"serde",
"serde_json",
"sha2 0.10.9",
"sha2 0.11.1",
"tempfile",
"thiserror",
"x509-cert",
"zeroize",
]
[[package]]
name = "custos-wasm"
version = "0.6.0"
version = "0.21.0"
dependencies = [
"custos-qr",
"custos-seal",
@@ -339,6 +511,7 @@ dependencies = [
"custos-totp",
"custos-vault",
"data-encoding",
"getrandom 0.2.17",
"getrandom 0.4.3",
"qrcode",
"serde",
@@ -359,10 +532,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid 0.9.6",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der_derive"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "digest"
version = "0.10.7"
@@ -478,6 +664,22 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "generic-array"
version = "0.14.9"
@@ -523,6 +725,15 @@ dependencies = [
"subtle",
]
[[package]]
name = "hex-conservative"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3fef046dca3ca91ee1408a8c1b80ab777e80a4d308d1bf4e7adb3fcb047e08"
dependencies = [
"arrayvec",
]
[[package]]
name = "hkdf"
version = "0.13.0"
@@ -574,6 +785,7 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
dependencies = [
"block-padding",
"hybrid-array",
]
@@ -616,6 +828,22 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "minisign-verify"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "num-bigint-dig"
version = "0.8.6"
@@ -903,6 +1131,15 @@ dependencies = [
"subtle",
]
[[package]]
name = "roxmltree"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
[[package]]
name = "rsa"
version = "0.9.10"
@@ -946,6 +1183,16 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "salsa20"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c"
dependencies = [
"cfg-if",
"cipher 0.5.2",
]
[[package]]
name = "sec1"
version = "0.7.3"
@@ -1009,6 +1256,17 @@ dependencies = [
"zmij",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
name = "sha1"
version = "0.11.0"
@@ -1052,6 +1310,12 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "smallvec"
version = "1.16.4"
@@ -1184,6 +1448,27 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tls_codec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
dependencies = [
"tls_codec_derive",
"zeroize",
]
[[package]]
name = "tls_codec_derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "typenum"
version = "1.20.1"
@@ -1254,6 +1539,20 @@ dependencies = [
"zeroize",
]
[[package]]
name = "x509-cert"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
dependencies = [
"const-oid 0.9.6",
"der",
"sha1 0.10.7",
"signature",
"spki",
"tls_codec",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
+8 -2
View File
@@ -3,9 +3,9 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.6.0"
version = "0.21.0"
edition = "2024"
license = "MPL-2.0"
license = "CPAL-1.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
[workspace.dependencies]
@@ -23,3 +23,9 @@ sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
# RSA-3072 key generation (custos-sign) takes minutes unoptimised; these keep `cargo test` usable.
[profile.dev.package.num-bigint-dig]
opt-level = 3
[profile.dev.package.rsa]
opt-level = 3
+140 -345
View File
@@ -1,373 +1,168 @@
Mozilla Public License Version 2.0
==================================
Common Public Attribution License Version 1.0 (CPAL)
1. Definitions
--------------
1. “Definitions”
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.0.1 “Commercial Use” means distribution or otherwise making the Covered Code available to a third party.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.1 “Contributor” means each entity that creates or contributes to the creation of Modifications.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.2 “Contributor Version” means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.3 “Covered Code” means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
1.4 “Electronic Distribution Mechanism” means a mechanism generally accepted in the software development community for the electronic transfer of data.
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
1.5 “Executable” means Covered Code in any form other than Source Code.
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6 “Initial Developer” means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7 “Larger Work” means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8 “License” means this document.
1.8. "License"
means this document.
1.8.1 “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.9 “Modifications” means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is:
1.10. "Modifications"
means any of the following:
A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
B. Any new file that contains any part of the Original Code or previous Modifications.
(b) any new file in Source Code Form that contains any Covered
Software.
1.10 “Original Code” means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.10.1 “Patent Claims” means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.11 “Source Code” means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor’s choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.12 “You” (or “Your”) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, “You” includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. Source Code License.
2. License Grants and Conditions
--------------------------------
2.1 The Initial Developer Grant.
The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims:
2.1. Grants
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof).
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License.
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
(d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices.
2.2. Effective Date
2.2 Contributor Grant.
Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and
2.3. Limitations on Grant Scope
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code.
(d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor.
3. Distribution Obligations.
3.1 Application of License.
The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients’ rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5.
3.2 Availability of Source Code.
Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party.
3.3 Description of Modifications.
You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.
3.4 Intellectual Property Matters
(a) Third Party Claims. If Contributor has knowledge that a license under a third party’s intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled “LEGAL” which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained.
(b) Contributor APIs. If Contributor’s Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file.
(c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor’s Modifications are Contributor’s original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License.
3.5 Required Notices.
You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients’ rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
3.6 Distribution of Executable Versions.
You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients’ rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient’s rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer, Original Developer or any Contributor. You hereby agree to indemnify the Initial Developer, Original Developer and every Contributor for any liability incurred by the Initial Developer, Original Developer or such Contributor as a result of any such terms You offer.
3.7 Larger Works.
You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code.
4. Inability to Comply Due to Statute or Regulation.
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
5. Application of this License.
This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.
6. Versions of the License.
6.1 New Versions.
Socialtext, Inc. (“Socialtext”) may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.
6.2 Effect of New Versions.
Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Socialtext. No one other than Socialtext has the right to modify the terms applicable to Covered Code created under this License.
6.3 Derivative Works.
If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases “Socialtext”, “CPAL” or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the CPAL. (Filling in the name of the Initial Developer, Original Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)
7. DISCLAIMER OF WARRANTY.
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER, ORIGINAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
8. TERMINATION.
8.1 This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
8.2 If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer, Original Developer or a Contributor (the Initial Developer, Original Developer or Contributor against whom You file such action is referred to as “Participant”) alleging that:
(a) such Participant’s Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above.
(b) any software, hardware, or device, other than such Participant’s Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant.
8.3 If You assert a patent infringement claim against Participant alleging that such Participant’s Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.
8.4 In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination.
9. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ORIGINAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY’S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
10. U.S. GOVERNMENT END USERS.
The Covered Code is a “commercial item,” as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of “commercial computer software” and “commercial computer software documentation,” as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein.
11. MISCELLANEOUS.
This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys’ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License.
12. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer, Original Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer, Original Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
13. MULTIPLE-LICENSED CODE.
Initial Developer may designate portions of the Covered Code as Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the CPAL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A.
14. ADDITIONAL TERM: ATTRIBUTION
(a) As a modest attribution to the organizer of the development of the Original Code (“Original Developer”), in the hope that its promotional value may help justify the time, money and effort invested in writing the Original Code, the Original Developer may include in Exhibit B (“Attribution Information”) a requirement that each time an Executable and Source Code or a Larger Work is launched or initially run (which includes initiating a session), a prominent display of the Original Developer’s Attribution Information (as defined below) must occur on the graphic user interface employed by the end user to access such Covered Code (which may include display on a splash screen), if any. The size of the graphic image should be consistent with the size of the other elements of the Attribution Information. If the access by the end user to the Executable and Source Code does not create a graphic user interface for access to the Covered Code, this obligation shall not apply. If the Original Code displays such Attribution Information in a particular form (such as in the form of a splash screen, notice at login, an “about” display, or dedicated attribution area on user interface screens), continued use of such form for that Attribution Information is one way of meeting this requirement for notice.
(b) Attribution information may only include a copyright notice, a brief phrase, graphic image and a URL (“Attribution Information”) and is subject to the Attribution Limits as defined below. For these purposes, prominent shall mean display for sufficient duration to give reasonable notice to the user of the identity of the Original Developer and that if You include Attribution Information or similar information for other parties, You must ensure that the Attribution Information for the Original Developer shall be no less prominent than such Attribution Information or similar information for the other party. For greater certainty, the Original Developer may choose to specify in Exhibit B below that the above attribution requirement only applies to an Executable and Source Code resulting from the Original Code or any Modification, but not a Larger Work. The intent is to provide for reasonably modest attribution, therefore the Original Developer cannot require that You display, at any time, more than the following information as Attribution Information: (a) a copyright notice including the name of the Original Developer; (b) a word or one phrase (not exceeding 10 words); (c) one graphic image provided by the Original Developer; and (d) a URL (collectively, the “Attribution Limits”).
(c) If Exhibit B does not include any Attribution Information, then there are no requirements for You to display any Attribution Information of the Original Developer.
(d) You acknowledge that all trademarks, service marks and/or trade names contained within the Attribution Information distributed with the Covered Code are the exclusive property of their owners and may only be used with the permission of their owners, or under circumstances otherwise permitted by law or as expressly set out in this License.
15. ADDITIONAL TERM: NETWORK USE.
The term “External Deployment” means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.
EXHIBIT A. Common Public Attribution License Version 1.0.
"The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/license/cpal_1-0. The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B.
Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Original Code is CustosPublic.
The Original Developer is the Initial Developer.
The Initial Developer of the Original Code is Marek Novák. All portions of the code written by Marek Novák are Copyright (c) 2026. All Rights Reserved.
Contributor: none."
EXHIBIT B. Attribution Information
Attribution Copyright Notice: Copyright (c) 2026 Marek Novák
Attribution Phrase (not exceeding 10 words): Built on Domi
Attribution URL: https://aula.marek-novak.cz
Graphic Image as provided in the Covered Code, if any: none.
Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
+19 -1
View File
@@ -11,6 +11,8 @@ 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)) |
| `custos-browser`, `custos-native`, `extension/` | The Edge/Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.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).
@@ -19,4 +21,20 @@ for what it does and does not protect. Report vulnerabilities as described in [`
cargo test --workspace
```
Licence: MPL-2.0. The memorable-password words come from the EFF wordlist (CC BY 3.0 US), filtered with the ESDB/SCOWL English dictionary (see `crates/custos-gen/wordlists/SOURCES.md`).
## Licence
CustosPublic is licensed under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`), from v0.20.0 on: see
[LICENSE](LICENSE). Versions before this change (up to and including v0.19.1) stay available under MPL-2.0 to those
who received them under it.
**Attribution (Exhibit B).** Anyone who redistributes CustosPublic, or software built on it, must show this credit
where CPAL-1.0 §14 asks for it:
| | |
| :-- | :-- |
| Attribution Copyright Notice | Copyright (c) 2026 Marek Novák |
| Attribution Phrase | Built on Domi |
| Attribution URL | https://aula.marek-novak.cz |
| Graphic Image | none |
Third-party parts keep their own licences. The memorable-password words come from the EFF wordlist (CC BY 3.0 US), filtered with the ESDB/SCOWL English dictionary (see `crates/custos-gen/wordlists/SOURCES.md`).
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "custos-browser"
description = "Custos in the browser: which login may be filled into which page, and Chrome's native messaging frames"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
zeroize.workspace = true
+66
View File
@@ -0,0 +1,66 @@
//! Chrome's native messaging frames: a 32-bit length in native byte order (little-endian on every machine
//! Custos runs on), then that many bytes of UTF-8 JSON. Messages to the host are capped here at 64 KiB (the
//! desktop's pipe limit); Chrome itself refuses messages to the browser over 1 MB.
//!
//! Frames can hold a login's password: they are `Zeroizing`, so the bytes are wiped when dropped.
use std::io::{self, Read, Write};
use zeroize::Zeroizing;
/// The largest message the extension may send to the host.
pub const MAX_TO_HOST: usize = 64 * 1024;
/// The largest message Chrome accepts from a host.
pub const MAX_TO_BROWSER: usize = 1024 * 1024;
/// Reads one frame. `Ok(None)` when the browser closed the stream (the extension disconnected).
pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
let mut len = [0u8; 4];
match r.read_exact(&mut len) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
let n = u32::from_le_bytes(len) as usize;
if n > MAX_TO_HOST {
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
}
let mut buf = Zeroizing::new(vec![0u8; n]);
r.read_exact(&mut buf)?;
Ok(Some(buf))
}
/// Writes one frame and flushes it (Chrome reads frame by frame).
pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> {
if msg.len() > MAX_TO_BROWSER {
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
}
w.write_all(&(msg.len() as u32).to_le_bytes())?;
w.write_all(msg)?;
w.flush()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_round_trip_and_oversized_ones_are_refused() {
let mut out = Vec::new();
write_frame(&mut out, br#"{"op":"browser_status"}"#).unwrap();
write_frame(&mut out, b"{}").unwrap();
assert_eq!(&out[..4], &23u32.to_le_bytes());
let mut r = &out[..];
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), br#"{"op":"browser_status"}"#);
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), b"{}");
assert!(read_frame(&mut r).unwrap().is_none(), "end of stream is the extension going away");
// A length over the limit is refused before anything is allocated.
let big = ((MAX_TO_HOST + 1) as u32).to_le_bytes();
assert_eq!(read_frame(&mut &big[..]).unwrap_err().kind(), io::ErrorKind::InvalidData);
// A frame cut short is an error, not a short message.
let mut cut = 10u32.to_le_bytes().to_vec();
cut.extend_from_slice(b"{}");
assert!(read_frame(&mut &cut[..]).is_err());
assert!(write_frame(&mut Vec::new(), &vec![b' '; MAX_TO_BROWSER + 1]).is_err());
}
}
+281
View File
@@ -0,0 +1,281 @@
//! What the browser extension may fill where (docs/BROWSER.md). The extension and its native host live in
//! this public repository; the rules that decide which login goes into which page live here too, so the
//! desktop app and anyone reviewing the extension apply the same ones.
//!
//! - [`Origin`]: a page's origin as the browser reports it (never as the page claims).
//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it,
//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains
//! (`paypa1.com`, `paypal.com.evil.net`) never match.
//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON).
//!
//! ```
//! use custos_browser::{login_matches, Origin};
//! let page = Origin::parse("https://accounts.github.com/login?return=/")?;
//! assert!(login_matches("https://github.com", &page).is_some());
//! assert!(login_matches("https://github.com.evil.net", &page).is_none());
//! # Ok::<(), custos_browser::OriginError>(())
//! ```
pub mod framing;
use std::fmt;
/// A page's origin: scheme, host (lowercase, no trailing dot) and port (the scheme's default when absent).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Origin {
pub scheme: Scheme,
pub host: String,
pub port: u16,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scheme {
Https,
Http,
}
impl Scheme {
fn default_port(self) -> u16 {
match self {
Scheme::Https => 443,
Scheme::Http => 80,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum OriginError {
/// Not an `http(s)://host…` URL.
NotWeb,
/// A host that is empty, too long or has characters a host cannot have.
BadHost,
BadPort,
}
impl fmt::Display for OriginError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
OriginError::NotWeb => "not a web address",
OriginError::BadHost => "not a valid host",
OriginError::BadPort => "not a valid port",
})
}
}
impl std::error::Error for OriginError {}
/// Splits `scheme://host:port/…` (userinfo refused: `https://bank.com@evil.net` must not read as bank.com).
fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u16>), OriginError> {
let url = url.trim();
let (scheme, rest) = match url.split_once("://") {
Some((s, rest)) => match s.to_ascii_lowercase().as_str() {
"https" => (Scheme::Https, rest),
"http" => (Scheme::Http, rest),
_ => return Err(OriginError::NotWeb),
},
None => (default.ok_or(OriginError::NotWeb)?, url),
};
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
if authority.contains('@') {
return Err(OriginError::BadHost);
}
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
let (h, after) = v6.split_once(']').ok_or(OriginError::BadHost)?;
(format!("[{}]", h.to_ascii_lowercase()), after.strip_prefix(':'))
} else {
match authority.rsplit_once(':') {
Some((h, p)) => (h.to_ascii_lowercase(), Some(p)),
None => (authority.to_ascii_lowercase(), None),
}
};
let host = host.trim_end_matches('.').to_string();
let ok = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '[' | ']' | ':');
if host.is_empty() || host.len() > 253 || !host.chars().all(ok) || host.contains("..") {
return Err(OriginError::BadHost);
}
let port = match port {
None | Some("") => None,
Some(p) => Some(
p.parse::<u16>()
.map_err(|_| OriginError::BadPort)
.and_then(|n| if n == 0 { Err(OriginError::BadPort) } else { Ok(n) })?,
),
};
Ok((scheme, host, port))
}
impl Origin {
/// A page URL as the browser reports it (`sender.url`, the tab's URL).
pub fn parse(url: &str) -> Result<Origin, OriginError> {
let (scheme, host, port) = split(url, None)?;
Ok(Origin { scheme, port: port.unwrap_or(scheme.default_port()), host })
}
fn is_loopback(&self) -> bool {
self.host == "localhost"
|| self.host.ends_with(".localhost")
|| self.host == "127.0.0.1"
|| self.host == "[::1]"
}
fn is_ip(&self) -> bool {
self.host.starts_with('[')
|| self.host.split('.').all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
}
/// May a login be filled into this page at all? Only over https, or plain http on this machine.
pub fn fillable(&self) -> bool {
self.scheme == Scheme::Https || self.is_loopback()
}
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let scheme = match self.scheme {
Scheme::Https => "https",
Scheme::Http => "http",
};
if self.port == self.scheme.default_port() {
write!(f, "{scheme}://{}", self.host)
} else {
write!(f, "{scheme}://{}:{}", self.host, self.port)
}
}
}
/// How well a login's URL fits a page, best first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Match {
/// The page is on the login's host itself (`www.` counts as the host).
Exact,
/// The page is on a subdomain of the login's host (`accounts.github.com` for `github.com`).
Subdomain,
}
/// Does the login stored with `item_url` belong on `page`? `None` when it must not be offered there.
///
/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes
/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and
/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for
/// an IP address matches only that exact host.
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
if !page.fillable() {
return None;
}
let (scheme, host, port) = split(item_url, Some(Scheme::Https)).ok()?;
if scheme != page.scheme || port.unwrap_or(scheme.default_port()) != page.port {
return None;
}
let strip = |h: &str| h.strip_prefix("www.").map(str::to_string).unwrap_or_else(|| h.to_string());
let (item, at) = (strip(&host), strip(&page.host));
if item == at {
return Some(Match::Exact);
}
if page.is_ip() || !item.contains('.') || item.starts_with('[') {
return None;
}
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
}
/// The best match among a login's URLs.
pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) -> Option<Match> {
urls.into_iter().filter_map(|u| login_matches(u, page)).min()
}
#[cfg(test)]
mod tests {
use super::*;
fn page(u: &str) -> Origin {
Origin::parse(u).unwrap()
}
#[test]
fn origins_parse_as_the_browser_reports_them() {
assert_eq!(
page("https://GitHub.com./login?x=1#y"),
Origin { scheme: Scheme::Https, host: "github.com".into(), port: 443 }
);
assert_eq!(page("http://localhost:5173/").port, 5173);
assert_eq!(page("https://[::1]:8443/").host, "[::1]");
assert_eq!(page("https://bank.cz").to_string(), "https://bank.cz");
assert_eq!(page("http://127.0.0.1:8080/a").to_string(), "http://127.0.0.1:8080");
for bad in [
"ftp://x.cz",
"file:///C:/a.html",
"chrome-extension://abc/",
"javascript:alert(1)",
"about:blank",
"https://",
"https://a..b.cz/",
"https://bank.cz:99999/",
"https://bank.cz:0/",
"https://bad host.cz/",
] {
assert!(Origin::parse(bad).is_err(), "{bad}");
}
// Userinfo is refused outright: it is how look-alike links hide their real host.
assert_eq!(Origin::parse("https://bank.cz@evil.net/"), Err(OriginError::BadHost));
}
#[test]
fn a_login_matches_its_host_and_its_subdomains_only() {
let gh = page("https://github.com/login");
assert_eq!(login_matches("https://github.com", &gh), Some(Match::Exact));
assert_eq!(login_matches("github.com/login", &gh), Some(Match::Exact), "no scheme means https");
assert_eq!(login_matches("https://www.github.com/", &gh), Some(Match::Exact));
assert_eq!(login_matches("https://github.com", &page("https://www.github.com/")), Some(Match::Exact));
assert_eq!(login_matches("https://github.com", &page("https://gist.github.com/")), Some(Match::Subdomain));
// A login for a subdomain does not go to its parent or its siblings.
assert_eq!(login_matches("https://gist.github.com", &gh), None);
assert_eq!(login_matches("https://gist.github.com", &page("https://api.github.com/")), None);
// Look-alikes never match.
for evil in [
"https://github.com.evil.net/",
"https://evilgithub.com/",
"https://github.co/",
"https://githuh.com/",
"https://xn--gthub-cta.com/",
] {
assert_eq!(login_matches("https://github.com", &page(evil)), None, "{evil}");
}
}
#[test]
fn scheme_port_and_plain_http_are_strict() {
// Never over plain http on the internet, even for a login saved with http.
assert_eq!(login_matches("http://intranet.example", &page("http://intranet.example/")), None);
// On this machine plain http is fine, with the port the login names.
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:5173/login")), Some(Match::Exact));
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:8080/")), None);
assert_eq!(login_matches("http://localhost", &page("http://localhost:8080/")), None);
// An https login does not go to the http page of the same host, nor the other way round.
assert_eq!(login_matches("https://localhost", &page("http://localhost/")), None);
assert_eq!(
login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa:5001/")),
Some(Match::Exact)
);
assert_eq!(login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa/")), None);
}
#[test]
fn bare_names_and_addresses_match_exactly_only() {
assert_eq!(login_matches("https://192.168.1.1", &page("https://192.168.1.1/")), Some(Match::Exact));
assert_eq!(login_matches("https://168.1.1", &page("https://192.168.1.1/")), None);
assert_eq!(login_matches("https://cz", &page("https://bank.cz/")), None);
assert_eq!(login_matches("https://[::1]", &page("https://[::1]/")), Some(Match::Exact));
assert_eq!(login_matches("not a url at all", &page("https://bank.cz/")), None);
assert_eq!(login_matches("", &page("https://bank.cz/")), None);
}
#[test]
fn the_best_of_several_urls_wins() {
let p = page("https://www.github.com/");
assert_eq!(best_match(["https://gitlab.com", "https://github.com"], &p), Some(Match::Exact));
assert_eq!(best_match(["https://gitlab.com"], &p), None);
assert_eq!(
best_match(["https://github.com", "https://www.github.com"], &page("https://gist.github.com/")),
Some(Match::Subdomain)
);
}
}
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "custos-kdbx"
description = "KeePass KDBX 4 import and export for Custos: the file format and the item mapping"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
aes = "0.9"
cbc = { version = "0.2", features = ["alloc", "block-padding"] }
chacha20 = "0.10"
salsa20 = "0.11"
argon2.workspace = true
hmac.workspace = true
sha2.workspace = true
zeroize.workspace = true
rand.workspace = true
thiserror.workspace = true
data-encoding.workspace = true
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
roxmltree = { version = "0.21", default-features = false, features = ["std"] }
[dev-dependencies]
serde_json.workspace = true
+41
View File
@@ -0,0 +1,41 @@
//! A dev tool for the KeePassXC interop check (tools/kdbx/interop.sh). The password comes from
//! `KDBX_PASSWORD`, never from the command line.
//!
//! ```text
//! kdbx_tool new OUT [fast] an empty KDBX 4 database (fast: Argon2id 1 MiB, 2 passes)
//! kdbx_tool roundtrip IN OUT IN → Custos items → OUT, as the app's import and export do
//! kdbx_tool items IN the Custos items IN maps to, as JSON (test databases only: it prints secrets)
//! ```
use custos_kdbx::{Database, Kdf, Key, SecretString, WriteOptions, from_items, read, to_items, write};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let password = SecretString::new(std::env::var("KDBX_PASSWORD").expect("set KDBX_PASSWORD"));
let key = Key { password: Some(&password), key_file: None };
let open = |path: &str| read(&std::fs::read(path).expect("read"), &key).unwrap_or_else(|e| panic!("{path}: {e}"));
match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
["new", out, ref rest @ ..] => {
let mut opts = WriteOptions::default();
if rest == ["fast"] {
opts.kdf = Kdf::Argon2id { m_kib: 1024, t: 2, p: 1 };
}
let db = Database { name: "Interop".into(), ..Default::default() };
std::fs::write(out, write(&db, &key, opts).expect("write")).expect("write file");
}
["roundtrip", input, out] => {
let db = open(input);
let items = to_items(&db);
let back = from_items(&items, &db.name);
std::fs::write(out, write(&back, &key, WriteOptions::default()).expect("write")).expect("write file");
eprintln!("{} items", items.len());
}
["items", input] => {
println!("{}", serde_json::to_string_pretty(&to_items(&open(input))).expect("json"));
}
_ => {
eprintln!("usage: kdbx_tool new OUT [fast] | roundtrip IN OUT | items IN");
std::process::exit(2);
}
}
}
+220
View File
@@ -0,0 +1,220 @@
//! The only module that calls the cryptographic crates: the composite key, key files, the KDFs, the
//! outer ciphers, the HMAC block keys and the inner stream (docs/KDBX.md, "Reading").
use crate::{Error, Key};
use aes::Aes256;
use aes::cipher::{BlockCipherEncrypt, BlockModeDecrypt, BlockModeEncrypt, KeyInit, KeyIvInit, StreamCipher};
use cbc::cipher::block_padding::Pkcs7;
use chacha20::ChaCha20;
use hmac::{Hmac, Mac};
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use sha2::{Digest, Sha256, Sha512};
use zeroize::Zeroizing;
pub(crate) type K32 = Zeroizing<[u8; 32]>;
pub(crate) type K64 = Zeroizing<[u8; 64]>;
pub(crate) fn fill_random(buf: &mut [u8]) {
UnwrapErr(SysRng).fill_bytes(buf);
}
pub(crate) fn sha256(parts: &[&[u8]]) -> K32 {
let mut h = Sha256::new();
for p in parts {
h.update(p);
}
Zeroizing::new(h.finalize().into())
}
pub(crate) fn sha512(parts: &[&[u8]]) -> K64 {
let mut h = Sha512::new();
for p in parts {
h.update(p);
}
Zeroizing::new(h.finalize().into())
}
/// SHA-256 over each key part's 32-byte form, concatenated (KeePass's composite key).
pub(crate) fn composite(key: &Key) -> Result<K32, Error> {
let mut parts: Vec<K32> = Vec::new();
if let Some(p) = key.password.filter(|p| !p.is_empty()) {
parts.push(sha256(&[p.expose().as_bytes()]));
}
if let Some(f) = key.key_file {
parts.push(key_file(f)?);
}
if parts.is_empty() {
return Err(Error::NoKey);
}
let refs: Vec<&[u8]> = parts.iter().map(|p| p.as_slice()).collect();
Ok(sha256(&refs))
}
/// A key file's 32-byte key: KeePass XML 2.0 or 1.0, 32 raw bytes, 64 hex digits, or SHA-256 of the file.
pub(crate) fn key_file(f: &[u8]) -> Result<K32, Error> {
let head = &f[..f.len().min(256)];
if head.windows(8).any(|w| w == b"<KeyFile") {
return xml_key_file(f);
}
if f.len() == 32 {
let mut k = Zeroizing::new([0u8; 32]);
k.copy_from_slice(f);
return Ok(k);
}
if f.len() == 64
&& f.iter().all(u8::is_ascii_hexdigit)
&& let Ok(b) = data_encoding::HEXLOWER_PERMISSIVE.decode(f)
{
let mut k = Zeroizing::new([0u8; 32]);
k.copy_from_slice(&b);
return Ok(k);
}
Ok(sha256(&[f]))
}
fn xml_key_file(f: &[u8]) -> Result<K32, Error> {
const BAD: Error = Error::Malformed("key file");
let text = std::str::from_utf8(f).map_err(|_| BAD)?;
let doc = roxmltree::Document::parse_with_options(
text,
roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1000, ..Default::default() },
)
.map_err(|_| BAD)?;
let find = |name: &str| doc.descendants().find(|n| n.has_tag_name(name));
let version = find("Version").and_then(|n| n.text()).unwrap_or("").trim().to_owned();
let data = find("Data").ok_or(BAD)?;
let body: Zeroizing<String> = Zeroizing::new(data.text().unwrap_or("").split_whitespace().collect());
let bytes = Zeroizing::new(if version.starts_with("2.") {
let b = data_encoding::HEXUPPER_PERMISSIVE.decode(body.as_bytes()).map_err(|_| BAD)?;
if let Some(hash) = data.attribute("Hash") {
let want = data_encoding::HEXUPPER_PERMISSIVE.decode(hash.trim().as_bytes()).map_err(|_| BAD)?;
if sha256(&[&b])[..4] != want[..] {
return Err(Error::Malformed("key file checksum"));
}
}
b
} else if version.starts_with("1.") {
data_encoding::BASE64.decode(body.as_bytes()).map_err(|_| BAD)?
} else {
return Err(Error::Malformed("key file version"));
});
let k: [u8; 32] = bytes.as_slice().try_into().map_err(|_| BAD)?;
Ok(Zeroizing::new(k))
}
/// Argon2d or Argon2id. The caller has checked the parameters against the limits.
pub(crate) fn argon2(composite: &[u8], id: bool, salt: &[u8], m_kib: u32, t: u32, p: u32) -> Result<K32, Error> {
use argon2::{Algorithm, Argon2, Params, Version};
let params = Params::new(m_kib, t, p, Some(32)).map_err(|_| Error::UnsupportedKdf)?;
let alg = if id { Algorithm::Argon2id } else { Algorithm::Argon2d };
let mut out = Zeroizing::new([0u8; 32]);
Argon2::new(alg, Version::V0x13, params)
.hash_password_into(composite, salt, out.as_mut())
.map_err(|_| Error::UnsupportedKdf)?;
Ok(out)
}
/// AES-KDF: `rounds` AES-256-ECB encryptions of both halves keyed with `seed`, then SHA-256.
pub(crate) fn aes_kdf(composite: &[u8], seed: &[u8; 32], rounds: u64) -> K32 {
let cipher = Aes256::new(seed.into());
let mut blocks = Zeroizing::new([[0u8; 16]; 2]);
blocks[0].copy_from_slice(&composite[..16]);
blocks[1].copy_from_slice(&composite[16..32]);
for _ in 0..rounds {
for b in blocks.iter_mut() {
cipher.encrypt_block(b.into());
}
}
sha256(&[&blocks[0], &blocks[1]])
}
pub(crate) struct Keys {
pub cipher: K32,
hmac_base: K64,
}
impl Keys {
pub(crate) fn new(master_seed: &[u8], transformed: &[u8]) -> Self {
Keys { cipher: sha256(&[master_seed, transformed]), hmac_base: sha512(&[master_seed, transformed, &[1]]) }
}
fn block_key(&self, index: u64) -> K64 {
sha512(&[&index.to_le_bytes(), self.hmac_base.as_slice()])
}
pub(crate) fn header_hmac(&self, header: &[u8]) -> [u8; 32] {
mac(self.block_key(u64::MAX).as_slice(), &[header])
}
pub(crate) fn block_hmac(&self, index: u64, data: &[u8]) -> [u8; 32] {
mac(self.block_key(index).as_slice(), &[&index.to_le_bytes(), &(data.len() as u32).to_le_bytes(), data])
}
}
fn mac(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {
let mut m = <Hmac<Sha256>>::new_from_slice(key).expect("HMAC takes any key length");
for p in parts {
m.update(p);
}
m.finalize().into_bytes().into()
}
/// Constant-time comparison of two MACs.
pub(crate) fn same(a: &[u8; 32], b: &[u8]) -> bool {
b.len() == 32 && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
pub(crate) fn chacha20(key: &[u8; 32], nonce: &[u8; 12], data: &mut [u8]) {
ChaCha20::new(key.into(), nonce.into()).apply_keystream(data);
}
pub(crate) fn aes_cbc_decrypt(key: &[u8; 32], iv: &[u8; 16], data: &mut Vec<u8>) -> Result<(), Error> {
let n = cbc::Decryptor::<Aes256>::new(key.into(), iv.into())
.decrypt_padded::<Pkcs7>(data)
.map_err(|_| Error::Corrupted)?
.len();
data.truncate(n);
Ok(())
}
pub(crate) fn aes_cbc_encrypt(key: &[u8; 32], iv: &[u8; 16], data: &mut Vec<u8>) {
let len = data.len();
data.resize(len + 16 - len % 16, 0);
let n = cbc::Encryptor::<Aes256>::new(key.into(), iv.into())
.encrypt_padded::<Pkcs7>(data, len)
.expect("room for the padding")
.len();
data.truncate(n);
}
/// The inner stream that hides protected values.
pub(crate) enum InnerStream {
/// KDBX 4: ChaCha20 keyed from SHA-512 of the stream key.
ChaCha20(ChaCha20),
/// KDBX 3.1: Salsa20 keyed with SHA-256 of the stream key and KeePass's fixed nonce.
Salsa20(salsa20::Salsa20),
}
impl InnerStream {
pub(crate) fn chacha20(stream_key: &[u8]) -> Self {
let h = sha512(&[stream_key]);
let key = Zeroizing::new(<[u8; 32]>::try_from(&h[..32]).expect("32 bytes"));
let nonce: [u8; 12] = h[32..44].try_into().expect("12 bytes");
InnerStream::ChaCha20(ChaCha20::new((&*key).into(), (&nonce).into()))
}
pub(crate) fn salsa20(stream_key: &[u8]) -> Self {
const NONCE: [u8; 8] = [0xE8, 0x30, 0x09, 0x4B, 0x97, 0x20, 0x5D, 0x2A];
let key = sha256(&[stream_key]);
InnerStream::Salsa20(salsa20::Salsa20::new((&*key).into(), (&NONCE).into()))
}
pub(crate) fn apply(&mut self, data: &mut [u8]) {
match self {
InnerStream::ChaCha20(c) => c.apply_keystream(data),
InnerStream::Salsa20(c) => c.apply_keystream(data),
}
}
}
+568
View File
@@ -0,0 +1,568 @@
//! The outer KDBX 4 file: header, KDF parameters, HMAC blocks, payload cipher, gzip, inner header
//! (docs/KDBX.md, "Reading" and "Writing").
use crate::crypto::{self, InnerStream, K32, Keys};
use crate::{Database, Error, Key, xml};
use custos_vault::SecretBytes;
use std::io::{Read, Write};
use zeroize::Zeroizing;
const SIG1: [u8; 4] = [0x03, 0xD9, 0xA2, 0x9A];
const SIG2: [u8; 4] = [0x67, 0xFB, 0x4B, 0xB5];
const CIPHER_AES256: [u8; 16] = uuid(0x31c1f2e6_bf71_4350_be58_05216afc5aff);
const CIPHER_CHACHA20: [u8; 16] = uuid(0xd6038a2b_8b6f_4cb5_a524_339a31dbb59a);
const KDF_AES: [u8; 16] = uuid(0xc9d9f39a_628a_4460_bf74_0d08c18a4fea);
const KDF_ARGON2D: [u8; 16] = uuid(0xef636ddf_8c29_444b_91f7_a9a403e30a0c);
const KDF_ARGON2ID: [u8; 16] = uuid(0x9e298b19_56db_4773_b23d_fc3ec6f0a1e6);
const fn uuid(v: u128) -> [u8; 16] {
v.to_be_bytes()
}
const MAX_FILE: usize = 512 << 20;
const MAX_FIELD: usize = 64 << 10;
const MAX_PAYLOAD: u64 = 512 << 20;
const MAX_ARGON2_BYTES: u64 = 2 << 30;
const MAX_AES_ROUNDS: u64 = 1 << 30;
const BLOCK: usize = 1 << 20;
const STREAM_CHACHA20: u32 = 3;
/// The outer cipher an export uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cipher {
Aes256,
ChaCha20,
}
/// The key derivation an export uses. `m_kib` is Argon2's memory in KiB.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kdf {
Argon2d { m_kib: u32, t: u32, p: u32 },
Argon2id { m_kib: u32, t: u32, p: u32 },
Aes { rounds: u64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WriteOptions {
pub cipher: Cipher,
pub kdf: Kdf,
}
impl Default for WriteOptions {
/// ChaCha20 and Argon2id with the vault's own defaults (64 MiB, 20 passes, 1 lane).
fn default() -> Self {
WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 65_536, t: 20, p: 1 } }
}
}
struct Cur<'a> {
b: &'a [u8],
pos: usize,
}
impl<'a> Cur<'a> {
fn take(&mut self, n: usize, e: Error) -> Result<&'a [u8], Error> {
let end = self.pos.checked_add(n).filter(|&end| end <= self.b.len()).ok_or(e)?;
let s = &self.b[self.pos..end];
self.pos = end;
Ok(s)
}
fn u8(&mut self, e: Error) -> Result<u8, Error> {
Ok(self.take(1, e)?[0])
}
fn u32(&mut self, e: Error) -> Result<u32, Error> {
Ok(u32::from_le_bytes(self.take(4, e)?.try_into().expect("4 bytes")))
}
}
/// Opens a KDBX 4 file.
pub fn read(bytes: &[u8], key: &Key) -> Result<Database, Error> {
if bytes.len() > MAX_FILE {
return Err(Error::TooLarge);
}
if bytes.len() < 12 || bytes[..4] != SIG1 || bytes[4..8] != SIG2 {
return Err(Error::NotKdbx);
}
let minor = u16::from_le_bytes([bytes[8], bytes[9]]);
let major = u16::from_le_bytes([bytes[10], bytes[11]]);
match major {
4 => {}
3 => return read3(bytes, key),
_ => return Err(Error::UnsupportedVersion(major, minor)),
}
// The outer header.
let mut c = Cur { b: bytes, pos: 12 };
let (mut cipher, mut compression, mut seed, mut iv, mut kdf) = (None, None, None, None, None);
loop {
let id = c.u8(Error::Corrupted)?;
let len = c.u32(Error::Corrupted)? as usize;
if len > MAX_FIELD {
return Err(Error::Malformed("header field too long"));
}
let data = c.take(len, Error::Corrupted)?;
match id {
0 => break,
2 => cipher = Some(data),
3 => compression = Some(u32::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("compression"))?)),
4 => seed = Some(data),
7 => iv = Some(data),
11 => kdf = Some(data),
_ => {} // public custom data, and KDBX 3 fields that mean nothing here
}
}
let header = &bytes[..c.pos];
let hash = c.take(32, Error::Corrupted)?;
let hmac = c.take(32, Error::Corrupted)?;
if crypto::sha256(&[header])[..] != hash[..] {
return Err(Error::Corrupted);
}
let cipher = match cipher.ok_or(Error::Malformed("no cipher"))? {
c if c == CIPHER_AES256 => Cipher::Aes256,
c if c == CIPHER_CHACHA20 => Cipher::ChaCha20,
_ => return Err(Error::UnsupportedCipher),
};
let seed = seed.filter(|s| s.len() == 32).ok_or(Error::Malformed("master seed"))?;
let (kdf, salt) = parse_kdf(kdf.ok_or(Error::Malformed("no KDF parameters"))?)?;
// The key, checked against the header before anything is decrypted.
let transformed = transform(&crypto::composite(key)?, kdf, &salt)?;
let keys = Keys::new(seed, transformed.as_slice());
if !crypto::same(&keys.header_hmac(header), hmac) {
return Err(Error::WrongKey);
}
// HMAC blocks.
let mut payload = Vec::new();
for index in 0u64.. {
let mac = c.take(32, Error::Corrupted)?;
let len = c.u32(Error::Corrupted)? as usize;
let data = c.take(len, Error::Corrupted)?;
if !crypto::same(&keys.block_hmac(index, data), mac) {
return Err(Error::Corrupted);
}
if len == 0 {
break;
}
payload.extend_from_slice(data);
}
let mut plain = Zeroizing::new(payload);
let iv = iv.ok_or(Error::Malformed("no IV"))?;
match cipher {
Cipher::Aes256 => {
let iv: &[u8; 16] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
crypto::aes_cbc_decrypt(&keys.cipher, iv, &mut plain)?;
}
Cipher::ChaCha20 => {
let iv: &[u8; 12] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
crypto::chacha20(&keys.cipher, iv, &mut plain);
}
}
let inner = match compression {
Some(0) => plain,
Some(1) => gunzip(&plain)?,
_ => return Err(Error::Malformed("compression")),
};
// The inner header.
let mut c = Cur { b: &inner, pos: 0 };
let (mut stream_id, mut stream_key) = (None, None);
let mut pool = Vec::new();
loop {
let id = c.u8(Error::Malformed("inner header"))?;
let len = c.u32(Error::Malformed("inner header"))? as usize;
let data = c.take(len, Error::Malformed("inner header"))?;
match id {
0 => break,
1 => stream_id = Some(u32::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("inner stream"))?)),
2 => stream_key = Some(data),
3 => {
let (_flags, content) = data.split_first().ok_or(Error::Malformed("attachment"))?;
pool.push(SecretBytes::from(content));
}
_ => {}
}
}
let stream_key = stream_key.filter(|k| !k.is_empty()).ok_or(Error::Malformed("inner stream"))?;
let mut stream = match stream_id {
Some(STREAM_CHACHA20) => InnerStream::chacha20(stream_key),
_ => return Err(Error::UnsupportedStream),
};
xml::parse(&inner[c.pos..], &mut stream, &pool)
}
/// KDBX 3.1: 16-bit header field lengths, AES-KDF from the header, no header HMAC (the first 32 bytes of the
/// payload must equal `StreamStartBytes` instead), SHA-256 hashed blocks, a Salsa20 inner stream, and the
/// attachments in `Meta/Binaries` (docs/KDBX.md, "KDBX 3.1").
fn read3(bytes: &[u8], key: &Key) -> Result<Database, Error> {
let mut c = Cur { b: bytes, pos: 12 };
let (mut cipher, mut compression, mut seed, mut iv) = (None, None, None, None);
let (mut tseed, mut rounds, mut stream_key, mut start, mut stream_id) = (None, None, None, None, None);
let u32_ = |d: &[u8]| d.try_into().map(u32::from_le_bytes).map_err(|_| Error::Malformed("header field"));
loop {
let id = c.u8(Error::Corrupted)?;
let len = u16::from_le_bytes(c.take(2, Error::Corrupted)?.try_into().expect("2 bytes")) as usize;
let data = c.take(len, Error::Corrupted)?;
match id {
0 => break,
2 => cipher = Some(data),
3 => compression = Some(u32_(data)?),
4 => seed = Some(data),
5 => tseed = Some(data),
6 => rounds = Some(u64::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("rounds"))?)),
7 => iv = Some(data),
8 => stream_key = Some(data),
9 => start = Some(data),
10 => stream_id = Some(u32_(data)?),
_ => {}
}
}
let cipher = match cipher.ok_or(Error::Malformed("no cipher"))? {
c if c == CIPHER_AES256 => Cipher::Aes256,
c if c == CIPHER_CHACHA20 => Cipher::ChaCha20,
_ => return Err(Error::UnsupportedCipher),
};
let seed = seed.filter(|s| s.len() == 32).ok_or(Error::Malformed("master seed"))?;
let tseed: &[u8; 32] = tseed.and_then(|s| s.try_into().ok()).ok_or(Error::UnsupportedKdf)?;
let kdf = Kdf::Aes { rounds: rounds.ok_or(Error::UnsupportedKdf)? };
check_kdf(kdf)?;
let start: &[u8; 32] = start.and_then(|s| s.try_into().ok()).ok_or(Error::Malformed("stream start bytes"))?;
let stream_key = stream_key.filter(|k| !k.is_empty()).ok_or(Error::Malformed("inner stream"))?;
let mut stream = match stream_id {
Some(2) => InnerStream::salsa20(stream_key),
Some(STREAM_CHACHA20) => InnerStream::chacha20(stream_key),
_ => return Err(Error::UnsupportedStream),
};
let transformed = transform(&crypto::composite(key)?, kdf, tseed)?;
let keys = Keys::new(seed, transformed.as_slice());
let mut plain = Zeroizing::new(bytes[c.pos..].to_vec());
let iv = iv.ok_or(Error::Malformed("no IV"))?;
match cipher {
Cipher::Aes256 => {
let iv: &[u8; 16] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
// A wrong key gives garbage, usually with broken padding: that is a wrong key, not damage.
crypto::aes_cbc_decrypt(&keys.cipher, iv, &mut plain).map_err(|_| Error::WrongKey)?;
}
Cipher::ChaCha20 => {
let iv: &[u8; 12] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
crypto::chacha20(&keys.cipher, iv, &mut plain);
}
}
if plain.len() < 32 || !crypto::same(start, &plain[..32]) {
return Err(Error::WrongKey);
}
// Hashed blocks: index (u32), SHA-256 (32), length (u32), data; a zero length ends them.
let mut c = Cur { b: &plain, pos: 32 };
let mut payload = Zeroizing::new(Vec::new());
for index in 0u32.. {
if c.u32(Error::Corrupted)? != index {
return Err(Error::Corrupted);
}
let hash = c.take(32, Error::Corrupted)?;
let len = c.u32(Error::Corrupted)? as usize;
if len == 0 {
if hash.iter().any(|&b| b != 0) {
return Err(Error::Corrupted);
}
break;
}
let data = c.take(len, Error::Corrupted)?;
if crypto::sha256(&[data])[..] != hash[..] {
return Err(Error::Corrupted);
}
payload.extend_from_slice(data);
}
let xml_bytes = match compression {
Some(0) => payload,
Some(1) => gunzip(&payload)?,
_ => return Err(Error::Malformed("compression")),
};
xml::parse(&xml_bytes, &mut stream, &[])
}
/// Writes a KDBX 4.0 file (docs/KDBX.md, "Writing").
pub fn write(db: &Database, key: &Key, opts: WriteOptions) -> Result<Vec<u8>, Error> {
let composite = crypto::composite(key)?;
let mut seed = [0u8; 32];
let mut salt = [0u8; 32];
let mut stream_key = Zeroizing::new([0u8; 64]);
crypto::fill_random(&mut seed);
crypto::fill_random(&mut salt);
crypto::fill_random(stream_key.as_mut());
let mut iv = vec![0u8; if opts.cipher == Cipher::Aes256 { 16 } else { 12 }];
crypto::fill_random(&mut iv);
check_kdf(opts.kdf)?;
let transformed = transform(&composite, opts.kdf, &salt)?;
let keys = Keys::new(&seed, transformed.as_slice());
let mut out = Vec::new();
out.extend_from_slice(&SIG1);
out.extend_from_slice(&SIG2);
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&4u16.to_le_bytes());
let cipher_id = if opts.cipher == Cipher::Aes256 { CIPHER_AES256 } else { CIPHER_CHACHA20 };
field(&mut out, 2, &cipher_id);
field(&mut out, 3, &1u32.to_le_bytes());
field(&mut out, 4, &seed);
field(&mut out, 7, &iv);
field(&mut out, 11, &kdf_dict(opts.kdf, &salt));
field(&mut out, 0, b"\r\n\r\n");
let hash = crypto::sha256(&[&out]);
let hmac = keys.header_hmac(&out);
out.extend_from_slice(hash.as_slice());
out.extend_from_slice(&hmac);
let mut stream = InnerStream::chacha20(stream_key.as_slice());
let mut pool: Vec<&SecretBytes> = Vec::new();
let body = xml::write(db, &mut stream, &mut pool);
let mut inner = Zeroizing::new(Vec::with_capacity(body.len() + 128));
field(&mut inner, 1, &STREAM_CHACHA20.to_le_bytes());
field(&mut inner, 2, stream_key.as_slice());
for a in pool {
let mut b = Zeroizing::new(Vec::with_capacity(a.len() + 1));
b.push(0);
b.extend_from_slice(a.expose());
field(&mut inner, 3, &b);
}
field(&mut inner, 0, &[]);
inner.extend_from_slice(body.as_bytes());
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&inner).expect("writing to memory");
let mut payload = gz.finish().expect("writing to memory");
match opts.cipher {
Cipher::Aes256 => crypto::aes_cbc_encrypt(&keys.cipher, iv.as_slice().try_into().expect("16"), &mut payload),
Cipher::ChaCha20 => crypto::chacha20(&keys.cipher, iv.as_slice().try_into().expect("12"), &mut payload),
}
let mut index = 0u64;
for chunk in payload.chunks(BLOCK).chain(std::iter::once(&[][..])) {
out.extend_from_slice(&keys.block_hmac(index, chunk));
out.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
out.extend_from_slice(chunk);
index += 1;
}
Ok(out)
}
fn field(out: &mut Vec<u8>, id: u8, data: &[u8]) {
out.push(id);
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out.extend_from_slice(data);
}
pub(crate) fn gunzip(data: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error> {
let mut out = Zeroizing::new(Vec::new());
flate2::read::GzDecoder::new(data).take(MAX_PAYLOAD + 1).read_to_end(&mut out).map_err(|_| Error::Corrupted)?;
if out.len() as u64 > MAX_PAYLOAD {
return Err(Error::TooLarge);
}
Ok(out)
}
fn transform(composite: &K32, kdf: Kdf, salt: &[u8]) -> Result<K32, Error> {
match kdf {
Kdf::Argon2d { m_kib, t, p } => crypto::argon2(composite.as_slice(), false, salt, m_kib, t, p),
Kdf::Argon2id { m_kib, t, p } => crypto::argon2(composite.as_slice(), true, salt, m_kib, t, p),
Kdf::Aes { rounds } => {
let seed: &[u8; 32] = salt.try_into().map_err(|_| Error::UnsupportedKdf)?;
Ok(crypto::aes_kdf(composite.as_slice(), seed, rounds))
}
}
}
fn check_kdf(kdf: Kdf) -> Result<(), Error> {
let ok = match kdf {
Kdf::Argon2d { m_kib, t, p } | Kdf::Argon2id { m_kib, t, p } => {
(1..=64).contains(&p)
&& (1..=1000).contains(&t)
&& u64::from(m_kib) * 1024 <= MAX_ARGON2_BYTES
&& m_kib >= 8 * p
}
Kdf::Aes { rounds } => (1..=MAX_AES_ROUNDS).contains(&rounds),
};
if ok { Ok(()) } else { Err(Error::UnsupportedKdf) }
}
// VariantDictionary value types.
const VD_U32: u8 = 0x04;
const VD_U64: u8 = 0x05;
const VD_BYTES: u8 = 0x42;
/// The KDF and its salt (Argon2 `S`) or seed (AES-KDF `S`), checked against the limits.
fn parse_kdf(d: &[u8]) -> Result<(Kdf, Vec<u8>), Error> {
const BAD: Error = Error::Malformed("KDF parameters");
let mut c = Cur { b: d, pos: 0 };
let version = u16::from_le_bytes(c.take(2, BAD)?.try_into().expect("2 bytes"));
if version & 0xFF00 != 0x0100 {
return Err(BAD);
}
let mut map: Vec<(&[u8], u8, &[u8])> = Vec::new();
loop {
let kind = c.u8(BAD)?;
if kind == 0 {
break;
}
let klen = c.u32(BAD)? as usize;
let k = c.take(klen, BAD)?;
let vlen = c.u32(BAD)? as usize;
let v = c.take(vlen, BAD)?;
map.push((k, kind, v));
}
let get = |name: &str, kind: u8| map.iter().find(|(k, t, _)| *k == name.as_bytes() && *t == kind).map(|e| e.2);
let u32_ = |name| get(name, VD_U32).and_then(|v| v.try_into().ok()).map(u32::from_le_bytes);
let u64_ = |name| get(name, VD_U64).and_then(|v| v.try_into().ok()).map(u64::from_le_bytes);
let id = get("$UUID", VD_BYTES).ok_or(BAD)?;
let salt = get("S", VD_BYTES).ok_or(Error::UnsupportedKdf)?.to_vec();
let kdf = if id == KDF_AES {
if salt.len() != 32 {
return Err(Error::UnsupportedKdf);
}
Kdf::Aes { rounds: u64_("R").ok_or(Error::UnsupportedKdf)? }
} else if id == KDF_ARGON2D || id == KDF_ARGON2ID {
let m = u64_("M").ok_or(Error::UnsupportedKdf)?;
let t = u64_("I").ok_or(Error::UnsupportedKdf)?;
let p = u32_("P").ok_or(Error::UnsupportedKdf)?;
let extra = |n| get(n, VD_BYTES).is_some_and(|v| !v.is_empty());
if u32_("V") != Some(0x13) || extra("K") || extra("A") || !(8..=64).contains(&salt.len()) {
return Err(Error::UnsupportedKdf);
}
if m % 1024 != 0 || m > MAX_ARGON2_BYTES || t > 1000 {
return Err(Error::UnsupportedKdf);
}
let (m_kib, t) = ((m / 1024) as u32, t as u32);
if id == KDF_ARGON2D { Kdf::Argon2d { m_kib, t, p } } else { Kdf::Argon2id { m_kib, t, p } }
} else {
return Err(Error::UnsupportedKdf);
};
check_kdf(kdf)?;
Ok((kdf, salt))
}
fn kdf_dict(kdf: Kdf, salt: &[u8; 32]) -> Vec<u8> {
let mut d = 0x0100u16.to_le_bytes().to_vec();
let mut item = |kind: u8, k: &str, v: &[u8]| {
d.push(kind);
d.extend_from_slice(&(k.len() as u32).to_le_bytes());
d.extend_from_slice(k.as_bytes());
d.extend_from_slice(&(v.len() as u32).to_le_bytes());
d.extend_from_slice(v);
};
match kdf {
Kdf::Argon2d { m_kib, t, p } | Kdf::Argon2id { m_kib, t, p } => {
let id = if matches!(kdf, Kdf::Argon2d { .. }) { KDF_ARGON2D } else { KDF_ARGON2ID };
item(VD_BYTES, "$UUID", &id);
item(VD_BYTES, "S", salt);
item(VD_U32, "P", &p.to_le_bytes());
item(VD_U64, "M", &(u64::from(m_kib) * 1024).to_le_bytes());
item(VD_U64, "I", &u64::from(t).to_le_bytes());
item(VD_U32, "V", &0x13u32.to_le_bytes());
}
Kdf::Aes { rounds } => {
item(VD_BYTES, "$UUID", &KDF_AES);
item(VD_U64, "R", &rounds.to_le_bytes());
item(VD_BYTES, "S", salt);
}
}
d.push(0);
d
}
/// Test hooks: build files with chosen KDF parameters, inner streams or payloads, to check the reader refuses them.
#[doc(hidden)]
pub mod testing {
use super::*;
/// A valid file around `inner` (inner header + XML, before gzip) with the given KDF dictionary bytes,
/// keyed with `transformed` directly (no KDF runs).
pub fn build(kdf_dict_bytes: &[u8], transformed: &[u8; 32], inner: &[u8], gzip: bool) -> Vec<u8> {
let payload = if gzip {
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
gz.write_all(inner).unwrap();
gz.finish().unwrap()
} else {
inner.to_vec()
};
assemble(kdf_dict_bytes, transformed, payload, gzip)
}
/// The same around a payload that is already gzipped.
pub fn build_compressed(kdf_dict_bytes: &[u8], transformed: &[u8; 32], gz: &[u8]) -> Vec<u8> {
assemble(kdf_dict_bytes, transformed, gz.to_vec(), true)
}
fn assemble(kdf_dict_bytes: &[u8], transformed: &[u8; 32], mut payload: Vec<u8>, gzip: bool) -> Vec<u8> {
let seed = [7u8; 32];
let iv = [9u8; 12];
let keys = Keys::new(&seed, transformed);
let mut out = Vec::new();
out.extend_from_slice(&SIG1);
out.extend_from_slice(&SIG2);
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&4u16.to_le_bytes());
field(&mut out, 2, &CIPHER_CHACHA20);
field(&mut out, 3, &u32::from(gzip).to_le_bytes());
field(&mut out, 4, &seed);
field(&mut out, 7, &iv);
field(&mut out, 11, kdf_dict_bytes);
field(&mut out, 0, b"\r\n\r\n");
let hash = crypto::sha256(&[&out]);
let hmac = keys.header_hmac(&out);
out.extend_from_slice(hash.as_slice());
out.extend_from_slice(&hmac);
crypto::chacha20(&keys.cipher, &iv, &mut payload);
for (index, chunk) in payload.chunks(BLOCK).chain(std::iter::once(&[][..])).enumerate() {
out.extend_from_slice(&keys.block_hmac(index as u64, chunk));
out.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
out.extend_from_slice(chunk);
}
out
}
/// A KDF dictionary for AES-KDF with `rounds` (and a fixed seed), or raw entries.
pub fn aes_dict(rounds: u64) -> Vec<u8> {
kdf_dict(Kdf::Aes { rounds }, &[3u8; 32])
}
/// An Argon2 dictionary with the given raw values (memory in bytes), unchecked.
pub fn argon2_dict(id: bool, m_bytes: u64, t: u64, p: u32, version: u32) -> Vec<u8> {
let mut d = 0x0100u16.to_le_bytes().to_vec();
let mut item = |kind: u8, k: &str, v: &[u8]| {
d.push(kind);
d.extend_from_slice(&(k.len() as u32).to_le_bytes());
d.extend_from_slice(k.as_bytes());
d.extend_from_slice(&(v.len() as u32).to_le_bytes());
d.extend_from_slice(v);
};
item(VD_BYTES, "$UUID", if id { &KDF_ARGON2ID } else { &KDF_ARGON2D });
item(VD_BYTES, "S", &[5u8; 32]);
item(VD_U32, "P", &p.to_le_bytes());
item(VD_U64, "M", &m_bytes.to_le_bytes());
item(VD_U64, "I", &t.to_le_bytes());
item(VD_U32, "V", &version.to_le_bytes());
d.push(0);
d
}
/// The transformed key AES-KDF gives for a password and `aes_dict(rounds)`.
pub fn aes_transformed(password: &str, rounds: u64) -> [u8; 32] {
let composite = crypto::sha256(&[crypto::sha256(&[password.as_bytes()]).as_slice()]);
*crypto::aes_kdf(composite.as_slice(), &[3u8; 32], rounds)
}
/// An inner header: stream id, a 64-byte stream key of 1s, then `xml`.
pub fn inner(stream_id: u32, xml: &[u8]) -> Vec<u8> {
let mut v = Vec::new();
field(&mut v, 1, &stream_id.to_le_bytes());
field(&mut v, 2, &[1u8; 64]);
field(&mut v, 0, &[]);
v.extend_from_slice(xml);
v
}
}
+121
View File
@@ -0,0 +1,121 @@
//! KeePass KDBX import (3.1 and 4) and export (4) (docs/KDBX.md).
//!
//! Two layers: [`read`] / [`write`] turn bytes and a [`Key`] into a [`Database`] and back;
//! [`to_items`] / [`from_items`] map KeePass entries to Custos items and back.
mod crypto;
mod format;
mod map;
mod time;
mod xml;
pub use custos_vault::{SecretBytes, SecretString};
#[doc(hidden)]
pub use format::testing;
pub use format::{Cipher, Kdf, WriteOptions, read, write};
pub use map::{from_items, to_items};
pub use time::{format_iso, parse_iso};
/// A whole KDBX database, as far as Custos keeps it (docs/KDBX.md, "What does not survive").
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Database {
/// `Meta/DatabaseName`.
pub name: String,
pub root: Group,
/// The recycle bin group, when the file has one switched on. Its entries are not imported.
pub recycle_bin: Option<[u8; 16]>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Group {
pub uuid: [u8; 16],
pub name: String,
pub groups: Vec<Group>,
pub entries: Vec<Entry>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Entry {
pub uuid: [u8; 16],
/// In file order. Keys are unique within an entry.
pub strings: Vec<StringField>,
pub attachments: Vec<custos_vault::Attachment>,
pub tags: Vec<String>,
pub times: Times,
pub autotype: AutoType,
/// Older versions of this entry, oldest first (KeePass order). Their own history is empty.
pub history: Vec<Entry>,
}
impl Entry {
/// The value of the string called `key`.
pub fn get(&self, key: &str) -> Option<&SecretString> {
self.strings.iter().find(|s| s.key == key).map(|s| &s.value)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StringField {
pub key: String,
pub value: SecretString,
/// Written XORed with the inner stream (KeePass's "protect in memory").
pub protected: bool,
}
/// Unix seconds (UTC).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Times {
pub created: i64,
pub modified: i64,
/// `ExpiryTime` when `Expires` is true.
pub expires: Option<i64>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AutoType {
pub default_sequence: String,
/// The `Window` of each association, in order.
pub windows: Vec<String>,
}
/// What opens a KDBX file: a password, a key file, or both.
#[derive(Clone, Copy, Default)]
pub struct Key<'a> {
/// An empty password counts as no password (as in KeePassXC).
pub password: Option<&'a SecretString>,
/// The key file's whole content.
pub key_file: Option<&'a [u8]>,
}
impl std::fmt::Debug for Key<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Key")
.field("password", &self.password.is_some())
.field("key_file", &self.key_file.is_some())
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error("this is not a KeePass database")]
NotKdbx,
#[error("unsupported KDBX version {0}.{1}")]
UnsupportedVersion(u16, u16),
#[error("a password or a key file is needed")]
NoKey,
#[error("wrong password or key file")]
WrongKey,
#[error("the file is damaged")]
Corrupted,
#[error("unsupported cipher: only AES-256 and ChaCha20 are supported")]
UnsupportedCipher,
#[error("unsupported key derivation settings")]
UnsupportedKdf,
#[error("unsupported inner stream: only ChaCha20 and Salsa20 are supported")]
UnsupportedStream,
#[error("the file is too large")]
TooLarge,
#[error("malformed KDBX file: {0}")]
Malformed(&'static str),
}
+410
View File
@@ -0,0 +1,410 @@
//! 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<bool> {
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_<n>`: KeePassXC's extra URLs. Its number, `KP2A_URL` itself being 0.
fn extra_url(key: &str) -> Option<u32> {
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<Item> {
let mut out = Vec::new();
collect(&db.root, &mut Vec::new(), db.recycle_bin, &mut out);
out
}
fn collect(g: &Group, path: &mut Vec<String>, bin: Option<[u8; 16]>, out: &mut Vec<Item>) {
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<Mapped> {
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::<u32>().ok()).unwrap_or(30);
let digits = parts.next().and_then(|d| d.trim().parse::<u32>().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<bool>, 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<HistoryEntry> {
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<String> = 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<Entry> {
let mut hist: Vec<&HistoryEntry> = item.history.iter().collect();
hist.sort_by_key(|h| h.changed);
let mut times: Vec<i64> = 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()
}
+111
View File
@@ -0,0 +1,111 @@
//! KDBX times: base64 of an i64 LE count of seconds since 0001-01-01 (KDBX 4), or ISO 8601 (KeePass XML).
/// Seconds from 0001-01-01T00:00:00Z to the Unix epoch.
const EPOCH_OFFSET: i64 = 62_135_596_800;
pub(crate) fn from_kdbx(text: &str) -> Option<i64> {
let t = text.trim();
if let Ok(b) = data_encoding::BASE64.decode(t.as_bytes())
&& let Ok(b) = <[u8; 8]>::try_from(b.as_slice())
{
return i64::from_le_bytes(b).checked_sub(EPOCH_OFFSET);
}
parse_iso(t)
}
pub(crate) fn to_kdbx(unix: i64) -> String {
data_encoding::BASE64.encode(&unix.saturating_add(EPOCH_OFFSET).to_le_bytes())
}
/// `YYYY-MM-DD` (midnight UTC) or `YYYY-MM-DDTHH:MM:SS` with an optional `Z` → Unix seconds.
pub fn parse_iso(s: &str) -> Option<i64> {
let s = s.trim();
let s = s.strip_suffix('Z').unwrap_or(s);
let (date, time) = match s.split_once('T') {
Some((d, t)) => (d, Some(t)),
None => (s, None),
};
let mut d = date.splitn(3, '-');
let y: i64 = num(d.next()?, 4)?;
let m: u32 = num(d.next()?, 2)? as u32;
let day: u32 = num(d.next()?, 2)? as u32;
if !(1..=12).contains(&m) || day == 0 || day > days_in_month(y, m) {
return None;
}
let mut secs = 0;
if let Some(t) = time {
let mut p = t.splitn(3, ':');
let (h, mi, se) = (num(p.next()?, 2)?, num(p.next()?, 2)?, num(p.next()?, 2)?);
if h > 23 || mi > 59 || se > 59 {
return None;
}
secs = h * 3600 + mi * 60 + se;
}
Some(days_from_civil(y, m, day) * 86_400 + secs)
}
/// Unix seconds → `YYYY-MM-DD` when it is midnight UTC, otherwise `YYYY-MM-DDTHH:MM:SSZ`.
pub fn format_iso(unix: i64) -> String {
let (days, secs) = (unix.div_euclid(86_400), unix.rem_euclid(86_400));
let (y, m, d) = civil_from_days(days);
if secs == 0 {
format!("{y:04}-{m:02}-{d:02}")
} else {
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", secs / 3600, secs / 60 % 60, secs % 60)
}
}
fn num(s: &str, len: usize) -> Option<i64> {
(s.len() == len && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
}
fn days_in_month(y: i64, m: u32) -> u32 {
match m {
2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
// Howard Hinnant's civil-date algorithms.
fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (i64::from(m) + 9) % 12;
let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(yoe + era * 400 + i64::from(m <= 2), m, d)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iso_round_trips_and_refuses_nonsense() {
assert_eq!(parse_iso("1970-01-01"), Some(0));
assert_eq!(parse_iso("2026-11-03T19:26:49Z"), Some(1_793_734_009));
assert_eq!(format_iso(1_793_734_009), "2026-11-03T19:26:49Z");
assert_eq!(format_iso(parse_iso("2024-02-29").unwrap()), "2024-02-29");
assert_eq!(format_iso(parse_iso("0001-01-01").unwrap()), "0001-01-01");
for bad in ["", "2023-02-29", "2026-13-01", "26-01-01", "2026-01-01T24:00:00Z", "next year", "2026-1-1"] {
assert_eq!(parse_iso(bad), None, "{bad}");
}
assert_eq!(from_kdbx(&to_kdbx(1_793_734_009)), Some(1_793_734_009));
assert_eq!(from_kdbx("2026-11-03T19:26:49Z"), Some(1_793_734_009));
}
}
+348
View File
@@ -0,0 +1,348 @@
//! The inner XML: parsed with roxmltree (no DTD, so no entity tricks), written by hand.
use crate::crypto::InnerStream;
use crate::{AutoType, Database, Entry, Error, Group, StringField, Times, time};
use custos_vault::{Attachment, SecretBytes, SecretString};
use roxmltree::{Node, NodeId};
use std::collections::HashMap;
use std::fmt::Write as _;
use zeroize::Zeroizing;
const MAX_DEPTH: usize = 256;
pub(crate) fn parse(xml: &[u8], stream: &mut InnerStream, pool: &[SecretBytes]) -> Result<Database, Error> {
let xml = xml.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(xml);
let body = std::str::from_utf8(xml).map_err(|_| Error::Malformed("XML is not UTF-8"))?;
let doc = roxmltree::Document::parse_with_options(
body,
roxmltree::ParsingOptions { allow_dtd: false, ..Default::default() },
)
.map_err(|e| match e {
roxmltree::Error::DtdDetected => Error::Malformed("XML with a DOCTYPE"),
_ => Error::Malformed("XML"),
})?;
// Protected values, unmasked in document order: every one consumes the stream, used or not.
let mut protected: HashMap<NodeId, Zeroizing<Vec<u8>>> = HashMap::new();
for n in doc.descendants().filter(|n| n.is_element()) {
if n.attribute("Protected").is_some_and(|v| v.eq_ignore_ascii_case("true")) {
let mut bytes = Zeroizing::new(
data_encoding::BASE64.decode(n_text(n).as_bytes()).map_err(|_| Error::Malformed("protected value"))?,
);
stream.apply(&mut bytes);
protected.insert(n.id(), bytes);
}
}
let root = doc.root_element();
if !root.has_tag_name("KeePassFile") {
return Err(Error::Malformed("not a KeePass XML document"));
}
let meta = child(root, "Meta");
let name = meta.and_then(|m| child(m, "DatabaseName")).map(text).unwrap_or_default();
let recycle_bin = meta
.filter(|m| child(*m, "RecycleBinEnabled").is_some_and(|n| text(n).eq_ignore_ascii_case("true")))
.and_then(|m| child(m, "RecycleBinUUID"))
.and_then(|n| uuid(n).ok())
.filter(|u| *u != [0; 16]);
let group = child(root, "Root").and_then(|r| child(r, "Group")).ok_or(Error::Malformed("no root group"))?;
// Attachments: KDBX 4 keeps them in the inner header (by index), KDBX 3.1 in Meta/Binaries (by ID).
let mut binaries: HashMap<String, SecretBytes> =
pool.iter().enumerate().map(|(i, b)| (i.to_string(), b.clone())).collect();
for b in meta.and_then(|m| child(m, "Binaries")).into_iter().flat_map(|bs| bs.children()) {
if !b.has_tag_name("Binary") {
continue;
}
let id = b.attribute("ID").ok_or(Error::Malformed("attachment"))?.to_owned();
let raw = match protected.get(&b.id()) {
Some(bytes) => bytes.clone(),
None => Zeroizing::new(
data_encoding::BASE64.decode(n_text(b).as_bytes()).map_err(|_| Error::Malformed("attachment"))?,
),
};
let data = if b.attribute("Compressed").is_some_and(|v| v.eq_ignore_ascii_case("true")) {
crate::format::gunzip(&raw)?
} else {
raw
};
binaries.insert(id, SecretBytes::new(data.to_vec()));
}
let ctx = Ctx { protected: &protected, binaries: &binaries };
Ok(Database { name, root: ctx.group(group, 0)?, recycle_bin })
}
struct Ctx<'a> {
protected: &'a HashMap<NodeId, Zeroizing<Vec<u8>>>,
binaries: &'a HashMap<String, SecretBytes>,
}
impl Ctx<'_> {
fn group(&self, n: Node, depth: usize) -> Result<Group, Error> {
if depth > MAX_DEPTH {
return Err(Error::Malformed("groups nested too deeply"));
}
let mut g = Group {
uuid: child(n, "UUID").map(uuid).transpose()?.unwrap_or_default(),
name: child(n, "Name").map(text).unwrap_or_default(),
..Default::default()
};
for c in n.children().filter(|c| c.is_element()) {
match c.tag_name().name() {
"Entry" => g.entries.push(self.entry(c, true)?),
"Group" => g.groups.push(self.group(c, depth + 1)?),
_ => {}
}
}
Ok(g)
}
fn entry(&self, n: Node, with_history: bool) -> Result<Entry, Error> {
let mut e = Entry { uuid: child(n, "UUID").map(uuid).transpose()?.unwrap_or_default(), ..Default::default() };
for c in n.children().filter(|c| c.is_element()) {
match c.tag_name().name() {
"Tags" => {
e.tags =
text(c).split([';', ',']).map(str::trim).filter(|t| !t.is_empty()).map(Into::into).collect()
}
"Times" => e.times = times(c),
"String" => {
let key = child(c, "Key").map(text).unwrap_or_default();
let v = child(c, "Value");
let (value, protected) = match v.and_then(|v| self.protected.get(&v.id())) {
Some(b) => {
let s = String::from_utf8(b.to_vec()).map_err(|_| Error::Malformed("protected value"))?;
(SecretString::new(s), true)
}
None => (SecretString::new(v.map(text).unwrap_or_default()), false),
};
if !e.strings.iter().any(|s| s.key == key) {
e.strings.push(StringField { key, value, protected });
}
}
"Binary" => {
let name = child(c, "Key").map(text).unwrap_or_default();
let r = child(c, "Value").and_then(|v| v.attribute("Ref")).ok_or(Error::Malformed("attachment"))?;
let data = self.binaries.get(r).ok_or(Error::Malformed("attachment"))?;
e.attachments.push(Attachment { name, data: data.clone() });
}
"AutoType" => {
e.autotype = AutoType {
default_sequence: child(c, "DefaultSequence").map(text).unwrap_or_default(),
windows: c
.children()
.filter(|a| a.has_tag_name("Association"))
.map(|a| child(a, "Window").map(text).unwrap_or_default())
.collect(),
}
}
"History" if with_history => {
for h in c.children().filter(|h| h.has_tag_name("Entry")) {
e.history.push(self.entry(h, false)?);
}
}
_ => {}
}
}
Ok(e)
}
}
fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> {
n.children().find(|c| c.has_tag_name(name))
}
/// Base64 text without its whitespace.
fn n_text(n: Node) -> Zeroizing<String> {
Zeroizing::new(n.text().unwrap_or("").split_whitespace().collect())
}
fn text(n: Node) -> String {
n.text().unwrap_or("").to_owned()
}
fn uuid(n: Node) -> Result<[u8; 16], Error> {
let t = n.text().unwrap_or("").trim();
data_encoding::BASE64.decode(t.as_bytes()).ok().and_then(|b| b.try_into().ok()).ok_or(Error::Malformed("UUID"))
}
fn times(n: Node) -> Times {
let get = |name| child(n, name).and_then(|c| time::from_kdbx(c.text().unwrap_or("")));
let expires = child(n, "Expires").is_some_and(|c| text(c).trim().eq_ignore_ascii_case("true"));
Times {
created: get("CreationTime").unwrap_or(0),
modified: get("LastModificationTime").unwrap_or(0),
expires: if expires { get("ExpiryTime") } else { None },
}
}
/// The XML, protected values masked with `stream` in document order; attachments go to `pool` in the
/// order their `Ref`s are written.
pub(crate) fn write<'d>(
db: &'d Database,
stream: &mut InnerStream,
pool: &mut Vec<&'d SecretBytes>,
) -> Zeroizing<String> {
let mut w = W { out: Zeroizing::new(String::new()), stream, pool };
w.raw("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<KeePassFile>\n\t<Meta>\n");
w.el(2, "Generator", "Custos");
w.el(2, "DatabaseName", &db.name);
w.raw("\t\t<MemoryProtection>\n");
for (k, v) in [("ProtectTitle", "False"), ("ProtectUserName", "False"), ("ProtectPassword", "True")] {
w.el(3, k, v);
}
for (k, v) in [("ProtectURL", "False"), ("ProtectNotes", "False")] {
w.el(3, k, v);
}
w.raw("\t\t</MemoryProtection>\n");
w.el(2, "RecycleBinEnabled", "False");
w.el(2, "HistoryMaxItems", "20");
w.el(2, "HistoryMaxSize", "6291456");
w.raw("\t</Meta>\n\t<Root>\n");
w.group(&db.root, 2);
w.raw("\t\t<DeletedObjects/>\n\t</Root>\n</KeePassFile>\n");
w.out
}
struct W<'s, 'd> {
out: Zeroizing<String>,
stream: &'s mut InnerStream,
pool: &'s mut Vec<&'d SecretBytes>,
}
impl<'d> W<'_, 'd> {
fn raw(&mut self, s: &str) {
self.out.push_str(s);
}
fn indent(&mut self, n: usize) {
for _ in 0..n {
self.out.push('\t');
}
}
fn el(&mut self, depth: usize, name: &str, value: &str) {
self.indent(depth);
if value.is_empty() {
let _ = writeln!(self.out, "<{name}/>");
} else {
let _ = write!(self.out, "<{name}>");
escape(&mut self.out, value);
let _ = writeln!(self.out, "</{name}>");
}
}
fn times(&mut self, d: usize, t: &Times) {
self.indent(d);
self.raw("<Times>\n");
let m = time::to_kdbx(t.modified);
self.el(d + 1, "LastModificationTime", &m);
self.el(d + 1, "CreationTime", &time::to_kdbx(t.created));
self.el(d + 1, "LastAccessTime", &m);
self.el(d + 1, "ExpiryTime", &time::to_kdbx(t.expires.unwrap_or(t.modified)));
self.el(d + 1, "Expires", if t.expires.is_some() { "True" } else { "False" });
self.el(d + 1, "UsageCount", "0");
self.el(d + 1, "LocationChanged", &m);
self.indent(d);
self.raw("</Times>\n");
}
fn group(&mut self, g: &'d Group, d: usize) {
self.indent(d);
self.raw("<Group>\n");
self.el(d + 1, "UUID", &data_encoding::BASE64.encode(&g.uuid));
self.el(d + 1, "Name", &g.name);
self.el(d + 1, "IconID", "48");
self.el(d + 1, "IsExpanded", "True");
for e in &g.entries {
self.entry(e, d + 1, true);
}
for sub in &g.groups {
self.group(sub, d + 1);
}
self.indent(d);
self.raw("</Group>\n");
}
fn entry(&mut self, e: &'d Entry, d: usize, with_history: bool) {
self.indent(d);
self.raw("<Entry>\n");
self.el(d + 1, "UUID", &data_encoding::BASE64.encode(&e.uuid));
self.el(d + 1, "IconID", "0");
self.el(d + 1, "Tags", &e.tags.join(";"));
self.times(d + 1, &e.times);
for s in &e.strings {
self.indent(d + 1);
self.raw("<String>\n");
self.el(d + 2, "Key", &s.key);
self.indent(d + 2);
if s.protected {
let mut b = Zeroizing::new(s.value.expose().as_bytes().to_vec());
self.stream.apply(&mut b);
let _ = writeln!(self.out, "<Value Protected=\"True\">{}</Value>", data_encoding::BASE64.encode(&b));
} else if s.value.is_empty() {
self.raw("<Value/>\n");
} else {
self.raw("<Value>");
escape(&mut self.out, s.value.expose());
self.raw("</Value>\n");
}
self.indent(d + 1);
self.raw("</String>\n");
}
for a in &e.attachments {
let r = self.pool.len();
self.pool.push(&a.data);
self.indent(d + 1);
self.raw("<Binary>\n");
self.el(d + 2, "Key", &a.name);
self.indent(d + 2);
let _ = writeln!(self.out, "<Value Ref=\"{r}\"/>");
self.indent(d + 1);
self.raw("</Binary>\n");
}
self.indent(d + 1);
self.raw("<AutoType>\n");
self.el(d + 2, "Enabled", "True");
self.el(d + 2, "DataTransferObfuscation", "0");
self.el(d + 2, "DefaultSequence", &e.autotype.default_sequence);
for win in &e.autotype.windows {
self.indent(d + 2);
self.raw("<Association>\n");
self.el(d + 3, "Window", win);
self.el(d + 3, "KeystrokeSequence", "");
self.indent(d + 2);
self.raw("</Association>\n");
}
self.indent(d + 1);
self.raw("</AutoType>\n");
if with_history && !e.history.is_empty() {
self.indent(d + 1);
self.raw("<History>\n");
for h in &e.history {
self.entry(h, d + 2, false);
}
self.indent(d + 1);
self.raw("</History>\n");
}
self.indent(d);
self.raw("</Entry>\n");
}
}
/// XML text escaping. `\r` is written as a character reference so a parser's line-end normalization keeps
/// it; characters XML 1.0 cannot carry at all (other C0 controls) are dropped.
fn escape(out: &mut String, s: &str) {
for ch in s.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\r' => out.push_str("&#13;"),
'\t' | '\n' => out.push(ch),
c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
c => out.push(c),
}
}
}
@@ -0,0 +1,97 @@
// Files written by KeePassXC 2.7.12 (keepassxc-cli), from tools/kdbx/sample.xml, password "custos-test":
// V3 by `import` (KDBX 3.1, AES-KDF, AES-256, a recycle bin), V4 by `merge` of V3 into an empty KDBX 4
// file Custos wrote (KDBX 4.0, Argon2id 1 MiB, ChaCha20; KeePassXC keeps a file's format when it saves).
// These are test vectors: the first two steps of tools/kdbx/interop.sh make new ones
// (scratch script: base64 of each file, 100 characters per line).
const V3: &str = "
A9mimmf7S7UBAAMAAhAAMcHy5r9xQ1C+WAUhavxa/wMEAAEAAAAEIABxP6+yGbKtLFUqLZSBYUCDYrbP08dc4XTSSqHBRDGfewUg
AFDZzHIfvtxlCIOFQuMhnUD+NylHzyQm9bamu47pm/UrBggAgmVhAAAAAAAHEAA6MUS+RAp24tIyFbSnmrErCCAAA+p+nPcr2YHO
jXJHmIcuYjPzGWstYcLO7OiEoylZBl0JIACBvX6LL+NQDaZSTEd6UDMIjNQjLlh/0ZrbdX1W93wVzAoEAAIAAAAABAANCg0Kyl93
gyBLluY5EMk0XHCZdq9Ud2wtSiM9pdzcamLzP00nUlV0BnVsIHixNUf1ifpPmATO2Z01CHyoZE6jW1nwNyeuQT/YppuEeXh3K3AY
mDtjqB3bohJLgTyg1PslOOGhHr009FLUqVRSU042X92tmlUYmesXH+AWOPpBK1uoN/ZV2UButF+6kLFB5T2x/Ds1e97gxfPPS/hp
O/RQrjvugGAsoc6dZUpDv1Dw+NoyHXQNHW/mfLFDBP1iyve8Kp97NDvQpCyMZT2tbJvwPGyLVQgSMLXMPc3kBrDt0WqZ4Jmcx7z8
+Vr0/Ly1TzoWRvurUgcHSRtiUMvQmPl7X/LLbzg2S9XORw7oGAKvNPiyh7mriTpV9OVUapObkLVBnihZmYaj1xwHJtgcIv+dFpcY
hE4zA+/gqXf3RWDfwhY0p81tobTVaMAzd3Wu5H28NIWXs8z33i8LQ74CRH2Sq6s52JlRt62ofu2jcGlkFxNrv+j9+FE9kL0Sex5Y
8fZvx/bNrwT79Jea79V19zsQpT2tzSEM6cB3wDekj5Kba96kOc6bRH1J7HsNDSbDss0tF16MiTEBSIHW5lJwk1x/m8gmHBurHYUl
dXHZKN1MoJ+ROyfR0BrerI5ETlN48f7ZZTsO7L6twynU6MqiyDlXjGQUUFaVeUsObyklQ59+pD5CUx9ve0Uak8P2KS01gEXiBNtw
b+vBkSbiNcaSOrl4DXwXINPA3RpHURGjwu5M4HHWI9keIsrwfFmGRlH5oNroxihBFEOUSfL4ChdmG/rbtGxHekba5pyAWyVE0z4h
lYIKjldWKzQjtPCbWWmbGspopEaBL9G2GE9RpA4gRN3ZrDR6WcbBLQYNwOYoiPU38m1L1KjSV59WpzoL7/xfslTEvEH83LHkf6mt
LfbHC8Y2AVN27bt6C8zDTUYJFeUTiierSvf22s5m1s2NbfVqJC1XJFREJuusEY/RGPJa+OdSoN7E0sQFDOoDtZihZSSdp+IkdXkl
skgcIqyC8/ioos62g6xYWndMI9b+FgDuH1ADSSSugC3CfVMHhUio93o9Z41DsIQMSzliF2Ggp+0wIBwsakaxWoqjVh0ydRX39GQ0
eSC2z6Rt1TT1CouDQTsf5G57r4217pQvbzFhs7Yfc9ZetzCN5JBzw2hFYHEvoJR5YzAJD1txFt7AfeHdN/3F70RYpKbj8txOnS/F
aXuexKaHDBlVlEf2DakTjQNZpK+Su94TJ6me4mO5qJTeZ4KlEoRrAttY6DRQ0ThjHh5erLf44rrxzas8kqYE5XMe0iUiDVaIVwu1
9oOnqURbqMeDcoGqxrc/LkeSyEuZ+F4+xx9uJ15NV3eexj5E6OZoB5Wqy6gHdEXiPV0PmMJksJSI/IBtCR4/AzKoTUe6JRWJAd51
fDQ8r4CivKzwkMyyHMcaUu8LQ5jqt87EeGJ3mWnDRC0A8/TR25VOKmrLK1G+e+RTF/ySC0t6ndxQbt79HeNbio/E3goxVOAYfryO
vMhJS+aJsDwd9ERAFXFzFyrGb2iuyKvbT1GKDFWa/+voFiCtnMa/JF26Z6sr+Yytgr58bB9+7CJiCyqrywkCze8+NZ6v6LTj/xJ0
gflMpCavrnXTN2BzNUDoONsSk03RNDGxN7Y8S2m4BoRdRjJ0Sr2Ta8u5iePIg7TmIcnhP96pJ1qAZkZYdai87du/4wIHHBx/CLf1
xaOAVcg3M1E/EHxxlJ9K3G0QBO05RXQL73riIAj3NFAIV8OIMTxq+fwkTG1VLGwfPS7Ezkt6vE5pkSaktlC+XVsuWroZpUXbvGXv
bGcLGCWr4pciROyCAm9NDvuZNrgkLLewmAGRYlgX7iZUNPwfmypEw7ians6jV4BEKYu71FZngB7FqM5t8NaTx9Ljed8Qt+IGCKa9
ZioRmIOrelaRo+NB8/Bas/vdg7AsrVsIZrSEF5JdFhJZ2Cx/AoTwZ7yhOg3Vl3kwG6VfwQrVZA9PpO4StthFQY5KeJGIRkn9KRyY
mYnL2fnPiof0ZCPwe0gQKQrGjjkYqOPZtM3YNkUtMoP9O1fz8BbBoDxa0E49qGgNxgzIEV1fw7w0pHnT4RaeX8hu+SaRWRW5dqxa
GLEjicraTg1fC5WDyh/RH3T6F9KQ2oiUKjZnUHSBJRZf++rquooN51mKS8LWC8Tti5NhWz69psjygpxeNEMrorQpV9KFtE5JNMtt
mjoF6j1uiXL2muNSlEzNyXBvKTWRYiMesHIKpORaOce3zO2PZOqnykN8ro9/zonA50z9kodJ7Skq/HiwM+MSyVKogLSgM1uHBdRl
ce0S3zBq1go514OLX5LGLDdLmu3OgRNxCC/KC4YT806pLDjpRW+Q7xItfta2TOsvjqB02tE+IrBFw2BmPtWCRq3zpyUl+PHS+bd6
5tDiCZQSN1dr9BAsnPY6nsXNJTy9AnSZ3J7rZlk52rrCTiZ/uSlTeEQDONndkof4z9Qd7+edKN7ZFk+f/GTtpyH/kzxdQ0cLnH/7
lPf7cJIjlVJ+Irt43uR0wc0w8ONftEyByVMqO4maMUbuTFbJdTUuPoZxs1HepWRrzzcy8ggx5XUe5556vuO1kWTgXmt38ms8DPx2
EezM4gWIDruwEca+7OiLDhGdhWqFAx22YinL5EvarEO9xvu44pjgbuyM87rdipjXrqOhCsvPUkWTG1NG+vEs7XYCft/iPFBDgnNJ
L544kOGEDtdLZB7rSt++gUh0Vmph6CXxCq15P+3IuTFYxWoueN4dI01bXhc3/HprHwCrJDYBzD+T0lRh9pn8n6FhFC2xc/CcNbbC
Hl4THNc9Rs3qmWBpz5aHW+isE4B7Aeaq85VFpZ75IPXjlaO0FAzB4RxIh14YmnF44IrS8cHpRf0IvDnTk6RJe+iDVRCbw7AHbWu8
6hYI6tHBtnCtVYX1kkK+93zBG23dqaNyz6pxqI+ULNLsoROxcC6RGVJLMJad7YCxdsVzzo9sCTrlykZKi7pU5hZo3/epKMfRmGLY
CX84PBeCeMXZzLpFdsp/+jPcdHhaG9A4XkWSlR9CmvFNf9jTckuApYF/FDYGdAnMSC5QNJhE4aKexL8LnbF2qZ9xb/JE+0M63W8u
uRsucRNuOGjP8cn43MsvQ/5SSZuyv1H4hXKekKMEj92zlKofKZe3Sw28kZv4XekSUdTWoUycehykkHOfJ6GCIGQx8Vp59FDD7Ux3
TjYD6Z0M+jsjciIDVUpGWPxM7TbWgUxYqPPliu70TG7yD6ZcJ/ZR6vcYIq1kE1+HhySLdmdKCRPDoRFxslWEGygRgP0f1j84koa3
oB2/WqEboTG3FjStCForRlWqip1fqoO8CN9m5JcqWuR4tU0z0yCnRb22OWfAGroGtOZdZq65bkl7QwvcO1UAMmVocprocUWcuL+S
95lOV30LGMck7hawZIMsPIGxEwaAHOY1x7GXNyJNXyokllWzIOQB9f8ijgZ2K0aXlY0BMNeahOg0GtLJ1wD9TiIJjR0EfeX6K4SE
B7N9w5IVBxFj2ov51V+QJ2JNgBcz9LY4tzlRf2WtUGjsrTu5tKADCawDylACdyuAIf01TxjwI6KFUqbcoHxmdbcg1pzogiRFwS9A
RAaW5cFVdAQZfGrb7OWAVlVv39I/7ERpKl8v+kaZtcWJo4ti8h93Tk87oUBzTmw/EuvmEPqmGb3U74aeNiusERjDETPvptNA4AQ+
wacNeHlR8Xoo7OtEbO+bgPYq0iGdnQ==
";
const V4: &str = "
A9mimmf7S7UAAAQAAhAAAADWA4ori29MtaUkM5ox27WaAwQAAAABAAAABCAAAADzupOsQNxJtVlkoq/jSw09K0bVSZhptX92AZ1p
i1Pc0QcMAAAAJwtbrtLHFXIogTGFC4sAAAAAAUIFAAAAJFVVSUQQAAAAnimLGVbbR3OyPfw+xvCh5gUBAAAASQgAAAACAAAAAAAA
AAUBAAAATQgAAAAAABAAAAAAAAQBAAAAUAQAAAABAAAAQgEAAABTIAAAAOH9a1nQE9Z0DF7AXihl/5svsTxxIIsQrLyRqgPGli+D
BAEAAABWBAAAABMAAAAAAAQAAAANCg0KIlabXPdaLY1rYYaqe9H8l1/Gt/dAEcsHxmVR2oBITjLi4+QPmaXni/MJuSznD3Mk/O7W
YO67iKNBV7s3/9/ikiisk3nXhJ4Lqt9eZkb7R9Hy/DMSz+bPBHi9B9V6oD54oAsAAJsOIWmXzG35TT0OQ2M2K6GBwLAN9ZbyhohI
yk5GrqyFh/Q5M4/i0wjSBS1LmurEvAF9VxcCuFdZyTZrJxoGj2R5Y1fts01H37aFGCOiJP54EoTYs3aJzrzBk+WeSJZ7fvx7+2tA
7NfV8l4UtMaaw/nIoLQoMMGY4hyS58sMXtu1btPNfvKHvJUUSspQoEyOQ6yNuOB/mCGSOJhN4lTuWWXavJwFEIX8tBEI1CzHwken
kK8uiZleYqo+IqpZN0yVvZwUhfb+k+VASWAw7O/I/WOA4ONOdID058GIDWYEHuLoSIVRW+BXDm8n5WS5DQ7faaBjhQt6oZDSQRAv
EVSfN0R7MZe4xr4pXHV+B0oS6fTOsYCjxNYlznqnckivTz5lInl9uun4h1UQUwT59o0L/CiNrAI4todbXb9laCJl+xJTljMoPzYD
afNdVC5LLmETU7ThsMvgPsmcthzzqS9SdUfrzDZBD/u83Wwbpp2tHx4m6jGFabN8WgA7S2QqddfPJRo4DjpgaqHyuMFTarNM546f
+qhTN1X2kWLUUeRtZ7Pnh6Nv9uy12wMktM/S2WXRm17+MATqOSJcDx+REChuuXEl20gY4cxgReiPyr09ruRaN3WKdex+e2gP3DQa
mxIX7NsKwBRLwX6b/tDc22vAs64X43fJEuNJF/5WFWr96SgO0LDph5JZKHnuT+rU/g5ji0c095PJH2a/wFx8QiFEr5BA6kYVSPIU
8isa5v8TdQpk4V+yl7GRf72sW2wLeSwiS+oad8ttNNxOzA6uiXaWQTKsESN7Q6qxgKxsToqqdiAm3hCr4jKd1k7VUIllspabwXqW
OVXu1dUyT9gcsMK/DNru5M5Xel7ZtKF5O1TBoE7V5o2qjy7hnqhjcNM9DnoeshEbG8Ll97JFnmyfClYx2yy3uCdgwpryfqimllXA
cqCvsX47vDQYPK/HXmd9249qP+k2nLEen1QiHhY9qlIt0LwyiYEe+17C/rVN9UQdVWQYGpKnK4tw2R1h1+f+3LSjr9CjzK9JBI65
GwENYY/V0iwWwTvLzKbnjSB6ZcUCC34jxLQTWIMjACm0ltKCNfOC6iF338IMglQtZ+RDKEfxxY3zjB22Pqk8ZAyK+xKEGb0DCjlq
xtwbLlelOpSaoO7xR9GyuBdLyKzjsNEe/Oo92bl9uF6ugrtbhV1Nwjb9awhZ056H83/HizMbf1J88m2pROz31gD2rDrBkHiXQ/iW
RLgpzriEgpPUrDNtQB8XOlO0yJnJR3oIyG/SQbGnx2sGghbXWYvIioLnr54YBBXFT9zGBOQKnf185xsiLpqiEr62RalPynMncCFc
zH+/zdl8JbYHR/mcVRKJ95hA6Y0gk2RWqo4tLt7yz80y8Ctu0/4gh/LYjjkUId5P8McNVEBhcFQbzavkLlUNsovZOjjl67UxzM7l
F/fbBjULIdb6caRa/EDgGef/0bfUuU5ZEM9AMxPgxXrCRReH/e+YNVR743bdUw6bMjOjg4sq4B4H2ERuwiEKL1Rl+Vm/AlEwR/8u
jO3C7uSbDz/um+giIsJQxoHwHKlYa3C3/Gx9AP1gzUgRDkxDPYtMRUT34YMieBMcDsi598PFXnZWFBt3wl7ppNbCrZq3/jRqs90j
zR5hBgAB/Tsqa3OaZoz/uGkwGVKQmonziHVKgBrAKHZOJvtlfWDkmIAg0khQ95OmB9WGYOZu3YraxCW4G+CNV0WSYzgxK7c3Xvsr
3tv5Ne2eORtioat6GnnrliMCeK1UaXKI4aiYcT7ZUn11/OqSDBXn8vyFjNIL3ozGhiOQDvVv8DM2sd1JHEv7Zj2XJIdebJuUCy/S
shs5/GHyHYg6t0r3LeprOND1YMp9Ty332Zy5wCrttFI9nKown5WrQSa6GL+Etfwhk9tfISKI5PxPv6FPEzBs6LERj1SxED65CmPu
9N0VdK78dAsNe26AIwTZKYqUDhYwWbEeXNIx1WalO3zk9C4VsXQ3YpWwwbFtam4w3CdoWaqQrSPPddRkzo62KKxxiHYfPcA/gE56
mFuIjjS9kBr40UboApMTgBTqQD3fDveHJ0WiTNMsLHTKWXIL6ZZt1UksPuraCqurolSP7VrGpN9ioyoDdimY6WzMbEYmFY8gEM1F
YFzybW4RE3IPfUILQFvByPoEwRnaq5ah7ynrL/ZVk1y+kt+s563cxaUzOXf9sKOB1Ycweo/EHrg21gkkN8Nu73T1rGEVQv9q0sDW
6DnZ66gSuUUHNH9aAQkHW6069jFUjl9/3lsc0+BodGPOL7s+B6/sdRVRX4w3ujBcheKoEb2mAxvpuA604M0HSqNO30hqUIWawzES
CLtzpJysjcw3u0ySRT3wfcZcVcvhcEsNdBwJQ3Iz8fFMukWeZMnmfVwvBb1JrSb2vURX8P31uZQDnbaAjAnZfMUE1kngQqk038uA
VrRbhGoPhWXCOKpt8E1dWQwchP3L5YdhMfAI7ND5e3Nn90iMqI8BVvDYdVHbS0BdrI5GFGy/anKbKdMcBDfaFFr6N0QexQ05zWg5
huld3SVmStBKTQJJIyEstVFY44MtEXtA7iNwi82vLa2uKIA6DD89Fe44ktXLgReThc+iH4o2+7jiap8pFFzYh19rG9mFE9U22T2B
O2SmGea8K2ad+1+g/EA12W1jEnGuAxIZlMPV05Kd+1xBMB2YMu+Pdffpbp1MJQbfRAs3el3NEeq0/UUIGW9LOupqAZY7vElk47Kg
FI93N49DzC4Mhv0M36X38PKaCq5mi47Mxd1yKwc1y3GQBIN91gLVx0txw6yjiHcWbqFEPvQY2UEnr0dT5Xm2I8TnJ2tpKz42eTEs
S9kcqvNCNV1KhQ9jrlMi9+64qbD6vUpNCq7DjIiaZP8MYpgoZnWsJloTIaTVGPbqUsruGHe/8K8gx//34RmA2K3FkofH4iC/ztSJ
u+x5NXjEyVyEyHT8HvKj5JZXN7tFoqEyL43pevk7OaYmLOEh1RKRegDkcJrglQBqSohUTu/dd9SgM6AlVxMvS7H5Hw5+Oq5s6s8K
+vda4a8mWeJfRH0em5Sk0IXkxUR9I+OBuYnREoDT/dliDavRJ+IF0plHeOre7bFQFu8Rsv02PnHeYhJmVME38kxYXOuxMmZ4muuj
7UaKV6sxHsPdWU5IMe9qGi5qSWp0Q21KLZ89DBWT56vwkySR0QjZTTbb/wmUYT57S9MCrmhF/ncbJM7A14xrjl0y/0K65N7Y8UgD
7Fol550Yl+rhTYWM/egpIJr9wmz6FHuHw86DZv/RHJyKPgfIPlZvy+Z3eaSwGz8jeTa+NaSY9+v0TpVTHDBTyeZ17t8L0cW0RU0v
Olwh939wYrYVE6SzQFv85nllEmRN0J/O3lzm/LaCydqzEpezAg1Xxd3VxXEMZAgc3B14O4rzDTigTHdi1/6yk3lQnxYVOCaFgEbC
n3SWMHJMnT31P/sWIOs/Cn57A2IZ4i1JsqoGORyo8NXSOcRrOusTTewH9MJiRkEelYlRrEV1xWl1ZGt1jcjbkkOdunvio3JM/xpe
C/aBgU7zc28doM9AdKq51ZEYx3JU3VqKE/+quCgeEmz5vE7OSya7jSE+v0jTD7JOKTs/hwJWslKCr93R/mspG38Pv5Lq/ksNRLwz
m9fIgtGblTCK/O/oz6iSSNvhJL54Uu+8C9X2k+rUcHDGi7SkqRdrpmdudgfGHQuOwLOA7lQlh1yKuDy5pEeVmyrgUFqehpa37vDS
CswLKbmv3UA3Op95mptfwdj6b+Jqy4/V9bSW9KbBgAmYhFoQM29QLbL+c3bCjPmPxxe9ff/on/KPR5tHRBeeIlywWbZh+CMWoYkt
NqnfihsZJgT0EECsY7tPNPK5BphIPstuKTjxPPDXG5XhVpF7NLC2/yhvMmOu1X0Hzp4jKf3C8zvlZOPK5UBIbfB7EQOzMZdqtHzq
BHdA9FSFNSUm2fVRCA1YDtUAOqF6AF/j0btxILsn/C5jANRGZPcVWzoowmd6//xYMHCqJqW8Df2yAAAAAA==
";
+353
View File
@@ -0,0 +1,353 @@
//! The KDBX 4 file format (docs/KDBX.md, "Tests"): round trips, keys, tampering, hostile input.
use custos_kdbx::{
AutoType, Cipher, Database, Entry, Error, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times,
WriteOptions, read, testing, write,
};
use custos_vault::Attachment;
use sha2::{Digest, Sha256};
/// Cheap parameters so the tamper tests can run the KDF once per byte.
const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } };
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
fn s(key: &str, value: &str, protected: bool) -> StringField {
StringField { key: key.into(), value: value.into(), protected }
}
pub fn sample() -> Database {
let snapshot = Entry {
uuid: [2; 16],
strings: vec![s("Title", "GitHub", false), s("Password", "Old-Secret-Value", true)],
times: Times { created: 1_700_000_000, modified: 1_700_000_100, expires: None },
..Default::default()
};
let login = Entry {
uuid: [2; 16],
strings: vec![
s("Title", "GitHub & <Gist>", false),
s("UserName", "alice", false),
s("Password", "Hunter2-Secret-Value", true),
s("URL", "https://github.com", false),
s("Notes", "line one\r\nline \"two\"\n\ttabbed — Česky", false),
s("Recovery code", "Protected-Recovery-Code", true),
s("Empty protected", "", true),
s("Plain", "", false),
],
attachments: vec![Attachment {
name: "id_ed25519".into(),
data: SecretBytes::from(&b"\x00\x01Attached-Key"[..]),
}],
tags: vec!["dev".into(), "work".into()],
times: Times { created: 1_700_000_000, modified: 1_700_000_200, expires: Some(1_800_000_000) },
autotype: AutoType {
default_sequence: "{USERNAME}{TAB}{PASSWORD}{ENTER}".into(),
windows: vec!["*GitHub*".into()],
},
history: vec![snapshot],
};
let note = Entry {
uuid: [3; 16],
strings: vec![s("Title", "Note", false), s("Notes", "just text", false)],
times: Times { created: 0, modified: 0, expires: None },
..Default::default()
};
Database {
name: "Test database".into(),
root: Group {
uuid: [1; 16],
name: "Root".into(),
entries: vec![note],
groups: vec![Group {
uuid: [4; 16],
name: "Internet".into(),
entries: vec![login],
groups: vec![Group { uuid: [5; 16], name: "Empty".into(), ..Default::default() }],
}],
},
recycle_bin: None,
}
}
fn key(p: &SecretString) -> Key<'_> {
Key { password: Some(p), key_file: None }
}
#[test]
fn write_then_read_is_identical_for_every_cipher_and_kdf() {
let db = sample();
let p = pw("correct horse");
for cipher in [Cipher::ChaCha20, Cipher::Aes256] {
for kdf in
[Kdf::Argon2id { m_kib: 64, t: 1, p: 1 }, Kdf::Argon2d { m_kib: 128, t: 2, p: 2 }, Kdf::Aes { rounds: 100 }]
{
let bytes = write(&db, &key(&p), WriteOptions { cipher, kdf }).unwrap();
assert_eq!(read(&bytes, &key(&p)).unwrap(), db, "{cipher:?} {kdf:?}");
}
}
// Every write is fresh: seed, IV, salt and inner stream key.
assert_ne!(write(&db, &key(&p), FAST).unwrap(), write(&db, &key(&p), FAST).unwrap());
}
#[test]
fn the_wrong_password_or_no_key_fails_clearly() {
let p = pw("right");
let bytes = write(&sample(), &key(&p), FAST).unwrap();
assert_eq!(read(&bytes, &key(&pw("wrong"))), Err(Error::WrongKey));
assert_eq!(read(&bytes, &Key::default()), Err(Error::NoKey));
// An empty password is no password.
assert_eq!(read(&bytes, &key(&pw(""))), Err(Error::NoKey));
let e = read(&bytes, &key(&pw("Typed-Attempt-9"))).unwrap_err().to_string();
assert!(!e.contains("Typed-Attempt-9") && !e.contains("right"), "{e}");
}
fn xml_v2(key: &[u8; 32]) -> Vec<u8> {
let hex: String = key.iter().map(|b| format!("{b:02X}")).collect();
let hash: String = Sha256::digest(key)[..4].iter().map(|b| format!("{b:02X}")).collect();
let (a, b) = hex.split_at(32);
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<KeyFile>\n\t<Meta>\n\t\t<Version>2.0</Version>\n\t</Meta>\n\t<Key>\n\t\t<Data Hash=\"{hash}\">\n\t\t\t{a}\n\t\t\t{b}\n\t\t</Data>\n\t</Key>\n</KeyFile>\n"
)
.into_bytes()
}
#[test]
fn every_key_file_kind_works_alone_and_with_a_password() {
let raw: [u8; 32] = core::array::from_fn(|i| (i * 7 + 3) as u8);
let hex: Vec<u8> = raw.iter().map(|b| format!("{b:02x}")).collect::<String>().into_bytes();
let v1 = format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?><KeyFile><Meta><Version>1.00</Version></Meta><Key><Data>{}</Data></Key></KeyFile>",
data_encoding::BASE64.encode(&raw)
)
.into_bytes();
// These four are the same 32-byte key written four ways: each opens what another wrote.
let same = [raw.to_vec(), hex, xml_v2(&raw), v1];
let p = pw("pw");
for with_pw in [false, true] {
fn k<'a>(p: Option<&'a SecretString>, f: &'a [u8]) -> Key<'a> {
Key { password: p, key_file: Some(f) }
}
let p = with_pw.then_some(&p);
let bytes = write(&sample(), &k(p, &same[0]), FAST).unwrap();
for f in &same {
assert_eq!(read(&bytes, &k(p, f)).unwrap(), sample());
}
assert_eq!(read(&bytes, &k(p, b"another file")), Err(Error::WrongKey));
if let Some(p) = p {
assert_eq!(read(&bytes, &key(p)), Err(Error::WrongKey), "the key file is needed too");
}
}
// Any other file is hashed.
let photo = b"\x89PNG not really a key file, just some bytes".to_vec();
let bytes = write(&sample(), &Key { password: None, key_file: Some(&photo) }, FAST).unwrap();
assert!(read(&bytes, &Key { password: None, key_file: Some(&photo) }).is_ok());
// A version 2.0 key file with a wrong checksum is refused, not guessed.
let mut bad = xml_v2(&raw);
let at = bad.windows(6).position(|w| w == b"Hash=\"").unwrap() + 6;
bad[at] = if bad[at] == b'0' { b'1' } else { b'0' };
assert_eq!(
write(&sample(), &Key { password: None, key_file: Some(&bad) }, FAST),
Err(Error::Malformed("key file checksum"))
);
}
/// Where the parts of a file written with FAST start: header end, then the 64 bytes of hash + HMAC.
fn header_len(bytes: &[u8]) -> usize {
let mut pos = 12;
loop {
let id = bytes[pos];
let len = u32::from_le_bytes(bytes[pos + 1..pos + 5].try_into().unwrap()) as usize;
pos += 5 + len;
if id == 0 {
return pos;
}
}
}
#[test]
fn changing_any_byte_fails_and_never_panics() {
let p = pw("pw");
let small = Database { name: "x".into(), ..Default::default() };
let bytes = write(&small, &key(&p), FAST).unwrap();
let h = header_len(&bytes);
for i in 0..bytes.len() {
let mut b = bytes.clone();
b[i] ^= 0x01;
let r = read(&b, &key(&p));
assert!(r.is_err(), "byte {i} of {} changed and the file still opened", bytes.len());
let e = r.unwrap_err();
if (12..h).contains(&i) || (h..h + 32).contains(&i) {
// Header or its hash: caught by the hash (or the field structure) before any key work.
assert!(matches!(e, Error::Corrupted | Error::Malformed(_) | Error::NotKdbx), "byte {i}: {e:?}");
} else if (h + 32..h + 64).contains(&i) {
assert_eq!(e, Error::WrongKey, "byte {i} (header HMAC)");
} else if i >= h + 64 {
assert_eq!(e, Error::Corrupted, "byte {i} (blocks)");
}
}
}
#[test]
fn truncation_at_any_point_fails() {
let p = pw("pw");
let bytes = write(&Database::default(), &key(&p), FAST).unwrap();
for len in 0..bytes.len() {
assert!(read(&bytes[..len], &key(&p)).is_err(), "truncated to {len}");
}
}
#[test]
fn not_kdbx_kdbx3_and_future_versions() {
let p = pw("pw");
assert_eq!(read(b"", &key(&p)), Err(Error::NotKdbx));
assert_eq!(read(b"PK\x03\x04 a zip file", &key(&p)), Err(Error::NotKdbx));
let mut kdb1 = vec![0x03, 0xD9, 0xA2, 0x9A, 0x65, 0xFB, 0x4B, 0xB5];
kdb1.extend([0; 120]);
assert_eq!(read(&kdb1, &key(&p)), Err(Error::NotKdbx));
let good = write(&Database::default(), &key(&p), FAST).unwrap();
let with_version = |minor: u16, major: u16| {
let mut b = good.clone();
b[8..10].copy_from_slice(&minor.to_le_bytes());
b[10..12].copy_from_slice(&major.to_le_bytes());
b
};
assert_eq!(read(&with_version(1, 2), &key(&p)), Err(Error::UnsupportedVersion(2, 1)));
assert_eq!(read(&with_version(0, 5), &key(&p)), Err(Error::UnsupportedVersion(5, 0)));
// KDBX 4.1 reads like 4.0 (only the header hash notices the changed version bytes).
let v41 = with_version(1, 4);
assert_eq!(read(&v41, &key(&p)), Err(Error::Corrupted));
}
/// Replaces the cipher id in a file and fixes the header hash, so only the cipher is wrong.
fn with_cipher(bytes: &[u8], id: [u8; 16]) -> Vec<u8> {
let mut b = bytes.to_vec();
assert_eq!(b[12], 2, "the cipher is the first field");
b[17..33].copy_from_slice(&id);
let h = header_len(&b);
let hash = Sha256::digest(&b[..h]);
b[h..h + 32].copy_from_slice(&hash);
b
}
#[test]
fn twofish_and_unknown_ciphers_are_refused() {
let p = pw("pw");
let bytes = write(&Database::default(), &key(&p), FAST).unwrap();
let twofish = 0xad68f29f_576f_4bb9_a36a_d47af965346cu128.to_be_bytes();
assert_eq!(read(&with_cipher(&bytes, twofish), &key(&p)), Err(Error::UnsupportedCipher));
assert_eq!(read(&with_cipher(&bytes, [0; 16]), &key(&p)), Err(Error::UnsupportedCipher));
}
#[test]
fn kdf_parameters_out_of_limits_are_refused_before_any_work() {
let p = pw("pw");
let inner = testing::inner(3, b"<KeePassFile/>");
let t = [0u8; 32];
let start = std::time::Instant::now();
for dict in [
testing::argon2_dict(true, 4 << 30, 1, 1, 0x13), // 4 GiB
testing::argon2_dict(true, (64 << 10) + 1, 1, 1, 0x13), // not whole KiB
testing::argon2_dict(true, 64 << 10, 1001, 1, 0x13),
testing::argon2_dict(true, 64 << 10, 0, 1, 0x13),
testing::argon2_dict(false, 64 << 10, 1, 0, 0x13),
testing::argon2_dict(false, 64 << 10, 1, 65, 0x13),
testing::argon2_dict(false, 64 << 10, 1, 1, 0x10), // Argon2 version 1.0
testing::aes_dict(1 << 31),
testing::aes_dict(0),
] {
assert_eq!(read(&testing::build(&dict, &t, &inner, true), &key(&p)), Err(Error::UnsupportedKdf));
}
assert!(start.elapsed().as_secs() < 5, "the limits are checked before Argon2 or AES-KDF runs");
}
/// A file that opens with password "pw" (AES-KDF, 1 round) around this inner XML.
fn file_around(xml: &[u8], stream: u32) -> Vec<u8> {
testing::build(&testing::aes_dict(1), &testing::aes_transformed("pw", 1), &testing::inner(stream, xml), true)
}
#[test]
fn the_test_builder_itself_makes_files_that_open() {
let xml =
b"<KeePassFile><Root><Group><UUID>AAAAAAAAAAAAAAAAAAAAAA==</UUID><Name>R</Name></Group></Root></KeePassFile>";
let db = read(&file_around(xml, 3), &key(&pw("pw"))).unwrap();
assert_eq!(db.root.name, "R");
}
#[test]
fn doctype_and_entity_tricks_are_refused() {
let laughs = br#"<?xml version="1.0"?>
<!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">]>
<KeePassFile><Meta><DatabaseName>&lol2;</DatabaseName></Meta></KeePassFile>"#;
assert_eq!(read(&file_around(laughs, 3), &key(&pw("pw"))), Err(Error::Malformed("XML with a DOCTYPE")));
let xxe =
br#"<?xml version="1.0"?><!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><KeePassFile>&e;</KeePassFile>"#;
assert_eq!(read(&file_around(xxe, 3), &key(&pw("pw"))), Err(Error::Malformed("XML with a DOCTYPE")));
}
#[test]
fn deep_nesting_and_broken_xml_are_refused() {
let mut deep = b"<KeePassFile><Root>".to_vec();
for _ in 0..300 {
deep.extend_from_slice(b"<Group><UUID>AAAAAAAAAAAAAAAAAAAAAA==</UUID>");
}
for _ in 0..300 {
deep.extend_from_slice(b"</Group>");
}
deep.extend_from_slice(b"</Root></KeePassFile>");
assert_eq!(read(&file_around(&deep, 3), &key(&pw("pw"))), Err(Error::Malformed("groups nested too deeply")));
for bad in [&b"<KeePassFile><Root>"[..], b"not xml", b"\xff\xfe", b"<Other/>"] {
assert!(matches!(read(&file_around(bad, 3), &key(&pw("pw"))), Err(Error::Malformed(_))));
}
// A protected value that is not base64, and an attachment reference to nothing.
let bad_value = b"<KeePassFile><Root><Group><Entry><String><Key>Password</Key><Value Protected=\"True\">!!</Value></String></Entry></Group></Root></KeePassFile>";
assert_eq!(read(&file_around(bad_value, 3), &key(&pw("pw"))), Err(Error::Malformed("protected value")));
let bad_ref = b"<KeePassFile><Root><Group><Entry><Binary><Key>a</Key><Value Ref=\"7\"/></Binary></Entry></Group></Root></KeePassFile>";
assert_eq!(read(&file_around(bad_ref, 3), &key(&pw("pw"))), Err(Error::Malformed("attachment")));
}
#[test]
fn salsa20_inner_stream_is_refused() {
let xml = b"<KeePassFile/>";
assert_eq!(read(&file_around(xml, 2), &key(&pw("pw"))), Err(Error::UnsupportedStream));
assert_eq!(read(&file_around(xml, 0), &key(&pw("pw"))), Err(Error::UnsupportedStream));
}
#[test]
fn a_gzip_bomb_stops_at_the_limit() {
// 600 MiB of zeros, compressed: a few hundred KiB on disk.
use flate2::{Compression, write::GzEncoder};
use std::io::Write;
let mut gz = GzEncoder::new(Vec::new(), Compression::fast());
let zeros = vec![0u8; 1 << 20];
gz.write_all(&testing::inner(3, b"")).unwrap();
for _ in 0..600 {
gz.write_all(&zeros).unwrap();
}
let bomb = gz.finish().unwrap();
assert!(bomb.len() < 4 << 20);
let file = testing::build_compressed(&testing::aes_dict(1), &testing::aes_transformed("pw", 1), &bomb);
assert_eq!(read(&file, &key(&pw("pw"))), Err(Error::TooLarge));
}
#[test]
fn no_secret_in_debug_output() {
let db = sample();
let p = pw("Master-Password-Here");
let file = [7u8; 32];
let k = Key { password: Some(&p), key_file: Some(&file) };
for out in [format!("{db:?}"), format!("{db:#?}"), format!("{k:?}"), format!("{:?}", Error::WrongKey)] {
for leaked in [
"Hunter2-Secret-Value",
"Protected-Recovery-Code",
"Old-Secret-Value",
"Attached-Key",
"Master-Password-Here",
] {
assert!(!out.contains(leaked), "{leaked} in {out}");
}
}
assert!(format!("{db:?}").contains("Internet"), "non-secret parts stay readable");
}
+87
View File
@@ -0,0 +1,87 @@
//! Files KeePassXC wrote open with what tools/kdbx/sample.xml put in them (docs/KDBX.md, "Tests").
use custos_kdbx::{Error, Key, SecretString, read, to_items};
use custos_vault::{Item, ItemType};
include!("data/keepassxc_files.rs");
fn bytes(b64: &str) -> Vec<u8> {
let clean: String = b64.split_whitespace().collect();
data_encoding::BASE64.decode(clean.as_bytes()).unwrap()
}
fn open(b64: &str) -> custos_kdbx::Database {
let p = SecretString::from("custos-test");
read(&bytes(b64), &Key { password: Some(&p), key_file: None }).unwrap()
}
fn field<'a>(item: &'a Item, name: &str) -> Vec<&'a str> {
item.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect()
}
fn check(items: &[Item]) {
let by = |title: &str| items.iter().find(|i| i.title == title).unwrap_or_else(|| panic!("no {title}"));
let gh = by("GitHub");
assert_eq!(gh.id, "11".repeat(16));
assert_eq!(gh.kind, ItemType::WebLogin);
assert_eq!(gh.folder, ["Internet"]);
assert_eq!(field(gh, "username"), ["alice"]);
assert_eq!(field(gh, "password"), ["Hunter3-Current & <ok>"]);
assert_eq!(field(gh, "url"), ["https://github.com", "https://gist.github.com", "https://api.github.com"]);
assert!(field(gh, "totp")[0].starts_with("otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP"));
assert_eq!(field(gh, "Recovery codes"), ["Recovery-Secret-123"]);
assert!(gh.field("Recovery codes").unwrap().secret, "protected in KeePass, secret in Custos");
assert_eq!(field(gh, "Account id"), ["42"]);
assert!(!gh.field("Account id").unwrap().secret);
assert_eq!(field(gh, "expires"), ["2030-01-01"]);
assert_eq!(field(gh, "autotype-sequence"), ["{USERNAME}{TAB}{PASSWORD}{ENTER}"]);
assert_eq!(field(gh, "autotype-match"), ["*GitHub*", "Firefox - GitHub"]);
assert_eq!(gh.notes.expose(), "Line one\nLine two & <three>");
assert_eq!(gh.tags, ["dev", "work"]);
assert_eq!(gh.created, 1_682_935_200_000); // 2023-05-01T10:00:00Z
assert_eq!(gh.modified, 1_769_938_200_000); // 2026-02-01T09:30:00Z
let history: Vec<(&str, i64)> = gh.history.iter().map(|h| (h.value.expose(), h.changed)).collect();
assert_eq!(history, [("Hunter1-Oldest", 1_704_096_000_000), ("Hunter2-Old", 1_735_718_400_000)]);
assert!(gh.history.iter().all(|h| h.field == "password"));
assert_eq!(gh.attachments.len(), 1);
assert_eq!(gh.attachments[0].name, "codes.txt");
assert_eq!(gh.attachments[0].data.expose(), b"Backup codes:\n1111-2222\n3333-4444\n");
let mail = by("Mail");
assert_eq!(mail.folder, ["Internet", "Mail"]);
assert_eq!(field(mail, "totp"), ["otpauth://totp/Mail?secret=JBSWY3DPEHPK3PXP&period=60&digits=8"]);
let note = by("Alarm code");
assert_eq!(note.kind, ItemType::SecureNote, "no user name, password or URL");
assert!(note.folder.is_empty());
assert_eq!(note.notes.expose(), "Front door: 4711");
}
#[test]
fn keepassxc_kdbx_3_1_with_a_recycle_bin() {
let db = open(V3);
assert_eq!(db.name, "Custos interop");
assert!(db.recycle_bin.is_some());
let items = to_items(&db);
check(&items);
assert_eq!(items.len(), 3, "the recycle bin's entry is not imported");
assert!(items.iter().all(|i| i.title != "Old account"));
}
#[test]
fn keepassxc_kdbx_4() {
let db = open(V4);
let items = to_items(&db);
check(&items);
// This file's recycle bin is switched off, so the merged "Recycle Bin" is an ordinary group.
assert!(items.iter().any(|i| i.title == "Old account" && i.folder == ["Recycle Bin"]));
}
#[test]
fn keepassxc_files_refuse_the_wrong_password() {
let wrong = SecretString::from("custos-test ");
for f in [V3, V4] {
assert_eq!(read(&bytes(f), &Key { password: Some(&wrong), key_file: None }), Err(Error::WrongKey));
}
}
+262
View File
@@ -0,0 +1,262 @@
//! Custos items ↔ KeePass entries (docs/KDBX.md, "Mapping").
use custos_kdbx::{
AutoType, Cipher, Database, Entry, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times, WriteOptions,
from_items, read, to_items, write,
};
use custos_vault::{Attachment, Field, Item, ItemType};
const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } };
const T: i64 = 1_790_000_000_000; // whole seconds: KeePass keeps seconds
fn through_a_file(items: &[Item]) -> Vec<Item> {
let p = SecretString::from("pw");
let key = Key { password: Some(&p), key_file: None };
let bytes = write(&from_items(items, "Custos"), &key, FAST).unwrap();
to_items(&read(&bytes, &key).unwrap())
}
fn every_type() -> Vec<Item> {
let mut login = Item::new(ItemType::WebLogin, "GitHub", T);
login.set("username", "alice", T);
login.set("password", "First-Pass-1", T);
login.set("password", "Second-Pass-2", T + 1000);
login.set("password", "Current-Pass-3", T + 2000);
login.set("url", "https://github.com", T);
login.set("totp", "JBSWY3DPEHPK3PXP", T);
login.set("autotype-match", "*GitHub*", T);
login.set("autotype-sequence", "{USERNAME}{TAB}{PASSWORD}{ENTER}", T);
login.add_field(Field::text("url", "https://gist.github.com"));
login.add_field(Field::text("url", "https://api.github.com"));
login.add_field(Field::secret("Recovery code", "Recovery-1234"));
login.add_field(Field::text("Account", ""));
login.add_field(Field::text("expires", "2031-06-30T12:00:00Z"));
login.add_field(Field::text("autotype-match", "Firefox - GitHub"));
login.tags = vec!["dev".into(), "work".into()];
login.notes = "line one\r\nline <two> & \"three\"".into();
login.folder = vec!["Internet".into(), "Code".into()];
login.modified = T + 2000;
let mut api = Item::new(ItemType::ApiCredential, "Stripe", T);
for (k, v) in
[("service", "Stripe"), ("key-id", "pk_live_1"), ("secret", "sk-Old"), ("endpoint", "https://api.stripe.com")]
{
api.set(k, v, T);
}
api.set("secret", "sk-New", T + 5000);
api.set("expires", "2027-01-31", T);
let mut app = Item::new(ItemType::LocalApp, "Backup tool", T);
for (k, v) in [("target", "restic"), ("username", "backup"), ("password", "Restic-Pass")] {
app.set(k, v, T);
}
let mut wifi = Item::new(ItemType::Wifi, "Home", T);
for (k, v) in [("ssid", "Domi"), ("password", "Wifi-Pass"), ("security", "WPA"), ("hidden", "false")] {
wifi.set(k, v, T);
}
let mut note = Item::new(ItemType::SecureNote, "Keys", T);
note.notes = "the spare key is with the neighbours".into();
note.attachments =
vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\xffkey bytes"[..]) }];
note.folder = vec!["Home".into()];
let mut card = Item::new(ItemType::Card, "Visa", T);
for (k, v) in [
("cardholder", "A N Other"),
("number", "4111111111111111"),
("expiry", "12/29"),
("cvv", "123"),
("pin", "0000"),
] {
card.set(k, v, T);
}
// Two secret fields changed at the same moment: one KeePass snapshot.
card.set("number", "4000000000000002", T + 9000);
card.set("cvv", "456", T + 9000);
let mut pair = Item::new(ItemType::KeyPair, "Signing key", T);
for (k, v) in [
("algorithm", "ed25519"),
("public-key", "ssh-ed25519 AAAA… me"),
("private-key", "-----BEGIN PRIVATE KEY-----\nMC4…\n-----END PRIVATE KEY-----\n"),
] {
pair.set(k, v, T);
}
let empty: Vec<Item> = ItemType::ALL.into_iter().map(|k| Item::new(k, &format!("empty {k:?}"), T)).collect();
[vec![login, api, app, wifi, note, card, pair], empty].concat()
}
#[test]
fn every_item_type_survives_export_and_import() {
let items = every_type();
let back = through_a_file(&items);
assert_eq!(back.len(), items.len());
// Items come back folder by folder (root first), so match them by id.
for a in &items {
let b = back.iter().find(|b| b.id == a.id).unwrap_or_else(|| panic!("{} is missing", a.title));
assert_eq!(a, b, "{}", a.title);
for (fa, fb) in a.fields.iter().zip(&b.fields) {
assert_eq!(fa.value, fb.value, "{} / {}", a.title, fa.name);
}
assert_eq!(a.notes, b.notes, "{}", a.title);
}
}
#[test]
fn the_export_looks_like_keepass_to_keepassxc() {
let db = from_items(&every_type(), "Custos");
let internet = db.root.groups.iter().find(|g| g.name == "Internet").unwrap();
let gh = &internet.groups[0].entries[0];
assert_eq!(internet.groups[0].name, "Code");
let get = |e: &Entry, k: &str| e.get(k).map(|v| v.expose().to_owned());
assert_eq!(get(gh, "UserName").as_deref(), Some("alice"));
assert_eq!(get(gh, "URL").as_deref(), Some("https://github.com"));
assert_eq!(get(gh, "KP2A_URL").as_deref(), Some("https://gist.github.com"));
assert_eq!(get(gh, "KP2A_URL_1").as_deref(), Some("https://api.github.com"));
assert_eq!(get(gh, "otp").as_deref(), Some("JBSWY3DPEHPK3PXP"));
assert!(gh.strings.iter().find(|s| s.key == "Password").unwrap().protected);
assert!(gh.strings.iter().find(|s| s.key == "Recovery code").unwrap().protected);
assert!(gh.get("custos-type").is_none(), "a login looks like a login without help");
assert_eq!(gh.times.expires, custos_kdbx::parse_iso("2031-06-30T12:00:00Z"));
assert_eq!(gh.autotype.windows, ["*GitHub*", "Firefox - GitHub"]);
// Two password changes: two snapshots, oldest first, each with the password it had then.
let old: Vec<String> = gh.history.iter().map(|h| h.get("Password").unwrap().expose().to_owned()).collect();
assert_eq!(old, ["First-Pass-1", "Second-Pass-2"]);
let entry = |title: &str| {
fn find<'a>(g: &'a Group, t: &str) -> Option<&'a Entry> {
g.entries
.iter()
.find(|e| e.get("Title").unwrap().expose() == t)
.or_else(|| g.groups.iter().find_map(|s| find(s, t)))
}
find(&db.root, title).unwrap()
};
let api = entry("Stripe");
assert_eq!(api.get("custos-type").unwrap().expose(), "api-credential");
assert_eq!(api.get("Password").unwrap().expose(), "sk-New");
assert_eq!(api.times.expires, custos_kdbx::parse_iso("2027-01-31"));
let card = entry("Visa");
assert_eq!(card.get("UserName").unwrap().expose(), "A N Other");
assert_eq!(card.get("Password").unwrap().expose(), "4000000000000002");
assert!(card.strings.iter().find(|s| s.key == "cvv").unwrap().protected);
assert_eq!(card.history.len(), 1, "both changes in one snapshot");
assert_eq!(card.history[0].get("cvv").unwrap().expose(), "123");
assert_eq!(card.history[0].get("Password").unwrap().expose(), "4111111111111111");
assert_eq!(entry("Home").get("UserName").unwrap().expose(), "Domi", "Wi-Fi: SSID as the user name");
assert!(entry("Keys").get("custos-type").is_none(), "a note looks like a note");
// Empty template fields stay out; Custos's own type and template names come back as custom strings.
assert!(entry("empty ApiCredential").get("key-id").is_none());
}
fn s(key: &str, value: &str, protected: bool) -> StringField {
StringField { key: key.into(), value: value.into(), protected }
}
#[test]
fn a_keepass_database_maps_as_the_table_says() {
let entry = |n: u8, strings: Vec<StringField>| Entry {
uuid: [n; 16],
strings,
times: Times { created: 1_700_000_000, modified: 1_700_000_500, expires: None },
..Default::default()
};
let mut login = entry(
1,
vec![
s("Notes", "n", false),
s("KP2A_URL_2", "https://three.example", false),
s("KP2A_URL", "https://two.example", false),
s("Password", "Now-1", true),
s("PIN", "9999", true),
s("Title", "Bank", false),
s("TOTP Seed", "JBSW Y3DP EHPK 3PXP", true),
s("URL", "https://one.example", false),
s("UserName", "me", false),
],
);
login.tags = vec!["money".into(), "important".into()];
login.autotype = AutoType { default_sequence: "{PASSWORD}{ENTER}".into(), windows: vec![] };
// Snapshots: the PIN changed first, then the password; the last one changed nothing secret.
login.history = vec![
entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "1111", true)]),
entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "9999", true)]),
entry(1, vec![s("Title", "Bank renamed", false), s("Password", "Now-1", true), s("PIN", "9999", true)]),
];
for (i, h) in login.history.iter_mut().enumerate() {
h.times.modified = 1_700_000_100 + i as i64 * 100;
}
let only_custom = entry(2, vec![s("Title", "Licence", false), s("Licence key", "ABCD-EFGH", true)]);
let binned = entry(3, vec![s("Title", "Deleted", false), s("Password", "x", true)]);
let db = Database {
name: "KeePass".into(),
root: Group {
uuid: [9; 16],
name: "Root".into(),
entries: vec![only_custom],
groups: vec![
Group { uuid: [8; 16], name: "Banking".into(), entries: vec![login], groups: vec![] },
Group { uuid: [7; 16], name: "Recycle Bin".into(), entries: vec![binned], groups: vec![] },
],
},
recycle_bin: Some([7; 16]),
};
let items = to_items(&db);
assert_eq!(items.len(), 2, "nothing from the recycle bin");
let licence = &items[0];
assert_eq!(licence.kind, ItemType::SecureNote);
assert_eq!(licence.fields, [Field::secret("Licence key", "ABCD-EFGH")]);
let bank = &items[1];
assert_eq!(bank.kind, ItemType::WebLogin);
assert_eq!(bank.id, "01".repeat(16));
assert_eq!(bank.folder, ["Banking"]);
assert_eq!(bank.tags, ["money", "important"]);
let f = |name: &str| bank.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect::<Vec<_>>();
assert_eq!(f("url"), ["https://one.example", "https://two.example", "https://three.example"]);
assert_eq!(f("totp"), ["JBSWY3DPEHPK3PXP"], "default settings: the bare seed, spaces removed");
assert_eq!(f("PIN"), ["9999"]);
assert_eq!(f("autotype-sequence"), ["{PASSWORD}{ENTER}"]);
let h: Vec<(&str, &str, i64)> =
bank.history.iter().map(|h| (h.field.as_str(), h.value.expose(), h.changed)).collect();
assert_eq!(h, [("PIN", "1111", 1_700_000_100_000), ("password", "Old-1", 1_700_000_200_000)]);
assert_eq!(bank.created, 1_700_000_000_000);
assert_eq!(bank.modified, 1_700_000_500_000);
}
#[test]
fn field_names_keepass_reserves_are_renamed_not_lost() {
let mut item = Item::new(ItemType::WebLogin, "Odd", T);
item.add_field(Field::text("Title", "a field called Title"));
item.add_field(Field::secret("custos-type", "not a type"));
item.add_field(Field::text("KP2A_URL", "not a URL"));
let db = from_items(&[item], "x");
let e = &db.root.entries[0];
assert_eq!(e.get("Title").unwrap().expose(), "Odd");
assert_eq!(e.get("Title (2)").unwrap().expose(), "a field called Title");
assert_eq!(e.get("custos-type (2)").unwrap().expose(), "not a type");
assert_eq!(e.get("KP2A_URL (2)").unwrap().expose(), "not a URL");
let keys: Vec<&str> = e.strings.iter().map(|s| s.key.as_str()).collect();
let mut unique = keys.clone();
unique.sort();
unique.dedup();
assert_eq!(keys.len(), unique.len(), "keys are unique: {keys:?}");
}
#[test]
fn ids_survive_and_bad_ids_get_a_fresh_uuid() {
let mut a = Item::new(ItemType::SecureNote, "a", T);
a.id = "00112233445566778899aabbccddeeff".into();
let mut b = Item::new(ItemType::SecureNote, "b", T);
b.id = "not hex".into();
let db = from_items(&[a, b], "x");
assert_eq!(
db.root.entries[0].uuid,
[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]
);
assert_ne!(db.root.entries[1].uuid, [0; 16]);
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "custos-native"
description = "Custos's native messaging host: the browser extension's way to the desktop Custos"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-browser = { path = "../custos-browser" }
serde_json.workspace = true
zeroize.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] }
+240
View File
@@ -0,0 +1,240 @@
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it
//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards
//! three requests to the desktop Custos over its Domi pipe and returns the answers:
//!
//! - `browser_status`: is Custos running and unlocked;
//! - `browser_match { origin }`: the logins for a page (title, username; never a password);
//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page.
//!
//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the
//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from
//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses
//! a pipe that is not served by custos.exe.
use std::io::{self, Write};
use custos_browser::framing::{read_frame, write_frame};
use serde_json::{Value, json};
use zeroize::Zeroizing;
const PIPE: &str = r"\\.\pipe\custos-domi";
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill"];
/// The request Custos gets: only known fields, of the right types.
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> {
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
let mut out = json!({ "op": op, "app": "Custos for your browser" });
if op != "browser_status" {
let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?;
out["origin"] = origin.into();
}
if op == "browser_fill" {
let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?;
out["id"] = id.into();
}
// The extension's own request number comes back with the answer, so it can pair them.
if let Some(n) = v.get("seq").and_then(Value::as_u64) {
out["seq"] = n.into();
}
Ok(out)
}
fn error(code: &str, seq: Option<u64>) -> Vec<u8> {
serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default()
}
fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> {
let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64));
let req = match rebuild(msg) {
Ok(r) => r,
Err(code) => return Zeroizing::new(error(code, seq)),
};
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
match pipe::call(pipe, &bytes) {
Ok(resp) => {
// Custos does not know the extension's request number: put it back.
let Ok(mut v) = serde_json::from_slice::<Value>(&resp) else {
return Zeroizing::new(error("bad_answer", seq));
};
if let (Some(obj), Some(n)) = (v.as_object_mut(), seq) {
obj.insert("seq".into(), n.into());
}
let out = Zeroizing::new(serde_json::to_vec(&v).unwrap_or_default());
zeroize_json(v);
out
}
Err(code) => Zeroizing::new(error(code, seq)),
}
}
/// Wipes the strings of a parsed answer (it can hold a password) before dropping it.
fn zeroize_json(v: Value) {
use zeroize::Zeroize;
match v {
Value::String(mut s) => s.zeroize(),
Value::Array(a) => a.into_iter().for_each(zeroize_json),
Value::Object(o) => o.into_iter().for_each(|(_, v)| zeroize_json(v)),
_ => {}
}
}
fn main() {
// Tests point the host at another Custos.
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
loop {
let msg = match read_frame(&mut stdin) {
Ok(Some(m)) => m,
// The extension disconnected, or sent something that is not a frame: done.
Ok(None) | Err(_) => return,
};
let out = answer(&msg, &pipe);
let mut w = stdout.lock();
if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
return;
}
}
}
#[cfg(windows)]
mod pipe {
use std::time::Duration;
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
INVALID_HANDLE_VALUE,
};
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, OPEN_EXISTING, ReadFile, WriteFile};
use windows_sys::Win32::System::Pipes::{
GetNamedPipeServerProcessId, PIPE_READMODE_MESSAGE, SetNamedPipeHandleState, WaitNamedPipeW,
};
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
};
use zeroize::Zeroizing;
struct Handle(HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
unsafe { CloseHandle(self.0) };
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn server_exe(h: HANDLE) -> Option<String> {
unsafe {
let mut pid = 0u32;
if GetNamedPipeServerProcessId(h, &mut pid) == 0 {
return None;
}
let p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if p.is_null() {
return None;
}
let p = Handle(p);
let mut buf = vec![0u16; 1024];
let mut len = buf.len() as u32;
let ok = QueryFullProcessImageNameW(p.0, 0, buf.as_mut_ptr(), &mut len);
(ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
}
}
/// One request, one answer. The error is a code the extension shows as a sentence.
pub fn call(name: &str, request: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
let w = wide(name);
unsafe {
let mut h = INVALID_HANDLE_VALUE;
// Busy: every instance is in use. Not found: Custos is between instances for a moment, or not running.
for _ in 0..50 {
h = CreateFileW(
w.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
0,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
);
if h != INVALID_HANDLE_VALUE {
break;
}
match GetLastError() {
ERROR_PIPE_BUSY => {
WaitNamedPipeW(w.as_ptr(), 200);
}
ERROR_FILE_NOT_FOUND => std::thread::sleep(Duration::from_millis(20)),
_ => break,
}
}
if h == INVALID_HANDLE_VALUE {
return Err("not_running");
}
let h = Handle(h);
// Anything else serving this pipe could collect passwords: only custos.exe gets the request.
if !server_exe(h.0).unwrap_or_default().to_lowercase().ends_with("\\custos.exe") {
return Err("not_custos");
}
let mode = PIPE_READMODE_MESSAGE;
SetNamedPipeHandleState(h.0, &mode, std::ptr::null(), std::ptr::null());
let mut n = 0u32;
if WriteFile(h.0, request.as_ptr(), request.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
return Err("not_running");
}
let mut buf = Zeroizing::new(vec![0u8; 64 * 1024]);
if ReadFile(h.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
return Err("no_answer");
}
buf.truncate(n as usize);
Ok(buf)
}
}
}
#[cfg(not(windows))]
mod pipe {
pub fn call(_: &str, _: &[u8]) -> Result<zeroize::Zeroizing<Vec<u8>>, &'static str> {
Err("not_running")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() {
let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap();
assert_eq!(
fill,
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" })
);
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status");
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok());
// Custos's other Domi requests never pass through the browser's host.
for other in [
r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#,
r#"{"op":"list","namespace":"arca"}"#,
r#"{"op":"set","ref":"domi://x/y","value":"v"}"#,
r#"{"op":"subkey"}"#,
] {
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}");
}
// Missing or wrong fields.
assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err());
assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err());
assert!(rebuild(b"not json").is_err());
}
#[test]
fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
let out = answer(br#"{"op":"browser_status","seq":3}"#, r"\\.\pipe\custos-test-nobody-here");
let v: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 }));
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, PIPE)).unwrap();
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
}
}
+30 -4
View File
@@ -52,7 +52,9 @@ fn random<const N: usize>() -> Zeroizing<[u8; N]> {
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
let mut k = Zeroizing::new([0u8; 32]);
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm)
.expand(&info.concat(), k.as_mut())
.expect("32 bytes is a valid HKDF length");
k
}
@@ -64,8 +66,8 @@ fn xnonce(n: &[u8]) -> XNonce {
XNonce::try_from(n).expect("24-byte nonce")
}
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
/// wiped on drop.
/// The one-time key pair of a device waiting for a secret. Its secret half is wiped on drop and leaves
/// memory only through `secret_bytes`, for a caller that keeps a long-lived key (`from_secret`).
pub struct Recipient {
secret: StaticSecret,
public: [u8; 32],
@@ -78,6 +80,30 @@ impl Recipient {
Recipient { secret, public }
}
/// A long-lived key the caller kept (docs/SEAL.md, "A kept key"): the PC's Provisio sealing key, stored
/// DPAPI-sealed and restored at start. Refuses a secret everyone knows: one that clamps to zero (a
/// wiped or never-filled buffer), and, as `seal` does for a public key, one whose shared secrets would
/// not be contributory.
pub fn from_secret(secret: Zeroizing<[u8; 32]>) -> Result<Recipient, SealError> {
let secret = StaticSecret::from(*secret);
let public = PublicKey::from(&secret).to_bytes();
let zero = PublicKey::from(&StaticSecret::from([0u8; 32])).to_bytes();
if public == zero {
return Err(SealError::BadKey);
}
let probe = StaticSecret::from(*random::<32>());
if !probe.diffie_hellman(&PublicKey::from(public)).was_contributory() {
return Err(SealError::BadKey);
}
Ok(Recipient { secret, public })
}
/// The secret half, for a caller that keeps this key (sealed with DPAPI or the like) instead of
/// dropping it after one box. One-time keys never call this.
pub fn secret_bytes(&self) -> Zeroizing<[u8; 32]> {
Zeroizing::new(self.secret.to_bytes())
}
/// What the device sends: 32 bytes.
pub fn public(&self) -> [u8; 32] {
self.public
@@ -109,7 +135,7 @@ impl Recipient {
impl std::fmt::Debug for Recipient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
write!(f, "Recipient {{ match_code: {}, secret: [redacted] }}", self.match_code())
}
}
+44
View File
@@ -72,3 +72,47 @@ fn at_rest_seals_open_with_the_same_key_and_context_only() {
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
}
#[test]
fn a_kept_recipient_comes_back_from_its_secret() {
// The PC keeps its Provisio sealing key (DPAPI-sealed) and restores it at the next start.
let r = Recipient::generate();
let kept = r.secret_bytes();
let back = Recipient::from_secret(kept).unwrap();
assert_eq!(back.public(), r.public());
assert_eq!(back.match_code(), r.match_code());
assert_eq!(back.secret_bytes().as_slice(), r.secret_bytes().as_slice());
// A box sealed to the original opens with the restored key, for its purpose only.
let ctx = b"provision-offer:vault:fabrica/gitea-read-token";
let b = seal(&r.public(), ctx, b"gitea token").unwrap();
assert_eq!(back.open(&b, ctx).unwrap().as_slice(), b"gitea token");
assert_eq!(back.open(&b, b"provision-offer:vault:fabrica/other"), Err(SealError::Rejected));
// Another kept key does not open it.
let other = Recipient::from_secret(Recipient::generate().secret_bytes()).unwrap();
assert_eq!(other.open(&b, ctx), Err(SealError::Rejected));
}
#[test]
fn a_known_secret_is_refused() {
// All zeros (a wiped or never-filled buffer) is a key everyone knows, and so is anything that clamps to it.
assert_eq!(Recipient::from_secret(zeroize::Zeroizing::new([0u8; 32])).unwrap_err(), SealError::BadKey);
let mut clamps_to_zero = [0u8; 32];
clamps_to_zero[0] = 0b0000_0111;
clamps_to_zero[31] = 0b1000_0000;
assert_eq!(Recipient::from_secret(zeroize::Zeroizing::new(clamps_to_zero)).unwrap_err(), SealError::BadKey);
}
#[test]
fn a_kept_recipient_prints_redacted() {
let r = Recipient::generate();
let secret = r.secret_bytes();
let back = Recipient::from_secret(secret.clone()).unwrap();
for shown in [format!("{r:?}"), format!("{back:?}"), format!("{back:#?}")] {
assert!(shown.contains("[redacted]"), "{shown}");
assert!(!shown.contains(&format!("{:?}", *secret)));
assert!(!shown.contains(&format!("{:?}", &secret[..8])));
let hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
assert!(!shown.contains(&hex[..16]));
assert!(!shown.contains(&format!("{:?}", back.public())));
}
}
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "custos-sign"
description = "Custos Domi: release signatures without the key leaving the vault (minisign, SHA256SUMS, Authenticode digests) and the household CA"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
thiserror.workspace = true
zeroize.workspace = true
data-encoding.workspace = true
# Deploy approvals: parsed, then written again in canonical form and compared.
serde.workspace = true
serde_json.workspace = true
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
ed25519-dalek = "2"
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
blake2 = "0.10"
x509-cert = { version = "0.2.5", features = ["builder"] }
# rsa 0.9 generates keys through rand_core 0.6; the bytes come from `rand`'s SysRng (lib.rs, `OsRng06`).
rand_core = "0.6"
rand.workspace = true
# cosign container image signatures (core 0.18.0): ECDSA P-256 with SHA-256, RFC 6979 nonces.
p256 = { version = "0.13", features = ["ecdsa", "pkcs8", "pem"] }
[dev-dependencies]
minisign-verify = "0.3"
x509-cert = { version = "0.2.5", features = ["builder"] }
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
+53
View File
@@ -0,0 +1,53 @@
//! For tools/signing/interop.ps1 only: makes **throwaway test keys** in a temp folder and signs with them, so the
//! real minisign, signtool and osslsigncode can check what this crate produces. The vault never does this: there,
//! keys are made inside the vault and only signatures come out.
//!
//! interop ca <dir> root.cer, root.pem, leaf.cer, leaf.key.der (test only)
//! interop authenticode <leaf.key.der> <file.dig> writes <file.dig>.signed
//! interop minisign <dir> <file> <dir>/minisign.pub, <file>.minisig
//! interop manifest <dir> <SHA256SUMS> <SHA256SUMS>.minisig, with the key in <dir>
use std::fs;
use std::path::Path;
use custos_sign::*;
use data_encoding::BASE64;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let arg = |i: usize| args.get(i).map(String::as_str).expect("missing argument");
match arg(0) {
"ca" => {
let dir = Path::new(arg(1));
fs::create_dir_all(dir).unwrap();
let root = new_root("Domi Interop Test Root", 1).unwrap();
let leaf = new_code_signing("Domi Interop Test Signing", 1, &root.secret, &root.cert_der).unwrap();
fs::write(dir.join("root.cer"), &root.cert_der).unwrap();
fs::write(dir.join("root.pem"), cert_pem(&root.cert_der)).unwrap();
fs::write(dir.join("leaf.cer"), &leaf.cert_der).unwrap();
fs::write(dir.join("leaf.key.der"), leaf.secret.expose()).unwrap();
}
"authenticode" => {
let key = RsaSecret::from_pkcs8_der(fs::read(arg(1)).unwrap()).unwrap();
let dig = fs::read_to_string(arg(2)).unwrap();
let digest = BASE64.decode(dig.trim().as_bytes()).unwrap();
let sig = authenticode(&key, &digest).unwrap();
fs::write(format!("{}.signed", arg(2)), BASE64.encode(&sig)).unwrap();
}
"minisign" | "manifest" => {
let dir = Path::new(arg(1));
let file = Path::new(arg(2));
let key = new_ed25519();
fs::write(dir.join("minisign.pub"), minisign_public(&key.public, &key.key_id)).unwrap();
let data = fs::read(file).unwrap();
let name = file.file_name().unwrap().to_str().unwrap();
let sig = if arg(0) == "manifest" {
manifest(&key.secret, &key.key_id, std::str::from_utf8(&data).unwrap(), 1_793_750_000).unwrap()
} else {
minisign(&key.secret, &key.key_id, &blake2b512(&data), name, 1_793_750_000).unwrap()
};
fs::write(format!("{}.minisig", file.display()), sig).unwrap();
}
other => panic!("unknown command {other}"),
}
}
+112
View File
@@ -0,0 +1,112 @@
//! Tauri's updater envelope and cosign container image signatures (core 0.18.0, docs/TEAM.md, "Signature
//! envelopes").
use std::fmt;
use data_encoding::BASE64;
use zeroize::Zeroizing;
use crate::{Error, OsRng06};
// ---- Tauri's updater ----
/// The content of Tauri's `<file>.sig`: the base64 of the whole minisign signature file. Tauri's `pubkey` is,
/// likewise, the base64 of `minisign.pub`.
pub fn tauri_updater(minisig: &str) -> String {
BASE64.encode(minisig.as_bytes())
}
/// The minisign text inside a Tauri `.sig`, or `None` when it is not base64 of UTF-8.
pub fn tauri_updater_open(sig: &str) -> Option<String> {
String::from_utf8(BASE64.decode(sig.trim().as_bytes()).ok()?).ok()
}
// ---- cosign ----
/// An ECDSA P-256 secret scalar. Wiped on drop; never printed.
pub struct P256Secret(Zeroizing<[u8; 32]>);
impl P256Secret {
/// Refuses bytes that are not a valid scalar (zero, or not below the group order).
pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, Error> {
let bytes = Zeroizing::new(bytes);
p256::ecdsa::SigningKey::from_bytes(&(*bytes).into()).map_err(|_| Error::BadKey)?;
Ok(P256Secret(bytes))
}
pub fn expose(&self) -> &[u8; 32] {
&self.0
}
fn key(&self) -> Result<p256::ecdsa::SigningKey, Error> {
p256::ecdsa::SigningKey::from_bytes(&(*self.0).into()).map_err(|_| Error::BadKey)
}
/// The public key as `cosign.pub` holds it: a PEM `PUBLIC KEY` (SubjectPublicKeyInfo).
pub fn public_pem(&self) -> Result<String, Error> {
use p256::pkcs8::EncodePublicKey;
self.key()?.verifying_key().to_public_key_pem(p256::pkcs8::LineEnding::LF).map_err(|_| Error::BadKey)
}
}
impl fmt::Debug for P256Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// A new random P-256 key, from the OS CSPRNG.
pub fn new_p256() -> P256Secret {
let key = p256::ecdsa::SigningKey::random(&mut OsRng06);
let mut bytes = Zeroizing::new([0u8; 32]);
bytes.copy_from_slice(&key.to_bytes());
P256Secret(bytes)
}
/// An image reference as cosign's payload names it: the repository, without a tag or digest, 1–255 of
/// `[a-z0-9._/:-]`, starting and ending with a letter or digit, no `//`.
pub fn image_ok(image: &str) -> Result<(), Error> {
let b = image.as_bytes();
if !(1..=255).contains(&b.len()) {
return Err(Error::Image("not 1 to 255 characters"));
}
if !b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._/:-".contains(c)) {
return Err(Error::Image("only a-z 0-9 . _ / : - (a repository, without @digest)"));
}
if !b[0].is_ascii_alphanumeric() || !b[b.len() - 1].is_ascii_alphanumeric() || image.contains("//") {
return Err(Error::Image("not a repository name"));
}
Ok(())
}
/// cosign's simple-signing payload for `image` at the manifest whose SHA-256 is `digest`, exactly as docs/TEAM.md
/// writes it: these keys in this order, no spaces, `"optional":null`.
pub fn cosign_payload(image: &str, digest: &[u8]) -> Result<String, Error> {
let digest: &[u8; 32] = digest.try_into().map_err(|_| Error::DigestLength(32))?;
image_ok(image)?;
let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
Ok(format!(
"{{\"critical\":{{\"identity\":{{\"docker-reference\":\"{image}\"}},\"image\":{{\"docker-manifest-digest\":\"sha256:{hex}\"}},\"type\":\"cosign container image signature\"}},\"optional\":null}}"
))
}
/// The ECDSA P-256 SHA-256 signature (ASN.1 DER) over `payload`, as `cosign sign` makes it and `cosign verify
/// --key` and `openssl dgst -sha256 -verify` check it. Nonces are RFC 6979's.
pub fn cosign(secret: &P256Secret, payload: &str) -> Result<Vec<u8>, Error> {
use p256::ecdsa::signature::Signer;
let sig: p256::ecdsa::Signature = secret.key()?.sign(payload.as_bytes());
Ok(sig.to_der().as_bytes().to_vec())
}
/// Checks a cosign signature (DER, as [`cosign`] makes it) over `payload` with a `cosign.pub` PEM.
pub fn cosign_verify(public_pem: &str, payload: &[u8], der: &[u8]) -> bool {
use p256::ecdsa::signature::Verifier;
use p256::pkcs8::DecodePublicKey;
let Ok(key) = p256::ecdsa::VerifyingKey::from_public_key_pem(public_pem) else {
return false;
};
let Ok(sig) = p256::ecdsa::Signature::from_der(der) else {
return false;
};
key.verify(payload, &sig).is_ok()
}
+622
View File
@@ -0,0 +1,622 @@
//! Custos Domi · signing: the signature formats docs/SIGNING.md describes, over digests, so the file never has to
//! reach the vault and the key never has to leave it.
//!
//! - minisign (prehashed `ED`, what minisign and Tauri's updater verify) over a BLAKE2b-512 digest;
//! - a canonical `SHA256SUMS` manifest, checked here and signed as minisign;
//! - Authenticode: RSA PKCS#1 v1.5 over the 32-byte digest `signtool sign /dg` writes;
//! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3);
//! - Android APKs: an RSA-4096 key with a self-signed certificate, signing the SHA-512 digests of the APK
//! Signature Scheme v2/v3 signed data with RSA PKCS#1 v1.5 (apksig does the APK itself, on the build's side);
//! - Tauri's updater: the base64 of a minisign signature file (core 0.18.0);
//! - cosign container image signatures (core 0.18.0): ECDSA P-256 over cosign's simple-signing payload, written
//! here from the image and its manifest digest, never taken from the request.
//!
//! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`.
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use blake2::{Blake2b512, Digest};
use data_encoding::BASE64;
use ed25519_dalek::{Signer as _, SigningKey};
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use rsa::RsaPrivateKey;
use rsa::pkcs1v15;
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey};
use rsa::signature::hazmat::PrehashSigner;
use sha2_010::{Sha256, Sha512};
use x509_cert::Certificate;
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
use x509_cert::der::{Decode, Encode};
use x509_cert::ext::pkix::ExtendedKeyUsage;
use x509_cert::name::Name;
use x509_cert::serial_number::SerialNumber;
use x509_cert::spki::SubjectPublicKeyInfoOwned;
use x509_cert::time::Validity;
use zeroize::Zeroizing;
mod cosign;
pub use cosign::{
P256Secret, cosign, cosign_payload, cosign_verify, image_ok, new_p256, tauri_updater, tauri_updater_open,
};
/// Authenticode's code-signing purpose (RFC 5280 id-kp-codeSigning).
const CODE_SIGNING: x509_cert::der::oid::ObjectIdentifier =
x509_cert::der::oid::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.3");
const RSA_BITS: usize = 3072;
/// An Android app's signing key: RSA-4096. apksig signs with SHA512withRSA for any RSA key over 3072 bits.
pub const ANDROID_RSA_BITS: usize = 4096;
/// An Android app's certificate is valid this long: the key can never change for the app's whole life.
pub const ANDROID_YEARS: u64 = 100;
/// One `apk` request carries 1 to this many SHA-512 digests (v2 and v3 are two).
pub const MAX_APK_DIGESTS: usize = 4;
const DAY: u64 = 24 * 60 * 60;
/// The largest manifest Custos signs (docs/SIGNING.md).
pub const MAX_MANIFEST: usize = 32 * 1024;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error {
#[error("the digest must be {0} bytes")]
DigestLength(usize),
#[error("the file name cannot be used in a signature: {0}")]
FileName(&'static str),
#[error("the manifest is not in canonical SHA256SUMS form: line {line}: {why}")]
Manifest { line: usize, why: &'static str },
#[error("the key cannot be read")]
BadKey,
#[error("the certificate cannot be built or read")]
Certificate,
#[error("the approval cannot be signed: {0}")]
Approval(&'static str),
#[error("an APK request is 1 to 4 SHA-512 digests of 64 bytes each")]
ApkDigests,
#[error("the image reference is not usable: {0}")]
Image(&'static str),
}
/// An Ed25519 seed. Wiped on drop; never printed.
pub struct Ed25519Secret(Zeroizing<[u8; 32]>);
impl Ed25519Secret {
pub fn from_bytes(seed: [u8; 32]) -> Self {
Ed25519Secret(Zeroizing::new(seed))
}
/// The seed, for storing in the vault body. Only the vault calls this.
pub fn expose(&self) -> &[u8; 32] {
&self.0
}
pub fn public(&self) -> [u8; 32] {
SigningKey::from_bytes(&self.0).verifying_key().to_bytes()
}
}
impl fmt::Debug for Ed25519Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// An RSA private key as PKCS#8 DER. Wiped on drop; never printed.
pub struct RsaSecret(Zeroizing<Vec<u8>>);
impl RsaSecret {
pub fn from_pkcs8_der(der: Vec<u8>) -> Result<Self, Error> {
let der = Zeroizing::new(der);
RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| Error::BadKey)?;
Ok(RsaSecret(der))
}
/// The PKCS#8 DER, for storing in the vault body. Only the vault calls this.
pub fn expose(&self) -> &[u8] {
&self.0
}
fn key(&self) -> Result<RsaPrivateKey, Error> {
RsaPrivateKey::from_pkcs8_der(&self.0).map_err(|_| Error::BadKey)
}
}
impl fmt::Debug for RsaSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// Fills `buf` from the OS CSPRNG through `rand`'s `SysRng`, as the rest of the workspace does (the browser build
/// routes it to `crypto.getRandomValues`).
fn fill(buf: &mut [u8]) {
rand::Rng::fill_bytes(&mut UnwrapErr(SysRng), buf);
}
/// rand_core 0.6's interface, which `rsa` 0.9 generates keys with, over [`fill`].
struct OsRng06;
impl rand_core::RngCore for OsRng06 {
fn next_u32(&mut self) -> u32 {
let mut b = [0u8; 4];
fill(&mut b);
u32::from_le_bytes(b)
}
fn next_u64(&mut self) -> u64 {
let mut b = [0u8; 8];
fill(&mut b);
u64::from_le_bytes(b)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
fill(dest);
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
fill(dest);
Ok(())
}
}
impl rand_core::CryptoRng for OsRng06 {}
// ---- minisign ----
/// A new Ed25519 key with a random minisign key id.
pub struct NewEd25519 {
pub secret: Ed25519Secret,
pub public: [u8; 32],
pub key_id: [u8; 8],
}
pub fn new_ed25519() -> NewEd25519 {
let mut seed = Zeroizing::new([0u8; 32]);
fill(&mut *seed);
let mut key_id = [0u8; 8];
fill(&mut key_id);
let secret = Ed25519Secret(seed);
let public = secret.public();
NewEd25519 { secret, public, key_id }
}
/// minisign prints a key id as one little-endian u64 in upper-case hex.
pub fn key_id_hex(key_id: &[u8; 8]) -> String {
format!("{:016X}", u64::from_le_bytes(*key_id))
}
/// The BLAKE2b-512 of `data`: what a prehashed minisign signature signs.
pub fn blake2b512(data: &[u8]) -> [u8; 64] {
Blake2b512::digest(data).into()
}
/// `minisign.pub`: the public key file minisign `-V -p` and Tauri (base64 of it) read.
pub fn minisign_public(public: &[u8; 32], key_id: &[u8; 8]) -> String {
let mut raw = Vec::with_capacity(42);
raw.extend_from_slice(b"Ed");
raw.extend_from_slice(key_id);
raw.extend_from_slice(public);
format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw))
}
/// A plain Ed25519 signature over `message` itself: no prehash, no digest, no wrapping (core 0.21.0, the Domi
/// licence, docs/SIGNING.md "Domi licences"). ed25519-dalek's deterministic RFC 8032 signature.
pub fn ed25519_plain(secret: &Ed25519Secret, message: &[u8]) -> [u8; 64] {
SigningKey::from_bytes(&secret.0).sign(message).to_bytes()
}
/// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`.
/// The trusted comment is `timestamp:<unix seconds>\tfile:<file>\thashed`, as minisign writes it.
pub fn minisign(
secret: &Ed25519Secret,
key_id: &[u8; 8],
digest: &[u8],
file: &str,
timestamp: u64,
) -> Result<String, Error> {
let digest: &[u8; 64] = digest.try_into().map_err(|_| Error::DigestLength(64))?;
check_file_name(file)?;
let key = SigningKey::from_bytes(&secret.0);
let signature = key.sign(digest).to_bytes();
let trusted = format!("timestamp:{timestamp}\tfile:{file}\thashed");
let mut global_msg = Vec::with_capacity(64 + trusted.len());
global_msg.extend_from_slice(&signature);
global_msg.extend_from_slice(trusted.as_bytes());
let global = key.sign(&global_msg).to_bytes();
let mut line = Vec::with_capacity(74);
line.extend_from_slice(b"ED");
line.extend_from_slice(key_id);
line.extend_from_slice(&signature);
Ok(format!(
"untrusted comment: signature from Custos key {}\n{}\ntrusted comment: {trusted}\n{}\n",
key_id_hex(key_id),
BASE64.encode(&line),
BASE64.encode(&global)
))
}
fn check_file_name(file: &str) -> Result<(), Error> {
if file.is_empty() {
return Err(Error::FileName("empty"));
}
if file.len() > 255 {
return Err(Error::FileName("longer than 255 bytes"));
}
if file.chars().any(char::is_control) {
return Err(Error::FileName("control characters"));
}
if file.contains(['/', '\\']) {
return Err(Error::FileName("a path, not a file name"));
}
Ok(())
}
// ---- the SHA256SUMS manifest ----
/// Checks that `text` is a canonical `SHA256SUMS` (docs/SIGNING.md): `<64 lower hex> <name>\n` lines, names
/// without `/`, `\`, control characters or a leading `-`, unique, sorted by bytes, at least one line.
pub fn manifest_check(text: &str) -> Result<(), Error> {
let err = |line: usize, why: &'static str| Err(Error::Manifest { line, why });
if text.len() > MAX_MANIFEST {
return err(0, "larger than 32 KiB");
}
if text.is_empty() {
return err(0, "empty");
}
if !text.ends_with('\n') {
return err(text.lines().count(), "the last line has no newline");
}
let mut prev: Option<&str> = None;
for (i, line) in text.split_terminator('\n').enumerate() {
let n = i + 1;
if line.ends_with('\r') {
return err(n, "CRLF line ending");
}
let Some((hash, name)) = line.split_once(" ") else {
return err(n, "not `<sha256> <name>`");
};
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return err(n, "the hash is not 64 lower-case hex digits");
}
if name.is_empty()
|| name.starts_with(['-', ' ', '*'])
|| name.contains(['/', '\\'])
|| name.chars().any(char::is_control)
{
return err(n, "not a plain file name");
}
if prev.is_some_and(|p| p.as_bytes() >= name.as_bytes()) {
return err(n, "names are not sorted and unique");
}
prev = Some(name);
}
Ok(())
}
/// Signs a canonical manifest as minisign (file name `SHA256SUMS`).
pub fn manifest(secret: &Ed25519Secret, key_id: &[u8; 8], text: &str, timestamp: u64) -> Result<String, Error> {
manifest_check(text)?;
minisign(secret, key_id, &blake2b512(text.as_bytes()), "SHA256SUMS", timestamp)
}
// ---- Authenticode ----
/// RSA PKCS#1 v1.5 with the SHA-256 DigestInfo over the 32 bytes of signtool's `.dig` (384 bytes for RSA-3072):
/// what goes, base64-encoded, into `.dig.signed`.
pub fn authenticode(secret: &RsaSecret, digest: &[u8]) -> Result<Vec<u8>, Error> {
if digest.len() != 32 {
return Err(Error::DigestLength(32));
}
let key = pkcs1v15::SigningKey::<Sha256>::new(secret.key()?);
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
Ok(Box::<[u8]>::from(sig).into_vec())
}
// ---- the household CA ----
/// A new RSA-3072 key and its certificate.
pub struct NewCert {
pub secret: RsaSecret,
pub cert_der: Vec<u8>,
}
fn new_rsa(bits: usize) -> Result<(RsaPrivateKey, RsaSecret), Error> {
let key = RsaPrivateKey::new(&mut OsRng06, bits).map_err(|_| Error::BadKey)?;
let der = key.to_pkcs8_der().map_err(|_| Error::BadKey)?.as_bytes().to_vec();
Ok((key, RsaSecret(Zeroizing::new(der))))
}
fn serial() -> Result<SerialNumber, Error> {
let mut bytes = [0u8; 16];
fill(&mut bytes);
bytes[0] &= 0x7f; // positive
bytes[0] |= 0x01; // and without a leading zero byte
SerialNumber::new(&bytes).map_err(|_| Error::Certificate)
}
fn name(cn: &str) -> Result<Name, Error> {
if cn.is_empty() || cn.len() > 64 || cn.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#']) {
return Err(Error::Certificate);
}
Name::from_str(&format!("CN={cn},O=Domi")).map_err(|_| Error::Certificate)
}
fn spki(key: &RsaPrivateKey) -> Result<SubjectPublicKeyInfoOwned, Error> {
let der = key.to_public_key().to_public_key_der().map_err(|_| Error::Certificate)?;
SubjectPublicKeyInfoOwned::from_der(der.as_bytes()).map_err(|_| Error::Certificate)
}
/// A self-signed root CA, valid for `years` years from now.
pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
let (key, secret) = new_rsa(RSA_BITS)?;
let spki = spki(&key)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
let builder = CertificateBuilder::new(Profile::Root, serial()?, validity, name(cn)?, spki, &signer)
.map_err(|_| Error::Certificate)?;
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
/// A code-signing leaf issued by `issuer`, valid for `years` years from now.
pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &[u8]) -> Result<NewCert, Error> {
let issuer_cert = Certificate::from_der(issuer_cert).map_err(|_| Error::Certificate)?;
let (key, secret) = new_rsa(RSA_BITS)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(issuer.key()?);
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
let profile = Profile::Leaf {
issuer: issuer_cert.tbs_certificate.subject.clone(),
enable_key_agreement: false,
enable_key_encipherment: false,
};
let mut builder = CertificateBuilder::new(profile, serial()?, validity, name(cn)?, spki(&key)?, &signer)
.map_err(|_| Error::Certificate)?;
builder.add_extension(&ExtendedKeyUsage(vec![CODE_SIGNING])).map_err(|_| Error::Certificate)?;
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
// ---- Android APKs ----
/// One attribute value of an Android certificate's subject: 1 to 64 bytes, no characters RFC 4514 would have to
/// escape, no control characters, no space at either end.
fn subject_part(s: &str) -> Result<&str, Error> {
let bad = s.is_empty()
|| s.len() > 64
|| s.trim() != s
|| s.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#'])
|| s.chars().any(char::is_control);
if bad { Err(Error::Certificate) } else { Ok(s) }
}
/// A new Android app signing key: RSA-4096 and a self-signed X.509 v3 certificate `CN=<cn>, O=<o>, C=<c>` valid
/// [`ANDROID_YEARS`] years from now, an end-entity certificate (not a CA, key usage digitalSignature +
/// nonRepudiation, no extended key usage). `c` is a two-letter country code. Slow: one RSA-4096 key.
pub fn new_android(cn: &str, o: &str, c: &str) -> Result<NewCert, Error> {
let (cn, o) = (subject_part(cn)?, subject_part(o)?);
if c.len() != 2 || !c.bytes().all(|b| b.is_ascii_uppercase()) {
return Err(Error::Certificate);
}
// RFC 4514 order: the string names the most specific part first, the certificate encodes C, O, CN.
let subject = Name::from_str(&format!("CN={cn},O={o},C={c}")).map_err(|_| Error::Certificate)?;
let (key, secret) = new_rsa(ANDROID_RSA_BITS)?;
let spki = spki(&key)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
let validity =
Validity::from_now(Duration::from_secs(ANDROID_YEARS * 365 * DAY)).map_err(|_| Error::Certificate)?;
// A leaf issued by itself: self-signed, but without the CA extensions of a root.
let profile =
Profile::Leaf { issuer: subject.clone(), enable_key_agreement: false, enable_key_encipherment: false };
let builder = CertificateBuilder::new(profile, serial()?, validity, subject, spki, &signer)
.map_err(|_| Error::Certificate)?;
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
/// RSA PKCS#1 v1.5 with the SHA-512 DigestInfo over each 64-byte digest in `digests` (1 to [`MAX_APK_DIGESTS`],
/// concatenated): the signatures, concatenated in the same order, for APK Signature Scheme v2 and v3
/// (`RSA_PKCS1_V1_5_WITH_SHA512`, what apksig picks for an RSA key over 3072 bits).
pub fn apk(secret: &RsaSecret, digests: &[u8]) -> Result<Vec<u8>, Error> {
if digests.is_empty() || digests.len() % 64 != 0 || digests.len() > 64 * MAX_APK_DIGESTS {
return Err(Error::ApkDigests);
}
let key = pkcs1v15::SigningKey::<Sha512>::new(secret.key()?);
let mut out = Vec::new();
for digest in digests.chunks(64) {
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
out.extend_from_slice(&Box::<[u8]>::from(sig));
}
Ok(out)
}
/// A certificate as PEM, for tools that want text.
pub fn cert_pem(der: &[u8]) -> String {
let b64 = BASE64.encode(der);
let mut out = String::from("-----BEGIN CERTIFICATE-----\n");
for chunk in b64.as_bytes().chunks(64) {
out.push_str(std::str::from_utf8(chunk).expect("base64 is ASCII"));
out.push('\n');
}
out.push_str("-----END CERTIFICATE-----\n");
out
}
/// The SHA-256 (hex) of `bytes`, for the audit log.
pub fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
// ---- deploy approvals ----
/// The largest approval text Custos reads (docs/SIGNING.md).
pub const MAX_APPROVAL: usize = 8 * 1024;
/// An approval expires at most this many seconds after it is checked: 25 hours (a release's approval lives a day,
/// and its card may wait for Mark that long; an hour before core 0.17.1).
pub const APPROVAL_MAX_AHEAD: u64 = 25 * 3600;
/// A deploy approval, read from its canonical JSON (docs/SIGNING.md, "approval"). Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Approval {
pub run: String,
pub repo: String,
pub commit: String,
pub pipeline: String,
pub version: String,
pub targets: Vec<String>,
/// Unix seconds.
pub expires: u64,
}
/// The JSON as it is parsed: `v` first, the rest as [`Approval`].
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct ApprovalJson {
v: u64,
run: String,
repo: String,
commit: String,
pipeline: String,
version: String,
targets: Vec<String>,
expires: u64,
}
impl Approval {
/// The canonical text (docs/SIGNING.md): one line, no spaces, keys in the fixed order, `"` and `\` escaped,
/// nothing else. Meaningful for an approval that passed [`approval_check`].
pub fn canonical(&self) -> String {
fn string(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c => out.push(c),
}
}
out.push('"');
}
let mut out = String::with_capacity(256);
out.push_str("{\"v\":1,\"run\":");
string(&mut out, &self.run);
out.push_str(",\"repo\":");
string(&mut out, &self.repo);
out.push_str(",\"commit\":");
string(&mut out, &self.commit);
out.push_str(",\"pipeline\":");
string(&mut out, &self.pipeline);
out.push_str(",\"version\":");
string(&mut out, &self.version);
out.push_str(",\"targets\":[");
for (i, t) in self.targets.iter().enumerate() {
if i > 0 {
out.push(',');
}
string(&mut out, t);
}
out.push_str("],\"expires\":");
out.push_str(&self.expires.to_string());
out.push('}');
out
}
}
/// A run id: `[A-Za-z0-9._-]{1,64}`.
pub fn run_id_ok(run: &str) -> bool {
(1..=64).contains(&run.len()) && run.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
}
/// `[A-Za-z0-9._+-]{1,64}`: an approval's repo, pipeline and version.
fn name_ok(s: &str) -> bool {
(1..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"._+-".contains(&c))
}
/// Characters a target may not hold: control characters, and the invisible ones that change how the rest of the
/// line is shown on the card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen).
fn unprintable(c: char) -> bool {
c.is_control()
|| matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}')
|| matches!(c, '\u{2060}'..='\u{2069}' | '\u{FEFF}')
}
/// Checks that `text` is a deploy approval in canonical form that has not expired at `now_secs` and expires at most
/// 25 hours later ([`APPROVAL_MAX_AHEAD`], docs/SIGNING.md). It is parsed, written again in canonical form and
/// compared byte for byte, so any other spelling of the same values (key order, spaces, escapes, a trailing newline)
/// is refused.
pub fn approval_check(text: &str, now_secs: u64) -> Result<Approval, Error> {
let a = approval_parse(text)?;
if a.expires <= now_secs {
return Err(Error::Approval("it has expired"));
}
if a.expires > now_secs.saturating_add(APPROVAL_MAX_AHEAD) {
return Err(Error::Approval("it expires more than 25 hours from now"));
}
Ok(a)
}
/// [`approval_check`] without the clock: the canonical form and every member's rule, not the expiry. For reading
/// what a refused or expired request said; never enough to sign.
pub fn approval_parse(text: &str) -> Result<Approval, Error> {
let err = |why: &'static str| Err(Error::Approval(why));
if text.len() > MAX_APPROVAL {
return err("larger than 8 KiB");
}
let Ok(j) = serde_json::from_str::<ApprovalJson>(text) else {
return err("not an approval in canonical form");
};
if j.v != 1 {
return err("v is not 1");
}
let a = Approval {
run: j.run,
repo: j.repo,
commit: j.commit,
pipeline: j.pipeline,
version: j.version,
targets: j.targets,
expires: j.expires,
};
if !run_id_ok(&a.run) {
return err("the run is not a run id ([A-Za-z0-9._-], 1 to 64)");
}
if !name_ok(&a.repo) {
return err("the repo is not 1 to 64 of [A-Za-z0-9._+-]");
}
if a.commit.len() != 40 || !a.commit.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) {
return err("the commit is not 40 lower-case hex digits");
}
if !name_ok(&a.pipeline) {
return err("the pipeline is not 1 to 64 of [A-Za-z0-9._+-]");
}
if !name_ok(&a.version) {
return err("the version is not 1 to 64 of [A-Za-z0-9._+-]");
}
if !(1..=16).contains(&a.targets.len()) {
return err("there must be 1 to 16 targets");
}
for t in &a.targets {
if !(1..=80).contains(&t.chars().count()) {
return err("a target is not 1 to 80 characters");
}
if t.chars().any(unprintable) {
return err("a target has control or invisible characters");
}
}
if a.canonical() != text {
return err("not in canonical form (key order, spaces or escaping)");
}
Ok(a)
}
/// Signs a deploy approval for `run` as prehashed minisign over the text's bytes, file name `approval-<run>.json`.
/// The text is checked with [`approval_check`] at `timestamp` (Unix seconds) and must name `run`.
pub fn approval(
secret: &Ed25519Secret,
key_id: &[u8; 8],
text: &str,
timestamp: u64,
run: &str,
) -> Result<String, Error> {
let a = approval_check(text, timestamp)?;
if a.run != run {
return Err(Error::Approval("the approval's run is not the request's"));
}
minisign(secret, key_id, &blake2b512(text.as_bytes()), &format!("approval-{run}.json"), timestamp)
}
+213
View File
@@ -0,0 +1,213 @@
//! Deploy approvals (docs/SIGNING.md, "approval"): the canonical form is checked byte for byte, and the signature is
//! a prehashed minisign over the text that minisign-verify (what Tauri and the hub's tools check with) accepts.
use custos_sign::*;
const NOW: u64 = 1_793_000_000;
const COMMIT: &str = "3f2a9c1d0e4b5a6978877665544332211aabbccd";
/// The doc's example, with an expiry 10 minutes after NOW.
fn canonical() -> String {
format!(
r#"{{"v":1,"run":"r-42","repo":"Arca","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#,
NOW + 600
)
}
fn with(from: &str, to: &str) -> String {
let t = canonical();
assert!(t.contains(from), "{from:?}");
t.replacen(from, to, 1)
}
fn refused(text: &str, now: u64) -> String {
match approval_check(text, now) {
Ok(a) => panic!("accepted {text:?}: {a:?}"),
Err(e) => e.to_string(),
}
}
#[test]
fn the_canonical_approval_is_accepted_and_reads_back() {
let a = approval_check(&canonical(), NOW).unwrap();
assert_eq!(a.run, "r-42");
assert_eq!(a.repo, "Arca");
assert_eq!(a.commit, COMMIT);
assert_eq!(a.pipeline, "release");
assert_eq!(a.version, "0.7.0");
assert_eq!(a.targets, ["deploy to nixos-vm", "publish to Aula"]);
assert_eq!(a.expires, NOW + 600);
assert_eq!(a.canonical(), canonical());
}
#[test]
fn reordered_keys_spaces_and_other_shapes_are_refused() {
let t = canonical();
let reordered = with(r#""run":"r-42","repo":"Arca","#, r#""repo":"Arca","run":"r-42","#);
let bad = [
reordered,
t.replace(',', ", "),
t.replace(':', ": "),
format!("{t}\n"),
format!(" {t}"),
t.replace("{\"v\"", "{\n\"v\""),
with(r#""v":1,"#, r#""v":1,"x":1,"#),
with(r#""v":1,"#, ""),
with(r#""v":1,"#, r#""v":1,"v":1,"#),
with(r#""v":1,"#, r#""v":2,"#),
with(r#""v":1,"#, r#""v":1.0,"#),
with(r#""v":1,"#, r#""v":"1","#),
format!("[{t}]"),
"not json".to_string(),
String::new(),
];
for b in &bad {
refused(b, NOW);
}
}
#[test]
fn escaping_must_be_minimal() {
// A quote and a backslash in a target are escaped the one way JSON allows; the result is canonical.
let q = with("publish to Aula", r#"say \"hi\" \\ there"#);
assert_eq!(approval_check(&q, NOW).unwrap().targets[1], r#"say "hi" \ there"#);
// Raw non-ASCII is canonical; the same text through \u escapes is not.
let raw = with("publish to Aula", "publikovat na Aulu é");
assert!(approval_check(&raw, NOW).is_ok());
for b in [
with("publish to Aula", r"publikovat na Aulu \u00e9"),
with("publish to Aula", r"publish to \u0041ula"),
with("publish to Aula", r"publish\/to Aula"),
with("r-42", r"r\u002d42"),
] {
refused(&b, NOW);
}
}
#[test]
fn a_bad_run_repo_pipeline_or_version_is_refused() {
for run in ["", "r 42", "r/42", "r\\\\42", "ř-42", &"r".repeat(65)] {
let e = refused(&with("\"run\":\"r-42\"", &format!("\"run\":\"{run}\"")), NOW);
assert!(e.contains("run"), "{run:?}: {e}");
}
let ok_run = "a.B_c-9".to_string() + &"x".repeat(57);
assert_eq!(ok_run.len(), 64);
assert!(approval_check(&with("\"run\":\"r-42\"", &format!("\"run\":\"{ok_run}\"")), NOW).is_ok());
for (member, value) in [("repo", "Arca"), ("pipeline", "release"), ("version", "0.7.0")] {
let from = format!("\"{member}\":\"{value}\"");
for bad in ["", "a b", "a/b", "a:b", &"a".repeat(65)] {
let e = refused(&with(&from, &format!("\"{member}\":\"{bad}\"")), NOW);
assert!(e.contains(member), "{member} {bad:?}: {e}");
}
let fine = format!("\"{member}\":\"A.b_c-1+x{}\"", "z".repeat(55));
assert!(approval_check(&with(&from, &fine), NOW).is_ok(), "{fine}");
}
}
#[test]
fn a_bad_commit_is_refused() {
for bad in [COMMIT.to_uppercase(), COMMIT[..39].to_string(), format!("{COMMIT}0"), COMMIT.replace('a', "g")] {
let e = refused(&with(COMMIT, &bad), NOW);
assert!(e.contains("commit"), "{bad}: {e}");
}
}
#[test]
fn targets_have_limits() {
let list = |ts: &[String]| ts.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
let from = r#""targets":["deploy to nixos-vm","publish to Aula"]"#;
let set = |ts: &[String]| with(from, &format!("\"targets\":[{}]", list(ts)));
let n = |k: usize| (0..k).map(|i| format!("deploy to host-{i}")).collect::<Vec<_>>();
assert!(approval_check(&set(&n(1)), NOW).is_ok());
assert!(approval_check(&set(&n(16)), NOW).is_ok());
assert!(approval_check(&set(&["é".repeat(80)]), NOW).is_ok(), "80 characters, not bytes");
for bad in [
set(&[]),
set(&n(17)),
set(&[String::new()]),
set(&["x".repeat(81)]),
set(&["tab\\there".to_string()]),
set(&["line\\nbreak".to_string()]),
set(&["nul\\u0000".to_string()]),
set(&["del\u{7f}".to_string()]),
set(&["right-to-left \u{202e}evil".to_string()]),
set(&["zero\u{200b}width".to_string()]),
with(from, r#""targets":"deploy to nixos-vm""#),
with(from, r#""targets":[1]"#),
] {
let e = refused(&bad, NOW);
assert!(e.contains("target") || e.contains("form"), "{bad}: {e}");
}
}
#[test]
fn the_expiry_is_after_now_and_within_25_hours() {
let at = |exp: u64| with(&format!("\"expires\":{}", NOW + 600), &format!("\"expires\":{exp}"));
assert!(approval_check(&at(NOW + 1), NOW).is_ok());
assert!(approval_check(&at(NOW + 3600), NOW).is_ok());
// A release's approval lives a day, and its card may wait for Mark that long (core 0.17.1).
assert_eq!(APPROVAL_MAX_AHEAD, 25 * 3600);
assert!(approval_check(&at(NOW + 24 * 3600), NOW).is_ok());
assert!(approval_check(&at(NOW + 25 * 3600), NOW).is_ok());
for exp in [NOW, NOW - 1, 0, NOW + 25 * 3600 + 1, u64::MAX] {
let e = refused(&at(exp), NOW);
assert!(e.contains("expire"), "{exp}: {e}");
}
// The same text expires as time passes.
assert!(refused(&canonical(), NOW + 600).contains("expire"));
for bad in
[format!("\"expires\":{}.0", NOW + 600), format!("\"expires\":-{}", NOW + 600), "\"expires\":\"1\"".into()]
{
refused(&with(&format!("\"expires\":{}", NOW + 600), &bad), NOW);
}
}
#[test]
fn an_oversized_text_is_refused_before_parsing() {
let huge = with("publish to Aula", &"x".repeat(MAX_APPROVAL));
assert!(refused(&huge, NOW).contains("larger"));
}
#[test]
fn the_approval_signature_verifies_with_minisign() {
let k = new_ed25519();
let text = canonical();
let sig = approval(&k.secret, &k.key_id, &text, NOW, "r-42").unwrap();
let public = minisign_verify::PublicKey::decode(&minisign_public(&k.public, &k.key_id)).unwrap();
let decoded = minisign_verify::Signature::decode(&sig).unwrap();
public.verify(text.as_bytes(), &decoded, false).unwrap();
assert!(public.verify(with("Arca", "Fabrica").as_bytes(), &decoded, false).is_err());
assert_eq!(decoded.trusted_comment(), format!("timestamp:{NOW}\tfile:approval-r-42.json\thashed"));
assert!(sig.ends_with('\n'));
}
#[test]
fn approval_signs_only_a_valid_text_for_its_own_run() {
let k = new_ed25519();
let e = approval(&k.secret, &k.key_id, &canonical(), NOW, "r-43").unwrap_err();
assert!(e.to_string().contains("run"), "{e}");
assert!(approval(&k.secret, &k.key_id, &format!("{}\n", canonical()), NOW, "r-42").is_err());
assert!(approval(&k.secret, &k.key_id, &canonical(), NOW + 600, "r-42").is_err(), "expired at signing time");
}
#[test]
fn parse_reads_the_form_without_the_clock() {
// For the audit of a refused or expired request: everything but the expiry is checked.
let a = approval_parse(&canonical()).unwrap();
assert_eq!(a, approval_check(&canonical(), NOW).unwrap());
assert!(approval_check(&canonical(), NOW + 10_000).is_err());
assert_eq!(approval_parse(&canonical()).unwrap().expires, NOW + 600);
assert!(approval_parse(&canonical().replace(',', ", ")).is_err());
assert!(approval_parse(&with("\"run\":\"r-42\"", "\"run\":\"r 42\"")).is_err());
}
#[test]
fn run_ids_follow_the_rule() {
for ok in ["r-42", "setup-1", "a.b_c", &"x".repeat(64)] {
assert!(run_id_ok(ok), "{ok}");
}
for bad in ["", "a b", "a/b", "ř", &"x".repeat(65)] {
assert!(!run_id_ok(bad), "{bad}");
}
}
+91
View File
@@ -0,0 +1,91 @@
//! cosign and the Tauri updater envelope (docs/TEAM.md, "Signature envelopes"; core 0.18.0).
use custos_sign::*;
#[test]
fn the_cosign_payload_is_written_exactly_as_the_doc_says() {
let p = cosign_payload("gitea.example/team/arca", &[0xab; 32]).unwrap();
assert_eq!(
p,
"{\"critical\":{\"identity\":{\"docker-reference\":\"gitea.example/team/arca\"},\"image\":{\"docker-manifest-digest\":\"sha256:abababababababababababababababababababababababababababababababab\"},\"type\":\"cosign container image signature\"},\"optional\":null}"
);
let v: serde_json::Value = serde_json::from_str(&p).unwrap();
assert_eq!(v["critical"]["type"], "cosign container image signature");
assert!(v["optional"].is_null());
}
#[test]
fn image_references_are_checked() {
for bad in ["", "Arca", "a b", "x@sha256:00", "/a", "a/", "a//b", "a\"b", "a\nb"] {
assert!(cosign_payload(bad, &[0; 32]).is_err(), "{bad:?}");
}
for good in ["arca", "registry.example:5000/team/app", "ghcr.io/mnovak/custos-share"] {
assert!(cosign_payload(good, &[0; 32]).is_ok(), "{good}");
}
assert_eq!(cosign_payload("arca", &[0; 31]), Err(Error::DigestLength(32)));
}
#[test]
fn a_cosign_signature_verifies_and_only_over_its_payload() {
let key = new_p256();
let pem = key.public_pem().unwrap();
assert!(pem.starts_with("-----BEGIN PUBLIC KEY-----\n"));
let payload = cosign_payload("arca", &[7; 32]).unwrap();
let sig = cosign(&key, &payload).unwrap();
assert!(cosign_verify(&pem, payload.as_bytes(), &sig));
// RFC 6979: the same key and payload give the same signature.
assert_eq!(sig, cosign(&key, &payload).unwrap());
let other = cosign_payload("arca", &[8; 32]).unwrap();
assert!(!cosign_verify(&pem, other.as_bytes(), &sig));
assert!(!cosign_verify(&new_p256().public_pem().unwrap(), payload.as_bytes(), &sig));
let again = P256Secret::from_bytes(*key.expose()).unwrap();
assert_eq!(again.public_pem().unwrap(), pem);
assert_eq!(format!("{key:?}"), "[redacted]");
assert!(P256Secret::from_bytes([0; 32]).is_err());
assert!(P256Secret::from_bytes([0xff; 32]).is_err());
}
/// The cosign signature against openssl, a standard tool (`openssl dgst -sha256 -verify`, what a cosign
/// signature is underneath). Skipped with a note when openssl is not on PATH.
#[test]
fn openssl_verifies_a_cosign_signature() {
if std::process::Command::new("openssl").arg("version").output().is_err() {
eprintln!("openssl not found: skipped");
return;
}
let dir = std::env::temp_dir().join(format!("custos-cosign-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let key = new_p256();
let payload = cosign_payload("registry.example/team/arca", &[3; 32]).unwrap();
let sig = cosign(&key, &payload).unwrap();
std::fs::write(dir.join("cosign.pub"), key.public_pem().unwrap()).unwrap();
std::fs::write(dir.join("payload.json"), &payload).unwrap();
std::fs::write(dir.join("other.json"), payload.replace("arca", "arcb")).unwrap();
std::fs::write(dir.join("sig.der"), &sig).unwrap();
let verify = |file: &str| {
std::process::Command::new("openssl")
.args(["dgst", "-sha256", "-verify", "cosign.pub", "-signature", "sig.der", file])
.current_dir(&dir)
.output()
.unwrap()
};
let ok = verify("payload.json");
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stdout));
assert!(String::from_utf8_lossy(&ok.stdout).contains("Verified OK"));
assert!(!verify("other.json").status.success());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_tauri_envelope_is_base64_of_the_minisign_file_and_tauris_verifier_reads_it() {
let k = new_ed25519();
let file = b"Arca_0.7.0_x64-setup.exe contents";
let minisig = minisign(&k.secret, &k.key_id, &blake2b512(file), "Arca_0.7.0_x64-setup.exe", 1_794_000_000).unwrap();
let sig = tauri_updater(&minisig);
let pubkey = tauri_updater(&minisign_public(&k.public, &k.key_id));
// What tauri-plugin-updater does: base64-decode both, then minisign-verify.
let pk = minisign_verify::PublicKey::decode(&tauri_updater_open(&pubkey).unwrap()).unwrap();
let s = minisign_verify::Signature::decode(&tauri_updater_open(&sig).unwrap()).unwrap();
pk.verify(file, &s, true).unwrap();
assert!(pk.verify(b"another file", &s, true).is_err());
assert_eq!(tauri_updater_open("not base64!"), None);
}
+8
View File
@@ -0,0 +1,8 @@
Throwaway **test keys** for the known-answer tests in `../kat.rs`. They sign nothing real and are not secret.
- `minisign.key`, `minisign.pub`: made by minisign 0.12 (`minisign -G -W`, unencrypted);
`payload.bin.minisig`: `minisign -S -m payload.bin -t "timestamp:1700000000<TAB>file:payload.bin<TAB>hashed"`.
- `rsa3072.pk8.der`: `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072`, then `openssl pkcs8 -topk8 -nocrypt`;
`digest.openssl.sig`: `openssl pkeyutl -sign -in digest.bin -pkeyopt digest:sha256` (PKCS#1 v1.5).
- `digest512.bin` (64 random bytes) and `digest512.openssl.sig`: `openssl pkeyutl -sign -inkey rsa3072.pk8.der -keyform DER
-in digest512.bin -pkeyopt digest:sha512` (PKCS#1 v1.5 with the SHA-512 DigestInfo: the `apk` kind).
+1
View File
@@ -0,0 +1 @@
a 32-byte authenticode digest!!!
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign encrypted secret key
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxBvPgUoXv/LZDCnnxOD2qjtAzgKzt2QB+BBy+4kjkKJHj7TUGad2U26fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign public key F2BF174A81CF1BC4
RWTEG8+BShe/8m6fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7
+1
View File
@@ -0,0 +1 @@
Domi release test payload: not a real file.
+4
View File
@@ -0,0 +1,4 @@
untrusted comment: signature from minisign secret key
RUTEG8+BShe/8k8Vdth34r/l/IFsZ8pkM0jYtPdZhh0DM64A4TS0EKmGNrkj5Pu2Xwc2tIyuRxlM7v4EBYvg56e31UQelhhc2QY=
trusted comment: timestamp:1700000000 file:payload.bin hashed
dt96Kkj7fBuSn8yp9AA3Ggx3FFf5G6Ta6MnGjyP//1FsvNhJtwd2Mh3dgDLwJqXPggz+P3mJgFrfFvg53CohAg==
Binary file not shown.
+252
View File
@@ -0,0 +1,252 @@
//! Mandatory test 1 (docs/SIGNING.md): known answers for every signature kind, from tools that are not this crate.
//! The fixtures are throwaway test keys: `minisign.key` was made by minisign 0.12 (`-G -W`, unencrypted) and
//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der`, `digest.openssl.sig` and `digest512.openssl.sig` by
//! `openssl pkeyutl`.
//! tools/signing/interop.ps1 checks the other direction with the real minisign, signtool and osslsigncode.
use std::fs;
use std::path::PathBuf;
use custos_sign::*;
use data_encoding::BASE64;
use x509_cert::Certificate;
use x509_cert::der::{Decode, Encode};
fn fixture(name: &str) -> Vec<u8> {
fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap()
}
fn text(name: &str) -> String {
String::from_utf8(fixture(name)).unwrap()
}
/// The seed and key id of minisign's unencrypted secret key file.
fn minisign_key() -> (Ed25519Secret, [u8; 8]) {
let file = text("minisign.key");
let raw = BASE64.decode(file.lines().nth(1).unwrap().as_bytes()).unwrap();
assert_eq!(&raw[0..2], b"Ed");
assert_eq!(&raw[2..4], &[0, 0], "the fixture key must be unencrypted");
// sig_alg 2, kdf_alg 2, cksum_alg 2, salt 32, opslimit 8, memlimit 8, then key id 8 and seed ‖ public 64.
let key_id: [u8; 8] = raw[54..62].try_into().unwrap();
let seed: [u8; 32] = raw[62..94].try_into().unwrap();
(Ed25519Secret::from_bytes(seed), key_id)
}
#[test]
fn minisign_signature_equals_the_real_minisigns() {
let (secret, key_id) = minisign_key();
let ours = minisign(&secret, &key_id, &blake2b512(&fixture("payload.bin")), "payload.bin", 1_700_000_000).unwrap();
let theirs = text("payload.bin.minisig");
// The untrusted comment is free text; the signature, the trusted comment and the global signature are not.
let tail = |s: &str| s.lines().skip(1).map(String::from).collect::<Vec<_>>();
assert_eq!(tail(&ours), tail(&theirs));
assert!(ours.ends_with('\n'));
}
#[test]
fn the_public_key_file_equals_the_real_minisigns() {
let (secret, key_id) = minisign_key();
let ours = minisign_public(&secret.public(), &key_id);
assert_eq!(ours, text("minisign.pub"));
}
#[test]
fn minisign_verify_accepts_our_signatures_and_rejects_a_changed_file() {
// minisign-verify is what Tauri's updater checks signatures with.
let (secret, key_id) = minisign_key();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
let data = b"the installer bytes";
let sig = minisign(&secret, &key_id, &blake2b512(data), "Arca_0.2.0_x64-setup.exe", 1_793_750_000).unwrap();
let sig = minisign_verify::Signature::decode(&sig).unwrap();
public.verify(data, &sig, false).unwrap();
assert!(public.verify(b"another file", &sig, false).is_err());
assert_eq!(sig.trusted_comment(), "timestamp:1793750000\tfile:Arca_0.2.0_x64-setup.exe\thashed");
}
#[test]
fn a_manifest_is_signed_over_its_own_text() {
let (secret, key_id) = minisign_key();
let sums =
format!("{} Arca_0.2.0_x64-setup.exe\n{} Arca_0.2.0_x64-setup.exe.sig\n", "a".repeat(64), "0".repeat(64));
let sig = manifest(&secret, &key_id, &sums, 1_793_750_000).unwrap();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
public.verify(sums.as_bytes(), &minisign_verify::Signature::decode(&sig).unwrap(), false).unwrap();
assert!(sig.contains("\tfile:SHA256SUMS\t"));
}
#[test]
fn only_a_canonical_manifest_is_signed() {
let h = "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3";
assert!(manifest_check(&format!("{h} a.exe\n{h} b.exe\n")).is_ok());
let bad = [
("", "empty"),
(&*format!("{h} b.exe\n{h} a.exe\n"), "sorted"),
(&*format!("{h} a.exe\n{h} a.exe\n"), "sorted and unique"),
(&*format!("{} a.exe\n", h.to_uppercase()), "lower-case"),
(&*format!("{h} a.exe\r\n"), "CRLF"),
(&*format!("{h} a.exe"), "no newline"),
(&*format!("{h} a.exe\n"), "not `<sha256> <name>`"),
(&*format!("{h} *a.exe\n"), "not `<sha256> <name>`"),
(&*format!("{h} dir/a.exe\n"), "plain file name"),
(&*format!("{h} -rf\n"), "plain file name"),
(&*format!("{} a.exe\n", &h[..63]), "64 lower-case"),
];
for (t, why) in bad {
let e = manifest_check(t).unwrap_err().to_string();
assert!(e.contains(why), "{t:?}: {e}");
}
let big = format!("{h} {}\n", "x".repeat(MAX_MANIFEST));
assert!(manifest_check(&big).unwrap_err().to_string().contains("32 KiB"));
}
#[test]
fn authenticode_signature_equals_openssls() {
let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
let ours = authenticode(&key, &fixture("digest.bin")).unwrap();
assert_eq!(ours.len(), 384);
assert_eq!(ours, fixture("digest.openssl.sig"));
assert_eq!(authenticode(&key, &[0u8; 31]).unwrap_err(), Error::DigestLength(32));
assert_eq!(authenticode(&key, &[0u8; 64]).unwrap_err(), Error::DigestLength(32));
}
#[test]
fn apk_signatures_equal_openssls_sha512_pkcs1() {
// The PKCS#1 v1.5 SHA-512 DigestInfo does not depend on the key size: the 3072-bit fixture checks it.
let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
let digest = fixture("digest512.bin");
let expected = fixture("digest512.openssl.sig");
assert_eq!(apk(&key, &digest).unwrap(), expected);
// Two digests (v2 and v3): two signatures, in order.
let mut two = digest.clone();
two.extend(custos_sign::sha256_hex(&digest).as_bytes()); // any other 64 bytes
let both = apk(&key, &two).unwrap();
assert_eq!(both.len(), 2 * 384);
assert_eq!(&both[..384], expected.as_slice());
assert_eq!(both[384..].to_vec(), apk(&key, &two[64..]).unwrap());
for bad in [0usize, 32, 63, 65, 64 * 5] {
assert_eq!(apk(&key, &vec![1u8; bad]).unwrap_err(), Error::ApkDigests, "{bad}");
}
}
#[test]
fn an_android_key_is_rsa_4096_with_a_self_signed_end_entity_certificate_for_100_years() {
use rsa::RsaPublicKey;
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::Verifier;
use rsa::signature::hazmat::PrehashVerifier;
use rsa::traits::PublicKeyParts;
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage, KeyUsage};
let made = new_android("Postea", "Marek Novak", "CZ").unwrap();
let c = Certificate::from_der(&made.cert_der).unwrap();
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject, "self-signed");
let v = &c.tbs_certificate.validity;
let days = (v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / 86_400;
assert_eq!(days, 100 * 365);
let (_, bc) = c.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(!bc.ca, "not a CA");
assert!(c.tbs_certificate.get::<KeyUsage>().unwrap().is_some());
assert!(c.tbs_certificate.get::<ExtendedKeyUsage>().unwrap().is_none(), "no extended key usage");
let spki = c.tbs_certificate.subject_public_key_info.to_der().unwrap();
assert_eq!(RsaPublicKey::from_public_key_der(&spki).unwrap().n().bits(), 4096);
// Signed by its own key, and that key makes the APK signatures.
let sha256 = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(&spki).unwrap();
sha256
.verify(&c.tbs_certificate.to_der().unwrap(), &Signature::try_from(c.signature.raw_bytes()).unwrap())
.unwrap();
let digests = [3u8; 128];
let sigs = apk(&made.secret, &digests).unwrap();
assert_eq!(sigs.len(), 2 * 512);
let sha512 = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
for (d, s) in digests.chunks(64).zip(sigs.chunks(512)) {
sha512.verify_prehash(d, &Signature::try_from(s).unwrap()).unwrap();
}
// An Android key is not an Authenticode key, but the function cannot tell: the vault keeps them apart.
assert_eq!(format!("{:?}", made.secret), "[redacted]");
for (cn, o, c) in [
("", "O", "CZ"),
("A,B", "O", "CZ"),
(" Postea", "O", "CZ"),
("Postea", "O=x", "CZ"),
("Postea", "O", "cz"),
("Postea", "O", "CZE"),
(
"Postea", "O
", "CZ",
),
] {
assert!(matches!(new_android(cn, o, c), Err(Error::Certificate)), "{cn:?} {o:?} {c:?}");
}
}
#[test]
fn digests_and_file_names_are_checked() {
let (secret, key_id) = minisign_key();
assert_eq!(minisign(&secret, &key_id, &[0u8; 32], "a", 1).unwrap_err(), Error::DigestLength(64));
for bad in ["", "dir/a.exe", "a\\b", "a\nb", "tab\there"] {
assert!(matches!(minisign(&secret, &key_id, &[0u8; 64], bad, 1), Err(Error::FileName(_))), "{bad:?}");
}
}
#[test]
fn the_household_ca_issues_a_code_signing_leaf() {
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::Verifier;
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage};
let root = new_root("Domi Household Root CA", 10).unwrap();
let rkey = RsaSecret::from_pkcs8_der(root.secret.expose().to_vec()).unwrap();
let leaf = new_code_signing("Domi Code Signing", 2, &rkey, &root.cert_der).unwrap();
let rc = Certificate::from_der(&root.cert_der).unwrap();
let lc = Certificate::from_der(&leaf.cert_der).unwrap();
assert_eq!(rc.tbs_certificate.subject.to_string(), "CN=Domi Household Root CA,O=Domi");
assert_eq!(rc.tbs_certificate.issuer, rc.tbs_certificate.subject);
assert_eq!(lc.tbs_certificate.issuer, rc.tbs_certificate.subject);
let years = |c: &Certificate| {
let v = &c.tbs_certificate.validity;
(v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / (365 * 86_400)
};
assert_eq!((years(&rc), years(&lc)), (10, 2));
let (_, bc) = rc.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(bc.ca);
let (_, bc) = lc.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(!bc.ca);
let (_, eku) = lc.tbs_certificate.get::<ExtendedKeyUsage>().unwrap().unwrap();
assert_eq!(eku.0.iter().map(|o| o.to_string()).collect::<Vec<_>>(), vec!["1.3.6.1.5.5.7.3.3"]);
// The leaf is signed by the root's key, and the leaf's key is the one in its certificate.
let rpub = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&rc.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
let sig = Signature::try_from(lc.signature.raw_bytes()).unwrap();
rpub.verify(&lc.tbs_certificate.to_der().unwrap(), &sig).unwrap();
let digest = [7u8; 32];
let lsig = authenticode(&leaf.secret, &digest).unwrap();
let lpub = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&lc.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
use rsa::signature::hazmat::PrehashVerifier;
lpub.verify_prehash(&digest, &Signature::try_from(lsig.as_slice()).unwrap()).unwrap();
assert!(cert_pem(&root.cert_der).starts_with("-----BEGIN CERTIFICATE-----\n"));
}
#[test]
fn secrets_never_print() {
let (secret, _) = minisign_key();
let rsa = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
assert_eq!(format!("{secret:?}"), "[redacted]");
assert_eq!(format!("{rsa:?}"), "[redacted]");
let made = new_ed25519();
assert_eq!(format!("{:?}", made.secret), "[redacted]");
assert_eq!(made.public, made.secret.public());
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "custos-team"
description = "Custos Domi: team vaults' pure parts (member keys, policy evaluation, the canonical sign.request, approval statements, policy proofs)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-seal = { path = "../custos-seal" }
custos-sign = { path = "../custos-sign" }
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
sha2.workspace = true
hmac.workspace = true
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
zeroize.workspace = true
thiserror.workspace = true
rand.workspace = true
[dev-dependencies]
minisign-verify = "0.3"
+54
View File
@@ -0,0 +1,54 @@
//! The canonical JSON every signed text here uses (as deploy approvals, SIGNING.md): fixed key order, no spaces,
//! `"` and `\` escaped and nothing else, no newline. Callers only write strings that passed [`text_ok`].
/// Appends `s` as a JSON string with minimal escaping.
pub fn string(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c => out.push(c),
}
}
out.push('"');
}
/// Appends `["a","b"]`.
pub fn strings(out: &mut String, list: &[String]) {
out.push('[');
for (i, s) in list.iter().enumerate() {
if i > 0 {
out.push(',');
}
string(out, s);
}
out.push(']');
}
/// Characters a shown text may not hold: control characters, and the invisible ones that change how a line looks
/// on a card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen).
pub fn unprintable(c: char) -> bool {
c.is_control()
|| matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}')
|| matches!(c, '\u{2060}'..='\u{2069}' | '\u{FEFF}')
}
/// 1..=`max` characters, none of them [`unprintable`].
pub fn text_ok(s: &str, max: usize) -> bool {
(1..=max).contains(&s.chars().count()) && !s.chars().any(unprintable)
}
/// `min..=max` bytes, every one ASCII alphanumeric or in `extra`.
pub fn ascii_ok(s: &str, min: usize, max: usize, extra: &[u8]) -> bool {
(min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || extra.contains(&c))
}
/// An environment name: `[a-z][a-z0-9-]{0,31}`.
pub fn env_ok(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 32
&& b[0].is_ascii_lowercase()
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
}
+34
View File
@@ -0,0 +1,34 @@
//! The one interface an external signer is reached through (docs/TEAM.md, Authenticode). A hardware token or a
//! cloud signing service holds the private key; Custos approves, then hands the adapter the digest and the
//! credential that lets it ask. Adapters are the app's (I/O); this crate only names the shape.
use std::fmt;
/// The credential an adapter uses, borrowed from the team vault for one call. Prints `[redacted]` for `secret`.
pub struct SignerCredential<'a> {
pub id: &'a str,
pub name: &'a str,
/// Which adapter: `command` in this phase.
pub adapter: &'a str,
pub endpoint: &'a str,
pub account: &'a str,
pub secret: &'a str,
}
impl fmt::Debug for SignerCredential<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SignerCredential")
.field("id", &self.id)
.field("adapter", &self.adapter)
.field("endpoint", &self.endpoint)
.field("secret", &"[redacted]")
.finish_non_exhaustive()
}
}
/// Signs a 32-byte SHA-256 digest (signtool's `.dig`) with a key Custos never holds: returns the raw signature
/// (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo, as `signtool sign /di` wants it). An error names what failed,
/// never the credential.
pub trait ExternalSigner {
fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result<Vec<u8>, String>;
}
+100
View File
@@ -0,0 +1,100 @@
//! Custos Domi · teams (docs/TEAM.md, core 0.18.0): the pure parts of team vaults and team signing.
//!
//! - [`member`]: a person's member key (X25519 to receive the team key, Ed25519 to sign approvals), the member id,
//! the join code, and sealing the team key to a member;
//! - [`policy`]: one rule per environment, its canonical text, and [`policy::evaluate`];
//! - [`request`]: the canonical `sign.request` and `target.request`, their hash and match code;
//! - [`statement`]: a member's signed approval of one request;
//! - [`proof`]: the team identity's policy proof, and checking it;
//! - [`reply`]: what goes back to Fabrica, sealed; [`target`]: a released target credential;
//! - [`external`]: the interface an external signer (a hardware token, a cloud signing service) is reached through.
//!
//! No I/O, no clock: every check takes `now` from the caller. Secrets print as `[redacted]`.
pub mod canon;
pub mod external;
pub mod member;
pub mod policy;
pub mod proof;
pub mod reply;
pub mod request;
pub mod statement;
pub mod target;
pub use member::{MemberKey, MemberPublic, TeamIdentity};
pub use policy::{EnvRule, Evaluation, KeyRole, Policy, RosterMember, Verdict, evaluate};
pub use proof::{Proof, Verified, verify_proof};
pub use request::{Format, SignRequest, TargetRequest};
pub use statement::Statement;
/// How far ahead a request may expire: 25 hours, as deploy approvals (SIGNING.md).
pub const MAX_AHEAD_SECS: u64 = 25 * 3600;
/// How long a signed request's hash is remembered against replay: longer than any request lives.
pub const SEEN_SECS: u64 = 48 * 3600;
/// The most members a team has (member slots in one file).
pub const MAX_MEMBERS: usize = 32;
/// Why something is refused. None of them carries a key, a credential or a signature.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TeamError {
#[error("not in canonical form: {0}")]
NotCanonical(&'static str),
#[error("{0}")]
Invalid(&'static str),
#[error("the request has expired")]
Expired,
#[error("the match code is not this request's: someone else's request may be waiting, refuse it")]
WrongMatch,
#[error("this request was already answered: a replay is refused")]
Replayed,
#[error("the request is for another team")]
WrongTeam,
#[error("not a member of this team")]
NotAMember,
#[error("a signature does not verify")]
BadSignature,
#[error("the policy has no rule for this environment")]
UnknownEnv,
#[error("the policy cannot be met: {0}")]
Unsatisfiable(&'static str),
#[error("the policy needs {0} more approval(s)")]
NeedMore(u8),
#[error("this member may not approve this request: {0}")]
NotEligible(&'static str),
#[error("the key cannot be read")]
BadKey,
}
pub(crate) fn hex(b: &[u8]) -> String {
data_encoding::HEXLOWER.encode(b)
}
pub(crate) fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
let v = data_encoding::HEXLOWER.decode(s.as_bytes()).ok()?;
v.try_into().ok()
}
pub(crate) fn b64(b: &[u8]) -> String {
data_encoding::BASE64.encode(b)
}
pub(crate) fn unb64(s: &str) -> Option<Vec<u8>> {
data_encoding::BASE64.decode(s.as_bytes()).ok()
}
pub(crate) fn sha256(b: &[u8]) -> [u8; 32] {
use sha2::Digest;
sha2::Sha256::digest(b).into()
}
/// 32 lower-case hex digits: a team, member or request id.
pub fn id_ok(s: &str) -> bool {
s.len() == 32 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
/// A random 16-byte id, hex.
pub fn new_id() -> String {
let mut b = [0u8; 16];
rand::Rng::fill_bytes(&mut rand::rand_core::UnwrapErr(rand::rngs::SysRng), &mut b);
hex(&b)
}
+179
View File
@@ -0,0 +1,179 @@
//! A person's member key, the team identity, and sealing the team key to a member (docs/TEAM.md, "The member key",
//! "The team vault file").
use std::fmt;
use custos_seal::Recipient;
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use zeroize::Zeroizing;
use crate::{TeamError, hex, sha256};
/// The size of a sealed team key: custos-seal's box around 32 bytes.
pub const SEALED_KEY_LEN: usize = 4 + 32 + 24 + 32 + 16;
/// The public half of a member key, as the roster and the service keep it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MemberPublic {
pub ed25519: [u8; 32],
pub x25519: [u8; 32],
}
impl MemberPublic {
/// The member id: the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 ‖ x25519)`, 32 hex.
pub fn id(&self) -> String {
hex(&self.id_bytes())
}
pub fn id_bytes(&self) -> [u8; 16] {
let mut m = Vec::with_capacity(16 + 64);
m.extend_from_slice(b"custos member v1");
m.extend_from_slice(&self.ed25519);
m.extend_from_slice(&self.x25519);
sha256(&m)[..16].try_into().expect("16 bytes")
}
/// The code a joining member's screen shows and the approving member compares: `match_code(x25519)`.
pub fn join_code(&self) -> String {
custos_seal::match_code(&self.x25519)
}
/// Both keys must be usable: an Ed25519 point and a contributory X25519 key.
pub fn check(&self) -> Result<(), TeamError> {
VerifyingKey::from_bytes(&self.ed25519).map_err(|_| TeamError::BadKey)?;
custos_seal::seal(&self.x25519, b"check", b"").map_err(|_| TeamError::BadKey)?;
Ok(())
}
/// Checks an Ed25519 signature by this member over `msg`.
pub fn verify(&self, msg: &[u8], sig: &[u8; 64]) -> bool {
verify(&self.ed25519, msg, sig)
}
}
pub(crate) fn verify(public: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> bool {
let Ok(key) = VerifyingKey::from_bytes(public) else {
return false;
};
key.verify_strict(msg, &Signature::from_bytes(sig)).is_ok()
}
/// The context a team key is sealed under for one member slot.
pub fn key_context(team: &str, epoch: u32, member: &str) -> Vec<u8> {
format!("custos team key v1:{team}:{epoch}:{member}").into_bytes()
}
/// Seals the 32-byte team key to a member for one team and epoch: the member slot's box ([`SEALED_KEY_LEN`] bytes).
pub fn seal_team_key(team_key: &[u8; 32], to: &MemberPublic, team: &str, epoch: u32) -> Result<Vec<u8>, TeamError> {
custos_seal::seal(&to.x25519, &key_context(team, epoch, &to.id()), team_key).map_err(|_| TeamError::BadKey)
}
/// A person's member key. Lives in their own vault; wiped on drop; prints `[redacted]`.
pub struct MemberKey {
x: Recipient,
ed: SigningKey,
}
impl MemberKey {
/// A new member key from the OS CSPRNG.
pub fn generate() -> MemberKey {
let ed = custos_seal::random_bytes();
MemberKey { x: Recipient::generate(), ed: SigningKey::from_bytes(&ed) }
}
/// The key as the member's vault keeps it.
pub fn from_secrets(x25519: Zeroizing<[u8; 32]>, ed25519: Zeroizing<[u8; 32]>) -> Result<MemberKey, TeamError> {
let x = Recipient::from_secret(x25519).map_err(|_| TeamError::BadKey)?;
Ok(MemberKey { x, ed: SigningKey::from_bytes(&ed25519) })
}
/// The X25519 secret, for the member's own vault only.
pub fn x25519_secret(&self) -> Zeroizing<[u8; 32]> {
self.x.secret_bytes()
}
/// The Ed25519 seed, for the member's own vault only.
pub fn ed25519_secret(&self) -> Zeroizing<[u8; 32]> {
Zeroizing::new(self.ed.to_bytes())
}
pub fn public(&self) -> MemberPublic {
MemberPublic { ed25519: self.ed.verifying_key().to_bytes(), x25519: self.x.public() }
}
pub fn id(&self) -> String {
self.public().id()
}
/// Opens this member's slot of a team vault: the team key.
pub fn open_team_key(&self, sealed: &[u8], team: &str, epoch: u32) -> Result<Zeroizing<[u8; 32]>, TeamError> {
let k = self.x.open(sealed, &key_context(team, epoch, &self.id())).map_err(|_| TeamError::NotAMember)?;
let k: [u8; 32] = k.as_slice().try_into().map_err(|_| TeamError::NotAMember)?;
Ok(Zeroizing::new(k))
}
/// Signs `msg` with the member's Ed25519 key (approval statements only; the domain is the caller's prefix).
pub(crate) fn sign(&self, msg: &[u8]) -> [u8; 64] {
self.ed.sign(msg).to_bytes()
}
/// Opens a box sealed to this member's X25519 key (for a joiner: nothing else is ever sealed to it).
pub fn recipient(&self) -> &Recipient {
&self.x
}
}
impl fmt::Debug for MemberKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// The team identity: an Ed25519 key in the team body that signs the policy and the proofs, and never rotates.
pub struct TeamIdentity(SigningKey);
/// Domain prefixes, so a signature of one kind never passes for another.
pub const POLICY_DOMAIN: &[u8] = b"custos team policy v1\0";
pub const PROOF_DOMAIN: &[u8] = b"custos team proof v1\0";
impl TeamIdentity {
pub fn generate() -> TeamIdentity {
TeamIdentity(SigningKey::from_bytes(&custos_seal::random_bytes()))
}
pub fn from_secret(secret: &[u8; 32]) -> TeamIdentity {
TeamIdentity(SigningKey::from_bytes(secret))
}
pub fn secret(&self) -> Zeroizing<[u8; 32]> {
Zeroizing::new(self.0.to_bytes())
}
pub fn public(&self) -> [u8; 32] {
self.0.verifying_key().to_bytes()
}
pub fn sign_policy(&self, text: &str) -> [u8; 64] {
self.0.sign(&[POLICY_DOMAIN, text.as_bytes()].concat()).to_bytes()
}
pub fn sign_proof(&self, text: &str) -> [u8; 64] {
self.0.sign(&[PROOF_DOMAIN, text.as_bytes()].concat()).to_bytes()
}
}
impl fmt::Debug for TeamIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// Checks the team identity's signature on a policy text.
pub fn verify_policy_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool {
verify(identity, &[POLICY_DOMAIN, text.as_bytes()].concat(), sig)
}
/// Checks the team identity's signature on a proof text.
pub fn verify_proof_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool {
verify(identity, &[PROOF_DOMAIN, text.as_bytes()].concat(), sig)
}
+290
View File
@@ -0,0 +1,290 @@
//! The approval policy: one rule per environment, its canonical text, and its evaluation (docs/TEAM.md, "Policy").
use serde::{Deserialize, Serialize};
use crate::{TeamError, canon, id_ok};
/// One environment's rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnvRule {
pub env: String,
/// How many members must approve: 0 ..= 10. At 0 a test-role key signs without a card.
pub approvals: u8,
/// The approvers must not include the release's author, when the team has 2 or more members.
pub others: bool,
/// Member ids allowed to approve; empty = every member.
pub approvers: Vec<String>,
}
/// A team's policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Policy {
pub team: String,
pub rev: u32,
pub envs: Vec<EnvRule>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyJson {
v: u32,
team: String,
rev: u32,
envs: Vec<EnvRule>,
}
pub const MAX_APPROVALS: u8 = 10;
pub const MAX_ENVS: usize = 8;
impl Policy {
/// The default (docs/TEAM.md): preview 0, staging 1, production 1 by someone other than the author.
pub fn default_for(team: &str) -> Policy {
let rule = |env: &str, approvals, others| EnvRule { env: env.into(), approvals, others, approvers: vec![] };
Policy {
team: team.into(),
rev: 1,
envs: vec![rule("preview", 0, false), rule("staging", 1, false), rule("production", 1, true)],
}
}
pub fn rule(&self, env: &str) -> Option<&EnvRule> {
self.envs.iter().find(|r| r.env == env)
}
/// The canonical text the team identity signs.
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(256);
o.push_str("{\"v\":1,\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"rev\":");
o.push_str(&self.rev.to_string());
o.push_str(",\"envs\":[");
for (i, r) in self.envs.iter().enumerate() {
if i > 0 {
o.push(',');
}
o.push_str("{\"env\":");
canon::string(&mut o, &r.env);
o.push_str(",\"approvals\":");
o.push_str(&r.approvals.to_string());
o.push_str(",\"others\":");
o.push_str(if r.others { "true" } else { "false" });
o.push_str(",\"approvers\":");
canon::strings(&mut o, &r.approvers);
o.push('}');
}
o.push_str("]}");
o
}
/// Every rule as docs/TEAM.md allows it.
pub fn check(&self) -> Result<(), TeamError> {
let bad = |why| Err(TeamError::Invalid(why));
if !id_ok(&self.team) {
return bad("the policy's team is not an id");
}
if self.rev == 0 {
return bad("the policy's rev starts at 1");
}
if self.envs.is_empty() || self.envs.len() > MAX_ENVS {
return bad("a policy has 1 to 8 environments");
}
for (i, r) in self.envs.iter().enumerate() {
if !canon::env_ok(&r.env) {
return bad("an environment is not [a-z][a-z0-9-]{0,31}");
}
if self.envs[..i].iter().any(|o| o.env == r.env) {
return bad("an environment is named twice");
}
if r.approvals > MAX_APPROVALS {
return bad("at most 10 approvals");
}
if r.approvers.len() > crate::MAX_MEMBERS || !r.approvers.iter().all(|a| id_ok(a)) {
return bad("approvers are member ids");
}
if r.approvers.iter().enumerate().any(|(j, a)| r.approvers[..j].contains(a)) {
return bad("an approver is named twice");
}
}
Ok(())
}
/// Reads a canonical policy text; anything else is refused, not normalised.
pub fn parse(text: &str) -> Result<Policy, TeamError> {
if text.len() > 16 * 1024 {
return Err(TeamError::NotCanonical("a policy is at most 16 KiB"));
}
let j: PolicyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a policy"))?;
if j.v != 1 {
return Err(TeamError::NotCanonical("v is not 1"));
}
let p = Policy { team: j.team, rev: j.rev, envs: j.envs };
p.check()?;
if p.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
Ok(p)
}
/// Replaces (or adds) one environment's rule and raises `rev`.
pub fn set_rule(&mut self, rule: EnvRule) -> Result<(), TeamError> {
let mut next = self.clone();
match next.envs.iter_mut().find(|r| r.env == rule.env) {
Some(r) => *r = rule,
None => next.envs.push(rule),
}
next.rev = self.rev.checked_add(1).ok_or(TeamError::Invalid("rev overflow"))?;
next.check()?;
*self = next;
Ok(())
}
}
/// A member as the policy sees it: who they are and the names Fabrica knows them by.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RosterMember {
pub id: String,
pub name: String,
pub handles: Vec<String>,
pub ed25519: [u8; 32],
}
impl RosterMember {
/// The member's id, or one of their handles (ASCII case-insensitive), names `author`.
pub fn is(&self, author: &str) -> bool {
!author.is_empty() && (self.id == author || self.handles.iter().any(|h| h.eq_ignore_ascii_case(author)))
}
}
/// Which kind of key a verdict allows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KeyRole {
/// The environment asks for 1+ approvals and they are there: the release keys.
Release,
/// The environment asks for 0: a test-role key, no card.
Test,
}
impl KeyRole {
pub fn word(self) -> &'static str {
match self {
KeyRole::Release => "release",
KeyRole::Test => "test",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
Allowed(KeyRole),
/// This many more eligible approvals are needed.
Need(u8),
/// No set of approvals can ever meet the rule.
Unsatisfiable(&'static str),
UnknownEnv,
}
/// The verdict and how it was reached.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Evaluation {
pub verdict: Verdict,
/// Members who may approve this request.
pub eligible: Vec<String>,
/// The approvals that counted, distinct, in the order given.
pub counted: Vec<String>,
/// Approvals that did not count: not on the roster, not eligible (the author, not an approver), a repeat.
pub ignored: Vec<String>,
}
impl Evaluation {
pub fn into_result(self) -> Result<KeyRole, TeamError> {
match self.verdict {
Verdict::Allowed(r) => Ok(r),
Verdict::Need(n) => Err(TeamError::NeedMore(n)),
Verdict::Unsatisfiable(w) => Err(TeamError::Unsatisfiable(w)),
Verdict::UnknownEnv => Err(TeamError::UnknownEnv),
}
}
}
/// Who may approve a request for `env` by `author`.
pub fn eligible(policy: &Policy, roster: &[RosterMember], env: &str, author: &str) -> Option<Vec<String>> {
let rule = policy.rule(env)?;
let others = rule.others && roster.len() >= 2;
Some(
roster
.iter()
.filter(|m| rule.approvers.is_empty() || rule.approvers.contains(&m.id))
.filter(|m| !(others && m.is(author)))
.map(|m| m.id.clone())
.collect(),
)
}
/// Evaluates the policy for one request (docs/TEAM.md, "Evaluation"). `approvers` are member ids whose approval
/// statements were already checked.
pub fn evaluate(policy: &Policy, roster: &[RosterMember], env: &str, author: &str, approvers: &[String]) -> Evaluation {
let Some(rule) = policy.rule(env) else {
return Evaluation {
verdict: Verdict::UnknownEnv,
eligible: vec![],
counted: vec![],
ignored: approvers.to_vec(),
};
};
let eligible = eligible(policy, roster, env, author).unwrap_or_default();
let mut counted: Vec<String> = Vec::new();
let mut ignored = Vec::new();
for a in approvers {
if eligible.contains(a) && !counted.contains(a) {
counted.push(a.clone());
} else {
ignored.push(a.clone());
}
}
// `others` needs to know who the author is (core 0.18.1): an empty author, or one no member is, would let the
// author approve their own release under a name the rule cannot see.
let unknown_author = rule.others && roster.len() >= 2 && !roster.iter().any(|m| m.is(author));
let verdict = if rule.approvals == 0 {
Verdict::Allowed(KeyRole::Test)
} else if unknown_author {
Verdict::Unsatisfiable("the release's author is not a member the team knows, so the rule cannot exclude them")
} else if counted.len() >= rule.approvals as usize {
Verdict::Allowed(KeyRole::Release)
} else if eligible.len() < rule.approvals as usize {
Verdict::Unsatisfiable(if rule.others && roster.len() >= 2 && eligible.is_empty() {
"only the author may approve, and the rule needs someone else"
} else {
"the rule needs more approvals than there are members who may give them"
})
} else {
Verdict::Need(rule.approvals - counted.len() as u8)
};
Evaluation { verdict, eligible, counted, ignored }
}
/// Why `member` may not approve this request, or `Ok`.
pub fn may_approve(
policy: &Policy,
roster: &[RosterMember],
env: &str,
author: &str,
member: &str,
) -> Result<(), TeamError> {
let rule = policy.rule(env).ok_or(TeamError::UnknownEnv)?;
let Some(me) = roster.iter().find(|m| m.id == member) else {
return Err(TeamError::NotAMember);
};
if !rule.approvers.is_empty() && !rule.approvers.contains(&me.id) {
return Err(TeamError::NotEligible("not on this environment's approver list"));
}
if rule.others && roster.len() >= 2 && me.is(author) {
return Err(TeamError::NotEligible("the release's author may not approve it here"));
}
if rule.approvals > 0 && rule.others && roster.len() >= 2 && !roster.iter().any(|m| m.is(author)) {
return Err(TeamError::NotEligible("the release's author is not a member the team knows"));
}
Ok(())
}
+227
View File
@@ -0,0 +1,227 @@
//! The policy proof (docs/TEAM.md, "The policy proof"): signed by the team identity, it says which request was
//! signed under which policy, with whose approvals, by whom, and over which envelope. Anyone who pinned the team
//! identity checks it with [`verify_proof`], which accepts only what the signing Custos itself would have signed.
use serde::{Deserialize, Serialize};
use crate::member::{TeamIdentity, verify_policy_sig, verify_proof_sig};
use crate::policy::{KeyRole, Policy, RosterMember, evaluate};
use crate::request::SignRequest;
use crate::statement::{Statement, verified_members};
use crate::{TeamError, b64, canon, hex, sha256, unb64, unhex};
/// The proof as it travels: its canonical text and the team identity's signature over it (base64).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Proof {
pub text: String,
pub sig: String,
}
/// A roster member as a proof lists them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RosterJson {
id: String,
name: String,
handles: Vec<String>,
ed25519: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BodyJson {
v: u32,
team: String,
request: String,
env: String,
author: String,
policy: String,
policy_sig: String,
roster: Vec<RosterJson>,
approvals: Vec<Statement>,
signer: String,
role: KeyRole,
signature: String,
at: u64,
}
/// What a proof says, as the team's Custos builds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProofBody {
pub team: String,
/// The request hash (hex).
pub request: String,
pub env: String,
pub author: String,
pub policy: String,
pub policy_sig: [u8; 64],
pub roster: Vec<RosterMember>,
pub approvals: Vec<Statement>,
pub signer: String,
pub role: KeyRole,
/// SHA-256 (hex) of the envelope that was returned.
pub signature: String,
pub at: u64,
}
impl ProofBody {
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(1024);
o.push_str("{\"v\":1,\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"request\":");
canon::string(&mut o, &self.request);
o.push_str(",\"env\":");
canon::string(&mut o, &self.env);
o.push_str(",\"author\":");
canon::string(&mut o, &self.author);
o.push_str(",\"policy\":");
canon::string(&mut o, &self.policy);
o.push_str(",\"policy_sig\":");
canon::string(&mut o, &b64(&self.policy_sig));
o.push_str(",\"roster\":[");
for (i, m) in self.roster.iter().enumerate() {
if i > 0 {
o.push(',');
}
o.push_str("{\"id\":");
canon::string(&mut o, &m.id);
o.push_str(",\"name\":");
canon::string(&mut o, &m.name);
o.push_str(",\"handles\":");
canon::strings(&mut o, &m.handles);
o.push_str(",\"ed25519\":");
canon::string(&mut o, &hex(&m.ed25519));
o.push('}');
}
o.push_str("],\"approvals\":[");
for (i, s) in self.approvals.iter().enumerate() {
if i > 0 {
o.push(',');
}
o.push_str("{\"member\":");
canon::string(&mut o, &s.member);
o.push_str(",\"code\":");
canon::string(&mut o, &s.code);
o.push_str(",\"at\":");
o.push_str(&s.at.to_string());
o.push_str(",\"sig\":");
canon::string(&mut o, &s.sig);
o.push('}');
}
o.push_str("],\"signer\":");
canon::string(&mut o, &self.signer);
o.push_str(",\"role\":");
canon::string(&mut o, self.role.word());
o.push_str(",\"signature\":");
canon::string(&mut o, &self.signature);
o.push_str(",\"at\":");
o.push_str(&self.at.to_string());
o.push('}');
o
}
/// Signed by the team identity.
pub fn sign(&self, identity: &TeamIdentity) -> Proof {
let text = self.canonical();
let sig = identity.sign_proof(&text);
Proof { text, sig: b64(&sig) }
}
pub fn parse(text: &str) -> Result<ProofBody, TeamError> {
if text.len() > 64 * 1024 {
return Err(TeamError::NotCanonical("a proof is at most 64 KiB"));
}
let j: BodyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a proof"))?;
if j.v != 1 {
return Err(TeamError::NotCanonical("v is not 1"));
}
let mut roster = Vec::new();
for m in j.roster {
let ed25519 = unhex::<32>(&m.ed25519).ok_or(TeamError::Invalid("a roster key is not 64 hex"))?;
roster.push(RosterMember { id: m.id, name: m.name, handles: m.handles, ed25519 });
}
let body = ProofBody {
team: j.team,
request: j.request,
env: j.env,
author: j.author,
policy: j.policy,
policy_sig: unb64(&j.policy_sig)
.and_then(|s| s.try_into().ok())
.ok_or(TeamError::Invalid("policy_sig is not base64 of 64 bytes"))?,
roster,
approvals: j.approvals,
signer: j.signer,
role: j.role,
signature: j.signature,
at: j.at,
};
if body.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
Ok(body)
}
}
/// What a proof established.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verified {
pub role: KeyRole,
pub env: String,
pub signer: String,
/// The approvals that counted under the policy.
pub approvers: Vec<String>,
pub policy_rev: u32,
}
/// Checks a proof against the pinned team identity, the request it was made for and the envelope that came back
/// with it: both signatures, every approval (signature, roster, the request's own match code), the request and
/// envelope hashes, and the policy evaluated again. The clock is not consulted: a proof stays checkable after its
/// request expired.
pub fn verify_proof(
proof: &Proof,
identity: &[u8; 32],
request_text: &str,
envelope: &[u8],
) -> Result<Verified, TeamError> {
let sig: [u8; 64] = unb64(&proof.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?;
if !verify_proof_sig(identity, &proof.text, &sig) {
return Err(TeamError::BadSignature);
}
let body = ProofBody::parse(&proof.text)?;
let req = SignRequest::parse(request_text)?;
if body.request != req.hash_hex() {
return Err(TeamError::Invalid("the proof is for another request"));
}
if body.team != req.team || body.env != req.env || body.author != req.author {
return Err(TeamError::Invalid("the proof does not match the request's team, env or author"));
}
if body.signature != hex(&sha256(envelope)) {
return Err(TeamError::Invalid("the proof is for another signature"));
}
if !verify_policy_sig(identity, &body.policy, &body.policy_sig) {
return Err(TeamError::BadSignature);
}
let policy = Policy::parse(&body.policy)?;
if policy.team != body.team {
return Err(TeamError::WrongTeam);
}
if !body.roster.iter().any(|m| m.id == body.signer) {
return Err(TeamError::NotAMember);
}
for s in &body.approvals {
s.verify(&req, &body.roster)?;
}
let approvers = verified_members(&body.approvals, &req, &body.roster);
let eval = evaluate(&policy, &body.roster, &req.env, &req.author, &approvers);
let role = eval.clone().into_result()?;
if role != body.role {
return Err(TeamError::Invalid("the proof's key role is not what the policy gives"));
}
if role == KeyRole::Release && !eval.counted.contains(&body.signer) {
return Err(TeamError::Invalid("the signer's own approval is not among those that counted"));
}
Ok(Verified { role, env: body.env, signer: body.signer, approvers: eval.counted, policy_rev: policy.rev })
}
+50
View File
@@ -0,0 +1,50 @@
//! What goes back to Fabrica, sealed to the request's `pub` (docs/TEAM.md, "The reply").
use serde::{Deserialize, Serialize};
use crate::proof::Proof;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReplyKey {
pub id: String,
/// `minisign.pub` text, `cosign.pub` PEM, or a certificate PEM.
pub public: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReplySigner {
pub member: String,
pub name: String,
}
/// `sign.reply` v1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignReply {
pub v: u32,
pub op: String,
/// The request hash (hex).
pub request: String,
pub format: String,
/// The envelope (docs/TEAM.md, "Signature envelopes").
pub signature: String,
/// cosign only: the payload that was signed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload: Option<String>,
pub key: ReplyKey,
pub signer: ReplySigner,
pub proof: Proof,
/// The deployment ticket (core 0.18.1): 32 random bytes, base64, for the `mac` of this deployment's
/// `target.request`s. Secret: it travels only inside the sealed reply; never log it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ticket: Option<String>,
}
impl SignReply {
/// The bytes the proof's `signature` hashes: the envelope as text.
pub fn envelope(&self) -> &[u8] {
self.signature.as_bytes()
}
}
+384
View File
@@ -0,0 +1,384 @@
//! The canonical `sign.request` and `target.request` (docs/TEAM.md, "The signing request"). Parsed, written again
//! in canonical form and compared byte for byte: any other spelling is refused, not normalised.
use serde::Deserialize;
use crate::{MAX_AHEAD_SECS, TeamError, b64, canon, hex, id_ok, sha256, unb64};
/// The largest request text read.
pub const MAX_REQUEST: usize = 4 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Minisign,
TauriUpdater,
Apk,
Cosign,
Authenticode,
}
impl Format {
pub fn word(self) -> &'static str {
match self {
Format::Minisign => "minisign",
Format::TauriUpdater => "tauri-updater",
Format::Apk => "apk",
Format::Cosign => "cosign",
Format::Authenticode => "authenticode",
}
}
pub fn from_word(w: &str) -> Option<Format> {
Some(match w {
"minisign" => Format::Minisign,
"tauri-updater" => Format::TauriUpdater,
"apk" => Format::Apk,
"cosign" => Format::Cosign,
"authenticode" => Format::Authenticode,
_ => return None,
})
}
/// Whether `digest` has this format's length (docs/TEAM.md, `artifact_digest`).
pub fn digest_ok(self, digest: &[u8]) -> bool {
match self {
Format::Minisign | Format::TauriUpdater => digest.len() == 64,
Format::Apk => !digest.is_empty() && digest.len() % 64 == 0 && digest.len() <= 64 * 4,
Format::Cosign | Format::Authenticode => digest.len() == 32,
}
}
}
/// What the build claims about the file; shown on the card.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Artifact {
pub name: String,
pub size: u64,
pub sha256: String,
}
/// A checked `sign.request`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignRequest {
pub team: String,
pub id: String,
pub project: String,
pub release: String,
pub env: String,
pub author: String,
pub format: Format,
pub artifact: Artifact,
pub artifact_digest: Vec<u8>,
pub image: String,
pub public: [u8; 32],
pub expires: u64,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SignJson {
v: u32,
op: String,
team: String,
id: String,
project: String,
release: String,
env: String,
author: String,
format: String,
artifact: Artifact,
artifact_digest: String,
image: String,
#[serde(rename = "pub")]
public: String,
expires: u64,
}
fn lower_hex(s: &str, len: usize) -> bool {
s.len() == len && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
pub(crate) fn pub_key(s: &str) -> Result<[u8; 32], TeamError> {
let k: [u8; 32] =
unb64(s).and_then(|v| v.try_into().ok()).ok_or(TeamError::Invalid("pub is not base64 of 32 bytes"))?;
if k == [0; 32] {
return Err(TeamError::Invalid("pub is all zeros"));
}
Ok(k)
}
fn name_ok(name: &str) -> bool {
canon::text_ok(name, 200) && !name.contains(['/', '\\'])
}
impl SignRequest {
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(640);
o.push_str("{\"v\":1,\"op\":\"sign.request\",\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"id\":");
canon::string(&mut o, &self.id);
o.push_str(",\"project\":");
canon::string(&mut o, &self.project);
o.push_str(",\"release\":");
canon::string(&mut o, &self.release);
o.push_str(",\"env\":");
canon::string(&mut o, &self.env);
o.push_str(",\"author\":");
canon::string(&mut o, &self.author);
o.push_str(",\"format\":");
canon::string(&mut o, self.format.word());
o.push_str(",\"artifact\":{\"name\":");
canon::string(&mut o, &self.artifact.name);
o.push_str(",\"size\":");
o.push_str(&self.artifact.size.to_string());
o.push_str(",\"sha256\":");
canon::string(&mut o, &self.artifact.sha256);
o.push_str("},\"artifact_digest\":");
canon::string(&mut o, &b64(&self.artifact_digest));
o.push_str(",\"image\":");
canon::string(&mut o, &self.image);
o.push_str(",\"pub\":");
canon::string(&mut o, &b64(&self.public));
o.push_str(",\"expires\":");
o.push_str(&self.expires.to_string());
o.push('}');
o
}
/// Every field as docs/TEAM.md allows it, without the clock.
pub fn check_fields(&self) -> Result<(), TeamError> {
let bad = |w| Err(TeamError::Invalid(w));
if !id_ok(&self.team) || !id_ok(&self.id) {
return bad("team and id are 32 lower-case hex digits");
}
if !canon::ascii_ok(&self.project, 1, 128, b"._/-") {
return bad("project is 1 to 128 of [A-Za-z0-9._/-]");
}
if !canon::ascii_ok(&self.release, 1, 64, b"._+-") {
return bad("release is 1 to 64 of [A-Za-z0-9._+-]");
}
if !canon::env_ok(&self.env) {
return bad("env is [a-z][a-z0-9-]{0,31}");
}
if !canon::ascii_ok(&self.author, 0, 64, b"._@-") {
return bad("author is 0 to 64 of [A-Za-z0-9._@-]");
}
if !name_ok(&self.artifact.name) {
return bad("the artifact's name is 1 to 200 characters, no path, no control characters");
}
if !lower_hex(&self.artifact.sha256, 64) {
return bad("the artifact's sha256 is 64 lower-case hex digits");
}
if !self.format.digest_ok(&self.artifact_digest) {
return bad("artifact_digest has the wrong length for its format");
}
match self.format {
Format::Cosign => {
custos_sign::image_ok(&self.image).map_err(|_| TeamError::Invalid("image is not a repository"))?
}
_ if !self.image.is_empty() => return bad("image is for cosign only"),
_ => {}
}
Ok(())
}
/// Reads a canonical request, without the clock: for showing what an expired request said. Never enough to sign.
pub fn parse(text: &str) -> Result<SignRequest, TeamError> {
if text.len() > MAX_REQUEST {
return Err(TeamError::NotCanonical("a request is at most 4 KiB"));
}
let j: SignJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a sign.request"))?;
if j.v != 1 || j.op != "sign.request" {
return Err(TeamError::NotCanonical("not a sign.request v1"));
}
let format = Format::from_word(&j.format).ok_or(TeamError::Invalid("an unknown format"))?;
let digest = unb64(&j.artifact_digest).ok_or(TeamError::Invalid("artifact_digest is not base64"))?;
let r = SignRequest {
team: j.team,
id: j.id,
project: j.project,
release: j.release,
env: j.env,
author: j.author,
format,
artifact: j.artifact,
artifact_digest: digest,
image: j.image,
public: pub_key(&j.public)?,
expires: j.expires,
};
r.check_fields()?;
if r.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
Ok(r)
}
/// [`SignRequest::parse`] and the clock: not expired at `now` (Unix seconds), at most 25 hours ahead.
pub fn check(text: &str, now: u64) -> Result<SignRequest, TeamError> {
let r = SignRequest::parse(text)?;
if r.expires <= now {
return Err(TeamError::Expired);
}
if r.expires > now.saturating_add(MAX_AHEAD_SECS) {
return Err(TeamError::Invalid("it expires more than 25 hours from now"));
}
Ok(r)
}
/// SHA-256 of the canonical text.
pub fn hash(&self) -> [u8; 32] {
sha256(self.canonical().as_bytes())
}
pub fn hash_hex(&self) -> String {
hex(&self.hash())
}
/// The match code Fabrica shows and every card shows: `match_code(pub)`.
pub fn match_code(&self) -> String {
custos_seal::match_code(&self.public)
}
/// The context the reply is sealed under.
pub fn reply_context(&self) -> Vec<u8> {
format!("team-sign:{}", self.id).into_bytes()
}
}
/// Fabrica asks for a target credential for one deployment (docs/TEAM.md, "Target credentials").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetRequest {
pub team: String,
pub id: String,
pub target: String,
/// The hash of the `sign.request` whose signature this deployment deploys.
pub deployment: String,
pub public: [u8; 32],
pub expires: u64,
/// HMAC-SHA256 with the deployment's ticket (core 0.18.1): only the Fabrica that opened the signing reply has the
/// ticket, so only it can ask for the deployment's credentials.
pub mac: [u8; 32],
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TargetJson {
v: u32,
op: String,
team: String,
id: String,
target: String,
deployment: String,
#[serde(rename = "pub")]
public: String,
expires: u64,
mac: String,
}
/// The domain of a target request's MAC.
pub const TARGET_MAC_DOMAIN: &[u8] = b"custos team target v1\0";
impl TargetRequest {
/// The text the MAC covers: the canonical request without `mac`.
fn unsigned(&self) -> String {
let mut o = String::with_capacity(256);
o.push_str("{\"v\":1,\"op\":\"target.request\",\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"id\":");
canon::string(&mut o, &self.id);
o.push_str(",\"target\":");
canon::string(&mut o, &self.target);
o.push_str(",\"deployment\":");
canon::string(&mut o, &self.deployment);
o.push_str(",\"pub\":");
canon::string(&mut o, &b64(&self.public));
o.push_str(",\"expires\":");
o.push_str(&self.expires.to_string());
o
}
fn mac_over(&self, ticket: &[u8; 32]) -> hmac::Hmac<sha2::Sha256> {
use hmac::KeyInit;
let mut m = <hmac::Hmac<sha2::Sha256> as KeyInit>::new_from_slice(ticket).expect("any key length");
hmac::Mac::update(&mut m, TARGET_MAC_DOMAIN);
hmac::Mac::update(&mut m, self.unsigned().as_bytes());
m
}
/// Sets `mac` with the deployment's ticket (from the sealed `sign.reply`).
pub fn sign_with(mut self, ticket: &[u8; 32]) -> TargetRequest {
self.mac = hmac::Mac::finalize(self.mac_over(ticket)).into_bytes().into();
self
}
/// Whether `mac` was made with this ticket (constant time).
pub fn mac_ok(&self, ticket: &[u8; 32]) -> bool {
hmac::Mac::verify_slice(self.mac_over(ticket), &self.mac).is_ok()
}
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(256);
o.push_str("{\"v\":1,\"op\":\"target.request\",\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"id\":");
canon::string(&mut o, &self.id);
o.push_str(",\"target\":");
canon::string(&mut o, &self.target);
o.push_str(",\"deployment\":");
canon::string(&mut o, &self.deployment);
o.push_str(",\"pub\":");
canon::string(&mut o, &b64(&self.public));
o.push_str(",\"expires\":");
o.push_str(&self.expires.to_string());
o.push_str(",\"mac\":");
canon::string(&mut o, &b64(&self.mac));
o.push('}');
o
}
/// Reads and checks a canonical target request at `now`; it lives at most 25 hours.
pub fn check(text: &str, now: u64) -> Result<TargetRequest, TeamError> {
if text.len() > MAX_REQUEST {
return Err(TeamError::NotCanonical("a request is at most 4 KiB"));
}
let j: TargetJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a target.request"))?;
if j.v != 1 || j.op != "target.request" {
return Err(TeamError::NotCanonical("not a target.request v1"));
}
let r = TargetRequest {
team: j.team,
id: j.id,
target: j.target,
deployment: j.deployment,
public: pub_key(&j.public)?,
expires: j.expires,
mac: unb64(&j.mac)
.and_then(|m| m.try_into().ok())
.ok_or(TeamError::Invalid("mac is not base64 of 32 bytes"))?,
};
if !id_ok(&r.team) || !id_ok(&r.id) || !lower_hex(&r.target, 16) || !lower_hex(&r.deployment, 64) {
return Err(TeamError::Invalid("team, id, target and deployment are hex ids"));
}
if r.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
if r.expires <= now {
return Err(TeamError::Expired);
}
if r.expires > now.saturating_add(MAX_AHEAD_SECS) {
return Err(TeamError::Invalid("it expires more than 25 hours from now"));
}
Ok(r)
}
pub fn match_code(&self) -> String {
custos_seal::match_code(&self.public)
}
pub fn reply_context(&self) -> Vec<u8> {
format!("team-target:{}", self.id).into_bytes()
}
}
+75
View File
@@ -0,0 +1,75 @@
//! A member's approval of one request (docs/TEAM.md, "Approval statements").
use serde::{Deserialize, Serialize};
use crate::member::MemberKey;
use crate::policy::RosterMember;
use crate::request::SignRequest;
use crate::{TeamError, b64, unb64, unhex};
pub const APPROVAL_DOMAIN: &[u8] = b"custos team approval v1\0";
/// `{"member", "code", "at", "sig"}`: who approved which request (by its hash, outside), with which code, when.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Statement {
pub member: String,
pub code: String,
pub at: u64,
/// Base64 of the 64-byte Ed25519 signature.
pub sig: String,
}
/// What a statement signs.
pub fn message(request_hash: &[u8; 32], code: &str, member: &[u8; 16], at: u64) -> Vec<u8> {
let mut m = Vec::with_capacity(APPROVAL_DOMAIN.len() + 32 + 6 + 16 + 8);
m.extend_from_slice(APPROVAL_DOMAIN);
m.extend_from_slice(request_hash);
m.extend_from_slice(code.as_bytes());
m.extend_from_slice(member);
m.extend_from_slice(&at.to_be_bytes());
m
}
fn code_ok(code: &str) -> bool {
code.len() == 6 && code.bytes().all(|c| c.is_ascii_digit())
}
/// A member approves `req`. `shown_code` is the code the card showed: when it is not the request's own match code,
/// the request changed after the card was drawn, or it is someone else's, and nothing is signed (`WrongMatch`).
pub fn approve(key: &MemberKey, req: &SignRequest, shown_code: &str, now: u64) -> Result<Statement, TeamError> {
if shown_code != req.match_code() {
return Err(TeamError::WrongMatch);
}
let id = key.public().id_bytes();
let sig = key.sign(&message(&req.hash(), shown_code, &id, now));
Ok(Statement { member: key.id(), code: shown_code.into(), at: now, sig: b64(&sig) })
}
impl Statement {
/// Checks this statement for `req` against the roster: the member is on it, the code is the request's own,
/// the signature is the member's.
pub fn verify(&self, req: &SignRequest, roster: &[RosterMember]) -> Result<(), TeamError> {
if !code_ok(&self.code) || self.code != req.match_code() {
return Err(TeamError::WrongMatch);
}
let m = roster.iter().find(|m| m.id == self.member).ok_or(TeamError::NotAMember)?;
let id: [u8; 16] = unhex(&self.member).ok_or(TeamError::NotAMember)?;
let sig: [u8; 64] = unb64(&self.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?;
if !crate::member::verify(&m.ed25519, &message(&req.hash(), &self.code, &id, self.at), &sig) {
return Err(TeamError::BadSignature);
}
Ok(())
}
}
/// The member ids of the statements that verify for `req`, each once, in order; the others are dropped.
pub fn verified_members(statements: &[Statement], req: &SignRequest, roster: &[RosterMember]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for s in statements {
if s.verify(req, roster).is_ok() && !out.contains(&s.member) {
out.push(s.member.clone());
}
}
out
}
+66
View File
@@ -0,0 +1,66 @@
//! Target credentials (docs/TEAM.md, "Target credentials"): what they are, and the plaintext a released one is
//! sealed as.
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TargetKind {
/// An OpenSSH private key.
SshKey,
/// A WinRM user and password.
Winrm,
/// An OpenSSH user and password.
Openssh,
/// A Docker registry token.
Registry,
/// A kubeconfig.
Kubeconfig,
}
impl TargetKind {
pub fn word(self) -> &'static str {
match self {
TargetKind::SshKey => "ssh-key",
TargetKind::Winrm => "winrm",
TargetKind::Openssh => "openssh",
TargetKind::Registry => "registry",
TargetKind::Kubeconfig => "kubeconfig",
}
}
}
/// The largest target credential.
pub const MAX_SECRET: usize = 64 * 1024;
/// A released credential, as sealed to the Fabrica server's one-time key (`team-target:<request id>`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetRelease {
pub v: u32,
pub op: String,
pub team: String,
pub target: String,
pub kind: TargetKind,
pub name: String,
pub host: String,
pub user: String,
pub secret: String,
/// The deployment's request hash.
pub deployment: String,
pub project: String,
pub env: String,
}
impl fmt::Debug for TargetRelease {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TargetRelease")
.field("target", &self.target)
.field("kind", &self.kind)
.field("deployment", &self.deployment)
.field("secret", &"[redacted]")
.finish_non_exhaustive()
}
}
+213
View File
@@ -0,0 +1,213 @@
//! Mandatory: policy evaluation, every combination of team size, environment and the author/approver rule
//! (docs/TEAM.md, "Evaluation").
use custos_team::policy::{EnvRule, may_approve};
use custos_team::*;
const TEAM: &str = "0123456789abcdef0123456789abcdef";
fn roster(n: usize) -> Vec<RosterMember> {
(0..n)
.map(|i| RosterMember {
id: format!("{i:032x}"),
name: format!("Member {i}"),
// Member 0 is the author; Fabrica names them by handle, in another case.
handles: if i == 0 { vec!["MNovak".into()] } else { vec![format!("dev{i}")] },
ed25519: [i as u8; 32],
})
.collect()
}
fn id(i: usize) -> String {
format!("{i:032x}")
}
const OUTSIDER: &str = "ffffffffffffffffffffffffffffffff";
/// The approver sets every size is tried with.
fn approver_sets(n: usize) -> Vec<(&'static str, Vec<String>)> {
let mut v = vec![("nobody", vec![]), ("the author", vec![id(0)]), ("an outsider", vec![OUTSIDER.into()])];
if n >= 2 {
v.push(("one other", vec![id(1)]));
v.push(("the author and one other", vec![id(0), id(1)]));
v.push(("one other twice", vec![id(1), id(1)]));
}
if n >= 3 {
v.push(("two others", vec![id(1), id(2)]));
}
v
}
/// The rule in the doc's own words, for the default policy.
fn expected(n: usize, env: &str, author_is_member: bool, set: &[String]) -> Verdict {
let members: Vec<&String> = set.iter().filter(|a| a.as_str() != OUTSIDER).collect();
let mut distinct: Vec<&String> = Vec::new();
for m in members {
if !distinct.contains(&m) {
distinct.push(m);
}
}
match env {
"preview" => Verdict::Allowed(KeyRole::Test),
"staging" => {
if distinct.is_empty() {
Verdict::Need(1)
} else {
Verdict::Allowed(KeyRole::Release)
}
}
"production" => {
// "1 by someone other than the release author when the team has 2+ members"
// ... and the rule must know the author: someone no member is (or nobody named) cannot be excluded.
if n >= 2 && !author_is_member {
return Verdict::Unsatisfiable(
"the release's author is not a member the team knows, so the rule cannot exclude them",
);
}
let author_excluded = n >= 2 && author_is_member;
let counted = distinct.iter().filter(|m| !(author_excluded && m.as_str() == id(0))).count();
if counted >= 1 { Verdict::Allowed(KeyRole::Release) } else { Verdict::Need(1) }
}
_ => Verdict::UnknownEnv,
}
}
#[test]
fn every_size_environment_author_and_approver_under_the_default_policy() {
let policy = Policy::default_for(TEAM);
let mut cases = 0;
for n in [1usize, 2, 3, 4, 10] {
let r = roster(n);
for env in ["preview", "staging", "production", "qa"] {
// The author by handle (any case), by member id, someone outside the team, or nobody named.
for (author, is_member) in
[("mnovak", true), ("MNOVAK", true), (id(0).as_str(), true), ("stranger", false), ("", false)]
{
for (what, set) in approver_sets(n) {
let got = evaluate(&policy, &r, env, author, &set);
let want = expected(n, env, is_member, &set);
assert_eq!(got.verdict, want, "size {n}, {env}, author {author:?}, approved by {what}");
cases += 1;
}
}
}
}
assert!(cases > 400, "{cases}");
}
#[test]
fn a_team_of_one_approves_its_own_production_release_and_a_second_member_ends_that() {
let p = Policy::default_for(TEAM);
let solo = roster(1);
assert_eq!(evaluate(&p, &solo, "production", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release));
assert!(may_approve(&p, &solo, "production", "mnovak", &id(0)).is_ok());
let two = roster(2);
let e = evaluate(&p, &two, "production", "mnovak", &[id(0)]);
assert_eq!(e.verdict, Verdict::Need(1));
assert_eq!(e.ignored, vec![id(0)]);
assert_eq!(e.eligible, vec![id(1)]);
assert_eq!(
may_approve(&p, &two, "production", "mnovak", &id(0)),
Err(TeamError::NotEligible("the release's author may not approve it here"))
);
assert!(may_approve(&p, &two, "production", "mnovak", &id(1)).is_ok());
assert_eq!(may_approve(&p, &two, "production", "mnovak", OUTSIDER), Err(TeamError::NotAMember));
assert_eq!(may_approve(&p, &two, "qa", "mnovak", &id(1)), Err(TeamError::UnknownEnv));
}
#[test]
fn several_approvals_others_and_approver_lists() {
let mut p = Policy::default_for(TEAM);
p.set_rule(EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] }).unwrap();
assert_eq!(p.rev, 2);
// Two members, the author excluded: one left for two approvals, which can never be met.
assert!(matches!(evaluate(&p, &roster(2), "production", "mnovak", &[]).verdict, Verdict::Unsatisfiable(_)));
// A team of one: `others` does not apply, but two approvals from one person cannot be.
assert!(matches!(evaluate(&p, &roster(1), "production", "mnovak", &[id(0)]).verdict, Verdict::Unsatisfiable(_)));
let three = roster(3);
assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(1)]).verdict, Verdict::Need(1));
assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(0), id(1)]).verdict, Verdict::Need(1));
assert_eq!(
evaluate(&p, &three, "production", "mnovak", &[id(1), id(2)]).verdict,
Verdict::Allowed(KeyRole::Release)
);
// Someone no member is, or nobody named: the rule cannot exclude the author, so it refuses (core 0.18.1).
for author in ["stranger", ""] {
assert!(matches!(
evaluate(&p, &three, "production", author, &[id(0), id(1)]).verdict,
Verdict::Unsatisfiable(_)
));
assert!(matches!(may_approve(&p, &three, "production", author, &id(1)), Err(TeamError::NotEligible(_))));
}
// Only member 1 may approve staging.
p.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: false, approvers: vec![id(1)] }).unwrap();
let four = roster(4);
assert_eq!(evaluate(&p, &four, "staging", "", &[id(2)]).verdict, Verdict::Need(1));
assert_eq!(evaluate(&p, &four, "staging", "", &[id(2), id(1)]).verdict, Verdict::Allowed(KeyRole::Release));
assert!(matches!(may_approve(&p, &four, "staging", "", &id(2)), Err(TeamError::NotEligible(_))));
// The only listed approver is the author, and the rule wants someone else.
p.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![id(0)] }).unwrap();
assert!(matches!(evaluate(&p, &four, "staging", "mnovak", &[id(0)]).verdict, Verdict::Unsatisfiable(_)));
// ... but in a team of one the author is the only member and approves.
let solo_policy = {
let mut q = Policy::default_for(TEAM);
q.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![id(0)] }).unwrap();
q
};
assert_eq!(
evaluate(&solo_policy, &roster(1), "staging", "mnovak", &[id(0)]).verdict,
Verdict::Allowed(KeyRole::Release)
);
// A preview made strict.
p.set_rule(EnvRule { env: "preview".into(), approvals: 1, others: false, approvers: vec![] }).unwrap();
assert_eq!(evaluate(&p, &four, "preview", "mnovak", &[]).verdict, Verdict::Need(1));
assert_eq!(evaluate(&p, &four, "preview", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release));
}
#[test]
fn the_policy_text_is_canonical_and_its_rules_are_checked() {
let p = Policy::default_for(TEAM);
let text = p.canonical();
assert_eq!(
text,
"{\"v\":1,\"team\":\"0123456789abcdef0123456789abcdef\",\"rev\":1,\"envs\":[{\"env\":\"preview\",\"approvals\":0,\"others\":false,\"approvers\":[]},{\"env\":\"staging\",\"approvals\":1,\"others\":false,\"approvers\":[]},{\"env\":\"production\",\"approvals\":1,\"others\":true,\"approvers\":[]}]}"
);
assert_eq!(Policy::parse(&text).unwrap(), p);
for bad in [
text.replace("{\"v\":1,", "{ \"v\":1,"),
text.replace("\"rev\":1", "\"rev\":0"),
text.replace("\"approvals\":0", "\"approvals\":11"),
text.replace("\"staging\"", "\"preview\""),
text.replace("\"staging\"", "\"Staging\""),
text.replace("\"approvers\":[]}]", "\"approvers\":[\"nope\"]}]"),
text.replace("{\"v\":1,", "{\"v\":2,"),
text.clone() + "\n",
text.replace(
"\"others\":false,\"approvers\":[]},{\"env\":\"staging\"",
"\"others\":false,\"approvers\":[],\"x\":1},{\"env\":\"staging\"",
),
] {
assert!(Policy::parse(&bad).is_err(), "{bad}");
}
let mut q = p.clone();
assert!(q.set_rule(EnvRule { env: "prod uction".into(), approvals: 1, others: true, approvers: vec![] }).is_err());
assert_eq!(q, p, "a refused change leaves the policy as it was");
}
#[test]
fn the_identity_signs_the_policy_and_nothing_else_passes_for_it() {
let identity = TeamIdentity::generate();
let text = Policy::default_for(TEAM).canonical();
let sig = identity.sign_policy(&text);
assert!(custos_team::member::verify_policy_sig(&identity.public(), &text, &sig));
assert!(!custos_team::member::verify_policy_sig(
&identity.public(),
&text.replace("\"approvals\":1,\"others\":true", "\"approvals\":0,\"others\":true"),
&sig
));
// A proof signature is not a policy signature.
let proof_sig = identity.sign_proof(&text);
assert!(!custos_team::member::verify_policy_sig(&identity.public(), &text, &proof_sig));
assert_eq!(format!("{identity:?}"), "[redacted]");
}
+190
View File
@@ -0,0 +1,190 @@
//! The canonical sign.request, match codes, approval statements and the policy proof (docs/TEAM.md).
use custos_team::policy::Policy;
use custos_team::proof::ProofBody;
use custos_team::statement::{approve, verified_members};
use custos_team::*;
const NOW: u64 = 1_794_000_000;
pub fn request(team: &str, env: &str, author: &str, public: [u8; 32]) -> SignRequest {
SignRequest {
team: team.into(),
id: "aa".repeat(16),
project: "mnovak/Arca".into(),
release: "0.7.0".into(),
env: env.into(),
author: author.into(),
format: Format::Minisign,
artifact: custos_team::request::Artifact {
name: "Arca_0.7.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4".repeat(32),
},
artifact_digest: vec![9; 64],
image: String::new(),
public,
expires: NOW + 3600,
}
}
#[test]
fn a_request_is_read_only_in_canonical_form() {
let fabrica = custos_seal::Recipient::generate();
let r = request(&"01".repeat(16), "production", "mnovak", fabrica.public());
let text = r.canonical();
assert!(text.starts_with("{\"v\":1,\"op\":\"sign.request\",\"team\":\"0101"));
assert_eq!(SignRequest::check(&text, NOW).unwrap(), r);
assert_eq!(r.match_code(), fabrica.match_code());
for bad in [
text.replace(",\"id\"", ", \"id\""),
text.replace("\"op\":\"sign.request\"", "\"op\":\"sign.reply\""),
text.replace("\"format\":\"minisign\"", "\"format\":\"gpg\""),
text.replace("mnovak/Arca", "mnovak/Arca\\u0041"),
text.replace("Arca_0.7.0_x64-setup.exe", "../Arca.exe"),
text.replace("\"env\":\"production\"", "\"env\":\"Production\""),
format!("{text}\n"),
text.replace("\"image\":\"\"", "\"image\":\"arca\""),
] {
assert!(SignRequest::check(&bad, NOW).is_err(), "{bad}");
}
assert_eq!(SignRequest::check(&text, r.expires), Err(TeamError::Expired));
let mut far = r.clone();
far.expires = NOW + 25 * 3600 + 1;
assert!(SignRequest::check(&far.canonical(), NOW).is_err());
// Digest lengths per format.
let mut apk = r.clone();
apk.format = Format::Apk;
apk.artifact_digest = vec![1; 128];
assert!(SignRequest::check(&apk.canonical(), NOW).is_ok());
apk.artifact_digest = vec![1; 64 * 5];
assert!(SignRequest::check(&apk.canonical(), NOW).is_err());
let mut cosign = r.clone();
cosign.format = Format::Cosign;
cosign.artifact_digest = vec![1; 32];
assert!(SignRequest::check(&cosign.canonical(), NOW).is_err(), "cosign needs an image");
cosign.image = "registry.example/team/arca".into();
assert!(SignRequest::check(&cosign.canonical(), NOW).is_ok());
}
fn roster_of(keys: &[&MemberKey]) -> Vec<RosterMember> {
keys.iter()
.enumerate()
.map(|(i, k)| RosterMember {
id: k.id(),
name: format!("M{i}"),
handles: if i == 0 { vec!["mnovak".into()] } else { vec![] },
ed25519: k.public().ed25519,
})
.collect()
}
#[test]
fn a_wrong_match_code_is_refused_and_never_counts() {
let (a, b) = (MemberKey::generate(), MemberKey::generate());
let roster = roster_of(&[&a, &b]);
let fabrica = custos_seal::Recipient::generate();
let req = request(&"01".repeat(16), "production", "mnovak", fabrica.public());
// B's card showed another code: B approves nothing.
let wrong = if req.match_code() == "000000" { "000001" } else { "000000" };
assert_eq!(approve(&b, &req, wrong, NOW), Err(TeamError::WrongMatch));
// A request whose pub was swapped after B's card was drawn: the code B saw is the old request's.
let shown = req.match_code();
let mut swapped = req.clone();
swapped.public = custos_seal::Recipient::generate().public();
assert_eq!(approve(&b, &swapped, &shown, NOW), Err(TeamError::WrongMatch));
// A statement made for one request does not count for the swapped one.
let s = approve(&b, &req, &shown, NOW).unwrap();
s.verify(&req, &roster).unwrap();
assert_eq!(s.verify(&swapped, &roster), Err(TeamError::WrongMatch));
assert!(verified_members(&[s.clone()], &swapped, &roster).is_empty());
// A forged code inside a statement fails its signature or its code.
let mut forged = s.clone();
forged.code = wrong.into();
assert_eq!(forged.verify(&req, &roster), Err(TeamError::WrongMatch));
let mut other_member = s.clone();
other_member.member = a.id();
assert_eq!(other_member.verify(&req, &roster), Err(TeamError::BadSignature));
// Not on the roster.
let c = MemberKey::generate();
let sc = approve(&c, &req, &shown, NOW).unwrap();
assert_eq!(sc.verify(&req, &roster), Err(TeamError::NotAMember));
assert_eq!(verified_members(&[s.clone(), s.clone(), sc], &req, &roster), vec![b.id()]);
}
#[test]
fn member_keys_seal_the_team_key_to_one_member_team_and_epoch() {
let (a, b) = (MemberKey::generate(), MemberKey::generate());
let team = "02".repeat(16);
let key = [7u8; 32];
let sealed = custos_team::member::seal_team_key(&key, &a.public(), &team, 3).unwrap();
assert_eq!(sealed.len(), custos_team::member::SEALED_KEY_LEN);
assert_eq!(*a.open_team_key(&sealed, &team, 3).unwrap(), key);
assert_eq!(a.open_team_key(&sealed, &team, 4), Err(TeamError::NotAMember));
assert_eq!(a.open_team_key(&sealed, &"03".repeat(16), 3), Err(TeamError::NotAMember));
assert_eq!(b.open_team_key(&sealed, &team, 3), Err(TeamError::NotAMember));
// The key round-trips through its secrets; ids and codes are stable.
let again = MemberKey::from_secrets(a.x25519_secret(), a.ed25519_secret()).unwrap();
assert_eq!(again.public(), a.public());
assert_eq!(a.public().join_code(), custos_seal::match_code(&a.public().x25519));
assert_eq!(a.id().len(), 32);
assert_ne!(a.id(), b.id());
assert_eq!(format!("{a:?}"), "[redacted]");
a.public().check().unwrap();
}
#[test]
fn a_proof_verifies_only_for_its_request_signature_policy_and_identity() {
let identity = TeamIdentity::generate();
let team = "04".repeat(16);
let (a, b) = (MemberKey::generate(), MemberKey::generate());
let roster = roster_of(&[&a, &b]);
let policy = Policy::default_for(&team);
let policy_text = policy.canonical();
let fabrica = custos_seal::Recipient::generate();
let req = request(&team, "production", "mnovak", fabrica.public());
let req_text = req.canonical();
let s = approve(&b, &req, &req.match_code(), NOW).unwrap();
let envelope = b"untrusted comment: ...".to_vec();
let body = |approvals: Vec<Statement>, signer: String, role: KeyRole| ProofBody {
team: team.clone(),
request: req.hash_hex(),
env: req.env.clone(),
author: req.author.clone(),
policy: policy_text.clone(),
policy_sig: identity.sign_policy(&policy_text),
roster: roster.clone(),
approvals,
signer,
role,
signature: custos_sign::sha256_hex(&envelope),
at: NOW,
};
let good = body(vec![s.clone()], b.id(), KeyRole::Release).sign(&identity);
assert_eq!(ProofBody::parse(&good.text).unwrap(), body(vec![s.clone()], b.id(), KeyRole::Release));
let v = verify_proof(&good, &identity.public(), &req_text, &envelope).unwrap();
assert_eq!((v.role, v.signer.as_str(), v.approvers.clone()), (KeyRole::Release, b.id().as_str(), vec![b.id()]));
// Another identity, another envelope, another request.
assert_eq!(
verify_proof(&good, &TeamIdentity::generate().public(), &req_text, &envelope),
Err(TeamError::BadSignature)
);
assert!(verify_proof(&good, &identity.public(), &req_text, b"another signature").is_err());
let mut other = req.clone();
other.release = "0.7.1".into();
assert!(verify_proof(&good, &identity.public(), &other.canonical(), &envelope).is_err());
// The author's own approval does not make a production proof.
let sa = approve(&a, &req, &req.match_code(), NOW).unwrap();
let selfish = body(vec![sa], a.id(), KeyRole::Release).sign(&identity);
assert_eq!(verify_proof(&selfish, &identity.public(), &req_text, &envelope), Err(TeamError::NeedMore(1)));
// A proof claiming the test role for production, or signed by someone who did not approve.
let wrong_role = body(vec![s.clone()], b.id(), KeyRole::Test).sign(&identity);
assert!(verify_proof(&wrong_role, &identity.public(), &req_text, &envelope).is_err());
let not_approver = body(vec![s.clone()], a.id(), KeyRole::Release).sign(&identity);
assert!(verify_proof(&not_approver, &identity.public(), &req_text, &envelope).is_err());
// An edited text breaks the identity's signature.
let mut edited = good.clone();
edited.text = edited.text.replace("\"production\"", "\"staging\"");
assert_eq!(verify_proof(&edited, &identity.public(), &req_text, &envelope), Err(TeamError::BadSignature));
}
+13
View File
@@ -16,6 +16,19 @@ serde_json.workspace = true
thiserror.workspace = true
hkdf.workspace = true
sha2.workspace = true
data-encoding.workspace = true
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
# Signing keys for releases (docs/SIGNING.md).
custos-sign = { path = "../custos-sign" }
# Team vaults (docs/TEAM.md, core 0.18.0).
custos-team = { path = "../custos-team" }
[dev-dependencies]
tempfile = "3"
custos-seal = { path = "../custos-seal" }
minisign-verify = "0.3"
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
x509-cert = "0.2.5"
+15
View File
@@ -66,3 +66,18 @@ pub fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new)
}
/// The Domi root secret from a 24-word mnemonic (docs/IDENTITY.md): HKDF-SHA256 over its BIP39 seed.
pub fn domi_root_secret(mnemonic: &bip39::Mnemonic) -> Zeroizing<[u8; KEY_LEN]> {
let seed = Zeroizing::new(mnemonic.to_seed_normalized(""));
hkdf(seed.as_ref(), b"tessera root v1", b"ed25519")
}
pub fn ed25519_public(secret: &[u8; KEY_LEN]) -> [u8; 32] {
ed25519_dalek::SigningKey::from_bytes(secret).verifying_key().to_bytes()
}
pub fn ed25519_sign(secret: &[u8; KEY_LEN], msg: &[u8]) -> [u8; 64] {
use ed25519_dalek::Signer;
ed25519_dalek::SigningKey::from_bytes(secret).sign(msg).to_bytes()
}
+124
View File
@@ -15,6 +15,15 @@ pub const SLOT_PASSWORD: u8 = 1;
pub const SLOT_FACTOR: u8 = 2;
pub const SLOT_PAIR: u8 = 3;
pub const SLOT_SINGLE: u8 = 4;
/// The recovery key's slot (core 0.17.0; docs/FACTORS.md, "The recovery key").
pub const SLOT_RECOVERY: u8 = 5;
pub const RECOVERY_ID_LEN: usize = 4;
/// A team vault's member slot (core 0.18.0; docs/TEAM.md): the team key sealed to one member.
pub const SLOT_MEMBER: u8 = 6;
/// team id (16) ‖ member id (16) ‖ epoch (4) ‖ sealed team key (108).
pub const MEMBER_SLOT_LEN: usize = 16 + 16 + 4 + 108;
/// A team has at most this many members.
pub const MAX_MEMBER_SLOTS: usize = 32;
const KDF_ARGON2ID: u8 = 1;
pub const SALT_LEN: usize = 32;
pub const ID_LEN: usize = 16;
@@ -244,6 +253,80 @@ impl SingleSlot {
}
}
/// The recovery slot (kind 5): the vault key, wrapped by the recovery key alone. At most one, never in a machine
/// store. `id` says which printed key it is and is not secret.
pub struct RecoverySlot {
pub id: [u8; RECOVERY_ID_LEN],
pub salt: [u8; SALT_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl RecoverySlot {
fn head(&self) -> Vec<u8> {
let mut h = Vec::with_capacity(RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN);
h.extend_from_slice(&self.id);
h.extend_from_slice(&self.salt);
h.extend_from_slice(&self.nonce);
h
}
pub fn aad(&self) -> Vec<u8> {
v2_aad(SLOT_RECOVERY, &self.head())
}
pub fn raw(&self) -> RawSlot {
let mut p = self.head();
p.extend_from_slice(&self.wrapped);
RawSlot { kind: SLOT_RECOVERY, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
const HEAD: usize = RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN;
if payload.len() != HEAD + WRAPPED_LEN {
return Err(Error::Malformed);
}
Ok(RecoverySlot {
id: payload[..RECOVERY_ID_LEN].try_into().unwrap(),
salt: payload[RECOVERY_ID_LEN..RECOVERY_ID_LEN + SALT_LEN].try_into().unwrap(),
nonce: payload[RECOVERY_ID_LEN + SALT_LEN..HEAD].try_into().unwrap(),
wrapped: payload[HEAD..].to_vec(),
})
}
}
/// A team vault's member slot (kind 6): the box carries its own binding (its context names team, epoch and member).
#[derive(Clone)]
pub struct MemberSlot {
pub team: [u8; ID_LEN],
pub member: [u8; ID_LEN],
pub epoch: u32,
pub sealed: Vec<u8>,
}
impl MemberSlot {
pub fn raw(&self) -> RawSlot {
let mut p = Vec::with_capacity(MEMBER_SLOT_LEN);
p.extend_from_slice(&self.team);
p.extend_from_slice(&self.member);
p.extend_from_slice(&self.epoch.to_le_bytes());
p.extend_from_slice(&self.sealed);
RawSlot { kind: SLOT_MEMBER, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
if payload.len() != MEMBER_SLOT_LEN {
return Err(Error::Malformed);
}
Ok(MemberSlot {
team: payload[..16].try_into().unwrap(),
member: payload[16..32].try_into().unwrap(),
epoch: u32::from_le_bytes(payload[32..36].try_into().unwrap()),
sealed: payload[36..].to_vec(),
})
}
}
pub struct Header {
pub version: u16,
pub slots: Vec<RawSlot>,
@@ -303,6 +386,9 @@ impl Header {
/// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces").
fn check_v2(&self) -> Result<(), Error> {
if self.slots.iter().any(|s| s.kind == SLOT_MEMBER) {
return self.check_team();
}
let mut ids = Vec::new();
for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) {
ids.push(FactorSlot::parse(&s.payload)?.id);
@@ -317,6 +403,7 @@ impl Header {
return Err(Error::Malformed);
}
let mut singles = 0;
let mut recoveries = 0;
for s in &self.slots {
match s.kind {
SLOT_FACTOR => {}
@@ -333,6 +420,10 @@ impl Header {
}
singles += 1;
}
SLOT_RECOVERY => {
RecoverySlot::parse(&s.payload)?;
recoveries += 1;
}
// A v1 password slot, or an unknown kind, has no place in a v2 header.
_ => return Err(Error::Malformed),
}
@@ -341,9 +432,38 @@ impl Header {
if singles > 0 && (singles != 1 || ids.len() != 1) {
return Err(Error::Malformed);
}
// One recovery key at most, and none for a vault that opens by itself.
if recoveries > 1 || (recoveries == 1 && singles > 0) {
return Err(Error::Malformed);
}
Ok(())
}
/// A team vault (docs/TEAM.md): 1 ..= 32 member slots and nothing else, one team id and epoch, distinct members.
fn check_team(&self) -> Result<(), Error> {
if self.slots.len() > MAX_MEMBER_SLOTS || self.slots.iter().any(|s| s.kind != SLOT_MEMBER) {
return Err(Error::Malformed);
}
let slots = self.slots.iter().map(|s| MemberSlot::parse(&s.payload)).collect::<Result<Vec<_>, _>>()?;
let first = &slots[0];
let mut members: Vec<[u8; ID_LEN]> = Vec::with_capacity(slots.len());
for s in &slots {
if s.team != first.team || s.epoch != first.epoch || members.contains(&s.member) {
return Err(Error::Malformed);
}
members.push(s.member);
}
Ok(())
}
pub fn is_team(&self) -> bool {
self.slots.iter().any(|s| s.kind == SLOT_MEMBER)
}
pub fn member_slots(&self) -> Vec<MemberSlot> {
self.slots.iter().filter(|s| s.kind == SLOT_MEMBER).filter_map(|s| MemberSlot::parse(&s.payload).ok()).collect()
}
pub fn factor_slots(&self) -> Vec<FactorSlot> {
self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect()
}
@@ -356,6 +476,10 @@ impl Header {
self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok())
}
pub fn recovery_slot(&self) -> Option<RecoverySlot> {
self.slots.iter().find(|s| s.kind == SLOT_RECOVERY).and_then(|s| RecoverySlot::parse(&s.payload).ok())
}
pub fn is_machine_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == SLOT_SINGLE)
}
+306
View File
@@ -0,0 +1,306 @@
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates and
//! revocations of keys the person revoked. It derives each app's backup secret from it.
//!
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
//!
//! ```
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 })?;
//! let mut words = Vec::new();
//! let shown = Enrollment::begin().show(|w| words = w.iter().map(|s| s.to_string()).collect());
//! let typed = shown.challenge().map(|i| words[i - 1].clone()); // the person types these back
//! let confirmed = shown.confirm(&[&typed[0], &typed[1], &typed[2]]).map_err(|(_, e)| e)?;
//! let root_public = confirmed.import(&mut vault)?;
//! # Ok::<(), custos_vault::Error>(())
//! ```
//!
//! Importing before the mnemonic was shown does not compile:
//!
//! ```compile_fail
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
//! Enrollment::begin().import(&mut vault);
//! ```
//!
//! Nor does confirming words that were never shown:
//!
//! ```compile_fail
//! # use custos_vault::identity::Enrollment;
//! Enrollment::begin().confirm(&["abandon", "abandon", "art"]);
//! ```
//!
//! Nor importing straight after showing, without the person typing the words back:
//!
//! ```compile_fail
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
//! Enrollment::begin().show(|_| {}).import(&mut vault);
//! ```
use crate::crypto::{self, KEY_LEN};
use crate::{Error, SecretString, Vault, hex, now_ms, unhex};
use serde::{Deserialize, Serialize};
use std::fmt;
use zeroize::Zeroizing;
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
const CERT_MAGIC: &[u8] = b"TSC1";
/// And `REVOKE_DOMAIN ‖ tbs`, only for a `tbs` that starts with `REVOKE_MAGIC ‖ its public key ‖ a key the
/// person revoked ‖ that key's revoked_at` (Fundamentum docs/TESSERA.md §12).
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
const REVOKE_MAGIC: &[u8] = b"TRV1";
/// magic 4, root 32, subkey 32, revoked_at 8, part 2, parts 2, count 4.
const REVOKE_HEADER: usize = 84;
const BACKUP_SALT: &[u8] = b"tessera backup v1";
const WORDS: usize = 24;
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
pub struct Enrollment {
entropy: Zeroizing<[u8; 32]>,
}
/// Step 2: the words were shown; the person must type three of them back.
pub struct Shown {
entropy: Zeroizing<[u8; 32]>,
challenge: [usize; 3],
}
/// Step 3: the words were confirmed. Holds the root secret; the entropy is gone.
pub struct Confirmed {
secret: Zeroizing<[u8; KEY_LEN]>,
}
fn mnemonic(entropy: &[u8; 32]) -> bip39::Mnemonic {
bip39::Mnemonic::from_entropy_in(bip39::Language::English, entropy)
.expect("32 bytes is a valid BIP39 entropy length")
}
fn normalize(w: &str) -> String {
w.trim().to_lowercase()
}
/// Three different word positions, 1-based, ascending.
fn random_challenge() -> [usize; 3] {
let mut picked = Vec::with_capacity(3);
while picked.len() < 3 {
let mut b = [0u8; 1];
crypto::fill_random(&mut b);
// 240 = 10 × 24: rejection sampling keeps every position equally likely.
if b[0] < 240 {
let i = (b[0] as usize % WORDS) + 1;
if !picked.contains(&i) {
picked.push(i);
}
}
}
picked.sort();
[picked[0], picked[1], picked[2]]
}
impl Enrollment {
/// 32 bytes from the OS CSPRNG.
pub fn begin() -> Enrollment {
let mut entropy = Zeroizing::new([0u8; 32]);
crypto::fill_random(entropy.as_mut());
Enrollment { entropy }
}
/// Known entropy, for test vectors.
pub fn with_entropy(entropy: [u8; 32]) -> Enrollment {
Enrollment { entropy: Zeroizing::new(entropy) }
}
/// Hands the 24 words to `display`, once. The only way to [`Shown`].
pub fn show(self, display: impl FnOnce(&[&str])) -> Shown {
let phrase = Zeroizing::new(mnemonic(&self.entropy).to_string());
let words: Vec<&str> = phrase.split(' ').collect();
display(&words);
Shown { entropy: self.entropy, challenge: random_challenge() }
}
/// Restores an identity from its whole phrase, typed back (docs/IDENTITY.md, "Restoring it"): all 24
/// words prove more than three. Any case, any spacing. Anything that is not 24 English BIP39 words with a
/// valid checksum is [`Error::NotAMnemonic`], which names no word.
pub fn restore(phrase: &str) -> Result<Confirmed, Error> {
// Room for lowercasing without a reallocation that would leave a copy behind.
let mut joined = Zeroizing::new(String::with_capacity(phrase.len() * 3 + 1));
for (i, w) in phrase.split_whitespace().enumerate() {
if i > 0 {
joined.push(' ');
}
joined.extend(w.chars().flat_map(char::to_lowercase));
}
if joined.split(' ').count() != WORDS {
return Err(Error::NotAMnemonic);
}
let m =
bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &joined).map_err(|_| Error::NotAMnemonic)?;
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
}
}
impl Shown {
/// The positions (1–24) of the three words to type back.
pub fn challenge(&self) -> [usize; 3] {
self.challenge
}
/// Checks the three typed words (any case, surrounding spaces ignored). On a mismatch this `Shown` comes
/// back with [`Error::WrongWords`], so the person can try again; the words are not shown again.
pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)> {
let m = mnemonic(&self.entropy);
let phrase = Zeroizing::new(m.to_string());
let all: Vec<&str> = phrase.split(' ').collect();
let ok = self.challenge.iter().zip(words).all(|(&i, typed)| *Zeroizing::new(normalize(typed)) == all[i - 1]);
if !ok {
return Err((self, Error::WrongWords));
}
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
}
}
impl Confirmed {
/// Stores the root in `vault` and returns its public key. The caller saves the vault. A vault has one
/// identity: a second import is [`Error::IdentityExists`].
pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error> {
if vault.identity.is_some() {
return Err(Error::IdentityExists);
}
let public = crypto::ed25519_public(&self.secret);
vault.identity = Some(Root { secret: self.secret, public, created: now_ms(), issued: Vec::new() });
Ok(public)
}
}
impl fmt::Debug for Enrollment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Enrollment([redacted])")
}
}
impl fmt::Debug for Shown {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Shown([redacted])")
}
}
impl fmt::Debug for Confirmed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Confirmed([redacted])")
}
}
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issued {
/// `app` or `device`.
pub kind: String,
pub app_id: String,
pub purpose: String,
/// The subkey's public key, base64url.
pub subkey: String,
/// The program or device it was issued to.
pub label: String,
/// Unix seconds.
pub not_before: u64,
pub not_after: u64,
/// Unix milliseconds.
pub issued: i64,
/// Unix seconds: when the person revoked the key (core 0.10.0).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<u64>,
/// The signed `TRV1` statements, base64url, once an app sent the events to keep.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub revocation: Vec<String>,
}
/// The identity in an unlocked vault.
pub(crate) struct Root {
secret: Zeroizing<[u8; KEY_LEN]>,
pub(crate) public: [u8; 32],
pub(crate) created: i64,
pub(crate) issued: Vec<Issued>,
}
/// The `identity` body member.
#[derive(Serialize, Deserialize)]
pub(crate) struct RootJson {
root: SecretString,
public: String,
created: i64,
#[serde(default)]
issued: Vec<Issued>,
}
impl Root {
pub(crate) fn sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
let names_me = tbs.len() > CERT_MAGIC.len() + 32
&& &tbs[..CERT_MAGIC.len()] == CERT_MAGIC
&& tbs[CERT_MAGIC.len()..CERT_MAGIC.len() + 32] == self.public;
if !names_me {
return Err(Error::NotACert);
}
let msg = Zeroizing::new([CERT_DOMAIN, tbs].concat());
Ok(crypto::ed25519_sign(&self.secret, &msg))
}
pub(crate) fn sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
let names_me = tbs.len() >= REVOKE_HEADER && &tbs[..4] == REVOKE_MAGIC && tbs[4..36] == self.public;
if !names_me {
return Err(Error::NotARevocation);
}
let subkey = data_encoding::BASE64URL_NOPAD.encode(&tbs[36..68]);
let at = u64::from_be_bytes(tbs[68..76].try_into().expect("8 bytes"));
if !self.issued.iter().any(|i| i.subkey == subkey && i.revoked_at == Some(at)) {
return Err(Error::NotARevocation);
}
let msg = Zeroizing::new([REVOKE_DOMAIN, tbs].concat());
Ok(crypto::ed25519_sign(&self.secret, &msg))
}
/// Marks every cert of `subkey` revoked; keeps the earliest time if one was marked before.
pub(crate) fn mark_revoked(&mut self, subkey: &str, at: u64) -> Result<u64, Error> {
let mut certs = self.issued.iter().filter(|i| i.subkey == subkey).peekable();
if certs.peek().is_none() {
return Err(Error::UnknownKey);
}
let at = certs.filter_map(|i| i.revoked_at).min().unwrap_or(at);
self.issued.iter_mut().filter(|i| i.subkey == subkey).for_each(|i| i.revoked_at = Some(at));
Ok(at)
}
pub(crate) fn record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
let mut certs = self.issued.iter_mut().filter(|i| i.subkey == subkey).peekable();
if certs.peek().is_none() {
return Err(Error::UnknownKey);
}
certs.for_each(|i| i.revocation = statements.clone());
Ok(())
}
/// `HKDF-SHA256(salt "tessera backup v1", ikm = root secret, info = app id)` (docs/IDENTITY.md).
pub(crate) fn backup_secret(&self, app_id: &str) -> Zeroizing<[u8; KEY_LEN]> {
crypto::hkdf(self.secret.as_ref(), BACKUP_SALT, app_id.as_bytes())
}
pub(crate) fn json(&self) -> RootJson {
RootJson {
root: SecretString::new(hex(self.secret.as_ref())),
public: hex(&self.public),
created: self.created,
issued: self.issued.clone(),
}
}
/// `None` when malformed, or when the public key is not the secret's.
pub(crate) fn from_json(j: &RootJson) -> Option<Root> {
let secret = Zeroizing::new(unhex::<KEY_LEN>(j.root.expose())?);
let public = unhex::<32>(&j.public)?;
if crypto::ed25519_public(&secret) != public {
return None;
}
Some(Root { secret, public, created: j.created, issued: j.issued.clone() })
}
}
+21 -1
View File
@@ -1,6 +1,6 @@
//! Typed items and their templates (docs/FORMAT.md, "Item types and their fields").
use crate::secret::SecretString;
use crate::secret::{SecretBytes, SecretString};
use serde::{Deserialize, Serialize};
use std::fmt;
@@ -116,6 +116,19 @@ impl fmt::Debug for HistoryEntry {
}
}
/// A file kept with an item (imported from KeePass, docs/KDBX.md). The content counts as secret.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
pub name: String,
pub data: SecretBytes,
}
impl fmt::Debug for Attachment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Attachment").field("name", &self.name).field("len", &self.data.len()).finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
pub id: String,
@@ -132,6 +145,11 @@ pub struct Item {
pub modified: i64,
#[serde(default)]
pub history: Vec<HistoryEntry>,
/// Folder names, outermost first (a KeePass group path). Empty: no folder.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub folder: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<Attachment>,
}
impl Item {
@@ -151,6 +169,8 @@ impl Item {
created: now,
modified: now,
history: Vec::new(),
folder: Vec::new(),
attachments: Vec::new(),
}
}
+385 -9
View File
@@ -19,13 +19,25 @@
mod crypto;
mod device;
mod format;
pub mod identity;
pub mod licence;
mod item;
pub mod provision;
mod recovery;
mod save;
mod secret;
pub mod security;
pub mod signing;
pub mod team;
pub use item::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use recovery::RecoveryKey;
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
pub use secret::SecretString;
pub use secret::{SecretBytes, SecretString};
pub use team::{
KnownTeam, NewSigner, NewTarget, Removal, RemovedMember, SignerView, TargetView, TeamAction, TeamAuditEntry,
TeamMember, TeamView,
};
use crypto::KEY_LEN;
use format::{
@@ -59,8 +71,47 @@ pub enum Error {
FactorRejected,
#[error("these two factors are kept on the same device; use one of them with another factor")]
SameDevice,
#[error("this is not a recovery key as Custos prints it: check each group of characters")]
RecoveryKeyMistyped,
#[error("this recovery key does not open this vault: it is another vault's, or an older one that was replaced")]
WrongRecoveryKey,
#[error("this vault has no recovery key")]
NoRecoveryKey,
#[error("a vault has at most 8 factors and one master password")]
TooManyFactors,
#[error("this vault has no Domi identity yet")]
NoIdentity,
#[error("this vault already has a Domi identity")]
IdentityExists,
#[error("the Domi identity signs only certificates that name it")]
NotACert,
#[error("those words are not the ones in the recovery phrase")]
WrongWords,
#[error("these are not the 24 words of a recovery phrase: check each word and their order")]
NotAMnemonic,
#[error("the Domi identity signs a revocation only for a key revoked in Custos, at the time it was revoked")]
NotARevocation,
#[error("the Domi identity did not certify this key")]
UnknownKey,
#[error("this vault already has {0} signing keys")]
SigningExists(&'static str),
/// Names the member that does not fit (docs/FORMAT.md), never its value.
#[error("provision audit: {0}")]
Provision(&'static str),
/// Names the rule a security change breaks (docs/FORMAT.md, "The security member"), never a value.
#[error("security: {0}")]
Security(&'static str),
#[error("signing keys: {0}")]
Signing(String),
/// A team vault operation was refused (docs/TEAM.md); names why, never a value.
#[error("team: {0}")]
Team(String),
#[error("this is not a team vault")]
NotATeam,
#[error("this member key does not open this team vault: not a member, or removed")]
NotAMember,
#[error("this team vault is older than the one this member has seen, or another team's under the same id")]
TeamRollback,
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -243,6 +294,7 @@ const BODY_FORMAT_2: u32 = 2;
const INFO_FACTOR: &[u8] = b"custos factor v2";
const INFO_PAIR: &[u8] = b"custos pair v2";
const INFO_SINGLE: &[u8] = b"custos single v2";
const INFO_RECOVERY: &[u8] = b"custos recovery v2";
#[derive(Deserialize)]
struct Body {
@@ -250,6 +302,22 @@ struct Body {
items: Vec<Item>,
#[serde(default)]
factors: Vec<FactorJson>,
#[serde(default)]
identity: Option<identity::RootJson>,
#[serde(default)]
signing: Option<signing::StoreJson>,
#[serde(default)]
provision: Option<provision::ProvisionJson>,
#[serde(default)]
security: Option<security::State>,
/// `"team"` for a team vault (core 0.18.0, docs/TEAM.md).
#[serde(default)]
kind: Option<String>,
#[serde(default)]
team: Option<team::TeamJson>,
/// A person's member key (core 0.18.0).
#[serde(default)]
member: Option<team::MemberJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -259,6 +327,20 @@ struct BodyRef<'a> {
items: &'a [Item],
#[serde(skip_serializing_if = "Vec::is_empty")]
factors: Vec<FactorJson>,
#[serde(skip_serializing_if = "Option::is_none")]
identity: Option<identity::RootJson>,
#[serde(skip_serializing_if = "Option::is_none")]
signing: Option<signing::StoreJson>,
#[serde(skip_serializing_if = "Option::is_none")]
provision: Option<provision::ProvisionJson>,
#[serde(skip_serializing_if = "Option::is_none")]
security: Option<security::State>,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
team: Option<team::TeamJson>,
#[serde(skip_serializing_if = "Option::is_none")]
member: Option<team::MemberJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
@@ -271,6 +353,18 @@ pub struct Vault {
factors: Vec<FactorRec>,
/// Argon2 parameters for a password factor added later.
kdf_new: KdfParams,
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
identity: Option<identity::Root>,
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
signing: signing::Store,
/// The Provisio audit (docs/FORMAT.md), oldest first.
provision: Vec<provision::ProvisionEntry>,
/// The security level's Setup window, the checklist and their audit (docs/FORMAT.md).
security: security::State,
/// A team vault's own state (docs/TEAM.md); `None` for every other vault.
team: Option<team::TeamState>,
/// A person's member key and the teams it has opened (docs/TEAM.md); never in a team vault.
member: Option<team::MemberState>,
}
impl fmt::Debug for Vault {
@@ -279,6 +373,7 @@ impl fmt::Debug for Vault {
.field("version", &self.version)
.field("items", &self.items.len())
.field("factors", &self.factors.len())
.field("identity", &self.identity.is_some())
.finish_non_exhaustive()
}
}
@@ -311,7 +406,8 @@ fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams
}
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let mut slot =
FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
Ok(slot)
@@ -356,11 +452,42 @@ fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
}
impl Vault {
/// An empty version-2 vault with `key` and no slots yet: a team vault writes its member slots itself.
pub(crate) fn empty_v2(key: Zeroizing<[u8; KEY_LEN]>) -> Vault {
Vault {
key,
version: VERSION_2,
slots: Vec::new(),
items: Vec::new(),
factors: Vec::new(),
kdf_new: KdfParams::DEFAULT,
identity: None,
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
}
}
/// A new, empty version-1 vault with a fresh random vault key wrapped by `password`.
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
let key = crypto::random_key();
let slot = password_slot(&key, password, kdf)?;
Ok(Vault { key, version: VERSION, slots: vec![slot.raw()], items: Vec::new(), factors: Vec::new(), kdf_new: kdf })
Ok(Vault {
key,
version: VERSION,
slots: vec![slot.raw()],
items: Vec::new(),
factors: Vec::new(),
kdf_new: kdf,
identity: None,
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
})
}
/// A new, empty version-2 vault that opens with these two factors together (docs/FACTORS.md).
@@ -375,6 +502,12 @@ impl Vault {
items: Vec::new(),
factors: Vec::new(),
kdf_new: kdf,
identity: None,
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
@@ -389,7 +522,13 @@ impl Vault {
let key = crypto::random_key();
let mut id = [0u8; ID_LEN];
crypto::fill_random(&mut id);
let rec = FactorRec { id, kind: FactorKind::Device, label: label.into(), created: now_ms(), key: crypto::random_key() };
let rec = FactorRec {
id,
kind: FactorKind::Device,
label: label.into(),
created: now_ms(),
key: crypto::random_key(),
};
let fslot = factor_slot(id, &rec.key, &u, KdfParams::DEFAULT)?;
let mut single = SingleSlot { id, nonce: crypto::random_nonce(), wrapped: Vec::new() };
single.wrapped = crypto::seal(&single_kek(&rec), &single.nonce, key.as_ref(), &single.aad());
@@ -400,6 +539,12 @@ impl Vault {
items: Vec::new(),
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
identity: None,
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
})
}
@@ -504,7 +649,8 @@ impl Vault {
if body.format != want {
return Err(Error::Corrupted);
}
let factors: Vec<FactorRec> = body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
let factors: Vec<FactorRec> =
body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
// Every factor slot in the header has its key in the body, and the other way round.
if header.version == VERSION_2 {
let mut in_header: Vec<_> = header.factor_slots().iter().map(|s| s.id).collect();
@@ -516,7 +662,40 @@ impl Vault {
}
}
let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT);
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new })
let identity = match &body.identity {
Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?),
None => None,
};
let signing = match body.signing {
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
None => signing::Store::default(),
};
let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?;
// A team vault (member slots) has a team body and nothing of a person's; every other vault has none.
let team = match (header.is_team(), body.kind.as_deref(), body.team) {
(true, Some("team"), Some(j)) => Some(team::TeamState::from_json(j).ok_or(Error::Corrupted)?),
(false, None, None) => None,
_ => return Err(Error::Corrupted),
};
let member = match body.member {
Some(_) if team.is_some() => return Err(Error::Corrupted),
Some(j) => Some(team::MemberState::from_json(j).ok_or(Error::Corrupted)?),
None => None,
};
Ok(Vault {
key,
version: header.version,
slots: header.slots,
items: body.items,
factors,
kdf_new,
identity,
signing,
provision: provision::from_json(body.provision),
security,
team,
member,
})
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
@@ -549,6 +728,13 @@ impl Vault {
format: if v2 { BODY_FORMAT_2 } else { BODY_FORMAT },
items: &self.items,
factors: self.factors.iter().map(FactorRec::json).collect(),
identity: self.identity.as_ref().map(identity::Root::json),
signing: self.signing.json(),
provision: provision::json(&self.provision),
security: self.security.json(),
kind: self.team.is_some().then_some("team"),
team: self.team.as_ref().map(team::TeamState::json),
member: self.member.as_ref().map(team::MemberState::json),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
@@ -586,6 +772,137 @@ impl Vault {
Ok(())
}
/// A machine-key vault: one device factor opens it alone (a Claude Code store, or Custos's hands-off vault
/// before it is taken over).
pub fn opens_with_machine_key(&self) -> bool {
self.is_store()
}
/// *Take over the vault* (Custos docs/12_hands_off.md, section 6): adds the master password as a factor paired
/// with the device key, removes the PC-only access, and ticks the items that end unattended work. Returns the
/// password factor's id. Only on a machine-key vault, once. The caller saves.
pub fn take_over(&mut self, password: &SecretString, kdf: KdfParams, now: i64) -> Result<String, Error> {
if !self.is_store() {
return Err(Error::FactorRejected);
}
let slots = self.slots.clone();
let kdf_was = self.kdf_new;
// Without its single slot the vault is an ordinary version-2 vault with one factor; the password pairs with it.
self.slots.retain(|s| s.kind != format::SLOT_SINGLE);
self.kdf_new = kdf;
match self.add_factor(Unlock::Password(password), "Master password") {
Ok(id) => {
self.security_taken_over(now);
Ok(id)
}
Err(e) => {
self.slots = slots;
self.kdf_new = kdf_was;
Err(e)
}
}
}
// ---- the recovery key (docs/FACTORS.md, "The recovery key") ----
/// Which recovery key a vault file has (its id, 8 hex characters), from the header alone.
pub fn recovery_id_of(bytes: &[u8]) -> Result<Option<String>, Error> {
Ok(Header::parse(bytes)?.0.recovery_slot().map(|s| recovery::id_hex(&s.id)))
}
/// Which recovery key this vault has.
pub fn recovery_id(&self) -> Option<String> {
self.slots
.iter()
.find(|s| s.kind == format::SLOT_RECOVERY)
.and_then(|s| format::RecoverySlot::parse(&s.payload).ok())
.map(|s| recovery::id_hex(&s.id))
}
fn recovery_put(&mut self) -> RecoveryKey {
let mut id = [0u8; recovery::ID_LEN];
crypto::fill_random(&mut id);
let material = crypto::random_key();
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = format::RecoverySlot { id, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY);
slot.wrapped = crypto::seal(&kek, &slot.nonce, self.key.as_ref(), &slot.aad());
self.slots.retain(|s| s.kind != format::SLOT_RECOVERY);
self.slots.push(slot.raw());
recovery::encode(&id, &material)
}
/// Makes the vault's recovery key and returns it, once: it is in no file and no log, so what the caller does
/// not show or print is lost. A key the vault already had stops working. Only a two-factor vault has one
/// (not version 1, not a machine-key vault). The caller saves.
pub fn recovery_create(&mut self, now: i64) -> Result<RecoveryKey, Error> {
if self.version != VERSION_2 {
return Err(Error::NeedTwoFactors);
}
if self.is_store() {
return Err(Error::FactorRejected);
}
let key = self.recovery_put();
self.security.recovery_note(security::Action::RecoveryCreated, key.id(), now);
Ok(key)
}
/// Removes the recovery key: from the next save on, only the factors open the vault. The caller saves.
pub fn recovery_remove(&mut self, now: i64) -> Result<(), Error> {
let id = self.recovery_id().ok_or(Error::NoRecoveryKey)?;
self.slots.retain(|s| s.kind != format::SLOT_RECOVERY);
self.security.recovery_note(security::Action::RecoveryRemoved, &id, now);
Ok(())
}
/// Opens a vault with its recovery key and, before handing it back, replaces what opened it until now: every
/// factor is dropped, `new_password` and `second` (anything but a password) become its two factors, and the
/// used recovery key is replaced by the new one returned here. The items and everything else stay. Nothing is
/// written: the caller saves, and until it does the file is as it was.
///
/// This is the only call that takes a recovery key, so the key is never an everyday unlock.
pub fn recover(
bytes: &[u8],
key: &SecretString,
new_password: &SecretString,
kdf: KdfParams,
second: Unlock,
label: &str,
now: i64,
) -> Result<(Vault, RecoveryKey), Error> {
// What was typed is checked first: a typing mistake is not a wrong key.
let (id, material) = recovery::decode(key)?;
if second.kind() == FactorKind::Password {
return Err(Error::NeedTwoFactors);
}
second.check()?;
if new_password.expose().is_empty() {
return Err(Error::WrongPassword);
}
kdf.check()?;
let (header, body_at) = Header::parse(bytes)?;
if header.version != VERSION_2 {
return Err(Error::NoRecoveryKey);
}
let slot = header.recovery_slot().ok_or(Error::NoRecoveryKey)?;
if slot.id != id {
return Err(Error::WrongRecoveryKey);
}
let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY);
let k = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::WrongRecoveryKey)?;
let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
// Whoever held the old factors holds nothing of this vault from the next save on.
v.slots.clear();
v.factors.clear();
v.kdf_new = kdf;
v.add_factor(Unlock::Password(new_password), "Master password")?;
v.add_factor(second, label)?;
let new_key = v.recovery_put();
v.security.recovery_note(security::Action::Recovered, &recovery::id_hex(&id), now);
Ok((v, new_key))
}
fn is_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
}
@@ -604,7 +921,8 @@ impl Vault {
/// as a phone's passkey and its approval key): together they open nothing, so one device is never two
/// factors. Returns its id.
pub fn add_factor_apart(&mut self, u: Unlock, label: &str, apart: &[&str]) -> Result<String, Error> {
let apart: Vec<[u8; ID_LEN]> = apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::<Result<_, _>>()?;
let apart: Vec<[u8; ID_LEN]> =
apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::<Result<_, _>>()?;
if apart.iter().any(|a| !self.factors.iter().any(|f| f.id == *a)) {
return Err(Error::FactorRejected);
}
@@ -652,7 +970,13 @@ impl Vault {
/// Turns an unlocked version-1 vault into version 2 with its password and a second factor.
/// The vault key and the items stay; from the next save on, the password alone opens nothing.
pub fn upgrade_to_two_factors(&mut self, password: &SecretString, kdf: KdfParams, second: Unlock, label: &str) -> Result<(), Error> {
pub fn upgrade_to_two_factors(
&mut self,
password: &SecretString,
kdf: KdfParams,
second: Unlock,
label: &str,
) -> Result<(), Error> {
if self.version != VERSION {
return Err(Error::UnsupportedVersion(self.version));
}
@@ -725,4 +1049,56 @@ impl Vault {
let i = self.items.iter().position(|it| it.id == id)?;
Some(self.items.remove(i))
}
// ---- the Domi identity (docs/IDENTITY.md); created with identity::Enrollment ----
/// The root public key, if this vault has a Domi identity.
pub fn domi_root_public(&self) -> Option<[u8; 32]> {
self.identity.as_ref().map(|r| r.public)
}
/// When the identity was created (Unix milliseconds).
pub fn domi_created(&self) -> Option<i64> {
self.identity.as_ref().map(|r| r.created)
}
/// Ed25519 with the root over `"tessera cert v1" ‖ tbs`. Refuses a `tbs` that does not start with
/// `TSC1` and this root's public key ([`Error::NotACert`]): the root signs certificates and nothing else.
pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_cert(tbs)
}
/// The certs this vault has signed, oldest first.
pub fn domi_issued(&self) -> &[identity::Issued] {
self.identity.as_ref().map(|r| r.issued.as_slice()).unwrap_or(&[])
}
/// Records a cert this vault signed. The caller saves the vault.
pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
Ok(())
}
/// The person revoked the key `subkey` (base64url): marks every cert of it. Returns the revocation time in
/// effect, the earlier one if it was marked before. The caller saves the vault.
pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.mark_revoked(subkey, revoked_at)
}
/// Ed25519 with the root over `"tessera revoke v1\0" ‖ tbs`, for a `tbs` that starts with `TRV1`, this
/// root's public key, a key marked revoked and its `revoked_at` ([`Error::NotARevocation`] otherwise).
pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_revocation(tbs)
}
/// Keeps the signed statements (base64url `TRV1`) with every cert of `subkey`. The caller saves the vault.
pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.record_revocation(subkey, statements)
}
/// The backup secret of the app `app_id` (docs/IDENTITY.md): derived from the root, handed to that app
/// only. The caller checks `app_id` (a-z, 0-9, `-`) and the app's right to it.
pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error> {
Ok(self.identity.as_ref().ok_or(Error::NoIdentity)?.backup_secret(app_id))
}
}
+843
View File
@@ -0,0 +1,843 @@
//! Domi licences (core 0.21.0, docs/SIGNING.md "Domi licences"; the byte format is Fundamentum's docs/LICENCE.md,
//! licence v1): the key `domi-licence`, the strict parser of what it signs, and Mark's licence grant.
//!
//! The key is an Ed25519 key in the signing store under the reserved id [`LICENCE_KEY`], with no scope: every
//! other signing path refuses it, so it signs only the two payload kinds here (a licence, a revocation list), and
//! no other key signs them. Its secret never leaves this module and `signing.rs`; only its public key does.
//!
//! What it signs is parsed here **before** anything else, byte for byte as the spec's strict parser does (§2.4
//! steps 1–4 and 7 for a licence, §4.1 for a revocation list): malformed input is refused with the spec's code and
//! never reaches a card. Then the grant decides: a licence from `licence-issue` (its Canalis app id, and a
//! Domi-signed program) whose apps are all on Mark's allowlist, within the cap, is signed at once; anything else
//! that is well formed asks Mark on a card. A revocation list always asks. Refused outright, never a card: a licence
//! whose `issued` is more than a day from this clock, a licence id this key signed before (`replay`), a revocation
//! list whose `seq` is not higher than the highest this key signed (`rollback`), and any caller but `licence-issue`.
//!
//! The grant and the log live in the signing store's `licence` member, which cores before 0.21.0 ignore (and drop if
//! they save the vault: then the grant is gone, which fails closed, and the service's own anti-rollback check still
//! holds, Fundamentum docs/LICENCE.md §4.2). The key itself is an ordinary Ed25519 entry every core reads.
use serde::{Deserialize, Serialize};
use crate::{Error, Vault};
/// The reserved id of the licence key.
pub const LICENCE_KEY: &str = "domi-licence";
/// The one Canalis app that may ask for a licence signature.
pub const LICENCE_ISSUER: &str = "licence-issue";
/// The first line of a licence payload, inside the signed bytes.
pub const LICENCE_PREFIX: &str = "domi-licence-v1\n";
/// The first line of a revocation list payload, inside the signed bytes.
pub const REVOCATIONS_PREFIX: &str = "domi-revocations-v1\n";
/// What the `sig:` line adds to a payload to make the file: `sig: ` (5), 86 characters, LF.
const SIG_LINE_LEN: usize = 5 + 86 + 1;
/// The largest licence payload signed: the spec caps the **file** at 4096 bytes, so a payload is at most what still
/// fits with its signature line. Stricter than the spec's payload parser, never looser.
pub const LICENCE_PAYLOAD_MAX: usize = 4096 - SIG_LINE_LEN;
/// The largest revocation list payload signed, for the spec's 61 440-byte file.
pub const REVOCATIONS_PAYLOAD_MAX: usize = 61_440 - SIG_LINE_LEN;
/// How far a licence's `issued` may be from this clock, either way (seconds).
pub const CLOCK_TOLERANCE_S: i64 = 86_400;
/// At most this many licence signatures in a rolling day; past it, each one asks on a card.
pub const DAY_CAP: usize = 50;
const DAY_MS: i64 = 86_400_000;
/// At most this many app ids on the allowlist.
pub const ALLOW_MAX: usize = 256;
/// At most this many signatures in the log. Every licence id and revocation `seq` signed must stay known (replay,
/// rollback), so a full log refuses to sign more rather than forget (`log_full`).
pub const LOG_MAX: usize = 20_000;
const MAX_APPS: usize = 64;
const MAX_SEQ: u64 = (1 << 53) - 1;
const LICENCE_FIELDS: [&str; 7] = ["id", "issued", "nickname", "bundle", "scope", "seats", "apps"];
const REVOCATION_FIELDS: [&str; 3] = ["seq", "issued", "revoked"];
/// A licence payload, as parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Licence {
pub id: String,
/// Unix seconds.
pub issued: i64,
pub nickname: String,
pub bundle: String,
/// `None` for `scope: household`, the seat count for `scope: seat`.
pub seats: Option<u8>,
/// Sorted ascending and unique.
pub apps: Vec<String>,
}
/// A revocation list payload, as parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Revocations {
pub seq: u64,
/// Unix seconds.
pub issued: i64,
/// Sorted strictly ascending.
pub revoked: Vec<String>,
}
/// What a payload is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Payload {
Licence(Licence),
Revocations(Revocations),
}
/// Why a payload is not signed. [`LicenceRefusal::code`] is the spec's error code (Fundamentum docs/LICENCE.md §8)
/// where the spec has one, else Custos's own. None carries payload or key bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum LicenceRefusal {
/// The spec's strict parser refused the payload (§2.4 steps 1–4 and 7, §4.1).
#[error("the payload is malformed: {0}")]
Malformed(&'static str),
/// There is no `domi-licence` key yet.
#[error("there is no licence key in this vault")]
NoKey,
/// Only `licence-issue` may ask.
#[error("only licence-issue may ask for a licence signature")]
NotAllowed,
/// The licence's `issued` is more than a day from this clock.
#[error("the licence is dated more than a day from this PC's clock")]
Clock,
/// This key signed a licence with this id before.
#[error("a licence with this id was signed before")]
Replay,
/// This key signed a revocation list with this `seq` or a higher one before.
#[error("a revocation list with this seq or a higher one was signed before")]
Rollback,
/// The log is full.
#[error("the licence log is full")]
LogFull,
/// Asked to sign without a card where the grant does not cover the request.
#[error("this needs Mark's answer on a card")]
NeedsCard,
}
impl LicenceRefusal {
pub fn code(self) -> &'static str {
match self {
LicenceRefusal::Malformed(c) => c,
LicenceRefusal::NoKey => "no_key",
LicenceRefusal::NotAllowed => "not_allowed",
LicenceRefusal::Clock => "clock",
LicenceRefusal::Replay => "replay",
LicenceRefusal::Rollback => "rollback",
LicenceRefusal::LogFull => "log_full",
LicenceRefusal::NeedsCard => "needs_card",
}
}
}
// ---- the strict parser (Fundamentum docs/LICENCE.md §2.4 steps 1–4 and 7, §4.1) ----
fn malformed(code: &'static str) -> LicenceRefusal {
LicenceRefusal::Malformed(code)
}
/// A licence id: 8–64 bytes of `[A-Za-z0-9_-]`.
pub fn licence_id_ok(s: &str) -> bool {
(8..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
/// A Tessera id (a bundle, an app): 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`.
pub fn tessera_id_ok(s: &str) -> bool {
(1..=32).contains(&s.len())
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& !s.starts_with('-')
&& !s.ends_with('-')
}
/// A nickname: 1–32 bytes of `[A-Za-z0-9 ._-]`, no space at either end, never two spaces in a row.
fn nickname_ok(s: &str) -> bool {
(1..=32).contains(&s.len())
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b' ' | b'.' | b'_' | b'-'))
&& !s.starts_with(' ')
&& !s.ends_with(' ')
&& !s.contains(" ")
}
/// `[1-9]`, `[1-4][0-9]` or `50`.
fn seats(s: &str) -> Option<u8> {
let ok = matches!(s.as_bytes(), [b'1'..=b'9'] | [b'1'..=b'4', b'0'..=b'9'] | [b'5', b'0']);
ok.then(|| s.parse().ok()).flatten()
}
/// Decimal 1 to 2^53 − 1, no leading zero, no sign.
fn seq(s: &str) -> Option<u64> {
let digits = !s.is_empty() && s.len() <= 16 && s.bytes().all(|b| b.is_ascii_digit()) && !s.starts_with('0');
digits.then(|| s.parse::<u64>().ok()).flatten().filter(|n| (1..=MAX_SEQ).contains(n))
}
/// `YYYY-MM-DDTHH:MM:SSZ`, year 2000–2999, a real Gregorian date, no leap second: Unix seconds.
pub fn parse_utc(s: &str) -> Option<i64> {
let b = s.as_bytes();
if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' || b[19] != b'Z' {
return None;
}
let num = |from: usize, to: usize| -> Option<i64> {
let part = &b[from..to];
part.iter().all(u8::is_ascii_digit).then(|| part.iter().fold(0i64, |n, d| n * 10 + i64::from(d - b'0')))
};
let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?);
let (h, mi, sec) = (num(11, 13)?, num(14, 16)?, num(17, 19)?);
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
let days_in = match mo {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return None,
};
if !(2000..=2999).contains(&y) || !(1..=days_in).contains(&d) || h > 23 || mi > 59 || sec > 59 {
return None;
}
// Days from the civil date (Howard Hinnant's algorithm).
let (yy, mm) = if mo <= 2 { (y - 1, mo + 9) } else { (y, mo - 3) };
let era = yy.div_euclid(400);
let yoe = yy - era * 400;
let doy = (153 * mm + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some(days * 86_400 + h * 3600 + mi * 60 + sec)
}
/// The apps value: every element a Tessera id, at most 64, then sorted ascending and unique (in that order of checks).
fn apps(s: &str) -> Result<Vec<String>, LicenceRefusal> {
let list: Vec<&str> = s.split(',').collect();
if !list.iter().all(|a| tessera_id_ok(a)) {
return Err(malformed("bad_apps"));
}
if list.len() > MAX_APPS {
return Err(malformed("too_many_apps"));
}
for pair in list.windows(2) {
match pair[0].cmp(pair[1]) {
std::cmp::Ordering::Equal => return Err(malformed("apps_duplicate")),
std::cmp::Ordering::Greater => return Err(malformed("apps_unsorted")),
std::cmp::Ordering::Less => {}
}
}
Ok(list.into_iter().map(String::from).collect())
}
/// `<name>: <value>`: a 1–16 byte `[a-z]` name, one space, a non-empty value.
fn field(line: &str) -> Result<(&str, &str), LicenceRefusal> {
let (name, value) = line.split_once(": ").ok_or(malformed("bad_line"))?;
if !(1..=16).contains(&name.len()) || !name.bytes().all(|b| b.is_ascii_lowercase()) || value.is_empty() {
return Err(malformed("bad_line"));
}
Ok((name, value))
}
/// Steps 1–4 on a payload, and the lines after the prefix (step 7's input). The prefix says the kind.
fn structure(input: &[u8]) -> Result<(bool, Vec<&str>), LicenceRefusal> {
if input.len() > REVOCATIONS_PAYLOAD_MAX {
return Err(malformed("too_large"));
}
if input.is_empty() {
return Err(malformed("truncated"));
}
if input.contains(&b'\r') {
return Err(malformed("crlf"));
}
if input.iter().any(|&b| b != b'\n' && !(0x20..=0x7e).contains(&b)) {
return Err(malformed("bad_byte"));
}
let licence = input.starts_with(LICENCE_PREFIX.as_bytes());
let prefix = if licence {
LICENCE_PREFIX
} else if input.starts_with(REVOCATIONS_PREFIX.as_bytes()) {
REVOCATIONS_PREFIX
} else if LICENCE_PREFIX.as_bytes().starts_with(input) || REVOCATIONS_PREFIX.as_bytes().starts_with(input) {
return Err(malformed("truncated"));
} else {
return Err(malformed("bad_prefix"));
};
if licence && input.len() > LICENCE_PAYLOAD_MAX {
return Err(malformed("too_large"));
}
if input.last() != Some(&b'\n') {
return Err(malformed("truncated"));
}
// Printable ASCII and LF only: valid UTF-8.
let text = std::str::from_utf8(input).map_err(|_| malformed("bad_byte"))?;
let body = &text[prefix.len()..];
let lines = if body.is_empty() { Vec::new() } else { body[..body.len() - 1].split('\n').collect() };
Ok((licence, lines))
}
fn licence_fields(lines: &[&str]) -> Result<Licence, LicenceRefusal> {
let mut v: [Option<&str>; 7] = [None; 7];
let mut last: Option<usize> = None;
let (mut issued, mut household, mut seat_count, mut app_list) = (None, None, None, None);
for line in lines {
let (name, value) = field(line)?;
let i = LICENCE_FIELDS.iter().position(|f| *f == name).ok_or(malformed("unknown_field"))?;
if v[i].is_some() {
return Err(malformed("duplicate_field"));
}
if last.is_some_and(|l| i < l) {
return Err(malformed("field_order"));
}
last = Some(i);
v[i] = Some(value);
match i {
0 if !licence_id_ok(value) => return Err(malformed("bad_id")),
1 => issued = Some(parse_utc(value).ok_or(malformed("bad_issued"))?),
2 if !nickname_ok(value) => return Err(malformed("bad_nickname")),
3 if !tessera_id_ok(value) => return Err(malformed("bad_bundle")),
4 => {
household = Some(match value {
"household" => true,
"seat" => false,
_ => return Err(malformed("bad_scope")),
})
}
5 => seat_count = Some(seats(value).ok_or(malformed("bad_seats"))?),
6 => app_list = Some(apps(value)?),
_ => {}
}
}
let (Some(id), Some(issued), Some(nickname), Some(bundle), Some(household), Some(apps)) =
(v[0], issued, v[2], v[3], household, app_list)
else {
return Err(malformed("missing_field"));
};
let seats = match (household, seat_count) {
(true, None) => None,
(true, Some(_)) => return Err(malformed("seats_with_household")),
(false, Some(n)) => Some(n),
(false, None) => return Err(malformed("seats_missing")),
};
Ok(Licence { id: id.into(), issued, nickname: nickname.into(), bundle: bundle.into(), seats, apps })
}
fn revocation_fields(lines: &[&str]) -> Result<Revocations, LicenceRefusal> {
let (mut seq_v, mut issued) = (None, None);
let mut revoked: Vec<String> = Vec::new();
let mut last: Option<usize> = None;
for line in lines {
let (name, value) = field(line)?;
let i = REVOCATION_FIELDS.iter().position(|f| *f == name).ok_or(malformed("unknown_field"))?;
let seen = match i {
0 => seq_v.is_some(),
1 => issued.is_some(),
_ => false,
};
if seen {
return Err(malformed("duplicate_field"));
}
if last.is_some_and(|l| i < l) {
return Err(malformed("field_order"));
}
last = Some(i);
match i {
0 => seq_v = Some(seq(value).ok_or(malformed("bad_seq"))?),
1 => issued = Some(parse_utc(value).ok_or(malformed("bad_issued"))?),
_ => {
if !licence_id_ok(value) {
return Err(malformed("bad_id"));
}
if let Some(prev) = revoked.last() {
match prev.as_str().cmp(value) {
std::cmp::Ordering::Equal => return Err(malformed("revoked_duplicate")),
std::cmp::Ordering::Greater => return Err(malformed("revoked_unsorted")),
std::cmp::Ordering::Less => {}
}
}
revoked.push(value.into());
}
}
}
let (Some(seq), Some(issued)) = (seq_v, issued) else { return Err(malformed("missing_field")) };
Ok(Revocations { seq, issued, revoked })
}
/// The strict parser on a payload: a licence (§2.4 steps 1–4 and 7) or a revocation list (§4.1), by its prefix.
/// Custos never sees a `sig:` line, so steps 5 and 6 do not apply: one in a payload is an `unknown_field`.
pub fn parse_payload(payload: &[u8]) -> Result<Payload, LicenceRefusal> {
let (licence, lines) = structure(payload)?;
if licence {
licence_fields(&lines).map(Payload::Licence)
} else {
revocation_fields(&lines).map(Payload::Revocations)
}
}
// ---- the grant, the log, and what Custos does with a request ----
/// Mark's licence grant: what `licence-issue` may have signed without a card. Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceGrant {
/// The app ids a licence may name and still be signed without a card (Tessera ids, sorted, unique).
pub allow: Vec<String>,
/// Unix milliseconds: when Mark gave it, or last changed it.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
}
/// How a signature was allowed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LicenceBy {
/// Mark's licence grant covered it: no card.
Grant,
/// Mark said yes on a card.
Card,
}
/// One signature in the log: when, what (a licence's id and apps, or a revocation list's seq and count), and how it
/// was allowed. Never the signature, the payload or the nickname.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceEntry {
pub at: i64,
pub by: LicenceBy,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub licence: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub apps: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seq: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked: Option<u64>,
}
/// The grant and the log, in the signing store.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceStore {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grant: Option<LicenceGrant>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub log: Vec<LicenceEntry>,
}
impl LicenceStore {
pub(crate) fn is_empty(&self) -> bool {
self.grant.is_none() && self.log.is_empty()
}
/// What this core could have written; anything else makes the vault refuse to open.
pub(crate) fn ok(&self) -> bool {
let grant_ok = self.grant.as_ref().is_none_or(|g| allow_ok(&g.allow));
let entry_ok = |e: &LicenceEntry| match (&e.licence, e.seq) {
(Some(id), None) => {
licence_id_ok(id)
&& e.revoked.is_none()
&& (1..=MAX_APPS).contains(&e.apps.len())
&& e.apps.iter().all(|a| tessera_id_ok(a))
}
(None, Some(n)) => (1..=MAX_SEQ).contains(&n) && e.apps.is_empty(),
_ => false,
};
grant_ok && self.log.len() <= LOG_MAX && self.log.iter().all(entry_ok)
}
}
fn allow_ok(allow: &[String]) -> bool {
allow.len() <= ALLOW_MAX && allow.iter().all(|a| tessera_id_ok(a)) && allow.windows(2).all(|p| p[0] < p[1])
}
/// Why a well-formed request asks Mark on a card instead of being signed at once. Shown on the card.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase", tag = "why")]
pub enum CardReason {
/// A revocation list always asks.
Revocations,
/// There is no licence grant.
NoGrant,
/// The caller is not a program signed with Domi's certificate.
NotDomiSigned,
/// *Sign only with a card* is ticked.
CardSigning,
/// These apps are not on the allowlist.
OffAllowlist { apps: Vec<String> },
/// The day's cap of licence signatures is reached.
OverCap { signed: usize },
}
/// What Custos would do with a well-formed request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LicenceAsk {
pub payload: Payload,
/// Empty: the grant signs it now. Else the card's reasons.
pub card: Vec<CardReason>,
}
/// Who asks: the caller's authenticated Canalis app id, and whether its program is signed with one of Domi's
/// code-signing certificates (the desktop's check; docs/25 in Custos).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Caller<'a> {
pub app: &'a str,
pub domi_signed: bool,
}
impl Vault {
/// Makes the licence key (Ed25519) and returns its 32-byte public key, the one the Atrium Domi service ships.
/// Refused when there is one already. Call it only from Mark's own click. The caller saves.
pub fn licence_key_create(&mut self, now: i64) -> Result<[u8; 32], Error> {
if self.signing.get(LICENCE_KEY).is_some() {
return Err(Error::Signing(format!("there is a key `{LICENCE_KEY}` already")));
}
let public = self.signing.add_licence_key(now);
let words = format!("licence key {LICENCE_KEY} made");
self.security.standing_note(crate::security::Action::StandingGranted, &words, now);
Ok(public)
}
/// The licence key's public key, if there is one.
pub fn licence_public(&self) -> Option<[u8; 32]> {
self.signing.get(LICENCE_KEY).and_then(|k| k.public)
}
/// The licence grant, if Mark gave it.
pub fn licence_grant(&self) -> Option<LicenceGrant> {
self.signing.licence.grant.clone()
}
/// Gives the licence grant, or replaces its allowlist (its counts stay), and writes `standing-granted`. Refused
/// while *Sign only with a card* is ticked, and before there is a licence key. Call it only from Mark's own click.
/// The caller saves.
pub fn licence_grant_set(&mut self, allow: &[String], now: i64) -> Result<LicenceGrant, Error> {
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(Error::Signing("Sign only with a card is ticked".into()));
}
if self.signing.get(LICENCE_KEY).is_none() {
return Err(Error::Signing("make the licence key first".into()));
}
let mut list: Vec<String> = Vec::new();
for a in allow.iter().map(|a| a.trim()).filter(|a| !a.is_empty()) {
if !tessera_id_ok(a) {
return Err(Error::Signing(format!("`{a}` is not an app id (a-z, 0-9 and -, up to 32)")));
}
list.push(a.to_string());
}
list.sort();
list.dedup();
if list.len() > ALLOW_MAX {
return Err(Error::Signing(format!("the allowlist holds at most {ALLOW_MAX} apps")));
}
let old = self.signing.licence.grant.clone();
let grant = LicenceGrant {
allow: list,
granted: now,
last_used: old.as_ref().and_then(|g| g.last_used),
uses: old.map_or(0, |g| g.uses),
};
let words = format!("Domi licences by {LICENCE_ISSUER}: {}", grant.allow.join(", "));
self.security.standing_note(crate::security::Action::StandingGranted, &words, now);
self.signing.licence.grant = Some(grant.clone());
Ok(grant)
}
/// Removes the licence grant (`standing-revoked`): from then on every licence asks on a card. The key and the log
/// stay. False when there is none. The caller saves.
pub fn licence_grant_revoke(&mut self, now: i64) -> bool {
let Some(g) = self.signing.licence.grant.take() else { return false };
let words = format!("Domi licences by {LICENCE_ISSUER}: {}", g.allow.join(", "));
self.security.standing_note(crate::security::Action::StandingRevoked, &words, now);
true
}
/// Every licence signature, oldest first.
pub fn licence_log(&self) -> &[LicenceEntry] {
&self.signing.licence.log
}
/// What Custos does with `payload` from `caller` at `now` (Unix milliseconds): refused (the code says why, no
/// card), signed by the grant (no reasons), or asked on a card (its reasons). Changes nothing.
pub fn licence_ask(&self, payload: &[u8], caller: Caller<'_>, now: i64) -> Result<LicenceAsk, LicenceRefusal> {
let parsed = parse_payload(payload)?;
if self.signing.get(LICENCE_KEY).is_none() {
return Err(LicenceRefusal::NoKey);
}
if caller.app != LICENCE_ISSUER {
return Err(LicenceRefusal::NotAllowed);
}
if self.signing.licence.log.len() >= LOG_MAX {
return Err(LicenceRefusal::LogFull);
}
let log = &self.signing.licence.log;
let mut card = Vec::new();
match &parsed {
Payload::Licence(l) => {
if (l.issued - now.div_euclid(1000)).abs() > CLOCK_TOLERANCE_S {
return Err(LicenceRefusal::Clock);
}
if log.iter().any(|e| e.licence.as_deref() == Some(l.id.as_str())) {
return Err(LicenceRefusal::Replay);
}
if !caller.domi_signed {
card.push(CardReason::NotDomiSigned);
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
card.push(CardReason::CardSigning);
}
match &self.signing.licence.grant {
None => card.push(CardReason::NoGrant),
Some(g) => {
let off: Vec<String> = l.apps.iter().filter(|a| !g.allow.contains(a)).cloned().collect();
if !off.is_empty() {
card.push(CardReason::OffAllowlist { apps: off });
}
}
}
let today = log.iter().filter(|e| e.licence.is_some() && e.at > now - DAY_MS).count();
if today >= DAY_CAP {
card.push(CardReason::OverCap { signed: today });
}
}
Payload::Revocations(r) => {
if log.iter().filter_map(|e| e.seq).any(|s| s >= r.seq) {
return Err(LicenceRefusal::Rollback);
}
card.push(CardReason::Revocations);
}
}
Ok(LicenceAsk { payload: parsed, card })
}
/// Checks `payload` again ([`Vault::licence_ask`]) and signs it: by the grant when `by` is [`LicenceBy::Grant`]
/// (refused with `needs_card` when the grant does not cover it), or after Mark's yes on a card. Returns the
/// signature in base64url without padding (86 characters), and logs it. The caller saves.
pub fn licence_sign(
&mut self,
payload: &[u8],
caller: Caller<'_>,
by: LicenceBy,
now: i64,
) -> Result<String, LicenceRefusal> {
let ask = self.licence_ask(payload, caller, now)?;
if by == LicenceBy::Grant && !ask.card.is_empty() {
return Err(LicenceRefusal::NeedsCard);
}
let signature = self.signing.licence_signature(payload).ok_or(LicenceRefusal::NoKey)?;
let entry = match &ask.payload {
Payload::Licence(l) => LicenceEntry {
at: now,
by,
licence: Some(l.id.clone()),
apps: l.apps.clone(),
seq: None,
revoked: None,
},
Payload::Revocations(r) => LicenceEntry {
at: now,
by,
licence: None,
apps: Vec::new(),
seq: Some(r.seq),
revoked: Some(r.revoked.len() as u64),
},
};
self.signing.licence.log.push(entry);
if by == LicenceBy::Grant
&& let Some(g) = self.signing.licence.grant.as_mut()
{
g.uses = g.uses.saturating_add(1);
g.last_used = Some(now);
}
Ok(data_encoding::BASE64URL_NOPAD.encode(&signature))
}
}
#[cfg(test)]
mod tests {
use super::*;
const NOW_S: i64 = 1_795_896_907; // 2026-11-28T20:15:07Z
const NOW: i64 = NOW_S * 1000;
fn licence(id: &str, apps: &str) -> Vec<u8> {
format!(
"domi-licence-v1\nid: {id}\nissued: 2026-11-28T20:15:07Z\nnickname: Novak family\nbundle: household-all\n\
scope: household\napps: {apps}\n"
)
.into_bytes()
}
fn revocations(seq: u64, ids: &[&str]) -> Vec<u8> {
let mut s = format!("domi-revocations-v1\nseq: {seq}\nissued: 2026-11-28T20:15:07Z\n");
for id in ids {
s.push_str(&format!("revoked: {id}\n"));
}
s.into_bytes()
}
fn code(p: &[u8]) -> &'static str {
parse_payload(p).unwrap_err().code()
}
const ISSUER: Caller<'static> = Caller { app: LICENCE_ISSUER, domi_signed: true };
fn vault() -> Vault {
let pw = crate::SecretString::from("pw");
let mut v = Vault::create(&pw, crate::KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.licence_key_create(NOW).unwrap();
v
}
#[test]
fn the_spec_example_parses_and_its_time_is_utc() {
assert_eq!(parse_utc("2026-11-28T20:15:07Z"), Some(NOW_S));
assert_eq!(parse_utc("2000-01-01T00:00:00Z"), Some(946_684_800));
assert_eq!(parse_utc("2024-02-29T00:00:00Z").is_some(), true);
for bad in ["2023-02-29T00:00:00Z", "2100-02-29T00:00:00Z", "1999-12-31T23:59:59Z", "2026-11-28T24:00:00Z",
"2026-11-28T20:15:60Z", "2026-11-28 20:15:07Z", "2026-11-28T20:15:07z", "2026-13-01T00:00:00Z"] {
assert_eq!(parse_utc(bad), None, "{bad}");
}
let Payload::Licence(l) = parse_payload(&licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,fiscus,medicus,tabula")).unwrap()
else {
panic!("a licence")
};
assert_eq!((l.issued, l.seats, l.apps.len()), (NOW_S, None, 4));
}
#[test]
fn a_malformed_payload_is_refused_with_the_specs_code() {
let ok = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula");
let with = |from: &str, to: &str| String::from_utf8(ok.clone()).unwrap().replace(from, to).into_bytes();
assert_eq!(code(b""), "truncated");
assert_eq!(code(b"domi-lic"), "truncated");
assert_eq!(code(b"hello\n"), "bad_prefix");
assert_eq!(code(&with("\n", "\r\n")), "crlf");
assert_eq!(code(&with("Novak", "Nov\tak")), "bad_byte");
assert_eq!(code(&ok[..ok.len() - 1]), "truncated");
assert_eq!(code(&with("id: ", "id:")), "bad_line");
assert_eq!(code(&with("bundle: ", "colour: blue\nbundle: ")), "unknown_field");
assert_eq!(code(&with("bundle: ", "id: k3Jx0Qm1T9yZpW2bA7cD4f\nbundle: ")), "duplicate_field");
assert_eq!(code(&with("nickname: Novak family\nbundle: household-all", "bundle: household-all\nnickname: Novak family")), "field_order");
assert_eq!(code(&with("scope: household\n", "")), "missing_field");
assert_eq!(code(&with("k3Jx0Qm1T9yZpW2bA7cD4e", "short")), "bad_id");
assert_eq!(code(&with("2026-11-28T20:15:07Z", "2026-02-30T20:15:07Z")), "bad_issued");
assert_eq!(code(&with("Novak family", "Novak family")), "bad_nickname");
assert_eq!(code(&with("household-all", "-all")), "bad_bundle");
assert_eq!(code(&with("scope: household", "scope: family")), "bad_scope");
assert_eq!(code(&with("scope: household", "scope: seat\nseats: 51")), "bad_seats");
assert_eq!(code(&with("scope: household", "scope: household\nseats: 2")), "seats_with_household");
assert_eq!(code(&with("scope: household", "scope: seat")), "seats_missing");
assert_eq!(code(&with("calenda,tabula", "calenda,,tabula")), "bad_apps");
assert_eq!(code(&with("calenda,tabula", "tabula,calenda")), "apps_unsorted");
assert_eq!(code(&with("calenda,tabula", "calenda,calenda")), "apps_duplicate");
let many: Vec<String> = (0..65).map(|i| format!("app{i:03}")).collect();
assert_eq!(code(&with("calenda,tabula", &many.join(","))), "too_many_apps");
assert_eq!(code(&with("apps: calenda,tabula\n", "apps: calenda,tabula\nsig: x\n")), "unknown_field");
let mut big = ok.clone();
big.truncate(big.len() - 1);
big.extend(std::iter::repeat_n(b'a', LICENCE_PAYLOAD_MAX));
big.push(b'\n');
assert_eq!(code(&big), "too_large");
// A seat licence is fine.
assert!(parse_payload(&with("scope: household", "scope: seat\nseats: 50")).is_ok());
}
#[test]
fn a_revocation_list_parses_strictly() {
let a = "AAAAAAAAAAAAAAAAAAAAAA";
let b = "BBBBBBBBBBBBBBBBBBBBBB";
assert!(matches!(parse_payload(&revocations(1, &[])).unwrap(), Payload::Revocations(r) if r.revoked.is_empty()));
assert!(matches!(parse_payload(&revocations(7, &[a, b])).unwrap(), Payload::Revocations(r) if r.seq == 7));
assert_eq!(code(&revocations(7, &[b, a])), "revoked_unsorted");
assert_eq!(code(&revocations(7, &[a, a])), "revoked_duplicate");
assert_eq!(code(&revocations(0, &[])), "bad_seq");
assert_eq!(code(&revocations(MAX_SEQ + 1, &[])), "bad_seq");
assert_eq!(code(b"domi-revocations-v1\nissued: 2026-11-28T20:15:07Z\n"), "missing_field");
let reordered = b"domi-revocations-v1\nseq: 3\nrevoked: AAAAAAAAAAAAAAAAAAAAAA\nissued: 2026-11-28T20:15:07Z\n";
assert_eq!(code(reordered), "field_order");
}
#[test]
fn the_grant_signs_an_allowed_licence_and_a_signature_verifies() {
let mut v = vault();
let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula");
// No grant yet: a card.
assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap().card, vec![CardReason::NoGrant]);
assert_eq!(v.licence_sign(&p, ISSUER, LicenceBy::Grant, NOW), Err(LicenceRefusal::NeedsCard));
v.licence_grant_set(&["tabula".into(), "calenda".into()], NOW).unwrap();
let sig = v.licence_sign(&p, ISSUER, LicenceBy::Grant, NOW).unwrap();
assert_eq!(sig.len(), 86);
let raw = data_encoding::BASE64URL_NOPAD.decode(sig.as_bytes()).unwrap();
let key = ed25519_dalek::VerifyingKey::from_bytes(&v.licence_public().unwrap()).unwrap();
let sig = ed25519_dalek::Signature::from_slice(&raw).unwrap();
assert!(key.verify_strict(&p, &sig).is_ok(), "plain Ed25519 over the exact payload");
assert_eq!(v.licence_grant().unwrap().uses, 1);
assert_eq!(v.licence_log()[0].licence.as_deref(), Some("k3Jx0Qm1T9yZpW2bA7cD4e"));
// The same id again is a replay, refused with no card.
assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap_err(), LicenceRefusal::Replay);
}
#[test]
fn off_the_allowlist_unsigned_programs_and_the_cap_ask_on_a_card() {
let mut v = vault();
v.licence_grant_set(&["tabula".into()], NOW).unwrap();
let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula");
assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap().card, vec![CardReason::OffAllowlist { apps: vec!["calenda".into()] }]);
let unsigned = Caller { app: LICENCE_ISSUER, domi_signed: false };
let q = licence("k3Jx0Qm1T9yZpW2bA7cD4f", "tabula");
assert_eq!(v.licence_ask(&q, unsigned, NOW).unwrap().card, vec![CardReason::NotDomiSigned]);
for i in 0..DAY_CAP {
v.licence_sign(&licence(&format!("id-number-{i:03}"), "tabula"), ISSUER, LicenceBy::Grant, NOW).unwrap();
}
assert_eq!(v.licence_ask(&q, ISSUER, NOW).unwrap().card, vec![CardReason::OverCap { signed: DAY_CAP }]);
// Mark's card signs past the cap; a day later the grant signs again.
assert!(v.licence_sign(&q, ISSUER, LicenceBy::Card, NOW).is_ok());
let r = licence("k3Jx0Qm1T9yZpW2bA7cD4g", "tabula");
assert_eq!(v.licence_ask(&r, ISSUER, NOW + DAY_MS).unwrap().card, vec![]);
}
#[test]
fn refused_without_a_card_another_caller_a_bad_clock_and_a_rollback() {
let mut v = vault();
v.licence_grant_set(&["tabula".into()], NOW).unwrap();
let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "tabula");
let other = Caller { app: "atrium", domi_signed: true };
assert_eq!(v.licence_ask(&p, other, NOW).unwrap_err(), LicenceRefusal::NotAllowed);
assert_eq!(v.licence_ask(&p, ISSUER, NOW + 2 * DAY_MS).unwrap_err(), LicenceRefusal::Clock);
assert_eq!(v.licence_ask(&p, ISSUER, NOW - 2 * DAY_MS).unwrap_err(), LicenceRefusal::Clock);
// A revocation list always asks, and never goes back.
let r5 = revocations(5, &["k3Jx0Qm1T9yZpW2bA7cD4e"]);
assert_eq!(v.licence_ask(&r5, ISSUER, NOW).unwrap().card, vec![CardReason::Revocations]);
assert_eq!(v.licence_sign(&r5, ISSUER, LicenceBy::Grant, NOW), Err(LicenceRefusal::NeedsCard));
v.licence_sign(&r5, ISSUER, LicenceBy::Card, NOW).unwrap();
assert_eq!(v.licence_ask(&r5, ISSUER, NOW).unwrap_err(), LicenceRefusal::Rollback);
assert_eq!(v.licence_ask(&revocations(4, &[]), ISSUER, NOW).unwrap_err(), LicenceRefusal::Rollback);
assert!(v.licence_ask(&revocations(6, &[]), ISSUER, NOW).is_ok());
}
#[test]
fn the_licence_key_signs_nothing_else_and_its_state_survives_a_save() {
let mut v = vault();
assert!(v.licence_key_create(NOW).is_err(), "one licence key");
let req = crate::signing::Request {
key: LICENCE_KEY.into(),
kind: crate::signing::SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-1".into()),
context: crate::signing::Context {
repo: "mnovak/Custos".into(),
pipeline: "release".into(),
file: "x.exe".into(),
..Default::default()
},
via: crate::signing::Via::Local,
};
assert!(matches!(v.signing_check(&req), Err(crate::signing::Refusal::Invalid(_))));
assert!(v.signing_set_scope(LICENCE_KEY, &["*".into()], &["*".into()]).is_err());
v.licence_grant_set(&["tabula".into()], NOW).unwrap();
v.licence_sign(&licence("k3Jx0Qm1T9yZpW2bA7cD4e", "tabula"), ISSUER, LicenceBy::Grant, NOW).unwrap();
let again = Vault::open(&v.to_bytes().unwrap(), &crate::SecretString::from("pw")).unwrap();
assert_eq!(again.licence_public(), v.licence_public());
assert_eq!(again.licence_grant(), v.licence_grant());
assert_eq!(again.licence_log(), v.licence_log());
}
}
+233
View File
@@ -0,0 +1,233 @@
//! The Provisio audit (docs/FORMAT.md, "The provision audit"): the vault body member `provision`, beside
//! signing's audit. One entry per outcome of a server's ask or offer. An entry holds no secret: every member is
//! something the server sent in the clear through the mailbox, or the match code of a public key.
use serde::{Deserialize, Serialize};
use crate::{Error, Vault};
/// The log keeps the newest this many entries.
pub const AUDIT_LIMIT: usize = 5_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
/// The server asked Custos for a secret (or asked it to make one).
Ask,
/// The server offered a secret it made.
Offer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Store {
/// A Domi-ref item in the vault.
Vault,
/// The local Claude Code store.
Claude,
/// The cloud Claude Code store.
Cloud,
/// Shown once on the card and stored nowhere: a display offer (core 0.12.0).
Display,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
/// Ask: Mark approved; the item's value was sealed to the request.
Approved,
/// Ask with `--generate`: Custos made the item, stored it and sealed it to the request.
Generated,
/// Offer: Mark accepted; the value was stored.
Accepted,
/// Mark refused on the card.
Refused,
/// Outside the scope: refused before a card, or again when storing.
OutOfScope,
/// An offer's box did not match the offer (item, store, kind or code key), or did not open.
Invalid,
/// Nobody answered within five minutes.
Expired,
/// A display offer: Mark typed the code the phone shows, Custos checked it and sent it (core 0.12.0).
Confirmed,
}
/// One audit entry. Append-only: nothing edits or removes one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProvisionEntry {
/// Unix milliseconds.
pub at: i64,
pub direction: Direction,
/// The name the factor service gave the server.
pub host: String,
pub item: String,
pub store: Store,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run: Option<String>,
/// An offer's label (`--kind`), or an ask's `--generate` recipe.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
/// The match code both screens showed: six digits.
pub code: String,
pub outcome: Outcome,
/// An accepted offer replaced an existing item.
#[serde(default)]
pub replaced: bool,
}
/// The body member: `{"audit": [...]}`.
#[derive(Serialize, Deserialize)]
pub(crate) struct ProvisionJson {
#[serde(default)]
audit: Vec<ProvisionEntry>,
}
/// The log as the vault keeps it, oldest first.
pub(crate) fn from_json(j: Option<ProvisionJson>) -> Vec<ProvisionEntry> {
let mut audit = j.map(|j| j.audit).unwrap_or_default();
trim(&mut audit);
audit
}
/// Absent while the log is empty, so a vault without entries is written exactly as before.
pub(crate) fn json(audit: &[ProvisionEntry]) -> Option<ProvisionJson> {
(!audit.is_empty()).then(|| ProvisionJson { audit: audit.to_vec() })
}
fn trim(audit: &mut Vec<ProvisionEntry>) {
if audit.len() > AUDIT_LIMIT {
audit.drain(..audit.len() - AUDIT_LIMIT);
}
}
/// `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks an item.
fn item_ok(item: &str) -> bool {
let parts: Vec<&str> = item.split('/').collect();
parts.len() <= 4
&& parts.iter().all(|p| {
let b = p.as_bytes();
(1..=64).contains(&b.len())
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(c))
})
}
impl ProvisionEntry {
/// Whether every member fits docs/FORMAT.md. The error names the member, never its value.
pub fn check(&self) -> Result<(), Error> {
let host = self.host.as_bytes();
if !(1..=253).contains(&host.len()) || !host.iter().all(|c| c.is_ascii_alphanumeric() || b".-".contains(c)) {
return Err(Error::Provision("the host is not a host name"));
}
if !item_ok(&self.item) {
return Err(Error::Provision("the item is not an item name"));
}
if let Some(run) = &self.run {
let r = run.as_bytes();
if !(1..=64).contains(&r.len()) || !r.iter().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(c)) {
return Err(Error::Provision("the run is not a run id"));
}
}
if let Some(kind) = &self.kind
&& (kind.chars().count() > 200 || kind.chars().any(char::is_control))
{
return Err(Error::Provision("the kind is longer than 200 characters or has control characters"));
}
if self.code.len() != 6 || !self.code.bytes().all(|c| c.is_ascii_digit()) {
return Err(Error::Provision("the match code is not six digits"));
}
// A display offer stores nothing; `confirmed` is its outcome and nobody else's.
if self.store == Store::Display {
if self.direction != Direction::Offer {
return Err(Error::Provision("a display is an offer"));
}
if matches!(self.outcome, Outcome::Accepted | Outcome::Approved | Outcome::Generated) || self.replaced {
return Err(Error::Provision("a display offer stores nothing"));
}
} else if self.outcome == Outcome::Confirmed {
return Err(Error::Provision("only a display offer is confirmed"));
}
Ok(())
}
}
impl Vault {
/// Records one outcome, after `ProvisionEntry::check`. Beyond `AUDIT_LIMIT` entries the oldest goes. The
/// caller saves.
pub fn provision_record(&mut self, entry: ProvisionEntry) -> Result<(), Error> {
entry.check()?;
self.provision.push(entry);
trim(&mut self.provision);
Ok(())
}
/// Every outcome, oldest first (newest last).
pub fn provision_audit(&self) -> &[ProvisionEntry] {
&self.provision
}
}
#[cfg(test)]
mod tests {
//! An older reader still opens a vault with the member. It lives here because only the crate can decrypt the
//! body and parse it the way core 0.10.0 did.
use super::*;
use crate::format::Header;
use crate::{FactorJson, Item, ItemType, KdfParams, SecretString, crypto, identity, signing};
/// The body as core 0.10.0 parsed it (src/lib.rs `Body` at v0.10.0): no `provision`.
#[derive(Deserialize)]
#[allow(dead_code)]
struct BodyV0_10 {
format: u32,
items: Vec<Item>,
#[serde(default)]
factors: Vec<FactorJson>,
#[serde(default)]
identity: Option<identity::RootJson>,
#[serde(default)]
signing: Option<signing::StoreJson>,
}
fn body_json(v: &Vault) -> String {
let bytes = v.to_bytes().unwrap();
let (header, at) = Header::parse(&bytes).unwrap();
let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap();
String::from_utf8(json.to_vec()).unwrap()
}
fn entry() -> ProvisionEntry {
ProvisionEntry {
at: 1_793_750_000_000,
direction: Direction::Offer,
host: "nixos-vm".into(),
item: "arca/gitea-read-token".into(),
store: Store::Vault,
run: None,
kind: Some("Gitea token, read:repository".into()),
code: "684361".into(),
outcome: Outcome::Accepted,
replaced: true,
}
}
#[test]
fn an_older_reader_opens_a_vault_with_the_provision_audit() {
let mut v =
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.add(Item::new(ItemType::SecureNote, "kept", 1));
// Without entries the body has no trace of the member, so it is byte-for-byte what 0.10.0 wrote.
assert!(!body_json(&v).contains("provision"));
v.provision_record(entry()).unwrap();
let json = body_json(&v);
assert!(json.contains(r#""provision":{"audit":[{"#), "{json}");
// Core 0.10.0's parser takes it and keeps everything it knows.
let old: BodyV0_10 = serde_json::from_str(&json).unwrap();
assert_eq!(old.format, 1);
assert_eq!(old.items.len(), 1);
assert_eq!(old.items[0].title, "kept");
assert!(old.identity.is_none() && old.signing.is_none());
}
}
+150
View File
@@ -0,0 +1,150 @@
//! The recovery key (docs/FACTORS.md, "The recovery key"): one long random key per vault that opens it alone, for
//! the day the factors are gone. It is printed once and kept on paper. It is never an everyday unlock:
//! [`crate::Vault::recover`] is the only call that takes it, and it replaces every factor before it returns.
use crate::Error;
use crate::secret::SecretString;
use data_encoding::BASE32_NOPAD;
use sha2::{Digest, Sha256};
use std::fmt;
use zeroize::Zeroizing;
pub(crate) const ID_LEN: usize = 4;
pub(crate) const MATERIAL_LEN: usize = 32;
const CHECK_LEN: usize = 4;
const CHECK_CONTEXT: &[u8] = b"custos recovery key v1";
/// 40 bytes as base32: 64 characters, written as 8 groups of 8.
const TEXT_LEN: usize = 64;
const GROUP: usize = 8;
/// A recovery key as it is printed. `Debug` never shows it.
pub struct RecoveryKey {
id: String,
text: Zeroizing<String>,
}
impl RecoveryKey {
/// Which key this is (8 hex characters): not secret, shown in Settings and printed next to the key.
pub fn id(&self) -> &str {
&self.id
}
/// The key: 8 groups of 8 characters, `A-Z` and `2-7`.
pub fn expose(&self) -> &str {
&self.text
}
}
impl fmt::Debug for RecoveryKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RecoveryKey({}, [redacted])", self.id)
}
}
pub(crate) fn id_hex(id: &[u8; ID_LEN]) -> String {
id.iter().map(|b| format!("{b:02x}")).collect()
}
fn check(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> [u8; CHECK_LEN] {
let mut h = Sha256::new();
h.update(CHECK_CONTEXT);
h.update(id);
h.update(material);
let d = h.finalize();
[d[0], d[1], d[2], d[3]]
}
pub(crate) fn encode(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> RecoveryKey {
let mut raw = Zeroizing::new([0u8; ID_LEN + MATERIAL_LEN + CHECK_LEN]);
raw[..ID_LEN].copy_from_slice(id);
raw[ID_LEN..ID_LEN + MATERIAL_LEN].copy_from_slice(material);
raw[ID_LEN + MATERIAL_LEN..].copy_from_slice(&check(id, material));
let flat = Zeroizing::new(BASE32_NOPAD.encode(raw.as_ref()));
let mut text = Zeroizing::new(String::with_capacity(TEXT_LEN + TEXT_LEN / GROUP));
for (i, c) in flat.chars().enumerate() {
if i > 0 && i % GROUP == 0 {
text.push('-');
}
text.push(c);
}
RecoveryKey { id: id_hex(id), text }
}
/// The id and the material of a typed key. Case, spaces and hyphens do not matter; a key that is too short, too
/// long, has another character or fails its check is `RecoveryKeyMistyped`, before any vault is touched.
pub(crate) fn decode(text: &SecretString) -> Result<([u8; ID_LEN], Zeroizing<[u8; MATERIAL_LEN]>), Error> {
let mut flat = Zeroizing::new(String::with_capacity(TEXT_LEN));
for c in text.expose().chars() {
match c {
' ' | '-' | '\t' | '\r' | '\n' => {}
c if c.is_ascii_alphanumeric() && flat.len() < TEXT_LEN + 1 => flat.push(c.to_ascii_uppercase()),
_ => return Err(Error::RecoveryKeyMistyped),
}
}
if flat.len() != TEXT_LEN {
return Err(Error::RecoveryKeyMistyped);
}
let raw = Zeroizing::new(BASE32_NOPAD.decode(flat.as_bytes()).map_err(|_| Error::RecoveryKeyMistyped)?);
if raw.len() != ID_LEN + MATERIAL_LEN + CHECK_LEN {
return Err(Error::RecoveryKeyMistyped);
}
let id: [u8; ID_LEN] = raw[..ID_LEN].try_into().expect("checked");
let mut material = Zeroizing::new([0u8; MATERIAL_LEN]);
material.copy_from_slice(&raw[ID_LEN..ID_LEN + MATERIAL_LEN]);
if raw[ID_LEN + MATERIAL_LEN..] != check(&id, &material) {
return Err(Error::RecoveryKeyMistyped);
}
Ok((id, material))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_printed_key_reads_back_however_it_is_typed() {
let key = encode(&[0xa1, 0xb2, 0xc3, 0xd4], &[9; 32]);
assert_eq!(key.id(), "a1b2c3d4");
let text = key.expose().to_owned();
assert_eq!(text.len(), 64 + 7);
assert!(
text.split('-')
.all(|g| g.len() == 8 && g.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
);
for typed in
[text.clone(), text.to_lowercase(), text.replace('-', " "), text.replace('-', ""), format!(" {text}\r\n")]
{
let (id, material) = decode(&SecretString::from(typed.as_str())).unwrap();
assert_eq!((id, *material), ([0xa1, 0xb2, 0xc3, 0xd4], [9; 32]));
}
assert_eq!(format!("{key:?}"), "RecoveryKey(a1b2c3d4, [redacted])");
}
#[test]
fn a_mistyped_key_is_told_apart_before_any_vault_is_touched() {
let text = encode(&[1, 2, 3, 4], &[9; 32]).expose().to_owned();
let mistyped = |s: String| matches!(decode(&SecretString::from(s.as_str())), Err(Error::RecoveryKeyMistyped));
// One character changed, anywhere: the check catches it.
for at in [0usize, 7, 40, 70] {
let mut chars: Vec<char> = text.chars().collect();
if chars[at] == '-' {
continue;
}
chars[at] = if chars[at] == 'A' { 'B' } else { 'A' };
assert!(mistyped(chars.into_iter().collect()), "position {at}");
}
// Two groups swapped, a group missing, one too many, a character that is never in a key.
let groups: Vec<&str> = text.split('-').collect();
let mut swapped = groups.clone();
swapped.swap(2, 6);
if swapped != groups {
assert!(mistyped(swapped.join("-")));
}
assert!(mistyped(groups[1..].join("-")));
assert!(mistyped(format!("{text}-AAAAAAAA")));
assert!(mistyped(text.replacen(|c: char| c != '-', "1", 1)));
assert!(mistyped(text.replacen('-', "_", 1)));
assert!(mistyped(String::new()));
assert!(mistyped("A".repeat(100_000)));
}
}
+52
View File
@@ -57,3 +57,55 @@ impl<'de> Deserialize<'de> for SecretString {
String::deserialize(d).map(Self::new)
}
}
/// Bytes that are wiped from memory when dropped and never printed (an attachment's content).
/// `Debug` gives `[redacted]`; serialized as base64.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SecretBytes(Zeroizing<Vec<u8>>);
impl SecretBytes {
pub fn new(b: Vec<u8>) -> Self {
Self(Zeroizing::new(b))
}
/// The content. Keep the borrow short.
pub fn expose(&self) -> &[u8] {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<&[u8]> for SecretBytes {
fn from(b: &[u8]) -> Self {
Self::new(b.to_vec())
}
}
impl fmt::Debug for SecretBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl Serialize for SecretBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&Zeroizing::new(data_encoding::BASE64.encode(&self.0)))
}
}
impl<'de> Deserialize<'de> for SecretBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = Zeroizing::new(String::deserialize(d)?);
data_encoding::BASE64
.decode(s.as_bytes())
.map(Self::new)
.map_err(|_| serde::de::Error::custom("attachment data is not base64"))
}
}
+922
View File
@@ -0,0 +1,922 @@
//! The security level and the hardening checklist (docs/FORMAT.md, "The security member"): the vault body member
//! `security`. The level is computed from the Setup window and the ticked items, never stored; every change is in an
//! append-only audit. Nothing here is secret.
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
use crate::{Error, Vault};
/// The log keeps the newest this many entries.
pub const AUDIT_LIMIT: usize = 5_000;
/// How long Setup lasts from *Connect via SSH*, in milliseconds: 2 hours.
pub const SETUP_WINDOW: i64 = 2 * 60 * 60 * 1000;
/// A checklist item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Item {
/// Move the Authelia TOTP to my phone.
TotpOnPhone,
/// Approve with Windows Hello.
HelloApprovals,
/// Narrow the server scope.
NarrowScope,
/// Rotate what setup made.
RotateSetup,
/// Turn off Connect via SSH.
NoSsh,
/// The phone approves this PC.
PhoneApproves,
/// Turn off auto-connect (Custos docs/12_hands_off.md).
NoAutoConnect,
/// Never accept unattended: a new connect opens no Setup window.
NoUnattended,
/// Sign only with a card.
CardSigning,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Level {
/// From *Connect via SSH* until 2 hours later or *Finish setup*.
Setup,
/// After Setup, and every vault that never had one.
Standard,
/// Not in Setup, and at least one checklist item ticked.
Hardened,
}
/// How an undo was confirmed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Auth {
Hello,
Password,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Action {
SetupStarted,
SetupFinished,
/// Written by the first change after the window ended on its own.
SetupExpired,
Ticked,
Unticked,
SshConnected,
TotpMoved,
/// Connected by itself at start (`detail`: where and as whom).
AutoConnected,
/// A setup run stored items without a card (`detail`: the run and the item names).
UnattendedStored,
/// One of those items was removed (`detail`: the run and the item).
SetupItemRemoved,
/// Signed without a card (`detail`: the key, the kind, the run and the file).
UnattendedSigned,
/// *Take over the vault*: a master password added, the PC-only access removed.
TakenOver,
/// A standing approval was granted on a card (core 0.16.0; `detail`: the rule's repository, key, kind, pipeline
/// and origin). Written by [`Vault::standing_grant`] only.
StandingGranted,
/// A standing approval was revoked (`detail`: the same). Written by [`Vault::standing_revoke`] only.
StandingRevoked,
/// A recovery key was made (core 0.17.0; `detail`: the key's id, never the key). Written by
/// [`Vault::recovery_create`] only.
RecoveryCreated,
/// The recovery key was removed (`detail`: its id). Written by [`Vault::recovery_remove`] only.
RecoveryRemoved,
/// The vault was opened with its recovery key: every factor and the key were replaced (`detail`: the used
/// key's id). Written by [`Vault::recover`] only.
Recovered,
}
/// What *Connect via SSH* needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SshRule {
/// Offered, one click (Setup).
Allowed,
/// Offered after Windows Hello or the master password.
NeedsAuth,
/// Not offered (*Turn off Connect via SSH* is ticked).
Off,
}
/// A Setup window, Unix milliseconds: Setup holds for `started <= now < until`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Window {
pub started: i64,
pub until: i64,
}
/// The server scope prefixes *Narrow the server scope* replaced, kept for its undo.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeptScope {
#[serde(default)]
pub ask: Vec<String>,
#[serde(default)]
pub offer: Vec<String>,
}
/// One audit entry. Append-only: nothing edits or removes one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecurityEntry {
/// Unix milliseconds.
pub at: i64,
pub action: Action,
/// The checklist item, for `ticked` and `unticked`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub item: Option<Item>,
/// How an undo was confirmed, for `unticked`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<Auth>,
/// What a note says (`auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`): names,
/// never a value. At most 500 characters, no control characters.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
/// Everything *Settings → Security* shows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SecurityView {
pub level: Level,
/// The last Setup window, if there was one.
pub setup: Option<Window>,
/// When that window ended (Finish setup, or `until` once its expiry was noticed).
pub finished: Option<i64>,
/// Milliseconds of Setup left, while in Setup.
pub setup_remaining: Option<i64>,
pub ticked: BTreeSet<Item>,
pub kept_scope: Option<KeptScope>,
/// Oldest first.
pub audit: Vec<SecurityEntry>,
}
/// The member as the vault keeps it, and as it is written.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct State {
#[serde(default, skip_serializing_if = "Option::is_none")]
setup: Option<Window>,
#[serde(default, skip_serializing_if = "Option::is_none")]
finished: Option<i64>,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
ticked: BTreeSet<Item>,
#[serde(default, skip_serializing_if = "Option::is_none")]
kept_scope: Option<KeptScope>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
audit: Vec<SecurityEntry>,
}
/// At most this many prefixes on each side of a kept scope.
const KEPT_MAX: usize = 64;
/// A kept scope prefix: 1 to 200 characters, no control characters. The error names the rule, never the value.
fn kept_ok(list: &[String]) -> Result<(), Error> {
if list.len() > KEPT_MAX {
return Err(Error::Security("a kept scope has at most 64 prefixes on each side"));
}
if list.iter().any(|p| !(1..=200).contains(&p.chars().count()) || p.chars().any(char::is_control)) {
return Err(Error::Security("a kept scope prefix is 1 to 200 characters without control characters"));
}
Ok(())
}
/// A note's detail: 1 to 500 characters, no control characters. The error names the rule, never the text.
fn detail_ok(d: &str) -> Result<(), Error> {
if !(1..=500).contains(&d.chars().count()) || d.chars().any(char::is_control) {
return Err(Error::Security("a note is 1 to 500 characters without control characters"));
}
Ok(())
}
fn trim(audit: &mut Vec<SecurityEntry>) {
if audit.len() > AUDIT_LIMIT {
audit.drain(..audit.len() - AUDIT_LIMIT);
}
}
impl State {
/// The member as read, checked; `None` when it breaks a rule (the vault then does not open).
pub(crate) fn from_json(j: Option<State>) -> Option<State> {
let mut st = j.unwrap_or_default();
if let Some(w) = st.setup
&& w.until <= w.started
{
return None;
}
if st.finished.is_some() && st.setup.is_none() {
return None;
}
if let Some(k) = &st.kept_scope
&& (kept_ok(&k.ask).is_err() || kept_ok(&k.offer).is_err())
{
return None;
}
trim(&mut st.audit);
Some(st)
}
/// Absent while nothing was ever set, so a vault without it is written exactly as before.
pub(crate) fn json(&self) -> Option<State> {
(*self != State::default()).then(|| self.clone())
}
/// Setup holds for `started <= now < until` of a window that has not finished.
fn in_setup(&self, now: i64) -> bool {
self.finished.is_none() && self.setup.is_some_and(|w| w.started <= now && now < w.until)
}
fn level(&self, now: i64) -> Level {
if self.in_setup(now) {
Level::Setup
} else if self.ticked.is_empty() {
Level::Standard
} else {
Level::Hardened
}
}
fn push(&mut self, at: i64, action: Action, item: Option<Item>, auth: Option<Auth>) {
self.audit.push(SecurityEntry { at, action, item, auth, detail: None });
trim(&mut self.audit);
}
/// Whether a checklist item is ticked.
pub(crate) fn is_ticked(&self, item: Item) -> bool {
self.ticked.contains(&item)
}
/// `standing-granted` or `standing-revoked`, with the rule as its detail (cut to what a note may hold).
pub(crate) fn standing_note(&mut self, action: Action, detail: &str, now: i64) {
debug_assert!(matches!(action, Action::StandingGranted | Action::StandingRevoked));
let detail: String = detail.chars().filter(|c| !c.is_control()).take(500).collect();
self.notice_expiry(now);
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail) });
trim(&mut self.audit);
}
/// `recovery-created`, `recovery-removed` or `recovered`, with the key's id as its detail.
pub(crate) fn recovery_note(&mut self, action: Action, id: &str, now: i64) {
debug_assert!(matches!(action, Action::RecoveryCreated | Action::RecoveryRemoved | Action::Recovered));
self.notice_expiry(now);
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(id.to_owned()) });
trim(&mut self.audit);
}
/// Before any change: a window that ended on its own is written down once, as `setup-expired` at `now` and
/// `finished` = `until`.
fn notice_expiry(&mut self, now: i64) {
if let Some(w) = self.setup
&& self.finished.is_none()
&& now >= w.until
{
self.finished = Some(w.until);
self.push(now, Action::SetupExpired, None, None);
}
}
}
/// *Accept all* on a run card: only in Setup, for a setup run (its id starts with `setup-`) that holds Provisio
/// lines only.
pub fn accept_all_allowed(level: Level, run_id: &str, only_provision: bool) -> bool {
level == Level::Setup && run_id.starts_with("setup-") && only_provision
}
/// Whether a line that replaces a stored item starts ticked: only where *Accept all* applies (a setup run in
/// Setup); otherwise Mark ticks it himself.
pub fn replacing_line_preticked(level: Level, setup_run: bool) -> bool {
level == Level::Setup && setup_run
}
/// What *Connect via SSH* needs: off when *Turn off Connect via SSH* is ticked, one click in Setup, Windows Hello or
/// the master password otherwise.
pub fn ssh_needs_auth(level: Level, ticked: &BTreeSet<Item>) -> SshRule {
if ticked.contains(&Item::NoSsh) {
SshRule::Off
} else if level == Level::Setup {
SshRule::Allowed
} else {
SshRule::NeedsAuth
}
}
/// Whether a server may offer a TOTP seed into the vault: not once it was moved to the phone.
pub fn totp_offer_allowed(ticked: &BTreeSet<Item>) -> bool {
!ticked.contains(&Item::TotpOnPhone)
}
/// The Provisio namespaces a setup run may fill without a card (Custos docs/12_hands_off.md, section 3).
pub const UNATTENDED_NAMESPACES: [&str; 5] = ["arca/", "custos/", "fabrica/", "aula/", "gitea/"];
/// A setup run's id: `setup-` and 1 to 58 of `[A-Za-z0-9._-]`.
pub fn is_setup_run(run: &str) -> bool {
run.strip_prefix("setup-").is_some_and(|rest| {
(1..=58).contains(&rest.len()) && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
})
}
/// Whether Custos may connect to the factor service by itself (at start, with no device token).
pub fn auto_connect_allowed(level: Level, ticked: &BTreeSet<Item>) -> bool {
level != Level::Hardened && !ticked.contains(&Item::NoAutoConnect) && !ticked.contains(&Item::NoSsh)
}
/// Whether a new connection opens the Setup window.
pub fn setup_on_connect(ticked: &BTreeSet<Item>) -> bool {
!ticked.contains(&Item::NoUnattended) && !ticked.contains(&Item::NoSsh)
}
/// Ask or offer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verb {
Ask,
Offer,
}
/// Where a Provisio line goes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Store {
Vault,
Claude,
Display,
}
/// A Provisio line as the unattended rule sees it.
#[derive(Debug, Clone, Copy)]
pub struct ProvisionAsk<'a> {
pub verb: Verb,
/// `--generate`: Custos makes the value.
pub generate: bool,
/// The item exists already (an ask would read it, an offer would replace it).
pub exists: bool,
pub store: Store,
pub item: &'a str,
/// An offer of kind `totp`.
pub totp: bool,
}
/// Whether a Provisio line is answered without a card: a setup run, in Setup, new items in the allowed namespaces.
pub fn unattended_provision(level: Level, ticked: &BTreeSet<Item>, run: &str, req: &ProvisionAsk) -> bool {
if level != Level::Setup || !is_setup_run(run) || ticked.contains(&Item::NoUnattended) || req.exists {
return false;
}
if req.totp && !totp_offer_allowed(ticked) {
return false;
}
match (req.store, req.verb) {
// The Claude Code store takes the names the server offers; it is never read this way.
(Store::Claude, Verb::Offer) => true,
(Store::Vault, Verb::Ask) if !req.generate => false,
(Store::Vault, _) => UNATTENDED_NAMESPACES
.iter()
.any(|ns| req.item.strip_prefix(ns).is_some_and(|rest| !rest.is_empty() && !rest.contains(".."))),
_ => false,
}
}
/// Whether a run's signature is made without a card: a machine-key vault (not taken over), the release kinds.
pub fn unattended_sign(
level: Level,
ticked: &BTreeSet<Item>,
machine_key_vault: bool,
kind: &str,
has_run: bool,
) -> bool {
machine_key_vault
&& has_run
&& level != Level::Hardened
&& !ticked.contains(&Item::CardSigning)
&& matches!(kind, "minisign" | "manifest" | "authenticode" | "approval")
}
/// Whether *Sign & release*, *Accept*, *Accept all* and approvals ask for Windows Hello first.
pub fn hello_for_approvals(ticked: &BTreeSet<Item>) -> bool {
ticked.contains(&Item::HelloApprovals)
}
impl Vault {
/// The level at `now` (Unix milliseconds).
pub fn security_level(&self, now: i64) -> Level {
self.security.level(now)
}
/// The level, the Setup window and what is left of it, the ticked items, the kept scope and the audit.
pub fn security_view(&self, now: i64) -> SecurityView {
let st = &self.security;
SecurityView {
level: st.level(now),
setup: st.setup,
finished: st.finished,
setup_remaining: st.setup.filter(|_| st.in_setup(now)).map(|w| w.until - now),
ticked: st.ticked.clone(),
kept_scope: st.kept_scope.clone(),
audit: st.audit.clone(),
}
}
/// Starts Setup (*Connect via SSH*): a window of 2 hours from `now`, audited `setup-started`. While in Setup it
/// changes nothing and returns the window that holds. The caller saves.
pub fn security_start_setup(&mut self, now: i64) -> Window {
let st = &mut self.security;
st.notice_expiry(now);
if st.in_setup(now)
&& let Some(w) = st.setup
{
return w;
}
let w = Window { started: now, until: now.saturating_add(SETUP_WINDOW) };
st.setup = Some(w);
st.finished = None;
st.push(now, Action::SetupStarted, None, None);
w
}
/// *Finish setup*: ends the window at `now`, audited `setup-finished`. False when not in Setup. The caller saves.
pub fn security_finish_setup(&mut self, now: i64) -> bool {
let st = &mut self.security;
st.notice_expiry(now);
if !st.in_setup(now) {
return false;
}
st.finished = Some(now);
st.push(now, Action::SetupFinished, None, None);
true
}
/// Ticks a checklist item, audited `ticked`. False (and no entry) when it was ticked already. The caller saves.
pub fn security_tick(&mut self, item: Item, now: i64) -> bool {
let st = &mut self.security;
st.notice_expiry(now);
if !st.ticked.insert(item) {
return false;
}
st.push(now, Action::Ticked, Some(item), None);
true
}
/// Unticks a checklist item after Windows Hello or the master password, audited `unticked` with how. False (and
/// no entry) when it was not ticked. The caller saves.
pub fn security_untick(&mut self, item: Item, auth: Auth, now: i64) -> bool {
let st = &mut self.security;
st.notice_expiry(now);
if !st.ticked.remove(&item) {
return false;
}
st.push(now, Action::Unticked, Some(item), Some(auth));
true
}
/// Keeps the scope prefixes *Narrow the server scope* replaces. Refused when a scope is kept already (its undo
/// has not taken it back), so the first prefixes are never lost. The caller saves.
pub fn security_keep_scope(&mut self, ask: &[String], offer: &[String]) -> Result<(), Error> {
if self.security.kept_scope.is_some() {
return Err(Error::Security("a scope is kept already; take it back first"));
}
kept_ok(ask)?;
kept_ok(offer)?;
self.security.kept_scope = Some(KeptScope { ask: ask.to_vec(), offer: offer.to_vec() });
Ok(())
}
/// Takes the kept prefixes back, for the undo. The caller saves.
pub fn security_take_kept_scope(&mut self) -> Option<KeptScope> {
self.security.kept_scope.take()
}
/// Records a note with its detail: `auto-connected`, `unattended-stored`, `setup-item-removed` or
/// `unattended-signed`. The caller saves.
pub fn security_note(&mut self, action: Action, detail: &str, now: i64) -> Result<(), Error> {
if !matches!(
action,
Action::AutoConnected | Action::UnattendedStored | Action::SetupItemRemoved | Action::UnattendedSigned
) {
return Err(Error::Security(
"only auto-connected, unattended-stored, setup-item-removed and unattended-signed are notes",
));
}
detail_ok(detail)?;
let st = &mut self.security;
st.notice_expiry(now);
st.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail.to_owned()) });
trim(&mut st.audit);
Ok(())
}
/// The take-over's half in this member: ticks the items that end unattended work and writes `taken-over`.
pub(crate) fn security_taken_over(&mut self, now: i64) {
self.security.notice_expiry(now);
for item in [Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning] {
self.security_tick(item, now);
}
self.security.push(now, Action::TakenOver, None, None);
}
/// Records `ssh-connected` or `totp-moved`; the other actions are written by the calls above. The caller saves.
pub fn security_record(&mut self, action: Action, item: Option<Item>, now: i64) -> Result<(), Error> {
if !matches!(action, Action::SshConnected | Action::TotpMoved) {
return Err(Error::Security("only ssh-connected and totp-moved are recorded directly"));
}
let st = &mut self.security;
st.notice_expiry(now);
st.push(now, action, item, None);
Ok(())
}
}
#[cfg(test)]
mod tests {
//! An older reader still opens a vault with the member, and unknown values make the vault refuse to open. They
//! live here because only the crate can decrypt the body, change it and seal it again.
use super::*;
use crate::format::Header;
use crate::{FactorJson, Item as VaultItem, ItemType, KdfParams, SecretString, crypto, identity, provision};
const NOW: i64 = 1_793_750_000_000;
fn vault() -> Vault {
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap()
}
fn body_json(v: &Vault) -> String {
let bytes = v.to_bytes().unwrap();
let (header, at) = Header::parse(&bytes).unwrap();
let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap();
String::from_utf8(json.to_vec()).unwrap()
}
/// The vault's file with its body replaced by `json`, sealed with the vault's key as `to_bytes` does.
fn with_body(v: &Vault, json: &str) -> Vec<u8> {
let bytes = v.to_bytes().unwrap();
let (header, at) = Header::parse(&bytes).unwrap();
let mut out = bytes[..at].to_vec();
out.extend_from_slice(&crypto::seal(&v.key, &header.body_nonce, json.as_bytes(), &bytes[..at]));
out
}
// ---- the body as core 0.11.0 parsed it (src/lib.rs, src/signing.rs, src/provision.rs at v0.11.0) ----
#[derive(Deserialize)]
#[allow(dead_code)]
struct BodyV0_11 {
format: u32,
items: Vec<VaultItem>,
#[serde(default)]
factors: Vec<FactorJson>,
#[serde(default)]
identity: Option<identity::RootJson>,
#[serde(default)]
signing: Option<SigningV0_11>,
#[serde(default)]
provision: Option<ProvisionV0_11>,
}
#[derive(Deserialize)]
#[allow(dead_code)]
struct SigningV0_11 {
#[serde(default)]
keys: Vec<KeyV0_11>,
#[serde(default)]
audit: Vec<SignEntryV0_11>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct KeyV0_11 {
id: String,
kind: OldKeyKind,
role: OldRole,
name: String,
created: i64,
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
enum OldKeyKind {
Ed25519,
RootCa,
CodeSigning,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum OldRole {
Release,
Test,
}
#[derive(Deserialize)]
#[allow(dead_code)]
struct SignEntryV0_11 {
at: i64,
key: String,
kind: OldSignKind,
outcome: OldSignOutcome,
via: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum OldSignKind {
Minisign,
Manifest,
Authenticode,
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
enum OldSignOutcome {
Approved,
Auto,
Refused,
Expired,
OutOfScope,
Invalid,
}
#[derive(Deserialize)]
#[allow(dead_code)]
struct ProvisionV0_11 {
#[serde(default)]
audit: Vec<ProvisionEntryV0_11>,
}
#[derive(Deserialize)]
#[allow(dead_code)]
struct ProvisionEntryV0_11 {
store: OldStore,
outcome: OldProvisionOutcome,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum OldStore {
Vault,
Claude,
Cloud,
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
enum OldProvisionOutcome {
Approved,
Generated,
Accepted,
Refused,
OutOfScope,
Invalid,
Expired,
}
fn display_entry(outcome: provision::Outcome) -> provision::ProvisionEntry {
provision::ProvisionEntry {
at: NOW,
direction: provision::Direction::Offer,
host: "nixos-vm".into(),
item: "arca/authelia-mark".into(),
store: provision::Store::Display,
run: None,
kind: Some("totp".into()),
code: "684361".into(),
outcome,
replaced: false,
}
}
#[test]
fn an_older_reader_opens_a_vault_with_the_security_member() {
let mut v = vault();
v.add(VaultItem::new(ItemType::SecureNote, "kept", 1));
// Never set: the body has no trace of the member, so it is byte-for-byte what 0.11.0 wrote.
assert!(!body_json(&v).contains("security"));
v.security_start_setup(NOW);
v.security_tick(Item::HelloApprovals, NOW + 1);
v.security_untick(Item::HelloApprovals, Auth::Hello, NOW + 2);
v.security_tick(Item::NoSsh, NOW + 3);
v.security_keep_scope(&["arca/".to_string()], &[]).unwrap();
v.security_record(Action::SshConnected, None, NOW + 4).unwrap();
let json = body_json(&v);
assert!(json.contains(r#""security":{"setup":{"started":"#), "{json}");
assert!(json.contains(r#""ticked":["no-ssh"]"#) && json.contains(r#""keptScope":{"ask":["arca/"]"#), "{json}");
// Core 0.11.0's parser takes it and keeps everything it knows.
let old: BodyV0_11 = serde_json::from_str(&json).unwrap();
assert_eq!(old.items.len(), 1);
assert_eq!(old.items[0].title, "kept");
// And this core reads it back the same.
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.security_view(NOW + 5), v.security_view(NOW + 5));
}
#[test]
fn an_older_reader_opens_a_vault_with_the_approval_key_and_runs_but_not_approval_entries() {
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
let mut v = vault();
v.signing_create(Role::Release, &["*".to_string()], &["*".to_string()], NOW).unwrap();
let mut r = Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-42".into()),
context: Context { file: "a.exe".into(), version: "0.7.0".into(), ..Default::default() },
via: Via::Local,
};
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
v.provision_record(provision::ProvisionEntry {
store: provision::Store::Vault,
outcome: provision::Outcome::Accepted,
..display_entry(provision::Outcome::Accepted)
})
.unwrap();
let json = body_json(&v);
assert!(json.contains(r#""id":"domi-approve""#) && json.contains(r#""run":"r-42""#), "{json}");
assert!(serde_json::from_str::<BodyV0_11>(&json).is_ok(), "the new key and members are ignored");
// An approval entry is a kind 0.11.0 does not know: it refuses the vault (docs/FORMAT.md).
r.key = "domi-approve".into();
r.kind = SignKind::Approval;
r.digest = vec![];
v.signing_refuse(&r, crate::signing::Outcome::Refused, None, NOW + 1);
assert!(serde_json::from_str::<BodyV0_11>(&body_json(&v)).is_err());
}
#[test]
fn an_older_reader_refuses_display_and_confirmed() {
for (store, outcome) in [
(provision::Store::Display, provision::Outcome::Refused),
(provision::Store::Display, provision::Outcome::Confirmed),
] {
let mut v = vault();
v.provision_record(provision::ProvisionEntry { store, ..display_entry(outcome) }).unwrap();
assert!(serde_json::from_str::<BodyV0_11>(&body_json(&v)).is_err(), "{store:?} {outcome:?}");
// This core reads it.
assert!(Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).is_ok());
}
}
/// A vault whose release key has signed once and has one standing approval, used once (core 0.16.0).
fn vault_with_a_standing_approval() -> Vault {
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
let mut v = vault();
v.signing_create(Role::Release, &["release".to_string()], &["Arca".to_string()], NOW).unwrap();
let r = Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-42".into()),
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
};
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
v.standing_grant(&r, NOW + 1).unwrap();
v.signing_sign(&r, Approval::Standing, NOW + 2).unwrap();
v
}
#[test]
fn an_older_reader_refuses_a_vault_in_which_a_standing_approval_was_granted() {
let v = vault_with_a_standing_approval();
let json = body_json(&v);
assert!(json.contains(r#""standing":[{"id":""#) && json.contains(r#""outcome":"standing""#), "{json}");
assert!(json.contains(r#""action":"standing-granted""#), "{json}");
// Core 0.11.0 does not know the outcome or the action: it refuses the file rather than misread it.
assert!(serde_json::from_str::<BodyV0_11>(&json).is_err());
// The rules alone it would ignore: with the outcome it knows, its signing parser takes the member.
let plain = json.replace(r#""outcome":"standing""#, r#""outcome":"approved""#);
let body: serde_json::Value = serde_json::from_str(&plain).unwrap();
let old: SigningV0_11 = serde_json::from_value(body["signing"].clone()).unwrap();
assert_eq!(old.audit.len(), 2);
// This core reads it back the same.
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.standing_rules(), v.standing_rules());
assert_eq!(back.standing_rules()[0].uses, 1);
}
#[test]
fn a_rule_whose_count_is_at_its_end_still_signs() {
use crate::signing::{Approval, Context, Request, SignKind, Via};
let v = vault_with_a_standing_approval();
let json = body_json(&v).replace(r#""uses":1"#, r#""uses":18446744073709551615"#);
let mut full = Vault::open(&with_body(&v, &json), &SecretString::from("pw")).unwrap();
let r = Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-43".into()),
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
};
full.signing_sign(&r, Approval::Standing, NOW + 9).expect("signed, not a panic");
assert_eq!(full.standing_rules()[0].uses, u64::MAX);
}
#[test]
fn a_broken_android_grant_makes_the_vault_refuse_to_open() {
let mut v = vault();
v.android_grant_set(&["mnovak/*".to_string()], "Marek Novak", "CZ", NOW).unwrap();
let json = body_json(&v);
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
let from = r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ""#;
assert!(json.contains(from), "{json}");
for to in [
r#""repos":["*/*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":["*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":[],"o":"Marek Novak","c":"CZ""#,
r#""repos":["mnovak/*","mnovak/*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":["mnovak/*"],"o":"","c":"CZ""#,
r#""repos":["mnovak/*"],"o":"Marek Novak","c":"Czech""#,
r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ","made":["Not An Id"]"#,
] {
let bad = json.replacen(from, to, 1);
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
}
}
#[test]
fn a_broken_standing_approval_makes_the_vault_refuse_to_open() {
let v = vault_with_a_standing_approval();
let json = body_json(&v);
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
let id = v.standing_rules()[0].id.clone();
let shape = r#""kind":"minisign","pipeline":"release","via":"local""#;
let cases = [
// A rule edited to name another repository, pipeline, kind or origin no longer has its id.
(
r#""repo":"Arca","key":"domi-release","keyCreated""#.to_string(),
r#""repo":"Fabrica","key":"domi-release","keyCreated""#.to_string(),
),
(shape.to_string(), r#""kind":"minisign","pipeline":"deploy","via":"local""#.to_string()),
(shape.to_string(), r#""kind":"apk","pipeline":"release","via":"local""#.to_string()),
(shape.to_string(), r#""kind":"minisign","pipeline":"release","via":"remote""#.to_string()),
(shape.to_string(), r#""kind":"sigstore","pipeline":"release","via":"local""#.to_string()),
(format!(r#""id":"{id}""#), r#""id":"0000000000000000""#.to_string()),
// Targets belong to approvals only.
(
r#""via":"local","granted""#.to_string(),
r#""via":"local","targets":["deploy to nixos-vm"],"granted""#.to_string(),
),
];
for (from, to) in cases {
assert!(json.contains(&from), "{from} in {json}");
let bad = json.replacen(&from, &to, 1);
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
}
}
#[test]
fn unknown_or_broken_security_values_make_the_vault_refuse_to_open() {
let mut v = vault();
v.security_start_setup(NOW);
v.security_tick(Item::NoSsh, NOW + 1);
v.security_untick(Item::NoSsh, Auth::Password, NOW + 2);
v.security_tick(Item::RotateSetup, NOW + 3);
v.security_keep_scope(&["arca/".to_string()], &["fabrica/".to_string()]).unwrap();
let json = body_json(&v);
// The file as written opens.
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
let until = format!(r#""until":{}"#, NOW + SETUP_WINDOW);
let cases = [
(r#""ticked":["rotate-setup"]"#, r#""ticked":["rotate-later"]"#.to_string()),
(r#""action":"ticked""#, r#""action":"tocked""#.to_string()),
(r#""auth":"password""#, r#""auth":"pin""#.to_string()),
(r#""item":"no-ssh""#, r#""item":"no-telnet""#.to_string()),
(until.as_str(), format!(r#""until":{NOW}"#)),
(r#""ask":["arca/"]"#, r#""ask":["arca/\n"]"#.to_string()),
(r#""ask":["arca/"]"#, r#""ask":[""]"#.to_string()),
];
for (from, to) in cases {
assert!(json.contains(from), "{from} in {json}");
let bad = json.replacen(from, &to, 1);
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
}
// `finished` without a window.
let mut no_window = json.clone();
let start = no_window.find(r#""setup":{"#).unwrap();
let end = start + no_window[start..].find('}').unwrap() + 2;
no_window.replace_range(start..end, r#""finished":5,"#);
let r = Vault::open(&with_body(&v, &no_window), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{no_window}");
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+265
View File
@@ -0,0 +1,265 @@
//! Android APK signing keys (core 0.14.0, docs/SIGNING.md "apk"): the key and its certificate, the `apk` kind and
//! nothing else, scope, the test-key rules, malformed requests, the audit through a reopen, and never unattended.
//! That no API path returns an Android key's private half is part of the unit test in src/signing.rs.
use std::collections::BTreeSet;
use std::sync::OnceLock;
use custos_vault::security::{self, Level};
use custos_vault::signing::{AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{Error, KdfParams, SecretString, Vault};
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::hazmat::PrehashVerifier;
use x509_cert::der::{Decode, Encode};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const REPO: &str = "mnovak/Postea";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn spec(id: &str, role: Role, pipelines: &[&str], repos: &[&str]) -> AndroidKey {
AndroidKey {
id: id.into(),
name: if role == Role::Release { "Postea Android".into() } else { "Domi test Android".into() },
cn: if role == Role::Release { "Postea".into() } else { "Domi Test Android".into() },
o: if role == Role::Release { "Marek Novak".into() } else { "Domi".into() },
c: "CZ".into(),
role,
pipelines: s(pipelines),
repos: s(repos),
}
}
/// A vault with the release and test sets, `postea-android` (release, `mnovak/Postea`) and `domi-test-android`
/// (test, any). Two RSA-4096 keys are made once and the vault reopened from its bytes for each test.
fn vault() -> Vault {
static BYTES: OnceLock<Vec<u8>> = OnceLock::new();
let bytes = BYTES.get_or_init(|| {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap();
v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap();
v.to_bytes().unwrap()
});
Vault::open(bytes, &SecretString::from("pw")).unwrap()
}
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
Context {
repo: repo.into(),
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: trigger.into(),
file: "Postea-1.0.0.apk".into(),
size: 9_876_543,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "1.0.0".into(),
}
}
fn apk_req(key: &str, digests: usize, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Apk,
digest: (0..digests * 64).map(|i| (i % 251) as u8).collect(),
manifest: None,
approval: None,
run: Some("r-7".into()),
context: c,
via: Via::Local,
}
}
fn release() -> Context {
ctx("release", REPO, "tag")
}
#[test]
fn an_android_key_has_its_certificate_and_no_secret_in_its_view() {
let v = vault();
let keys = v.signing_keys();
let k = keys.iter().find(|k| k.id == "postea-android").unwrap();
assert_eq!((k.kind, k.role, k.auto_approve), (KeyKind::Android, Role::Release, false));
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&[REPO])));
assert_eq!((k.issuer.clone(), k.key_id.clone(), k.minisign_public.clone()), (None, None, None));
let cert = v.signing_export_cert("postea-android").unwrap();
assert_eq!(k.cert.as_deref(), Some(cert.as_slice()));
let c = x509_cert::Certificate::from_der(&cert).unwrap();
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject);
let t = keys.iter().find(|k| k.id == "domi-test-android").unwrap();
assert_eq!((t.kind, t.role, t.auto_approve), (KeyKind::Android, Role::Test, true));
// Both serialise as the closed value `android`.
assert!(serde_json::to_string(k).unwrap().contains(r#""kind":"android""#));
}
#[test]
fn ids_and_names_are_checked_and_an_id_is_made_once() {
let mut v = vault();
let again = v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(again, Err(Error::Signing(m)) if m.contains("already")));
let taken = v.signing_create_android(&spec("domi-release", Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(taken, Err(Error::Signing(_))), "an id of another kind");
for bad in ["", "Postea", "postea android", "postea/android", &"x".repeat(65)] {
let r = v.signing_create_android(&spec(bad, Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(r, Err(Error::Signing(_))), "{bad:?}");
}
let mut odd = spec("odd-android", Role::Release, &["release"], &[REPO]);
odd.c = "Czechia".into();
assert!(matches!(v.signing_create_android(&odd, NOW), Err(Error::Signing(m)) if m.contains("country")));
assert_eq!(v.signing_keys().len(), 9, "nothing was added");
}
#[test]
fn an_apk_request_signs_every_digest_with_sha512_pkcs1_and_the_certificates_key() {
let mut v = vault();
let req = apk_req("postea-android", 2, release());
assert!(v.signing_check(&req).is_ok());
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
assert_eq!(signed.bytes.len(), 2 * 512, "two RSA-4096 signatures");
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("postea-android").unwrap()).unwrap();
let spki = cert.tbs_certificate.subject_public_key_info.to_der().unwrap();
let key = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
for (d, sig) in req.digest.chunks(64).zip(signed.bytes.chunks(512)) {
key.verify_prehash(d, &Signature::try_from(sig).unwrap()).unwrap();
}
// One request, one audit entry, whatever the number of digests.
let a = v.signing_audit().last().unwrap();
assert_eq!((a.key.as_str(), a.kind, a.outcome), ("postea-android", SignKind::Apk, Outcome::Approved));
assert_eq!((a.context.file.as_str(), a.run.as_deref()), ("Postea-1.0.0.apk", Some("r-7")));
}
#[test]
fn an_android_key_signs_only_apks_and_only_android_keys_sign_apks() {
let mut v = vault();
let mut exe = apk_req("postea-android", 0, release());
exe.kind = SignKind::Authenticode;
exe.digest = vec![9; 32];
let mut minisign = exe.clone();
minisign.kind = SignKind::Minisign;
minisign.digest = vec![9; 64];
let leaf = Request {
key: "domi-code-signing".into(),
context: ctx("release", "Arca", "tag"),
..apk_req("", 1, release())
};
let ed =
Request { key: "domi-release".into(), context: ctx("release", "Arca", "tag"), ..apk_req("", 1, release()) };
let root = Request { key: "domi-root".into(), ..apk_req("", 1, release()) };
let test_leaf = Request { key: "domi-test-code-signing".into(), ..apk_req("", 1, ctx("ci", REPO, "push")) };
for r in [&exe, &minisign, &leaf, &ed, &root, &test_leaf] {
assert!(matches!(v.signing_check(r), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
}
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
}
#[test]
fn another_repo_or_pipeline_is_out_of_scope_even_when_approved() {
let mut v = vault();
for c in [ctx("release", "mnovak/Arca", "tag"), ctx("release", "Postea", "tag"), ctx("nightly", REPO, "tag")] {
let r = apk_req("postea-android", 2, c);
assert!(matches!(v.signing_check(&r), Err(Refusal::OutOfScope(_))));
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
}
assert_eq!(v.signing_audit().iter().filter(|e| e.outcome == Outcome::OutOfScope).count(), 3);
}
#[test]
fn the_release_key_always_needs_mark_and_the_test_twin_signs_alone_but_never_a_tag() {
let mut v = vault();
let r = v.signing_sign(&apk_req("postea-android", 2, release()), Approval::Auto, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
let t = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "manual")), Approval::Auto, NOW).unwrap();
assert_eq!(t.bytes.len(), 1024);
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Auto);
let tag = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "tag")), Approval::Auto, NOW);
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
}
#[test]
fn malformed_apk_requests_are_refused() {
let mut v = vault();
let mut cases = Vec::new();
for n in [0usize, 1, 32, 63, 65, 64 * 5] {
let mut r = apk_req("postea-android", 0, release());
r.digest = vec![1; n];
if n != 1 {
cases.push(r);
}
}
let mut no_file = apk_req("postea-android", 2, release());
no_file.context.file = String::new();
let mut path = apk_req("postea-android", 2, release());
path.context.file = "out\\Postea.apk".into();
let mut stray = apk_req("postea-android", 2, release());
stray.approval = Some("{}".into());
let mut bad_run = apk_req("postea-android", 2, release());
bad_run.run = Some("r 7".into());
cases.extend([no_file, path, stray, bad_run]);
for r in &cases {
assert!(
matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))),
"{} bytes {:?}",
r.digest.len(),
r.context.file
);
}
assert_eq!(v.signing_audit().len(), cases.len());
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
}
#[test]
fn refused_and_expired_apk_requests_are_recorded_and_everything_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault();
let req = apk_req("postea-android", 2, release());
v.signing_refuse(&req, Outcome::Refused, Some("Mark refused this signature".into()), NOW);
v.signing_refuse(&req, Outcome::Expired, None, NOW + 1);
let signed = v.signing_sign(&req, Approval::Mark, NOW + 2).unwrap();
v.save(&path).unwrap();
let mut back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
assert_eq!(back.signing_audit(), v.signing_audit());
let outcomes: Vec<Outcome> = back.signing_audit().iter().map(|e| e.outcome).collect();
assert_eq!(outcomes, [Outcome::Refused, Outcome::Expired, Outcome::Approved]);
assert_eq!(back.signing_audit()[2].signature.as_deref(), Some(signed.sha256.as_str()));
assert_eq!(back.signing_keys(), v.signing_keys());
// The same key: a reopened vault makes the same (deterministic PKCS#1 v1.5) signatures.
assert_eq!(back.signing_sign(&req, Approval::Mark, NOW + 3).unwrap().bytes, signed.bytes);
}
#[test]
fn apk_requests_are_never_signed_unattended_even_on_the_hands_off_vault() {
// `unattended_sign` is a closed list of kinds: `apk` is not on it, so an APK always shows the card.
for level in [Level::Setup, Level::Standard] {
assert!(!security::unattended_sign(level, &BTreeSet::new(), true, "apk", true));
assert!(security::unattended_sign(level, &BTreeSet::new(), true, "authenticode", true));
}
}
#[test]
fn an_android_key_made_first_does_not_count_as_the_release_or_test_set() {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap();
v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap();
// No release set yet: there is nothing to add an approval key to, and the Android key is no model for one.
assert!(matches!(v.signing_add_approve(NOW), Err(Error::Signing(_))));
let ids = v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
assert_eq!(ids, ["domi-release", "domi-root", "domi-code-signing", "domi-approve"]);
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
let keys = v.signing_keys();
let approve = keys.iter().find(|k| k.id == "domi-approve").unwrap();
assert_eq!(approve.repos, s(&["Arca"]), "the release set's scope, not Postea's");
assert_eq!(keys.len(), 9);
}
+266
View File
@@ -0,0 +1,266 @@
//! The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): one answer for every Domi app's release
//! APK. It signs a request for a repository's own app key (`<name>-android`, scoped to exactly that repository and
//! `release`) from this PC's pipe, its first signature included, and makes that key when the app's first release
//! asks. Everything else still needs a card.
use custos_vault::security::{Action, Auth, Item};
use custos_vault::signing::{
AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via, android_key_id,
};
use custos_vault::{KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn vault() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["mnovak/Culina"]), NOW).unwrap();
v
}
fn granted(repos: &[&str]) -> Vault {
let mut v = vault();
v.android_grant_set(&s(repos), "Marek Novak", "CZ", NOW).unwrap();
v
}
fn apk(key: &str, repo: &str, pipeline: &str, run: Option<&str>) -> Request {
Request {
key: key.into(),
kind: SignKind::Apk,
digest: vec![5; 64],
manifest: None,
approval: None,
run: run.map(Into::into),
context: Context {
repo: repo.into(),
commit: COMMIT.into(),
pipeline: pipeline.into(),
step: "sign-apk".into(),
trigger: "tag".into(),
file: "Culina-1.2.0.apk".into(),
size: 9_400_000,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "1.2.0".into(),
},
via: Via::Local,
}
}
fn culina(run: &str) -> Request {
apk("culina-android", "mnovak/Culina", "release", Some(run))
}
fn notes(v: &Vault, action: Action) -> Vec<String> {
v.security_view(NOW + 1_000)
.audit
.into_iter()
.filter(|e| e.action == action)
.map(|e| e.detail.unwrap_or_default())
.collect()
}
#[test]
fn an_app_key_is_named_by_its_repository() {
assert_eq!(android_key_id("mnovak/Culina").as_deref(), Some("culina-android"));
assert_eq!(android_key_id("mnovak/domi-office").as_deref(), Some("domi-office-android"));
assert_eq!(android_key_id("mnovak/Domi.Office_2").as_deref(), Some("domi-office-2-android"));
for bad in ["Culina", "mnovak/", "/Culina", "mnovak/*", "a/b/c", "mnovak/Cu lina", "mnovak/Čulina", ""] {
assert_eq!(android_key_id(bad), None, "{bad}");
}
assert_eq!(android_key_id(&format!("mnovak/{}", "x".repeat(57))), None, "the id would be longer than 64");
}
#[test]
fn the_grant_makes_an_apps_key_and_signs_its_first_apk_without_a_card() {
let mut v = granted(&["mnovak/*"]);
assert!(!v.android_grant_fits(&culina("r-1"), NOW + 1), "no key yet");
let id = v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 1).unwrap();
assert_eq!(id, "culina-android");
let k = v.signing_keys().into_iter().find(|k| k.id == id).unwrap();
assert_eq!((k.kind, k.role, k.name.as_str()), (KeyKind::Android, Role::Release, "Culina Android"));
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&["mnovak/Culina"])));
let cert = String::from_utf8_lossy(k.cert.as_ref().unwrap()).into_owned();
assert!(cert.contains("Culina") && cert.contains("Marek Novak"), "the certificate names the app and Mark");
// Its first signature: no card, recorded as `standing`, counted on the grant.
assert!(v.android_grant_fits(&culina("r-1"), NOW + 2));
assert!(v.standing_rule_for(&culina("r-1"), NOW + 2).is_none(), "the grant is not a per-key rule");
let signed = v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2);
assert!(signed.is_ok(), "{signed:?}");
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
assert_eq!(v.signing_audit().last().unwrap().context.file, "Culina-1.2.0.apk");
v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 3).unwrap();
let g = v.android_grant().unwrap();
assert_eq!((g.uses, g.last_used, g.made.clone()), (2, Some(NOW + 3), s(&["culina-android"])));
// Granting, then the key it made: both `standing-granted`, a value cores since 0.16.0 read (core 0.19.1).
let granted_note = notes(&v, Action::StandingGranted);
assert_eq!(granted_note.len(), 2, "{granted_note:?}");
assert!(granted_note[0].contains("Android releases") && granted_note[0].contains("mnovak/*"), "{granted_note:?}");
assert_eq!(granted_note[1], "Android grant made culina-android for mnovak/Culina pipeline release");
// The public note call cannot write it.
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
}
#[test]
fn the_grant_never_makes_a_key_it_does_not_cover() {
let mut v = granted(&["mnovak/Culina", "mnovak/Liber"]);
for (repo, pipeline, via, why) in [
("mnovak/Postea", "release", Via::Local, "a repository no pattern matches"),
("someone/Culina", "release", Via::Local, "another owner"),
("mnovak/Culina", "ci", Via::Local, "another pipeline"),
("mnovak/Culina", "release", Via::Remote, "the server runner"),
("Culina", "release", Via::Local, "not owner/name"),
] {
assert!(v.android_grant_make_key(repo, pipeline, via, NOW + 1).is_err(), "{why}");
}
assert!(v.signing_keys().iter().all(|k| k.kind != KeyKind::Android), "nothing was made");
v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 2).unwrap();
assert!(v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 3).is_err(), "made once");
v.security_tick(Item::CardSigning, NOW + 4);
assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 5).is_err(), "paused");
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 6);
assert!(v.android_grant_revoke(NOW + 7));
assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 8).is_err(), "no grant");
assert_eq!(v.android_grant().map(|g| g.made), None);
}
#[test]
fn only_the_repositorys_own_app_key_in_its_own_scope_from_this_pc_with_a_run_fits() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
// A key of the right name with a wider scope, and one for the wrong repository, made by hand.
let wide = AndroidKey {
id: "liber-android".into(),
name: "Liber Android".into(),
cn: "Liber".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["*"]),
};
v.signing_create_android(&wide, NOW).unwrap();
v.signing_create_android(
&AndroidKey { id: "other-android".into(), repos: s(&["mnovak/Rosea"]), ..wide.clone() },
NOW,
)
.unwrap();
v.signing_create_android(&AndroidKey { id: "domi-test-android".into(), role: Role::Test, ..wide.clone() }, NOW)
.unwrap();
let mut remote = culina("r-1");
remote.via = Via::Remote;
let mut minisign = culina("r-1");
minisign.kind = SignKind::Minisign;
minisign.key = "domi-release".into();
minisign.digest = vec![7; 64];
for (req, why) in [
(remote, "the server runner"),
(apk("culina-android", "mnovak/Culina", "release", None), "no run"),
(apk("liber-android", "mnovak/Liber", "release", Some("r-1")), "a key with a wider scope"),
(apk("other-android", "mnovak/Rosea", "release", Some("r-1")), "not the repository's app key"),
(apk("domi-test-android", "mnovak/Liber", "release", Some("r-1")), "a test key"),
(minisign, "another kind"),
] {
assert!(!v.android_grant_fits(&req, NOW + 1), "{why}");
assert!(v.signing_sign(&req, Approval::Standing, NOW + 1).is_err(), "{why}: never signed without a card");
assert_ne!(v.signing_audit().last().unwrap().outcome, Outcome::Standing, "{why}");
}
assert_eq!(v.android_grant().unwrap().uses, 0);
}
#[test]
fn an_explicit_list_covers_only_its_repositories_and_bad_patterns_are_refused() {
let mut v = granted(&["mnovak/Culina"]);
v.signing_create_android(
&AndroidKey {
id: "liber-android".into(),
name: "Liber Android".into(),
cn: "Liber".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["mnovak/Liber"]),
},
NOW,
)
.unwrap();
let liber = apk("liber-android", "mnovak/Liber", "release", Some("r-1"));
assert!(!v.android_grant_fits(&liber, NOW + 1), "not in the list");
// Editing the list keeps the counts and covers the new repository; a key made by hand in that shape is covered.
v.android_grant_set(&s(&["mnovak/Culina", "mnovak/Liber", "mnovak/Liber"]), "Marek Novak", "CZ", NOW + 2).unwrap();
assert_eq!(v.android_grant().unwrap().repos, s(&["mnovak/Culina", "mnovak/Liber"]));
assert!(v.android_grant_fits(&liber, NOW + 3));
for bad in [&[][..], &["mnovak"], &["*/*"], &["*"], &["mnovak/*/x"], &["mn ovak/*"], &["mnovak/Cu*"]] {
assert!(v.android_grant_set(&s(bad), "Marek Novak", "CZ", NOW + 4).is_err(), "{bad:?}");
}
let many: Vec<String> = (0..65).map(|i| format!("mnovak/app{i}")).collect();
assert!(v.android_grant_set(&many, "Marek Novak", "CZ", NOW + 4).is_err(), "at most 64");
assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "Czech", NOW + 4).is_err(), "a two-letter country");
assert!(v.android_grant_set(&s(&["mnovak/*"]), "", "CZ", NOW + 4).is_err(), "an organisation");
assert_eq!(
v.android_grant().unwrap().repos,
s(&["mnovak/Culina", "mnovak/Liber"]),
"a refused edit changes nothing"
);
}
#[test]
fn sign_only_with_a_card_pauses_the_grant_and_revoking_ends_it() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.security_tick(Item::CardSigning, NOW + 1);
assert!(!v.android_grant_fits(&culina("r-1"), NOW + 2));
assert!(matches!(v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2), Err(Refusal::NeedsApproval(_))));
assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "CZ", NOW + 2).is_err(), "no grant while ticked");
assert!(v.android_grant().is_some(), "kept, paused");
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 3);
assert!(v.android_grant_fits(&culina("r-1"), NOW + 4));
assert!(v.android_grant_revoke(NOW + 5));
assert!(!v.android_grant_revoke(NOW + 6), "once");
assert!(!v.android_grant_fits(&culina("r-2"), NOW + 7));
assert!(matches!(v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 7), Err(Refusal::NeedsApproval(_))));
// Mark still signs it on a card, and the key stays.
assert!(v.signing_sign(&culina("r-2"), Approval::Mark, NOW + 8).is_ok());
let revoked = notes(&v, Action::StandingRevoked);
assert_eq!(revoked.len(), 1);
assert!(revoked[0].contains("Android releases"), "{revoked:?}");
}
#[test]
fn a_standing_rule_for_the_same_request_is_used_first() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.signing_sign(&culina("r-1"), Approval::Mark, NOW + 1).unwrap();
v.standing_grant(&culina("r-2"), NOW + 2).unwrap();
v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).unwrap();
assert_eq!(v.standing_rules()[0].uses, 1);
assert_eq!(v.android_grant().unwrap().uses, 0);
}
#[test]
fn the_grant_and_its_counts_survive_a_reopen() {
let mut v = granted(&["mnovak/*", "domi/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 1).unwrap();
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.android_grant(), v.android_grant());
assert!(back.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).is_ok());
assert_eq!(back.android_grant().unwrap().uses, 2);
assert!(back.android_grant_revoke(NOW + 3));
let again = Vault::open(&back.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(again.android_grant(), None);
}
+31 -7
View File
@@ -86,7 +86,9 @@ fn a_factor_is_added_and_removed_without_the_others() {
// Only the new factor's material is needed: its pairs come from the factor keys in the body.
let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let mut v =
open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE))
.unwrap();
let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect();
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]);
// A lost device: drop its factor; the other two still open, the device no longer helps.
@@ -108,7 +110,8 @@ fn a_forgotten_password_is_replaced_with_two_other_factors() {
let mut v = two_factor_vault();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap();
let mut v =
open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap();
v.change_password(&pw("New9-Password4"), FAST).unwrap();
let bytes2 = v.to_bytes().unwrap();
let dev = || Unlock::Material(FactorKind::Device, &DEVICE);
@@ -168,7 +171,14 @@ fn a_machine_store_opens_with_its_device_key_alone() {
let user = two_factor_vault().to_bytes().unwrap();
assert!(!Vault::is_machine_store(&user).unwrap());
assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors)));
assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err());
assert!(
Vault::open_with(
&bytes,
Unlock::Material(FactorKind::Device, &STORE),
Unlock::Material(FactorKind::Device, &STORE)
)
.is_err()
);
}
#[test]
@@ -178,10 +188,20 @@ fn limits_are_enforced() {
v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap();
}
assert_eq!(v.factors().len(), 8);
assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors)));
assert!(matches!(
v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"),
Err(Error::TooManyFactors)
));
// Every pair still opens with 8 factors (8 factor slots + 28 pair slots).
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok());
assert!(
open(
&bytes,
Unlock::Material(FactorKind::Device, &[100; 32]),
Unlock::Material(FactorKind::Device, &[105; 32])
)
.is_ok()
);
}
#[test]
@@ -190,7 +210,10 @@ fn no_factor_material_in_debug_output() {
let u = Unlock::Material(FactorKind::Device, &secret);
let p = pw("Orbit7-Fable3");
let printed = format!("{u:?} {:?}", Unlock::Password(&p));
assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}");
assert!(
!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"),
"{printed}"
);
let v = two_factor_vault();
let printed = format!("{v:?} {:?}", v.factors());
for f in v.factors() {
@@ -207,7 +230,8 @@ fn the_key_pair_item_type_round_trips() {
k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5);
v.add(k);
let bytes = v.to_bytes().unwrap();
let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let back =
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
}
+210
View File
@@ -0,0 +1,210 @@
//! Hands off (Custos docs/12_hands_off.md): a machine-key vault that Custos opens itself, the rules for auto-connect,
//! the unattended setup run and unattended signing, and *Take over the vault*.
use std::collections::BTreeSet;
use custos_vault::security::{
Action, Item, Level, ProvisionAsk, Store, Verb, auto_connect_allowed, is_setup_run, setup_on_connect,
unattended_provision, unattended_sign,
};
use custos_vault::{Error, FactorKind, KdfParams, SecretString, Unlock, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const PC: [u8; 32] = [7; 32];
fn none() -> BTreeSet<Item> {
BTreeSet::new()
}
fn ticked(items: &[Item]) -> BTreeSet<Item> {
items.iter().copied().collect()
}
// ---------------------------------------------------------------- take over
#[test]
fn a_machine_key_vault_is_taken_over_with_a_master_password() {
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
assert!(v.opens_with_machine_key());
// The hands-off vault holds the release set (with the approval key) from its first start.
v.signing_create(custos_vault::signing::Role::Release, &[], &[], NOW).unwrap();
let id = v.take_over(&SecretString::from("a long password"), FAST, NOW).expect("taken over");
assert!(!v.opens_with_machine_key());
assert!(v.factors().iter().any(|f| f.id == id && f.kind == FactorKind::Password));
let bytes = v.to_bytes().unwrap();
// This PC alone no longer opens it; the password and this PC do, and the keys are still there.
assert!(Vault::open_machine_store(&bytes, &PC).is_err(), "the PC-only access is gone");
let pw = SecretString::from("a long password");
let w = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &PC))
.expect("two factors");
assert!(w.same_key_as(&v));
assert_eq!(w.signing_keys().len(), v.signing_keys().len());
assert!(!w.signing_keys().is_empty());
// Unattended work is turned off, and it is audited.
let view = w.security_view(NOW);
assert!(view.ticked.contains(&Item::NoAutoConnect));
assert!(view.ticked.contains(&Item::NoUnattended));
assert!(view.ticked.contains(&Item::CardSigning));
assert_eq!(view.level, Level::Hardened);
assert!(view.audit.iter().any(|e| e.action == Action::TakenOver));
}
#[test]
fn only_a_machine_key_vault_is_taken_over_and_only_once() {
let mut user = Vault::create(&SecretString::from("pw"), FAST).unwrap();
assert!(!user.opens_with_machine_key());
assert!(user.take_over(&SecretString::from("a long password"), FAST, NOW).is_err());
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
v.take_over(&SecretString::from("a long password"), FAST, NOW).unwrap();
assert!(v.take_over(&SecretString::from("another long one"), FAST, NOW).is_err(), "once");
}
#[test]
fn after_the_take_over_a_phone_can_be_added_as_for_any_vault() {
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
assert!(v.add_factor(Unlock::Material(FactorKind::Approval, &[3; 32]), "phone").is_err(), "not before");
v.take_over(&SecretString::from("a long password"), FAST, NOW).unwrap();
v.add_factor(Unlock::Material(FactorKind::Approval, &[3; 32]), "phone").expect("after");
let bytes = v.to_bytes().unwrap();
assert!(
Vault::open_with(
&bytes,
Unlock::Material(FactorKind::Device, &PC),
Unlock::Material(FactorKind::Approval, &[3; 32])
)
.is_ok()
);
}
#[test]
fn notes_carry_their_detail_and_refuse_other_actions() {
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
v.security_note(Action::AutoConnected, "Connected to 192.168.100.217 as MARK-PC", NOW).unwrap();
v.security_note(Action::UnattendedStored, "setup-1: arca/authelia-mark, arca/totp-mark", NOW).unwrap();
v.security_note(Action::SetupItemRemoved, "setup-1: arca/totp-mark", NOW).unwrap();
v.security_note(Action::UnattendedSigned, "domi-release minisign run r42 Arca_0.3.0_x64-setup.exe", NOW).unwrap();
assert!(v.security_note(Action::Ticked, "x", NOW).is_err());
assert!(v.security_note(Action::AutoConnected, "line\nbreak", NOW).is_err(), "no control characters");
assert!(v.security_note(Action::AutoConnected, &"x".repeat(501), NOW).is_err(), "at most 500 characters");
let bytes = v.to_bytes().unwrap();
let w = Vault::open_machine_store(&bytes, &PC).unwrap();
let audit = w.security_view(NOW).audit;
assert_eq!(audit.len(), 4);
assert_eq!(audit[0].detail.as_deref(), Some("Connected to 192.168.100.217 as MARK-PC"));
assert_eq!(audit[3].action, Action::UnattendedSigned);
}
// ---------------------------------------------------------------- auto-connect and the Setup window
#[test]
fn auto_connect_runs_in_setup_and_standard_and_stops_when_hardened() {
assert!(auto_connect_allowed(Level::Setup, &none()));
assert!(auto_connect_allowed(Level::Standard, &none()));
assert!(!auto_connect_allowed(Level::Hardened, &ticked(&[Item::HelloApprovals])));
assert!(!auto_connect_allowed(Level::Setup, &ticked(&[Item::NoAutoConnect])), "the item holds in Setup too");
assert!(!auto_connect_allowed(Level::Setup, &ticked(&[Item::NoSsh])), "no SSH implies no auto-connect");
}
#[test]
fn a_new_connect_opens_setup_unless_unattended_is_off() {
assert!(setup_on_connect(&none()));
assert!(!setup_on_connect(&ticked(&[Item::NoUnattended])));
assert!(!setup_on_connect(&ticked(&[Item::NoSsh])));
}
#[test]
fn setup_runs_are_named_setup_dash_something_short() {
assert!(is_setup_run("setup-1"));
assert!(is_setup_run("setup-2026-11-05.first_run"));
assert!(is_setup_run(&format!("setup-{}", "a".repeat(58))));
assert!(!is_setup_run(&format!("setup-{}", "a".repeat(59))));
assert!(!is_setup_run("setup-"));
assert!(!is_setup_run("setup-a b"));
assert!(!is_setup_run("setup-a/b"));
assert!(!is_setup_run("Setup-1"));
assert!(!is_setup_run("r42"));
}
// ---------------------------------------------------------------- the unattended setup run
fn ask(item: &str) -> ProvisionAsk<'_> {
ProvisionAsk { verb: Verb::Ask, generate: true, exists: false, store: Store::Vault, item, totp: false }
}
fn offer(item: &str) -> ProvisionAsk<'_> {
ProvisionAsk { verb: Verb::Offer, generate: false, exists: false, store: Store::Vault, item, totp: false }
}
#[test]
fn a_setup_run_in_setup_takes_new_items_in_the_allowed_namespaces() {
for item in ["arca/authelia-mark", "custos/x", "fabrica/hub-token", "aula/admin", "gitea/read-token"] {
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &ask(item)), "{item}");
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &offer(item)), "{item}");
}
let totp = ProvisionAsk { totp: true, ..offer("arca/totp-mark") };
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &totp));
let claude = ProvisionAsk { store: Store::Claude, ..offer("fabrica-hub-token") };
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &claude), "the Claude store's names");
}
#[test]
fn everything_else_waits_for_a_card() {
let s = |l, t: &BTreeSet<Item>, run, r: &ProvisionAsk| unattended_provision(l, t, run, r);
let n = none();
// Existing items, asks without --generate, replacing offers.
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { exists: true, ..ask("arca/x") }), "an existing item");
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { generate: false, ..ask("arca/x") }), "no --generate");
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { exists: true, ..offer("arca/x") }), "a replacing offer");
// Namespaces.
for item in ["mark/bank", "domi/root", "arcax/y", "arca", "../arca/x", "ARCA/x"] {
assert!(!s(Level::Setup, &n, "setup-1", &ask(item)), "{item}");
}
// Display offers, and asks from the Claude store.
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { store: Store::Display, ..offer("arca/totp-mark") }));
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { store: Store::Claude, ..ask("fabrica-hub-token") }));
// The run and the level.
assert!(!s(Level::Setup, &n, "r42", &ask("arca/x")), "not a setup run");
assert!(!s(Level::Standard, &n, "setup-1", &ask("arca/x")), "after the window");
assert!(!s(Level::Hardened, &ticked(&[Item::NarrowScope]), "setup-1", &ask("arca/x")));
// Items that turn it off.
assert!(!s(Level::Setup, &ticked(&[Item::NoUnattended]), "setup-1", &ask("arca/x")));
let totp = ProvisionAsk { totp: true, ..offer("arca/totp-mark") };
assert!(!s(Level::Setup, &ticked(&[Item::TotpOnPhone]), "setup-1", &totp), "the TOTP lives on the phone");
}
// ---------------------------------------------------------------- unattended signing
#[test]
fn a_machine_key_vault_signs_run_requests_of_the_release_kinds_without_a_card() {
for kind in ["minisign", "manifest", "authenticode", "approval"] {
assert!(unattended_sign(Level::Standard, &none(), true, kind, true), "{kind}");
assert!(unattended_sign(Level::Setup, &none(), true, kind, true), "{kind} in Setup");
}
}
#[test]
fn signing_waits_for_a_card_otherwise() {
assert!(!unattended_sign(Level::Standard, &none(), false, "minisign", true), "taken over");
assert!(!unattended_sign(Level::Standard, &none(), true, "minisign", false), "no run");
assert!(!unattended_sign(Level::Standard, &none(), true, "ssh", true), "another kind");
assert!(!unattended_sign(Level::Hardened, &ticked(&[Item::CardSigning]), true, "minisign", true));
assert!(!unattended_sign(Level::Hardened, &ticked(&[Item::HelloApprovals]), true, "minisign", true), "hardened");
}
#[test]
fn the_new_items_round_trip_and_can_be_undone() {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
for item in [Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning] {
assert!(v.security_tick(item, NOW));
}
let bytes = v.to_bytes().unwrap();
let mut w = Vault::open(&bytes, &SecretString::from("pw")).unwrap();
assert_eq!(w.security_view(NOW).ticked, ticked(&[Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning]));
assert!(w.security_untick(Item::CardSigning, custos_vault::security::Auth::Hello, NOW));
assert!(!w.security_view(NOW).ticked.contains(&Item::CardSigning));
let _ = Error::Corrupted;
}
+395
View File
@@ -0,0 +1,395 @@
//! Mandatory tests for the Domi identity (docs/IDENTITY.md): the mnemonic order, the vector shared with
//! Fundamentum, signing only certs, persistence, and no way to get the root key out.
use custos_vault::identity::{Enrollment, Issued};
use custos_vault::{Error, FactorKind, KdfParams, SecretString, Unlock, Vault};
use ed25519_dalek::{Signature, VerifyingKey};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
/// The root public key of `abandon` × 23 + `art` (Fundamentum `crates/tessera/tests/mandatory.rs`).
const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs";
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
fn vault() -> Vault {
Vault::create(&SecretString::from("pw"), FAST).unwrap()
}
fn b64url(s: &str) -> Vec<u8> {
data_encoding::BASE64URL_NOPAD.decode(s.as_bytes()).unwrap()
}
/// Runs the whole enrolment with known entropy, typing the right words. Returns the words shown.
fn enrol(v: &mut Vault, entropy: [u8; 32]) -> Vec<String> {
let mut words = Vec::new();
let shown = Enrollment::with_entropy(entropy).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| words[i - 1].clone());
let confirmed = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
confirmed.import(v).unwrap();
words
}
#[test]
fn the_zero_vector_matches_fundamentum() {
let mut v = vault();
let words = enrol(&mut v, [0; 32]);
assert_eq!(words.len(), 24);
assert!(words[..23].iter().all(|w| w == "abandon") && words[23] == "art");
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
}
#[test]
fn the_same_mnemonic_gives_the_same_root() {
let (mut a, mut b) = (vault(), vault());
enrol(&mut a, [42; 32]);
enrol(&mut b, [42; 32]);
assert_eq!(a.domi_root_public(), b.domi_root_public());
let mut c = vault();
enrol(&mut c, [43; 32]);
assert_ne!(a.domi_root_public(), c.domi_root_public());
}
#[test]
fn the_mnemonic_is_shown_before_anything_is_imported() {
// The order trap at run time; at compile time see the compile_fail doctests in src/identity.rs.
let v = vault();
let mut log = Vec::new();
let shown = Enrollment::begin().show(|w| {
assert_eq!(w.len(), 24);
log.push("shown");
});
assert_eq!(log, ["shown"]);
assert!(v.domi_root_public().is_none(), "nothing in the vault before confirm + import");
// Wrong words: refused, and the same Shown comes back to try again.
let (shown, e) = shown.confirm(&["zoo", "zoo", "zoo"]).expect_err("wrong words are refused");
assert!(matches!(e, Error::WrongWords));
let c = shown.challenge();
assert!(c.iter().all(|&i| (1..=24).contains(&i)) && c[0] != c[1] && c[1] != c[2] && c[0] != c[2]);
assert!(v.domi_root_public().is_none());
}
#[test]
fn the_challenge_accepts_any_spacing_and_case() {
let mut v = vault();
let mut words = Vec::new();
let shown = Enrollment::with_entropy([5; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| format!(" {} ", words[i - 1].to_uppercase()));
shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap().import(&mut v).unwrap();
assert!(v.domi_root_public().is_some());
}
#[test]
fn an_identity_is_created_once() {
let mut v = vault();
enrol(&mut v, [1; 32]);
let first = v.domi_root_public();
let mut words = Vec::new();
let shown = Enrollment::with_entropy([2; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| words[i - 1].clone());
let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
assert!(matches!(c.import(&mut v), Err(Error::IdentityExists)));
assert_eq!(v.domi_root_public(), first);
}
/// A cert's to-be-signed bytes as tessera makes them: TSC1 ‖ root ‖ subkey ‖ ids ‖ validity.
fn tbs(root: &[u8; 32]) -> Vec<u8> {
let mut t = b"TSC1".to_vec();
t.extend_from_slice(root);
t.extend_from_slice(&[9; 32]);
t.extend_from_slice(b"\x06fiscus\x04sync");
t.extend_from_slice(&1u64.to_be_bytes());
t.extend_from_slice(&2u64.to_be_bytes());
t
}
#[test]
fn the_root_signs_certs_and_nothing_else() {
let mut v = vault();
assert!(matches!(v.domi_sign_cert(&tbs(&[0; 32])), Err(Error::NoIdentity)));
enrol(&mut v, [0; 32]);
let root = v.domi_root_public().unwrap();
let t = tbs(&root);
let sig = v.domi_sign_cert(&t).unwrap();
let vk = VerifyingKey::from_bytes(&root).unwrap();
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
// Not a cert, a cert for another root, the bare prefix: refused.
assert!(matches!(v.domi_sign_cert(b"pay 100 CZK to mallory"), Err(Error::NotACert)));
assert!(matches!(v.domi_sign_cert(&tbs(&[1; 32])), Err(Error::NotACert)));
assert!(matches!(v.domi_sign_cert(&t[..36]), Err(Error::NotACert)));
}
#[test]
fn the_identity_survives_saving_in_both_versions() {
let issued = Issued {
kind: "app".into(),
app_id: "fiscus".into(),
purpose: "sync".into(),
subkey: "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk".into(),
label: "fiscus.exe".into(),
not_before: 1,
not_after: 2,
issued: 3,
revoked_at: Some(4),
revocation: vec!["VFJWMQ".into()],
};
// Version 1.
let mut v = vault();
enrol(&mut v, [0; 32]);
v.domi_record(issued.clone()).unwrap();
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.domi_root_public(), v.domi_root_public());
assert_eq!(back.domi_issued(), std::slice::from_ref(&issued));
assert!(back.domi_created().is_some());
let t = tbs(&back.domi_root_public().unwrap());
assert_eq!(back.domi_sign_cert(&t).unwrap(), v.domi_sign_cert(&t).unwrap(), "the same key came back");
// Version 2.
let pw = SecretString::from("pw");
let mut v2 =
Vault::create_with(Unlock::Password(&pw), "pw", Unlock::Material(FactorKind::Device, &[7; 32]), "pc", FAST)
.unwrap();
enrol(&mut v2, [3; 32]);
let bytes = v2.to_bytes().unwrap();
let back = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &[7; 32])).unwrap();
assert_eq!(back.domi_root_public(), v2.domi_root_public());
// A vault without an identity still opens and has none.
let plain = Vault::open(&vault().to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert!(plain.domi_root_public().is_none() && plain.domi_issued().is_empty());
}
#[test]
fn a_record_needs_an_identity() {
let mut v = vault();
let i = Issued {
kind: "app".into(),
app_id: "x".into(),
purpose: "y".into(),
subkey: String::new(),
label: String::new(),
not_before: 0,
not_after: 1,
issued: 0,
..Issued::default()
};
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
assert!(matches!(v.domi_mark_revoked("x", 1), Err(Error::NoIdentity)));
assert!(matches!(v.domi_backup_secret("fiscus"), Err(Error::NoIdentity)));
}
// ---- v1.1: restoring, revoking, the backup secret (docs/IDENTITY.md) ----
const ZERO_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon art";
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
const SUBKEY_9: &str = "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"; // [9; 32]
#[test]
fn the_24_words_restore_the_same_root() {
let mut v = vault();
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v).unwrap();
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
// Any case, any spacing, as long as the words are right.
let mut w = vault();
let messy = format!(" {}\n", ZERO_PHRASE.to_uppercase().replace(' ', " \t"));
Enrollment::restore(&messy).unwrap().import(&mut w).unwrap();
assert_eq!(w.domi_root_public(), v.domi_root_public());
// And from words that were shown: the same root as enrolling.
let mut e = vault();
let words = enrol(&mut e, [42; 32]);
let mut r = vault();
Enrollment::restore(&words.join(" ")).unwrap().import(&mut r).unwrap();
assert_eq!(r.domi_root_public(), e.domi_root_public());
}
#[test]
fn a_wrong_phrase_restores_nothing_and_names_no_word() {
let bad_checksum = ZERO_PHRASE.replace("art", "abandon");
let short = "abandon ".repeat(11) + "about";
let typo = ZERO_PHRASE.replacen("abandon", "abandn", 1);
for phrase in [bad_checksum.as_str(), short.as_str(), typo.as_str(), "", "art"] {
let e = Enrollment::restore(phrase).map(|_| ()).unwrap_err();
assert!(matches!(e, Error::NotAMnemonic), "{phrase}");
let shown = format!("{e} {e:?}");
assert!(!shown.contains("abandon") && !shown.contains("art "), "{shown}");
}
// Into a vault that has one already: refused, the old one stays.
let mut v = vault();
enrol(&mut v, [5; 32]);
let before = v.domi_root_public();
assert!(matches!(Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v), Err(Error::IdentityExists)));
assert_eq!(v.domi_root_public(), before);
}
/// A revocation's to-be-signed bytes as tessera makes them: TRV1 ‖ root ‖ subkey ‖ revoked_at ‖ part ‖
/// parts ‖ count ‖ hashes.
fn trv1(root: &[u8; 32], subkey: &[u8; 32], revoked_at: u64) -> Vec<u8> {
let mut t = b"TRV1".to_vec();
t.extend_from_slice(root);
t.extend_from_slice(subkey);
t.extend_from_slice(&revoked_at.to_be_bytes());
t.extend_from_slice(&0u16.to_be_bytes());
t.extend_from_slice(&1u16.to_be_bytes());
t.extend_from_slice(&1u32.to_be_bytes());
t.extend_from_slice(&[7; 32]);
t
}
fn issued_to(subkey: &str, app_id: &str) -> Issued {
Issued {
kind: "app".into(),
app_id: app_id.into(),
purpose: "sync".into(),
subkey: subkey.into(),
label: "fiscus.exe".into(),
not_before: 1,
not_after: 2,
issued: 3,
..Issued::default()
}
}
#[test]
fn the_root_signs_a_revocation_only_for_a_key_the_person_revoked() {
let mut v = vault();
enrol(&mut v, [0; 32]);
let root = v.domi_root_public().unwrap();
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
// Issued, but not revoked yet: refused.
let t = trv1(&root, &[9; 32], 1000);
assert!(matches!(v.domi_sign_revocation(&t), Err(Error::NotARevocation)));
// An unknown key cannot be marked.
assert!(matches!(v.domi_mark_revoked("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", 1000), Err(Error::UnknownKey)));
// A renewal issued a second cert for the same key: marking covers both, and the first time stays.
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 1000).unwrap(), 1000);
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 2000).unwrap(), 1000, "the first revocation time stays");
assert!(v.domi_issued().iter().all(|i| i.revoked_at == Some(1000)));
let sig = v.domi_sign_revocation(&t).unwrap();
let vk = VerifyingKey::from_bytes(&root).unwrap();
vk.verify_strict(&[REVOKE_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
assert!(
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).is_err(),
"not a cert signature"
);
// Another time, another key, another root, a cert, garbage, the bare prefix: refused.
for bad in [
trv1(&root, &[9; 32], 999),
trv1(&root, &[10; 32], 1000),
trv1(&[1; 32], &[9; 32], 1000),
tbs(&root),
b"pay 100 CZK to mallory".to_vec(),
t[..76].to_vec(),
] {
assert!(matches!(v.domi_sign_revocation(&bad), Err(Error::NotARevocation)), "{bad:?}");
}
// And the cert signer never signs a revocation.
assert!(matches!(v.domi_sign_cert(&t), Err(Error::NotACert)));
// The statements are kept with every cert of the key, and survive a save.
v.domi_record_revocation(SUBKEY_9, vec!["first".into(), "second".into()]).unwrap();
assert!(matches!(
v.domi_record_revocation("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", vec![]),
Err(Error::UnknownKey)
));
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert!(back.domi_issued().iter().all(|i| i.revoked_at == Some(1000) && i.revocation == ["first", "second"]));
assert_eq!(back.domi_sign_revocation(&t).unwrap(), sig);
}
#[test]
fn a_cert_without_a_revocation_is_saved_as_before() {
let mut v = vault();
enrol(&mut v, [0; 32]);
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
let json = serde_json::to_string(&v.domi_issued()[0]).unwrap();
assert!(!json.contains("revoked_at") && !json.contains("revocation"), "{json}");
// And a record from core 0.7.0, without the two members, reads.
let old: Issued = serde_json::from_str(
r#"{"kind":"app","app_id":"fiscus","purpose":"sync","subkey":"x","label":"l","not_before":1,"not_after":2,"issued":3}"#,
)
.unwrap();
assert_eq!((old.revoked_at, old.revocation.len()), (None, 0));
}
#[test]
fn the_backup_secret_matches_fundamentum() {
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
let mut v = vault();
enrol(&mut v, [0; 32]);
let secret = v.domi_backup_secret("fiscus").unwrap();
let expand = |info: &[u8]| {
let mut out = [0u8; 32];
hkdf::Hkdf::<sha2::Sha256>::from_prk(secret.as_ref()).unwrap().expand(info, &mut out).unwrap();
out
};
// Fundamentum docs/TESSERA.md §12.
assert_eq!(expand(b"mailbox").to_vec(), b64url("IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU"));
let key = expand(b"seal");
let tag = chacha20poly1305::XChaCha20Poly1305::new_from_slice(&key)
.unwrap()
.encrypt(&chacha20poly1305::XNonce::try_from(&[0u8; 24][..]).unwrap(), Payload { msg: b"", aad: b"" })
.unwrap();
assert_eq!(tag, b64url("ci_JRbtsx5prR83KT9Y7LA"));
// One per app, the same from the restored words.
assert_ne!(*v.domi_backup_secret("calenda").unwrap(), *secret);
let mut r = vault();
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut r).unwrap();
assert_eq!(*r.domi_backup_secret("fiscus").unwrap(), *secret);
}
#[test]
fn nothing_prints_the_root() {
let mut v = vault();
let mut words = Vec::new();
let e = Enrollment::with_entropy([0; 32]);
assert_eq!(format!("{e:?}"), "Enrollment([redacted])");
let shown = e.show(|w| words = w.iter().map(|s| s.to_string()).collect());
assert_eq!(format!("{shown:?}"), "Shown([redacted])");
let pick = shown.challenge().map(|i| words[i - 1].clone());
let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
assert_eq!(format!("{c:?}"), "Confirmed([redacted])");
c.import(&mut v).unwrap();
let dbg = format!("{v:?}");
assert!(!dbg.contains("abandon") && !dbg.to_lowercase().contains("root"), "{dbg}");
}
/// No key export: the public surface of the identity module is locked. A new public function fails this
/// test until it has been checked to return no secret.
#[test]
fn the_identity_surface_is_locked() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut got = Vec::new();
for file in ["identity.rs", "lib.rs"] {
let text = std::fs::read_to_string(dir.join(file)).unwrap();
for line in text.lines() {
let l = line.trim();
if l.starts_with("pub fn ") && (file == "identity.rs" || l.starts_with("pub fn domi_")) {
got.push(format!("{file}: {}", l.trim_end_matches(" {")));
}
}
}
got.sort();
let mut want = vec![
"identity.rs: pub fn begin() -> Enrollment",
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
"identity.rs: pub fn restore(phrase: &str) -> Result<Confirmed, Error>",
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
// The app's own backup secret, derived: by design (docs/IDENTITY.md), never the root.
"lib.rs: pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error>",
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
"lib.rs: pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error>",
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
"lib.rs: pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error>",
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
"lib.rs: pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
];
want.sort();
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
}
+43 -1
View File
@@ -2,7 +2,8 @@
//! password change, no secret in Debug/Display.
use custos_vault::{
CrashPoint, Error, Field, Item, ItemType, KdfParams, SecretString, Vault, save_atomic, save_atomic_crashing,
Attachment, CrashPoint, Error, Field, Item, ItemType, KdfParams, SecretBytes, SecretString, Vault, save_atomic,
save_atomic_crashing,
};
use std::path::Path;
@@ -229,3 +230,44 @@ fn device_wrap_opens_the_same_vault_and_nothing_else() {
assert!(Vault::open_with_device(&bytes, &other, material).is_err());
assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature"));
}
#[test]
fn folders_and_attachments_survive_a_save_and_old_bodies_still_open() {
// core 0.8.0 (docs/FORMAT.md): `folder` and `attachments` are optional item members.
let mut item = Item::new(ItemType::SecureNote, "Keys", 1);
item.folder = vec!["Internet".into(), "Mail".into()];
item.attachments =
vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\xffAttached-Secret"[..]) }];
let mut v = Vault::create(&pw("pw"), FAST).unwrap();
v.add(item.clone());
v.add(Item::new(ItemType::WebLogin, "Plain", 1));
let back = Vault::open(&v.to_bytes().unwrap(), &pw("pw")).unwrap();
assert_eq!(back.items(), v.items());
assert_eq!(back.items()[0].folder, ["Internet", "Mail"]);
assert_eq!(back.items()[0].attachments[0].data.expose(), b"\x00\xffAttached-Secret");
assert!(back.items()[1].folder.is_empty() && back.items()[1].attachments.is_empty());
// An item written by an older core has neither member.
let old: Item = serde_json::from_str(
r#"{"id":"00112233445566778899aabbccddeeff","type":"web-login","title":"Old","created":1,"modified":1}"#,
)
.unwrap();
assert!(old.folder.is_empty() && old.attachments.is_empty());
// Without them, the JSON has no trace of them either (an older core reads it unchanged).
let json = serde_json::to_string(&old).unwrap();
assert!(!json.contains("folder") && !json.contains("attachments"), "{json}");
// Attachment data that is not base64 is refused, not guessed.
let bad = r#"{"id":"0","type":"secure-note","title":"x","created":1,"modified":1,"attachments":[{"name":"a","data":"!!"}]}"#;
assert!(serde_json::from_str::<Item>(bad).is_err());
}
#[test]
fn attachment_bytes_never_print() {
let a = Attachment { name: "secret.txt".into(), data: SecretBytes::from(&b"Attached-Secret-Bytes"[..]) };
let mut item = Item::new(ItemType::SecureNote, "With file", 1);
item.attachments.push(a.clone());
for out in [format!("{a:?}"), format!("{item:?}"), format!("{item:#?}"), format!("{:?}", a.data)] {
assert!(!out.contains("Attached-Secret-Bytes") && !out.contains("QXR0YWNoZWQt"), "{out}");
}
assert!(format!("{a:?}").contains("secret.txt"));
}
+210
View File
@@ -0,0 +1,210 @@
//! Mandatory tests for the Provisio audit (docs/FORMAT.md, "The provision audit"): it survives a reopen, takes
//! only entries that fit, is append-only and bounded, and has no member that could hold a secret. That an older
//! reader still opens such a vault is a unit test in src/provision.rs, which can see the decrypted body.
use custos_vault::provision::{AUDIT_LIMIT, Direction, Outcome, ProvisionEntry, Store};
use custos_vault::{Error, KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
/// One way to spoil an entry.
type Change = Box<dyn Fn(&mut ProvisionEntry)>;
fn entry(i: i64, outcome: Outcome) -> ProvisionEntry {
ProvisionEntry {
at: NOW + i,
direction: Direction::Offer,
host: "nixos-vm".into(),
item: "fabrica/gitea-read-token".into(),
store: Store::Vault,
run: Some("deploy-7".into()),
kind: Some("Gitea token, read:repository".into()),
code: "684361".into(),
outcome,
replaced: false,
}
}
#[test]
fn the_provision_audit_records_every_outcome_and_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
assert!(v.provision_audit().is_empty());
let all = [
Outcome::Approved,
Outcome::Generated,
Outcome::Accepted,
Outcome::Refused,
Outcome::OutOfScope,
Outcome::Invalid,
Outcome::Expired,
];
for (i, o) in all.iter().enumerate() {
let mut e = entry(i as i64, *o);
if i % 2 == 0 {
e.direction = Direction::Ask;
e.store = Store::Vault;
e.kind = None;
e.run = None;
} else {
e.store = if i % 3 == 0 { Store::Claude } else { Store::Cloud };
e.item = "fabrica-hub-token".into();
}
e.replaced = *o == Outcome::Accepted;
v.provision_record(e).unwrap();
}
v.save(&path).unwrap();
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
let audit: &[ProvisionEntry] = back.provision_audit();
assert_eq!(audit, v.provision_audit());
assert_eq!(audit.iter().map(|e| e.outcome).collect::<Vec<_>>(), all);
// Newest last.
assert!(audit.windows(2).all(|w| w[0].at < w[1].at));
assert_eq!(audit[0].direction, Direction::Ask);
assert_eq!(audit[1].store, Store::Cloud);
assert_eq!(audit[3].store, Store::Claude);
assert!(audit[2].replaced && !audit[1].replaced);
// The signing audit is a separate log and stays empty.
assert!(back.signing_audit().is_empty());
}
#[test]
fn entries_that_do_not_fit_are_refused_and_not_stored() {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.provision_record(entry(0, Outcome::Approved)).unwrap();
let secretish = "ghp_s3cr3tV4lu3ThatMustNeverBeInAnError";
let bad: Vec<Change> = vec![
Box::new(|e| e.code = "68436".into()),
Box::new(|e| e.code = "68436a".into()),
Box::new(|e| e.code = "6843611".into()),
Box::new(|e| e.item = "Arca/x".into()),
Box::new(|e| e.item = "../x".into()),
Box::new(|e| e.item = "a/b/c/d/e".into()),
Box::new(|e| e.item = String::new()),
Box::new(|e| e.item = format!("arca/{}", "x".repeat(65))),
Box::new(|e| e.run = Some(String::new())),
Box::new(|e| e.run = Some("run 1".into())),
Box::new(|e| e.run = Some("r".repeat(65))),
Box::new(|e| e.host = String::new()),
Box::new(|e| e.host = "nixos vm".into()),
Box::new(|e| e.host = "h".repeat(254)),
Box::new(|e| e.kind = Some("x".repeat(201))),
Box::new(move |e| e.kind = Some(format!("token\n{secretish}"))),
];
for (i, change) in bad.iter().enumerate() {
let mut e = entry(1, Outcome::Accepted);
change(&mut e);
let err = v.provision_record(e).unwrap_err();
assert!(matches!(err, Error::Provision(_)), "case {i}: {err:?}");
assert!(!format!("{err}{err:?}").contains(secretish), "case {i}: an error repeats a value");
}
assert_eq!(v.provision_audit(), [entry(0, Outcome::Approved)]);
// The limits themselves fit.
let mut e = entry(2, Outcome::Accepted);
e.item = format!("a{0}/b{0}/c{0}/d{0}", "x".repeat(63));
e.run = Some("R".repeat(64));
e.host = "h".repeat(253);
e.kind = Some("k".repeat(200));
v.provision_record(e).unwrap();
assert_eq!(v.provision_audit().len(), 2);
}
#[test]
fn the_audit_is_append_only_and_keeps_the_newest_entries() {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.provision_record(entry(0, Outcome::Refused)).unwrap();
let before = v.provision_audit().to_vec();
v.provision_record(entry(1, Outcome::Accepted)).unwrap();
// Recording appends; what was there is unchanged.
assert_eq!(&v.provision_audit()[..1], before.as_slice());
assert_eq!(v.provision_audit()[1], entry(1, Outcome::Accepted));
assert_eq!(AUDIT_LIMIT, 5_000);
for i in 2..(AUDIT_LIMIT as i64 + 3) {
v.provision_record(entry(i, Outcome::Expired)).unwrap();
}
let audit = v.provision_audit();
assert_eq!(audit.len(), AUDIT_LIMIT);
// The three oldest went; the newest is last.
assert_eq!(audit[0].at, NOW + 3);
assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 2);
}
#[test]
fn an_entry_has_no_member_that_could_hold_a_secret() {
// Every member, with every option set: the JSON has exactly these names and nothing like a value.
let mut e = entry(0, Outcome::Accepted);
e.replaced = true;
let json: serde_json::Value = serde_json::to_value(&e).unwrap();
let mut names: Vec<&str> = json.as_object().unwrap().keys().map(String::as_str).collect();
names.sort();
assert_eq!(names, ["at", "code", "direction", "host", "item", "kind", "outcome", "replaced", "run", "store"]);
for v in json.as_object().unwrap().values() {
assert!(!v.is_object() && !v.is_array(), "no nested member to hide a value in");
}
assert_eq!(
serde_json::to_string(&e).unwrap(),
r#"{"at":1793750000000,"direction":"offer","host":"nixos-vm","item":"fabrica/gitea-read-token","store":"vault","run":"deploy-7","kind":"Gitea token, read:repository","code":"684361","outcome":"accepted","replaced":true}"#
);
// The options are left out when absent; the outcomes are spelled as docs/FORMAT.md says.
let mut e = entry(0, Outcome::OutOfScope);
e.run = None;
e.kind = None;
let s = serde_json::to_string(&e).unwrap();
assert!(!s.contains("\"run\"") && !s.contains("\"kind\"") && s.contains("\"out-of-scope\""), "{s}");
}
// ---- display offers (core 0.12.0) ----
fn display(i: i64, outcome: Outcome) -> ProvisionEntry {
ProvisionEntry {
item: "arca/authelia-mark".into(),
store: Store::Display,
kind: Some("totp".into()),
run: None,
..entry(i, outcome)
}
}
#[test]
fn a_display_offer_is_recorded_as_confirmed_and_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
for (i, o) in [Outcome::Confirmed, Outcome::Refused, Outcome::Expired, Outcome::Invalid, Outcome::OutOfScope]
.into_iter()
.enumerate()
{
v.provision_record(display(i as i64, o)).unwrap();
}
let s = serde_json::to_string(&v.provision_audit()[0]).unwrap();
assert!(s.contains(r#""store":"display""#) && s.contains(r#""outcome":"confirmed""#), "{s}");
v.save(&path).unwrap();
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
assert_eq!(back.provision_audit(), v.provision_audit());
assert_eq!(back.provision_audit()[0].outcome, Outcome::Confirmed);
}
#[test]
fn display_and_confirmed_go_only_together_and_store_nothing() {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
let bad: Vec<ProvisionEntry> = vec![
// Nothing is stored, so nothing is accepted, approved, generated or replaced.
display(0, Outcome::Accepted),
display(0, Outcome::Approved),
display(0, Outcome::Generated),
ProvisionEntry { replaced: true, ..display(0, Outcome::Confirmed) },
// A display is an offer.
ProvisionEntry { direction: Direction::Ask, ..display(0, Outcome::Confirmed) },
// Confirmed is a display offer's outcome only.
entry(0, Outcome::Confirmed),
ProvisionEntry { store: Store::Claude, ..entry(0, Outcome::Confirmed) },
];
for (i, e) in bad.into_iter().enumerate() {
assert!(matches!(v.provision_record(e), Err(Error::Provision(_))), "case {i}");
}
assert!(v.provision_audit().is_empty());
}
+227
View File
@@ -0,0 +1,227 @@
//! The recovery key (docs/FACTORS.md, "The recovery key"): made on request, printed once, and taken by
//! `Vault::recover` only, which replaces every factor and the key itself before it hands the vault back.
use custos_vault::security::Action;
use custos_vault::{Error, FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const PC: [u8; 32] = [7; 32];
const NEW_PC: [u8; 32] = [8; 32];
const PHONE: [u8; 32] = [9; 32];
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
fn device(m: &[u8; 32]) -> Unlock<'_> {
Unlock::Material(FactorKind::Device, m)
}
/// A two-factor vault (password, this PC, a phone's approval) with one item.
fn vault() -> Vault {
let old = pw("the old master password");
let mut v = Vault::create_with(Unlock::Password(&old), "Master password", device(&PC), "MARK-PC", FAST).unwrap();
v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
let mut item = Item::new(ItemType::WebLogin, "Gitea", NOW);
item.set("password", "item-secret-value", NOW);
v.add(item);
v
}
fn actions(v: &Vault) -> Vec<Action> {
v.security_view(NOW + 60_000).audit.iter().map(|e| e.action).collect()
}
fn recover(bytes: &[u8], key: &str, new_password: &str) -> Result<(Vault, custos_vault::RecoveryKey), Error> {
Vault::recover(bytes, &pw(key), &pw(new_password), FAST, device(&NEW_PC), "MARK-PC", NOW + 5000)
}
#[test]
fn a_vault_without_a_recovery_key_is_as_before_and_making_one_changes_only_the_header() {
let v = vault();
let before = v.to_bytes().unwrap();
assert_eq!(Vault::recovery_id_of(&before).unwrap(), None);
assert_eq!(v.recovery_id(), None);
assert!(matches!(recover(&before, &"A".repeat(64), "a new master password"), Err(Error::RecoveryKeyMistyped)));
let mut v = v;
let key = v.recovery_create(NOW).unwrap();
assert_eq!(v.recovery_id().as_deref(), Some(key.id()));
let after = v.to_bytes().unwrap();
assert_eq!(Vault::recovery_id_of(&after).unwrap().as_deref(), Some(key.id()));
// The factors still open it, exactly as before, and the item is there.
let old = pw("the old master password");
let w = Vault::open_with(&after, Unlock::Password(&old), device(&PC)).unwrap();
assert_eq!((w.items().len(), w.factors().len()), (1, 3));
assert_eq!(actions(&w), [Action::RecoveryCreated]);
assert_eq!(w.security_view(NOW).audit[0].detail.as_deref(), Some(key.id()));
// The key is in neither the file nor the audit.
let flat = key.expose().replace('-', "");
let text = String::from_utf8_lossy(&after).into_owned();
assert!(!text.contains(&flat) && !text.contains(key.expose()));
}
#[test]
fn recovering_forces_a_new_password_new_factors_and_a_new_key() {
let mut v = vault();
let key = v.recovery_create(NOW).unwrap();
let bytes = v.to_bytes().unwrap();
let (r, new_key) = recover(&bytes, key.expose(), "a new master password").expect("recovered");
// Everything in the vault is still there.
assert_eq!(r.items().len(), 1);
assert_eq!(r.item(&r.items()[0].id).unwrap().field("password").unwrap().value.expose(), "item-secret-value");
// Exactly the two new factors; the old password, the old PC key and the phone are gone.
let kinds: Vec<FactorKind> = r.factors().iter().map(|f| f.kind).collect();
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device]);
assert_ne!(new_key.id(), key.id());
assert_ne!(new_key.expose(), key.expose());
assert_eq!(r.recovery_id().as_deref(), Some(new_key.id()));
assert_eq!(actions(&r), [Action::RecoveryCreated, Action::Recovered]);
let last = r.security_view(NOW + 5000).audit[1].clone();
assert_eq!((last.at, last.detail.as_deref()), (NOW + 5000, Some(key.id())));
let saved = r.to_bytes().unwrap();
let (old, new) = (pw("the old master password"), pw("a new master password"));
assert!(Vault::open_with(&saved, Unlock::Password(&new), device(&NEW_PC)).is_ok());
assert!(matches!(Vault::open_with(&saved, Unlock::Password(&old), device(&NEW_PC)), Err(Error::WrongPassword)));
assert!(matches!(Vault::open_with(&saved, Unlock::Password(&new), device(&PC)), Err(Error::FactorRejected)));
assert!(Vault::open_with(&saved, device(&PC), Unlock::Material(FactorKind::Approval, &PHONE)).is_err());
// The used key is spent; the new one works, once more.
assert!(matches!(recover(&saved, key.expose(), "yet another password"), Err(Error::WrongRecoveryKey)));
assert!(recover(&saved, new_key.expose(), "yet another password").is_ok());
}
#[test]
fn a_recovery_key_is_never_an_everyday_unlock() {
let mut v = vault();
let key = v.recovery_create(NOW).unwrap();
let bytes = v.to_bytes().unwrap();
let text = pw(key.expose());
let (_, material) = (key.id(), key.expose().replace('-', ""));
// It is not a password and not a factor: no ordinary way of opening takes it, alone or with a real factor.
assert!(Vault::open(&bytes, &text).is_err());
let old = pw("the old master password");
assert!(matches!(Vault::open_with(&bytes, Unlock::Password(&text), device(&PC)), Err(Error::WrongPassword)));
for kind in [FactorKind::Device, FactorKind::Totp, FactorKind::Approval, FactorKind::Passkey] {
let as_material = Unlock::Material(kind, &material.as_bytes()[..32]);
assert!(Vault::open_with(&bytes, Unlock::Password(&old), as_material).is_err(), "{kind:?}");
}
assert!(Vault::open_machine_store(&bytes, &PC).is_err());
assert_eq!(Vault::is_machine_store(&bytes).unwrap(), false);
// It does not count as a factor: two are still needed and it is not listed.
assert_eq!(Vault::factor_ids(&bytes).unwrap().len(), 3);
// Recovering needs a real second factor and a password worth the name.
let two_passwords =
Vault::recover(&bytes, &text, &pw("a new master password"), FAST, Unlock::Password(&old), "x", NOW);
assert!(matches!(two_passwords, Err(Error::NeedTwoFactors)));
let short = Vault::recover(&bytes, &text, &pw(""), FAST, device(&NEW_PC), "x", NOW);
assert!(matches!(short, Err(Error::WrongPassword) | Err(Error::FactorRejected)));
// A refused recovery changed nothing: the key still works.
assert!(recover(&bytes, key.expose(), "a new master password").is_ok());
}
#[test]
fn a_wrong_an_old_or_another_vaults_key_opens_nothing() {
let mut v = vault();
let first = v.recovery_create(NOW).unwrap();
// A second key replaces the first: one key per vault.
let second = v.recovery_create(NOW + 1000).unwrap();
assert_ne!(first.id(), second.id());
let bytes = v.to_bytes().unwrap();
assert!(matches!(recover(&bytes, first.expose(), "a new master password"), Err(Error::WrongRecoveryKey)));
let mut other = vault();
let others = other.recovery_create(NOW).unwrap();
assert!(matches!(recover(&bytes, others.expose(), "a new master password"), Err(Error::WrongRecoveryKey)));
// The right key with its last character changed: the check says so before the vault is tried.
let forged: String = {
let mut flat: Vec<char> = second.expose().chars().collect();
let last = flat.len() - 1;
flat[last] = if flat[last] == 'A' { 'B' } else { 'A' };
flat.into_iter().collect()
};
assert!(matches!(recover(&bytes, &forged, "a new master password"), Err(Error::RecoveryKeyMistyped)));
assert!(recover(&bytes, second.expose(), "a new master password").is_ok());
assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryCreated]);
}
#[test]
fn removing_the_key_closes_that_door_and_is_audited() {
let mut v = vault();
assert!(matches!(v.recovery_remove(NOW), Err(Error::NoRecoveryKey)));
let key = v.recovery_create(NOW).unwrap();
v.recovery_remove(NOW + 1000).unwrap();
assert_eq!(v.recovery_id(), None);
let bytes = v.to_bytes().unwrap();
assert_eq!(Vault::recovery_id_of(&bytes).unwrap(), None);
assert!(matches!(recover(&bytes, key.expose(), "a new master password"), Err(Error::NoRecoveryKey)));
assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryRemoved]);
// The file is an ordinary two-factor vault again: byte for byte the slots an older reader knows.
let old = pw("the old master password");
assert!(Vault::open_with(&bytes, Unlock::Password(&old), device(&PC)).is_ok());
}
#[test]
fn only_a_two_factor_vault_gets_a_recovery_key() {
// Version 1: one password. A recovery key would be its second way in without a second factor to replace.
let mut v1 = Vault::create(&pw("a version one password"), FAST).unwrap();
assert!(matches!(v1.recovery_create(NOW), Err(Error::NeedTwoFactors)));
// A machine store opens itself; it has nothing to recover and must stay exactly one factor and its slot.
let mut store = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
assert!(matches!(store.recovery_create(NOW), Err(Error::FactorRejected)));
assert!(Vault::open_machine_store(&store.to_bytes().unwrap(), &PC).is_ok());
}
#[test]
fn a_header_with_a_broken_or_a_second_recovery_slot_is_malformed() {
let mut v = vault();
v.recovery_create(NOW).unwrap();
let bytes = v.to_bytes().unwrap();
let plain = vault().to_bytes().unwrap();
// The slot count is the byte after magic (6) and version (2); slots follow as kind, length (u16 LE), payload.
let count = bytes[8] as usize;
assert_eq!(count, plain[8] as usize + 1);
let mut at = 9;
let mut found = None;
for _ in 0..count {
let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize;
if bytes[at] == 5 {
found = Some((at, len));
}
at += 3 + len;
}
let (at, len) = found.expect("a recovery slot, kind 5");
assert_eq!(len, 4 + 32 + 24 + 48);
// A kind this reader does not know.
let mut unknown = bytes.clone();
unknown[at] = 6;
assert!(matches!(Vault::factor_ids(&unknown), Err(Error::Malformed)));
// The slot twice.
let mut twice = bytes[..at + 3 + len].to_vec();
twice.extend_from_slice(&bytes[at..at + 3 + len]);
twice.extend_from_slice(&bytes[at + 3 + len..]);
twice[8] += 1;
assert!(matches!(Vault::factor_ids(&twice), Err(Error::Malformed)));
// A changed byte in the slot: the header is the body's AAD, so the vault does not open at all.
let mut flipped = bytes.clone();
flipped[at + 3 + 10] ^= 1;
let old = pw("the old master password");
assert!(matches!(Vault::open_with(&flipped, Unlock::Password(&old), device(&PC)), Err(Error::Corrupted)));
}
#[test]
fn the_key_and_the_audit_survive_a_reopen_and_ordinary_changes() {
let mut v = vault();
let key = v.recovery_create(NOW).unwrap();
let old = pw("the old master password");
let mut w = Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&old), device(&PC)).unwrap();
// Changing the password, adding and removing a factor: none of them touches the recovery key.
w.change_password(&pw("a changed master password"), FAST).unwrap();
let id = w.add_factor(Unlock::Material(FactorKind::Totp, &[5; 32]), "TOTP").unwrap();
w.remove_factor(&id).unwrap();
assert_eq!(w.recovery_id().as_deref(), Some(key.id()));
let bytes = w.to_bytes().unwrap();
assert!(recover(&bytes, key.expose(), "a new master password").is_ok());
}
+269
View File
@@ -0,0 +1,269 @@
//! The security member (docs/FORMAT.md, "The security member"): the level rules, the checklist and its audit, the
//! kept scope, and the rules the app asks before a card. That an older reader still opens such a vault, and that
//! unknown values are refused, are unit tests in src/security.rs, which can see the decrypted body.
use std::collections::BTreeSet;
use custos_vault::security::{
AUDIT_LIMIT, Action, Auth, Item, KeptScope, Level, SETUP_WINDOW, SshRule, Window, accept_all_allowed,
hello_for_approvals, replacing_line_preticked, ssh_needs_auth, totp_offer_allowed,
};
use custos_vault::{Error, KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const HOUR: i64 = 3_600_000;
fn vault() -> Vault {
Vault::create(&SecretString::from("pw"), FAST).unwrap()
}
fn actions(v: &Vault) -> Vec<Action> {
v.security_view(NOW).audit.iter().map(|e| e.action).collect()
}
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn a_vault_that_never_had_setup_is_standard() {
let v = vault();
assert_eq!(v.security_level(NOW), Level::Standard);
let view = v.security_view(NOW);
assert_eq!(view.level, Level::Standard);
assert!(view.setup.is_none() && view.setup_remaining.is_none());
assert!(view.ticked.is_empty() && view.audit.is_empty() && view.kept_scope.is_none());
}
#[test]
fn setup_lasts_two_hours_from_its_start() {
assert_eq!(SETUP_WINDOW, 2 * HOUR);
let mut v = vault();
let w = v.security_start_setup(NOW);
assert_eq!(w, Window { started: NOW, until: NOW + 2 * HOUR });
assert_eq!(v.security_level(NOW), Level::Setup);
assert_eq!(v.security_level(NOW + 2 * HOUR - 1), Level::Setup, "the last millisecond is still Setup");
assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard, "`until` itself is not");
assert_eq!(v.security_level(NOW - 1), Level::Standard, "a clock set back before the start is not Setup");
assert_eq!(v.security_view(NOW + HOUR).setup_remaining, Some(HOUR));
assert_eq!(v.security_view(NOW + 2 * HOUR).setup_remaining, None);
assert_eq!(actions(&v), [Action::SetupStarted]);
}
#[test]
fn starting_setup_again_while_in_setup_extends_nothing() {
let mut v = vault();
let w = v.security_start_setup(NOW);
assert_eq!(v.security_start_setup(NOW + HOUR), w);
assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard);
assert_eq!(actions(&v), [Action::SetupStarted], "no second entry");
}
#[test]
fn finish_setup_ends_it_early_and_is_audited() {
let mut v = vault();
assert!(!v.security_finish_setup(NOW), "nothing to finish");
v.security_start_setup(NOW);
assert!(v.security_finish_setup(NOW + 10));
assert_eq!(v.security_level(NOW + 10), Level::Standard);
assert_eq!(v.security_view(NOW + 10).finished, Some(NOW + 10));
assert!(!v.security_finish_setup(NOW + 20), "once");
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished]);
// A later Connect via SSH starts a new window.
let w = v.security_start_setup(NOW + HOUR);
assert_eq!(w, Window { started: NOW + HOUR, until: NOW + 3 * HOUR });
assert_eq!(v.security_level(NOW + HOUR), Level::Setup);
assert_eq!(v.security_view(NOW + HOUR).finished, None);
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished, Action::SetupStarted]);
}
#[test]
fn expiry_is_audited_once_by_the_first_change_that_notices_it() {
let mut v = vault();
v.security_start_setup(NOW);
// Reading notices nothing.
assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Standard);
assert_eq!(actions(&v), [Action::SetupStarted]);
v.security_tick(Item::NoSsh, NOW + 3 * HOUR);
v.security_record(Action::SshConnected, None, NOW + 3 * HOUR + 1).unwrap();
assert!(!v.security_finish_setup(NOW + 3 * HOUR + 2));
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupExpired, Action::Ticked, Action::SshConnected]);
let view = v.security_view(NOW + 3 * HOUR);
assert_eq!(view.finished, Some(NOW + 2 * HOUR), "ended at `until`");
assert_eq!(view.audit[1].at, NOW + 3 * HOUR, "written when noticed");
// Starting again after expiry opens a new window.
let w = v.security_start_setup(NOW + 4 * HOUR);
assert_eq!(w.started, NOW + 4 * HOUR);
assert_eq!(*actions(&v).last().unwrap(), Action::SetupStarted);
}
#[test]
fn ticking_hardens_and_undoing_needs_hello_or_the_password_and_is_audited() {
let mut v = vault();
assert!(v.security_tick(Item::HelloApprovals, NOW));
assert!(!v.security_tick(Item::HelloApprovals, NOW + 1), "ticked already: no entry");
assert_eq!(v.security_level(NOW), Level::Hardened);
assert!(v.security_tick(Item::NoSsh, NOW + 2));
assert!(v.security_untick(Item::NoSsh, Auth::Hello, NOW + 3));
assert!(!v.security_untick(Item::NoSsh, Auth::Password, NOW + 4), "not ticked: no entry");
assert_eq!(v.security_level(NOW + 5), Level::Hardened);
assert!(v.security_untick(Item::HelloApprovals, Auth::Password, NOW + 5));
assert_eq!(v.security_level(NOW + 6), Level::Standard);
let audit = v.security_view(NOW + 6).audit;
let got: Vec<_> = audit.iter().map(|e| (e.at, e.action, e.item, e.auth)).collect();
assert_eq!(
got,
[
(NOW, Action::Ticked, Some(Item::HelloApprovals), None),
(NOW + 2, Action::Ticked, Some(Item::NoSsh), None),
(NOW + 3, Action::Unticked, Some(Item::NoSsh), Some(Auth::Hello)),
(NOW + 5, Action::Unticked, Some(Item::HelloApprovals), Some(Auth::Password)),
]
);
}
#[test]
fn ticked_items_hold_during_setup() {
let mut v = vault();
v.security_tick(Item::NoSsh, NOW);
v.security_tick(Item::TotpOnPhone, NOW);
v.security_start_setup(NOW + 1);
assert_eq!(v.security_level(NOW + 1), Level::Setup);
let ticked = v.security_view(NOW + 1).ticked;
assert_eq!(ticked, BTreeSet::from([Item::TotpOnPhone, Item::NoSsh]));
assert_eq!(ssh_needs_auth(Level::Setup, &ticked), SshRule::Off, "Setup never undoes hardening");
assert!(!totp_offer_allowed(&ticked));
// After Setup the ticks are still there: Hardened.
assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Hardened);
}
#[test]
fn the_state_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault();
v.security_start_setup(NOW);
v.security_tick(Item::NarrowScope, NOW + 1);
v.security_keep_scope(&s(&["arca/"]), &s(&["arca/", "fabrica/"])).unwrap();
v.security_record(Action::TotpMoved, Some(Item::TotpOnPhone), NOW + 2).unwrap();
v.save(&path).unwrap();
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
assert_eq!(back.security_view(NOW + 3), v.security_view(NOW + 3));
assert_eq!(back.security_level(NOW + 3), Level::Setup);
let view = back.security_view(NOW + 3);
assert_eq!(view.kept_scope, Some(KeptScope { ask: s(&["arca/"]), offer: s(&["arca/", "fabrica/"]) }));
assert_eq!(view.audit.last().unwrap().item, Some(Item::TotpOnPhone));
}
#[test]
fn the_kept_scope_is_kept_once_and_taken_back() {
let mut v = vault();
assert!(v.security_take_kept_scope().is_none());
v.security_keep_scope(&s(&["arca/"]), &s(&["fabrica/"])).unwrap();
// A second keep would lose the first prefixes: refused.
assert!(matches!(v.security_keep_scope(&s(&["x/"]), &[]), Err(Error::Security(_))));
let kept = v.security_take_kept_scope().unwrap();
assert_eq!(kept, KeptScope { ask: s(&["arca/"]), offer: s(&["fabrica/"]) });
assert!(v.security_take_kept_scope().is_none());
// The rules for a prefix.
for bad in [s(&[""]), s(&["a\nb"]), vec!["x".repeat(201)], (0..65).map(|i| format!("p{i}/")).collect()] {
assert!(matches!(v.security_keep_scope(&bad, &[]), Err(Error::Security(_))), "{bad:?}");
assert!(matches!(v.security_keep_scope(&[], &bad), Err(Error::Security(_))), "{bad:?}");
}
v.security_keep_scope(&[], &[]).unwrap();
assert_eq!(v.security_take_kept_scope(), Some(KeptScope { ask: vec![], offer: vec![] }));
}
#[test]
fn only_ssh_connected_and_totp_moved_are_recorded_directly() {
let mut v = vault();
v.security_record(Action::SshConnected, None, NOW).unwrap();
v.security_record(Action::TotpMoved, None, NOW + 1).unwrap();
for a in [Action::SetupStarted, Action::SetupFinished, Action::SetupExpired, Action::Ticked, Action::Unticked] {
assert!(matches!(v.security_record(a, Some(Item::NoSsh), NOW + 2), Err(Error::Security(_))), "{a:?}");
}
assert_eq!(actions(&v), [Action::SshConnected, Action::TotpMoved]);
}
#[test]
fn the_audit_keeps_the_newest_5000() {
assert_eq!(AUDIT_LIMIT, 5_000);
let mut v = vault();
for i in 0..(AUDIT_LIMIT as i64 + 2) {
v.security_record(Action::SshConnected, None, NOW + i).unwrap();
}
let audit = v.security_view(NOW).audit;
assert_eq!(audit.len(), AUDIT_LIMIT);
assert_eq!(audit[0].at, NOW + 2);
assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 1);
}
#[test]
fn the_rules_before_a_card() {
let none = BTreeSet::new();
// Accept all: only in Setup, only for a setup run with Provisio lines only.
assert!(accept_all_allowed(Level::Setup, "setup-1", true));
assert!(!accept_all_allowed(Level::Setup, "setup-1", false), "a signing or approval line");
assert!(!accept_all_allowed(Level::Setup, "r-42", true), "not a setup run");
assert!(!accept_all_allowed(Level::Setup, "Setup-1", true), "the prefix is exact");
assert!(!accept_all_allowed(Level::Standard, "setup-1", true));
assert!(!accept_all_allowed(Level::Hardened, "setup-1", true));
// A line that replaces a stored item is pre-ticked only where Accept all applies.
assert!(replacing_line_preticked(Level::Setup, true));
assert!(!replacing_line_preticked(Level::Setup, false));
assert!(!replacing_line_preticked(Level::Standard, true));
assert!(!replacing_line_preticked(Level::Hardened, true));
// Connect via SSH.
assert_eq!(ssh_needs_auth(Level::Setup, &none), SshRule::Allowed);
assert_eq!(ssh_needs_auth(Level::Standard, &none), SshRule::NeedsAuth);
let hello = BTreeSet::from([Item::HelloApprovals]);
assert_eq!(ssh_needs_auth(Level::Hardened, &hello), SshRule::NeedsAuth);
let off = BTreeSet::from([Item::NoSsh]);
for l in [Level::Setup, Level::Standard, Level::Hardened] {
assert_eq!(ssh_needs_auth(l, &off), SshRule::Off);
}
// TOTP offers and Hello for approvals.
assert!(totp_offer_allowed(&none) && totp_offer_allowed(&hello));
assert!(!totp_offer_allowed(&BTreeSet::from([Item::TotpOnPhone])));
assert!(hello_for_approvals(&hello) && !hello_for_approvals(&none) && !hello_for_approvals(&off));
}
#[test]
fn values_are_spelled_as_docs_format_says() {
let all = [
Item::TotpOnPhone,
Item::HelloApprovals,
Item::NarrowScope,
Item::RotateSetup,
Item::NoSsh,
Item::PhoneApproves,
];
assert_eq!(
serde_json::to_string(&all).unwrap(),
r#"["totp-on-phone","hello-approvals","narrow-scope","rotate-setup","no-ssh","phone-approves"]"#
);
let actions = [
Action::SetupStarted,
Action::SetupFinished,
Action::SetupExpired,
Action::Ticked,
Action::Unticked,
Action::SshConnected,
Action::TotpMoved,
];
assert_eq!(
serde_json::to_string(&actions).unwrap(),
r#"["setup-started","setup-finished","setup-expired","ticked","unticked","ssh-connected","totp-moved"]"#
);
assert_eq!(serde_json::to_string(&[Auth::Hello, Auth::Password]).unwrap(), r#"["hello","password"]"#);
assert_eq!(
serde_json::to_string(&[Level::Setup, Level::Standard, Level::Hardened]).unwrap(),
r#"["setup","standard","hardened"]"#
);
assert_eq!(
serde_json::to_string(&[SshRule::Allowed, SshRule::NeedsAuth, SshRule::Off]).unwrap(),
r#"["allowed","needs-auth","off"]"#
);
}
+398
View File
@@ -0,0 +1,398 @@
//! Mandatory tests for signing keys (docs/SIGNING.md): scope (4) and the audit log through a reopen (6). That no API
//! path returns a private key (2) is a unit test in src/signing.rs, which can see the stored secrets; the app tests
//! it again over its pipe ops and mailbox messages.
use custos_vault::signing::{Approval, AuditEntry, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{Error, KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn vault_with_keys() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca", "Fabrica"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v
}
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
Context {
repo: repo.into(),
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: trigger.into(),
file: "Arca_0.2.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
..Default::default()
}
}
fn minisign_req(key: &str, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Minisign,
digest: vec![7; 64],
manifest: None,
approval: None,
run: None,
context: c,
via: Via::Local,
}
}
fn authenticode_req(key: &str, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Authenticode,
digest: vec![9; 32],
manifest: None,
approval: None,
run: None,
context: c,
via: Via::Remote,
}
}
#[test]
fn the_release_and_test_sets_are_made_once_each() {
let mut v = vault_with_keys();
let keys = v.signing_keys();
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
assert_eq!(
ids,
[
"domi-release",
"domi-root",
"domi-code-signing",
"domi-approve",
"domi-test",
"domi-test-root",
"domi-test-code-signing"
]
);
assert_eq!(keys[1].kind, KeyKind::RootCa);
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
assert_eq!(keys[6].issuer.as_deref(), Some("domi-test-root"));
assert!(!keys[0].auto_approve && !keys[2].auto_approve && !keys[3].auto_approve);
assert!(keys[4].auto_approve && keys[6].auto_approve && !keys[5].auto_approve);
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
// The root's certificate is exported; a key without one is not.
assert_eq!(v.signing_export_cert("domi-root").unwrap(), keys[1].cert.clone().unwrap());
assert!(v.signing_export_cert("domi-release").is_err());
}
#[test]
fn every_kind_signs_and_verifies() {
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::hazmat::PrehashVerifier;
use x509_cert::der::{Decode, Encode};
let mut v = vault_with_keys();
let data = b"the installer";
let mut req = minisign_req("domi-release", ctx("release", "Arca", "tag"));
req.digest = custos_sign::blake2b512(data).to_vec();
let sig = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
let public = minisign_verify::PublicKey::decode(v.signing_keys()[0].minisign_public.as_deref().unwrap()).unwrap();
let text = String::from_utf8(sig.bytes.clone()).unwrap();
public.verify(data, &minisign_verify::Signature::decode(&text).unwrap(), false).unwrap();
assert_eq!(sig.sha256, custos_sign::sha256_hex(&sig.bytes));
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
let man = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums.clone()), ..req.clone() };
let msig = v.signing_sign(&man, Approval::Mark, NOW).unwrap();
public
.verify(
sums.as_bytes(),
&minisign_verify::Signature::decode(std::str::from_utf8(&msig.bytes).unwrap()).unwrap(),
false,
)
.unwrap();
let auth = authenticode_req("domi-code-signing", ctx("release", "Arca", "tag"));
let asig = v.signing_sign(&auth, Approval::Mark, NOW).unwrap();
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("domi-code-signing").unwrap()).unwrap();
let key = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&cert.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
key.verify_prehash(&auth.digest, &Signature::try_from(asig.bytes.as_slice()).unwrap()).unwrap();
}
#[test]
fn a_pipeline_or_repo_off_the_list_is_refused_even_when_approved() {
let mut v = vault_with_keys();
for c in [ctx("nightly", "Arca", "tag"), ctx("release", "Custos", "tag")] {
let req = minisign_req("domi-release", c);
assert!(matches!(v.signing_check(&req), Err(Refusal::OutOfScope(_))));
assert!(matches!(v.signing_sign(&req, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
}
let leaf = authenticode_req("domi-code-signing", ctx("release", "Custos", "tag"));
assert!(
matches!(v.signing_sign(&leaf, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))),
"the leaf has the same scope"
);
// Widening the scope takes an explicit change.
v.signing_set_scope("domi-release", &s(&["release", "nightly"]), &s(&["Arca"])).unwrap();
assert!(v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW).is_ok());
assert!(v.signing_set_scope("domi-root", &s(&["*"]), &s(&["*"])).is_err());
}
#[test]
fn release_keys_never_sign_without_mark_and_test_keys_never_sign_a_tag() {
let mut v = vault_with_keys();
let r = v.signing_sign(&minisign_req("domi-release", ctx("release", "Arca", "tag")), Approval::Auto, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
let t = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW);
assert!(t.is_ok());
let tag = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "tag")), Approval::Auto, NOW);
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
let leaf =
v.signing_sign(&authenticode_req("domi-test-code-signing", ctx("ci", "Arca", "push")), Approval::Auto, NOW);
assert!(leaf.is_ok());
}
#[test]
fn malformed_requests_and_the_root_are_refused() {
let mut v = vault_with_keys();
let mut short = minisign_req("domi-release", ctx("release", "Arca", "tag"));
short.digest = vec![0; 32];
let wrong_key = authenticode_req("domi-release", ctx("release", "Arca", "tag"));
let root = authenticode_req("domi-root", ctx("release", "Arca", "tag"));
let mut path = minisign_req("domi-release", ctx("release", "Arca", "tag"));
path.context.file = "..\\evil.exe".into();
let man =
Request { kind: SignKind::Manifest, manifest: Some("not sums\n".into()), digest: vec![], ..short.clone() };
let none = minisign_req("nope", ctx("release", "Arca", "tag"));
for r in [&short, &wrong_key, &root, &path, &man] {
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
}
assert!(matches!(v.signing_sign(&none, Approval::Mark, NOW), Err(Refusal::NoKey(_))));
}
#[test]
fn the_audit_log_records_every_outcome_and_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault_with_keys();
let rel = minisign_req("domi-release", ctx("release", "Arca", "tag"));
let signed = v.signing_sign(&rel, Approval::Mark, NOW).unwrap();
v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW + 1).unwrap();
v.signing_refuse(&rel, Outcome::Refused, None, NOW + 2);
v.signing_refuse(&rel, Outcome::Expired, Some("no answer in 5 minutes".into()), NOW + 3);
let _ = v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW + 4);
let _ = v.signing_sign(&minisign_req("nope", ctx("release", "Arca", "tag")), Approval::Mark, NOW + 5);
// A refusal can never be recorded as a signature.
v.signing_refuse(&rel, Outcome::Approved, None, NOW + 6);
v.save(&path).unwrap();
let reopened = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
let audit: &[AuditEntry] = reopened.signing_audit();
let outcomes: Vec<Outcome> = audit.iter().map(|e| e.outcome).collect();
assert_eq!(
outcomes,
[
Outcome::Approved,
Outcome::Auto,
Outcome::Refused,
Outcome::Expired,
Outcome::OutOfScope,
Outcome::Invalid,
Outcome::Refused
]
);
assert_eq!(audit[0].signature.as_deref(), Some(signed.sha256.as_str()));
assert!(audit[2..].iter().all(|e| e.signature.is_none()));
assert_eq!(audit[0].context, ctx("release", "Arca", "tag"));
assert_eq!(audit[0].via, Via::Local);
assert_eq!(audit[3].reason.as_deref(), Some("no answer in 5 minutes"));
assert_eq!(reopened.signing_audit(), v.signing_audit());
// The keys came back too, and still sign.
let mut reopened = reopened;
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
}
// ---- deploy approvals (core 0.12.0) ----
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
fn approval_text(run: &str, repo: &str, expires_in: i64) -> String {
format!(
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#,
NOW / 1000 + expires_in
)
}
fn approval_req(run: &str) -> Request {
Request {
key: "domi-approve".into(),
kind: SignKind::Approval,
digest: vec![],
manifest: None,
approval: Some(approval_text(run, "Arca", 600)),
run: Some(run.into()),
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
trigger: "tag".into(),
..Default::default()
},
via: Via::Remote,
}
}
#[test]
fn domi_approve_is_made_with_the_release_keys() {
let v = vault_with_keys();
let keys = v.signing_keys();
let a = keys.iter().find(|k| k.id == "domi-approve").expect("made with the release set");
assert_eq!(a.kind, KeyKind::Ed25519);
assert_eq!(a.role, Role::Release);
assert_eq!(a.name, "Domi deploy approval");
assert!(!a.auto_approve, "it always asks");
let rel = keys.iter().find(|k| k.id == "domi-release").unwrap();
assert_eq!((&a.pipelines, &a.repos), (&rel.pipelines, &rel.repos), "the release keys' scope");
assert!(a.minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
assert_ne!(a.key_id, rel.key_id);
// The test set has no approval key.
assert!(!keys.iter().any(|k| k.role == Role::Test && k.id.contains("approve")));
}
#[test]
fn an_approval_is_signed_by_domi_approve_and_verifies_with_minisign() {
let mut v = vault_with_keys();
let req = approval_req("r-42");
v.signing_check_at(&req, NOW).unwrap();
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
let text = String::from_utf8(signed.bytes.clone()).unwrap();
let pubkey = v.signing_keys().into_iter().find(|k| k.id == "domi-approve").unwrap().minisign_public.unwrap();
let public = minisign_verify::PublicKey::decode(&pubkey).unwrap();
let sig = minisign_verify::Signature::decode(&text).unwrap();
public.verify(req.approval.as_deref().unwrap().as_bytes(), &sig, false).unwrap();
assert_eq!(sig.trusted_comment(), format!("timestamp:{}\tfile:approval-r-42.json\thashed", NOW / 1000));
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
let e = v.signing_audit().last().unwrap();
assert_eq!((e.key.as_str(), e.kind, e.outcome), ("domi-approve", SignKind::Approval, Outcome::Approved));
assert_eq!(e.run.as_deref(), Some("r-42"));
assert_eq!(e.context.file, "approval-r-42.json");
assert_eq!((e.context.commit.as_str(), e.context.version.as_str()), (COMMIT, "0.7.0"), "filled from the JSON");
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
}
#[test]
fn domi_approve_signs_only_approvals_and_approvals_only_with_domi_approve() {
let mut v = vault_with_keys();
let by_release = Request { key: "domi-release".into(), ..approval_req("r-42") };
let by_test = Request { key: "domi-test".into(), ..approval_req("r-42") };
let mut digest = minisign_req("domi-approve", ctx("release", "Arca", "tag"));
digest.run = Some("r-42".into());
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
let manifest = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums), ..digest.clone() };
let authenticode = Request { kind: SignKind::Authenticode, digest: vec![1; 32], ..digest.clone() };
for r in [&by_release, &by_test, &digest, &manifest, &authenticode] {
assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}");
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
}
let code_signing = Request { key: "domi-code-signing".into(), ..approval_req("r-42") };
assert!(matches!(v.signing_check_at(&code_signing, NOW), Err(Refusal::Invalid(_))));
// A release key: never without Mark.
assert!(matches!(v.signing_sign(&approval_req("r-42"), Approval::Auto, NOW), Err(Refusal::NeedsApproval(_))));
assert!(v.signing_audit().iter().all(|e| e.signature.is_none()), "nothing was signed");
}
#[test]
fn an_approval_needs_its_run_a_canonical_unexpired_text_and_a_matching_context() {
let mut v = vault_with_keys();
let invalid = |v: &mut Vault, r: &Request| {
assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}");
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
};
invalid(&mut v, &Request { run: None, ..approval_req("r-42") });
invalid(&mut v, &Request { run: Some("r-43".into()), ..approval_req("r-42") });
invalid(&mut v, &Request { approval: None, ..approval_req("r-42") });
let mut spaced = approval_req("r-42");
spaced.approval = Some(spaced.approval.unwrap().replace(',', ", "));
invalid(&mut v, &spaced);
let mut late = approval_req("r-42");
late.approval = Some(approval_text("r-42", "Arca", 25 * 3600 + 1));
invalid(&mut v, &late);
// A day ahead is fine (core 0.17.1): a release's approval lives that long.
let mut day = approval_req("r-42");
day.approval = Some(approval_text("r-42", "Arca", 24 * 3600));
assert!(v.signing_check_at(&day, NOW).is_ok());
let mut past = approval_req("r-42");
past.approval = Some(approval_text("r-42", "Arca", 0));
invalid(&mut v, &past);
let zeros = "0".repeat(40);
for (member, value) in
[("repo", "Fabrica"), ("pipeline", "nightly"), ("commit", zeros.as_str()), ("version", "0.8.0")]
{
let mut r = approval_req("r-42");
match member {
"repo" => r.context.repo = value.into(),
"pipeline" => r.context.pipeline = value.into(),
"commit" => r.context.commit = value.into(),
_ => r.context.version = value.into(),
}
invalid(&mut v, &r);
}
// The expiry is checked against the time given: valid now, expired ten minutes later.
let ok = approval_req("r-42");
assert!(v.signing_check_at(&ok, NOW).is_ok());
assert!(matches!(v.signing_check_at(&ok, NOW + 600_000), Err(Refusal::Invalid(_))));
assert!(matches!(v.signing_sign(&ok, Approval::Mark, NOW + 600_000), Err(Refusal::Invalid(_))));
}
#[test]
fn an_approval_for_a_repo_off_the_list_is_out_of_scope() {
let mut v = vault_with_keys();
let mut r = approval_req("r-42");
r.approval = Some(approval_text("r-42", "Custos", 600));
r.context.repo = "Custos".into();
assert!(matches!(v.signing_check_at(&r, NOW), Err(Refusal::OutOfScope(_))));
// The JSON's repo is what counts, even when the context leaves it empty.
r.context.repo = String::new();
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::OutOfScope);
}
#[test]
fn any_request_may_name_its_run_and_the_audit_keeps_it() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault_with_keys();
let mut r = minisign_req("domi-release", ctx("release", "Arca", "tag"));
r.run = Some("r-42".into());
r.context.version = "0.7.0".into();
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
v.signing_refuse(&r, Outcome::Refused, None, NOW + 1);
let mut bad = r.clone();
bad.run = Some("r 42".into());
assert!(matches!(v.signing_check_at(&bad, NOW), Err(Refusal::Invalid(_))));
let mut stray = r.clone();
stray.approval = Some(approval_text("r-42", "Arca", 600));
assert!(matches!(v.signing_check_at(&stray, NOW), Err(Refusal::Invalid(_))), "approval text on a digest request");
v.save(&path).unwrap();
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
let a = back.signing_audit();
assert_eq!(a[0].run.as_deref(), Some("r-42"));
assert_eq!(a[0].context.version, "0.7.0");
assert_eq!(a[1].run.as_deref(), Some("r-42"));
assert_eq!(back.signing_audit(), v.signing_audit());
}
#[test]
fn the_approval_key_is_added_only_to_release_keys_and_only_once() {
let mut empty = Vault::create(&SecretString::from("pw"), FAST).unwrap();
assert!(matches!(empty.signing_add_approve(NOW), Err(Error::Signing(_))), "no release keys");
let mut v = vault_with_keys();
assert!(matches!(v.signing_add_approve(NOW), Err(Error::SigningExists("approval"))));
}
+386
View File
@@ -0,0 +1,386 @@
//! Standing approvals (core 0.16.0, docs/SIGNING.md "Standing approvals"): a rule Mark grants from a request he is
//! approving, for one repository, key, kind, pipeline and origin. A later request that fits is signed without
//! asking and recorded as `standing`; everything else still needs him.
use custos_vault::security::{Action, Auth, Item};
use custos_vault::signing::{AndroidKey, Approval, Context, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
/// The release set for the pipelines `release` and `deploy` of Arca, Aula and Fabrica, and the test set.
fn vault() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release", "deploy"]), &s(&["Arca", "Aula", "Fabrica"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v
}
fn ctx(pipeline: &str, repo: &str) -> Context {
Context {
repo: repo.into(),
commit: COMMIT.into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: "tag".into(),
file: "Arca_0.7.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "0.7.0".into(),
}
}
fn minisign(repo: &str, pipeline: &str, run: &str) -> Request {
Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![7; 64],
manifest: None,
approval: None,
run: Some(run.into()),
context: ctx(pipeline, repo),
via: Via::Local,
}
}
fn authenticode(repo: &str, run: &str) -> Request {
Request {
key: "domi-code-signing".into(),
kind: SignKind::Authenticode,
digest: vec![9; 32],
..minisign(repo, "release", run)
}
}
fn approval(repo: &str, run: &str, targets: &[&str], via: Via) -> Request {
let targets = targets.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
let text = format!(
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"deploy","version":"0.7.0","targets":[{targets}],"expires":{}}}"#,
NOW / 1000 + 600
);
Request {
key: "domi-approve".into(),
kind: SignKind::Approval,
digest: vec![],
manifest: None,
approval: Some(text),
run: Some(run.into()),
context: Context {
repo: repo.into(),
pipeline: "deploy".into(),
trigger: "manual".into(),
..Default::default()
},
via,
}
}
/// Mark approves `req` on a card (the key's signature that must come before any rule).
fn mark_signs(v: &mut Vault, req: &Request) {
v.signing_sign(req, Approval::Mark, NOW).expect("signed with Mark's click");
}
/// Mark approves `req` with *Always allow*: the rule first, then the signature.
fn always(v: &mut Vault, req: &Request) -> String {
let rule = v.standing_grant(req, NOW + 1).expect("granted");
v.signing_sign(req, Approval::Mark, NOW + 1).unwrap();
rule.id
}
fn outcomes(v: &Vault) -> Vec<Outcome> {
v.signing_audit().iter().map(|e| e.outcome).collect()
}
#[test]
fn a_granted_rule_signs_the_next_matching_request_and_records_it() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
assert!(v.standing_rules().is_empty());
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-2"), NOW).is_none(), "nothing fits before a grant");
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
let rules = v.standing_rules();
assert_eq!(rules.len(), 1);
let r = &rules[0];
assert_eq!(
(r.id.as_str(), r.repo.as_str(), r.key.as_str(), r.pipeline.as_str()),
(id.as_str(), "Arca", "domi-release", "release")
);
assert_eq!((r.kind, r.via, r.granted, r.uses, r.last_used), (SignKind::Minisign, Via::Local, NOW + 1, 0, None));
// The next run: it fits, and signing with the rule records everything an approved entry holds.
let next = minisign("Arca", "release", "r-3");
assert_eq!(v.standing_rule_for(&next, NOW + 5).map(|r| r.id), Some(id.clone()));
let signed = v.signing_sign(&next, Approval::Standing, NOW + 5).expect("signed by the rule");
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Approved, Outcome::Standing]);
let e = v.signing_audit().last().unwrap().clone();
assert_eq!(e.context, ctx("release", "Arca"));
assert_eq!(
(e.key.as_str(), e.kind, e.via, e.run.as_deref(), e.at),
("domi-release", SignKind::Minisign, Via::Local, Some("r-3"), NOW + 5)
);
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
let r = &v.standing_rules()[0];
assert_eq!((r.uses, r.last_used), (1, Some(NOW + 5)));
// Granting the same thing again makes no second rule and keeps the count.
assert_eq!(v.standing_grant(&minisign("Arca", "release", "r-4"), NOW + 9).unwrap().id, id);
assert_eq!(v.standing_rules().len(), 1);
assert_eq!(v.standing_rules()[0].uses, 1);
}
#[test]
fn another_repository_key_kind_pipeline_or_origin_does_not_fit() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
mark_signs(&mut v, &authenticode("Arca", "r-1"));
always(&mut v, &minisign("Arca", "release", "r-2"));
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-3"), NOW).is_some());
let sums = format!("{} Arca_0.7.0_x64-setup.exe\n", "c".repeat(64));
let cases: [(&str, Request); 5] = [
("another repository", minisign("Fabrica", "release", "r-3")),
("another pipeline", minisign("Arca", "deploy", "r-3")),
("another key and kind", authenticode("Arca", "r-3")),
(
"another kind of the same key",
Request {
kind: SignKind::Manifest,
digest: vec![],
manifest: Some(sums),
..minisign("Arca", "release", "r-3")
},
),
("the server runner", Request { via: Via::Remote, ..minisign("Arca", "release", "r-3") }),
];
for (what, req) in cases {
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}: the key itself would sign it");
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
let r = v.signing_sign(&req, Approval::Standing, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{what}: {r:?}");
}
assert_eq!(v.standing_rules()[0].uses, 0);
}
#[test]
fn a_request_out_of_the_keys_scope_never_fits_and_narrowing_the_scope_stops_the_rule() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
// Out of scope today: no rule can be made for it.
assert!(v.standing_grant(&minisign("Postea", "release", "r-2"), NOW).is_err());
assert!(v.standing_grant(&minisign("Arca", "nightly", "r-2"), NOW).is_err());
assert!(v.standing_rules().is_empty());
always(&mut v, &minisign("Arca", "release", "r-2"));
// Mark narrows the key: Arca may no longer use it. The rule is still listed and no longer fits.
v.signing_set_scope("domi-release", &s(&["release"]), &s(&["Fabrica"])).unwrap();
let req = minisign("Arca", "release", "r-3");
assert!(v.standing_rule_for(&req, NOW).is_none());
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW), Err(Refusal::OutOfScope(_))));
assert_eq!(v.standing_rules().len(), 1);
}
#[test]
fn a_request_without_a_run_never_fits() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let no_run = Request { run: None, ..minisign("Arca", "release", "x") };
assert!(v.standing_grant(&no_run, NOW).is_err(), "and cannot start a rule");
always(&mut v, &minisign("Arca", "release", "r-2"));
assert!(v.standing_rule_for(&no_run, NOW).is_none());
assert!(matches!(v.signing_sign(&no_run, Approval::Standing, NOW), Err(Refusal::NeedsApproval(_))));
}
#[test]
fn a_keys_first_signature_cannot_start_a_rule() {
let mut v = vault();
let first = minisign("Arca", "release", "r-1");
assert!(v.standing_can_grant(&first, NOW).is_err());
assert!(v.standing_grant(&first, NOW).is_err(), "the key has never signed");
assert!(v.standing_rules().is_empty());
// A refused or expired card is not a signature either.
v.signing_refuse(&first, Outcome::Refused, None, NOW);
assert!(v.standing_grant(&first, NOW).is_err());
// Mark signs once on the card; from then on the key can have a rule.
mark_signs(&mut v, &first);
assert!(v.standing_can_grant(&minisign("Arca", "release", "r-2"), NOW).is_ok());
// Another key of the same vault has still never signed.
assert!(v.standing_grant(&authenticode("Arca", "r-2"), NOW).is_err());
}
#[test]
fn a_test_key_and_a_server_runners_release_signature_cannot_start_a_rule() {
let mut v = vault();
let test = Request {
key: "domi-test".into(),
context: Context { trigger: "push".into(), ..ctx("ci", "Arca") },
..minisign("Arca", "ci", "r-1")
};
v.signing_sign(&test, Approval::Auto, NOW).unwrap();
assert!(v.standing_grant(&test, NOW).is_err(), "a test key signs without asking anyway");
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let remote = Request { via: Via::Remote, ..minisign("Arca", "release", "r-2") };
assert!(v.standing_can_grant(&remote, NOW).is_err());
assert!(v.standing_grant(&remote, NOW).is_err(), "a release signature asked through the mailbox");
assert!(v.standing_rules().is_empty());
}
#[test]
fn an_approval_rule_holds_only_for_the_targets_it_was_granted_for() {
let mut v = vault();
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
let id = always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
let r = &v.standing_rules()[0];
assert_eq!((r.repo.as_str(), r.pipeline.as_str(), r.via), ("Aula", "deploy", Via::Remote));
assert_eq!(r.targets, s(&["deploy to nixos-vm"]));
assert!(v.standing_rule_for(&approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Remote), NOW).is_some());
// A target Mark has not seen, alone or next to the known one; another repository; the same from this PC.
for (what, req) in [
("a new target", approval("Aula", "r-3", &["publish to Aula"], Via::Remote)),
(
"a new target next to the old",
approval("Aula", "r-3", &["deploy to nixos-vm", "publish to Aula"], Via::Remote),
),
("another repository", approval("Arca", "r-3", &["deploy to nixos-vm"], Via::Remote)),
("this PC's pipe", approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Local)),
] {
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}");
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
}
// Granting again on a card that shows the new target adds it to the same rule.
let wider = approval("Aula", "r-4", &["deploy to nixos-vm", "publish to Aula"], Via::Remote);
assert_eq!(always(&mut v, &wider), id);
assert_eq!(v.standing_rules().len(), 1);
assert_eq!(v.standing_rules()[0].targets, s(&["deploy to nixos-vm", "publish to Aula"]));
let signed =
v.signing_sign(&approval("Aula", "r-5", &["publish to Aula"], Via::Remote), Approval::Standing, NOW + 9);
assert!(signed.is_ok(), "{signed:?}");
assert_eq!(v.signing_audit().last().unwrap().context.file, "approval-r-5.json");
}
#[test]
fn sign_only_with_a_card_pauses_every_rule() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
always(&mut v, &minisign("Arca", "release", "r-2"));
let req = minisign("Arca", "release", "r-3");
v.security_tick(Item::CardSigning, NOW + 2);
assert!(v.standing_rule_for(&req, NOW + 3).is_none());
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 3), Err(Refusal::NeedsApproval(_))));
assert!(v.standing_can_grant(&req, NOW + 3).is_err(), "and no new rule while it is ticked");
assert_eq!(v.standing_rules().len(), 1, "the rule is kept, paused");
// Other checklist items do not pause it.
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 4);
v.security_tick(Item::NoAutoConnect, NOW + 4);
assert!(v.standing_rule_for(&req, NOW + 5).is_some());
}
#[test]
fn a_revoked_rule_no_longer_fits_and_both_are_in_the_security_audit() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
assert!(!v.standing_revoke("0000000000000000", NOW + 2), "no such rule");
assert!(v.standing_revoke(&id, NOW + 3));
assert!(!v.standing_revoke(&id, NOW + 4), "once");
assert!(v.standing_rules().is_empty());
let req = minisign("Arca", "release", "r-3");
assert!(v.standing_rule_for(&req, NOW + 5).is_none());
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 5), Err(Refusal::NeedsApproval(_))));
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
let notes: Vec<(Action, String)> = v
.security_view(NOW + 6)
.audit
.into_iter()
.filter(|e| matches!(e.action, Action::StandingGranted | Action::StandingRevoked))
.map(|e| (e.action, e.detail.unwrap_or_default()))
.collect();
assert_eq!(notes.len(), 2, "{notes:?}");
assert_eq!(notes[0].0, Action::StandingGranted);
assert_eq!(notes[1].0, Action::StandingRevoked);
for (_, d) in &notes {
assert!(
d.contains("Arca") && d.contains("domi-release") && d.contains("minisign") && d.contains("release"),
"{d}"
);
}
// The public note call cannot write them.
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
}
#[test]
fn rules_and_the_standing_outcome_survive_a_reopen() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
always(&mut v, &minisign("Arca", "release", "r-2"));
always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
v.signing_sign(&minisign("Arca", "release", "r-3"), Approval::Standing, NOW + 5).unwrap();
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.standing_rules(), v.standing_rules());
assert_eq!(back.standing_rules().len(), 2);
assert_eq!(back.signing_audit(), v.signing_audit());
// After the restart the rule still answers, and still only what it was granted for.
assert!(back.signing_sign(&minisign("Arca", "release", "r-4"), Approval::Standing, NOW + 9).is_ok());
assert!(back.standing_rule_for(&minisign("Fabrica", "release", "r-4"), NOW + 9).is_none());
assert_eq!(back.standing_rules().iter().find(|r| r.repo == "Arca").unwrap().uses, 2);
}
#[test]
fn signing_with_standing_and_no_rule_is_refused_and_recorded() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let req = minisign("Arca", "release", "r-2");
let r = v.signing_sign(&req, Approval::Standing, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{r:?}");
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Refused]);
assert!(v.signing_audit()[1].signature.is_none());
}
#[test]
fn an_android_keys_rule_signs_its_apks_and_nothing_else() {
let spec = AndroidKey {
id: "postea-android".into(),
name: "Postea Android".into(),
cn: "Postea".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["mnovak/Postea"]),
};
let apk = |run: &str| Request {
key: "postea-android".into(),
kind: SignKind::Apk,
digest: vec![3; 128],
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Postea") },
..minisign("mnovak/Postea", "release", run)
};
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create_android(&spec, NOW).unwrap();
// The first signature (the card says so) cannot be the one that starts the rule.
assert!(v.standing_grant(&apk("r-1"), NOW).is_err());
mark_signs(&mut v, &apk("r-1"));
always(&mut v, &apk("r-2"));
let signed = v.signing_sign(&apk("r-3"), Approval::Standing, NOW + 2).expect("an APK fits its rule");
assert_eq!(signed.bytes.len(), 2 * 512, "v2 and v3, RSA-4096");
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
// Postea's rule says nothing about another repository: that is out of the key's scope, as before.
let other = Request {
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Other") },
..apk("r-4")
};
assert!(matches!(v.signing_sign(&other, Approval::Standing, NOW + 3), Err(Refusal::OutOfScope(_))));
}
+485
View File
@@ -0,0 +1,485 @@
//! Team vaults (docs/TEAM.md, core 0.18.0): opening, adding and removing members, the policy, signing every
//! format, replays, target credentials.
use custos_team::external::{ExternalSigner, SignerCredential};
use custos_team::policy::{EnvRule, KeyRole};
use custos_team::request::{Artifact, Format, SignRequest, TargetRequest};
use custos_team::target::{TargetKind, TargetRelease};
use custos_team::{MemberKey, TeamError, verify_proof};
use custos_vault::{Error, NewSigner, NewTarget, SecretString, Vault};
const NOW: i64 = 1_794_000_000_000;
const NOW_S: u64 = 1_794_000_000;
struct Team {
vault: Vault,
a: MemberKey,
b: MemberKey,
}
/// Mark founds a team, makes its keys and adds Petra (comparing her join code).
fn team() -> Team {
let a = MemberKey::generate();
let b = MemberKey::generate();
let mut vault = Vault::create_team("Domi", &a, "Mark", &["mnovak".into()], NOW).unwrap();
vault.team_create_keys(&a.id(), NOW).unwrap();
let code = b.public().join_code();
vault.team_add_member(&b.public(), "Petra", &["petra".into()], &a.id(), &code, NOW).unwrap();
Team { vault, a, b }
}
fn request(vault: &Vault, env: &str, author: &str, format: Format, fabrica: &custos_seal::Recipient) -> String {
let (digest, image) = match format {
Format::Minisign | Format::TauriUpdater => (custos_sign::blake2b512(b"the installer").to_vec(), ""),
Format::Apk => (vec![5u8; 128], ""),
Format::Cosign => (vec![6u8; 32], "registry.example/domi/arca"),
Format::Authenticode => (vec![7u8; 32], ""),
};
SignRequest {
team: vault.team_view().unwrap().id,
id: custos_team::new_id(),
project: "mnovak/Arca".into(),
release: "0.7.0".into(),
env: env.into(),
author: author.into(),
format,
artifact: Artifact {
name: "Arca_0.7.0_x64-setup.exe".into(),
size: 13,
sha256: custos_sign::sha256_hex(b"the installer"),
},
artifact_digest: digest.to_vec(),
image: image.into(),
public: fabrica.public(),
expires: NOW_S + 3600,
}
.canonical()
}
#[test]
fn members_open_the_team_vault_and_outsiders_do_not() {
let t = team();
let bytes = t.vault.to_bytes().unwrap();
let (id, epoch, members) = Vault::team_peek(&bytes).unwrap();
assert_eq!((id.as_str(), epoch, members.len()), (t.vault.team_view().unwrap().id.as_str(), 1, 2));
for k in [&t.a, &t.b] {
let v = Vault::open_team(&bytes, k).unwrap();
assert!(v.is_team());
assert_eq!(v.team_view().unwrap().members.len(), 2);
assert_eq!(v.signing_keys().len(), 4);
}
assert!(matches!(Vault::open_team(&bytes, &MemberKey::generate()), Err(Error::NotAMember)));
// A team vault is not a two-factor vault, and a personal vault is not a team vault.
assert!(Vault::factor_kinds(&bytes).unwrap().is_empty());
let mut personal =
Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 })
.unwrap();
assert!(matches!(Vault::open_team(&personal.to_bytes().unwrap(), &t.a), Err(Error::NotATeam)));
// A changed header byte (a member slot moved to another epoch) does not open.
let mut moved = bytes.clone();
moved[9 + 3 + 32] ^= 1;
assert!(Vault::open_team(&moved, &t.a).is_err());
// The member key lives in the member's own vault and survives a save.
personal.member_key_create(NOW).unwrap();
let again = Vault::open(&personal.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(again.member_key().unwrap().id(), personal.member_key().unwrap().id());
}
#[test]
fn a_wrong_join_code_adds_nobody() {
let mut t = team();
let c = MemberKey::generate();
let wrong = if c.public().join_code() == "111111" { "222222" } else { "111111" };
let e = t.vault.team_add_member(&c.public(), "Eve", &[], &t.a.id(), wrong, NOW).unwrap_err();
assert!(e.to_string().contains("match code"), "{e}");
assert_eq!(t.vault.team_view().unwrap().members.len(), 2);
// An outsider cannot add anyone either.
let code = c.public().join_code();
assert!(t.vault.team_add_member(&c.public(), "Eve", &[], &c.id(), &code, NOW).is_err());
}
/// Mandatory: removing a member rotates the team key; the old member cannot unwrap anything created after.
#[test]
fn a_removed_member_cannot_open_anything_written_after() {
let mut t = team();
let before = t.vault.to_bytes().unwrap();
assert!(Vault::open_team(&before, &t.b).is_ok());
t.vault
.team_add_target(
NewTarget {
kind: TargetKind::SshKey,
name: "web-1".into(),
project: "mnovak/Arca".into(),
env: "production".into(),
host: "web-1.example".into(),
user: "deploy".into(),
secret: SecretString::from("-----BEGIN OPENSSH PRIVATE KEY-----\nold\n"),
},
&t.a.id(),
NOW,
)
.unwrap();
let removal = t.vault.team_remove_member(&t.b.id(), &t.a.id(), NOW + 1).unwrap();
assert_eq!(removal.epoch, 2);
assert_eq!(removal.rotate, vec!["target web-1".to_string()]);
// Something created after the removal.
t.vault
.team_add_target(
NewTarget {
kind: TargetKind::Registry,
name: "registry".into(),
project: "mnovak/Arca".into(),
env: "production".into(),
host: String::new(),
user: String::new(),
secret: SecretString::from("new-registry-token-after-removal"),
},
&t.a.id(),
NOW + 2,
)
.unwrap();
let after = t.vault.to_bytes().unwrap();
// B has no slot, and B's old slot (from the earlier file) does not open the new body.
assert!(matches!(Vault::open_team(&after, &t.b), Err(Error::NotAMember)));
let (_, epoch, members) = Vault::team_peek(&after).unwrap();
assert_eq!((epoch, members), (2, vec![t.a.id()]));
let mut spliced = Vec::new();
let (hb, _) = header_len(&before);
let (ha, _) = header_len(&after);
spliced.extend_from_slice(&before[..hb]);
spliced.extend_from_slice(&after[ha..]);
assert!(Vault::open_team(&spliced, &t.b).is_err(), "the old key does not open the new body");
// The new token is in no byte of the file B can read.
assert!(!contains(&after, b"new-registry-token"));
// A still opens it, at epoch 2, and B is listed as removed.
let v = Vault::open_team(&after, &t.a).unwrap();
let view = v.team_view().unwrap();
assert_eq!((view.epoch, view.members.len(), view.removed[0].name.as_str()), (2, 1, "Petra"));
// The last member cannot be removed.
let mut v = v;
assert!(v.team_remove_member(&t.a.id(), &t.a.id(), NOW).is_err());
}
fn header_len(bytes: &[u8]) -> (usize, ()) {
let count = bytes[8] as usize;
let mut at = 9;
for _ in 0..count {
let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize;
at += 3 + len;
}
(at + 24, ())
}
fn contains(hay: &[u8], needle: &[u8]) -> bool {
hay.windows(needle.len()).any(|w| w == needle)
}
#[test]
fn a_member_refuses_an_older_copy_or_another_identity() {
let mut t = team();
let mut own =
Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 })
.unwrap();
// Mark's own vault holds his member key; the team was made with the same key.
let c = MemberKey::generate();
let code = c.public().join_code();
t.vault.team_add_member(&c.public(), "Third", &[], &t.a.id(), &code, NOW).unwrap();
own.member_key_create(NOW).unwrap();
let old = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
t.vault.team_remove_member(&c.id(), &t.a.id(), NOW).unwrap();
let new = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
own.member_note_team(&new).unwrap();
assert!(matches!(own.member_note_team(&old), Err(Error::TeamRollback)));
let impostor = Vault::create_team("Domi", &t.a, "Mark", &[], NOW).unwrap();
own.member_note_team(&impostor).unwrap(); // another id: a team of its own
assert_eq!(own.member_teams().len(), 2);
}
#[test]
fn the_policy_is_set_per_environment_signed_and_kept() {
let mut t = team();
let p = t
.vault
.team_set_rule(
EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![t.b.id()] },
&t.a.id(),
NOW,
)
.unwrap();
assert_eq!(p.rev, 2);
assert!(
t.vault
.team_set_rule(
EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec!["ab".repeat(16)] },
&t.a.id(),
NOW
)
.is_err()
);
let v = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.b).unwrap();
let (text, sig) = v.team_policy_signed().unwrap();
assert!(custos_team::member::verify_policy_sig(&v.team_identity().unwrap(), &text, &sig));
assert_eq!(v.team_policy().unwrap().rule("staging").unwrap().approvers, vec![t.b.id()]);
assert!(
v.team_audit().unwrap().iter().any(|e| e.detail.as_deref() == Some("staging: 1 approval(s), not the author"))
);
}
/// Mandatory: a signing request with a wrong or replayed match code is refused.
#[test]
fn wrong_and_replayed_match_codes_are_refused() {
let mut t = team();
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
let code = fabrica.match_code();
let wrong = if code == "000000" { "000001" } else { "000000" };
// Petra's card showed another code: nothing is signed, nothing recorded as seen.
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(wrong), None, NOW).unwrap_err(), TeamError::WrongMatch);
assert_eq!(t.vault.team_approve(&text, &t.b, wrong, NOW).unwrap_err(), TeamError::WrongMatch);
// The author may not approve production in a team of two.
assert!(matches!(t.vault.team_sign(&text, &[], &t.a, Some(&code), None, NOW), Err(TeamError::NotEligible(_))));
// Petra with the right code signs.
let reply = t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap();
// A refusal after the signature is refused too: nothing contradicts what was signed (core 0.18.1).
assert!(t.vault.team_refuse(&text, &t.a.id(), "late", NOW).unwrap_err().to_string().contains("replay"));
// The same request again (a replay): refused, by this vault, whoever asks.
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::Replayed);
assert_eq!(t.vault.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed);
// ... also after a save and reopen, and in Mark's copy once he has the saved file.
let reopened = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
assert_eq!(reopened.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed);
// Petra's approval statement from this request does not count for another one.
let other = request(&t.vault, "production", "mnovak", Format::Minisign, &custos_seal::Recipient::generate());
let statements: Vec<_> = custos_team::proof::ProofBody::parse(&reply.proof.text).unwrap().approvals;
let req = SignRequest::parse(&other).unwrap();
let eval = t.vault.team_evaluate(&req, &statements).unwrap();
assert!(eval.counted.is_empty());
// An expired request.
let late = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica);
assert_eq!(
t.vault.team_sign(&late, &[], &t.a, Some(&code), None, NOW + 3_601_000).unwrap_err(),
TeamError::Expired
);
}
#[test]
fn two_approvals_collect_statements_and_the_last_approver_signs() {
let mut t = team();
let c = MemberKey::generate();
let code = c.public().join_code();
t.vault.team_add_member(&c.public(), "Jan", &[], &t.a.id(), &code, NOW).unwrap();
t.vault
.team_set_rule(
EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] },
&t.a.id(),
NOW,
)
.unwrap();
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
let code = fabrica.match_code();
// Petra alone is not enough: she approves (a statement), she does not sign.
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::NeedMore(1));
let petra = t.vault.team_approve(&text, &t.b, &code, NOW).unwrap();
// Mark's statement (the author) does not count; Jan's does, and Jan signs.
let reply = t.vault.team_sign(&text, &[petra.clone()], &c, Some(&code), None, NOW).unwrap();
let v = verify_proof(&reply.proof, &t.vault.team_identity().unwrap(), &text, reply.envelope()).unwrap();
assert_eq!(v.approvers.len(), 2);
assert_eq!(v.signer, c.id());
let audit = t.vault.signing_audit().last().unwrap().clone();
assert_eq!(audit.by.as_deref(), Some(c.id().as_str()));
assert_eq!(audit.approvers.len(), 2);
assert_eq!(audit.env.as_deref(), Some("production"));
}
struct FakeHsm(custos_sign::RsaSecret);
impl ExternalSigner for FakeHsm {
fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result<Vec<u8>, String> {
if signer.secret != "hsm-pin" {
return Err("wrong credential".into());
}
custos_sign::authenticode(&self.0, digest).map_err(|e| e.to_string())
}
}
/// Every format signs and the proof checks; the signatures verify (minisign-verify is minisign's and Tauri's own
/// verifier; cosign with p256 here and openssl in custos-sign's tests).
#[test]
fn every_format_signs_with_the_right_key_and_verifies() {
let mut t = team();
let identity = t.vault.team_identity().unwrap();
t.vault
.team_create_android(
&custos_vault::signing::AndroidKey {
id: "arca-android".into(),
name: "Arca Android".into(),
cn: "Arca".into(),
o: "Domi".into(),
c: "CZ".into(),
role: custos_vault::signing::Role::Release,
pipelines: vec!["*".into()],
repos: vec!["mnovak/Arca".into()],
},
&t.a.id(),
NOW,
)
.unwrap();
let hsm = custos_sign::new_root("Fake HSM", 1).unwrap();
t.vault
.team_add_signer(
NewSigner {
name: "Fake cloud signer".into(),
adapter: "command".into(),
endpoint: "https://signer.example".into(),
account: "domi".into(),
secret: SecretString::from("hsm-pin"),
certificate: hsm.cert_der.clone(),
},
&t.a.id(),
NOW,
)
.unwrap();
let ext = FakeHsm(hsm.secret);
for format in [Format::Minisign, Format::TauriUpdater, Format::Cosign, Format::Apk, Format::Authenticode] {
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "production", "mnovak", format, &fabrica);
let reply = t.vault.team_sign(&text, &[], &t.b, Some(&fabrica.match_code()), Some(&ext), NOW).unwrap();
let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap();
assert_eq!(v.role, KeyRole::Release, "{format:?}");
assert_eq!(reply.signer.name, "Petra");
match format {
Format::Minisign | Format::TauriUpdater => {
assert_eq!(reply.key.id, "team-release");
let minisig = if format == Format::TauriUpdater {
custos_sign::tauri_updater_open(&reply.signature).unwrap()
} else {
reply.signature.clone()
};
let pk = minisign_verify::PublicKey::decode(&reply.key.public).unwrap();
pk.verify(b"the installer", &minisign_verify::Signature::decode(&minisig).unwrap(), true).unwrap();
}
Format::Cosign => {
assert_eq!(reply.key.id, "team-cosign");
let payload = reply.payload.as_deref().unwrap();
assert!(payload.contains("\"docker-reference\":\"registry.example/domi/arca\""));
let der = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap();
assert!(custos_sign::cosign_verify(&reply.key.public, payload.as_bytes(), &der));
}
Format::Apk => {
assert_eq!(reply.key.id, "arca-android");
let sig = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap();
assert_eq!(sig.len(), 2 * 512);
assert!(reply.key.public.starts_with("-----BEGIN CERTIFICATE-----"));
}
Format::Authenticode => {
assert!(reply.key.id.starts_with("signer:"));
assert_eq!(data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap().len(), 384);
}
}
}
// Preview: 0 approvals, the test key, no code needed; a release key never signs it.
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "preview", "mnovak", Format::Minisign, &fabrica);
let reply = t.vault.team_sign(&text, &[], &t.a, None, None, NOW).unwrap();
assert_eq!(reply.key.id, "team-preview");
let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap();
assert_eq!(v.role, KeyRole::Test);
// Authenticode is never signed without an approval, and not without the adapter.
let text = request(&t.vault, "preview", "mnovak", Format::Authenticode, &fabrica);
assert!(t.vault.team_sign(&text, &[], &t.a, None, Some(&ext), NOW).is_err());
let text = request(&t.vault, "production", "mnovak", Format::Authenticode, &custos_seal::Recipient::generate());
let code = SignRequest::parse(&text).unwrap().match_code();
assert!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).is_err());
}
#[test]
fn a_target_credential_is_released_once_for_a_signed_deployment_of_its_project_and_environment() {
let mut t = team();
let target = t
.vault
.team_add_target(
NewTarget {
kind: TargetKind::Kubeconfig,
name: "prod cluster".into(),
project: "mnovak/Arca".into(),
env: "production".into(),
host: "k8s.example".into(),
user: "fabrica".into(),
secret: SecretString::from("apiVersion: v1\nkind: Config\n"),
},
&t.a.id(),
NOW,
)
.unwrap();
assert!(!format!("{:?}", t.vault.team_targets().unwrap()).contains("apiVersion"));
let team_id = t.vault.team_view().unwrap().id;
let fabrica = custos_seal::Recipient::generate();
let ticket_of = |r: &custos_team::reply::SignReply| -> [u8; 32] {
data_encoding::BASE64.decode(r.ticket.as_deref().unwrap().as_bytes()).unwrap().try_into().unwrap()
};
let ask = |deployment: &str, ticket: &[u8; 32]| {
TargetRequest {
team: team_id.clone(),
id: custos_team::new_id(),
target: target.clone(),
deployment: deployment.into(),
public: fabrica.public(),
expires: NOW_S + 600,
mac: [0; 32],
}
.sign_with(ticket)
.canonical()
};
// No signed deployment yet.
let unsigned = "ab".repeat(32);
assert!(t.vault.team_target_release(&ask(&unsigned, &[1; 32]), &t.b.id(), NOW).is_err());
// A staging deployment is not a production one.
let staging = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica);
let r = t.vault.team_sign(&staging, &[], &t.a, Some(&fabrica.match_code()), None, NOW).unwrap();
assert!(t.vault.team_target_release(&ask(&r.request, &ticket_of(&r)), &t.b.id(), NOW).is_err());
let prod = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
let r = t.vault.team_sign(&prod, &[], &t.b, Some(&fabrica.match_code()), None, NOW).unwrap();
// Someone who knows the deployment's hash (the service, another connection) but not its ticket gets nothing.
let e = t.vault.team_target_release(&ask(&r.request, &[7; 32]), &t.b.id(), NOW).unwrap_err();
assert!(e.to_string().contains("ticket"), "{e}");
let ask = |deployment: &str| ask(deployment, &ticket_of(&r));
let (json, req) = t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap();
let released: TargetRelease = serde_json::from_str(&json).unwrap();
assert_eq!((released.secret.as_str(), released.env.as_str()), ("apiVersion: v1\nkind: Config\n", "production"));
assert!(!format!("{released:?}").contains("apiVersion"));
assert_eq!(req.reply_context(), format!("team-target:{}", req.id).into_bytes());
// Once per deployment.
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap_err().to_string().contains("replay"));
// Too late: a deployment signed more than 25 hours ago.
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW + 26 * 3_600_000).is_err());
assert!(t.vault.team_audit().unwrap().iter().any(|e| e.action == custos_vault::TeamAction::TargetReleased));
}
#[test]
fn nothing_secret_prints_or_reaches_a_view() {
let mut t = team();
t.vault
.team_add_signer(
NewSigner {
name: "HSM".into(),
adapter: "command".into(),
endpoint: String::new(),
account: String::new(),
secret: SecretString::from("very-secret-pin-123"),
certificate: vec![],
},
&t.a.id(),
NOW,
)
.unwrap();
let shown = format!(
"{:?} {:?} {:?} {:?}",
t.vault,
t.vault.team_view(),
t.vault.team_signers().unwrap(),
serde_json::to_string(&t.vault.team_view()).unwrap()
);
assert!(!shown.contains("very-secret-pin-123"));
assert!(!contains(&t.vault.to_bytes().unwrap(), b"very-secret-pin-123"));
}
+2
View File
@@ -23,3 +23,5 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = "0.4"
# rand_core 0.6 (custos-sign, through custos-vault) uses getrandom 0.2: the same browser CSPRNG (lib.rs, `fill_v02`).
getrandom02 = { package = "getrandom", version = "0.2", features = ["custom"] }
+32
View File
@@ -123,6 +123,15 @@ enum Request {
r#pub: String,
context: String,
},
/// Pairs this phone as a Domi device (Custos docs/07_domi_identity.md): seals its device label and its
/// Ed25519 device public key (`device`, base64url, made non-extractable by the page) to the PC that
/// waits with `pub`, for `domi-pair:<id>`. Returns the box and its sender code. Nothing secret goes in.
DomiPair {
r#pub: String,
id: String,
label: String,
device: String,
},
}
fn err(msg: impl ToString) -> Value {
@@ -415,6 +424,21 @@ pub fn handle(request: &[u8]) -> Value {
Err(e) => err(e),
}
}
Request::DomiPair { r#pub, id, label, device } => {
let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32);
let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") };
let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect();
let plain = json!({ "label": label, "device": device }).to_string();
match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
}),
Err(e) => err(e),
}
}
Request::PhoneApprove { wrapped, prf, r#pub, context } => {
let (Some(wrapped), Some(prf_key), Some(public)) = (b64(&wrapped), key32(&prf), b64(&r#pub)) else {
return err("A malformed request.");
@@ -449,6 +473,14 @@ mod abi {
Ok(())
}
/// The same for getrandom 0.2, which rand_core 0.6 (custos-sign's RSA and X.509 crates) is built on. The
/// browser never makes signing keys, but the crates must link.
fn fill_v02(dest: &mut [u8]) -> Result<(), getrandom02::Error> {
unsafe { random_fill(dest.as_mut_ptr(), dest.len()) };
Ok(())
}
getrandom02::register_custom_getrandom!(fill_v02);
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
if len == 0 {
+18
View File
@@ -138,3 +138,21 @@ fn a_phone_pairs_then_opens_and_approves() {
let pw = SecretString::from(PASSWORD);
assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok());
}
#[test]
fn a_phone_pairs_as_a_domi_device() {
// The PC waits with a one-time key; the phone seals its device public key and label to it.
let pc = Recipient::generate();
let device = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 32]);
let r = call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }));
assert_eq!(r["ok"], true, "{r}");
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap());
assert!(pc.open(&sealed, b"domi-pair:other").is_err(), "the box is for this pairing only");
let plain: Value = serde_json::from_slice(&pc.open(&sealed, b"domi-pair:abc_-1").unwrap()).unwrap();
assert_eq!(plain, json!({ "label": "Pixel", "device": device }));
// Malformed: a device key of the wrong length, an id that would change the context.
let short = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 31]);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }))["ok"], false);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }))["ok"], false);
}
+99
View File
@@ -0,0 +1,99 @@
# Custos in the browser
Version 1 of the browser extension: Chromium (Edge and Chrome) on Windows, logins only. Passkeys come later.
The extension, its native host and the rule that decides which login belongs on which page are all in this
public repository, so anyone can read what the browser side does. The desktop app (the private `Custos`
repo) holds the vault and answers the host; its side is `docs/13_browser.md` there.
```
page ─(content script)─► service worker ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe
extension/content.js extension/background.js crates/custos-native the desktop app
```
## The pieces
| Piece | What it does | What it never does |
|:--|:--|:--|
| `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on click asks for the logins of *its own frame*, and fills the one the person picks. | Fill without a click; read anything from Custos before the list is opened; trust what the page says about its own address. |
| `extension/popup.*` | The toolbar popup: the logins for the active tab; a click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. |
| `extension/background.js` | Owns the one connection to the native host; turns each request into `browser_status`, `browser_match` or `browser_fill`, with the origin taken from **`sender.url`** (the frame's real URL, as the browser reports it). | Accept messages from pages or other extensions (`sender.id` must be its own). |
| `crates/custos-native` | The native messaging host. Reads frames from stdin, **rebuilds** each request from its known fields (op, origin ≤ 2 KiB, id ≤ 128 bytes, seq), forwards it to the Custos pipe and returns the answer. | Forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed answers are zeroized). |
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match` (which login fits which page) and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
## Which login goes where (`custos-browser`)
A page's origin is `scheme://host[:port]`, host lowercased, trailing dot removed. A login's stored `url`
fields (an item may have several) match a page when:
1. the page is **fillable**: `https`, or plain `http` only on this machine (`localhost`, `*.localhost`,
`127.0.0.1`, `[::1]`). Plain http on the internet is never filled, even for a login saved with `http://`;
2. the schemes are equal (a stored URL without a scheme means `https`);
3. the ports are equal (the stored URL's port, or the scheme's default when it names none);
4. the page's host is the login's host (**exact**; `www.` counts as the host) or a subdomain of it
(**subdomain**: `accounts.github.com` for `github.com`). A login for a subdomain never goes to its parent
or to a sibling. A login for an IP address or a bare name (`cz`) matches only that exact host.
URLs with userinfo (`https://bank.cz@evil.net`) are refused outright. Look-alikes (`github.com.evil.net`,
`githuh.com`, punycode twins) never match, because nothing is compared but labels. Exact matches are offered
before subdomain matches, then by title; at most 50 logins per page.
## The messages
Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON. The host accepts at most 64 KiB per
message (the desktop pipe's limit). Every request may carry `seq` (a number); the answer carries it back.
| Extension → host | Host → Custos | Answer |
|:--|:--|:--|
| `{"op":"browser_status"}` | `{"op":"browser_status","app":"Custos for your browser"}` | `{"ok":true}` |
| `{"op":"browser_match","origin":"https://github.com"}` | + `origin` | `{"ok":true,"logins":[{"id","title","username"}]}`: never a password |
| `{"op":"browser_fill","id":"…","origin":"…"}` | + `origin`, `id` | `{"ok":true,"username","password","totp"}` only if that login matches `origin`, else `"error":"no_match"` |
Errors the extension turns into a sentence: `not_connected` (no host registered), `not_running`,
`not_custos` (the pipe's server is not `custos.exe`: nothing was sent), `locked`, `denied`, `not_found`,
`no_match`, `no_answer`, `bad_request`.
## What Custos checks (the desktop's side, summarised)
- The host is a Domi client like any other: Custos identifies it by its executable and asks the person once
whether it may use **`web-logins/`**. That grant is the browser's only; no `domi://` ref may use the
`web-logins` namespace and the browser ops reach nothing else.
- Custos parses the origin again with `custos-browser` and checks the login against it on **every**
`browser_fill`, whatever the extension asked for before.
- Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then
answers `locked`.
## Registration and the extension id
The extension's `manifest.json` carries a public `key`, which fixes its id to
**`jchkapmceepdnlhagfppeckggaecdcmn`** however it is loaded (unpacked or packed). The desktop's *Connect*
writes the host manifest with `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]`
and registers it under `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` and
`HKCU\Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos`, so only this extension can start
the host. The private key that matches the public key is not in this repository; it is only needed to pack a
`.crx` with the same id.
## Threat model, briefly
- A malicious **page** cannot ask for a login: content scripts run in an isolated world, the button and list
are in a closed shadow root, the origin comes from the browser, and filling needs a click in Custos's own UI.
A page *can* read what was filled into its own fields: that is what filling is.
- A malicious **frame** on a good site is a different origin: it gets only its own origin's logins.
- Another **extension** cannot message this one (`sender.id`), and cannot start the host (`allowed_origins`).
- A program that **impersonates Custos** by creating the pipe first gets nothing: the host checks the pipe
server's image path ends in `\custos.exe` before writing the request. (A process of the same user that can
replace `custos.exe` is out of scope, as everywhere in Custos: docs/THREAT_MODEL.md.)
- The extension holds no secret at rest and no state beyond the open native port.
## Not yet
Passkeys (WebAuthn through the extension), Firefox, saving new logins from the browser, filling cards.
## Tests
```
cargo test -p custos-browser -p custos-native
```
`custos-browser` covers origin parsing, look-alikes, ports and schemes, bare names and IPs, best-of-several and
the frames; `custos-native` that only the three ops pass, rebuilt from known fields. The desktop repo has the
pipe tests and an end-to-end run in Edge.
+59
View File
@@ -10,6 +10,13 @@ on, Custos writes it as v2 only.
A **machine store** (the Claude Code store) is the one exception: a separate file whose vault key is
wrapped by one device key alone, so a program can open it unattended. It never holds the user's secrets.
**Taking over a machine-key vault** (core 0.13.0, Custos's hands-off vault): `Vault::take_over(password)` adds the
master password as a factor paired with the device key and removes the single slot, in one step. From then on it is
an ordinary version-2 vault: two factors open it, the device key alone does not, and factors are added as for any
vault (a phone, a TOTP backup). Only a machine-key vault is taken over, and only once; `opens_with_machine_key()`
says which it is. The take-over also ticks `no-auto-connect`, `no-unattended` and `card-signing` and writes
`taken-over` (FORMAT.md, "The security member").
## Keys
```
@@ -72,6 +79,10 @@ is the whole header, as in v1.
### Limits a reader enforces
- 1 ..= 64 slots; at most 8 factor slots; a factor type outside 1..=5 is malformed.
- At most one recovery slot (kind 5, core 0.17.0), of exactly 108 bytes, and none in a machine store.
- A **team vault** (core 0.18.0, docs/TEAM.md) has 1 ..= 32 member slots (kind 6, 144 bytes) and no other slot;
a file that mixes member slots with any other kind is malformed. It is opened with `Vault::open_team` and a
member key, never with factors.
- A pair slot whose two ids are equal, or not in order, or name a factor that has no factor slot, is malformed.
- Argon2 limits as in v1, checked before any work.
- Material for types 2..5: 32 ..= 64 bytes, else `FactorRejected` before any work.
@@ -89,6 +100,54 @@ slot, then the body.
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
| A machine store: its one device factor unwraps, then the single slot | — |
## The recovery key (core 0.17.0)
A two-factor vault can have **one recovery key**: 32 random bytes that open the vault alone, for the day the
factors are gone (a forgotten password and a dead PC, a lost phone and a reinstalled Windows). It is the one
deliberate exception to "never one secret", and it is hedged accordingly:
- **It is made on request and returned once** (`Vault::recovery_create`). It is in no file and no log. The app
shows or prints it and keeps nothing. Making a new one replaces the old one.
- **It is never an everyday unlock.** `Vault::recover` is the only call that takes it. Before it returns the vault
it drops **every** factor, makes the new master password and one new second factor the vault's two factors, and
replaces the recovery key (the new one is returned, once). Whoever held the old password, an old PC key or a
phone holds nothing of the vault from the next save on. No `open` or `open_with` accepts a recovery key, as a
password or as material.
- **It is audited** in the security member: `recovery-created`, `recovery-removed`, `recovered`, each with the
key's id (never the key).
- A version-1 vault and a machine-key vault have none (`NeedTwoFactors`, `FactorRejected`).
- `recover` writes nothing. Until the caller saves, the file is as it was and the old factors still open it.
- The vault key stays the same across a recovery: a **copy of the file from before** still opens with the old
factors and the old recovery key. A recovery takes back the vault, not its old copies.
**As printed:** `id (4 bytes) ‖ key (32 bytes) ‖ check (4 bytes)` in base32 without padding, 64 characters in 8
groups of 8 (`A–Z`, `2–7`). The check is the first 4 bytes of `SHA-256("custos recovery key v1" ‖ id ‖ key)`.
A reader ignores case, spaces and hyphens; any other character, another length or a failed check is
`RecoveryKeyMistyped`, told apart from `WrongRecoveryKey` (a well-formed key that is not this vault's current one)
before the vault is touched. The **id** (8 hex characters) is not secret: it is in the header, shown in Settings
and printed next to the key, so the paper can be matched to the vault.
```
kind 5, recovery slot (at most one; never together with a single slot)
4 id
32 salt
24 wrap nonce
48 wrapped vault key KEK = HKDF-SHA256(key, salt, info "custos recovery v2")
AAD = magic ‖ version ‖ kind ‖ id ‖ salt ‖ nonce
```
It is not a factor: it has no factor slot, no pair slots and no entry in the body's `factors`, it does not count
toward the two factors or the limit of 8, and `factor_ids` does not list it. `Vault::recovery_id_of(bytes)` reads
its id from the header.
**Older readers.** A reader before core 0.17.0 knows slot kinds 2 to 4 and treats kind 5 as malformed: a vault
with a recovery key does not open in an older Custos ("the vault file is malformed"), and is not rewritten by
one. Removing the key (`recovery_remove`) makes the file readable by older readers again, apart from the three
audit actions, which they refuse like any unknown action (docs/FORMAT.md, "The security member").
**What it costs.** The paper is a complete way in. It is 256 bits, so it is not guessed; it is stolen, copied or
photographed. Keep it away from the PC and from the other vault's paper. Losing it loses nothing: make a new one.
## Which factors a file has
`Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed,
+125 -27
View File
@@ -119,6 +119,129 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
- 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);
since core 0.10.0 a cert may carry `revoked_at` and `revocation`.
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": "<base64>"}]`, 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.
- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request
(docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later.
- `provision` (optional, core 0.11.0): the Provisio audit, every outcome of a server's *ask* or *offer* (the app's
docs/10_provisio.md). An older Custos ignores it when it reads and drops it when it saves, so every Custos that
saves the vault must be 0.11.0 or later. See "The provision audit" below.
- `kind`, `team` (core 0.18.0): a team vault's body is `"kind": "team"` with the `team` member (docs/TEAM.md); no
other vault has either, and a team vault has no `factors`, `identity` or `member`.
- `member` (optional, core 0.18.0): a person's member key and the teams it opened (docs/TEAM.md). An older Custos
drops it when it saves, so every Custos that saves a member's vault must be 0.18.0 or later.
- `security` (optional, core 0.12.0): the security level, the hardening checklist and their audit (the app's
docs/11_runs_and_levels.md). An older Custos ignores it when it reads and drops it when it saves (the level falls
back to Standard, the checklist to unticked), so every Custos that saves the vault must be 0.12.0 or later. See
"The security member" below.
**Values older cores refuse.** A reader refuses a file whose closed lists hold a value it does not know (see each
member), so these values, new in core 0.12.0, make a vault unreadable for a core before 0.12.0 once they are
written: a `signing` audit entry of kind `approval` (docs/SIGNING.md), a `provision` entry with store `display` or
outcome `confirmed`. A vault without them still opens in core 0.11.0. Core 0.14.0 adds two more: a `signing` key
of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault that holds either does not open in a
core before 0.14.0. Core 0.16.0 adds the `signing` audit outcome `standing` and the `security` actions
`standing-granted` and `standing-revoked` (docs/SIGNING.md, "Standing approvals"): a vault in which a standing
approval was ever granted does not open in a core before 0.16.0. The rules themselves (`signing.standing`) are a
member older cores ignore and drop. Core 0.19.0 adds the member `signing.android` (the Android grant, docs/SIGNING.md "The Android
grant"), which older cores ignore and drop (the grant is lost, never widened). It adds no closed-list value:
a key the grant makes is `standing-granted` in the security audit (core 0.19.1), so a vault with the grant still
opens in every core since 0.16.0, as the phone app and the web vault may be.
### The provision audit (core 0.11.0)
```json
"provision": {
"audit": [
{ "at": 1793750100000, "direction": "offer", "host": "nixos-vm", "item": "fabrica/gitea-read-token",
"store": "vault", "run": "deploy-7", "kind": "Gitea token, read:repository", "code": "684361",
"outcome": "accepted", "replaced": true }
]
}
```
| Member | |
| :-- | :-- |
| `at` | Unix milliseconds |
| `direction` | `ask` (the server asked for a secret) or `offer` (the server offered one) |
| `host` | the name the factor service gave, 1–253 characters `[A-Za-z0-9.-]` |
| `item` | `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks it |
| `store` | `vault`, `claude`, `cloud` or (core 0.12.0) `display`: shown once on the card, stored nowhere |
| `run` | optional, `[A-Za-z0-9._-]{1,64}` |
| `kind` | optional, at most 200 characters, no control characters (an offer's label; an ask's `--generate` recipe) |
| `code` | the match code: six ASCII digits |
| `outcome` | `approved`, `generated`, `accepted`, `refused`, `out-of-scope`, `invalid`, `expired` or (core 0.12.0) `confirmed` |
| `replaced` | `true` when an accepted offer replaced an existing item |
A **display offer** (core 0.12.0; a TOTP seed moved to a phone) is an `offer` with store `display`. Its outcome is
`confirmed` (Mark typed the phone's current code, Custos checked it and sent it to the server), `refused`, `expired`,
`invalid` or `out-of-scope`; never `accepted`, `approved` or `generated`, and never `replaced`, because nothing is
stored. `confirmed` belongs to display offers only. A code Custos's own check refuses stays on the card and is not
an outcome; a code the server then refuses (its exit 10) is not seen by Custos, so there is no `confirmed-wrong`.
- **No value, ever.** There is no member that holds a secret: every member is something the server sent in the
clear through the mailbox (host, item, store, run, kind) or derives from a public key (`code`). A recorded
entry is checked against the table above; an entry that does not fit is refused, not stored.
- **Append-only.** The API records an entry and lists them (oldest first); nothing edits or removes one, except
that the log keeps the newest 5 000 entries and drops the oldest beyond that.
- Readers ignore members of an entry they do not know. A file whose `provision` has an `outcome`, `direction` or
`store` this core does not know does not open (`Corrupted`), as for `signing`.
### The security member (core 0.12.0; hands-off values 0.13.0)
```json
"security": {
"setup": { "started": 1793750000000, "until": 1793757200000 },
"finished": 1793751000000,
"ticked": ["hello-approvals", "no-ssh"],
"keptScope": { "ask": ["arca/"], "offer": ["arca/", "fabrica/"] },
"audit": [
{ "at": 1793750000000, "action": "setup-started" },
{ "at": 1793751000000, "action": "setup-finished" },
{ "at": 1793752000000, "action": "ticked", "item": "no-ssh" },
{ "at": 1793753000000, "action": "unticked", "item": "no-ssh", "auth": "hello" }
]
}
```
| Member | |
| :-- | :-- |
| `setup` | optional: the last Setup window, Unix milliseconds; `until` is 2 hours after `started` |
| `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed |
| `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` |
| `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo |
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked` (also for the Android grant and the keys it makes), or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters |
The **level** is computed, never stored:
- **Setup** while there is a `setup` window, it has not `finished`, and `started` ≤ now < `until`;
- otherwise **Hardened** when at least one item is ticked;
- otherwise **Standard** (also every vault without the member).
Ticked items hold during Setup too: Setup never undoes hardening. Starting Setup while in Setup changes nothing;
after a window ended a new one starts at now. Its expiry is written (`setup-expired`, and `finished` = `until`) by
the first change after it, not by reading.
- **Append-only** like `provision`: the API adds entries and lists them; the log keeps the newest 5 000.
- Absent while nothing was ever set, so a vault without it is written exactly as before.
- The values new in core 0.13.0 make a vault unreadable for a core before 0.13.0 once one is written, as the
0.12.0 values did before.
- **Hands-off rules** (core 0.13.0, `security`): `is_setup_run` (`setup-` and 1–58 of `[A-Za-z0-9._-]`),
`auto_connect_allowed` (not Hardened, neither `no-auto-connect` nor `no-ssh`), `setup_on_connect` (neither
`no-unattended` nor `no-ssh`), `unattended_provision` (in Setup, a setup run, `no-unattended` not ticked, never an
existing item: an `ask --generate` or an `offer` into `arca/`, `custos/`, `fabrica/`, `aula/`, `gitea/`, an offer
into the Claude Code store, a TOTP offer unless `totp-on-phone`; never `display`) and `unattended_sign` (a
machine-key vault, a request with a run, not Hardened, `card-signing` not ticked, the kinds `minisign`,
`manifest`, `authenticode`, `approval`; never `apk`, core 0.14.0). The app enforces them; the server never decides.
- Readers ignore members they do not know. A file whose `security` has an item, action or auth this core does not
know, a window whose `until` is not after `started`, `finished` without `setup`, or a kept scope that breaks the
rules above does not open (`Corrupted`).
### Item types and their fields (v1)
@@ -135,34 +258,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)
+99
View File
@@ -0,0 +1,99 @@
# The Domi identity (`custos-vault`, `identity`)
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
subkey certificates and revocations of keys the person revoked. The certificate format, the match code and verification are in Fundamentum
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
## Creating it: the order is mandatory
```
entropy 32 bytes from the OS CSPRNG
mnemonic BIP39 English, 24 words, shown ONCE
confirm the person types 3 words the vault picks at random
root Ed25519 secret = HKDF-SHA256(salt = "tessera root v1", ikm = BIP39 seed(mnemonic, ""), info = "ed25519")
import the secret goes into the vault; entropy, seed and mnemonic are wiped
```
A key that was created non-extractable first could never be backed up. So the code cannot do it in the other
order: `identity::Enrollment` is a typestate.
| Type | Holds | Only way forward |
|:--|:--|:--|
| `Enrollment` | the entropy | `show(display)`: hands the 24 words to `display`, once |
| `Shown` | the entropy, 3 word positions | `confirm(words)`: the 3 words, or it hands itself back to try again |
| `Confirmed` | the derived root secret; the entropy is wiped | `import(&mut vault)`: stores the root, returns its public key |
`import` exists only on `Confirmed`, `Confirmed` only comes from `confirm`, and `confirm` only from `show`.
Swapping the order does not compile (`compile_fail` doctests in `src/identity.rs`). None of the three types
is `Clone` or `Serialize`; each prints `[redacted]`.
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
### Restoring it from the 24 words (core 0.10.0)
`Enrollment::restore(phrase)` takes the whole phrase, typed back, and gives a `Confirmed`: the person typed
all 24 words, which proves more than three. The words are checked against the BIP39 English list and its
checksum (any case, any spacing between them); anything else is `Error::NotAMnemonic`, which names no word.
The same words give the same root, so every app and every group trusts it again.
## In the vault file
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
```json
"identity": {
"root": "<64 hex: the Ed25519 secret>",
"public": "<64 hex>",
"created": 1793000000000,
"issued": [
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000,
"revoked_at": 1795000000, "revocation": ["<base64url TRV1>"] }
]
}
```
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
a trust list.
- `revoked_at` (Unix seconds, core 0.10.0) is set when the person revokes the key; `revocation` holds the
signed statements once they exist. Both are left out until then. A renewed key has several certs: all of
them are marked.
- **A Custos older than core 0.10.0 drops `revoked_at` and `revocation` when it saves the vault**, so a
revocation in progress would have to be started again.
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
## Using it
| Function | What |
|:--|:--|
| `Vault::domi_root_public()` | the root public key, if there is an identity |
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
| `Vault::domi_mark_revoked(subkey, at)` | the person revoked this key: marks every cert of it, returns the time in effect (the first one, if it was marked before) |
| `Vault::domi_sign_revocation(tbs)` | Ed25519 over `"tessera revoke v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TRV1`, this root's public key, a key marked revoked and that key's `revoked_at` |
| `Vault::domi_record_revocation(subkey, statements)` | keeps the signed statements with the key's certs |
| `Vault::domi_backup_secret(app_id)` | the app's backup secret (below) |
The prefix checks mean the vault is not a general signing oracle: whatever the app hands it, the result
can only ever verify as a certificate naming this root, or as a revocation of a key the person revoked, at
the time they did. The two domains differ, so neither can pass for the other. Statement format: Fundamentum
docs/TESSERA.md §12.
### The backup secret (core 0.10.0)
```
backup secret = HKDF-SHA256(salt = "tessera backup v1", ikm = the root secret, info = app id)
```
Custos hands an app its own (Domi pipe `backup_key`, behind the app's namespace grant); the app seals its
backup with it and names its backup mailbox from it (Fundamentum docs/TESSERA.md §12). It comes back from
the 24 words alone. The caller passes a valid app id (a-z, 0-9, `-`). Test vector, shared with Fundamentum:
the zero-entropy root, app `fiscus` → `HKDF-Expand(secret, "mailbox")` =
`IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU`, and XChaCha20-Poly1305 with
`HKDF-Expand(secret, "seal")`, a zero nonce and empty input = `ci_JRbtsx5prR83KT9Y7LA` (the tag).
## What it does not protect
The root secret is in the vault body, so everything in docs/THREAT_MODEL.md about an unlocked vault applies:
malware running as you while the vault is open can read it from memory. It never reaches the webview, the
Domi pipe, logs or the web vault.
+128
View File
@@ -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 (`<Data Hash="…">` 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 `<!DOCTYPE>` (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.
+23 -2
View File
@@ -20,8 +20,29 @@ aad "CSL1" ‖ E ‖ context
A box opens only with the context it was sealed for, so a box for one request does not work as another.
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
- **Plaintext limit:** 32 KiB.
- **The recipient's secret half** lives only in memory, as `x25519_dalek::StaticSecret` with `zeroize`,
and is wiped on drop. Nothing writes it to disk.
- **The recipient's secret half** lives in memory as `x25519_dalek::StaticSecret` with `zeroize`, and is
wiped on drop. One-time keys (`Recipient::generate`) are the default and nothing writes them to disk.
### A kept key (core 0.11.0)
The recipient's secret may now be kept by the caller, for one purpose: the PC's Provisio sealing key
(docs/10_provisio.md in the app), the key the server seals **offers** to. Custos makes it once with
`Recipient::generate`, keeps `Recipient::secret_bytes()` DPAPI-sealed in `<data> actors\provision.key`, and
restores it with `Recipient::from_secret` at every start. Everything else (approvals, pairing, a Provisio *ask*)
still uses a fresh one-time key per request.
```
Recipient::from_secret(Zeroizing<[u8; 32]>) -> Result<Recipient, SealError> // BadKey for a known key
Recipient::secret_bytes(&self) -> Zeroizing<[u8; 32]> // only for a key that is kept
```
- `from_secret` refuses (`BadKey`) a secret that X25519 clamps to zero (all zeros: a wiped or never-filled
buffer) and, as for public keys, one whose shared secrets would not be contributory.
- A kept key opens every box ever sealed to it, so the **context** carries the binding: an offer is sealed for
`provision-offer:<store>:<item>`, and the PC checks the plaintext's item, store, kind and code key against the
offer before it shows a card. The mailbox refuses an offer whose ephemeral key it has seen (replay).
- `secret_bytes` hands out the secret in a `Zeroizing` buffer. It goes to the caller's sealed storage and
nowhere else: never a log, a message or a file in the clear. `Debug` of a `Recipient` prints `[redacted]`.
## The match code
+444
View File
@@ -0,0 +1,444 @@
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0; teams 0.18.0; the Android grant 0.19.0)
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
records it. This page is the contract for the keys, the signature kinds and the audit log.
## Where the keys live
In the vault body, next to `identity` (FORMAT.md), as the optional member `signing`:
```json
"signing": {
"keys": [
{ "id": "domi-release", "kind": "ed25519", "role": "release", "name": "Domi release",
"secret": "<base64>", "public": "<base64>", "keyId": "<16 hex>", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca", "Fabrica"] },
{ "id": "domi-root", "kind": "root-ca", "role": "release", "name": "Domi Household Root CA",
"secret": "<base64>", "cert": "<base64 DER>", "created": 1793750000000, "pipelines": [], "repos": [] },
{ "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing",
"secret": "<base64>", "cert": "<base64 DER>", "issuer": "domi-root", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca"] },
{ "id": "domi-approve", "kind": "ed25519", "role": "release", "name": "Domi deploy approval",
"secret": "<base64>", "public": "<base64>", "keyId": "<16 hex>", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca", "Fabrica"] }
],
"audit": [
{ "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local",
"repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag",
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>",
"run": "r-42", "version": "0.1.0" }
]
}
```
Why a body member and not new item types: item types are a closed list, so an older Custos (or the web vault on an
older core) would refuse a whole vault that has an item of a new type; and an item's fields can be revealed,
copied, shared, exported to KeePass and edited, which are all paths a signing key must never take. A body member is
ignored by older readers (FORMAT.md, "Readers ignore JSON members they do not know") and is reachable only through
the functions below. As with `identity`, an older Custos drops `signing` when it saves: every Custos that saves the
vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vault up.
### Keys
| `kind` | Key | Signs | Created |
| :-- | :-- | :-- | :-- |
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | random |
| `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random |
| `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random |
| `ecdsa-p256` (core 0.18.0) | ECDSA P-256; `secret` is the 32-byte scalar; a team vault's cosign key (docs/TEAM.md) | only `cosign`, only through `team_sign` | random |
| `android` (core 0.14.0) | RSA-4096; `secret` PKCS#8 DER; `cert` a self-signed X.509 v3 certificate, valid 100 years, no EKU, under no root | only `apk` | random |
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and
(since core 0.12.0) `domi-approve` ("Domi deploy approval"), the Ed25519 key that signs deploy approvals, with the
release keys' scope. A vault whose release keys were made by an older core gets it with `signing_add_approve`
(*Create approval key*).
*Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
never trusted by Mark's PCs.
*Create Android key* (`signing_create_android`, core 0.14.0) makes one Android app signing key at a time, with the
id, name, certificate subject (`CN`, `O`, a two-letter `C`), role and scope the app gives it; an id is used once.
An Android key is a key of its own, not part of a set: it never counts as the release or test set (core 0.14.1).
The app makes `postea-android` (`CN=Postea, O=Marek Novak, C=CZ`, release, pipeline `release`, repo
`mnovak/Postea`) and its test twin `domi-test-android` (`CN=Domi Test Android, O=Domi, C=CZ`, test). An Android
key's certificate *is* the app's identity: Android accepts an update only when it is signed by the same certificate,
for the app's whole life. Its loss ends the app's updates for good, and there is no phrase to recover it from (the
vault has none), so **the vault must have two backups off the PC before the first real signature**. Its public
half is the certificate (`signing_export_cert`).
`pipelines` and `repos` list who may ask (pipeline names, repository folder names; `*` means any). A request from
a pipeline or repo not on its key's lists is refused **even when approved**. Release keys always need approval.
Test keys are approved automatically, but only for requests whose `trigger` is not `tag` (a manual run, a push).
Certificates:
- root: subject and issuer `CN=<name>, O=Domi`, `basicConstraints` CA (critical), `keyUsage` keyCertSign + cRLSign
(critical), subject key identifier;
- leaf: subject `CN=<name>, O=Domi`, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation,
`extKeyUsage` codeSigning, subject and authority key identifiers; both signed with sha256WithRSAEncryption.
The root's certificate (public part only) is exported as DER (`.cer`) to install as Trusted Root and Trusted
Publisher.
- android: subject and issuer `CN=<cn>, O=<o>, C=<c>` (encoded C, O, CN; `C` a PrintableString), validity 100 × 365
days, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation, subject and authority key
identifiers (both of its own key), no `extKeyUsage`; sha256WithRSAEncryption by its own key.
## Signature kinds
A request names a key, a kind and what to sign. Custos never receives the file.
| `kind` | The request carries | Custos returns |
| :-- | :-- | :-- |
| `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) |
| `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it |
| `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` |
| `approval` | `approval`: a deploy approval's canonical JSON (at most 8 KiB, see below), and `run` | a `.minisig` file over it |
| `apk` (core 0.14.0) | `digest`: 1 to 4 SHA-512 digests of APK Signature Scheme signed data, concatenated (64·n bytes) | the n RSA PKCS#1 v1.5 signatures (512 bytes each), concatenated in the same order |
Any request may carry a `run` (`[A-Za-z0-9._-]{1,64}`, core 0.12.0): the build's run id, so the app can show every
request of one run on one card. It is kept in the audit entry. A malformed `run` is `invalid`; `approval` text on a
request of another kind is `invalid` too.
### minisign
minisign's format (`jedisct1.github.io/minisign`), the **prehashed** variant, the one current minisign writes by
default and Tauri's updater (minisign-verify) checks:
```
untrusted comment: signature from Custos key <KEYID>
base64("ED" ‖ key_id ‖ ed25519(BLAKE2b-512(file)))
trusted comment: timestamp:<unix seconds> file:<file name> hashed
base64(ed25519(signature ‖ trusted comment text))
```
`key_id` is the key's 8 bytes as stored; `<KEYID>` is them as one little-endian u64 in upper-case hex, as minisign
prints it. The trusted comment text is what follows `trusted comment: `, without the newline. Every line ends in `\n`.
The public key file is `untrusted comment: minisign public key <KEYID>` and `base64("Ed" ‖ key_id ‖ public)`.
Tauri's updater wants the same two files one level further wrapped: its `pubkey` and each `.sig` are the base64 of
the whole minisign text. That wrapping is the build's job.
### manifest
`SHA256SUMS` in one canonical form, so the same set of files always gives the same bytes: one line per file,
`<64 lower-case hex> <name>\n` (two spaces), names without `/`, `\`, control characters or leading `-`, unique,
sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign`
(file name `SHA256SUMS`). A text in any other form is refused, not normalised.
### approval (core 0.12.0)
A deploy approval says "this run of this commit may deploy to these targets until then". Fabrica's hub checks it with
`domi-approve`'s public key before it runs a deploy step. What is signed is one line of JSON, no spaces, the keys in
exactly this order:
```
{"v":1,"run":"r-42","repo":"Arca","commit":"<40 hex>","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":1793000000}
```
| Key | |
| :-- | :-- |
| `v` | `1` |
| `run` | `[A-Za-z0-9._-]{1,64}`, equal to the request's `run` |
| `repo`, `pipeline`, `version` | 1–64 of `[A-Za-z0-9._+-]` |
| `commit` | 40 lower-case hex digits |
| `targets` | 1–16 strings of 1–80 characters (Unicode scalar values); no control characters, and none of the invisible ones that change how a line looks on the card (U+00AD, U+061C, U+180E, U+200B–U+200F, U+2028–U+202E, U+2060–U+2069, U+FEFF) |
| `expires` | Unix seconds, later than now and at most 90 000 s (25 hours) after now (checked before the card and again when signing). Before core 0.17.1 the limit was 3 600 s; a release's approval now lives a day, so its card can wait for Mark that long |
Strings use JSON's minimal escaping: a quote is written `\"`, a backslash `\\`, every other character as
itself (no `\u` escapes, no `\/`; control characters cannot occur). There is no newline at the end. Custos
parses the text, writes it again in this form and refuses anything that is not byte-identical (`invalid`): another
key order, a space, an escape, a duplicate or unknown key, a number written as `1.0`.
The signature is a prehashed minisign signature over those bytes, made exactly as for `minisign` with the file name
`approval-<run>.json`, so the trusted comment is `timestamp:<now>\tfile:approval-<run>.json\thashed`
(the `hashed` that minisign itself writes for a prehashed signature). `minisign -V -P <domi-approve public key> -m
approval.json` verifies it.
`domi-approve` signs only `approval`, and `approval` is signed only by `domi-approve`; it is a release key, so it
always asks. The scope is checked against the JSON's `repo` and `pipeline`; a request whose context names another
`repo`, `pipeline`, `commit` or `version` than its JSON is `invalid` (an empty context member is filled from the JSON
in the audit). The audit entry's `file` is `approval-<run>.json`.
### authenticode
The file is signed by Windows' own tools in three steps, so the key stays in Custos:
1. `signtool sign /dg <dir> /fd sha256 /f <leaf.cer> <file>` writes `<file>.dig` (the base64 of the 32-byte SHA-256
of the signature's authenticated attributes, no newline) and `<file>.p7u` (the unsigned PKCS#7).
2. Custos signs those 32 bytes: RSA PKCS#1 v1.5 with the SHA-256 DigestInfo. The build writes the base64 of the
384 bytes, no newline, to `<file>.dig.signed`.
3. `signtool sign /di <dir> <file>` puts the signature in; `signtool timestamp /tr <url> /td sha256 <file>` adds a
timestamp.
Checked on 2026-11-04 with signtool 10.0.26100 and a throwaway RSA-3072 key: the result verifies with
`osslsigncode verify -CAfile <root>`; `signtool verify /pa` on a machine that does not trust the root fails only
with "terminated in a root certificate which is not trusted", and a wrong signature gives "No signature found".
`signtool verify /pa` on a machine that trusts the root is the last check, done where the root is installed.
### apk (core 0.14.0)
An APK is signed by Google's apksig (`apksigner.jar` from the Android SDK build-tools) on the build's side; Custos
signs only what apksig's signer would sign. APK Signature Scheme v2 and v3 each sign one *signed data* block (the
APK's content digests, the certificate, attributes; v3 adds the SDK range), so a v2+v3 APK needs two signatures.
apksig picks `RSA_PKCS1_V1_5_WITH_SHA512` (`SHA512withRSA`) for every RSA key over 3072 bits and has no way to
choose otherwise, so the kind takes **SHA-512** digests and signs each with the SHA-512 DigestInfo:
- `digest` is 64·n bytes, n from 1 to 4: the SHA-512 of each signed data block, in the order the build wants the
signatures back. Anything else is `invalid`. The context's `file` (the APK's name) is required, as for minisign.
- The answer is the n signatures concatenated, 512 bytes each for RSA-4096. One request, one card line, one audit
entry (its `signature` is the SHA-256 of all of them), so a release run raises **one** card for its APK.
- `apk` is signed only by an `android` key, and an `android` key signs nothing else: an Authenticode key cannot sign
an APK and an Android key cannot sign an exe (`invalid`).
- `apk` is not one of the kinds the hands-off vault may sign without a card (FORMAT.md, `unattended_sign`): an
Android key cannot be revoked or replaced, so its signatures always ask.
The client (`custos-sign apk`, in the app's repository) runs apksig twice: once with a stand-in signer that records
the digests and answers with placeholder signatures (the signed data does not depend on the signatures), then, with
Custos's answer, again with a signer that hands each recorded digest its signature, and refuses any digest it did
not record. It verifies the result with apksig's verifier before it writes the APK.
### Team kinds (core 0.18.0)
`tauri-updater` (the base64 of a `minisign` file) and `cosign` (ECDSA P-256 over cosign's simple-signing payload)
exist only in team vaults and are signed only by `Vault::team_sign` (docs/TEAM.md); `signing_sign` refuses them
(`invalid`). A team audit entry carries `by`, `env`, `request` and `approvers`; its context's `repo` is the project,
`pipeline` the environment, `version` the release, `trigger` `team`. A core before 0.18.0 refuses a vault holding
any of these values (`Corrupted`); only team vaults do.
## Standing approvals (core 0.16.0)
A release key always asks. A **standing approval** is Mark's answer kept: "always allow this, for this repository".
It is a rule in `signing.standing`, made only from a request Mark is approving on a card, and a later request that
fits it is signed without a card.
```json
"standing": [
{ "id": "5b0c1e0f6a2d4c11", "repo": "mnovak/Postea", "key": "postea-android", "keyCreated": 1793750000000,
"kind": "apk", "pipeline": "release", "via": "local", "granted": 1794000000000, "lastUsed": 1794100000000, "uses": 3 },
{ "id": "9d3e…", "repo": "Aula", "key": "domi-approve", "keyCreated": 1793750000000, "kind": "approval",
"pipeline": "deploy", "via": "remote", "targets": ["deploy to nixos-vm"], "granted": 1794000000000, "uses": 0 }
]
```
**What a rule is.** Five things, all compared exactly (no `*`, no prefix): the repository and the pipeline as the
scope check reads them (an approval's own `repo` and `pipeline`), the key (its id and its `created` time, so a key
made later under the same id never inherits a rule), the kind, and `via` (the Domi pipe or the factor service's
mailbox). A rule for an `approval` also keeps the targets it was granted for. `id` is the first 16 hex characters
of the SHA-256 of `repo`, `key`, `kind`, `pipeline` and `via` joined by newlines, so one rule exists per
combination. The trigger and the step are not part of a rule; they are in every audit entry.
**A request fits a rule** (`standing_rule_for`) when all of these hold:
- `signing_check` passes: a rule never widens a key's scope, and narrowing the scope afterwards stops the rule;
- the request names a run;
- repository, pipeline, key (id and `created`), kind and `via` equal the rule's;
- for an approval, every target of the request is one of the rule's targets;
- `via` is `local`, or the kind is `approval`: a release signature asked through the mailbox never fits a rule;
- the checklist item `card-signing` (*Sign only with a card*) is not ticked.
**A rule is made** (`standing_grant`) only when the request would itself fit the rule being made, the key is a
release key (a test key needs none), and **the key has signed before** (an `approved` or `standing` audit entry):
a key's first signature is never the one that starts a rule. Granting again for an approval adds its targets to
the rule. At most 256 rules. `standing_revoke` removes one. Granting and revoking are written to the security audit
(`standing-granted`, `standing-revoked`, with the rule's fields as the detail).
**Signing with a rule** is `signing_sign(req, Approval::Standing, now)`: it checks the request, finds the rule
(refusing with `NeedsApproval` when none fits), signs, records the outcome `standing` with everything an `approved`
entry holds, and counts the use on the rule (`uses`, `lastUsed`).
Never covered by a rule, by construction: another repository, key, kind, pipeline or origin; a request out of the
key's scope; a request without a run; a key's first signature; a deploy to a target the rule was not granted for;
a release signature the server runner asks for; creating a key.
## The Android grant (core 0.19.0)
A standing approval is one repository's one key, and never a key's first signature. Mark has a dozen Domi apps, each
with its own Android key (`<app>-android`), each new: that is a card to make the key's first signature and another to
store the rule, per app. **The Android grant** is one answer for all of them: "sign my apps' release APKs, and make
each app's key when its first release asks". One grant per vault, in `signing.android`:
```json
"android": { "repos": ["mnovak/*"], "o": "Marek Novak", "c": "CZ", "granted": 1794000000000,
"lastUsed": 1794100000000, "uses": 3, "made": ["culina-android"] }
```
- `repos`: 1 to 64 patterns, each `owner/name` or `owner/*` (every repository of that owner, never another
owner's); owner and name are 1 to 64 of `A-Z a-z 0-9 . _ -`.
- `o`, `c`: the certificate subject's organisation and country for the keys it makes.
- `uses`, `lastUsed`: as on a standing approval. `made`: the ids of the keys it made, oldest first (at most 256).
**An app's key** is named by its repository: `android_key_id("mnovak/Culina")` is `culina-android` (the name in
lower case, `.` and `_` as `-`). The grant only ever deals in that key, and only when its scope is exactly that
repository and the pipeline `release`, with the role `release`: a key with a wider scope (or `*`) is never the
grant's, and a key the grant did not make but that has this shape (`postea-android`) is covered too.
**A request fits the grant** (`android_grant_fits`) when all of these hold:
- `signing_check` passes (scope as always: the grant never widens a key's scope);
- the kind is `apk` and `via` is `local`: an APK the server runner asks for never fits;
- the request names a run;
- the pipeline is `release` and the repository matches one of the patterns;
- the key is that repository's app key, as above;
- `card-signing` (*Sign only with a card*) is not ticked.
A key's first signature fits too: that is the point of the grant. `signing_sign(req, Approval::Standing, now)` signs
a request that fits a standing approval or the grant (a standing approval first), records the outcome `standing`,
and counts the use on whichever fitted.
**Making a key** (`android_grant_make_key(repo, pipeline, via, now)`): the grant covers the repository, the
pipeline is `release`, `via` is `local`, `card-signing` is not ticked, and the vault has no key under that id. It
makes the RSA-4096 key with the certificate `CN=<Name>` (the repository's name, first letter upper case), `O` and `C`
from the grant, named `<Name> Android`, scoped to exactly that repository and `release`, adds the id to `made`, and
writes `standing-granted` to the security audit (`Android grant made <id> for <repo> pipeline release`). Core 0.19.0
wrote a new action, `android-key-made`, which older cores refuse; 0.19.1 keeps to the values every core since 0.16.0
reads, because the phone app and the web vault open the same vault. It is a key like any other: not exportable,
removed only as any key is.
**Granting** (`android_grant_set(repos, o, c, now)`) stores or replaces the grant (the counts and `made` stay) and
writes `standing-granted` with `Android releases: <patterns> pipeline release, keys made on first use`. It is
refused while `card-signing` is ticked. `android_grant_revoke` removes it (`standing-revoked`). Neither asks
anyone: the app calls them only from Mark's own click.
Never covered by the grant: another kind, the server runner, a pipeline other than `release`, a repository no pattern
matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card*
is ticked.
## Domi licences (core 0.21.0)
A Domi licence is a small text file the Atrium Domi service checks before it unlocks a paid app. Its byte format,
the paste code, the revocation list and the service's own checks are Fundamentum's `docs/LICENCE.md` (licence v1);
this core is the one that **signs**, and it parses what it signs exactly as that spec's strict parser does. The code
is `crates/custos-vault/src/licence.rs`.
### The key
- One key per vault, **`domi-licence`**: Ed25519, made in the vault by Mark's click (`licence_key_create`), never
exported. Only its 32-byte public key leaves (`licence_public`); the service ships it.
- It is stored as an ordinary Ed25519 entry (release, **no scope**, no minisign key id), so every core reads the vault
as before. An empty scope is never in scope, so no older core can sign with it either.
- It signs **only** the two payload kinds below, as a plain Ed25519 signature over the exact payload bytes (no
prehash, no digest; `custos_sign::ed25519_plain`). `signing_check` refuses it for every other kind, its scope
cannot be set, no Android key can take its id, and no other key signs these payloads.
### What it signs
| Payload | Starts with | Cap (bytes) | Parser |
| :-- | :-- | :-- | :-- |
| a licence | `domi-licence-v1
` | 4004 | LICENCE.md §2.4 steps 1–4 and 7 |
| a revocation list | `domi-revocations-v1
` | 61 348 | LICENCE.md §4.1 |
The caps are the spec's file caps (4096 and 61 440) less the `sig:` line (92 bytes), so every file signed here also
passes the service's size check. A malformed payload is refused with the spec's error code (§8: `too_large`,
`crlf`, `bad_byte`, `bad_prefix`, `truncated`, `bad_line`, `unknown_field`, `duplicate_field`, `field_order`,
`missing_field`, `bad_id`, `bad_issued`, `bad_nickname`, `bad_bundle`, `bad_scope`, `bad_seats`,
`seats_with_household`, `seats_missing`, `bad_apps`, `apps_unsorted`, `apps_duplicate`, `too_many_apps`,
`bad_seq`, `revoked_unsorted`, `revoked_duplicate`) and **never reaches a card**. A payload never contains a `sig:`
line: one is an `unknown_field`.
### The licence grant
One grant per vault, in `signing.licence.grant`, given by Mark's click (`licence_grant_set`, `standing-granted`) and
removed the same way (`licence_grant_revoke`, `standing-revoked`):
```json
"licence": { "grant": { "allow": ["calenda", "fiscus", "medicus", "tabula"], "granted": 1795896907000,
"lastUsed": 1795896990000, "uses": 4 },
"log": [ { "at": 1795896990000, "by": "grant", "licence": "k3Jx0Qm1T9yZpW2bA7cD4e",
"apps": ["calenda", "tabula"] },
{ "at": 1795897000000, "by": "card", "seq": 7, "revoked": 3 } ] }
```
`licence_ask(payload, caller, now)` decides, and changes nothing:
| | Result |
| :-- | :-- |
| malformed | refused, the spec's code |
| no `domi-licence` key | refused, `no_key` |
| a caller whose Canalis app id is not `licence-issue` | refused, `not_allowed` |
| the log holds 20 000 signatures | refused, `log_full` (it never forgets what replay and rollback need) |
| a licence whose `issued` is more than 24 h from this clock, either way | refused, `clock` |
| a licence id this key signed before | refused, `replay` |
| a revocation list whose `seq` is not higher than every `seq` this key signed | refused, `rollback` |
| a revocation list | **a card, always** |
| a licence, and any of: no grant; a caller program not signed with Domi's certificate; *Sign only with a card* ticked; an app not on `allow`; 50 licences signed in the last 24 h | a card, with each reason |
| a licence and none of those | signed by the grant, no card |
`licence_sign(payload, caller, by, now)` checks again, refuses `needs_card` when `by` is `grant` and the grant does
not cover it, signs, returns the signature in base64url without padding (86 characters), logs it (when, how, the
licence id and its apps, or the list's `seq` and how many ids it revokes: never the signature, the payload or the
nickname) and counts the grant's use.
Cores before 0.21.0 ignore `signing.licence` and drop it if they save the vault: the grant is then gone, so every
licence asks again, and the key stays. Replay and rollback are then only as good as what is left; the service keeps
its own anti-rollback check (LICENCE.md §4.2), which a restored or rewritten vault cannot get past.
## The audit log
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
one entry, whatever happened:
| `outcome` | |
| :-- | :-- |
| `approved` | Mark approved; signed |
| `standing` | (core 0.16.0) a standing approval fitted; signed without asking |
| `auto` | a test key; signed without asking |
| `refused` | Mark refused |
| `expired` | nobody answered before the card's wait ran out (the app's wait: 24 hours since Custos 0.17.0, 5 minutes before), or the requester withdrew it |
| `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) |
| `invalid` | the request was malformed (wrong digest length, a manifest or approval not in canonical form, an expired approval, a kind the key cannot do) |
`signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or
`remote` (the factor service's mailbox). `run` (core 0.12.0) is the request's run, absent without one; `version`
(core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen
and travels with it.
**Compatibility (core 0.16.0).** A core before 0.16.0 ignores `standing` when it reads and drops it when it saves
(the rules are gone and every request asks again). The audit outcome `standing` and the security actions
`standing-granted` and `standing-revoked` are values it does not know: once a rule was granted, every Custos that
opens the vault must be on core 0.16.0 or later (an older one refuses it as `Corrupted`).
**Compatibility.** A key of kind `android` and an audit entry of kind `apk` (core 0.14.0) are values a core
before 0.14.0 does not know: once the vault holds an Android key, every Custos that opens it must be on core 0.14.0
or later (an older one refuses the vault as `Corrupted`; the web vault, which never reads `signing`, is unaffected).
Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind
`approval` is a value they do not know, so a core before 0.12.0 refuses a vault that holds one (`Corrupted`): once a
vault has recorded an approval request, every Custos that opens it must be on core 0.12.0 or later.
## The API (custos-vault)
```
Vault::signing_create(role, pipelines, repos, now) -> ids // release (with domi-approve) or test set
Vault::signing_add_approve(now) -> "domi-approve" // for release keys made before 0.12.0
Vault::signing_create_android(&AndroidKey, now) -> id // one Android key (core 0.14.0)
Vault::signing_keys() -> [SigningKeyView] // public parts only
Vault::signing_set_scope(id, pipelines, repos)
Vault::signing_export_cert(id) -> DER // a certificate, never a key
Vault::signing_minisign_public(id) -> minisign.pub text
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark (the clock: now_ms)
Vault::signing_check_at(&request, now) -> Ok | Refusal // the same at `now` (an approval's expiry)
Vault::signing_sign(&request, Approval::{Mark, Auto, Standing}, now) -> Signed // checks again, signs, records
Vault::signing_refuse(&request, outcome, now) // records refused / expired
Vault::signing_audit() -> [AuditEntry]
Vault::standing_can_grant(&request, now) -> Ok | why not // may the card offer "always"? (0.16.0)
Vault::standing_grant(&request, now) -> StandingRule // before signing the approved request
Vault::standing_rule_for(&request, now) -> Option<StandingRule>
Vault::standing_rules() -> [StandingRule]
Vault::standing_revoke(id, now) -> bool
android_key_id(repo) -> Option<String> (core 0.19.0)
Vault::android_grant() -> Option<AndroidGrant>
Vault::android_grant_set(repos, o, c, now) -> Result<AndroidGrant, Error>
Vault::android_grant_revoke(now) -> bool
Vault::android_grant_fits(req, now) -> bool
Vault::android_grant_make_key(repo, pipeline, via, now) -> Result<String, Error>
licence::parse_payload(bytes) -> Payload | LicenceRefusal (core 0.21.0)
Vault::licence_key_create(now) -> [u8; 32] // the public key, never the secret
Vault::licence_public() -> Option<[u8; 32]>
Vault::licence_grant() / licence_grant_set(allow, now) / licence_grant_revoke(now)
Vault::licence_ask(payload, Caller { app, domi_signed }, now) -> LicenceAsk { payload, card: [CardReason] }
Vault::licence_sign(payload, caller, LicenceBy::{Grant, Card}, now) -> base64url signature
Vault::licence_log() -> [LicenceEntry]
```
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
+310
View File
@@ -0,0 +1,310 @@
# Team vaults, policies and team signing (core 0.18.0; review fixes 0.18.1)
A **team vault** is a `.custos` file that a small team (1 to 32 people) shares: the team's release-signing keys,
its target credentials, its external-signer credentials and its approval policy. Each member opens it with the
**member key** kept in their own vault, so any member's Custos can open it and no server ever can. The pure parts
live here: the member key, the member slot, the team body, policy evaluation, the `sign.request` canonical form,
approval statements, the policy proof and the signature envelopes. Transport, prompts and storage are the app's
(Custos `docs/27_team_vault.md`).
```
member's own vault (two factors) ──► member key (X25519 + Ed25519)
│ opens its member slot
team vault ── member slots: team key sealed to each member's X25519 key
└─ body (XChaCha20-Poly1305 under the team key): roster, policy, signing keys, targets, signers, audit
```
## The member key
Every person who is in a team has one member key, made at random the first time they create or join a team, and
kept in their own vault (body member `member`, below). It never leaves that vault.
| Part | |
| :-- | :-- |
| `x25519` | 32-byte X25519 secret: the team key is sealed to its public half (custos-seal) |
| `ed25519` | 32-byte Ed25519 seed: signs the member's approvals |
| member id | the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 public ‖ x25519 public)`, 32 hex |
The **join code** a joining member's screen shows is `custos_seal::match_code(x25519 public)` (SEAL.md): the member
who approves the join compares it with the code on their own card.
In the member's own vault:
```json
"member": {
"x25519": "<64 hex>", "ed25519": "<64 hex>", "created": 1794000000000,
"teams": [ { "id": "<32 hex>", "name": "Domi", "epoch": 3, "identity": "<64 hex: the team identity's public key>" } ]
}
```
`teams` is what this member has seen: a team vault whose identity differs, or whose epoch is lower than the one
recorded, is refused (`TeamRollback`): an old copy of the file, or a fork made with an old team key, does not open
as current. An older Custos drops `member` when it saves: every Custos that saves a member's vault must be 0.18.0
or later (the member would have to be invited again).
## The team vault file
Version 2 (FACTORS.md) with one new slot kind and no factor slots:
```
kind 6, member slot (144 bytes)
16 team id
16 member id
4 epoch u32
108 sealed team key custos-seal box of the 32-byte team key, to the member's X25519 key,
context "custos team key v1:<team id hex>:<epoch>:<member id hex>"
```
- A team vault has 1 ..= 32 member slots and **only** member slots; a file that mixes member slots with factor,
pair, single or recovery slots is malformed. All member slots carry the same team id and epoch.
- The slot is authenticated by its box: the context binds team, epoch and member, so a slot moved to another
member, team or epoch does not open. The body AAD is the whole header, as for every vault.
- **Opening** (`Vault::open_team(bytes, &member_key)`): the slot with this member's id, its box opened, the body
decrypted with the team key. The body must be `"kind": "team"` with the same team id and epoch, and the member
must be on its roster; else `NotAMember` (no slot, a removed member) or `Corrupted`.
- A core before 0.18.0 skips kind 6, finds no factor slot and refuses the file: it never misreads a team vault.
### Rotation: removing a member
`team_remove_member` makes a **new random team key**, raises the epoch and writes member slots for the remaining
members only. The body (every key, credential and policy) is encrypted under the new key at the next save, so the
removed member cannot open anything written after. What they could read before stays read: Custos never hands out
a signing key, but the target and signer credentials they could reveal should be rotated at their source (the
app's card says which).
The **team identity** (an Ed25519 key in the body) does not rotate: it is what Fabrica and every target pin, and a
removed member never held it outside Custos. Rotating it is a new team.
## The team body
```json
{ "format": 2, "kind": "team", "items": [],
"team": {
"id": "<32 hex>", "name": "Domi", "created": 1794000000000, "epoch": 1,
"identity": { "secret": "<64 hex>", "public": "<64 hex>" },
"members": [ { "id": "<32 hex>", "name": "Mark", "handles": ["mnovak"], "ed25519": "<64 hex>",
"x25519": "<64 hex>", "added": 1794000000000, "by": "<member id or empty for the founder>",
"code": "684361" } ],
"removed": [ { "id": "<32 hex>", "name": "Old", "at": 1794100000000, "by": "<member id>", "epoch": 2 } ],
"policy": { "text": "<canonical policy JSON>", "sig": "<base64: the identity's signature>" },
"targets": [ { "id": "<16 hex>", "kind": "ssh-key", "name": "web-1", "project": "mnovak/Arca", "env": "production",
"host": "web-1.example", "user": "deploy", "secret": "<the credential>", "created": 1794000000000,
"by": "<member id>" } ],
"signers": [ { "id": "<16 hex>", "name": "Cloud signing", "adapter": "command", "endpoint": "…",
"account": "…", "secret": "<the credential>", "certificate": "<base64 DER or empty>",
"created": 1794000000000, "by": "<member id>" } ],
"seen": [ { "request": "<64 hex>", "at": 1794000000 } ],
"audit": [ { "at": 1794000000000, "action": "member-added", "by": "<member id>", "detail": "Petra" } ] },
"signing": { "keys": [ … ], "audit": [ … ] } }
```
- `handles`: the names Fabrica knows the member by (git host user names), 0 ..= 8 of `[A-Za-z0-9._-]{1,64}`. The
policy's author rule matches a request's `author` against them (ASCII case-insensitive) and against the member id.
- `targets` and `signers` are **not items**: an item can be revealed, copied, shared and exported, and these are
reached only through `team_target_*` and `team_signer_*`. `secret` is never in a view, a `Debug` or an error.
- `seen`: every request a member of this vault signed or refused as replayed, kept 48 hours (longer than any
request lives, 25 hours). A request whose hash is in it is refused (`Replayed`).
- `audit` (team actions; signatures are in `signing.audit`): `team-created`, `member-added`, `member-removed`,
`policy-set`, `target-added`, `target-removed`, `target-released`, `signer-added`, `signer-removed`,
`keys-created`. `detail` names, never holds a value. Append-only, newest 5 000.
- `signing` is the store of SIGNING.md, with the team's keys (below) and its audit; a team audit entry carries
`by` (the signing member's id), `env`, `release`, `request` (the request hash) and `approvers`.
### Team keys
`team_create_keys` makes the team's set, once:
| id | kind | role | Signs |
| :-- | :-- | :-- | :-- |
| `team-release` | `ed25519` | release | `minisign`, `tauri-updater` when the policy asks for 1+ approvals |
| `team-preview` | `ed25519` | test | the same, when the environment's policy asks for **0** approvals |
| `team-cosign` | `ecdsa-p256` (new kind) | release | `cosign` when the policy asks for 1+ approvals |
| `team-cosign-preview` | `ecdsa-p256` | test | `cosign` at 0 approvals |
An Android key (`android`, SIGNING.md) is made per app with `team_create_android`; at 0 approvals an `apk` request
needs a test Android key, else it is `NoKey`. Authenticode is never signed with a key in the vault: a request goes
to an external signer (`signers`) after the policy is met.
**Why 0 approvals uses a different key.** A preview signature is made without anyone looking. It must not be
mistakable for a release: it is made by a test-role key that production targets do not trust, exactly as today's
test keys (SIGNING.md). A signature by `team-release` always means the policy's people approved it.
## Policy
One rule per environment, signed by the team identity:
```
{"v":1,"team":"<32 hex>","rev":2,"envs":[{"env":"preview","approvals":0,"others":false,"approvers":[]},{"env":"staging","approvals":1,"others":false,"approvers":[]},{"env":"production","approvals":1,"others":true,"approvers":[]}]}
```
| Key | |
| :-- | :-- |
| `rev` | starts at 1, +1 on every change |
| `envs` | 1 ..= 8 rules, `env` unique, `[a-z][a-z0-9-]{0,31}`, sorted as written by `Policy::canonical` (the order given) |
| `approvals` | 0 ..= 10: how many members must approve |
| `others` | the approvers must not include the release's author, **when the team has 2 or more members** |
| `approvers` | member ids allowed to approve; empty = every member |
Canonical form as for deploy approvals (SIGNING.md): this key order, no spaces, minimal escaping, no newline;
anything else is refused, not normalised. Signature: Ed25519 by the team identity over
`"custos team policy v1\0" ‖ text`.
**Defaults** (`Policy::default_for(team)`): preview 0, staging 1, production 1 with `others`. A team of one approves
its own production releases (the `others` rule needs two members); when a second member joins, it applies.
### Evaluation
`evaluate(policy, roster, env, author, approvers) -> Verdict`, pure:
1. No rule for `env`: `UnknownEnv`.
2. `approvals == 0`: `Allowed { key_role: Test }`.
3. Eligible = roster members in `approvers` (or all); minus the author when `others` and the roster has ≥ 2 members.
The author is the member whose id equals `author` or whose handles contain it. Under `others` with 2+ members,
an author no member is (or an empty one) is `Unsatisfiable` (core 0.18.1): the rule cannot exclude someone it
cannot recognise, so it refuses instead of letting anyone approve.
4. Counted = distinct eligible members among `approvers` given. Members not on the roster, ineligible members and
duplicates are not counted (and listed in `ignored`).
5. Counted ≥ `approvals`: `Allowed { key_role: Release }`. Eligible < `approvals`: `Unsatisfiable` (no set of
approvals can ever meet it: say so instead of waiting a day). Else `Need { more }`.
## The signing request (`sign.request`, v1)
Fabrica asks for a signature with one line of canonical JSON (the app relays it; the core checks it):
```
{"v":1,"op":"sign.request","team":"<32 hex>","id":"<32 hex>","project":"mnovak/Arca","release":"0.7.0","env":"production","author":"mnovak","format":"minisign","artifact":{"name":"Arca_0.7.0_x64-setup.exe","size":25145977,"sha256":"<64 hex>"},"artifact_digest":"<base64>","image":"","pub":"<base64, 32 bytes>","expires":1794003600}
```
| Key | |
| :-- | :-- |
| `team` | the team id |
| `id` | 16 random bytes, hex: the request's own nonce |
| `project` | 1–128 of `[A-Za-z0-9._/-]` |
| `release` | 1–64 of `[A-Za-z0-9._+-]` (the version) |
| `env` | as in the policy |
| `author` | the release's author as Fabrica knows them, 0–64 of `[A-Za-z0-9._@-]` (empty: unknown) |
| `format` | `minisign`, `tauri-updater`, `apk`, `cosign`, `authenticode` |
| `artifact` | `name` (1–200 characters, no `/`, `\` or control characters), `size`, `sha256` (64 lower-case hex) |
| `artifact_digest` | base64; minisign and tauri-updater: BLAKE2b-512 of the file (64 bytes); apk: 1–4 SHA-512 digests of APK Signature Scheme signed data (64·n); cosign: the image manifest's SHA-256 (32); authenticode: signtool's 32-byte `.dig` |
| `image` | cosign only, else empty: the image reference without tag or digest, 1–255 of `[a-z0-9._/:-]` |
| `pub` | Fabrica's one-time X25519 key: the reply is sealed to it, and its match code is the request's code |
| `expires` | Unix seconds, later than now, at most 25 hours ahead |
The **request hash** is `SHA-256(text)`, hex. The **match code** is `match_code(pub)`: Fabrica shows it beside the
release, every member's card shows it.
### Approval statements
A member who approves signs, with their member key:
```
Ed25519( "custos team approval v1\0" ‖ request hash (32) ‖ match code (6 ASCII digits) ‖ member id (16) ‖ at (u64 BE, Unix seconds) )
```
`approve(request, shown_code, member_key, now)` refuses (`WrongMatch`) when the code the card showed is not the
request's match code: a request whose `pub` was swapped after the card was drawn is not approved. A statement whose
code is not the request's never counts.
### Signing
`Vault::team_sign(request_text, statements, signer, shown_code, now)` in the vault of the member whose Custos signs:
1. parses the request (canonical, fields as above, `team` = this team, not expired), refuses a hash in `seen`
(`Replayed`);
2. checks every statement's signature against the roster, and that its code is the request's;
3. evaluates the policy with the signer's own approval added (a signer approves by signing, and their shown code
must match: `WrongMatch` otherwise);
4. picks the key: by format and the verdict's role (`team-release` / `team-preview`, `team-cosign` /
`team-cosign-preview`, the Android key of that role whose `repos` holds the request's `project`, or for
authenticode the team's first external signer, never at 0 approvals);
5. signs, records the request in `seen` and an audit entry with `by`, `env`, `release`, `request`, `approvers`;
6. returns the reply.
A refusal by the policy, the code or the clock changes nothing. A member who refuses on the card records an audit
entry `refused` and the request's hash in `seen` (`team_refuse`).
### The reply (`sign.reply`, v1)
Sealed to the request's `pub` with the context `team-sign:<request id>`:
```json
{ "v": 1, "op": "sign.reply", "request": "<request hash>", "format": "minisign",
"signature": "<the envelope, below>", "payload": "<cosign: the signed payload, else absent>",
"key": { "id": "team-release", "public": "<minisign.pub text | cosign.pub PEM | certificate PEM>" },
"signer": { "member": "<member id>", "name": "Petra" },
"proof": { … } }
```
### The policy proof
What makes a signature checkable as *approved by the team's rules*, by anyone who pinned the team identity:
```
{"v":1,"team":"<id>","request":"<request hash>","env":"production","author":"mnovak","policy":"<policy text>","policy_sig":"<b64>","roster":[{"id":"<id>","name":"Mark","handles":["mnovak"],"ed25519":"<hex>"}],"approvals":[{"member":"<id>","code":"684361","at":1794000000,"sig":"<b64>"}],"signer":"<id>","role":"release","signature":"<sha256 hex of the envelope>","at":1794000100}
```
plus `"sig"`: Ed25519 by the team identity over `"custos team proof v1\0" ‖ that text`, carried next to it as
`{"text": …, "sig": …}`. `role` is `release` or `test` (0 approvals: no approvals listed). For `release`, the
signer's own approval is one of those that count: the signature is made in an approving member's Custos. `verify_proof(proof, team_identity_public, request_text, envelope, now)` checks both
signatures, every approval against the roster and the request's code, the request hash and the envelope hash, and
evaluates the policy again: it accepts only what `team_sign` itself would have signed.
## Signature envelopes
| `format` | `signature` in the reply | Check it with |
| :-- | :-- | :-- |
| `minisign` | the `.minisig` text (prehashed, SIGNING.md) | `minisign -V -P <pub> -m <file>`, minisign-verify |
| `tauri-updater` | base64 of that `.minisig` text: the content of Tauri's `<file>.sig` | Tauri's updater (minisign-verify) with `pubkey` = base64 of `minisign.pub` |
| `apk` | base64 of the n RSA PKCS#1 v1.5 SHA-512 signatures (512 bytes each) | apksig pass 2 then `apksigner verify` (the app's `custos-sign apk`) |
| `cosign` | base64 of the ECDSA P-256 SHA-256 signature (ASN.1 DER) over `payload` | `cosign verify --key cosign.pub --insecure-ignore-tlog=true <image>@<digest>` once attached; `openssl dgst -sha256 -verify cosign.pub -signature sig.der payload.json` |
| `authenticode` | base64 of what the external signer returned for the `.dig` (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo) | `signtool sign /di`, then `signtool verify /pa`, `osslsigncode verify` |
**cosign.** The payload is cosign's *simple signing* JSON, written by Custos (never taken from the request), with the
keys in this order and no spaces:
```
{"critical":{"identity":{"docker-reference":"<image>"},"image":{"docker-manifest-digest":"sha256:<64 hex>"},"type":"cosign container image signature"},"optional":null}
```
No transparency log is involved: Fabrica attaches it with
`cosign attach signature --payload payload.json --signature <base64> <image>@sha256:<digest>`, and a target checks it
with the team's `cosign.pub` (PEM, SubjectPublicKeyInfo) and `--insecure-ignore-tlog=true`, or by fetching the
`sha256-<digest>.sig` manifest and checking the layer's `dev.cosignproject.cosign/signature` annotation over the
layer's bytes, which are this payload.
## Target credentials
A target credential is handed to the Fabrica server for one deployment: `team_target_release(target id, request,
deployment, now)` returns the plaintext to seal, only when the target's `project` and `env` equal the deployment's,
**and the request's `mac` was made with that deployment's ticket** (core 0.18.1), and records `target-released`
with the deployment's request hash.
**The ticket.** `team_sign` makes 32 random bytes per signed request, keeps them in the team body (`tickets`, 25
hours) and puts them in the reply (`"ticket"`, base64), which only the requester can open. A `target.request` ends
with `"mac":"<base64>"`: HMAC-SHA256(ticket, `"custos team target v1\0"` ‖ the canonical request up to and including
`"expires":N`, without the closing brace). Knowing a deployment's hash (the service stores every request text; a
proof names it) is not enough: without the ticket nobody else, not the service and not another connection, can ask
for its credentials or use up its one release. One release per (target, deployment): a second
call is `Replayed`. The app seals it to the server's one-time key (`team-target:<id>`); the service hands the box
out once, to the caller that asked (Custos `docs/27_team_vault.md`).
`kind`: `ssh-key` (an OpenSSH private key), `winrm` (user and password), `openssh` (user and password),
`registry` (a Docker registry token), `kubeconfig` (the kubeconfig text). `secret` ≤ 64 KiB.
## Limits (known, not fixed in 0.18.x)
- **Every member holds the team's secrets in their Custos**: the team identity, the release keys and the credentials
are in the body every member decrypts. Custos never hands them out, but a member running a modified build of the
public core can copy them before they are removed, and then sign directly, write proofs, or build a fork at a higher
epoch for the remaining members, which `member_note_team` would accept as current. Removing a member you no longer
trust means a new team (new identity, new keys), not only a new epoch.
- **Any member can change the policy.** `team_set_rule` is one member's action (audited as `policy-set`, signed by the
identity). A member who loosens production and then signs their own release passes `verify_proof`. Policy changes
that need the current policy's approvals are future work; until then, review the team audit.
## Crates
`custos-team` (pure): member keys, wrapping, policy, request, statements, proof, envelopes, on `ed25519-dalek`,
`x25519-dalek` through `custos-seal`, `sha2`, `p256` (cosign verification only). `custos-sign` gains `cosign`
(ECDSA P-256 with `p256`, RFC 6979 deterministic nonces) and `tauri_updater`. `custos-vault` holds the file format,
the body and `team_sign`.
+6
View File
@@ -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
@@ -67,6 +69,10 @@ just as plainly, what it does not.
password, the TOTP code or a PC.
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
screens; a request you did not start is someone else's.
- **Losing the vault loses its signing keys.** They never leave it, so no backup holds them but a backup of the
vault itself, and there is no phrase to rebuild them from. Most can be replaced with new keys; an Android app's
key (docs/SIGNING.md, `android`) cannot: Android accepts updates only from the same certificate, so its loss ends
that app's updates for good. Keep two copies of the vault off the PC before the first real signature.
## Design rules that follow from this
+91
View File
@@ -0,0 +1,91 @@
// Custos's service worker (docs/BROWSER.md). It owns the connection to the native host and answers the
// content scripts and the popup. The page origin it sends to Custos is always the browser's (`sender.url`,
// the tab's URL), never what a page says about itself; Custos decides which logins belong to it.
const HOST = 'cz.marek_novak.custos';
/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */
let port = null;
let seq = 0;
const waiting = new Map();
function connect() {
if (port) return port;
port = chrome.runtime.connectNative(HOST);
port.onMessage.addListener((msg) => {
const w = waiting.get(msg.seq);
if (!w) return;
waiting.delete(msg.seq);
w(msg);
});
port.onDisconnect.addListener(() => {
// Not registered, or the host exited: every open request fails the same way.
const why = chrome.runtime.lastError?.message ?? '';
const error = /not found|forbidden/i.test(why) ? 'not_connected' : 'not_running';
for (const w of waiting.values()) w({ ok: false, error });
waiting.clear();
port = null;
});
return port;
}
function ask(request) {
return new Promise((resolve) => {
const n = ++seq;
waiting.set(n, resolve);
try {
connect().postMessage({ ...request, seq: n });
} catch {
waiting.delete(n);
resolve({ ok: false, error: 'not_connected' });
}
// Custos may wait up to a minute for an unlock or an approval.
setTimeout(() => {
if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' });
}, 75_000);
});
}
/** `https://host[:port]` of a page or frame URL; null for anything Custos never fills. */
function originOf(url) {
try {
const u = new URL(url);
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
return u.origin;
} catch {
return null;
}
}
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
// Only this extension's own pages and content scripts reach here; pages cannot send to it.
if (sender.id !== chrome.runtime.id) return false;
(async () => {
switch (msg?.kind) {
case 'status':
return reply(await ask({ op: 'browser_status' }));
case 'match': {
// From a content script: the logins for the frame it runs in.
const origin = originOf(sender.url);
if (!origin) return reply({ ok: false, error: 'no_match' });
return reply({ ...(await ask({ op: 'browser_match', origin })), origin });
}
case 'fill': {
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
const origin = originOf(sender.url);
if (!origin || typeof msg.id !== 'string') return reply({ ok: false, error: 'no_match' });
return reply(await ask({ op: 'browser_fill', id: msg.id, origin }));
}
case 'match-tab': {
// From the popup: the logins for the active tab's page.
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const origin = tab && originOf(tab.url);
if (!origin) return reply({ ok: false, error: 'no_match', tab: tab?.id ?? null });
return reply({ ...(await ask({ op: 'browser_match', origin })), origin, tab: tab.id });
}
default:
return reply({ ok: false, error: 'bad_request' });
}
})();
return true;
});
+173
View File
@@ -0,0 +1,173 @@
// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this
// frame's site, and fills the one the person picks. Nothing is filled without a click. The button and the
// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens.
(() => {
const SENTENCES = {
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
not_running: 'Custos is not running. Start it, then try again.',
not_custos: 'Something other than Custos answered. Nothing was sent.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
not_found: 'That login is no longer in Custos.',
no_match: 'That login does not belong to this site.',
no_answer: 'Custos did not answer.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const visible = (el) => {
const r = el.getBoundingClientRect();
const s = getComputedStyle(el);
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && !el.disabled && !el.readOnly;
};
const isText = (el) => el instanceof HTMLInputElement && ['text', 'email', 'tel'].includes(el.type);
const isOtp = (el) =>
el instanceof HTMLInputElement &&
(el.autocomplete === 'one-time-code' || /(^|[^a-z])(otp|totp|2fa|mfa|one.?time|verification.?code)/i.test(`${el.name} ${el.id}`));
const isUserName = (el) => isText(el) && /username|email/i.test(`${el.autocomplete} ${el.name} ${el.id} ${el.type}`);
/** The username field of a password field: the one the page marks, else the last text field before it. */
function usernameFor(pw) {
const inputs = [...(pw.form ?? document).querySelectorAll('input')].filter(visible);
const marked = inputs.find((el) => isText(el) && /username|email/i.test(el.autocomplete));
if (marked) return marked;
for (let i = inputs.indexOf(pw) - 1; i >= 0; i--) if (isText(inputs[i]) && !isOtp(inputs[i])) return inputs[i];
return null;
}
/** The fields a login fills, around `near` (the focused field) or on the whole page. */
function fieldsAround(near) {
const all = [...document.querySelectorAll('input')].filter(visible);
const otp = (near && isOtp(near) ? near : null) ?? all.find(isOtp) ?? null;
const scope = near?.form ? [...near.form.querySelectorAll('input')].filter(visible) : all;
const pass = (near?.type === 'password' ? near : null) ?? scope.find((el) => el.type === 'password') ?? null;
const user = pass ? usernameFor(pass) : ((near && isUserName(near) ? near : null) ?? scope.find(isUserName) ?? null);
return { user, pass, otp };
}
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
function put(el, value) {
if (!el || typeof value !== 'string' || !value) return;
el.focus();
setValue.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
}
async function fill(id, near) {
const r = await chrome.runtime.sendMessage({ kind: 'fill', id });
if (!r?.ok) return say(r?.error);
const f = fieldsAround(near);
put(f.user, r.username);
put(f.pass, r.password);
if (f.otp) put(f.otp, r.totp);
return null;
}
// ---- the button and the list ----
const host = document.createElement('custos-fill');
const root = host.attachShadow({ mode: 'closed' });
root.innerHTML = `
<style>
:host { all: initial; }
.chip, .menu { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
.chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d;
cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
.chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; }
.menu { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px;
background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); }
.head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none;
color: inherit; text-align: left; cursor: pointer; font: inherit; }
button.login:hover, button.login:focus-visible { background: #262b33; outline: none; }
.title { font-weight: 600; }
.user { color: #9aa3b1; font-size: 12px; }
.note { padding: 6px 8px; color: #c9d1dc; }
[hidden] { display: none !important; }
</style>
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5l5 2v4c0 3.2-2.1 5.8-5 7-2.9-1.2-5-3.8-5-7v-4z"
fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none"
stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>`;
const chip = root.querySelector('.chip');
const menu = root.querySelector('.menu');
let field = null;
function place() {
if (!field || !field.isConnected) return hide();
const r = field.getBoundingClientRect();
chip.style.left = `${Math.max(0, r.right - 28)}px`;
chip.style.top = `${r.top + Math.max(0, (r.height - 24) / 2)}px`;
menu.style.left = `${Math.max(4, r.left)}px`;
menu.style.top = `${r.bottom + 4}px`;
}
function hide() {
chip.hidden = true;
menu.hidden = true;
field = null;
}
function note(text) {
menu.replaceChildren(Object.assign(document.createElement('div'), { className: 'note', textContent: text }));
menu.hidden = false;
}
async function open() {
const target = field;
note('Asking Custos…');
const r = await chrome.runtime.sendMessage({ kind: 'match' });
if (field !== target) return;
if (!r?.ok) return note(say(r?.error));
if (!r.logins.length) return note('Custos has no login for this site.');
const head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' });
const items = r.logins.map((l) => {
const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' });
b.setAttribute('role', 'menuitem');
b.append(
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
);
b.addEventListener('click', async () => {
const why = await fill(l.id, target);
if (why) note(why);
else hide();
});
return b;
});
menu.replaceChildren(head, ...items);
items[0]?.focus();
}
chip.addEventListener('click', () => (menu.hidden ? void open() : (menu.hidden = true)));
// A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it.
host.addEventListener('mousedown', (e) => e.preventDefault());
document.addEventListener(
'focusin',
(e) => {
const el = e.target;
if (!(el instanceof HTMLInputElement) || !visible(el)) return;
if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return;
if (!host.isConnected) document.documentElement.append(host);
field = el;
menu.hidden = true;
chip.hidden = false;
place();
},
true,
);
document.addEventListener('keydown', (e) => e.key === 'Escape' && !menu.hidden && hide(), true);
document.addEventListener('pointerdown', (e) => e.target !== host && e.target !== field && hide(), true);
window.addEventListener('scroll', place, true);
window.addEventListener('resize', place);
// The popup's choice, in the top frame: fill the page's login form.
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
if (sender.id !== chrome.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false;
fill(msg.id, null).then((why) => reply({ ok: !why, error: why }));
return true;
});
})();
+38
View File
@@ -0,0 +1,38 @@
{
"manifest_version": 3,
"name": "Custos",
"short_name": "Custos",
"description": "Fills your logins from the Custos on this computer, only into the site they belong to.",
"version": "0.15.0",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
"minimum_chrome_version": "116",
"permissions": [
"nativeMessaging",
"activeTab"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "Custos",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"js": [
"content.js"
],
"all_frames": true,
"run_at": "document_idle"
}
],
"content_security_policy": {
"extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'"
}
}
+77
View File
@@ -0,0 +1,77 @@
:root {
color-scheme: dark;
--bg: #101216;
--panel: #15181d;
--hover: #262b33;
--line: #2b3038;
--fg: #e8ebf0;
--muted: #9aa3b1;
--accent: #c9d1dc;
}
body {
width: 320px;
margin: 0;
background: var(--bg);
color: var(--fg);
font: 13px/1.45 "Segoe UI", system-ui, sans-serif;
}
header {
display: flex;
align-items: baseline;
gap: 10px;
padding: 12px 14px 10px;
border-bottom: 1px solid var(--line);
background: var(--panel);
}
.wordmark {
color: var(--accent);
font-size: 12px;
letter-spacing: 0.3em;
}
.site {
overflow: hidden;
color: var(--muted);
white-space: nowrap;
text-overflow: ellipsis;
}
main {
padding: 8px;
}
.note {
margin: 6px 6px 10px;
}
.logins {
margin: 0;
padding: 0;
list-style: none;
}
.logins button {
display: grid;
width: 100%;
padding: 8px 10px;
border: 0;
border-radius: 8px;
background: none;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.logins button:hover,
.logins button:focus-visible {
background: var(--hover);
outline: none;
}
.title {
font-weight: 600;
}
.user {
color: var(--muted);
font-size: 12px;
}
footer {
padding: 8px 14px 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 12px;
}
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custos</title>
<link rel="stylesheet" href="popup.css">
<script src="popup.js" defer></script>
</head>
<body>
<header>
<span class="wordmark">CUSTOS</span>
<span id="site" class="site"></span>
</header>
<main>
<p id="note" class="note">Asking Custos…</p>
<ul id="logins" class="logins" aria-label="Logins for this site"></ul>
</main>
<footer>Only logins saved for this site are offered here.</footer>
</body>
</html>
+50
View File
@@ -0,0 +1,50 @@
// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form
// (the top frame's content script asks for the secrets itself, so they go only where they belong).
const SENTENCES = {
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
not_running: 'Custos is not running. Start it, then try again.',
not_custos: 'Something other than Custos answered. Nothing was sent.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
not_found: 'That login is no longer in Custos.',
no_match: 'Custos fills only web pages (https, or this computer).',
no_answer: 'Custos did not answer.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const note = document.getElementById('note');
const list = document.getElementById('logins');
async function show() {
const r = await chrome.runtime.sendMessage({ kind: 'match-tab' });
if (r?.origin) document.getElementById('site').textContent = new URL(r.origin).host;
if (!r?.ok) {
note.textContent = say(r?.error);
return;
}
if (!r.logins.length) {
note.textContent = 'Custos has no login for this site.';
return;
}
note.hidden = true;
for (const l of r.logins) {
const li = document.createElement('li');
const b = Object.assign(document.createElement('button'), { type: 'button' });
b.append(
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
);
b.addEventListener('click', async () => {
const done = await chrome.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 }).catch(() => null);
if (done?.ok) window.close();
else {
note.hidden = false;
note.textContent = done?.error ?? 'This page has no login form Custos can fill.';
}
});
li.append(b);
list.append(li);
}
list.querySelector('button')?.focus();
}
void show();
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]))

Some files were not shown because too many files have changed in this diff Show More