Cotton code
91 lines · 3.9 KB · RustRaw
//! THE BACKUP KEY IS A RECOVERY CODE. One per person on a platform: a code of the same kind a signed-in account gets//! ([`recovery_code`]: 24 characters, 110 random bits and a typo check), minted quietly the first time Backup is//! turned on and kept in the phone's synced key store (iCloud Keychain as a synchronizable item; Google's Block Store,//! end-to-end encrypted under the screen lock). A new phone signed into the same Apple Account or Google account finds//! it and opens the files with no step at all.//!//! **Show my recovery code** reveals that same code: nothing is re-sealed, and a person who keeps it opens every file//! on a phone whose key store has nothing (iCloud Keychain off, no screen lock, a phone too old for Google's cloud//! restore, or another platform). Typing it into a second Cotton app makes both apps share one key, which is how//! Android's apps (whose key stores are each app's own) come to one code.//!//! **Why the code itself and not a key it wraps**: one secret, one thing to explain. 110 random bits need no stretch//! against a guesser holding the file, so the key is the code through HKDF, quick on any phone. **A file's own key**//! is that key through HKDF again with the file's random id as the salt, so no two files share a key.use hkdf::Hkdf;use sha2::Sha256;use zeroize::Zeroizing;use crate::vault::recovery_code::{self, Problem};const KEY_SALT: &[u8] = b"cotton backup 1";const KEY_INFO: &[u8] = b"cotton backup 1 key";const FILE_INFO: &[u8] = b"cotton backup 1 file key";const CHECK_INFO: &[u8] = b"cotton backup 1 key check";/// The backup key, held with the code it comes from. Both are wiped when it goes.#[derive(Clone)]pub struct BackupKey {    /// The code's 24 characters, no dashes.    code: Zeroizing<String>,    key: Zeroizing<[u8; 32]>,}impl std::fmt::Debug for BackupKey {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        write!(f, "BackupKey({})", self.check())    }}impl PartialEq for BackupKey {    fn eq(&self, other: &Self) -> bool {        self.check() == other.check()    }}impl Eq for BackupKey {}impl BackupKey {    /// A new key from the OS random source.    pub fn mint() -> BackupKey {        BackupKey::from_code(&recovery_code::mint()).expect("a minted code reads back")    }    /// [`mint`](Self::mint) from the 14 bytes given.    pub fn mint_with(bytes: &[u8; 14]) -> BackupKey {        BackupKey::from_code(&recovery_code::mint_with(bytes)).expect("a minted code reads back")    }    /// The key a code gives, typed loosely (case, spaces, dashes and lookalikes forgiven), or why the typing is not a    /// code (caught before anything is tried).    pub fn from_code(typed: &str) -> Result<BackupKey, Problem> {        let code = Zeroizing::new(recovery_code::normalize(typed)?);        let mut key = Zeroizing::new([0u8; 32]);        Hkdf::<Sha256>::new(Some(KEY_SALT), code.as_bytes()).expand(KEY_INFO, &mut key[..]).expect("32 bytes");        Ok(BackupKey { code, key })    }    /// The code in its six groups, as the key store keeps it and as Show my recovery code shows it.    pub fn code(&self) -> String {        recovery_code::grouped(&self.code)    }    /// Sixteen hex characters that name this key in a file's open header, so a file made with another code is told    /// apart from a damaged one. They open nothing.    pub fn check(&self) -> String {        let mut out = [0u8; 8];        Hkdf::<Sha256>::new(None, &self.key[..]).expand(CHECK_INFO, &mut out).expect("8 bytes");        out.iter().map(|b| format!("{b:02x}")).collect()    }    /// The key that seals the file with this random id.    pub(crate) fn file_key(&self, file_id: &[u8]) -> Zeroizing<[u8; 32]> {        let mut out = Zeroizing::new([0u8; 32]);        Hkdf::<Sha256>::new(Some(file_id), &self.key[..]).expand(FILE_INFO, &mut out[..]).expect("32 bytes");        out    }}#[cfg(test)]#[path = "key_tests.rs"]mod tests;