use std::net::IpAddr;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_rustls::TlsConnector;
use super::response::TlsInfo;
pub type TlsTunnel = tokio_rustls::client::TlsStream<TcpStream>;
const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
const SPECULATIVE_TLS_TIMEOUT: Duration = Duration::from_millis(1_500);
const IMPLICIT_TLS_PORTS: &[u16] = &[
443, 465, 636, 989, 990, 993, 995, 2376, 5061, 5671, 5986, 6697, 8443, 8883, ];
pub fn is_tls_port(port: u16) -> bool {
IMPLICIT_TLS_PORTS.contains(&port)
}
#[derive(Debug)]
struct AcceptAnyServerCert;
impl ServerCertVerifier for AcceptAnyServerCert {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
vec![
SignatureScheme::RSA_PKCS1_SHA256,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::ECDSA_NISTP256_SHA256,
SignatureScheme::ECDSA_NISTP384_SHA384,
SignatureScheme::ECDSA_NISTP521_SHA512,
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::ED25519,
]
}
}
fn connector() -> &'static TlsConnector {
static CONNECTOR: OnceLock<TlsConnector> = OnceLock::new();
CONNECTOR.get_or_init(|| {
let config = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.expect("ring provider supports the default TLS versions")
.dangerous()
.with_custom_certificate_verifier(Arc::new(AcceptAnyServerCert))
.with_no_client_auth();
TlsConnector::from(Arc::new(config))
})
}
pub async fn handshake(stream: TcpStream, peer: IpAddr) -> Option<(TlsTunnel, TlsInfo)> {
handshake_within(stream, peer, TLS_HANDSHAKE_TIMEOUT).await
}
pub async fn speculative_handshake(
stream: TcpStream,
peer: IpAddr,
) -> Option<(TlsTunnel, TlsInfo)> {
handshake_within(stream, peer, SPECULATIVE_TLS_TIMEOUT).await
}
async fn handshake_within(
stream: TcpStream,
peer: IpAddr,
budget: Duration,
) -> Option<(TlsTunnel, TlsInfo)> {
let server_name = ServerName::IpAddress(peer.into());
let connect = connector().connect(server_name, stream);
let tls = timeout(budget, connect).await.ok()?.ok()?;
let connection = tls.get_ref().1;
let certificates: Vec<Vec<u8>> = connection
.peer_certificates()
.unwrap_or(&[])
.iter()
.map(|der| der.as_ref().to_vec())
.collect();
let version = protocol_version_name(connection.protocol_version());
let cipher_suite = connection
.negotiated_cipher_suite()
.and_then(|suite| suite.suite().as_str());
let alpn = connection
.alpn_protocol()
.map(|protocol| String::from_utf8_lossy(protocol).into_owned());
Some((
tls,
TlsInfo {
certificates,
version,
cipher_suite,
alpn,
},
))
}
fn protocol_version_name(version: Option<rustls::ProtocolVersion>) -> Option<&'static str> {
match version? {
rustls::ProtocolVersion::TLSv1_3 => Some("TLSv1.3"),
rustls::ProtocolVersion::TLSv1_2 => Some("TLSv1.2"),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn implicit_tls_ports_are_recognised() {
assert!(is_tls_port(443));
assert!(is_tls_port(993));
assert!(!is_tls_port(80));
assert!(!is_tls_port(22));
}
#[test]
fn connector_builds_with_ring_provider() {
let _ = connector();
}
}