Cotton code
386 lines · 13.7 KB · RustRaw
//! New passwords and how strong a password is, on the device.//!//! ```text//! Recipe::from_value(json)        {"random":{length, lower, upper, digits, symbols, no_look_alikes}}//!                                 or {"words":{count, separator, capitalize, number}}//! recipe.generate()               a password from the OS random source (generate_with: a given one)//! recipe.bits()                   the entropy the recipe draws, exactly//! strength(password)              the guesses an attacker who knows common shapes needs, as bits and a score//! ```//!//! **Random** builds a [`PasswordRule`] from switches: each chosen class at//! least once, every draw uniform. **Words** draws from the EFF large word//! list (7776 words, 12.92 bits each, bundled), the diceware list a person//! can say aloud.//!//! **Strength** is an estimate, never a promise: the cheapest reading of the//! password as pieces an attacker tries first (a common password, a word of//! the bundled list, a repeat, a run like `abcd` or `4321`, a keyboard row, a//! year) and single characters otherwise, the cheapest by a shortest path over//! the string, each piece costing the bits of guessing it. Nothing is sent//! anywhere.use rand::Rng;use serde::{Deserialize, Serialize};use zeroize::Zeroizing;use super::password_rule::{CharClass, PasswordRule, RuleError};/// The EFF large word list, one word a line, 7776 lines (eff.org/dice, CC BY 3.0 US;/// the file's sha256 with its dice numbers was addd3553…903e).pub const EFF_LARGE: &str = include_str!("eff_large_wordlist.txt");/// The most common passwords, lower case, most common first (SecLists' Pwdb top 1000, MIT;/// 3+ characters, lower-cased, repeats dropped: 990 lines).pub const COMMON: &str = include_str!("common_passwords.txt");/// Characters one reads for another, left out when asked.pub const LOOK_ALIKES: &str = "0O1lI|`'\"";const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";const UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";const DIGITS: &str = "0123456789";const SYMBOLS: &str = "-_.!@#$%*+=?";/// The fewest and most words a memorable password holds.pub const WORDS_MIN: usize = 3;pub const WORDS_MAX: usize = 12;fn yes() -> bool {    true}/// A random password's switches.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct Random {    pub length: usize,    #[serde(default = "yes")]    pub lower: bool,    #[serde(default = "yes")]    pub upper: bool,    #[serde(default = "yes")]    pub digits: bool,    #[serde(default = "yes")]    pub symbols: bool,    #[serde(default = "yes")]    pub no_look_alikes: bool,}/// A memorable password's switches.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct Words {    pub count: usize,    #[serde(default = "dash")]    pub separator: String,    /// Each word's first letter upper case.    #[serde(default)]    pub capitalize: bool,    /// One digit after one word, at random.    #[serde(default)]    pub number: bool,}fn dash() -> String {    "-".into()}/// How a new password is made.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case", deny_unknown_fields)]pub enum Recipe {    Random(Random),    Words(Words),}/// Why a recipe was refused, in words.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum RecipeError {    #[error("the recipe does not read: {0}")]    DoesNotRead(String),    #[error("{0}")]    Rule(#[from] RuleError),    #[error("a random password needs at least one kind of character")]    NoClasses,    #[error("a memorable password is {WORDS_MIN} to {WORDS_MAX} words, not {0}")]    BadCount(usize),    #[error("a separator is at most 3 characters and never a letter")]    BadSeparator,}/// The EFF words, in list order.pub fn eff_words() -> &'static [&'static str] {    static WORDS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();    WORDS.get_or_init(|| EFF_LARGE.lines().filter(|line| !line.is_empty()).collect())}impl Recipe {    /// What Keys offers before a person changes a switch: 20 random characters.    pub fn shipped() -> Recipe {        Recipe::Random(Random { length: 20, lower: true, upper: true, digits: true, symbols: true, no_look_alikes: true })    }    pub fn from_value(value: &serde_json::Value) -> Result<Recipe, RecipeError> {        let recipe: Recipe = serde_json::from_value(value.clone()).map_err(|error| RecipeError::DoesNotRead(error.to_string()))?;        recipe.check()?;        Ok(recipe)    }    pub fn check(&self) -> Result<(), RecipeError> {        match self {            Recipe::Random(random) => random.rule().map(|_| ()),            Recipe::Words(words) => words.check(),        }    }    pub fn generate(&self) -> Result<Zeroizing<String>, RecipeError> {        self.generate_with(&mut rand::rngs::OsRng)    }    pub fn generate_with<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<Zeroizing<String>, RecipeError> {        match self {            Recipe::Random(random) => Ok(random.rule()?.generate_with(rng)?),            Recipe::Words(words) => words.generate_with(rng),        }    }    /// The bits the recipe draws: what an attacker who knows the recipe    /// faces. Random counts the pool per character (the at-least draws cost a    /// little, not counted); Words counts 12.92 a word, plus the digit.    pub fn bits(&self) -> Result<f64, RecipeError> {        match self {            Recipe::Random(random) => {                let rule = random.rule()?;                let pool: usize = rule.classes.iter().map(|class| class.chars.chars().count()).sum();                Ok(rule.length as f64 * (pool as f64).log2())            }            Recipe::Words(words) => {                words.check()?;                let mut bits = words.count as f64 * (eff_words().len() as f64).log2();                if words.number {                    bits += (10.0 * words.count as f64).log2();                }                Ok(bits)            }        }    }}impl Random {    /// The [`PasswordRule`] these switches make.    pub fn rule(&self) -> Result<PasswordRule, RecipeError> {        let keep = |chars: &str| -> String {            if self.no_look_alikes {                chars.chars().filter(|ch| !LOOK_ALIKES.contains(*ch)).collect()            } else {                chars.to_string()            }        };        let mut classes = Vec::new();        for (on, id, chars) in [(self.lower, "lower", LOWER), (self.upper, "upper", UPPER), (self.digits, "digits", DIGITS), (self.symbols, "symbols", SYMBOLS)] {            if on {                classes.push(CharClass { id: id.into(), chars: keep(chars), at_least: 1 });            }        }        if classes.is_empty() {            return Err(RecipeError::NoClasses);        }        let rule = PasswordRule { length: self.length, classes };        rule.check()?;        Ok(rule)    }}impl Words {    fn check(&self) -> Result<(), RecipeError> {        if !(WORDS_MIN..=WORDS_MAX).contains(&self.count) {            return Err(RecipeError::BadCount(self.count));        }        if self.separator.chars().count() > 3 || self.separator.chars().any(char::is_alphabetic) {            return Err(RecipeError::BadSeparator);        }        Ok(())    }    fn generate_with<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<Zeroizing<String>, RecipeError> {        self.check()?;        let list = eff_words();        let digit_after = if self.number { Some(rng.gen_range(0..self.count)) } else { None };        let mut out = Zeroizing::new(String::new());        for at in 0..self.count {            if at > 0 {                out.push_str(&self.separator);            }            let word = list[rng.gen_range(0..list.len())];            if self.capitalize {                let mut chars = word.chars();                if let Some(first) = chars.next() {                    out.extend(first.to_uppercase());                    out.push_str(chars.as_str());                }            } else {                out.push_str(word);            }            if digit_after == Some(at) {                out.push(char::from(b'0' + rng.gen_range(0..10u8)));            }        }        Ok(out)    }}/// How strong a password reads.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Strength {    /// log2 of the guesses the estimate needs.    pub bits: f64,    /// 0 very weak, 1 weak, 2 fair, 3 good, 4 strong.    pub score: u8,    /// The score's word: `very_weak`, `weak`, `fair`, `good`, `strong` (a line key, never a sentence).    pub word: &'static str,}impl Strength {    /// Weak enough for Health to name it.    pub fn is_weak(&self) -> bool {        self.score <= 1    }}/// Bits at which each score starts (fair, good, strong); below the first two, very weak or weak.pub const SCORE_BITS: [f64; 4] = [28.0, 36.0, 60.0, 80.0];fn common() -> &'static std::collections::HashMap<&'static str, usize> {    static COMMON_MAP: std::sync::OnceLock<std::collections::HashMap<&'static str, usize>> = std::sync::OnceLock::new();    COMMON_MAP.get_or_init(|| COMMON.lines().enumerate().map(|(rank, word)| (word, rank)).collect())}fn eff_set() -> &'static std::collections::HashSet<&'static str> {    static SET: std::sync::OnceLock<std::collections::HashSet<&'static str>> = std::sync::OnceLock::new();    SET.get_or_init(|| eff_words().iter().copied().collect())}const KEYBOARD_ROWS: [&str; 4] = ["`1234567890-=", "qwertyuiop[]\\", "asdfghjkl;'", "zxcvbnm,./"];/// How many characters each class holds: lower, upper, digits, ASCII symbols, anything else.const CLASS_POOL: [f64; 5] = [26.0, 26.0, 10.0, 33.0, 100.0];fn class_of(ch: char) -> u8 {    if ch.is_ascii_lowercase() {        0    } else if ch.is_ascii_uppercase() {        1    } else if ch.is_ascii_digit() {        2    } else if ch.is_ascii() {        3    } else {        4    }}fn pool_of(ch: char) -> f64 {    match class_of(ch) {        0 | 1 => 26.0,        class => CLASS_POOL[class as usize],    }}/// The letter a look-alike digit or symbol stands for in a word (`p@ssw0rd`).fn unleet(ch: char) -> char {    match ch {        '0' => 'o',        '1' | '!' | '|' => 'i',        '3' => 'e',        '4' | '@' => 'a',        '5' | '$' => 's',        '7' | '+' => 't',        '8' => 'b',        '9' => 'g',        _ => ch,    }}/// The cost in bits of guessing `piece` as one known shape, if it is one.fn piece_bits(piece: &[char]) -> Option<f64> {    let n = piece.len();    let lower: String = piece.iter().collect::<String>().to_lowercase();    let unleet: String = lower.chars().map(unleet).collect();    let leet_bits = lower.chars().zip(unleet.chars()).filter(|(a, b)| a != b).count() as f64;    let mut best: Option<f64> = None;    let mut take = |bits: f64| best = Some(best.map_or(bits, |b: f64| b.min(bits)));    let case_bits = {        let uppers = piece.iter().filter(|ch| ch.is_uppercase()).count();        if uppers == 0 {            0.0        } else if (uppers == 1 && piece[0].is_uppercase()) || uppers == n {            1.0        } else {            n as f64        }    };    if n >= 3 {        for (word, extra) in [(lower.as_str(), 0.0), (unleet.as_str(), leet_bits)] {            if let Some(rank) = common().get(word) {                take(((*rank + 2) as f64).log2() + case_bits + extra);            }            if eff_set().contains(word) {                take((eff_words().len() as f64).log2() + case_bits + extra);            }        }        if piece.iter().all(|ch| *ch == piece[0]) {            take(pool_of(piece[0]).log2() + (n as f64).log2());        }        let codes: Vec<i64> = lower.chars().map(|ch| ch as i64).collect();        let step = codes[1] - codes[0];        if step.abs() == 1 && codes.windows(2).all(|pair| pair[1] - pair[0] == step) {            take(pool_of(piece[0]).log2() + 1.0 + (n as f64).log2());        }        if KEYBOARD_ROWS.iter().any(|row| row.contains(lower.as_str()) || row.chars().rev().collect::<String>().contains(lower.as_str())) {            take(6.0 + (n as f64).log2() + 1.0);        }    }    if n == 4 && piece.iter().all(|ch| ch.is_ascii_digit()) {        let year: u32 = lower.parse().unwrap_or(0);        if (1900..=2099).contains(&year) {            take(200f64.log2());        }    }    best}/// The estimate: the cheapest reading of `password` as known pieces and/// single characters, by a shortest path over its characters.pub fn strength(password: &str) -> Strength {    let chars: Vec<char> = password.chars().collect();    let n = chars.len();    let mut cost = vec![f64::INFINITY; n + 1];    cost[0] = 0.0;    // A character no piece explains is brute-forced over every class the    // password shows, as an attacker who has seen its shape would.    let mut classes: Vec<u8> = chars.iter().map(|&ch| class_of(ch)).collect();    classes.sort_unstable();    classes.dedup();    let pool: f64 = classes.iter().map(|&class| CLASS_POOL[class as usize]).sum();    for end in 1..=n {        let single = cost[end - 1] + pool.log2();        if single < cost[end] {            cost[end] = single;        }        for start in 0..end.saturating_sub(2) {            if let Some(bits) = piece_bits(&chars[start..end]) {                if cost[start] + bits < cost[end] {                    cost[end] = cost[start] + bits;                }            }        }    }    let bits = if n == 0 { 0.0 } else { cost[n] };    let score = SCORE_BITS.iter().filter(|&&floor| bits >= floor).count() as u8;    let word = ["very_weak", "weak", "fair", "good", "strong"][score as usize];    Strength { bits: (bits * 10.0).round() / 10.0, score, word }}#[cfg(test)]#[path = "generator_tests.rs"]mod tests;