425 lines
14 KiB
Rust
425 lines
14 KiB
Rust
use crate::net::wire;
|
|
use anyhow::{Result, anyhow};
|
|
|
|
use tracing::{debug, info};
|
|
|
|
use super::framing;
|
|
use super::payloads::*;
|
|
use super::trust::TransportError;
|
|
use crate::identity::Identity;
|
|
|
|
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v4-server-hello\0";
|
|
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v4-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,
|
|
pub node_admin: bool,
|
|
pub live_profiles: bool,
|
|
pub node_settings: bool,
|
|
pub channel_structure: bool,
|
|
pub forums: bool,
|
|
/// Lower-case hex Ed25519 identity of the server.
|
|
pub server_identity: String,
|
|
}
|
|
|
|
/// Perform HELLO, AUTH, SESSION inside an established TLS 1.3 connection.
|
|
///
|
|
/// * `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,
|
|
binding: &[u8],
|
|
trust_key: &str,
|
|
expected_identity: Option<&str>,
|
|
) -> Result<Outcome> {
|
|
run_inner(
|
|
stream,
|
|
identity,
|
|
seq,
|
|
binding,
|
|
trust_key,
|
|
expected_identity,
|
|
None,
|
|
)
|
|
.await
|
|
}
|
|
|
|
async fn run_inner(
|
|
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
|
identity: &Identity,
|
|
seq: &mut u32,
|
|
binding: &[u8],
|
|
trust_key: &str,
|
|
expected_identity: Option<&str>,
|
|
supplied_proof: Option<Vec<u8>>,
|
|
) -> 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));
|
|
}
|
|
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()
|
|
.try_into()
|
|
.map_err(|_| anyhow!("invalid server identity key"))?;
|
|
let server_key = ed25519_dalek::VerifyingKey::from_bytes(&server_public)?;
|
|
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature)?;
|
|
let mut unsigned_hello = hello.clone();
|
|
unsigned_hello.server_signature.clear();
|
|
server_key
|
|
.verify_strict(
|
|
&server_hello_transcript(binding, &wire::encode(&unsigned_hello)?),
|
|
&signature,
|
|
)
|
|
.map_err(|_| anyhow!("server handshake signature verification failed"))?;
|
|
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)?;
|
|
|
|
// AUTH
|
|
let sk = identity
|
|
.signing_key()
|
|
.ok_or_else(|| anyhow!("no signing key"))?;
|
|
use ed25519_dalek::Signer;
|
|
|
|
let account_proof = match supplied_proof {
|
|
Some(proof) => proof,
|
|
None => crate::net::account::admission_proof(identity).await?,
|
|
};
|
|
anyhow::ensure!(
|
|
!account_proof.is_empty(),
|
|
"Central account sign-in required"
|
|
);
|
|
let mut auth = AuthPayload {
|
|
client_pubkey: sk.verifying_key().to_bytes().to_vec(),
|
|
nickname: identity.nickname.clone(),
|
|
lnex_version: LNEX_VERSION.into(),
|
|
signature: Vec::new(),
|
|
account_proof,
|
|
};
|
|
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 sent nick={}", identity.nickname);
|
|
|
|
// SESSION
|
|
let pkt = framing::read(stream).await?;
|
|
if pkt.packet_id == PID_ERROR {
|
|
let e: ErrorPayload = wire::decode(&pkt.payload)?;
|
|
return Err(anyhow!("auth rejected: {}", e.message));
|
|
}
|
|
if pkt.packet_id != PID_SESSION {
|
|
return Err(anyhow!("expected SESSION, got 0x{:04X}", pkt.packet_id));
|
|
}
|
|
if pkt.sequence != 1 {
|
|
return Err(anyhow!("invalid SESSION sequence"));
|
|
}
|
|
let sess: SessionPayload = wire::decode(&pkt.payload)?;
|
|
if sess.session_id.is_empty() || sess.token.is_empty() {
|
|
return Err(anyhow!("invalid session response"));
|
|
}
|
|
|
|
info!(
|
|
"authenticated, session {}",
|
|
sess.session_id.chars().take(8).collect::<String>()
|
|
);
|
|
|
|
Ok(Outcome {
|
|
session_id: sess.session_id,
|
|
node_name: hello.node_name,
|
|
private_mode: hello.private_mode,
|
|
node_admin: sess.node_admin,
|
|
live_profiles: sess.live_profiles,
|
|
node_settings: sess.node_settings,
|
|
channel_structure: sess.channel_structure,
|
|
forums: sess.forums,
|
|
server_identity,
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use ed25519_dalek::{Signer, SigningKey};
|
|
use tokio::io::AsyncWriteExt;
|
|
|
|
async fn run_for_test(
|
|
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
|
identity: &Identity,
|
|
seq: &mut u32,
|
|
binding: &[u8],
|
|
trust_key: &str,
|
|
expected_identity: Option<&str>,
|
|
) -> Result<Outcome> {
|
|
run_inner(
|
|
stream,
|
|
identity,
|
|
seq,
|
|
binding,
|
|
trust_key,
|
|
expected_identity,
|
|
Some(b"test-account-proof".to_vec()),
|
|
)
|
|
.await
|
|
}
|
|
|
|
/// 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,
|
|
node_admin: false,
|
|
live_profiles: false,
|
|
node_settings: false,
|
|
channel_structure: false,
|
|
forums: false,
|
|
};
|
|
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], "v4", true));
|
|
let mut seq = 0;
|
|
let outcome = run_for_test(&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();
|
|
assert_eq!(auth.account_proof, b"test-account-proof");
|
|
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], "v4", false));
|
|
let mut seq = 0;
|
|
let error = run_for_test(&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], "v4", false));
|
|
let mut seq = 0;
|
|
let error = run_for_test(
|
|
&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_for_test(&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("v4")
|
|
));
|
|
}
|
|
#[tokio::test]
|
|
async fn empty_account_proof_is_rejected_before_auth() {
|
|
let key = SigningKey::generate(&mut rand::rng());
|
|
let (mut client, server) = tokio::io::duplex(8192);
|
|
let task = tokio::spawn(fake_server(server, key, [9; 32], "v4", false));
|
|
let mut seq = 0;
|
|
let error = run_inner(
|
|
&mut client,
|
|
&identity(),
|
|
&mut seq,
|
|
&[9; 32],
|
|
"h:7600",
|
|
None,
|
|
Some(Vec::new()),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert!(
|
|
error
|
|
.to_string()
|
|
.contains("Central account sign-in required")
|
|
);
|
|
assert_eq!(seq, 0);
|
|
drop(client);
|
|
task.await.unwrap();
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod capability_tests {
|
|
use super::*;
|
|
#[test]
|
|
fn legacy_sessions_do_not_advertise_admin_and_new_flag_roundtrips() {
|
|
let legacy: SessionPayload = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap();
|
|
assert!(!legacy.node_admin);
|
|
assert!(!legacy.live_profiles);
|
|
let mut privileged = legacy;
|
|
privileged.node_admin = true;
|
|
privileged.live_profiles = true;
|
|
let bytes = wire::encode(&privileged).unwrap();
|
|
assert!(wire::decode::<SessionPayload>(&bytes).unwrap().node_admin);
|
|
assert!(
|
|
wire::decode::<SessionPayload>(&bytes)
|
|
.unwrap()
|
|
.live_profiles
|
|
);
|
|
}
|
|
}
|