[vault] Format v2: factor, pair and single slots; open_with any two factors; upgrade from v1; key-pair item type
This commit is contained in:
@@ -55,6 +55,13 @@ pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u
|
||||
.expect("encryption cannot fail for in-memory buffers")
|
||||
}
|
||||
|
||||
/// HKDF-SHA256(ikm, salt, info) → 32-byte key: the factor, pair and single KEKs (docs/FACTORS.md).
|
||||
pub fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
let mut k = Zeroizing::new([0u8; KEY_LEN]);
|
||||
hkdf::Hkdf::<sha2::Sha256>::new(Some(salt), ikm).expand(info, k.as_mut()).expect("32 bytes is a valid HKDF length");
|
||||
k
|
||||
}
|
||||
|
||||
/// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD.
|
||||
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
|
||||
cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new)
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout").
|
||||
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout"; version 2 in
|
||||
//! docs/FACTORS.md).
|
||||
|
||||
use crate::crypto::{KEY_LEN, NONCE_LEN, TAG_LEN};
|
||||
use crate::{Error, KdfParams};
|
||||
|
||||
pub const MAGIC: &[u8; 6] = b"CUSTOS";
|
||||
pub const VERSION: u16 = 1;
|
||||
/// Two factors (docs/FACTORS.md).
|
||||
pub const VERSION_2: u16 = 2;
|
||||
pub const MAX_SLOTS: usize = 8;
|
||||
pub const MAX_SLOTS_V2: usize = 64;
|
||||
pub const MAX_FACTORS: usize = 8;
|
||||
pub const SLOT_PASSWORD: u8 = 1;
|
||||
pub const SLOT_FACTOR: u8 = 2;
|
||||
pub const SLOT_PAIR: u8 = 3;
|
||||
pub const SLOT_SINGLE: u8 = 4;
|
||||
const KDF_ARGON2ID: u8 = 1;
|
||||
pub const SALT_LEN: usize = 32;
|
||||
pub const ID_LEN: usize = 16;
|
||||
/// kdf(1) m(4) t(4) p(4) salt(32) nonce(24): the part of a password slot that is its own AAD.
|
||||
const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_LEN;
|
||||
const PW_PAYLOAD_LEN: usize = PW_AAD_LEN + KEY_LEN + TAG_LEN;
|
||||
const WRAPPED_LEN: usize = KEY_LEN + TAG_LEN;
|
||||
|
||||
/// One key slot as stored. Unknown kinds are kept and written back unchanged.
|
||||
/// One key slot as stored. Unknown kinds are kept and written back unchanged (version 1).
|
||||
#[derive(Clone)]
|
||||
pub struct RawSlot {
|
||||
pub kind: u8,
|
||||
@@ -73,7 +83,169 @@ impl PasswordSlot {
|
||||
}
|
||||
}
|
||||
|
||||
fn v2_aad(kind: u8, head: &[u8]) -> Vec<u8> {
|
||||
let mut a = Vec::with_capacity(9 + head.len());
|
||||
a.extend_from_slice(MAGIC);
|
||||
a.extend_from_slice(&VERSION_2.to_le_bytes());
|
||||
a.push(kind);
|
||||
a.extend_from_slice(head);
|
||||
a
|
||||
}
|
||||
|
||||
/// A factor slot (kind 2): the factor key `F`, wrapped by a KEK from the factor's material.
|
||||
pub struct FactorSlot {
|
||||
pub id: [u8; ID_LEN],
|
||||
pub kind: u8,
|
||||
/// Argon2id parameters; password factors only.
|
||||
pub kdf: Option<KdfParams>,
|
||||
pub salt: [u8; SALT_LEN],
|
||||
pub nonce: [u8; NONCE_LEN],
|
||||
pub wrapped: Vec<u8>,
|
||||
}
|
||||
|
||||
impl FactorSlot {
|
||||
fn head(&self) -> Vec<u8> {
|
||||
let mut p = Vec::with_capacity(ID_LEN + 1 + 13 + SALT_LEN + NONCE_LEN);
|
||||
p.extend_from_slice(&self.id);
|
||||
p.push(self.kind);
|
||||
if let Some(k) = self.kdf {
|
||||
p.push(KDF_ARGON2ID);
|
||||
p.extend_from_slice(&k.m_cost_kib.to_le_bytes());
|
||||
p.extend_from_slice(&k.t_cost.to_le_bytes());
|
||||
p.extend_from_slice(&k.p_cost.to_le_bytes());
|
||||
}
|
||||
p.extend_from_slice(&self.salt);
|
||||
p.extend_from_slice(&self.nonce);
|
||||
p
|
||||
}
|
||||
|
||||
pub fn aad(&self) -> Vec<u8> {
|
||||
v2_aad(SLOT_FACTOR, &self.head())
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = self.head();
|
||||
p.extend_from_slice(&self.wrapped);
|
||||
RawSlot { kind: SLOT_FACTOR, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
let kind = *payload.get(ID_LEN).ok_or(Error::Malformed)?;
|
||||
let id: [u8; ID_LEN] = payload[..ID_LEN].try_into().unwrap();
|
||||
let mut at = ID_LEN + 1;
|
||||
let kdf = match kind {
|
||||
1 => {
|
||||
if payload.len() != at + 13 + SALT_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
if payload[at] != KDF_ARGON2ID {
|
||||
return Err(Error::UnsupportedKdf);
|
||||
}
|
||||
let u32_at = |i: usize| u32::from_le_bytes(payload[i..i + 4].try_into().unwrap());
|
||||
let k = KdfParams { m_cost_kib: u32_at(at + 1), t_cost: u32_at(at + 5), p_cost: u32_at(at + 9) };
|
||||
k.check()?;
|
||||
at += 13;
|
||||
Some(k)
|
||||
}
|
||||
2..=5 => {
|
||||
if payload.len() != at + SALT_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
None
|
||||
}
|
||||
_ => return Err(Error::Malformed),
|
||||
};
|
||||
Ok(FactorSlot {
|
||||
id,
|
||||
kind,
|
||||
kdf,
|
||||
salt: payload[at..at + SALT_LEN].try_into().unwrap(),
|
||||
nonce: payload[at + SALT_LEN..at + SALT_LEN + NONCE_LEN].try_into().unwrap(),
|
||||
wrapped: payload[at + SALT_LEN + NONCE_LEN..].to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A pair slot (kind 3): the vault key, wrapped by a KEK from two factor keys. `a < b` bytewise.
|
||||
pub struct PairSlot {
|
||||
pub a: [u8; ID_LEN],
|
||||
pub b: [u8; ID_LEN],
|
||||
pub nonce: [u8; NONCE_LEN],
|
||||
pub wrapped: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PairSlot {
|
||||
pub fn aad(&self) -> Vec<u8> {
|
||||
let mut h = Vec::with_capacity(2 * ID_LEN + NONCE_LEN);
|
||||
h.extend_from_slice(&self.a);
|
||||
h.extend_from_slice(&self.b);
|
||||
h.extend_from_slice(&self.nonce);
|
||||
v2_aad(SLOT_PAIR, &h)
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = Vec::with_capacity(2 * ID_LEN + NONCE_LEN + WRAPPED_LEN);
|
||||
p.extend_from_slice(&self.a);
|
||||
p.extend_from_slice(&self.b);
|
||||
p.extend_from_slice(&self.nonce);
|
||||
p.extend_from_slice(&self.wrapped);
|
||||
RawSlot { kind: SLOT_PAIR, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
if payload.len() != 2 * ID_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let s = PairSlot {
|
||||
a: payload[..ID_LEN].try_into().unwrap(),
|
||||
b: payload[ID_LEN..2 * ID_LEN].try_into().unwrap(),
|
||||
nonce: payload[2 * ID_LEN..2 * ID_LEN + NONCE_LEN].try_into().unwrap(),
|
||||
wrapped: payload[2 * ID_LEN + NONCE_LEN..].to_vec(),
|
||||
};
|
||||
if s.a >= s.b {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single slot (kind 4, machine stores only): the vault key, wrapped by one factor key.
|
||||
pub struct SingleSlot {
|
||||
pub id: [u8; ID_LEN],
|
||||
pub nonce: [u8; NONCE_LEN],
|
||||
pub wrapped: Vec<u8>,
|
||||
}
|
||||
|
||||
impl SingleSlot {
|
||||
pub fn aad(&self) -> Vec<u8> {
|
||||
let mut h = Vec::with_capacity(ID_LEN + NONCE_LEN);
|
||||
h.extend_from_slice(&self.id);
|
||||
h.extend_from_slice(&self.nonce);
|
||||
v2_aad(SLOT_SINGLE, &h)
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = Vec::with_capacity(ID_LEN + NONCE_LEN + WRAPPED_LEN);
|
||||
p.extend_from_slice(&self.id);
|
||||
p.extend_from_slice(&self.nonce);
|
||||
p.extend_from_slice(&self.wrapped);
|
||||
RawSlot { kind: SLOT_SINGLE, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
if payload.len() != ID_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(SingleSlot {
|
||||
id: payload[..ID_LEN].try_into().unwrap(),
|
||||
nonce: payload[ID_LEN..ID_LEN + NONCE_LEN].try_into().unwrap(),
|
||||
wrapped: payload[ID_LEN + NONCE_LEN..].to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Header {
|
||||
pub version: u16,
|
||||
pub slots: Vec<RawSlot>,
|
||||
pub body_nonce: [u8; NONCE_LEN],
|
||||
}
|
||||
@@ -82,7 +254,7 @@ impl Header {
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut h = Vec::new();
|
||||
h.extend_from_slice(MAGIC);
|
||||
h.extend_from_slice(&VERSION.to_le_bytes());
|
||||
h.extend_from_slice(&self.version.to_le_bytes());
|
||||
h.push(self.slots.len() as u8);
|
||||
for s in &self.slots {
|
||||
h.push(s.kind);
|
||||
@@ -99,11 +271,13 @@ impl Header {
|
||||
return Err(Error::NotAVault);
|
||||
}
|
||||
let version = u16::from_le_bytes([bytes[6], bytes[7]]);
|
||||
if version != VERSION {
|
||||
return Err(Error::UnsupportedVersion(version));
|
||||
}
|
||||
let max = match version {
|
||||
VERSION => MAX_SLOTS,
|
||||
VERSION_2 => MAX_SLOTS_V2,
|
||||
v => return Err(Error::UnsupportedVersion(v)),
|
||||
};
|
||||
let count = bytes[8] as usize;
|
||||
if count == 0 || count > MAX_SLOTS {
|
||||
if count == 0 || count > max {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut at = 9;
|
||||
@@ -120,6 +294,69 @@ impl Header {
|
||||
if bytes.len() < at + TAG_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok((Header { slots, body_nonce }, at))
|
||||
let header = Header { version, slots, body_nonce };
|
||||
if version == VERSION_2 {
|
||||
header.check_v2()?;
|
||||
}
|
||||
Ok((header, at))
|
||||
}
|
||||
|
||||
/// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces").
|
||||
fn check_v2(&self) -> Result<(), Error> {
|
||||
let mut ids = Vec::new();
|
||||
for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) {
|
||||
ids.push(FactorSlot::parse(&s.payload)?.id);
|
||||
}
|
||||
if ids.is_empty() || ids.len() > MAX_FACTORS {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut seen = ids.clone();
|
||||
seen.sort();
|
||||
seen.dedup();
|
||||
if seen.len() != ids.len() {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut singles = 0;
|
||||
for s in &self.slots {
|
||||
match s.kind {
|
||||
SLOT_FACTOR => {}
|
||||
SLOT_PAIR => {
|
||||
let p = PairSlot::parse(&s.payload)?;
|
||||
if !ids.contains(&p.a) || !ids.contains(&p.b) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
}
|
||||
SLOT_SINGLE => {
|
||||
let p = SingleSlot::parse(&s.payload)?;
|
||||
if !ids.contains(&p.id) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
singles += 1;
|
||||
}
|
||||
// A v1 password slot, or an unknown kind, has no place in a v2 header.
|
||||
_ => return Err(Error::Malformed),
|
||||
}
|
||||
}
|
||||
// A machine store is exactly one factor and its single slot.
|
||||
if singles > 0 && (singles != 1 || ids.len() != 1) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn factor_slots(&self) -> Vec<FactorSlot> {
|
||||
self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn pair_slots(&self) -> Vec<PairSlot> {
|
||||
self.slots.iter().filter(|s| s.kind == SLOT_PAIR).filter_map(|s| PairSlot::parse(&s.payload).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn single_slot(&self) -> Option<SingleSlot> {
|
||||
self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok())
|
||||
}
|
||||
|
||||
pub fn is_machine_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == SLOT_SINGLE)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,16 +16,19 @@ pub enum ItemType {
|
||||
Wifi,
|
||||
SecureNote,
|
||||
Card,
|
||||
/// A signing or SSH key pair (docs/FACTORS.md, "The key-pair item type").
|
||||
KeyPair,
|
||||
}
|
||||
|
||||
impl ItemType {
|
||||
pub const ALL: [ItemType; 6] = [
|
||||
pub const ALL: [ItemType; 7] = [
|
||||
ItemType::WebLogin,
|
||||
ItemType::ApiCredential,
|
||||
ItemType::LocalApp,
|
||||
ItemType::Wifi,
|
||||
ItemType::SecureNote,
|
||||
ItemType::Card,
|
||||
ItemType::KeyPair,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
@@ -36,6 +39,7 @@ impl ItemType {
|
||||
ItemType::Wifi => "Wi-Fi",
|
||||
ItemType::SecureNote => "Secure note",
|
||||
ItemType::Card => "Card",
|
||||
ItemType::KeyPair => "Key pair",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +63,15 @@ impl ItemType {
|
||||
ItemType::Card => {
|
||||
&[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)]
|
||||
}
|
||||
ItemType::KeyPair => &[
|
||||
("algorithm", false),
|
||||
("public-key", false),
|
||||
("public-pem", false),
|
||||
("private-key", true),
|
||||
("private-openssh", true),
|
||||
("fingerprint", false),
|
||||
("comment", false),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+485
-30
@@ -1,13 +1,18 @@
|
||||
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md.
|
||||
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md
|
||||
//! (version 1) and docs/FACTORS.md (version 2: any two factors).
|
||||
//!
|
||||
//! ```
|
||||
//! use custos_vault::{Item, ItemType, KdfParams, SecretString, Vault};
|
||||
//! use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
|
||||
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
|
||||
//! let device_key = [7u8; 32]; // in the app: a key file only this Windows account can read
|
||||
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
//! let mut vault = Vault::create(&password, kdf)?;
|
||||
//! let mut vault = Vault::create_with(
|
||||
//! Unlock::Password(&password), "Master password",
|
||||
//! Unlock::Material(FactorKind::Device, &device_key), "This PC", 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);
|
||||
//! let back = Vault::open_with(&bytes, Unlock::Password(&password), Unlock::Material(FactorKind::Device, &device_key))?;
|
||||
//! assert_eq!(back.items().len(), 1);
|
||||
//! # Ok::<(), custos_vault::Error>(())
|
||||
//! ```
|
||||
|
||||
@@ -23,7 +28,10 @@ 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 format::{
|
||||
FactorSlot, Header, ID_LEN, MAX_FACTORS, PairSlot, PasswordSlot, RawSlot, SALT_LEN, SLOT_FACTOR, SLOT_PAIR,
|
||||
SLOT_PASSWORD, SingleSlot, VERSION, VERSION_2,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
@@ -45,6 +53,12 @@ pub enum Error {
|
||||
Corrupted,
|
||||
#[error("this device's unlock key no longer opens the vault; use the master password")]
|
||||
DeviceKeyRejected,
|
||||
#[error("this vault opens with two different factors")]
|
||||
NeedTwoFactors,
|
||||
#[error("this factor does not open the vault")]
|
||||
FactorRejected,
|
||||
#[error("a vault has at most 8 factors and one master password")]
|
||||
TooManyFactors,
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
@@ -80,12 +94,160 @@ impl Default for KdfParams {
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of secret a factor is (docs/FACTORS.md, "Factor KEKs").
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum FactorKind {
|
||||
/// The master password.
|
||||
Password,
|
||||
/// A key one device keeps (a DPAPI-protected key file, a key in the phone's storage).
|
||||
Device,
|
||||
/// A share the TOTP service releases after a valid code.
|
||||
Totp,
|
||||
/// A secret another paired device sends after you approve there.
|
||||
Approval,
|
||||
/// A WebAuthn PRF output (Face ID, Touch ID, Windows Hello passkey).
|
||||
Passkey,
|
||||
}
|
||||
|
||||
impl FactorKind {
|
||||
fn code(self) -> u8 {
|
||||
match self {
|
||||
FactorKind::Password => 1,
|
||||
FactorKind::Device => 2,
|
||||
FactorKind::Totp => 3,
|
||||
FactorKind::Approval => 4,
|
||||
FactorKind::Passkey => 5,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_code(c: u8) -> Option<Self> {
|
||||
Some(match c {
|
||||
1 => FactorKind::Password,
|
||||
2 => FactorKind::Device,
|
||||
3 => FactorKind::Totp,
|
||||
4 => FactorKind::Approval,
|
||||
5 => FactorKind::Passkey,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One factor given to open a vault. `Debug` never prints the password or the material.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Unlock<'a> {
|
||||
Password(&'a SecretString),
|
||||
/// Any other factor: its kind and 32..=64 bytes of material.
|
||||
Material(FactorKind, &'a [u8]),
|
||||
}
|
||||
|
||||
impl Unlock<'_> {
|
||||
fn kind(&self) -> FactorKind {
|
||||
match self {
|
||||
Unlock::Password(_) => FactorKind::Password,
|
||||
Unlock::Material(k, _) => *k,
|
||||
}
|
||||
}
|
||||
|
||||
/// Material for types 2..5 must be 32..=64 bytes, and a password is never passed as material.
|
||||
fn check(&self) -> Result<(), Error> {
|
||||
match self {
|
||||
Unlock::Password(_) => Ok(()),
|
||||
Unlock::Material(FactorKind::Password, _) => Err(Error::FactorRejected),
|
||||
Unlock::Material(_, m) if (32..=64).contains(&m.len()) => Ok(()),
|
||||
Unlock::Material(..) => Err(Error::FactorRejected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Unlock<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Unlock::Password(_) => f.write_str("Password([redacted])"),
|
||||
Unlock::Material(k, _) => write!(f, "Material({k:?}, [redacted])"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A factor of an unlocked vault, as the app lists it. Never carries the factor key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FactorInfo {
|
||||
/// 32 hex digits.
|
||||
pub id: String,
|
||||
pub kind: FactorKind,
|
||||
pub label: String,
|
||||
pub created: i64,
|
||||
}
|
||||
|
||||
/// A factor as the body keeps it: its key `F` is what lets an unlocked vault add pairs.
|
||||
#[derive(Clone)]
|
||||
struct FactorRec {
|
||||
id: [u8; ID_LEN],
|
||||
kind: FactorKind,
|
||||
label: String,
|
||||
created: i64,
|
||||
key: Zeroizing<[u8; KEY_LEN]>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct FactorJson {
|
||||
id: String,
|
||||
#[serde(rename = "type")]
|
||||
kind: FactorKind,
|
||||
label: String,
|
||||
created: i64,
|
||||
key: SecretString,
|
||||
}
|
||||
|
||||
fn hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
|
||||
if s.len() != 2 * N {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; N];
|
||||
for (i, o) in out.iter_mut().enumerate() {
|
||||
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl FactorRec {
|
||||
fn json(&self) -> FactorJson {
|
||||
FactorJson {
|
||||
id: hex(&self.id),
|
||||
kind: self.kind,
|
||||
label: self.label.clone(),
|
||||
created: self.created,
|
||||
key: SecretString::new(hex(self.key.as_ref())),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_json(j: &FactorJson) -> Option<FactorRec> {
|
||||
Some(FactorRec {
|
||||
id: unhex(&j.id)?,
|
||||
kind: j.kind,
|
||||
label: j.label.clone(),
|
||||
created: j.created,
|
||||
key: Zeroizing::new(unhex(j.key.expose())?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const BODY_FORMAT: u32 = 1;
|
||||
const BODY_FORMAT_2: u32 = 2;
|
||||
const INFO_FACTOR: &[u8] = b"custos factor v2";
|
||||
const INFO_PAIR: &[u8] = b"custos pair v2";
|
||||
const INFO_SINGLE: &[u8] = b"custos single v2";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Body {
|
||||
format: u32,
|
||||
items: Vec<Item>,
|
||||
#[serde(default)]
|
||||
factors: Vec<FactorJson>,
|
||||
}
|
||||
|
||||
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
||||
@@ -93,18 +255,29 @@ struct Body {
|
||||
struct BodyRef<'a> {
|
||||
format: u32,
|
||||
items: &'a [Item],
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
factors: Vec<FactorJson>,
|
||||
}
|
||||
|
||||
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
||||
pub struct Vault {
|
||||
key: Zeroizing<[u8; KEY_LEN]>,
|
||||
version: u16,
|
||||
slots: Vec<RawSlot>,
|
||||
items: Vec<Item>,
|
||||
/// Version 2 only.
|
||||
factors: Vec<FactorRec>,
|
||||
/// Argon2 parameters for a password factor added later.
|
||||
kdf_new: KdfParams,
|
||||
}
|
||||
|
||||
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()
|
||||
f.debug_struct("Vault")
|
||||
.field("version", &self.version)
|
||||
.field("items", &self.items.len())
|
||||
.field("factors", &self.factors.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,21 +291,127 @@ fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
/// The KEK a factor's material gives for one factor slot.
|
||||
fn factor_kek(u: &Unlock, salt: &[u8], kdf: Option<KdfParams>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
|
||||
match (u, kdf) {
|
||||
(Unlock::Password(p), Some(k)) => crypto::derive_kek(p.expose().as_bytes(), salt, k),
|
||||
(Unlock::Material(_, m), None) => Ok(crypto::hkdf(m, salt, INFO_FACTOR)),
|
||||
_ => Err(Error::FactorRejected),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new factor slot wrapping `key` (the factor key `F`) with `u`'s material.
|
||||
fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams) -> Result<FactorSlot, Error> {
|
||||
u.check()?;
|
||||
let kdf = matches!(u, Unlock::Password(_)).then_some(kdf);
|
||||
if let Some(k) = kdf {
|
||||
k.check()?;
|
||||
}
|
||||
let mut salt = [0u8; SALT_LEN];
|
||||
crypto::fill_random(&mut salt);
|
||||
let mut slot = FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
|
||||
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn pair_kek(a: &FactorRec, b: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
let (x, y) = if a.id < b.id { (a, b) } else { (b, a) };
|
||||
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
|
||||
ikm[..KEY_LEN].copy_from_slice(x.key.as_ref());
|
||||
ikm[KEY_LEN..].copy_from_slice(y.key.as_ref());
|
||||
let mut salt = [0u8; 2 * ID_LEN];
|
||||
salt[..ID_LEN].copy_from_slice(&x.id);
|
||||
salt[ID_LEN..].copy_from_slice(&y.id);
|
||||
crypto::hkdf(ikm.as_ref(), &salt, INFO_PAIR)
|
||||
}
|
||||
|
||||
fn pair_slot(vault_key: &[u8; KEY_LEN], a: &FactorRec, b: &FactorRec) -> PairSlot {
|
||||
let (x, y) = if a.id < b.id { (a.id, b.id) } else { (b.id, a.id) };
|
||||
let mut slot = PairSlot { a: x, b: y, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
slot.wrapped = crypto::seal(&pair_kek(a, b), &slot.nonce, vault_key, &slot.aad());
|
||||
slot
|
||||
}
|
||||
|
||||
fn single_kek(f: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
crypto::hkdf(f.key.as_ref(), &f.id, INFO_SINGLE)
|
||||
}
|
||||
|
||||
fn key32(k: Zeroizing<Vec<u8>>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
|
||||
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?))
|
||||
}
|
||||
|
||||
/// The first factor slot of `u`'s kind that `u` unwraps: its id and factor key.
|
||||
fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
|
||||
u.check()?;
|
||||
for slot in header.factor_slots().into_iter().filter(|s| s.kind == u.kind().code()) {
|
||||
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
|
||||
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
|
||||
return Ok(FactorRec { id: slot.id, kind: u.kind(), label: String::new(), created: 0, key: key32(k)? });
|
||||
}
|
||||
}
|
||||
Err(if matches!(u, Unlock::Password(_)) { Error::WrongPassword } else { Error::FactorRejected })
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
/// A new, empty vault with a fresh random vault key wrapped by `password`.
|
||||
/// A new, empty version-1 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() })
|
||||
Ok(Vault { key, version: VERSION, slots: vec![slot.raw()], items: Vec::new(), factors: Vec::new(), kdf_new: kdf })
|
||||
}
|
||||
|
||||
/// A new, empty version-2 vault that opens with these two factors together (docs/FACTORS.md).
|
||||
pub fn create_with(a: Unlock, label_a: &str, b: Unlock, label_b: &str, kdf: KdfParams) -> Result<Vault, Error> {
|
||||
if a.kind() == FactorKind::Password && b.kind() == FactorKind::Password {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let mut v = Vault {
|
||||
key: crypto::random_key(),
|
||||
version: VERSION_2,
|
||||
slots: Vec::new(),
|
||||
items: Vec::new(),
|
||||
factors: Vec::new(),
|
||||
kdf_new: kdf,
|
||||
};
|
||||
v.add_factor(a, label_a)?;
|
||||
v.add_factor(b, label_b)?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// A machine store: a separate vault that one device key opens alone, for a program that must
|
||||
/// open it unattended (the Claude Code store). Never for the user's own secrets.
|
||||
pub fn create_machine_store(material: &[u8], label: &str) -> Result<Vault, Error> {
|
||||
let u = Unlock::Material(FactorKind::Device, material);
|
||||
u.check()?;
|
||||
let key = crypto::random_key();
|
||||
let mut id = [0u8; ID_LEN];
|
||||
crypto::fill_random(&mut id);
|
||||
let rec = FactorRec { id, kind: FactorKind::Device, label: label.into(), created: now_ms(), key: crypto::random_key() };
|
||||
let fslot = factor_slot(id, &rec.key, &u, KdfParams::DEFAULT)?;
|
||||
let mut single = SingleSlot { id, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
single.wrapped = crypto::seal(&single_kek(&rec), &single.nonce, key.as_ref(), &single.aad());
|
||||
Ok(Vault {
|
||||
key,
|
||||
version: VERSION_2,
|
||||
slots: vec![fslot.raw(), single.raw()],
|
||||
items: Vec::new(),
|
||||
factors: vec![rec],
|
||||
kdf_new: KdfParams::DEFAULT,
|
||||
})
|
||||
}
|
||||
|
||||
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.
|
||||
/// Unlocks a version-1 vault with its password. A version-2 vault needs [`Vault::open_with`].
|
||||
/// 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)?;
|
||||
if header.version == VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let pw_slots: Vec<PasswordSlot> = header
|
||||
.slots
|
||||
.iter()
|
||||
@@ -145,34 +424,104 @@ impl Vault {
|
||||
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);
|
||||
let kdf = slot.kdf;
|
||||
let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
|
||||
v.kdf_new = kdf;
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
Err(Error::WrongPassword)
|
||||
}
|
||||
|
||||
/// Unlocks a version-2 vault with two different factors, in any order (docs/FACTORS.md, "Opening").
|
||||
pub fn open_with(bytes: &[u8], a: Unlock, b: Unlock) -> Result<Vault, Error> {
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version != VERSION_2 || header.is_machine_store() {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
// Refuse bad material before any Argon2 work.
|
||||
a.check()?;
|
||||
b.check()?;
|
||||
let fa = unwrap_factor(&header, &a)?;
|
||||
let fb = unwrap_factor(&header, &b)?;
|
||||
if fa.id == fb.id {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
|
||||
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::Corrupted)?;
|
||||
let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
|
||||
Vault::open_body(bytes, header, body_at, key32(k)?)
|
||||
}
|
||||
|
||||
/// Opens a machine store with its one device key. A user vault is never opened this way.
|
||||
pub fn open_machine_store(bytes: &[u8], material: &[u8]) -> Result<Vault, Error> {
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version != VERSION_2 || !header.is_machine_store() {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let f = unwrap_factor(&header, &Unlock::Material(FactorKind::Device, material))?;
|
||||
let slot = header.single_slot().filter(|s| s.id == f.id).ok_or(Error::Corrupted)?;
|
||||
let k = crypto::open(&single_kek(&f), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
|
||||
Vault::open_body(bytes, header, body_at, key32(k)?)
|
||||
}
|
||||
|
||||
/// The format version of a vault file (1 or 2), from its header alone.
|
||||
pub fn version_of(bytes: &[u8]) -> Result<u16, Error> {
|
||||
Ok(Header::parse(bytes)?.0.version)
|
||||
}
|
||||
|
||||
/// The kinds of factor a vault opens with, from its header alone: what the unlock screen offers.
|
||||
pub fn factor_kinds(bytes: &[u8]) -> Result<Vec<FactorKind>, Error> {
|
||||
let (header, _) = Header::parse(bytes)?;
|
||||
if header.version == VERSION {
|
||||
return Ok(vec![FactorKind::Password]);
|
||||
}
|
||||
Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect())
|
||||
}
|
||||
|
||||
pub fn is_machine_store(bytes: &[u8]) -> Result<bool, Error> {
|
||||
Ok(Header::parse(bytes)?.0.is_machine_store())
|
||||
}
|
||||
|
||||
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 {
|
||||
let want = if header.version == VERSION_2 { BODY_FORMAT_2 } else { BODY_FORMAT };
|
||||
if body.format != want {
|
||||
return Err(Error::Corrupted);
|
||||
}
|
||||
Ok(Vault { key, slots: header.slots, items: body.items })
|
||||
let factors: Vec<FactorRec> = body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
|
||||
// Every factor slot in the header has its key in the body, and the other way round.
|
||||
if header.version == VERSION_2 {
|
||||
let mut in_header: Vec<_> = header.factor_slots().iter().map(|s| s.id).collect();
|
||||
let mut in_body: Vec<_> = factors.iter().map(|f| f.id).collect();
|
||||
in_header.sort();
|
||||
in_body.sort();
|
||||
if in_header != in_body {
|
||||
return Err(Error::Corrupted);
|
||||
}
|
||||
}
|
||||
let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT);
|
||||
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new })
|
||||
}
|
||||
|
||||
/// 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".
|
||||
/// Windows Hello signature). Version 1 only: a version-2 vault never opens with one secret.
|
||||
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
if self.version == VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
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.
|
||||
/// Unlocks with a device blob instead of the password (version 1). 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)?;
|
||||
if header.version == VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let key = device::unwrap(blob, material)?;
|
||||
Vault::open_body(bytes, header, body_at, key)
|
||||
}
|
||||
@@ -180,9 +529,14 @@ impl Vault {
|
||||
/// 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 out = Header { version: self.version, 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 };
|
||||
let v2 = self.version == VERSION_2;
|
||||
let body = BodyRef {
|
||||
format: if v2 { BODY_FORMAT_2 } else { BODY_FORMAT },
|
||||
items: &self.items,
|
||||
factors: self.factors.iter().map(FactorRec::json).collect(),
|
||||
};
|
||||
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);
|
||||
@@ -194,28 +548,129 @@ impl Vault {
|
||||
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.
|
||||
/// Changes the master password. Version 1: a new password slot. Version 2: the password factor's
|
||||
/// key is rewrapped, so its pairs keep working (also after a forgotten password: open with two
|
||||
/// other factors, then set a new one). 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());
|
||||
if self.version == VERSION {
|
||||
let slot = password_slot(&self.key, new_password, kdf)?;
|
||||
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
|
||||
self.slots.insert(0, slot.raw());
|
||||
self.kdf_new = kdf;
|
||||
return Ok(());
|
||||
}
|
||||
if self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
self.kdf_new = kdf;
|
||||
let Some(rec) = self.factors.iter().find(|f| f.kind == FactorKind::Password).cloned() else {
|
||||
self.add_factor(Unlock::Password(new_password), "Master password")?;
|
||||
return Ok(());
|
||||
};
|
||||
let slot = factor_slot(rec.id, &rec.key, &Unlock::Password(new_password), kdf)?;
|
||||
let at = self.factor_slot_index(&rec.id).ok_or(Error::Corrupted)?;
|
||||
self.slots[at] = slot.raw();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
|
||||
}
|
||||
|
||||
fn factor_slot_index(&self, id: &[u8; ID_LEN]) -> Option<usize> {
|
||||
self.slots.iter().position(|s| s.kind == SLOT_FACTOR && s.payload.get(..ID_LEN) == Some(&id[..]))
|
||||
}
|
||||
|
||||
/// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md).
|
||||
/// Returns its id. A second master password is refused; use [`Vault::change_password`].
|
||||
pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result<String, Error> {
|
||||
if self.version != VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
if self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
u.check()?;
|
||||
if self.factors.len() >= MAX_FACTORS
|
||||
|| (u.kind() == FactorKind::Password && self.factors.iter().any(|f| f.kind == FactorKind::Password))
|
||||
{
|
||||
return Err(Error::TooManyFactors);
|
||||
}
|
||||
let mut id = [0u8; ID_LEN];
|
||||
crypto::fill_random(&mut id);
|
||||
let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() };
|
||||
let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?;
|
||||
self.slots.push(slot.raw());
|
||||
for other in &self.factors {
|
||||
self.slots.push(pair_slot(&self.key, &rec, other).raw());
|
||||
}
|
||||
self.factors.push(rec);
|
||||
Ok(hex(&id))
|
||||
}
|
||||
|
||||
/// Removes a factor (a lost phone, an old PC) and every pair it is part of. A vault keeps at least two.
|
||||
pub fn remove_factor(&mut self, id: &str) -> Result<(), Error> {
|
||||
let id: [u8; ID_LEN] = unhex(id).ok_or(Error::FactorRejected)?;
|
||||
if !self.factors.iter().any(|f| f.id == id) {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
if self.factors.len() <= 2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
self.factors.retain(|f| f.id != id);
|
||||
self.slots.retain(|s| match s.kind {
|
||||
SLOT_FACTOR => s.payload.get(..ID_LEN) != Some(&id[..]),
|
||||
SLOT_PAIR => s.payload.get(..ID_LEN) != Some(&id[..]) && s.payload.get(ID_LEN..2 * ID_LEN) != Some(&id[..]),
|
||||
_ => true,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turns an unlocked version-1 vault into version 2 with its password and a second factor.
|
||||
/// The vault key and the items stay; from the next save on, the password alone opens nothing.
|
||||
pub fn upgrade_to_two_factors(&mut self, password: &SecretString, kdf: KdfParams, second: Unlock, label: &str) -> Result<(), Error> {
|
||||
if self.version != VERSION {
|
||||
return Err(Error::UnsupportedVersion(self.version));
|
||||
}
|
||||
if second.kind() == FactorKind::Password {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
second.check()?;
|
||||
self.version = VERSION_2;
|
||||
self.slots.clear();
|
||||
self.factors.clear();
|
||||
self.kdf_new = kdf;
|
||||
self.add_factor(Unlock::Password(password), "Master password")?;
|
||||
self.add_factor(second, label)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The factors of a version-2 vault, oldest first. Empty for version 1.
|
||||
pub fn factors(&self) -> Vec<FactorInfo> {
|
||||
self.factors
|
||||
.iter()
|
||||
.map(|f| FactorInfo { id: hex(&f.id), kind: f.kind, label: f.label.clone(), created: f.created })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 1 or 2.
|
||||
pub fn version(&self) -> u16 {
|
||||
self.version
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// The KDF parameters of the (first) password slot or password factor.
|
||||
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)
|
||||
self.slots.iter().find_map(|s| match s.kind {
|
||||
SLOT_PASSWORD => PasswordSlot::parse(&s.payload).ok().map(|p| p.kdf),
|
||||
SLOT_FACTOR => FactorSlot::parse(&s.payload).ok().and_then(|f| f.kdf),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn items(&self) -> &[Item] {
|
||||
|
||||
@@ -80,6 +80,7 @@ pub fn primary_secret(kind: ItemType) -> &'static str {
|
||||
ItemType::ApiCredential => "secret",
|
||||
ItemType::Card => "number",
|
||||
ItemType::SecureNote => "notes",
|
||||
ItemType::KeyPair => "private-key",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +91,7 @@ fn primary_user(kind: ItemType) -> Option<&'static str> {
|
||||
ItemType::Wifi => Some("ssid"),
|
||||
ItemType::Card => Some("cardholder"),
|
||||
ItemType::SecureNote => None,
|
||||
ItemType::KeyPair => Some("public-key"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user