Compare commits

..

14 Commits

Author SHA1 Message Date
mnovak e3128b35aa [repo] Merge: feature/share-wasm (share links, browser build, PR #5) 2026-10-31 18:31:49 +01:00
mnovak 5ee1c0da6b [share] Share links and the browser build: custos-share (blob v1, key in the fragment, optional password), custos-wasm (JSON ABI, no wasm-bindgen), docs/SHARE.md, threat model (v0.3.0) 2026-10-31 18:20:51 +01:00
mnovak 4aac99fb47 [repo] Merge: feature/real-words (real English words only, ASCII-only symbols, PR #4) 2026-10-31 13:55:00 +01:00
mnovak faa5d8dfc9 [gen] Real words: memorable passwords from EFF words a US English dictionary knows; strict-site symbols ASCII only (v0.2.1) 2026-10-31 13:54:44 +01:00
mnovak a68b3b46bf [repo] Merge: feature/totp-qr (TOTP, QR payloads, device key wrap, PR #3) 2026-10-31 10:44:58 +01:00
mnovak 0b9cce40e2 [core] TOTP, QR payloads, device key wrap: custos-totp, custos-qr, Vault::wrap_for_device (v0.2.0) 2026-10-31 10:44:24 +01:00
mnovak fe90e7691b [core] Tests: RFC 6238/4226 vectors, otpauth parsing, Wi-Fi escaping, device key wrap 2026-10-31 10:44:24 +01:00
mnovak 686c662835 [repo] Merge: feature/nickname-parts (nickname follows the title, PR #2) 2026-10-31 10:24:00 +01:00
mnovak fba6e5492a [gen] Nickname: draw word and number once, render them for any title (NicknameParts) 2026-10-31 10:23:53 +01:00
mnovak fac0184e46 [repo] Merge: feature/core (vault file v1, generators, PR #1) 2026-10-31 10:13:46 +01:00
mnovak 1ac6c0e01e [gen] Wordlists: keep the EFF list byte-exact in checkouts 2026-10-31 10:13:06 +01:00
mnovak eb710c3135 [core] Vault and generators: Argon2id key slot + XChaCha20-Poly1305 file, atomic save, item templates, memorable/nickname/random/PIN/strict generators 2026-10-31 10:12:57 +01:00
mnovak 42ddcf0287 [core] Tests: the mandatory vault and generator tests, written before the code 2026-10-31 10:12:56 +01:00
mnovak 33831648cb [docs] Format and threat model: vault file v1, KDBX mapping, what is not protected 2026-10-31 09:56:51 +01:00
44 changed files with 19643 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
# The browser build takes its randomness from crypto.getRandomValues through getrandom's custom
# backend (crates/custos-wasm/src/lib.rs, `random_fill`): no wasm-bindgen.
[target.wasm32-unknown-unknown]
rustflags = ['--cfg', 'getrandom_backend="custom"']
+2
View File
@@ -0,0 +1,2 @@
# Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md).
crates/custos-gen/wordlists/eff_large_wordlist.txt -text
+10
View File
@@ -8,7 +8,12 @@ The Windows app lives in the private `Custos` repo and depends on this one by gi
```
crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, item model, SecretString
crates/custos-gen memorable password, nickname, random, PIN, strict-site generators + wordlists
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-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
docs/FORMAT.md the vault file format (versioned; change it before the code)
docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
docs/THREAT_MODEL.md what is and is not protected
```
@@ -16,7 +21,12 @@ docs/THREAT_MODEL.md what is and is not protected
```
cargo test --workspace # all mandatory tests
cargo test --workspace --release # same, faster Argon2
# the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake):
nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm
node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it
```
- `.cargo/config.toml` selects getrandom's custom backend for wasm32: `random_fill` → `crypto.getRandomValues`.
- WSL: run commands with `wsl -d Debian --exec bash -lc '…'`; plain `wsl -- …` expands `$VARS` too early.
On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: is off limits).
## Rules
Generated
+658
View File
@@ -0,0 +1,658 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "argon2"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"password-hash",
"zeroize",
]
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "blake2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"
dependencies = [
"digest",
]
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"rand_core",
]
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer",
"crypto-common",
"inout",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"getrandom",
"hybrid-array",
"rand_core",
]
[[package]]
name = "ctutils"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a"
dependencies = [
"cmov",
]
[[package]]
name = "custos-gen"
version = "0.3.0"
dependencies = [
"custos-vault",
"rand",
"regex",
"unicode-normalization",
"zeroize",
]
[[package]]
name = "custos-qr"
version = "0.3.0"
[[package]]
name = "custos-share"
version = "0.3.0"
dependencies = [
"argon2",
"chacha20poly1305",
"custos-vault",
"data-encoding",
"hkdf",
"rand",
"serde",
"serde_json",
"sha2",
"thiserror",
"zeroize",
]
[[package]]
name = "custos-totp"
version = "0.3.0"
dependencies = [
"custos-vault",
"data-encoding",
"hmac",
"percent-encoding",
"sha1",
"sha2",
"zeroize",
]
[[package]]
name = "custos-vault"
version = "0.3.0"
dependencies = [
"argon2",
"chacha20poly1305",
"hkdf",
"rand",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror",
"zeroize",
]
[[package]]
name = "custos-wasm"
version = "0.3.0"
dependencies = [
"custos-qr",
"custos-share",
"custos-totp",
"custos-vault",
"data-encoding",
"getrandom",
"qrcode",
"serde",
"serde_json",
"zeroize",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"rand_core",
]
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "inout"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
dependencies = [
"hybrid-array",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "password-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"
dependencies = [
"phc",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "phc"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"
dependencies = [
"base64ct",
"ctutils",
]
[[package]]
name = "poly1305"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures",
"universal-hash",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "qrcode"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20",
"getrandom",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common",
"ctutils",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+25
View File
@@ -0,0 +1,25 @@
[workspace]
resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.3.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
[workspace.dependencies]
argon2 = { version = "0.6", default-features = false, features = ["alloc", "zeroize"] }
chacha20poly1305 = "0.11"
zeroize = { version = "1.9", features = ["derive"] }
rand = "0.10"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
unicode-normalization = "0.1"
hmac = "0.13"
sha1 = "0.11"
sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
+22
View File
@@ -0,0 +1,22 @@
# Custos Domi — core
The public, auditable core of [Custos Domi](https://gitea.marek-novak.cz/mnovak), a small local-first
password and secret manager: everything that touches plaintext or keys.
| Crate | What |
|:--|:--|
| `custos-vault` | The `.custos` file: Argon2id → key slot → XChaCha20-Poly1305, atomic save, typed items |
| `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site |
| `custos-totp` | TOTP (RFC 6238) and HOTP (RFC 4226), `otpauth://` URIs |
| `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) |
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).
```
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`).
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-gen"
description = "Custos password, passphrase, nickname and PIN generators"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
rand.workspace = true
zeroize.workspace = true
unicode-normalization.workspace = true
[dev-dependencies]
regex = "1"
+516
View File
@@ -0,0 +1,516 @@
//! Password, passphrase, nickname and PIN generators. Randomness comes only from the OS CSPRNG
//! (`rand`'s `SysRng`), and every result reports its entropy computed from the template, counting only
//! the random choices.
use custos_vault::SecretString;
use rand::RngExt;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use std::sync::LazyLock;
use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::is_combining_mark;
/// A generated value and how many bits of randomness went into it.
#[derive(Clone, Debug)]
pub struct Generated {
pub value: SecretString,
pub entropy_bits: f64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GenError(pub String);
impl std::fmt::Display for GenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for GenError {}
fn fail<T>(msg: &str) -> Result<T, GenError> {
Err(GenError(msg.into()))
}
fn rng() -> UnwrapErr<SysRng> {
UnwrapErr(SysRng)
}
fn pick<T: Copy>(items: &[T]) -> T {
items[rng().random_range(0..items.len())]
}
fn digit() -> char {
pick(&DIGITS)
}
const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// ---------- word lists ----------
fn plain_list(text: &'static str) -> Vec<&'static str> {
text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect()
}
/// The words of memorable passwords (7,322): the EFF large wordlist without the words a standard US
/// English spellchecker dictionary does not know (brand names, names, coinages, hyphenated words).
/// See `wordlists/SOURCES.md`.
pub static MEMORABLE_WORDS: LazyLock<Vec<&str>> =
LazyLock::new(|| plain_list(include_str!("../wordlists/memorable.txt")));
static NOUNS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/nouns.txt")));
static ADJECTIVES: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/adjectives.txt")));
static VERBS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/verbs.txt")));
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WordKind {
Adjective,
Noun,
Verb,
}
/// The nickname word list for one part of speech.
pub fn words(kind: WordKind) -> &'static [&'static str] {
match kind {
WordKind::Adjective => &ADJECTIVES,
WordKind::Noun => &NOUNS,
WordKind::Verb => &VERBS,
}
}
fn capitalize(w: &str) -> String {
let mut c = w.chars();
c.next().map(|f| f.to_uppercase().chain(c).collect()).unwrap_or_default()
}
// ---------- memorable password ----------
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Separator {
Hyphen,
Space,
Period,
Comma,
Underscore,
/// A random digit in every gap.
Digit,
/// A random digit or symbol from [`SEPARATOR_SYMBOLS`] in every gap.
DigitOrSymbol,
}
pub const SEPARATOR_SYMBOLS: &str = "!@#$%^&*-_=+?";
impl Separator {
fn choices(self) -> Vec<char> {
match self {
Separator::Hyphen => vec!['-'],
Separator::Space => vec![' '],
Separator::Period => vec!['.'],
Separator::Comma => vec![','],
Separator::Underscore => vec!['_'],
Separator::Digit => DIGITS.to_vec(),
Separator::DigitOrSymbol => DIGITS.iter().copied().chain(SEPARATOR_SYMBOLS.chars()).collect(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MemorableOptions {
/// 3..=10.
pub words: u8,
/// One random digit after every word.
pub digit_after_word: bool,
/// First letter of each word in capitals (adds no entropy).
pub capitalize: bool,
pub separator: Separator,
}
impl Default for MemorableOptions {
fn default() -> Self {
MemorableOptions { words: 4, digit_after_word: true, capitalize: true, separator: Separator::Hyphen }
}
}
pub const MIN_WORDS: u8 = 3;
pub const MAX_WORDS: u8 = 10;
/// Bits of entropy of a memorable password with these options.
pub fn memorable_entropy(o: &MemorableOptions) -> f64 {
let n = o.words.clamp(MIN_WORDS, MAX_WORDS) as f64;
let per_word = (MEMORABLE_WORDS.len() as f64).log2() + if o.digit_after_word { 10f64.log2() } else { 0.0 };
n * per_word + (n - 1.0) * (o.separator.choices().len() as f64).log2()
}
/// `Word7-Other3-Third9-Fourth2`.
pub fn memorable(o: &MemorableOptions) -> Generated {
let n = o.words.clamp(MIN_WORDS, MAX_WORDS);
let seps = o.separator.choices();
let mut out = String::with_capacity(n as usize * 12);
for i in 0..n {
if i > 0 {
out.push(pick(&seps));
}
let w = pick(&MEMORABLE_WORDS);
if o.capitalize {
out.push_str(&capitalize(w));
} else {
out.push_str(w);
}
if o.digit_after_word {
out.push(digit());
}
}
Generated { value: SecretString::new(out), entropy_bits: memorable_entropy(o) }
}
// ---------- nickname ----------
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NicknameOptions {
/// Tokens `{Name}`, `{Word}`, `{Number}` and literal text, e.g. `{Name}.{Word}.{Number}`.
pub template: String,
/// Where `{Word}` comes from (their union).
pub kinds: Vec<WordKind>,
/// Length of `{Number}`, 1..=4.
pub digits: u8,
/// a→4, e→3, i→1, o→0, s→5, t→7 in `{Word}` after its first letter (adds no entropy).
pub leet: bool,
}
impl Default for NicknameOptions {
fn default() -> Self {
NicknameOptions {
template: "{Name}.{Word}.{Number}".into(),
kinds: vec![WordKind::Noun],
digits: 2,
leet: false,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Token {
Literal(String),
Name,
Word,
Number,
}
fn parse_template(t: &str) -> Result<Vec<Token>, GenError> {
let mut out = Vec::new();
let mut rest = t;
while !rest.is_empty() {
match rest.find(['{', '}']) {
Some(i) if rest.as_bytes()[i] == b'}' => return fail("the template has a '}' without '{'"),
Some(i) => {
if i > 0 {
out.push(Token::Literal(rest[..i].into()));
}
let end = rest[i..].find('}').ok_or_else(|| GenError("the template has a '{' without '}'".into()))?;
out.push(match &rest[i + 1..i + end] {
"Name" => Token::Name,
"Word" => Token::Word,
"Number" => Token::Number,
other => {
return Err(GenError(format!(
"unknown token {{{other}}}: use {{Name}}, {{Word}} or {{Number}}"
)));
}
});
rest = &rest[i + end + 1..];
}
None => {
out.push(Token::Literal(rest.into()));
rest = "";
}
}
}
Ok(out)
}
/// Normalises an entry title for `{Name}`: diacritics stripped, letters and digits only, PascalCase,
/// at most 20 characters. `Česká spořitelna` → `CeskaSporitelna`.
pub fn normalize_name(title: &str) -> String {
let mut words: Vec<String> = vec![String::new()];
for c in title.nfd().filter(|c| !is_combining_mark(*c)) {
let mapped = match c {
'ß' => "ss",
'æ' => "ae",
'Æ' => "Ae",
'œ' => "oe",
'Œ' => "Oe",
'ø' => "o",
'Ø' => "O",
'ł' => "l",
'Ł' => "L",
'đ' => "d",
'Đ' => "D",
'þ' => "th",
'Þ' => "Th",
c if c.is_ascii_alphanumeric() => {
words.last_mut().unwrap().push(c);
continue;
}
_ => {
words.push(String::new());
continue;
}
};
words.last_mut().unwrap().push_str(mapped);
}
words.iter().map(|w| capitalize(w)).collect::<String>().chars().take(20).collect()
}
fn leetify(w: &str) -> String {
let mut c = w.chars();
let first = c.next().map(String::from).unwrap_or_default();
first
+ &c.map(|ch| match ch {
'a' => '4',
'e' => '3',
'i' => '1',
'o' => '0',
's' => '5',
't' => '7',
other => other,
})
.collect::<String>()
}
/// The random parts of a nickname, drawn once. The title can keep changing afterwards: [`render`]
/// fills it in without drawing new words or numbers (a new web login's nickname follows its title as
/// it is typed).
///
/// [`render`]: NicknameParts::render
#[derive(Clone, Debug)]
pub struct NicknameParts {
/// One per `{Word}` in the template, capitalised (and leetified if asked).
pub words: Vec<String>,
/// One per `{Number}` in the template.
pub numbers: Vec<String>,
pub entropy_bits: f64,
}
fn word_pool(kinds: &[WordKind]) -> Vec<&'static str> {
let mut pool: Vec<&'static str> = kinds.iter().flat_map(|k| words(*k).iter().copied()).collect();
// Overlapping lists: count each word once, so the entropy stays honest.
pool.sort_unstable();
pool.dedup();
pool
}
/// Draws the words and numbers for `o.template`.
pub fn nickname_parts(o: &NicknameOptions) -> Result<NicknameParts, GenError> {
let tokens = parse_template(&o.template)?;
if !(1..=4).contains(&o.digits) {
return fail("the number must have 1 to 4 digits");
}
let pool = word_pool(&o.kinds);
let mut parts = NicknameParts { words: Vec::new(), numbers: Vec::new(), entropy_bits: 0.0 };
for t in &tokens {
match t {
Token::Word => {
if pool.is_empty() {
return fail("choose at least one kind of word");
}
let w = capitalize(pick(&pool));
parts.words.push(if o.leet { leetify(&w) } else { w });
parts.entropy_bits += (pool.len() as f64).log2();
}
Token::Number => {
parts.numbers.push((0..o.digits).map(|_| digit()).collect());
parts.entropy_bits += o.digits as f64 * 10f64.log2();
}
Token::Literal(_) | Token::Name => {}
}
}
Ok(parts)
}
impl NicknameParts {
/// The nickname for `title`. With an empty (normalised) title, `{Name}` is left out together with
/// the literal separator next to it. `template` must be the one the parts were drawn for.
pub fn render(&self, title: &str, template: &str) -> Result<String, GenError> {
let mut tokens = parse_template(template)?;
let name = normalize_name(title);
if name.is_empty() {
while let Some(i) = tokens.iter().position(|t| *t == Token::Name) {
tokens.remove(i);
if i == 0 {
if matches!(tokens.first(), Some(Token::Literal(_))) {
tokens.remove(0);
}
} else if matches!(tokens.get(i - 1), Some(Token::Literal(_))) {
tokens.remove(i - 1);
}
}
}
let (mut words, mut numbers) = (self.words.iter(), self.numbers.iter());
let mismatch = || GenError("the template changed since its words were drawn".into());
let mut out = String::new();
for t in &tokens {
match t {
Token::Literal(s) => out.push_str(s),
Token::Name => out.push_str(&name),
Token::Word => out.push_str(words.next().ok_or_else(mismatch)?),
Token::Number => out.push_str(numbers.next().ok_or_else(mismatch)?),
}
}
Ok(out)
}
}
/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}`
/// is left out together with the literal separator next to it.
pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError> {
let parts = nickname_parts(o)?;
let value = parts.render(title, &o.template)?;
Ok(Generated { value: SecretString::new(value), entropy_bits: parts.entropy_bits })
}
// ---------- random, strict site, PIN ----------
// Only English letters A–Z/a–z, digits 0–9 and ASCII symbols: every keyboard layout can type them.
pub const RANDOM_SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/~";
pub const LOOKALIKES: &str = "Il1O0o|";
pub const MAX_LENGTH: u16 = 128;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RandomOptions {
pub length: u16,
pub upper: bool,
pub lower: bool,
pub digits: bool,
pub symbols: bool,
pub exclude_lookalikes: bool,
}
impl Default for RandomOptions {
fn default() -> Self {
RandomOptions { length: 20, upper: true, lower: true, digits: true, symbols: true, exclude_lookalikes: false }
}
}
fn class_chars(upper: bool, lower: bool, digits: bool, symbols: &str) -> Vec<Vec<char>> {
let mut classes = Vec::new();
if lower {
classes.push(('a'..='z').collect());
}
if upper {
classes.push(('A'..='Z').collect());
}
if digits {
classes.push(('0'..='9').collect());
}
if !symbols.is_empty() {
classes.push(symbols.chars().collect());
}
classes
}
fn check_length(length: u16) -> Result<usize, GenError> {
if length == 0 || length > MAX_LENGTH {
return Err(GenError(format!("length must be 1 to {MAX_LENGTH}")));
}
Ok(length as usize)
}
/// `length` characters, each drawn uniformly from the chosen classes.
pub fn random(o: &RandomOptions) -> Result<Generated, GenError> {
let len = check_length(o.length)?;
let mut alphabet: Vec<char> =
class_chars(o.upper, o.lower, o.digits, if o.symbols { RANDOM_SYMBOLS } else { "" }).concat();
if o.exclude_lookalikes {
alphabet.retain(|c| !LOOKALIKES.contains(*c));
}
if alphabet.is_empty() {
return fail("choose at least one kind of character");
}
let value: String = (0..len).map(|_| pick(&alphabet)).collect();
Ok(Generated { value: SecretString::new(value), entropy_bits: len as f64 * (alphabet.len() as f64).log2() })
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClassRule {
Exclude,
Allow,
Require,
}
/// For sites with rules: exactly `length` characters (their maximum), only allowed classes, and at
/// least one of each required class.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StrictOptions {
pub length: u16,
pub lower: ClassRule,
pub upper: ClassRule,
pub digits: ClassRule,
pub symbols: ClassRule,
/// The symbols the site accepts. Only ASCII symbols count: letters, digits, spaces and anything
/// outside ASCII (`€`, `§`, `ž`) are ignored.
pub allowed_symbols: String,
}
impl Default for StrictOptions {
fn default() -> Self {
StrictOptions {
length: 16,
lower: ClassRule::Require,
upper: ClassRule::Require,
digits: ClassRule::Require,
symbols: ClassRule::Require,
allowed_symbols: "!@#$%&*?-_".into(),
}
}
}
pub fn strict(o: &StrictOptions) -> Result<Generated, GenError> {
let len = check_length(o.length)?;
let mut symbols: Vec<char> = o.allowed_symbols.chars().filter(char::is_ascii_punctuation).collect();
symbols.sort_unstable();
symbols.dedup();
let rules = [
(o.lower, ('a'..='z').collect::<Vec<char>>()),
(o.upper, ('A'..='Z').collect()),
(o.digits, ('0'..='9').collect()),
(o.symbols, symbols),
];
if rules.iter().any(|(r, set)| *r == ClassRule::Require && set.is_empty()) {
return fail("symbols are required but none are allowed");
}
let allowed: Vec<&Vec<char>> =
rules.iter().filter(|(r, s)| *r != ClassRule::Exclude && !s.is_empty()).map(|(_, s)| s).collect();
let required: Vec<&Vec<char>> = rules.iter().filter(|(r, _)| *r == ClassRule::Require).map(|(_, s)| s).collect();
if allowed.is_empty() {
return fail("choose at least one kind of character");
}
if required.len() > len {
return fail("the length is shorter than the number of required kinds of character");
}
let alphabet: Vec<char> = allowed.iter().flat_map(|s| s.iter().copied()).collect();
// Rejection sampling: uniform over all strings that satisfy the rules.
let value = loop {
let s: Vec<char> = (0..len).map(|_| pick(&alphabet)).collect();
if required.iter().all(|set| s.iter().any(|c| set.contains(c))) {
break s.into_iter().collect::<String>();
}
};
// Entropy = log2(number of valid strings), by inclusion–exclusion over the required classes.
let n = alphabet.len() as f64;
let mut count = 0.0;
for mask in 0u32..(1 << required.len()) {
let removed: usize = (0..required.len()).filter(|i| mask & (1 << i) != 0).map(|i| required[i].len()).sum();
let sign = if mask.count_ones() % 2 == 0 { 1.0 } else { -1.0 };
count += sign * (n - removed as f64).powi(len as i32);
}
Ok(Generated { value: SecretString::new(value), entropy_bits: count.log2() })
}
/// `length` random digits.
pub fn pin(length: u8) -> Generated {
let len = length.clamp(1, 32) as usize;
let value: String = (0..len).map(|_| digit()).collect();
Generated { value: SecretString::new(value), entropy_bits: len as f64 * 10f64.log2() }
}
+292
View File
@@ -0,0 +1,292 @@
//! The mandatory generator tests (CLAUDE.md).
use custos_gen::{
ClassRule, MAX_LENGTH, MEMORABLE_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions,
WordKind, memorable, memorable_entropy, nickname, nickname_parts, normalize_name, pin, random, strict,
};
use regex::Regex;
use std::collections::HashSet;
const SAMPLES: usize = 10_000;
#[test]
fn memorable_words_are_real_english_words() {
assert_eq!(MEMORABLE_WORDS.len(), 7_322);
let unique: HashSet<_> = MEMORABLE_WORDS.iter().collect();
assert_eq!(unique.len(), 7_322);
assert!(MEMORABLE_WORDS.iter().all(|w| w.len() >= 3 && w.bytes().all(|b| b.is_ascii_lowercase())));
// Every word comes from the EFF list...
let eff: HashSet<&str> = include_str!("../wordlists/eff_large_wordlist.txt")
.lines()
.filter_map(|l| l.split('\t').nth(1))
.map(str::trim)
.collect();
assert!(MEMORABLE_WORDS.iter().all(|w| eff.contains(w)));
// ...minus brand names, names, coinages and hyphenated words that no dictionary lists.
for not_a_word in ["walmart", "iphone", "skype", "myspace", "monday", "december", "pranker", "finlike", "felt-tip"]
{
assert!(eff.contains(not_a_word), "{not_a_word} is not in the EFF list any more");
assert!(!MEMORABLE_WORDS.contains(&not_a_word), "{not_a_word}");
}
}
#[test]
fn memorable_default_shape() {
let o = MemorableOptions::default();
assert_eq!((o.words, o.digit_after_word, o.capitalize, o.separator), (4, true, true, Separator::Hyphen));
let re = Regex::new(r"^[A-Z][a-z]+[0-9](-[A-Z][a-z]+[0-9]){3}$").unwrap();
for _ in 0..1_000 {
let g = memorable(&o);
assert!(re.is_match(g.value.expose()), "{}", g.value.expose());
}
}
#[test]
fn memorable_shape_at_every_slider_value_and_option() {
let seps = [
(Separator::Hyphen, "-"),
(Separator::Space, " "),
(Separator::Period, r"\."),
(Separator::Comma, ","),
(Separator::Underscore, "_"),
(Separator::Digit, "[0-9]"),
(Separator::DigitOrSymbol, r"[0-9!@#$%^&*\-_=+?]"),
];
for words in 3..=10u8 {
for (sep, sep_re) in seps {
for (digit, cap) in [(true, true), (false, true), (true, false), (false, false)] {
let o = MemorableOptions { words, digit_after_word: digit, capitalize: cap, separator: sep };
let word =
format!("{}{}", if cap { "[A-Z][a-z]+" } else { "[a-z]+" }, if digit { "[0-9]" } else { "" });
let re = Regex::new(&format!("^{word}({sep_re}{word}){{{}}}$", words - 1)).unwrap();
for _ in 0..20 {
let g = memorable(&o);
assert!(re.is_match(g.value.expose()), "{o:?}: {}", g.value.expose());
}
}
}
}
}
#[test]
fn memorable_entropy_counts_only_random_choices() {
let per_word = 7_322f64.log2() + 10f64.log2();
for words in 3..=10u8 {
let o = MemorableOptions { words, ..Default::default() };
let e = memorable_entropy(&o);
assert!((e - words as f64 * per_word).abs() < 1e-9, "{words}: {e}");
assert!((memorable(&o).entropy_bits - e).abs() < 1e-9);
// Capitalising every word is not a random choice: it adds nothing.
let lower = MemorableOptions { capitalize: false, ..o };
assert!((memorable_entropy(&lower) - e).abs() < 1e-9);
}
let four = memorable_entropy(&MemorableOptions::default());
assert!((64.0..66.0).contains(&four), "4 words with digits is about 65 bits: {four}");
let no_digits = MemorableOptions { digit_after_word: false, ..Default::default() };
assert!((memorable_entropy(&no_digits) - 4.0 * 7_322f64.log2()).abs() < 1e-9);
// A random-digit separator is a random choice per gap.
let digit_sep = MemorableOptions { separator: Separator::Digit, ..Default::default() };
assert!((memorable_entropy(&digit_sep) - (four + 3.0 * 10f64.log2())).abs() < 1e-9);
}
#[test]
fn nickname_default_template_with_diacritics() {
let o = NicknameOptions::default();
assert_eq!(o.template, "{Name}.{Word}.{Number}");
assert_eq!(o.kinds, vec![WordKind::Noun]);
assert_eq!(o.digits, 2);
let re = Regex::new(r"^CeskaSporitelna\.[A-Z][a-z]+\.[0-9]{2}$").unwrap();
let nouns: HashSet<&str> = custos_gen::words(WordKind::Noun).iter().copied().collect();
for _ in 0..1_000 {
let n = nickname("Česká spořitelna", &o).unwrap();
let s = n.value.expose();
assert!(re.is_match(s), "{s}");
let word = s.split('.').nth(1).unwrap().to_lowercase();
assert!(nouns.contains(word.as_str()), "{word} is not from the noun list");
}
let gh = nickname("GitHub", &o).unwrap();
assert!(Regex::new(r"^GitHub\.[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(gh.value.expose()));
}
#[test]
fn nickname_word_comes_from_the_selected_kinds() {
for kinds in [vec![WordKind::Adjective], vec![WordKind::Verb], vec![WordKind::Adjective, WordKind::Verb]] {
let allowed: HashSet<&str> = kinds.iter().flat_map(|k| custos_gen::words(*k).iter().copied()).collect();
let o = NicknameOptions { template: "{Word}".into(), kinds: kinds.clone(), ..Default::default() };
for _ in 0..500 {
let w = nickname("x", &o).unwrap().value.expose().to_lowercase();
assert!(allowed.contains(w.as_str()), "{w} not in {kinds:?}");
}
}
}
#[test]
fn nickname_without_title_drops_name_and_its_separator() {
let d = NicknameOptions::default();
let re = Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap();
for title in ["", " ", "!!!"] {
let s = nickname(title, &d).unwrap().value.expose().to_owned();
assert!(re.is_match(&s), "{title:?} -> {s}");
}
let o = NicknameOptions { template: "{Word}_{Name}{Number}".into(), ..Default::default() };
let s = nickname("", &o).unwrap().value.expose().to_owned();
assert!(Regex::new(r"^[A-Z][a-z]+[0-9]{2}$").unwrap().is_match(&s), "{s}");
let s = nickname("Proton Mail", &o).unwrap().value.expose().to_owned();
assert!(Regex::new(r"^[A-Z][a-z]+_ProtonMail[0-9]{2}$").unwrap().is_match(&s), "{s}");
}
#[test]
fn nickname_options_and_entropy() {
for digits in 1..=4u8 {
let o = NicknameOptions { template: "{Number}".into(), digits, ..Default::default() };
let n = nickname("x", &o).unwrap();
assert_eq!(n.value.expose().len(), digits as usize);
assert!((n.entropy_bits - digits as f64 * 10f64.log2()).abs() < 1e-9);
}
let d = nickname("GitHub", &NicknameOptions::default()).unwrap();
let nouns = custos_gen::words(WordKind::Noun).len() as f64;
assert!((d.entropy_bits - (nouns.log2() + 2.0 * 10f64.log2())).abs() < 1e-9, "the name adds nothing");
let leet = NicknameOptions { leet: true, ..Default::default() };
let l = nickname("GitHub", &leet).unwrap();
assert!((l.entropy_bits - d.entropy_bits).abs() < 1e-9, "leetspeak on a known pattern adds nothing");
assert!(nickname("x", &NicknameOptions { template: "{Bogus}".into(), ..Default::default() }).is_err());
assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err());
}
#[test]
fn nickname_parts_keep_word_and_number_while_the_title_changes() {
let o = NicknameOptions::default();
let parts = nickname_parts(&o).unwrap();
let typed: Vec<String> = ["", "G", "Gi", "GitHub"].iter().map(|t| parts.render(t, &o.template).unwrap()).collect();
let tail = typed[0].clone(); // "Lantern.47": no title, so {Name} and its "." are left out
assert!(Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(&tail), "{tail}");
assert_eq!(typed[1], format!("G.{tail}"));
assert_eq!(typed[3], format!("GitHub.{tail}"));
assert!(parts.render("x", "{Word}{Word}").is_err(), "a template with more tokens than parts");
}
#[test]
fn name_normalisation() {
assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna");
assert_eq!(normalize_name("GitHub"), "GitHub");
assert_eq!(normalize_name("proton mail"), "ProtonMail");
assert_eq!(normalize_name("Žluťoučký kůň úpěl ďábelské ódy"), "ZlutouckyKunUpelDabe");
assert_eq!(normalize_name(" "), "");
assert_eq!(normalize_name("Straße 42"), "Strasse42");
assert!(normalize_name("A very long name that goes on and on").len() <= 20);
}
#[test]
fn word_lists_are_plain_and_unique() {
for k in [WordKind::Adjective, WordKind::Noun, WordKind::Verb] {
let w = custos_gen::words(k);
assert!(w.len() >= 150, "{k:?}: {}", w.len());
let unique: HashSet<_> = w.iter().collect();
assert_eq!(unique.len(), w.len(), "{k:?} has duplicates");
assert!(w.iter().all(|s| s.len() >= 3 && s.bytes().all(|b| b.is_ascii_lowercase())), "{k:?}");
}
}
#[test]
fn strict_site_template_is_never_violated() {
let o = StrictOptions {
length: 12,
lower: ClassRule::Require,
upper: ClassRule::Require,
digits: ClassRule::Require,
symbols: ClassRule::Require,
allowed_symbols: "!#$".into(),
};
let allowed: HashSet<char> = ('a'..='z').chain('A'..='Z').chain('0'..='9').chain("!#$".chars()).collect();
for _ in 0..SAMPLES {
let g = strict(&o).unwrap();
let s = g.value.expose();
assert_eq!(s.chars().count(), 12, "{s}");
assert!(s.chars().all(|c| allowed.contains(&c)), "{s}");
assert!(s.chars().any(|c| c.is_ascii_lowercase()), "{s}");
assert!(s.chars().any(|c| c.is_ascii_uppercase()), "{s}");
assert!(s.chars().any(|c| c.is_ascii_digit()), "{s}");
assert!(s.chars().any(|c| "!#$".contains(c)), "{s}");
}
// Excluded classes never appear.
let digits_only = StrictOptions {
length: 6,
lower: ClassRule::Exclude,
upper: ClassRule::Exclude,
digits: ClassRule::Require,
symbols: ClassRule::Exclude,
allowed_symbols: String::new(),
};
for _ in 0..SAMPLES {
assert!(strict(&digits_only).unwrap().value.expose().bytes().all(|b| b.is_ascii_digit()));
}
// More required classes than characters cannot be satisfied.
assert!(strict(&StrictOptions { length: 3, ..o.clone() }).is_err());
// Entropy counts only strings that satisfy the rules: less than length × log2(alphabet).
let e = strict(&o).unwrap().entropy_bits;
assert!(e < 12.0 * 65f64.log2() && e > 12.0 * 65f64.log2() - 3.0, "{e}");
}
#[test]
fn random_and_pin() {
let o = RandomOptions::default();
for _ in 0..1_000 {
let g = random(&o).unwrap();
assert_eq!(g.value.expose().chars().count(), o.length as usize);
}
let no_look = RandomOptions { exclude_lookalikes: true, ..o.clone() };
for _ in 0..SAMPLES / 10 {
let s = random(&no_look).unwrap().value.expose().to_owned();
assert!(!s.chars().any(|c| "Il1O0o|".contains(c)), "{s}");
}
let g =
random(&RandomOptions { length: 20, upper: false, lower: true, digits: false, symbols: false, ..o }).unwrap();
assert!((g.entropy_bits - 20.0 * 26f64.log2()).abs() < 1e-9);
let p = pin(6);
assert!(p.value.expose().len() == 6 && p.value.expose().bytes().all(|b| b.is_ascii_digit()));
assert!((p.entropy_bits - 6.0 * 10f64.log2()).abs() < 1e-9);
}
#[test]
fn random_and_strict_use_only_english_letters_digits_and_ascii_symbols() {
let ok = |c: char| c.is_ascii_alphanumeric() || c.is_ascii_punctuation();
let all = RandomOptions { length: MAX_LENGTH, ..RandomOptions::default() };
for _ in 0..SAMPLES / 10 {
let s = random(&all).unwrap().value.expose().to_owned();
assert!(s.chars().all(ok), "{s}");
}
// Symbols the site lists outside ASCII, letters, digits and spaces are ignored.
let o = StrictOptions { length: 32, allowed_symbols: "€§ž é1!".into(), ..StrictOptions::default() };
for _ in 0..SAMPLES / 10 {
let s = strict(&o).unwrap().value.expose().to_owned();
assert!(s.chars().all(|c| c.is_ascii_alphanumeric() || c == '!'), "{s}");
}
let none_left = StrictOptions { allowed_symbols: "€§".into(), ..StrictOptions::default() };
assert!(strict(&none_left).is_err(), "required symbols, but none of the listed ones is ASCII");
}
/// Nicknames (≈ 30 000 combinations by design: they are names, not secrets) and short PINs are
/// excluded: their spaces are small enough that repeats in 10 000 draws are expected.
#[test]
fn no_repeats_in_ten_thousand_samples() {
let mut seen = HashSet::new();
for _ in 0..SAMPLES {
assert!(seen.insert(memorable(&MemorableOptions::default()).value.expose().to_owned()));
}
let mut seen = HashSet::new();
for _ in 0..SAMPLES {
assert!(seen.insert(random(&RandomOptions::default()).unwrap().value.expose().to_owned()));
}
let strict_o = StrictOptions::default();
let mut seen = HashSet::new();
for _ in 0..SAMPLES {
assert!(seen.insert(strict(&strict_o).unwrap().value.expose().to_owned()));
}
}
#[test]
fn generated_values_are_redacted_in_debug() {
let g = memorable(&MemorableOptions::default());
let out = format!("{g:?}");
assert!(!out.contains(g.value.expose()) && out.contains("[redacted]"), "{out}");
}
+29
View File
@@ -0,0 +1,29 @@
# Word lists: sources and licences
| File | Used for | Source | Licence |
|:--|:--|:--|:--|
| `eff_large_wordlist.txt` | The source of `memorable.txt` (kept as published) | Electronic Frontier Foundation, "Deep Dive: EFF's New Wordlists for Random Passphrases" (2016), downloaded unchanged from https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt (sha256 `addd35536511597a02fa0a9ff1e5284677b8883b83e986e43f15a3db996b903e`) | CC BY 3.0 US. Attribution: © Electronic Frontier Foundation. |
| `memorable.txt` | Memorable passwords (7,322 words, 12.838 bits each) | The EFF list minus every word that SCOWL/ESDB size 60, US spelling (the size of hunspell's `en_US` dictionary) does not list as a plain lowercase word. Made by `derive_memorable.py` from https://app.aspell.net/create?max_size=60&spelling=US&max_variant=0&diacritic=strip&download=wordlist&encoding=utf-8&format=inline (ESDB revision 1e5b7d3, 2026-06-24; sha256 of the download `bfbc258a6baaa50aec6fe07330b25b57cd90f3dd429345b8280df0414ccf242c`) | CC BY 3.0 US (© Electronic Frontier Foundation), and the ESDB notice below |
| `nouns.txt`, `adjectives.txt`, `verbs.txt` | Nicknames (`{Word}`) | Written for Custos Domi in 2026 by hand: common, family-friendly English words | CC0 1.0 (public domain dedication) |
## How they are used
- Memorable passwords use only real English words. The EFF list has brand names (`walmart`, `iphone`,
`skype`), names (`monday`, `december`), coinages (`pranker`, `finlike`) and four hyphenated words
(`felt-tip`, …); a word stays only if the standard US spellchecker dictionary knows it. 454 words go,
7,322 stay (tested, with examples), so each word is worth log2(7,322) = 12.838 bits instead of 12.925.
- To rebuild `memorable.txt`, download the URL above and run `python derive_memorable.py <file>`.
- The nickname lists are not secret material: a nickname is a name, not a password. They are kept short,
friendly and unique (tested), and each word has at least three letters.
## ESDB (SCOWL) notice
Copyright 2000-2026 by Kevin Atkinson
Permission to use, copy, modify, distribute, and sell any part of the English
Speller Database (ESDB, previously known as SCOWLv2), or word lists
created from it, is hereby granted without fee, provided that the above
copyright notice appears in all copies and that both the above copyright
notice and this notice appear in supporting documentation. Kevin Atkinson
makes no representations about the suitability of this database for any
purpose. It is provided "as is" without express or implied warranty.
@@ -0,0 +1,14 @@
# Adjectives for nicknames. Written for Custos; dedicated to the public domain (CC0 1.0). See SOURCES.md.
able agile airy amber ample ancient arctic ardent atomic autumn azure balmy bold brave breezy bright
brisk bronze bubbly busy calm candid careful cheerful chilly civic classic clever cloudy cobalt
cosmic cozy crafty crimson crisp curious daring dapper dazzling deft dewy dreamy dusty eager early
earnest easy electric elegant epic even exact fair famous fancy fearless fiery fine firm fleet fluffy
fond frank fresh friendly frosty gentle giant gifted glad gleaming glossy golden graceful grand grassy
green handy happy hardy hearty helpful heroic hidden honest humble icy ideal jolly jovial joyful keen
kind large lavish lively loyal lucid lucky lunar magic majestic mellow merry mighty mild misty modern
modest neat nimble noble polar polite proud quick quiet radiant rapid rare ready regal rosy royal rustic
sandy savvy scenic serene sharp shiny silent silky silver simple sleek smart smooth snowy snug solar
solid sonic sparkly speedy spicy steady stellar stormy sturdy sublime sunny super swift tidy tiny
topaz tranquil trusty upbeat urban valiant vast velvet vivid warm wavy whimsical wild windy wise witty
woody young zany zesty zippy amiable bouncy dainty glowing jazzy plucky quirky snappy spry
sunlit thrifty twinkly velvety wintry
@@ -0,0 +1,24 @@
"""Rebuilds memorable.txt: the EFF large wordlist minus every word that the standard US English
spellchecker dictionary (SCOWL/ESDB size 60, the size of hunspell's en_US) does not list as a plain
lowercase word. That removes brand names (walmart), names and capitalised words (monday) and coinages
(pranker). See SOURCES.md for the exact download.
python derive_memorable.py <scowl-size-60.txt>
"""
import sys
from pathlib import Path
here = Path(__file__).parent
scowl = Path(sys.argv[1]).read_text(encoding="utf-8")
dictionary = set(scowl.split("---", 1)[1].split())
eff = [line.split("\t")[1].strip() for line in (here / "eff_large_wordlist.txt").read_text().splitlines()]
kept = [w for w in eff if w in dictionary]
header = """\
# Memorable-password words: the EFF large wordlist (CC BY 3.0 US, (c) Electronic Frontier Foundation)
# minus the words not in SCOWL/ESDB size 60 (US). Word list (c) 2000-2026 by Kevin Atkinson, see SOURCES.md.
# Generated by derive_memorable.py; do not edit by hand.
"""
(here / "memorable.txt").write_text(header + "\n".join(kept) + "\n", encoding="utf-8", newline="\n")
print(f"kept {len(kept)} of {len(eff)}")
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
# Nouns for nicknames. Written for Custos; dedicated to the public domain (CC0 1.0). See SOURCES.md.
acorn almond amber anchor anvil apple apricot arch arrow aspen atlas attic aurora autumn avocado
badger bagel balcony bamboo banjo banner barley barrel basil basket beacon beaver bell berry birch
biscuit bison blossom boat bonsai bramble breeze brick bridge brook broom bucket buffalo bugle bunny
cabin cactus camel candle canoe canyon caramel cargo carrot castle cedar cello chalk cherry chestnut
cider cinnamon clover cobalt cocoa comet compass copper coral cotton cougar coyote crane crayon
cricket crystal cupcake cypress daisy dawn delta desert dolphin domino donkey dragonfly drum dune
eagle echo elm ember emerald engine falcon feather fern ferry fiddle fig finch fjord flame flute
forest fossil fountain fox galaxy garden garnet gazelle geyser ginger glacier glider goose granite
grape gravel grove guitar gull harbor harp hazel heron hickory hill honey horizon hummingbird iceberg
igloo island ivory jade jaguar jasmine jelly jetty juniper kayak kelp kettle kite kiwi koala ladder
lagoon lake lantern larch lark lava lemon lighthouse lilac lily lime linen lion llama lobster locket
lotus lynx magnet magpie mango maple marble marsh meadow melon meteor mint mitten monsoon moon moose
moss mountain muffin nectar nest nickel nutmeg oak oasis ocean olive onyx orbit orchard orchid otter
owl oyster paddle panda papaya parrot peach peanut pebble pelican penguin pepper piano pigeon pine
planet plum pond poppy prairie pretzel puffin pumpkin quail quartz quill rabbit radish rainbow raven
reef ribbon river robin rocket rose ruby saddle saffron sage salmon sapphire satchel sequoia shell
sierra silver sparrow spruce squirrel star stone summit sunflower swan teapot thistle thunder tiger
timber toucan tulip tundra turtle twig valley velvet violet volcano walnut walrus willow window
wolf wren yak zebra zephyr harvest trumpet mosaic pixel puzzle saturn mercury jupiter neptune
cobble lantana spindle tinsel waffle sorbet truffle toffee nougat marzipan
+11
View File
@@ -0,0 +1,11 @@
# Verbs for nicknames (base form). Written for Custos; dedicated to the public domain (CC0 1.0). See SOURCES.md.
adapt admire amble arrive bake balance beam bloom blossom bounce brew build carve chant chase cheer
chirp climb coast collect cook craft create cruise dance dash dazzle deliver discover dive doodle
drift drum dwell embark enjoy explore fetch fiddle fix float flourish flutter fly fold forage gallop
gather giggle glide glow graze greet grow guide hike hop hover hum hurry imagine invent jog juggle
jump kindle knit laugh launch learn leap linger listen marvel meander mend mingle mix nestle nudge
observe orbit paddle paint pedal plant play ponder prance quest race ramble read relax rescue ride
roam row rush sail savor scamper scout sculpt seek shimmer shine sing sketch skate ski skip slide
smile soar sparkle spin sprint stargaze stroll study surf swim swing tinker travel trek twirl venture
voyage wade wander wave weave whistle wiggle wink wish wonder write yodel zigzag zoom bustle frolic
hustle mosey ripple sprout sway tumble twinkle waddle whirl
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "custos-qr"
description = "Custos QR payloads: Wi-Fi join codes and plain secrets (payload strings only, no rendering)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
+58
View File
@@ -0,0 +1,58 @@
//! QR payload strings. Rendering happens in the app; this crate only decides what the code says.
/// Security of a Wi-Fi network as the `WIFI:` payload names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WifiSecurity {
/// WPA, WPA2 or WPA3 (`T:WPA`).
Wpa,
Wep,
/// Open network (`T:nopass`).
None,
}
impl WifiSecurity {
/// From the vault's `security` field (`WPA`, `WEP`, `nopass`); anything else counts as WPA.
pub fn parse(s: &str) -> WifiSecurity {
match s.trim().to_ascii_uppercase().as_str() {
"WEP" => WifiSecurity::Wep,
"NOPASS" | "NONE" | "OPEN" => WifiSecurity::None,
_ => WifiSecurity::Wpa,
}
}
fn token(self) -> &'static str {
match self {
WifiSecurity::Wpa => "WPA",
WifiSecurity::Wep => "WEP",
WifiSecurity::None => "nopass",
}
}
}
/// Escapes `\`, `;`, `,`, `:` and `"` with a backslash, as the `WIFI:` format requires.
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '\\' | ';' | ',' | ':' | '"') {
out.push('\\');
}
out.push(c);
}
out
}
/// `WIFI:T:<WPA|WEP|nopass>;S:<ssid>;P:<password>;H:<true|false>;;` — a phone camera joins from it.
/// An open network gets no `P:` field.
pub fn wifi_payload(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> String {
let mut p = format!("WIFI:T:{};S:{};", security.token(), escape(ssid));
if security != WifiSecurity::None {
p.push_str(&format!("P:{};", escape(password)));
}
p.push_str(&format!("H:{hidden};;"));
p
}
/// A QR code that shows a secret to a phone camera is the plain value, so it can be typed elsewhere.
pub fn secret_payload(value: &str) -> String {
value.to_owned()
}
+72
View File
@@ -0,0 +1,72 @@
//! Wi-Fi QR payloads: every special character escaped, so a phone reads back exactly what was stored.
use custos_qr::{WifiSecurity, escape, secret_payload, wifi_payload};
/// What a reader does: split on unescaped `;`, undo `\x` escapes.
fn parse(payload: &str) -> Vec<(String, String)> {
let body = payload.strip_prefix("WIFI:").expect("prefix").strip_suffix(";;").expect("suffix");
let mut fields = Vec::new();
let mut cur = String::new();
let mut chars = body.chars();
while let Some(c) = chars.next() {
match c {
'\\' => cur.push(chars.next().expect("escape at end")),
';' => fields.push(std::mem::take(&mut cur)),
c => cur.push(c),
}
}
fields.push(cur);
fields
.into_iter()
.map(|f| {
let (k, v) = f.split_once(':').expect("key:value");
(k.to_owned(), v.to_owned())
})
.collect()
}
#[test]
fn escapes_every_special_character() {
assert_eq!(escape(r#"\;,:""#), r#"\\\;\,\:\""#);
assert_eq!(escape("plain-text_123 ok"), "plain-text_123 ok");
}
#[test]
fn ssid_and_password_with_every_special_character_survive() {
let nasty = r#"My\Net;5G,"home":x"#;
let pass = r#"p\a;s,s:w"o"r;d\"#;
let p = wifi_payload(nasty, pass, WifiSecurity::Wpa, true);
assert_eq!(p, r#"WIFI:T:WPA;S:My\\Net\;5G\,\"home\"\:x;P:p\\a\;s\,s\:w\"o\"r\;d\\;H:true;;"#);
let f = parse(&p);
assert_eq!(
f,
vec![
("T".into(), "WPA".into()),
("S".into(), nasty.into()),
("P".into(), pass.into()),
("H".into(), "true".into()),
]
);
}
#[test]
fn security_kinds_and_hidden_flag() {
assert_eq!(wifi_payload("Cafe", "secret", WifiSecurity::Wep, false), "WIFI:T:WEP;S:Cafe;P:secret;H:false;;");
// An open network has no password field.
assert_eq!(wifi_payload("Open", "ignored", WifiSecurity::None, false), "WIFI:T:nopass;S:Open;H:false;;");
assert_eq!(WifiSecurity::parse("WPA"), WifiSecurity::Wpa);
assert_eq!(WifiSecurity::parse("nopass"), WifiSecurity::None);
assert_eq!(WifiSecurity::parse("WEP"), WifiSecurity::Wep);
assert_eq!(WifiSecurity::parse("anything else"), WifiSecurity::Wpa);
}
#[test]
fn unicode_ssid_is_kept() {
let p = wifi_payload("Žluťoučký kůň 📶", "heslo", WifiSecurity::Wpa, false);
assert_eq!(parse(&p)[1].1, "Žluťoučký kůň 📶");
}
#[test]
fn secret_payload_is_the_value_itself() {
assert_eq!(secret_payload("sk-test;with:specials"), "sk-test;with:specials");
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "custos-share"
description = "Custos private share links: the secret encrypted in the sender's app, the key in the link fragment"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
argon2.workspace = true
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
rand.workspace = true
zeroize.workspace = true
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
thiserror.workspace = true
+296
View File
@@ -0,0 +1,296 @@
//! Private share links (docs/SHARE.md): a secret encrypted in the sender's app with a random key that
//! travels only in the link's fragment, optionally combined with a password told separately. The share
//! server stores the blob and never sees a key.
use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::aead::{Aead, KeyInit, Payload as AeadPayload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use custos_vault::{Item, SecretString};
use data_encoding::BASE64URL_NOPAD;
use hkdf::Hkdf;
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::fmt;
use zeroize::{Zeroize, Zeroizing};
pub use custos_vault::Field;
const MAGIC: &[u8; 4] = b"CSH1";
const FLAG_PASSWORD: u8 = 0x01;
const KEY_LEN: usize = 32;
const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 24;
const TAG_LEN: usize = 16;
const KDF_LEN: usize = 12;
const INFO: &[u8] = b"custos-share v1";
/// The largest blob a share may be (the server enforces the same limit).
pub const MAX_BLOB: usize = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ShareError {
#[error("this is not a Custos share")]
Malformed,
#[error("the link is incomplete: the part after # is missing or damaged")]
BadLink,
#[error("this share needs a password")]
PasswordRequired,
#[error("the share's password settings are not supported")]
UnsupportedKdf,
#[error("wrong password, or the link or the share is damaged; nothing was decrypted")]
DecryptFailed,
#[error("the secret is too large to share (at most 64 KB)")]
TooLarge,
}
/// Argon2id parameters for a password share.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShareKdf {
pub m_cost_kib: u32,
pub t_cost: u32,
pub p_cost: u32,
}
impl ShareKdf {
/// 19 MiB, 2 passes, 1 lane: OWASP's Argon2id minimum, about a second in a phone browser.
pub const DEFAULT: ShareKdf = ShareKdf { m_cost_kib: 19_456, t_cost: 2, p_cost: 1 };
fn check(&self) -> Result<(), ShareError> {
let ok = (8 * 1024..=256 * 1024).contains(&self.m_cost_kib)
&& (1..=16).contains(&self.t_cost)
&& (1..=4).contains(&self.p_cost);
if ok { Ok(()) } else { Err(ShareError::UnsupportedKdf) }
}
}
/// What a share carries: a title and the fields to show, with secret ones hidden until revealed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Payload {
pub title: String,
/// The item type (`web-login`, `wifi`, …), only for the recipient page's label.
pub kind: Option<String>,
pub fields: Vec<Field>,
pub notes: Option<SecretString>,
}
/// Fields never put into a share.
const NEVER_SHARED: [&str; 4] = ["totp", "autotype-match", "autotype-sequence", "domi-ref"];
impl Payload {
/// The item's non-empty fields and notes, without its TOTP seed (that would hand over the second
/// factor too) and its auto-type settings.
pub fn from_item(item: &Item) -> Payload {
let kind = serde_json::to_value(item.kind).ok().and_then(|v| v.as_str().map(str::to_owned));
Payload {
title: item.title.clone(),
kind,
fields: item
.fields
.iter()
.filter(|f| !f.value.is_empty() && !NEVER_SHARED.contains(&f.name.as_str()))
.cloned()
.collect(),
notes: (!item.notes.is_empty()).then(|| item.notes.clone()),
}
}
}
#[derive(Serialize)]
struct WireOut<'a> {
v: u32,
title: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<&'a str>,
fields: &'a [Field],
#[serde(skip_serializing_if = "Option::is_none")]
notes: Option<&'a SecretString>,
}
#[derive(Deserialize)]
struct WireIn {
v: u32,
title: String,
#[serde(default)]
kind: Option<String>,
#[serde(default)]
fields: Vec<Field>,
#[serde(default)]
notes: Option<SecretString>,
}
/// A sealed share: the blob to upload and the link fragment (`k=…` or `k=…&p=1`) to put after `#`.
pub struct Sealed {
pub blob: Vec<u8>,
pub fragment: String,
}
impl Sealed {
pub fn needs_password(&self) -> bool {
fragment_needs_password(&self.fragment)
}
/// `https://host/s/<id>#<fragment>`.
pub fn link(&self, base_url: &str, id: &str) -> String {
format!("{}/s/{id}#{}", base_url.trim_end_matches('/'), self.fragment)
}
}
impl fmt::Debug for Sealed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sealed").field("blob_len", &self.blob.len()).field("fragment", &"[redacted]").finish()
}
}
impl Drop for Sealed {
fn drop(&mut self) {
self.fragment.zeroize();
}
}
/// Whether a link fragment says the recipient needs a password (only a hint for the page; the blob decides).
pub fn fragment_needs_password(fragment: &str) -> bool {
fragment.trim_start_matches('#').split('&').any(|p| p == "p=1")
}
fn rng() -> UnwrapErr<SysRng> {
UnwrapErr(SysRng)
}
fn link_key(fragment: &str) -> Result<Zeroizing<[u8; KEY_LEN]>, ShareError> {
let k =
fragment.trim_start_matches('#').split('&').find_map(|p| p.strip_prefix("k=")).ok_or(ShareError::BadLink)?;
let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(k.as_bytes()).map_err(|_| ShareError::BadLink)?);
let mut key = Zeroizing::new([0u8; KEY_LEN]);
if bytes.len() != KEY_LEN {
return Err(ShareError::BadLink);
}
key.copy_from_slice(&bytes);
Ok(key)
}
fn message_key(
link: &[u8; KEY_LEN],
password: Option<(&SecretString, ShareKdf, &[u8])>,
) -> Result<Zeroizing<[u8; KEY_LEN]>, ShareError> {
let Some((pw, kdf, salt)) = password else {
return Ok(Zeroizing::new(*link));
};
kdf.check()?;
let params =
Params::new(kdf.m_cost_kib, kdf.t_cost, kdf.p_cost, Some(KEY_LEN)).map_err(|_| ShareError::UnsupportedKdf)?;
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
ikm[..KEY_LEN].copy_from_slice(link);
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password_into(pw.expose().as_bytes(), salt, &mut ikm[KEY_LEN..])
.map_err(|_| ShareError::UnsupportedKdf)?;
let mut key = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), ikm.as_ref()).expand(INFO, key.as_mut()).map_err(|_| ShareError::UnsupportedKdf)?;
Ok(key)
}
fn cipher(key: &[u8; KEY_LEN]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
/// Seals `payload` with a fresh link key and, if given, a password (default KDF).
pub fn seal(payload: &Payload, password: Option<&SecretString>) -> Result<Sealed, ShareError> {
seal_with_kdf(payload, password, ShareKdf::DEFAULT)
}
pub fn seal_with_kdf(payload: &Payload, password: Option<&SecretString>, kdf: ShareKdf) -> Result<Sealed, ShareError> {
let wire = WireOut {
v: 1,
title: &payload.title,
kind: payload.kind.as_deref(),
fields: &payload.fields,
notes: payload.notes.as_ref(),
};
let plaintext = Zeroizing::new(serde_json::to_vec(&wire).map_err(|_| ShareError::Malformed)?);
let overhead = 5 + KDF_LEN + SALT_LEN + NONCE_LEN + TAG_LEN;
if plaintext.len() + overhead > MAX_BLOB {
return Err(ShareError::TooLarge);
}
let mut link = Zeroizing::new([0u8; KEY_LEN]);
rng().fill_bytes(link.as_mut());
let mut blob = Vec::with_capacity(plaintext.len() + overhead);
blob.extend_from_slice(MAGIC);
let mut salt = [0u8; SALT_LEN];
if password.is_some() {
kdf.check()?;
rng().fill_bytes(&mut salt);
blob.push(FLAG_PASSWORD);
for v in [kdf.m_cost_kib, kdf.t_cost, kdf.p_cost] {
blob.extend_from_slice(&v.to_le_bytes());
}
blob.extend_from_slice(&salt);
} else {
blob.push(0);
}
let mut nonce = [0u8; NONCE_LEN];
rng().fill_bytes(&mut nonce);
blob.extend_from_slice(&nonce);
let key = message_key(&link, password.map(|p| (p, kdf, &salt[..])))?;
let ct = cipher(&key)
.encrypt(
&XNonce::try_from(&nonce[..]).map_err(|_| ShareError::Malformed)?,
AeadPayload { msg: &plaintext, aad: &blob },
)
.map_err(|_| ShareError::Malformed)?;
blob.extend_from_slice(&ct);
let mut fragment = format!("k={}", BASE64URL_NOPAD.encode(link.as_ref()));
if password.is_some() {
fragment.push_str("&p=1");
}
Ok(Sealed { blob, fragment })
}
/// Opens a blob with the link fragment (with or without its leading `#`) and the password, if the
/// share has one. Any change to the blob, a wrong key or a wrong password gives `DecryptFailed`.
pub fn open(blob: &[u8], fragment: &str, password: Option<&SecretString>) -> Result<Payload, ShareError> {
if blob.len() > MAX_BLOB || blob.len() < 5 || &blob[..4] != MAGIC || blob[4] & !FLAG_PASSWORD != 0 {
return Err(ShareError::Malformed);
}
let has_password = blob[4] & FLAG_PASSWORD != 0;
let mut at = 5;
let mut kdf = ShareKdf::DEFAULT;
let mut salt: &[u8] = &[];
if has_password {
if blob.len() < at + KDF_LEN + SALT_LEN {
return Err(ShareError::Malformed);
}
let u = |i: usize| u32::from_le_bytes(blob[at + i..at + i + 4].try_into().unwrap());
kdf = ShareKdf { m_cost_kib: u(0), t_cost: u(4), p_cost: u(8) };
at += KDF_LEN;
salt = &blob[at..at + SALT_LEN];
at += SALT_LEN;
}
if blob.len() < at + NONCE_LEN + TAG_LEN {
return Err(ShareError::Malformed);
}
let (header, ct) = blob.split_at(at + NONCE_LEN);
let nonce = &header[at..];
let link = link_key(fragment)?;
let pw = match (has_password, password) {
(true, None) => return Err(ShareError::PasswordRequired),
(true, Some(p)) => Some((p, kdf, salt)),
(false, _) => None,
};
let key = message_key(&link, pw)?;
let plaintext = Zeroizing::new(
cipher(&key)
.decrypt(&XNonce::try_from(nonce).map_err(|_| ShareError::Malformed)?, AeadPayload { msg: ct, aad: header })
.map_err(|_| ShareError::DecryptFailed)?,
);
let w: WireIn = serde_json::from_slice(&plaintext).map_err(|_| ShareError::Malformed)?;
if w.v != 1 {
return Err(ShareError::Malformed);
}
Ok(Payload { title: w.title, kind: w.kind, fields: w.fields, notes: w.notes })
}
+163
View File
@@ -0,0 +1,163 @@
//! The mandatory share tests (Day 2, tests 5 and 6) and the format checks from docs/SHARE.md.
use custos_share::{Field, Payload, ShareError, ShareKdf, open, seal, seal_with_kdf};
use custos_vault::{Item, ItemType, SecretString};
/// Fast parameters for tests; the format and the code path are the same as the default's.
const TEST_KDF: ShareKdf = ShareKdf { m_cost_kib: 8 * 1024, t_cost: 1, p_cost: 1 };
fn payload() -> Payload {
Payload {
title: "Router".into(),
kind: Some("wifi".into()),
fields: vec![Field::text("ssid", "Home"), Field::secret("password", "correct-horse-ž!")],
notes: None,
}
}
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
#[test]
fn round_trip_without_password() {
let s = seal(&payload(), None).unwrap();
assert!(s.fragment.starts_with("k=") && s.fragment.len() == 45, "{}", s.fragment);
assert!(!s.needs_password());
let got = open(&s.blob, &s.fragment, None).unwrap();
assert_eq!(got, payload());
}
#[test]
fn tamper_any_byte_or_wrong_key_fails_with_a_clear_error() {
let s = seal(&payload(), None).unwrap();
for i in 0..s.blob.len() {
let mut bad = s.blob.clone();
bad[i] ^= 0x01;
let e = open(&bad, &s.fragment, None).unwrap_err();
// Flipping the password flag on asks for a password; everything else fails to decrypt or parse.
assert!(
matches!(e, ShareError::DecryptFailed | ShareError::Malformed | ShareError::PasswordRequired),
"byte {i}: {e:?}"
);
}
// A different, well-formed key.
let other = seal(&payload(), None).unwrap();
assert_eq!(open(&s.blob, &other.fragment, None).unwrap_err(), ShareError::DecryptFailed);
// Truncated or extended.
assert!(open(&s.blob[..s.blob.len() - 1], &s.fragment, None).is_err());
let mut longer = s.blob.clone();
longer.push(0);
assert_eq!(open(&longer, &s.fragment, None).unwrap_err(), ShareError::DecryptFailed);
// The message is plain and never contains the secret.
let msg = ShareError::DecryptFailed.to_string();
assert!(msg.contains("damaged") && !msg.contains("correct-horse"), "{msg}");
}
#[test]
fn password_share_wrong_password_fails_right_one_works() {
let s = seal_with_kdf(&payload(), Some(&pw("tell-them-by-phone")), TEST_KDF).unwrap();
assert!(s.fragment.ends_with("&p=1") && s.needs_password());
assert_eq!(open(&s.blob, &s.fragment, None).unwrap_err(), ShareError::PasswordRequired);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("tell-them-by-phone!"))).unwrap_err(), ShareError::DecryptFailed);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw(""))).unwrap_err(), ShareError::DecryptFailed);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("tell-them-by-phone"))).unwrap(), payload());
// The link alone is not enough even with the hint removed: the blob decides.
let bare = s.fragment.trim_end_matches("&p=1");
assert_eq!(open(&s.blob, bare, None).unwrap_err(), ShareError::PasswordRequired);
// The password alone is not enough: a different link key with the right password fails.
let other = seal(&payload(), None).unwrap();
let wrong_key = format!("{}&p=1", other.fragment);
assert_eq!(open(&s.blob, &wrong_key, Some(&pw("tell-them-by-phone"))).unwrap_err(), ShareError::DecryptFailed);
}
#[test]
fn default_kdf_is_the_documented_one_and_works() {
assert_eq!(ShareKdf::DEFAULT, ShareKdf { m_cost_kib: 19_456, t_cost: 2, p_cost: 1 });
let s = seal(&payload(), Some(&pw("pw"))).unwrap();
assert_eq!(&s.blob[5..17], [0x00, 0x4c, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0]);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("pw"))).unwrap(), payload());
}
#[test]
fn layout_matches_docs() {
let s = seal(&payload(), None).unwrap();
assert_eq!(&s.blob[..4], b"CSH1");
assert_eq!(s.blob[4], 0);
let p = seal_with_kdf(&payload(), Some(&pw("x")), TEST_KDF).unwrap();
assert_eq!(p.blob[4], 1);
// magic + flags + kdf (12) + salt (16) + nonce (24) + tag (16) + plaintext
assert_eq!(p.blob.len(), s.blob.len() + 28);
// Unknown flags are rejected before any crypto.
let mut bad = s.blob.clone();
bad[4] = 0x02;
assert_eq!(open(&bad, &s.fragment, None).unwrap_err(), ShareError::Malformed);
}
#[test]
fn kdf_limits_are_checked_before_argon2() {
let s = seal_with_kdf(&payload(), Some(&pw("x")), TEST_KDF).unwrap();
for (offset, value) in [(5usize, 300 * 1024u32), (5, 1024), (9, 17), (9, 0), (13, 5), (13, 0)] {
let mut bad = s.blob.clone();
bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
assert_eq!(
open(&bad, &s.fragment, Some(&pw("x"))).unwrap_err(),
ShareError::UnsupportedKdf,
"{offset}={value}"
);
}
}
#[test]
fn bad_links_are_rejected() {
let s = seal(&payload(), None).unwrap();
for frag in
["", "k=", "k=abc", "x=1", &s.fragment[..44], &format!("{}A", s.fragment), &s.fragment.replace('k', "K")]
{
assert_eq!(open(&s.blob, frag, None).unwrap_err(), ShareError::BadLink, "{frag:?}");
}
// A leading '#' (location.hash) is accepted.
assert!(open(&s.blob, &format!("#{}", s.fragment), None).is_ok());
}
#[test]
fn size_limit() {
let big = Payload { notes: Some(SecretString::new("x".repeat(70_000))), ..payload() };
assert_eq!(seal(&big, None).unwrap_err(), ShareError::TooLarge);
let mut blob = seal(&payload(), None).unwrap().blob.clone();
blob.resize(64 * 1024 + 1, 0);
assert_eq!(open(&blob, "k=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", None).unwrap_err(), ShareError::Malformed);
}
#[test]
fn every_link_key_and_nonce_is_fresh() {
let a = seal(&payload(), None).unwrap();
let b = seal(&payload(), None).unwrap();
assert_ne!(a.fragment, b.fragment);
assert_ne!(a.blob[5..29], b.blob[5..29]);
}
#[test]
fn payload_from_item_leaves_out_empty_fields_totp_and_autotype() {
let mut item = Item::new(ItemType::WebLogin, "GitHub", 0);
item.set("username", "mark", 0);
item.set("password", "hunter2", 0);
item.set("totp", "JBSWY3DPEHPK3PXP", 0);
item.set("autotype-match", "exe:firefox.exe", 0);
item.notes = "recovery codes in the safe".into();
let p = Payload::from_item(&item);
assert_eq!(p.title, "GitHub");
assert_eq!(p.kind.as_deref(), Some("web-login"));
let names: Vec<_> = p.fields.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["username", "password"]);
assert!(p.fields[1].secret && !p.fields[0].secret);
assert_eq!(p.notes.as_ref().map(|n| n.expose()), Some("recovery codes in the safe"));
}
#[test]
fn secrets_are_redacted_in_debug() {
let s = seal(&payload(), Some(&pw("pw"))).unwrap();
let out = format!("{:?} {:?}", s, payload());
assert!(!out.contains("correct-horse") && !out.contains(&s.fragment[2..]), "{out}");
assert!(out.contains("[redacted]"), "{out}");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-totp"
description = "Custos TOTP (RFC 6238) and HOTP (RFC 4226), otpauth:// URIs"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
hmac.workspace = true
sha1.workspace = true
sha2.workspace = true
data-encoding.workspace = true
percent-encoding.workspace = true
zeroize.workspace = true
+221
View File
@@ -0,0 +1,221 @@
//! TOTP (RFC 6238) and HOTP (RFC 4226) on RustCrypto's HMAC, and `otpauth://` URIs.
//!
//! ```
//! use custos_totp::Totp;
//! let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub")?;
//! assert_eq!(t.code_at(1_700_000_000).len(), 6);
//! # Ok::<(), custos_totp::TotpError>(())
//! ```
use data_encoding::BASE32_NOPAD;
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use std::fmt;
use zeroize::Zeroizing;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Algorithm {
Sha1,
Sha256,
Sha512,
}
impl Algorithm {
fn name(self) -> &'static str {
match self {
Algorithm::Sha1 => "SHA1",
Algorithm::Sha256 => "SHA256",
Algorithm::Sha512 => "SHA512",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotpError(String);
impl fmt::Display for TotpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for TotpError {}
fn err<T>(msg: &str) -> Result<T, TotpError> {
Err(TotpError(msg.into()))
}
fn mac(alg: Algorithm, key: &[u8], msg: &[u8]) -> Vec<u8> {
// HMAC accepts keys of any length; `new_from_slice` cannot fail for it.
match alg {
Algorithm::Sha1 => {
let mut m = <Hmac<sha1::Sha1> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha256 => {
let mut m = <Hmac<sha2::Sha256> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha512 => {
let mut m = <Hmac<sha2::Sha512> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
}
}
/// RFC 4226: HMAC of the 8-byte big-endian counter, dynamic truncation, `digits` decimal digits.
pub fn hotp(secret: &[u8], counter: u64, digits: u32, alg: Algorithm) -> String {
let h = mac(alg, secret, &counter.to_be_bytes());
let off = (h[h.len() - 1] & 0x0f) as usize;
let bin = u32::from_be_bytes([h[off] & 0x7f, h[off + 1], h[off + 2], h[off + 3]]);
format!("{:0width$}", bin % 10u32.pow(digits), width = digits as usize)
}
/// A TOTP generator. The secret is wiped on drop and never printed.
#[derive(Clone)]
pub struct Totp {
secret: Zeroizing<Vec<u8>>,
algorithm: Algorithm,
digits: u32,
period: u64,
issuer: Option<String>,
account: Option<String>,
}
impl fmt::Debug for Totp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Totp")
.field("secret", &"[redacted]")
.field("algorithm", &self.algorithm)
.field("digits", &self.digits)
.field("period", &self.period)
.field("issuer", &self.issuer)
.finish_non_exhaustive()
}
}
fn decode_base32(s: &str) -> Result<Zeroizing<Vec<u8>>, TotpError> {
let clean: Zeroizing<String> = Zeroizing::new(
s.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '=').collect::<String>().to_uppercase(),
);
if clean.is_empty() {
return err("the 2FA secret is empty");
}
BASE32_NOPAD
.decode(clean.as_bytes())
.map(Zeroizing::new)
.map_err(|_| TotpError("the 2FA secret is not valid base32".into()))
}
impl Totp {
/// `digits` 6..=8, `period` in seconds (at least 1).
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, period: u64) -> Result<Totp, TotpError> {
if !(6..=8).contains(&digits) {
return err("a 2FA code has 6 to 8 digits");
}
if period == 0 {
return err("the 2FA period must be at least one second");
}
if secret.is_empty() {
return err("the 2FA secret is empty");
}
Ok(Totp { secret: Zeroizing::new(secret), algorithm, digits, period, issuer: None, account: None })
}
/// An `otpauth://totp/…` URI, or a bare base32 secret (spaces, lower case and `=` are fine).
pub fn parse(input: &str) -> Result<Totp, TotpError> {
let input = input.trim();
let Some(rest) = input.strip_prefix("otpauth://") else {
return Totp::new(decode_base32(input)?.to_vec(), Algorithm::Sha1, 6, 30);
};
let Some(rest) = rest.strip_prefix("totp/") else {
return err("only time-based codes (otpauth://totp) are supported");
};
let (label, query) = rest.split_once('?').unwrap_or((rest, ""));
let label = percent_decode_str(label).decode_utf8_lossy().into_owned();
let (mut issuer, account) = match label.split_once(':') {
Some((i, a)) => (Some(i.trim().to_owned()), Some(a.trim().to_owned())),
None if label.is_empty() => (None, None),
None => (None, Some(label.trim().to_owned())),
};
let (mut secret, mut alg, mut digits, mut period) = (None, Algorithm::Sha1, 6u32, 30u64);
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let v = Zeroizing::new(percent_decode_str(v).decode_utf8_lossy().into_owned());
match k.to_ascii_lowercase().as_str() {
"secret" => secret = Some(decode_base32(&v)?),
"issuer" => issuer = Some(v.to_string()),
"algorithm" => {
alg = match v.to_ascii_uppercase().as_str() {
"SHA1" => Algorithm::Sha1,
"SHA256" => Algorithm::Sha256,
"SHA512" => Algorithm::Sha512,
_ => return err("unsupported 2FA algorithm (use SHA1, SHA256 or SHA512)"),
}
}
"digits" => digits = v.parse().map_err(|_| TotpError("digits is not a number".into()))?,
"period" => period = v.parse().map_err(|_| TotpError("period is not a number".into()))?,
_ => {}
}
}
let secret = secret.ok_or_else(|| TotpError("the otpauth URI has no secret".into()))?;
let mut t = Totp::new(secret.to_vec(), alg, digits, period)?;
t.issuer = issuer.filter(|s| !s.is_empty());
t.account = account.filter(|s| !s.is_empty());
Ok(t)
}
/// The code for Unix time `unix_secs`.
pub fn code_at(&self, unix_secs: u64) -> String {
hotp(&self.secret, unix_secs / self.period, self.digits, self.algorithm)
}
/// Seconds until the code at `unix_secs` changes (1..=period).
pub fn seconds_left(&self, unix_secs: u64) -> u64 {
self.period - unix_secs % self.period
}
pub fn to_uri(&self) -> String {
let enc = |s: &str| utf8_percent_encode(s, NON_ALPHANUMERIC).to_string();
let label = match (&self.issuer, &self.account) {
(Some(i), Some(a)) => format!("{}:{}", enc(i), enc(a)),
(None, Some(a)) => enc(a),
(Some(i), None) => enc(i),
(None, None) => String::new(),
};
let mut uri = format!(
"otpauth://totp/{label}?secret={}&algorithm={}&digits={}&period={}",
BASE32_NOPAD.encode(&self.secret),
self.algorithm.name(),
self.digits,
self.period
);
if let Some(i) = &self.issuer {
uri.push_str(&format!("&issuer={}", enc(i)));
}
uri
}
pub fn issuer(&self) -> Option<&str> {
self.issuer.as_deref()
}
pub fn account(&self) -> Option<&str> {
self.account.as_deref()
}
pub fn digits(&self) -> u32 {
self.digits
}
pub fn period(&self) -> u64 {
self.period
}
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
}
+93
View File
@@ -0,0 +1,93 @@
//! RFC 6238 Appendix B and RFC 4226 Appendix D test vectors, exactly as published, plus otpauth parsing.
use custos_totp::{Algorithm, Totp, hotp};
const SEED_SHA1: &[u8] = b"12345678901234567890";
const SEED_SHA256: &[u8] = b"12345678901234567890123456789012";
const SEED_SHA512: &[u8] = b"1234567890123456789012345678901234567890123456789012345678901234";
#[test]
fn rfc6238_appendix_b() {
// Time (s), SHA1, SHA256, SHA512 — 8 digits, period 30, T0 = 0.
let table: [(u64, &str, &str, &str); 6] = [
(59, "94287082", "46119246", "90693936"),
(1111111109, "07081804", "68084774", "25091201"),
(1111111111, "14050471", "67062674", "99943326"),
(1234567890, "89005924", "91819424", "93441116"),
(2000000000, "69279037", "90698825", "38618901"),
(20000000000, "65353130", "77737706", "47863826"),
];
for (t, sha1, sha256, sha512) in table {
for (seed, alg, want) in [
(SEED_SHA1, Algorithm::Sha1, sha1),
(SEED_SHA256, Algorithm::Sha256, sha256),
(SEED_SHA512, Algorithm::Sha512, sha512),
] {
let totp = Totp::new(seed.to_vec(), alg, 8, 30).unwrap();
assert_eq!(totp.code_at(t), want, "T={t} {alg:?}");
}
}
}
#[test]
fn rfc4226_appendix_d() {
let want = ["755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489"];
for (counter, code) in want.iter().enumerate() {
assert_eq!(hotp(SEED_SHA1, counter as u64, 6, Algorithm::Sha1), *code, "counter {counter}");
}
}
#[test]
fn otpauth_uri_and_base32() {
// "12345678901234567890" in base32.
let b32 = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
let t = Totp::parse(&format!(
"otpauth://totp/Example%20Co:alice%40example.com?secret={b32}&issuer=Example%20Co&algorithm=SHA1&digits=8&period=30"
))
.unwrap();
assert_eq!(t.code_at(59), "94287082");
assert_eq!(t.issuer(), Some("Example Co"));
assert_eq!(t.account(), Some("alice@example.com"));
assert_eq!((t.digits(), t.period(), t.algorithm()), (8, 30, Algorithm::Sha1));
// Defaults: SHA1, 6 digits, 30 s. A bare secret (lower case, spaces, padding) works too.
let bare = Totp::parse("gezd gnbv gy3t qojq gezd gnbv gy3t qojq").unwrap();
assert_eq!(bare.code_at(59), "287082");
assert_eq!((bare.digits(), bare.period()), (6, 30));
assert_eq!(Totp::parse(&format!("{b32}====")).unwrap().code_at(59), "287082");
let sha256 = Totp::parse(
"otpauth://totp/x?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&algorithm=SHA256&digits=8",
)
.unwrap();
assert_eq!(sha256.code_at(59), "46119246");
for bad in [
"otpauth://hotp/x?secret=GEZDGNBV&counter=1",
"otpauth://totp/x?digits=6",
"otpauth://totp/x?secret=not*base32",
"otpauth://totp/x?secret=GEZDGNBV&digits=9",
"otpauth://totp/x?secret=GEZDGNBV&period=0",
"otpauth://totp/x?secret=GEZDGNBV&algorithm=MD5",
"",
] {
assert!(Totp::parse(bad).is_err(), "{bad} was accepted");
}
}
#[test]
fn round_trip_through_uri_and_countdown() {
let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub").unwrap();
let back = Totp::parse(&t.to_uri()).unwrap();
assert_eq!(back.code_at(1_700_000_000), t.code_at(1_700_000_000));
assert_eq!(back.issuer(), Some("GitHub"));
assert_eq!(t.seconds_left(1_700_000_000), 30 - 1_700_000_000 % 30);
assert_eq!(t.seconds_left(60), 30);
}
#[test]
fn secret_is_redacted_in_debug() {
let t = Totp::parse("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP").unwrap();
let out = format!("{t:?}");
assert!(!out.contains("JBSWY3DPEHPK3PXP") && !out.contains("72, 101") && out.contains("[redacted]"), "{out}");
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "custos-vault"
description = "Custos vault file format: Argon2id + XChaCha20-Poly1305, atomic save, item model"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
argon2.workspace = true
chacha20poly1305.workspace = true
zeroize.workspace = true
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
hkdf.workspace = true
sha2.workspace = true
[dev-dependencies]
tempfile = "3"
@@ -0,0 +1,19 @@
//! How long one unlock takes with given Argon2id parameters (default: `KdfParams::DEFAULT`):
//! `cargo run --release -p custos-vault --example kdf_timing [m_cost_kib t_cost]`
use custos_vault::{KdfParams, SecretString, Vault};
use std::time::Instant;
fn main() {
let args: Vec<u32> = std::env::args().skip(1).filter_map(|a| a.parse().ok()).collect();
let kdf = match args[..] {
[m, t] => KdfParams { m_cost_kib: m, t_cost: t, p_cost: 1 },
_ => KdfParams::DEFAULT,
};
let pw = SecretString::from("timing only");
let bytes = Vault::create(&pw, kdf).unwrap().to_bytes().unwrap();
for _ in 0..3 {
let t = Instant::now();
Vault::open(&bytes, &pw).unwrap();
println!("{kdf:?}: unlock in {:?}", t.elapsed());
}
}
+61
View File
@@ -0,0 +1,61 @@
//! The only module that calls the cryptographic crates.
use crate::{Error, KdfParams};
use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use zeroize::Zeroizing;
pub const KEY_LEN: usize = 32;
pub const NONCE_LEN: usize = 24;
pub const TAG_LEN: usize = 16;
/// Fills `buf` from the OS CSPRNG. Panics only if the OS has no randomness to give, where going on
/// without it would be worse.
pub fn fill_random(buf: &mut [u8]) {
UnwrapErr(SysRng).fill_bytes(buf);
}
pub fn random_key() -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
fill_random(k.as_mut());
k
}
pub fn random_nonce() -> [u8; NONCE_LEN] {
let mut n = [0u8; NONCE_LEN];
fill_random(&mut n);
n
}
/// Argon2id(password, salt) → key-encryption key. The caller has already checked `p` against the limits.
pub fn derive_kek(password: &[u8], salt: &[u8], p: KdfParams) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
let params = Params::new(p.m_cost_kib, p.t_cost, p.p_cost, Some(KEY_LEN)).map_err(|_| Error::UnsupportedKdf)?;
let mut kek = Zeroizing::new([0u8; KEY_LEN]);
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password_into(password, salt, kek.as_mut())
.map_err(|_| Error::UnsupportedKdf)?;
Ok(kek)
}
fn cipher(key: &[u8; KEY_LEN]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
fn nonce(n: &[u8; NONCE_LEN]) -> XNonce {
XNonce::try_from(&n[..]).expect("24-byte nonce")
}
pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
cipher(key)
.encrypt(&nonce(n), Payload { msg: plaintext, aad })
.expect("encryption cannot fail for in-memory buffers")
}
/// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD.
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)
}
+45
View File
@@ -0,0 +1,45 @@
//! Device unlock (docs/FORMAT.md, "Device key wrap"): the vault key wrapped with a key derived from
//! material only this device can produce (the desktop app uses a Windows Hello signature). The blob is
//! kept on that device, never in the vault file.
use crate::Error;
use crate::crypto::{self, KEY_LEN, NONCE_LEN, TAG_LEN};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"CDW1";
const SALT_LEN: usize = 32;
const INFO: &[u8] = b"custos device wrap v1";
pub const BLOB_LEN: usize = 4 + SALT_LEN + NONCE_LEN + KEY_LEN + TAG_LEN;
fn kek(material: &[u8], salt: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), material).expand(INFO, k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
/// `CDW1 ‖ salt ‖ nonce ‖ XChaCha20-Poly1305(HKDF-SHA256(material, salt), vault key, aad = CDW1 ‖ salt ‖ nonce)`.
pub fn wrap(key: &[u8; KEY_LEN], material: &[u8]) -> Vec<u8> {
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let nonce = crypto::random_nonce();
let mut blob = Vec::with_capacity(BLOB_LEN);
blob.extend_from_slice(MAGIC);
blob.extend_from_slice(&salt);
blob.extend_from_slice(&nonce);
let sealed = crypto::seal(&kek(material, &salt), &nonce, key, &blob);
blob.extend_from_slice(&sealed);
blob
}
pub fn unwrap(blob: &[u8], material: &[u8]) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
if blob.len() != BLOB_LEN || &blob[..4] != MAGIC {
return Err(Error::DeviceKeyRejected);
}
let salt = &blob[4..4 + SALT_LEN];
let nonce: [u8; NONCE_LEN] = blob[4 + SALT_LEN..4 + SALT_LEN + NONCE_LEN].try_into().unwrap();
let head = 4 + SALT_LEN + NONCE_LEN;
let k = crypto::open(&kek(material, salt), &nonce, &blob[head..], &blob[..head]).ok_or(Error::DeviceKeyRejected)?;
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::DeviceKeyRejected)?))
}
+125
View File
@@ -0,0 +1,125 @@
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout").
use crate::crypto::{KEY_LEN, NONCE_LEN, TAG_LEN};
use crate::{Error, KdfParams};
pub const MAGIC: &[u8; 6] = b"CUSTOS";
pub const VERSION: u16 = 1;
pub const MAX_SLOTS: usize = 8;
pub const SLOT_PASSWORD: u8 = 1;
const KDF_ARGON2ID: u8 = 1;
pub const SALT_LEN: usize = 32;
/// kdf(1) m(4) t(4) p(4) salt(32) nonce(24): the part of a password slot that is its own AAD.
const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_LEN;
const PW_PAYLOAD_LEN: usize = PW_AAD_LEN + KEY_LEN + TAG_LEN;
/// One key slot as stored. Unknown kinds are kept and written back unchanged.
#[derive(Clone)]
pub struct RawSlot {
pub kind: u8,
pub payload: Vec<u8>,
}
pub struct PasswordSlot {
pub kdf: KdfParams,
pub salt: [u8; SALT_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl PasswordSlot {
/// The bytes the wrapped key is authenticated against: magic ‖ version ‖ kind ‖ payload before the key.
pub fn aad(&self) -> Vec<u8> {
let mut a = Vec::with_capacity(9 + PW_AAD_LEN);
a.extend_from_slice(MAGIC);
a.extend_from_slice(&VERSION.to_le_bytes());
a.push(SLOT_PASSWORD);
a.extend_from_slice(&self.payload()[..PW_AAD_LEN]);
a
}
pub fn payload(&self) -> Vec<u8> {
let mut p = Vec::with_capacity(PW_PAYLOAD_LEN);
p.push(KDF_ARGON2ID);
p.extend_from_slice(&self.kdf.m_cost_kib.to_le_bytes());
p.extend_from_slice(&self.kdf.t_cost.to_le_bytes());
p.extend_from_slice(&self.kdf.p_cost.to_le_bytes());
p.extend_from_slice(&self.salt);
p.extend_from_slice(&self.nonce);
p.extend_from_slice(&self.wrapped);
p
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
if payload.len() != PW_PAYLOAD_LEN {
return Err(Error::Malformed);
}
if payload[0] != KDF_ARGON2ID {
return Err(Error::UnsupportedKdf);
}
let u32_at = |i: usize| u32::from_le_bytes(payload[i..i + 4].try_into().unwrap());
let kdf = KdfParams { m_cost_kib: u32_at(1), t_cost: u32_at(5), p_cost: u32_at(9) };
kdf.check()?;
Ok(PasswordSlot {
kdf,
salt: payload[13..13 + SALT_LEN].try_into().unwrap(),
nonce: payload[13 + SALT_LEN..PW_AAD_LEN].try_into().unwrap(),
wrapped: payload[PW_AAD_LEN..].to_vec(),
})
}
pub fn raw(&self) -> RawSlot {
RawSlot { kind: SLOT_PASSWORD, payload: self.payload() }
}
}
pub struct Header {
pub slots: Vec<RawSlot>,
pub body_nonce: [u8; NONCE_LEN],
}
impl Header {
pub fn to_bytes(&self) -> Vec<u8> {
let mut h = Vec::new();
h.extend_from_slice(MAGIC);
h.extend_from_slice(&VERSION.to_le_bytes());
h.push(self.slots.len() as u8);
for s in &self.slots {
h.push(s.kind);
h.extend_from_slice(&(s.payload.len() as u16).to_le_bytes());
h.extend_from_slice(&s.payload);
}
h.extend_from_slice(&self.body_nonce);
h
}
/// Parses the header; returns it and its length (where the body starts).
pub fn parse(bytes: &[u8]) -> Result<(Header, usize), Error> {
if bytes.len() < 9 || &bytes[..6] != MAGIC {
return Err(Error::NotAVault);
}
let version = u16::from_le_bytes([bytes[6], bytes[7]]);
if version != VERSION {
return Err(Error::UnsupportedVersion(version));
}
let count = bytes[8] as usize;
if count == 0 || count > MAX_SLOTS {
return Err(Error::Malformed);
}
let mut at = 9;
let mut slots = Vec::with_capacity(count);
for _ in 0..count {
let head = bytes.get(at..at + 3).ok_or(Error::Malformed)?;
let len = u16::from_le_bytes([head[1], head[2]]) as usize;
let payload = bytes.get(at + 3..at + 3 + len).ok_or(Error::Malformed)?;
slots.push(RawSlot { kind: head[0], payload: payload.to_vec() });
at += 3 + len;
}
let body_nonce = bytes.get(at..at + NONCE_LEN).ok_or(Error::Malformed)?.try_into().unwrap();
at += NONCE_LEN;
if bytes.len() < at + TAG_LEN {
return Err(Error::Malformed);
}
Ok((Header { slots, body_nonce }, at))
}
}
+184
View File
@@ -0,0 +1,184 @@
//! Typed items and their templates (docs/FORMAT.md, "Item types and their fields").
use crate::secret::SecretString;
use serde::{Deserialize, Serialize};
use std::fmt;
/// Previous values kept per item, oldest dropped first.
pub const HISTORY_LIMIT: usize = 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ItemType {
WebLogin,
ApiCredential,
LocalApp,
Wifi,
SecureNote,
Card,
}
impl ItemType {
pub const ALL: [ItemType; 6] = [
ItemType::WebLogin,
ItemType::ApiCredential,
ItemType::LocalApp,
ItemType::Wifi,
ItemType::SecureNote,
ItemType::Card,
];
pub fn label(self) -> &'static str {
match self {
ItemType::WebLogin => "Web login",
ItemType::ApiCredential => "API credential",
ItemType::LocalApp => "Local app credential",
ItemType::Wifi => "Wi-Fi",
ItemType::SecureNote => "Secure note",
ItemType::Card => "Card",
}
}
/// The template: field names in display order, and whether each is secret.
pub fn template(self) -> &'static [(&'static str, bool)] {
match self {
ItemType::WebLogin => &[
("username", false),
("password", true),
("url", false),
("totp", true),
("autotype-match", false),
("autotype-sequence", false),
],
ItemType::ApiCredential => {
&[("service", false), ("key-id", false), ("secret", true), ("endpoint", false), ("expires", false)]
}
ItemType::LocalApp => &[("target", false), ("username", false), ("password", true)],
ItemType::Wifi => &[("ssid", false), ("password", true), ("security", false), ("hidden", false)],
ItemType::SecureNote => &[],
ItemType::Card => {
&[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)]
}
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
pub name: String,
pub value: SecretString,
#[serde(default)]
pub secret: bool,
}
impl Field {
pub fn text(name: &str, value: &str) -> Self {
Self { name: name.into(), value: value.into(), secret: false }
}
pub fn secret(name: &str, value: &str) -> Self {
Self { name: name.into(), value: value.into(), secret: true }
}
}
impl fmt::Debug for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Field").field("name", &self.name).field("secret", &self.secret).finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HistoryEntry {
pub field: String,
pub value: SecretString,
pub changed: i64,
}
impl fmt::Debug for HistoryEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HistoryEntry")
.field("field", &self.field)
.field("changed", &self.changed)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
pub id: String,
#[serde(rename = "type")]
pub kind: ItemType,
pub title: String,
#[serde(default)]
pub fields: Vec<Field>,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub notes: SecretString,
pub created: i64,
pub modified: i64,
#[serde(default)]
pub history: Vec<HistoryEntry>,
}
impl Item {
/// A new item with every template field present and empty. `now` is Unix milliseconds.
pub fn new(kind: ItemType, title: &str, now: i64) -> Self {
Item {
id: new_id(),
kind,
title: title.into(),
fields: kind
.template()
.iter()
.map(|&(name, secret)| Field { name: name.into(), value: SecretString::default(), secret })
.collect(),
tags: Vec::new(),
notes: SecretString::default(),
created: now,
modified: now,
history: Vec::new(),
}
}
/// The first field called `name`.
pub fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|f| f.name == name)
}
/// Sets the first field called `name` (adding it if missing, secret if the template says so).
/// A changed secret field keeps its previous non-empty value in `history`.
pub fn set(&mut self, name: &str, value: &str, now: i64) {
let template_secret = self.kind.template().iter().any(|&(n, s)| n == name && s);
match self.fields.iter_mut().find(|f| f.name == name) {
Some(f) if f.value.expose() == value => return,
Some(f) => {
let old = std::mem::replace(&mut f.value, value.into());
if f.secret && !old.is_empty() {
self.history.push(HistoryEntry { field: name.into(), value: old, changed: now });
let excess = self.history.len().saturating_sub(HISTORY_LIMIT);
self.history.drain(..excess);
}
}
None => self.fields.push(Field { name: name.into(), value: value.into(), secret: template_secret }),
}
self.modified = now;
}
/// Appends a field, e.g. a second `url`.
pub fn add_field(&mut self, field: Field) {
self.fields.push(field);
}
}
/// 128 random bits as 32 hex digits.
pub fn new_id() -> String {
let mut b = [0u8; 16];
crate::crypto::fill_random(&mut b);
b.iter().map(|x| format!("{x:02x}")).collect()
}
/// Now, in Unix milliseconds.
pub fn now_ms() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
}
+249
View File
@@ -0,0 +1,249 @@
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md.
//!
//! ```
//! use custos_vault::{Item, ItemType, KdfParams, SecretString, Vault};
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
//! let mut vault = Vault::create(&password, kdf)?;
//! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms()));
//! let bytes = vault.to_bytes()?;
//! assert_eq!(Vault::open(&bytes, &password)?.items().len(), 1);
//! # Ok::<(), custos_vault::Error>(())
//! ```
mod crypto;
mod device;
mod format;
mod item;
mod save;
mod secret;
pub use item::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
pub use secret::SecretString;
use crypto::KEY_LEN;
use format::{Header, PasswordSlot, RawSlot, SALT_LEN, SLOT_PASSWORD};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::Path;
use zeroize::Zeroizing;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("not a Custos vault file")]
NotAVault,
#[error("vault format version {0} is not supported by this version of Custos")]
UnsupportedVersion(u16),
#[error("the vault file is malformed")]
Malformed,
#[error("the vault's key-derivation parameters are not supported")]
UnsupportedKdf,
#[error("wrong password")]
WrongPassword,
#[error("the vault file was changed or damaged after it was written")]
Corrupted,
#[error("this device's unlock key no longer opens the vault; use the master password")]
DeviceKeyRejected,
#[error("{0}")]
Io(#[from] std::io::Error),
}
/// Argon2id parameters, stored per vault (docs/FORMAT.md, "Limits").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KdfParams {
pub m_cost_kib: u32,
pub t_cost: u32,
pub p_cost: u32,
}
impl KdfParams {
/// 64 MiB, 20 passes, 1 lane: about 0.75 s per unlock on the dev machine (2026, release build;
/// measure with `cargo run --release -p custos-vault --example kdf_timing`).
pub const DEFAULT: KdfParams = KdfParams { m_cost_kib: 65_536, t_cost: 20, p_cost: 1 };
pub const MAX_M_COST_KIB: u32 = 2 * 1024 * 1024;
pub const MAX_T_COST: u32 = 64;
pub const MAX_P_COST: u32 = 16;
/// Refuses parameters outside the limits before any Argon2 work.
pub fn check(&self) -> Result<(), Error> {
let ok = (1..=Self::MAX_P_COST).contains(&self.p_cost)
&& (1..=Self::MAX_T_COST).contains(&self.t_cost)
&& (8 * self.p_cost..=Self::MAX_M_COST_KIB).contains(&self.m_cost_kib);
if ok { Ok(()) } else { Err(Error::UnsupportedKdf) }
}
}
impl Default for KdfParams {
fn default() -> Self {
Self::DEFAULT
}
}
const BODY_FORMAT: u32 = 1;
#[derive(Deserialize)]
struct Body {
format: u32,
items: Vec<Item>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
#[derive(Serialize)]
struct BodyRef<'a> {
format: u32,
items: &'a [Item],
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
pub struct Vault {
key: Zeroizing<[u8; KEY_LEN]>,
slots: Vec<RawSlot>,
items: Vec<Item>,
}
impl fmt::Debug for Vault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Vault").field("items", &self.items.len()).finish_non_exhaustive()
}
}
fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -> Result<PasswordSlot, Error> {
kdf.check()?;
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = PasswordSlot { kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, kdf)?;
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
Ok(slot)
}
impl Vault {
/// A new, empty 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, slots: vec![slot.raw()], items: Vec::new() })
}
pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> {
Vault::open(&std::fs::read(path)?, password)
}
/// Unlocks a vault. Returns no data at all unless both the key slot and the body authenticate.
pub fn open(bytes: &[u8], password: &SecretString) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
let pw_slots: Vec<PasswordSlot> = header
.slots
.iter()
.filter(|s| s.kind == SLOT_PASSWORD)
.map(|s| PasswordSlot::parse(&s.payload))
.collect::<Result<_, _>>()?;
if pw_slots.is_empty() {
return Err(Error::Malformed);
}
for slot in &pw_slots {
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?;
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
let key: Zeroizing<[u8; KEY_LEN]> =
Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?);
return Vault::open_body(bytes, header, body_at, key);
}
}
Err(Error::WrongPassword)
}
fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result<Vault, Error> {
let json =
crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?;
let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?;
if body.format != BODY_FORMAT {
return Err(Error::Corrupted);
}
Ok(Vault { key, slots: header.slots, items: body.items })
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
/// Windows Hello signature). Keep the blob on the device; see docs/FORMAT.md, "Device key wrap".
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
Ok(device::wrap(&self.key, material))
}
/// Unlocks with a device blob instead of the password. Fails with `DeviceKeyRejected` when the
/// material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
let key = device::unwrap(blob, material)?;
Vault::open_body(bytes, header, body_at, key)
}
/// The encrypted file contents, with a fresh body nonce.
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
let body_nonce = crypto::random_nonce();
let mut out = Header { slots: self.slots.clone(), body_nonce }.to_bytes();
let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len()));
let body = BodyRef { format: BODY_FORMAT, items: &self.items };
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);
out.extend_from_slice(&sealed);
Ok(out)
}
/// Encrypts and writes the vault atomically (see [`save_atomic`]).
pub fn save(&self, path: &Path) -> Result<(), Error> {
save_atomic(path, &self.to_bytes()?)
}
/// Wraps the same vault key with a new password (new salt and nonce). The items are untouched;
/// the old password stops working at the next save.
pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> {
let slot = password_slot(&self.key, new_password, kdf)?;
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
self.slots.insert(0, slot.raw());
Ok(())
}
/// Whether two unlocked vaults share a vault key (tests: a password change keeps the key).
#[doc(hidden)]
pub fn same_key_as(&self, other: &Vault) -> bool {
self.key[..] == other.key[..]
}
/// The KDF parameters of the first password slot.
pub fn kdf(&self) -> Option<KdfParams> {
self.slots
.iter()
.filter(|s| s.kind == SLOT_PASSWORD)
.find_map(|s| PasswordSlot::parse(&s.payload).ok())
.map(|s| s.kdf)
}
pub fn items(&self) -> &[Item] {
&self.items
}
pub fn item(&self, id: &str) -> Option<&Item> {
self.items.iter().find(|i| i.id == id)
}
pub fn item_mut(&mut self, id: &str) -> Option<&mut Item> {
self.items.iter_mut().find(|i| i.id == id)
}
pub fn add(&mut self, item: Item) {
self.items.push(item);
}
/// Replaces the item with the same id, or adds it.
pub fn put(&mut self, item: Item) {
match self.item_mut(&item.id) {
Some(slot) => *slot = item,
None => self.items.push(item),
}
}
pub fn remove(&mut self, id: &str) -> Option<Item> {
let i = self.items.iter().position(|it| it.id == id)?;
Some(self.items.remove(i))
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Atomic save (docs/FORMAT.md, "Saving").
use crate::Error;
use std::ffi::OsString;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
/// Where `save_atomic_crashing` stops, as if the process died there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CrashPoint {
MidTempWrite,
AfterTempWrite,
MidBackup,
AfterBackup,
}
/// Writes `bytes` to `path` so that a crash at any moment leaves either the previous file or the new one
/// in place, and keeps the previous version as `<path>.bak`.
pub fn save_atomic(path: &Path, bytes: &[u8]) -> Result<(), Error> {
save(path, bytes, None)
}
/// `save_atomic` that stops at `crash` with an error, for the crash tests.
#[doc(hidden)]
pub fn save_atomic_crashing(path: &Path, bytes: &[u8], crash: CrashPoint) -> Result<(), Error> {
save(path, bytes, Some(crash))
}
fn sibling(path: &Path, suffix: &str) -> PathBuf {
let mut name: OsString = path.file_name().unwrap_or_default().to_owned();
name.push(suffix);
path.with_file_name(name)
}
fn crashed(at: CrashPoint) -> Error {
Error::Io(std::io::Error::other(format!("simulated crash at {at:?}")))
}
/// Writes and fsyncs `path`; with `half`, writes only the first half and "crashes".
fn write_synced(path: &Path, bytes: &[u8], half: Option<CrashPoint>) -> Result<(), Error> {
let mut f = File::create(path)?;
if let Some(at) = half {
f.write_all(&bytes[..bytes.len() / 2])?;
return Err(crashed(at));
}
f.write_all(bytes)?;
f.sync_all()?;
Ok(())
}
/// `rename` that replaces the target. On Windows a sync client or a virus scanner can hold the target
/// open for a moment, so this retries for about two seconds before giving up.
fn replace(from: &Path, to: &Path) -> Result<(), Error> {
let mut tries = 0;
loop {
match std::fs::rename(from, to) {
Ok(()) => return Ok(()),
Err(e) if tries < 20 && e.kind() == std::io::ErrorKind::PermissionDenied => {
tries += 1;
std::thread::sleep(std::time::Duration::from_millis(100));
}
Err(e) => return Err(e.into()),
}
}
}
fn save(path: &Path, bytes: &[u8], crash: Option<CrashPoint>) -> Result<(), Error> {
let at = |p: CrashPoint| (crash == Some(p)).then_some(p);
let tmp = sibling(path, ".tmp");
write_synced(&tmp, bytes, at(CrashPoint::MidTempWrite))?;
if let Some(p) = at(CrashPoint::AfterTempWrite) {
return Err(crashed(p));
}
if path.exists() {
let old = std::fs::read(path)?;
let bak_tmp = sibling(path, ".bak.tmp");
write_synced(&bak_tmp, &old, at(CrashPoint::MidBackup))?;
replace(&bak_tmp, &sibling(path, ".bak"))?;
}
if let Some(p) = at(CrashPoint::AfterBackup) {
return Err(crashed(p));
}
replace(&tmp, path)?;
#[cfg(unix)]
if let Some(dir) = path.parent() {
File::open(dir)?.sync_all()?;
}
Ok(())
}
+59
View File
@@ -0,0 +1,59 @@
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use zeroize::Zeroizing;
/// A string that is wiped from memory when dropped and never printed.
/// `Debug` and `Display` give `[redacted]`; read it with [`SecretString::expose`].
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SecretString(Zeroizing<String>);
impl SecretString {
pub fn new(s: String) -> Self {
Self(Zeroizing::new(s))
}
/// The plaintext. Keep the borrow short and do not copy it into ordinary `String`s.
pub fn expose(&self) -> &str {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<&str> for SecretString {
fn from(s: &str) -> Self {
Self::new(s.to_owned())
}
}
impl From<String> for SecretString {
fn from(s: String) -> Self {
Self::new(s)
}
}
impl fmt::Debug for SecretString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl fmt::Display for SecretString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl Serialize for SecretString {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for SecretString {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
String::deserialize(d).map(Self::new)
}
}
+228
View File
@@ -0,0 +1,228 @@
//! The mandatory vault tests (CLAUDE.md): round-trip, wrong password, tamper, atomic save,
//! password change, no secret in Debug/Display.
use custos_vault::{
CrashPoint, Error, Field, Item, ItemType, KdfParams, SecretString, Vault, save_atomic, save_atomic_crashing,
};
use std::path::Path;
/// Cheap parameters so the tamper test can run Argon2 once per byte. Real vaults use `KdfParams::DEFAULT`.
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
fn sample_vault(password: &str) -> Vault {
let mut v = Vault::create(&pw(password), FAST).unwrap();
let mut login = Item::new(ItemType::WebLogin, "GitHub", 1_000);
login.set("username", "GitHub.Lantern.47", 1_000);
login.set("password", "Orbit7-Fable3-Quartz9-Lumen2", 1_000);
login.set("url", "https://github.com", 1_000);
login.add_field(Field::text("url", "https://gist.github.com"));
login.tags.push("dev".into());
login.set("password", "Second4-Value8-Here1-Now0", 2_000); // one history entry
v.add(login);
let mut note = Item::new(ItemType::SecureNote, "Česká spořitelna PIN letter", 1_500);
note.notes = pw("PIN 1234, keep the envelope");
v.add(note);
for kind in ItemType::ALL {
v.add(Item::new(kind, &format!("empty {kind:?}"), 3_000));
}
v
}
#[test]
fn round_trip_gives_identical_items() {
let v = sample_vault("correct horse");
let bytes = v.to_bytes().unwrap();
let back = Vault::open(&bytes, &pw("correct horse")).unwrap();
assert_eq!(back.items(), v.items());
assert_eq!(back.items().len(), 2 + ItemType::ALL.len());
let gh = back.items().iter().find(|i| i.title == "GitHub").unwrap();
assert_eq!(gh.history.len(), 1);
assert_eq!(gh.history[0].value.expose(), "Orbit7-Fable3-Quartz9-Lumen2");
assert_eq!(gh.fields.iter().filter(|f| f.name == "url").count(), 2);
// Through a file too, and a second save keeps working.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.custos");
v.save(&path).unwrap();
v.save(&path).unwrap();
assert_eq!(Vault::open_file(&path, &pw("correct horse")).unwrap().items(), v.items());
}
#[test]
fn every_save_uses_a_fresh_nonce() {
let v = sample_vault("pw");
assert_ne!(v.to_bytes().unwrap(), v.to_bytes().unwrap());
}
#[test]
fn wrong_password_fails_clearly_with_no_data() {
let bytes = sample_vault("right one").to_bytes().unwrap();
let e = Vault::open(&bytes, &pw("wrong one")).unwrap_err();
assert!(matches!(e, Error::WrongPassword), "{e:?}");
let msg = e.to_string();
assert!(msg.to_lowercase().contains("wrong password"), "{msg}");
assert!(!msg.contains("wrong one") && !msg.contains("right one"));
assert!(Vault::open(&bytes, &pw("")).is_err());
}
#[test]
fn flipping_any_byte_fails_authentication() {
let bytes = sample_vault("pw").to_bytes().unwrap();
for i in 0..bytes.len() {
for flip in [0x01u8, 0x80] {
let mut t = bytes.clone();
t[i] ^= flip;
assert!(Vault::open(&t, &pw("pw")).is_err(), "byte {i} ^ {flip:#x} was accepted");
}
}
// Truncated or extended files fail too.
for cut in [0, 5, 9, 100, bytes.len() - 1] {
assert!(Vault::open(&bytes[..cut], &pw("pw")).is_err(), "truncated to {cut}");
}
let mut longer = bytes.clone();
longer.push(0);
assert!(Vault::open(&longer, &pw("pw")).is_err());
}
#[test]
fn tampered_kdf_params_are_refused_before_argon2_runs() {
let bytes = sample_vault("pw").to_bytes().unwrap();
// m_cost sits right after magic(6) version(2) count(1) kind(1) len(2) kdf(1) = offset 13.
let mut t = bytes.clone();
t[13..17].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(matches!(Vault::open(&t, &pw("pw")), Err(Error::UnsupportedKdf)));
let mut t = bytes;
t[17..21].copy_from_slice(&1000u32.to_le_bytes()); // t_cost
assert!(matches!(Vault::open(&t, &pw("pw")), Err(Error::UnsupportedKdf)));
}
#[test]
fn not_a_vault_and_future_versions_are_refused() {
assert!(matches!(Vault::open(b"hello world, not a vault at all", &pw("x")), Err(Error::NotAVault)));
let mut bytes = sample_vault("pw").to_bytes().unwrap();
bytes[6] = 2;
assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::UnsupportedVersion(2))));
}
fn opens_with(path: &Path, password: &str, title: &str) -> bool {
Vault::open_file(path, &pw(password)).map(|v| v.items().iter().any(|i| i.title == title)).unwrap_or(false)
}
#[test]
fn crash_during_save_leaves_original_or_backup_openable() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("home.custos");
let bak = dir.path().join("home.custos.bak");
let mut v = sample_vault("pw");
v.save(&path).unwrap();
v.add(Item::new(ItemType::Wifi, "Second save", 5_000));
v.save(&path).unwrap();
// A normal save keeps the previous version as .bak.
assert!(opens_with(&path, "pw", "Second save"));
assert!(!opens_with(&bak, "pw", "Second save") && opens_with(&bak, "pw", "GitHub"));
v.add(Item::new(ItemType::Card, "Third save", 6_000));
let new_bytes = v.to_bytes().unwrap();
for crash in [CrashPoint::MidTempWrite, CrashPoint::AfterTempWrite, CrashPoint::MidBackup, CrashPoint::AfterBackup]
{
let e = save_atomic_crashing(&path, &new_bytes, crash).unwrap_err();
assert!(e.to_string().contains("simulated crash"), "{crash:?}: {e}");
// The vault on disk is the last complete save, untouched.
assert!(opens_with(&path, "pw", "Second save"), "{crash:?}: original");
assert!(!opens_with(&path, "pw", "Third save"), "{crash:?}: original changed");
// And a backup that opens is always there.
assert!(opens_with(&bak, "pw", "GitHub"), "{crash:?}: backup");
}
// Leftover temp files do not stop the next save.
save_atomic(&path, &new_bytes).unwrap();
assert!(opens_with(&path, "pw", "Third save"));
assert!(opens_with(&bak, "pw", "Second save"));
}
#[test]
fn crash_on_first_save_leaves_no_vault_but_no_garbage_either() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("new.custos");
let bytes = sample_vault("pw").to_bytes().unwrap();
save_atomic_crashing(&path, &bytes, CrashPoint::MidTempWrite).unwrap_err();
assert!(!path.exists());
save_atomic(&path, &bytes).unwrap();
assert!(opens_with(&path, "pw", "GitHub"));
}
#[test]
fn password_change_rewraps_the_key_and_keeps_items() {
let mut v = sample_vault("old password");
let items_before = v.items().to_vec();
v.change_password(&pw("new password"), FAST).unwrap();
let bytes = v.to_bytes().unwrap();
assert!(matches!(Vault::open(&bytes, &pw("old password")), Err(Error::WrongPassword)));
let back = Vault::open(&bytes, &pw("new password")).unwrap();
assert_eq!(back.items(), &items_before[..]);
// The vault key itself did not change: only its wrapping did.
assert!(back.same_key_as(&v));
}
#[test]
fn no_secret_in_debug_or_display() {
let secret = "Hunter2-Secret9-Value";
let s = pw(secret);
for out in [format!("{s:?}"), format!("{s}"), format!("{s:#?}")] {
assert!(!out.contains(secret) && out.contains("[redacted]"), "{out}");
}
let field = Field::secret("password", secret);
let mut item = Item::new(ItemType::WebLogin, "Example", 1);
item.set("password", secret, 1);
item.set("password", "Another-Secret-Two", 2);
item.notes = pw("note Secret-In-Notes");
let vault = {
let mut v = Vault::create(&pw("Master-Pass-Word"), FAST).unwrap();
v.add(item.clone());
v
};
let outs = [
format!("{field:?}"),
format!("{item:?}"),
format!("{item:#?}"),
format!("{:?}", item.history),
format!("{vault:?}"),
format!("{:?}", Error::WrongPassword),
];
for out in outs {
for leaked in [secret, "Another-Secret-Two", "Secret-In-Notes", "Master-Pass-Word"] {
assert!(!out.contains(leaked), "{leaked} leaked in {out}");
}
}
// Non-secret fields stay readable in Debug, which is what makes it useful.
assert!(format!("{item:?}").contains("Example"));
}
#[test]
fn device_wrap_opens_the_same_vault_and_nothing_else() {
// Windows Hello gives the desktop app a signature; the core turns it into a key wrap.
let v = sample_vault("pw");
let bytes = v.to_bytes().unwrap();
let material = b"signature bytes from the device key";
let blob = v.wrap_for_device(material).unwrap();
assert_ne!(v.wrap_for_device(material).unwrap(), blob, "fresh salt and nonce each time");
let back = Vault::open_with_device(&bytes, &blob, material).unwrap();
assert_eq!(back.items(), v.items());
assert!(matches!(Vault::open_with_device(&bytes, &blob, b"other signature"), Err(Error::DeviceKeyRejected)));
for i in 0..blob.len() {
let mut t = blob.clone();
t[i] ^= 1;
assert!(Vault::open_with_device(&bytes, &t, material).is_err(), "blob byte {i}");
}
// A blob made for another vault does not open this one.
let other = sample_vault("pw").wrap_for_device(material).unwrap();
assert!(Vault::open_with_device(&bytes, &other, material).is_err());
assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature"));
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "custos-wasm"
description = "Custos in the browser: the web vault's and the share page's crypto, compiled to WebAssembly"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
custos-vault = { path = "../custos-vault" }
custos-share = { path = "../custos-share" }
custos-totp = { path = "../custos-totp" }
custos-qr = { path = "../custos-qr" }
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
zeroize.workspace = true
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = "0.4"
+46
View File
@@ -0,0 +1,46 @@
// The whole JavaScript side of custos-wasm (see src/lib.rs, "ABI"): load the module, give it the
// browser's CSPRNG, and pass JSON requests in and out. The vault key never leaves WebAssembly memory.
/** @param {BufferSource | Response | Promise<Response>} source the custos_wasm.wasm bytes or a fetch of them */
export async function loadCustos(source) {
let memory;
const env = {
random_fill(ptr, len) {
// getRandomValues fills at most 65,536 bytes per call.
for (let off = 0; off < len; off += 65536) {
crypto.getRandomValues(new Uint8Array(memory.buffer, ptr + off, Math.min(65536, len - off)));
}
},
};
const { instance } =
source instanceof Response || source instanceof Promise
? await WebAssembly.instantiateStreaming(source, { env })
: await WebAssembly.instantiate(source, { env });
const x = instance.exports;
memory = x.memory;
const enc = new TextEncoder();
const dec = new TextDecoder();
/** Sends one request; resolves to the parsed response ({ok: true, …} or {ok: false, error}). */
function call(request) {
const bytes = enc.encode(JSON.stringify(request));
const ptr = x.alloc(bytes.length);
new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
bytes.fill(0);
const packed = x.call(ptr, bytes.length); // frees and zeroes the request
const outPtr = Number(packed >> 32n);
const outLen = Number(packed & 0xffffffffn);
const out = new Uint8Array(memory.buffer, outPtr, outLen);
const text = dec.decode(out);
x.dealloc(outPtr, outLen); // zeroes the response in WebAssembly memory
return JSON.parse(text);
}
return { call };
}
/** Base64 of bytes, for the `open` and `share_open` requests. */
export function toBase64(bytes) {
let s = '';
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s);
}
+32
View File
@@ -0,0 +1,32 @@
// node test.mjs <custos_wasm.wasm> [<vault file> <password>]: the JS loader against the real build.
import fs from 'node:fs';
import { loadCustos, toBase64 } from './custos.mjs';
const [wasmPath, vaultPath, password] = process.argv.slice(2);
const c = await loadCustos(fs.readFileSync(wasmPath));
const assert = (ok, msg) => { if (!ok) { console.error('FAIL', msg); process.exit(1); } };
const bad = c.call({ op: 'share_open', blob: 'Q1NIMQA=', fragment: 'k=x' });
assert(!bad.ok && bad.code === 'Malformed', JSON.stringify(bad));
assert(c.call({ op: 'items' }).error === 'The vault is locked.', 'locked');
if (vaultPath) {
const t0 = performance.now();
const r = c.call({ op: 'open', vault: toBase64(fs.readFileSync(vaultPath)), password });
const ms = Math.round(performance.now() - t0);
assert(r.ok, r.error);
console.log(`unlocked ${r.items.length} items in ${ms} ms (WebAssembly, default KDF)`);
const item = r.items.find((i) => i.hasMainSecret);
for (const pw of [null, 'by-phone']) {
const t1 = performance.now();
const s = c.call({ op: 'share_seal', id: item.id, password: pw });
assert(s.ok, s.error);
const o = c.call({ op: 'share_open', blob: s.blob, fragment: s.fragment, password: pw });
assert(o.ok && o.payload.title === item.title, JSON.stringify(o.error));
console.log(`share ${pw ? 'with' : 'without'} password: sealed and opened in ${Math.round(performance.now() - t1)} ms`);
}
const fresh = new Set(Array.from({ length: 100 }, () => c.call({ op: 'share_seal', id: item.id }).fragment));
assert(fresh.size === 100, 'link keys repeat: random_fill is broken');
c.call({ op: 'lock' });
}
console.log('ok');
+315
View File
@@ -0,0 +1,315 @@
//! Custos in the browser. The web vault and the share recipient page load this crate compiled to
//! `wasm32-unknown-unknown`; everything that touches a key or plaintext happens here, in code from this
//! public repository. The page's JavaScript only moves JSON in and out.
//!
//! # ABI (no wasm-bindgen)
//! Exports:
//! - `memory`
//! - `alloc(len) -> ptr` and `dealloc(ptr, len)`; `dealloc` zeroes the bytes before freeing them.
//! - `call(ptr, len) -> u64`: takes a JSON request the caller wrote into an `alloc`ed buffer (and frees it,
//! zeroed), returns `(response_ptr << 32) | response_len`. The caller reads the JSON response and gives it
//! back with `dealloc`.
//!
//! Import: `env.random_fill(ptr, len)`, which must fill the bytes from `crypto.getRandomValues`
//! (getrandom's custom backend; `.cargo/config.toml` selects it for this target).
//!
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
//! (and with it the key, wiped).
use custos_share::{Payload, ShareError};
use custos_vault::{Item, ItemType, SecretString, Vault};
use data_encoding::BASE64;
use qrcode::render::svg;
use qrcode::{EcLevel, QrCode};
use serde::Deserialize;
use serde_json::{Value, json};
use std::cell::RefCell;
use zeroize::Zeroizing;
thread_local! {
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
}
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", rename_all_fields = "camelCase")]
enum Request {
/// `vault`: the `.custos` file, base64.
Open {
vault: String,
password: SecretString,
},
Lock,
Items,
/// A field's value by name and index among fields of that name, or `name: "notes"`.
Reveal {
id: String,
name: String,
#[serde(default)]
index: usize,
},
/// `now`: Unix seconds (WebAssembly has no clock of its own).
Totp {
id: String,
now: u64,
},
/// A Wi-Fi item gives its join code, anything else its main secret.
Qr {
id: String,
},
ShareSeal {
id: String,
password: Option<SecretString>,
},
/// `blob`: base64, as the share server returned it.
ShareOpen {
blob: String,
fragment: String,
password: Option<SecretString>,
},
}
fn err(msg: impl ToString) -> Value {
json!({ "ok": false, "error": msg.to_string() })
}
/// The field *Copy* and the QR code use for each type (the desktop app's choice).
pub fn primary_secret(kind: ItemType) -> &'static str {
match kind {
ItemType::WebLogin | ItemType::LocalApp | ItemType::Wifi => "password",
ItemType::ApiCredential => "secret",
ItemType::Card => "number",
ItemType::SecureNote => "notes",
}
}
fn primary_user(kind: ItemType) -> Option<&'static str> {
match kind {
ItemType::WebLogin | ItemType::LocalApp => Some("username"),
ItemType::ApiCredential => Some("key-id"),
ItemType::Wifi => Some("ssid"),
ItemType::Card => Some("cardholder"),
ItemType::SecureNote => None,
}
}
fn plain<'a>(item: &'a Item, name: &str) -> Option<&'a str> {
item.field(name).filter(|f| !f.secret).map(|f| f.value.expose()).filter(|v| !v.is_empty())
}
fn value<'a>(item: &'a Item, name: &str, index: usize) -> Option<&'a SecretString> {
if name == "notes" {
return Some(&item.notes);
}
item.fields.iter().filter(|f| f.name == name).nth(index).map(|f| &f.value)
}
/// An item for the page: non-secret field values, secret ones only as "has a value".
fn view(item: &Item) -> Value {
let urls: Vec<&str> =
item.fields.iter().filter(|f| f.name == "url" && !f.value.is_empty()).map(|f| f.value.expose()).collect();
let subtitle = primary_user(item.kind)
.and_then(|n| plain(item, n))
.or(plain(item, "service"))
.or(plain(item, "target"))
.or(urls.first().copied())
.unwrap_or("");
let mut seen = std::collections::HashMap::<&str, usize>::new();
let fields: Vec<Value> = item
.fields
.iter()
.map(|f| {
let n = seen.entry(f.name.as_str()).or_default();
let index = *n;
*n += 1;
json!({
"name": f.name,
"index": index,
"secret": f.secret,
"hasValue": !f.value.is_empty(),
"value": if f.secret { Value::Null } else { Value::from(f.value.expose()) },
})
})
.collect();
let main = primary_secret(item.kind);
json!({
"id": item.id,
"kind": item.kind,
"title": item.title,
"subtitle": subtitle,
"urls": urls,
"tags": item.tags,
"fields": fields,
"hasNotes": !item.notes.is_empty(),
"mainSecret": main,
"hasMainSecret": value(item, main, 0).is_some_and(|v| !v.is_empty()),
"hasTotp": item.field("totp").is_some_and(|f| !f.value.is_empty()),
"modified": item.modified,
})
}
fn items(v: &Vault) -> Value {
json!({ "ok": true, "items": v.items().iter().map(view).collect::<Vec<_>>() })
}
fn with_item(id: &str, f: impl FnOnce(&Item) -> Value) -> Value {
VAULT.with_borrow(|v| match v {
None => err("The vault is locked."),
Some(v) => match v.item(id) {
None => err("Item not found."),
Some(item) => f(item),
},
})
}
fn qr_svg(payload: &str) -> Result<String, String> {
let code = QrCode::with_error_correction_level(payload.as_bytes(), EcLevel::M).map_err(|e| e.to_string())?;
Ok(code.render::<svg::Color>().min_dimensions(320, 320).quiet_zone(true).build())
}
fn payload_json(p: &Payload) -> Value {
json!({
"title": p.title,
"kind": p.kind,
"fields": p.fields.iter().map(|f| json!({ "name": f.name, "value": f.value.expose(), "secret": f.secret })).collect::<Vec<_>>(),
"notes": p.notes.as_ref().map(|n| n.expose()),
})
}
fn share_error(e: ShareError) -> Value {
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
}
/// Handles one request. Native code (and the tests) call this directly; the browser goes through `call`.
pub fn handle(request: &[u8]) -> Value {
let req: Request = match serde_json::from_slice(request) {
Ok(r) => r,
// serde's message can quote the input, which may hold a password: say only what failed.
Err(_) => return err("Bad request."),
};
match req {
Request::Open { vault, password } => {
let Ok(bytes) = BASE64.decode(vault.as_bytes()) else { return err("The vault file is damaged.") };
match Vault::open(&bytes, &password) {
Ok(v) => {
let out = items(&v);
VAULT.set(Some(v));
out
}
Err(e) => err(e),
}
}
Request::Lock => {
VAULT.set(None);
json!({ "ok": true })
}
Request::Items => VAULT.with_borrow(|v| v.as_ref().map(items).unwrap_or_else(|| err("The vault is locked."))),
Request::Reveal { id, name, index } => with_item(&id, |item| match value(item, &name, index) {
Some(v) => json!({ "ok": true, "value": v.expose() }),
None => err("No such field."),
}),
Request::Totp { id, now } => with_item(&id, |item| {
let Some(f) = item.field("totp").filter(|f| !f.value.is_empty()) else { return err("No 2FA code here.") };
match custos_totp::Totp::parse(f.value.expose()) {
Ok(t) => {
json!({ "ok": true, "code": t.code_at(now), "secondsLeft": t.seconds_left(now), "period": t.period() })
}
Err(e) => err(e),
}
}),
Request::Qr { id } => with_item(&id, |item| {
let f = |n: &str| item.field(n).map(|f| f.value.expose()).unwrap_or("");
let (payload, wifi) = if item.kind == ItemType::Wifi {
let p = custos_qr::wifi_payload(
f("ssid"),
f("password"),
custos_qr::WifiSecurity::parse(f("security")),
f("hidden") == "true",
);
(Zeroizing::new(p), true)
} else {
match value(item, primary_secret(item.kind), 0).filter(|v| !v.is_empty()) {
Some(v) => (Zeroizing::new(custos_qr::secret_payload(v.expose())), false),
None => return err("Nothing to show."),
}
};
match qr_svg(&payload) {
Ok(svg) => json!({ "ok": true, "svg": svg, "wifi": wifi }),
Err(e) => err(e),
}
}),
Request::ShareSeal { id, password } => with_item(&id, |item| {
let password = password.filter(|p| !p.is_empty());
match custos_share::seal(&Payload::from_item(item), password.as_ref()) {
Ok(s) => json!({ "ok": true, "blob": BASE64.encode(&s.blob), "fragment": s.fragment.as_str() }),
Err(e) => share_error(e),
}
}),
Request::ShareOpen { blob, fragment, password } => {
let Ok(bytes) = BASE64.decode(blob.as_bytes()) else { return share_error(ShareError::Malformed) };
match custos_share::open(&bytes, &fragment, password.as_ref()) {
Ok(p) => json!({ "ok": true, "payload": payload_json(&p) }),
Err(e) => share_error(e),
}
}
}
}
// ---------- the WebAssembly ABI ----------
#[cfg(target_arch = "wasm32")]
mod abi {
use std::alloc::{Layout, alloc as raw_alloc, dealloc as raw_dealloc};
use zeroize::Zeroize;
#[link(wasm_import_module = "env")]
unsafe extern "C" {
fn random_fill(ptr: *mut u8, len: usize);
}
/// getrandom's custom backend: the browser's CSPRNG.
#[unsafe(no_mangle)]
unsafe extern "Rust" fn __getrandom_v03_custom(dest: *mut u8, len: usize) -> Result<(), getrandom::Error> {
unsafe { random_fill(dest, len) };
Ok(())
}
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
if len == 0 {
return std::ptr::NonNull::dangling().as_ptr();
}
unsafe { raw_alloc(Layout::from_size_align(len, 1).expect("layout")) }
}
/// # Safety
/// `ptr` and `len` must come from `alloc` or `call`, and be given back once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) {
if len == 0 {
return;
}
unsafe {
std::slice::from_raw_parts_mut(ptr, len).zeroize();
raw_dealloc(ptr, Layout::from_size_align(len, 1).expect("layout"));
}
}
/// # Safety
/// `ptr`/`len` must be a buffer from `alloc` holding the request; `call` frees it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn call(ptr: *mut u8, len: usize) -> u64 {
let response = {
let request = unsafe { std::slice::from_raw_parts(ptr, len) };
super::handle(request)
};
unsafe { dealloc(ptr, len) };
let mut bytes = serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"ok\":false}".to_vec());
drop(response);
let out = alloc(bytes.len());
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len()) };
let packed = ((out as u64) << 32) | bytes.len() as u64;
bytes.zeroize();
packed
}
}
+112
View File
@@ -0,0 +1,112 @@
//! The JSON operations the browser calls, run natively.
use custos_vault::{Field, Item, ItemType, KdfParams, SecretString, Vault};
use data_encoding::BASE64;
use serde_json::{Value, json};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const PASSWORD: &str = "Test4-Vault7-Only2";
const SECRET: &str = "s3cret-Ž!";
fn call(v: Value) -> Value {
custos_wasm::handle(v.to_string().as_bytes())
}
fn vault_b64() -> (String, String, String) {
let mut v = Vault::create(&SecretString::from(PASSWORD), FAST).unwrap();
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
login.set("username", "mark", 0);
login.set("password", SECRET, 0);
login.set("url", "https://github.com", 0);
login.set("totp", "JBSWY3DPEHPK3PXP", 0);
let login_id = login.id.clone();
let mut wifi = Item::new(ItemType::Wifi, "Home", 0);
wifi.set("ssid", "Domov", 0);
wifi.set("password", SECRET, 0);
wifi.set("security", "WPA", 0);
wifi.add_field(Field::text("note", "2.4 GHz"));
let wifi_id = wifi.id.clone();
v.add(login);
v.add(wifi);
(BASE64.encode(&v.to_bytes().unwrap()), login_id, wifi_id)
}
#[test]
fn open_list_reveal_lock() {
let (vault, login, _) = vault_b64();
let bad = call(json!({ "op": "open", "vault": vault, "password": "wrong" }));
assert_eq!(bad["ok"], false);
assert_eq!(bad["error"], "wrong password");
let r = call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
assert_eq!(r["ok"], true, "{r}");
let text = r.to_string();
assert!(!text.contains(SECRET) && !text.contains("JBSWY3DP"), "the list holds no secret values");
let items = r["items"].as_array().unwrap();
assert_eq!(items.len(), 2);
let gh = items.iter().find(|i| i["id"] == login.as_str()).unwrap();
assert_eq!(
(gh["subtitle"].as_str(), gh["hasTotp"].as_bool(), gh["mainSecret"].as_str()),
(Some("mark"), Some(true), Some("password"))
);
let rv = call(json!({ "op": "reveal", "id": login, "name": "password" }));
assert_eq!(rv["value"], SECRET);
assert_eq!(call(json!({ "op": "reveal", "id": login, "name": "password", "index": 1 }))["ok"], false);
assert_eq!(call(json!({ "op": "lock" }))["ok"], true);
let locked = call(json!({ "op": "reveal", "id": login, "name": "password" }));
assert_eq!(locked["error"], "The vault is locked.");
assert_eq!(call(json!({ "op": "items" }))["ok"], false);
}
#[test]
fn totp_and_qr() {
let (vault, login, wifi) = vault_b64();
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
let now = 1_800_000_000u64;
let t = call(json!({ "op": "totp", "id": login, "now": now }));
let expected = custos_totp::Totp::parse("JBSWY3DPEHPK3PXP").unwrap();
assert_eq!(t["code"], expected.code_at(now));
assert_eq!(t["secondsLeft"], expected.seconds_left(now));
let q = call(json!({ "op": "qr", "id": wifi }));
assert_eq!((q["ok"].as_bool(), q["wifi"].as_bool()), (Some(true), Some(true)));
assert!(q["svg"].as_str().unwrap().starts_with("<?xml"));
let q = call(json!({ "op": "qr", "id": login }));
assert_eq!(q["wifi"], false);
}
#[test]
fn share_seal_and_open() {
let (vault, login, _) = vault_b64();
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
for password in [None, Some("by-phone")] {
let s = call(json!({ "op": "share_seal", "id": login, "password": password }));
assert_eq!(s["ok"], true, "{s}");
let (blob, fragment) = (s["blob"].as_str().unwrap(), s["fragment"].as_str().unwrap());
assert!(!blob.contains(SECRET));
let o = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": password }));
assert_eq!(o["ok"], true, "{o}");
let fields = o["payload"]["fields"].as_array().unwrap();
let names: Vec<_> = fields.iter().map(|f| f["name"].as_str().unwrap()).collect();
assert_eq!(names, ["username", "password", "url"], "no TOTP seed in a share");
assert_eq!(fields[1]["value"], SECRET);
if password.is_some() {
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": "nope" }));
assert_eq!(w["code"], "DecryptFailed");
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment }));
assert_eq!(w["code"], "PasswordRequired");
}
}
// An empty password means none.
let s = call(json!({ "op": "share_seal", "id": login, "password": "" }));
assert!(!s["fragment"].as_str().unwrap().contains("p=1"));
}
#[test]
fn bad_requests_never_echo_their_input() {
let r = custos_wasm::handle(br#"{"op":"open","vault":"x","password":"hunter2","extra":"#);
assert_eq!(r["error"], "Bad request.");
let r = call(json!({ "op": "share_open", "blob": "!!", "fragment": "k=hunter2" }));
assert!(!r.to_string().contains("hunter2"));
}
+202
View File
@@ -0,0 +1,202 @@
# The `.custos` vault file, format version 1
One file holds one vault. Everything after the header is one XChaCha20-Poly1305 ciphertext.
The header is not secret, but it is authenticated: changing any byte of it makes the body fail to open.
All integers are little-endian. The code is `crates/custos-vault/src/format.rs`.
## Keys
```
master password ──Argon2id(salt, m, t, p)──► KEK (32 bytes) ──unwraps──► vault key (32 random bytes)
│
body = XChaCha20-Poly1305(vault key, body nonce,
JSON, aad = whole header)
```
- The **vault key** is 32 bytes from the OS CSPRNG, made once when the vault is created.
- A **key slot** wraps the vault key. Version 1 has one kind: a password slot (Argon2id → KEK →
XChaCha20-Poly1305). Changing the password writes a new slot (new salt, new nonce) and leaves the vault
key alone. Windows Hello (desktop app) wraps the same vault key outside this file, on the one machine.
- **Nonces** are 24 random bytes, fresh for every slot write and every save. With 192-bit nonces random
generation is safe for any realistic number of saves.
## Layout
```
offset size field
0 6 magic "CUSTOS" (43 55 53 54 4F 53)
6 2 version u16 = 1
8 1 slot count u8, 1..=8
9 … slots repeated `slot count` times, see below
… 24 body nonce
──────── end of header ─────────────────────────────────────────────
… n+16 body ciphertext of n bytes of JSON + 16-byte Poly1305 tag, to end of file
```
Each slot:
```
size field
1 kind 1 = password; other values are skipped by readers that do not know them
2 length u16, bytes of payload that follow
len payload
```
Password slot payload (117 bytes):
```
size field
1 kdf 1 = Argon2id, version 0x13
4 m_cost u32, memory in KiB
4 t_cost u32, iterations
4 p_cost u32, lanes
32 salt
24 wrap nonce
48 wrapped key 32-byte vault key encrypted with the KEK + 16-byte tag
```
- **Slot AAD**: `magic ‖ version ‖ kind ‖ payload[0..69]` (everything in the slot before the wrapped key).
So the KDF parameters and salt cannot be swapped without the unwrap failing.
- **Body AAD**: the whole header, from offset 0 to the end of the body nonce.
### Limits a reader enforces before running Argon2
A tampered header must not make the reader allocate 16 GiB. Outside these ranges the file is refused
with "unsupported KDF parameters", before any work:
| Parameter | Allowed | Default written by Custos |
|:--|:--|:--|
| m_cost | 8·p ..= 2 097 152 KiB (2 GiB) | 65 536 KiB (64 MiB) |
| t_cost | 1 ..= 64 | 20 (≈ 0.75 s per unlock on the dev machine; `examples/kdf_timing.rs` measures it) |
| p_cost | 1 ..= 16 | 1 |
The parameters are stored per file, so a later version can raise the defaults; a vault keeps its
parameters until its password is changed.
### Errors
| Situation | Error |
|:--|:--|
| Wrong magic, or the file is shorter than a header | `NotAVault` |
| Version other than 1 | `UnsupportedVersion(n)` |
| No password slot, or a slot runs past the end | `Malformed` |
| KDF parameters outside the limits | `UnsupportedKdf` |
| No slot unwraps with the password | `WrongPassword` (a wrong password and a tampered slot look the same) |
| Slot unwraps but the body tag fails | `Corrupted` (header or body changed after it was written) |
No error carries any part of the password, the key or the plaintext.
## Body (the JSON inside)
UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
```json
{
"format": 1,
"items": [
{
"id": "6f1c…(32 hex)",
"type": "web-login",
"title": "GitHub",
"fields": [
{ "name": "username", "value": "GitHub.Lantern.47", "secret": false },
{ "name": "password", "value": "Fable7-Orbit3-…", "secret": true },
{ "name": "url", "value": "https://github.com", "secret": false }
],
"tags": ["dev"],
"notes": "",
"created": 1793000000000,
"modified": 1793000000000,
"history": [ { "field": "password", "value": "old…", "changed": 1792000000000 } ]
}
]
}
```
- Times are Unix milliseconds (UTC).
- `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.
### Item types and their fields (v1)
`*` = secret (`"secret": true`: hidden until revealed, copied with clipboard protection).
| `type` | Fields, in order |
|:--|:--|
| `web-login` | `username`, `password`*, `url` (repeatable), `totp`* (otpauth URI or base32 secret), `autotype-match`, `autotype-sequence` |
| `api-credential` | `service`, `key-id`, `secret`*, `endpoint`, `expires` (YYYY-MM-DD) |
| `local-app` | `target` (app or Credential Manager target), `username`, `password`* |
| `wifi` | `ssid`, `password`*, `security` (`WPA` / `WEP` / `nopass`), `hidden` (`true` / `false`) |
| `secure-note` | none: the text is `notes` |
| `card` | `cardholder`, `number`*, `expiry` (MM/YY), `cvv`*, `pin`* |
`notes` is secret for every type (it is shown only on reveal).
## Planned KDBX 4 mapping (export comes in v1.2)
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) |
## Device key wrap (not part of the file)
Quick unlock on one machine (the desktop app uses Windows Hello) keeps a separate 108-byte blob **on that
machine**, never in the vault file:
```
"CDW1" (4) ‖ salt (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(KEK, vault key, aad = "CDW1" ‖ salt ‖ nonce) (48)
KEK = HKDF-SHA256(ikm = device material, salt, info = "custos device wrap v1")
```
The device material is something only that device can produce on request (for Windows Hello: the RSA
signature of a fixed challenge by a TPM-held key, which only Hello can unlock). A wrong material or a
changed blob gives `DeviceKeyRejected`; a blob from another vault unwraps a key that fails the body tag
(`Corrupted`). Changing the master password does not change the vault key, so the app deletes the blob
itself when the password changes.
## Saving
`custos-vault::save_atomic` never leaves a half-written vault in place of the old one:
1. The new bytes go to `<name>.custos.tmp` in the same folder; the file is flushed with `fsync`.
2. If `<name>.custos` exists, it is copied to `<name>.custos.bak.tmp`, flushed, and renamed over
`<name>.custos.bak`.
3. `<name>.custos.tmp` is renamed over `<name>.custos` (`std::fs::rename`, which replaces the target; on
Unix the folder is flushed afterwards). A rename refused because a sync client or virus scanner holds
the file open is retried for about two seconds.
A crash in step 1 or 2 leaves the old vault untouched; a crash between 2 and 3 leaves both the old vault
and an identical `.bak`. Leftover `.tmp` files are ignored and overwritten by the next save.
## Versioning
A change that old readers would misread bumps `version`. Readers refuse versions they do not know rather
than guess. Adding JSON members or new slot kinds does not need a bump.
## Share links
Shares are not vault files; their blob and link format is in `docs/SHARE.md`.
+71
View File
@@ -0,0 +1,71 @@
# Private share links (`custos-share`), format version 1
A share link hands one secret to someone who has no Custos. The sender's app (desktop or web) encrypts it;
the share server stores only ciphertext; the key travels in the link's fragment, which browsers never send
to a server.
```
https://custos.example/s/<id>#k=<link key> no password
https://custos.example/s/<id>#k=<link key>&p=1 the recipient also needs a password, told separately
```
- `<id>`: chosen by the server (128 random bits, base64url, 22 characters). It is not secret.
- `<link key>`: 32 random bytes from the OS CSPRNG, base64url without padding (43 characters).
- `p=1` only tells the recipient page to ask for a password before it fetches anything. The blob's own
flag decides; a link with `p=1` removed still needs the password.
## Keys
```
no password: K = link key
with password: P = Argon2id(password (UTF-8), salt, m, t, p) → 32 bytes
K = HKDF-SHA256(salt = salt, ikm = link key ‖ P, info = "custos-share v1") → 32 bytes
```
Both the link and the password are needed; neither alone gives anything, and the server has neither.
Default share KDF: m = 19 MiB (19,456 KiB), t = 2, p = 1 (OWASP's Argon2id minimum; it runs in a phone
browser in about a second). It only has to slow down guessing by someone who already holds the link.
## Blob (what the server stores), all integers little-endian
| Offset | Size | Field |
|:--|:--|:--|
| 0 | 4 | magic `CSH1` |
| 4 | 1 | flags: bit 0 = password; other bits must be 0 |
| 5 | 28 | only if bit 0: `m_cost_kib` u32, `t_cost` u32, `p_cost` u32, salt (16 bytes) |
| … | 24 | nonce |
| … | rest | XChaCha20-Poly1305 ciphertext and 16-byte tag; AAD = every byte before it (magic to nonce) |
Limits a reader enforces before running Argon2: m from 8 MiB to 256 MiB, t from 1 to 16, p from 1 to 4.
A whole blob is at most 64 KiB.
## Plaintext
UTF-8 JSON, `{"v":1,"title":"…","kind":"web-login","fields":[{"name":"password","value":"…","secret":true}],"notes":"…"}`.
`kind` and `notes` may be missing. Built from an item by `Payload::from_item`, which leaves out empty
fields, the TOTP seed (sharing it would hand over the second factor too) and the auto-type settings.
## Errors (none contains secret material)
| Error | When | Says |
|:--|:--|:--|
| `Malformed` | wrong magic, too short, unknown flags, too large | not a Custos share |
| `BadLink` | fragment missing, not `k=` + 43 base64url characters | the link is incomplete |
| `PasswordRequired` | the blob has the password flag and no password was given | — |
| `UnsupportedKdf` | parameters outside the limits | — |
| `DecryptFailed` | the tag does not verify: wrong key, wrong password, or any byte changed | never garbage: nothing is returned |
A wrong password and a tampered blob give the same `DecryptFailed`; the page says "wrong password, or the
link or share is damaged".
## Server rules (the private app's share service implements them)
- Stores the blob, an expiry (1 hour, 1 day or 7 days; default 1 day) and a view count (default 1).
- `open` returns the blob and counts one view; the last view deletes it. Expired, used up and unknown ids
answer the same 404.
- Logs only the id, the time and the status code. Never a body, never a full URL.
## The browser build (`custos-wasm`)
The web vault and the recipient page run this repository's code compiled to `wasm32-unknown-unknown`,
with no wasm-bindgen: a JSON-in/JSON-out `call` export and a `random_fill` import backed by
`crypto.getRandomValues` (getrandom's custom backend). The ABI is documented in `crates/custos-wasm/src/lib.rs`.
+65
View File
@@ -0,0 +1,65 @@
# Threat model
Custos keeps one person's (or one household's) secrets in one encrypted file on their own disk, synced
as a plain file (e.g. by Arca to their own Nextcloud). This page says what that protects against and,
just as plainly, what it does not.
## Assets
- The secrets in the vault: passwords, API keys, TOTP seeds, Wi-Fi keys, card numbers, notes.
- The master password and the 256-bit vault key it unwraps.
## What is protected
| Attacker | Has | Gets | Why |
|:--|:--|:--|:--|
| Thief or sync server | The `.custos` file (any number of old versions) | Item count and sizes roughly (the ciphertext length), the KDF parameters. Nothing else. | XChaCha20-Poly1305 over the whole body; titles, URLs and usernames are inside it too. |
| Offline guesser | The file and a GPU farm | One Argon2id evaluation (64 MiB, 20 passes by default, ≈ 0.75 s on a desktop CPU) per guess | A 4-word memorable password with digits (~65 bits) is out of reach; a weak master password is not. **The master password is the whole defence here.** |
| Tamperer | Write access to the file | Can destroy it, or roll it back to an older version they saw. Cannot change, reorder, add or remove items unnoticed. | The header is the body's AAD; each slot's parameters are its wrap's AAD. |
| Share server operator | Every share blob, its id, size, expiry, view count, the uploader's login and the recipients' IP addresses | Nothing of the secret | The key is in the link's `#fragment`, which browsers never send; the server stores ciphertext only (docs/SHARE.md). |
| 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`. |
## What is NOT protected
- **A compromised OS or a malicious process running as you.** While the vault is unlocked, the key and
the decrypted items are in the app's memory. Malware with your privileges can read that memory, log your
keystrokes as you type the master password, or read the screen. No password manager defends against this.
- **A memory dump while unlocked** (crash dump, hibernation file, swap). Secrets are held in zeroizing types
and wiped when dropped, which shrinks the window; it does not close it. Copies may remain where the
standard library or the JSON parser moved a buffer, in the webview (the desktop app shows a revealed
value there), and in OS buffers. Use full-disk encryption (BitLocker) for the hibernation file and swap.
- **The clipboard.** A copied secret is readable by every process until it is cleared (30 s in the
desktop app), and by any clipboard manager that ignores the "exclude from history" marker.
- **Auto-type** sends keystrokes to whatever window has focus. The app re-checks the target window before
typing, but a window that steals focus at the wrong moment can receive them.
- **Device unlock (Windows Hello).** The blob on disk is only as strong as the device key behind it: anyone
who can make Windows Hello sign as you on that machine (your PIN, your face, or malware running while
you approve a prompt) can unlock the vault there. It does not help an attacker who has only the vault file.
- **Rollback.** Someone with write access to the synced file can replace it with an older version.
Custos does not detect that (there is no trusted counter to compare against).
- **Shoulder surfing and QR codes.** A revealed password or a shown QR code is readable by anyone who
can see the screen.
- **Metadata.** File size and modification times reveal roughly how much is stored and when it changed.
- **Side channels.** No effort beyond what the RustCrypto crates provide (constant-time tag comparison).
- **The web vault trusts the server that serves its code.** In the browser, the page, its JavaScript and the
WebAssembly come from the home server on every visit. Whoever controls that server (or its TLS
certificate) can serve a modified page that sends the master password away the next time someone unlocks
in the browser. The desktop app does not have this problem. Authelia keeps strangers out; it does not
protect against the server itself. The same holds for the share page and the recipient.
- **Browser memory.** In the web vault the key and the decrypted items live in WebAssembly memory, and a
revealed or copied value passes through JavaScript strings, which cannot be wiped. Lock (or close the tab)
when done.
## Design rules that follow from this
- No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG
(`rand`'s `SysRng`/`getrandom`), `zeroize`. All RustCrypto / rust-random.
- Secret-holding types never print their contents: `Debug` and `Display` give `[redacted]` (tested).
- Errors never contain secret material; a wrong password and a tampered slot give the same error.
- The reader checks KDF parameters against fixed limits before running Argon2, so a crafted file cannot
make it allocate unbounded memory.
- Generated passwords take their randomness only from the OS CSPRNG, and their reported entropy counts only
the random choices (a fixed pattern like capitalisation adds nothing).
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"