// Copyright (c) 2026 The Sojourn contributors // SPDX-License-Identifier: MIT //! Sojourn protocol skeleton. //! //! This is the bare shape of the envelope, not a finished or reviewed design. //! Do not rely on it to protect anyone. //! //! What it shows: //! - Sealed envelopes: nothing on the outside says who sent a message or who it is for. //! A mailbox holds opaque blobs and recipients find theirs by trying to open them. //! - Fixed size buckets: every envelope is padded to one of a few sizes, so length //! says little about content. //! - Hybrid key agreement: X25519 together with ML-KEM-768 (FIPS 203), so recording //! traffic today and breaking X25519 later is not enough to read it. //! - Signed inside the seal: the sender's Ed25519 signature covers the recipient's key //! and the envelope's ephemeral key, so a message can't be re-sealed to someone else. //! //! Not here yet: Tor transport, onion-service mailboxes, ratcheting (forward secrecy //! per message), contact verification, disappearing messages, the mobile apps. use chacha20poly1305::aead::{Aead, KeyInit, Payload}; use chacha20poly1305::{XChaCha20Poly1305, XNonce}; use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use hkdf::Hkdf; use ml_kem::kem::{Decapsulate, Encapsulate, KeyExport}; use ml_kem::{DecapsulationKey, EncapsulationKey, MlKem768, Seed}; use sha2::Sha256; use x25519_dalek::{PublicKey as XPublic, StaticSecret}; use zeroize::{Zeroize, Zeroizing}; pub const VERSION: u8 = 0; const X_LEN: usize = 32; const ED_LEN: usize = 32; const SIG_LEN: usize = 64; const KEM_SEED_LEN: usize = 64; pub const KEM_EK_LEN: usize = 1184; pub const KEM_CT_LEN: usize = 1088; const NONCE_LEN: usize = 24; const TAG_LEN: usize = 16; /// Bytes on the outside of every envelope: version, ephemeral key, KEM ciphertext, nonce, tag. pub const OUTER_OVERHEAD: usize = 1 + X_LEN + KEM_CT_LEN + NONCE_LEN + TAG_LEN; /// Bytes inside the seal before the message: sender key, signature, message length. const INNER_HEADER: usize = ED_LEN + SIG_LEN + 4; /// Every envelope is exactly one of these sizes. pub const BUCKETS: [usize; 4] = [2048, 4096, 16384, 65536]; pub const SECRET_LEN: usize = X_LEN + 32 + KEM_SEED_LEN; pub const PUBLIC_LEN: usize = X_LEN + ED_LEN + KEM_EK_LEN; /// Largest message that fits in the largest bucket. pub const MAX_MESSAGE: usize = BUCKETS[3] - OUTER_OVERHEAD - INNER_HEADER; #[derive(Debug, PartialEq, Eq)] pub enum Error { TooLong, BadPublicKey, BadSecretKey, /// The envelope isn't for this identity, or it was altered, or it's malformed. /// Deliberately one error: a mailbox reader learns nothing from which it was. NotForUs, Random, } fn random() -> Result, Error> { let mut b = Zeroizing::new([0u8; N]); getrandom::getrandom(b.as_mut()).map_err(|_| Error::Random)?; Ok(b) } /// A person's long-term keys. Never leaves their device. pub struct Identity { x: StaticSecret, ed: SigningKey, kem_seed: Zeroizing<[u8; KEM_SEED_LEN]>, } /// What a person shares so others can write to them. #[derive(Clone, PartialEq, Eq, Debug)] pub struct PublicIdentity { pub x: [u8; X_LEN], pub ed: [u8; ED_LEN], pub kem: Vec, } impl Identity { pub fn generate() -> Result { let x = random::<32>()?; let ed = random::<32>()?; let seed = random::()?; Ok(Self { x: StaticSecret::from(*x), ed: SigningKey::from_bytes(&ed), kem_seed: seed }) } pub fn to_bytes(&self) -> Zeroizing> { let mut v = Zeroizing::new(Vec::with_capacity(SECRET_LEN)); v.extend_from_slice(self.x.as_bytes()); v.extend_from_slice(self.ed.as_bytes()); v.extend_from_slice(self.kem_seed.as_ref()); v } pub fn from_bytes(b: &[u8]) -> Result { if b.len() != SECRET_LEN { return Err(Error::BadSecretKey); } let mut x = [0u8; 32]; let mut ed = [0u8; 32]; let mut seed = Zeroizing::new([0u8; KEM_SEED_LEN]); x.copy_from_slice(&b[..32]); ed.copy_from_slice(&b[32..64]); seed.copy_from_slice(&b[64..]); let id = Self { x: StaticSecret::from(x), ed: SigningKey::from_bytes(&ed), kem_seed: seed }; x.zeroize(); ed.zeroize(); Ok(id) } fn kem(&self) -> DecapsulationKey { let seed = Seed::try_from(self.kem_seed.as_ref()).expect("seed length"); DecapsulationKey::::from_seed(seed) } pub fn public(&self) -> PublicIdentity { PublicIdentity { x: XPublic::from(&self.x).to_bytes(), ed: self.ed.verifying_key().to_bytes(), kem: self.kem().encapsulation_key().to_bytes().to_vec(), } } } impl PublicIdentity { pub fn to_bytes(&self) -> Vec { [&self.x[..], &self.ed[..], &self.kem[..]].concat() } pub fn from_bytes(b: &[u8]) -> Result { if b.len() != PUBLIC_LEN { return Err(Error::BadPublicKey); } let mut x = [0u8; 32]; let mut ed = [0u8; 32]; x.copy_from_slice(&b[..32]); ed.copy_from_slice(&b[32..64]); VerifyingKey::from_bytes(&ed).map_err(|_| Error::BadPublicKey)?; let kem = b[64..].to_vec(); kem_ek(&kem)?; Ok(Self { x, ed, kem }) } } fn kem_ek(b: &[u8]) -> Result, Error> { let key = b.try_into().map_err(|_| Error::BadPublicKey)?; EncapsulationKey::::new(&key).map_err(|_| Error::BadPublicKey) } fn bucket_for(message_len: usize) -> Option { BUCKETS.iter().copied().find(|b| *b >= OUTER_OVERHEAD + INNER_HEADER + message_len) } fn derive_key(x_shared: &[u8], kem_shared: &[u8], eph: &[u8], to_x: &[u8]) -> Zeroizing<[u8; 32]> { let ikm = Zeroizing::new([x_shared, kem_shared].concat()); let salt = [eph, to_x].concat(); let hk = Hkdf::::new(Some(&salt), &ikm); let mut key = Zeroizing::new([0u8; 32]); hk.expand(b"sojourn v0 envelope key", key.as_mut()).expect("32 bytes is a valid length"); key } fn signed_bytes(to: &PublicIdentity, eph: &[u8], msg: &[u8]) -> Vec { [b"sojourn v0 signature".as_slice(), &to.x, &to.ed, eph, &(msg.len() as u32).to_be_bytes(), msg].concat() } /// Seal a message from `from` to `to`. The result carries no sender or recipient on the outside. pub fn seal(from: &Identity, to: &PublicIdentity, msg: &[u8]) -> Result, Error> { if msg.len() > MAX_MESSAGE { return Err(Error::TooLong); } let size = bucket_for(msg.len()).ok_or(Error::TooLong)?; let eph_secret = StaticSecret::from(*random::<32>()?); let eph = XPublic::from(&eph_secret).to_bytes(); let x_shared = eph_secret.diffie_hellman(&XPublic::from(to.x)); let (kem_ct, kem_shared) = kem_ek(&to.kem)?.encapsulate(); let key = derive_key(x_shared.as_bytes(), kem_shared.as_ref(), &eph, &to.x); let sig = from.ed.sign(&signed_bytes(to, &eph, msg)); let inner_len = size - OUTER_OVERHEAD; let mut inner = Zeroizing::new(Vec::with_capacity(inner_len)); inner.extend_from_slice(&from.ed.verifying_key().to_bytes()); inner.extend_from_slice(&sig.to_bytes()); inner.extend_from_slice(&(msg.len() as u32).to_be_bytes()); inner.extend_from_slice(msg); inner.resize(inner_len, 0); let nonce = random::()?; let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref()).expect("32-byte key"); let header = [&[VERSION][..], &eph, kem_ct.as_ref()].concat(); let ct = cipher .encrypt(&XNonce::try_from(&nonce[..]).expect("nonce length"), Payload { msg: &inner, aad: &header }) .map_err(|_| Error::Random)?; let mut out = header; out.extend_from_slice(nonce.as_ref()); out.extend_from_slice(&ct); debug_assert_eq!(out.len(), size); Ok(out) } /// A message that opened, with the sender's signing key so the reader can match it to a contact. #[derive(Debug, PartialEq, Eq)] pub struct Opened { pub from_ed: [u8; ED_LEN], pub message: Vec, } /// Try to open an envelope. Anything not for `me`, altered, or malformed gives `NotForUs`. pub fn open(me: &Identity, envelope: &[u8]) -> Result { if !BUCKETS.contains(&envelope.len()) || envelope[0] != VERSION { return Err(Error::NotForUs); } let eph: [u8; 32] = envelope[1..33].try_into().map_err(|_| Error::NotForUs)?; let kem_ct = &envelope[33..33 + KEM_CT_LEN]; let nonce = &envelope[33 + KEM_CT_LEN..33 + KEM_CT_LEN + NONCE_LEN]; let header = &envelope[..33 + KEM_CT_LEN]; let ct = &envelope[33 + KEM_CT_LEN + NONCE_LEN..]; let x_shared = me.x.diffie_hellman(&XPublic::from(eph)); let kem_shared = me.kem().decapsulate_slice(kem_ct).map_err(|_| Error::NotForUs)?; let mine = me.public(); let key = derive_key(x_shared.as_bytes(), kem_shared.as_ref(), &eph, &mine.x); let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref()).expect("32-byte key"); let inner = Zeroizing::new( cipher .decrypt(&XNonce::try_from(nonce).map_err(|_| Error::NotForUs)?, Payload { msg: ct, aad: header }) .map_err(|_| Error::NotForUs)?, ); let from_ed: [u8; 32] = inner[..32].try_into().map_err(|_| Error::NotForUs)?; let sig = Signature::from_bytes(inner[32..96].try_into().map_err(|_| Error::NotForUs)?); let len = u32::from_be_bytes(inner[96..100].try_into().map_err(|_| Error::NotForUs)?) as usize; if 100 + len > inner.len() || inner[100 + len..].iter().any(|b| *b != 0) { return Err(Error::NotForUs); } let message = inner[100..100 + len].to_vec(); let vk = VerifyingKey::from_bytes(&from_ed).map_err(|_| Error::NotForUs)?; vk.verify(&signed_bytes(&mine, &eph, &message), &sig).map_err(|_| Error::NotForUs)?; Ok(Opened { from_ed, message }) } pub fn to_hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } pub fn from_hex(s: &str) -> Option> { let s = s.trim(); if s.len() % 2 != 0 { return None; } (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()).collect() } #[cfg(test)] mod tests { use super::*; #[test] fn round_trip() { let alice = Identity::generate().unwrap(); let bob = Identity::generate().unwrap(); let env = seal(&alice, &bob.public(), b"meet at the harbor").unwrap(); let got = open(&bob, &env).unwrap(); assert_eq!(got.message, b"meet at the harbor"); assert_eq!(got.from_ed, alice.public().ed); } #[test] fn someone_else_cannot_open_it() { let alice = Identity::generate().unwrap(); let bob = Identity::generate().unwrap(); let eve = Identity::generate().unwrap(); let env = seal(&alice, &bob.public(), b"hi").unwrap(); assert_eq!(open(&eve, &env), Err(Error::NotForUs)); } #[test] fn any_flipped_bit_is_rejected() { let alice = Identity::generate().unwrap(); let bob = Identity::generate().unwrap(); let env = seal(&alice, &bob.public(), b"hi").unwrap(); for i in [0, 1, 40, 33 + KEM_CT_LEN, 33 + KEM_CT_LEN + NONCE_LEN + 5, env.len() - 1] { let mut bad = env.clone(); bad[i] ^= 1; assert_eq!(open(&bob, &bad), Err(Error::NotForUs), "byte {i}"); } } #[test] fn length_only_shows_the_bucket() { let alice = Identity::generate().unwrap(); let bob = Identity::generate().unwrap(); let short = seal(&alice, &bob.public(), b"a").unwrap(); let longer = seal(&alice, &bob.public(), &[7u8; 700]).unwrap(); assert_eq!(short.len(), 2048); assert_eq!(longer.len(), 2048); assert_eq!(seal(&alice, &bob.public(), &vec![1u8; 2500]).unwrap().len(), 4096); assert_eq!(seal(&alice, &bob.public(), &vec![1u8; MAX_MESSAGE + 1]), Err(Error::TooLong)); } #[test] fn same_message_twice_looks_different() { let alice = Identity::generate().unwrap(); let bob = Identity::generate().unwrap(); let a = seal(&alice, &bob.public(), b"same").unwrap(); let b = seal(&alice, &bob.public(), b"same").unwrap(); assert_ne!(a, b); } #[test] fn keys_survive_a_save_and_load() { let alice = Identity::generate().unwrap(); let again = Identity::from_bytes(&alice.to_bytes()).unwrap(); assert_eq!(alice.public(), again.public()); let pubkey = PublicIdentity::from_bytes(&alice.public().to_bytes()).unwrap(); assert_eq!(pubkey, alice.public()); assert_eq!(from_hex(&to_hex(&[0, 255, 16])).unwrap(), vec![0, 255, 16]); } }