chat: send and receive as ratchet frames through the outbox payload
Chat plaintext is ratchet-encrypted once, before the first delivery attempt,
and the frame is what the outbox stores and retries, so a retried message
re-sends identical bytes instead of advancing the sending chain twice.
- dispatch: Kind::Ratchet for the `rat ` prefix, matched before the unknown
[a-z]{3} prefix rule
- node: encode_chat_frame / ingest_chat_frame (the wire halves of Node::send
and handle_incoming), bootstrap derived from the peers' static prekey DH
because the Noise handshake is frozen and carries no ratchet key
- outbox: nullable outbox.payload + Outbox::send_payload; NULL payload keeps
the previous row-for-row behaviour
- store: additive outbox.payload migration, enqueue_outbox_payload,
OutboxEntry::payload
- add_friend_payload: a changed prekey clears the (prekey-bound) ratchet state
tests/ratchet_wire.rs (5) covers one frame per send, byte-identical retries,
out-of-order delivery, replay, tampering and fresh-friend both directions.
tests/tui_spec.rs and crates/onionwire-sdk/src/lib.rs only gained a
`payload: None` field in their OutboxEntry test fixtures: the card's required
field on a pub struct cannot be added without it.
This commit is contained in:
parent
14fccd5396
commit
69a15fe909
9 changed files with 619 additions and 13 deletions
163
src/node.rs
163
src/node.rs
|
|
@ -7,8 +7,11 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|||
|
||||
use futures::StreamExt;
|
||||
use futures::io::{AsyncRead, AsyncWrite};
|
||||
use hkdf::Hkdf;
|
||||
use sha2::Sha256;
|
||||
use tor_cell::relaycell::msg::Connected;
|
||||
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
||||
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::dispatch::{self, Kind};
|
||||
|
|
@ -20,6 +23,7 @@ use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
|||
use crate::pay;
|
||||
use crate::profile;
|
||||
use crate::qr;
|
||||
use crate::ratchet::{RatchetKeyPair, RatchetState};
|
||||
use crate::ratelimit::TokenBucket;
|
||||
use crate::sanitize;
|
||||
use crate::session::{self, Keys};
|
||||
|
|
@ -387,12 +391,23 @@ impl Node {
|
|||
|
||||
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
let prekey_changed = store
|
||||
.get_friend(&p.pubkey)
|
||||
.map_err(|e| e.to_string())?
|
||||
.map(|f| f.prekey != p.signed_prekey)
|
||||
.unwrap_or(false);
|
||||
store
|
||||
.upsert_friend(&p.pubkey, &p.onion, None)
|
||||
.map_err(|e| e.to_string())?;
|
||||
store
|
||||
.set_friend_prekey(&p.pubkey, &p.signed_prekey)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if prekey_changed {
|
||||
// The bootstrap epoch is derived from the peers' static prekey DH,
|
||||
// so a refreshed invite makes the stored ratchet state unusable on
|
||||
// both sides. Drop it: the next frame rebuilds a fresh state.
|
||||
store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -876,9 +891,18 @@ impl Node {
|
|||
/// when the peer's onion is unreachable — the outbox worker then retries with
|
||||
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
||||
/// frame) still fails immediately and is never retried.
|
||||
///
|
||||
/// Chat travels as a `rat ` frame: the plaintext is ratchet-encrypted once,
|
||||
/// here, before the first attempt, and the frame is what the outbox retries.
|
||||
/// Local history keeps the plaintext (the store is encrypted at rest).
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||
self.ensure_running()?;
|
||||
self.outbox.send(friend_pk, plaintext).await
|
||||
let keys = self.keys()?;
|
||||
let frame = {
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
encode_chat_frame(&store, &keys, friend_pk, plaintext)?
|
||||
};
|
||||
self.outbox.send_payload(friend_pk, plaintext, &frame).await
|
||||
}
|
||||
|
||||
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||||
|
|
@ -1001,6 +1025,17 @@ impl Node {
|
|||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
Kind::Ratchet => {
|
||||
// Chat arrives as a ratchet frame: decrypt, log the plaintext,
|
||||
// drop the frame. A bad frame is logged and dropped — the
|
||||
// ciphertext is never stored and there is no plaintext fallback.
|
||||
let keys = self.keys()?;
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
if let Err(e) = ingest_chat_frame(&store, &keys, &sess.peer_identity, &pt) {
|
||||
eprintln!("rat dropped ({e})");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
|
||||
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
|
||||
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
|
||||
|
|
@ -1175,6 +1210,132 @@ impl Node {
|
|||
}
|
||||
}
|
||||
|
||||
/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]).
|
||||
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
|
||||
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
|
||||
const RATCHET_BOOTSTRAP_KEY_INFO: &[u8] = b"ratchet-key";
|
||||
|
||||
/// Bootstrap a peer's ratchet state from key material both sides already have.
|
||||
///
|
||||
/// The Noise handshake is frozen and carries no payload, so no wire field can
|
||||
/// hand over an initial ratchet public key. Both peers instead derive the
|
||||
/// bootstrap epoch from the X25519 DH of the two signed prekeys — each side
|
||||
/// computes the same secret — and seed each side's initial ratchet keypair with
|
||||
/// that DH plus *its own* identity pubkey. Each peer therefore derives its own
|
||||
/// keypair and the peer's, and the two agree on the epoch without a new wire
|
||||
/// field; fresh entropy enters at the first DH ratchet step. Because the
|
||||
/// derivation is prekey-bound, a peer whose prekey changed gets its stored state
|
||||
/// dropped (`Node::add_friend_payload`).
|
||||
fn bootstrap_ratchet(
|
||||
keys: &Keys,
|
||||
peer_pk: &[u8],
|
||||
peer_prekey: &[u8],
|
||||
) -> Result<RatchetState, String> {
|
||||
let peer_pk: [u8; 32] = peer_pk
|
||||
.try_into()
|
||||
.map_err(|_| "peer pubkey is not 32 bytes".to_string())?;
|
||||
let peer_prekey: [u8; 32] = peer_prekey
|
||||
.try_into()
|
||||
.map_err(|_| "peer prekey is not 32 bytes".to_string())?;
|
||||
let shared =
|
||||
StaticSecret::from(keys.prekey_sk).diffie_hellman(&X25519Public::from(peer_prekey));
|
||||
let hk = Hkdf::<Sha256>::new(Some(RATCHET_BOOTSTRAP_SALT), shared.as_bytes());
|
||||
|
||||
let mut root_key = [0u8; 32];
|
||||
hk.expand(RATCHET_BOOTSTRAP_ROOT_INFO, &mut root_key)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let local = RatchetKeyPair::from_secret(ratchet_seed(&hk, &keys.identity_pk)?);
|
||||
let remote = ratchet_seed(&hk, &peer_pk)?;
|
||||
let remote_pub = X25519Public::from(&StaticSecret::from(remote)).to_bytes();
|
||||
Ok(RatchetState::bootstrap(root_key, local, remote_pub))
|
||||
}
|
||||
|
||||
/// `HKDF(info = "ratchet-key" || pubkey)` — the initial ratchet secret both
|
||||
/// peers compute for the peer with that identity pubkey.
|
||||
fn ratchet_seed(hk: &Hkdf<Sha256>, pubkey: &[u8; 32]) -> Result<[u8; 32], String> {
|
||||
let mut info = Vec::with_capacity(RATCHET_BOOTSTRAP_KEY_INFO.len() + 32);
|
||||
info.extend_from_slice(RATCHET_BOOTSTRAP_KEY_INFO);
|
||||
info.extend_from_slice(pubkey);
|
||||
let mut seed = Zeroizing::new([0u8; 32]);
|
||||
hk.expand(&info, &mut seed[..]).map_err(|e| e.to_string())?;
|
||||
Ok(*seed)
|
||||
}
|
||||
|
||||
/// The peer's ratchet state: the persisted blob when there is one, a freshly
|
||||
/// bootstrapped state otherwise.
|
||||
///
|
||||
/// The blob is opaque to the store; `RatchetState::to_bytes`/`from_bytes` own
|
||||
/// the format. Nothing is written here — the caller persists once, after a
|
||||
/// successful encrypt/decrypt, so a rejected frame cannot leave a half-created
|
||||
/// session behind.
|
||||
fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result<RatchetState, String> {
|
||||
if let Some(blob) = store.load_ratchet(friend_pk).map_err(|e| e.to_string())? {
|
||||
return RatchetState::from_bytes(&blob).map_err(|e| format!("ratchet state: {e}"));
|
||||
}
|
||||
let f = store
|
||||
.get_friend(friend_pk)
|
||||
.map_err(|e| e.to_string())?
|
||||
.ok_or_else(|| "unknown friend".to_string())?;
|
||||
if f.prekey.len() != 32 {
|
||||
return Err("friend missing prekey".into());
|
||||
}
|
||||
bootstrap_ratchet(keys, friend_pk, &f.prekey)
|
||||
}
|
||||
|
||||
/// Encode one chat send as a `rat ` frame, then persist the advanced state.
|
||||
///
|
||||
/// Exactly one frame per call, and the caller passes those bytes to
|
||||
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
||||
/// advancing the sending chain a second time.
|
||||
///
|
||||
/// Public because it is the wire half of `Node::send`: `tests/ratchet_wire.rs`
|
||||
/// drives the real path without Tor. Callers hold the store lock across
|
||||
/// load → encrypt → save.
|
||||
pub fn encode_chat_frame(
|
||||
store: &Store,
|
||||
keys: &Keys,
|
||||
friend_pk: &[u8],
|
||||
plaintext: &[u8],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut state = ratchet_for(store, keys, friend_pk)?;
|
||||
let frame = state.encrypt(plaintext).map_err(|e| e.to_string())?;
|
||||
let blob = Zeroizing::new(state.to_bytes());
|
||||
store
|
||||
.save_ratchet(friend_pk, &blob)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
/// Decrypt one inbound `rat ` frame and append it to the chat log as an
|
||||
/// incoming line, then persist the advanced state.
|
||||
///
|
||||
/// Returns the logged plaintext, or `Err` for anything that did not
|
||||
/// authenticate — a bad frame writes no chat row and leaves the stored state
|
||||
/// untouched, because `RatchetState` validates fully before it mutates. The
|
||||
/// ciphertext is never stored and there is no plaintext fallback.
|
||||
///
|
||||
/// Public for the same reason as [`encode_chat_frame`]. Callers hold the store
|
||||
/// lock across load → decrypt → append → save, which is what makes the
|
||||
/// read-modify-write atomic against a second inbound session on the same peer.
|
||||
pub fn ingest_chat_frame(
|
||||
store: &Store,
|
||||
keys: &Keys,
|
||||
peer_pk: &[u8],
|
||||
frame: &[u8],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut state = ratchet_for(store, keys, peer_pk)?;
|
||||
let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?;
|
||||
let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec());
|
||||
store
|
||||
.append_message(peer_pk, "in", &line[..])
|
||||
.map_err(|e| e.to_string())?;
|
||||
let blob = Zeroizing::new(state.to_bytes());
|
||||
store
|
||||
.save_ratchet(peer_pk, &blob)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(line.to_vec())
|
||||
}
|
||||
|
||||
fn spawn_rend(
|
||||
node: Arc<Node>,
|
||||
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
||||
|
|
|
|||
Loading…
Reference in a new issue