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
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue