//! The `c2:` box: one chat payload sealed by one device for one device on a //! **Double Ratchet** (`assets/design/chat/SEALING.md`). //! //! The cryptography is Olm, from vodozemac (the Matrix team's audited Rust //! crate): a triple Diffie-Hellman first message over the recipient's //! identity key and one of its one-time keys, then a Double Ratchet per pair //! of devices. Nothing here derives a message key: this module keeps the //! account and the sessions, signs and checks what a device publishes, frames //! the box, and seals its own state file at rest. //! //! ```text //! a device's record { identity: Curve25519, signing: Ed25519, //! sig: Ed25519("cotton-chat-c2-device" ‖ chat key ‖ identity) } //! a one-time key { key: Curve25519, sig: Ed25519("cotton-chat-c2-prekey" ‖ identity ‖ key), fallback? } //! a box "c2:" + base64url(01 ‖ type (0 first, 1 later) ‖ sender identity (32) ‖ Olm message) //! the state file "c2s:" ‖ nonce (12) ‖ AES-256-GCM(HKDF-SHA256(chat secret, info "cotton-chat-c2-store"), //! aad = "cotton-chat-c2-store" ‖ chat public key, the store's JSON) //! ``` //! //! **Pins.** A device (by its handle) that has spoken `c2` with this one is //! pinned: the caller refuses its `c1` boxes and never seals `c1` for it //! again ([`Store::pinned`]). //! //! **Opened, not yet taken.** A box's words are kept in the store from the //! moment it opens until its envelope is acknowledged ([`Store::taken`]): an //! envelope held back and read again, or read again after a crash, opens //! again from here, since its message key is gone. use std::collections::{BTreeMap, BTreeSet}; use aes_gcm::aead::{Aead, Payload}; use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use hkdf::Hkdf; use rand::RngCore; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use vodozemac::olm::{Account, AccountPickle, DecryptionError, OlmMessage, Session, SessionConfig, SessionCreationError, SessionPickle}; use vodozemac::{Curve25519PublicKey, Ed25519PublicKey, Ed25519Signature}; use zeroize::Zeroizing; /// The prefix every `c2` box carries. pub const BOX_PREFIX: &str = "c2:"; const BOX_VERSION: u8 = 1; const DEVICE_STATEMENT: &[u8] = b"cotton-chat-c2-device"; const PREKEY_STATEMENT: &[u8] = b"cotton-chat-c2-prekey"; const STORE_INFO: &[u8] = b"cotton-chat-c2-store"; const STORE_PREFIX: &[u8] = b"c2s:"; const STORE_VERSION: u32 = 1; const NONCE_LEN: usize = 12; /// One-time keys a device keeps published; it tops up below [`PREKEYS_LOW`]. pub const PREKEYS_TARGET: usize = 50; pub const PREKEYS_LOW: usize = 25; /// Sessions kept with one device: both sides starting at once makes two. pub const SESSIONS_PER_DEVICE: usize = 4; /// Opened boxes kept until taken, at most; the oldest go first. pub const OPENED_MAX: usize = 2000; /// An opened box nobody took is forgotten after this long (the Worker's own hold). pub const OPENED_MS: i64 = 30 * 24 * 3_600_000; /// The fallback key is replaced after this long. pub const FALLBACK_MS: i64 = 7 * 24 * 3_600_000; /// What a device publishes beside its chat key: its Olm identity and signing keys, the second vouching for both. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Record { pub identity: String, pub signing: String, pub sig: String, } /// One of a device's published one-time keys (or its fallback key), signed. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Prekey { pub key: String, pub sig: String, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub fallback: bool, } /// A record whose signature held: the device's identity key and the key that signs for it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Verified { pub identity: [u8; 32], pub signing: [u8; 32], } /// Why a box could not be sealed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SealError { /// No session with this device yet: claim one of its one-time keys and seal again with it. NeedPrekey, /// The claimed key's signature does not hold, or the exchange would be weak. BadPrekey, } /// Why a box was not opened. Never shown; a dropped box is as if never sent. #[derive(Debug, Clone, PartialEq, Eq)] pub enum OpenError { /// Not a `c2` box this build reads. Unreadable, /// Sealed by an identity the sender does not publish. UnknownSender, /// Its key was used already: a replay, or a box opened and taken before. Replayed, /// No session opens it (this side's state was lost, or the other's): the pair is due a fresh session. Undecryptable { identity: [u8; 32] }, /// Too far ahead of the chain: more than the ratchet keeps skipping for. TooFarAhead, } /// An opened box: who sealed it (identity and the handle it was published under) and the payload. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Opened { pub identity: [u8; 32], pub handle: String, pub payload: Vec, } /// A device's whole ratchet: its account, its sessions, its pins and what it opened but has not had taken. pub struct Store { account: Account, /// Sessions by the other device's identity (base64url), the one to seal with first. sessions: BTreeMap>, /// Device handles that spoke `c2` with this device, each with the identity it last spoke with. pins: BTreeMap, opened: BTreeMap, /// Identities whose sessions opened nothing: the next box for them starts a fresh session. reset: BTreeSet, fallback_at: i64, } #[derive(Clone, Serialize, Deserialize)] struct Kept { /// SHA-256 of the box, base64url: the same item with another box is not this one. sealed: String, identity: String, handle: String, payload: String, at: i64, } #[derive(Serialize, Deserialize)] struct StoreFile { v: u32, account: AccountPickle, #[serde(default)] sessions: BTreeMap>, #[serde(default)] pins: BTreeMap, #[serde(default)] opened: BTreeMap, #[serde(default)] reset: BTreeSet, #[serde(default)] fallback_at: i64, } impl Store { /// A fresh account with its first fallback key (`now`: ms, for the fallback's age). pub fn new(now: i64) -> Self { let mut account = Account::new(); account.generate_fallback_key(); Self { account, sessions: BTreeMap::new(), pins: BTreeMap::new(), opened: BTreeMap::new(), reset: BTreeSet::new(), fallback_at: now } } /// This device's identity key. pub fn identity(&self) -> [u8; 32] { self.account.curve25519_key().to_bytes() } /// What this device publishes beside its chat key `chat_pub`. pub fn record(&self, chat_pub: &[u8; 32]) -> Record { let identity = self.identity(); let sig = self.account.sign(device_statement(chat_pub, &identity)); Record { identity: text(&identity), signing: text(self.account.ed25519_key().as_bytes()), sig: URL_SAFE_NO_PAD.encode(sig.to_bytes()) } } /// The one-time keys to publish when the Worker holds `left` of them: those not yet /// published, made when there are none and `left` is under [`PREKEYS_LOW`]. /// [`Store::published`] once the Worker took them. pub fn prekeys(&mut self, left: usize) -> Vec { if self.account.one_time_keys().is_empty() && left < PREKEYS_LOW { self.account.generate_one_time_keys(PREKEYS_TARGET.saturating_sub(left)); } let identity = self.identity(); let mut keys: Vec<_> = self.account.one_time_keys().into_iter().collect(); keys.sort_by_key(|(id, _)| id.to_base64()); keys.into_iter().map(|(_, key)| self.signed(&identity, &key, false)).collect() } /// The fallback key to publish, if it is new: replaced when older than [`FALLBACK_MS`]. pub fn fallback(&mut self, now: i64) -> Option { if now.saturating_sub(self.fallback_at) > FALLBACK_MS { self.account.generate_fallback_key(); self.fallback_at = now; } let identity = self.identity(); self.account.fallback_key().into_values().next().map(|key| self.signed(&identity, &key, true)) } /// The keys handed out by [`Store::prekeys`] and [`Store::fallback`] are on the Worker now. pub fn published(&mut self) { self.account.mark_keys_as_published(); } fn signed(&self, identity: &[u8; 32], key: &Curve25519PublicKey, fallback: bool) -> Prekey { let sig = self.account.sign(prekey_statement(identity, &key.to_bytes())); Prekey { key: text(&key.to_bytes()), sig: URL_SAFE_NO_PAD.encode(sig.to_bytes()), fallback } } /// Whether sealing for this device needs one of its one-time keys first. pub fn needs_prekey(&self, device: &Verified) -> bool { let id = text(&device.identity); self.reset.contains(&id) || self.sessions.get(&id).is_none_or(Vec::is_empty) } /// Seal `payload` for one device (published under `handle`), on its newest session, or on /// a fresh one from `claimed` (its one-time key, checked against its record here). pub fn seal(&mut self, handle: &str, device: &Verified, claimed: Option<&Prekey>, payload: &[u8]) -> Result { let id = text(&device.identity); if self.needs_prekey(device) { let prekey = claimed.ok_or(SealError::NeedPrekey)?; let key = verify_prekey(device, prekey).ok_or(SealError::BadPrekey)?; let session = self .account .create_outbound_session(SessionConfig::version_1(), Curve25519PublicKey::from_bytes(device.identity), Curve25519PublicKey::from_bytes(key)) .map_err(|_| SealError::BadPrekey)?; self.keep(&id, session); self.reset.remove(&id); } let session = self.sessions.get_mut(&id).and_then(|s| s.first_mut()).ok_or(SealError::NeedPrekey)?; let message = session.encrypt(payload).map_err(|_| SealError::BadPrekey)?; self.pins.insert(handle.to_string(), id); Ok(frame(&self.identity(), &message)) } /// Open a box from one of `senders` (each a handle and its checked record). `item` names the /// envelope it came in (kind, id, peer, direction): a box opened before and not yet taken /// opens again from what was kept. `now`: ms. pub fn open(&mut self, item: &str, sealed: &str, senders: &[(String, Verified)], now: i64) -> Result { let digest = URL_SAFE_NO_PAD.encode(Sha256::digest(sealed.as_bytes())); if let Some(kept) = self.opened.get(item).filter(|k| k.sealed == digest) { let identity = key_of(&kept.identity).ok_or(OpenError::Unreadable)?; let payload = URL_SAFE_NO_PAD.decode(&kept.payload).map_err(|_| OpenError::Unreadable)?; return Ok(Opened { identity, handle: kept.handle.clone(), payload }); } let (identity, message) = unframe(sealed).ok_or(OpenError::Unreadable)?; let (handle, _) = senders.iter().find(|(_, v)| v.identity == identity).ok_or(OpenError::UnknownSender)?; let id = text(&identity); let payload = match &message { OlmMessage::PreKey(first) => { // A first message of a session already made here (one sent again before an answer) opens on it. let known = self.sessions.get(&id).and_then(|list| list.iter().position(|s| s.session_id() == first.session_id())); match known { Some(at) => self.decrypt_at(&id, at, &message)?, None => { let made = self.account.create_inbound_session(SessionConfig::version_1(), Curve25519PublicKey::from_bytes(identity), first).map_err(|e| match e { SessionCreationError::MissingOneTimeKey(_) => OpenError::Replayed, SessionCreationError::Decryption(d) => decryption(d, identity), _ => OpenError::Undecryptable { identity }, })?; self.keep(&id, made.session); self.reset.remove(&id); made.plaintext } } } OlmMessage::Normal(_) => { let count = self.sessions.get(&id).map_or(0, Vec::len); let mut worst = OpenError::Undecryptable { identity }; let mut opened = None; for at in 0..count { match self.decrypt_at(&id, at, &message) { Ok(plain) => { opened = Some(plain); break; } // A key used already, or a gap too wide, on a session that knows this chain: not a lost session. Err(e @ (OpenError::Replayed | OpenError::TooFarAhead)) => worst = e, Err(_) => {} } } match opened { Some(plain) => plain, None => { if matches!(worst, OpenError::Undecryptable { .. }) { self.reset.insert(id.clone()); } return Err(worst); } } } }; self.pins.insert(handle.clone(), id.clone()); self.opened.insert(item.to_string(), Kept { sealed: digest, identity: id, handle: handle.clone(), payload: URL_SAFE_NO_PAD.encode(&payload), at: now }); self.trim_opened(now); Ok(Opened { identity, handle: handle.clone(), payload }) } /// Open a box **without changing anything**: what an iPhone's notification extension does to draw an alert /// (SEALING.md), the app opening it for real later. Only a box on a session this store already holds opens (a /// first message of a new session needs the sender's published record, which the extension does not ask): its /// sealer is trusted as that session's other side, checked when the session was made. A box opened and not yet /// taken opens from what was kept. `None` for every other box. pub fn peek(&self, item: &str, sealed: &str) -> Option<([u8; 32], Vec)> { let digest = URL_SAFE_NO_PAD.encode(Sha256::digest(sealed.as_bytes())); if let Some(kept) = self.opened.get(item).filter(|k| k.sealed == digest) { return Some((key_of(&kept.identity)?, URL_SAFE_NO_PAD.decode(&kept.payload).ok()?)); } let (identity, message) = unframe(sealed)?; let sessions = self.sessions.get(&text(&identity))?; let first = match &message { OlmMessage::PreKey(m) => Some(m.session_id()), OlmMessage::Normal(_) => None, }; sessions.iter().filter(|s| first.as_ref().is_none_or(|id| &s.session_id() == id)).find_map(|session| { // A copy of the session: its keys are used on the copy alone, and the copy is dropped. let mut copy = Session::from_pickle(session.pickle()); copy.decrypt(&message).ok().map(|plain| (identity, plain)) }) } /// The session at `at` opens it: it moves to the front, the one to seal with next. fn decrypt_at(&mut self, id: &str, at: usize, message: &OlmMessage) -> Result, OpenError> { let identity = key_of(id).unwrap_or([0; 32]); let list = self.sessions.get_mut(id).ok_or(OpenError::Undecryptable { identity })?; let plain = list[at].decrypt(message).map_err(|e| decryption(e, identity))?; let session = list.remove(at); list.insert(0, session); Ok(plain) } fn keep(&mut self, id: &str, session: Session) { let list = self.sessions.entry(id.to_string()).or_default(); list.insert(0, session); list.truncate(SESSIONS_PER_DEVICE); } fn trim_opened(&mut self, now: i64) { self.opened.retain(|_, k| now.saturating_sub(k.at) < OPENED_MS); while self.opened.len() > OPENED_MAX { let Some(oldest) = self.opened.iter().min_by_key(|(_, k)| k.at).map(|(key, _)| key.clone()) else { break }; self.opened.remove(&oldest); } } /// These envelopes were taken: their kept words go. pub fn taken<'a>(&mut self, items: impl IntoIterator) -> bool { let before = self.opened.len(); for item in items { self.opened.remove(item); } before != self.opened.len() } /// Whether this device handle has spoken `c2` with this device: no `c1` from or for it again. pub fn pinned(&self, handle: &str) -> bool { self.pins.contains_key(handle) } /// How much this ratchet holds: the devices it has sessions with, the sessions, the handles pinned, the boxes opened and not taken. pub fn summary(&self) -> (usize, usize, usize, usize) { (self.sessions.len(), self.sessions.values().map(Vec::len).sum(), self.pins.len(), self.opened.len()) } /// Whether a fresh session is due with this identity (its boxes opened nothing). pub fn due_reset(&self, identity: &[u8; 32]) -> bool { self.reset.contains(&text(identity)) } /// The store sealed under the chat key (`chat_secret`), for its file. pub fn to_bytes(&self, chat_secret: &[u8; 32]) -> Option> { let file = StoreFile { v: STORE_VERSION, account: self.account.pickle(), sessions: self.sessions.iter().map(|(k, list)| (k.clone(), list.iter().map(Session::pickle).collect())).collect(), pins: self.pins.clone(), opened: self.opened.clone(), reset: self.reset.clone(), fallback_at: self.fallback_at, }; let plain = Zeroizing::new(serde_json::to_vec(&file).ok()?); let mut nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(&mut nonce); seal_store_with(chat_secret, &nonce, &plain) } /// A store read back from its file; `None` when the chat key is not the one it was sealed under, or it is not one. pub fn from_bytes(chat_secret: &[u8; 32], bytes: &[u8]) -> Option { let plain = open_store(chat_secret, bytes)?; let file: StoreFile = serde_json::from_slice(&plain).ok()?; if file.v != STORE_VERSION { return None; } Some(Self { account: Account::from_pickle(file.account), sessions: file.sessions.into_iter().map(|(k, list)| (k, list.into_iter().map(Session::from_pickle).collect())).collect(), pins: file.pins, opened: file.opened, reset: file.reset, fallback_at: file.fallback_at, }) } } fn decryption(error: DecryptionError, identity: [u8; 32]) -> OpenError { match error { DecryptionError::MissingMessageKey(_) => OpenError::Replayed, DecryptionError::TooBigMessageGap(..) => OpenError::TooFarAhead, _ => OpenError::Undecryptable { identity }, } } /// A device's record checked against the chat key it was published with. pub fn verify_record(chat_pub: &[u8; 32], record: &Record) -> Option { let identity = key_of(&record.identity)?; let signing = key_of(&record.signing)?; let key = Ed25519PublicKey::from_slice(&signing).ok()?; let sig = Ed25519Signature::from_slice(&URL_SAFE_NO_PAD.decode(&record.sig).ok()?).ok()?; key.verify(&device_statement(chat_pub, &identity), &sig).ok()?; Some(Verified { identity, signing }) } /// A one-time key checked against the device's record: its key, when the signature holds. pub fn verify_prekey(device: &Verified, prekey: &Prekey) -> Option<[u8; 32]> { let key = key_of(&prekey.key)?; let signing = Ed25519PublicKey::from_slice(&device.signing).ok()?; let sig = Ed25519Signature::from_slice(&URL_SAFE_NO_PAD.decode(&prekey.sig).ok()?).ok()?; signing.verify(&prekey_statement(&device.identity, &key), &sig).ok()?; Some(key) } /// What a device's signing key signs to vouch for its identity beside its chat key. pub fn device_statement(chat_pub: &[u8; 32], identity: &[u8; 32]) -> Vec { [DEVICE_STATEMENT, chat_pub.as_slice(), identity.as_slice()].concat() } /// What a device's signing key signs for each of its one-time keys. pub fn prekey_statement(identity: &[u8; 32], key: &[u8; 32]) -> Vec { [PREKEY_STATEMENT, identity.as_slice(), key.as_slice()].concat() } /// Whether a box is a `c2` one. pub fn is_c2(sealed: &str) -> bool { sealed.starts_with(BOX_PREFIX) } /// The identity a `c2` box names as its sealer, without opening it. pub fn sender_of(sealed: &str) -> Option<[u8; 32]> { unframe(sealed).map(|(identity, _)| identity) } fn frame(identity: &[u8; 32], message: &OlmMessage) -> String { let (kind, bytes) = message.to_parts(); let mut body = Vec::with_capacity(34 + bytes.len()); body.push(BOX_VERSION); body.push(kind as u8); body.extend_from_slice(identity); body.extend_from_slice(&bytes); format!("{BOX_PREFIX}{}", URL_SAFE_NO_PAD.encode(body)) } fn unframe(sealed: &str) -> Option<([u8; 32], OlmMessage)> { let body = URL_SAFE_NO_PAD.decode(sealed.strip_prefix(BOX_PREFIX)?).ok()?; if body.len() < 35 || body[0] != BOX_VERSION { return None; } let identity: [u8; 32] = body[2..34].try_into().ok()?; let message = OlmMessage::from_parts(body[1] as usize, &body[34..]).ok()?; Some((identity, message)) } /// The state file's sealing with its nonce supplied: the vectors' form. pub fn seal_store_with(chat_secret: &[u8; 32], nonce: &[u8; NONCE_LEN], plain: &[u8]) -> Option> { let chat_pub = crate::vault::wrap::public_of(chat_secret); let key = store_key(chat_secret)?; let cipher = Aes256Gcm::new(Key::::from_slice(key.as_slice())); let aad = [STORE_INFO, chat_pub.as_slice()].concat(); let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: plain, aad: &aad }).ok()?; Some([STORE_PREFIX, nonce.as_slice(), &ct].concat()) } fn open_store(chat_secret: &[u8; 32], bytes: &[u8]) -> Option>> { let rest = bytes.strip_prefix(STORE_PREFIX)?; if rest.len() < NONCE_LEN + 16 { return None; } let chat_pub = crate::vault::wrap::public_of(chat_secret); let key = store_key(chat_secret)?; let cipher = Aes256Gcm::new(Key::::from_slice(key.as_slice())); let aad = [STORE_INFO, chat_pub.as_slice()].concat(); cipher.decrypt(Nonce::from_slice(&rest[..NONCE_LEN]), Payload { msg: &rest[NONCE_LEN..], aad: &aad }).ok().map(Zeroizing::new) } fn store_key(chat_secret: &[u8; 32]) -> Option> { let mut key = Zeroizing::new([0u8; 32]); Hkdf::::new(None, chat_secret).expand(STORE_INFO, key.as_mut_slice()).ok()?; Some(key) } /// The state file's name for a chat key: one store per key, so a new key starts afresh. pub fn store_name(chat_pub: &[u8; 32]) -> String { format!("chat-ratchet-{}.c2", hex::encode(&Sha256::digest(chat_pub)[..8])) } fn text(key: &[u8]) -> String { URL_SAFE_NO_PAD.encode(key) } fn key_of(text: &str) -> Option<[u8; 32]> { URL_SAFE_NO_PAD.decode(text).ok()?.try_into().ok() } #[cfg(test)] #[path = "ratchet_tests.rs"] mod tests;