//! 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))); } }