[repo] Merge: feature/core (vault file v1, generators, PR #1)

This commit was merged in pull request #1.
This commit is contained in:
2026-10-31 10:13:46 +01:00
24 changed files with 10392 additions and 0 deletions
+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
Generated
+541
View File
@@ -0,0 +1,541 @@
# 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 = "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.1.0"
dependencies = [
"custos-vault",
"rand",
"regex",
"unicode-normalization",
"zeroize",
]
[[package]]
name = "custos-vault"
version = "0.1.0"
dependencies = [
"argon2",
"chacha20poly1305",
"rand",
"serde",
"serde_json",
"tempfile",
"thiserror",
"zeroize",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"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 = "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 = "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 = "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 = "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"
+19
View File
@@ -0,0 +1,19 @@
[workspace]
resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.1.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"
+18
View File
@@ -0,0 +1,18 @@
# 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 |
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 EFF wordlist is CC BY 3.0 US (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"
+483
View File
@@ -0,0 +1,483 @@
//! 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 ----------
/// The EFF large wordlist (7,776 words), with its four hyphenated words made plain: the hyphen is
/// removed, and `yo-yo` (the list also has `yoyo`) becomes `yoyos`, so all 7,776 stay distinct.
pub static EFF_WORDS: LazyLock<Vec<String>> = LazyLock::new(|| {
include_str!("../wordlists/eff_large_wordlist.txt")
.lines()
.filter_map(|l| l.split('\t').nth(1))
.map(|w| match w.trim() {
"yo-yo" => "yoyos".to_owned(),
w => w.replace('-', ""),
})
.collect()
});
fn plain_list(text: &'static str) -> Vec<&'static str> {
text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect()
}
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 = (EFF_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 = &EFF_WORDS[rng().random_range(0..EFF_WORDS.len())];
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>()
}
/// 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 mut tokens = parse_template(&o.template)?;
if !(1..=4).contains(&o.digits) {
return fail("the number must have 1 to 4 digits");
}
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 pool: Vec<&str> = Vec::new();
for k in &o.kinds {
if !pool.is_empty() && pool.iter().any(|w| words(*k).contains(w)) {
// Overlapping lists: keep the union without duplicates, so entropy stays honest.
pool.extend(words(*k).iter().filter(|w| !pool.contains(w)).collect::<Vec<_>>());
} else {
pool.extend_from_slice(words(*k));
}
}
if pool.is_empty() && tokens.contains(&Token::Word) {
return fail("choose at least one kind of word");
}
let mut out = String::new();
let mut bits = 0.0;
for t in &tokens {
match t {
Token::Literal(s) => out.push_str(s),
Token::Name => out.push_str(&name),
Token::Word => {
let w = capitalize(pick(&pool));
out.push_str(&if o.leet { leetify(&w) } else { w });
bits += (pool.len() as f64).log2();
}
Token::Number => {
(0..o.digits).for_each(|_| out.push(digit()));
bits += o.digits as f64 * 10f64.log2();
}
}
}
Ok(Generated { value: SecretString::new(out), entropy_bits: bits })
}
// ---------- random, strict site, PIN ----------
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.
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(|c| !c.is_alphanumeric() && !c.is_whitespace()).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() }
}
+249
View File
@@ -0,0 +1,249 @@
//! The mandatory generator tests (CLAUDE.md).
use custos_gen::{
ClassRule, EFF_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions, WordKind,
memorable, memorable_entropy, nickname, normalize_name, pin, random, strict,
};
use regex::Regex;
use std::collections::HashSet;
const SAMPLES: usize = 10_000;
#[test]
fn eff_list_is_complete_and_plain() {
assert_eq!(EFF_WORDS.len(), 7_776);
let unique: HashSet<_> = EFF_WORDS.iter().collect();
assert_eq!(unique.len(), 7_776, "a word repeats after removing hyphens");
assert!(EFF_WORDS.iter().all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase())));
}
#[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_776f64.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_776f64.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 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);
}
/// 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}");
}
+15
View File
@@ -0,0 +1,15 @@
# Word lists: sources and licences
| File | Used for | Source | Licence |
|:--|:--|:--|:--|
| `eff_large_wordlist.txt` | Memorable passwords (7,776 words, 12.925 bits each) | 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. |
| `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
- The EFF list file is kept as published. Four of its words contain a hyphen (`drop-down`, `felt-tip`,
`t-shirt`, `yo-yo`); the generator removes the hyphen so every word is plain letters (`dropdown`, …).
`yoyo` is already in the list, so `yo-yo` becomes `yoyos` instead. All 7,776 words stay distinct (tested),
so each word is still worth log2(7,776) bits.
- 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.
@@ -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
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
+19
View File
@@ -0,0 +1,19 @@
[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
[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)
}
+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)
}
+232
View File
@@ -0,0 +1,232 @@
//! 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 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("{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 })
}
/// 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)
}
}
+204
View File
@@ -0,0 +1,204 @@
//! 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"));
}
+182
View File
@@ -0,0 +1,182 @@
# 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) |
## 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.
+50
View File
@@ -0,0 +1,50 @@
# 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. |
| 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.
- **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).
## 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"