use std::io::{Read, Write};
use std::net::{IpAddr, TcpStream};
use std::sync::{Arc, OnceLock};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{ClientConfig, ClientConnection, DigitallySignedStruct, SignatureScheme, StreamOwned};
use crate::fingerprint::Tunnel;
pub(crate) trait ReadWrite: Read + Write {
fn socket(&self) -> &TcpStream;
}
impl ReadWrite for TcpStream {
fn socket(&self) -> &TcpStream {
self
}
}
impl ReadWrite for StreamOwned<ClientConnection, TcpStream> {
fn socket(&self) -> &TcpStream {
self.get_ref()
}
}
pub(crate) fn wrap(
tcp: TcpStream,
peer: IpAddr,
tunnel: Option<Tunnel>,
) -> Option<Box<dyn ReadWrite>> {
match tunnel {
None => Some(Box::new(tcp)),
Some(Tunnel::Tls) => {
let name = ServerName::IpAddress(peer.into());
let conn = ClientConnection::new(config().clone(), name).ok()?;
Some(Box::new(StreamOwned::new(conn, tcp)))
}
}
}
fn config() -> &'static Arc<ClientConfig> {
static CONFIG: OnceLock<Arc<ClientConfig>> = OnceLock::new();
CONFIG.get_or_init(|| {
let config =
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.expect("the ring provider supports the default TLS versions")
.dangerous()
.with_custom_certificate_verifier(Arc::new(AcceptAnyServerCert))
.with_no_client_auth();
Arc::new(config)
})
}
#[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,
]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_tunnel_returns_the_plain_socket() {
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let accepted = std::thread::spawn(move || listener.accept().map(|(sock, _)| sock));
let tcp = TcpStream::connect(addr).unwrap();
let mut wrapped = wrap(tcp, addr.ip(), None).expect("a plain socket wraps to itself");
let mut server = accepted.join().unwrap().unwrap();
wrapped.write_all(b"ping").unwrap();
let mut buf = [0u8; 4];
server.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"ping", "the bytes crossed the un-tunnelled stream");
}
#[test]
fn the_client_config_is_built_once_and_shared() {
let first = config();
let second = config();
assert!(
Arc::ptr_eq(first, second),
"the config is a shared singleton, not rebuilt per call"
);
}
}