Skip to content

Commit

Permalink
feat: use Rustls for connections with strict TLS
Browse files Browse the repository at this point in the history
  • Loading branch information
link2xt committed Nov 7, 2024
1 parent 2a244eb commit 13c12a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 24 deletions.
Binary file removed assets/root-certificates/letsencrypt/isrgrootx1.der
Binary file not shown.
42 changes: 18 additions & 24 deletions src/net/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,38 @@
use std::sync::Arc;

use anyhow::Result;
use once_cell::sync::Lazy;

use crate::net::session::SessionStream;

// this certificate is missing on older android devices (eg. lg with android6 from 2017)
// certificate downloaded from https://letsencrypt.org/certificates/
static LETSENCRYPT_ROOT: Lazy<async_native_tls::Certificate> = Lazy::new(|| {
async_native_tls::Certificate::from_der(include_bytes!(
"../../assets/root-certificates/letsencrypt/isrgrootx1.der"
))
.unwrap()
});

pub async fn wrap_tls(
strict_tls: bool,
hostname: &str,
alpn: &[&str],
stream: impl SessionStream,
stream: impl SessionStream + 'static,
) -> Result<impl SessionStream> {
let tls_builder = async_native_tls::TlsConnector::new()
.min_protocol_version(Some(async_native_tls::Protocol::Tlsv12))
.request_alpns(alpn)
.add_root_certificate(LETSENCRYPT_ROOT.clone());
let tls = if strict_tls {
tls_builder
} else {
tls_builder
if strict_tls {
// We use native_tls because it accepts 1024-bit RSA keys.
// Rustls does not support them even if
// certificate checks are disabled: <https://github.com/rustls/rustls/issues/234>.
let tls = async_native_tls::TlsConnector::new()
.min_protocol_version(Some(async_native_tls::Protocol::Tlsv12))
.request_alpns(alpn)
.danger_accept_invalid_hostnames(true)
.danger_accept_invalid_certs(true)
};
let tls_stream = tls.connect(hostname, stream).await?;
Ok(tls_stream)
.danger_accept_invalid_certs(true);
let tls_stream = tls.connect(hostname, stream).await?;
let boxed_stream: Box<dyn SessionStream> = Box::new(tls_stream);
Ok(boxed_stream)
} else {
let tls_stream = wrap_rustls(hostname, alpn, stream).await?;
let boxed_stream: Box<dyn SessionStream> = Box::new(tls_stream);
Ok(boxed_stream)
}
}

pub async fn wrap_rustls(
hostname: &str,
alpn: &[&str],
stream: impl SessionStream,
stream: impl SessionStream + 'static,
) -> Result<impl SessionStream> {
let mut root_cert_store = rustls::RootCertStore::empty();
root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
Expand Down

0 comments on commit 13c12a8

Please sign in to comment.