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>;
pub(super) const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
pub(super) const SPECULATIVE_TLS_TIMEOUT: Duration = Duration::from_millis(1_500);
const IMPLICIT_TLS_PORTS: &[u16] = &[
443, 465, 636, 989, 990, 993, 995, 2376, 3269, 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,
server: ServerName<'static>,
) -> Option<(TlsTunnel, TlsInfo)> {
handshake_within(stream, server, TLS_HANDSHAKE_TIMEOUT).await
}
pub async fn speculative_handshake(
stream: TcpStream,
server: ServerName<'static>,
) -> Option<(TlsTunnel, TlsInfo)> {
handshake_within(stream, server, SPECULATIVE_TLS_TIMEOUT).await
}
async fn handshake_within(
stream: TcpStream,
server: ServerName<'static>,
budget: Duration,
) -> Option<(TlsTunnel, TlsInfo)> {
let connect = connector().connect(server, stream);
let given = super::on_path(budget);
let Ok(done) = timeout(given, connect).await else {
super::tell(|tally| tally.ran_out(given));
return None;
};
let tls = done.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,
},
))
}
pub(super) const LEGACY_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500);
const LEGACY_CLIENT_HELLO: &[u8] = &[
0x16, 0x03, 0x01, 0x00, 0x37, 0x01, 0x00, 0x00, 0x33, 0x03, 0x01, 0x5a, 0x0d, 0x00, 0x00, 0x5a,
0x0d, 0x00, 0x00, 0x5a, 0x0d, 0x00, 0x00, 0x5a, 0x0d, 0x00, 0x00, 0x5a, 0x0d, 0x00, 0x00, 0x5a,
0x0d, 0x00, 0x00, 0x5a, 0x0d, 0x00, 0x00, 0x5a, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x2f,
0x00, 0x35, 0x00, 0x0a, 0x00, 0x05, 0x00, 0x3c, 0x00, 0x3d, 0x01, 0x00,
];
pub async fn legacy_version(stream: TcpStream) -> Option<&'static str> {
timeout(
super::on_path(LEGACY_PROBE_TIMEOUT),
legacy_exchange(stream),
)
.await
.unwrap_or_default()
}
pub const REFUSED: &str = "TLS (version not established)";
async fn legacy_exchange(mut stream: TcpStream) -> Option<&'static str> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
stream.write_all(LEGACY_CLIENT_HELLO).await.ok()?;
let mut buffer = [0u8; 128];
let read = stream.read(&mut buffer).await.ok()?;
server_version(&buffer[..read])
}
fn server_version(record: &[u8]) -> Option<&'static str> {
let content_type = *record.first()?;
if content_type == 0x15 {
return Some(REFUSED);
}
if content_type != 0x16 {
return None; }
let body = record.get(5..)?;
if *body.first()? != 0x02 {
return None; }
let version = body.get(4..6)?;
version_name(u16::from_be_bytes([version[0], version[1]]))
}
fn version_name(version: u16) -> Option<&'static str> {
match version {
0x0300 => Some("SSLv3"),
0x0301 => Some("TLSv1.0"),
0x0302 => Some("TLSv1.1"),
0x0303 => Some("TLSv1.2"),
_ => None,
}
}
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 a_legacy_server_hello_names_its_version() {
let hello = |version: [u8; 2]| {
let mut record = vec![0x16, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46];
record.extend_from_slice(&version);
record.extend_from_slice(&[0u8; 32]); record
};
assert_eq!(server_version(&hello([0x03, 0x00])), Some("SSLv3"));
assert_eq!(server_version(&hello([0x03, 0x01])), Some("TLSv1.0"));
assert_eq!(server_version(&hello([0x03, 0x02])), Some("TLSv1.1"));
assert_eq!(server_version(&hello([0x03, 0x03])), Some("TLSv1.2"));
assert_eq!(server_version(&hello([0x03, 0x09])), None, "not a version");
}
#[test]
fn an_alert_establishes_tls_without_establishing_a_version() {
assert_eq!(
server_version(&[0x15, 0x03, 0x01, 0x00, 0x02, 0x02, 0x28]),
Some(REFUSED)
);
}
#[test]
fn what_is_not_a_server_hello_names_nothing() {
assert_eq!(server_version(b"HTTP/1.1 200 OK"), None);
assert_eq!(server_version(b"SSH-2.0-OpenSSH_9.6p1"), None);
assert_eq!(server_version(&[]), None);
assert_eq!(server_version(&[0x16, 0x03, 0x01, 0x00, 0x4a]), None);
assert_eq!(
server_version(&[0x16, 0x03, 0x01, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00]),
None
);
assert_eq!(
server_version(&[0x16, 0x03, 0x01, 0x00, 0x04, 0x02, 0x00, 0x00, 0x46]),
None
);
}
#[test]
fn the_client_hello_declares_its_own_length_correctly() {
let record_length = u16::from_be_bytes([LEGACY_CLIENT_HELLO[3], LEGACY_CLIENT_HELLO[4]]);
assert_eq!(
usize::from(record_length),
LEGACY_CLIENT_HELLO.len() - 5,
"the record length must count everything after the header"
);
let handshake_length = u32::from_be_bytes([
0,
LEGACY_CLIENT_HELLO[6],
LEGACY_CLIENT_HELLO[7],
LEGACY_CLIENT_HELLO[8],
]);
assert_eq!(
handshake_length as usize,
LEGACY_CLIENT_HELLO.len() - 9,
"the handshake length must count everything after its own header"
);
assert_eq!(LEGACY_CLIENT_HELLO[0], 0x16, "a handshake record");
assert_eq!(LEGACY_CLIENT_HELLO[5], 0x01, "a client hello");
}
proptest::proptest! {
#[test]
fn the_version_walk_never_panics(record in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..256)) {
let _ = server_version(&record);
}
}
#[test]
fn connector_builds_with_ring_provider() {
let _ = connector();
}
}