servo-net hands its public cookie jar to Nacre instead of writing plain cookie_jar.json; store::cookies seals it in cookies.bin (XChaCha20-Poly1305) with a keyring-held key, saves on change and at exit, migrates the old plain jar. No keyring: cookies for the run only, Settings says so (D-019). Smokes with a throwaway GNOME Keyring (SMOKE_KEYRING=1). Co-Authored-By: Claude Opus 5.5 <[email protected]>
695 lines
27 KiB
Rust
695 lines
27 KiB
Rust
//! Encrypted store for passwords, addresses and payment cards. No keyring service needed.
|
|
//!
|
|
//! vault.json holds metadata and one sealed blob (XChaCha20-Poly1305) with all entries.
|
|
//! device mode: the 256-bit vault key sits in vault.key (owner-only). Protects against casual
|
|
//! snooping and backups, not against someone with the user's account.
|
|
//! master mode: the vault key is wrapped with Argon2id(master password) and only kept in memory
|
|
//! while unlocked. Locks itself after `vault.autolock_min` idle minutes.
|
|
//! Changing modes re-wraps the same vault key, so entries are never re-encrypted.
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use base64::Engine as _;
|
|
use base64::engine::general_purpose::STANDARD as B64;
|
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
|
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
|
use serde::{Deserialize, Serialize};
|
|
use url::Url;
|
|
|
|
use crate::util;
|
|
|
|
const AAD: &[u8] = b"nacre-vault-v2";
|
|
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
pub struct Login {
|
|
pub id: u64,
|
|
/// Origin the login belongs to ("https://example.com").
|
|
pub origin: String,
|
|
pub username: String,
|
|
pub password: String,
|
|
#[serde(default)]
|
|
pub note: String,
|
|
#[serde(default)]
|
|
pub created: u64,
|
|
#[serde(default)]
|
|
pub used: u64,
|
|
#[serde(default)]
|
|
pub changed: u64,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
#[serde(default)]
|
|
pub struct Address {
|
|
pub id: u64,
|
|
pub name: String,
|
|
pub organization: String,
|
|
pub street: String,
|
|
pub city: String,
|
|
pub region: String,
|
|
pub postal_code: String,
|
|
pub country: String,
|
|
pub phone: String,
|
|
pub email: String,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
#[serde(default)]
|
|
pub struct Card {
|
|
pub id: u64,
|
|
pub name: String,
|
|
pub number: String,
|
|
pub exp_month: u32,
|
|
pub exp_year: u32,
|
|
pub nickname: String,
|
|
}
|
|
|
|
impl Card {
|
|
/// "•••• 4242"
|
|
pub fn masked(&self) -> String {
|
|
let digits: String = self.number.chars().filter(char::is_ascii_digit).collect();
|
|
let last: String = digits.chars().rev().take(4).collect::<Vec<_>>().into_iter().rev().collect();
|
|
format!("•••• {last}")
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
#[serde(default)]
|
|
pub struct Contents {
|
|
pub logins: Vec<Login>,
|
|
pub addresses: Vec<Address>,
|
|
pub cards: Vec<Card>,
|
|
/// Origins where the user said "never save".
|
|
pub never: Vec<String>,
|
|
pub next_id: u64,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum Mode {
|
|
Device,
|
|
Master,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
struct Meta {
|
|
v: u32,
|
|
mode: Mode,
|
|
/// Sealed `Contents` as base64 (nonce || ciphertext).
|
|
#[serde(default)]
|
|
data: String,
|
|
/// Master mode: Argon2 salt and the vault key sealed with the password-derived key.
|
|
#[serde(default)]
|
|
salt: String,
|
|
#[serde(default)]
|
|
wrapped: String,
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub enum VaultError {
|
|
Locked,
|
|
WrongPassword,
|
|
Damaged(String),
|
|
Io(String),
|
|
}
|
|
|
|
impl std::fmt::Display for VaultError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
VaultError::Locked => write!(f, "The password store is locked."),
|
|
VaultError::WrongPassword => write!(f, "That password is not right."),
|
|
VaultError::Damaged(what) => write!(f, "The password store could not be read ({what})."),
|
|
VaultError::Io(what) => write!(f, "The password store could not be saved ({what})."),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// XChaCha20-Poly1305 with a fresh random nonce: nonce || ciphertext. `aad` names what is sealed. Also used by the
|
|
/// cookie store.
|
|
pub(crate) fn seal(key: &[u8; 32], aad: &[u8], plain: &[u8]) -> Vec<u8> {
|
|
let cipher = XChaCha20Poly1305::new(chacha20poly1305::Key::from_slice(key));
|
|
let mut nonce = [0u8; 24];
|
|
util::random_bytes(&mut nonce);
|
|
let sealed = cipher.encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad }).expect("encryption with a valid key cannot fail");
|
|
let mut out = nonce.to_vec();
|
|
out.extend(sealed);
|
|
out
|
|
}
|
|
|
|
pub(crate) fn unseal(key: &[u8; 32], aad: &[u8], blob: &[u8]) -> Option<Vec<u8>> {
|
|
if blob.len() < 24 + 16 {
|
|
return None;
|
|
}
|
|
let cipher = XChaCha20Poly1305::new(chacha20poly1305::Key::from_slice(key));
|
|
cipher.decrypt(XNonce::from_slice(&blob[..24]), Payload { msg: &blob[24..], aad }).ok()
|
|
}
|
|
|
|
fn password_key(password: &str, salt: &[u8]) -> [u8; 32] {
|
|
let mut out = [0u8; 32];
|
|
// Argon2id with the crate's defaults (19 MiB, 2 passes): about 50 ms here, fine for an unlock.
|
|
if argon2::Argon2::default().hash_password_into(password.as_bytes(), salt, &mut out).is_err() {
|
|
log::error!("argon2 failed; salt too short?");
|
|
}
|
|
out
|
|
}
|
|
|
|
pub struct Vault {
|
|
path: PathBuf,
|
|
key_path: PathBuf,
|
|
meta: Meta,
|
|
key: Option<[u8; 32]>,
|
|
pub contents: Contents,
|
|
/// Incognito: nothing is written.
|
|
read_only: bool,
|
|
/// Last activity, for auto-lock (seconds).
|
|
pub last_used: u64,
|
|
/// Master mode: when the password was last entered, for "ask again before revealing".
|
|
pub last_auth: u64,
|
|
}
|
|
|
|
impl Vault {
|
|
pub fn load(path: PathBuf, key_path: PathBuf, read_only: bool) -> Vault {
|
|
let meta: Option<Meta> = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok());
|
|
let fresh = meta.is_none();
|
|
let meta = meta.unwrap_or(Meta { v: 2, mode: Mode::Device, data: String::new(), salt: String::new(), wrapped: String::new() });
|
|
let mut vault = Vault { path, key_path, meta, key: None, contents: Contents::default(), read_only, last_used: util::now(), last_auth: 0 };
|
|
if vault.meta.mode == Mode::Device {
|
|
match vault.device_key(fresh) {
|
|
Some(key) => {
|
|
if let Err(error) = vault.unlock_with(key) {
|
|
log::error!("vault: {error}");
|
|
}
|
|
},
|
|
None => log::error!("vault: the key file is missing; saved passwords cannot be read"),
|
|
}
|
|
}
|
|
vault
|
|
}
|
|
|
|
/// Read the device key, or make one for a new vault.
|
|
fn device_key(&self, create: bool) -> Option<[u8; 32]> {
|
|
if let Ok(text) = std::fs::read_to_string(&self.key_path)
|
|
&& let Ok(bytes) = B64.decode(text.trim())
|
|
&& let Ok(key) = <[u8; 32]>::try_from(bytes.as_slice())
|
|
{
|
|
return Some(key);
|
|
}
|
|
if !create {
|
|
return None;
|
|
}
|
|
let mut key = [0u8; 32];
|
|
util::random_bytes(&mut key);
|
|
// Incognito keeps an empty vault in memory only.
|
|
if self.read_only {
|
|
return Some(key);
|
|
}
|
|
if let Err(error) = util::write_atomic(&self.key_path, B64.encode(key).as_bytes(), true) {
|
|
log::error!("vault: could not write the key file: {error}");
|
|
}
|
|
Some(key)
|
|
}
|
|
|
|
fn unlock_with(&mut self, key: [u8; 32]) -> Result<(), VaultError> {
|
|
if self.meta.data.is_empty() {
|
|
self.contents = Contents::default();
|
|
} else {
|
|
let blob = B64.decode(&self.meta.data).map_err(|e| VaultError::Damaged(e.to_string()))?;
|
|
let plain = unseal(&key, AAD, &blob).ok_or(VaultError::WrongPassword)?;
|
|
self.contents = serde_json::from_slice(&plain).map_err(|e| VaultError::Damaged(e.to_string()))?;
|
|
}
|
|
self.key = Some(key);
|
|
self.last_used = util::now();
|
|
Ok(())
|
|
}
|
|
|
|
pub fn mode(&self) -> Mode {
|
|
self.meta.mode.clone()
|
|
}
|
|
|
|
pub fn locked(&self) -> bool {
|
|
self.key.is_none()
|
|
}
|
|
|
|
/// Unlock a master-password vault.
|
|
pub fn unlock(&mut self, password: &str) -> Result<(), VaultError> {
|
|
if !self.locked() {
|
|
return Ok(());
|
|
}
|
|
let salt = B64.decode(&self.meta.salt).map_err(|e| VaultError::Damaged(e.to_string()))?;
|
|
let wrapped = B64.decode(&self.meta.wrapped).map_err(|e| VaultError::Damaged(e.to_string()))?;
|
|
let kek = password_key(password, &salt);
|
|
let key_bytes = unseal(&kek, AAD, &wrapped).ok_or(VaultError::WrongPassword)?;
|
|
let key = <[u8; 32]>::try_from(key_bytes.as_slice()).map_err(|_| VaultError::Damaged("bad key".into()))?;
|
|
self.unlock_with(key)?;
|
|
self.last_auth = util::now();
|
|
Ok(())
|
|
}
|
|
|
|
/// Check the master password without changing the lock state (re-authentication).
|
|
pub fn check_password(&mut self, password: &str) -> bool {
|
|
if self.meta.mode != Mode::Master {
|
|
return true;
|
|
}
|
|
let Ok(salt) = B64.decode(&self.meta.salt) else { return false };
|
|
let Ok(wrapped) = B64.decode(&self.meta.wrapped) else { return false };
|
|
let ok = unseal(&password_key(password, &salt), AAD, &wrapped).is_some();
|
|
if ok {
|
|
self.last_auth = util::now();
|
|
}
|
|
ok
|
|
}
|
|
|
|
/// Master mode only: forget the key.
|
|
pub fn lock(&mut self) {
|
|
if self.meta.mode == Mode::Master && self.key.is_some() {
|
|
self.key = None;
|
|
self.contents = Contents::default();
|
|
}
|
|
}
|
|
|
|
/// Lock after `minutes` of no use (0 = never).
|
|
pub fn autolock(&mut self, minutes: u32) {
|
|
if minutes > 0 && self.meta.mode == Mode::Master && !self.locked() && util::now().saturating_sub(self.last_used) > minutes as u64 * 60 {
|
|
self.lock();
|
|
}
|
|
}
|
|
|
|
pub fn touch(&mut self) {
|
|
self.last_used = util::now();
|
|
}
|
|
|
|
/// Whether revealing a password needs the master password again.
|
|
pub fn needs_reauth(&self, reauth: bool, minutes: u32) -> bool {
|
|
reauth && self.meta.mode == Mode::Master && (minutes == 0 || util::now().saturating_sub(self.last_auth) > minutes as u64 * 60)
|
|
}
|
|
|
|
fn save(&mut self) -> Result<(), VaultError> {
|
|
let key = self.key.ok_or(VaultError::Locked)?;
|
|
if self.read_only {
|
|
return Ok(());
|
|
}
|
|
let plain = serde_json::to_vec(&self.contents).map_err(|e| VaultError::Io(e.to_string()))?;
|
|
self.meta.data = B64.encode(seal(&key, AAD, &plain));
|
|
util::save_json_private(&self.path, &self.meta).map_err(|e| VaultError::Io(e.to_string()))
|
|
}
|
|
|
|
/// Switch to (or change) master-password mode.
|
|
pub fn set_master(&mut self, password: &str) -> Result<(), VaultError> {
|
|
let key = self.key.ok_or(VaultError::Locked)?;
|
|
let mut salt = [0u8; 16];
|
|
util::random_bytes(&mut salt);
|
|
let kek = password_key(password, &salt);
|
|
self.meta.salt = B64.encode(salt);
|
|
self.meta.wrapped = B64.encode(seal(&kek, AAD, &key));
|
|
self.meta.mode = Mode::Master;
|
|
self.save()?;
|
|
if !self.read_only {
|
|
let _ = std::fs::remove_file(&self.key_path);
|
|
}
|
|
self.last_auth = util::now();
|
|
Ok(())
|
|
}
|
|
|
|
/// Back to device mode (the vault must be unlocked).
|
|
pub fn remove_master(&mut self) -> Result<(), VaultError> {
|
|
let key = self.key.ok_or(VaultError::Locked)?;
|
|
if !self.read_only {
|
|
util::write_atomic(&self.key_path, B64.encode(key).as_bytes(), true).map_err(|e| VaultError::Io(e.to_string()))?;
|
|
}
|
|
self.meta.mode = Mode::Device;
|
|
self.meta.salt.clear();
|
|
self.meta.wrapped.clear();
|
|
self.save()
|
|
}
|
|
|
|
fn new_id(&mut self) -> u64 {
|
|
self.contents.next_id += 1;
|
|
self.contents.next_id
|
|
}
|
|
|
|
pub fn logins_for(&self, url: &str) -> Vec<&Login> {
|
|
let origin = origin_of(url);
|
|
if origin.is_empty() || self.locked() {
|
|
return Vec::new();
|
|
}
|
|
let site = site_of(url);
|
|
let mut out: Vec<&Login> = self.contents.logins.iter().filter(|l| l.origin == origin).collect();
|
|
// Logins saved on another page of the same site come after exact matches.
|
|
out.extend(self.contents.logins.iter().filter(|l| l.origin != origin && site_of(&l.origin) == site));
|
|
out
|
|
}
|
|
|
|
pub fn find(&self, url: &str, username: &str) -> Option<&Login> {
|
|
let origin = origin_of(url);
|
|
self.contents.logins.iter().find(|l| l.origin == origin && l.username == username)
|
|
}
|
|
|
|
/// Save a login; returns `true` when something new was stored or a password changed.
|
|
pub fn upsert_login(&mut self, url: &str, username: &str, password: &str, note: &str) -> Result<bool, VaultError> {
|
|
if self.locked() {
|
|
return Err(VaultError::Locked);
|
|
}
|
|
let origin = origin_of(url);
|
|
if origin.is_empty() || password.is_empty() {
|
|
return Ok(false);
|
|
}
|
|
let now = util::now();
|
|
let changed = if let Some(login) = self.contents.logins.iter_mut().find(|l| l.origin == origin && l.username == username) {
|
|
if login.password == password && (note.is_empty() || login.note == note) {
|
|
login.used = now;
|
|
false
|
|
} else {
|
|
login.password = password.to_owned();
|
|
if !note.is_empty() {
|
|
login.note = note.to_owned();
|
|
}
|
|
login.changed = now;
|
|
true
|
|
}
|
|
} else {
|
|
let id = self.new_id();
|
|
self.contents.logins.push(Login { id, origin, username: username.to_owned(), password: password.to_owned(), note: note.to_owned(), created: now, used: now, changed: now });
|
|
true
|
|
};
|
|
self.save()?;
|
|
self.touch();
|
|
Ok(changed)
|
|
}
|
|
|
|
pub fn update_login(&mut self, login: Login) -> Result<(), VaultError> {
|
|
if let Some(slot) = self.contents.logins.iter_mut().find(|l| l.id == login.id) {
|
|
let changed_pw = slot.password != login.password;
|
|
*slot = login;
|
|
if changed_pw {
|
|
slot.changed = util::now();
|
|
}
|
|
}
|
|
self.save()
|
|
}
|
|
|
|
pub fn mark_used(&mut self, id: u64) {
|
|
if let Some(login) = self.contents.logins.iter_mut().find(|l| l.id == id) {
|
|
login.used = util::now();
|
|
let _ = self.save();
|
|
}
|
|
}
|
|
|
|
pub fn delete_login(&mut self, id: u64) -> Result<(), VaultError> {
|
|
self.contents.logins.retain(|l| l.id != id);
|
|
self.save()
|
|
}
|
|
|
|
pub fn upsert_address(&mut self, mut address: Address) -> Result<(), VaultError> {
|
|
if address.id == 0 {
|
|
address.id = self.new_id();
|
|
self.contents.addresses.push(address);
|
|
} else if let Some(slot) = self.contents.addresses.iter_mut().find(|a| a.id == address.id) {
|
|
*slot = address;
|
|
}
|
|
self.save()
|
|
}
|
|
|
|
pub fn delete_address(&mut self, id: u64) -> Result<(), VaultError> {
|
|
self.contents.addresses.retain(|a| a.id != id);
|
|
self.save()
|
|
}
|
|
|
|
pub fn upsert_card(&mut self, mut card: Card) -> Result<(), VaultError> {
|
|
card.number.retain(|c| c.is_ascii_digit());
|
|
if card.id == 0 {
|
|
card.id = self.new_id();
|
|
self.contents.cards.push(card);
|
|
} else if let Some(slot) = self.contents.cards.iter_mut().find(|c| c.id == card.id) {
|
|
*slot = card;
|
|
}
|
|
self.save()
|
|
}
|
|
|
|
pub fn delete_card(&mut self, id: u64) -> Result<(), VaultError> {
|
|
self.contents.cards.retain(|c| c.id != id);
|
|
self.save()
|
|
}
|
|
|
|
pub fn never_for(&self, url: &str) -> bool {
|
|
let origin = origin_of(url);
|
|
self.contents.never.iter().any(|o| *o == origin)
|
|
}
|
|
|
|
pub fn add_never(&mut self, url: &str) -> Result<(), VaultError> {
|
|
let origin = origin_of(url);
|
|
if !origin.is_empty() && !self.contents.never.contains(&origin) {
|
|
self.contents.never.push(origin);
|
|
}
|
|
self.save()
|
|
}
|
|
|
|
pub fn remove_never(&mut self, origin: &str) -> Result<(), VaultError> {
|
|
self.contents.never.retain(|o| o != origin);
|
|
self.save()
|
|
}
|
|
|
|
/// Import a CSV export from Chrome/Edge/Brave/Opera (name,url,username,password,note) or
|
|
/// Firefox (url,username,password,httpRealm,formActionOrigin,guid,...) or Bitwarden
|
|
/// (login_uri, login_username, login_password). Returns (added, skipped).
|
|
pub fn import_csv(&mut self, text: &str) -> Result<(usize, usize), VaultError> {
|
|
if self.locked() {
|
|
return Err(VaultError::Locked);
|
|
}
|
|
let rows = parse_csv(text);
|
|
let Some(header) = rows.first() else { return Ok((0, 0)) };
|
|
let header: Vec<String> = header.iter().map(|h| h.trim().to_lowercase()).collect();
|
|
let col = |names: &[&str]| names.iter().find_map(|n| header.iter().position(|h| h == n));
|
|
let (Some(url_col), Some(user_col), Some(pass_col)) = (col(&["url", "login_uri", "origin", "website"]), col(&["username", "login_username", "user", "login"]), col(&["password", "login_password"])) else {
|
|
return Err(VaultError::Damaged("the file has no url, username and password columns".into()));
|
|
};
|
|
let note_col = col(&["note", "notes", "comment"]);
|
|
let mut added = 0;
|
|
let mut skipped = 0;
|
|
let now = util::now();
|
|
for row in rows.iter().skip(1) {
|
|
let get = |i: usize| row.get(i).map(|s| s.trim().to_owned()).unwrap_or_default();
|
|
let url = get(url_col);
|
|
let password = row.get(pass_col).cloned().unwrap_or_default();
|
|
let origin = origin_of(&url);
|
|
if origin.is_empty() || password.is_empty() {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
let username = get(user_col);
|
|
if self.contents.logins.iter().any(|l| l.origin == origin && l.username == username && l.password == password) {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
let note = note_col.map(get).unwrap_or_default();
|
|
let id = self.new_id();
|
|
self.contents.logins.push(Login { id, origin, username, password, note, created: now, used: 0, changed: now });
|
|
added += 1;
|
|
}
|
|
self.save()?;
|
|
Ok((added, skipped))
|
|
}
|
|
|
|
/// CSV in Chrome's format, which every password manager reads.
|
|
pub fn export_csv(&self) -> Result<String, VaultError> {
|
|
if self.locked() {
|
|
return Err(VaultError::Locked);
|
|
}
|
|
let mut out = String::from("name,url,username,password,note\n");
|
|
for l in &self.contents.logins {
|
|
let name = Url::parse(&l.origin).ok().and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default();
|
|
out.push_str(&[name.as_str(), &l.origin, &l.username, &l.password, &l.note].iter().map(|f| csv_field(f)).collect::<Vec<_>>().join(","));
|
|
out.push('\n');
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Logins with weak or reused passwords: (login id, reason).
|
|
pub fn weak_or_reused(&self) -> Vec<(u64, &'static str)> {
|
|
let mut out = Vec::new();
|
|
for l in &self.contents.logins {
|
|
if strength(&l.password).0 <= 1 {
|
|
out.push((l.id, "Weak password"));
|
|
} else if self.contents.logins.iter().any(|o| o.id != l.id && o.password == l.password) {
|
|
out.push((l.id, "Used on more than one site"));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
/// "https://example.com" for any URL on that origin; "" for things that are not web pages.
|
|
pub fn origin_of(url: &str) -> String {
|
|
let parsed = Url::parse(url).or_else(|_| Url::parse(&format!("https://{url}")));
|
|
match parsed {
|
|
Ok(u) if matches!(u.scheme(), "http" | "https") && u.host_str().is_some() => u.origin().ascii_serialization(),
|
|
_ => String::new(),
|
|
}
|
|
}
|
|
|
|
/// Registrable-ish part of the host, so logins on login.example.com show on example.com.
|
|
pub fn site_of(url: &str) -> String {
|
|
Url::parse(url).ok().and_then(|u| u.host_str().map(util::base_domain)).unwrap_or_default()
|
|
}
|
|
|
|
fn csv_field(field: &str) -> String {
|
|
if field.contains([',', '"', '\n', '\r']) { format!("\"{}\"", field.replace('"', "\"\"")) } else { field.to_owned() }
|
|
}
|
|
|
|
/// RFC 4180 CSV: quoted fields, doubled quotes, newlines inside quotes.
|
|
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
|
|
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
|
let mut rows = Vec::new();
|
|
let mut row = Vec::new();
|
|
let mut field = String::new();
|
|
let mut quoted = false;
|
|
let mut chars = text.chars().peekable();
|
|
while let Some(c) = chars.next() {
|
|
if quoted {
|
|
match c {
|
|
'"' if chars.peek() == Some(&'"') => {
|
|
field.push('"');
|
|
chars.next();
|
|
},
|
|
'"' => quoted = false,
|
|
_ => field.push(c),
|
|
}
|
|
continue;
|
|
}
|
|
match c {
|
|
'"' if field.is_empty() => quoted = true,
|
|
',' => row.push(std::mem::take(&mut field)),
|
|
'\r' => {},
|
|
'\n' => {
|
|
row.push(std::mem::take(&mut field));
|
|
if !(row.len() == 1 && row[0].is_empty()) {
|
|
rows.push(std::mem::take(&mut row));
|
|
} else {
|
|
row.clear();
|
|
}
|
|
},
|
|
_ => field.push(c),
|
|
}
|
|
}
|
|
if !field.is_empty() || !row.is_empty() {
|
|
row.push(field);
|
|
rows.push(row);
|
|
}
|
|
rows
|
|
}
|
|
|
|
const AMBIGUOUS: &str = "Il1O0o";
|
|
const SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/";
|
|
|
|
/// A random password with at least one character of each chosen kind.
|
|
pub fn generate(length: usize, symbols: bool) -> String {
|
|
let length = length.clamp(8, 128);
|
|
let lower: Vec<char> = ('a'..='z').filter(|c| !AMBIGUOUS.contains(*c)).collect();
|
|
let upper: Vec<char> = ('A'..='Z').filter(|c| !AMBIGUOUS.contains(*c)).collect();
|
|
let digits: Vec<char> = ('2'..='9').collect();
|
|
let syms: Vec<char> = SYMBOLS.chars().collect();
|
|
let mut sets: Vec<&Vec<char>> = vec![&lower, &upper, &digits];
|
|
if symbols {
|
|
sets.push(&syms);
|
|
}
|
|
let all: Vec<char> = sets.iter().flat_map(|s| s.iter().copied()).collect();
|
|
let mut out: Vec<char> = sets.iter().map(|s| s[util::random_below(s.len())]).collect();
|
|
while out.len() < length {
|
|
out.push(all[util::random_below(all.len())]);
|
|
}
|
|
// Fisher-Yates so the guaranteed characters are not always first.
|
|
for i in (1..out.len()).rev() {
|
|
out.swap(i, util::random_below(i + 1));
|
|
}
|
|
out.into_iter().collect()
|
|
}
|
|
|
|
const WORDS: &[&str] = &[
|
|
"acorn", "amber", "anchor", "apple", "arrow", "aspen", "atlas", "badge", "bamboo", "banjo", "basil", "beacon", "birch", "bison", "blaze", "bloom", "boulder", "breeze", "brick", "brook", "cabin", "cactus", "candle", "canyon", "carbon", "cedar", "cello", "chalk", "cherry", "cider", "cinder", "clover", "cobalt", "comet", "copper", "coral", "cotton", "crane", "crater", "cricket", "crystal", "cypress", "dahlia", "delta", "denim", "desert", "dune", "eagle", "ember", "falcon", "fern", "fjord", "flint", "forest", "fossil", "galaxy", "garnet", "ginger", "glacier", "granite", "gravel", "harbor", "hazel", "heron", "hollow", "honey", "horizon", "indigo", "island", "ivory", "jasper", "juniper", "kayak", "kettle", "lagoon", "lantern", "lemon", "lilac", "linen", "lotus", "maple", "marble", "meadow", "meteor", "mint", "mosaic", "nectar", "nickel", "oasis", "ocean", "olive", "onyx", "orbit", "orchid", "otter", "paddle", "pebble", "pepper", "pine", "planet", "plum", "pollen", "prairie", "prism", "quartz", "quill", "raven", "reef", "ridge", "river", "rocket", "saffron", "sage", "salmon", "sapphire", "shadow", "silver", "spruce", "stone", "summit", "thistle", "thunder", "timber", "topaz", "tulip", "tundra", "velvet", "violet", "walnut", "willow", "winter", "yarrow", "zephyr",
|
|
];
|
|
|
|
/// "maple-orbit-quartz-reef-4" style passphrase.
|
|
pub fn passphrase(words: usize, sep: &str) -> String {
|
|
let mut parts: Vec<String> = (0..words.clamp(3, 12)).map(|_| WORDS[util::random_below(WORDS.len())].to_owned()).collect();
|
|
parts.push(util::random_below(100).to_string());
|
|
parts.join(sep)
|
|
}
|
|
|
|
const COMMON: &[&str] = &["password", "passw0rd", "qwerty", "qwertyuiop", "letmein", "welcome", "admin", "login", "iloveyou", "monkey", "dragon", "football", "baseball", "sunshine", "princess", "starwars", "123456", "12345678", "123456789", "abc123", "111111", "000000"];
|
|
|
|
/// Rough strength: (0..=4, label).
|
|
pub fn strength(password: &str) -> (u8, &'static str) {
|
|
let lower = password.to_lowercase();
|
|
if password.is_empty() {
|
|
return (0, "Empty");
|
|
}
|
|
if COMMON.iter().any(|c| lower.contains(c)) && password.len() < 14 {
|
|
return (0, "Very weak");
|
|
}
|
|
let mut pool = 0u32;
|
|
if password.chars().any(|c| c.is_ascii_lowercase()) { pool += 26 }
|
|
if password.chars().any(|c| c.is_ascii_uppercase()) { pool += 26 }
|
|
if password.chars().any(|c| c.is_ascii_digit()) { pool += 10 }
|
|
if password.chars().any(|c| !c.is_ascii_alphanumeric()) { pool += 32 }
|
|
let unique = password.chars().collect::<std::collections::HashSet<_>>().len();
|
|
let bits = (unique.max(1) as f64).min(password.chars().count() as f64) * (pool.max(2) as f64).log2();
|
|
match bits as u32 {
|
|
0..=27 => (0, "Very weak"),
|
|
28..=39 => (1, "Weak"),
|
|
40..=59 => (2, "Fair"),
|
|
60..=79 => (3, "Strong"),
|
|
_ => (4, "Very strong"),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn temp_vault() -> (Vault, PathBuf) {
|
|
let dir = std::env::temp_dir().join(format!("nacre-vault-test-{}", util::random_hex(6)));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
(Vault::load(dir.join("vault.json"), dir.join("vault.key"), false), dir)
|
|
}
|
|
|
|
#[test]
|
|
fn device_and_master_modes() {
|
|
let (mut v, dir) = temp_vault();
|
|
assert!(!v.locked());
|
|
assert!(v.upsert_login("https://a.example/login", "me", "pw1", "").unwrap());
|
|
assert!(!v.upsert_login("https://a.example/other", "me", "pw1", "").unwrap());
|
|
v.set_master("correct horse").unwrap();
|
|
assert!(!dir.join("vault.key").exists());
|
|
let mut again = Vault::load(dir.join("vault.json"), dir.join("vault.key"), false);
|
|
assert!(again.locked());
|
|
assert_eq!(again.unlock("wrong"), Err(VaultError::WrongPassword));
|
|
again.unlock("correct horse").unwrap();
|
|
assert_eq!(again.logins_for("https://a.example/")[0].password, "pw1");
|
|
again.remove_master().unwrap();
|
|
let third = Vault::load(dir.join("vault.json"), dir.join("vault.key"), false);
|
|
assert!(!third.locked());
|
|
assert_eq!(third.contents.logins.len(), 1);
|
|
let _ = std::fs::remove_dir_all(dir);
|
|
}
|
|
|
|
#[test]
|
|
fn csv_round_trip() {
|
|
let (mut v, dir) = temp_vault();
|
|
v.upsert_login("https://a.example", "me", "p,\"w\"", "note\nline").unwrap();
|
|
let csv = v.export_csv().unwrap();
|
|
let (mut w, dir2) = temp_vault();
|
|
assert_eq!(w.import_csv(&csv).unwrap(), (1, 0));
|
|
assert_eq!(w.contents.logins[0].password, "p,\"w\"");
|
|
assert_eq!(w.contents.logins[0].note, "note\nline");
|
|
assert_eq!(w.import_csv(&csv).unwrap(), (0, 1));
|
|
let _ = std::fs::remove_dir_all(dir);
|
|
let _ = std::fs::remove_dir_all(dir2);
|
|
}
|
|
|
|
#[test]
|
|
fn generator() {
|
|
let p = generate(20, true);
|
|
assert_eq!(p.chars().count(), 20);
|
|
assert!(p.chars().any(|c| c.is_ascii_digit()));
|
|
assert!(strength(&p).0 >= 3);
|
|
assert_eq!(strength("password1").0, 0);
|
|
}
|
|
}
|