250 lines
9.2 KiB
Rust
250 lines
9.2 KiB
Rust
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md.
|
|
//!
|
|
//! ```
|
|
//! use custos_vault::{Item, ItemType, KdfParams, SecretString, Vault};
|
|
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
|
|
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
|
//! let mut vault = Vault::create(&password, kdf)?;
|
|
//! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms()));
|
|
//! let bytes = vault.to_bytes()?;
|
|
//! assert_eq!(Vault::open(&bytes, &password)?.items().len(), 1);
|
|
//! # Ok::<(), custos_vault::Error>(())
|
|
//! ```
|
|
|
|
mod crypto;
|
|
mod device;
|
|
mod format;
|
|
mod item;
|
|
mod save;
|
|
mod secret;
|
|
|
|
pub use item::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
|
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
|
|
pub use secret::SecretString;
|
|
|
|
use crypto::KEY_LEN;
|
|
use format::{Header, PasswordSlot, RawSlot, SALT_LEN, SLOT_PASSWORD};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::fmt;
|
|
use std::path::Path;
|
|
use zeroize::Zeroizing;
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum Error {
|
|
#[error("not a Custos vault file")]
|
|
NotAVault,
|
|
#[error("vault format version {0} is not supported by this version of Custos")]
|
|
UnsupportedVersion(u16),
|
|
#[error("the vault file is malformed")]
|
|
Malformed,
|
|
#[error("the vault's key-derivation parameters are not supported")]
|
|
UnsupportedKdf,
|
|
#[error("wrong password")]
|
|
WrongPassword,
|
|
#[error("the vault file was changed or damaged after it was written")]
|
|
Corrupted,
|
|
#[error("this device's unlock key no longer opens the vault; use the master password")]
|
|
DeviceKeyRejected,
|
|
#[error("{0}")]
|
|
Io(#[from] std::io::Error),
|
|
}
|
|
|
|
/// Argon2id parameters, stored per vault (docs/FORMAT.md, "Limits").
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct KdfParams {
|
|
pub m_cost_kib: u32,
|
|
pub t_cost: u32,
|
|
pub p_cost: u32,
|
|
}
|
|
|
|
impl KdfParams {
|
|
/// 64 MiB, 20 passes, 1 lane: about 0.75 s per unlock on the dev machine (2026, release build;
|
|
/// measure with `cargo run --release -p custos-vault --example kdf_timing`).
|
|
pub const DEFAULT: KdfParams = KdfParams { m_cost_kib: 65_536, t_cost: 20, p_cost: 1 };
|
|
pub const MAX_M_COST_KIB: u32 = 2 * 1024 * 1024;
|
|
pub const MAX_T_COST: u32 = 64;
|
|
pub const MAX_P_COST: u32 = 16;
|
|
|
|
/// Refuses parameters outside the limits before any Argon2 work.
|
|
pub fn check(&self) -> Result<(), Error> {
|
|
let ok = (1..=Self::MAX_P_COST).contains(&self.p_cost)
|
|
&& (1..=Self::MAX_T_COST).contains(&self.t_cost)
|
|
&& (8 * self.p_cost..=Self::MAX_M_COST_KIB).contains(&self.m_cost_kib);
|
|
if ok { Ok(()) } else { Err(Error::UnsupportedKdf) }
|
|
}
|
|
}
|
|
|
|
impl Default for KdfParams {
|
|
fn default() -> Self {
|
|
Self::DEFAULT
|
|
}
|
|
}
|
|
|
|
const BODY_FORMAT: u32 = 1;
|
|
|
|
#[derive(Deserialize)]
|
|
struct Body {
|
|
format: u32,
|
|
items: Vec<Item>,
|
|
}
|
|
|
|
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
|
#[derive(Serialize)]
|
|
struct BodyRef<'a> {
|
|
format: u32,
|
|
items: &'a [Item],
|
|
}
|
|
|
|
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
|
pub struct Vault {
|
|
key: Zeroizing<[u8; KEY_LEN]>,
|
|
slots: Vec<RawSlot>,
|
|
items: Vec<Item>,
|
|
}
|
|
|
|
impl fmt::Debug for Vault {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("Vault").field("items", &self.items.len()).finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -> Result<PasswordSlot, Error> {
|
|
kdf.check()?;
|
|
let mut salt = [0u8; SALT_LEN];
|
|
crypto::fill_random(&mut salt);
|
|
let mut slot = PasswordSlot { kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
|
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, kdf)?;
|
|
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
|
|
Ok(slot)
|
|
}
|
|
|
|
impl Vault {
|
|
/// A new, empty vault with a fresh random vault key wrapped by `password`.
|
|
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
|
|
let key = crypto::random_key();
|
|
let slot = password_slot(&key, password, kdf)?;
|
|
Ok(Vault { key, slots: vec![slot.raw()], items: Vec::new() })
|
|
}
|
|
|
|
pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> {
|
|
Vault::open(&std::fs::read(path)?, password)
|
|
}
|
|
|
|
/// Unlocks a vault. Returns no data at all unless both the key slot and the body authenticate.
|
|
pub fn open(bytes: &[u8], password: &SecretString) -> Result<Vault, Error> {
|
|
let (header, body_at) = Header::parse(bytes)?;
|
|
let pw_slots: Vec<PasswordSlot> = header
|
|
.slots
|
|
.iter()
|
|
.filter(|s| s.kind == SLOT_PASSWORD)
|
|
.map(|s| PasswordSlot::parse(&s.payload))
|
|
.collect::<Result<_, _>>()?;
|
|
if pw_slots.is_empty() {
|
|
return Err(Error::Malformed);
|
|
}
|
|
for slot in &pw_slots {
|
|
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?;
|
|
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
|
|
let key: Zeroizing<[u8; KEY_LEN]> =
|
|
Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?);
|
|
return Vault::open_body(bytes, header, body_at, key);
|
|
}
|
|
}
|
|
Err(Error::WrongPassword)
|
|
}
|
|
|
|
fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result<Vault, Error> {
|
|
let json =
|
|
crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?;
|
|
let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?;
|
|
if body.format != BODY_FORMAT {
|
|
return Err(Error::Corrupted);
|
|
}
|
|
Ok(Vault { key, slots: header.slots, items: body.items })
|
|
}
|
|
|
|
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
|
|
/// Windows Hello signature). Keep the blob on the device; see docs/FORMAT.md, "Device key wrap".
|
|
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
|
|
Ok(device::wrap(&self.key, material))
|
|
}
|
|
|
|
/// Unlocks with a device blob instead of the password. Fails with `DeviceKeyRejected` when the
|
|
/// material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
|
|
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
|
|
let (header, body_at) = Header::parse(bytes)?;
|
|
let key = device::unwrap(blob, material)?;
|
|
Vault::open_body(bytes, header, body_at, key)
|
|
}
|
|
|
|
/// The encrypted file contents, with a fresh body nonce.
|
|
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
|
|
let body_nonce = crypto::random_nonce();
|
|
let mut out = Header { slots: self.slots.clone(), body_nonce }.to_bytes();
|
|
let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len()));
|
|
let body = BodyRef { format: BODY_FORMAT, items: &self.items };
|
|
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
|
|
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
|
|
out.extend_from_slice(&sealed);
|
|
Ok(out)
|
|
}
|
|
|
|
/// Encrypts and writes the vault atomically (see [`save_atomic`]).
|
|
pub fn save(&self, path: &Path) -> Result<(), Error> {
|
|
save_atomic(path, &self.to_bytes()?)
|
|
}
|
|
|
|
/// Wraps the same vault key with a new password (new salt and nonce). The items are untouched;
|
|
/// the old password stops working at the next save.
|
|
pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> {
|
|
let slot = password_slot(&self.key, new_password, kdf)?;
|
|
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
|
|
self.slots.insert(0, slot.raw());
|
|
Ok(())
|
|
}
|
|
|
|
/// Whether two unlocked vaults share a vault key (tests: a password change keeps the key).
|
|
#[doc(hidden)]
|
|
pub fn same_key_as(&self, other: &Vault) -> bool {
|
|
self.key[..] == other.key[..]
|
|
}
|
|
|
|
/// The KDF parameters of the first password slot.
|
|
pub fn kdf(&self) -> Option<KdfParams> {
|
|
self.slots
|
|
.iter()
|
|
.filter(|s| s.kind == SLOT_PASSWORD)
|
|
.find_map(|s| PasswordSlot::parse(&s.payload).ok())
|
|
.map(|s| s.kdf)
|
|
}
|
|
|
|
pub fn items(&self) -> &[Item] {
|
|
&self.items
|
|
}
|
|
|
|
pub fn item(&self, id: &str) -> Option<&Item> {
|
|
self.items.iter().find(|i| i.id == id)
|
|
}
|
|
|
|
pub fn item_mut(&mut self, id: &str) -> Option<&mut Item> {
|
|
self.items.iter_mut().find(|i| i.id == id)
|
|
}
|
|
|
|
pub fn add(&mut self, item: Item) {
|
|
self.items.push(item);
|
|
}
|
|
|
|
/// Replaces the item with the same id, or adds it.
|
|
pub fn put(&mut self, item: Item) {
|
|
match self.item_mut(&item.id) {
|
|
Some(slot) => *slot = item,
|
|
None => self.items.push(item),
|
|
}
|
|
}
|
|
|
|
pub fn remove(&mut self, id: &str) -> Option<Item> {
|
|
let i = self.items.iter().position(|it| it.id == id)?;
|
|
Some(self.items.remove(i))
|
|
}
|
|
}
|