diff --git a/Cargo.lock b/Cargo.lock index 74fc442..25f4bbb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,14 +329,14 @@ dependencies = [ [[package]] name = "custos-browser" -version = "0.16.1" +version = "0.17.0" dependencies = [ "zeroize", ] [[package]] name = "custos-gen" -version = "0.16.1" +version = "0.17.0" dependencies = [ "custos-vault", "data-encoding", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "custos-kdbx" -version = "0.16.1" +version = "0.17.0" dependencies = [ "aes", "argon2", @@ -369,7 +369,7 @@ dependencies = [ [[package]] name = "custos-keys" -version = "0.16.1" +version = "0.17.0" dependencies = [ "custos-vault", "ed25519-dalek", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "custos-native" -version = "0.16.1" +version = "0.17.0" dependencies = [ "custos-browser", "serde_json", @@ -392,11 +392,11 @@ dependencies = [ [[package]] name = "custos-qr" -version = "0.16.1" +version = "0.17.0" [[package]] name = "custos-seal" -version = "0.16.1" +version = "0.17.0" dependencies = [ "chacha20poly1305", "hkdf", @@ -409,7 +409,7 @@ dependencies = [ [[package]] name = "custos-share" -version = "0.16.1" +version = "0.17.0" dependencies = [ "argon2", "chacha20poly1305", @@ -426,7 +426,7 @@ dependencies = [ [[package]] name = "custos-sign" -version = "0.16.1" +version = "0.17.0" dependencies = [ "blake2 0.10.6", "data-encoding", @@ -445,7 +445,7 @@ dependencies = [ [[package]] name = "custos-totp" -version = "0.16.1" +version = "0.17.0" dependencies = [ "custos-vault", "data-encoding", @@ -458,7 +458,7 @@ dependencies = [ [[package]] name = "custos-vault" -version = "0.16.1" +version = "0.17.0" dependencies = [ "argon2", "bip39", @@ -482,7 +482,7 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.16.1" +version = "0.17.0" dependencies = [ "custos-qr", "custos-seal", diff --git a/Cargo.toml b/Cargo.toml index 5c15d45..905fe6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.16.1" +version = "0.17.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-vault/src/format.rs b/crates/custos-vault/src/format.rs index cea9a0e..3fe4309 100644 --- a/crates/custos-vault/src/format.rs +++ b/crates/custos-vault/src/format.rs @@ -15,6 +15,9 @@ pub const SLOT_PASSWORD: u8 = 1; pub const SLOT_FACTOR: u8 = 2; pub const SLOT_PAIR: u8 = 3; pub const SLOT_SINGLE: u8 = 4; +/// The recovery key's slot (core 0.17.0; docs/FACTORS.md, "The recovery key"). +pub const SLOT_RECOVERY: u8 = 5; +pub const RECOVERY_ID_LEN: usize = 4; const KDF_ARGON2ID: u8 = 1; pub const SALT_LEN: usize = 32; pub const ID_LEN: usize = 16; @@ -244,6 +247,48 @@ impl SingleSlot { } } +/// The recovery slot (kind 5): the vault key, wrapped by the recovery key alone. At most one, never in a machine +/// store. `id` says which printed key it is and is not secret. +pub struct RecoverySlot { + pub id: [u8; RECOVERY_ID_LEN], + pub salt: [u8; SALT_LEN], + pub nonce: [u8; NONCE_LEN], + pub wrapped: Vec, +} + +impl RecoverySlot { + fn head(&self) -> Vec { + let mut h = Vec::with_capacity(RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN); + h.extend_from_slice(&self.id); + h.extend_from_slice(&self.salt); + h.extend_from_slice(&self.nonce); + h + } + + pub fn aad(&self) -> Vec { + v2_aad(SLOT_RECOVERY, &self.head()) + } + + pub fn raw(&self) -> RawSlot { + let mut p = self.head(); + p.extend_from_slice(&self.wrapped); + RawSlot { kind: SLOT_RECOVERY, payload: p } + } + + pub fn parse(payload: &[u8]) -> Result { + const HEAD: usize = RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN; + if payload.len() != HEAD + WRAPPED_LEN { + return Err(Error::Malformed); + } + Ok(RecoverySlot { + id: payload[..RECOVERY_ID_LEN].try_into().unwrap(), + salt: payload[RECOVERY_ID_LEN..RECOVERY_ID_LEN + SALT_LEN].try_into().unwrap(), + nonce: payload[RECOVERY_ID_LEN + SALT_LEN..HEAD].try_into().unwrap(), + wrapped: payload[HEAD..].to_vec(), + }) + } +} + pub struct Header { pub version: u16, pub slots: Vec, @@ -317,6 +362,7 @@ impl Header { return Err(Error::Malformed); } let mut singles = 0; + let mut recoveries = 0; for s in &self.slots { match s.kind { SLOT_FACTOR => {} @@ -333,6 +379,10 @@ impl Header { } singles += 1; } + SLOT_RECOVERY => { + RecoverySlot::parse(&s.payload)?; + recoveries += 1; + } // A v1 password slot, or an unknown kind, has no place in a v2 header. _ => return Err(Error::Malformed), } @@ -341,6 +391,10 @@ impl Header { if singles > 0 && (singles != 1 || ids.len() != 1) { return Err(Error::Malformed); } + // One recovery key at most, and none for a vault that opens by itself. + if recoveries > 1 || (recoveries == 1 && singles > 0) { + return Err(Error::Malformed); + } Ok(()) } @@ -356,6 +410,10 @@ impl Header { self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok()) } + pub fn recovery_slot(&self) -> Option { + self.slots.iter().find(|s| s.kind == SLOT_RECOVERY).and_then(|s| RecoverySlot::parse(&s.payload).ok()) + } + pub fn is_machine_store(&self) -> bool { self.slots.iter().any(|s| s.kind == SLOT_SINGLE) } diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index c213a26..0cc59cb 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -22,12 +22,14 @@ mod format; pub mod identity; mod item; pub mod provision; +mod recovery; mod save; mod secret; pub mod security; pub mod signing; pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms}; +pub use recovery::RecoveryKey; pub use save::{CrashPoint, save_atomic, save_atomic_crashing}; pub use secret::{SecretBytes, SecretString}; @@ -63,6 +65,12 @@ pub enum Error { FactorRejected, #[error("these two factors are kept on the same device; use one of them with another factor")] SameDevice, + #[error("this is not a recovery key as Custos prints it: check each group of characters")] + RecoveryKeyMistyped, + #[error("this recovery key does not open this vault: it is another vault's, or an older one that was replaced")] + WrongRecoveryKey, + #[error("this vault has no recovery key")] + NoRecoveryKey, #[error("a vault has at most 8 factors and one master password")] TooManyFactors, #[error("this vault has no Domi identity yet")] @@ -271,6 +279,7 @@ 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"; +const INFO_RECOVERY: &[u8] = b"custos recovery v2"; #[derive(Deserialize)] struct Body { @@ -721,6 +730,106 @@ impl Vault { } } + // ---- the recovery key (docs/FACTORS.md, "The recovery key") ---- + + /// Which recovery key a vault file has (its id, 8 hex characters), from the header alone. + pub fn recovery_id_of(bytes: &[u8]) -> Result, Error> { + Ok(Header::parse(bytes)?.0.recovery_slot().map(|s| recovery::id_hex(&s.id))) + } + + /// Which recovery key this vault has. + pub fn recovery_id(&self) -> Option { + self.slots + .iter() + .find(|s| s.kind == format::SLOT_RECOVERY) + .and_then(|s| format::RecoverySlot::parse(&s.payload).ok()) + .map(|s| recovery::id_hex(&s.id)) + } + + fn recovery_put(&mut self) -> RecoveryKey { + let mut id = [0u8; recovery::ID_LEN]; + crypto::fill_random(&mut id); + let material = crypto::random_key(); + let mut salt = [0u8; SALT_LEN]; + crypto::fill_random(&mut salt); + let mut slot = format::RecoverySlot { id, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() }; + let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY); + slot.wrapped = crypto::seal(&kek, &slot.nonce, self.key.as_ref(), &slot.aad()); + self.slots.retain(|s| s.kind != format::SLOT_RECOVERY); + self.slots.push(slot.raw()); + recovery::encode(&id, &material) + } + + /// Makes the vault's recovery key and returns it, once: it is in no file and no log, so what the caller does + /// not show or print is lost. A key the vault already had stops working. Only a two-factor vault has one + /// (not version 1, not a machine-key vault). The caller saves. + pub fn recovery_create(&mut self, now: i64) -> Result { + if self.version != VERSION_2 { + return Err(Error::NeedTwoFactors); + } + if self.is_store() { + return Err(Error::FactorRejected); + } + let key = self.recovery_put(); + self.security.recovery_note(security::Action::RecoveryCreated, key.id(), now); + Ok(key) + } + + /// Removes the recovery key: from the next save on, only the factors open the vault. The caller saves. + pub fn recovery_remove(&mut self, now: i64) -> Result<(), Error> { + let id = self.recovery_id().ok_or(Error::NoRecoveryKey)?; + self.slots.retain(|s| s.kind != format::SLOT_RECOVERY); + self.security.recovery_note(security::Action::RecoveryRemoved, &id, now); + Ok(()) + } + + /// Opens a vault with its recovery key and, before handing it back, replaces what opened it until now: every + /// factor is dropped, `new_password` and `second` (anything but a password) become its two factors, and the + /// used recovery key is replaced by the new one returned here. The items and everything else stay. Nothing is + /// written: the caller saves, and until it does the file is as it was. + /// + /// This is the only call that takes a recovery key, so the key is never an everyday unlock. + pub fn recover( + bytes: &[u8], + key: &SecretString, + new_password: &SecretString, + kdf: KdfParams, + second: Unlock, + label: &str, + now: i64, + ) -> Result<(Vault, RecoveryKey), Error> { + // What was typed is checked first: a typing mistake is not a wrong key. + let (id, material) = recovery::decode(key)?; + if second.kind() == FactorKind::Password { + return Err(Error::NeedTwoFactors); + } + second.check()?; + if new_password.expose().is_empty() { + return Err(Error::WrongPassword); + } + kdf.check()?; + let (header, body_at) = Header::parse(bytes)?; + if header.version != VERSION_2 { + return Err(Error::NoRecoveryKey); + } + let slot = header.recovery_slot().ok_or(Error::NoRecoveryKey)?; + if slot.id != id { + return Err(Error::WrongRecoveryKey); + } + let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY); + let k = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::WrongRecoveryKey)?; + let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?; + // Whoever held the old factors holds nothing of this vault from the next save on. + v.slots.clear(); + v.factors.clear(); + v.kdf_new = kdf; + v.add_factor(Unlock::Password(new_password), "Master password")?; + v.add_factor(second, label)?; + let new_key = v.recovery_put(); + v.security.recovery_note(security::Action::Recovered, &recovery::id_hex(&id), now); + Ok((v, new_key)) + } + fn is_store(&self) -> bool { self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE) } diff --git a/crates/custos-vault/src/recovery.rs b/crates/custos-vault/src/recovery.rs new file mode 100644 index 0000000..e4dfce1 --- /dev/null +++ b/crates/custos-vault/src/recovery.rs @@ -0,0 +1,150 @@ +//! The recovery key (docs/FACTORS.md, "The recovery key"): one long random key per vault that opens it alone, for +//! the day the factors are gone. It is printed once and kept on paper. It is never an everyday unlock: +//! [`crate::Vault::recover`] is the only call that takes it, and it replaces every factor before it returns. + +use crate::Error; +use crate::secret::SecretString; +use data_encoding::BASE32_NOPAD; +use sha2::{Digest, Sha256}; +use std::fmt; +use zeroize::Zeroizing; + +pub(crate) const ID_LEN: usize = 4; +pub(crate) const MATERIAL_LEN: usize = 32; +const CHECK_LEN: usize = 4; +const CHECK_CONTEXT: &[u8] = b"custos recovery key v1"; +/// 40 bytes as base32: 64 characters, written as 8 groups of 8. +const TEXT_LEN: usize = 64; +const GROUP: usize = 8; + +/// A recovery key as it is printed. `Debug` never shows it. +pub struct RecoveryKey { + id: String, + text: Zeroizing, +} + +impl RecoveryKey { + /// Which key this is (8 hex characters): not secret, shown in Settings and printed next to the key. + pub fn id(&self) -> &str { + &self.id + } + + /// The key: 8 groups of 8 characters, `A-Z` and `2-7`. + pub fn expose(&self) -> &str { + &self.text + } +} + +impl fmt::Debug for RecoveryKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "RecoveryKey({}, [redacted])", self.id) + } +} + +pub(crate) fn id_hex(id: &[u8; ID_LEN]) -> String { + id.iter().map(|b| format!("{b:02x}")).collect() +} + +fn check(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> [u8; CHECK_LEN] { + let mut h = Sha256::new(); + h.update(CHECK_CONTEXT); + h.update(id); + h.update(material); + let d = h.finalize(); + [d[0], d[1], d[2], d[3]] +} + +pub(crate) fn encode(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> RecoveryKey { + let mut raw = Zeroizing::new([0u8; ID_LEN + MATERIAL_LEN + CHECK_LEN]); + raw[..ID_LEN].copy_from_slice(id); + raw[ID_LEN..ID_LEN + MATERIAL_LEN].copy_from_slice(material); + raw[ID_LEN + MATERIAL_LEN..].copy_from_slice(&check(id, material)); + let flat = Zeroizing::new(BASE32_NOPAD.encode(raw.as_ref())); + let mut text = Zeroizing::new(String::with_capacity(TEXT_LEN + TEXT_LEN / GROUP)); + for (i, c) in flat.chars().enumerate() { + if i > 0 && i % GROUP == 0 { + text.push('-'); + } + text.push(c); + } + RecoveryKey { id: id_hex(id), text } +} + +/// The id and the material of a typed key. Case, spaces and hyphens do not matter; a key that is too short, too +/// long, has another character or fails its check is `RecoveryKeyMistyped`, before any vault is touched. +pub(crate) fn decode(text: &SecretString) -> Result<([u8; ID_LEN], Zeroizing<[u8; MATERIAL_LEN]>), Error> { + let mut flat = Zeroizing::new(String::with_capacity(TEXT_LEN)); + for c in text.expose().chars() { + match c { + ' ' | '-' | '\t' | '\r' | '\n' => {} + c if c.is_ascii_alphanumeric() && flat.len() < TEXT_LEN + 1 => flat.push(c.to_ascii_uppercase()), + _ => return Err(Error::RecoveryKeyMistyped), + } + } + if flat.len() != TEXT_LEN { + return Err(Error::RecoveryKeyMistyped); + } + let raw = Zeroizing::new(BASE32_NOPAD.decode(flat.as_bytes()).map_err(|_| Error::RecoveryKeyMistyped)?); + if raw.len() != ID_LEN + MATERIAL_LEN + CHECK_LEN { + return Err(Error::RecoveryKeyMistyped); + } + let id: [u8; ID_LEN] = raw[..ID_LEN].try_into().expect("checked"); + let mut material = Zeroizing::new([0u8; MATERIAL_LEN]); + material.copy_from_slice(&raw[ID_LEN..ID_LEN + MATERIAL_LEN]); + if raw[ID_LEN + MATERIAL_LEN..] != check(&id, &material) { + return Err(Error::RecoveryKeyMistyped); + } + Ok((id, material)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_printed_key_reads_back_however_it_is_typed() { + let key = encode(&[0xa1, 0xb2, 0xc3, 0xd4], &[9; 32]); + assert_eq!(key.id(), "a1b2c3d4"); + let text = key.expose().to_owned(); + assert_eq!(text.len(), 64 + 7); + assert!( + text.split('-') + .all(|g| g.len() == 8 && g.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b))) + ); + for typed in + [text.clone(), text.to_lowercase(), text.replace('-', " "), text.replace('-', ""), format!(" {text}\r\n")] + { + let (id, material) = decode(&SecretString::from(typed.as_str())).unwrap(); + assert_eq!((id, *material), ([0xa1, 0xb2, 0xc3, 0xd4], [9; 32])); + } + assert_eq!(format!("{key:?}"), "RecoveryKey(a1b2c3d4, [redacted])"); + } + + #[test] + fn a_mistyped_key_is_told_apart_before_any_vault_is_touched() { + let text = encode(&[1, 2, 3, 4], &[9; 32]).expose().to_owned(); + let mistyped = |s: String| matches!(decode(&SecretString::from(s.as_str())), Err(Error::RecoveryKeyMistyped)); + // One character changed, anywhere: the check catches it. + for at in [0usize, 7, 40, 70] { + let mut chars: Vec = text.chars().collect(); + if chars[at] == '-' { + continue; + } + chars[at] = if chars[at] == 'A' { 'B' } else { 'A' }; + assert!(mistyped(chars.into_iter().collect()), "position {at}"); + } + // Two groups swapped, a group missing, one too many, a character that is never in a key. + let groups: Vec<&str> = text.split('-').collect(); + let mut swapped = groups.clone(); + swapped.swap(2, 6); + if swapped != groups { + assert!(mistyped(swapped.join("-"))); + } + assert!(mistyped(groups[1..].join("-"))); + assert!(mistyped(format!("{text}-AAAAAAAA"))); + assert!(mistyped(text.replacen(|c: char| c != '-', "1", 1))); + assert!(mistyped(text.replacen('-', "_", 1))); + assert!(mistyped(String::new())); + assert!(mistyped("A".repeat(100_000))); + } +} diff --git a/crates/custos-vault/src/security.rs b/crates/custos-vault/src/security.rs index f3dc4c8..b36d8c6 100644 --- a/crates/custos-vault/src/security.rs +++ b/crates/custos-vault/src/security.rs @@ -82,6 +82,14 @@ pub enum Action { StandingGranted, /// A standing approval was revoked (`detail`: the same). Written by [`Vault::standing_revoke`] only. StandingRevoked, + /// A recovery key was made (core 0.17.0; `detail`: the key's id, never the key). Written by + /// [`Vault::recovery_create`] only. + RecoveryCreated, + /// The recovery key was removed (`detail`: its id). Written by [`Vault::recovery_remove`] only. + RecoveryRemoved, + /// The vault was opened with its recovery key: every factor and the key were replaced (`detail`: the used + /// key's id). Written by [`Vault::recover`] only. + Recovered, } /// What *Connect via SSH* needs. @@ -251,6 +259,14 @@ impl State { trim(&mut self.audit); } + /// `recovery-created`, `recovery-removed` or `recovered`, with the key's id as its detail. + pub(crate) fn recovery_note(&mut self, action: Action, id: &str, now: i64) { + debug_assert!(matches!(action, Action::RecoveryCreated | Action::RecoveryRemoved | Action::Recovered)); + self.notice_expiry(now); + self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(id.to_owned()) }); + trim(&mut self.audit); + } + /// Before any change: a window that ended on its own is written down once, as `setup-expired` at `now` and /// `finished` = `until`. fn notice_expiry(&mut self, now: i64) { diff --git a/crates/custos-vault/tests/factors.rs b/crates/custos-vault/tests/factors.rs index fcc7816..ab2530e 100644 --- a/crates/custos-vault/tests/factors.rs +++ b/crates/custos-vault/tests/factors.rs @@ -86,7 +86,9 @@ fn a_factor_is_added_and_removed_without_the_others() { // Only the new factor's material is needed: its pairs come from the factor keys in the body. let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap(); let bytes = v.to_bytes().unwrap(); - let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); + let mut v = + open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)) + .unwrap(); let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect(); assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]); // A lost device: drop its factor; the other two still open, the device no longer helps. @@ -108,7 +110,8 @@ fn a_forgotten_password_is_replaced_with_two_other_factors() { let mut v = two_factor_vault(); v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap(); let bytes = v.to_bytes().unwrap(); - let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap(); + let mut v = + open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap(); v.change_password(&pw("New9-Password4"), FAST).unwrap(); let bytes2 = v.to_bytes().unwrap(); let dev = || Unlock::Material(FactorKind::Device, &DEVICE); @@ -168,7 +171,14 @@ fn a_machine_store_opens_with_its_device_key_alone() { let user = two_factor_vault().to_bytes().unwrap(); assert!(!Vault::is_machine_store(&user).unwrap()); assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors))); - assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err()); + assert!( + Vault::open_with( + &bytes, + Unlock::Material(FactorKind::Device, &STORE), + Unlock::Material(FactorKind::Device, &STORE) + ) + .is_err() + ); } #[test] @@ -178,10 +188,20 @@ fn limits_are_enforced() { v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap(); } assert_eq!(v.factors().len(), 8); - assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors))); + assert!(matches!( + v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), + Err(Error::TooManyFactors) + )); // Every pair still opens with 8 factors (8 factor slots + 28 pair slots). let bytes = v.to_bytes().unwrap(); - assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok()); + assert!( + open( + &bytes, + Unlock::Material(FactorKind::Device, &[100; 32]), + Unlock::Material(FactorKind::Device, &[105; 32]) + ) + .is_ok() + ); } #[test] @@ -190,7 +210,10 @@ fn no_factor_material_in_debug_output() { let u = Unlock::Material(FactorKind::Device, &secret); let p = pw("Orbit7-Fable3"); let printed = format!("{u:?} {:?}", Unlock::Password(&p)); - assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}"); + assert!( + !printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), + "{printed}" + ); let v = two_factor_vault(); let printed = format!("{v:?} {:?}", v.factors()); for f in v.factors() { @@ -207,7 +230,8 @@ fn the_key_pair_item_type_round_trips() { k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5); v.add(k); let bytes = v.to_bytes().unwrap(); - let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); + let back = + open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap(); assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret)); } diff --git a/crates/custos-vault/tests/recovery.rs b/crates/custos-vault/tests/recovery.rs new file mode 100644 index 0000000..057602a --- /dev/null +++ b/crates/custos-vault/tests/recovery.rs @@ -0,0 +1,227 @@ +//! The recovery key (docs/FACTORS.md, "The recovery key"): made on request, printed once, and taken by +//! `Vault::recover` only, which replaces every factor and the key itself before it hands the vault back. + +use custos_vault::security::Action; +use custos_vault::{Error, FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault}; + +const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; +const NOW: i64 = 1_793_750_000_000; +const PC: [u8; 32] = [7; 32]; +const NEW_PC: [u8; 32] = [8; 32]; +const PHONE: [u8; 32] = [9; 32]; + +fn pw(s: &str) -> SecretString { + SecretString::from(s) +} + +fn device(m: &[u8; 32]) -> Unlock<'_> { + Unlock::Material(FactorKind::Device, m) +} + +/// A two-factor vault (password, this PC, a phone's approval) with one item. +fn vault() -> Vault { + let old = pw("the old master password"); + let mut v = Vault::create_with(Unlock::Password(&old), "Master password", device(&PC), "MARK-PC", FAST).unwrap(); + v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap(); + let mut item = Item::new(ItemType::WebLogin, "Gitea", NOW); + item.set("password", "item-secret-value", NOW); + v.add(item); + v +} + +fn actions(v: &Vault) -> Vec { + v.security_view(NOW + 60_000).audit.iter().map(|e| e.action).collect() +} + +fn recover(bytes: &[u8], key: &str, new_password: &str) -> Result<(Vault, custos_vault::RecoveryKey), Error> { + Vault::recover(bytes, &pw(key), &pw(new_password), FAST, device(&NEW_PC), "MARK-PC", NOW + 5000) +} + +#[test] +fn a_vault_without_a_recovery_key_is_as_before_and_making_one_changes_only_the_header() { + let v = vault(); + let before = v.to_bytes().unwrap(); + assert_eq!(Vault::recovery_id_of(&before).unwrap(), None); + assert_eq!(v.recovery_id(), None); + assert!(matches!(recover(&before, &"A".repeat(64), "a new master password"), Err(Error::RecoveryKeyMistyped))); + + let mut v = v; + let key = v.recovery_create(NOW).unwrap(); + assert_eq!(v.recovery_id().as_deref(), Some(key.id())); + let after = v.to_bytes().unwrap(); + assert_eq!(Vault::recovery_id_of(&after).unwrap().as_deref(), Some(key.id())); + // The factors still open it, exactly as before, and the item is there. + let old = pw("the old master password"); + let w = Vault::open_with(&after, Unlock::Password(&old), device(&PC)).unwrap(); + assert_eq!((w.items().len(), w.factors().len()), (1, 3)); + assert_eq!(actions(&w), [Action::RecoveryCreated]); + assert_eq!(w.security_view(NOW).audit[0].detail.as_deref(), Some(key.id())); + // The key is in neither the file nor the audit. + let flat = key.expose().replace('-', ""); + let text = String::from_utf8_lossy(&after).into_owned(); + assert!(!text.contains(&flat) && !text.contains(key.expose())); +} + +#[test] +fn recovering_forces_a_new_password_new_factors_and_a_new_key() { + let mut v = vault(); + let key = v.recovery_create(NOW).unwrap(); + let bytes = v.to_bytes().unwrap(); + + let (r, new_key) = recover(&bytes, key.expose(), "a new master password").expect("recovered"); + // Everything in the vault is still there. + assert_eq!(r.items().len(), 1); + assert_eq!(r.item(&r.items()[0].id).unwrap().field("password").unwrap().value.expose(), "item-secret-value"); + // Exactly the two new factors; the old password, the old PC key and the phone are gone. + let kinds: Vec = r.factors().iter().map(|f| f.kind).collect(); + assert_eq!(kinds, [FactorKind::Password, FactorKind::Device]); + assert_ne!(new_key.id(), key.id()); + assert_ne!(new_key.expose(), key.expose()); + assert_eq!(r.recovery_id().as_deref(), Some(new_key.id())); + assert_eq!(actions(&r), [Action::RecoveryCreated, Action::Recovered]); + let last = r.security_view(NOW + 5000).audit[1].clone(); + assert_eq!((last.at, last.detail.as_deref()), (NOW + 5000, Some(key.id()))); + + let saved = r.to_bytes().unwrap(); + let (old, new) = (pw("the old master password"), pw("a new master password")); + assert!(Vault::open_with(&saved, Unlock::Password(&new), device(&NEW_PC)).is_ok()); + assert!(matches!(Vault::open_with(&saved, Unlock::Password(&old), device(&NEW_PC)), Err(Error::WrongPassword))); + assert!(matches!(Vault::open_with(&saved, Unlock::Password(&new), device(&PC)), Err(Error::FactorRejected))); + assert!(Vault::open_with(&saved, device(&PC), Unlock::Material(FactorKind::Approval, &PHONE)).is_err()); + // The used key is spent; the new one works, once more. + assert!(matches!(recover(&saved, key.expose(), "yet another password"), Err(Error::WrongRecoveryKey))); + assert!(recover(&saved, new_key.expose(), "yet another password").is_ok()); +} + +#[test] +fn a_recovery_key_is_never_an_everyday_unlock() { + let mut v = vault(); + let key = v.recovery_create(NOW).unwrap(); + let bytes = v.to_bytes().unwrap(); + let text = pw(key.expose()); + let (_, material) = (key.id(), key.expose().replace('-', "")); + // It is not a password and not a factor: no ordinary way of opening takes it, alone or with a real factor. + assert!(Vault::open(&bytes, &text).is_err()); + let old = pw("the old master password"); + assert!(matches!(Vault::open_with(&bytes, Unlock::Password(&text), device(&PC)), Err(Error::WrongPassword))); + for kind in [FactorKind::Device, FactorKind::Totp, FactorKind::Approval, FactorKind::Passkey] { + let as_material = Unlock::Material(kind, &material.as_bytes()[..32]); + assert!(Vault::open_with(&bytes, Unlock::Password(&old), as_material).is_err(), "{kind:?}"); + } + assert!(Vault::open_machine_store(&bytes, &PC).is_err()); + assert_eq!(Vault::is_machine_store(&bytes).unwrap(), false); + // It does not count as a factor: two are still needed and it is not listed. + assert_eq!(Vault::factor_ids(&bytes).unwrap().len(), 3); + // Recovering needs a real second factor and a password worth the name. + let two_passwords = + Vault::recover(&bytes, &text, &pw("a new master password"), FAST, Unlock::Password(&old), "x", NOW); + assert!(matches!(two_passwords, Err(Error::NeedTwoFactors))); + let short = Vault::recover(&bytes, &text, &pw(""), FAST, device(&NEW_PC), "x", NOW); + assert!(matches!(short, Err(Error::WrongPassword) | Err(Error::FactorRejected))); + // A refused recovery changed nothing: the key still works. + assert!(recover(&bytes, key.expose(), "a new master password").is_ok()); +} + +#[test] +fn a_wrong_an_old_or_another_vaults_key_opens_nothing() { + let mut v = vault(); + let first = v.recovery_create(NOW).unwrap(); + // A second key replaces the first: one key per vault. + let second = v.recovery_create(NOW + 1000).unwrap(); + assert_ne!(first.id(), second.id()); + let bytes = v.to_bytes().unwrap(); + assert!(matches!(recover(&bytes, first.expose(), "a new master password"), Err(Error::WrongRecoveryKey))); + + let mut other = vault(); + let others = other.recovery_create(NOW).unwrap(); + assert!(matches!(recover(&bytes, others.expose(), "a new master password"), Err(Error::WrongRecoveryKey))); + // The right key with its last character changed: the check says so before the vault is tried. + let forged: String = { + let mut flat: Vec = second.expose().chars().collect(); + let last = flat.len() - 1; + flat[last] = if flat[last] == 'A' { 'B' } else { 'A' }; + flat.into_iter().collect() + }; + assert!(matches!(recover(&bytes, &forged, "a new master password"), Err(Error::RecoveryKeyMistyped))); + assert!(recover(&bytes, second.expose(), "a new master password").is_ok()); + assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryCreated]); +} + +#[test] +fn removing_the_key_closes_that_door_and_is_audited() { + let mut v = vault(); + assert!(matches!(v.recovery_remove(NOW), Err(Error::NoRecoveryKey))); + let key = v.recovery_create(NOW).unwrap(); + v.recovery_remove(NOW + 1000).unwrap(); + assert_eq!(v.recovery_id(), None); + let bytes = v.to_bytes().unwrap(); + assert_eq!(Vault::recovery_id_of(&bytes).unwrap(), None); + assert!(matches!(recover(&bytes, key.expose(), "a new master password"), Err(Error::NoRecoveryKey))); + assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryRemoved]); + // The file is an ordinary two-factor vault again: byte for byte the slots an older reader knows. + let old = pw("the old master password"); + assert!(Vault::open_with(&bytes, Unlock::Password(&old), device(&PC)).is_ok()); +} + +#[test] +fn only_a_two_factor_vault_gets_a_recovery_key() { + // Version 1: one password. A recovery key would be its second way in without a second factor to replace. + let mut v1 = Vault::create(&pw("a version one password"), FAST).unwrap(); + assert!(matches!(v1.recovery_create(NOW), Err(Error::NeedTwoFactors))); + // A machine store opens itself; it has nothing to recover and must stay exactly one factor and its slot. + let mut store = Vault::create_machine_store(&PC, "MARK-PC").unwrap(); + assert!(matches!(store.recovery_create(NOW), Err(Error::FactorRejected))); + assert!(Vault::open_machine_store(&store.to_bytes().unwrap(), &PC).is_ok()); +} + +#[test] +fn a_header_with_a_broken_or_a_second_recovery_slot_is_malformed() { + let mut v = vault(); + v.recovery_create(NOW).unwrap(); + let bytes = v.to_bytes().unwrap(); + let plain = vault().to_bytes().unwrap(); + // The slot count is the byte after magic (6) and version (2); slots follow as kind, length (u16 LE), payload. + let count = bytes[8] as usize; + assert_eq!(count, plain[8] as usize + 1); + let mut at = 9; + let mut found = None; + for _ in 0..count { + let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize; + if bytes[at] == 5 { + found = Some((at, len)); + } + at += 3 + len; + } + let (at, len) = found.expect("a recovery slot, kind 5"); + assert_eq!(len, 4 + 32 + 24 + 48); + // A kind this reader does not know. + let mut unknown = bytes.clone(); + unknown[at] = 6; + assert!(matches!(Vault::factor_ids(&unknown), Err(Error::Malformed))); + // The slot twice. + let mut twice = bytes[..at + 3 + len].to_vec(); + twice.extend_from_slice(&bytes[at..at + 3 + len]); + twice.extend_from_slice(&bytes[at + 3 + len..]); + twice[8] += 1; + assert!(matches!(Vault::factor_ids(&twice), Err(Error::Malformed))); + // A changed byte in the slot: the header is the body's AAD, so the vault does not open at all. + let mut flipped = bytes.clone(); + flipped[at + 3 + 10] ^= 1; + let old = pw("the old master password"); + assert!(matches!(Vault::open_with(&flipped, Unlock::Password(&old), device(&PC)), Err(Error::Corrupted))); +} + +#[test] +fn the_key_and_the_audit_survive_a_reopen_and_ordinary_changes() { + let mut v = vault(); + let key = v.recovery_create(NOW).unwrap(); + let old = pw("the old master password"); + let mut w = Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&old), device(&PC)).unwrap(); + // Changing the password, adding and removing a factor: none of them touches the recovery key. + w.change_password(&pw("a changed master password"), FAST).unwrap(); + let id = w.add_factor(Unlock::Material(FactorKind::Totp, &[5; 32]), "TOTP").unwrap(); + w.remove_factor(&id).unwrap(); + assert_eq!(w.recovery_id().as_deref(), Some(key.id())); + let bytes = w.to_bytes().unwrap(); + assert!(recover(&bytes, key.expose(), "a new master password").is_ok()); +} diff --git a/docs/FACTORS.md b/docs/FACTORS.md index fa78899..9162567 100644 --- a/docs/FACTORS.md +++ b/docs/FACTORS.md @@ -79,6 +79,7 @@ is the whole header, as in v1. ### Limits a reader enforces - 1 ..= 64 slots; at most 8 factor slots; a factor type outside 1..=5 is malformed. +- At most one recovery slot (kind 5, core 0.17.0), of exactly 108 bytes, and none in a machine store. - A pair slot whose two ids are equal, or not in order, or name a factor that has no factor slot, is malformed. - Argon2 limits as in v1, checked before any work. - Material for types 2..5: 32 ..= 64 bytes, else `FactorRejected` before any work. @@ -96,6 +97,54 @@ slot, then the body. | Both unwrap, but their pair slot is missing or fails | `Corrupted` | | A machine store: its one device factor unwraps, then the single slot | — | +## The recovery key (core 0.17.0) + +A two-factor vault can have **one recovery key**: 32 random bytes that open the vault alone, for the day the +factors are gone (a forgotten password and a dead PC, a lost phone and a reinstalled Windows). It is the one +deliberate exception to "never one secret", and it is hedged accordingly: + +- **It is made on request and returned once** (`Vault::recovery_create`). It is in no file and no log. The app + shows or prints it and keeps nothing. Making a new one replaces the old one. +- **It is never an everyday unlock.** `Vault::recover` is the only call that takes it. Before it returns the vault + it drops **every** factor, makes the new master password and one new second factor the vault's two factors, and + replaces the recovery key (the new one is returned, once). Whoever held the old password, an old PC key or a + phone holds nothing of the vault from the next save on. No `open` or `open_with` accepts a recovery key, as a + password or as material. +- **It is audited** in the security member: `recovery-created`, `recovery-removed`, `recovered`, each with the + key's id (never the key). +- A version-1 vault and a machine-key vault have none (`NeedTwoFactors`, `FactorRejected`). +- `recover` writes nothing. Until the caller saves, the file is as it was and the old factors still open it. +- The vault key stays the same across a recovery: a **copy of the file from before** still opens with the old + factors and the old recovery key. A recovery takes back the vault, not its old copies. + +**As printed:** `id (4 bytes) ‖ key (32 bytes) ‖ check (4 bytes)` in base32 without padding, 64 characters in 8 +groups of 8 (`A–Z`, `2–7`). The check is the first 4 bytes of `SHA-256("custos recovery key v1" ‖ id ‖ key)`. +A reader ignores case, spaces and hyphens; any other character, another length or a failed check is +`RecoveryKeyMistyped`, told apart from `WrongRecoveryKey` (a well-formed key that is not this vault's current one) +before the vault is touched. The **id** (8 hex characters) is not secret: it is in the header, shown in Settings +and printed next to the key, so the paper can be matched to the vault. + +``` +kind 5, recovery slot (at most one; never together with a single slot) +4 id +32 salt +24 wrap nonce +48 wrapped vault key KEK = HKDF-SHA256(key, salt, info "custos recovery v2") +AAD = magic ‖ version ‖ kind ‖ id ‖ salt ‖ nonce +``` + +It is not a factor: it has no factor slot, no pair slots and no entry in the body's `factors`, it does not count +toward the two factors or the limit of 8, and `factor_ids` does not list it. `Vault::recovery_id_of(bytes)` reads +its id from the header. + +**Older readers.** A reader before core 0.17.0 knows slot kinds 2 to 4 and treats kind 5 as malformed: a vault +with a recovery key does not open in an older Custos ("the vault file is malformed"), and is not rewritten by +one. Removing the key (`recovery_remove`) makes the file readable by older readers again, apart from the three +audit actions, which they refuse like any unknown action (docs/FORMAT.md, "The security member"). + +**What it costs.** The paper is a complete way in. It is 256 bits, so it is not guessed; it is stolen, copied or +photographed. Keep it away from the PC and from the other vault's paper. Losing it loses nothing: make a new one. + ## Which factors a file has `Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed, diff --git a/docs/FORMAT.md b/docs/FORMAT.md index afcb01a..fe4775a 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -209,7 +209,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos, | `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed | | `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` | | `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo | -| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters | +| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked`, or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters | The **level** is computed, never stored: