//! 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(msg: &str) -> Result { Err(GenError(msg.into())) } fn rng() -> UnwrapErr { UnwrapErr(SysRng) } fn pick(items: &[T]) -> T { items[rng().random_range(0..items.len())] } fn digit() -> char { pick(&DIGITS) } const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; // ---------- word lists ---------- fn plain_list(text: &'static str) -> Vec<&'static str> { text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect() } /// The words of memorable passwords (7,322): the EFF large wordlist without the words a standard US /// English spellchecker dictionary does not know (brand names, names, coinages, hyphenated words). /// See `wordlists/SOURCES.md`. pub static MEMORABLE_WORDS: LazyLock> = LazyLock::new(|| plain_list(include_str!("../wordlists/memorable.txt"))); static NOUNS: LazyLock> = LazyLock::new(|| plain_list(include_str!("../wordlists/nouns.txt"))); static ADJECTIVES: LazyLock> = LazyLock::new(|| plain_list(include_str!("../wordlists/adjectives.txt"))); static VERBS: LazyLock> = 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 { match self { Separator::Hyphen => vec!['-'], Separator::Space => vec![' '], Separator::Period => vec!['.'], Separator::Comma => vec![','], Separator::Underscore => vec!['_'], Separator::Digit => DIGITS.to_vec(), Separator::DigitOrSymbol => DIGITS.iter().copied().chain(SEPARATOR_SYMBOLS.chars()).collect(), } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MemorableOptions { /// 3..=10. pub words: u8, /// One random digit after every word. pub digit_after_word: bool, /// First letter of each word in capitals (adds no entropy). pub capitalize: bool, pub separator: Separator, } impl Default for MemorableOptions { fn default() -> Self { MemorableOptions { words: 4, digit_after_word: true, capitalize: true, separator: Separator::Hyphen } } } pub const MIN_WORDS: u8 = 3; pub const MAX_WORDS: u8 = 10; /// Bits of entropy of a memorable password with these options. pub fn memorable_entropy(o: &MemorableOptions) -> f64 { let n = o.words.clamp(MIN_WORDS, MAX_WORDS) as f64; let per_word = (MEMORABLE_WORDS.len() as f64).log2() + if o.digit_after_word { 10f64.log2() } else { 0.0 }; n * per_word + (n - 1.0) * (o.separator.choices().len() as f64).log2() } /// `Word7-Other3-Third9-Fourth2`. pub fn memorable(o: &MemorableOptions) -> Generated { let n = o.words.clamp(MIN_WORDS, MAX_WORDS); let seps = o.separator.choices(); let mut out = String::with_capacity(n as usize * 12); for i in 0..n { if i > 0 { out.push(pick(&seps)); } let w = pick(&MEMORABLE_WORDS); if o.capitalize { out.push_str(&capitalize(w)); } else { out.push_str(w); } if o.digit_after_word { out.push(digit()); } } Generated { value: SecretString::new(out), entropy_bits: memorable_entropy(o) } } // ---------- nickname ---------- #[derive(Clone, Debug, PartialEq, Eq)] pub struct NicknameOptions { /// Tokens `{Name}`, `{Word}`, `{Number}` and literal text, e.g. `{Name}.{Word}.{Number}`. pub template: String, /// Where `{Word}` comes from (their union). pub kinds: Vec, /// 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, 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 = 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::().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::() } /// The random parts of a nickname, drawn once. The title can keep changing afterwards: [`render`] /// fills it in without drawing new words or numbers (a new web login's nickname follows its title as /// it is typed). /// /// [`render`]: NicknameParts::render #[derive(Clone, Debug)] pub struct NicknameParts { /// One per `{Word}` in the template, capitalised (and leetified if asked). pub words: Vec, /// One per `{Number}` in the template. pub numbers: Vec, 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 { let tokens = parse_template(&o.template)?; if !(1..=4).contains(&o.digits) { return fail("the number must have 1 to 4 digits"); } let pool = word_pool(&o.kinds); let mut parts = NicknameParts { words: Vec::new(), numbers: Vec::new(), entropy_bits: 0.0 }; for t in &tokens { match t { Token::Word => { if pool.is_empty() { return fail("choose at least one kind of word"); } let w = capitalize(pick(&pool)); parts.words.push(if o.leet { leetify(&w) } else { w }); parts.entropy_bits += (pool.len() as f64).log2(); } Token::Number => { parts.numbers.push((0..o.digits).map(|_| digit()).collect()); parts.entropy_bits += o.digits as f64 * 10f64.log2(); } Token::Literal(_) | Token::Name => {} } } Ok(parts) } impl NicknameParts { /// The nickname for `title`. With an empty (normalised) title, `{Name}` is left out together with /// the literal separator next to it. `template` must be the one the parts were drawn for. pub fn render(&self, title: &str, template: &str) -> Result { let mut tokens = parse_template(template)?; let name = normalize_name(title); if name.is_empty() { while let Some(i) = tokens.iter().position(|t| *t == Token::Name) { tokens.remove(i); if i == 0 { if matches!(tokens.first(), Some(Token::Literal(_))) { tokens.remove(0); } } else if matches!(tokens.get(i - 1), Some(Token::Literal(_))) { tokens.remove(i - 1); } } } let (mut words, mut numbers) = (self.words.iter(), self.numbers.iter()); let mismatch = || GenError("the template changed since its words were drawn".into()); let mut out = String::new(); for t in &tokens { match t { Token::Literal(s) => out.push_str(s), Token::Name => out.push_str(&name), Token::Word => out.push_str(words.next().ok_or_else(mismatch)?), Token::Number => out.push_str(numbers.next().ok_or_else(mismatch)?), } } Ok(out) } } /// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}` /// is left out together with the literal separator next to it. pub fn nickname(title: &str, o: &NicknameOptions) -> Result { let parts = nickname_parts(o)?; let value = parts.render(title, &o.template)?; Ok(Generated { value: SecretString::new(value), entropy_bits: parts.entropy_bits }) } // ---------- random, strict site, PIN ---------- // Only English letters A–Z/a–z, digits 0–9 and ASCII symbols: every keyboard layout can type them. pub const RANDOM_SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/~"; pub const LOOKALIKES: &str = "Il1O0o|"; pub const MAX_LENGTH: u16 = 128; #[derive(Clone, Debug, PartialEq, Eq)] pub struct RandomOptions { pub length: u16, pub upper: bool, pub lower: bool, pub digits: bool, pub symbols: bool, pub exclude_lookalikes: bool, } impl Default for RandomOptions { fn default() -> Self { RandomOptions { length: 20, upper: true, lower: true, digits: true, symbols: true, exclude_lookalikes: false } } } fn class_chars(upper: bool, lower: bool, digits: bool, symbols: &str) -> Vec> { 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 { 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 { let len = check_length(o.length)?; let mut alphabet: Vec = class_chars(o.upper, o.lower, o.digits, if o.symbols { RANDOM_SYMBOLS } else { "" }).concat(); if o.exclude_lookalikes { alphabet.retain(|c| !LOOKALIKES.contains(*c)); } if alphabet.is_empty() { return fail("choose at least one kind of character"); } let value: String = (0..len).map(|_| pick(&alphabet)).collect(); Ok(Generated { value: SecretString::new(value), entropy_bits: len as f64 * (alphabet.len() as f64).log2() }) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ClassRule { Exclude, Allow, Require, } /// For sites with rules: exactly `length` characters (their maximum), only allowed classes, and at /// least one of each required class. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StrictOptions { pub length: u16, pub lower: ClassRule, pub upper: ClassRule, pub digits: ClassRule, pub symbols: ClassRule, /// The symbols the site accepts. Only ASCII symbols count: letters, digits, spaces and anything /// outside ASCII (`€`, `§`, `ž`) are ignored. pub allowed_symbols: String, } impl Default for StrictOptions { fn default() -> Self { StrictOptions { length: 16, lower: ClassRule::Require, upper: ClassRule::Require, digits: ClassRule::Require, symbols: ClassRule::Require, allowed_symbols: "!@#$%&*?-_".into(), } } } pub fn strict(o: &StrictOptions) -> Result { let len = check_length(o.length)?; let mut symbols: Vec = o.allowed_symbols.chars().filter(char::is_ascii_punctuation).collect(); symbols.sort_unstable(); symbols.dedup(); let rules = [ (o.lower, ('a'..='z').collect::>()), (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> = rules.iter().filter(|(r, s)| *r != ClassRule::Exclude && !s.is_empty()).map(|(_, s)| s).collect(); let required: Vec<&Vec> = 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 = 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 = (0..len).map(|_| pick(&alphabet)).collect(); if required.iter().all(|set| s.iter().any(|c| set.contains(c))) { break s.into_iter().collect::(); } }; // 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() } } // ---------- keys and API keys (docs/KEYS.md) ---------- /// How a secret key is written out. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum KeyEncoding { /// Lowercase hex. Hex, /// Base64url without padding. Base64Url, /// Standard base64 with padding. Base64, } /// `bytes` random bytes (16..=128), encoded: symmetric keys, HMAC and JWT secrets. pub fn secret_key(bytes: usize, encoding: KeyEncoding) -> Result { if !(16..=128).contains(&bytes) { return Err(GenError("a secret key is 16 to 128 bytes".into())); } let mut raw = zeroize::Zeroizing::new(vec![0u8; bytes]); rand::Rng::fill_bytes(&mut rng(), &mut raw); let value = match encoding { KeyEncoding::Hex => data_encoding::HEXLOWER.encode(&raw), KeyEncoding::Base64Url => data_encoding::BASE64URL_NOPAD.encode(&raw), KeyEncoding::Base64 => data_encoding::BASE64.encode(&raw), }; Ok(Generated { value: SecretString::new(value), entropy_bits: 8.0 * bytes as f64 }) } const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const API_KEY_RANDOM: usize = 32; /// CRC-32 (IEEE 802.3, reflected, as zlib computes it): the API key checksum. Not a security feature. fn crc32(data: &[u8]) -> u32 { let mut crc = !0u32; for &b in data { crc ^= b as u32; for _ in 0..8 { crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; } } !crc } fn checksum6(body: &str) -> String { let mut n = crc32(body.as_bytes()) as u64; let mut out = [b'0'; 6]; for c in out.iter_mut().rev() { *c = BASE62[(n % 62) as usize]; n /= 62; } String::from_utf8(out.to_vec()).expect("base62 is ASCII") } /// `_` + 32 uniform base62 characters (190.5 bits) + a 6-character CRC-32 checksum. /// The prefix is empty, or a lowercase letter and up to 15 lowercase letters or digits. pub fn api_key(prefix: &str) -> Result { let ok = prefix.is_empty() || (prefix.len() <= 16 && prefix.starts_with(|c: char| c.is_ascii_lowercase()) && prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())); if !ok { return Err(GenError("the prefix is a lowercase letter and up to 15 lowercase letters or digits".into())); } let mut body = if prefix.is_empty() { String::new() } else { format!("{prefix}_") }; for _ in 0..API_KEY_RANDOM { body.push(BASE62[rng().random_range(0..62)] as char); } let sum = checksum6(&body); body.push_str(&sum); Ok(Generated { value: SecretString::new(body), entropy_bits: API_KEY_RANDOM as f64 * 62f64.log2() }) } /// Whether an API key's last 6 characters are the checksum of the rest (a typo, or not one of ours). pub fn api_key_checksum_ok(key: &str) -> bool { key.len() > 6 && key.is_char_boundary(key.len() - 6) && { let (body, sum) = key.split_at(key.len() - 6); checksum6(body) == sum } }