1#![deny(unsafe_op_in_unsafe_fn)]
33
34use rustls::{
35 CertificateError, DigitallySignedStruct, Error, SignatureScheme,
36 client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
37 crypto::CryptoProvider,
38 pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime, pem::PemObject},
39};
40use std::{
41 sync::{
42 Arc,
43 atomic::{AtomicU64, Ordering},
44 },
45 time::{Duration, Instant},
46};
47
48pub use rustls;
49pub use rustls::unbuffered::{ConnectionState, UnbufferedStatus};
50
51#[derive(Debug)]
53struct SuppliedTime(AtomicU64);
54
55#[derive(Debug, Clone)]
63pub struct HostTime(Arc<SuppliedTime>);
64impl HostTime {
65 pub fn new(unix_seconds: u64) -> Self {
66 Self(Arc::new(SuppliedTime(AtomicU64::new(unix_seconds))))
67 }
68 pub fn set(&self, unix_seconds: u64) {
69 self.0.0.store(unix_seconds, Ordering::Relaxed);
70 }
71 pub fn unix_seconds(&self) -> u64 {
72 self.0.0.load(Ordering::Relaxed)
73 }
74 pub fn time_provider(&self) -> Arc<dyn rustls::time_provider::TimeProvider> {
76 self.0.clone()
77 }
78}
79
80fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
83 #[cfg(feature = "ring")]
84 {
85 Ok(Arc::new(rustls::crypto::ring::default_provider()))
86 }
87 #[cfg(not(feature = "ring"))]
88 {
89 CryptoProvider::get_default().cloned().ok_or_else(|| {
90 Error::General(
91 "no rustls crypto provider: pass one or install a process default".into(),
92 )
93 })
94 }
95}
96impl rustls::time_provider::TimeProvider for SuppliedTime {
97 fn current_time(&self) -> Option<UnixTime> {
98 Some(UnixTime::since_unix_epoch(Duration::from_secs(
99 self.0.load(Ordering::Relaxed),
100 )))
101 }
102}
103
104#[derive(Debug, Clone)]
108pub struct ClientOptions {
109 pub alpn: Vec<Vec<u8>>,
110 pub ca: Option<Vec<CertificateDer<'static>>>,
111 pub extra_ca_pem: Vec<u8>,
112 pub reject_unauthorized: bool,
113 pub enable_sni: bool,
114 pub provider: Option<Arc<CryptoProvider>>,
118}
119impl Default for ClientOptions {
120 fn default() -> Self {
121 Self {
122 alpn: vec![b"http/1.1".to_vec()],
123 ca: None,
124 extra_ca_pem: Vec::new(),
125 reject_unauthorized: true,
126 enable_sni: true,
127 provider: None,
128 }
129 }
130}
131
132#[derive(Clone)]
133pub struct ClientConfig {
134 config: Arc<rustls::ClientConfig>,
135 time: HostTime,
136}
137impl ClientConfig {
138 pub fn new(options: ClientOptions, unix_seconds: u64) -> Result<Self, Error> {
139 let provider = match options.provider {
140 Some(provider) => provider,
141 None => default_provider()?,
142 };
143 let time = HostTime::new(unix_seconds);
144 let mut roots = rustls::RootCertStore::empty();
145 if let Some(ca) = options.ca {
146 for cert in ca {
147 roots.add(cert)?;
148 }
149 } else {
150 roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
151 for cert in CertificateDer::pem_slice_iter(&options.extra_ca_pem) {
152 roots.add(cert.map_err(|e| Error::General(e.to_string()))?)?;
153 }
154 }
155 let mut config =
156 rustls::ClientConfig::builder_with_details(provider.clone(), time.time_provider())
157 .with_safe_default_protocol_versions()?
158 .with_root_certificates(roots)
159 .with_no_client_auth();
160 if !options.reject_unauthorized {
161 config
162 .dangerous()
163 .set_certificate_verifier(Arc::new(Unverified { provider }));
164 }
165 config.alpn_protocols = options.alpn;
166 config.enable_sni = options.enable_sni;
167 Ok(Self::from_rustls(Arc::new(config), time))
168 }
169 pub fn from_rustls(config: Arc<rustls::ClientConfig>, time: HostTime) -> Self {
174 Self { config, time }
175 }
176 pub fn rustls_config(&self) -> &Arc<rustls::ClientConfig> {
177 &self.config
178 }
179 pub fn with_alpn(&self, alpn: Vec<Vec<u8>>) -> Self {
183 let mut config = (*self.config).clone();
184 config.alpn_protocols = alpn;
185 Self::from_rustls(Arc::new(config), self.time.clone())
186 }
187 pub fn connect(&self, name: ServerName<'static>) -> Result<Client, Error> {
189 Ok(Client {
190 inner: rustls::client::UnbufferedClientConnection::new(self.config.clone(), name)?,
191 time: self.time.clone(),
192 deadline: None,
193 timed_out: false,
194 })
195 }
196}
197
198#[derive(Clone)]
199pub struct ServerConfig {
200 config: Arc<rustls::ServerConfig>,
201 time: HostTime,
202}
203impl ServerConfig {
204 pub fn new(
207 chain: Vec<CertificateDer<'static>>,
208 key: PrivateKeyDer<'static>,
209 alpn: Vec<Vec<u8>>,
210 unix_seconds: u64,
211 ) -> Result<Self, Error> {
212 Self::with_provider(default_provider()?, chain, key, alpn, unix_seconds)
213 }
214 pub fn with_provider(
216 provider: Arc<CryptoProvider>,
217 chain: Vec<CertificateDer<'static>>,
218 key: PrivateKeyDer<'static>,
219 alpn: Vec<Vec<u8>>,
220 unix_seconds: u64,
221 ) -> Result<Self, Error> {
222 let time = HostTime::new(unix_seconds);
223 let mut config = rustls::ServerConfig::builder_with_details(provider, time.time_provider())
224 .with_safe_default_protocol_versions()?
225 .with_no_client_auth()
226 .with_single_cert(chain, key)?;
227 config.alpn_protocols = alpn;
228 Ok(Self::from_rustls(Arc::new(config), time))
230 }
231 pub fn from_rustls(config: Arc<rustls::ServerConfig>, time: HostTime) -> Self {
235 Self { config, time }
236 }
237 pub fn rustls_config(&self) -> &Arc<rustls::ServerConfig> {
238 &self.config
239 }
240 pub fn accept(&self) -> Result<Server, Error> {
241 Ok(Server {
242 inner: rustls::server::UnbufferedServerConnection::new(self.config.clone())?,
243 time: self.time.clone(),
244 deadline: None,
245 timed_out: false,
246 })
247 }
248}
249
250mod channel_binding;
251#[cfg(feature = "ring")]
252pub use channel_binding::tls_server_end_point;
253pub use channel_binding::{EndPointHash, tls_server_end_point_hash};
254
255macro_rules! endpoint {
256 ($name:ident, $connection:ty, $data:ty) => {
257 pub struct $name {
258 inner: $connection,
259 time: HostTime,
260 deadline: Option<Instant>,
261 timed_out: bool,
262 }
263 impl $name {
264 pub fn process<'c, 'i>(
266 &'c mut self,
267 incoming: &'i mut [u8],
268 unix_seconds: u64,
269 ) -> UnbufferedStatus<'c, 'i, $data> {
270 self.time.set(unix_seconds);
271 if self.timed_out {
272 return UnbufferedStatus {
273 discard: 0,
274 state: Err(Error::General("TLS handshake timeout".into())),
275 };
276 }
277 self.inner.process_tls_records(incoming)
278 }
279 pub fn alpn_protocol(&self) -> Option<&[u8]> {
280 self.inner.alpn_protocol()
281 }
282 pub fn peer_certificates(
285 &self,
286 ) -> Option<&[rustls::pki_types::CertificateDer<'static>]> {
287 self.inner.peer_certificates()
288 }
289 pub fn is_handshaking(&self) -> bool {
290 self.inner.is_handshaking()
291 }
292 pub fn handshake_kind(&self) -> Option<rustls::HandshakeKind> {
293 self.inner.handshake_kind()
294 }
295 pub fn set_handshake_deadline(&mut self, deadline: Option<Instant>) {
296 self.deadline = deadline;
297 }
298 pub fn next_timeout(&self) -> Option<Instant> {
299 if self.inner.is_handshaking() && !self.timed_out {
300 self.deadline
301 } else {
302 None
303 }
304 }
305 pub fn handle_timeout(&mut self, now: Instant) -> Option<&'static str> {
307 if self.next_timeout().is_some_and(|d| now >= d) {
308 self.timed_out = true;
309 self.deadline = None;
310 Some("ERR_TLS_HANDSHAKE_TIMEOUT")
311 } else {
312 None
313 }
314 }
315 }
316 };
317}
318endpoint!(
319 Client,
320 rustls::client::UnbufferedClientConnection,
321 rustls::client::ClientConnectionData
322);
323endpoint!(
324 Server,
325 rustls::server::UnbufferedServerConnection,
326 rustls::server::ServerConnectionData
327);
328
329pub fn node_error_code(error: &Error) -> &'static str {
332 match error {
333 Error::InvalidCertificate(
334 CertificateError::Expired | CertificateError::ExpiredContext { .. },
335 ) => "CERT_HAS_EXPIRED",
336 Error::InvalidCertificate(
337 CertificateError::NotValidYet | CertificateError::NotValidYetContext { .. },
338 ) => "CERT_NOT_YET_VALID",
339 Error::InvalidCertificate(
340 CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
341 ) => "ERR_TLS_CERT_ALTNAME_INVALID",
342 Error::InvalidCertificate(CertificateError::UnknownIssuer) => {
343 "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
344 }
345 Error::InvalidCertificate(CertificateError::Revoked) => "CERT_REVOKED",
346 Error::NoApplicationProtocol => "ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL",
347 _ => "ERR_SSL_PROTOCOL_ERROR",
348 }
349}
350
351#[derive(Debug)]
352struct Unverified {
353 provider: Arc<CryptoProvider>,
354}
355impl ServerCertVerifier for Unverified {
356 fn verify_server_cert(
357 &self,
358 _: &CertificateDer<'_>,
359 _: &[CertificateDer<'_>],
360 _: &ServerName<'_>,
361 _: &[u8],
362 _: UnixTime,
363 ) -> Result<ServerCertVerified, Error> {
364 Ok(ServerCertVerified::assertion())
365 }
366 fn verify_tls12_signature(
368 &self,
369 message: &[u8],
370 cert: &CertificateDer<'_>,
371 dss: &DigitallySignedStruct,
372 ) -> Result<HandshakeSignatureValid, Error> {
373 rustls::crypto::verify_tls12_signature(
374 message,
375 cert,
376 dss,
377 &self.provider.signature_verification_algorithms,
378 )
379 }
380 fn verify_tls13_signature(
381 &self,
382 message: &[u8],
383 cert: &CertificateDer<'_>,
384 dss: &DigitallySignedStruct,
385 ) -> Result<HandshakeSignatureValid, Error> {
386 rustls::crypto::verify_tls13_signature(
387 message,
388 cert,
389 dss,
390 &self.provider.signature_verification_algorithms,
391 )
392 }
393 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
394 self.provider
395 .signature_verification_algorithms
396 .supported_schemes()
397 }
398}
399
400#[cfg(feature = "turnloop")]
401pub mod asynchronous;
402#[cfg(feature = "turnloop")]
403pub use asynchronous::TlsStream;