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.
This commit is contained in:
Loki 2026-10-24 22:05:19 +02:00
parent 5f594046a6
commit 29883a3187
31 changed files with 2085 additions and 567 deletions

View file

@ -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<u8> {
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<u8> {
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<Vec<u8>> {
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<Vec<u8>> {
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",
);
}
}

View file

@ -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::<Sha256>::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<u8> {
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<Vec<u8>> {
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());
}
}

View file

@ -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<RawPacket> {
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<u8> {
let mut keys = [0u8; 64];
Hkdf::<Sha256>::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());
}
}

View file

@ -39,7 +39,7 @@ pub fn decode_frame(bytes: &[u8]) -> Result<RawPacket> {
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<Ra
stream.read_exact(&mut buf).await?;
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
if flags != 0 {
return Err(anyhow!("unexpected handshake flags"));
return Err(anyhow!("unexpected frame flags"));
}
let mut payload = vec![0u8; payload_length as usize];
if !payload.is_empty() {
@ -76,6 +76,9 @@ pub async fn write(
seq: &mut u32,
payload: &[u8],
) -> 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(())

View file

@ -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<u8> {
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<u8> {
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<Outcome> {
// 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::<String>()
);
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<u8>) {
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::<TransportError>(),
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::<TransportError>(),
Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3")
));
}
}

View file

@ -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<NetCommand>,
event_rx: Arc<Mutex<mpsc::Receiver<NetEvent>>>,
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<NetEvent> {
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::<NetCommand>(64);
let (event_tx, event_rx) = mpsc::channel::<NetEvent>(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,
}
}

View file

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

View file

@ -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<String>,
restored: bool,
cmd_rx: &mut mpsc::Receiver<NetCommand>,
@ -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<VoiceState> = None;
let mut used_voice_routes = std::collections::HashSet::new();
let mut voice_endpoint: Option<std::net::SocketAddr> = 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?,
}
}
}

View file

@ -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?;
}
_ => {}
}

View file

@ -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?;
}
_ => {}
}

View file

@ -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?;
}
_ => {}
}

View file

@ -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<NetCommand>,
event_tx: mpsc::Sender<NetEvent>,
) {
@ -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::<TransportError>();
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(),

View file

@ -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<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncStream for T {}
pub type Stream = Box<dyn AsyncStream>;
/// 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<ServerRecord>,
}
pub async fn connect(address: &str) -> Result<Stream> {
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<Connected> {
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<String>,
mismatch: bool,
ca_valid: bool,
ca_error: Option<String>,
}
#[derive(Debug)]
struct TrustVerifier {
mode: Mode,
pin: Option<String>,
webpki: Arc<WebPkiServerVerifier>,
algorithms: rustls::crypto::WebPkiSupportedAlgorithms,
observed: Arc<Mutex<Observed>>,
}
impl TrustVerifier {
fn observe<R>(&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<ServerCertVerified, rustls::Error> {
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<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algorithms.supported_schemes()
}
}
/// Connect, verify and return the TLS stream plus the channel binding.
pub async fn connect(address: &str, trust: &TrustStore) -> Result<Stream> {
Ok(connect_with_peer(address, trust).await?.stream)
}
pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result<Connected> {
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::<std::net::IpAddr>()
.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<Observed>,
) -> 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::<rustls::Error>());
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<u8>, 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<Connected>) -> TransportError {
match result {
Ok(_) => panic!("connection must not succeed"),
Err(error) => error
.downcast_ref::<TransportError>()
.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();
}
}

569
src/net/trust.rs Normal file
View file

@ -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<TrustProblem> {
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<String>,
/// Lower-case hex Ed25519 server identity, stored after the first authenticated handshake.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
pub first_seen: i64,
}
#[derive(Default, Serialize, Deserialize)]
struct FileFormat {
version: u32,
servers: BTreeMap<String, ServerRecord>,
}
struct Inner {
path: Option<PathBuf>,
servers: BTreeMap<String, ServerRecord>,
}
/// Thread safe, file backed trust store (`<config dir>/vnox/known_servers.json`).
#[derive(Clone)]
pub struct TrustStore {
inner: Arc<Mutex<Inner>>,
}
/// 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<ServerAddress> {
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 {
/// `<config dir>/vnox/known_servers.json`.
pub fn default_path() -> Option<PathBuf> {
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::<FileFormat>(&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<ServerRecord> {
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<String> {
let cleaned: String = value
.trim()
.trim_start_matches("sha256:")
.chars()
.filter(|c| *c != ':' && !c.is_whitespace())
.collect::<String>()
.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::<Vec<_>>()
.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<String> {
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::<Vec<_>>()
.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());
}
}

View file

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