1use crate::tls::TlsIdentity;
7use ::openssl::hash::MessageDigest;
8use ::openssl::ssl::{
9 Ssl, SslContext, SslMethod, SslOptions, SslSessionCacheMode, SslVerifyMode, SslVersion,
10};
11use ::openssl::x509::X509Ref;
12use std::{io, net::SocketAddr, pin::Pin, time::Duration};
13use tokio::{net::TcpStream, time::timeout};
14use tokio_openssl::SslStream;
15pub type SecureStream = SslStream<TcpStream>;
17
18pub struct TlsEndpoint {
20 context: SslContext,
21 pin: [u8; 32],
22}
23
24impl TlsEndpoint {
25 pub fn from_identity(
29 identity: TlsIdentity,
30 trust_anchor: &X509Ref,
31 peer_leaf: &X509Ref,
32 ) -> io::Result<Self> {
33 let pin = leaf_fingerprint(peer_leaf)?;
34 let mut context = identity.into_context_builder(SslMethod::tls())?;
35 context.set_min_proto_version(Some(SslVersion::TLS1_2))?;
36 context.set_max_proto_version(Some(SslVersion::TLS1_2))?;
37 context.set_groups_list("brainpoolP256r1")?;
38 context.set_cipher_list("ECDHE-ECDSA-AES128-GCM-SHA256")?;
39 context.set_options(
40 SslOptions::NO_RENEGOTIATION | SslOptions::NO_TICKET | SslOptions::NO_COMPRESSION,
41 );
42 context.set_session_cache_mode(SslSessionCacheMode::OFF);
43 context.cert_store_mut().add_cert(trust_anchor.to_owned())?;
44 context.set_verify_depth(2);
45 context.set_verify_callback(
46 SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT,
47 move |valid, chain| {
48 valid
49 && (chain.error_depth() != 0
50 || chain.current_cert().is_some_and(|leaf| {
51 leaf_fingerprint(leaf).is_ok_and(|seen| seen == pin)
52 }))
53 },
54 );
55 Ok(Self {
56 context: context.build(),
57 pin,
58 })
59 }
60
61 pub fn peer_fingerprint(&self) -> [u8; 32] {
63 self.pin
64 }
65
66 pub async fn connect(
68 &self,
69 address: SocketAddr,
70 sni: &str,
71 budget: Duration,
72 ) -> io::Result<SslStream<TcpStream>> {
73 check_loopback(address)?;
74 timeout(budget, async {
75 self.connect_socket(TcpStream::connect(address).await?, sni, budget)
76 .await
77 })
78 .await?
79 }
80
81 pub async fn connect_socket(
83 &self,
84 tcp: TcpStream,
85 sni: &str,
86 budget: Duration,
87 ) -> io::Result<SecureStream> {
88 check_loopback(tcp.peer_addr()?)?;
89 check_server_name(sni)?;
90 let mut ssl = Ssl::new(&self.context)?;
91 ssl.set_hostname(sni)?;
92 let mut tls = SslStream::new(ssl, tcp)?;
93 timeout(budget, Pin::new(&mut tls).connect())
94 .await?
95 .map_err(io::Error::other)?;
96 Ok(tls)
97 }
98
99 pub async fn accept(
101 &self,
102 tcp: TcpStream,
103 budget: Duration,
104 ) -> io::Result<SslStream<TcpStream>> {
105 check_loopback(tcp.local_addr()?)?;
106 check_loopback(tcp.peer_addr()?)?;
107 let mut tls = SslStream::new(Ssl::new(&self.context)?, tcp)?;
108 timeout(budget, Pin::new(&mut tls).accept())
109 .await?
110 .map_err(io::Error::other)?;
111 Ok(tls)
112 }
113}
114
115pub fn leaf_fingerprint(leaf: &X509Ref) -> io::Result<[u8; 32]> {
117 let digest = leaf.digest(MessageDigest::sha256())?;
118 digest.as_ref().try_into().map_err(io::Error::other)
119}
120
121pub fn check_loopback(address: SocketAddr) -> io::Result<()> {
123 if address.ip().is_loopback() {
124 Ok(())
125 } else {
126 Err(io::Error::new(
127 io::ErrorKind::InvalidInput,
128 "the simulator requires a loopback address",
129 ))
130 }
131}
132
133pub fn check_server_name(name: &str) -> io::Result<()> {
135 let valid = name.len() <= 253
136 && name.parse::<std::net::IpAddr>().is_err()
137 && name.split('.').all(|label| {
138 !label.is_empty()
139 && label.len() <= 63
140 && !label.starts_with('-')
141 && !label.ends_with('-')
142 && label
143 .bytes()
144 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
145 });
146 if valid {
147 Ok(())
148 } else {
149 Err(io::Error::new(
150 io::ErrorKind::InvalidInput,
151 "expected a DNS name for TLS SNI",
152 ))
153 }
154}