Cotton code
487 lines · 19.1 KB · RustRaw
//! THE RECOVERY CODE AND THE PLATFORM KEY (rulings R7a and//! R7c): two ways back into a person's vault on a new device, neither of which//! the object can use.//!//! **What the object holds**, for each kind (`code`, one platform key per store: `google`, `apple`, and `trusted`, a trusted person's): a salt, the//! derivation's parameters, the SHA-256 of an *auth key*, and the vault master//! key wrapped under a *wrap key*. Both keys come from the person's secret//! (the code they keep, or the random key the phone's own synced key store//! keeps) through the derivation below, and never reach the object together//! with anything that opens the wrap: the auth key proves the secret is known//! (the object compares its hash, counts the tries and only then answers the//! wrap), the wrap key never leaves a device. A dump of the object holds a//! hash and a wrap under a key stretched from 110 random bits.//!//! **The code**: 24 characters of Crockford's base32 (digits and capitals,//! no I, L, O or U), said and typed in six groups of four: `7K3Q-9XWD-…`.//! Twenty-two carry 110 random bits; the last two are a check over them (the//! first 10 bits of a SHA-256), so a typo is caught on the device before a//! try is spent on the object (1 in 1024 slips through and is refused there).//! Reading it back is forgiving: case, spaces and dashes do not matter, and//! O reads as 0, I and L as 1, U as V.//!//! **The derivation**: the secret, stretched (scrypt for a code, at the//! parameters stored beside the salt; none for a platform key, already 256//! random bits), then HKDF-SHA256 into the two keys.//!//! PURE, as the whole vault module is: the OS random source is named at each//! call site and has a `*_with` sibling taking the bytes.use aes_gcm::aead::{Aead, KeyInit, Payload};use aes_gcm::{Aes256Gcm, Key, Nonce};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use hkdf::Hkdf;use rand::RngCore;use sha2::{Digest, Sha256};use zeroize::Zeroizing;/// The 32 symbols, in value order.pub const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";/// Characters carrying random bits.pub const DATA_CHARS: usize = 22;/// Characters of check.pub const CHECK_CHARS: usize = 2;/// Characters in a whole code (dashes aside).pub const CODE_CHARS: usize = DATA_CHARS + CHECK_CHARS;/// Characters in a group.pub const GROUP: usize = 4;/// What a wrap begins with.pub const WRAP_PREFIX: &str = "r1:";const NONCE_LEN: usize = 12;const TAG_LEN: usize = 16;/// The two kinds of recovery secret.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Kind {    /// A code the person keeps.    Code,    /// A random key Google's Block Store keeps (Android), backed up end-to-end encrypted.    Google,    /// A random key iCloud Keychain keeps (iPhone, Mac), as a synchronizable item.    Apple,    /// A random secret split in two (R7d): one half sealed to a trusted person, who holds it in their own object and    /// hands it to a new device of this person when they approve; the other half kept by this person's object, which    /// releases it to that device only after the approval. Neither half alone opens anything.    Trusted,    /// The circle (TRUSTED RECOVERY BUILD 1, step 4): a random secret R = H ⊕ Q. The object keeps H; Q is shared among    /// the person's helpers any k of n ([`circle_pieces`]). A new device gets H only after a wait anyone told can stop,    /// and Q only from k helpers who each checked it by the six digits. Neither the object nor fewer than k helpers    /// open anything.    Circle,}impl Kind {    pub fn as_str(self) -> &'static str {        match self {            Kind::Code => "code",            Kind::Google => "google",            Kind::Apple => "apple",            Kind::Trusted => "trusted",            Kind::Circle => "circle",        }    }    pub fn parse(word: &str) -> Option<Kind> {        match word {            "code" => Some(Kind::Code),            "google" => Some(Kind::Google),            "apple" => Some(Kind::Apple),            "trusted" => Some(Kind::Trusted),            "circle" => Some(Kind::Circle),            _ => None,        }    }    /// The derivation a new secret of this kind is made with.    /// Whether this is a platform store's key (no stretch, kept by the platform, never shown).    pub fn is_platform(self) -> bool {        matches!(self, Kind::Google | Kind::Apple)    }    pub fn kdf(self) -> Kdf {        match self {            Kind::Code => Kdf::SCRYPT,            Kind::Google | Kind::Apple | Kind::Trusted | Kind::Circle => Kdf::None,        }    }}/// How a secret is stretched before HKDF. Stored beside the salt as text/// ([`Kdf::text`]), so a later build that stretches harder still opens an/// older record.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Kdf {    /// scrypt at 2^log_n, r, p.    Scrypt { log_n: u8, r: u32, p: u32 },    /// No stretch: the secret is 256 random bits.    None,}impl Kdf {    /// What a code is stretched with: 2^15 × r 8 is 32 MiB and a fraction of a    /// second on a phone, once, at the moment the person types it.    pub const SCRYPT: Kdf = Kdf::Scrypt { log_n: 15, r: 8, p: 1 };    pub fn text(self) -> String {        match self {            Kdf::Scrypt { log_n, r, p } => format!("scrypt:{log_n}:{r}:{p}"),            Kdf::None => "none".to_string(),        }    }    /// The stored text read back; None for one this build does not know or    /// one too weak (a code stretched below 2^14) or too heavy (above 2^20) to take.    pub fn parse(text: &str) -> Option<Kdf> {        if text == "none" {            return Some(Kdf::None);        }        let mut parts = text.strip_prefix("scrypt:")?.split(':');        let log_n: u8 = parts.next()?.parse().ok()?;        let r: u32 = parts.next()?.parse().ok()?;        let p: u32 = parts.next()?.parse().ok()?;        if parts.next().is_some() || !(10..=20).contains(&log_n) || r == 0 || r > 32 || p == 0 || p > 4 {            return None;        }        Some(Kdf::Scrypt { log_n, r, p })    }}/// Why a typed code was not taken, before any try is spent.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Problem {    /// Too few or too many characters.    Length,    /// A character that is in no code.    Character,    /// The check does not match: a typo.    Check,}impl Problem {    pub fn code(self) -> &'static str {        match self {            Problem::Length => "recovery_code_length",            Problem::Character => "recovery_code_character",            Problem::Check => "recovery_code_check",        }    }}/// A new code, from the OS random source, in its groups.pub fn mint() -> String {    let mut bytes = [0u8; 14];    rand::rngs::OsRng.fill_bytes(&mut bytes);    mint_with(&bytes)}/// [`mint`] from the 14 bytes given (110 of their 112 bits are used).pub fn mint_with(bytes: &[u8; 14]) -> String {    let mut data = String::with_capacity(DATA_CHARS);    let mut acc: u32 = 0;    let mut bits = 0;    let mut byte = bytes.iter();    while data.len() < DATA_CHARS {        if bits < 5 {            acc = (acc << 8) | u32::from(*byte.next().unwrap_or(&0));            bits += 8;        }        bits -= 5;        data.push(ALPHABET[((acc >> bits) & 31) as usize] as char);    }    grouped(&format!("{data}{}", check(&data)))}/// The check characters of the 22 data characters.fn check(data: &str) -> String {    let digest = Sha256::new().chain_update(b"cotton-recovery-check:v1:").chain_update(data.as_bytes()).finalize();    let ten = (u32::from(digest[0]) << 2) | (u32::from(digest[1]) >> 6);    [ALPHABET[(ten >> 5) as usize] as char, ALPHABET[(ten & 31) as usize] as char].iter().collect()}/// A code in its groups of four, dash between.pub fn grouped(chars: &str) -> String {    chars.as_bytes().chunks(GROUP).map(|chunk| std::str::from_utf8(chunk).unwrap_or_default()).collect::<Vec<_>>().join("-")}/// What the person typed, read back as the 24 characters of a code, or why/// not. Case, spaces and dashes do not matter; O, I, L and U read as the/// characters they are mistaken for.pub fn normalize(typed: &str) -> Result<String, Problem> {    let mut out = String::with_capacity(CODE_CHARS);    for c in typed.chars() {        if c.is_whitespace() || c == '-' || c == '–' || c == '.' {            continue;        }        let c = match c.to_ascii_uppercase() {            'O' => '0',            'I' | 'L' => '1',            'U' => 'V',            other => other,        };        if !ALPHABET.contains(&(c as u8)) || !c.is_ascii() {            return Err(Problem::Character);        }        out.push(c);    }    if out.len() != CODE_CHARS {        return Err(Problem::Length);    }    if check(&out[..DATA_CHARS]) != out[DATA_CHARS..] {        return Err(Problem::Check);    }    Ok(out)}/// The two keys a secret gives.pub struct Keys {    /// Opens the wrap; never leaves a device.    pub wrap: Zeroizing<[u8; 32]>,    /// Proves the secret to the object, which keeps only its hash.    pub auth: Zeroizing<[u8; 32]>,}impl std::fmt::Debug for Keys {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str("Keys(…)")    }}/// The keys of `secret` (a normalized code's characters, or a platform key's/// bytes) under `salt` and `kdf`. None when scrypt refuses its parameters.pub fn derive(secret: &[u8], salt: &[u8], kdf: Kdf) -> Option<Keys> {    let stretched: Zeroizing<Vec<u8>> = match kdf {        Kdf::Scrypt { log_n, r, p } => {            let params = scrypt::Params::new(log_n, r, p, 32).ok()?;            let mut out = Zeroizing::new(vec![0u8; 32]);            scrypt::scrypt(secret, salt, &params, &mut out).ok()?;            out        }        Kdf::None => Zeroizing::new(secret.to_vec()),    };    let hk = Hkdf::<Sha256>::new(Some(salt), &stretched);    let mut wrap = Zeroizing::new([0u8; 32]);    let mut auth = Zeroizing::new([0u8; 32]);    hk.expand(b"cotton-recovery:v1:wrap", wrap.as_mut()).ok()?;    hk.expand(b"cotton-recovery:v1:auth", auth.as_mut()).ok()?;    Some(Keys { wrap, auth })}/// The hex SHA-256 of an auth key: what the object keeps and compares.pub fn auth_hash(auth: &[u8; 32]) -> String {    Sha256::digest(auth).iter().map(|b| format!("{b:02x}")).collect()}/// 16 random bytes of salt.pub fn salt() -> [u8; 16] {    let mut salt = [0u8; 16];    rand::rngs::OsRng.fill_bytes(&mut salt);    salt}/// A trusted person's secret split in two halves: `(theirs, the object's)`, each 32 bytes, joined by XOR. Either half/// alone is 32 uniformly random bytes and says nothing of the secret.pub fn split(secret: &[u8; 32]) -> (Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>) {    let mut theirs = Zeroizing::new([0u8; 32]);    rand::rngs::OsRng.fill_bytes(theirs.as_mut());    split_with(secret, &theirs)}/// [`split`] with the trusted person's half supplied.pub fn split_with(secret: &[u8; 32], theirs: &[u8; 32]) -> (Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>) {    let mut held = Zeroizing::new([0u8; 32]);    for (i, byte) in held.iter_mut().enumerate() {        *byte = secret[i] ^ theirs[i];    }    (Zeroizing::new(*theirs), held)}/// The secret from its two halves.pub fn join(theirs: &[u8; 32], held: &[u8; 32]) -> Zeroizing<[u8; 32]> {    let mut secret = Zeroizing::new([0u8; 32]);    for (i, byte) in secret.iter_mut().enumerate() {        *byte = theirs[i] ^ held[i];    }    secret}/// The context a trusted person's half is sealed to them under (cotton-core seal/share.rs `seal_to_person`).pub fn help_context(owner: &str) -> String {    format!("help:{owner}")}/// Whose recovery a compare is for (TRUSTED RECOVERY BUILD 2, review M1): the person's account (their number, as the/// helper's own pin of them holds it and as the new device signed in with it), the setup (`trusted` for the one-helper/// scheme, else the circle's id), the helper's place in it, and the request (the ask's id, or the circle request's)./// Every field goes into the commit and the digits, so a compare cannot be moved to another person, setup, place or/// request without the screens disagreeing.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct HelpFor<'a> {    pub account: &'a str,    pub setup: &'a str,    pub index: u32,    pub request: &'a str,}/// The setup of the one-helper scheme, for [`HelpFor`].pub const TRUSTED_SETUP: &str = "trusted";fn bind(hash: &mut Sha256, at: &HelpFor) {    for field in [at.account.as_bytes(), at.setup.as_bytes(), &at.index.to_be_bytes(), at.request.as_bytes()] {        hash.update((field.len() as u32).to_be_bytes());        hash.update(field);    }}/// What a new device asking a helper commits to before the helper's nonce exists: whose recovery ([`HelpFor`]), its/// vault key's public half and its own nonce. The Worker checks the reveal against it (apps/business/src/recovery.ts/// `helpCommit`), and the helper's phone checks it again against the commit IT saw when it set its nonce, so a key the/// server swaps in later breaks it.pub fn help_commit(at: &HelpFor, device_key: &[u8; 32], nonce: &[u8; 32]) -> [u8; 32] {    let mut hash = Sha256::new();    hash.update(b"cotton-help-commit-v2");    bind(&mut hash, at);    hash.update(device_key);    hash.update(nonce);    hash.finalize().into()}/// The six digits the new device shows and its helper types: worked out on both phones from whose recovery it is, the/// device's key and both nonces, never relayed. The construction is approval's (`vault::approval::sas_of`, the/// Bluetooth numeric comparison): the device commits before the helper's nonce exists and reveals only after, so the/// server cannot choose the code, and a key it swapped makes the two screens disagree.pub fn help_sas(at: &HelpFor, device_key: &[u8; 32], nonce_a: &[u8; 32], nonce_b: &[u8; 32]) -> String {    let mut hash = Sha256::new();    hash.update(b"cotton-help-sas-v2");    bind(&mut hash, at);    hash.update(device_key);    hash.update(nonce_a);    hash.update(nonce_b);    let digest: [u8; 32] = hash.finalize().into();    let n = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]) % 1_000_000;    format!("{n:06}")}/// Whether what the helper typed is the code: digits only, spaces and dashes aside.pub fn help_code_matches(code: &str, typed: &str) -> bool {    let digits: String = typed.chars().filter(|c| !c.is_whitespace() && *c != '-').collect();    digits.len() == 6 && digits.chars().all(|c| c.is_ascii_digit()) && digits == code}/// The context a helper's piece of the circle is sealed to them under: the setup and their place in it, so a piece/// opens only as what it was made for.pub fn circle_context(setup: &str, index: usize) -> String {    format!("help-circle:{setup}:{index}")}/// Q shared among `n` helpers so any `k` give it back (TRUSTED RECOVERY BUILD 1, step 4): replicated XOR, no field/// arithmetic. 1 of 1: the one piece is Q. 2 of 3: Q = q0 ⊕ q1 ⊕ q2 with q0, q1 random, and helper i holds every part/// but q_i, so any two hold all three and one alone lacks a uniformly random part. A piece is its parts, each one byte/// of index and 32 bytes. None for any other k of n.pub fn circle_pieces(q: &[u8; 32], k: usize, n: usize) -> Option<Vec<Vec<u8>>> {    match (k, n) {        (1, 1) => Some(vec![std::iter::once(0u8).chain(q.iter().copied()).collect()]),        (2, 3) => {            let mut parts = [[0u8; 32]; 3];            rand::rngs::OsRng.fill_bytes(&mut parts[0]);            rand::rngs::OsRng.fill_bytes(&mut parts[1]);            for i in 0..32 {                parts[2][i] = q[i] ^ parts[0][i] ^ parts[1][i];            }            let pieces = (0..3)                .map(|holder| {                    let mut piece = Vec::with_capacity(2 * 33);                    for (index, part) in parts.iter().enumerate().filter(|(index, _)| *index != holder) {                        piece.push(index as u8);                        piece.extend_from_slice(part);                    }                    piece                })                .collect();            parts.iter_mut().for_each(|part| part.fill(0));            Some(pieces)        }        _ => None,    }}/// Q from pieces of a k-of-n circle, or None when they do not hold every part (fewer than k helpers, the same piece/// twice, a part out of range or a piece cut short).pub fn circle_join(k: usize, n: usize, pieces: &[&[u8]]) -> Option<Zeroizing<[u8; 32]>> {    let parts_needed = match (k, n) {        (1, 1) => 1,        (2, 3) => 3,        _ => return None,    };    let mut parts: Vec<Option<[u8; 32]>> = vec![None; parts_needed];    for piece in pieces {        if piece.is_empty() || piece.len() % 33 != 0 {            return None;        }        for chunk in piece.chunks(33) {            let index = usize::from(chunk[0]);            let slot = parts.get_mut(index)?;            let part: [u8; 32] = chunk[1..].try_into().ok()?;            if slot.is_some_and(|held| held != part) {                return None;            }            *slot = Some(part);        }    }    let mut q = Zeroizing::new([0u8; 32]);    for part in parts {        let part = part?;        for (i, byte) in q.iter_mut().enumerate() {            *byte ^= part[i];        }    }    Some(q)}/// A new platform key: 32 random bytes.pub fn platform_key() -> Zeroizing<[u8; 32]> {    let mut key = Zeroizing::new([0u8; 32]);    rand::rngs::OsRng.fill_bytes(key.as_mut());    key}fn aad(kind: Kind, vmk_version: u32) -> String {    format!("cotton-recovery:v1:{}:{vmk_version}", kind.as_str())}/// The vault master key wrapped under a wrap key, bound to its kind and version.pub fn wrap(wrap_key: &[u8; 32], kind: Kind, vmk_version: u32, vmk: &[u8; 32]) -> Option<String> {    let mut nonce = [0u8; NONCE_LEN];    rand::rngs::OsRng.fill_bytes(&mut nonce);    wrap_with(&nonce, wrap_key, kind, vmk_version, vmk)}/// [`wrap`] with the nonce supplied.pub fn wrap_with(nonce: &[u8; NONCE_LEN], wrap_key: &[u8; 32], kind: Kind, vmk_version: u32, vmk: &[u8; 32]) -> Option<String> {    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrap_key));    let aad = aad(kind, vmk_version);    let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: vmk, aad: aad.as_bytes() }).ok()?;    let mut body = Vec::with_capacity(NONCE_LEN + ct.len());    body.extend_from_slice(nonce);    body.extend_from_slice(&ct);    Some(format!("{WRAP_PREFIX}{}", URL_SAFE_NO_PAD.encode(body)))}/// The vault master key a wrap holds, or None (another key, kind or version,/// a tampered body): the caller does the same in every case.pub fn unwrap(wrap_key: &[u8; 32], kind: Kind, vmk_version: u32, wrapped: &str) -> Option<Zeroizing<[u8; 32]>> {    let body = URL_SAFE_NO_PAD.decode(wrapped.strip_prefix(WRAP_PREFIX)?).ok()?;    if body.len() != NONCE_LEN + 32 + TAG_LEN {        return None;    }    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrap_key));    let aad = aad(kind, vmk_version);    let plain = Zeroizing::new(cipher.decrypt(Nonce::from_slice(&body[..NONCE_LEN]), Payload { msg: &body[NONCE_LEN..], aad: aad.as_bytes() }).ok()?);    let mut out = Zeroizing::new([0u8; 32]);    out.copy_from_slice(&plain);    Some(out)}#[cfg(test)]#[path = "recovery_code_tests.rs"]mod tests;