ratchet: Double Ratchet state machine for chat frames
New wire-independent `src/ratchet.rs` + `tests/ratchet.rs`: KDF_RK/KDF_CK as in the Signal spec, symmetric ratchet, DH ratchet, skipped-key store with the MAX_SKIP / MAX_SKIPPED_KEYS bounds, versioned state serialization and zeroize of every superseded secret. Initiation gate: per-direction chains seeded by ratchet-key ordering (option (a)), so both peers can build a sending chain before either has received, and a single deterministic tie-break (lower ratchet key rotates first) keeps exactly one rotation in flight. Documented under "Initiation and convergence" and covered by both_peers_send_first_converges, which fails on a crossing rotation. Adds hkdf 0.12 + hmac 0.12 (0.13 pulls digest 0.11 and will not build against sha2 0.10) and regenerates crates/onionwire-sdk/Cargo.lock.
This commit is contained in:
parent
3eee27fd09
commit
8b2e834616
6 changed files with 1204 additions and 0 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -2637,6 +2637,8 @@ dependencies = [
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"futures",
|
"futures",
|
||||||
|
"hkdf",
|
||||||
|
"hmac",
|
||||||
"md-5",
|
"md-5",
|
||||||
"qrcode",
|
"qrcode",
|
||||||
"rand 0.8.8",
|
"rand 0.8.8",
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,8 @@ ratatui = { version = "0.30.2", default-features = false, features = ["crossterm
|
||||||
x25519-dalek = { version = "2", features = ["static_secrets"] }
|
x25519-dalek = { version = "2", features = ["static_secrets"] }
|
||||||
snow = "0.10"
|
snow = "0.10"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
hkdf = "0.12"
|
||||||
|
hmac = "0.12"
|
||||||
argon2 = "0.5"
|
argon2 = "0.5"
|
||||||
chacha20poly1305 = "0.10"
|
chacha20poly1305 = "0.10"
|
||||||
sha3 = "0.10"
|
sha3 = "0.10"
|
||||||
|
|
|
||||||
2
crates/onionwire-sdk/Cargo.lock
generated
2
crates/onionwire-sdk/Cargo.lock
generated
|
|
@ -2768,6 +2768,8 @@ dependencies = [
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"futures",
|
"futures",
|
||||||
|
"hkdf",
|
||||||
|
"hmac",
|
||||||
"md-5",
|
"md-5",
|
||||||
"qrcode",
|
"qrcode",
|
||||||
"rand 0.8.8",
|
"rand 0.8.8",
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ pub mod outbox;
|
||||||
pub mod pay;
|
pub mod pay;
|
||||||
pub mod profile;
|
pub mod profile;
|
||||||
pub mod qr;
|
pub mod qr;
|
||||||
|
pub mod ratchet;
|
||||||
pub mod ratelimit;
|
pub mod ratelimit;
|
||||||
pub mod sanitize;
|
pub mod sanitize;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
|
|
|
||||||
777
src/ratchet.rs
Normal file
777
src/ratchet.rs
Normal file
|
|
@ -0,0 +1,777 @@
|
||||||
|
//! 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"));
|
||||||
|
}
|
||||||
|
match frame[FRAME_PREFIX.len()] {
|
||||||
|
FRAME_VERSION => {}
|
||||||
|
_ => return Err(Error::BadFrame("version")),
|
||||||
|
}
|
||||||
|
if frame.len() < MIN_FRAME_LEN {
|
||||||
|
return Err(Error::BadFrame("truncated"));
|
||||||
|
}
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
420
tests/ratchet.rs
Normal file
420
tests/ratchet.rs
Normal file
|
|
@ -0,0 +1,420 @@
|
||||||
|
//! Double Ratchet module tests: KDF vectors, ratchet steps, skipped-key bounds,
|
||||||
|
//! replay/tamper failure, serialization and zeroize.
|
||||||
|
|
||||||
|
use onionwire::ratchet::{
|
||||||
|
Error, FRAME_PREFIX, FRAME_VERSION, HEADER_OFFSET, MAX_SKIP, MAX_SKIPPED_KEYS, RatchetKeyPair,
|
||||||
|
RatchetState, STATE_VERSION, kdf_ck,
|
||||||
|
};
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
|
const ROOT: [u8; 32] = [0x7au8; 32];
|
||||||
|
|
||||||
|
/// Two peers from one bootstrap root. `a` is always the peer whose ratchet key
|
||||||
|
/// sorts lower, so the documented bootstrap tie-break (lower key rotates first)
|
||||||
|
/// is predictable instead of coin-flip dependent.
|
||||||
|
fn peers() -> (RatchetState, RatchetState) {
|
||||||
|
let k1 = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||||
|
let k2 = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||||
|
let (lo, hi) = if k1.public() < k2.public() {
|
||||||
|
(k1, k2)
|
||||||
|
} else {
|
||||||
|
(k2, k1)
|
||||||
|
};
|
||||||
|
let (lo_pub, hi_pub) = (lo.public(), hi.public());
|
||||||
|
assert_ne!(lo_pub, hi_pub, "test keypairs must differ");
|
||||||
|
(
|
||||||
|
RatchetState::bootstrap(ROOT, lo, hi_pub),
|
||||||
|
RatchetState::bootstrap(ROOT, hi, lo_pub),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_at(frame: &[u8]) -> [u8; 40] {
|
||||||
|
frame[HEADER_OFFSET..HEADER_OFFSET + 40]
|
||||||
|
.try_into()
|
||||||
|
.expect("40")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patch(frame: &[u8], offset: usize, value: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = frame.to_vec();
|
||||||
|
let at = HEADER_OFFSET + offset;
|
||||||
|
out[at..at + value.len()].copy_from_slice(value);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failing test first: `KDF_CK(ck) = (HMAC-SHA256(ck, 0x01), HMAC-SHA256(ck, 0x02))`,
|
||||||
|
/// first 32 bytes each, for `ck = 0x00..0x1f`.
|
||||||
|
///
|
||||||
|
/// Independently computed with:
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// python3 -c "
|
||||||
|
/// import hmac,hashlib
|
||||||
|
/// ck=bytes(range(32))
|
||||||
|
/// print(hmac.new(ck,bytes([1]),hashlib.sha256).digest().hex())
|
||||||
|
/// print(hmac.new(ck,bytes([2]),hashlib.sha256).digest().hex())
|
||||||
|
/// "
|
||||||
|
/// ```
|
||||||
|
#[test]
|
||||||
|
fn kdf_ck_matches_an_independently_computed_vector() {
|
||||||
|
let ck: [u8; 32] = std::array::from_fn(|i| i as u8);
|
||||||
|
let (message_key, next_chain_key) = kdf_ck(&ck);
|
||||||
|
|
||||||
|
let expected_message_key = "9b4c8120a4823a95f47cde17a244f4507244ee6e3957d1fab9fa29b44d3829b7";
|
||||||
|
let expected_next_chain_key =
|
||||||
|
"4304c22c84a53755ab08ead8d97a8d429be5efa480682d7ad1da27f73e1fbe1d";
|
||||||
|
|
||||||
|
assert_eq!(hex(&message_key[..]), expected_message_key);
|
||||||
|
assert_eq!(hex(&next_chain_key), expected_next_chain_key);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex(bytes: &[u8]) -> String {
|
||||||
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frames_use_the_typed_prefix_and_version() {
|
||||||
|
let (mut a, _b) = peers();
|
||||||
|
let frame = a.encrypt(b"hi").expect("encrypt");
|
||||||
|
assert_eq!(&frame[..4], FRAME_PREFIX);
|
||||||
|
assert_eq!(&frame[..4], b"rat ");
|
||||||
|
assert_eq!(frame[4], FRAME_VERSION);
|
||||||
|
assert_eq!(header_at(&frame).len(), 40);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The gate of the card: both peers build and use a sending chain before either
|
||||||
|
/// has received anything, then both receive, then keep exchanging.
|
||||||
|
#[test]
|
||||||
|
fn both_peers_send_first_converges() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let (a_pub, b_pub) = (a.public(), b.public());
|
||||||
|
|
||||||
|
let a1 = a.encrypt(b"a-first").expect("a encrypt");
|
||||||
|
let b1 = b.encrypt(b"b-first").expect("b encrypt");
|
||||||
|
|
||||||
|
assert_eq!(b.decrypt(&a1).expect("b decrypt a1"), b"a-first");
|
||||||
|
assert_eq!(a.decrypt(&b1).expect("a decrypt b1"), b"b-first");
|
||||||
|
|
||||||
|
// A further exchange in both directions must still decrypt.
|
||||||
|
let a2 = a.encrypt(b"a-second").expect("a encrypt");
|
||||||
|
let b2 = b.encrypt(b"b-second").expect("b encrypt");
|
||||||
|
assert_eq!(b.decrypt(&a2).expect("b decrypt a2"), b"a-second");
|
||||||
|
assert_eq!(a.decrypt(&b2).expect("a decrypt b2"), b"b-second");
|
||||||
|
|
||||||
|
// And the DH ratchet actually moved on both sides.
|
||||||
|
assert_ne!(a.public(), a_pub, "a never rotated its ratchet key");
|
||||||
|
assert_ne!(b.public(), b_pub, "b never rotated its ratchet key");
|
||||||
|
|
||||||
|
let a3 = a.encrypt(b"a-third").expect("a encrypt");
|
||||||
|
assert_eq!(b.decrypt(&a3).expect("b decrypt a3"), b"a-third");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same race, delivered in the other order: the receiving order must not matter.
|
||||||
|
#[test]
|
||||||
|
fn both_peers_send_first_converges_in_either_receive_order() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let a1 = a.encrypt(b"one").expect("a encrypt");
|
||||||
|
let b1 = b.encrypt(b"two").expect("b encrypt");
|
||||||
|
|
||||||
|
assert_eq!(a.decrypt(&b1).expect("a first"), b"two");
|
||||||
|
assert_eq!(b.decrypt(&a1).expect("b second"), b"one");
|
||||||
|
|
||||||
|
let a2 = a.encrypt(b"three").expect("a encrypt");
|
||||||
|
let b2 = b.encrypt(b"four").expect("b encrypt");
|
||||||
|
assert_eq!(b.decrypt(&a2).expect("b"), b"three");
|
||||||
|
assert_eq!(a.decrypt(&b2).expect("a"), b"four");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A→B, B→A, A→B with the DH ratchet stepping along the way.
|
||||||
|
#[test]
|
||||||
|
fn round_trip_across_two_dh_ratchet_steps() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let (a_pub, b_pub) = (a.public(), b.public());
|
||||||
|
|
||||||
|
let m1 = a.encrypt(b"m1").expect("encrypt");
|
||||||
|
assert_eq!(b.decrypt(&m1).expect("decrypt m1"), b"m1");
|
||||||
|
|
||||||
|
let m2 = b.encrypt(b"m2").expect("encrypt");
|
||||||
|
assert_eq!(a.decrypt(&m2).expect("decrypt m2"), b"m2");
|
||||||
|
|
||||||
|
let m3 = a.encrypt(b"m3").expect("encrypt");
|
||||||
|
assert_eq!(b.decrypt(&m3).expect("decrypt m3"), b"m3");
|
||||||
|
|
||||||
|
// Both directions took at least one DH ratchet step.
|
||||||
|
assert_ne!(a.public(), a_pub, "a's sending ratchet never advanced");
|
||||||
|
assert_ne!(b.public(), b_pub, "b's sending ratchet never advanced");
|
||||||
|
|
||||||
|
let m4 = b.encrypt(b"m4").expect("encrypt");
|
||||||
|
assert_eq!(a.decrypt(&m4).expect("decrypt m4"), b"m4");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_within_one_chain() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let frames: Vec<Vec<u8>> = (0..5)
|
||||||
|
.map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt"))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
assert_eq!(b.decrypt(&frames[4]).expect("4"), b"m4");
|
||||||
|
for i in [2usize, 0, 1, 3] {
|
||||||
|
assert_eq!(
|
||||||
|
b.decrypt(&frames[i]).expect("out of order"),
|
||||||
|
format!("m{i}").as_bytes()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
b.recv_index(),
|
||||||
|
5,
|
||||||
|
"chain index should have consumed all five"
|
||||||
|
);
|
||||||
|
assert_eq!(b.skipped_len(), 0, "every skipped key was used");
|
||||||
|
|
||||||
|
// A fresh message continues the same chain.
|
||||||
|
let next = a.encrypt(b"m5").expect("encrypt");
|
||||||
|
assert_eq!(b.decrypt(&next).expect("m5"), b"m5");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `PN` case: a key skipped in the previous chain survives a DH ratchet step.
|
||||||
|
#[test]
|
||||||
|
fn key_skipped_before_a_ratchet_step_still_decrypts_after_it() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
|
||||||
|
// A sends three; B only gets the last, so 0 and 1 are skipped.
|
||||||
|
let old: Vec<Vec<u8>> = (0..3)
|
||||||
|
.map(|i| a.encrypt(format!("old{i}").as_bytes()).expect("encrypt"))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(b.decrypt(&old[2]).expect("old2"), b"old2");
|
||||||
|
assert_eq!(b.skipped_len(), 2);
|
||||||
|
|
||||||
|
// B replies; A (the lower ratchet key) rotates its sending chain.
|
||||||
|
let reply = b.encrypt(b"reply").expect("encrypt");
|
||||||
|
assert_eq!(a.decrypt(&reply).expect("reply"), b"reply");
|
||||||
|
let b_pub = b.public();
|
||||||
|
|
||||||
|
// Two messages on the new epoch. B's first one is a full DH ratchet step.
|
||||||
|
let new0 = a.encrypt(b"new0").expect("encrypt");
|
||||||
|
let new1 = a.encrypt(b"new1").expect("encrypt");
|
||||||
|
assert_eq!(b.decrypt(&new0).expect("new0"), b"new0");
|
||||||
|
assert_ne!(b.public(), b_pub, "b should have rotated in the step");
|
||||||
|
assert_eq!(b.decrypt(&new1).expect("new1"), b"new1");
|
||||||
|
|
||||||
|
// The old chain's skipped keys are still usable after the step.
|
||||||
|
assert_eq!(b.decrypt(&old[0]).expect("old0"), b"old0");
|
||||||
|
assert_eq!(b.decrypt(&old[1]).expect("old1"), b"old1");
|
||||||
|
assert_eq!(b.skipped_len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn n_beyond_max_skip_is_rejected_and_the_state_is_untouched() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let frame = a.encrypt(b"far").expect("encrypt");
|
||||||
|
|
||||||
|
let too_far = patch(&frame, 32, &(MAX_SKIP + 1).to_be_bytes());
|
||||||
|
let before = b.to_bytes();
|
||||||
|
let err = b
|
||||||
|
.decrypt(&too_far)
|
||||||
|
.expect_err("must reject a >MAX_SKIP jump");
|
||||||
|
assert_eq!(err, Error::MaxSkipExceeded);
|
||||||
|
assert_eq!(before, b.to_bytes(), "state changed on a rejected frame");
|
||||||
|
|
||||||
|
// MAX_SKIP itself is legal: the bound is exclusive of the limit, so the
|
||||||
|
// frame gets as far as the AEAD (wrong key -> Authentication), and the
|
||||||
|
// failed open still leaves the state byte-identical.
|
||||||
|
let at_limit = patch(&frame, 32, &MAX_SKIP.to_be_bytes());
|
||||||
|
let after_limit_check = b.to_bytes();
|
||||||
|
assert_eq!(
|
||||||
|
b.decrypt(&at_limit).expect_err("wrong key"),
|
||||||
|
Error::Authentication
|
||||||
|
);
|
||||||
|
assert_eq!(after_limit_check, b.to_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replay_fails_closed() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let frame = a.encrypt(b"once").expect("encrypt");
|
||||||
|
|
||||||
|
assert_eq!(b.decrypt(&frame).expect("first"), b"once");
|
||||||
|
let err = b.decrypt(&frame).expect_err("replay must fail");
|
||||||
|
assert_eq!(err, Error::UsedMessageKey);
|
||||||
|
|
||||||
|
// And it really did not yield plaintext a second time: the error carries no
|
||||||
|
// payload, and a decrypted-once frame is gone from the skipped store too.
|
||||||
|
assert_eq!(b.skipped_len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn skipped_keys_never_exceed_the_cap_and_evict_oldest_first() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let per_epoch = 1400usize;
|
||||||
|
|
||||||
|
let mut first_epoch: Vec<Vec<u8>> = Vec::new();
|
||||||
|
let mut last_epoch: Vec<Vec<u8>> = Vec::new();
|
||||||
|
|
||||||
|
for epoch in 0..3 {
|
||||||
|
let frames: Vec<Vec<u8>> = (0..per_epoch)
|
||||||
|
.map(|i| {
|
||||||
|
a.encrypt(format!("e{epoch}-{i}").as_bytes())
|
||||||
|
.expect("encrypt")
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
// B only receives the last frame of each chain: the rest are skipped.
|
||||||
|
assert_eq!(
|
||||||
|
b.decrypt(frames.last().expect("frame")).expect("last"),
|
||||||
|
format!("e{epoch}-{}", per_epoch - 1).as_bytes()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
b.skipped_len() <= MAX_SKIPPED_KEYS,
|
||||||
|
"store grew past the cap: {}",
|
||||||
|
b.skipped_len()
|
||||||
|
);
|
||||||
|
if epoch == 0 {
|
||||||
|
first_epoch = frames;
|
||||||
|
} else if epoch == 2 {
|
||||||
|
last_epoch = frames;
|
||||||
|
} else {
|
||||||
|
// A reply moves A to a new sending chain for the next epoch.
|
||||||
|
let reply = b.encrypt(b"reply").expect("encrypt");
|
||||||
|
assert_eq!(a.decrypt(&reply).expect("reply"), b"reply");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
b.skipped_len(),
|
||||||
|
MAX_SKIPPED_KEYS,
|
||||||
|
"store should be full, not under the cap"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The newest chain's early keys are present...
|
||||||
|
assert_eq!(
|
||||||
|
b.decrypt(&last_epoch[0]).expect("newest chain key kept"),
|
||||||
|
b"e2-0"
|
||||||
|
);
|
||||||
|
// ...and the first chain's are the ones that were evicted.
|
||||||
|
assert!(
|
||||||
|
b.decrypt(&first_epoch[0]).is_err(),
|
||||||
|
"oldest skipped key should have been evicted"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_tamper_fails_authentication() {
|
||||||
|
// dh_pub[0], N low byte, PN low byte: each is covered by the AEAD's AAD.
|
||||||
|
for offset in [0usize, 35, 39] {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let frame = a.encrypt(b"secret").expect("encrypt");
|
||||||
|
let mut tampered = frame.clone();
|
||||||
|
tampered[HEADER_OFFSET + offset] ^= 0x01;
|
||||||
|
|
||||||
|
let err = b
|
||||||
|
.decrypt(&tampered)
|
||||||
|
.expect_err("tampered header must not decrypt");
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
err,
|
||||||
|
Error::Authentication | Error::MaxSkipExceeded | Error::UsedMessageKey
|
||||||
|
),
|
||||||
|
"unexpected error for header byte {offset}: {err:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// State was not advanced by the rejected frame: the real one still opens.
|
||||||
|
assert_eq!(b.decrypt(&frame).expect("untampered"), b"secret");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn state_round_trips_and_rejects_garbage() {
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let frames: Vec<Vec<u8>> = (0..3)
|
||||||
|
.map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt"))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(b.decrypt(&frames[2]).expect("m2"), b"m2");
|
||||||
|
assert_eq!(b.skipped_len(), 2);
|
||||||
|
|
||||||
|
let bytes = b.to_bytes();
|
||||||
|
assert_eq!(bytes[0], STATE_VERSION);
|
||||||
|
|
||||||
|
let mut reloaded = RatchetState::from_bytes(&bytes).expect("reload");
|
||||||
|
assert_eq!(reloaded.to_bytes(), bytes, "round trip is not stable");
|
||||||
|
assert_eq!(reloaded.skipped_len(), 2);
|
||||||
|
assert_eq!(reloaded.recv_index(), b.recv_index());
|
||||||
|
assert_eq!(reloaded.public(), b.public());
|
||||||
|
assert_eq!(reloaded.remote_pub(), b.remote_pub());
|
||||||
|
|
||||||
|
// A reloaded state keeps the conversation going, skipped keys included.
|
||||||
|
let next = a.encrypt(b"after reload").expect("encrypt");
|
||||||
|
assert_eq!(reloaded.decrypt(&next).expect("next"), b"after reload");
|
||||||
|
assert_eq!(reloaded.decrypt(&frames[0]).expect("skipped"), b"m0");
|
||||||
|
|
||||||
|
// Truncated, empty, wrong version, trailing bytes.
|
||||||
|
assert!(RatchetState::from_bytes(&[]).is_err());
|
||||||
|
assert!(RatchetState::from_bytes(&bytes[..bytes.len() - 1]).is_err());
|
||||||
|
assert!(RatchetState::from_bytes(&[0u8; 3]).is_err());
|
||||||
|
let mut trailing = bytes.clone();
|
||||||
|
trailing.push(0);
|
||||||
|
assert!(RatchetState::from_bytes(&trailing).is_err());
|
||||||
|
let mut wrong_version = bytes.clone();
|
||||||
|
wrong_version[0] = STATE_VERSION + 1;
|
||||||
|
assert_eq!(
|
||||||
|
RatchetState::from_bytes(&wrong_version).expect_err("wrong version"),
|
||||||
|
Error::UnsupportedStateVersion(STATE_VERSION + 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
// A tampered secret no longer matches its public key.
|
||||||
|
let mut bad_secret = bytes.clone();
|
||||||
|
bad_secret[33] ^= 0xff;
|
||||||
|
assert!(RatchetState::from_bytes(&bad_secret).is_err());
|
||||||
|
|
||||||
|
// An absurd skipped-key count is a truncation error, not a panic or an
|
||||||
|
// allocation of 4 billion entries.
|
||||||
|
let mut huge_count = bytes.clone();
|
||||||
|
huge_count[206..210].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
assert!(RatchetState::from_bytes(&huge_count).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_state_wipes_its_secrets() {
|
||||||
|
assert_zeroize_on_drop::<RatchetState>();
|
||||||
|
assert_zeroize_on_drop::<RatchetKeyPair>();
|
||||||
|
|
||||||
|
let (mut a, mut b) = peers();
|
||||||
|
let frames: Vec<Vec<u8>> = (0..3)
|
||||||
|
.map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt"))
|
||||||
|
.collect();
|
||||||
|
let _ = b.decrypt(&frames[2]).expect("m2");
|
||||||
|
|
||||||
|
let before = b.to_bytes();
|
||||||
|
assert!(
|
||||||
|
before[1..33].iter().any(|byte| *byte != 0),
|
||||||
|
"root key should be live before zeroize"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
before[33..65].iter().any(|byte| *byte != 0),
|
||||||
|
"ratchet secret should be live before zeroize"
|
||||||
|
);
|
||||||
|
assert!(before[206..210] != 0u32.to_be_bytes(), "no skipped keys");
|
||||||
|
|
||||||
|
b.zeroize();
|
||||||
|
|
||||||
|
let after = b.to_bytes();
|
||||||
|
assert!(
|
||||||
|
after[1..33].iter().all(|byte| *byte == 0),
|
||||||
|
"root key survived zeroize"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
after[33..65].iter().all(|byte| *byte == 0),
|
||||||
|
"ratchet secret survived zeroize"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
after[129..161].iter().all(|byte| *byte == 0)
|
||||||
|
&& after[165..197].iter().all(|byte| *byte == 0),
|
||||||
|
"chain keys survived zeroize"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
after[206..210],
|
||||||
|
0u32.to_be_bytes(),
|
||||||
|
"skipped message keys survived zeroize"
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue