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:
parent
5f594046a6
commit
29883a3187
31 changed files with 2085 additions and 567 deletions
|
|
@ -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")
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue