1use crate::error::RedisError;
27use crate::stream::RedisStream;
28use tokio::net::TcpStream;
29
30pub struct TlsConfig {
56 pub(crate) backend: TlsBackend,
57 pub(crate) accept_invalid_certs: bool,
58 pub(crate) accept_invalid_hostnames: bool,
59 pub(crate) root_ca_pem: Option<Vec<u8>>,
63 pub(crate) client_auth_pem: Option<(Vec<u8>, Vec<u8>)>,
65}
66
67pub(crate) enum TlsBackend {
68 #[cfg(feature = "tls-native-tls")]
69 NativeTls,
70 #[cfg(feature = "tls-native-tls")]
71 NativeTlsCustom(native_tls::TlsConnector),
72 #[cfg(feature = "tls-rustls")]
73 Rustls,
74 #[cfg(feature = "tls-rustls")]
75 RustlsCustom(std::sync::Arc<rustls::ClientConfig>),
76}
77
78impl TlsConfig {
79 #[cfg(feature = "tls-native-tls")]
81 #[cfg_attr(docsrs, doc(cfg(feature = "tls-native-tls")))]
82 pub fn default_native_tls() -> Self {
83 Self {
84 backend: TlsBackend::NativeTls,
85 accept_invalid_certs: false,
86 accept_invalid_hostnames: false,
87 root_ca_pem: None,
88 client_auth_pem: None,
89 }
90 }
91
92 #[cfg(feature = "tls-rustls")]
94 #[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
95 pub fn default_rustls() -> Self {
96 Self {
97 backend: TlsBackend::Rustls,
98 accept_invalid_certs: false,
99 accept_invalid_hostnames: false,
100 root_ca_pem: None,
101 client_auth_pem: None,
102 }
103 }
104
105 #[cfg(feature = "tls-rustls")]
113 #[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
114 pub fn from_rustls_config(config: std::sync::Arc<rustls::ClientConfig>) -> Self {
115 Self {
116 backend: TlsBackend::RustlsCustom(config),
117 accept_invalid_certs: false,
118 accept_invalid_hostnames: false,
119 root_ca_pem: None,
120 client_auth_pem: None,
121 }
122 }
123
124 #[cfg(feature = "tls-native-tls")]
132 #[cfg_attr(docsrs, doc(cfg(feature = "tls-native-tls")))]
133 pub fn from_native_tls_connector(connector: native_tls::TlsConnector) -> Self {
134 Self {
135 backend: TlsBackend::NativeTlsCustom(connector),
136 accept_invalid_certs: false,
137 accept_invalid_hostnames: false,
138 root_ca_pem: None,
139 client_auth_pem: None,
140 }
141 }
142
143 pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
148 self.accept_invalid_certs = accept;
149 self
150 }
151
152 pub fn danger_accept_invalid_hostnames(mut self, accept: bool) -> Self {
156 self.accept_invalid_hostnames = accept;
157 self
158 }
159
160 pub fn with_root_ca_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
180 self.root_ca_pem = Some(pem.into());
181 self
182 }
183
184 pub fn with_client_auth_pem(
205 mut self,
206 cert_pem: impl Into<Vec<u8>>,
207 key_pem: impl Into<Vec<u8>>,
208 ) -> Self {
209 self.client_auth_pem = Some((cert_pem.into(), key_pem.into()));
210 self
211 }
212
213 pub(crate) async fn connect(
215 &self,
216 tcp: TcpStream,
217 hostname: &str,
218 ) -> Result<RedisStream, RedisError> {
219 match &self.backend {
220 #[cfg(feature = "tls-native-tls")]
221 TlsBackend::NativeTls => self.connect_native_tls(tcp, hostname).await,
222 #[cfg(feature = "tls-native-tls")]
223 TlsBackend::NativeTlsCustom(connector) => {
224 Self::connect_native_tls_custom(connector.clone(), tcp, hostname).await
225 }
226 #[cfg(feature = "tls-rustls")]
227 TlsBackend::Rustls => self.connect_rustls(tcp, hostname).await,
228 #[cfg(feature = "tls-rustls")]
229 TlsBackend::RustlsCustom(config) => {
230 Self::connect_rustls_custom(config.clone(), tcp, hostname).await
231 }
232 }
233 }
234
235 #[cfg(feature = "tls-native-tls")]
236 async fn connect_native_tls(
237 &self,
238 tcp: TcpStream,
239 hostname: &str,
240 ) -> Result<RedisStream, RedisError> {
241 let mut builder = native_tls::TlsConnector::builder();
242 builder.danger_accept_invalid_certs(self.accept_invalid_certs);
243 builder.danger_accept_invalid_hostnames(self.accept_invalid_hostnames);
244 if let Some(ref ca) = self.root_ca_pem {
245 let cert = native_tls::Certificate::from_pem(ca)
246 .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
247 builder.add_root_certificate(cert);
248 }
249 if let Some((ref cert_pem, ref key_pem)) = self.client_auth_pem {
250 let identity = native_tls::Identity::from_pkcs8(cert_pem, key_pem)
251 .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
252 builder.identity(identity);
253 }
254
255 let connector = builder
256 .build()
257 .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
258 let connector = tokio_native_tls::TlsConnector::from(connector);
259
260 let tls_stream = connector
261 .connect(hostname, tcp)
262 .await
263 .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
264
265 Ok(RedisStream::NativeTls(Box::new(tls_stream)))
266 }
267
268 #[cfg(feature = "tls-native-tls")]
269 async fn connect_native_tls_custom(
270 connector: native_tls::TlsConnector,
271 tcp: TcpStream,
272 hostname: &str,
273 ) -> Result<RedisStream, RedisError> {
274 let connector = tokio_native_tls::TlsConnector::from(connector);
275
276 let tls_stream = connector
277 .connect(hostname, tcp)
278 .await
279 .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
280
281 Ok(RedisStream::NativeTls(Box::new(tls_stream)))
282 }
283
284 #[cfg(feature = "tls-rustls")]
287 fn rustls_root_store(&self) -> Result<rustls::RootCertStore, RedisError> {
288 let mut root_store = rustls::RootCertStore::empty();
289 if let Some(ref ca) = self.root_ca_pem {
290 for cert in parse_certs_pem(ca)? {
291 root_store
292 .add(cert)
293 .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
294 }
295 } else {
296 let native_result = rustls_native_certs::load_native_certs();
297 for cert in native_result.certs {
298 let _ = root_store.add(cert);
299 }
300 if root_store.is_empty() {
301 root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
302 }
303 }
304 Ok(root_store)
305 }
306
307 #[cfg(feature = "tls-rustls")]
308 async fn connect_rustls(
309 &self,
310 tcp: TcpStream,
311 hostname: &str,
312 ) -> Result<RedisStream, RedisError> {
313 use std::sync::Arc;
314
315 let builder = rustls::ClientConfig::builder_with_provider(Arc::new(
322 rustls::crypto::ring::default_provider(),
323 ))
324 .with_safe_default_protocol_versions()
325 .map_err(|error| RedisError::from(std::io::Error::other(error)))?;
326 let builder = if self.accept_invalid_certs {
327 builder
328 .dangerous()
329 .with_custom_certificate_verifier(Arc::new(DangerousVerifier))
330 } else {
331 builder.with_root_certificates(self.rustls_root_store()?)
332 };
333 let config = match &self.client_auth_pem {
334 Some((cert_pem, key_pem)) => builder
335 .with_client_auth_cert(parse_certs_pem(cert_pem)?, parse_private_key_pem(key_pem)?)
336 .map_err(|e| RedisError::from(std::io::Error::other(e)))?,
337 None => builder.with_no_client_auth(),
338 };
339
340 let connector = tokio_rustls::TlsConnector::from(Arc::new(config));
341 let server_name =
342 rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|e| {
343 RedisError::from(std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
344 })?;
345
346 let tls_stream = connector
347 .connect(server_name, tcp)
348 .await
349 .map_err(RedisError::from)?;
350
351 Ok(RedisStream::Rustls(Box::new(tls_stream)))
352 }
353
354 #[cfg(feature = "tls-rustls")]
355 async fn connect_rustls_custom(
356 config: std::sync::Arc<rustls::ClientConfig>,
357 tcp: TcpStream,
358 hostname: &str,
359 ) -> Result<RedisStream, RedisError> {
360 let connector = tokio_rustls::TlsConnector::from(config);
361 let server_name =
362 rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|e| {
363 RedisError::from(std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
364 })?;
365
366 let tls_stream = connector
367 .connect(server_name, tcp)
368 .await
369 .map_err(RedisError::from)?;
370
371 Ok(RedisStream::Rustls(Box::new(tls_stream)))
372 }
373}
374
375#[cfg(feature = "tls-rustls")]
377fn parse_certs_pem(
378 pem: &[u8],
379) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>, RedisError> {
380 use rustls::pki_types::pem::PemObject;
381 rustls::pki_types::CertificateDer::pem_slice_iter(pem)
382 .collect::<Result<Vec<_>, _>>()
383 .map_err(|e| RedisError::from(std::io::Error::other(e)))
384}
385
386#[cfg(feature = "tls-rustls")]
388fn parse_private_key_pem(
389 pem: &[u8],
390) -> Result<rustls::pki_types::PrivateKeyDer<'static>, RedisError> {
391 use rustls::pki_types::pem::PemObject;
392 rustls::pki_types::PrivateKeyDer::from_pem_slice(pem)
393 .map_err(|e| RedisError::from(std::io::Error::other(e)))
394}
395
396#[cfg(feature = "tls-rustls")]
399#[derive(Debug)]
400struct DangerousVerifier;
401
402#[cfg(feature = "tls-rustls")]
403impl rustls::client::danger::ServerCertVerifier for DangerousVerifier {
404 fn verify_server_cert(
405 &self,
406 _end_entity: &rustls::pki_types::CertificateDer<'_>,
407 _intermediates: &[rustls::pki_types::CertificateDer<'_>],
408 _server_name: &rustls::pki_types::ServerName<'_>,
409 _ocsp_response: &[u8],
410 _now: rustls::pki_types::UnixTime,
411 ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
412 Ok(rustls::client::danger::ServerCertVerified::assertion())
413 }
414
415 fn verify_tls12_signature(
416 &self,
417 _message: &[u8],
418 _cert: &rustls::pki_types::CertificateDer<'_>,
419 _dss: &rustls::DigitallySignedStruct,
420 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
421 Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
422 }
423
424 fn verify_tls13_signature(
425 &self,
426 _message: &[u8],
427 _cert: &rustls::pki_types::CertificateDer<'_>,
428 _dss: &rustls::DigitallySignedStruct,
429 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
430 Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
431 }
432
433 fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
434 rustls::crypto::ring::default_provider()
435 .signature_verification_algorithms
436 .supported_schemes()
437 }
438}
439
440#[cfg(test)]
441pub(crate) mod tests {
442 use super::*;
443
444 const TEST_CERT: &str = "-----BEGIN CERTIFICATE-----\n\
446MIIBijCCATGgAwIBAgIUeYWzxqGH+ak/HDH9RMB1+u5Lhf4wCgYIKoZIzj0EAwIw\n\
447GzEZMBcGA1UEAwwQcmVkaXMtdG93ZXItdGVzdDAeFw0yNjA2MTIyMTAxNTNaFw0z\n\
448NjA2MDkyMTAxNTNaMBsxGTAXBgNVBAMMEHJlZGlzLXRvd2VyLXRlc3QwWTATBgcq\n\
449hkjOPQIBBggqhkjOPQMBBwNCAARTJOAo81mVG4sncY5w6LVlG+y3O4llaHzx7UOq\n\
450MKxs4Csh4kTiDRmwUoIq9DISRM1uYUR5dR9MjoMk/NEt3Jxpo1MwUTAdBgNVHQ4E\n\
451FgQUkxm6d0TuRcV/ZOvIdRHtudvybO0wHwYDVR0jBBgwFoAUkxm6d0TuRcV/ZOvI\n\
452dRHtudvybO0wDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNHADBEAiBMx2WV\n\
4538zEWSydXPqn7rabmh91JYNG3ikU1ggxscXSnDAIgVKG6VLZwvTHDRA6HSFdoAqyc\n\
4542c6Rr4ZJh79vhNSj8jM=\n\
455-----END CERTIFICATE-----\n";
456
457 const TEST_KEY: &str = "-----BEGIN PRIVATE KEY-----\n\
458MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgju5KBtu0Tyd5YVXR\n\
459JwQS3S1hW6Ts2I3ASTerbjBlJPahRANCAARTJOAo81mVG4sncY5w6LVlG+y3O4ll\n\
460aHzx7UOqMKxs4Csh4kTiDRmwUoIq9DISRM1uYUR5dR9MjoMk/NEt3Jxp\n\
461-----END PRIVATE KEY-----\n";
462
463 #[cfg(feature = "tls-rustls")]
464 pub(crate) fn server_config() -> std::sync::Arc<rustls::ServerConfig> {
465 let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider());
466 let config = rustls::ServerConfig::builder_with_provider(provider)
467 .with_safe_default_protocol_versions()
468 .unwrap()
469 .with_no_client_auth()
470 .with_single_cert(
471 parse_certs_pem(TEST_CERT.as_bytes()).unwrap(),
472 parse_private_key_pem(TEST_KEY.as_bytes()).unwrap(),
473 )
474 .unwrap();
475 std::sync::Arc::new(config)
476 }
477
478 #[cfg(feature = "tls-rustls")]
479 #[test]
480 fn with_root_ca_pem_sets_field_and_builds_store() {
481 let tls = TlsConfig::default_rustls().with_root_ca_pem(TEST_CERT.as_bytes().to_vec());
482 assert!(tls.root_ca_pem.is_some());
483 let store = tls.rustls_root_store().expect("custom CA should parse");
485 assert_eq!(store.len(), 1);
486 }
487
488 #[cfg(feature = "tls-rustls")]
489 #[test]
490 fn with_client_auth_pem_builds_a_client_config() {
491 let tls = TlsConfig::default_rustls()
492 .with_root_ca_pem(TEST_CERT.as_bytes().to_vec())
493 .with_client_auth_pem(TEST_CERT.as_bytes().to_vec(), TEST_KEY.as_bytes().to_vec());
494 assert!(tls.client_auth_pem.is_some());
495 let certs = parse_certs_pem(TEST_CERT.as_bytes()).unwrap();
497 let key = parse_private_key_pem(TEST_KEY.as_bytes()).unwrap();
498 rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(
499 rustls::crypto::ring::default_provider(),
500 ))
501 .with_safe_default_protocol_versions()
502 .unwrap()
503 .with_root_certificates(tls.rustls_root_store().unwrap())
504 .with_client_auth_cert(certs, key)
505 .expect("mTLS client config should build");
506 }
507
508 #[cfg(feature = "tls-rustls")]
509 #[test]
510 fn parse_helpers_reject_garbage() {
511 assert!(parse_certs_pem(b"not a pem").unwrap().is_empty());
513 assert!(parse_private_key_pem(b"-----BEGIN CERTIFICATE-----\nx\n").is_err());
515 }
516}