Compare commits

...

8 Commits

21 changed files with 8177 additions and 74 deletions
+2
View File
@@ -8,6 +8,8 @@ The Windows app lives in the private `Custos` repo and depends on this one by gi
``` ```
crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, item model, SecretString crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, item model, SecretString
crates/custos-gen memorable password, nickname, random, PIN, strict-site generators + wordlists crates/custos-gen memorable password, nickname, random, PIN, strict-site generators + wordlists
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
docs/FORMAT.md the vault file format (versioned; change it before the code) docs/FORMAT.md the vault file format (versioned; change it before the code)
docs/THREAT_MODEL.md what is and is not protected docs/THREAT_MODEL.md what is and is not protected
``` ```
Generated
+80 -2
View File
@@ -111,6 +111,12 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.3.1" version = "0.3.1"
@@ -142,7 +148,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-gen" name = "custos-gen"
version = "0.1.0" version = "0.2.1"
dependencies = [ dependencies = [
"custos-vault", "custos-vault",
"rand", "rand",
@@ -151,20 +157,45 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "custos-qr"
version = "0.2.1"
[[package]]
name = "custos-totp"
version = "0.2.1"
dependencies = [
"custos-vault",
"data-encoding",
"hmac",
"percent-encoding",
"sha1",
"sha2",
"zeroize",
]
[[package]] [[package]]
name = "custos-vault" name = "custos-vault"
version = "0.1.0" version = "0.2.1"
dependencies = [ dependencies = [
"argon2", "argon2",
"chacha20poly1305", "chacha20poly1305",
"hkdf",
"rand", "rand",
"serde", "serde",
"serde_json", "serde_json",
"sha2",
"tempfile", "tempfile",
"thiserror", "thiserror",
"zeroize", "zeroize",
] ]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.11.3" version = "0.11.3"
@@ -172,6 +203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [ dependencies = [
"block-buffer", "block-buffer",
"const-oid",
"crypto-common", "crypto-common",
"ctutils", "ctutils",
] ]
@@ -204,6 +236,24 @@ dependencies = [
"rand_core", "rand_core",
] ]
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]] [[package]]
name = "hybrid-array" name = "hybrid-array"
version = "0.4.15" version = "0.4.15"
@@ -261,6 +311,12 @@ dependencies = [
"phc", "phc",
] ]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]] [[package]]
name = "phc" name = "phc"
version = "0.6.1" version = "0.6.1"
@@ -407,6 +463,28 @@ dependencies = [
"zmij", "zmij",
] ]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.119" version = "2.0.119"
+7 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.2.1"
edition = "2024" edition = "2024"
license = "MPL-2.0" license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
@@ -17,3 +17,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
thiserror = "2" thiserror = "2"
unicode-normalization = "0.1" unicode-normalization = "0.1"
hmac = "0.13"
sha1 = "0.11"
sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
+3 -1
View File
@@ -7,6 +7,8 @@ password and secret manager: everything that touches plaintext or keys.
|:--|:--| |:--|:--|
| `custos-vault` | The `.custos` file: Argon2id → key slot → XChaCha20-Poly1305, atomic save, typed items | | `custos-vault` | The `.custos` file: Argon2id → key slot → XChaCha20-Poly1305, atomic save, typed items |
| `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site | | `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site |
| `custos-totp` | TOTP (RFC 6238) and HOTP (RFC 4226), `otpauth://` URIs |
| `custos-qr` | QR payloads: Wi-Fi join codes (escaped), plain secrets |
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md) Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md). for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
@@ -15,4 +17,4 @@ for what it does and does not protect. Report vulnerabilities as described in [`
cargo test --workspace cargo test --workspace
``` ```
Licence: MPL-2.0. The EFF wordlist is CC BY 3.0 US (see `crates/custos-gen/wordlists/SOURCES.md`). Licence: MPL-2.0. The memorable-password words come from the EFF wordlist (CC BY 3.0 US), filtered with the ESDB/SCOWL English dictionary (see `crates/custos-gen/wordlists/SOURCES.md`).
+77 -44
View File
@@ -48,23 +48,16 @@ const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// ---------- word lists ---------- // ---------- 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> { fn plain_list(text: &'static str) -> Vec<&'static str> {
text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect() text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect()
} }
/// The words of memorable passwords (7,322): the EFF large wordlist without the words a standard US
/// English spellchecker dictionary does not know (brand names, names, coinages, hyphenated words).
/// See `wordlists/SOURCES.md`.
pub static MEMORABLE_WORDS: LazyLock<Vec<&str>> =
LazyLock::new(|| plain_list(include_str!("../wordlists/memorable.txt")));
static NOUNS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/nouns.txt"))); static 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 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"))); static VERBS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/verbs.txt")));
@@ -144,7 +137,7 @@ pub const MAX_WORDS: u8 = 10;
/// Bits of entropy of a memorable password with these options. /// Bits of entropy of a memorable password with these options.
pub fn memorable_entropy(o: &MemorableOptions) -> f64 { pub fn memorable_entropy(o: &MemorableOptions) -> f64 {
let n = o.words.clamp(MIN_WORDS, MAX_WORDS) as 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 }; let per_word = (MEMORABLE_WORDS.len() as f64).log2() + if o.digit_after_word { 10f64.log2() } else { 0.0 };
n * per_word + (n - 1.0) * (o.separator.choices().len() as f64).log2() n * per_word + (n - 1.0) * (o.separator.choices().len() as f64).log2()
} }
@@ -157,7 +150,7 @@ pub fn memorable(o: &MemorableOptions) -> Generated {
if i > 0 { if i > 0 {
out.push(pick(&seps)); out.push(pick(&seps));
} }
let w = &EFF_WORDS[rng().random_range(0..EFF_WORDS.len())]; let w = pick(&MEMORABLE_WORDS);
if o.capitalize { if o.capitalize {
out.push_str(&capitalize(w)); out.push_str(&capitalize(w));
} else { } else {
@@ -284,13 +277,61 @@ fn leetify(w: &str) -> String {
.collect::<String>() .collect::<String>()
} }
/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}` /// The random parts of a nickname, drawn once. The title can keep changing afterwards: [`render`]
/// is left out together with the literal separator next to it. /// fills it in without drawing new words or numbers (a new web login's nickname follows its title as
pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError> { /// it is typed).
let mut tokens = parse_template(&o.template)?; ///
/// [`render`]: NicknameParts::render
#[derive(Clone, Debug)]
pub struct NicknameParts {
/// One per `{Word}` in the template, capitalised (and leetified if asked).
pub words: Vec<String>,
/// One per `{Number}` in the template.
pub numbers: Vec<String>,
pub entropy_bits: f64,
}
fn word_pool(kinds: &[WordKind]) -> Vec<&'static str> {
let mut pool: Vec<&'static str> = kinds.iter().flat_map(|k| words(*k).iter().copied()).collect();
// Overlapping lists: count each word once, so the entropy stays honest.
pool.sort_unstable();
pool.dedup();
pool
}
/// Draws the words and numbers for `o.template`.
pub fn nickname_parts(o: &NicknameOptions) -> Result<NicknameParts, GenError> {
let tokens = parse_template(&o.template)?;
if !(1..=4).contains(&o.digits) { if !(1..=4).contains(&o.digits) {
return fail("the number must have 1 to 4 digits"); return fail("the number must have 1 to 4 digits");
} }
let pool = word_pool(&o.kinds);
let mut parts = NicknameParts { words: Vec::new(), numbers: Vec::new(), entropy_bits: 0.0 };
for t in &tokens {
match t {
Token::Word => {
if pool.is_empty() {
return fail("choose at least one kind of word");
}
let w = capitalize(pick(&pool));
parts.words.push(if o.leet { leetify(&w) } else { w });
parts.entropy_bits += (pool.len() as f64).log2();
}
Token::Number => {
parts.numbers.push((0..o.digits).map(|_| digit()).collect());
parts.entropy_bits += o.digits as f64 * 10f64.log2();
}
Token::Literal(_) | Token::Name => {}
}
}
Ok(parts)
}
impl NicknameParts {
/// The nickname for `title`. With an empty (normalised) title, `{Name}` is left out together with
/// the literal separator next to it. `template` must be the one the parts were drawn for.
pub fn render(&self, title: &str, template: &str) -> Result<String, GenError> {
let mut tokens = parse_template(template)?;
let name = normalize_name(title); let name = normalize_name(title);
if name.is_empty() { if name.is_empty() {
while let Some(i) = tokens.iter().position(|t| *t == Token::Name) { while let Some(i) = tokens.iter().position(|t| *t == Token::Name) {
@@ -304,39 +345,31 @@ pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError>
} }
} }
} }
let mut pool: Vec<&str> = Vec::new(); let (mut words, mut numbers) = (self.words.iter(), self.numbers.iter());
for k in &o.kinds { let mismatch = || GenError("the template changed since its words were drawn".into());
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 out = String::new();
let mut bits = 0.0;
for t in &tokens { for t in &tokens {
match t { match t {
Token::Literal(s) => out.push_str(s), Token::Literal(s) => out.push_str(s),
Token::Name => out.push_str(&name), Token::Name => out.push_str(&name),
Token::Word => { Token::Word => out.push_str(words.next().ok_or_else(mismatch)?),
let w = capitalize(pick(&pool)); Token::Number => out.push_str(numbers.next().ok_or_else(mismatch)?),
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(out)
} }
Ok(Generated { value: SecretString::new(out), entropy_bits: bits }) }
/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}`
/// is left out together with the literal separator next to it.
pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError> {
let parts = nickname_parts(o)?;
let value = parts.render(title, &o.template)?;
Ok(Generated { value: SecretString::new(value), entropy_bits: parts.entropy_bits })
} }
// ---------- random, strict site, PIN ---------- // ---------- random, strict site, PIN ----------
// Only English letters A–Z/a–z, digits 0–9 and ASCII symbols: every keyboard layout can type them.
pub const RANDOM_SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/~"; pub const RANDOM_SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/~";
pub const LOOKALIKES: &str = "Il1O0o|"; pub const LOOKALIKES: &str = "Il1O0o|";
@@ -413,7 +446,8 @@ pub struct StrictOptions {
pub upper: ClassRule, pub upper: ClassRule,
pub digits: ClassRule, pub digits: ClassRule,
pub symbols: ClassRule, pub symbols: ClassRule,
/// The symbols the site accepts. /// The symbols the site accepts. Only ASCII symbols count: letters, digits, spaces and anything
/// outside ASCII (`€`, `§`, `ž`) are ignored.
pub allowed_symbols: String, pub allowed_symbols: String,
} }
@@ -432,8 +466,7 @@ impl Default for StrictOptions {
pub fn strict(o: &StrictOptions) -> Result<Generated, GenError> { pub fn strict(o: &StrictOptions) -> Result<Generated, GenError> {
let len = check_length(o.length)?; let len = check_length(o.length)?;
let mut symbols: Vec<char> = let mut symbols: Vec<char> = o.allowed_symbols.chars().filter(char::is_ascii_punctuation).collect();
o.allowed_symbols.chars().filter(|c| !c.is_alphanumeric() && !c.is_whitespace()).collect();
symbols.sort_unstable(); symbols.sort_unstable();
symbols.dedup(); symbols.dedup();
let rules = [ let rules = [
+52 -9
View File
@@ -1,8 +1,8 @@
//! The mandatory generator tests (CLAUDE.md). //! The mandatory generator tests (CLAUDE.md).
use custos_gen::{ use custos_gen::{
ClassRule, EFF_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions, WordKind, ClassRule, MAX_LENGTH, MEMORABLE_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions,
memorable, memorable_entropy, nickname, normalize_name, pin, random, strict, WordKind, memorable, memorable_entropy, nickname, nickname_parts, normalize_name, pin, random, strict,
}; };
use regex::Regex; use regex::Regex;
use std::collections::HashSet; use std::collections::HashSet;
@@ -10,11 +10,24 @@ use std::collections::HashSet;
const SAMPLES: usize = 10_000; const SAMPLES: usize = 10_000;
#[test] #[test]
fn eff_list_is_complete_and_plain() { fn memorable_words_are_real_english_words() {
assert_eq!(EFF_WORDS.len(), 7_776); assert_eq!(MEMORABLE_WORDS.len(), 7_322);
let unique: HashSet<_> = EFF_WORDS.iter().collect(); let unique: HashSet<_> = MEMORABLE_WORDS.iter().collect();
assert_eq!(unique.len(), 7_776, "a word repeats after removing hyphens"); assert_eq!(unique.len(), 7_322);
assert!(EFF_WORDS.iter().all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase()))); assert!(MEMORABLE_WORDS.iter().all(|w| w.len() >= 3 && w.bytes().all(|b| b.is_ascii_lowercase())));
// Every word comes from the EFF list...
let eff: HashSet<&str> = include_str!("../wordlists/eff_large_wordlist.txt")
.lines()
.filter_map(|l| l.split('\t').nth(1))
.map(str::trim)
.collect();
assert!(MEMORABLE_WORDS.iter().all(|w| eff.contains(w)));
// ...minus brand names, names, coinages and hyphenated words that no dictionary lists.
for not_a_word in ["walmart", "iphone", "skype", "myspace", "monday", "december", "pranker", "finlike", "felt-tip"]
{
assert!(eff.contains(not_a_word), "{not_a_word} is not in the EFF list any more");
assert!(!MEMORABLE_WORDS.contains(&not_a_word), "{not_a_word}");
}
} }
#[test] #[test]
@@ -57,7 +70,7 @@ fn memorable_shape_at_every_slider_value_and_option() {
#[test] #[test]
fn memorable_entropy_counts_only_random_choices() { fn memorable_entropy_counts_only_random_choices() {
let per_word = 7_776f64.log2() + 10f64.log2(); let per_word = 7_322f64.log2() + 10f64.log2();
for words in 3..=10u8 { for words in 3..=10u8 {
let o = MemorableOptions { words, ..Default::default() }; let o = MemorableOptions { words, ..Default::default() };
let e = memorable_entropy(&o); let e = memorable_entropy(&o);
@@ -70,7 +83,7 @@ fn memorable_entropy_counts_only_random_choices() {
let four = memorable_entropy(&MemorableOptions::default()); let four = memorable_entropy(&MemorableOptions::default());
assert!((64.0..66.0).contains(&four), "4 words with digits is about 65 bits: {four}"); 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() }; let no_digits = MemorableOptions { digit_after_word: false, ..Default::default() };
assert!((memorable_entropy(&no_digits) - 4.0 * 7_776f64.log2()).abs() < 1e-9); assert!((memorable_entropy(&no_digits) - 4.0 * 7_322f64.log2()).abs() < 1e-9);
// A random-digit separator is a random choice per gap. // A random-digit separator is a random choice per gap.
let digit_sep = MemorableOptions { separator: Separator::Digit, ..Default::default() }; let digit_sep = MemorableOptions { separator: Separator::Digit, ..Default::default() };
assert!((memorable_entropy(&digit_sep) - (four + 3.0 * 10f64.log2())).abs() < 1e-9); assert!((memorable_entropy(&digit_sep) - (four + 3.0 * 10f64.log2())).abs() < 1e-9);
@@ -140,6 +153,18 @@ fn nickname_options_and_entropy() {
assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err()); assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err());
} }
#[test]
fn nickname_parts_keep_word_and_number_while_the_title_changes() {
let o = NicknameOptions::default();
let parts = nickname_parts(&o).unwrap();
let typed: Vec<String> = ["", "G", "Gi", "GitHub"].iter().map(|t| parts.render(t, &o.template).unwrap()).collect();
let tail = typed[0].clone(); // "Lantern.47": no title, so {Name} and its "." are left out
assert!(Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(&tail), "{tail}");
assert_eq!(typed[1], format!("G.{tail}"));
assert_eq!(typed[3], format!("GitHub.{tail}"));
assert!(parts.render("x", "{Word}{Word}").is_err(), "a template with more tokens than parts");
}
#[test] #[test]
fn name_normalisation() { fn name_normalisation() {
assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna"); assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna");
@@ -222,6 +247,24 @@ fn random_and_pin() {
assert!((p.entropy_bits - 6.0 * 10f64.log2()).abs() < 1e-9); assert!((p.entropy_bits - 6.0 * 10f64.log2()).abs() < 1e-9);
} }
#[test]
fn random_and_strict_use_only_english_letters_digits_and_ascii_symbols() {
let ok = |c: char| c.is_ascii_alphanumeric() || c.is_ascii_punctuation();
let all = RandomOptions { length: MAX_LENGTH, ..RandomOptions::default() };
for _ in 0..SAMPLES / 10 {
let s = random(&all).unwrap().value.expose().to_owned();
assert!(s.chars().all(ok), "{s}");
}
// Symbols the site lists outside ASCII, letters, digits and spaces are ignored.
let o = StrictOptions { length: 32, allowed_symbols: "€§ž é1!".into(), ..StrictOptions::default() };
for _ in 0..SAMPLES / 10 {
let s = strict(&o).unwrap().value.expose().to_owned();
assert!(s.chars().all(|c| c.is_ascii_alphanumeric() || c == '!'), "{s}");
}
let none_left = StrictOptions { allowed_symbols: "€§".into(), ..StrictOptions::default() };
assert!(strict(&none_left).is_err(), "required symbols, but none of the listed ones is ASCII");
}
/// Nicknames (≈ 30 000 combinations by design: they are names, not secrets) and short PINs are /// 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. /// excluded: their spaces are small enough that repeats in 10 000 draws are expected.
#[test] #[test]
+19 -5
View File
@@ -2,14 +2,28 @@
| File | Used for | Source | Licence | | 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. | | `eff_large_wordlist.txt` | The source of `memorable.txt` (kept as published) | Electronic Frontier Foundation, "Deep Dive: EFF's New Wordlists for Random Passphrases" (2016), downloaded unchanged from https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt (sha256 `addd35536511597a02fa0a9ff1e5284677b8883b83e986e43f15a3db996b903e`) | CC BY 3.0 US. Attribution: © Electronic Frontier Foundation. |
| `memorable.txt` | Memorable passwords (7,322 words, 12.838 bits each) | The EFF list minus every word that SCOWL/ESDB size 60, US spelling (the size of hunspell's `en_US` dictionary) does not list as a plain lowercase word. Made by `derive_memorable.py` from https://app.aspell.net/create?max_size=60&spelling=US&max_variant=0&diacritic=strip&download=wordlist&encoding=utf-8&format=inline (ESDB revision 1e5b7d3, 2026-06-24; sha256 of the download `bfbc258a6baaa50aec6fe07330b25b57cd90f3dd429345b8280df0414ccf242c`) | CC BY 3.0 US (© Electronic Frontier Foundation), and the ESDB notice below |
| `nouns.txt`, `adjectives.txt`, `verbs.txt` | Nicknames (`{Word}`) | Written for Custos Domi in 2026 by hand: common, family-friendly English words | CC0 1.0 (public domain dedication) | | `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 ## How they are used
- The EFF list file is kept as published. Four of its words contain a hyphen (`drop-down`, `felt-tip`, - Memorable passwords use only real English words. The EFF list has brand names (`walmart`, `iphone`,
`t-shirt`, `yo-yo`); the generator removes the hyphen so every word is plain letters (`dropdown`, …). `skype`), names (`monday`, `december`), coinages (`pranker`, `finlike`) and four hyphenated words
`yoyo` is already in the list, so `yo-yo` becomes `yoyos` instead. All 7,776 words stay distinct (tested), (`felt-tip`, …); a word stays only if the standard US spellchecker dictionary knows it. 454 words go,
so each word is still worth log2(7,776) bits. 7,322 stay (tested, with examples), so each word is worth log2(7,322) = 12.838 bits instead of 12.925.
- To rebuild `memorable.txt`, download the URL above and run `python derive_memorable.py <file>`.
- The nickname lists are not secret material: a nickname is a name, not a password. They are kept short, - 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. friendly and unique (tested), and each word has at least three letters.
## ESDB (SCOWL) notice
Copyright 2000-2026 by Kevin Atkinson
Permission to use, copy, modify, distribute, and sell any part of the English
Speller Database (ESDB, previously known as SCOWLv2), or word lists
created from it, is hereby granted without fee, provided that the above
copyright notice appears in all copies and that both the above copyright
notice and this notice appear in supporting documentation. Kevin Atkinson
makes no representations about the suitability of this database for any
purpose. It is provided "as is" without express or implied warranty.
@@ -0,0 +1,24 @@
"""Rebuilds memorable.txt: the EFF large wordlist minus every word that the standard US English
spellchecker dictionary (SCOWL/ESDB size 60, the size of hunspell's en_US) does not list as a plain
lowercase word. That removes brand names (walmart), names and capitalised words (monday) and coinages
(pranker). See SOURCES.md for the exact download.
python derive_memorable.py <scowl-size-60.txt>
"""
import sys
from pathlib import Path
here = Path(__file__).parent
scowl = Path(sys.argv[1]).read_text(encoding="utf-8")
dictionary = set(scowl.split("---", 1)[1].split())
eff = [line.split("\t")[1].strip() for line in (here / "eff_large_wordlist.txt").read_text().splitlines()]
kept = [w for w in eff if w in dictionary]
header = """\
# Memorable-password words: the EFF large wordlist (CC BY 3.0 US, (c) Electronic Frontier Foundation)
# minus the words not in SCOWL/ESDB size 60 (US). Word list (c) 2000-2026 by Kevin Atkinson, see SOURCES.md.
# Generated by derive_memorable.py; do not edit by hand.
"""
(here / "memorable.txt").write_text(header + "\n".join(kept) + "\n", encoding="utf-8", newline="\n")
print(f"kept {len(kept)} of {len(eff)}")
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "custos-qr"
description = "Custos QR payloads: Wi-Fi join codes and plain secrets (payload strings only, no rendering)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
+58
View File
@@ -0,0 +1,58 @@
//! QR payload strings. Rendering happens in the app; this crate only decides what the code says.
/// Security of a Wi-Fi network as the `WIFI:` payload names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WifiSecurity {
/// WPA, WPA2 or WPA3 (`T:WPA`).
Wpa,
Wep,
/// Open network (`T:nopass`).
None,
}
impl WifiSecurity {
/// From the vault's `security` field (`WPA`, `WEP`, `nopass`); anything else counts as WPA.
pub fn parse(s: &str) -> WifiSecurity {
match s.trim().to_ascii_uppercase().as_str() {
"WEP" => WifiSecurity::Wep,
"NOPASS" | "NONE" | "OPEN" => WifiSecurity::None,
_ => WifiSecurity::Wpa,
}
}
fn token(self) -> &'static str {
match self {
WifiSecurity::Wpa => "WPA",
WifiSecurity::Wep => "WEP",
WifiSecurity::None => "nopass",
}
}
}
/// Escapes `\`, `;`, `,`, `:` and `"` with a backslash, as the `WIFI:` format requires.
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '\\' | ';' | ',' | ':' | '"') {
out.push('\\');
}
out.push(c);
}
out
}
/// `WIFI:T:<WPA|WEP|nopass>;S:<ssid>;P:<password>;H:<true|false>;;` — a phone camera joins from it.
/// An open network gets no `P:` field.
pub fn wifi_payload(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> String {
let mut p = format!("WIFI:T:{};S:{};", security.token(), escape(ssid));
if security != WifiSecurity::None {
p.push_str(&format!("P:{};", escape(password)));
}
p.push_str(&format!("H:{hidden};;"));
p
}
/// A QR code that shows a secret to a phone camera is the plain value, so it can be typed elsewhere.
pub fn secret_payload(value: &str) -> String {
value.to_owned()
}
+72
View File
@@ -0,0 +1,72 @@
//! Wi-Fi QR payloads: every special character escaped, so a phone reads back exactly what was stored.
use custos_qr::{WifiSecurity, escape, secret_payload, wifi_payload};
/// What a reader does: split on unescaped `;`, undo `\x` escapes.
fn parse(payload: &str) -> Vec<(String, String)> {
let body = payload.strip_prefix("WIFI:").expect("prefix").strip_suffix(";;").expect("suffix");
let mut fields = Vec::new();
let mut cur = String::new();
let mut chars = body.chars();
while let Some(c) = chars.next() {
match c {
'\\' => cur.push(chars.next().expect("escape at end")),
';' => fields.push(std::mem::take(&mut cur)),
c => cur.push(c),
}
}
fields.push(cur);
fields
.into_iter()
.map(|f| {
let (k, v) = f.split_once(':').expect("key:value");
(k.to_owned(), v.to_owned())
})
.collect()
}
#[test]
fn escapes_every_special_character() {
assert_eq!(escape(r#"\;,:""#), r#"\\\;\,\:\""#);
assert_eq!(escape("plain-text_123 ok"), "plain-text_123 ok");
}
#[test]
fn ssid_and_password_with_every_special_character_survive() {
let nasty = r#"My\Net;5G,"home":x"#;
let pass = r#"p\a;s,s:w"o"r;d\"#;
let p = wifi_payload(nasty, pass, WifiSecurity::Wpa, true);
assert_eq!(p, r#"WIFI:T:WPA;S:My\\Net\;5G\,\"home\"\:x;P:p\\a\;s\,s\:w\"o\"r\;d\\;H:true;;"#);
let f = parse(&p);
assert_eq!(
f,
vec![
("T".into(), "WPA".into()),
("S".into(), nasty.into()),
("P".into(), pass.into()),
("H".into(), "true".into()),
]
);
}
#[test]
fn security_kinds_and_hidden_flag() {
assert_eq!(wifi_payload("Cafe", "secret", WifiSecurity::Wep, false), "WIFI:T:WEP;S:Cafe;P:secret;H:false;;");
// An open network has no password field.
assert_eq!(wifi_payload("Open", "ignored", WifiSecurity::None, false), "WIFI:T:nopass;S:Open;H:false;;");
assert_eq!(WifiSecurity::parse("WPA"), WifiSecurity::Wpa);
assert_eq!(WifiSecurity::parse("nopass"), WifiSecurity::None);
assert_eq!(WifiSecurity::parse("WEP"), WifiSecurity::Wep);
assert_eq!(WifiSecurity::parse("anything else"), WifiSecurity::Wpa);
}
#[test]
fn unicode_ssid_is_kept() {
let p = wifi_payload("Žluťoučký kůň 📶", "heslo", WifiSecurity::Wpa, false);
assert_eq!(parse(&p)[1].1, "Žluťoučký kůň 📶");
}
#[test]
fn secret_payload_is_the_value_itself() {
assert_eq!(secret_payload("sk-test;with:specials"), "sk-test;with:specials");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-totp"
description = "Custos TOTP (RFC 6238) and HOTP (RFC 4226), otpauth:// URIs"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
hmac.workspace = true
sha1.workspace = true
sha2.workspace = true
data-encoding.workspace = true
percent-encoding.workspace = true
zeroize.workspace = true
+221
View File
@@ -0,0 +1,221 @@
//! TOTP (RFC 6238) and HOTP (RFC 4226) on RustCrypto's HMAC, and `otpauth://` URIs.
//!
//! ```
//! use custos_totp::Totp;
//! let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub")?;
//! assert_eq!(t.code_at(1_700_000_000).len(), 6);
//! # Ok::<(), custos_totp::TotpError>(())
//! ```
use data_encoding::BASE32_NOPAD;
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use std::fmt;
use zeroize::Zeroizing;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Algorithm {
Sha1,
Sha256,
Sha512,
}
impl Algorithm {
fn name(self) -> &'static str {
match self {
Algorithm::Sha1 => "SHA1",
Algorithm::Sha256 => "SHA256",
Algorithm::Sha512 => "SHA512",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotpError(String);
impl fmt::Display for TotpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for TotpError {}
fn err<T>(msg: &str) -> Result<T, TotpError> {
Err(TotpError(msg.into()))
}
fn mac(alg: Algorithm, key: &[u8], msg: &[u8]) -> Vec<u8> {
// HMAC accepts keys of any length; `new_from_slice` cannot fail for it.
match alg {
Algorithm::Sha1 => {
let mut m = <Hmac<sha1::Sha1> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha256 => {
let mut m = <Hmac<sha2::Sha256> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha512 => {
let mut m = <Hmac<sha2::Sha512> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
}
}
/// RFC 4226: HMAC of the 8-byte big-endian counter, dynamic truncation, `digits` decimal digits.
pub fn hotp(secret: &[u8], counter: u64, digits: u32, alg: Algorithm) -> String {
let h = mac(alg, secret, &counter.to_be_bytes());
let off = (h[h.len() - 1] & 0x0f) as usize;
let bin = u32::from_be_bytes([h[off] & 0x7f, h[off + 1], h[off + 2], h[off + 3]]);
format!("{:0width$}", bin % 10u32.pow(digits), width = digits as usize)
}
/// A TOTP generator. The secret is wiped on drop and never printed.
#[derive(Clone)]
pub struct Totp {
secret: Zeroizing<Vec<u8>>,
algorithm: Algorithm,
digits: u32,
period: u64,
issuer: Option<String>,
account: Option<String>,
}
impl fmt::Debug for Totp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Totp")
.field("secret", &"[redacted]")
.field("algorithm", &self.algorithm)
.field("digits", &self.digits)
.field("period", &self.period)
.field("issuer", &self.issuer)
.finish_non_exhaustive()
}
}
fn decode_base32(s: &str) -> Result<Zeroizing<Vec<u8>>, TotpError> {
let clean: Zeroizing<String> = Zeroizing::new(
s.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '=').collect::<String>().to_uppercase(),
);
if clean.is_empty() {
return err("the 2FA secret is empty");
}
BASE32_NOPAD
.decode(clean.as_bytes())
.map(Zeroizing::new)
.map_err(|_| TotpError("the 2FA secret is not valid base32".into()))
}
impl Totp {
/// `digits` 6..=8, `period` in seconds (at least 1).
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, period: u64) -> Result<Totp, TotpError> {
if !(6..=8).contains(&digits) {
return err("a 2FA code has 6 to 8 digits");
}
if period == 0 {
return err("the 2FA period must be at least one second");
}
if secret.is_empty() {
return err("the 2FA secret is empty");
}
Ok(Totp { secret: Zeroizing::new(secret), algorithm, digits, period, issuer: None, account: None })
}
/// An `otpauth://totp/…` URI, or a bare base32 secret (spaces, lower case and `=` are fine).
pub fn parse(input: &str) -> Result<Totp, TotpError> {
let input = input.trim();
let Some(rest) = input.strip_prefix("otpauth://") else {
return Totp::new(decode_base32(input)?.to_vec(), Algorithm::Sha1, 6, 30);
};
let Some(rest) = rest.strip_prefix("totp/") else {
return err("only time-based codes (otpauth://totp) are supported");
};
let (label, query) = rest.split_once('?').unwrap_or((rest, ""));
let label = percent_decode_str(label).decode_utf8_lossy().into_owned();
let (mut issuer, account) = match label.split_once(':') {
Some((i, a)) => (Some(i.trim().to_owned()), Some(a.trim().to_owned())),
None if label.is_empty() => (None, None),
None => (None, Some(label.trim().to_owned())),
};
let (mut secret, mut alg, mut digits, mut period) = (None, Algorithm::Sha1, 6u32, 30u64);
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let v = Zeroizing::new(percent_decode_str(v).decode_utf8_lossy().into_owned());
match k.to_ascii_lowercase().as_str() {
"secret" => secret = Some(decode_base32(&v)?),
"issuer" => issuer = Some(v.to_string()),
"algorithm" => {
alg = match v.to_ascii_uppercase().as_str() {
"SHA1" => Algorithm::Sha1,
"SHA256" => Algorithm::Sha256,
"SHA512" => Algorithm::Sha512,
_ => return err("unsupported 2FA algorithm (use SHA1, SHA256 or SHA512)"),
}
}
"digits" => digits = v.parse().map_err(|_| TotpError("digits is not a number".into()))?,
"period" => period = v.parse().map_err(|_| TotpError("period is not a number".into()))?,
_ => {}
}
}
let secret = secret.ok_or_else(|| TotpError("the otpauth URI has no secret".into()))?;
let mut t = Totp::new(secret.to_vec(), alg, digits, period)?;
t.issuer = issuer.filter(|s| !s.is_empty());
t.account = account.filter(|s| !s.is_empty());
Ok(t)
}
/// The code for Unix time `unix_secs`.
pub fn code_at(&self, unix_secs: u64) -> String {
hotp(&self.secret, unix_secs / self.period, self.digits, self.algorithm)
}
/// Seconds until the code at `unix_secs` changes (1..=period).
pub fn seconds_left(&self, unix_secs: u64) -> u64 {
self.period - unix_secs % self.period
}
pub fn to_uri(&self) -> String {
let enc = |s: &str| utf8_percent_encode(s, NON_ALPHANUMERIC).to_string();
let label = match (&self.issuer, &self.account) {
(Some(i), Some(a)) => format!("{}:{}", enc(i), enc(a)),
(None, Some(a)) => enc(a),
(Some(i), None) => enc(i),
(None, None) => String::new(),
};
let mut uri = format!(
"otpauth://totp/{label}?secret={}&algorithm={}&digits={}&period={}",
BASE32_NOPAD.encode(&self.secret),
self.algorithm.name(),
self.digits,
self.period
);
if let Some(i) = &self.issuer {
uri.push_str(&format!("&issuer={}", enc(i)));
}
uri
}
pub fn issuer(&self) -> Option<&str> {
self.issuer.as_deref()
}
pub fn account(&self) -> Option<&str> {
self.account.as_deref()
}
pub fn digits(&self) -> u32 {
self.digits
}
pub fn period(&self) -> u64 {
self.period
}
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
}
+93
View File
@@ -0,0 +1,93 @@
//! RFC 6238 Appendix B and RFC 4226 Appendix D test vectors, exactly as published, plus otpauth parsing.
use custos_totp::{Algorithm, Totp, hotp};
const SEED_SHA1: &[u8] = b"12345678901234567890";
const SEED_SHA256: &[u8] = b"12345678901234567890123456789012";
const SEED_SHA512: &[u8] = b"1234567890123456789012345678901234567890123456789012345678901234";
#[test]
fn rfc6238_appendix_b() {
// Time (s), SHA1, SHA256, SHA512 — 8 digits, period 30, T0 = 0.
let table: [(u64, &str, &str, &str); 6] = [
(59, "94287082", "46119246", "90693936"),
(1111111109, "07081804", "68084774", "25091201"),
(1111111111, "14050471", "67062674", "99943326"),
(1234567890, "89005924", "91819424", "93441116"),
(2000000000, "69279037", "90698825", "38618901"),
(20000000000, "65353130", "77737706", "47863826"),
];
for (t, sha1, sha256, sha512) in table {
for (seed, alg, want) in [
(SEED_SHA1, Algorithm::Sha1, sha1),
(SEED_SHA256, Algorithm::Sha256, sha256),
(SEED_SHA512, Algorithm::Sha512, sha512),
] {
let totp = Totp::new(seed.to_vec(), alg, 8, 30).unwrap();
assert_eq!(totp.code_at(t), want, "T={t} {alg:?}");
}
}
}
#[test]
fn rfc4226_appendix_d() {
let want = ["755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489"];
for (counter, code) in want.iter().enumerate() {
assert_eq!(hotp(SEED_SHA1, counter as u64, 6, Algorithm::Sha1), *code, "counter {counter}");
}
}
#[test]
fn otpauth_uri_and_base32() {
// "12345678901234567890" in base32.
let b32 = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
let t = Totp::parse(&format!(
"otpauth://totp/Example%20Co:alice%40example.com?secret={b32}&issuer=Example%20Co&algorithm=SHA1&digits=8&period=30"
))
.unwrap();
assert_eq!(t.code_at(59), "94287082");
assert_eq!(t.issuer(), Some("Example Co"));
assert_eq!(t.account(), Some("alice@example.com"));
assert_eq!((t.digits(), t.period(), t.algorithm()), (8, 30, Algorithm::Sha1));
// Defaults: SHA1, 6 digits, 30 s. A bare secret (lower case, spaces, padding) works too.
let bare = Totp::parse("gezd gnbv gy3t qojq gezd gnbv gy3t qojq").unwrap();
assert_eq!(bare.code_at(59), "287082");
assert_eq!((bare.digits(), bare.period()), (6, 30));
assert_eq!(Totp::parse(&format!("{b32}====")).unwrap().code_at(59), "287082");
let sha256 = Totp::parse(
"otpauth://totp/x?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&algorithm=SHA256&digits=8",
)
.unwrap();
assert_eq!(sha256.code_at(59), "46119246");
for bad in [
"otpauth://hotp/x?secret=GEZDGNBV&counter=1",
"otpauth://totp/x?digits=6",
"otpauth://totp/x?secret=not*base32",
"otpauth://totp/x?secret=GEZDGNBV&digits=9",
"otpauth://totp/x?secret=GEZDGNBV&period=0",
"otpauth://totp/x?secret=GEZDGNBV&algorithm=MD5",
"",
] {
assert!(Totp::parse(bad).is_err(), "{bad} was accepted");
}
}
#[test]
fn round_trip_through_uri_and_countdown() {
let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub").unwrap();
let back = Totp::parse(&t.to_uri()).unwrap();
assert_eq!(back.code_at(1_700_000_000), t.code_at(1_700_000_000));
assert_eq!(back.issuer(), Some("GitHub"));
assert_eq!(t.seconds_left(1_700_000_000), 30 - 1_700_000_000 % 30);
assert_eq!(t.seconds_left(60), 30);
}
#[test]
fn secret_is_redacted_in_debug() {
let t = Totp::parse("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP").unwrap();
let out = format!("{t:?}");
assert!(!out.contains("JBSWY3DPEHPK3PXP") && !out.contains("72, 101") && out.contains("[redacted]"), "{out}");
}
+2
View File
@@ -14,6 +14,8 @@ rand.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
thiserror.workspace = true thiserror.workspace = true
hkdf.workspace = true
sha2.workspace = true
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
+45
View File
@@ -0,0 +1,45 @@
//! Device unlock (docs/FORMAT.md, "Device key wrap"): the vault key wrapped with a key derived from
//! material only this device can produce (the desktop app uses a Windows Hello signature). The blob is
//! kept on that device, never in the vault file.
use crate::Error;
use crate::crypto::{self, KEY_LEN, NONCE_LEN, TAG_LEN};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"CDW1";
const SALT_LEN: usize = 32;
const INFO: &[u8] = b"custos device wrap v1";
pub const BLOB_LEN: usize = 4 + SALT_LEN + NONCE_LEN + KEY_LEN + TAG_LEN;
fn kek(material: &[u8], salt: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), material).expand(INFO, k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
/// `CDW1 ‖ salt ‖ nonce ‖ XChaCha20-Poly1305(HKDF-SHA256(material, salt), vault key, aad = CDW1 ‖ salt ‖ nonce)`.
pub fn wrap(key: &[u8; KEY_LEN], material: &[u8]) -> Vec<u8> {
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let nonce = crypto::random_nonce();
let mut blob = Vec::with_capacity(BLOB_LEN);
blob.extend_from_slice(MAGIC);
blob.extend_from_slice(&salt);
blob.extend_from_slice(&nonce);
let sealed = crypto::seal(&kek(material, &salt), &nonce, key, &blob);
blob.extend_from_slice(&sealed);
blob
}
pub fn unwrap(blob: &[u8], material: &[u8]) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
if blob.len() != BLOB_LEN || &blob[..4] != MAGIC {
return Err(Error::DeviceKeyRejected);
}
let salt = &blob[4..4 + SALT_LEN];
let nonce: [u8; NONCE_LEN] = blob[4 + SALT_LEN..4 + SALT_LEN + NONCE_LEN].try_into().unwrap();
let head = 4 + SALT_LEN + NONCE_LEN;
let k = crypto::open(&kek(material, salt), &nonce, &blob[head..], &blob[..head]).ok_or(Error::DeviceKeyRejected)?;
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::DeviceKeyRejected)?))
}
+17
View File
@@ -12,6 +12,7 @@
//! ``` //! ```
mod crypto; mod crypto;
mod device;
mod format; mod format;
mod item; mod item;
mod save; mod save;
@@ -42,6 +43,8 @@ pub enum Error {
WrongPassword, WrongPassword,
#[error("the vault file was changed or damaged after it was written")] #[error("the vault file was changed or damaged after it was written")]
Corrupted, Corrupted,
#[error("this device's unlock key no longer opens the vault; use the master password")]
DeviceKeyRejected,
#[error("{0}")] #[error("{0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
} }
@@ -160,6 +163,20 @@ impl Vault {
Ok(Vault { key, slots: header.slots, items: body.items }) Ok(Vault { key, slots: header.slots, items: body.items })
} }
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
/// Windows Hello signature). Keep the blob on the device; see docs/FORMAT.md, "Device key wrap".
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
Ok(device::wrap(&self.key, material))
}
/// Unlocks with a device blob instead of the password. Fails with `DeviceKeyRejected` when the
/// material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
let key = device::unwrap(blob, material)?;
Vault::open_body(bytes, header, body_at, key)
}
/// The encrypted file contents, with a fresh body nonce. /// The encrypted file contents, with a fresh body nonce.
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> { pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
let body_nonce = crypto::random_nonce(); let body_nonce = crypto::random_nonce();
+24
View File
@@ -202,3 +202,27 @@ fn no_secret_in_debug_or_display() {
// Non-secret fields stay readable in Debug, which is what makes it useful. // Non-secret fields stay readable in Debug, which is what makes it useful.
assert!(format!("{item:?}").contains("Example")); assert!(format!("{item:?}").contains("Example"));
} }
#[test]
fn device_wrap_opens_the_same_vault_and_nothing_else() {
// Windows Hello gives the desktop app a signature; the core turns it into a key wrap.
let v = sample_vault("pw");
let bytes = v.to_bytes().unwrap();
let material = b"signature bytes from the device key";
let blob = v.wrap_for_device(material).unwrap();
assert_ne!(v.wrap_for_device(material).unwrap(), blob, "fresh salt and nonce each time");
let back = Vault::open_with_device(&bytes, &blob, material).unwrap();
assert_eq!(back.items(), v.items());
assert!(matches!(Vault::open_with_device(&bytes, &blob, b"other signature"), Err(Error::DeviceKeyRejected)));
for i in 0..blob.len() {
let mut t = blob.clone();
t[i] ^= 1;
assert!(Vault::open_with_device(&bytes, &t, material).is_err(), "blob byte {i}");
}
// A blob made for another vault does not open this one.
let other = sample_vault("pw").wrap_for_device(material).unwrap();
assert!(Vault::open_with_device(&bytes, &other, material).is_err());
assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature"));
}
+16
View File
@@ -162,6 +162,22 @@ become *protected* strings.
| `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` | | `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` |
| `history` entries | `History` entries (one per change, with that old password) | | `history` entries | `History` entries (one per change, with that old password) |
## Device key wrap (not part of the file)
Quick unlock on one machine (the desktop app uses Windows Hello) keeps a separate 108-byte blob **on that
machine**, never in the vault file:
```
"CDW1" (4) ‖ salt (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(KEK, vault key, aad = "CDW1" ‖ salt ‖ nonce) (48)
KEK = HKDF-SHA256(ikm = device material, salt, info = "custos device wrap v1")
```
The device material is something only that device can produce on request (for Windows Hello: the RSA
signature of a fixed challenge by a TPM-held key, which only Hello can unlock). A wrong material or a
changed blob gives `DeviceKeyRejected`; a blob from another vault unwraps a key that fails the body tag
(`Corrupted`). Changing the master password does not change the vault key, so the app deletes the blob
itself when the password changes.
## Saving ## Saving
`custos-vault::save_atomic` never leaves a half-written vault in place of the old one: `custos-vault::save_atomic` never leaves a half-written vault in place of the old one:
+3
View File
@@ -31,6 +31,9 @@ just as plainly, what it does not.
desktop app), and by any clipboard manager that ignores the "exclude from history" marker. 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 - **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. typing, but a window that steals focus at the wrong moment can receive them.
- **Device unlock (Windows Hello).** The blob on disk is only as strong as the device key behind it: anyone
who can make Windows Hello sign as you on that machine (your PIN, your face, or malware running while
you approve a prompt) can unlock the vault there. It does not help an attacker who has only the vault file.
- **Rollback.** Someone with write access to the synced file can replace it with an older version. - **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). 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 - **Shoulder surfing and QR codes.** A revealed password or a shown QR code is readable by anyone who