-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.rs
62 lines (50 loc) · 2.17 KB
/
tls.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
pub use tokio_rustls;
#[cfg(feature = "client-tls-helper")]
use std::sync::Arc;
#[cfg(feature = "client-tls-helper")]
use tokio_rustls::{TlsConnector, rustls::{self, OwnedTrustAnchor}};
#[cfg(feature = "client-tls-helper")]
pub fn build_connector() -> TlsConnector {
let mut root_cert_store = rustls::RootCertStore::empty();
root_cert_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(
|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
},
));
let config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_cert_store)
.with_no_client_auth();
TlsConnector::from(Arc::new(config))
}
#[cfg(feature = "server-tls-helper")]
use std::{sync::Arc, path::Path, io::{self, BufReader}, fs::File};
#[cfg(feature = "server-tls-helper")]
use tokio_rustls::{TlsAcceptor, rustls::{self, Certificate, PrivateKey}};
#[cfg(feature = "server-tls-helper")]
pub fn load_certs<P: AsRef<Path>>(path: P) -> io::Result<Vec<Certificate>> {
let mut certs = rustls_pemfile::certs(&mut BufReader::new(File::open(path)?))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid certs"))?;
Ok(certs.drain(..).map(Certificate).collect())
}
#[cfg(feature = "server-tls-helper")]
pub fn load_rsa_key<P: AsRef<Path>>(path: P) -> io::Result<PrivateKey> {
let mut keys = rustls_pemfile::rsa_private_keys(&mut BufReader::new(File::open(path)?))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid key"))?;
let key = keys.drain(..).map(PrivateKey).next()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid key"))?;
Ok(key)
}
#[cfg(feature = "server-tls-helper")]
pub fn build_acceptor(key: PrivateKey, certs: Vec<Certificate>) -> io::Result<TlsAcceptor> {
let config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(certs, key)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
Ok(TlsAcceptor::from(Arc::new(config)))
}