//! Health: which passwords are weak, reused, old or known breached, worked//! out on the device inside the unlock and sent nowhere.//!//! ```text//! ReuseKey::from_vmk(vmk) the key the reuse check hashes under (HKDF of the VMK)//! key.tag(password) HMAC-SHA256, 16 bytes: equal for equal passwords, nothing else//! check(items, key, now) → Finding per item: weak, reused (with whom), old//! breach_range(password) → ("5BAA6", "1E4C9B93F3F0682250B6CF8331B7EE68FD8") — only the first five go out//! breach_count(range_body, suffix) how often the range answer has seen that password//! ```//!//! **Reused** compares keyed hashes, never the passwords side by side and//! never a bare hash: a tag is HMAC under a key derived from the vault//! master key, so a tag that leaked would be no dictionary's entry. Tags//! are made for one check and dropped with it.//!//! **Breached** is Have I Been Pwned's k-anonymity range: the shell sends the//! first five hex characters of the password's SHA-1 and nothing else, and//! the core reads the answer's suffixes against the rest. It is an act the//! person runs, off by default; this module only makes the prefix and reads//! the answer.//!//! **Pure**: the clock is the caller's.use hkdf::Hkdf;use hmac::{Hmac, Mac};use sha1::{Digest, Sha1};use sha2::Sha256;use zeroize::Zeroizing;usesuper::generator::strength;usecrate::vault::seal::Vmk;/// A password unchanged for longer than this many days is old.pubconst OLD_DAYS: u64 = 365;/// The address the range is asked of, `{prefix}` the five characters.pubconst RANGE_URL: &str = "https://api.pwnedpasswords.com/range/{prefix}";const REUSE_INFO: &[u8] = b"cotton keys reuse v1";/// The key a reuse check hashes under.pubstructReuseKey(Zeroizing<[u8; 32]>);implReuseKey {pubfn from_vmk(vmk: &Vmk) -> ReuseKey {ReuseKey::from_bytes(vmk.expose()) }/// From the master key's bytes (the vectors).pubfn from_bytes(master: &[u8]) -> ReuseKey {letmut out = Zeroizing::new([0u8; 32]);Hkdf::<Sha256>::new(None, master).expand(REUSE_INFO, out.as_mut()).expect("32 bytes is a valid HKDF length");ReuseKey(out) }/// The tag of one password: equal passwords, equal tags.pubfn tag(&self, password: &str) -> [u8; 16] {letmut mac = <Hmac<Sha256> as hmac::digest::KeyInit>::new_from_slice(self.0.as_ref()).expect("HMAC takes any key"); mac.update(password.as_bytes());let full = mac.finalize().into_bytes();letmut out = [0u8; 16]; out.copy_from_slice(&full[..16]); out }}/// One opened item, as the check reads it.pubstructItem<'a> {pub id: &'a str,pub password: &'a str,/// When the password was last changed (else made), UNIX seconds.pub changed_at: Option<u64>,}/// What the check found about one item. An item with nothing to say is left out.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pubstructFinding {pub id: String,pub weak: bool,/// The other items holding the same password, by id.pub reused_with: Vec<String>,pub old: bool,/// Days since it was changed, when the item says.pub age_days: Option<u64>,}/// Weak, reused and old, for each item that is any of them, in the items' order.pubfn check(items: &[Item<'_>], key: &ReuseKey, now: u64) -> Vec<Finding> {let tags: Vec<[u8; 16]> = items.iter().map(|item| key.tag(item.password)).collect();letmut out = Vec::new();for (at, item) in items.iter().enumerate() {let reused_with: Vec<String> = items .iter() .enumerate() .filter(|(other, _)| *other != at && tags[*other] == tags[at]) .map(|(_, other)| other.id.to_string()) .collect();let age_days = item.changed_at.map(|changed| now.saturating_sub(changed) / 86_400);let finding = Finding { id: item.id.to_string(), weak: strength(item.password).is_weak(), reused_with, old: age_days.is_some_and(|days| days > OLD_DAYS), age_days, };if finding.weak || finding.old || !finding.reused_with.is_empty() { out.push(finding); } } out}/// The password's SHA-1, upper-case hex, split where the range is asked: the/// first five characters go out, the other 35 stay here.pubfn breach_range(password: &str) -> (String, Zeroizing<String>) {let digest = Sha1::digest(password.as_bytes());let hex = Zeroizing::new(hex::encode_upper(digest)); (hex[..5].to_string(), Zeroizing::new(hex[5..].to_string()))}/// How many times the range answer (`SUFFIX:COUNT` lines) has seen this/// suffix; 0 when it is absent or only padding (a count of 0).pubfn breach_count(range_body: &str, suffix: &str) -> u64 { range_body .lines() .filter_map(|line| line.trim().split_once(':')) .find(|(seen, _)| seen.eq_ignore_ascii_case(suffix)) .and_then(|(_, count)| count.trim().parse().ok()) .unwrap_or(0)}/// Whether a range answer reads as one: every non-empty line `35 hex:count`.pubfn is_range_body(range_body: &str) -> bool { range_body.lines().filter(|line| !line.trim().is_empty()).all(|line| { line.trim() .split_once(':') .is_some_and(|(suffix, count)| suffix.len() == 35 && suffix.chars().all(|ch| ch.is_ascii_hexdigit()) && count.parse::<u64>().is_ok()) })}#[cfg(test)]#[path = "health_tests.rs"]mod tests;