|
2 | 2 | use std::sync::Arc;
|
3 | 3 |
|
4 | 4 | use anyhow::Result;
|
5 |
| -use async_native_tls::{Certificate, Protocol, TlsConnector, TlsStream}; |
6 |
| -use once_cell::sync::Lazy; |
7 |
| -use tokio::io::{AsyncRead, AsyncWrite}; |
8 | 5 |
|
9 |
| -// this certificate is missing on older android devices (eg. lg with android6 from 2017) |
10 |
| -// certificate downloaded from https://letsencrypt.org/certificates/ |
11 |
| -static LETSENCRYPT_ROOT: Lazy<Certificate> = Lazy::new(|| { |
12 |
| - Certificate::from_der(include_bytes!( |
13 |
| - "../../assets/root-certificates/letsencrypt/isrgrootx1.der" |
14 |
| - )) |
15 |
| - .unwrap() |
16 |
| -}); |
| 6 | +use crate::net::session::SessionStream; |
17 | 7 |
|
18 |
| -pub async fn wrap_tls<T: AsyncRead + AsyncWrite + Unpin>( |
| 8 | +pub async fn wrap_tls( |
19 | 9 | strict_tls: bool,
|
20 | 10 | hostname: &str,
|
21 | 11 | alpn: &[&str],
|
22 |
| - stream: T, |
23 |
| -) -> Result<TlsStream<T>> { |
24 |
| - let tls_builder = TlsConnector::new() |
25 |
| - .min_protocol_version(Some(Protocol::Tlsv12)) |
26 |
| - .request_alpns(alpn) |
27 |
| - .add_root_certificate(LETSENCRYPT_ROOT.clone()); |
28 |
| - let tls = if strict_tls { |
29 |
| - tls_builder |
| 12 | + stream: impl SessionStream + 'static, |
| 13 | +) -> Result<impl SessionStream> { |
| 14 | + if strict_tls { |
| 15 | + let tls_stream = wrap_rustls(hostname, alpn, stream).await?; |
| 16 | + let boxed_stream: Box<dyn SessionStream> = Box::new(tls_stream); |
| 17 | + Ok(boxed_stream) |
30 | 18 | } else {
|
31 |
| - tls_builder |
| 19 | + // We use native_tls because it accepts 1024-bit RSA keys. |
| 20 | + // Rustls does not support them even if |
| 21 | + // certificate checks are disabled: <https://github.com/rustls/rustls/issues/234>. |
| 22 | + let tls = async_native_tls::TlsConnector::new() |
| 23 | + .min_protocol_version(Some(async_native_tls::Protocol::Tlsv12)) |
| 24 | + .request_alpns(alpn) |
32 | 25 | .danger_accept_invalid_hostnames(true)
|
33 |
| - .danger_accept_invalid_certs(true) |
34 |
| - }; |
35 |
| - let tls_stream = tls.connect(hostname, stream).await?; |
36 |
| - Ok(tls_stream) |
| 26 | + .danger_accept_invalid_certs(true); |
| 27 | + let tls_stream = tls.connect(hostname, stream).await?; |
| 28 | + let boxed_stream: Box<dyn SessionStream> = Box::new(tls_stream); |
| 29 | + Ok(boxed_stream) |
| 30 | + } |
37 | 31 | }
|
38 | 32 |
|
39 |
| -pub async fn wrap_rustls<T: AsyncRead + AsyncWrite + Unpin>( |
| 33 | +pub async fn wrap_rustls( |
40 | 34 | hostname: &str,
|
41 | 35 | alpn: &[&str],
|
42 |
| - stream: T, |
43 |
| -) -> Result<tokio_rustls::client::TlsStream<T>> { |
| 36 | + stream: impl SessionStream, |
| 37 | +) -> Result<impl SessionStream> { |
44 | 38 | let mut root_cert_store = rustls::RootCertStore::empty();
|
45 | 39 | root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
46 | 40 |
|
|
0 commit comments