Cotton code
196 lines · 7.6 KB · RustRaw
//! The wrap primitive: 32 bytes, sealed to one X25519 public key (spec §2.1).//!//! Sealed-box shaped, HPKE base mode in spirit. An ephemeral pair per wrap, a//! shared secret by X25519, a key by HKDF-SHA256 over it, and AES-256-GCM with//! the recipient's public key as associated data.//!//! ```text//! wrap(recipient_pub, plaintext)//!   eph     = X25519 keypair//!   shared  = x25519(eph.secret, recipient_pub)        // all-zero is REFUSED//!   key     = HKDF-SHA256(ikm = shared,//!                         salt = eph.pub || recipient_pub,//!                         info = "cotton-vault-wrap-v1", 32)//!   nonce   = 12 random bytes//!   ct      = AES-256-GCM(key, nonce, plaintext, aad = recipient_pub)//!   →  "w1:" + base64url_nopad(eph.pub || nonce || ct)//! ```//!//! **Why the salt and the aad are what they are.** The salt binds the derived//! key to BOTH halves of the exchange, so a wrap made for one device cannot be//! replayed as a wrap made for another by swapping the ephemeral half. The aad//! binds the ciphertext to the recipient, so a row moved from one device's//! `cotton_vault_keys` line to another's fails to open rather than opening//! something it should not.//!//! **Why the all-zero shared secret is refused.** X25519 answers all zeroes for//! a small-order public key. A key derived from it is a key an attacker who//! chose that public key also knows, so a wrap made to one is a wrap made to//! nobody — and it would LOOK like a wrap. A refusal is the only honest answer.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;/// The prefix every wrap carries. A value without it is not a wrap, and/// nothing tries to open one.pub const WRAP_PREFIX: &str = "w1:";/// HKDF's domain separator. It carries the VERSION, so a later scheme derives a/// different key from the same exchange rather than silently sharing one.const INFO: &[u8] = b"cotton-vault-wrap-v1";const NONCE_LEN: usize = 12;const KEY_LEN: usize = 32;/// AES-GCM's authentication tag. A body shorter than an ephemeral key, a nonce/// and a tag cannot be a wrap of anything.const TAG_LEN: usize = 16;/// Wrap `plaintext` for one X25519 public key.////// `None` when the recipient's public key is one X25519 answers all zeroes/// for — see the module header. The ephemeral secret and the nonce come from/// the OS; [`wrap_with`] takes them, which is what the vectors below use.pub fn wrap(recipient_pub: &[u8; 32], plaintext: &[u8]) -> Option<String> {    let mut ephemeral = Zeroizing::new([0u8; 32]);    let mut nonce = [0u8; NONCE_LEN];    let mut rng = rand::rngs::OsRng;    rng.fill_bytes(ephemeral.as_mut_slice());    rng.fill_bytes(&mut nonce);    wrap_with(&ephemeral, &nonce, recipient_pub, plaintext)}/// [`wrap`] with the randomness supplied — the pure half, so a test is a vector/// rather than a round trip that could pass for the wrong reason.pub fn wrap_with(    ephemeral_secret: &[u8; 32],    nonce: &[u8; NONCE_LEN],    recipient_pub: &[u8; 32],    plaintext: &[u8],) -> Option<String> {    let ephemeral_pub = public_of(ephemeral_secret);    let shared = Zeroizing::new(x25519_dalek::x25519(*ephemeral_secret, *recipient_pub));    let key = derive_key(&shared, &ephemeral_pub, recipient_pub)?;    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_slice()));    let ciphertext = cipher        .encrypt(            Nonce::from_slice(nonce),            Payload {                msg: plaintext,                aad: recipient_pub.as_slice(),            },        )        .ok()?;    let mut body = Vec::with_capacity(32 + NONCE_LEN + ciphertext.len());    body.extend_from_slice(&ephemeral_pub);    body.extend_from_slice(nonce);    body.extend_from_slice(&ciphertext);    Some(format!("{WRAP_PREFIX}{}", URL_SAFE_NO_PAD.encode(body)))}/// Open a wrap with the recipient's private scalar.////// `None` for every way it can fail — a wrong key, a tampered body, a value/// that is not a wrap at all — and deliberately so: the caller's next move is/// the same for all of them, and a reason that distinguished them would be an/// oracle.pub fn unwrap(recipient_secret: &[u8; 32], wrapped: &str) -> Option<Vec<u8>> {    let body = URL_SAFE_NO_PAD        .decode(wrapped.strip_prefix(WRAP_PREFIX)?)        .ok()?;    if body.len() < 32 + NONCE_LEN + TAG_LEN {        return None;    }    let ephemeral_pub: [u8; 32] = body[..32].try_into().ok()?;    let nonce = &body[32..32 + NONCE_LEN];    let ciphertext = &body[32 + NONCE_LEN..];    let recipient_pub = public_of(recipient_secret);    let shared = Zeroizing::new(x25519_dalek::x25519(*recipient_secret, ephemeral_pub));    let key = derive_key(&shared, &ephemeral_pub, &recipient_pub)?;    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_slice()));    cipher        .decrypt(            Nonce::from_slice(nonce),            Payload {                msg: ciphertext,                aad: recipient_pub.as_slice(),            },        )        .ok()}/// The public half of a private scalar — what a device publishes in its/// `cotton_vault_keys` row.pub fn public_of(secret: &[u8; 32]) -> [u8; 32] {    x25519_dalek::x25519(*secret, x25519_dalek::X25519_BASEPOINT_BYTES)}/// What a person compares to know two screens name the same device key: the/// first eight bytes of SHA-256 over the 32-byte public half, as four groups/// of four hex digits (`1a2b 3c4d 5e6f 7a8b`). The phone's Devices list and/// the Mac importer's waiting line both say it, so an approval can be checked/// by eye. `None` for a value that is not a 32-byte base64url key.pub fn fingerprint(public_key: &str) -> Option<String> {    use sha2::Digest as _;    let bytes = URL_SAFE_NO_PAD.decode(public_key).ok()?;    if bytes.len() != 32 {        return None;    }    let digest = Sha256::digest(&bytes);    let hex: String = digest[..8].iter().map(|byte| format!("{byte:02x}")).collect();    Some(        hex.as_bytes()            .chunks(4)            .map(|chunk| std::str::from_utf8(chunk).unwrap_or_default())            .collect::<Vec<_>>()            .join(" "),    )}/// A fresh X25519 private scalar, from the OS.////// The public half is [`public_of`]. The scalar is returned inside/// [`Zeroizing`] so a caller that drops it without storing it does not leave it/// on the stack.pub fn mint_vault_key() -> Zeroizing<[u8; 32]> {    let mut secret = Zeroizing::new([0u8; 32]);    rand::rngs::OsRng.fill_bytes(secret.as_mut_slice());    secret}/// Both sides derive the same key from the same three inputs — the whole of the/// agreement, stated once so the two halves cannot drift.////// The wrapping side computes the shared secret as/// `x25519(ephemeral_secret, recipient_pub)` and the opening side as/// `x25519(recipient_secret, ephemeral_pub)`; those are the same 32 bytes, and/// this function is everything that happens after them.fn derive_key(    shared: &Zeroizing<[u8; 32]>,    ephemeral_pub: &[u8; 32],    recipient_pub: &[u8; 32],) -> Option<Zeroizing<[u8; KEY_LEN]>> {    if shared.as_slice() == [0u8; 32] {        return None;    }    let mut salt = [0u8; 64];    salt[..32].copy_from_slice(ephemeral_pub);    salt[32..].copy_from_slice(recipient_pub);    let mut key = Zeroizing::new([0u8; KEY_LEN]);    Hkdf::<Sha256>::new(Some(&salt), shared.as_slice())        .expand(INFO, key.as_mut_slice())        .ok()?;    Some(key)}#[cfg(test)]#[path = "wrap_tests.rs"]mod tests;