[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
+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() }
}