[core] Vault and generators: Argon2id key slot + XChaCha20-Poly1305 file, atomic save, item templates, memorable/nickname/random/PIN/strict generators

This commit is contained in:
2026-10-31 10:12:57 +01:00
parent 42ddcf0287
commit eb710c3135
21 changed files with 9710 additions and 4 deletions
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() }
}
+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)
}
}
+4 -3
View File
@@ -67,7 +67,7 @@ with "unsupported KDF parameters", before any work:
| Parameter | Allowed | Default written by Custos | | Parameter | Allowed | Default written by Custos |
|:--|:--|:--| |:--|:--|:--|
| m_cost | 8·p ..= 2 097 152 KiB (2 GiB) | 65 536 KiB (64 MiB) | | m_cost | 8·p ..= 2 097 152 KiB (2 GiB) | 65 536 KiB (64 MiB) |
| t_cost | 1 ..= 64 | 3 (measured ≈ 0.5–1 s on the dev machine, see `custos-vault` `KdfParams::DEFAULT`) | | 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 | | p_cost | 1 ..= 16 | 1 |
The parameters are stored per file, so a later version can raise the defaults; a vault keeps its The parameters are stored per file, so a later version can raise the defaults; a vault keeps its
@@ -169,8 +169,9 @@ become *protected* strings.
1. The new bytes go to `<name>.custos.tmp` in the same folder; the file is flushed with `fsync`. 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 2. If `<name>.custos` exists, it is copied to `<name>.custos.bak.tmp`, flushed, and renamed over
`<name>.custos.bak`. `<name>.custos.bak`.
3. `<name>.custos.tmp` is renamed over `<name>.custos` (`MoveFileEx` with `REPLACE_EXISTING` on Windows, 3. `<name>.custos.tmp` is renamed over `<name>.custos` (`std::fs::rename`, which replaces the target; on
`rename` on Unix, then the folder is flushed on Unix). 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 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. and an identical `.bak`. Leftover `.tmp` files are ignored and overwritten by the next save.
+1 -1
View File
@@ -14,7 +14,7 @@ just as plainly, what it does not.
| Attacker | Has | Gets | Why | | 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. | | 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, 3 passes by default) 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.** | | 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. | | 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`. | | Someone who crashes the machine mid-save | — | Nothing | Atomic save: temp file, fsync, rename; the previous version is kept as `.bak`. |
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"