mailcycle 0.3.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! Sealing to a public key: how inbound mail reaches an address the server
//! cannot read.
//!
//! Ephemeral-static ECDH, in the shape of a NaCl sealed box:
//!
//! ```text
//! shared  = X25519(ephemeral_private, recipient_public)
//! secret  = HMAC(shared, transcript | "/enc") | HMAC(shared, transcript | "/mac")
//! box     = ChaCha20(secret[0..32], nonce, plaintext)
//!           + HMAC(secret[32..64], nonce | ciphertext | aad)
//! ```
//!
//! where `transcript` is `"mailcycle/v1/seal-to-public" | shared |
//! ephemeral_public | recipient_public`. Binding both public keys is what
//! stops a box sealed to one address being replayed as one sealed to another.
//! The raw curve output is never used as a key: it is a point, not uniform
//! bytes, which is what the HMAC step fixes.
//!
//! # What that is and is not
//!
//! It is NOT forward secrecy. The recipient's key is
//! `subkey(vault_key, "inbox-sealing/...")`: deterministic, permanent, and
//! re-derivable from the recovery phrase for as long as that phrase exists.
//! Anyone who ever obtains the phrase can decrypt every message ever sealed to
//! that address, including ones captured years earlier. There is no ratchet
//! and no key rotation.
//!
//! It also does NOT authenticate the sender. Anyone holding the address's
//! public key can seal to it, which is what an email address is. A successful
//! open says the ciphertext is intact, never who wrote it.

use crate::encoding::be64;
use crate::error::{Error, Result};

use super::primitives::{
    chacha20, constant_time_equal, hmac_sha256, is_all_zero, public_key_from, shared_secret, KEY_BYTES,
    NONCE_BYTES,
};

const DOMAIN: &[u8] = b"mailcycle/v1/seal-to-public";
const ENC: &[u8] = b"/enc";
const MAC: &[u8] = b"/mac";

/// A sealed box in raw bytes. Callers choose how to encode it.
pub struct RawSealedBox {
    pub ephemeral_public_key: Vec<u8>,
    pub nonce: Vec<u8>,
    pub ciphertext: Vec<u8>,
    pub tag: Vec<u8>,
}

fn derive_secret(shared: &[u8], ephemeral_public: &[u8], recipient_public: &[u8]) -> [u8; 64] {
    let mut transcript = Vec::with_capacity(DOMAIN.len() + 96);
    transcript.extend_from_slice(DOMAIN);
    transcript.extend_from_slice(shared);
    transcript.extend_from_slice(ephemeral_public);
    transcript.extend_from_slice(recipient_public);

    let mut enc_input = transcript.clone();
    enc_input.extend_from_slice(ENC);
    let mut mac_input = transcript;
    mac_input.extend_from_slice(MAC);

    let mut secret = [0u8; 64];
    secret[..32].copy_from_slice(&hmac_sha256(shared, &enc_input));
    secret[32..].copy_from_slice(&hmac_sha256(shared, &mac_input));
    secret
}

fn mac_input(nonce: &[u8], ciphertext: &[u8], aad: &[u8], version: u8) -> Vec<u8> {
    let mut out = Vec::with_capacity(nonce.len() + ciphertext.len() + aad.len() + 8);
    out.extend_from_slice(nonce);
    out.extend_from_slice(ciphertext);
    out.extend_from_slice(aad);
    if version != 1 {
        out.extend_from_slice(&be64(aad.len()));
    }
    out
}

/// Seals to a public key.
///
/// Randomness is a parameter so the test vectors can pin it; everywhere else
/// it is the operating system's CSPRNG.
pub fn seal_raw(
    recipient_public_key: &[u8],
    plaintext: &[u8],
    aad: &[u8],
    random: &mut dyn FnMut(usize) -> Vec<u8>,
    version: u8,
) -> Result<RawSealedBox> {
    if recipient_public_key.len() != KEY_BYTES {
        return Err(Error::Unsupported("Recipient public key must be 32 bytes.".into()));
    }

    let ephemeral_private = random(KEY_BYTES);
    if ephemeral_private.len() != KEY_BYTES {
        return Err(Error::Unsupported("Random source returned short.".into()));
    }
    let ephemeral_public = public_key_from(&ephemeral_private);

    let shared = shared_secret(&ephemeral_private, recipient_public_key);
    // All zero means the recipient key had small order and contributed
    // nothing. Refusing here is the difference between encrypting and
    // appearing to.
    if is_all_zero(&shared) {
        return Err(Error::Unsupported("Recipient public key is not usable.".into()));
    }

    let secret = derive_secret(&shared, &ephemeral_public, recipient_public_key);
    let nonce = random(NONCE_BYTES);
    let ciphertext = chacha20(&secret[..32], &nonce, plaintext);
    let tag = hmac_sha256(&secret[32..], &mac_input(&nonce, &ciphertext, aad, version));

    Ok(RawSealedBox { ephemeral_public_key: ephemeral_public.to_vec(), nonce, ciphertext, tag: tag.to_vec() })
}

pub fn open_raw(private_key: &[u8], box_: &RawSealedBox, aad: &[u8], version: u8) -> Result<Vec<u8>> {
    if private_key.len() != KEY_BYTES
        || box_.ephemeral_public_key.len() != KEY_BYTES
        || box_.nonce.len() != NONCE_BYTES
    {
        return Err(Error::Decryption);
    }

    let shared = shared_secret(private_key, &box_.ephemeral_public_key);
    if is_all_zero(&shared) {
        return Err(Error::Decryption);
    }

    let secret = derive_secret(&shared, &box_.ephemeral_public_key, &public_key_from(private_key));
    let expected = hmac_sha256(&secret[32..], &mac_input(&box_.nonce, &box_.ciphertext, aad, version));
    // Verify before decrypting. Never act on unauthenticated ciphertext.
    if !constant_time_equal(&expected, &box_.tag) {
        return Err(Error::Decryption);
    }
    Ok(chacha20(&secret[..32], &box_.nonce, &box_.ciphertext))
}