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

@ -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