Cotton code
146 lines · 6.6 KB · RustRaw
//! The `c1:` box: one chat payload sealed by one device for one device.//!//! The vault's wrap ([`crate::vault::wrap`]) in its authenticated form: an//! ephemeral X25519 pair per box, AND the sender device's own static key, so//! the box says which device sealed it and nobody without that device's//! private half can make one that says so (HPKE's auth mode in spirit).//!//! ```text//! seal(sender_secret, recipient_pub, payload)//!   eph     = X25519 keypair//!   dh1     = x25519(eph.secret, recipient_pub)          // all-zero REFUSED//!   dh2     = x25519(sender_secret, recipient_pub)       // all-zero REFUSED//!   key     = HKDF-SHA256(ikm  = dh1 || dh2,//!                         salt = eph.pub || sender_pub || recipient_pub,//!                         info = "cotton-chat-v1", 32)//!   nonce   = 12 random bytes//!   ct      = AES-256-GCM(key, nonce, payload,//!                         aad = "cotton-chat-v1" || sender_pub || recipient_pub)//!   →  "c1:" + base64url_nopad(eph.pub || sender_pub || nonce || ct)//! ```//!//! **Its own domain.** The info string is not the vault's: a chat box can never//! be offered as a vault wrap, nor a wrap as a box, and a later scheme (`c2:`)//! derives different keys from the same exchange.//!//! **What it gives.** Only the recipient device reads the payload; the sender//! device is named and cannot be forged by a third party; a box moved to//! another device, or edited, fails to open. **What it does not give.** No//! forward secrecy: a device's chat private half, once stolen, opens every box//! ever sealed for it that the thief also kept. No post-compromise healing//! either: that is a ratchet's job (the upgrade path is `c2:`, an X3DH-style//! first message and a Double Ratchet per pair of devices, keyed off these//! same published keys). And the keys themselves are as honest as the Worker//! that hands them out: a fingerprint compared by eye//! ([`crate::vault::wrap::fingerprint`]) is what catches a swapped key.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 sha2::Sha256;use zeroize::Zeroizing;use crate::vault::wrap::public_of;/// The prefix every box carries.pub const BOX_PREFIX: &str = "c1:";/// HKDF's info and the head of the aad: the scheme and its version.const INFO: &[u8] = b"cotton-chat-v1";const NONCE_LEN: usize = 12;const TAG_LEN: usize = 16;/// What an opened box says: the device that sealed it and the payload.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Opened {    pub sender: [u8; 32],    pub payload: Vec<u8>,}/// Seal `payload` from this device (`sender_secret`) for one device's public key./// `None` when either exchange answers all zeroes (a small-order key).pub fn seal(sender_secret: &[u8; 32], recipient_pub: &[u8; 32], payload: &[u8]) -> Option<String> {    let mut ephemeral = Zeroizing::new([0u8; 32]);    let mut nonce = [0u8; NONCE_LEN];    rand::rngs::OsRng.fill_bytes(ephemeral.as_mut_slice());    rand::rngs::OsRng.fill_bytes(&mut nonce);    seal_with(&ephemeral, &nonce, sender_secret, recipient_pub, payload)}/// [`seal`] with its randomness supplied: the vectors' form.pub fn seal_with(ephemeral_secret: &[u8; 32], nonce: &[u8; NONCE_LEN], sender_secret: &[u8; 32], recipient_pub: &[u8; 32], payload: &[u8]) -> Option<String> {    let ephemeral_pub = public_of(ephemeral_secret);    let sender_pub = public_of(sender_secret);    let dh1 = Zeroizing::new(x25519_dalek::x25519(*ephemeral_secret, *recipient_pub));    let dh2 = Zeroizing::new(x25519_dalek::x25519(*sender_secret, *recipient_pub));    let key = derive(&dh1, &dh2, &ephemeral_pub, &sender_pub, recipient_pub)?;    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_slice()));    let aad = aad(&sender_pub, recipient_pub);    let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: payload, aad: &aad }).ok()?;    let mut body = Vec::with_capacity(64 + NONCE_LEN + ct.len());    body.extend_from_slice(&ephemeral_pub);    body.extend_from_slice(&sender_pub);    body.extend_from_slice(nonce);    body.extend_from_slice(&ct);    Some(format!("{BOX_PREFIX}{}", URL_SAFE_NO_PAD.encode(body)))}/// Open a box with this device's private half: the sealing device and the/// payload, or `None` for every way it can fail (one answer, no oracle).pub fn open(recipient_secret: &[u8; 32], sealed: &str) -> Option<Opened> {    let body = URL_SAFE_NO_PAD.decode(sealed.strip_prefix(BOX_PREFIX)?).ok()?;    if body.len() < 64 + NONCE_LEN + TAG_LEN {        return None;    }    let ephemeral_pub: [u8; 32] = body[..32].try_into().ok()?;    let sender_pub: [u8; 32] = body[32..64].try_into().ok()?;    let nonce = &body[64..64 + NONCE_LEN];    let ct = &body[64 + NONCE_LEN..];    let recipient_pub = public_of(recipient_secret);    let dh1 = Zeroizing::new(x25519_dalek::x25519(*recipient_secret, ephemeral_pub));    let dh2 = Zeroizing::new(x25519_dalek::x25519(*recipient_secret, sender_pub));    let key = derive(&dh1, &dh2, &ephemeral_pub, &sender_pub, &recipient_pub)?;    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_slice()));    let aad = aad(&sender_pub, &recipient_pub);    let payload = cipher.decrypt(Nonce::from_slice(nonce), Payload { msg: ct, aad: &aad }).ok()?;    Some(Opened { sender: sender_pub, payload })}/// A public key as the wire carries it: 32 bytes, base64url without padding.pub fn key_from_text(text: &str) -> Option<[u8; 32]> {    URL_SAFE_NO_PAD.decode(text).ok()?.try_into().ok()}pub fn key_text(key: &[u8; 32]) -> String {    URL_SAFE_NO_PAD.encode(key)}fn aad(sender_pub: &[u8; 32], recipient_pub: &[u8; 32]) -> Vec<u8> {    let mut aad = Vec::with_capacity(INFO.len() + 64);    aad.extend_from_slice(INFO);    aad.extend_from_slice(sender_pub);    aad.extend_from_slice(recipient_pub);    aad}fn derive(dh1: &[u8; 32], dh2: &[u8; 32], ephemeral_pub: &[u8; 32], sender_pub: &[u8; 32], recipient_pub: &[u8; 32]) -> Option<Zeroizing<[u8; 32]>> {    if dh1 == &[0u8; 32] || dh2 == &[0u8; 32] {        return None;    }    let mut ikm = Zeroizing::new([0u8; 64]);    ikm[..32].copy_from_slice(dh1);    ikm[32..].copy_from_slice(dh2);    let mut salt = [0u8; 96];    salt[..32].copy_from_slice(ephemeral_pub);    salt[32..64].copy_from_slice(sender_pub);    salt[64..].copy_from_slice(recipient_pub);    let mut key = Zeroizing::new([0u8; 32]);    Hkdf::<Sha256>::new(Some(&salt), ikm.as_slice()).expand(INFO, key.as_mut_slice()).ok()?;    Some(key)}#[cfg(test)]#[path = "seal_tests.rs"]mod tests;