onionwire/src/ratchet.rs

780 lines
28 KiB
Rust
Raw Normal View History

//! Double Ratchet for chat payloads: one state machine per friend.
//!
//! Wire-independent on purpose. A frame is opaque bytes that ride *inside* the
//! existing Noise transport message; nothing here knows about Arti, sessions or
//! the store. `rat ` follows the protocol's `[a-z]{3} ` typed-prefix convention
//! (`docs/PROTOCOL.md`), so a pre-ratchet client drops it as an unknown prefix
//! instead of rendering ciphertext as a chat line.
//!
//! # Frame
//!
//! ```text
//! b"rat " || 0x01 || header[40] || nonce[12] || ciphertext
//! header = dh_pub[32] || N u32 BE || PN u32 BE
//! ```
//!
//! `dh_pub` is the sender's current ratchet public key, `N` the index of this
//! message in the sender's current sending chain, `PN` how many messages the
//! sender sent in its *previous* sending chain. The header is plaintext inside
//! the ratchet frame and is used verbatim as AEAD associated data, so a tampered
//! `dh_pub`/`N`/`PN` fails closed. The whole frame travels inside the Noise
//! transport (never in clear on the wire), so an observer learns neither message
//! counts nor ratchet keys (`docs/THREAT_MODEL.md`).
//!
//! # KDFs
//!
//! Signal's constructions, unchanged:
//!
//! - `KDF_RK(root, dh_out)` = HKDF-SHA256(salt = root, ikm = dh_out,
//! info = `onionwire-ratchet-v1-kdfrk`) -> 64 bytes = `(root', chain_key)`.
//! - `KDF_CK(ck)` = `(HMAC-SHA256(ck, 0x01), HMAC-SHA256(ck, 0x02))`, first 32
//! bytes each: `(message_key, next_chain_key)`. The message key is the
//! ChaCha20-Poly1305 key; the 12-byte nonce is random per message.
//!
//! # Initiation and convergence
//!
//! Signal's X3DH init assumes exactly one side speaks first. Here every message
//! is its own dialed one-shot Noise session and **either peer may send first**,
//! so two peers can each build a fresh sending chain before either has received
//! anything.
//!
//! The resolution is per-direction chains with role-separated derivation: an
//! epoch is identified by the *unordered pair* of the two current ratchet public
//! keys, and the epoch's two chain keys come from two `KDF_RK` calls on that
//! pair's shared secret. The first call yields the chain for the direction
//! `lo -> hi` (lexicographically lower public key to higher), the second — on
//! the first call's root — the chain for `hi -> lo`, and the second call's root
//! is the epoch's new root. Which side authored which direction is therefore
//! decided by public-key order, never by who spoke first, so both peers derive
//! the same two chains for the same pair and each sends on its own direction.
//!
//! Invariant: *the root and the chain keys are a pure function of the sequence
//! of ratchet-key pairs, and the two peers walk that sequence in the same
//! causal order.* A DH ratchet step happens only when a frame arrives carrying a
//! ratchet public key we have not adopted yet, and the side that performs the
//! step is exactly the side that receives; the peer cannot have rotated a second
//! time without having received ours first, so at most one rotation is ever in
//! flight. Both peers therefore feed `KDF_RK` the same `(root, dh)` pairs in the
//! same order and stay in lockstep — including when both peers send before
//! receiving anything, and including the reply that follows that race.
//!
//! The bootstrap epoch is a special case: both peers may send on it immediately
//! (the peer's initial ratchet public key is exchanged with the session key), so
//! it needs a deterministic tie-break for the *first* rotation. The peer whose
//! ratchet public key is lexicographically lower rotates; the other adopts and
//! only then rotates. From the second epoch on, every rotation is a reply to an
//! adopted key, so no tie-break is needed and the ratchet alternates.
//!
//! # Bounds
//!
//! `MAX_SKIP` per chain jump, `MAX_SKIPPED_KEYS` stored keys with oldest-first
//! eviction, and a skipped key is deleted as soon as it decrypts a frame. Any
//! bound check happens before the state is touched, so a rejected frame leaves
//! the state byte-identical.
use std::collections::{BTreeMap, HashMap};
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use rand::RngCore;
use sha2::Sha256;
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
/// Largest gap between two messages of one chain we will derive keys for.
pub const MAX_SKIP: u32 = 2000;
/// Largest number of skipped message keys kept at once.
pub const MAX_SKIPPED_KEYS: usize = 2000;
/// Typed frame prefix (`[a-z]{3} ` convention).
pub const FRAME_PREFIX: &[u8; 4] = b"rat ";
/// Frame version byte.
pub const FRAME_VERSION: u8 = 1;
/// `dh_pub[32] || N u32 BE || PN u32 BE`.
pub const HEADER_LEN: usize = 40;
/// Offset of the header inside a frame (`rat ` + version).
pub const HEADER_OFFSET: usize = 5;
/// Serialized-state version byte.
pub const STATE_VERSION: u8 = 1;
const NONCE_LEN: usize = 12;
const TAG_LEN: usize = 16;
const MIN_FRAME_LEN: usize = HEADER_OFFSET + HEADER_LEN + NONCE_LEN + TAG_LEN;
const KDF_RK_INFO: &[u8] = b"onionwire-ratchet-v1-kdfrk";
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
/// Frame is not ours: bad prefix, bad version, truncated, or trailing bytes.
BadFrame(&'static str),
/// Header claims a chain jump beyond `MAX_SKIP`. Nothing was advanced.
MaxSkipExceeded,
/// This message key is gone: replayed, already used, or older than the chain.
UsedMessageKey,
/// AEAD rejected the frame: wrong key or a tampered header.
Authentication,
/// Serialized state is not a version-1 ratchet state.
BadState(&'static str),
/// A serialized state with this version cannot be read.
UnsupportedStateVersion(u8),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::BadFrame(why) => write!(f, "bad ratchet frame: {why}"),
Error::MaxSkipExceeded => write!(f, "ratchet chain jump exceeds MAX_SKIP"),
Error::UsedMessageKey => write!(f, "ratchet message key already used"),
Error::Authentication => write!(f, "ratchet frame failed authentication"),
Error::BadState(why) => write!(f, "bad ratchet state: {why}"),
Error::UnsupportedStateVersion(v) => write!(f, "unsupported ratchet state version {v}"),
}
}
}
impl std::error::Error for Error {}
/// `KDF_RK`: HKDF-SHA256(salt = root, ikm = dh_out) -> `(new_root, chain_key)`.
pub fn kdf_rk(root: &[u8; 32], dh_out: &[u8; 32]) -> ([u8; 32], [u8; 32]) {
let hk = Hkdf::<Sha256>::new(Some(root), dh_out);
let mut okm = Zeroizing::new([0u8; 64]);
hk.expand(KDF_RK_INFO, &mut okm[..])
.expect("64 bytes is a valid HKDF-SHA256 output length");
let mut new_root = [0u8; 32];
new_root.copy_from_slice(&okm[..32]);
let mut chain_key = [0u8; 32];
chain_key.copy_from_slice(&okm[32..]);
(new_root, chain_key)
}
/// `KDF_CK`: `(message_key, next_chain_key)` = HMAC-SHA256(ck, 0x01|0x02).
pub fn kdf_ck(chain_key: &[u8; 32]) -> (Zeroizing<[u8; 32]>, [u8; 32]) {
let mut message_key = Zeroizing::new([0u8; 32]);
message_key.copy_from_slice(&hmac_sha256(chain_key, &[0x01]));
let next = hmac_sha256(chain_key, &[0x02]);
(message_key, next)
}
fn hmac_sha256(key: &[u8; 32], data: &[u8]) -> [u8; 32] {
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC accepts any key length");
mac.update(data);
let out = mac.finalize().into_bytes();
let mut buf = [0u8; 32];
buf.copy_from_slice(&out[..32]);
buf
}
fn dh(secret: &[u8; 32], public: &[u8; 32]) -> [u8; 32] {
let secret = StaticSecret::from(*secret);
secret
.diffie_hellman(&X25519Public::from(*public))
.to_bytes()
}
/// One ratchet keypair. The secret wipes on drop; `Debug` never prints it.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct RatchetKeyPair {
secret: Zeroizing<[u8; 32]>,
#[zeroize(skip)]
public: [u8; 32],
}
impl RatchetKeyPair {
pub fn generate() -> Self {
let mut secret = Zeroizing::new([0u8; 32]);
rand::rngs::OsRng.fill_bytes(&mut secret[..]);
Self::from_secret(*secret)
}
pub fn from_secret(secret: [u8; 32]) -> Self {
let secret = Zeroizing::new(secret);
let public = X25519Public::from(&StaticSecret::from(*secret)).to_bytes();
Self { secret, public }
}
pub fn public(&self) -> [u8; 32] {
self.public
}
}
impl std::fmt::Debug for RatchetKeyPair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RatchetKeyPair")
.field("secret", &"<redacted>")
.field("public", &self.public)
.finish()
}
}
/// `(sender ratchet public key, index in that sending chain)`.
type SkippedKeyId = ([u8; 32], u32);
/// A message key tagged with the chain position it belongs to.
type SkippedKey = (SkippedKeyId, [u8; 32]);
/// Skipped message keys, tagged with the sending ratchet key they belong to and
/// the index in that chain. Evicts oldest-first at `MAX_SKIPPED_KEYS`.
#[derive(Default)]
struct SkippedKeys {
map: HashMap<SkippedKeyId, (u64, Zeroizing<[u8; 32]>)>,
order: BTreeMap<u64, SkippedKeyId>,
next_serial: u64,
}
impl SkippedKeys {
fn len(&self) -> usize {
self.map.len()
}
fn peek(&self, pubkey: &[u8; 32], n: u32) -> Option<Zeroizing<[u8; 32]>> {
self.map.get(&(*pubkey, n)).map(|(_, key)| key.clone())
}
fn take(&mut self, pubkey: &[u8; 32], n: u32) -> Option<Zeroizing<[u8; 32]>> {
let (serial, key) = self.map.remove(&(*pubkey, n))?;
debug_assert!(self.order.remove(&serial).is_some());
Some(key)
}
fn insert(&mut self, pubkey: [u8; 32], n: u32, key: [u8; 32]) {
if self.map.contains_key(&(pubkey, n)) {
return;
}
while self.map.len() >= MAX_SKIPPED_KEYS {
let Some((&serial, &old_key)) = self.order.iter().next() else {
break;
};
self.order.remove(&serial);
let _ = self.map.remove(&old_key);
}
let serial = self.next_serial;
self.next_serial += 1;
self.map.insert((pubkey, n), (serial, Zeroizing::new(key)));
self.order.insert(serial, (pubkey, n));
}
/// In insertion order: `(dh_pub, n, message key)`.
fn iter(&self) -> impl Iterator<Item = ([u8; 32], u32, [u8; 32])> + '_ {
self.order.iter().filter_map(|(_, &(pubkey, n))| {
self.map
.get(&(pubkey, n))
.map(|(_, key)| (pubkey, n, **key))
})
}
}
impl Zeroize for SkippedKeys {
fn zeroize(&mut self) {
for (_, key) in self.map.values_mut() {
key.zeroize();
}
self.map.clear();
self.order.clear();
}
}
/// One friend's Double Ratchet state. Chat only.
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct RatchetState {
/// Session root, advanced by every DH ratchet step.
root_key: Zeroizing<[u8; 32]>,
/// Our current ratchet keypair.
local: RatchetKeyPair,
/// The peer's adopted ratchet public key.
#[zeroize(skip)]
remote_pub: [u8; 32],
/// Sending chain `(chain key, index)`.
send_ck: Zeroizing<[u8; 32]>,
#[zeroize(skip)]
send_n: u32,
/// Receiving chain `(chain key, index)`.
recv_ck: Zeroizing<[u8; 32]>,
#[zeroize(skip)]
recv_n: u32,
/// `PN`: messages sent in our previous sending chain.
#[zeroize(skip)]
prev_send_len: u32,
/// Cleared on the peer's first message; picks the bootstrap tie-break.
#[zeroize(skip)]
established: bool,
skipped: SkippedKeys,
}
impl std::fmt::Debug for RatchetState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RatchetState")
.field("local_pub", &self.local.public())
.field("remote_pub", &self.remote_pub)
.field("send_n", &self.send_n)
.field("recv_n", &self.recv_n)
.field("prev_send_len", &self.prev_send_len)
.field("skipped", &self.skipped.len())
.finish_non_exhaustive()
}
}
/// What a decrypt would do, fully validated, before a single field is touched.
struct ChainPlan {
message_key: Zeroizing<[u8; 32]>,
chain_key: Zeroizing<[u8; 32]>,
next_n: u32,
skipped: Vec<SkippedKey>,
}
/// A full DH ratchet step, validated, ready to be applied.
struct StepPlan {
root_key: [u8; 32],
local: RatchetKeyPair,
remote_pub: [u8; 32],
send_ck: [u8; 32],
recv: ChainPlan,
retired: Vec<SkippedKey>,
prev_send_len: u32,
}
impl RatchetState {
/// Bootstrap both chain directions from the session root, our initial
/// ratchet keypair and the peer's initial ratchet public key. Both peers may
/// send immediately; see the module docs for the convergence argument.
pub fn bootstrap(root_key: [u8; 32], local: RatchetKeyPair, remote_pub: [u8; 32]) -> Self {
let shared = dh(&local.secret, &remote_pub);
let (root, ck_lo, ck_hi) = epoch_chains(&root_key, &shared);
let send_ck = chain_for(&local.public, &remote_pub, ck_lo, ck_hi);
let recv_ck = chain_for(&remote_pub, &local.public, ck_lo, ck_hi);
Self {
root_key: Zeroizing::new(root),
local,
remote_pub,
send_ck: Zeroizing::new(send_ck),
send_n: 0,
recv_ck: Zeroizing::new(recv_ck),
recv_n: 0,
prev_send_len: 0,
established: false,
skipped: SkippedKeys::default(),
}
}
/// Our current ratchet public key: what the peer sees in our headers.
pub fn public(&self) -> [u8; 32] {
self.local.public()
}
/// The peer's current ratchet public key.
pub fn remote_pub(&self) -> [u8; 32] {
self.remote_pub
}
/// Index the next message we send will carry.
pub fn send_index(&self) -> u32 {
self.send_n
}
/// Index of the next message we expect on the current receiving chain.
pub fn recv_index(&self) -> u32 {
self.recv_n
}
pub fn skipped_len(&self) -> usize {
self.skipped.len()
}
pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
let (message_key, next_ck) = kdf_ck(&self.send_ck);
let header = header_bytes(&self.local.public(), self.send_n, self.prev_send_len);
let mut nonce = [0u8; NONCE_LEN];
rand::rngs::OsRng.fill_bytes(&mut nonce);
let cipher = ChaCha20Poly1305::new(Key::from_slice(&message_key[..]));
let ciphertext = cipher
.encrypt(
Nonce::from_slice(&nonce),
Payload {
msg: plaintext,
aad: &header,
},
)
.map_err(|_| Error::Authentication)?;
*self.send_ck = next_ck;
self.send_n += 1;
let mut frame = Vec::with_capacity(MIN_FRAME_LEN + ciphertext.len());
frame.extend_from_slice(FRAME_PREFIX);
frame.push(FRAME_VERSION);
frame.extend_from_slice(&header);
frame.extend_from_slice(&nonce);
frame.extend_from_slice(&ciphertext);
Ok(frame)
}
pub fn decrypt(&mut self, frame: &[u8]) -> Result<Vec<u8>> {
let frame = Frame::parse(frame)?;
// A key we skipped earlier: use it, then forget it, so a replay of the
// same frame fails closed.
if let Some(message_key) = self.skipped.peek(&frame.dh_pub, frame.n) {
let plaintext = open(&message_key, &frame)?;
self.skipped.take(&frame.dh_pub, frame.n);
return Ok(plaintext);
}
if frame.dh_pub == self.remote_pub {
let plan = self.plan_chain(&self.recv_ck, self.recv_n, &frame, self.remote_pub)?;
let plaintext = open(&plan.message_key, &frame)?;
self.apply_chain(plan);
if !self.established {
self.established = true;
if self.local.public < self.remote_pub {
self.rotate_sending_chain();
}
}
return Ok(plaintext);
}
// A ratchet key we have not adopted yet: full DH ratchet step.
let plan = self.plan_step(&frame)?;
let plaintext = open(&plan.recv.message_key, &frame)?;
self.apply_step(plan);
Ok(plaintext)
}
/// Validate a receive on a chain we already hold, deriving any keys we
/// skipped over. Pure: nothing is mutated and no chain is advanced.
fn plan_chain(
&self,
chain_key: &[u8; 32],
next_n: u32,
frame: &Frame,
skipped_for: [u8; 32],
) -> Result<ChainPlan> {
if frame.n < next_n {
return Err(Error::UsedMessageKey);
}
let jump = frame.n - next_n;
if jump > MAX_SKIP {
return Err(Error::MaxSkipExceeded);
}
let mut ck = Zeroizing::new(*chain_key);
let mut skipped = Vec::with_capacity(jump as usize);
for n in next_n..frame.n {
let (message_key, next) = kdf_ck(&ck);
skipped.push(((skipped_for, n), *message_key));
*ck = next;
}
let (message_key, next_ck) = kdf_ck(&ck);
Ok(ChainPlan {
message_key,
chain_key: Zeroizing::new(next_ck),
next_n: frame.n + 1,
skipped,
})
}
fn apply_chain(&mut self, plan: ChainPlan) {
for ((pubkey, n), key) in plan.skipped {
self.skipped.insert(pubkey, n, key);
}
*self.recv_ck = *plan.chain_key;
self.recv_n = plan.next_n;
}
/// Validate a full DH ratchet step: retire the old chain (skipping up to
/// `PN`), derive the new receiving chain, then rotate our sending keypair
/// and derive the new sending chain. Pure up to the returned plan.
fn plan_step(&self, frame: &Frame) -> Result<StepPlan> {
// Retire the old receiving chain: the peer tells us with `PN` how many
// messages it sent there, so we can still read stragglers.
if frame.pn < self.recv_n {
return Err(Error::UsedMessageKey);
}
let jump = frame.pn - self.recv_n;
if jump > MAX_SKIP {
return Err(Error::MaxSkipExceeded);
}
let mut retired = Vec::with_capacity(jump as usize);
let mut ck = Zeroizing::new(*self.recv_ck);
for n in self.recv_n..frame.pn {
let (message_key, next) = kdf_ck(&ck);
retired.push(((self.remote_pub, n), *message_key));
*ck = next;
}
// (a) receiving half of the step, on the pair we and the peer now share.
let shared = dh(&self.local.secret, &frame.dh_pub);
let (root_a, ck_lo, ck_hi) = epoch_chains(&self.root_key, &shared);
let recv_ck = chain_for(&frame.dh_pub, &self.local.public, ck_lo, ck_hi);
let recv = self.plan_chain(&recv_ck, 0, frame, frame.dh_pub)?;
// (b) sending half: a fresh keypair, so our sending direction ratchets.
let local = RatchetKeyPair::generate();
let shared = dh(&local.secret, &frame.dh_pub);
let (root, ck_lo, ck_hi) = epoch_chains(&root_a, &shared);
let send_ck = chain_for(&local.public, &frame.dh_pub, ck_lo, ck_hi);
Ok(StepPlan {
root_key: root,
local,
remote_pub: frame.dh_pub,
send_ck,
recv,
retired,
prev_send_len: self.send_n,
})
}
fn apply_step(&mut self, plan: StepPlan) {
let StepPlan {
root_key,
local,
remote_pub,
send_ck,
recv,
retired,
prev_send_len,
} = plan;
for ((pubkey, n), key) in retired {
self.skipped.insert(pubkey, n, key);
}
self.root_key = Zeroizing::new(root_key);
self.local = local;
self.remote_pub = remote_pub;
self.send_ck = Zeroizing::new(send_ck);
self.prev_send_len = prev_send_len;
self.send_n = 0;
self.established = true;
self.apply_chain(recv);
}
/// Bootstrap tie-break rotation: rotate only our sending chain; the
/// receiving chain stays on the epoch both peers already share.
fn rotate_sending_chain(&mut self) {
let local = RatchetKeyPair::generate();
let shared = dh(&local.secret, &self.remote_pub);
let (root, ck_lo, ck_hi) = epoch_chains(&self.root_key, &shared);
let send_ck = chain_for(&local.public, &self.remote_pub, ck_lo, ck_hi);
self.root_key = Zeroizing::new(root);
self.send_ck = Zeroizing::new(send_ck);
self.local = local;
self.prev_send_len = self.send_n;
self.send_n = 0;
}
/// Versioned state for the persistence card. The returned bytes contain
/// ratchet secrets — the caller owns wiping them. Layout (`STATE_VERSION` 1):
///
/// ```text
/// 0 version byte 0x01
/// 1..33 root_key
/// 33..65 local ratchet secret
/// 65..97 local ratchet public
/// 97..129 remote ratchet public
/// 129..161 sending chain key
/// 161..165 send_n u32 BE
/// 165..197 receiving chain key
/// 197..201 recv_n u32 BE
/// 201..205 prev_send_len u32 BE
/// 205 established (0 or 1)
/// 206..210 skipped count u32 BE
/// then, in insertion order: dh_pub[32] || n u32 BE || message key[32]
/// ```
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Zeroizing::new(Vec::with_capacity(210));
out.push(STATE_VERSION);
out.extend_from_slice(&self.root_key[..]);
out.extend_from_slice(&self.local.secret[..]);
out.extend_from_slice(&self.local.public);
out.extend_from_slice(&self.remote_pub);
out.extend_from_slice(&self.send_ck[..]);
out.extend_from_slice(&self.send_n.to_be_bytes());
out.extend_from_slice(&self.recv_ck[..]);
out.extend_from_slice(&self.recv_n.to_be_bytes());
out.extend_from_slice(&self.prev_send_len.to_be_bytes());
out.push(u8::from(self.established));
out.extend_from_slice(&(self.skipped.len() as u32).to_be_bytes());
for (pubkey, n, key) in self.skipped.iter() {
out.extend_from_slice(&pubkey);
out.extend_from_slice(&n.to_be_bytes());
out.extend_from_slice(&key);
}
out.to_vec()
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let mut r = Reader::new(bytes);
let version = r.u8()?;
if version != STATE_VERSION {
return Err(Error::UnsupportedStateVersion(version));
}
let root_key = Zeroizing::new(r.array32()?);
let secret = Zeroizing::new(r.array32()?);
let local_pub = r.array32()?;
let remote_pub = r.array32()?;
let send_ck = Zeroizing::new(r.array32()?);
let send_n = r.u32()?;
let recv_ck = Zeroizing::new(r.array32()?);
let recv_n = r.u32()?;
let prev_send_len = r.u32()?;
let established = match r.u8()? {
0 => false,
1 => true,
_ => return Err(Error::BadState("established flag")),
};
let count = r.u32()? as usize;
let mut skipped = SkippedKeys::default();
for _ in 0..count {
let pubkey = r.array32()?;
let n = r.u32()?;
let key = r.array32()?;
skipped.insert(pubkey, n, key);
}
r.end()?;
let local = RatchetKeyPair::from_secret(*secret);
if local.public != local_pub {
return Err(Error::BadState(
"ratchet secret does not match its public key",
));
}
// A blob may not smuggle in more keys than the live cap allows.
if skipped.len() != count {
return Err(Error::BadState("skipped key count"));
}
Ok(Self {
root_key,
local,
remote_pub,
send_ck,
recv_ck,
send_n,
recv_n,
prev_send_len,
established,
skipped,
})
}
}
/// `KDF_RK` twice on one pair: `(root, ck_lo, ck_hi)` where `lo` is the
/// lexicographically lower public key of the pair.
fn epoch_chains(root: &[u8; 32], shared: &[u8; 32]) -> ([u8; 32], [u8; 32], [u8; 32]) {
let (root, ck_lo) = kdf_rk(root, shared);
let (root, ck_hi) = kdf_rk(&root, shared);
(root, ck_lo, ck_hi)
}
fn chain_for(sender: &[u8; 32], receiver: &[u8; 32], ck_lo: [u8; 32], ck_hi: [u8; 32]) -> [u8; 32] {
if sender <= receiver { ck_lo } else { ck_hi }
}
fn header_bytes(dh_pub: &[u8; 32], n: u32, pn: u32) -> [u8; HEADER_LEN] {
let mut header = [0u8; HEADER_LEN];
header[..32].copy_from_slice(dh_pub);
header[32..36].copy_from_slice(&n.to_be_bytes());
header[36..40].copy_from_slice(&pn.to_be_bytes());
header
}
struct Frame<'a> {
header: [u8; HEADER_LEN],
dh_pub: [u8; 32],
n: u32,
pn: u32,
nonce: [u8; NONCE_LEN],
ciphertext: &'a [u8],
}
impl<'a> Frame<'a> {
fn parse(frame: &'a [u8]) -> Result<Self> {
if !frame.starts_with(FRAME_PREFIX) {
return Err(Error::BadFrame("prefix"));
}
// Length first: a frame too short to hold a header, nonce and tag is
// truncated whatever its version byte claims, and indexing anything
// past the prefix on it would be out of bounds.
if frame.len() < MIN_FRAME_LEN {
return Err(Error::BadFrame("truncated"));
}
match frame[FRAME_PREFIX.len()] {
FRAME_VERSION => {}
_ => return Err(Error::BadFrame("version")),
}
let mut header = [0u8; HEADER_LEN];
header.copy_from_slice(&frame[HEADER_OFFSET..HEADER_OFFSET + HEADER_LEN]);
let mut dh_pub = [0u8; 32];
dh_pub.copy_from_slice(&header[..32]);
let n = u32::from_be_bytes(header[32..36].try_into().expect("4 bytes"));
let pn = u32::from_be_bytes(header[36..40].try_into().expect("4 bytes"));
let nonce_at = HEADER_OFFSET + HEADER_LEN;
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&frame[nonce_at..nonce_at + NONCE_LEN]);
Ok(Self {
header,
dh_pub,
n,
pn,
nonce,
ciphertext: &frame[nonce_at + NONCE_LEN..],
})
}
}
/// AEAD-open with the header as associated data.
fn open(message_key: &[u8; 32], frame: &Frame<'_>) -> Result<Vec<u8>> {
let cipher = ChaCha20Poly1305::new(Key::from_slice(message_key));
cipher
.decrypt(
Nonce::from_slice(&frame.nonce),
Payload {
msg: frame.ciphertext,
aad: &frame.header,
},
)
.map_err(|_| Error::Authentication)
}
struct Reader<'a> {
bytes: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self { bytes, at: 0 }
}
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
let end = self
.at
.checked_add(n)
.ok_or(Error::BadState("length overflow"))?;
let slice = self
.bytes
.get(self.at..end)
.ok_or(Error::BadState("truncated"))?;
self.at = end;
Ok(slice)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?[0])
}
fn u32(&mut self) -> Result<u32> {
Ok(u32::from_be_bytes(
self.take(4)?.try_into().expect("4 bytes"),
))
}
fn array32(&mut self) -> Result<[u8; 32]> {
Ok(self.take(32)?.try_into().expect("32 bytes"))
}
fn end(&self) -> Result<()> {
if self.at != self.bytes.len() {
return Err(Error::BadState("trailing bytes"));
}
Ok(())
}
}