From 9a20ace6e69836dca20b12a5a0409c202053e7bf Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:05:19 +0200 Subject: [PATCH 1/8] feat(client): TLS 1.3 control connection with SPKI pinning and LNEx v3 Replace the custom X25519/HKDF/ChaCha20 TCP layer with rustls (TLS 1.3 only, ALPN vnox-lnex/3, no plaintext or fallback). Add a trust store (pin, trust on first use, public CA), block changed fingerprints and identities, bind the Ed25519 auth signature to the TLS exporter, add RU/EN trust dialog and update the interop test and e2e voice tool. Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4 --- Cargo.lock | 206 +++++++- Cargo.toml | 5 + protocol/lnex.proto | 9 +- src/bin/e2e_voice.rs | 69 ++- src/main.rs | 54 ++ src/net/crypto/cipher.rs | 90 ---- src/net/crypto/mod.rs | 92 ---- src/net/framing/io.rs | 137 +---- src/net/framing/mod.rs | 7 +- src/net/handshake.rs | 290 +++++++++-- src/net/mod.rs | 17 +- src/net/payloads/mod.rs | 2 +- src/net/session/handlers/core.rs | 56 +- src/net/session/handlers/social/friends.rs | 22 +- src/net/session/handlers/social/guild.rs | 52 +- src/net/session/handlers/social/mod.rs | 78 +-- src/net/session/task.rs | 10 +- src/net/transport.rs | 523 ++++++++++++++++--- src/net/trust.rs | 569 +++++++++++++++++++++ src/net/types/event.rs | 2 + src/ui/bridge.rs | 24 + src/ui/slint/connect.slint | 54 ++ src/ui/slint/main.slint | 15 + src/ui/state/default.rs | 1 + src/ui/state/mod.rs | 2 +- src/ui/state/types.rs | 20 + src/ui/update.rs | 48 +- tests/gateway_interop.rs | 117 ++++- translations/en/LC_MESSAGES/vnox-client.po | 33 ++ translations/ru.json | 15 +- translations/ru/LC_MESSAGES/vnox-client.po | 33 ++ 31 files changed, 2085 insertions(+), 567 deletions(-) delete mode 100644 src/net/crypto/cipher.rs delete mode 100644 src/net/crypto/mod.rs create mode 100644 src/net/trust.rs diff --git a/Cargo.lock b/Cargo.lock index 677b341..0276cb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,6 +298,45 @@ dependencies = [ "libloading", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-channel" version = "2.5.0" @@ -458,6 +497,9 @@ name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "bitflags" @@ -1108,12 +1150,38 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "derive_more" version = "2.1.1" @@ -3368,6 +3436,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -3378,6 +3456,12 @@ dependencies = [ "serde", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -3816,6 +3900,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -3977,6 +4070,16 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4185,6 +4288,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "presser" version = "0.3.1" @@ -4399,6 +4508,20 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -4629,6 +4752,15 @@ dependencies = [ "transpose", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -5227,6 +5359,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -5360,6 +5503,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -5810,6 +5983,7 @@ dependencies = [ "prost", "prost-build", "rand", + "rcgen", "rfd", "rustls", "serde", @@ -6628,6 +6802,24 @@ dependencies = [ "zeroize", ] +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "xattr" version = "1.6.1" @@ -6675,6 +6867,16 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yazi" version = "0.2.1" @@ -6712,7 +6914,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -6852,7 +7054,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 404f652..48b8241 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,11 @@ nnnoiseless = { version = "0.5.2", default-features = false, optional = t image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] } rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal", "wayland"] } +[dev-dependencies] +# Test gateway certificates, and a TLS 1.2 only server for the downgrade test. +rcgen = "0.14" +rustls = { version = "0.23", features = ["tls12"] } + [features] default = ["screen-capture"] rnnoise = ["dep:nnnoiseless"] diff --git a/protocol/lnex.proto b/protocol/lnex.proto index 3b18f62..84fb355 100644 --- a/protocol/lnex.proto +++ b/protocol/lnex.proto @@ -8,8 +8,11 @@ message Hello { bytes server_pubkey = 2; bytes challenge_nonce = 3; string node_name = 4; - bytes server_eph_pubkey = 5; + // LNEx v3: the ephemeral X25519 exchange was replaced by TLS 1.3. + reserved 5; + reserved "server_eph_pubkey"; bool private_mode = 6; + // Ed25519 over "VNOX-LNEx-v3-server-hello\0" || tls_exporter || Hello(signature empty). bytes server_signature = 7; } @@ -17,8 +20,10 @@ message Auth { bytes client_pubkey = 1; string nickname = 2; string lnex_version = 3; + // Ed25519 over the client-auth transcript bound to the TLS exporter (see docs/02-protocol/tls.md). bytes signature = 4; - bytes client_eph_pubkey = 5; + reserved 5; + reserved "client_eph_pubkey"; } message Session { diff --git a/src/bin/e2e_voice.rs b/src/bin/e2e_voice.rs index 40af5bd..0019fbe 100644 --- a/src/bin/e2e_voice.rs +++ b/src/bin/e2e_voice.rs @@ -1,4 +1,8 @@ //! Headless authenticated voice smoke test. Run vnox-serverd first (combined gateway+voice relay). +//! +//! The control connection is TLS 1.3, so the gateway certificate must be trusted. Pass the +//! fingerprint printed by the gateway (`--fingerprint HEX`) or, for a throwaway loopback +//! check only, `--trust-first-use`. The trust store is in memory: nothing is persisted. use anyhow::{Context, Result}; use tokio::time::{Duration, timeout}; use vnox_client::{ @@ -9,15 +13,15 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Res timeout(Duration::from_secs(8), async { loop { if let Some(event) = handle.try_recv() { + if predicate(&event) { + return Ok(event); + } if let NetEvent::Disconnected { ref reason, .. } = event { anyhow::bail!("connection ended: {reason}"); } if let NetEvent::Error { code, ref message } = event { anyhow::bail!("gateway error {code}: {message}"); } - if predicate(&event) { - return Ok(event); - } } tokio::time::sleep(Duration::from_millis(5)).await; } @@ -25,14 +29,42 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Res .await .context("timed out waiting for network event")? } -async fn client(name: &str, address: &str) -> Result { - let handle = net::spawn(identity::generate(name)); +/// How the smoke test decides about the gateway certificate. +enum Trust { + Fingerprint(String), + FirstUse, +} + +async fn client(name: &str, address: &str, trust: &Trust) -> Result { + let handle = net::spawn_with_trust(identity::generate(name), net::TrustStore::in_memory()); + let key = net::trust::parse_address(address)?.key; + match trust { + Trust::Fingerprint(fingerprint) => handle.trust().pin(&key, fingerprint)?, + Trust::FirstUse => {} + } handle .send(NetCommand::Connect { address: address.into(), auto_reconnect: false, }) .await; + if matches!(trust, Trust::FirstUse) { + // The explicit opt-in replaces the interactive prompt: pin what the gateway presents. + if let NetEvent::TrustProblem(net::TrustProblem::Untrusted { fingerprint, .. }) = + event(&handle, |e| matches!(e, NetEvent::TrustProblem(_))).await? + { + eprintln!("trusting gateway fingerprint {fingerprint} (--trust-first-use)"); + handle.trust().pin(&key, &fingerprint)?; + // The refused first attempt reports its disconnect before we reconnect. + event(&handle, |e| matches!(e, NetEvent::Disconnected { .. })).await?; + handle + .send(NetCommand::Connect { + address: address.into(), + auto_reconnect: false, + }) + .await; + } + } event( &handle, |event| matches!(event,NetEvent::ChannelState {channel_id,..} if channel_id=="general"), @@ -52,11 +84,26 @@ async fn client(name: &str, address: &str) -> Result { } #[tokio::main] async fn main() -> Result<()> { - let address = std::env::args() - .nth(1) - .unwrap_or_else(|| "127.0.0.1:7600".into()); - let alice = client("voice-fixture-alice", &address).await?; - let bob = client("voice-fixture-bob", &address).await?; + let mut address = "127.0.0.1:7600".to_string(); + let mut trust = None; + let mut args = std::env::args().skip(1); + while let Some(argument) = args.next() { + match argument.as_str() { + "--trust-first-use" => trust = Some(Trust::FirstUse), + "--fingerprint" => { + let value = args.next().context("--fingerprint needs a value")?; + trust = Some(Trust::Fingerprint(net::trust::normalize_fingerprint( + &value, + )?)); + } + other => address = other.to_string(), + } + } + let trust = trust.context( + "the gateway certificate must be trusted: pass --fingerprint HEX (from the gateway log) or --trust-first-use", + )?; + let alice = client("voice-fixture-alice", &address, &trust).await?; + let bob = client("voice-fixture-bob", &address, &trust).await?; // The real network layer registers the current credentials with encrypted empty-Opus packets. tokio::time::sleep(Duration::from_millis(250)).await; let marker = b"authenticated-vnox-voice-fixture"; @@ -113,6 +160,6 @@ async fn main() -> Result<()> { .await?; alice.send(NetCommand::Disconnect).await; bob.send(NetCommand::Disconnect).await; - println!("Authenticated v2 UDP voice relay passed"); + println!("TLS 1.3 control plane and authenticated UDP voice relay passed"); Ok(()) } diff --git a/src/main.rs b/src/main.rs index 335b435..3ff3c53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -353,6 +353,60 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { }); } + { + // First trust: remember the confirmed fingerprint, then connect again. + let state = state.clone(); + window.on_trust_accept(move || { + let mut s = state.borrow_mut(); + let Some(prompt) = s.ui.trust_prompt.take() else { + return; + }; + if prompt.kind != ui::state::TrustPromptKind::FirstUse { + return; + } + if let Err(error) = s.net.trust().pin(&prompt.address, &prompt.received) { + tracing::warn!(%error, "could not save the trusted fingerprint"); + s.ui.status_msg = Some("Could not save the trusted fingerprint".into()); + return; + } + s.ui.conn = ConnState::Connecting; + s.ui.status_msg = Some("Connecting…".into()); + let auto_reconnect = s.ui.auto_reconnect; + let net = s.net.clone(); + drop(s); + tokio::spawn(async move { + net.send(NetCommand::Connect { + address: prompt.address, + auto_reconnect, + }) + .await; + }); + }); + } + + { + // A blocked change: forgetting is the only way forward and needs a new decision. + let state = state.clone(); + window.on_trust_forget(move || { + let mut s = state.borrow_mut(); + let Some(prompt) = s.ui.trust_prompt.take() else { + return; + }; + if let Err(error) = s.net.trust().forget(&prompt.address) { + tracing::warn!(%error, "could not forget the server"); + } + s.ui.status_msg = + Some("Server forgotten. Connect again to review its fingerprint.".into()); + }); + } + + { + let state = state.clone(); + window.on_trust_dismiss(move || { + state.borrow_mut().ui.trust_prompt = None; + }); + } + { let state = state.clone(); window.on_disconnect(move || { diff --git a/src/net/crypto/cipher.rs b/src/net/crypto/cipher.rs deleted file mode 100644 index 2930348..0000000 --- a/src/net/crypto/cipher.rs +++ /dev/null @@ -1,90 +0,0 @@ -use chacha20poly1305::{ - ChaCha20Poly1305, Key, KeyInit, Nonce, - aead::{Aead, Payload}, -}; - -fn make_nonce(cid: &[u8; 8], seq: u64) -> [u8; 12] { - let mut nonce = [0u8; 12]; - nonce[..8].copy_from_slice(cid); - nonce[8..12].copy_from_slice(&(seq as u32).to_le_bytes()); - nonce -} - -#[cfg(test)] -pub fn encrypt_with_key(key: &[u8; 32], cid: &[u8; 8], seq: u64, plaintext: &[u8]) -> Vec { - encrypt_with_aad(key, cid, seq, plaintext, &[]) -} - -pub fn encrypt_with_aad( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - plaintext: &[u8], - aad: &[u8], -) -> Vec { - let cipher = ChaCha20Poly1305::new(&Key::from(*key)); - let nonce_bytes = make_nonce(cid, seq); - let nonce = Nonce::from(nonce_bytes); - cipher - .encrypt( - &nonce, - Payload { - msg: plaintext, - aad, - }, - ) - .expect("ChaCha20-Poly1305 encryption infallible") -} - -#[cfg(test)] -pub fn decrypt_with_key( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - ciphertext: &[u8], -) -> anyhow::Result> { - decrypt_with_aad(key, cid, seq, ciphertext, &[]) -} - -pub fn decrypt_with_aad( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - ciphertext: &[u8], - aad: &[u8], -) -> anyhow::Result> { - let cipher = ChaCha20Poly1305::new(&Key::from(*key)); - let nonce_bytes = make_nonce(cid, seq); - let nonce = Nonce::from(nonce_bytes); - cipher - .decrypt( - &nonce, - Payload { - msg: ciphertext, - aad, - }, - ) - .map_err(|e| anyhow::anyhow!("decryption failed: {e:?}")) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ciphertext_matches_existing_lnex_wire_format() { - let key = core::array::from_fn(|index| index as u8); - let cid = [7, 0, 0, 0, 0x40, 0x41, 0x42, 0x43]; - // Independently checked with Python cryptography and shared with gateway. - let expected = hex::decode( - "1fa23e7a312509b0fc8729521811348ff880daa5598c43a57635975f81278abdf4461b25af86aee1c3", - ) - .unwrap(); - let ciphertext = encrypt_with_key(&key, &cid, 0x47464544, b"VNOX dependency migration"); - assert_eq!(ciphertext, expected); - assert_eq!( - decrypt_with_key(&key, &cid, 0x47464544, &expected).unwrap(), - b"VNOX dependency migration", - ); - } -} diff --git a/src/net/crypto/mod.rs b/src/net/crypto/mod.rs deleted file mode 100644 index d7415ce..0000000 --- a/src/net/crypto/mod.rs +++ /dev/null @@ -1,92 +0,0 @@ -use hkdf::Hkdf; -use sha2::{Digest, Sha256}; -use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret}; - -pub mod cipher; - -/// Session encryption context (mirrors gateway/src/proto/crypto.rs). -/// -/// Two derived keys: -/// - `c2s_key`: client → server -/// - `s2c_key`: server → client -/// -/// Nonce: `cid (8 bytes) || packet_seq (4 bytes LE)`. -#[derive(Clone)] -pub struct SessionCrypto { - c2s_key: [u8; 32], - s2c_key: [u8; 32], - cid: [u8; 8], -} - -impl SessionCrypto { - pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self { - let salt = b"VNOX-LNEx-KDF-v2"; - let hk = Hkdf::::new(Some(salt), shared_secret); - - let mut keys = [0u8; 64]; - hk.expand(b"session-keys", &mut keys) - .expect("64 bytes within HKDF max"); - - let c2s_key: [u8; 32] = keys[..32].try_into().unwrap(); - let s2c_key: [u8; 32] = keys[32..64].try_into().unwrap(); - - let hash = Sha256::digest(session_id.as_bytes()); - let cid: [u8; 8] = hash[..8].try_into().unwrap(); - - Self { - c2s_key, - s2c_key, - cid, - } - } - - pub fn encrypt_c2s_aad(&self, seq: u64, plaintext: &[u8], aad: &[u8]) -> Vec { - cipher::encrypt_with_aad(&self.c2s_key, &self.cid, seq, plaintext, aad) - } - pub fn decrypt_s2c_aad( - &self, - seq: u64, - ciphertext: &[u8], - aad: &[u8], - ) -> anyhow::Result> { - cipher::decrypt_with_aad(&self.s2c_key, &self.cid, seq, ciphertext, aad) - } - - pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) { - let mut rng = rand::rng(); - let sk = EphemeralSecret::random_from_rng(&mut rng); - let pk = PublicKey::from(&sk); - (sk, pk) - } - - pub fn ecdh(secret: EphemeralSecret, peer_public: &PublicKey) -> SharedSecret { - secret.diffie_hellman(peer_public) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn encrypt_then_decrypt_roundtrip() { - let shared_secret = [0xABu8; 32]; - let crypto = SessionCrypto::derive(&shared_secret, "test-session"); - - let plaintext = b"hello encrypted world"; - let ct = crypto.encrypt_c2s_aad(42, plaintext, b"header"); - let decrypted = - cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 42, &ct, b"header").unwrap(); - assert_eq!(decrypted, plaintext); - } - - #[test] - fn tampered_ciphertext_fails() { - let shared_secret = [0xABu8; 32]; - let crypto = SessionCrypto::derive(&shared_secret, "test-session"); - - let mut ct = crypto.encrypt_c2s_aad(0, b"data", b"header"); - ct[5] ^= 0xFF; - assert!(cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 0, &ct, b"header").is_err()); - } -} diff --git a/src/net/framing/io.rs b/src/net/framing/io.rs index 8223169..9a02185 100644 --- a/src/net/framing/io.rs +++ b/src/net/framing/io.rs @@ -1,66 +1,9 @@ +//! Session frame reader. Frames travel inside the TLS 1.3 stream, so there is no per frame +//! encryption: a dedicated task retains partial frames across command/timer selection and +//! enforces strictly increasing sequence numbers. use anyhow::{Result, anyhow}; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; -use super::super::crypto::SessionCrypto; -use super::super::payloads::HDR_SIZE; use super::RawPacket; -use super::parse_header; - -const ENCRYPTED_FLAG: u16 = 1 << 1; -const KNOWN_FLAGS: u16 = ENCRYPTED_FLAG; - -pub async fn read_encrypted( - stream: &mut (impl tokio::io::AsyncRead + Unpin), - crypto: &SessionCrypto, -) -> Result { - let mut buf = [0u8; HDR_SIZE]; - stream.read_exact(&mut buf).await?; - let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?; - if flags & !KNOWN_FLAGS != 0 { - return Err(anyhow!("unknown packet flags: 0x{:04X}", flags)); - } - if flags & ENCRYPTED_FLAG == 0 { - return Err(anyhow!("packet not encrypted")); - } - let mut encrypted = vec![0u8; payload_length as usize]; - if !encrypted.is_empty() { - stream.read_exact(&mut encrypted).await?; - } - let payload = crypto.decrypt_s2c_aad(sequence as u64, &encrypted, &buf)?; - Ok(RawPacket { - packet_id, - sequence, - payload, - }) -} - -pub async fn write_encrypted( - stream: &mut (impl tokio::io::AsyncWrite + Unpin), - id: u16, - seq: &mut u32, - payload: &[u8], - crypto: &SessionCrypto, -) -> Result<()> { - if *seq == u32::MAX { - return Err(anyhow!("session sequence exhausted; reconnect required")); - } - if payload.len() > super::super::payloads::MAX_PAYLOAD as usize - 16 { - return Err(anyhow!("payload too large")); - } - let mut hdr = [0u8; HDR_SIZE]; - hdr[0..2].copy_from_slice(&id.to_be_bytes()); - hdr[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes()); - hdr[4..8].copy_from_slice(&seq.to_be_bytes()); - hdr[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes()); - let encrypted = crypto.encrypt_c2s_aad(*seq as u64, payload, &hdr); - *seq += 1; - let mut frame = Vec::with_capacity(HDR_SIZE + encrypted.len()); - frame.extend_from_slice(&hdr); - frame.extend_from_slice(&encrypted); - stream.write_all(&frame).await?; - Ok(()) -} /// A dedicated reader retains partial frames across command/timer selection. /// Dropping a session cancels its reader and releases the socket half. @@ -69,25 +12,21 @@ pub struct Reader { task: tokio::task::JoinHandle<()>, } impl Reader { - pub fn new( - mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static, - crypto: SessionCrypto, - ) -> Self { + pub fn new(mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static) -> Self { let (sender, receiver) = tokio::sync::mpsc::channel(32); let task = tokio::spawn(async move { + // HELLO was 0 and SESSION was 1. let mut expected = 2u32; loop { - let result = read_encrypted(&mut stream, &crypto) - .await - .and_then(|packet| { - if packet.sequence != expected { - return Err(anyhow!("replayed or reordered control packet")); - } - expected = expected - .checked_add(1) - .ok_or_else(|| anyhow!("session sequence exhausted"))?; - Ok(packet) - }); + let result = super::read(&mut stream).await.and_then(|packet| { + if packet.sequence != expected { + return Err(anyhow!("replayed or reordered control packet")); + } + expected = expected + .checked_add(1) + .ok_or_else(|| anyhow!("session sequence exhausted"))?; + Ok(packet) + }); let failed = result.is_err(); if sender.send(result).await.is_err() || failed { break; @@ -112,34 +51,18 @@ impl Drop for Reader { #[cfg(test)] mod tests { use super::*; - use hkdf::Hkdf; - use sha2::{Digest, Sha256}; + use tokio::io::AsyncWriteExt; use tokio::time::{Duration, timeout}; fn server_frame(pid: u16, seq: u32, payload: &[u8]) -> Vec { - let mut keys = [0u8; 64]; - Hkdf::::new(Some(b"VNOX-LNEx-KDF-v2"), &[7; 32]) - .expand(b"session-keys", &mut keys) - .unwrap(); - let key: [u8; 32] = keys[32..].try_into().unwrap(); - let cid: [u8; 8] = Sha256::digest(b"fixture-session")[..8].try_into().unwrap(); - let mut header = [0u8; 12]; - header[..2].copy_from_slice(&pid.to_be_bytes()); - header[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes()); - header[4..8].copy_from_slice(&seq.to_be_bytes()); - header[8..].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes()); - let body = - crate::net::crypto::cipher::encrypt_with_aad(&key, &cid, seq as u64, payload, &header); - [header.as_slice(), body.as_slice()].concat() - } - fn crypto() -> SessionCrypto { - SessionCrypto::derive(&[7; 32], "fixture-session") + let mut seq = seq; + super::super::encode_frame(pid, &mut seq, payload) } #[tokio::test] async fn cancelling_wait_retains_partial_control_frame() { let (reader, mut writer) = tokio::io::duplex(256); - let mut reader = Reader::new(reader, crypto()); + let mut reader = Reader::new(reader); let frame = server_frame(5, 2, b"protobuf"); writer.write_all(&frame[..5]).await.unwrap(); assert!( @@ -157,7 +80,7 @@ mod tests { #[tokio::test] async fn replayed_control_sequence_is_rejected() { let (reader, mut writer) = tokio::io::duplex(256); - let mut reader = Reader::new(reader, crypto()); + let mut reader = Reader::new(reader); let frame = server_frame(5, 2, b""); writer.write_all(&frame).await.unwrap(); reader.next().await.unwrap(); @@ -165,22 +88,12 @@ mod tests { assert!(reader.next().await.is_err()); } #[tokio::test] - async fn changing_packet_id_invalidates_authentication() { - let (mut reader, mut writer) = tokio::io::duplex(256); - let mut frame = server_frame(5, 2, b"same body"); - frame[1] ^= 1; + async fn legacy_encrypted_flag_is_rejected() { + let (reader, mut writer) = tokio::io::duplex(256); + let mut reader = Reader::new(reader); + let mut frame = server_frame(5, 2, b"0123456789abcdef"); + frame[2..4].copy_from_slice(&2u16.to_be_bytes()); writer.write_all(&frame).await.unwrap(); - assert!(read_encrypted(&mut reader, &crypto()).await.is_err()); - } - #[tokio::test] - async fn sequence_exhaustion_never_wraps_nonce() { - let (_, mut writer) = tokio::io::duplex(256); - let mut seq = u32::MAX; - assert!( - write_encrypted(&mut writer, 4, &mut seq, b"", &crypto()) - .await - .is_err() - ); - assert_eq!(seq, u32::MAX); + assert!(reader.next().await.is_err()); } } diff --git a/src/net/framing/mod.rs b/src/net/framing/mod.rs index 8616fbe..ff3b56b 100644 --- a/src/net/framing/mod.rs +++ b/src/net/framing/mod.rs @@ -39,7 +39,7 @@ pub fn decode_frame(bytes: &[u8]) -> Result { let hdr: [u8; HDR_SIZE] = bytes[..HDR_SIZE].try_into().expect("header length"); let (packet_id, flags, sequence, payload_length) = parse_header(&hdr)?; if flags != 0 { - return Err(anyhow!("unexpected handshake flags")); + return Err(anyhow!("unexpected frame flags")); } let end = HDR_SIZE + payload_length as usize; if bytes.len() < end { @@ -57,7 +57,7 @@ pub async fn read(stream: &mut (impl tokio::io::AsyncRead + Unpin)) -> Result Result<()> { + if *seq == u32::MAX { + return Err(anyhow!("session sequence exhausted; reconnect required")); + } let frame = encode_frame(id, seq, payload); stream.write_all(&frame).await?; Ok(()) diff --git a/src/net/handshake.rs b/src/net/handshake.rs index 536ebd4..39abd57 100644 --- a/src/net/handshake.rs +++ b/src/net/handshake.rs @@ -3,31 +3,85 @@ use anyhow::{Result, anyhow}; use tracing::{debug, info}; -use super::crypto::SessionCrypto; use super::framing; use super::payloads::*; +use super::trust::TransportError; use crate::identity::Identity; -/// Perform HELLO → AUTH → SESSION with X25519 ECDH key exchange. +const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0"; +const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0"; + +/// Bytes signed by the server identity: context, TLS exporter, HELLO without signature. +pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec { + let mut out = SERVER_HELLO_CONTEXT.to_vec(); + out.extend_from_slice(binding); + out.extend_from_slice(unsigned_hello); + out +} + +/// Bytes signed by the client identity. The TLS exporter makes the signature valid for +/// this connection only, so it cannot be relayed to another server or connection. +pub fn client_auth_transcript( + binding: &[u8], + signed_hello: &[u8], + unsigned_auth: &[u8], +) -> Vec { + let mut out = CLIENT_AUTH_CONTEXT.to_vec(); + out.extend_from_slice(binding); + out.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes()); + out.extend_from_slice(signed_hello); + out.extend_from_slice(unsigned_auth); + out +} + +/// What the handshake learned about the server and the new session. +#[derive(Debug, Clone)] +pub struct Outcome { + pub session_id: String, + pub node_name: String, + pub private_mode: bool, + /// Lower-case hex Ed25519 identity of the server. + pub server_identity: String, +} + +/// Perform HELLO, AUTH, SESSION inside an established TLS 1.3 connection. /// -/// Returns (session_id, node_name, private_mode, crypto). -/// All subsequent packets must be encrypted with `crypto`. +/// * `binding` is the TLS exporter value, covered by both signatures. +/// * `trust_key` and `expected_identity` implement the identity pin: a server presenting a +/// different Ed25519 identity than the stored one is rejected before AUTH is sent. pub async fn run( stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin), identity: &Identity, seq: &mut u32, -) -> Result<(String, String, bool, SessionCrypto)> { - // HELLO — receive server's ephemeral X25519 public key + binding: &[u8], + trust_key: &str, + expected_identity: Option<&str>, +) -> Result { + // HELLO let pkt = framing::read(stream).await?; + if pkt.packet_id == PID_ERROR { + let e: ErrorPayload = wire::decode(&pkt.payload)?; + return Err(anyhow!("server rejected the connection: {}", e.message)); + } if pkt.packet_id != PID_HELLO { return Err(anyhow!("expected HELLO, got 0x{:04X}", pkt.packet_id)); } - let hello: HelloPayload = wire::decode(&pkt.payload)?; - debug!("← HELLO node={}", hello.node_name); - if pkt.sequence != 0 { return Err(anyhow!("invalid HELLO sequence")); } + let hello: HelloPayload = wire::decode(&pkt.payload)?; + debug!("HELLO node={}", hello.node_name); + if hello.lnex_version != LNEX_VERSION { + return Err(TransportError::ProtocolMismatch(format!( + "The server speaks LNEx {} but this client requires {}. Update the outdated side.", + hello.lnex_version, LNEX_VERSION + )) + .into()); + } + if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 { + return Err(anyhow!("invalid server handshake key/challenge")); + } + let server_public: [u8; 32] = hello .server_pubkey .as_slice() @@ -37,32 +91,27 @@ pub async fn run( let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature)?; let mut unsigned_hello = hello.clone(); unsigned_hello.server_signature.clear(); - let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec(); - hello_transcript.extend_from_slice(&wire::encode(&unsigned_hello)?); server_key - .verify_strict(&hello_transcript, &signature) + .verify_strict( + &server_hello_transcript(binding, &wire::encode(&unsigned_hello)?), + &signature, + ) .map_err(|_| anyhow!("server handshake signature verification failed"))?; - // Keep full signed hello for the client-auth transcript before moving fields. + let server_identity = hex::encode(server_public); + if let Some(expected) = expected_identity + && expected != server_identity + { + return Err(TransportError::IdentityChanged { + address: trust_key.to_string(), + expected: expected.to_string(), + actual: server_identity, + } + .into()); + } + // Keep the full signed hello for the client-auth transcript. let signed_hello = wire::encode(&hello)?; - // Generate our own ephemeral X25519 keypair - let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral(); - let eph_pk_hex = eph_pk.as_bytes().to_vec(); - - // Parse server's ephemeral key from HELLO - let server_eph_raw = hello.server_eph_pubkey; - let server_eph_key: [u8; 32] = server_eph_raw - .try_into() - .map_err(|_| anyhow!("bad server_eph_pubkey length"))?; - let server_eph_pk = x25519_dalek::PublicKey::from(server_eph_key); - - // AUTH — include our ephemeral public key - if hello.lnex_version != LNEX_VERSION { - return Err(anyhow!("unsupported LNEx version")); - } - if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 { - return Err(anyhow!("invalid server handshake key/challenge")); - } + // AUTH let sk = identity .signing_key() .ok_or_else(|| anyhow!("no signing key"))?; @@ -73,15 +122,11 @@ pub async fn run( nickname: identity.nickname.clone(), lnex_version: LNEX_VERSION.into(), signature: Vec::new(), - client_eph_pubkey: eph_pk_hex, }; - let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec(); - auth_transcript.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes()); - auth_transcript.extend_from_slice(&signed_hello); - auth_transcript.extend_from_slice(&wire::encode(&auth)?); - auth.signature = sk.sign(&auth_transcript).to_bytes().to_vec(); + let transcript = client_auth_transcript(binding, &signed_hello, &wire::encode(&auth)?); + auth.signature = sk.sign(&transcript).to_bytes().to_vec(); framing::write(stream, PID_AUTH, seq, &wire::encode(&auth)?).await?; - debug!("→ AUTH nick={}", identity.nickname); + debug!("AUTH sent nick={}", identity.nickname); // SESSION let pkt = framing::read(stream).await?; @@ -96,21 +141,172 @@ pub async fn run( return Err(anyhow!("invalid SESSION sequence")); } let sess: SessionPayload = wire::decode(&pkt.payload)?; - - // Derive encryption keys from ECDH shared secret - let shared_secret = SessionCrypto::ecdh(eph_sk, &server_eph_pk); - if !shared_secret.was_contributory() { - return Err(anyhow!("invalid server ECDH key")); - } if sess.session_id.is_empty() || sess.token.is_empty() { return Err(anyhow!("invalid session response")); } - let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id); info!( - "authenticated — session {} encrypted", + "authenticated, session {}", sess.session_id.chars().take(8).collect::() ); - Ok((sess.session_id, hello.node_name, hello.private_mode, crypto)) + Ok(Outcome { + session_id: sess.session_id, + node_name: hello.node_name, + private_mode: hello.private_mode, + server_identity, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::{Signer, SigningKey}; + use tokio::io::AsyncWriteExt; + + /// Scripted gateway: sends a HELLO signed over `hello_binding` and returns the AUTH it gets. + async fn fake_server( + mut stream: tokio::io::DuplexStream, + server_key: SigningKey, + hello_binding: [u8; 32], + version: &str, + send_session: bool, + ) -> (AuthPayload, Vec) { + let mut hello = HelloPayload { + lnex_version: version.into(), + server_pubkey: server_key.verifying_key().to_bytes().to_vec(), + challenge_nonce: vec![7; 32], + node_name: "fake".into(), + private_mode: true, + server_signature: Vec::new(), + }; + let unsigned = wire::encode(&hello).unwrap(); + hello.server_signature = server_key + .sign(&server_hello_transcript(&hello_binding, &unsigned)) + .to_bytes() + .to_vec(); + let signed = wire::encode(&hello).unwrap(); + let mut seq = 0; + framing::write(&mut stream, PID_HELLO, &mut seq, &signed) + .await + .unwrap(); + let Ok(packet) = framing::read(&mut stream).await else { + return (AuthPayload::default(), signed); + }; + let auth: AuthPayload = wire::decode(&packet.payload).unwrap(); + if send_session { + let session = SessionPayload { + session_id: "session-1".into(), + token: "token".into(), + expires_at: 0, + }; + framing::write( + &mut stream, + PID_SESSION, + &mut seq, + &wire::encode(&session).unwrap(), + ) + .await + .unwrap(); + } + let _ = stream.shutdown().await; + (auth, signed) + } + + fn identity() -> Identity { + crate::identity::generate("handshake-test") + } + + #[tokio::test] + async fn authenticated_handshake_returns_server_identity_and_binds_signature() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v3", true)); + let mut seq = 0; + let outcome = run(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None) + .await + .unwrap(); + assert_eq!(outcome.session_id, "session-1"); + assert_eq!( + outcome.server_identity, + hex::encode(server_key.verifying_key().to_bytes()) + ); + // The AUTH signature is valid for this connection and invalid for any other one. + let (auth, signed_hello) = task.await.unwrap(); + let client_public = ed25519_dalek::VerifyingKey::from_bytes( + &auth.client_pubkey.clone().try_into().unwrap(), + ) + .unwrap(); + let signature = ed25519_dalek::Signature::from_slice(&auth.signature).unwrap(); + let mut unsigned_auth = auth.clone(); + unsigned_auth.signature.clear(); + let unsigned = wire::encode(&unsigned_auth).unwrap(); + client_public + .verify_strict( + &client_auth_transcript(&[9; 32], &signed_hello, &unsigned), + &signature, + ) + .unwrap(); + assert!( + client_public + .verify_strict( + &client_auth_transcript(&[8; 32], &signed_hello, &unsigned), + &signature + ) + .is_err(), + "a signature made on one TLS connection must not verify on another" + ); + } + + #[tokio::test] + async fn hello_relayed_from_another_tls_connection_is_rejected() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + // The relay forwards a HELLO signed for a different TLS session. + tokio::spawn(fake_server(server, server_key, [1; 32], "v3", false)); + let mut seq = 0; + let error = run(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None) + .await + .unwrap_err(); + assert!(error.to_string().contains("signature verification failed")); + assert_eq!(seq, 0, "no AUTH may be sent to an unauthenticated peer"); + } + + #[tokio::test] + async fn changed_server_identity_is_blocked_before_auth() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + tokio::spawn(fake_server(server, server_key, [3; 32], "v3", false)); + let mut seq = 0; + let error = run( + &mut client, + &identity(), + &mut seq, + &[3; 32], + "h:7600", + Some(&"00".repeat(32)), + ) + .await + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(TransportError::IdentityChanged { .. }) + )); + assert_eq!(seq, 0); + } + + #[tokio::test] + async fn old_protocol_version_gives_explicit_error() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + tokio::spawn(fake_server(server, server_key, [4; 32], "v2", false)); + let mut seq = 0; + let error = run(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None) + .await + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3") + )); + } } diff --git a/src/net/mod.rs b/src/net/mod.rs index c7862ec..4db7a2d 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -1,14 +1,15 @@ -pub mod crypto; pub mod framing; pub mod handshake; mod internal; pub mod payloads; mod session; pub mod transport; +pub mod trust; mod types; pub mod voice; pub mod wire; +pub use trust::{TransportError, TrustProblem, TrustStore}; pub use types::{ ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo, WebhookManagementResult, WebhookOperation, @@ -26,23 +27,35 @@ use crate::identity::Identity; pub struct NetHandle { cmd_tx: mpsc::Sender, event_rx: Arc>>, + trust: trust::TrustStore, } impl NetHandle { pub async fn send(&self, cmd: NetCommand) { let _ = self.cmd_tx.send(cmd).await; } + /// Server trust decisions (pinned fingerprints). Share it with the UI. + pub fn trust(&self) -> &trust::TrustStore { + &self.trust + } pub fn try_recv(&self) -> Option { self.event_rx.try_lock().ok()?.try_recv().ok() } } +/// Spawn the network task with the persistent trust store. pub fn spawn(identity: Identity) -> NetHandle { + spawn_with_trust(identity, trust::TrustStore::load_default()) +} + +/// Spawn with an explicit trust store (tests, headless tools). +pub fn spawn_with_trust(identity: Identity, trust: trust::TrustStore) -> NetHandle { let (cmd_tx, cmd_rx) = mpsc::channel::(64); let (event_tx, event_rx) = mpsc::channel::(256); - tokio::spawn(session::net_task(identity, cmd_rx, event_tx)); + tokio::spawn(session::net_task(identity, trust.clone(), cmd_rx, event_tx)); NetHandle { cmd_tx, event_rx: Arc::new(Mutex::new(event_rx)), + trust, } } diff --git a/src/net/payloads/mod.rs b/src/net/payloads/mod.rs index 1c16b1a..99f475e 100644 --- a/src/net/payloads/mod.rs +++ b/src/net/payloads/mod.rs @@ -67,7 +67,7 @@ pub const PID_FRIEND_EVENT: u16 = 0x0158; pub const PID_ERROR: u16 = 0x00F0; pub const PID_DISCONNECT: u16 = 0x00FF; -pub const LNEX_VERSION: &str = "v2"; +pub const LNEX_VERSION: &str = "v3"; pub const HDR_SIZE: usize = 12; pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024; diff --git a/src/net/session/handlers/core.rs b/src/net/session/handlers/core.rs index 27124ee..b2ecff0 100644 --- a/src/net/session/handlers/core.rs +++ b/src/net/session/handlers/core.rs @@ -11,6 +11,7 @@ use crate::net::wire; use crate::net::{ framing, handshake, internal, payloads::*, + trust::TrustStore, types::{NetCommand, NetEvent}, }; @@ -20,6 +21,7 @@ use super::{VoiceState, handle_cmd}; pub async fn session_loop( identity: &Identity, address: &str, + trust: &TrustStore, channels: &mut Vec, restored: bool, cmd_rx: &mut mpsc::Receiver, @@ -27,7 +29,7 @@ pub async fn session_loop( ) -> Result<()> { let connection = tokio::time::timeout( Duration::from_secs(10), - crate::net::transport::connect_with_peer(address), + crate::net::transport::connect_with_peer(address, trust), ) .await .context("gateway connection timed out")??; @@ -35,12 +37,29 @@ pub async fn session_loop( let mut stream = connection.stream; let mut seq = 0u32; - let (session_id, node_name, private_mode, crypto) = tokio::time::timeout( + let outcome = tokio::time::timeout( Duration::from_secs(10), - handshake::run(&mut stream, identity, &mut seq), + handshake::run( + &mut stream, + identity, + &mut seq, + &connection.binding, + &connection.trust_key, + connection + .record + .as_ref() + .and_then(|record| record.identity.as_deref()), + ), ) .await .context("gateway handshake timed out")??; + // The identity is learned inside an already trusted channel and then pinned. + if let Err(error) = trust.set_identity(&connection.trust_key, &outcome.server_identity) { + tracing::warn!(%error, "could not store the server identity"); + } + let session_id = outcome.session_id; + let node_name = outcome.node_name; + let private_mode = outcome.private_mode; let _ = event_tx .send(NetEvent::Connected { session_id: session_id.clone(), @@ -51,18 +70,17 @@ pub async fn session_loop( .await; for channel_id in channels.clone() { - framing::io::write_encrypted( + framing::write( &mut stream, PID_JOIN_CHANNEL, &mut seq, &wire::encode(&JoinChannelPayload { channel_id })?, - &crypto, ) .await?; } let (reader, mut stream) = tokio::io::split(stream); - let mut incoming = framing::io::Reader::new(reader, crypto.clone()); + let mut incoming = framing::io::Reader::new(reader); let mut voice_state: Option = None; let mut used_voice_routes = std::collections::HashSet::new(); let mut voice_endpoint: Option = None; @@ -77,7 +95,7 @@ pub async fn session_loop( _ = ping_tick.tick() => { let ts = now_ms(); let payload = wire::encode(&PingPayload { timestamp: ts })?; - framing::io::write_encrypted(&mut stream, PID_PING, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_PING, &mut seq, &payload).await?; } result = incoming.next() => { let pkt = result?; @@ -113,8 +131,8 @@ pub async fn session_loop( cmd = cmd_rx.recv() => { match cmd { None | Some(NetCommand::Disconnect) => { - let _ = framing::io::write_encrypted(&mut stream, PID_DISCONNECT, &mut seq, - &wire::encode(&Disconnect {reason: "bye".into()})?, &crypto).await; + let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq, + &wire::encode(&Disconnect {reason: "bye".into()})?).await; return Ok(()); } Some(NetCommand::Connect { address, auto_reconnect }) => { @@ -129,14 +147,14 @@ pub async fn session_loop( } Some(NetCommand::JoinChannel { channel_id }) => { track_channel(channels, &channel_id); - framing::io::write_encrypted(&mut stream, PID_JOIN_CHANNEL, &mut seq, - &wire::encode(&JoinChannelPayload { channel_id })?, &crypto).await?; + framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq, + &wire::encode(&JoinChannelPayload { channel_id })?).await?; } Some(NetCommand::LeaveChannel { channel_id }) => { channels.retain(|c| c != &channel_id); if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;} - framing::io::write_encrypted(&mut stream, PID_LEAVE_CHANNEL, &mut seq, - &wire::encode(&LeaveChannelPayload { channel_id })?, &crypto).await?; + framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq, + &wire::encode(&LeaveChannelPayload { channel_id })?).await?; } Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => { let payload = wire::encode(&ChannelCreatePayload { @@ -145,14 +163,14 @@ pub async fn session_loop( kind, guild_id, })?; - framing::io::write_encrypted(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?; } Some(NetCommand::ChannelDelete { channel_id }) => { let payload = wire::encode(&ChannelDeletePayload { channel_id })?; - framing::io::write_encrypted(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?; } Some(NetCommand::ChannelList) => { - framing::io::write_encrypted(&mut stream, PID_CHANNEL_LIST, &mut seq, b"", &crypto).await?; + framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?; } Some(NetCommand::SendChat { channel_id, content, reply_to }) => { let msg = ChatMessagePayload { @@ -162,16 +180,16 @@ pub async fn session_loop( edited: false, reply_to, }; - framing::io::write_encrypted(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?, &crypto).await?; + framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?; } Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => { if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;} } Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => { let payload = wire::encode(&ReadReceipt {channel_id,last_read_message_id,user_id: identity.pubkey_hex.clone()})?; - framing::io::write_encrypted(&mut stream, PID_READ_RECEIPT, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_READ_RECEIPT, &mut seq, &payload).await?; } - Some(other) => handle_cmd(other, &mut stream, &mut seq, &crypto, identity).await?, + Some(other) => handle_cmd(other, &mut stream, &mut seq, identity).await?, } } } diff --git a/src/net/session/handlers/social/friends.rs b/src/net/session/handlers/social/friends.rs index 6804a0a..4c18901 100644 --- a/src/net/session/handlers/social/friends.rs +++ b/src/net/session/handlers/social/friends.rs @@ -1,13 +1,12 @@ use crate::net::wire; use anyhow::Result; -use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand}; +use crate::net::{framing, payloads::*, types::NetCommand}; pub async fn handle_cmd( cmd: NetCommand, stream: &mut (impl tokio::io::AsyncWrite + Unpin), seq: &mut u32, - crypto: &SessionCrypto, ) -> Result<()> { match cmd { NetCommand::PresenceUpdate { @@ -21,44 +20,43 @@ pub async fn handle_cmd( activity_type: activity, activity_text, })?; - framing::io::write_encrypted(stream, PID_PRESENCE_UPDATE, seq, &payload, crypto) - .await?; + framing::write(stream, PID_PRESENCE_UPDATE, seq, &payload).await?; } NetCommand::FriendRequest { target_user_id } => { let payload = wire::encode(&FriendRequestPayload { to_user_id: target_user_id, })?; - framing::io::write_encrypted(stream, PID_FRIEND_REQUEST, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_REQUEST, seq, &payload).await?; } NetCommand::FriendAccept { user_id } => { let payload = wire::encode(&FriendAcceptPayload { from_user_id: user_id, })?; - framing::io::write_encrypted(stream, PID_FRIEND_ACCEPT, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_ACCEPT, seq, &payload).await?; } NetCommand::FriendDecline { user_id } => { let payload = wire::encode(&FriendDeclinePayload { from_user_id: user_id, })?; - framing::io::write_encrypted(stream, PID_FRIEND_DECLINE, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_DECLINE, seq, &payload).await?; } NetCommand::FriendRemove { user_id } => { let payload = wire::encode(&FriendRemovePayload { user_id })?; - framing::io::write_encrypted(stream, PID_FRIEND_REMOVE, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_REMOVE, seq, &payload).await?; } NetCommand::FriendList => { - framing::io::write_encrypted(stream, PID_FRIEND_LIST, seq, b"", crypto).await?; + framing::write(stream, PID_FRIEND_LIST, seq, b"").await?; } NetCommand::BlockUser { user_id } => { let payload = wire::encode(&BlockUserPayload { user_id })?; - framing::io::write_encrypted(stream, PID_BLOCK_USER, seq, &payload, crypto).await?; + framing::write(stream, PID_BLOCK_USER, seq, &payload).await?; } NetCommand::UnblockUser { user_id } => { let payload = wire::encode(&UnblockUserPayload { user_id })?; - framing::io::write_encrypted(stream, PID_UNBLOCK_USER, seq, &payload, crypto).await?; + framing::write(stream, PID_UNBLOCK_USER, seq, &payload).await?; } NetCommand::BlockList => { - framing::io::write_encrypted(stream, PID_BLOCK_LIST, seq, b"", crypto).await?; + framing::write(stream, PID_BLOCK_LIST, seq, b"").await?; } _ => {} } diff --git a/src/net/session/handlers/social/guild.rs b/src/net/session/handlers/social/guild.rs index a4d38b7..1c316d0 100644 --- a/src/net/session/handlers/social/guild.rs +++ b/src/net/session/handlers/social/guild.rs @@ -1,25 +1,24 @@ use crate::net::wire; use anyhow::Result; -use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand}; +use crate::net::{framing, payloads::*, types::NetCommand}; pub async fn handle_cmd( cmd: NetCommand, stream: &mut (impl tokio::io::AsyncWrite + Unpin), seq: &mut u32, - crypto: &SessionCrypto, ) -> Result<()> { match cmd { NetCommand::GuildCreate { name } => { let payload = wire::encode(&GuildCreatePayload { name })?; - framing::io::write_encrypted(stream, PID_GUILD_CREATE, seq, &payload, crypto).await?; + framing::write(stream, PID_GUILD_CREATE, seq, &payload).await?; } NetCommand::GuildDelete { guild_id } => { let payload = wire::encode(&GuildDeletePayload { guild_id })?; - framing::io::write_encrypted(stream, PID_GUILD_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_GUILD_DELETE, seq, &payload).await?; } NetCommand::GuildList => { - framing::io::write_encrypted(stream, PID_GUILD_LIST, seq, b"", crypto).await?; + framing::write(stream, PID_GUILD_LIST, seq, b"").await?; } NetCommand::GuildJoin { guild_id, @@ -30,12 +29,10 @@ pub async fn handle_cmd( code, ..Default::default() })?; - framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto) - .await?; + framing::write(stream, PID_INVITE_ACCEPT, seq, &payload).await?; } else { let payload = wire::encode(&GuildJoinPayload { guild_id })?; - framing::io::write_encrypted(stream, PID_GUILD_MEMBER_JOIN, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_MEMBER_JOIN, seq, &payload).await?; } } NetCommand::GuildLeave { guild_id } => { @@ -43,8 +40,7 @@ pub async fn handle_cmd( guild_id, user_id: String::new(), })?; - framing::io::write_encrypted(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload).await?; } NetCommand::InviteCreate { guild_id, @@ -56,14 +52,14 @@ pub async fn handle_cmd( max_uses, expires_in_seconds, })?; - framing::io::write_encrypted(stream, PID_INVITE_CREATE, seq, &payload, crypto).await?; + framing::write(stream, PID_INVITE_CREATE, seq, &payload).await?; } NetCommand::InviteAccept { code } => { let payload = wire::encode(&InviteAcceptPayload { code, ..Default::default() })?; - framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto).await?; + framing::write(stream, PID_INVITE_ACCEPT, seq, &payload).await?; } NetCommand::InviteDelete { guild_id, @@ -73,7 +69,7 @@ pub async fn handle_cmd( guild_id, invite_id, })?; - framing::io::write_encrypted(stream, PID_INVITE_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_INVITE_DELETE, seq, &payload).await?; } NetCommand::RoleCreate { guild_id, @@ -88,32 +84,23 @@ pub async fn handle_cmd( permissions, id: String::new(), })?; - framing::io::write_encrypted(stream, PID_ROLE_CREATE, seq, &payload, crypto).await?; + framing::write(stream, PID_ROLE_CREATE, seq, &payload).await?; } NetCommand::RoleDelete { guild_id, role_id } => { let payload = wire::encode(&RoleDeletePayload { guild_id, role_id })?; - framing::io::write_encrypted(stream, PID_ROLE_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_ROLE_DELETE, seq, &payload).await?; } NetCommand::GuildMemberKick { guild_id, user_id } => { let payload = wire::encode(&GuildMemberKickPayload { guild_id, user_id })?; - framing::io::write_encrypted(stream, PID_GUILD_MEMBER_KICK, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_MEMBER_KICK, seq, &payload).await?; } NetCommand::GuildAuditLogFetch { guild_id, limit } => { let payload = wire::encode(&GuildAuditLogFetchPayload { guild_id, limit })?; - framing::io::write_encrypted(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload).await?; } NetCommand::GuildMemberListFetch { guild_id } => { let payload = wire::encode(&GuildMemberListFetchPayload { guild_id })?; - framing::io::write_encrypted( - stream, - PID_GUILD_MEMBER_LIST_FETCH, - seq, - &payload, - crypto, - ) - .await?; + framing::write(stream, PID_GUILD_MEMBER_LIST_FETCH, seq, &payload).await?; } NetCommand::GuildRoleAssign { guild_id, @@ -125,8 +112,7 @@ pub async fn handle_cmd( user_id, role_id, })?; - framing::io::write_encrypted(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload).await?; } NetCommand::GuildRoleUnassign { guild_id, @@ -138,13 +124,11 @@ pub async fn handle_cmd( user_id, role_id, })?; - framing::io::write_encrypted(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload).await?; } NetCommand::GuildRoleListFetch { guild_id } => { let payload = wire::encode(&GuildRoleListFetchPayload { guild_id })?; - framing::io::write_encrypted(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload).await?; } _ => {} } diff --git a/src/net/session/handlers/social/mod.rs b/src/net/session/handlers/social/mod.rs index 25f8a1e..bc64d2e 100644 --- a/src/net/session/handlers/social/mod.rs +++ b/src/net/session/handlers/social/mod.rs @@ -5,7 +5,7 @@ use crate::net::wire; use anyhow::Result; use crate::identity::Identity; -use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand}; +use crate::net::{framing, payloads::*, types::NetCommand}; use super::core::now_ms; @@ -13,29 +13,14 @@ pub async fn handle_cmd( cmd: NetCommand, stream: &mut (impl tokio::io::AsyncWrite + Unpin), seq: &mut u32, - crypto: &SessionCrypto, identity: &Identity, ) -> Result<()> { match cmd { NetCommand::MediaControl(message) => { - framing::io::write_encrypted( - stream, - PID_MEDIA_CONTROL, - seq, - &wire::encode(&message)?, - crypto, - ) - .await?; + framing::write(stream, PID_MEDIA_CONTROL, seq, &wire::encode(&message)?).await?; } NetCommand::Webhook { operation, request } => { - framing::io::write_encrypted( - stream, - operation.packet_id(), - seq, - &wire::encode(&request)?, - crypto, - ) - .await?; + framing::write(stream, operation.packet_id(), seq, &wire::encode(&request)?).await?; } cmd @ (NetCommand::GuildCreate { .. } | NetCommand::GuildDelete { .. } @@ -52,9 +37,7 @@ pub async fn handle_cmd( | NetCommand::GuildMemberListFetch { .. } | NetCommand::GuildRoleAssign { .. } | NetCommand::GuildRoleUnassign { .. } - | NetCommand::GuildRoleListFetch { .. }) => { - guild::handle_cmd(cmd, stream, seq, crypto).await? - } + | NetCommand::GuildRoleListFetch { .. }) => guild::handle_cmd(cmd, stream, seq).await?, cmd @ (NetCommand::PresenceUpdate { .. } | NetCommand::FriendRequest { .. } @@ -64,7 +47,7 @@ pub async fn handle_cmd( | NetCommand::FriendList | NetCommand::BlockUser { .. } | NetCommand::UnblockUser { .. } - | NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq, crypto).await?, + | NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq).await?, NetCommand::ReactionAdd { channel_id, @@ -77,8 +60,7 @@ pub async fn handle_cmd( emoji, user_id: String::new(), })?; - framing::io::write_encrypted(stream, PID_MESSAGE_REACTION_ADD, seq, &payload, crypto) - .await?; + framing::write(stream, PID_MESSAGE_REACTION_ADD, seq, &payload).await?; } NetCommand::ReactionRemove { channel_id, @@ -91,14 +73,7 @@ pub async fn handle_cmd( emoji, user_id: String::new(), })?; - framing::io::write_encrypted( - stream, - PID_MESSAGE_REACTION_REMOVE, - seq, - &payload, - crypto, - ) - .await?; + framing::write(stream, PID_MESSAGE_REACTION_REMOVE, seq, &payload).await?; } NetCommand::MessageEdit { channel_id, @@ -110,7 +85,7 @@ pub async fn handle_cmd( channel_id, content, })?; - framing::io::write_encrypted(stream, PID_MESSAGE_EDIT, seq, &payload, crypto).await?; + framing::write(stream, PID_MESSAGE_EDIT, seq, &payload).await?; } NetCommand::MessageDelete { channel_id, @@ -120,11 +95,11 @@ pub async fn handle_cmd( message_id, channel_id, })?; - framing::io::write_encrypted(stream, PID_MESSAGE_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_MESSAGE_DELETE, seq, &payload).await?; } NetCommand::DmStart { target_user_id } => { let payload = wire::encode(&DmStartPayload { target_user_id })?; - framing::io::write_encrypted(stream, PID_DM_START, seq, &payload, crypto).await?; + framing::write(stream, PID_DM_START, seq, &payload).await?; } NetCommand::DmSend { dm_id, content } => { let msg = DmMessagePayload { @@ -133,16 +108,15 @@ pub async fn handle_cmd( content, timestamp: now_ms(), }; - framing::io::write_encrypted(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?, crypto) - .await?; + framing::write(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?).await?; } NetCommand::TypingStart { channel_id } => { let payload = wire::encode(&TypingStart { channel_id })?; - framing::io::write_encrypted(stream, PID_TYPING_START, seq, &payload, crypto).await?; + framing::write(stream, PID_TYPING_START, seq, &payload).await?; } NetCommand::DmReadAck { dm_id } => { let payload = wire::encode(&crate::net::wire::DmReadAck { dm_id })?; - framing::io::write_encrypted(stream, PID_DM_READ_ACK, seq, &payload, crypto).await?; + framing::write(stream, PID_DM_READ_ACK, seq, &payload).await?; } NetCommand::DmSearch { dm_id, query } => { let payload = wire::encode(&DmHistoryPayload { @@ -151,7 +125,7 @@ pub async fn handle_cmd( search_query: if query.is_empty() { None } else { Some(query) }, limit: None, })?; - framing::io::write_encrypted(stream, PID_DM_HISTORY, seq, &payload, crypto).await?; + framing::write(stream, PID_DM_HISTORY, seq, &payload).await?; } NetCommand::E2eeDmKeyExchange { dm_id, @@ -161,19 +135,11 @@ pub async fn handle_cmd( dm_id, e2ee_public_key, })?; - framing::io::write_encrypted(stream, PID_E2EE_DM_KEY_EXCHANGE, seq, &payload, crypto) - .await?; + framing::write(stream, PID_E2EE_DM_KEY_EXCHANGE, seq, &payload).await?; } NetCommand::E2eeDmKeyExchangeAck { dm_id } => { let payload = wire::encode(&E2eeDmKeyExchangeAckPayload { dm_id })?; - framing::io::write_encrypted( - stream, - PID_E2EE_DM_KEY_EXCHANGE_ACK, - seq, - &payload, - crypto, - ) - .await?; + framing::write(stream, PID_E2EE_DM_KEY_EXCHANGE_ACK, seq, &payload).await?; } NetCommand::E2eeDmSend { dm_id, ciphertext } => { let msg = E2eeDmMessagePayload { @@ -182,14 +148,7 @@ pub async fn handle_cmd( ciphertext, timestamp: now_ms(), }; - framing::io::write_encrypted( - stream, - PID_E2EE_DM_MESSAGE, - seq, - &wire::encode(&msg)?, - crypto, - ) - .await?; + framing::write(stream, PID_E2EE_DM_MESSAGE, seq, &wire::encode(&msg)?).await?; } NetCommand::E2eeDmHistory { dm_id, limit } => { let payload = wire::encode(&E2eeDmHistoryPayload { @@ -197,8 +156,7 @@ pub async fn handle_cmd( messages: vec![], limit, })?; - framing::io::write_encrypted(stream, PID_E2EE_DM_HISTORY, seq, &payload, crypto) - .await?; + framing::write(stream, PID_E2EE_DM_HISTORY, seq, &payload).await?; } _ => {} } diff --git a/src/net/session/task.rs b/src/net/session/task.rs index ecb70b4..bd65546 100644 --- a/src/net/session/task.rs +++ b/src/net/session/task.rs @@ -3,6 +3,7 @@ use tokio::time::sleep; use tracing::{error, info}; use crate::identity::Identity; +use crate::net::trust::{TransportError, TrustStore}; use crate::net::types::{NetCommand, NetEvent}; use super::{ @@ -13,6 +14,7 @@ use super::{ pub async fn net_task( identity: Identity, + trust: TrustStore, mut cmd_rx: mpsc::Receiver, event_tx: mpsc::Sender, ) { @@ -71,6 +73,7 @@ pub async fn net_task( match session_loop( &identity, &session.address, + &trust, &mut session.channels, restored, &mut cmd_rx, @@ -97,7 +100,12 @@ pub async fn net_task( continue; } error!("session ended: {e}"); - let retry = session.auto_reconnect; + // Trust failures and protocol mismatches never improve by retrying. + let transport = e.downcast_ref::(); + if let Some(problem) = transport.and_then(TransportError::trust_problem) { + let _ = event_tx.send(NetEvent::TrustProblem(problem)).await; + } + let retry = session.auto_reconnect && transport.is_none(); let _ = event_tx .send(NetEvent::Disconnected { reason: e.to_string(), diff --git a/src/net/transport.rs b/src/net/transport.rs index 6e4f246..24d54e4 100644 --- a/src/net/transport.rs +++ b/src/net/transport.rs @@ -1,112 +1,509 @@ -//! TCP/TLS transport selection. TLS never falls back to plaintext after an error. -use anyhow::{Context, Result, bail}; +//! TLS 1.3 transport. There is no plaintext mode and no fallback after any error. +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result}; +use rustls::client::WebPkiServerVerifier; +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; +use rustls::{CertificateError, DigitallySignedStruct, SignatureScheme}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::TcpStream; +use super::trust::{ + ServerRecord, TransportError, TrustKind, TrustStore, parse_address, spki_fingerprint, +}; + pub trait AsyncStream: AsyncRead + AsyncWrite + Unpin + Send {} impl AsyncStream for T {} pub type Stream = Box; +/// ALPN protocol id required from the gateway. +pub const ALPN: &[u8] = b"vnox-lnex/3"; +/// TLS exporter label of the channel binding (must match the gateway). +pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding"; +/// Length of the exported channel binding. +pub const BINDING_LEN: usize = 32; + pub struct Connected { pub stream: Stream, pub peer: std::net::SocketAddr, + /// TLS exporter value of this connection, signed by both sides of the LNEx handshake. + pub binding: [u8; BINDING_LEN], + /// Trust store key (`host:port`). + pub trust_key: String, + /// Stored record at connect time (for the identity check). + pub record: Option, } -pub async fn connect(address: &str) -> Result { - Ok(connect_with_peer(address).await?.stream) + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Mode { + /// Certificate SPKI must equal the stored pin. + Pin, + /// Certificate must pass public WebPKI validation. + Ca, + /// Unknown server: finish the handshake to learn the fingerprint, send nothing. + Probe, } -pub async fn connect_with_peer(address: &str) -> Result { - let explicit_plain = address.starts_with("lnex://"); - let authority = address - .strip_prefix("lnexs://") - .or_else(|| address.strip_prefix("lnex://")) - .unwrap_or(address); - if authority.contains('/') - || authority.contains('@') - || authority.contains('?') - || authority.contains('#') - { - bail!("expected a server host and port"); + +#[derive(Default, Debug)] +struct Observed { + fingerprint: Option, + mismatch: bool, + ca_valid: bool, + ca_error: Option, +} + +#[derive(Debug)] +struct TrustVerifier { + mode: Mode, + pin: Option, + webpki: Arc, + algorithms: rustls::crypto::WebPkiSupportedAlgorithms, + observed: Arc>, +} + +impl TrustVerifier { + fn observe(&self, f: impl FnOnce(&mut Observed) -> R) -> R { + f(&mut self + .observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)) } - let (host, port) = if let Some(value) = authority.strip_prefix('[') { - let (host, tail) = value.split_once(']').context("invalid IPv6 address")?; - let port = if tail.is_empty() { - 7600 - } else { - tail.strip_prefix(':') - .context("invalid server address")? - .parse()? +} + +impl ServerCertVerifier for TrustVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> std::result::Result { + let fingerprint = spki_fingerprint(end_entity.as_ref()) + .map_err(|_| rustls::Error::InvalidCertificate(CertificateError::BadEncoding))?; + self.observe(|o| o.fingerprint = Some(fingerprint.clone())); + let public = || { + self.webpki.verify_server_cert( + end_entity, + intermediates, + server_name, + ocsp_response, + now, + ) }; - (host, port) - } else if let Some((host, port)) = authority.rsplit_once(':') { - (host, port.parse()?) - } else { - (authority, 7600) - }; - if host.is_empty() { - bail!("server host is empty"); + match self.mode { + Mode::Pin => { + if self.pin.as_deref() == Some(fingerprint.as_str()) { + Ok(ServerCertVerified::assertion()) + } else { + self.observe(|o| o.mismatch = true); + Err(rustls::Error::InvalidCertificate( + CertificateError::ApplicationVerificationFailure, + )) + } + } + Mode::Ca => public().inspect_err(|e| { + self.observe(|o| o.ca_error = Some(e.to_string())); + }), + Mode::Probe => { + // Accept only to complete the handshake; the caller drops the connection + // before any LNEx byte is sent unless the certificate is publicly valid. + if public().is_ok() { + self.observe(|o| o.ca_valid = true); + } + Ok(ServerCertVerified::assertion()) + } + } } - let tcp = TcpStream::connect((host, port)) + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms) + } + + fn supported_verify_schemes(&self) -> Vec { + self.algorithms.supported_schemes() + } +} + +/// Connect, verify and return the TLS stream plus the channel binding. +pub async fn connect(address: &str, trust: &TrustStore) -> Result { + Ok(connect_with_peer(address, trust).await?.stream) +} + +pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result { + let parsed = parse_address(address)?; + let tcp = TcpStream::connect((parsed.host.as_str(), parsed.port)) .await .context("connect to gateway")?; tcp.set_nodelay(true)?; let peer = tcp.peer_addr()?; - let loopback_host = host.eq_ignore_ascii_case("localhost") - || host - .parse::() - .is_ok_and(|ip| ip.is_loopback()); - let plain = explicit_plain || (!address.starts_with("lnexs://") && loopback_host); - if plain { - if !tcp.peer_addr()?.ip().is_loopback() { - bail!("plaintext LNEx is restricted to loopback development; use lnexs://"); - } - return Ok(Connected { - stream: Box::new(tcp), - peer, - }); - } + let record = trust.get(&parsed.key); + let (mode, pin) = match &record { + Some(r) if r.trust == TrustKind::Pin => (Mode::Pin, r.spki_sha256.clone()), + Some(_) => (Mode::Ca, None), + None => (Mode::Probe, None), + }; + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); - let config = rustls::ClientConfig::builder_with_provider( - rustls::crypto::aws_lc_rs::default_provider().into(), - ) - .with_protocol_versions(&[&rustls::version::TLS13])? - .with_root_certificates(roots) - .with_no_client_auth(); - let server_name = rustls::pki_types::ServerName::try_from(host.to_owned()) - .context("invalid TLS server name")?; - let tls = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config)) + let webpki = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone()) + .build() + .context("build public certificate verifier")?; + let observed = Arc::new(Mutex::new(Observed::default())); + let verifier = Arc::new(TrustVerifier { + mode, + pin, + webpki, + algorithms: provider.signature_verification_algorithms, + observed: observed.clone(), + }); + let mut config = rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13])? + .dangerous() + .with_custom_certificate_verifier(verifier) + .with_no_client_auth(); + config.alpn_protocols = vec![ALPN.to_vec()]; + let server_name = + ServerName::try_from(parsed.host.clone()).context("invalid TLS server name")?; + let tls = match tokio_rustls::TlsConnector::from(Arc::new(config)) .connect(server_name, tcp) .await - .context("TLS certificate/connection verification failed")?; + { + Ok(tls) => tls, + Err(error) => { + return Err(map_tls_error( + error, + &parsed.key, + mode, + record.as_ref().and_then(|r| r.spki_sha256.as_deref()), + &observed, + )); + } + }; + let seen = observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if mode == Mode::Probe { + if seen.ca_valid { + // A publicly valid certificate for this host name: remember it, no prompt. + drop(seen); + if let Err(error) = trust.trust_public_ca(&parsed.key) { + tracing::warn!(%error, "could not save trust record"); + } + } else { + let fingerprint = seen.fingerprint.clone().unwrap_or_default(); + return Err(TransportError::UntrustedServer { + address: parsed.key, + fingerprint, + } + .into()); + } + } else { + drop(seen); + } + let connection = tls.get_ref().1; + if connection.protocol_version() != Some(rustls::ProtocolVersion::TLSv1_3) + || connection.alpn_protocol() != Some(ALPN) + { + return Err(TransportError::ProtocolMismatch( + "The server did not negotiate TLS 1.3 with LNEx v3. Ask its owner to update the server." + .into(), + ) + .into()); + } + let binding = connection + .export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None) + .context("TLS exporter unavailable")?; Ok(Connected { stream: Box::new(tls), peer, + binding, + record: trust.get(&parsed.key), + trust_key: parsed.key, }) } +const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server or a non-VNOX port, ask its owner to update it."; + +fn map_tls_error( + error: std::io::Error, + key: &str, + mode: Mode, + pin: Option<&str>, + observed: &Mutex, +) -> anyhow::Error { + let seen = observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if mode == Mode::Pin && seen.mismatch { + return TransportError::FingerprintChanged { + address: key.to_string(), + expected: pin.unwrap_or_default().to_string(), + actual: seen.fingerprint.clone().unwrap_or_default(), + } + .into(); + } + if mode == Mode::Ca + && let Some(reason) = &seen.ca_error + { + return TransportError::CertificateInvalid { + address: key.to_string(), + reason: reason.clone(), + } + .into(); + } + let rustls_error = error + .get_ref() + .and_then(|inner| inner.downcast_ref::()); + match rustls_error { + Some( + rustls::Error::InvalidMessage(_) + | rustls::Error::PeerIncompatible(_) + | rustls::Error::PeerMisbehaved(_), + ) => TransportError::ProtocolMismatch(NOT_TLS13.into()).into(), + Some(rustls::Error::AlertReceived( + rustls::AlertDescription::ProtocolVersion + | rustls::AlertDescription::NoApplicationProtocol + | rustls::AlertDescription::HandshakeFailure + | rustls::AlertDescription::InsufficientSecurity, + )) => TransportError::ProtocolMismatch(NOT_TLS13.into()).into(), + _ if error.kind() == std::io::ErrorKind::UnexpectedEof => { + TransportError::ProtocolMismatch(NOT_TLS13.into()).into() + } + _ => anyhow::Error::new(error).context("TLS handshake failed"), + } +} + #[cfg(test)] mod tests { use super::*; - use tokio::io::AsyncReadExt; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + struct TestServer { + port: u16, + fingerprint: String, + /// Application bytes received per connection, and the server side exporter value. + received: tokio::sync::mpsc::UnboundedReceiver<(Vec, Option<[u8; BINDING_LEN]>)>, + task: tokio::task::JoinHandle<()>, + } + impl Drop for TestServer { + fn drop(&mut self) { + self.task.abort(); + } + } + + async fn serve( + versions: &[&'static rustls::SupportedProtocolVersion], + alpn: bool, + ) -> TestServer { + let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); + let fingerprint = spki_fingerprint(certified.cert.der().as_ref()).unwrap(); + let key = rustls::pki_types::PrivateKeyDer::try_from(certified.signing_key.serialize_der()) + .unwrap(); + let mut config = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::aws_lc_rs::default_provider(), + )) + .with_protocol_versions(versions) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![certified.cert.der().clone()], key) + .unwrap(); + if alpn { + config.alpn_protocols = vec![ALPN.to_vec()]; + } + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (sender, received) = tokio::sync::mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + loop { + let Ok((tcp, _)) = listener.accept().await else { + return; + }; + let acceptor = acceptor.clone(); + let sender = sender.clone(); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(tcp).await else { + return; + }; + let binding = tls + .get_ref() + .1 + .export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None) + .ok(); + let mut data = Vec::new(); + let _ = tls.read_to_end(&mut data).await; + let _ = sender.send((data, binding)); + }); + } + }); + TestServer { + port, + fingerprint, + received, + task, + } + } + + fn error_of(result: Result) -> TransportError { + match result { + Ok(_) => panic!("connection must not succeed"), + Err(error) => error + .downcast_ref::() + .cloned() + .unwrap_or_else(|| panic!("not a transport error: {error:#}")), + } + } + + async fn quiet(server: &mut TestServer) -> bool { + // A rejected connection must not have carried a single application byte. + match tokio::time::timeout( + std::time::Duration::from_millis(300), + server.received.recv(), + ) + .await + { + Ok(Some((data, _))) => data.is_empty(), + _ => true, + } + } + #[tokio::test] - async fn tls_failure_never_retries_plaintext() { + async fn unknown_self_signed_server_needs_confirmation_and_receives_nothing() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let address = format!("127.0.0.1:{}", server.port); + let error = error_of(connect_with_peer(&address, &trust).await); + assert_eq!( + error, + TransportError::UntrustedServer { + address: address.clone(), + fingerprint: server.fingerprint.clone() + } + ); + assert!(trust.get(&address).is_none(), "no implicit trust"); + assert!(quiet(&mut server).await); + } + + #[tokio::test] + async fn pinned_fingerprint_connects_and_shares_the_channel_binding() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + trust.pin(&key, &server.fingerprint).unwrap(); + // The lnex:// and lnexs:// schemes are both TLS and map to the same record. + let mut connected = connect_with_peer(&format!("lnex://{key}"), &trust) + .await + .unwrap(); + connected.stream.write_all(b"hello").await.unwrap(); + connected.stream.shutdown().await.unwrap(); + let (data, server_binding) = server.received.recv().await.unwrap(); + assert_eq!(data, b"hello"); + assert_eq!(server_binding, Some(connected.binding)); + assert_ne!(connected.binding, [0u8; BINDING_LEN]); + } + + #[tokio::test] + async fn changed_fingerprint_is_rejected_without_application_data() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + let trusted_before = "ab".repeat(32); + trust.pin(&key, &trusted_before).unwrap(); + let error = error_of(connect_with_peer(&key, &trust).await); + assert_eq!( + error, + TransportError::FingerprintChanged { + address: key.clone(), + expected: trusted_before.clone(), + actual: server.fingerprint.clone(), + } + ); + assert!(error.trust_problem().is_some()); + assert_eq!( + trust.get(&key).unwrap().spki_sha256.as_deref(), + Some(trusted_before.as_str()), + "the stored pin is never replaced automatically" + ); + assert!(quiet(&mut server).await); + } + + #[tokio::test] + async fn public_ca_trust_never_degrades_to_trust_on_first_use() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + trust.trust_public_ca(&key).unwrap(); + let error = error_of(connect_with_peer(&key, &trust).await); + assert!(matches!(error, TransportError::CertificateInvalid { .. })); + assert!(error.trust_problem().is_none()); + assert!(quiet(&mut server).await); + } + + #[tokio::test] + async fn tls12_only_server_is_rejected_with_a_clear_error() { + let server = serve(&[&rustls::version::TLS12], true).await; + let trust = TrustStore::in_memory(); + trust + .pin(&format!("127.0.0.1:{}", server.port), &server.fingerprint) + .unwrap(); + let error = + error_of(connect_with_peer(&format!("127.0.0.1:{}", server.port), &trust).await); + assert!(matches!(&error, TransportError::ProtocolMismatch(m) if m.contains("TLS 1.3"))); + } + + #[tokio::test] + async fn server_without_lnex_alpn_is_rejected() { + let server = serve(&[&rustls::version::TLS13], false).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + trust.pin(&key, &server.fingerprint).unwrap(); + let error = error_of(connect_with_peer(&key, &trust).await); + assert!(matches!(error, TransportError::ProtocolMismatch(_))); + } + + #[tokio::test] + async fn old_plaintext_v2_server_is_reported_and_never_retried() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let task = tokio::spawn(async move { let (mut stream, _) = listener.accept().await.unwrap(); + // An LNEx v2 gateway speaks first: HELLO frame header (id 0x0001). + stream + .write_all(&[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4]) + .await + .unwrap(); let first = stream.read_u8().await.unwrap(); assert_eq!( first, 22, - "first record must be a TLS handshake, never LNEx plaintext" + "the client must start a TLS handshake, never LNEx plaintext" ); drop(stream); assert!( - tokio::time::timeout(std::time::Duration::from_millis(30), listener.accept()) + tokio::time::timeout(std::time::Duration::from_millis(100), listener.accept()) .await .is_err(), - "certificate/handshake errors must not cause a downgrade reconnect" + "no downgrade reconnect after a failed TLS handshake" ); }); - assert!(connect(&format!("lnexs://{address}")).await.is_err()); + let trust = TrustStore::in_memory(); + let error = error_of(connect_with_peer(&format!("lnexs://{address}"), &trust).await); + assert!(matches!(&error, TransportError::ProtocolMismatch(m) if m.contains("TLS 1.3"))); task.await.unwrap(); } } diff --git a/src/net/trust.rs b/src/net/trust.rs new file mode 100644 index 0000000..1f01a29 --- /dev/null +++ b/src/net/trust.rs @@ -0,0 +1,569 @@ +//! Server trust for the TLS 1.3 control connection (LNEx v3). +//! +//! Model (see `VNOX-Server/docs/02-protocol/tls.md`): +//! * a stored **pin** (SHA-256 of the certificate SubjectPublicKeyInfo) always wins, +//! * without a record a certificate valid for the host name under the bundled public roots is +//! accepted (`ca` trust), +//! * otherwise the user must confirm the fingerprint once (trust on first use), +//! * a changed fingerprint is a hard error, never an automatic downgrade. +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Default gateway port. +pub const DEFAULT_PORT: u16 = 7600; + +/// Why a connection was stopped for trust reasons. Downcast from `anyhow::Error`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TransportError { + /// No trust record and no valid public certificate: the user must confirm `fingerprint`. + UntrustedServer { + address: String, + fingerprint: String, + }, + /// The pinned fingerprint of a known server changed. + FingerprintChanged { + address: String, + expected: String, + actual: String, + }, + /// The server authenticated with another Ed25519 identity than the stored one. + IdentityChanged { + address: String, + expected: String, + actual: String, + }, + /// A server marked as CA trusted no longer presents a valid public certificate. + CertificateInvalid { address: String, reason: String }, + /// The peer does not speak TLS 1.3 / LNEx v3. + ProtocolMismatch(String), +} + +impl std::fmt::Display for TransportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UntrustedServer { + address, + fingerprint, + } => write!( + f, + "server {address} is not trusted yet (fingerprint {fingerprint})" + ), + Self::FingerprintChanged { + address, + expected, + actual, + } => write!( + f, + "certificate fingerprint of {address} changed: expected {expected}, received {actual}" + ), + Self::IdentityChanged { + address, + expected, + actual, + } => write!( + f, + "server identity of {address} changed: expected {expected}, received {actual}" + ), + Self::CertificateInvalid { address, reason } => { + write!(f, "certificate of {address} is not valid: {reason}") + } + Self::ProtocolMismatch(message) => f.write_str(message), + } + } +} +impl std::error::Error for TransportError {} + +/// A trust decision the UI has to present. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TrustProblem { + Untrusted { + address: String, + fingerprint: String, + }, + FingerprintChanged { + address: String, + expected: String, + actual: String, + }, + IdentityChanged { + address: String, + expected: String, + actual: String, + }, +} + +impl TransportError { + /// The trust prompt for this error, if the user can act on it. + pub fn trust_problem(&self) -> Option { + match self.clone() { + Self::UntrustedServer { + address, + fingerprint, + } => Some(TrustProblem::Untrusted { + address, + fingerprint, + }), + Self::FingerprintChanged { + address, + expected, + actual, + } => Some(TrustProblem::FingerprintChanged { + address, + expected, + actual, + }), + Self::IdentityChanged { + address, + expected, + actual, + } => Some(TrustProblem::IdentityChanged { + address, + expected, + actual, + }), + _ => None, + } + } +} + +/// How a server is trusted. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TrustKind { + /// Certificate SPKI SHA-256 must equal `spki_sha256`. + Pin, + /// Certificate must validate for the host name under the bundled public roots. + Ca, +} + +/// Stored trust for one `host:port`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServerRecord { + pub trust: TrustKind, + /// Lower-case hex SHA-256 of the certificate SPKI (only for `pin`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spki_sha256: Option, + /// Lower-case hex Ed25519 server identity, stored after the first authenticated handshake. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identity: Option, + pub first_seen: i64, +} + +#[derive(Default, Serialize, Deserialize)] +struct FileFormat { + version: u32, + servers: BTreeMap, +} + +struct Inner { + path: Option, + servers: BTreeMap, +} + +/// Thread safe, file backed trust store (`/vnox/known_servers.json`). +#[derive(Clone)] +pub struct TrustStore { + inner: Arc>, +} + +/// A parsed server address. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServerAddress { + pub host: String, + pub port: u16, + /// Normalised `host:port` key used by the trust store. + pub key: String, +} + +/// Parse `host`, `host:port`, `[v6]:port`, optionally prefixed with `lnexs://` or `lnex://`. +/// Both schemes mean TLS 1.3; plaintext does not exist anymore. +pub fn parse_address(address: &str) -> Result { + let authority = address + .strip_prefix("lnexs://") + .or_else(|| address.strip_prefix("lnex://")) + .unwrap_or(address) + .trim(); + if authority.contains('/') + || authority.contains('@') + || authority.contains('?') + || authority.contains('#') + || authority.contains(char::is_whitespace) + { + bail!("expected a server host and port"); + } + let (host, port) = if let Some(value) = authority.strip_prefix('[') { + let (host, tail) = value.split_once(']').context("invalid IPv6 address")?; + let port = if tail.is_empty() { + DEFAULT_PORT + } else { + tail.strip_prefix(':') + .context("invalid server address")? + .parse()? + }; + (host, port) + } else if let Some((host, port)) = authority.rsplit_once(':') { + (host, port.parse()?) + } else { + (authority, DEFAULT_PORT) + }; + if host.is_empty() { + bail!("server host is empty"); + } + let host = host.to_ascii_lowercase(); + let key = if host.contains(':') { + format!("[{host}]:{port}") + } else { + format!("{host}:{port}") + }; + Ok(ServerAddress { host, port, key }) +} + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +impl TrustStore { + /// `/vnox/known_servers.json`. + pub fn default_path() -> Option { + dirs::config_dir().map(|p| p.join("vnox").join("known_servers.json")) + } + + /// Load the default store. A missing or unreadable file yields an empty store: the user + /// is asked again, trust is never granted implicitly. + pub fn load_default() -> Self { + match Self::default_path() { + Some(path) => Self::load(path), + None => Self::in_memory(), + } + } + + pub fn load(path: PathBuf) -> Self { + let servers = match std::fs::read(&path) { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(file) if file.version == 1 => file.servers, + Ok(file) => { + tracing::warn!(version = file.version, "unsupported trust store version"); + BTreeMap::new() + } + Err(error) => { + tracing::warn!(%error, "trust store is corrupt, starting empty"); + BTreeMap::new() + } + }, + Err(_) => BTreeMap::new(), + }; + Self { + inner: Arc::new(Mutex::new(Inner { + path: Some(path), + servers, + })), + } + } + + /// A store that is never written to disk (tests, headless tools). + pub fn in_memory() -> Self { + Self { + inner: Arc::new(Mutex::new(Inner { + path: None, + servers: BTreeMap::new(), + })), + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + pub fn get(&self, key: &str) -> Option { + self.lock().servers.get(key).cloned() + } + + /// Trust exactly this certificate fingerprint for `key` (replaces any previous record). + pub fn pin(&self, key: &str, spki_sha256: &str) -> Result<()> { + let fingerprint = normalize_fingerprint(spki_sha256)?; + let mut inner = self.lock(); + inner.servers.insert( + key.to_string(), + ServerRecord { + trust: TrustKind::Pin, + spki_sha256: Some(fingerprint), + identity: None, + first_seen: now_secs(), + }, + ); + Self::save(&inner) + } + + /// Remember that `key` presented a certificate valid under the public roots. + pub fn trust_public_ca(&self, key: &str) -> Result<()> { + let mut inner = self.lock(); + if inner.servers.contains_key(key) { + return Ok(()); + } + inner.servers.insert( + key.to_string(), + ServerRecord { + trust: TrustKind::Ca, + spki_sha256: None, + identity: None, + first_seen: now_secs(), + }, + ); + Self::save(&inner) + } + + /// Store the authenticated server identity once. + pub fn set_identity(&self, key: &str, identity_hex: &str) -> Result<()> { + let mut inner = self.lock(); + let Some(record) = inner.servers.get_mut(key) else { + return Ok(()); + }; + if record.identity.as_deref() == Some(identity_hex) { + return Ok(()); + } + if record.identity.is_some() { + bail!("refusing to overwrite the stored server identity"); + } + record.identity = Some(identity_hex.to_string()); + Self::save(&inner) + } + + /// Delete the record. The next connection starts a fresh trust decision. + pub fn forget(&self, key: &str) -> Result<()> { + let mut inner = self.lock(); + if inner.servers.remove(key).is_some() { + Self::save(&inner)?; + } + Ok(()) + } + + fn save(inner: &Inner) -> Result<()> { + let Some(path) = &inner.path else { + return Ok(()); + }; + let parent = path.parent().context("trust store path has no parent")?; + std::fs::create_dir_all(parent)?; + let bytes = serde_json::to_vec_pretty(&FileFormat { + version: 1, + servers: inner.servers.clone(), + })?; + write_private(path, &bytes) + } +} + +fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { + use std::io::Write; + let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let result = (|| -> Result<()> { + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&temporary, path)?; + Ok(()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result +} + +/// Accept `ab:cd:...`, upper or lower case, with optional `sha256:` prefix; return 64 lower-case hex. +pub fn normalize_fingerprint(value: &str) -> Result { + let cleaned: String = value + .trim() + .trim_start_matches("sha256:") + .chars() + .filter(|c| *c != ':' && !c.is_whitespace()) + .collect::() + .to_ascii_lowercase(); + if cleaned.len() != 64 || !cleaned.chars().all(|c| c.is_ascii_hexdigit()) { + bail!("a SHA-256 fingerprint is 64 hexadecimal characters"); + } + Ok(cleaned) +} + +/// `ab cd ef ...` grouped for display (pairs separated by colons). +pub fn display_fingerprint(hex_fingerprint: &str) -> String { + hex_fingerprint + .as_bytes() + .chunks(2) + .map(|pair| String::from_utf8_lossy(pair).to_ascii_uppercase()) + .collect::>() + .join(":") +} + +fn read_tlv(data: &[u8]) -> Result<(u8, usize, usize)> { + let tag = *data.first().context("truncated DER")?; + let first = *data.get(1).context("truncated DER")?; + let (header, length) = if first & 0x80 == 0 { + (2usize, first as usize) + } else { + let count = (first & 0x7F) as usize; + if count == 0 || count > 4 { + bail!("unsupported DER length"); + } + let bytes = data.get(2..2 + count).context("truncated DER")?; + ( + 2 + count, + bytes.iter().fold(0usize, |acc, b| (acc << 8) | *b as usize), + ) + }; + if data.len() < header + length { + bail!("truncated DER"); + } + Ok((tag, header, length)) +} + +/// The complete SubjectPublicKeyInfo SEQUENCE of an X.509 certificate. +pub fn spki_der(cert_der: &[u8]) -> Result<&[u8]> { + let (tag, header, length) = read_tlv(cert_der)?; + anyhow::ensure!(tag == 0x30, "certificate is not a SEQUENCE"); + let tbs_all = &cert_der[header..header + length]; + let (tag, header, length) = read_tlv(tbs_all)?; + anyhow::ensure!(tag == 0x30, "tbsCertificate is not a SEQUENCE"); + let mut rest = &tbs_all[header..header + length]; + // [version], serial, signature, issuer, validity, subject precede the SPKI. + let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 }; + while skip > 0 { + let (_, header, length) = read_tlv(rest)?; + rest = &rest[header + length..]; + skip -= 1; + } + let (tag, header, length) = read_tlv(rest)?; + anyhow::ensure!(tag == 0x30, "SubjectPublicKeyInfo is not a SEQUENCE"); + Ok(&rest[..header + length]) +} + +/// Lower-case hex SHA-256 over the certificate SPKI DER. +pub fn spki_fingerprint(cert_der: &[u8]) -> Result { + Ok(hex::encode(Sha256::digest(spki_der(cert_der)?))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_path() -> PathBuf { + std::env::temp_dir() + .join(format!("vnox-trust-{}", uuid::Uuid::new_v4())) + .join("known_servers.json") + } + + #[test] + fn address_forms_are_normalised() { + assert_eq!( + parse_address("Example.ORG").unwrap().key, + "example.org:7600" + ); + assert_eq!( + parse_address("lnexs://example.org:7700").unwrap().key, + "example.org:7700" + ); + assert_eq!(parse_address("lnex://[::1]").unwrap().key, "[::1]:7600"); + assert_eq!(parse_address("127.0.0.1:1").unwrap().port, 1); + for bad in ["", "host/path", "user@host", "host?x", "host#x", "a b"] { + assert!(parse_address(bad).is_err(), "{bad}"); + } + } + + #[test] + fn fingerprint_normalisation_and_display() { + let hex64 = "ab".repeat(32); + let colons = hex64 + .as_bytes() + .chunks(2) + .map(|c| String::from_utf8_lossy(c).to_string()) + .collect::>() + .join(":") + .to_ascii_uppercase(); + assert_eq!(normalize_fingerprint(&colons).unwrap(), hex64); + assert_eq!( + normalize_fingerprint(&format!("sha256:{hex64}")).unwrap(), + hex64 + ); + assert!(normalize_fingerprint("abcd").is_err()); + assert!(normalize_fingerprint(&"zz".repeat(32)).is_err()); + assert_eq!(display_fingerprint(&hex64), colons); + } + + #[test] + fn spki_fingerprint_of_ed25519_certificate_is_hash_of_fixed_prefix_and_key() { + let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap(); + let cert = rcgen::CertificateParams::new(vec!["x.example".into()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let mut spki = vec![ + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, + ]; + spki.extend_from_slice(key.public_key_raw()); + assert_eq!( + spki_fingerprint(cert.der().as_ref()).unwrap(), + hex::encode(Sha256::digest(&spki)) + ); + assert!(spki_fingerprint(b"junk").is_err()); + } + + #[test] + fn records_persist_with_private_permissions_and_forget_works() { + let path = temp_path(); + let store = TrustStore::load(path.clone()); + let fingerprint = "cd".repeat(32); + store.pin("h:7600", &fingerprint).unwrap(); + store.set_identity("h:7600", &"11".repeat(32)).unwrap(); + // The identity of a known server can never be silently replaced. + assert!(store.set_identity("h:7600", &"22".repeat(32)).is_err()); + let reloaded = TrustStore::load(path.clone()); + let record = reloaded.get("h:7600").unwrap(); + assert_eq!(record.trust, TrustKind::Pin); + assert_eq!(record.spki_sha256.as_deref(), Some(fingerprint.as_str())); + assert_eq!(record.identity.as_deref(), Some("11".repeat(32).as_str())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + reloaded.forget("h:7600").unwrap(); + assert!(TrustStore::load(path.clone()).get("h:7600").is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn corrupt_store_starts_empty_instead_of_trusting() { + let path = temp_path(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"{not json").unwrap(); + let store = TrustStore::load(path.clone()); + assert!(store.get("h:7600").is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn public_ca_record_is_not_overwritten_and_pin_rejects_bad_hex() { + let store = TrustStore::in_memory(); + store.trust_public_ca("h:1").unwrap(); + store.trust_public_ca("h:1").unwrap(); + assert_eq!(store.get("h:1").unwrap().trust, TrustKind::Ca); + assert!(store.pin("h:1", "nothex").is_err()); + } +} diff --git a/src/net/types/event.rs b/src/net/types/event.rs index 806035d..17851b5 100644 --- a/src/net/types/event.rs +++ b/src/net/types/event.rs @@ -20,6 +20,8 @@ pub enum NetEvent { reason: String, will_retry: bool, }, + /// The user has to decide about a server certificate (first use or changed fingerprint). + TrustProblem(crate::net::trust::TrustProblem), Reconnecting { attempt: u32, delay_secs: u64, diff --git a/src/ui/bridge.rs b/src/ui/bridge.rs index 9f5f3cd..e942eed 100644 --- a/src/ui/bridge.rs +++ b/src/ui/bridge.rs @@ -382,6 +382,30 @@ pub fn sync_connect(window: &MainWindow, state: &UiState) { ConnState::Connecting | ConnState::Reconnecting { .. } )); window.set_auto_reconnect(state.auto_reconnect); + { + use crate::ui::state::TrustPromptKind; + let (kind, address, received, expected) = match &state.trust_prompt { + None => (0, "", "", ""), + Some(prompt) => ( + match prompt.kind { + TrustPromptKind::FirstUse => 1, + TrustPromptKind::FingerprintChanged => 2, + TrustPromptKind::IdentityChanged => 3, + }, + prompt.address.as_str(), + prompt.received.as_str(), + prompt.expected.as_str(), + ), + }; + window.set_trust_kind(kind); + window.set_trust_address(SharedString::from(address)); + window.set_trust_received(SharedString::from( + vnox_client::net::trust::display_fingerprint(received), + )); + window.set_trust_expected(SharedString::from( + vnox_client::net::trust::display_fingerprint(expected), + )); + } if let ConnState::Connected { ref node_name, .. } = state.conn { window.set_node_name(SharedString::from(node_name.as_str())); } else if matches!(state.conn, ConnState::Disconnected) { diff --git a/src/ui/slint/connect.slint b/src/ui/slint/connect.slint index 6d0f3f4..7b5348e 100644 --- a/src/ui/slint/connect.slint +++ b/src/ui/slint/connect.slint @@ -16,6 +16,14 @@ export component ConnectScreen inherits Rectangle { callback remove-bookmark(string); callback add-bookmark(string); callback open-settings(); + // 0 none, 1 first use, 2 certificate fingerprint changed, 3 server identity changed + in property trust-kind: 0; + in property trust-address; + in property trust-received; + in property trust-expected; + callback trust-accept(); + callback trust-forget(); + callback trust-dismiss(); background: Theme.bg-base; VerticalLayout { padding: 32px; spacing: 22px; @@ -86,4 +94,50 @@ export component ConnectScreen inherits Rectangle { Rectangle { vertical-stretch: 1; } Text { text: @tr("Your server. Your community."); color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-alignment: center; } } + if root.trust-kind != 0 : Rectangle { + background: #000000a0; + TouchArea { } + HorizontalLayout { + Rectangle { horizontal-stretch: 1; } + VerticalLayout { + Rectangle { vertical-stretch: 1; } + Rectangle { + width: 560px; + height: trust-card.preferred-height; + background: Theme.bg-surface; border-radius: 14px; + border-width: 1px; border-color: root.trust-kind == 1 ? Theme.border : Theme.danger; + trust-card := VerticalLayout { + padding: 26px; spacing: 12px; alignment: start; + Text { + text: root.trust-kind == 1 ? @tr("Trust this server?") : root.trust-kind == 2 ? @tr("Server fingerprint changed") : @tr("Server identity changed"); + color: root.trust-kind == 1 ? Theme.text-primary : Theme.danger; + font-size: Math.max(11px, Theme.font-size * 1.375); font-weight: 600; wrap: word-wrap; + } + Text { + text: root.trust-kind == 1 + ? @tr("This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match.") + : root.trust-kind == 2 + ? @tr("The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.") + : @tr("The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."); + color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; + } + Text { text: @tr("Server address"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); } + Text { text: root.trust-address; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); wrap: word-wrap; } + if root.trust-kind != 1 : Text { text: @tr("Previously trusted fingerprint"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); } + if root.trust-kind != 1 : Text { text: root.trust-expected; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; } + Text { text: root.trust-kind == 1 ? @tr("Fingerprint (SHA-256)") : @tr("Received fingerprint"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); } + Text { text: root.trust-received; color: root.trust-kind == 1 ? Theme.accent : Theme.danger; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; } + HorizontalLayout { + spacing: 9px; alignment: end; + if root.trust-kind != 1 : ActionButton { text: @tr("Forget this server"); danger: true; clicked => { root.trust-forget(); } } + ActionButton { text: root.trust-kind == 1 ? @tr("Cancel") : @tr("Close"); clicked => { root.trust-dismiss(); } } + if root.trust-kind == 1 : ActionButton { text: @tr("Trust and connect"); active: true; clicked => { root.trust-accept(); } } + } + } + } + Rectangle { vertical-stretch: 1; } + } + Rectangle { horizontal-stretch: 1; } + } + } } diff --git a/src/ui/slint/main.slint b/src/ui/slint/main.slint index f6a4ac4..0cf3032 100644 --- a/src/ui/slint/main.slint +++ b/src/ui/slint/main.slint @@ -71,6 +71,11 @@ export component MainWindow inherits Window { in-out property connecting: false; in-out property auto-reconnect: false; in-out property node-name: ""; + // 0 none, 1 first use, 2 certificate fingerprint changed, 3 server identity changed + in-out property trust-kind: 0; + in-out property trust-address: ""; + in-out property trust-received: ""; + in-out property trust-expected: ""; in-out property identity-pubkey: ""; in-out property vault-enabled: false; @@ -155,6 +160,9 @@ export component MainWindow inherits Window { callback connect(string); callback remove-bookmark(string); callback add-bookmark(string); + callback trust-accept(); + callback trust-forget(); + callback trust-dismiss(); callback close-settings(); callback set-passphrase(string, string); callback remove-passphrase(); @@ -177,6 +185,13 @@ export component MainWindow inherits Window { connecting: root.connecting; auto-reconnect <=> root.auto-reconnect; node-name: root.node-name; + trust-kind: root.trust-kind; + trust-address: root.trust-address; + trust-received: root.trust-received; + trust-expected: root.trust-expected; + trust-accept => { root.trust-accept(); } + trust-forget => { root.trust-forget(); } + trust-dismiss => { root.trust-dismiss(); } open-settings => { root.open-settings(); } address-edited(text) => { root.address-edited(text); } auto-reconnect-changed(value) => { root.auto-reconnect-changed(value); } diff --git a/src/ui/state/default.rs b/src/ui/state/default.rs index 9b1bf93..5d52840 100644 --- a/src/ui/state/default.rs +++ b/src/ui/state/default.rs @@ -12,6 +12,7 @@ impl Default for UiState { bookmarks: default_bookmarks(), selected_bookmark: 0, status_msg: None, + trust_prompt: None, channels: Vec::new(), active_channel: None, messages: Default::default(), diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 0e83b31..53b8061 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -4,7 +4,7 @@ mod navigation; mod types; pub use models::{Channel, ChatMessage, DmConversation, FriendState, GuildState, NodeBookmark}; -pub use types::{ConnState, UiState, VoiceUiState}; +pub use types::{ConnState, TrustPrompt, TrustPromptKind, UiState, VoiceUiState}; use models::bookmark_label_from_address; diff --git a/src/ui/state/types.rs b/src/ui/state/types.rs index c4124a3..793de86 100644 --- a/src/ui/state/types.rs +++ b/src/ui/state/types.rs @@ -24,6 +24,25 @@ pub enum ConnState { }, } +/// A pending server trust decision (first use or blocked fingerprint change). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TrustPrompt { + pub kind: TrustPromptKind, + /// Trust store key, `host:port`. + pub address: String, + /// Lower-case hex value that was received. + pub received: String, + /// Lower-case hex value that was trusted before (changed fingerprint or identity). + pub expected: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrustPromptKind { + FirstUse, + FingerprintChanged, + IdentityChanged, +} + pub struct UiState { pub appearance: crate::ui::appearance::AppearancePreferences, pub conn: ConnState, @@ -31,6 +50,7 @@ pub struct UiState { pub bookmarks: Vec, pub selected_bookmark: usize, pub status_msg: Option, + pub trust_prompt: Option, pub channels: Vec, pub active_channel: Option, diff --git a/src/ui/update.rs b/src/ui/update.rs index b1ec3dc..c0b49f2 100644 --- a/src/ui/update.rs +++ b/src/ui/update.rs @@ -75,6 +75,41 @@ pub fn process_net_events(state: &mut AppState) { }); } } + NetEvent::TrustProblem(problem) => { + use crate::ui::state::{TrustPrompt, TrustPromptKind}; + use vnox_client::net::TrustProblem; + state.ui.trust_prompt = Some(match problem { + TrustProblem::Untrusted { + address, + fingerprint, + } => TrustPrompt { + kind: TrustPromptKind::FirstUse, + address, + received: fingerprint, + expected: String::new(), + }, + TrustProblem::FingerprintChanged { + address, + expected, + actual, + } => TrustPrompt { + kind: TrustPromptKind::FingerprintChanged, + address, + received: actual, + expected, + }, + TrustProblem::IdentityChanged { + address, + expected, + actual, + } => TrustPrompt { + kind: TrustPromptKind::IdentityChanged, + address, + received: actual, + expected, + }, + }); + } NetEvent::Disconnected { reason, will_retry } => { if let Some(ui) = &state.webhooks { ui.disconnected(); @@ -97,10 +132,14 @@ pub fn process_net_events(state: &mut AppState) { state.ui.active_channel = None; state.ui.user_names.clear(); state.ui.rtt_ms = None; - state.ui.status_msg = Some(crate::ui::i18n::Message::with( - "Disconnected: {reason}", - vec![("reason", reason.to_string())], - )); + state.ui.status_msg = if state.ui.trust_prompt.is_some() { + None + } else { + Some(crate::ui::i18n::Message::with( + "Disconnected: {reason}", + vec![("reason", reason.to_string())], + )) + }; } if !will_retry { state.ui.dm_conversations.clear(); @@ -348,6 +387,7 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) { | NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"), NetEvent::Connected { .. } | NetEvent::Disconnected { .. } + | NetEvent::TrustProblem(_) | NetEvent::Reconnecting { .. } | NetEvent::VoicePacket { .. } | NetEvent::E2eeDmKeyExchange { .. } diff --git a/tests/gateway_interop.rs b/tests/gateway_interop.rs index 2979392..c12eb1c 100644 --- a/tests/gateway_interop.rs +++ b/tests/gateway_interop.rs @@ -1,4 +1,5 @@ -//! Real gateway fixture. Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored. +//! Real gateway fixture over TLS 1.3 (LNEx v3). +//! Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored. use std::{ path::PathBuf, process::{Child, Command, Stdio}, @@ -6,7 +7,7 @@ use std::{ }; use vnox_client::{ identity, - net::{self, NetCommand, NetEvent, NetHandle}, + net::{self, NetCommand, NetEvent, NetHandle, TrustProblem, TrustStore}, }; struct Gateway { @@ -27,15 +28,15 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Net tokio::time::timeout(Duration::from_secs(8), async { loop { if let Some(event) = handle.try_recv() { + if predicate(&event) { + return event; + } if let NetEvent::Disconnected { ref reason, .. } = event { panic!("unexpected disconnect: {reason}"); } if let NetEvent::Error { code, ref message } = event { panic!("gateway error {code}: {message}"); } - if predicate(&event) { - return event; - } if let NetEvent::WebhookError(ref result) = event { panic!( "unexpected webhook error at stage {stage}, request {}: {} ({})", @@ -49,6 +50,43 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Net .await .unwrap_or_else(|_| panic!("gateway event timeout at stage {stage}")) } +/// First connection: the client must stop at the untrusted certificate, show the same +/// fingerprint the gateway published, and connect only after the fingerprint is pinned. +async fn connect_with_first_trust(handle: &NetHandle, address: &str, published: &str) { + handle + .send(NetCommand::Connect { + address: address.into(), + auto_reconnect: false, + }) + .await; + let prompt = event(handle, |e| matches!(e, NetEvent::TrustProblem(_))).await; + let NetEvent::TrustProblem(TrustProblem::Untrusted { fingerprint, .. }) = prompt else { + panic!("expected the first-use trust prompt, got {prompt:?}"); + }; + assert_eq!( + fingerprint, published, + "the prompt must show the fingerprint published by the gateway" + ); + event(handle, |e| { + matches!( + e, + NetEvent::Disconnected { + will_retry: false, + .. + } + ) + }) + .await; + let key = net::trust::parse_address(address).unwrap().key; + handle.trust().pin(&key, &fingerprint).unwrap(); + handle + .send(NetCommand::Connect { + address: address.into(), + auto_reconnect: false, + }) + .await; +} + fn free_port() -> u16 { std::net::TcpListener::bind("127.0.0.1:0") .unwrap() @@ -59,7 +97,7 @@ fn free_port() -> u16 { #[tokio::test] #[ignore = "requires a freshly built current VNOX gateway binary"] -async fn native_network_connects_signed_v2_and_exchanges_protobuf_chat() { +async fn native_network_connects_signed_v3_over_tls_and_exchanges_protobuf_chat() { let binary = std::env::var_os("VNOX_GATEWAY_BIN") .expect("set VNOX_GATEWAY_BIN to the current server binary"); let directory = std::env::temp_dir().join(format!("vnox-interop-{}", uuid::Uuid::new_v4())); @@ -95,6 +133,7 @@ mode = "private" .stderr(Stdio::inherit()) .spawn() .unwrap(); + let data_dir = directory.clone(); let _gateway = Gateway { child, directory }; let address = format!("127.0.0.1:{port}"); tokio::time::timeout(Duration::from_secs(8), async { @@ -110,13 +149,44 @@ mode = "private" // In-memory identity only; never touch a real profile or encrypted vault. let alice_identity = identity::generate("interop-alice"); let alice_user_id = alice_identity.pubkey_hex.clone(); - let alice = net::spawn(alice_identity); - alice + // Trust is kept in memory: never touch the real ~/.config/vnox/known_servers.json. + let alice = net::spawn_with_trust(alice_identity, TrustStore::in_memory()); + let published = std::fs::read_to_string(data_dir.join("tls").join("fingerprint.txt")) + .unwrap() + .trim() + .to_string(); + // A client that pinned another fingerprint is blocked before sending anything. + let impostor = + net::spawn_with_trust(identity::generate("interop-pin"), TrustStore::in_memory()); + impostor + .trust() + .pin( + &net::trust::parse_address(&address).unwrap().key, + &"ab".repeat(32), + ) + .unwrap(); + impostor .send(NetCommand::Connect { - address, - auto_reconnect: false, + address: address.clone(), + auto_reconnect: true, }) .await; + let blocked = event(&impostor, |e| matches!(e, NetEvent::TrustProblem(_))).await; + assert!(matches!( + blocked, + NetEvent::TrustProblem(TrustProblem::FingerprintChanged { ref actual, .. }) if actual == &published + )); + event(&impostor, |e| { + matches!( + e, + NetEvent::Disconnected { + will_retry: false, + .. + } + ) + }) + .await; + connect_with_first_trust(&alice, &address, &published).await; event( &alice, |e| matches!(e,NetEvent::Connected {node_name,..} if node_name=="interop-node"), @@ -260,7 +330,16 @@ mode = "private" event(&alice,|e|matches!(e,NetEvent::WebhookResult(result) if result.request_id=="revoke-fixture" && result.secret.is_empty() && result.hook.as_ref().is_some_and(|hook|hook.revoked))).await; let guest_identity = identity::generate("webhook-unprivileged"); let guest_user_id = guest_identity.pubkey_hex.clone(); - let guest = net::spawn(guest_identity); + let guest = net::spawn_with_trust(guest_identity, TrustStore::in_memory()); + guest + .trust() + .pin( + &net::trust::parse_address(&format!("127.0.0.1:{port}")) + .unwrap() + .key, + &published, + ) + .unwrap(); guest .send(NetCommand::Connect { address: format!("127.0.0.1:{port}"), @@ -301,6 +380,22 @@ mode = "private" .await; alice.send(NetCommand::FriendList).await; event(&alice,|e|matches!(e,NetEvent::FriendList {friends} if friends.iter().any(|friend|friend.user_id==guest_user_id))).await; + // The server identity was stored after the first authenticated handshake. + let identity_file: serde_json::Value = + serde_json::from_slice(&std::fs::read(data_dir.join("server_identity.json")).unwrap()) + .unwrap(); + let record = alice + .trust() + .get( + &net::trust::parse_address(&format!("127.0.0.1:{port}")) + .unwrap() + .key, + ) + .unwrap(); + assert_eq!( + record.identity.as_deref(), + identity_file["pubkey_hex"].as_str() + ); guest.send(NetCommand::Disconnect).await; alice.send(NetCommand::Disconnect).await; } diff --git a/translations/en/LC_MESSAGES/vnox-client.po b/translations/en/LC_MESSAGES/vnox-client.po index 992e947..08cef80 100644 --- a/translations/en/LC_MESSAGES/vnox-client.po +++ b/translations/en/LC_MESSAGES/vnox-client.po @@ -214,9 +214,15 @@ msgstr "Export keys" msgid "Extra dark" msgstr "Extra dark" +msgid "Fingerprint (SHA-256)" +msgstr "Fingerprint (SHA-256)" + msgid "For example: /home/user/themes/my-vnox.css" msgstr "For example: /home/user/themes/my-vnox.css" +msgid "Forget this server" +msgstr "Forget this server" + msgid "Friends" msgstr "Friends" @@ -409,6 +415,9 @@ msgstr "Preview active · not broadcasting" msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch." msgstr "Preview stays local until you start broadcasting. Only members of your voice channel can watch." +msgid "Previously trusted fingerprint" +msgstr "Previously trusted fingerprint" + msgid "Profile and keys" msgstr "Profile and keys" @@ -424,6 +433,9 @@ msgstr "Push to talk" msgid "Receive updates here, or send signed channel events to your own service." msgstr "Receive updates here, or send signed channel events to your own service." +msgid "Received fingerprint" +msgstr "Received fingerprint" + msgid "Reconnect automatically" msgstr "Reconnect automatically" @@ -496,6 +508,12 @@ msgstr "Send" msgid "Server address" msgstr "Server address" +msgid "Server fingerprint changed" +msgstr "Server fingerprint changed" + +msgid "Server identity changed" +msgstr "Server identity changed" + msgid "Settings" msgstr "Settings" @@ -541,9 +559,15 @@ msgstr "Text size" msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key." msgstr "The backup passphrase is optional. Without it, your backup contains an unprotected secret key." +msgid "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." + msgid "The old secret stops working. Update the external integration with the new secret." msgstr "The old secret stops working. Update the external integration with the new secret." +msgid "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." + msgid "Theme editor" msgstr "Theme editor" @@ -556,6 +580,15 @@ msgstr "Themes, colours and text" msgid "This cannot be undone." msgstr "This cannot be undone." +msgid "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match." +msgstr "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match." + +msgid "Trust and connect" +msgstr "Trust and connect" + +msgid "Trust this server?" +msgstr "Trust this server?" + msgid "Undeafen" msgstr "Undeafen" diff --git a/translations/ru.json b/translations/ru.json index 5a27904..dac5a8a 100644 --- a/translations/ru.json +++ b/translations/ru.json @@ -351,5 +351,18 @@ "Starting broadcast…": "Запуск трансляции…", "WebRTC connection timed out": "Время ожидания соединения WebRTC истекло", "Broadcast authorization timed out": "Время ожидания разрешения на трансляцию истекло", - "Broadcast connection timed out": "Время ожидания подключения к трансляции истекло" + "Broadcast connection timed out": "Время ожидания подключения к трансляции истекло", + "Trust this server?": "Доверять этому серверу?", + "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match.": "Это первое подключение к этому серверу. Его сертификат выдан не публичным центром сертификации, поэтому Vnox не может проверить его автоматически. Сравни отпечаток с тем, что опубликовал владелец сервера, и доверяй, только если они совпадают.", + "Server fingerprint changed": "Отпечаток сервера изменился", + "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.": "Сертификат этого сервера отличается от того, которому ты доверял раньше. Это может быть атакой на соединение, или владелец переустановил сервер. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение.", + "Server identity changed": "Ключ сервера изменился", + "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.": "Сервер подтвердил другой ключ, чем тот, которому ты доверял раньше. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение.", + "Previously trusted fingerprint": "Ранее доверенный отпечаток", + "Fingerprint (SHA-256)": "Отпечаток (SHA-256)", + "Received fingerprint": "Полученный отпечаток", + "Forget this server": "Забыть этот сервер", + "Trust and connect": "Доверять и подключиться", + "Could not save the trusted fingerprint": "Не удалось сохранить доверенный отпечаток", + "Server forgotten. Connect again to review its fingerprint.": "Сервер забыт. Подключись снова, чтобы проверить его отпечаток." } diff --git a/translations/ru/LC_MESSAGES/vnox-client.po b/translations/ru/LC_MESSAGES/vnox-client.po index f05dd88..c2dcca4 100644 --- a/translations/ru/LC_MESSAGES/vnox-client.po +++ b/translations/ru/LC_MESSAGES/vnox-client.po @@ -215,9 +215,15 @@ msgstr "Экспортировать ключи" msgid "Extra dark" msgstr "Мега-тёмная" +msgid "Fingerprint (SHA-256)" +msgstr "Отпечаток (SHA-256)" + msgid "For example: /home/user/themes/my-vnox.css" msgstr "Например: /home/user/themes/my-vnox.css" +msgid "Forget this server" +msgstr "Забыть этот сервер" + msgid "Friends" msgstr "Друзья" @@ -410,6 +416,9 @@ msgstr "Предпросмотр активен · без трансляции" msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch." msgstr "Предпросмотр остаётся локальным, пока ты не начнёшь трансляцию. Смотреть её могут только участники твоей голосовой комнаты." +msgid "Previously trusted fingerprint" +msgstr "Ранее доверенный отпечаток" + msgid "Profile and keys" msgstr "Профиль и ключи" @@ -425,6 +434,9 @@ msgstr "Нажми и говори" msgid "Receive updates here, or send signed channel events to your own service." msgstr "Получайте обновления в этом канале или отправляйте подписанные события в свой сервис." +msgid "Received fingerprint" +msgstr "Полученный отпечаток" + msgid "Reconnect automatically" msgstr "Переподключаться при потере связи" @@ -497,6 +509,12 @@ msgstr "Отправить" msgid "Server address" msgstr "Адрес сервера" +msgid "Server fingerprint changed" +msgstr "Отпечаток сервера изменился" + +msgid "Server identity changed" +msgstr "Ключ сервера изменился" + msgid "Settings" msgstr "Настройки" @@ -542,9 +560,15 @@ msgstr "Размер текста" msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key." msgstr "Пароль резервной копии можно оставить пустым. Такая копия содержит секретный ключ без защиты." +msgid "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "Сертификат этого сервера отличается от того, которому ты доверял раньше. Это может быть атакой на соединение, или владелец переустановил сервер. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение." + msgid "The old secret stops working. Update the external integration with the new secret." msgstr "Старый секрет перестанет работать. Укажите новый секрет во внешней интеграции." +msgid "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "Сервер подтвердил другой ключ, чем тот, которому ты доверял раньше. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение." + msgid "Theme editor" msgstr "Редактор темы" @@ -557,6 +581,15 @@ msgstr "Темы, цвета и текст" msgid "This cannot be undone." msgstr "Это действие нельзя отменить." +msgid "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match." +msgstr "Это первое подключение к этому серверу. Его сертификат выдан не публичным центром сертификации, поэтому Vnox не может проверить его автоматически. Сравни отпечаток с тем, что опубликовал владелец сервера, и доверяй, только если они совпадают." + +msgid "Trust and connect" +msgstr "Доверять и подключиться" + +msgid "Trust this server?" +msgstr "Доверять этому серверу?" + msgid "Undeafen" msgstr "Включить звук" From 29883a31872295a8e6b64ae0d6d28bf55ed0c015 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:05:19 +0200 Subject: [PATCH 2/8] feat(client): TLS 1.3 control connection with SPKI pinning and LNEx v3 Replace the custom X25519/HKDF/ChaCha20 TCP layer with rustls (TLS 1.3 only, ALPN vnox-lnex/3, no plaintext or fallback). Add a trust store (pin, trust on first use, public CA), block changed fingerprints and identities, bind the Ed25519 auth signature to the TLS exporter, add RU/EN trust dialog and update the interop test and e2e voice tool. --- Cargo.lock | 206 +++++++- Cargo.toml | 5 + protocol/lnex.proto | 9 +- src/bin/e2e_voice.rs | 69 ++- src/main.rs | 54 ++ src/net/crypto/cipher.rs | 90 ---- src/net/crypto/mod.rs | 92 ---- src/net/framing/io.rs | 137 +---- src/net/framing/mod.rs | 7 +- src/net/handshake.rs | 290 +++++++++-- src/net/mod.rs | 17 +- src/net/payloads/mod.rs | 2 +- src/net/session/handlers/core.rs | 56 +- src/net/session/handlers/social/friends.rs | 22 +- src/net/session/handlers/social/guild.rs | 52 +- src/net/session/handlers/social/mod.rs | 78 +-- src/net/session/task.rs | 10 +- src/net/transport.rs | 523 ++++++++++++++++--- src/net/trust.rs | 569 +++++++++++++++++++++ src/net/types/event.rs | 2 + src/ui/bridge.rs | 24 + src/ui/slint/connect.slint | 54 ++ src/ui/slint/main.slint | 15 + src/ui/state/default.rs | 1 + src/ui/state/mod.rs | 2 +- src/ui/state/types.rs | 20 + src/ui/update.rs | 48 +- tests/gateway_interop.rs | 117 ++++- translations/en/LC_MESSAGES/vnox-client.po | 33 ++ translations/ru.json | 15 +- translations/ru/LC_MESSAGES/vnox-client.po | 33 ++ 31 files changed, 2085 insertions(+), 567 deletions(-) delete mode 100644 src/net/crypto/cipher.rs delete mode 100644 src/net/crypto/mod.rs create mode 100644 src/net/trust.rs diff --git a/Cargo.lock b/Cargo.lock index 677b341..0276cb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,6 +298,45 @@ dependencies = [ "libloading", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-channel" version = "2.5.0" @@ -458,6 +497,9 @@ name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "bitflags" @@ -1108,12 +1150,38 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "derive_more" version = "2.1.1" @@ -3368,6 +3436,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -3378,6 +3456,12 @@ dependencies = [ "serde", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -3816,6 +3900,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -3977,6 +4070,16 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4185,6 +4288,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "presser" version = "0.3.1" @@ -4399,6 +4508,20 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -4629,6 +4752,15 @@ dependencies = [ "transpose", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -5227,6 +5359,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -5360,6 +5503,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -5810,6 +5983,7 @@ dependencies = [ "prost", "prost-build", "rand", + "rcgen", "rfd", "rustls", "serde", @@ -6628,6 +6802,24 @@ dependencies = [ "zeroize", ] +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "xattr" version = "1.6.1" @@ -6675,6 +6867,16 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yazi" version = "0.2.1" @@ -6712,7 +6914,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -6852,7 +7054,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 404f652..48b8241 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,11 @@ nnnoiseless = { version = "0.5.2", default-features = false, optional = t image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] } rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal", "wayland"] } +[dev-dependencies] +# Test gateway certificates, and a TLS 1.2 only server for the downgrade test. +rcgen = "0.14" +rustls = { version = "0.23", features = ["tls12"] } + [features] default = ["screen-capture"] rnnoise = ["dep:nnnoiseless"] diff --git a/protocol/lnex.proto b/protocol/lnex.proto index 3b18f62..84fb355 100644 --- a/protocol/lnex.proto +++ b/protocol/lnex.proto @@ -8,8 +8,11 @@ message Hello { bytes server_pubkey = 2; bytes challenge_nonce = 3; string node_name = 4; - bytes server_eph_pubkey = 5; + // LNEx v3: the ephemeral X25519 exchange was replaced by TLS 1.3. + reserved 5; + reserved "server_eph_pubkey"; bool private_mode = 6; + // Ed25519 over "VNOX-LNEx-v3-server-hello\0" || tls_exporter || Hello(signature empty). bytes server_signature = 7; } @@ -17,8 +20,10 @@ message Auth { bytes client_pubkey = 1; string nickname = 2; string lnex_version = 3; + // Ed25519 over the client-auth transcript bound to the TLS exporter (see docs/02-protocol/tls.md). bytes signature = 4; - bytes client_eph_pubkey = 5; + reserved 5; + reserved "client_eph_pubkey"; } message Session { diff --git a/src/bin/e2e_voice.rs b/src/bin/e2e_voice.rs index 40af5bd..0019fbe 100644 --- a/src/bin/e2e_voice.rs +++ b/src/bin/e2e_voice.rs @@ -1,4 +1,8 @@ //! Headless authenticated voice smoke test. Run vnox-serverd first (combined gateway+voice relay). +//! +//! The control connection is TLS 1.3, so the gateway certificate must be trusted. Pass the +//! fingerprint printed by the gateway (`--fingerprint HEX`) or, for a throwaway loopback +//! check only, `--trust-first-use`. The trust store is in memory: nothing is persisted. use anyhow::{Context, Result}; use tokio::time::{Duration, timeout}; use vnox_client::{ @@ -9,15 +13,15 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Res timeout(Duration::from_secs(8), async { loop { if let Some(event) = handle.try_recv() { + if predicate(&event) { + return Ok(event); + } if let NetEvent::Disconnected { ref reason, .. } = event { anyhow::bail!("connection ended: {reason}"); } if let NetEvent::Error { code, ref message } = event { anyhow::bail!("gateway error {code}: {message}"); } - if predicate(&event) { - return Ok(event); - } } tokio::time::sleep(Duration::from_millis(5)).await; } @@ -25,14 +29,42 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Res .await .context("timed out waiting for network event")? } -async fn client(name: &str, address: &str) -> Result { - let handle = net::spawn(identity::generate(name)); +/// How the smoke test decides about the gateway certificate. +enum Trust { + Fingerprint(String), + FirstUse, +} + +async fn client(name: &str, address: &str, trust: &Trust) -> Result { + let handle = net::spawn_with_trust(identity::generate(name), net::TrustStore::in_memory()); + let key = net::trust::parse_address(address)?.key; + match trust { + Trust::Fingerprint(fingerprint) => handle.trust().pin(&key, fingerprint)?, + Trust::FirstUse => {} + } handle .send(NetCommand::Connect { address: address.into(), auto_reconnect: false, }) .await; + if matches!(trust, Trust::FirstUse) { + // The explicit opt-in replaces the interactive prompt: pin what the gateway presents. + if let NetEvent::TrustProblem(net::TrustProblem::Untrusted { fingerprint, .. }) = + event(&handle, |e| matches!(e, NetEvent::TrustProblem(_))).await? + { + eprintln!("trusting gateway fingerprint {fingerprint} (--trust-first-use)"); + handle.trust().pin(&key, &fingerprint)?; + // The refused first attempt reports its disconnect before we reconnect. + event(&handle, |e| matches!(e, NetEvent::Disconnected { .. })).await?; + handle + .send(NetCommand::Connect { + address: address.into(), + auto_reconnect: false, + }) + .await; + } + } event( &handle, |event| matches!(event,NetEvent::ChannelState {channel_id,..} if channel_id=="general"), @@ -52,11 +84,26 @@ async fn client(name: &str, address: &str) -> Result { } #[tokio::main] async fn main() -> Result<()> { - let address = std::env::args() - .nth(1) - .unwrap_or_else(|| "127.0.0.1:7600".into()); - let alice = client("voice-fixture-alice", &address).await?; - let bob = client("voice-fixture-bob", &address).await?; + let mut address = "127.0.0.1:7600".to_string(); + let mut trust = None; + let mut args = std::env::args().skip(1); + while let Some(argument) = args.next() { + match argument.as_str() { + "--trust-first-use" => trust = Some(Trust::FirstUse), + "--fingerprint" => { + let value = args.next().context("--fingerprint needs a value")?; + trust = Some(Trust::Fingerprint(net::trust::normalize_fingerprint( + &value, + )?)); + } + other => address = other.to_string(), + } + } + let trust = trust.context( + "the gateway certificate must be trusted: pass --fingerprint HEX (from the gateway log) or --trust-first-use", + )?; + let alice = client("voice-fixture-alice", &address, &trust).await?; + let bob = client("voice-fixture-bob", &address, &trust).await?; // The real network layer registers the current credentials with encrypted empty-Opus packets. tokio::time::sleep(Duration::from_millis(250)).await; let marker = b"authenticated-vnox-voice-fixture"; @@ -113,6 +160,6 @@ async fn main() -> Result<()> { .await?; alice.send(NetCommand::Disconnect).await; bob.send(NetCommand::Disconnect).await; - println!("Authenticated v2 UDP voice relay passed"); + println!("TLS 1.3 control plane and authenticated UDP voice relay passed"); Ok(()) } diff --git a/src/main.rs b/src/main.rs index 335b435..3ff3c53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -353,6 +353,60 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { }); } + { + // First trust: remember the confirmed fingerprint, then connect again. + let state = state.clone(); + window.on_trust_accept(move || { + let mut s = state.borrow_mut(); + let Some(prompt) = s.ui.trust_prompt.take() else { + return; + }; + if prompt.kind != ui::state::TrustPromptKind::FirstUse { + return; + } + if let Err(error) = s.net.trust().pin(&prompt.address, &prompt.received) { + tracing::warn!(%error, "could not save the trusted fingerprint"); + s.ui.status_msg = Some("Could not save the trusted fingerprint".into()); + return; + } + s.ui.conn = ConnState::Connecting; + s.ui.status_msg = Some("Connecting…".into()); + let auto_reconnect = s.ui.auto_reconnect; + let net = s.net.clone(); + drop(s); + tokio::spawn(async move { + net.send(NetCommand::Connect { + address: prompt.address, + auto_reconnect, + }) + .await; + }); + }); + } + + { + // A blocked change: forgetting is the only way forward and needs a new decision. + let state = state.clone(); + window.on_trust_forget(move || { + let mut s = state.borrow_mut(); + let Some(prompt) = s.ui.trust_prompt.take() else { + return; + }; + if let Err(error) = s.net.trust().forget(&prompt.address) { + tracing::warn!(%error, "could not forget the server"); + } + s.ui.status_msg = + Some("Server forgotten. Connect again to review its fingerprint.".into()); + }); + } + + { + let state = state.clone(); + window.on_trust_dismiss(move || { + state.borrow_mut().ui.trust_prompt = None; + }); + } + { let state = state.clone(); window.on_disconnect(move || { diff --git a/src/net/crypto/cipher.rs b/src/net/crypto/cipher.rs deleted file mode 100644 index 2930348..0000000 --- a/src/net/crypto/cipher.rs +++ /dev/null @@ -1,90 +0,0 @@ -use chacha20poly1305::{ - ChaCha20Poly1305, Key, KeyInit, Nonce, - aead::{Aead, Payload}, -}; - -fn make_nonce(cid: &[u8; 8], seq: u64) -> [u8; 12] { - let mut nonce = [0u8; 12]; - nonce[..8].copy_from_slice(cid); - nonce[8..12].copy_from_slice(&(seq as u32).to_le_bytes()); - nonce -} - -#[cfg(test)] -pub fn encrypt_with_key(key: &[u8; 32], cid: &[u8; 8], seq: u64, plaintext: &[u8]) -> Vec { - encrypt_with_aad(key, cid, seq, plaintext, &[]) -} - -pub fn encrypt_with_aad( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - plaintext: &[u8], - aad: &[u8], -) -> Vec { - let cipher = ChaCha20Poly1305::new(&Key::from(*key)); - let nonce_bytes = make_nonce(cid, seq); - let nonce = Nonce::from(nonce_bytes); - cipher - .encrypt( - &nonce, - Payload { - msg: plaintext, - aad, - }, - ) - .expect("ChaCha20-Poly1305 encryption infallible") -} - -#[cfg(test)] -pub fn decrypt_with_key( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - ciphertext: &[u8], -) -> anyhow::Result> { - decrypt_with_aad(key, cid, seq, ciphertext, &[]) -} - -pub fn decrypt_with_aad( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - ciphertext: &[u8], - aad: &[u8], -) -> anyhow::Result> { - let cipher = ChaCha20Poly1305::new(&Key::from(*key)); - let nonce_bytes = make_nonce(cid, seq); - let nonce = Nonce::from(nonce_bytes); - cipher - .decrypt( - &nonce, - Payload { - msg: ciphertext, - aad, - }, - ) - .map_err(|e| anyhow::anyhow!("decryption failed: {e:?}")) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ciphertext_matches_existing_lnex_wire_format() { - let key = core::array::from_fn(|index| index as u8); - let cid = [7, 0, 0, 0, 0x40, 0x41, 0x42, 0x43]; - // Independently checked with Python cryptography and shared with gateway. - let expected = hex::decode( - "1fa23e7a312509b0fc8729521811348ff880daa5598c43a57635975f81278abdf4461b25af86aee1c3", - ) - .unwrap(); - let ciphertext = encrypt_with_key(&key, &cid, 0x47464544, b"VNOX dependency migration"); - assert_eq!(ciphertext, expected); - assert_eq!( - decrypt_with_key(&key, &cid, 0x47464544, &expected).unwrap(), - b"VNOX dependency migration", - ); - } -} diff --git a/src/net/crypto/mod.rs b/src/net/crypto/mod.rs deleted file mode 100644 index d7415ce..0000000 --- a/src/net/crypto/mod.rs +++ /dev/null @@ -1,92 +0,0 @@ -use hkdf::Hkdf; -use sha2::{Digest, Sha256}; -use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret}; - -pub mod cipher; - -/// Session encryption context (mirrors gateway/src/proto/crypto.rs). -/// -/// Two derived keys: -/// - `c2s_key`: client → server -/// - `s2c_key`: server → client -/// -/// Nonce: `cid (8 bytes) || packet_seq (4 bytes LE)`. -#[derive(Clone)] -pub struct SessionCrypto { - c2s_key: [u8; 32], - s2c_key: [u8; 32], - cid: [u8; 8], -} - -impl SessionCrypto { - pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self { - let salt = b"VNOX-LNEx-KDF-v2"; - let hk = Hkdf::::new(Some(salt), shared_secret); - - let mut keys = [0u8; 64]; - hk.expand(b"session-keys", &mut keys) - .expect("64 bytes within HKDF max"); - - let c2s_key: [u8; 32] = keys[..32].try_into().unwrap(); - let s2c_key: [u8; 32] = keys[32..64].try_into().unwrap(); - - let hash = Sha256::digest(session_id.as_bytes()); - let cid: [u8; 8] = hash[..8].try_into().unwrap(); - - Self { - c2s_key, - s2c_key, - cid, - } - } - - pub fn encrypt_c2s_aad(&self, seq: u64, plaintext: &[u8], aad: &[u8]) -> Vec { - cipher::encrypt_with_aad(&self.c2s_key, &self.cid, seq, plaintext, aad) - } - pub fn decrypt_s2c_aad( - &self, - seq: u64, - ciphertext: &[u8], - aad: &[u8], - ) -> anyhow::Result> { - cipher::decrypt_with_aad(&self.s2c_key, &self.cid, seq, ciphertext, aad) - } - - pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) { - let mut rng = rand::rng(); - let sk = EphemeralSecret::random_from_rng(&mut rng); - let pk = PublicKey::from(&sk); - (sk, pk) - } - - pub fn ecdh(secret: EphemeralSecret, peer_public: &PublicKey) -> SharedSecret { - secret.diffie_hellman(peer_public) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn encrypt_then_decrypt_roundtrip() { - let shared_secret = [0xABu8; 32]; - let crypto = SessionCrypto::derive(&shared_secret, "test-session"); - - let plaintext = b"hello encrypted world"; - let ct = crypto.encrypt_c2s_aad(42, plaintext, b"header"); - let decrypted = - cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 42, &ct, b"header").unwrap(); - assert_eq!(decrypted, plaintext); - } - - #[test] - fn tampered_ciphertext_fails() { - let shared_secret = [0xABu8; 32]; - let crypto = SessionCrypto::derive(&shared_secret, "test-session"); - - let mut ct = crypto.encrypt_c2s_aad(0, b"data", b"header"); - ct[5] ^= 0xFF; - assert!(cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 0, &ct, b"header").is_err()); - } -} diff --git a/src/net/framing/io.rs b/src/net/framing/io.rs index 8223169..9a02185 100644 --- a/src/net/framing/io.rs +++ b/src/net/framing/io.rs @@ -1,66 +1,9 @@ +//! Session frame reader. Frames travel inside the TLS 1.3 stream, so there is no per frame +//! encryption: a dedicated task retains partial frames across command/timer selection and +//! enforces strictly increasing sequence numbers. use anyhow::{Result, anyhow}; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; -use super::super::crypto::SessionCrypto; -use super::super::payloads::HDR_SIZE; use super::RawPacket; -use super::parse_header; - -const ENCRYPTED_FLAG: u16 = 1 << 1; -const KNOWN_FLAGS: u16 = ENCRYPTED_FLAG; - -pub async fn read_encrypted( - stream: &mut (impl tokio::io::AsyncRead + Unpin), - crypto: &SessionCrypto, -) -> Result { - let mut buf = [0u8; HDR_SIZE]; - stream.read_exact(&mut buf).await?; - let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?; - if flags & !KNOWN_FLAGS != 0 { - return Err(anyhow!("unknown packet flags: 0x{:04X}", flags)); - } - if flags & ENCRYPTED_FLAG == 0 { - return Err(anyhow!("packet not encrypted")); - } - let mut encrypted = vec![0u8; payload_length as usize]; - if !encrypted.is_empty() { - stream.read_exact(&mut encrypted).await?; - } - let payload = crypto.decrypt_s2c_aad(sequence as u64, &encrypted, &buf)?; - Ok(RawPacket { - packet_id, - sequence, - payload, - }) -} - -pub async fn write_encrypted( - stream: &mut (impl tokio::io::AsyncWrite + Unpin), - id: u16, - seq: &mut u32, - payload: &[u8], - crypto: &SessionCrypto, -) -> Result<()> { - if *seq == u32::MAX { - return Err(anyhow!("session sequence exhausted; reconnect required")); - } - if payload.len() > super::super::payloads::MAX_PAYLOAD as usize - 16 { - return Err(anyhow!("payload too large")); - } - let mut hdr = [0u8; HDR_SIZE]; - hdr[0..2].copy_from_slice(&id.to_be_bytes()); - hdr[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes()); - hdr[4..8].copy_from_slice(&seq.to_be_bytes()); - hdr[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes()); - let encrypted = crypto.encrypt_c2s_aad(*seq as u64, payload, &hdr); - *seq += 1; - let mut frame = Vec::with_capacity(HDR_SIZE + encrypted.len()); - frame.extend_from_slice(&hdr); - frame.extend_from_slice(&encrypted); - stream.write_all(&frame).await?; - Ok(()) -} /// A dedicated reader retains partial frames across command/timer selection. /// Dropping a session cancels its reader and releases the socket half. @@ -69,25 +12,21 @@ pub struct Reader { task: tokio::task::JoinHandle<()>, } impl Reader { - pub fn new( - mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static, - crypto: SessionCrypto, - ) -> Self { + pub fn new(mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static) -> Self { let (sender, receiver) = tokio::sync::mpsc::channel(32); let task = tokio::spawn(async move { + // HELLO was 0 and SESSION was 1. let mut expected = 2u32; loop { - let result = read_encrypted(&mut stream, &crypto) - .await - .and_then(|packet| { - if packet.sequence != expected { - return Err(anyhow!("replayed or reordered control packet")); - } - expected = expected - .checked_add(1) - .ok_or_else(|| anyhow!("session sequence exhausted"))?; - Ok(packet) - }); + let result = super::read(&mut stream).await.and_then(|packet| { + if packet.sequence != expected { + return Err(anyhow!("replayed or reordered control packet")); + } + expected = expected + .checked_add(1) + .ok_or_else(|| anyhow!("session sequence exhausted"))?; + Ok(packet) + }); let failed = result.is_err(); if sender.send(result).await.is_err() || failed { break; @@ -112,34 +51,18 @@ impl Drop for Reader { #[cfg(test)] mod tests { use super::*; - use hkdf::Hkdf; - use sha2::{Digest, Sha256}; + use tokio::io::AsyncWriteExt; use tokio::time::{Duration, timeout}; fn server_frame(pid: u16, seq: u32, payload: &[u8]) -> Vec { - let mut keys = [0u8; 64]; - Hkdf::::new(Some(b"VNOX-LNEx-KDF-v2"), &[7; 32]) - .expand(b"session-keys", &mut keys) - .unwrap(); - let key: [u8; 32] = keys[32..].try_into().unwrap(); - let cid: [u8; 8] = Sha256::digest(b"fixture-session")[..8].try_into().unwrap(); - let mut header = [0u8; 12]; - header[..2].copy_from_slice(&pid.to_be_bytes()); - header[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes()); - header[4..8].copy_from_slice(&seq.to_be_bytes()); - header[8..].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes()); - let body = - crate::net::crypto::cipher::encrypt_with_aad(&key, &cid, seq as u64, payload, &header); - [header.as_slice(), body.as_slice()].concat() - } - fn crypto() -> SessionCrypto { - SessionCrypto::derive(&[7; 32], "fixture-session") + let mut seq = seq; + super::super::encode_frame(pid, &mut seq, payload) } #[tokio::test] async fn cancelling_wait_retains_partial_control_frame() { let (reader, mut writer) = tokio::io::duplex(256); - let mut reader = Reader::new(reader, crypto()); + let mut reader = Reader::new(reader); let frame = server_frame(5, 2, b"protobuf"); writer.write_all(&frame[..5]).await.unwrap(); assert!( @@ -157,7 +80,7 @@ mod tests { #[tokio::test] async fn replayed_control_sequence_is_rejected() { let (reader, mut writer) = tokio::io::duplex(256); - let mut reader = Reader::new(reader, crypto()); + let mut reader = Reader::new(reader); let frame = server_frame(5, 2, b""); writer.write_all(&frame).await.unwrap(); reader.next().await.unwrap(); @@ -165,22 +88,12 @@ mod tests { assert!(reader.next().await.is_err()); } #[tokio::test] - async fn changing_packet_id_invalidates_authentication() { - let (mut reader, mut writer) = tokio::io::duplex(256); - let mut frame = server_frame(5, 2, b"same body"); - frame[1] ^= 1; + async fn legacy_encrypted_flag_is_rejected() { + let (reader, mut writer) = tokio::io::duplex(256); + let mut reader = Reader::new(reader); + let mut frame = server_frame(5, 2, b"0123456789abcdef"); + frame[2..4].copy_from_slice(&2u16.to_be_bytes()); writer.write_all(&frame).await.unwrap(); - assert!(read_encrypted(&mut reader, &crypto()).await.is_err()); - } - #[tokio::test] - async fn sequence_exhaustion_never_wraps_nonce() { - let (_, mut writer) = tokio::io::duplex(256); - let mut seq = u32::MAX; - assert!( - write_encrypted(&mut writer, 4, &mut seq, b"", &crypto()) - .await - .is_err() - ); - assert_eq!(seq, u32::MAX); + assert!(reader.next().await.is_err()); } } diff --git a/src/net/framing/mod.rs b/src/net/framing/mod.rs index 8616fbe..ff3b56b 100644 --- a/src/net/framing/mod.rs +++ b/src/net/framing/mod.rs @@ -39,7 +39,7 @@ pub fn decode_frame(bytes: &[u8]) -> Result { let hdr: [u8; HDR_SIZE] = bytes[..HDR_SIZE].try_into().expect("header length"); let (packet_id, flags, sequence, payload_length) = parse_header(&hdr)?; if flags != 0 { - return Err(anyhow!("unexpected handshake flags")); + return Err(anyhow!("unexpected frame flags")); } let end = HDR_SIZE + payload_length as usize; if bytes.len() < end { @@ -57,7 +57,7 @@ pub async fn read(stream: &mut (impl tokio::io::AsyncRead + Unpin)) -> Result Result<()> { + if *seq == u32::MAX { + return Err(anyhow!("session sequence exhausted; reconnect required")); + } let frame = encode_frame(id, seq, payload); stream.write_all(&frame).await?; Ok(()) diff --git a/src/net/handshake.rs b/src/net/handshake.rs index 536ebd4..39abd57 100644 --- a/src/net/handshake.rs +++ b/src/net/handshake.rs @@ -3,31 +3,85 @@ use anyhow::{Result, anyhow}; use tracing::{debug, info}; -use super::crypto::SessionCrypto; use super::framing; use super::payloads::*; +use super::trust::TransportError; use crate::identity::Identity; -/// Perform HELLO → AUTH → SESSION with X25519 ECDH key exchange. +const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0"; +const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0"; + +/// Bytes signed by the server identity: context, TLS exporter, HELLO without signature. +pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec { + let mut out = SERVER_HELLO_CONTEXT.to_vec(); + out.extend_from_slice(binding); + out.extend_from_slice(unsigned_hello); + out +} + +/// Bytes signed by the client identity. The TLS exporter makes the signature valid for +/// this connection only, so it cannot be relayed to another server or connection. +pub fn client_auth_transcript( + binding: &[u8], + signed_hello: &[u8], + unsigned_auth: &[u8], +) -> Vec { + let mut out = CLIENT_AUTH_CONTEXT.to_vec(); + out.extend_from_slice(binding); + out.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes()); + out.extend_from_slice(signed_hello); + out.extend_from_slice(unsigned_auth); + out +} + +/// What the handshake learned about the server and the new session. +#[derive(Debug, Clone)] +pub struct Outcome { + pub session_id: String, + pub node_name: String, + pub private_mode: bool, + /// Lower-case hex Ed25519 identity of the server. + pub server_identity: String, +} + +/// Perform HELLO, AUTH, SESSION inside an established TLS 1.3 connection. /// -/// Returns (session_id, node_name, private_mode, crypto). -/// All subsequent packets must be encrypted with `crypto`. +/// * `binding` is the TLS exporter value, covered by both signatures. +/// * `trust_key` and `expected_identity` implement the identity pin: a server presenting a +/// different Ed25519 identity than the stored one is rejected before AUTH is sent. pub async fn run( stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin), identity: &Identity, seq: &mut u32, -) -> Result<(String, String, bool, SessionCrypto)> { - // HELLO — receive server's ephemeral X25519 public key + binding: &[u8], + trust_key: &str, + expected_identity: Option<&str>, +) -> Result { + // HELLO let pkt = framing::read(stream).await?; + if pkt.packet_id == PID_ERROR { + let e: ErrorPayload = wire::decode(&pkt.payload)?; + return Err(anyhow!("server rejected the connection: {}", e.message)); + } if pkt.packet_id != PID_HELLO { return Err(anyhow!("expected HELLO, got 0x{:04X}", pkt.packet_id)); } - let hello: HelloPayload = wire::decode(&pkt.payload)?; - debug!("← HELLO node={}", hello.node_name); - if pkt.sequence != 0 { return Err(anyhow!("invalid HELLO sequence")); } + let hello: HelloPayload = wire::decode(&pkt.payload)?; + debug!("HELLO node={}", hello.node_name); + if hello.lnex_version != LNEX_VERSION { + return Err(TransportError::ProtocolMismatch(format!( + "The server speaks LNEx {} but this client requires {}. Update the outdated side.", + hello.lnex_version, LNEX_VERSION + )) + .into()); + } + if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 { + return Err(anyhow!("invalid server handshake key/challenge")); + } + let server_public: [u8; 32] = hello .server_pubkey .as_slice() @@ -37,32 +91,27 @@ pub async fn run( let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature)?; let mut unsigned_hello = hello.clone(); unsigned_hello.server_signature.clear(); - let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec(); - hello_transcript.extend_from_slice(&wire::encode(&unsigned_hello)?); server_key - .verify_strict(&hello_transcript, &signature) + .verify_strict( + &server_hello_transcript(binding, &wire::encode(&unsigned_hello)?), + &signature, + ) .map_err(|_| anyhow!("server handshake signature verification failed"))?; - // Keep full signed hello for the client-auth transcript before moving fields. + let server_identity = hex::encode(server_public); + if let Some(expected) = expected_identity + && expected != server_identity + { + return Err(TransportError::IdentityChanged { + address: trust_key.to_string(), + expected: expected.to_string(), + actual: server_identity, + } + .into()); + } + // Keep the full signed hello for the client-auth transcript. let signed_hello = wire::encode(&hello)?; - // Generate our own ephemeral X25519 keypair - let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral(); - let eph_pk_hex = eph_pk.as_bytes().to_vec(); - - // Parse server's ephemeral key from HELLO - let server_eph_raw = hello.server_eph_pubkey; - let server_eph_key: [u8; 32] = server_eph_raw - .try_into() - .map_err(|_| anyhow!("bad server_eph_pubkey length"))?; - let server_eph_pk = x25519_dalek::PublicKey::from(server_eph_key); - - // AUTH — include our ephemeral public key - if hello.lnex_version != LNEX_VERSION { - return Err(anyhow!("unsupported LNEx version")); - } - if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 { - return Err(anyhow!("invalid server handshake key/challenge")); - } + // AUTH let sk = identity .signing_key() .ok_or_else(|| anyhow!("no signing key"))?; @@ -73,15 +122,11 @@ pub async fn run( nickname: identity.nickname.clone(), lnex_version: LNEX_VERSION.into(), signature: Vec::new(), - client_eph_pubkey: eph_pk_hex, }; - let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec(); - auth_transcript.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes()); - auth_transcript.extend_from_slice(&signed_hello); - auth_transcript.extend_from_slice(&wire::encode(&auth)?); - auth.signature = sk.sign(&auth_transcript).to_bytes().to_vec(); + let transcript = client_auth_transcript(binding, &signed_hello, &wire::encode(&auth)?); + auth.signature = sk.sign(&transcript).to_bytes().to_vec(); framing::write(stream, PID_AUTH, seq, &wire::encode(&auth)?).await?; - debug!("→ AUTH nick={}", identity.nickname); + debug!("AUTH sent nick={}", identity.nickname); // SESSION let pkt = framing::read(stream).await?; @@ -96,21 +141,172 @@ pub async fn run( return Err(anyhow!("invalid SESSION sequence")); } let sess: SessionPayload = wire::decode(&pkt.payload)?; - - // Derive encryption keys from ECDH shared secret - let shared_secret = SessionCrypto::ecdh(eph_sk, &server_eph_pk); - if !shared_secret.was_contributory() { - return Err(anyhow!("invalid server ECDH key")); - } if sess.session_id.is_empty() || sess.token.is_empty() { return Err(anyhow!("invalid session response")); } - let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id); info!( - "authenticated — session {} encrypted", + "authenticated, session {}", sess.session_id.chars().take(8).collect::() ); - Ok((sess.session_id, hello.node_name, hello.private_mode, crypto)) + Ok(Outcome { + session_id: sess.session_id, + node_name: hello.node_name, + private_mode: hello.private_mode, + server_identity, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::{Signer, SigningKey}; + use tokio::io::AsyncWriteExt; + + /// Scripted gateway: sends a HELLO signed over `hello_binding` and returns the AUTH it gets. + async fn fake_server( + mut stream: tokio::io::DuplexStream, + server_key: SigningKey, + hello_binding: [u8; 32], + version: &str, + send_session: bool, + ) -> (AuthPayload, Vec) { + let mut hello = HelloPayload { + lnex_version: version.into(), + server_pubkey: server_key.verifying_key().to_bytes().to_vec(), + challenge_nonce: vec![7; 32], + node_name: "fake".into(), + private_mode: true, + server_signature: Vec::new(), + }; + let unsigned = wire::encode(&hello).unwrap(); + hello.server_signature = server_key + .sign(&server_hello_transcript(&hello_binding, &unsigned)) + .to_bytes() + .to_vec(); + let signed = wire::encode(&hello).unwrap(); + let mut seq = 0; + framing::write(&mut stream, PID_HELLO, &mut seq, &signed) + .await + .unwrap(); + let Ok(packet) = framing::read(&mut stream).await else { + return (AuthPayload::default(), signed); + }; + let auth: AuthPayload = wire::decode(&packet.payload).unwrap(); + if send_session { + let session = SessionPayload { + session_id: "session-1".into(), + token: "token".into(), + expires_at: 0, + }; + framing::write( + &mut stream, + PID_SESSION, + &mut seq, + &wire::encode(&session).unwrap(), + ) + .await + .unwrap(); + } + let _ = stream.shutdown().await; + (auth, signed) + } + + fn identity() -> Identity { + crate::identity::generate("handshake-test") + } + + #[tokio::test] + async fn authenticated_handshake_returns_server_identity_and_binds_signature() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v3", true)); + let mut seq = 0; + let outcome = run(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None) + .await + .unwrap(); + assert_eq!(outcome.session_id, "session-1"); + assert_eq!( + outcome.server_identity, + hex::encode(server_key.verifying_key().to_bytes()) + ); + // The AUTH signature is valid for this connection and invalid for any other one. + let (auth, signed_hello) = task.await.unwrap(); + let client_public = ed25519_dalek::VerifyingKey::from_bytes( + &auth.client_pubkey.clone().try_into().unwrap(), + ) + .unwrap(); + let signature = ed25519_dalek::Signature::from_slice(&auth.signature).unwrap(); + let mut unsigned_auth = auth.clone(); + unsigned_auth.signature.clear(); + let unsigned = wire::encode(&unsigned_auth).unwrap(); + client_public + .verify_strict( + &client_auth_transcript(&[9; 32], &signed_hello, &unsigned), + &signature, + ) + .unwrap(); + assert!( + client_public + .verify_strict( + &client_auth_transcript(&[8; 32], &signed_hello, &unsigned), + &signature + ) + .is_err(), + "a signature made on one TLS connection must not verify on another" + ); + } + + #[tokio::test] + async fn hello_relayed_from_another_tls_connection_is_rejected() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + // The relay forwards a HELLO signed for a different TLS session. + tokio::spawn(fake_server(server, server_key, [1; 32], "v3", false)); + let mut seq = 0; + let error = run(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None) + .await + .unwrap_err(); + assert!(error.to_string().contains("signature verification failed")); + assert_eq!(seq, 0, "no AUTH may be sent to an unauthenticated peer"); + } + + #[tokio::test] + async fn changed_server_identity_is_blocked_before_auth() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + tokio::spawn(fake_server(server, server_key, [3; 32], "v3", false)); + let mut seq = 0; + let error = run( + &mut client, + &identity(), + &mut seq, + &[3; 32], + "h:7600", + Some(&"00".repeat(32)), + ) + .await + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(TransportError::IdentityChanged { .. }) + )); + assert_eq!(seq, 0); + } + + #[tokio::test] + async fn old_protocol_version_gives_explicit_error() { + let server_key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + tokio::spawn(fake_server(server, server_key, [4; 32], "v2", false)); + let mut seq = 0; + let error = run(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None) + .await + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3") + )); + } } diff --git a/src/net/mod.rs b/src/net/mod.rs index c7862ec..4db7a2d 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -1,14 +1,15 @@ -pub mod crypto; pub mod framing; pub mod handshake; mod internal; pub mod payloads; mod session; pub mod transport; +pub mod trust; mod types; pub mod voice; pub mod wire; +pub use trust::{TransportError, TrustProblem, TrustStore}; pub use types::{ ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo, WebhookManagementResult, WebhookOperation, @@ -26,23 +27,35 @@ use crate::identity::Identity; pub struct NetHandle { cmd_tx: mpsc::Sender, event_rx: Arc>>, + trust: trust::TrustStore, } impl NetHandle { pub async fn send(&self, cmd: NetCommand) { let _ = self.cmd_tx.send(cmd).await; } + /// Server trust decisions (pinned fingerprints). Share it with the UI. + pub fn trust(&self) -> &trust::TrustStore { + &self.trust + } pub fn try_recv(&self) -> Option { self.event_rx.try_lock().ok()?.try_recv().ok() } } +/// Spawn the network task with the persistent trust store. pub fn spawn(identity: Identity) -> NetHandle { + spawn_with_trust(identity, trust::TrustStore::load_default()) +} + +/// Spawn with an explicit trust store (tests, headless tools). +pub fn spawn_with_trust(identity: Identity, trust: trust::TrustStore) -> NetHandle { let (cmd_tx, cmd_rx) = mpsc::channel::(64); let (event_tx, event_rx) = mpsc::channel::(256); - tokio::spawn(session::net_task(identity, cmd_rx, event_tx)); + tokio::spawn(session::net_task(identity, trust.clone(), cmd_rx, event_tx)); NetHandle { cmd_tx, event_rx: Arc::new(Mutex::new(event_rx)), + trust, } } diff --git a/src/net/payloads/mod.rs b/src/net/payloads/mod.rs index 1c16b1a..99f475e 100644 --- a/src/net/payloads/mod.rs +++ b/src/net/payloads/mod.rs @@ -67,7 +67,7 @@ pub const PID_FRIEND_EVENT: u16 = 0x0158; pub const PID_ERROR: u16 = 0x00F0; pub const PID_DISCONNECT: u16 = 0x00FF; -pub const LNEX_VERSION: &str = "v2"; +pub const LNEX_VERSION: &str = "v3"; pub const HDR_SIZE: usize = 12; pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024; diff --git a/src/net/session/handlers/core.rs b/src/net/session/handlers/core.rs index 27124ee..b2ecff0 100644 --- a/src/net/session/handlers/core.rs +++ b/src/net/session/handlers/core.rs @@ -11,6 +11,7 @@ use crate::net::wire; use crate::net::{ framing, handshake, internal, payloads::*, + trust::TrustStore, types::{NetCommand, NetEvent}, }; @@ -20,6 +21,7 @@ use super::{VoiceState, handle_cmd}; pub async fn session_loop( identity: &Identity, address: &str, + trust: &TrustStore, channels: &mut Vec, restored: bool, cmd_rx: &mut mpsc::Receiver, @@ -27,7 +29,7 @@ pub async fn session_loop( ) -> Result<()> { let connection = tokio::time::timeout( Duration::from_secs(10), - crate::net::transport::connect_with_peer(address), + crate::net::transport::connect_with_peer(address, trust), ) .await .context("gateway connection timed out")??; @@ -35,12 +37,29 @@ pub async fn session_loop( let mut stream = connection.stream; let mut seq = 0u32; - let (session_id, node_name, private_mode, crypto) = tokio::time::timeout( + let outcome = tokio::time::timeout( Duration::from_secs(10), - handshake::run(&mut stream, identity, &mut seq), + handshake::run( + &mut stream, + identity, + &mut seq, + &connection.binding, + &connection.trust_key, + connection + .record + .as_ref() + .and_then(|record| record.identity.as_deref()), + ), ) .await .context("gateway handshake timed out")??; + // The identity is learned inside an already trusted channel and then pinned. + if let Err(error) = trust.set_identity(&connection.trust_key, &outcome.server_identity) { + tracing::warn!(%error, "could not store the server identity"); + } + let session_id = outcome.session_id; + let node_name = outcome.node_name; + let private_mode = outcome.private_mode; let _ = event_tx .send(NetEvent::Connected { session_id: session_id.clone(), @@ -51,18 +70,17 @@ pub async fn session_loop( .await; for channel_id in channels.clone() { - framing::io::write_encrypted( + framing::write( &mut stream, PID_JOIN_CHANNEL, &mut seq, &wire::encode(&JoinChannelPayload { channel_id })?, - &crypto, ) .await?; } let (reader, mut stream) = tokio::io::split(stream); - let mut incoming = framing::io::Reader::new(reader, crypto.clone()); + let mut incoming = framing::io::Reader::new(reader); let mut voice_state: Option = None; let mut used_voice_routes = std::collections::HashSet::new(); let mut voice_endpoint: Option = None; @@ -77,7 +95,7 @@ pub async fn session_loop( _ = ping_tick.tick() => { let ts = now_ms(); let payload = wire::encode(&PingPayload { timestamp: ts })?; - framing::io::write_encrypted(&mut stream, PID_PING, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_PING, &mut seq, &payload).await?; } result = incoming.next() => { let pkt = result?; @@ -113,8 +131,8 @@ pub async fn session_loop( cmd = cmd_rx.recv() => { match cmd { None | Some(NetCommand::Disconnect) => { - let _ = framing::io::write_encrypted(&mut stream, PID_DISCONNECT, &mut seq, - &wire::encode(&Disconnect {reason: "bye".into()})?, &crypto).await; + let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq, + &wire::encode(&Disconnect {reason: "bye".into()})?).await; return Ok(()); } Some(NetCommand::Connect { address, auto_reconnect }) => { @@ -129,14 +147,14 @@ pub async fn session_loop( } Some(NetCommand::JoinChannel { channel_id }) => { track_channel(channels, &channel_id); - framing::io::write_encrypted(&mut stream, PID_JOIN_CHANNEL, &mut seq, - &wire::encode(&JoinChannelPayload { channel_id })?, &crypto).await?; + framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq, + &wire::encode(&JoinChannelPayload { channel_id })?).await?; } Some(NetCommand::LeaveChannel { channel_id }) => { channels.retain(|c| c != &channel_id); if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;} - framing::io::write_encrypted(&mut stream, PID_LEAVE_CHANNEL, &mut seq, - &wire::encode(&LeaveChannelPayload { channel_id })?, &crypto).await?; + framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq, + &wire::encode(&LeaveChannelPayload { channel_id })?).await?; } Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => { let payload = wire::encode(&ChannelCreatePayload { @@ -145,14 +163,14 @@ pub async fn session_loop( kind, guild_id, })?; - framing::io::write_encrypted(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?; } Some(NetCommand::ChannelDelete { channel_id }) => { let payload = wire::encode(&ChannelDeletePayload { channel_id })?; - framing::io::write_encrypted(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?; } Some(NetCommand::ChannelList) => { - framing::io::write_encrypted(&mut stream, PID_CHANNEL_LIST, &mut seq, b"", &crypto).await?; + framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?; } Some(NetCommand::SendChat { channel_id, content, reply_to }) => { let msg = ChatMessagePayload { @@ -162,16 +180,16 @@ pub async fn session_loop( edited: false, reply_to, }; - framing::io::write_encrypted(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?, &crypto).await?; + framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?; } Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => { if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;} } Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => { let payload = wire::encode(&ReadReceipt {channel_id,last_read_message_id,user_id: identity.pubkey_hex.clone()})?; - framing::io::write_encrypted(&mut stream, PID_READ_RECEIPT, &mut seq, &payload, &crypto).await?; + framing::write(&mut stream, PID_READ_RECEIPT, &mut seq, &payload).await?; } - Some(other) => handle_cmd(other, &mut stream, &mut seq, &crypto, identity).await?, + Some(other) => handle_cmd(other, &mut stream, &mut seq, identity).await?, } } } diff --git a/src/net/session/handlers/social/friends.rs b/src/net/session/handlers/social/friends.rs index 6804a0a..4c18901 100644 --- a/src/net/session/handlers/social/friends.rs +++ b/src/net/session/handlers/social/friends.rs @@ -1,13 +1,12 @@ use crate::net::wire; use anyhow::Result; -use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand}; +use crate::net::{framing, payloads::*, types::NetCommand}; pub async fn handle_cmd( cmd: NetCommand, stream: &mut (impl tokio::io::AsyncWrite + Unpin), seq: &mut u32, - crypto: &SessionCrypto, ) -> Result<()> { match cmd { NetCommand::PresenceUpdate { @@ -21,44 +20,43 @@ pub async fn handle_cmd( activity_type: activity, activity_text, })?; - framing::io::write_encrypted(stream, PID_PRESENCE_UPDATE, seq, &payload, crypto) - .await?; + framing::write(stream, PID_PRESENCE_UPDATE, seq, &payload).await?; } NetCommand::FriendRequest { target_user_id } => { let payload = wire::encode(&FriendRequestPayload { to_user_id: target_user_id, })?; - framing::io::write_encrypted(stream, PID_FRIEND_REQUEST, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_REQUEST, seq, &payload).await?; } NetCommand::FriendAccept { user_id } => { let payload = wire::encode(&FriendAcceptPayload { from_user_id: user_id, })?; - framing::io::write_encrypted(stream, PID_FRIEND_ACCEPT, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_ACCEPT, seq, &payload).await?; } NetCommand::FriendDecline { user_id } => { let payload = wire::encode(&FriendDeclinePayload { from_user_id: user_id, })?; - framing::io::write_encrypted(stream, PID_FRIEND_DECLINE, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_DECLINE, seq, &payload).await?; } NetCommand::FriendRemove { user_id } => { let payload = wire::encode(&FriendRemovePayload { user_id })?; - framing::io::write_encrypted(stream, PID_FRIEND_REMOVE, seq, &payload, crypto).await?; + framing::write(stream, PID_FRIEND_REMOVE, seq, &payload).await?; } NetCommand::FriendList => { - framing::io::write_encrypted(stream, PID_FRIEND_LIST, seq, b"", crypto).await?; + framing::write(stream, PID_FRIEND_LIST, seq, b"").await?; } NetCommand::BlockUser { user_id } => { let payload = wire::encode(&BlockUserPayload { user_id })?; - framing::io::write_encrypted(stream, PID_BLOCK_USER, seq, &payload, crypto).await?; + framing::write(stream, PID_BLOCK_USER, seq, &payload).await?; } NetCommand::UnblockUser { user_id } => { let payload = wire::encode(&UnblockUserPayload { user_id })?; - framing::io::write_encrypted(stream, PID_UNBLOCK_USER, seq, &payload, crypto).await?; + framing::write(stream, PID_UNBLOCK_USER, seq, &payload).await?; } NetCommand::BlockList => { - framing::io::write_encrypted(stream, PID_BLOCK_LIST, seq, b"", crypto).await?; + framing::write(stream, PID_BLOCK_LIST, seq, b"").await?; } _ => {} } diff --git a/src/net/session/handlers/social/guild.rs b/src/net/session/handlers/social/guild.rs index a4d38b7..1c316d0 100644 --- a/src/net/session/handlers/social/guild.rs +++ b/src/net/session/handlers/social/guild.rs @@ -1,25 +1,24 @@ use crate::net::wire; use anyhow::Result; -use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand}; +use crate::net::{framing, payloads::*, types::NetCommand}; pub async fn handle_cmd( cmd: NetCommand, stream: &mut (impl tokio::io::AsyncWrite + Unpin), seq: &mut u32, - crypto: &SessionCrypto, ) -> Result<()> { match cmd { NetCommand::GuildCreate { name } => { let payload = wire::encode(&GuildCreatePayload { name })?; - framing::io::write_encrypted(stream, PID_GUILD_CREATE, seq, &payload, crypto).await?; + framing::write(stream, PID_GUILD_CREATE, seq, &payload).await?; } NetCommand::GuildDelete { guild_id } => { let payload = wire::encode(&GuildDeletePayload { guild_id })?; - framing::io::write_encrypted(stream, PID_GUILD_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_GUILD_DELETE, seq, &payload).await?; } NetCommand::GuildList => { - framing::io::write_encrypted(stream, PID_GUILD_LIST, seq, b"", crypto).await?; + framing::write(stream, PID_GUILD_LIST, seq, b"").await?; } NetCommand::GuildJoin { guild_id, @@ -30,12 +29,10 @@ pub async fn handle_cmd( code, ..Default::default() })?; - framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto) - .await?; + framing::write(stream, PID_INVITE_ACCEPT, seq, &payload).await?; } else { let payload = wire::encode(&GuildJoinPayload { guild_id })?; - framing::io::write_encrypted(stream, PID_GUILD_MEMBER_JOIN, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_MEMBER_JOIN, seq, &payload).await?; } } NetCommand::GuildLeave { guild_id } => { @@ -43,8 +40,7 @@ pub async fn handle_cmd( guild_id, user_id: String::new(), })?; - framing::io::write_encrypted(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload).await?; } NetCommand::InviteCreate { guild_id, @@ -56,14 +52,14 @@ pub async fn handle_cmd( max_uses, expires_in_seconds, })?; - framing::io::write_encrypted(stream, PID_INVITE_CREATE, seq, &payload, crypto).await?; + framing::write(stream, PID_INVITE_CREATE, seq, &payload).await?; } NetCommand::InviteAccept { code } => { let payload = wire::encode(&InviteAcceptPayload { code, ..Default::default() })?; - framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto).await?; + framing::write(stream, PID_INVITE_ACCEPT, seq, &payload).await?; } NetCommand::InviteDelete { guild_id, @@ -73,7 +69,7 @@ pub async fn handle_cmd( guild_id, invite_id, })?; - framing::io::write_encrypted(stream, PID_INVITE_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_INVITE_DELETE, seq, &payload).await?; } NetCommand::RoleCreate { guild_id, @@ -88,32 +84,23 @@ pub async fn handle_cmd( permissions, id: String::new(), })?; - framing::io::write_encrypted(stream, PID_ROLE_CREATE, seq, &payload, crypto).await?; + framing::write(stream, PID_ROLE_CREATE, seq, &payload).await?; } NetCommand::RoleDelete { guild_id, role_id } => { let payload = wire::encode(&RoleDeletePayload { guild_id, role_id })?; - framing::io::write_encrypted(stream, PID_ROLE_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_ROLE_DELETE, seq, &payload).await?; } NetCommand::GuildMemberKick { guild_id, user_id } => { let payload = wire::encode(&GuildMemberKickPayload { guild_id, user_id })?; - framing::io::write_encrypted(stream, PID_GUILD_MEMBER_KICK, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_MEMBER_KICK, seq, &payload).await?; } NetCommand::GuildAuditLogFetch { guild_id, limit } => { let payload = wire::encode(&GuildAuditLogFetchPayload { guild_id, limit })?; - framing::io::write_encrypted(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload).await?; } NetCommand::GuildMemberListFetch { guild_id } => { let payload = wire::encode(&GuildMemberListFetchPayload { guild_id })?; - framing::io::write_encrypted( - stream, - PID_GUILD_MEMBER_LIST_FETCH, - seq, - &payload, - crypto, - ) - .await?; + framing::write(stream, PID_GUILD_MEMBER_LIST_FETCH, seq, &payload).await?; } NetCommand::GuildRoleAssign { guild_id, @@ -125,8 +112,7 @@ pub async fn handle_cmd( user_id, role_id, })?; - framing::io::write_encrypted(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload).await?; } NetCommand::GuildRoleUnassign { guild_id, @@ -138,13 +124,11 @@ pub async fn handle_cmd( user_id, role_id, })?; - framing::io::write_encrypted(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload).await?; } NetCommand::GuildRoleListFetch { guild_id } => { let payload = wire::encode(&GuildRoleListFetchPayload { guild_id })?; - framing::io::write_encrypted(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload, crypto) - .await?; + framing::write(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload).await?; } _ => {} } diff --git a/src/net/session/handlers/social/mod.rs b/src/net/session/handlers/social/mod.rs index 25f8a1e..bc64d2e 100644 --- a/src/net/session/handlers/social/mod.rs +++ b/src/net/session/handlers/social/mod.rs @@ -5,7 +5,7 @@ use crate::net::wire; use anyhow::Result; use crate::identity::Identity; -use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand}; +use crate::net::{framing, payloads::*, types::NetCommand}; use super::core::now_ms; @@ -13,29 +13,14 @@ pub async fn handle_cmd( cmd: NetCommand, stream: &mut (impl tokio::io::AsyncWrite + Unpin), seq: &mut u32, - crypto: &SessionCrypto, identity: &Identity, ) -> Result<()> { match cmd { NetCommand::MediaControl(message) => { - framing::io::write_encrypted( - stream, - PID_MEDIA_CONTROL, - seq, - &wire::encode(&message)?, - crypto, - ) - .await?; + framing::write(stream, PID_MEDIA_CONTROL, seq, &wire::encode(&message)?).await?; } NetCommand::Webhook { operation, request } => { - framing::io::write_encrypted( - stream, - operation.packet_id(), - seq, - &wire::encode(&request)?, - crypto, - ) - .await?; + framing::write(stream, operation.packet_id(), seq, &wire::encode(&request)?).await?; } cmd @ (NetCommand::GuildCreate { .. } | NetCommand::GuildDelete { .. } @@ -52,9 +37,7 @@ pub async fn handle_cmd( | NetCommand::GuildMemberListFetch { .. } | NetCommand::GuildRoleAssign { .. } | NetCommand::GuildRoleUnassign { .. } - | NetCommand::GuildRoleListFetch { .. }) => { - guild::handle_cmd(cmd, stream, seq, crypto).await? - } + | NetCommand::GuildRoleListFetch { .. }) => guild::handle_cmd(cmd, stream, seq).await?, cmd @ (NetCommand::PresenceUpdate { .. } | NetCommand::FriendRequest { .. } @@ -64,7 +47,7 @@ pub async fn handle_cmd( | NetCommand::FriendList | NetCommand::BlockUser { .. } | NetCommand::UnblockUser { .. } - | NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq, crypto).await?, + | NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq).await?, NetCommand::ReactionAdd { channel_id, @@ -77,8 +60,7 @@ pub async fn handle_cmd( emoji, user_id: String::new(), })?; - framing::io::write_encrypted(stream, PID_MESSAGE_REACTION_ADD, seq, &payload, crypto) - .await?; + framing::write(stream, PID_MESSAGE_REACTION_ADD, seq, &payload).await?; } NetCommand::ReactionRemove { channel_id, @@ -91,14 +73,7 @@ pub async fn handle_cmd( emoji, user_id: String::new(), })?; - framing::io::write_encrypted( - stream, - PID_MESSAGE_REACTION_REMOVE, - seq, - &payload, - crypto, - ) - .await?; + framing::write(stream, PID_MESSAGE_REACTION_REMOVE, seq, &payload).await?; } NetCommand::MessageEdit { channel_id, @@ -110,7 +85,7 @@ pub async fn handle_cmd( channel_id, content, })?; - framing::io::write_encrypted(stream, PID_MESSAGE_EDIT, seq, &payload, crypto).await?; + framing::write(stream, PID_MESSAGE_EDIT, seq, &payload).await?; } NetCommand::MessageDelete { channel_id, @@ -120,11 +95,11 @@ pub async fn handle_cmd( message_id, channel_id, })?; - framing::io::write_encrypted(stream, PID_MESSAGE_DELETE, seq, &payload, crypto).await?; + framing::write(stream, PID_MESSAGE_DELETE, seq, &payload).await?; } NetCommand::DmStart { target_user_id } => { let payload = wire::encode(&DmStartPayload { target_user_id })?; - framing::io::write_encrypted(stream, PID_DM_START, seq, &payload, crypto).await?; + framing::write(stream, PID_DM_START, seq, &payload).await?; } NetCommand::DmSend { dm_id, content } => { let msg = DmMessagePayload { @@ -133,16 +108,15 @@ pub async fn handle_cmd( content, timestamp: now_ms(), }; - framing::io::write_encrypted(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?, crypto) - .await?; + framing::write(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?).await?; } NetCommand::TypingStart { channel_id } => { let payload = wire::encode(&TypingStart { channel_id })?; - framing::io::write_encrypted(stream, PID_TYPING_START, seq, &payload, crypto).await?; + framing::write(stream, PID_TYPING_START, seq, &payload).await?; } NetCommand::DmReadAck { dm_id } => { let payload = wire::encode(&crate::net::wire::DmReadAck { dm_id })?; - framing::io::write_encrypted(stream, PID_DM_READ_ACK, seq, &payload, crypto).await?; + framing::write(stream, PID_DM_READ_ACK, seq, &payload).await?; } NetCommand::DmSearch { dm_id, query } => { let payload = wire::encode(&DmHistoryPayload { @@ -151,7 +125,7 @@ pub async fn handle_cmd( search_query: if query.is_empty() { None } else { Some(query) }, limit: None, })?; - framing::io::write_encrypted(stream, PID_DM_HISTORY, seq, &payload, crypto).await?; + framing::write(stream, PID_DM_HISTORY, seq, &payload).await?; } NetCommand::E2eeDmKeyExchange { dm_id, @@ -161,19 +135,11 @@ pub async fn handle_cmd( dm_id, e2ee_public_key, })?; - framing::io::write_encrypted(stream, PID_E2EE_DM_KEY_EXCHANGE, seq, &payload, crypto) - .await?; + framing::write(stream, PID_E2EE_DM_KEY_EXCHANGE, seq, &payload).await?; } NetCommand::E2eeDmKeyExchangeAck { dm_id } => { let payload = wire::encode(&E2eeDmKeyExchangeAckPayload { dm_id })?; - framing::io::write_encrypted( - stream, - PID_E2EE_DM_KEY_EXCHANGE_ACK, - seq, - &payload, - crypto, - ) - .await?; + framing::write(stream, PID_E2EE_DM_KEY_EXCHANGE_ACK, seq, &payload).await?; } NetCommand::E2eeDmSend { dm_id, ciphertext } => { let msg = E2eeDmMessagePayload { @@ -182,14 +148,7 @@ pub async fn handle_cmd( ciphertext, timestamp: now_ms(), }; - framing::io::write_encrypted( - stream, - PID_E2EE_DM_MESSAGE, - seq, - &wire::encode(&msg)?, - crypto, - ) - .await?; + framing::write(stream, PID_E2EE_DM_MESSAGE, seq, &wire::encode(&msg)?).await?; } NetCommand::E2eeDmHistory { dm_id, limit } => { let payload = wire::encode(&E2eeDmHistoryPayload { @@ -197,8 +156,7 @@ pub async fn handle_cmd( messages: vec![], limit, })?; - framing::io::write_encrypted(stream, PID_E2EE_DM_HISTORY, seq, &payload, crypto) - .await?; + framing::write(stream, PID_E2EE_DM_HISTORY, seq, &payload).await?; } _ => {} } diff --git a/src/net/session/task.rs b/src/net/session/task.rs index ecb70b4..bd65546 100644 --- a/src/net/session/task.rs +++ b/src/net/session/task.rs @@ -3,6 +3,7 @@ use tokio::time::sleep; use tracing::{error, info}; use crate::identity::Identity; +use crate::net::trust::{TransportError, TrustStore}; use crate::net::types::{NetCommand, NetEvent}; use super::{ @@ -13,6 +14,7 @@ use super::{ pub async fn net_task( identity: Identity, + trust: TrustStore, mut cmd_rx: mpsc::Receiver, event_tx: mpsc::Sender, ) { @@ -71,6 +73,7 @@ pub async fn net_task( match session_loop( &identity, &session.address, + &trust, &mut session.channels, restored, &mut cmd_rx, @@ -97,7 +100,12 @@ pub async fn net_task( continue; } error!("session ended: {e}"); - let retry = session.auto_reconnect; + // Trust failures and protocol mismatches never improve by retrying. + let transport = e.downcast_ref::(); + if let Some(problem) = transport.and_then(TransportError::trust_problem) { + let _ = event_tx.send(NetEvent::TrustProblem(problem)).await; + } + let retry = session.auto_reconnect && transport.is_none(); let _ = event_tx .send(NetEvent::Disconnected { reason: e.to_string(), diff --git a/src/net/transport.rs b/src/net/transport.rs index 6e4f246..24d54e4 100644 --- a/src/net/transport.rs +++ b/src/net/transport.rs @@ -1,112 +1,509 @@ -//! TCP/TLS transport selection. TLS never falls back to plaintext after an error. -use anyhow::{Context, Result, bail}; +//! TLS 1.3 transport. There is no plaintext mode and no fallback after any error. +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result}; +use rustls::client::WebPkiServerVerifier; +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; +use rustls::{CertificateError, DigitallySignedStruct, SignatureScheme}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::TcpStream; +use super::trust::{ + ServerRecord, TransportError, TrustKind, TrustStore, parse_address, spki_fingerprint, +}; + pub trait AsyncStream: AsyncRead + AsyncWrite + Unpin + Send {} impl AsyncStream for T {} pub type Stream = Box; +/// ALPN protocol id required from the gateway. +pub const ALPN: &[u8] = b"vnox-lnex/3"; +/// TLS exporter label of the channel binding (must match the gateway). +pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding"; +/// Length of the exported channel binding. +pub const BINDING_LEN: usize = 32; + pub struct Connected { pub stream: Stream, pub peer: std::net::SocketAddr, + /// TLS exporter value of this connection, signed by both sides of the LNEx handshake. + pub binding: [u8; BINDING_LEN], + /// Trust store key (`host:port`). + pub trust_key: String, + /// Stored record at connect time (for the identity check). + pub record: Option, } -pub async fn connect(address: &str) -> Result { - Ok(connect_with_peer(address).await?.stream) + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Mode { + /// Certificate SPKI must equal the stored pin. + Pin, + /// Certificate must pass public WebPKI validation. + Ca, + /// Unknown server: finish the handshake to learn the fingerprint, send nothing. + Probe, } -pub async fn connect_with_peer(address: &str) -> Result { - let explicit_plain = address.starts_with("lnex://"); - let authority = address - .strip_prefix("lnexs://") - .or_else(|| address.strip_prefix("lnex://")) - .unwrap_or(address); - if authority.contains('/') - || authority.contains('@') - || authority.contains('?') - || authority.contains('#') - { - bail!("expected a server host and port"); + +#[derive(Default, Debug)] +struct Observed { + fingerprint: Option, + mismatch: bool, + ca_valid: bool, + ca_error: Option, +} + +#[derive(Debug)] +struct TrustVerifier { + mode: Mode, + pin: Option, + webpki: Arc, + algorithms: rustls::crypto::WebPkiSupportedAlgorithms, + observed: Arc>, +} + +impl TrustVerifier { + fn observe(&self, f: impl FnOnce(&mut Observed) -> R) -> R { + f(&mut self + .observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)) } - let (host, port) = if let Some(value) = authority.strip_prefix('[') { - let (host, tail) = value.split_once(']').context("invalid IPv6 address")?; - let port = if tail.is_empty() { - 7600 - } else { - tail.strip_prefix(':') - .context("invalid server address")? - .parse()? +} + +impl ServerCertVerifier for TrustVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> std::result::Result { + let fingerprint = spki_fingerprint(end_entity.as_ref()) + .map_err(|_| rustls::Error::InvalidCertificate(CertificateError::BadEncoding))?; + self.observe(|o| o.fingerprint = Some(fingerprint.clone())); + let public = || { + self.webpki.verify_server_cert( + end_entity, + intermediates, + server_name, + ocsp_response, + now, + ) }; - (host, port) - } else if let Some((host, port)) = authority.rsplit_once(':') { - (host, port.parse()?) - } else { - (authority, 7600) - }; - if host.is_empty() { - bail!("server host is empty"); + match self.mode { + Mode::Pin => { + if self.pin.as_deref() == Some(fingerprint.as_str()) { + Ok(ServerCertVerified::assertion()) + } else { + self.observe(|o| o.mismatch = true); + Err(rustls::Error::InvalidCertificate( + CertificateError::ApplicationVerificationFailure, + )) + } + } + Mode::Ca => public().inspect_err(|e| { + self.observe(|o| o.ca_error = Some(e.to_string())); + }), + Mode::Probe => { + // Accept only to complete the handshake; the caller drops the connection + // before any LNEx byte is sent unless the certificate is publicly valid. + if public().is_ok() { + self.observe(|o| o.ca_valid = true); + } + Ok(ServerCertVerified::assertion()) + } + } } - let tcp = TcpStream::connect((host, port)) + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms) + } + + fn supported_verify_schemes(&self) -> Vec { + self.algorithms.supported_schemes() + } +} + +/// Connect, verify and return the TLS stream plus the channel binding. +pub async fn connect(address: &str, trust: &TrustStore) -> Result { + Ok(connect_with_peer(address, trust).await?.stream) +} + +pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result { + let parsed = parse_address(address)?; + let tcp = TcpStream::connect((parsed.host.as_str(), parsed.port)) .await .context("connect to gateway")?; tcp.set_nodelay(true)?; let peer = tcp.peer_addr()?; - let loopback_host = host.eq_ignore_ascii_case("localhost") - || host - .parse::() - .is_ok_and(|ip| ip.is_loopback()); - let plain = explicit_plain || (!address.starts_with("lnexs://") && loopback_host); - if plain { - if !tcp.peer_addr()?.ip().is_loopback() { - bail!("plaintext LNEx is restricted to loopback development; use lnexs://"); - } - return Ok(Connected { - stream: Box::new(tcp), - peer, - }); - } + let record = trust.get(&parsed.key); + let (mode, pin) = match &record { + Some(r) if r.trust == TrustKind::Pin => (Mode::Pin, r.spki_sha256.clone()), + Some(_) => (Mode::Ca, None), + None => (Mode::Probe, None), + }; + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); - let config = rustls::ClientConfig::builder_with_provider( - rustls::crypto::aws_lc_rs::default_provider().into(), - ) - .with_protocol_versions(&[&rustls::version::TLS13])? - .with_root_certificates(roots) - .with_no_client_auth(); - let server_name = rustls::pki_types::ServerName::try_from(host.to_owned()) - .context("invalid TLS server name")?; - let tls = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config)) + let webpki = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone()) + .build() + .context("build public certificate verifier")?; + let observed = Arc::new(Mutex::new(Observed::default())); + let verifier = Arc::new(TrustVerifier { + mode, + pin, + webpki, + algorithms: provider.signature_verification_algorithms, + observed: observed.clone(), + }); + let mut config = rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13])? + .dangerous() + .with_custom_certificate_verifier(verifier) + .with_no_client_auth(); + config.alpn_protocols = vec![ALPN.to_vec()]; + let server_name = + ServerName::try_from(parsed.host.clone()).context("invalid TLS server name")?; + let tls = match tokio_rustls::TlsConnector::from(Arc::new(config)) .connect(server_name, tcp) .await - .context("TLS certificate/connection verification failed")?; + { + Ok(tls) => tls, + Err(error) => { + return Err(map_tls_error( + error, + &parsed.key, + mode, + record.as_ref().and_then(|r| r.spki_sha256.as_deref()), + &observed, + )); + } + }; + let seen = observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if mode == Mode::Probe { + if seen.ca_valid { + // A publicly valid certificate for this host name: remember it, no prompt. + drop(seen); + if let Err(error) = trust.trust_public_ca(&parsed.key) { + tracing::warn!(%error, "could not save trust record"); + } + } else { + let fingerprint = seen.fingerprint.clone().unwrap_or_default(); + return Err(TransportError::UntrustedServer { + address: parsed.key, + fingerprint, + } + .into()); + } + } else { + drop(seen); + } + let connection = tls.get_ref().1; + if connection.protocol_version() != Some(rustls::ProtocolVersion::TLSv1_3) + || connection.alpn_protocol() != Some(ALPN) + { + return Err(TransportError::ProtocolMismatch( + "The server did not negotiate TLS 1.3 with LNEx v3. Ask its owner to update the server." + .into(), + ) + .into()); + } + let binding = connection + .export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None) + .context("TLS exporter unavailable")?; Ok(Connected { stream: Box::new(tls), peer, + binding, + record: trust.get(&parsed.key), + trust_key: parsed.key, }) } +const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server or a non-VNOX port, ask its owner to update it."; + +fn map_tls_error( + error: std::io::Error, + key: &str, + mode: Mode, + pin: Option<&str>, + observed: &Mutex, +) -> anyhow::Error { + let seen = observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if mode == Mode::Pin && seen.mismatch { + return TransportError::FingerprintChanged { + address: key.to_string(), + expected: pin.unwrap_or_default().to_string(), + actual: seen.fingerprint.clone().unwrap_or_default(), + } + .into(); + } + if mode == Mode::Ca + && let Some(reason) = &seen.ca_error + { + return TransportError::CertificateInvalid { + address: key.to_string(), + reason: reason.clone(), + } + .into(); + } + let rustls_error = error + .get_ref() + .and_then(|inner| inner.downcast_ref::()); + match rustls_error { + Some( + rustls::Error::InvalidMessage(_) + | rustls::Error::PeerIncompatible(_) + | rustls::Error::PeerMisbehaved(_), + ) => TransportError::ProtocolMismatch(NOT_TLS13.into()).into(), + Some(rustls::Error::AlertReceived( + rustls::AlertDescription::ProtocolVersion + | rustls::AlertDescription::NoApplicationProtocol + | rustls::AlertDescription::HandshakeFailure + | rustls::AlertDescription::InsufficientSecurity, + )) => TransportError::ProtocolMismatch(NOT_TLS13.into()).into(), + _ if error.kind() == std::io::ErrorKind::UnexpectedEof => { + TransportError::ProtocolMismatch(NOT_TLS13.into()).into() + } + _ => anyhow::Error::new(error).context("TLS handshake failed"), + } +} + #[cfg(test)] mod tests { use super::*; - use tokio::io::AsyncReadExt; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + struct TestServer { + port: u16, + fingerprint: String, + /// Application bytes received per connection, and the server side exporter value. + received: tokio::sync::mpsc::UnboundedReceiver<(Vec, Option<[u8; BINDING_LEN]>)>, + task: tokio::task::JoinHandle<()>, + } + impl Drop for TestServer { + fn drop(&mut self) { + self.task.abort(); + } + } + + async fn serve( + versions: &[&'static rustls::SupportedProtocolVersion], + alpn: bool, + ) -> TestServer { + let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); + let fingerprint = spki_fingerprint(certified.cert.der().as_ref()).unwrap(); + let key = rustls::pki_types::PrivateKeyDer::try_from(certified.signing_key.serialize_der()) + .unwrap(); + let mut config = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::aws_lc_rs::default_provider(), + )) + .with_protocol_versions(versions) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![certified.cert.der().clone()], key) + .unwrap(); + if alpn { + config.alpn_protocols = vec![ALPN.to_vec()]; + } + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (sender, received) = tokio::sync::mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + loop { + let Ok((tcp, _)) = listener.accept().await else { + return; + }; + let acceptor = acceptor.clone(); + let sender = sender.clone(); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(tcp).await else { + return; + }; + let binding = tls + .get_ref() + .1 + .export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None) + .ok(); + let mut data = Vec::new(); + let _ = tls.read_to_end(&mut data).await; + let _ = sender.send((data, binding)); + }); + } + }); + TestServer { + port, + fingerprint, + received, + task, + } + } + + fn error_of(result: Result) -> TransportError { + match result { + Ok(_) => panic!("connection must not succeed"), + Err(error) => error + .downcast_ref::() + .cloned() + .unwrap_or_else(|| panic!("not a transport error: {error:#}")), + } + } + + async fn quiet(server: &mut TestServer) -> bool { + // A rejected connection must not have carried a single application byte. + match tokio::time::timeout( + std::time::Duration::from_millis(300), + server.received.recv(), + ) + .await + { + Ok(Some((data, _))) => data.is_empty(), + _ => true, + } + } + #[tokio::test] - async fn tls_failure_never_retries_plaintext() { + async fn unknown_self_signed_server_needs_confirmation_and_receives_nothing() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let address = format!("127.0.0.1:{}", server.port); + let error = error_of(connect_with_peer(&address, &trust).await); + assert_eq!( + error, + TransportError::UntrustedServer { + address: address.clone(), + fingerprint: server.fingerprint.clone() + } + ); + assert!(trust.get(&address).is_none(), "no implicit trust"); + assert!(quiet(&mut server).await); + } + + #[tokio::test] + async fn pinned_fingerprint_connects_and_shares_the_channel_binding() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + trust.pin(&key, &server.fingerprint).unwrap(); + // The lnex:// and lnexs:// schemes are both TLS and map to the same record. + let mut connected = connect_with_peer(&format!("lnex://{key}"), &trust) + .await + .unwrap(); + connected.stream.write_all(b"hello").await.unwrap(); + connected.stream.shutdown().await.unwrap(); + let (data, server_binding) = server.received.recv().await.unwrap(); + assert_eq!(data, b"hello"); + assert_eq!(server_binding, Some(connected.binding)); + assert_ne!(connected.binding, [0u8; BINDING_LEN]); + } + + #[tokio::test] + async fn changed_fingerprint_is_rejected_without_application_data() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + let trusted_before = "ab".repeat(32); + trust.pin(&key, &trusted_before).unwrap(); + let error = error_of(connect_with_peer(&key, &trust).await); + assert_eq!( + error, + TransportError::FingerprintChanged { + address: key.clone(), + expected: trusted_before.clone(), + actual: server.fingerprint.clone(), + } + ); + assert!(error.trust_problem().is_some()); + assert_eq!( + trust.get(&key).unwrap().spki_sha256.as_deref(), + Some(trusted_before.as_str()), + "the stored pin is never replaced automatically" + ); + assert!(quiet(&mut server).await); + } + + #[tokio::test] + async fn public_ca_trust_never_degrades_to_trust_on_first_use() { + let mut server = serve(&[&rustls::version::TLS13], true).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + trust.trust_public_ca(&key).unwrap(); + let error = error_of(connect_with_peer(&key, &trust).await); + assert!(matches!(error, TransportError::CertificateInvalid { .. })); + assert!(error.trust_problem().is_none()); + assert!(quiet(&mut server).await); + } + + #[tokio::test] + async fn tls12_only_server_is_rejected_with_a_clear_error() { + let server = serve(&[&rustls::version::TLS12], true).await; + let trust = TrustStore::in_memory(); + trust + .pin(&format!("127.0.0.1:{}", server.port), &server.fingerprint) + .unwrap(); + let error = + error_of(connect_with_peer(&format!("127.0.0.1:{}", server.port), &trust).await); + assert!(matches!(&error, TransportError::ProtocolMismatch(m) if m.contains("TLS 1.3"))); + } + + #[tokio::test] + async fn server_without_lnex_alpn_is_rejected() { + let server = serve(&[&rustls::version::TLS13], false).await; + let trust = TrustStore::in_memory(); + let key = format!("127.0.0.1:{}", server.port); + trust.pin(&key, &server.fingerprint).unwrap(); + let error = error_of(connect_with_peer(&key, &trust).await); + assert!(matches!(error, TransportError::ProtocolMismatch(_))); + } + + #[tokio::test] + async fn old_plaintext_v2_server_is_reported_and_never_retried() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let task = tokio::spawn(async move { let (mut stream, _) = listener.accept().await.unwrap(); + // An LNEx v2 gateway speaks first: HELLO frame header (id 0x0001). + stream + .write_all(&[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4]) + .await + .unwrap(); let first = stream.read_u8().await.unwrap(); assert_eq!( first, 22, - "first record must be a TLS handshake, never LNEx plaintext" + "the client must start a TLS handshake, never LNEx plaintext" ); drop(stream); assert!( - tokio::time::timeout(std::time::Duration::from_millis(30), listener.accept()) + tokio::time::timeout(std::time::Duration::from_millis(100), listener.accept()) .await .is_err(), - "certificate/handshake errors must not cause a downgrade reconnect" + "no downgrade reconnect after a failed TLS handshake" ); }); - assert!(connect(&format!("lnexs://{address}")).await.is_err()); + let trust = TrustStore::in_memory(); + let error = error_of(connect_with_peer(&format!("lnexs://{address}"), &trust).await); + assert!(matches!(&error, TransportError::ProtocolMismatch(m) if m.contains("TLS 1.3"))); task.await.unwrap(); } } diff --git a/src/net/trust.rs b/src/net/trust.rs new file mode 100644 index 0000000..1f01a29 --- /dev/null +++ b/src/net/trust.rs @@ -0,0 +1,569 @@ +//! Server trust for the TLS 1.3 control connection (LNEx v3). +//! +//! Model (see `VNOX-Server/docs/02-protocol/tls.md`): +//! * a stored **pin** (SHA-256 of the certificate SubjectPublicKeyInfo) always wins, +//! * without a record a certificate valid for the host name under the bundled public roots is +//! accepted (`ca` trust), +//! * otherwise the user must confirm the fingerprint once (trust on first use), +//! * a changed fingerprint is a hard error, never an automatic downgrade. +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Default gateway port. +pub const DEFAULT_PORT: u16 = 7600; + +/// Why a connection was stopped for trust reasons. Downcast from `anyhow::Error`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TransportError { + /// No trust record and no valid public certificate: the user must confirm `fingerprint`. + UntrustedServer { + address: String, + fingerprint: String, + }, + /// The pinned fingerprint of a known server changed. + FingerprintChanged { + address: String, + expected: String, + actual: String, + }, + /// The server authenticated with another Ed25519 identity than the stored one. + IdentityChanged { + address: String, + expected: String, + actual: String, + }, + /// A server marked as CA trusted no longer presents a valid public certificate. + CertificateInvalid { address: String, reason: String }, + /// The peer does not speak TLS 1.3 / LNEx v3. + ProtocolMismatch(String), +} + +impl std::fmt::Display for TransportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UntrustedServer { + address, + fingerprint, + } => write!( + f, + "server {address} is not trusted yet (fingerprint {fingerprint})" + ), + Self::FingerprintChanged { + address, + expected, + actual, + } => write!( + f, + "certificate fingerprint of {address} changed: expected {expected}, received {actual}" + ), + Self::IdentityChanged { + address, + expected, + actual, + } => write!( + f, + "server identity of {address} changed: expected {expected}, received {actual}" + ), + Self::CertificateInvalid { address, reason } => { + write!(f, "certificate of {address} is not valid: {reason}") + } + Self::ProtocolMismatch(message) => f.write_str(message), + } + } +} +impl std::error::Error for TransportError {} + +/// A trust decision the UI has to present. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TrustProblem { + Untrusted { + address: String, + fingerprint: String, + }, + FingerprintChanged { + address: String, + expected: String, + actual: String, + }, + IdentityChanged { + address: String, + expected: String, + actual: String, + }, +} + +impl TransportError { + /// The trust prompt for this error, if the user can act on it. + pub fn trust_problem(&self) -> Option { + match self.clone() { + Self::UntrustedServer { + address, + fingerprint, + } => Some(TrustProblem::Untrusted { + address, + fingerprint, + }), + Self::FingerprintChanged { + address, + expected, + actual, + } => Some(TrustProblem::FingerprintChanged { + address, + expected, + actual, + }), + Self::IdentityChanged { + address, + expected, + actual, + } => Some(TrustProblem::IdentityChanged { + address, + expected, + actual, + }), + _ => None, + } + } +} + +/// How a server is trusted. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TrustKind { + /// Certificate SPKI SHA-256 must equal `spki_sha256`. + Pin, + /// Certificate must validate for the host name under the bundled public roots. + Ca, +} + +/// Stored trust for one `host:port`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServerRecord { + pub trust: TrustKind, + /// Lower-case hex SHA-256 of the certificate SPKI (only for `pin`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spki_sha256: Option, + /// Lower-case hex Ed25519 server identity, stored after the first authenticated handshake. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identity: Option, + pub first_seen: i64, +} + +#[derive(Default, Serialize, Deserialize)] +struct FileFormat { + version: u32, + servers: BTreeMap, +} + +struct Inner { + path: Option, + servers: BTreeMap, +} + +/// Thread safe, file backed trust store (`/vnox/known_servers.json`). +#[derive(Clone)] +pub struct TrustStore { + inner: Arc>, +} + +/// A parsed server address. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServerAddress { + pub host: String, + pub port: u16, + /// Normalised `host:port` key used by the trust store. + pub key: String, +} + +/// Parse `host`, `host:port`, `[v6]:port`, optionally prefixed with `lnexs://` or `lnex://`. +/// Both schemes mean TLS 1.3; plaintext does not exist anymore. +pub fn parse_address(address: &str) -> Result { + let authority = address + .strip_prefix("lnexs://") + .or_else(|| address.strip_prefix("lnex://")) + .unwrap_or(address) + .trim(); + if authority.contains('/') + || authority.contains('@') + || authority.contains('?') + || authority.contains('#') + || authority.contains(char::is_whitespace) + { + bail!("expected a server host and port"); + } + let (host, port) = if let Some(value) = authority.strip_prefix('[') { + let (host, tail) = value.split_once(']').context("invalid IPv6 address")?; + let port = if tail.is_empty() { + DEFAULT_PORT + } else { + tail.strip_prefix(':') + .context("invalid server address")? + .parse()? + }; + (host, port) + } else if let Some((host, port)) = authority.rsplit_once(':') { + (host, port.parse()?) + } else { + (authority, DEFAULT_PORT) + }; + if host.is_empty() { + bail!("server host is empty"); + } + let host = host.to_ascii_lowercase(); + let key = if host.contains(':') { + format!("[{host}]:{port}") + } else { + format!("{host}:{port}") + }; + Ok(ServerAddress { host, port, key }) +} + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +impl TrustStore { + /// `/vnox/known_servers.json`. + pub fn default_path() -> Option { + dirs::config_dir().map(|p| p.join("vnox").join("known_servers.json")) + } + + /// Load the default store. A missing or unreadable file yields an empty store: the user + /// is asked again, trust is never granted implicitly. + pub fn load_default() -> Self { + match Self::default_path() { + Some(path) => Self::load(path), + None => Self::in_memory(), + } + } + + pub fn load(path: PathBuf) -> Self { + let servers = match std::fs::read(&path) { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(file) if file.version == 1 => file.servers, + Ok(file) => { + tracing::warn!(version = file.version, "unsupported trust store version"); + BTreeMap::new() + } + Err(error) => { + tracing::warn!(%error, "trust store is corrupt, starting empty"); + BTreeMap::new() + } + }, + Err(_) => BTreeMap::new(), + }; + Self { + inner: Arc::new(Mutex::new(Inner { + path: Some(path), + servers, + })), + } + } + + /// A store that is never written to disk (tests, headless tools). + pub fn in_memory() -> Self { + Self { + inner: Arc::new(Mutex::new(Inner { + path: None, + servers: BTreeMap::new(), + })), + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + pub fn get(&self, key: &str) -> Option { + self.lock().servers.get(key).cloned() + } + + /// Trust exactly this certificate fingerprint for `key` (replaces any previous record). + pub fn pin(&self, key: &str, spki_sha256: &str) -> Result<()> { + let fingerprint = normalize_fingerprint(spki_sha256)?; + let mut inner = self.lock(); + inner.servers.insert( + key.to_string(), + ServerRecord { + trust: TrustKind::Pin, + spki_sha256: Some(fingerprint), + identity: None, + first_seen: now_secs(), + }, + ); + Self::save(&inner) + } + + /// Remember that `key` presented a certificate valid under the public roots. + pub fn trust_public_ca(&self, key: &str) -> Result<()> { + let mut inner = self.lock(); + if inner.servers.contains_key(key) { + return Ok(()); + } + inner.servers.insert( + key.to_string(), + ServerRecord { + trust: TrustKind::Ca, + spki_sha256: None, + identity: None, + first_seen: now_secs(), + }, + ); + Self::save(&inner) + } + + /// Store the authenticated server identity once. + pub fn set_identity(&self, key: &str, identity_hex: &str) -> Result<()> { + let mut inner = self.lock(); + let Some(record) = inner.servers.get_mut(key) else { + return Ok(()); + }; + if record.identity.as_deref() == Some(identity_hex) { + return Ok(()); + } + if record.identity.is_some() { + bail!("refusing to overwrite the stored server identity"); + } + record.identity = Some(identity_hex.to_string()); + Self::save(&inner) + } + + /// Delete the record. The next connection starts a fresh trust decision. + pub fn forget(&self, key: &str) -> Result<()> { + let mut inner = self.lock(); + if inner.servers.remove(key).is_some() { + Self::save(&inner)?; + } + Ok(()) + } + + fn save(inner: &Inner) -> Result<()> { + let Some(path) = &inner.path else { + return Ok(()); + }; + let parent = path.parent().context("trust store path has no parent")?; + std::fs::create_dir_all(parent)?; + let bytes = serde_json::to_vec_pretty(&FileFormat { + version: 1, + servers: inner.servers.clone(), + })?; + write_private(path, &bytes) + } +} + +fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { + use std::io::Write; + let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let result = (|| -> Result<()> { + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&temporary, path)?; + Ok(()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result +} + +/// Accept `ab:cd:...`, upper or lower case, with optional `sha256:` prefix; return 64 lower-case hex. +pub fn normalize_fingerprint(value: &str) -> Result { + let cleaned: String = value + .trim() + .trim_start_matches("sha256:") + .chars() + .filter(|c| *c != ':' && !c.is_whitespace()) + .collect::() + .to_ascii_lowercase(); + if cleaned.len() != 64 || !cleaned.chars().all(|c| c.is_ascii_hexdigit()) { + bail!("a SHA-256 fingerprint is 64 hexadecimal characters"); + } + Ok(cleaned) +} + +/// `ab cd ef ...` grouped for display (pairs separated by colons). +pub fn display_fingerprint(hex_fingerprint: &str) -> String { + hex_fingerprint + .as_bytes() + .chunks(2) + .map(|pair| String::from_utf8_lossy(pair).to_ascii_uppercase()) + .collect::>() + .join(":") +} + +fn read_tlv(data: &[u8]) -> Result<(u8, usize, usize)> { + let tag = *data.first().context("truncated DER")?; + let first = *data.get(1).context("truncated DER")?; + let (header, length) = if first & 0x80 == 0 { + (2usize, first as usize) + } else { + let count = (first & 0x7F) as usize; + if count == 0 || count > 4 { + bail!("unsupported DER length"); + } + let bytes = data.get(2..2 + count).context("truncated DER")?; + ( + 2 + count, + bytes.iter().fold(0usize, |acc, b| (acc << 8) | *b as usize), + ) + }; + if data.len() < header + length { + bail!("truncated DER"); + } + Ok((tag, header, length)) +} + +/// The complete SubjectPublicKeyInfo SEQUENCE of an X.509 certificate. +pub fn spki_der(cert_der: &[u8]) -> Result<&[u8]> { + let (tag, header, length) = read_tlv(cert_der)?; + anyhow::ensure!(tag == 0x30, "certificate is not a SEQUENCE"); + let tbs_all = &cert_der[header..header + length]; + let (tag, header, length) = read_tlv(tbs_all)?; + anyhow::ensure!(tag == 0x30, "tbsCertificate is not a SEQUENCE"); + let mut rest = &tbs_all[header..header + length]; + // [version], serial, signature, issuer, validity, subject precede the SPKI. + let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 }; + while skip > 0 { + let (_, header, length) = read_tlv(rest)?; + rest = &rest[header + length..]; + skip -= 1; + } + let (tag, header, length) = read_tlv(rest)?; + anyhow::ensure!(tag == 0x30, "SubjectPublicKeyInfo is not a SEQUENCE"); + Ok(&rest[..header + length]) +} + +/// Lower-case hex SHA-256 over the certificate SPKI DER. +pub fn spki_fingerprint(cert_der: &[u8]) -> Result { + Ok(hex::encode(Sha256::digest(spki_der(cert_der)?))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_path() -> PathBuf { + std::env::temp_dir() + .join(format!("vnox-trust-{}", uuid::Uuid::new_v4())) + .join("known_servers.json") + } + + #[test] + fn address_forms_are_normalised() { + assert_eq!( + parse_address("Example.ORG").unwrap().key, + "example.org:7600" + ); + assert_eq!( + parse_address("lnexs://example.org:7700").unwrap().key, + "example.org:7700" + ); + assert_eq!(parse_address("lnex://[::1]").unwrap().key, "[::1]:7600"); + assert_eq!(parse_address("127.0.0.1:1").unwrap().port, 1); + for bad in ["", "host/path", "user@host", "host?x", "host#x", "a b"] { + assert!(parse_address(bad).is_err(), "{bad}"); + } + } + + #[test] + fn fingerprint_normalisation_and_display() { + let hex64 = "ab".repeat(32); + let colons = hex64 + .as_bytes() + .chunks(2) + .map(|c| String::from_utf8_lossy(c).to_string()) + .collect::>() + .join(":") + .to_ascii_uppercase(); + assert_eq!(normalize_fingerprint(&colons).unwrap(), hex64); + assert_eq!( + normalize_fingerprint(&format!("sha256:{hex64}")).unwrap(), + hex64 + ); + assert!(normalize_fingerprint("abcd").is_err()); + assert!(normalize_fingerprint(&"zz".repeat(32)).is_err()); + assert_eq!(display_fingerprint(&hex64), colons); + } + + #[test] + fn spki_fingerprint_of_ed25519_certificate_is_hash_of_fixed_prefix_and_key() { + let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap(); + let cert = rcgen::CertificateParams::new(vec!["x.example".into()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let mut spki = vec![ + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, + ]; + spki.extend_from_slice(key.public_key_raw()); + assert_eq!( + spki_fingerprint(cert.der().as_ref()).unwrap(), + hex::encode(Sha256::digest(&spki)) + ); + assert!(spki_fingerprint(b"junk").is_err()); + } + + #[test] + fn records_persist_with_private_permissions_and_forget_works() { + let path = temp_path(); + let store = TrustStore::load(path.clone()); + let fingerprint = "cd".repeat(32); + store.pin("h:7600", &fingerprint).unwrap(); + store.set_identity("h:7600", &"11".repeat(32)).unwrap(); + // The identity of a known server can never be silently replaced. + assert!(store.set_identity("h:7600", &"22".repeat(32)).is_err()); + let reloaded = TrustStore::load(path.clone()); + let record = reloaded.get("h:7600").unwrap(); + assert_eq!(record.trust, TrustKind::Pin); + assert_eq!(record.spki_sha256.as_deref(), Some(fingerprint.as_str())); + assert_eq!(record.identity.as_deref(), Some("11".repeat(32).as_str())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + reloaded.forget("h:7600").unwrap(); + assert!(TrustStore::load(path.clone()).get("h:7600").is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn corrupt_store_starts_empty_instead_of_trusting() { + let path = temp_path(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"{not json").unwrap(); + let store = TrustStore::load(path.clone()); + assert!(store.get("h:7600").is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn public_ca_record_is_not_overwritten_and_pin_rejects_bad_hex() { + let store = TrustStore::in_memory(); + store.trust_public_ca("h:1").unwrap(); + store.trust_public_ca("h:1").unwrap(); + assert_eq!(store.get("h:1").unwrap().trust, TrustKind::Ca); + assert!(store.pin("h:1", "nothex").is_err()); + } +} diff --git a/src/net/types/event.rs b/src/net/types/event.rs index 806035d..17851b5 100644 --- a/src/net/types/event.rs +++ b/src/net/types/event.rs @@ -20,6 +20,8 @@ pub enum NetEvent { reason: String, will_retry: bool, }, + /// The user has to decide about a server certificate (first use or changed fingerprint). + TrustProblem(crate::net::trust::TrustProblem), Reconnecting { attempt: u32, delay_secs: u64, diff --git a/src/ui/bridge.rs b/src/ui/bridge.rs index 9f5f3cd..e942eed 100644 --- a/src/ui/bridge.rs +++ b/src/ui/bridge.rs @@ -382,6 +382,30 @@ pub fn sync_connect(window: &MainWindow, state: &UiState) { ConnState::Connecting | ConnState::Reconnecting { .. } )); window.set_auto_reconnect(state.auto_reconnect); + { + use crate::ui::state::TrustPromptKind; + let (kind, address, received, expected) = match &state.trust_prompt { + None => (0, "", "", ""), + Some(prompt) => ( + match prompt.kind { + TrustPromptKind::FirstUse => 1, + TrustPromptKind::FingerprintChanged => 2, + TrustPromptKind::IdentityChanged => 3, + }, + prompt.address.as_str(), + prompt.received.as_str(), + prompt.expected.as_str(), + ), + }; + window.set_trust_kind(kind); + window.set_trust_address(SharedString::from(address)); + window.set_trust_received(SharedString::from( + vnox_client::net::trust::display_fingerprint(received), + )); + window.set_trust_expected(SharedString::from( + vnox_client::net::trust::display_fingerprint(expected), + )); + } if let ConnState::Connected { ref node_name, .. } = state.conn { window.set_node_name(SharedString::from(node_name.as_str())); } else if matches!(state.conn, ConnState::Disconnected) { diff --git a/src/ui/slint/connect.slint b/src/ui/slint/connect.slint index 6d0f3f4..7b5348e 100644 --- a/src/ui/slint/connect.slint +++ b/src/ui/slint/connect.slint @@ -16,6 +16,14 @@ export component ConnectScreen inherits Rectangle { callback remove-bookmark(string); callback add-bookmark(string); callback open-settings(); + // 0 none, 1 first use, 2 certificate fingerprint changed, 3 server identity changed + in property trust-kind: 0; + in property trust-address; + in property trust-received; + in property trust-expected; + callback trust-accept(); + callback trust-forget(); + callback trust-dismiss(); background: Theme.bg-base; VerticalLayout { padding: 32px; spacing: 22px; @@ -86,4 +94,50 @@ export component ConnectScreen inherits Rectangle { Rectangle { vertical-stretch: 1; } Text { text: @tr("Your server. Your community."); color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-alignment: center; } } + if root.trust-kind != 0 : Rectangle { + background: #000000a0; + TouchArea { } + HorizontalLayout { + Rectangle { horizontal-stretch: 1; } + VerticalLayout { + Rectangle { vertical-stretch: 1; } + Rectangle { + width: 560px; + height: trust-card.preferred-height; + background: Theme.bg-surface; border-radius: 14px; + border-width: 1px; border-color: root.trust-kind == 1 ? Theme.border : Theme.danger; + trust-card := VerticalLayout { + padding: 26px; spacing: 12px; alignment: start; + Text { + text: root.trust-kind == 1 ? @tr("Trust this server?") : root.trust-kind == 2 ? @tr("Server fingerprint changed") : @tr("Server identity changed"); + color: root.trust-kind == 1 ? Theme.text-primary : Theme.danger; + font-size: Math.max(11px, Theme.font-size * 1.375); font-weight: 600; wrap: word-wrap; + } + Text { + text: root.trust-kind == 1 + ? @tr("This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match.") + : root.trust-kind == 2 + ? @tr("The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.") + : @tr("The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."); + color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; + } + Text { text: @tr("Server address"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); } + Text { text: root.trust-address; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); wrap: word-wrap; } + if root.trust-kind != 1 : Text { text: @tr("Previously trusted fingerprint"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); } + if root.trust-kind != 1 : Text { text: root.trust-expected; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; } + Text { text: root.trust-kind == 1 ? @tr("Fingerprint (SHA-256)") : @tr("Received fingerprint"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); } + Text { text: root.trust-received; color: root.trust-kind == 1 ? Theme.accent : Theme.danger; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; } + HorizontalLayout { + spacing: 9px; alignment: end; + if root.trust-kind != 1 : ActionButton { text: @tr("Forget this server"); danger: true; clicked => { root.trust-forget(); } } + ActionButton { text: root.trust-kind == 1 ? @tr("Cancel") : @tr("Close"); clicked => { root.trust-dismiss(); } } + if root.trust-kind == 1 : ActionButton { text: @tr("Trust and connect"); active: true; clicked => { root.trust-accept(); } } + } + } + } + Rectangle { vertical-stretch: 1; } + } + Rectangle { horizontal-stretch: 1; } + } + } } diff --git a/src/ui/slint/main.slint b/src/ui/slint/main.slint index f6a4ac4..0cf3032 100644 --- a/src/ui/slint/main.slint +++ b/src/ui/slint/main.slint @@ -71,6 +71,11 @@ export component MainWindow inherits Window { in-out property connecting: false; in-out property auto-reconnect: false; in-out property node-name: ""; + // 0 none, 1 first use, 2 certificate fingerprint changed, 3 server identity changed + in-out property trust-kind: 0; + in-out property trust-address: ""; + in-out property trust-received: ""; + in-out property trust-expected: ""; in-out property identity-pubkey: ""; in-out property vault-enabled: false; @@ -155,6 +160,9 @@ export component MainWindow inherits Window { callback connect(string); callback remove-bookmark(string); callback add-bookmark(string); + callback trust-accept(); + callback trust-forget(); + callback trust-dismiss(); callback close-settings(); callback set-passphrase(string, string); callback remove-passphrase(); @@ -177,6 +185,13 @@ export component MainWindow inherits Window { connecting: root.connecting; auto-reconnect <=> root.auto-reconnect; node-name: root.node-name; + trust-kind: root.trust-kind; + trust-address: root.trust-address; + trust-received: root.trust-received; + trust-expected: root.trust-expected; + trust-accept => { root.trust-accept(); } + trust-forget => { root.trust-forget(); } + trust-dismiss => { root.trust-dismiss(); } open-settings => { root.open-settings(); } address-edited(text) => { root.address-edited(text); } auto-reconnect-changed(value) => { root.auto-reconnect-changed(value); } diff --git a/src/ui/state/default.rs b/src/ui/state/default.rs index 9b1bf93..5d52840 100644 --- a/src/ui/state/default.rs +++ b/src/ui/state/default.rs @@ -12,6 +12,7 @@ impl Default for UiState { bookmarks: default_bookmarks(), selected_bookmark: 0, status_msg: None, + trust_prompt: None, channels: Vec::new(), active_channel: None, messages: Default::default(), diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 0e83b31..53b8061 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -4,7 +4,7 @@ mod navigation; mod types; pub use models::{Channel, ChatMessage, DmConversation, FriendState, GuildState, NodeBookmark}; -pub use types::{ConnState, UiState, VoiceUiState}; +pub use types::{ConnState, TrustPrompt, TrustPromptKind, UiState, VoiceUiState}; use models::bookmark_label_from_address; diff --git a/src/ui/state/types.rs b/src/ui/state/types.rs index c4124a3..793de86 100644 --- a/src/ui/state/types.rs +++ b/src/ui/state/types.rs @@ -24,6 +24,25 @@ pub enum ConnState { }, } +/// A pending server trust decision (first use or blocked fingerprint change). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TrustPrompt { + pub kind: TrustPromptKind, + /// Trust store key, `host:port`. + pub address: String, + /// Lower-case hex value that was received. + pub received: String, + /// Lower-case hex value that was trusted before (changed fingerprint or identity). + pub expected: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrustPromptKind { + FirstUse, + FingerprintChanged, + IdentityChanged, +} + pub struct UiState { pub appearance: crate::ui::appearance::AppearancePreferences, pub conn: ConnState, @@ -31,6 +50,7 @@ pub struct UiState { pub bookmarks: Vec, pub selected_bookmark: usize, pub status_msg: Option, + pub trust_prompt: Option, pub channels: Vec, pub active_channel: Option, diff --git a/src/ui/update.rs b/src/ui/update.rs index b1ec3dc..c0b49f2 100644 --- a/src/ui/update.rs +++ b/src/ui/update.rs @@ -75,6 +75,41 @@ pub fn process_net_events(state: &mut AppState) { }); } } + NetEvent::TrustProblem(problem) => { + use crate::ui::state::{TrustPrompt, TrustPromptKind}; + use vnox_client::net::TrustProblem; + state.ui.trust_prompt = Some(match problem { + TrustProblem::Untrusted { + address, + fingerprint, + } => TrustPrompt { + kind: TrustPromptKind::FirstUse, + address, + received: fingerprint, + expected: String::new(), + }, + TrustProblem::FingerprintChanged { + address, + expected, + actual, + } => TrustPrompt { + kind: TrustPromptKind::FingerprintChanged, + address, + received: actual, + expected, + }, + TrustProblem::IdentityChanged { + address, + expected, + actual, + } => TrustPrompt { + kind: TrustPromptKind::IdentityChanged, + address, + received: actual, + expected, + }, + }); + } NetEvent::Disconnected { reason, will_retry } => { if let Some(ui) = &state.webhooks { ui.disconnected(); @@ -97,10 +132,14 @@ pub fn process_net_events(state: &mut AppState) { state.ui.active_channel = None; state.ui.user_names.clear(); state.ui.rtt_ms = None; - state.ui.status_msg = Some(crate::ui::i18n::Message::with( - "Disconnected: {reason}", - vec![("reason", reason.to_string())], - )); + state.ui.status_msg = if state.ui.trust_prompt.is_some() { + None + } else { + Some(crate::ui::i18n::Message::with( + "Disconnected: {reason}", + vec![("reason", reason.to_string())], + )) + }; } if !will_retry { state.ui.dm_conversations.clear(); @@ -348,6 +387,7 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) { | NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"), NetEvent::Connected { .. } | NetEvent::Disconnected { .. } + | NetEvent::TrustProblem(_) | NetEvent::Reconnecting { .. } | NetEvent::VoicePacket { .. } | NetEvent::E2eeDmKeyExchange { .. } diff --git a/tests/gateway_interop.rs b/tests/gateway_interop.rs index 2979392..c12eb1c 100644 --- a/tests/gateway_interop.rs +++ b/tests/gateway_interop.rs @@ -1,4 +1,5 @@ -//! Real gateway fixture. Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored. +//! Real gateway fixture over TLS 1.3 (LNEx v3). +//! Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored. use std::{ path::PathBuf, process::{Child, Command, Stdio}, @@ -6,7 +7,7 @@ use std::{ }; use vnox_client::{ identity, - net::{self, NetCommand, NetEvent, NetHandle}, + net::{self, NetCommand, NetEvent, NetHandle, TrustProblem, TrustStore}, }; struct Gateway { @@ -27,15 +28,15 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Net tokio::time::timeout(Duration::from_secs(8), async { loop { if let Some(event) = handle.try_recv() { + if predicate(&event) { + return event; + } if let NetEvent::Disconnected { ref reason, .. } = event { panic!("unexpected disconnect: {reason}"); } if let NetEvent::Error { code, ref message } = event { panic!("gateway error {code}: {message}"); } - if predicate(&event) { - return event; - } if let NetEvent::WebhookError(ref result) = event { panic!( "unexpected webhook error at stage {stage}, request {}: {} ({})", @@ -49,6 +50,43 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Net .await .unwrap_or_else(|_| panic!("gateway event timeout at stage {stage}")) } +/// First connection: the client must stop at the untrusted certificate, show the same +/// fingerprint the gateway published, and connect only after the fingerprint is pinned. +async fn connect_with_first_trust(handle: &NetHandle, address: &str, published: &str) { + handle + .send(NetCommand::Connect { + address: address.into(), + auto_reconnect: false, + }) + .await; + let prompt = event(handle, |e| matches!(e, NetEvent::TrustProblem(_))).await; + let NetEvent::TrustProblem(TrustProblem::Untrusted { fingerprint, .. }) = prompt else { + panic!("expected the first-use trust prompt, got {prompt:?}"); + }; + assert_eq!( + fingerprint, published, + "the prompt must show the fingerprint published by the gateway" + ); + event(handle, |e| { + matches!( + e, + NetEvent::Disconnected { + will_retry: false, + .. + } + ) + }) + .await; + let key = net::trust::parse_address(address).unwrap().key; + handle.trust().pin(&key, &fingerprint).unwrap(); + handle + .send(NetCommand::Connect { + address: address.into(), + auto_reconnect: false, + }) + .await; +} + fn free_port() -> u16 { std::net::TcpListener::bind("127.0.0.1:0") .unwrap() @@ -59,7 +97,7 @@ fn free_port() -> u16 { #[tokio::test] #[ignore = "requires a freshly built current VNOX gateway binary"] -async fn native_network_connects_signed_v2_and_exchanges_protobuf_chat() { +async fn native_network_connects_signed_v3_over_tls_and_exchanges_protobuf_chat() { let binary = std::env::var_os("VNOX_GATEWAY_BIN") .expect("set VNOX_GATEWAY_BIN to the current server binary"); let directory = std::env::temp_dir().join(format!("vnox-interop-{}", uuid::Uuid::new_v4())); @@ -95,6 +133,7 @@ mode = "private" .stderr(Stdio::inherit()) .spawn() .unwrap(); + let data_dir = directory.clone(); let _gateway = Gateway { child, directory }; let address = format!("127.0.0.1:{port}"); tokio::time::timeout(Duration::from_secs(8), async { @@ -110,13 +149,44 @@ mode = "private" // In-memory identity only; never touch a real profile or encrypted vault. let alice_identity = identity::generate("interop-alice"); let alice_user_id = alice_identity.pubkey_hex.clone(); - let alice = net::spawn(alice_identity); - alice + // Trust is kept in memory: never touch the real ~/.config/vnox/known_servers.json. + let alice = net::spawn_with_trust(alice_identity, TrustStore::in_memory()); + let published = std::fs::read_to_string(data_dir.join("tls").join("fingerprint.txt")) + .unwrap() + .trim() + .to_string(); + // A client that pinned another fingerprint is blocked before sending anything. + let impostor = + net::spawn_with_trust(identity::generate("interop-pin"), TrustStore::in_memory()); + impostor + .trust() + .pin( + &net::trust::parse_address(&address).unwrap().key, + &"ab".repeat(32), + ) + .unwrap(); + impostor .send(NetCommand::Connect { - address, - auto_reconnect: false, + address: address.clone(), + auto_reconnect: true, }) .await; + let blocked = event(&impostor, |e| matches!(e, NetEvent::TrustProblem(_))).await; + assert!(matches!( + blocked, + NetEvent::TrustProblem(TrustProblem::FingerprintChanged { ref actual, .. }) if actual == &published + )); + event(&impostor, |e| { + matches!( + e, + NetEvent::Disconnected { + will_retry: false, + .. + } + ) + }) + .await; + connect_with_first_trust(&alice, &address, &published).await; event( &alice, |e| matches!(e,NetEvent::Connected {node_name,..} if node_name=="interop-node"), @@ -260,7 +330,16 @@ mode = "private" event(&alice,|e|matches!(e,NetEvent::WebhookResult(result) if result.request_id=="revoke-fixture" && result.secret.is_empty() && result.hook.as_ref().is_some_and(|hook|hook.revoked))).await; let guest_identity = identity::generate("webhook-unprivileged"); let guest_user_id = guest_identity.pubkey_hex.clone(); - let guest = net::spawn(guest_identity); + let guest = net::spawn_with_trust(guest_identity, TrustStore::in_memory()); + guest + .trust() + .pin( + &net::trust::parse_address(&format!("127.0.0.1:{port}")) + .unwrap() + .key, + &published, + ) + .unwrap(); guest .send(NetCommand::Connect { address: format!("127.0.0.1:{port}"), @@ -301,6 +380,22 @@ mode = "private" .await; alice.send(NetCommand::FriendList).await; event(&alice,|e|matches!(e,NetEvent::FriendList {friends} if friends.iter().any(|friend|friend.user_id==guest_user_id))).await; + // The server identity was stored after the first authenticated handshake. + let identity_file: serde_json::Value = + serde_json::from_slice(&std::fs::read(data_dir.join("server_identity.json")).unwrap()) + .unwrap(); + let record = alice + .trust() + .get( + &net::trust::parse_address(&format!("127.0.0.1:{port}")) + .unwrap() + .key, + ) + .unwrap(); + assert_eq!( + record.identity.as_deref(), + identity_file["pubkey_hex"].as_str() + ); guest.send(NetCommand::Disconnect).await; alice.send(NetCommand::Disconnect).await; } diff --git a/translations/en/LC_MESSAGES/vnox-client.po b/translations/en/LC_MESSAGES/vnox-client.po index 992e947..08cef80 100644 --- a/translations/en/LC_MESSAGES/vnox-client.po +++ b/translations/en/LC_MESSAGES/vnox-client.po @@ -214,9 +214,15 @@ msgstr "Export keys" msgid "Extra dark" msgstr "Extra dark" +msgid "Fingerprint (SHA-256)" +msgstr "Fingerprint (SHA-256)" + msgid "For example: /home/user/themes/my-vnox.css" msgstr "For example: /home/user/themes/my-vnox.css" +msgid "Forget this server" +msgstr "Forget this server" + msgid "Friends" msgstr "Friends" @@ -409,6 +415,9 @@ msgstr "Preview active · not broadcasting" msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch." msgstr "Preview stays local until you start broadcasting. Only members of your voice channel can watch." +msgid "Previously trusted fingerprint" +msgstr "Previously trusted fingerprint" + msgid "Profile and keys" msgstr "Profile and keys" @@ -424,6 +433,9 @@ msgstr "Push to talk" msgid "Receive updates here, or send signed channel events to your own service." msgstr "Receive updates here, or send signed channel events to your own service." +msgid "Received fingerprint" +msgstr "Received fingerprint" + msgid "Reconnect automatically" msgstr "Reconnect automatically" @@ -496,6 +508,12 @@ msgstr "Send" msgid "Server address" msgstr "Server address" +msgid "Server fingerprint changed" +msgstr "Server fingerprint changed" + +msgid "Server identity changed" +msgstr "Server identity changed" + msgid "Settings" msgstr "Settings" @@ -541,9 +559,15 @@ msgstr "Text size" msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key." msgstr "The backup passphrase is optional. Without it, your backup contains an unprotected secret key." +msgid "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." + msgid "The old secret stops working. Update the external integration with the new secret." msgstr "The old secret stops working. Update the external integration with the new secret." +msgid "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." + msgid "Theme editor" msgstr "Theme editor" @@ -556,6 +580,15 @@ msgstr "Themes, colours and text" msgid "This cannot be undone." msgstr "This cannot be undone." +msgid "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match." +msgstr "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match." + +msgid "Trust and connect" +msgstr "Trust and connect" + +msgid "Trust this server?" +msgstr "Trust this server?" + msgid "Undeafen" msgstr "Undeafen" diff --git a/translations/ru.json b/translations/ru.json index 5a27904..dac5a8a 100644 --- a/translations/ru.json +++ b/translations/ru.json @@ -351,5 +351,18 @@ "Starting broadcast…": "Запуск трансляции…", "WebRTC connection timed out": "Время ожидания соединения WebRTC истекло", "Broadcast authorization timed out": "Время ожидания разрешения на трансляцию истекло", - "Broadcast connection timed out": "Время ожидания подключения к трансляции истекло" + "Broadcast connection timed out": "Время ожидания подключения к трансляции истекло", + "Trust this server?": "Доверять этому серверу?", + "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match.": "Это первое подключение к этому серверу. Его сертификат выдан не публичным центром сертификации, поэтому Vnox не может проверить его автоматически. Сравни отпечаток с тем, что опубликовал владелец сервера, и доверяй, только если они совпадают.", + "Server fingerprint changed": "Отпечаток сервера изменился", + "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.": "Сертификат этого сервера отличается от того, которому ты доверял раньше. Это может быть атакой на соединение, или владелец переустановил сервер. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение.", + "Server identity changed": "Ключ сервера изменился", + "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.": "Сервер подтвердил другой ключ, чем тот, которому ты доверял раньше. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение.", + "Previously trusted fingerprint": "Ранее доверенный отпечаток", + "Fingerprint (SHA-256)": "Отпечаток (SHA-256)", + "Received fingerprint": "Полученный отпечаток", + "Forget this server": "Забыть этот сервер", + "Trust and connect": "Доверять и подключиться", + "Could not save the trusted fingerprint": "Не удалось сохранить доверенный отпечаток", + "Server forgotten. Connect again to review its fingerprint.": "Сервер забыт. Подключись снова, чтобы проверить его отпечаток." } diff --git a/translations/ru/LC_MESSAGES/vnox-client.po b/translations/ru/LC_MESSAGES/vnox-client.po index f05dd88..c2dcca4 100644 --- a/translations/ru/LC_MESSAGES/vnox-client.po +++ b/translations/ru/LC_MESSAGES/vnox-client.po @@ -215,9 +215,15 @@ msgstr "Экспортировать ключи" msgid "Extra dark" msgstr "Мега-тёмная" +msgid "Fingerprint (SHA-256)" +msgstr "Отпечаток (SHA-256)" + msgid "For example: /home/user/themes/my-vnox.css" msgstr "Например: /home/user/themes/my-vnox.css" +msgid "Forget this server" +msgstr "Забыть этот сервер" + msgid "Friends" msgstr "Друзья" @@ -410,6 +416,9 @@ msgstr "Предпросмотр активен · без трансляции" msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch." msgstr "Предпросмотр остаётся локальным, пока ты не начнёшь трансляцию. Смотреть её могут только участники твоей голосовой комнаты." +msgid "Previously trusted fingerprint" +msgstr "Ранее доверенный отпечаток" + msgid "Profile and keys" msgstr "Профиль и ключи" @@ -425,6 +434,9 @@ msgstr "Нажми и говори" msgid "Receive updates here, or send signed channel events to your own service." msgstr "Получайте обновления в этом канале или отправляйте подписанные события в свой сервис." +msgid "Received fingerprint" +msgstr "Полученный отпечаток" + msgid "Reconnect automatically" msgstr "Переподключаться при потере связи" @@ -497,6 +509,12 @@ msgstr "Отправить" msgid "Server address" msgstr "Адрес сервера" +msgid "Server fingerprint changed" +msgstr "Отпечаток сервера изменился" + +msgid "Server identity changed" +msgstr "Ключ сервера изменился" + msgid "Settings" msgstr "Настройки" @@ -542,9 +560,15 @@ msgstr "Размер текста" msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key." msgstr "Пароль резервной копии можно оставить пустым. Такая копия содержит секретный ключ без защиты." +msgid "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "Сертификат этого сервера отличается от того, которому ты доверял раньше. Это может быть атакой на соединение, или владелец переустановил сервер. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение." + msgid "The old secret stops working. Update the external integration with the new secret." msgstr "Старый секрет перестанет работать. Укажите новый секрет во внешней интеграции." +msgid "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected." +msgstr "Сервер подтвердил другой ключ, чем тот, которому ты доверял раньше. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение." + msgid "Theme editor" msgstr "Редактор темы" @@ -557,6 +581,15 @@ msgstr "Темы, цвета и текст" msgid "This cannot be undone." msgstr "Это действие нельзя отменить." +msgid "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match." +msgstr "Это первое подключение к этому серверу. Его сертификат выдан не публичным центром сертификации, поэтому Vnox не может проверить его автоматически. Сравни отпечаток с тем, что опубликовал владелец сервера, и доверяй, только если они совпадают." + +msgid "Trust and connect" +msgstr "Доверять и подключиться" + +msgid "Trust this server?" +msgstr "Доверять этому серверу?" + msgid "Undeafen" msgstr "Включить звук" From 79e5755d2dd66f831b54ff4cf606bb43ea9f47d1 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:05:19 +0200 Subject: [PATCH 3/8] docs: describe TLS 1.3 control connection and LNEx v3 in client docs Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4 --- CHANGELOG.md | 7 +++ README.md | 4 +- docs/05-features/encryption.md | 98 +++++++++++----------------------- 3 files changed, 41 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef57f30..4bfc1b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Changed (breaking): LNEx v3, TLS 1.3 control connection +- The control connection is TLS 1.3 only (rustls, ALPN `vnox-lnex/3`). The custom X25519/HKDF/ChaCha20 TCP layer, the plaintext loopback shortcut and the `lnex://` plaintext meaning are removed. Protocol version `v3`; old gateways are refused with an explicit error, no fallback. +- Server trust: SPKI SHA-256 pin stored in `~/.config/vnox/known_servers.json` (trust on first use with a confirmation dialog, RU/EN), public CA certificates accepted without a prompt, a changed fingerprint or server identity is blocked and offers "Forget this server". +- Client auth signatures are bound to the TLS exporter and cannot be replayed on another connection. +- `vnox-e2e-voice` now needs `--fingerprint HEX` or `--trust-first-use`. +- Design and trust model: VNOX-Server `docs/02-protocol/tls.md`. + ### Added — Phase 2 guild member list + identity export/import + channel rate limit (fourth batch) #### Phase 2 guild member list with kick / role-assign UI (Phase E4) diff --git a/README.md b/README.md index 5e8050e..72787cb 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ The official desktop client for [VNOX](https://github.com/loki5512344/Vnox) — ### Implemented - **Auth:** Ed25519 keypair generation, challenge-response login, reconnect with exponential backoff -- **Encryption:** ChaCha20-Poly1305 AEAD + X25519 ECDH key exchange +- **Encryption:** TLS 1.3 (rustls) on the control connection with certificate pinning (trust on first use), ChaCha20-Poly1305 on UDP voice - **Text chat:** Persistent history, reactions, replies, edit, delete, typing indicators, read receipts - **Channel management:** Join, leave, create, delete; text and voice channels - **Guilds:** Create, list, leave, member list with roles, kick, audit log viewer @@ -58,7 +58,7 @@ Phase 1 is implemented. Not production ready. | Direct Messages | ✅ Working | | Friends & presence | ✅ Working | | Voice (send/receive) | 🔧 Partial (audio pipeline) | -| Encryption | ✅ ChaCha20-Poly1305 + X25519 | +| Encryption | ✅ TLS 1.3 (TCP) + ChaCha20-Poly1305 (voice) | | In-game overlay | 🔲 Phase 2 | | Mobile client | 🔲 Phase 3 | diff --git a/docs/05-features/encryption.md b/docs/05-features/encryption.md index f9175b3..27ad053 100644 --- a/docs/05-features/encryption.md +++ b/docs/05-features/encryption.md @@ -1,78 +1,44 @@ -# Encryption — Phase 1.1 +# Encryption -> **Phase 1.1 status:** Fully implemented. ChaCha20-Poly1305 AEAD with X25519 ECDH + HKDF-SHA256 key exchange. Both TCP (control) and UDP (voice) paths are now encrypted. Forward secrecy via ephemeral session keys. +> **Status (LNEx v3):** the TCP control plane is protected by **TLS 1.3** (rustls). +> The UDP voice path is protected by per route ChaCha20-Poly1305 keys delivered over the +> TLS control connection. The earlier custom X25519 + HKDF + ChaCha20-Poly1305 layer on +> TCP (LNEx v2) was removed. Design and trust model: [02-protocol/tls.md](../02-protocol/tls.md). -## Goal +## Layers -Replace all plaintext traffic (TCP + UDP) with ChaCha20-Poly1305 AEAD encryption. -X25519 ECDH ephemeral key exchange during handshake for forward secrecy. +| Path | Protection | Keys | +|------|------------|------| +| TCP control (chat, channels, auth) | TLS 1.3, ALPN `vnox-lnex/3`, no fallback | TLS handshake, server cert pinned by SPKI SHA-256 (TOFU) or a public CA | +| Server authenticity | Ed25519 server identity signs HELLO over the TLS exporter (channel binding) | `server_identity.json` | +| Client authenticity | Ed25519 client key signs AUTH over the same exporter | client identity | +| UDP voice | ChaCha20-Poly1305 AEAD per route | random `c2s_key` / `s2c_key` sent in `VoiceSession` over TLS | +| Direct messages E2EE (optional) | X25519 + HKDF + ChaCha20-Poly1305 between clients | per conversation keys, unchanged | -✅ **COMPLETED in Phase 1.1** +## What changed from v2 -## Key exchange (during HELLO handshake) +- Removed: ephemeral X25519 exchange in HELLO/AUTH, HKDF session key derivation for TCP, + per frame ChaCha20-Poly1305 with the `ENCRYPTED` flag, `SessionCrypto` in gateway and client. +- Added: mandatory TLS 1.3 listener and connector, certificate management, client trust store, + channel bound Ed25519 signatures. +- Unchanged: UDP voice packet format, voice node, E2EE for direct messages, Ed25519 identities. -1. Server generates ephemeral X25519 keypair per session -2. Server sends public key in `HELLO` packet -3. Client generates own ephemeral X25519 keypair -4. Both compute shared secret via X25519 ECDH -5. Shared secret → HKDF-SHA256 → two keys: - - `client→server` encryption key - - `server→client` encryption key -6. Ephemeral keys discarded after session (forward secrecy) +## Why TLS instead of a custom layer -## Packet encryption +- Reviewed, widely deployed handshake and record layer instead of a protocol we maintain. +- Standard tooling and key lifecycle (Let's Encrypt works out of the box). +- Forward secrecy, key updates and replay protection are provided by TLS 1.3. -- Algorithm: **ChaCha20-Poly1305** (AEAD) -- 96-bit nonce: `session_id || packet_sequence` -- 16-byte Poly1305 authentication tag per packet -- Applied to ALL packets on both TCP and UDP +## Voice keys -## Why ChaCha20-Poly1305 over AES-GCM - -- Constant-time on all platforms (no hardware AES requirement) -- Faster in software on ARM (common for mobile — Phase 3) -- Simpler nonce management (no IV collision risk) - -## Implementation plan - -### ✅ Client (DONE) -- `client/src/net/crypto.rs` — SessionCrypto with ChaCha20-Poly1305 -- `client/src/net/voice.rs` — `build_packet()` encrypts voice payloads with c2s_key -- `client/src/net/voice.rs` — `spawn_recv()` decrypts incoming voice with s2c_key -- `client/src/net/session/session_loop.rs` — voice_seq counter for encryption nonces - -### ✅ Gateway (DONE) -- `gateway/src/proto/crypto.rs` — X25519 ECDH, HKDF-SHA256, ChaCha20-Poly1305 -- `gateway/src/net/handshake.rs` — ephemeral key exchange in HELLO/AUTH -- `gateway/src/net/io.rs` — TCP framing with encryption - -### ✅ Voice -- `client/src/net/voice.rs` — encrypted voice packets on UDP (plaintext at rest in voice-node, encrypted on wire) -- Voice-node treats packets as opaque bytes (transparent relay) -- End-to-end encryption: client A → encrypted → voice-node → encrypted → client B - -## Nonce management - -Each session has a monotonic sequence counter: -- Start at 0 on session establishment -- Increment per packet (both directions independently) -- Nonce = `session_id (8 bytes) || sequence (4 bytes)` -- 12-byte nonce fits ChaCha20-Poly1305 standard - -## Key dependencies - -Already in `Cargo.toml` (workspace): -- `chacha20poly1305 = "0.10"` -- `x25519-dalek = { version = "2", features = ["static_secrets"] }` - -Need to add: -- `hkdf = "0.12"` for key derivation -- `sha2 = "0.10"` (HKDF dependency, likely already transitive) +`VoiceSession` is delivered after the channel authorization check. Keys are random per +route and never derived from the TCP session, so the UDP implementation did not need to +change when the TCP layer was replaced. ## Testing -- ✅ Unit test: encrypt → decrypt round-trip with known keys (`client/src/net/crypto.rs`) -- ✅ Unit test: tampered ciphertext fails authentication -- ✅ Unit test: build_packet creates valid encrypted packets -- Manual test: Run client + gateway + voice-node, join voice channel, verify packets encrypted -- Wireshark: Capture UDP traffic, confirm it's not readable plaintext +- Unit: SPKI fingerprint extraction, pin match and mismatch, unknown server, TLS 1.2 client + rejected, plaintext/v2 client gets an explicit error, channel binding signature replay rejected. +- Integration: `VNOX_GATEWAY_BIN=... cargo test --test gateway_interop -- --ignored` + in `VNOX-Client`, including the first trust flow. +- Voice: `cargo run --bin vnox-e2e-voice -- 127.0.0.1:7600 --trust-first-use` against `vnox-serverd`. From 82227203f95bc1475791440d9444476bbd38a2bf Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:05:19 +0200 Subject: [PATCH 4/8] docs: describe TLS 1.3 control connection and LNEx v3 in client docs --- CHANGELOG.md | 7 +++ README.md | 4 +- docs/05-features/encryption.md | 98 +++++++++++----------------------- 3 files changed, 41 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef57f30..4bfc1b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Changed (breaking): LNEx v3, TLS 1.3 control connection +- The control connection is TLS 1.3 only (rustls, ALPN `vnox-lnex/3`). The custom X25519/HKDF/ChaCha20 TCP layer, the plaintext loopback shortcut and the `lnex://` plaintext meaning are removed. Protocol version `v3`; old gateways are refused with an explicit error, no fallback. +- Server trust: SPKI SHA-256 pin stored in `~/.config/vnox/known_servers.json` (trust on first use with a confirmation dialog, RU/EN), public CA certificates accepted without a prompt, a changed fingerprint or server identity is blocked and offers "Forget this server". +- Client auth signatures are bound to the TLS exporter and cannot be replayed on another connection. +- `vnox-e2e-voice` now needs `--fingerprint HEX` or `--trust-first-use`. +- Design and trust model: VNOX-Server `docs/02-protocol/tls.md`. + ### Added — Phase 2 guild member list + identity export/import + channel rate limit (fourth batch) #### Phase 2 guild member list with kick / role-assign UI (Phase E4) diff --git a/README.md b/README.md index 5e8050e..72787cb 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ The official desktop client for [VNOX](https://github.com/loki5512344/Vnox) — ### Implemented - **Auth:** Ed25519 keypair generation, challenge-response login, reconnect with exponential backoff -- **Encryption:** ChaCha20-Poly1305 AEAD + X25519 ECDH key exchange +- **Encryption:** TLS 1.3 (rustls) on the control connection with certificate pinning (trust on first use), ChaCha20-Poly1305 on UDP voice - **Text chat:** Persistent history, reactions, replies, edit, delete, typing indicators, read receipts - **Channel management:** Join, leave, create, delete; text and voice channels - **Guilds:** Create, list, leave, member list with roles, kick, audit log viewer @@ -58,7 +58,7 @@ Phase 1 is implemented. Not production ready. | Direct Messages | ✅ Working | | Friends & presence | ✅ Working | | Voice (send/receive) | 🔧 Partial (audio pipeline) | -| Encryption | ✅ ChaCha20-Poly1305 + X25519 | +| Encryption | ✅ TLS 1.3 (TCP) + ChaCha20-Poly1305 (voice) | | In-game overlay | 🔲 Phase 2 | | Mobile client | 🔲 Phase 3 | diff --git a/docs/05-features/encryption.md b/docs/05-features/encryption.md index f9175b3..27ad053 100644 --- a/docs/05-features/encryption.md +++ b/docs/05-features/encryption.md @@ -1,78 +1,44 @@ -# Encryption — Phase 1.1 +# Encryption -> **Phase 1.1 status:** Fully implemented. ChaCha20-Poly1305 AEAD with X25519 ECDH + HKDF-SHA256 key exchange. Both TCP (control) and UDP (voice) paths are now encrypted. Forward secrecy via ephemeral session keys. +> **Status (LNEx v3):** the TCP control plane is protected by **TLS 1.3** (rustls). +> The UDP voice path is protected by per route ChaCha20-Poly1305 keys delivered over the +> TLS control connection. The earlier custom X25519 + HKDF + ChaCha20-Poly1305 layer on +> TCP (LNEx v2) was removed. Design and trust model: [02-protocol/tls.md](../02-protocol/tls.md). -## Goal +## Layers -Replace all plaintext traffic (TCP + UDP) with ChaCha20-Poly1305 AEAD encryption. -X25519 ECDH ephemeral key exchange during handshake for forward secrecy. +| Path | Protection | Keys | +|------|------------|------| +| TCP control (chat, channels, auth) | TLS 1.3, ALPN `vnox-lnex/3`, no fallback | TLS handshake, server cert pinned by SPKI SHA-256 (TOFU) or a public CA | +| Server authenticity | Ed25519 server identity signs HELLO over the TLS exporter (channel binding) | `server_identity.json` | +| Client authenticity | Ed25519 client key signs AUTH over the same exporter | client identity | +| UDP voice | ChaCha20-Poly1305 AEAD per route | random `c2s_key` / `s2c_key` sent in `VoiceSession` over TLS | +| Direct messages E2EE (optional) | X25519 + HKDF + ChaCha20-Poly1305 between clients | per conversation keys, unchanged | -✅ **COMPLETED in Phase 1.1** +## What changed from v2 -## Key exchange (during HELLO handshake) +- Removed: ephemeral X25519 exchange in HELLO/AUTH, HKDF session key derivation for TCP, + per frame ChaCha20-Poly1305 with the `ENCRYPTED` flag, `SessionCrypto` in gateway and client. +- Added: mandatory TLS 1.3 listener and connector, certificate management, client trust store, + channel bound Ed25519 signatures. +- Unchanged: UDP voice packet format, voice node, E2EE for direct messages, Ed25519 identities. -1. Server generates ephemeral X25519 keypair per session -2. Server sends public key in `HELLO` packet -3. Client generates own ephemeral X25519 keypair -4. Both compute shared secret via X25519 ECDH -5. Shared secret → HKDF-SHA256 → two keys: - - `client→server` encryption key - - `server→client` encryption key -6. Ephemeral keys discarded after session (forward secrecy) +## Why TLS instead of a custom layer -## Packet encryption +- Reviewed, widely deployed handshake and record layer instead of a protocol we maintain. +- Standard tooling and key lifecycle (Let's Encrypt works out of the box). +- Forward secrecy, key updates and replay protection are provided by TLS 1.3. -- Algorithm: **ChaCha20-Poly1305** (AEAD) -- 96-bit nonce: `session_id || packet_sequence` -- 16-byte Poly1305 authentication tag per packet -- Applied to ALL packets on both TCP and UDP +## Voice keys -## Why ChaCha20-Poly1305 over AES-GCM - -- Constant-time on all platforms (no hardware AES requirement) -- Faster in software on ARM (common for mobile — Phase 3) -- Simpler nonce management (no IV collision risk) - -## Implementation plan - -### ✅ Client (DONE) -- `client/src/net/crypto.rs` — SessionCrypto with ChaCha20-Poly1305 -- `client/src/net/voice.rs` — `build_packet()` encrypts voice payloads with c2s_key -- `client/src/net/voice.rs` — `spawn_recv()` decrypts incoming voice with s2c_key -- `client/src/net/session/session_loop.rs` — voice_seq counter for encryption nonces - -### ✅ Gateway (DONE) -- `gateway/src/proto/crypto.rs` — X25519 ECDH, HKDF-SHA256, ChaCha20-Poly1305 -- `gateway/src/net/handshake.rs` — ephemeral key exchange in HELLO/AUTH -- `gateway/src/net/io.rs` — TCP framing with encryption - -### ✅ Voice -- `client/src/net/voice.rs` — encrypted voice packets on UDP (plaintext at rest in voice-node, encrypted on wire) -- Voice-node treats packets as opaque bytes (transparent relay) -- End-to-end encryption: client A → encrypted → voice-node → encrypted → client B - -## Nonce management - -Each session has a monotonic sequence counter: -- Start at 0 on session establishment -- Increment per packet (both directions independently) -- Nonce = `session_id (8 bytes) || sequence (4 bytes)` -- 12-byte nonce fits ChaCha20-Poly1305 standard - -## Key dependencies - -Already in `Cargo.toml` (workspace): -- `chacha20poly1305 = "0.10"` -- `x25519-dalek = { version = "2", features = ["static_secrets"] }` - -Need to add: -- `hkdf = "0.12"` for key derivation -- `sha2 = "0.10"` (HKDF dependency, likely already transitive) +`VoiceSession` is delivered after the channel authorization check. Keys are random per +route and never derived from the TCP session, so the UDP implementation did not need to +change when the TCP layer was replaced. ## Testing -- ✅ Unit test: encrypt → decrypt round-trip with known keys (`client/src/net/crypto.rs`) -- ✅ Unit test: tampered ciphertext fails authentication -- ✅ Unit test: build_packet creates valid encrypted packets -- Manual test: Run client + gateway + voice-node, join voice channel, verify packets encrypted -- Wireshark: Capture UDP traffic, confirm it's not readable plaintext +- Unit: SPKI fingerprint extraction, pin match and mismatch, unknown server, TLS 1.2 client + rejected, plaintext/v2 client gets an explicit error, channel binding signature replay rejected. +- Integration: `VNOX_GATEWAY_BIN=... cargo test --test gateway_interop -- --ignored` + in `VNOX-Client`, including the first trust flow. +- Voice: `cargo run --bin vnox-e2e-voice -- 127.0.0.1:7600 --trust-first-use` against `vnox-serverd`. From 55c8ab0773479c3bdf7647f04e84e45d96c10249 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:13:47 +0200 Subject: [PATCH 5/8] fix(client): align the auto-reconnect checkbox with its label Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4 --- src/ui/slint/connect.slint | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ui/slint/connect.slint b/src/ui/slint/connect.slint index 7b5348e..9c6cb99 100644 --- a/src/ui/slint/connect.slint +++ b/src/ui/slint/connect.slint @@ -64,8 +64,9 @@ export component ConnectScreen inherits Rectangle { if root.connecting : ActionButton { text: @tr("Cancel"); height: 40px; clicked => { root.disconnect(); } } } HorizontalLayout { - ActionButton { text: root.auto-reconnect ? "✓" : "○"; width: 30px; quiet: true; clicked => { root.auto-reconnect = !root.auto-reconnect; root.auto-reconnect-changed(root.auto-reconnect); } } - Text { text: @tr("Reconnect automatically"); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); } + height: 30px; + ActionButton { text: root.auto-reconnect ? "✓" : "○"; width: 30px; height: 30px; quiet: true; clicked => { root.auto-reconnect = !root.auto-reconnect; root.auto-reconnect-changed(root.auto-reconnect); } } + Text { text: @tr("Reconnect automatically"); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); vertical-alignment: center; } Rectangle { horizontal-stretch: 1; } } if root.connecting : Text { text: @tr("Connecting…"); color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.8125); } From 6c1ac59f78a0a2c473b8cf554a9f085b6bbe7b29 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:13:47 +0200 Subject: [PATCH 6/8] fix(client): align the auto-reconnect checkbox with its label --- src/ui/slint/connect.slint | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ui/slint/connect.slint b/src/ui/slint/connect.slint index 7b5348e..9c6cb99 100644 --- a/src/ui/slint/connect.slint +++ b/src/ui/slint/connect.slint @@ -64,8 +64,9 @@ export component ConnectScreen inherits Rectangle { if root.connecting : ActionButton { text: @tr("Cancel"); height: 40px; clicked => { root.disconnect(); } } } HorizontalLayout { - ActionButton { text: root.auto-reconnect ? "✓" : "○"; width: 30px; quiet: true; clicked => { root.auto-reconnect = !root.auto-reconnect; root.auto-reconnect-changed(root.auto-reconnect); } } - Text { text: @tr("Reconnect automatically"); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); } + height: 30px; + ActionButton { text: root.auto-reconnect ? "✓" : "○"; width: 30px; height: 30px; quiet: true; clicked => { root.auto-reconnect = !root.auto-reconnect; root.auto-reconnect-changed(root.auto-reconnect); } } + Text { text: @tr("Reconnect automatically"); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); vertical-alignment: center; } Rectangle { horizontal-stretch: 1; } } if root.connecting : Text { text: @tr("Connecting…"); color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.8125); } From f658c75539f43423a6fb0134143b3d14eef4c48f Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 23:47:14 +0200 Subject: [PATCH 7/8] docs: record client UX defects found in the first live run Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4 --- docs/maintenance/ux-defects-2026-10-24.md | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/maintenance/ux-defects-2026-10-24.md diff --git a/docs/maintenance/ux-defects-2026-10-24.md b/docs/maintenance/ux-defects-2026-10-24.md new file mode 100644 index 0000000..7bf5420 --- /dev/null +++ b/docs/maintenance/ux-defects-2026-10-24.md @@ -0,0 +1,35 @@ +# Недочёты клиента после первого живого запуска (24.10.2026) + +Источник: пользовательский тест клиента `55c8ab0` на сервере `central.loki-code.dev`, Linux, Wayland. Скриншоты лежали в сессии, здесь пересказ. Статус обновляется по мере исправлений. + +Поток A: интерфейс и отзывчивость (Slint). Поток B: звук и аудио. Поток C: аккаунты и аватары (сеть, hub, протокол), делается после A. + +| № | Область | Проблема | Поток | Статус | +|---|---------|----------|-------|--------| +| 1 | Список каналов | Текст «general» стоит выше центра строки, не выровнен с иконкой `#` | A | открыто | +| 2 | Участники | У самого пользователя «Не в сети», хотя внизу «В сети»; аватар из двух букв «us» | A, C | открыто | +| 3 | Панель пользователя | Кривые иконки микрофона, наушников и настроек | A | открыто | +| 4 | Поле ввода | Ненужная подсказка «Enter отправить, Shift+Enter новая строка» | A | открыто | +| 5 | Иконки | Шестерёнка выглядит как цветок или снежинка, набор иконок самодельный | A | открыто | +| 6 | Шапка сервера | Кнопка «питание» рядом с названием сервера непонятна | A | открыто | +| 7 | Сообщения | В панели при наведении («Ответить, Править, Удалить») странная иконка слева | A | открыто | +| 8 | Эмодзи | Нет выбора эмодзи для текста сообщения и для реакций на сообщения | A | открыто | +| 9 | Звук | В голосовой комнате нет звуков: вход и выход участников, сообщения, упоминание или пинг, mute и unmute, подключение | B | открыто | +| 10a | Голос | По умолчанию стоит режим рации (PTT), выглядит странно и неудобно; нужен обычный режим по активации голоса | B | открыто | +| 10b | Голосовая комната | Страница слишком серая, текстовые кнопки «Выключить микрофон», «Выключить звук», «Покинуть комнату» неудобны; нужны иконочные кнопки | A | открыто | +| 10c | Голосовая комната | Верхняя строка «Подключение к голосовой комнате…» остаётся, хотя внизу «Голос подключён» | B | открыто | +| 10d | Аккаунт | Можно зайти на сервер без аккаунта; регистрация или вход в Central должны быть обязательными | C | открыто | +| 10e | Аватары | Две буквы вместо аватара; при первой регистрации нужен случайный сгенерированный аватар | C | открыто | +| 10f | Отзывчивость | Приложение реагирует медленно; нажатие срабатывает не с одного клика, а со второго | A | открыто | +| 11a | Настройки звука | В списках устройств вывода и микрофона мусорные ALSA-пункты (Discard all samples, Rate Converter Plugin, JACK, Open Sound System) | B | открыто | +| 11b | Настройки | Те же двойные клики в настройках | A | открыто | +| 12a | Темы | Тема работает странно (чёрная тема: части интерфейса остаются серыми, фон не везде одинаковый) | A | открыто | +| 12b | Аватар | Аватар в панели пользователя обновился, в карточке участника голосовой комнаты остались две буквы | A, C | открыто | +| 12c | Аватар | Неясно, доходит ли аватар до других пользователей. Проверить и, если нет, реализовать передачу | C | открыто | + +## Принципы исправления + +- Иконки берём из готового открытого набора с совместимой лицензией (Lucide, ISC), не рисуем сами. Лицензию кладём в репозиторий. +- Отзывчивость: сначала измерить причину (двойной клик, ожидание таймера, фокус), потом чинить, не угадывать. +- Любое изменение протокола сначала в документации (правило репозитория), затем в коде. +- Никаких длинных тире в пользовательских текстах. From 82dd9a324d834c956d7b81bac933e6c288197d91 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 23:47:14 +0200 Subject: [PATCH 8/8] docs: record client UX defects found in the first live run --- docs/maintenance/ux-defects-2026-10-24.md | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/maintenance/ux-defects-2026-10-24.md diff --git a/docs/maintenance/ux-defects-2026-10-24.md b/docs/maintenance/ux-defects-2026-10-24.md new file mode 100644 index 0000000..7bf5420 --- /dev/null +++ b/docs/maintenance/ux-defects-2026-10-24.md @@ -0,0 +1,35 @@ +# Недочёты клиента после первого живого запуска (24.10.2026) + +Источник: пользовательский тест клиента `55c8ab0` на сервере `central.loki-code.dev`, Linux, Wayland. Скриншоты лежали в сессии, здесь пересказ. Статус обновляется по мере исправлений. + +Поток A: интерфейс и отзывчивость (Slint). Поток B: звук и аудио. Поток C: аккаунты и аватары (сеть, hub, протокол), делается после A. + +| № | Область | Проблема | Поток | Статус | +|---|---------|----------|-------|--------| +| 1 | Список каналов | Текст «general» стоит выше центра строки, не выровнен с иконкой `#` | A | открыто | +| 2 | Участники | У самого пользователя «Не в сети», хотя внизу «В сети»; аватар из двух букв «us» | A, C | открыто | +| 3 | Панель пользователя | Кривые иконки микрофона, наушников и настроек | A | открыто | +| 4 | Поле ввода | Ненужная подсказка «Enter отправить, Shift+Enter новая строка» | A | открыто | +| 5 | Иконки | Шестерёнка выглядит как цветок или снежинка, набор иконок самодельный | A | открыто | +| 6 | Шапка сервера | Кнопка «питание» рядом с названием сервера непонятна | A | открыто | +| 7 | Сообщения | В панели при наведении («Ответить, Править, Удалить») странная иконка слева | A | открыто | +| 8 | Эмодзи | Нет выбора эмодзи для текста сообщения и для реакций на сообщения | A | открыто | +| 9 | Звук | В голосовой комнате нет звуков: вход и выход участников, сообщения, упоминание или пинг, mute и unmute, подключение | B | открыто | +| 10a | Голос | По умолчанию стоит режим рации (PTT), выглядит странно и неудобно; нужен обычный режим по активации голоса | B | открыто | +| 10b | Голосовая комната | Страница слишком серая, текстовые кнопки «Выключить микрофон», «Выключить звук», «Покинуть комнату» неудобны; нужны иконочные кнопки | A | открыто | +| 10c | Голосовая комната | Верхняя строка «Подключение к голосовой комнате…» остаётся, хотя внизу «Голос подключён» | B | открыто | +| 10d | Аккаунт | Можно зайти на сервер без аккаунта; регистрация или вход в Central должны быть обязательными | C | открыто | +| 10e | Аватары | Две буквы вместо аватара; при первой регистрации нужен случайный сгенерированный аватар | C | открыто | +| 10f | Отзывчивость | Приложение реагирует медленно; нажатие срабатывает не с одного клика, а со второго | A | открыто | +| 11a | Настройки звука | В списках устройств вывода и микрофона мусорные ALSA-пункты (Discard all samples, Rate Converter Plugin, JACK, Open Sound System) | B | открыто | +| 11b | Настройки | Те же двойные клики в настройках | A | открыто | +| 12a | Темы | Тема работает странно (чёрная тема: части интерфейса остаются серыми, фон не везде одинаковый) | A | открыто | +| 12b | Аватар | Аватар в панели пользователя обновился, в карточке участника голосовой комнаты остались две буквы | A, C | открыто | +| 12c | Аватар | Неясно, доходит ли аватар до других пользователей. Проверить и, если нет, реализовать передачу | C | открыто | + +## Принципы исправления + +- Иконки берём из готового открытого набора с совместимой лицензией (Lucide, ISC), не рисуем сами. Лицензию кладём в репозиторий. +- Отзывчивость: сначала измерить причину (двойной клик, ожидание таймера, фокус), потом чинить, не угадывать. +- Любое изменение протокола сначала в документации (правило репозитория), затем в коде. +- Никаких длинных тире в пользовательских текстах.