transport: ML-KEM-768 hybrid prelude and onionwire:v2 invites
All checks were successful
ci / test (pull_request) Successful in 18m32s
android-ci / android (pull_request) Successful in 20m14s
ci / sdk (pull_request) Successful in 3m11s

Adds an ML-KEM-768 install key beside the ed25519 identity and x25519
prekey. A friend added from a v2 invite always gets a version-2 PQ
prelude before Noise msg 1, and both sides bind (ct, ss_kem) into the
Noise prologue (onionwire-v2 \0 ct \0 ss_kem). The row decides: a
kem_pk friend without a prelude is rejected with 'prelude required',
a prelude for a classical row with 'unexpected prelude'.

Invites are now onionwire:v2 with kem=<base64url pk>; decode still
accepts v1 (no kem) and yields a classical friend. F8 rotates the
KEM key with the prekey and hard-cuts stored ratchet state. The TUI
labels a legacy friend 'classical'.

Docs: PROTOCOL (keys, framing, prologues, no-downgrade, invite v2),
THREAT_MODEL (what PQ transport does and does not buy; epoch 0 stays
classical), README (invite size, F8, legacy caveat). SDK exposes pq on
InviteInfo/FriendInfo and gains a v2 decode round-trip test.
This commit is contained in:
agent 2026-10-20 11:15:46 -04:00
commit c741b660e4
No known key found for this signature in database
26 changed files with 1637 additions and 177 deletions

View file

@ -1,6 +1,9 @@
use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
pub const VERSION: u8 = 1;
/// PQ handshake prelude. Body is `uint16 ct_len` (big-endian) followed by
/// exactly `ct_len` bytes. Only the opening frame of a session may use it.
pub const VERSION_PRELUDE: u8 = 2;
pub const MAX_FRAME: usize = 65535;
pub type Result<T> = std::result::Result<T, Error>;
@ -53,11 +56,65 @@ pub async fn write_frame<W: AsyncWrite + Unpin>(w: &mut W, body: &[u8]) -> Resul
}
pub async fn read_frame<R: AsyncRead + Unpin>(r: &mut R) -> Result<Vec<u8>> {
let (version, body) = read_versioned(r).await?;
if version != VERSION {
return Err(Error("bad version".into()));
}
Ok(body)
}
/// First frame of a handshake. Version 1 is Noise msg 1 (classical). Version 2
/// is the PQ prelude; the ciphertext is exactly `ct_len` bytes and must be the
/// ML-KEM-768 ciphertext length.
pub enum Opening {
Classical(Vec<u8>),
Prelude(Vec<u8>),
}
pub async fn read_opening<R: AsyncRead + Unpin>(r: &mut R) -> Result<Opening> {
let (version, body) = read_versioned(r).await?;
match version {
VERSION => Ok(Opening::Classical(body)),
VERSION_PRELUDE => Ok(Opening::Prelude(parse_prelude(&body)?)),
_ => Err(Error("bad version".into())),
}
}
pub async fn write_prelude<W: AsyncWrite + Unpin>(w: &mut W, ct: &[u8]) -> Result<()> {
if ct.len() > u16::MAX as usize {
return Err(Error("frame too large".into()));
}
let mut body = Vec::with_capacity(2 + ct.len());
body.extend_from_slice(&(ct.len() as u16).to_be_bytes());
body.extend_from_slice(ct);
let framed = encode_version(VERSION_PRELUDE, &body)?;
w.write_all(&framed)
.await
.map_err(|e| Error(e.to_string()))?;
w.flush().await.map_err(|e| Error(e.to_string()))
}
pub fn parse_prelude(body: &[u8]) -> Result<Vec<u8>> {
if body.len() < 2 {
return Err(Error("short frame".into()));
}
let ct_len = u16::from_be_bytes(body[..2].try_into().expect("2 bytes")) as usize;
if body.len() != 2 + ct_len {
return Err(Error("length mismatch".into()));
}
if ct_len != crate::kem::CT_LEN {
return Err(Error("bad prelude".into()));
}
Ok(body[2..].to_vec())
}
async fn read_versioned<R: AsyncRead + Unpin>(r: &mut R) -> Result<(u8, Vec<u8>)> {
let mut hdr = [0u8; 5];
r.read_exact(&mut hdr)
.await
.map_err(|e| Error(e.to_string()))?;
if hdr[0] != VERSION {
let version = hdr[0];
if version != VERSION && version != VERSION_PRELUDE {
return Err(Error("bad version".into()));
}
let len = u32::from_be_bytes(hdr[1..5].try_into().expect("4 bytes")) as usize;
@ -68,5 +125,16 @@ pub async fn read_frame<R: AsyncRead + Unpin>(r: &mut R) -> Result<Vec<u8>> {
r.read_exact(&mut body)
.await
.map_err(|e| Error(e.to_string()))?;
Ok(body)
Ok((version, body))
}
fn encode_version(version: u8, body: &[u8]) -> Result<Vec<u8>> {
if body.len() > MAX_FRAME {
return Err(Error("frame too large".into()));
}
let mut out = Vec::with_capacity(5 + body.len());
out.push(version);
out.extend_from_slice(&(body.len() as u32).to_be_bytes());
out.extend_from_slice(body);
Ok(out)
}

96
src/kem.rs Normal file
View file

@ -0,0 +1,96 @@
//! ML-KEM-768 (FIPS 203) install key.
//!
//! The decapsulation key is stored as the 64-byte seed (`DecapsulationKey::to_seed`),
//! the form the crate prefers. The 1184-byte encapsulation key is what an invite
//! carries. Ciphertext is 1088 bytes; the shared secret is 32.
use ml_kem::kem::{Decapsulate, Encapsulate, Kem};
use ml_kem::{DecapsulationKey768, EncapsulationKey768, KeyExport, MlKem768, Seed};
use zeroize::Zeroizing;
pub const PK_LEN: usize = 1184;
pub const CT_LEN: usize = 1088;
pub const SS_LEN: usize = 32;
pub const SEED_LEN: usize = 64;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for Error {}
/// A freshly generated install key. `seed` wipes on drop.
pub struct Keypair {
pub seed: Zeroizing<[u8; SEED_LEN]>,
pub pk: [u8; PK_LEN],
}
pub fn generate() -> Keypair {
let (dk, ek) = MlKem768::generate_keypair();
let seed_arr = dk.to_seed().expect("generate_keypair yields a seed");
let pk_arr = ek.to_bytes();
let mut seed = Zeroizing::new([0u8; SEED_LEN]);
let mut pk = [0u8; PK_LEN];
seed.copy_from_slice(seed_arr.as_slice());
pk.copy_from_slice(pk_arr.as_slice());
Keypair { seed, pk }
}
/// Canonical encapsulation-key bytes. Rejects a length or a key the crate
/// will not load, so a garbage `kem=` never becomes a friend row.
pub fn encode_pk(pk: &[u8]) -> Result<Vec<u8>> {
let ek = encapsulation_key(pk)?;
Ok(ek.to_bytes().as_slice().to_vec())
}
pub fn decode_pk(bytes: &[u8]) -> Result<Vec<u8>> {
encode_pk(bytes)
}
pub fn encapsulate(pk: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
let ek = encapsulation_key(pk)?;
let (ct, ss) = ek.encapsulate();
Ok((ct.as_slice().to_vec(), ss.as_slice().to_vec()))
}
/// Ciphertext bytes. Length is the only check: ML-KEM decapsulation of a
/// wrong ciphertext does not error (implicit rejection), so a bad ct is
/// caught by the handshake prologue, not here.
pub fn encode_ct(ct: &[u8]) -> Result<Vec<u8>> {
if ct.len() != CT_LEN {
return Err(Error("ct length".into()));
}
Ok(ct.to_vec())
}
pub fn decode_ct(bytes: &[u8]) -> Result<Vec<u8>> {
encode_ct(bytes)
}
pub fn decapsulate(seed: &[u8], ct: &[u8]) -> Result<Vec<u8>> {
if ct.len() != CT_LEN {
return Err(Error("ct length".into()));
}
let seed_arr = Seed::try_from(seed).map_err(|_| Error("seed length".into()))?;
let dk = DecapsulationKey768::from_seed(seed_arr);
let ss = dk
.decapsulate_slice(ct)
.map_err(|_| Error("ct length".into()))?;
Ok(ss.as_slice().to_vec())
}
fn encapsulation_key(pk: &[u8]) -> Result<EncapsulationKey768> {
if pk.len() != PK_LEN {
return Err(Error("pk length".into()));
}
let key = ml_kem::kem::Key::<EncapsulationKey768>::try_from(pk)
.map_err(|_| Error("pk length".into()))?;
EncapsulationKey768::new(&key).map_err(|_| Error("invalid encapsulation key".into()))
}

View file

@ -4,6 +4,7 @@ pub mod dispatch;
pub mod file;
pub mod frame;
pub mod hs;
pub mod kem;
pub mod loc;
pub mod node;
pub mod outbox;

View file

@ -427,7 +427,7 @@ impl Node {
pub fn qr_payload(&self) -> Result<String, String> {
let k = self.keys()?;
qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk).map_err(|e| e.to_string())
qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk, &k.kem_pk).map_err(|e| e.to_string())
}
pub fn write_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
@ -456,6 +456,10 @@ impl Node {
pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
let blob = std::fs::read(path).map_err(|e| e.to_string())?;
let k = crate::backup::open(passphrase, &blob)?;
let (kem_seed, kem_pk) = {
let cur = self.keys()?;
(cur.kem_seed, cur.kem_pk)
};
self.store
.lock()
.map_err(|e| e.to_string())?
@ -466,6 +470,11 @@ impl Node {
identity_pk: k.identity_pk,
prekey_sk: k.prekey_sk,
prekey_pk: k.prekey_pk,
// Backup blob is still the classical identity+prekey bundle. The
// KEM seed stays the one already in this store; friends who pinned
// a different encapsulation key have to re-paste.
kem_seed,
kem_pk,
};
Ok(())
}
@ -477,21 +486,30 @@ 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
let existing = store
.get_friend(&p.pubkey)
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())?;
let prekey_changed = existing
.as_ref()
.map(|f| f.prekey != p.signed_prekey)
.unwrap_or(false);
let kem_changed = existing
.as_ref()
.map(|f| f.kem_pk.as_deref() != p.kem_pk.as_deref())
.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 {
store
.set_friend_kem(&p.pubkey, p.kem_pk.as_deref())
.map_err(|e| e.to_string())?;
if prekey_changed || kem_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.
// and a new KEM key is the same hard cut as F8: the stored ratchet
// state is unusable. Drop it; the next frame rebuilds a fresh state.
store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?;
}
Ok(())
@ -1216,14 +1234,15 @@ impl Node {
)
.map_err(|e| e.to_string())?;
let pt = profile::encode(&prf);
let (onion, prekey) = {
let (onion, prekey, kem) = {
let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
(f.onion, f.prekey)
(f.onion, f.prekey, f.kem_pk)
};
self.try_send(&onion, friend_pk, &prekey, &pt).await
self.try_send(&onion, friend_pk, &prekey, &pt, kem.as_deref())
.await
}
/// Sign an invoice with this node's identity key.
@ -1719,14 +1738,15 @@ impl Node {
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
self.ensure_running()?;
let (onion, prekey) = {
let (onion, prekey, kem) = {
let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
(f.onion, f.prekey)
(f.onion, f.prekey, f.kem_pk)
};
self.try_send(&onion, friend_pk, &prekey, plaintext).await
self.try_send(&onion, friend_pk, &prekey, plaintext, kem.as_deref())
.await
}
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
@ -1801,7 +1821,7 @@ impl Node {
let mut notified = 0;
for f in &friends {
if self
.push_loc(&f.pubkey, &f.onion, &f.prekey, &loc_pt)
.push_loc(&f.pubkey, &f.onion, &f.prekey, f.kem_pk.as_deref(), &loc_pt)
.await
.is_ok()
{
@ -1815,17 +1835,18 @@ impl Node {
})
}
/// Rotate the long-lived signed prekey (F8). Hard cut, like the locator
/// rotate: the prekey is our Noise static and the bootstrap ratchet epoch is
/// Rotate the long-lived signed prekey and the ML-KEM-768 key together (F8).
/// Hard cut, like the locator rotate: the prekey is our Noise static, the
/// KEM key is what peers encapsulate to, and the bootstrap ratchet epoch is
/// derived from the prekey DH, so every stored session is dead the moment
/// this returns and every friend has to F3-paste the new invite. Nothing is
/// pushed to peers — a new prekey only travels inside a signed invite. The
/// identity key (and therefore the fingerprint) does not move; the caller
/// re-encodes the F2 invite around the returned pubkey.
/// pushed to peers — a new prekey or KEM key only travels inside a signed
/// invite. The identity key (and therefore the fingerprint) does not move.
pub fn rotate_prekey(&self) -> Result<[u8; 32], String> {
let mut k = self.keys()?;
let sk = StaticSecret::random_from_rng(OsRng);
let pk = X25519Public::from(&sk).to_bytes();
let kem_kp = crate::kem::generate();
{
let store = self.store.lock().map_err(|e| e.to_string())?;
// `replace_identity_keys` rewrites the prekey columns too; the
@ -1833,12 +1854,17 @@ impl Node {
store
.replace_identity_keys(&k.identity_sk, &k.identity_pk, &sk.to_bytes(), &pk)
.map_err(|e| e.to_string())?;
store
.set_kem_keys(&kem_kp.seed[..], &kem_kp.pk)
.map_err(|e| e.to_string())?;
for f in store.list_friends().map_err(|e| e.to_string())? {
store.clear_ratchet(&f.pubkey).map_err(|e| e.to_string())?;
}
}
k.prekey_sk = sk.to_bytes();
k.prekey_pk = pk;
k.kem_seed = *kem_kp.seed;
k.kem_pk = kem_kp.pk;
*self.keys.lock().map_err(|e| e.to_string())? = k;
Ok(pk)
}
@ -1907,6 +1933,7 @@ impl Node {
friend_pk: &[u8],
onion: &str,
prekey: &[u8],
remote_kem: Option<&[u8]>,
loc_pt: &[u8],
) -> Result<(), String> {
if prekey.len() != 32 {
@ -1915,7 +1942,10 @@ impl Node {
let deadline = Instant::now() + Duration::from_secs(180);
let mut last = None::<String>;
while Instant::now() < deadline {
match self.try_send(onion, friend_pk, prekey, loc_pt).await {
match self
.try_send(onion, friend_pk, prekey, loc_pt, remote_kem)
.await
{
Ok(()) => return Ok(()),
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
Err(e) => last = Some(e),
@ -1931,10 +1961,11 @@ impl Node {
pinned_id: &[u8],
remote_prekey: &[u8],
plaintext: &[u8],
remote_kem: Option<&[u8]>,
) -> Result<(), String> {
self.outbox
.deliverer()
.deliver(onion, pinned_id, remote_prekey, plaintext)
.deliver(onion, pinned_id, remote_prekey, plaintext, remote_kem)
.await
}
@ -1948,7 +1979,10 @@ impl Node {
let Ok(g) = store.lock() else {
return None;
};
g.get_friend_by_prekey(spk).ok().flatten().map(|f| f.pubkey)
g.get_friend_by_prekey(spk).ok().flatten().map(|f| session::PeerAuth {
identity: f.pubkey,
kem_pk: f.kem_pk,
})
})
.await
.map_err(session_err)?;
@ -2577,6 +2611,7 @@ pub(crate) mod tests {
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) })
}
@ -2687,18 +2722,33 @@ pub(crate) mod tests {
node.keys.lock().unwrap().prekey_pk
}
fn node_kem_pk(node: &Node) -> [u8; crate::kem::PK_LEN] {
node.keys.lock().unwrap().kem_pk
}
/// One peer→node dial, end to end: a real Noise IK handshake and one
/// already-encoded frame over an in-memory stream, into `handle_incoming`.
async fn deliver_frame(node: &Node, peer: &Keys, frame: &[u8]) -> Result<(), String> {
async fn deliver_frame(
node: &Node,
peer: &Keys,
frame: &[u8],
remote_kem: Option<&[u8]>,
) -> Result<(), String> {
let node_pk = node.identity_pk();
let node_prekey = node_prekey(node);
let (client_side, server_side) = tokio::io::duplex(64 * 1024);
let send = async {
let mut stream = Duplex(client_side);
let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey)
.await
.map_err(|e| e.into_message())?;
let mut sess = session::handshake_initiator(
&mut stream,
peer,
&node_pk,
&node_prekey,
remote_kem,
)
.await
.map_err(|e| e.into_message())?;
let ct = sess.encrypt(frame).map_err(|e| e.into_message())?;
frame::write_frame(&mut stream, &ct)
.await
@ -2709,8 +2759,13 @@ pub(crate) mod tests {
node.handle_incoming(&mut stream).await
};
let (sent, received) = futures::join!(send, receive);
sent?;
received
// The responder's error is the diagnostic one (e.g. a downgrade
// rejection); the initiator only sees the stream drop.
match (sent, received) {
(_, Err(e)) => Err(e),
(Err(e), Ok(())) => Err(e),
(Ok(()), Ok(())) => Ok(()),
}
}
fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> {
@ -2792,7 +2847,9 @@ pub(crate) mod tests {
let frame =
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode");
deliver_frame(&node, &peer, &frame).await.expect("receive");
deliver_frame(&node, &peer, &frame, None)
.await
.expect("receive");
assert_eq!(
chat_lines(&node, &peer),
@ -2801,6 +2858,74 @@ pub(crate) mod tests {
);
}
#[tokio::test]
async fn pq_prelude_session_round_trips_a_real_rat_frame() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
let peer = Keys::generate();
{
let store = node.store.lock().unwrap();
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
store
.set_friend_kem(&peer.identity_pk, Some(&peer.kem_pk))
.expect("friend kem");
}
let peer_store =
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
{
let nk = node_kem_pk(&node);
befriend(&peer_store, &node.identity_pk(), &node_prekey(&node), "node.onion");
peer_store
.set_friend_kem(&node.identity_pk(), Some(&nk))
.expect("node kem");
}
let frame =
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"pq hello").expect("encode");
let nk = node_kem_pk(&node);
deliver_frame(&node, &peer, &frame, Some(&nk))
.await
.expect("PQ handshake + rat frame");
assert_eq!(
chat_lines(&node, &peer),
vec![("in".to_string(), "pq hello".to_string())],
"a real ratchet frame survived the hybrid prelude"
);
}
#[tokio::test]
async fn a_prelude_less_session_against_a_kem_friend_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
let peer = Keys::generate();
{
let store = node.store.lock().unwrap();
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
store
.set_friend_kem(&peer.identity_pk, Some(&peer.kem_pk))
.expect("friend kem");
}
let peer_store =
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
befriend(&peer_store, &node.identity_pk(), &node_prekey(&node), "node.onion");
let frame =
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"downgrade").expect("encode");
let err = deliver_frame(&node, &peer, &frame, None)
.await
.expect_err("a classical session to a KEM friend must fail");
assert!(
err.contains(session::PRELUDE_REQUIRED),
"expected a hard downgrade rejection, got: {err}"
);
assert!(
chat_lines(&node, &peer).is_empty(),
"no application frame may be accepted after a downgrade"
);
}
#[tokio::test]
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
let dir = tempfile::tempdir().unwrap();
@ -2830,17 +2955,17 @@ pub(crate) mod tests {
.collect();
// Arrival order 2, 0, 1 — the ratchet holds the two it has not seen.
deliver_frame(&node, &peer, &frames[2]).await.unwrap();
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
deliver_frame(&node, &peer, &frames[1]).await.unwrap();
deliver_frame(&node, &peer, &frames[2], None).await.unwrap();
deliver_frame(&node, &peer, &frames[0], None).await.unwrap();
deliver_frame(&node, &peer, &frames[1], None).await.unwrap();
// A replay of an already-consumed frame, and a corrupted one: both are
// dropped inside `handle_incoming` without a chat row and without
// wedging the session.
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
deliver_frame(&node, &peer, &frames[0], None).await.unwrap();
let mut corrupt = frames[1].clone();
let last = corrupt.len() - 1;
corrupt[last] ^= 0x01;
deliver_frame(&node, &peer, &corrupt).await.unwrap();
deliver_frame(&node, &peer, &corrupt, None).await.unwrap();
assert_eq!(
chat_lines(&node, &peer),
@ -2864,6 +2989,7 @@ pub(crate) mod tests {
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
Box::pin(async { Ok(()) })
}
@ -2997,6 +3123,7 @@ pub(crate) mod tests {
let peer = Keys::generate();
let old_identity = node.identity_pk();
let old_prekey = node_prekey(&node);
let old_kem = node_kem_pk(&node);
*node.onion.lock().unwrap() = format!("{}.onion", "a".repeat(56));
{
let store = node.store.lock().unwrap();
@ -3010,6 +3137,11 @@ pub(crate) mod tests {
assert_ne!(new_prekey, old_prekey, "the prekey must actually change");
assert_eq!(node_prekey(&node), new_prekey, "the live keys follow");
assert_ne!(
node_kem_pk(&node),
old_kem,
"F8 rotates the ML-KEM key with the prekey"
);
assert_eq!(
node.identity_pk(),
old_identity,
@ -3022,6 +3154,11 @@ pub(crate) mod tests {
new_prekey.to_vec(),
"the self row carries the new prekey"
);
assert_eq!(
store.self_identity().unwrap().kem_pk,
node_kem_pk(&node).to_vec(),
"the self row carries the rotated KEM key"
);
assert!(
store.load_ratchet(&peer.identity_pk).unwrap().is_none(),
"the bootstrap epoch is prekey-bound, so the stored state is stale"
@ -3030,6 +3167,11 @@ pub(crate) mod tests {
let payload = qr::decode(&node.qr_payload().expect("re-encode the invite"))
.expect("the re-encoded invite decodes");
assert_eq!(payload.signed_prekey, new_prekey.to_vec());
assert_eq!(
payload.kem_pk.as_deref(),
Some(&node_kem_pk(&node)[..]),
"the new invite carries the rotated KEM key"
);
assert_eq!(
payload.pubkey,
old_identity.to_vec(),

View file

@ -21,6 +21,10 @@ use crate::store::Store;
pub use crate::store::{OutboxEntry, OutboxStatus};
/// Where one dial goes: locator, Noise static, and the friend's ML-KEM key
/// (`None` = legacy v1 friend, classical session).
type Target = (String, Vec<u8>, Option<Vec<u8>>);
/// First retry waits this long.
pub const BACKOFF_START_SECS: i64 = 30;
/// Backoff never sleeps longer than this.
@ -50,6 +54,8 @@ const PERMANENT_ERRORS: &[&str] = &[
"fingerprint mismatch",
"bad identity proof",
"unexpected handshake payload",
"prelude required",
"unexpected prelude",
"frame too large",
"bad version",
"length mismatch",
@ -69,6 +75,7 @@ pub trait Deliverer: Send + Sync {
pinned_id: &'a [u8],
prekey: &'a [u8],
plaintext: &'a [u8],
remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>>;
}
@ -92,6 +99,7 @@ impl Deliverer for ArtiDeliverer {
pinned_id: &'a [u8],
prekey: &'a [u8],
plaintext: &'a [u8],
remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async move {
let mut stream = self
@ -100,7 +108,7 @@ impl Deliverer for ArtiDeliverer {
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let mut sess =
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey, remote_kem)
.await
.map_err(|e| e.into_message())?;
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
@ -172,9 +180,12 @@ impl Outbox {
plaintext: &[u8],
payload: Option<&[u8]>,
) -> Result<OutboxStatus, String> {
let (onion, prekey) = self.target(friend_pk)?;
let (onion, prekey, kem) = self.target(friend_pk)?;
let wire = payload.unwrap_or(plaintext);
match self.deliverer.deliver(&onion, friend_pk, &prekey, wire).await {
match self
.deliverer
.deliver(&onion, friend_pk, &prekey, wire, kem.as_deref())
.await {
Ok(()) => {
self.store()?.append_message(friend_pk, "out", plaintext)?;
Ok(OutboxStatus::Sent)
@ -266,7 +277,7 @@ impl Outbox {
let mut out = Vec::with_capacity(rows.len());
for entry in rows {
self.store()?.mark_outbox_sending(entry.id, now)?;
let (onion, prekey) = match self.target(&entry.friend_pk) {
let (onion, prekey, kem) = match self.target(&entry.friend_pk) {
Ok(t) => t,
Err(e) => {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
@ -282,6 +293,7 @@ impl Outbox {
&prekey,
// Chat stores its frame here; everything else sends its body.
entry.payload.as_deref().unwrap_or(&entry.body),
kem.as_deref(),
)
.await;
let status = match result {
@ -311,9 +323,10 @@ impl Outbox {
Ok(out)
}
/// Friend's current locator + Noise static. Missing prekey means the invite
/// was never completed — retrying cannot fix that, so it is fatal.
fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec<u8>), String> {
/// Friend's current locator, Noise static, and KEM encapsulation key.
/// Missing prekey means the invite was never completed — retrying cannot
/// fix that, so it is fatal. `None` kem is a legacy v1 friend.
fn target(&self, friend_pk: &[u8]) -> Result<Target, String> {
let store = self.store()?;
let f = store
.get_friend(friend_pk)
@ -322,7 +335,7 @@ impl Outbox {
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
Ok((f.onion, f.prekey))
Ok((f.onion, f.prekey, f.kem_pk))
}
fn store(&self) -> Result<MutexGuard<'_, Store>, String> {

193
src/qr.rs
View file

@ -1,6 +1,8 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing;
use crate::kem;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
@ -19,19 +21,33 @@ pub struct QrPayload {
pub pubkey: Vec<u8>,
pub onion: String,
pub signed_prekey: Vec<u8>,
/// `None` for a legacy `onionwire:v1` invite (classical friend). `Some`
/// is the 1184-byte ML-KEM-768 encapsulation key from a v2 invite.
pub kem_pk: Option<Vec<u8>>,
}
/// Cap invite text before hex decode. Honest v1 is a few hundred bytes.
/// Cap invite text before decode. A v2 invite is ~1.9 KB; 4096 still holds.
const MAX_INVITE: usize = 4096;
const HEX_K: usize = 64;
const HEX_SPK: usize = 64;
const HEX_SIG: usize = 128;
/// `onionwire:v1:k={pubkey_hex}:o={v3onion}:spk={signed_prekey}:sig={sign(v2)}`
pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result<String> {
/// Encode a v2 invite. v1 is decode-only.
///
/// `kem=` is base64url, unpadded, of the 1184-byte encapsulation key.
/// Signature domain: `onionwire-invite-v2 || 0x00 || k || 0x00 || o || 0x00 || spk || 0x00 || kem`.
pub fn encode(
identity_sk: &[u8],
onion: &str,
signed_prekey: &[u8],
kem_pk: &[u8],
) -> Result<String> {
if signed_prekey.len() != 32 {
return Err(Error("spk must be 32 bytes".into()));
}
if kem_pk.len() != kem::PK_LEN {
return Err(Error("kem must be 1184 bytes".into()));
}
if !is_v3_onion(onion) {
return Err(Error("o must be a v3 onion".into()));
}
@ -42,16 +58,19 @@ pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result<S
let sk = SigningKey::from_bytes(&sk_bytes);
let k = to_hex(&sk.verifying_key().to_bytes());
let spk = to_hex(signed_prekey);
let msg = sign_msg_v2(&k, onion, &spk);
let kem_ascii = b64url_encode(kem_pk);
let msg = sign_msg_invite_v2(&k, onion, &spk, &kem_ascii);
let sig = to_hex(&sk.sign(&msg).to_bytes());
Ok(format!("onionwire:v1:k={k}:o={onion}:spk={spk}:sig={sig}"))
Ok(format!(
"onionwire:v2:k={k}:o={onion}:spk={spk}:kem={kem_ascii}:sig={sig}"
))
}
pub fn decode(raw: &str) -> Result<QrPayload> {
if raw.len() > MAX_INVITE {
return Err(Error("invite too long".into()));
}
let (k, onion, spk, sig) = parse_fields(raw)?;
let (version, k, onion, spk, kem_ascii, sig) = parse_fields(raw)?;
if !is_hex_len(&k, HEX_K) {
return Err(Error("k must be 32 bytes".into()));
}
@ -77,19 +96,46 @@ pub fn decode(raw: &str) -> Result<QrPayload> {
.map_err(|_| Error("sig must be 64 bytes".into()))?;
let vk = VerifyingKey::from_bytes(&pk_arr).map_err(|e| Error(e.to_string()))?;
let signature = Signature::from_bytes(&sig_arr);
let ok_v2 = vk
.verify(&sign_msg_v2(&k, &onion, &spk), &signature)
.is_ok();
let ok_v1 = vk
.verify(&sign_msg_v1(&k, &onion, &spk), &signature)
.is_ok();
if !ok_v2 && !ok_v1 {
return Err(Error("bad signature".into()));
}
let kem_pk = match version {
1 => {
if kem_ascii.is_some() {
return Err(Error("unknown field".into()));
}
let ok_tagged = vk
.verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature)
.is_ok();
let ok_legacy = vk
.verify(&sign_msg_v1_concat(&k, &onion, &spk), &signature)
.is_ok();
if !ok_tagged && !ok_legacy {
return Err(Error("bad signature".into()));
}
None
}
2 => {
let kem_ascii = kem_ascii.ok_or_else(|| Error("missing kem".into()))?;
if vk
.verify(
&sign_msg_invite_v2(&k, &onion, &spk, &kem_ascii),
&signature,
)
.is_err()
{
return Err(Error("bad signature".into()));
}
let pk = b64url_decode(&kem_ascii)?;
// Reject a kem= that is not a real encapsulation key. A stripped
// field never gets here: the signature above already covers it.
kem::decode_pk(&pk).map_err(|e| Error(e.to_string()))?;
Some(pk)
}
_ => return Err(Error("not an onionwire invite".into())),
};
Ok(QrPayload {
pubkey,
onion,
signed_prekey,
kem_pk,
})
}
@ -104,7 +150,23 @@ fn is_hex_len(s: &str, n: usize) -> bool {
s.len() == n && s.bytes().all(|c| c.is_ascii_hexdigit())
}
fn sign_msg_v2(k: &str, onion: &str, spk: &str) -> Vec<u8> {
fn sign_msg_invite_v2(k: &str, onion: &str, spk: &str, kem_ascii: &str) -> Vec<u8> {
let mut msg = Vec::with_capacity(19 + 4 + k.len() + onion.len() + spk.len() + kem_ascii.len());
msg.extend_from_slice(b"onionwire-invite-v2");
msg.push(0);
msg.extend_from_slice(k.as_bytes());
msg.push(0);
msg.extend_from_slice(onion.as_bytes());
msg.push(0);
msg.extend_from_slice(spk.as_bytes());
msg.push(0);
msg.extend_from_slice(kem_ascii.as_bytes());
msg
}
/// Tagged v1 domain. Named for the historical `sign_msg_v2` (the tag is
/// `onionwire-invite-v1`); encode no longer emits it.
fn sign_msg_v1_tagged(k: &str, onion: &str, spk: &str) -> Vec<u8> {
let mut msg = Vec::with_capacity(19 + 3 + k.len() + onion.len() + spk.len());
msg.extend_from_slice(b"onionwire-invite-v1");
msg.push(0);
@ -116,7 +178,7 @@ fn sign_msg_v2(k: &str, onion: &str, spk: &str) -> Vec<u8> {
msg
}
fn sign_msg_v1(k: &str, onion: &str, spk: &str) -> Vec<u8> {
fn sign_msg_v1_concat(k: &str, onion: &str, spk: &str) -> Vec<u8> {
let mut msg = Vec::with_capacity(k.len() + onion.len() + spk.len());
msg.extend_from_slice(k.as_bytes());
msg.extend_from_slice(onion.as_bytes());
@ -124,13 +186,18 @@ fn sign_msg_v1(k: &str, onion: &str, spk: &str) -> Vec<u8> {
msg
}
fn parse_fields(raw: &str) -> Result<(String, String, String, String)> {
let rest = raw
.strip_prefix("onionwire:v1:")
.ok_or_else(|| Error("not onionwire:v1".into()))?;
fn parse_fields(raw: &str) -> Result<(u8, String, String, String, Option<String>, String)> {
let (version, rest) = if let Some(rest) = raw.strip_prefix("onionwire:v2:") {
(2u8, rest)
} else if let Some(rest) = raw.strip_prefix("onionwire:v1:") {
(1u8, rest)
} else {
return Err(Error("not an onionwire invite".into()));
};
let mut k = None;
let mut o = None;
let mut spk = None;
let mut kem_f = None;
let mut sig = None;
for part in rest.split(':') {
if let Some(v) = part.strip_prefix("k=") {
@ -148,6 +215,14 @@ fn parse_fields(raw: &str) -> Result<(String, String, String, String)> {
return Err(Error("duplicate spk".into()));
}
spk = Some(v.to_string());
} else if let Some(v) = part.strip_prefix("kem=") {
if version != 2 {
return Err(Error("unknown field".into()));
}
if kem_f.is_some() {
return Err(Error("duplicate kem".into()));
}
kem_f = Some(v.to_string());
} else if let Some(v) = part.strip_prefix("sig=") {
if sig.is_some() {
return Err(Error("duplicate sig".into()));
@ -158,9 +233,11 @@ fn parse_fields(raw: &str) -> Result<(String, String, String, String)> {
}
}
Ok((
version,
k.ok_or_else(|| Error("missing k".into()))?,
o.ok_or_else(|| Error("missing o".into()))?,
spk.ok_or_else(|| Error("missing spk".into()))?,
kem_f,
sig.ok_or_else(|| Error("missing sig".into()))?,
))
}
@ -182,6 +259,77 @@ fn from_hex(s: &str) -> Result<Vec<u8>> {
.collect()
}
fn b64url_encode(data: &[u8]) -> String {
const T: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let mut i = 0;
while i + 3 <= data.len() {
let n = ((data[i] as u32) << 16) | ((data[i + 1] as u32) << 8) | data[i + 2] as u32;
out.push(T[((n >> 18) & 63) as usize] as char);
out.push(T[((n >> 12) & 63) as usize] as char);
out.push(T[((n >> 6) & 63) as usize] as char);
out.push(T[(n & 63) as usize] as char);
i += 3;
}
if i < data.len() {
let rem = data.len() - i;
let mut n = (data[i] as u32) << 16;
if rem == 2 {
n |= (data[i + 1] as u32) << 8;
}
out.push(T[((n >> 18) & 63) as usize] as char);
out.push(T[((n >> 12) & 63) as usize] as char);
if rem == 2 {
out.push(T[((n >> 6) & 63) as usize] as char);
}
}
out
}
fn b64url_decode(s: &str) -> Result<Vec<u8>> {
if s.is_empty() || s.len() % 4 == 1 || s.bytes().any(|b| b == b'=') {
return Err(Error("invalid kem".into()));
}
fn val(b: u8) -> Result<u8> {
Ok(match b {
b'A'..=b'Z' => b - b'A',
b'a'..=b'z' => b - b'a' + 26,
b'0'..=b'9' => b - b'0' + 52,
b'-' => 62,
b'_' => 63,
_ => return Err(Error("invalid kem".into())),
})
}
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
let mut i = 0;
while i + 4 <= bytes.len() {
let n = ((val(bytes[i])? as u32) << 18)
| ((val(bytes[i + 1])? as u32) << 12)
| ((val(bytes[i + 2])? as u32) << 6)
| val(bytes[i + 3])? as u32;
out.push((n >> 16) as u8);
out.push((n >> 8) as u8);
out.push(n as u8);
i += 4;
}
let rem = bytes.len() - i;
if rem == 2 {
let n = ((val(bytes[i])? as u32) << 18) | ((val(bytes[i + 1])? as u32) << 12);
out.push((n >> 16) as u8);
} else if rem == 3 {
let n = ((val(bytes[i])? as u32) << 18)
| ((val(bytes[i + 1])? as u32) << 12)
| ((val(bytes[i + 2])? as u32) << 6);
out.push((n >> 16) as u8);
out.push((n >> 8) as u8);
}
if out.len() != kem::PK_LEN {
return Err(Error("kem must be 1184 bytes".into()));
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
@ -196,10 +344,11 @@ mod tests {
let k = to_hex(&sk.verifying_key().to_bytes());
let onion = v3();
let spk = to_hex(&[9u8; 32]);
let sig = to_hex(&sk.sign(&sign_msg_v1(&k, &onion, &spk)).to_bytes());
let sig = to_hex(&sk.sign(&sign_msg_v1_concat(&k, &onion, &spk)).to_bytes());
let raw = format!("onionwire:v1:k={k}:o={onion}:spk={spk}:sig={sig}");
let p = decode(&raw).expect("legacy concat");
assert_eq!(p.onion, onion);
assert_eq!(p.signed_prekey, vec![9u8; 32]);
assert!(p.kem_pk.is_none(), "v1 invite is a classical friend");
}
}

View file

@ -8,8 +8,34 @@ use crate::store::SelfIdentity;
const PATTERN: &str = "Noise_IK_25519_ChaChaPoly_BLAKE2s";
const PROLOGUE: &[u8] = b"onionwire-v1";
/// Returned when a friend row has a KEM key and the session had no prelude.
/// Stable: the outbox treats it as a permanent protocol error.
pub const PRELUDE_REQUIRED: &str = "prelude required";
/// Returned when a prelude arrives for a friend row with no KEM key: the row,
/// not the wire, decides whether a session is hybrid.
pub const UNEXPECTED_PRELUDE: &str = "unexpected prelude";
const MSG_BUF: usize = 65535;
/// Who the responder just authenticated, plus whether that friend row requires
/// a PQ prelude. The rule is the row, not the bytes that arrived.
pub struct PeerAuth {
pub identity: Vec<u8>,
pub kem_pk: Option<Vec<u8>>,
}
/// Hybrid Noise prologue. Exact layout:
/// `onionwire-v2 || 0x00 || ct || 0x00 || ss_kem`
/// (`onionwire-v2` is 12 bytes, `ct` is the ML-KEM-768 ciphertext, `ss_kem` is 32 bytes).
pub fn hybrid_prologue(ct: &[u8], ss: &[u8]) -> Vec<u8> {
let mut p = Vec::with_capacity(12 + 1 + ct.len() + 1 + ss.len());
p.extend_from_slice(b"onionwire-v2");
p.push(0);
p.extend_from_slice(ct);
p.push(0);
p.extend_from_slice(ss);
p
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
@ -72,6 +98,10 @@ pub struct Keys {
pub prekey_sk: [u8; 32],
#[zeroize(skip)]
pub prekey_pk: [u8; 32],
/// 64-byte ML-KEM-768 seed. The decapsulation key.
pub kem_seed: [u8; crate::kem::SEED_LEN],
#[zeroize(skip)]
pub kem_pk: [u8; crate::kem::PK_LEN],
}
impl Keys {
@ -79,11 +109,14 @@ impl Keys {
let signing = SigningKey::generate(&mut OsRng);
let xsk = StaticSecret::random_from_rng(OsRng);
let xpk = X25519Public::from(&xsk);
let kem_kp = crate::kem::generate();
Self {
identity_sk: signing.to_bytes(),
identity_pk: signing.verifying_key().to_bytes(),
prekey_sk: xsk.to_bytes(),
prekey_pk: xpk.to_bytes(),
kem_seed: *kem_kp.seed,
kem_pk: kem_kp.pk,
}
}
@ -93,6 +126,8 @@ impl Keys {
identity_pk: to_32(&me.identity_pk)?,
prekey_sk: to_32(&me.prekey_sk)?,
prekey_pk: to_32(&me.prekey_pk)?,
kem_seed: to_64(&me.kem_sk)?,
kem_pk: to_pk(&me.kem_pk)?,
})
}
}
@ -192,17 +227,30 @@ pub async fn handshake_initiator<S>(
local: &Keys,
pinned_id: &[u8],
remote_prekey: &[u8],
remote_kem_pk: Option<&[u8]>,
) -> Result<Session>
where
S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin,
{
let prologue = if let Some(pk) = remote_kem_pk {
let (ct, ss) = crate::kem::encapsulate(pk).map_err(|e| Error::new(e.to_string()))?;
crate::frame::write_prelude(stream, &ct)
.await
.map_err(|e| Error::new(e.to_string()))?;
let mut ss = ss;
let prologue = hybrid_prologue(&ct, &ss);
ss.zeroize();
prologue
} else {
PROLOGUE.to_vec()
};
let params: snow::params::NoiseParams = PATTERN
.parse()
.map_err(|e: snow::Error| Error::new(e.to_string()))?;
let mut hs = Builder::new(params)
.local_private_key(&local.prekey_sk)?
.remote_public_key(remote_prekey)?
.prologue(PROLOGUE)?
.prologue(&prologue)?
.build_initiator()?;
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
@ -249,20 +297,33 @@ pub async fn handshake_responder<S, F>(
) -> Result<Session>
where
S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin,
F: FnOnce(&[u8]) -> Option<Vec<u8>>,
F: FnOnce(&[u8]) -> Option<PeerAuth>,
{
let opening = crate::frame::read_opening(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;
let (saw_prelude, prologue, msg1) = match opening {
crate::frame::Opening::Prelude(ct) => {
let mut ss = crate::kem::decapsulate(&local.kem_seed[..], &ct)
.map_err(|e| Error::new(e.to_string()))?;
let prologue = hybrid_prologue(&ct, &ss);
ss.zeroize();
let msg1 = crate::frame::read_frame(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;
(true, prologue, msg1)
}
crate::frame::Opening::Classical(body) => (false, PROLOGUE.to_vec(), body),
};
let params: snow::params::NoiseParams = PATTERN
.parse()
.map_err(|e: snow::Error| Error::new(e.to_string()))?;
let mut hs = Builder::new(params)
.local_private_key(&local.prekey_sk)?
.prologue(PROLOGUE)?
.prologue(&prologue)?
.build_responder()?;
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let msg1 = crate::frame::read_frame(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;
let n = hs.read_message(&msg1, &mut buf)?;
if n != 0 {
return Err(Error::new("unexpected handshake payload"));
@ -271,8 +332,18 @@ where
.get_remote_static()
.ok_or_else(|| Error::new("missing remote static"))?
.to_vec();
let expected_id =
lookup_identity(&remote_static).ok_or_else(|| Error::new("unknown prekey"))?;
let peer = lookup_identity(&remote_static).ok_or_else(|| Error::new("unknown prekey"))?;
// Friend row has a KEM key and this session did not open with a prelude.
// Fail before msg 2, the identity proofs, and any application frame.
if peer.kem_pk.is_some() && !saw_prelude {
return Err(Error::new(PRELUDE_REQUIRED));
}
// The other direction of the same rule: a legacy friend row is classical,
// and a prelude cannot upgrade it from the wire.
if peer.kem_pk.is_none() && saw_prelude {
return Err(Error::new(UNEXPECTED_PRELUDE));
}
let expected_id = peer.identity;
let n = hs.write_message(&[], &mut buf)?;
crate::frame::write_frame(stream, &buf[..n])
.await
@ -328,3 +399,11 @@ fn verify_proof(proof: &[u8], expected_pk: &[u8], hash: &[u8]) -> Result<()> {
fn to_32(v: &[u8]) -> Result<[u8; 32]> {
v.try_into().map_err(|_| Error::new("need 32 bytes"))
}
fn to_64(v: &[u8]) -> Result<[u8; crate::kem::SEED_LEN]> {
v.try_into().map_err(|_| Error::new("need 64 bytes"))
}
fn to_pk(v: &[u8]) -> Result<[u8; crate::kem::PK_LEN]> {
v.try_into().map_err(|_| Error::new("need 1184 bytes"))
}

View file

@ -63,6 +63,10 @@ pub struct SelfIdentity {
pub onion: String,
pub prekey_sk: Zeroizing<Vec<u8>>,
pub prekey_pk: Vec<u8>,
/// 64-byte ML-KEM-768 seed. Same sealing as `identity_sk`: raw bytes inside
/// the SQLCipher file, wiped when this value drops.
pub kem_sk: Zeroizing<Vec<u8>>,
pub kem_pk: Vec<u8>,
}
pub struct Friend {
@ -72,6 +76,9 @@ pub struct Friend {
pub onion: String,
pub last_connect_ok: bool,
pub prekey: Vec<u8>,
/// ML-KEM-768 encapsulation key from a v2 invite. `None` is a legacy v1
/// friend: outbound sessions stay classical and the UI must say so.
pub kem_pk: Option<Vec<u8>>,
}
pub struct FriendProfile {
@ -247,7 +254,8 @@ impl Store {
onion_updated_at INTEGER NOT NULL,
added_at INTEGER NOT NULL,
last_connect_ok INTEGER NOT NULL DEFAULT 1,
prekey BLOB NOT NULL DEFAULT x''
prekey BLOB NOT NULL DEFAULT x'',
kem_pk BLOB
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY,
@ -264,6 +272,8 @@ impl Store {
onion_rotated_at INTEGER NOT NULL,
prekey_sk BLOB NOT NULL,
prekey_pk BLOB NOT NULL,
kem_sk BLOB NOT NULL DEFAULT x'',
kem_pk BLOB NOT NULL DEFAULT x'',
hs_nickname TEXT NOT NULL DEFAULT 'ow0'
);
CREATE TABLE IF NOT EXISTS self_profile (
@ -611,6 +621,20 @@ impl Store {
Ok(())
}
/// Replace the install KEM key. F8 calls this with the prekey rotate.
/// Identity columns are untouched, and so is a backup restore that only
/// rewrites the classical keys.
pub fn set_kem_keys(&self, seed: &[u8], pk: &[u8]) -> Result<()> {
if seed.len() != crate::kem::SEED_LEN || pk.len() != crate::kem::PK_LEN {
return Err(Error("kem key length".into()));
}
self.conn.execute(
"UPDATE self SET kem_sk = ?1, kem_pk = ?2 WHERE id = 1",
params![seed, pk],
)?;
Ok(())
}
fn migrate(&self) -> Result<()> {
self.add_column_if_missing(
"friends",
@ -637,6 +661,21 @@ impl Store {
"hs_nickname",
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
)?;
self.add_column_if_missing(
"self",
"kem_sk",
"ALTER TABLE self ADD COLUMN kem_sk BLOB NOT NULL DEFAULT x''",
)?;
self.add_column_if_missing(
"self",
"kem_pk",
"ALTER TABLE self ADD COLUMN kem_pk BLOB NOT NULL DEFAULT x''",
)?;
self.add_column_if_missing(
"friends",
"kem_pk",
"ALTER TABLE friends ADD COLUMN kem_pk BLOB",
)?;
// The wallet file's passphrase (sealed). NULL on an install that has
// never been told one — a wallet created before this column, or a
// remote-mode wallet the user opens themselves.
@ -847,13 +886,32 @@ impl Store {
)?;
}
}
self.ensure_kem()?;
Ok(())
}
/// Fill a missing ML-KEM-768 install key. New installs and upgraded v1
/// stores both land here; an existing 64/1184 pair is left alone.
fn ensure_kem(&self) -> Result<()> {
let missing: i64 = self.conn.query_row(
"SELECT CASE WHEN length(kem_sk) = 64 AND length(kem_pk) = 1184 THEN 0 ELSE 1 END FROM self WHERE id = 1",
[],
|row| row.get(0),
)?;
if missing != 0 {
let kp = crate::kem::generate();
self.conn.execute(
"UPDATE self SET kem_sk = ?1, kem_pk = ?2 WHERE id = 1",
params![&kp.seed[..], kp.pk.as_slice()],
)?;
}
Ok(())
}
pub fn self_identity(&self) -> Result<SelfIdentity> {
self.conn
.query_row(
"SELECT identity_sk, identity_pk, onion, prekey_sk, prekey_pk FROM self WHERE id = 1",
"SELECT identity_sk, identity_pk, onion, prekey_sk, prekey_pk, kem_sk, kem_pk FROM self WHERE id = 1",
[],
|row| {
Ok(SelfIdentity {
@ -862,6 +920,8 @@ impl Store {
onion: row.get(2)?,
prekey_sk: Zeroizing::new(row.get(3)?),
prekey_pk: row.get(4)?,
kem_sk: Zeroizing::new(row.get(5)?),
kem_pk: row.get(6)?,
})
},
)
@ -909,7 +969,7 @@ impl Store {
pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE pubkey = ?1",
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends WHERE pubkey = ?1",
params![pubkey],
friend_from_row,
)
@ -923,7 +983,7 @@ impl Store {
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
params![onion],
friend_from_row,
)
@ -933,7 +993,7 @@ impl Store {
pub fn list_friends(&self) -> Result<Vec<Friend>> {
let mut stmt = self.conn.prepare(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends
ORDER BY COALESCE(petname, fingerprint) COLLATE NOCASE",
)?;
let rows = stmt.query_map([], friend_from_row)?;
@ -1084,10 +1144,27 @@ impl Store {
Ok(())
}
/// `None` stores NULL: a v1 invite, classical sessions from here on.
pub fn set_friend_kem(&self, pubkey: &[u8], kem_pk: Option<&[u8]>) -> Result<()> {
if let Some(pk) = kem_pk
&& pk.len() != crate::kem::PK_LEN
{
return Err(Error("kem pk length".into()));
}
let n = self.conn.execute(
"UPDATE friends SET kem_pk = ?1 WHERE pubkey = ?2",
params![kem_pk, pubkey],
)?;
if n == 0 {
return Err(Error("friend not found".into()));
}
Ok(())
}
pub fn get_friend_by_prekey(&self, prekey: &[u8]) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE prekey = ?1",
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends WHERE prekey = ?1",
params![prekey],
friend_from_row,
)
@ -1560,6 +1637,8 @@ fn profile_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FriendProfile>
}
fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
let kem: Option<Vec<u8>> = row.get(6)?;
let kem_pk = kem.filter(|k| k.len() == crate::kem::PK_LEN);
Ok(Friend {
pubkey: row.get(0)?,
fingerprint: row.get(1)?,
@ -1567,6 +1646,7 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
onion: row.get(3)?,
last_connect_ok: row.get::<_, i64>(4)? != 0,
prekey: row.get(5)?,
kem_pk,
})
}
@ -1877,6 +1957,41 @@ mod at_rest {
use super::*;
use zeroize::Zeroize;
/// An install that predates the KEM columns (or one whose pair was blanked)
/// must gain a fresh ML-KEM key on open, and keep it on the next open.
#[test]
fn a_store_without_a_kem_key_generates_one_once() {
let dir = tempfile::tempdir().unwrap();
let pass = "kem-migrate-pass";
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
store
.conn
.execute(
"UPDATE self SET kem_sk = x'', kem_pk = x'' WHERE id = 1",
[],
)
.unwrap();
store
.conn
.execute("UPDATE friends SET kem_pk = NULL WHERE 1 = 1", [])
.unwrap();
drop(store);
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
let me = store.self_identity().unwrap();
assert_eq!(me.kem_sk.len(), crate::kem::SEED_LEN);
assert_eq!(me.kem_pk.len(), crate::kem::PK_LEN);
let pk = me.kem_pk.clone();
drop(store);
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
assert_eq!(
store.self_identity().unwrap().kem_pk,
pk,
"an existing pair is never silently replaced"
);
}
/// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has
/// to run on the store's own keyed connection: a second, unkeyed one cannot
/// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently

View file

@ -3750,6 +3750,10 @@ pub struct FriendRow {
pub fingerprint: String,
/// Last dial to this peer's onion did not answer.
pub stale: bool,
/// Friend row has an ML-KEM key (v2 invite). `false` means sessions to
/// this friend are the classical `onionwire-v1` transport, and the roster
/// says so in words — no pretending it is hybrid.
pub pq: bool,
}
/// The roster row for one friend, fitted to the pane's inner width in cells.
@ -3759,6 +3763,7 @@ pub fn friend_row(friend: &Friend) -> FriendRow {
label: sanitize::display_text(raw.as_bytes()).to_string(),
fingerprint: friend.fingerprint.clone(),
stale: !friend.last_connect_ok,
pq: friend.kem_pk.is_some(),
}
}
@ -5552,7 +5557,10 @@ fn truncate_fp(fp: &str) -> String {
fn roster_row_text(row: &FriendRow, inner_width: u16) -> String {
let budget = (inner_width as usize).saturating_sub(2);
let stale_s = if row.stale { " stale" } else { "" };
let avail = budget.saturating_sub(cell_width(stale_s));
// A legacy v1 friend has no PQ transport; say the word rather than let the
// roster imply protection it does not have.
let pq_s = if row.pq { "" } else { " classical" };
let avail = budget.saturating_sub(cell_width(stale_s) + cell_width(pq_s));
// The name is what the reader is looking for. The fingerprint only
// disambiguates two friends with the same petname, so it gets what is left
// and is dropped entirely when the pane is too narrow to show a usable
@ -5568,7 +5576,7 @@ fn roster_row_text(row: &FriendRow, inner_width: u16) -> String {
} else {
(fit_cells(&row.label, avail), String::new())
};
fit_cells(&format!("{shown}{fp_part}{stale_s}"), budget)
fit_cells(&format!("{shown}{fp_part}{pq_s}{stale_s}"), budget)
}
fn to_hex(bytes: &[u8]) -> String {