Cotton code
218 lines · 10.9 KB · RustRaw
//! THE ONE SHARING KEY RULE (ruling R5, 15 Nov 2026).//!//! Each person has ONE sharing key, an X25519 pair. Its secret half is//! DERIVED from the person's data key, the way the table keys are, so every//! device that holds the DK holds it, a phone opens what was sent to it in a//! background pull with no presence prompt, an approved new phone has it with//! no step, and there is nothing to store or sync. Only the public half//! leaves the device: a phone posts it to its own object, which hands it only//! to the person's accepted people (and a made-up key to anyone else, so a//! lookup never says whether a number is on Cotton).//!//! ```text//! share secret  = HKDF-SHA256(ikm=DK, salt=database_id, info="cotton-share-v1")//! share pub     = X25519(share secret)//! sent box      = "p1:" b64url(eph.pub || sender_pub || nonce12 || AES-256-GCM(key, payload, aad))//!   key         = HKDF-SHA256(ikm = x25519(eph, rcpt) || x25519(sender, rcpt),//!                             salt = eph.pub || sender_pub || rcpt_pub, info = "cotton-send-v1")//!   aad         = "cotton-send-v1" || sender_pub || rcpt_pub || context//! wrapped_dek   = w1(friend's share_pub, DEK || table "\n" row_id)          (one record, plan §5)//! ```//!//! Anything sent (a Send's payload, a shared set's key) is sealed to the//! recipient's sharing key ON THE SENDER'S DEVICE; the objects route the box//! and never open it. The box names the sender's sharing key and nobody//! without that secret can make one that does (chat's `c1:` construction in//! its own domain, so a chat box is never a sent box). `context` binds the box//! to what carries it (a send's id), so a box moved onto another send opens//! nothing. No forward secrecy, as chat says of `c1:`: a stolen DK opens//! every box sent to that person that the thief also kept.//!//! The opener of a wrapped DEK checks the table and row the wrap names against//! the share row it came with, so a wrapped DEK moved onto another share//! opens nothing.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 super::keys::{hkdf, DataKey, Key32};use super::row::Dek;use super::{plain_field, SealError, NONCE_LEN};use crate::vault::seal::{open as vault_open, seal_with as vault_seal_with, Vmk};use crate::vault::wrap::{public_of, unwrap, wrap_with};/// HKDF info of the sharing key's secret half.pub const SHARE_INFO: &str = "cotton-share-v1";/// The prefix of a box sealed to a person.pub const SENT_PREFIX: &str = "p1:";/// The sent box's HKDF info and the head of its aad.const SENT_INFO: &[u8] = b"cotton-send-v1";const TAG_LEN: usize = 16;/// This person's sharing key, its secret half, from their DK.pub fn sharing_secret(dk: &DataKey, database_id: &str) -> Result<Key32, SealError> {    plain_field("database", database_id)?;    hkdf(dk, database_id, SHARE_INFO)}/// This person's sharing key, its public half: what their object hands their people.pub fn sharing_public(dk: &DataKey, database_id: &str) -> Result<[u8; 32], SealError> {    Ok(public_of(&*sharing_secret(dk, database_id)?))}/// The sharing key's public half as the wire carries it (base64url, no padding).pub fn key_text(key: &[u8; 32]) -> String {    URL_SAFE_NO_PAD.encode(key)}/// A sharing key off the wire; none when it is not 32 bytes of base64url.pub fn key_from_text(text: &str) -> Option<[u8; 32]> {    URL_SAFE_NO_PAD.decode(text).ok()?.try_into().ok()}/// What an opened sent box says: the sender's sharing key, and the payload.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Opened {    pub sender: [u8; 32],    pub payload: Vec<u8>,}/// Seal `payload` from this person (their sharing secret) to another person's/// sharing key, bound to `context` (what carries it: `send:<id>`).pub fn seal_to_person(sender_secret: &[u8; 32], recipient_pub: &[u8; 32], context: &str, payload: &[u8]) -> Result<String, SealError> {    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_to_person_with(&ephemeral, &nonce, sender_secret, recipient_pub, context, payload)}/// [`seal_to_person`] with its randomness supplied: the vectors' form.pub fn seal_to_person_with(ephemeral: &[u8; 32], nonce: &[u8; NONCE_LEN], sender_secret: &[u8; 32], recipient_pub: &[u8; 32], context: &str, payload: &[u8]) -> Result<String, SealError> {    let ephemeral_pub = public_of(ephemeral);    let sender_pub = public_of(sender_secret);    let dh1 = Zeroizing::new(x25519_dalek::x25519(*ephemeral, *recipient_pub));    let dh2 = Zeroizing::new(x25519_dalek::x25519(*sender_secret, *recipient_pub));    let key = sent_key(&dh1, &dh2, &ephemeral_pub, &sender_pub, recipient_pub).ok_or_else(|| SealError::BadInput("the recipient's sharing key is not a usable X25519 key".into()))?;    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_slice()));    let aad = sent_aad(&sender_pub, recipient_pub, context);    let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: payload, aad: &aad }).map_err(|_| SealError::Failed)?;    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);    Ok(format!("{SENT_PREFIX}{}", URL_SAFE_NO_PAD.encode(body)))}/// Open a box sent to this person, under `context`: the sender's sharing key/// and the payload, or `seal_does_not_open` for every way it can fail.pub fn open_from_person(recipient_secret: &[u8; 32], sealed: &str, context: &str) -> Result<Opened, SealError> {    let body = URL_SAFE_NO_PAD.decode(sealed.strip_prefix(SENT_PREFIX).ok_or(SealError::DoesNotOpen)?).map_err(|_| SealError::DoesNotOpen)?;    if body.len() < 64 + NONCE_LEN + TAG_LEN {        return Err(SealError::DoesNotOpen);    }    let ephemeral_pub: [u8; 32] = body[..32].try_into().map_err(|_| SealError::DoesNotOpen)?;    let sender: [u8; 32] = body[32..64].try_into().map_err(|_| SealError::DoesNotOpen)?;    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));    let key = sent_key(&dh1, &dh2, &ephemeral_pub, &sender, &recipient_pub).ok_or(SealError::DoesNotOpen)?;    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_slice()));    let aad = sent_aad(&sender, &recipient_pub, context);    let payload = cipher.decrypt(Nonce::from_slice(&body[64..64 + NONCE_LEN]), Payload { msg: &body[64 + NONCE_LEN..], aad: &aad }).map_err(|_| SealError::DoesNotOpen)?;    Ok(Opened { sender, payload })}fn sent_aad(sender_pub: &[u8; 32], recipient_pub: &[u8; 32], context: &str) -> Vec<u8> {    let mut aad = Vec::with_capacity(SENT_INFO.len() + 64 + context.len());    aad.extend_from_slice(SENT_INFO);    aad.extend_from_slice(sender_pub);    aad.extend_from_slice(recipient_pub);    aad.extend_from_slice(context.as_bytes());    aad}fn sent_key(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(SENT_INFO, key.as_mut_slice()).ok()?;    Some(key)}/// The prefix of the id a share key's private half is sealed under.pub const SHARE_SEAL_PREFIX: &str = "share-key:";fn share_plaintext(dek: &Dek, table: &str, row_id: &str) -> Result<Zeroizing<Vec<u8>>, SealError> {    plain_field("table", table)?;    plain_field("row", row_id)?;    let mut out = Zeroizing::new(Vec::with_capacity(32 + table.len() + 1 + row_id.len()));    out.extend_from_slice(dek.expose());    out.extend_from_slice(table.as_bytes());    out.push(b'\n');    out.extend_from_slice(row_id.as_bytes());    Ok(out)}/// `share.wrapped_dek` for one record, to the friend's share key.pub fn wrap_dek_for(share_pub: &[u8; 32], dek: &Dek, table: &str, row_id: &str) -> Result<String, SealError> {    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);    wrap_dek_for_with(&ephemeral, &nonce, share_pub, dek, table, row_id)}/// [`wrap_dek_for`] with the randomness supplied.pub fn wrap_dek_for_with(ephemeral: &[u8; 32], nonce: &[u8; NONCE_LEN], share_pub: &[u8; 32], dek: &Dek, table: &str, row_id: &str) -> Result<String, SealError> {    wrap_with(ephemeral, nonce, share_pub, &share_plaintext(dek, table, row_id)?).ok_or(SealError::BadInput("share_pub is not a usable X25519 key".into()))}/// The DEK out of a wrap, on the friend's phone, refused unless it names this/// table and row.pub fn open_shared_dek(share_secret: &[u8; 32], wrapped: &str, table: &str, row_id: &str) -> Result<Dek, SealError> {    let plain = Zeroizing::new(unwrap(share_secret, wrapped).ok_or(SealError::DoesNotOpen)?);    if plain.len() < 32 || plain[32..] != *format!("{table}\n{row_id}").as_bytes() {        return Err(SealError::DoesNotOpen);    }    let array: [u8; 32] = plain[..32].try_into().map_err(|_| SealError::DoesNotOpen)?;    Ok(Dek::from_bytes(array))}/// The share key's private half, sealed under the VMK, with the nonce supplied.pub fn seal_share_private_with(nonce: &[u8; NONCE_LEN], vmk: &Vmk, vmk_version: u32, person_fingerprint: &str, secret: &[u8; 32]) -> Result<String, SealError> {    vault_seal_with(nonce, vmk, &format!("{SHARE_SEAL_PREFIX}{person_fingerprint}"), vmk_version, secret).ok_or(SealError::Failed)}/// [`seal_share_private_with`] with a nonce from the OS.pub fn seal_share_private(vmk: &Vmk, vmk_version: u32, person_fingerprint: &str, secret: &[u8; 32]) -> Result<String, SealError> {    let mut nonce = [0u8; NONCE_LEN];    rand::rngs::OsRng.fill_bytes(&mut nonce);    seal_share_private_with(&nonce, vmk, vmk_version, person_fingerprint, secret)}/// The share key's private half back out.pub fn open_share_private(vmk: &Vmk, vmk_version: u32, person_fingerprint: &str, sealed: &str) -> Result<Zeroizing<[u8; 32]>, SealError> {    let bytes = Zeroizing::new(vault_open(vmk, &format!("{SHARE_SEAL_PREFIX}{person_fingerprint}"), vmk_version, sealed).ok_or(SealError::DoesNotOpen)?);    let array: [u8; 32] = bytes.as_slice().try_into().map_err(|_| SealError::DoesNotOpen)?;    Ok(Zeroizing::new(array))}#[cfg(test)]#[path = "share_tests.rs"]mod tests;