diff --git a/Cargo.toml b/Cargo.toml index 3a8dfb7..fdb8f1e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,3 +56,7 @@ mbedtls = { version = "0.8.1" } [[example]] name = "cureq" required-features = ["charset", "cookies", "socks-proxy", "native-tls"] + +[[example]] +name = "tls_config" +required-features = ["tls", "native-tls"] diff --git a/examples/tls_config.rs b/examples/tls_config.rs new file mode 100644 index 0000000..a38b447 --- /dev/null +++ b/examples/tls_config.rs @@ -0,0 +1,67 @@ +//! Example of how to make more in depth TLS config, like narrowing the allowed TLS versions. + +use std::sync::Arc; + +use native_tls::Protocol; +use rustls::version::TLS12; +use rustls::version::TLS13; + +pub fn main() { + let mut root_store = rustls::RootCertStore::empty(); + + // Uncomment this to use native-certs + + // let certs = rustls_native_certs::load_native_certs().expect("Could not load platform certs"); + // for cert in certs { + // // Repackage the certificate DER bytes. + // let rustls_cert = rustls::Certificate(cert.0); + // root_store + // .add(&rustls_cert) + // .expect("Failed to add native certificate too root store"); + // } + + // This adds webpki_roots certs. + root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| { + rustls::OwnedTrustAnchor::from_subject_spki_name_constraints( + ta.subject, + ta.spki, + ta.name_constraints, + ) + })); + + // This is how we narrow down the allowed TLS versions for rustls. + let protocol_versions = &[&TLS12, &TLS13]; + + // See rustls documentation for more configuration options. + let tls_config = rustls::ClientConfig::builder() + .with_safe_default_cipher_suites() + .with_safe_default_kx_groups() + .with_protocol_versions(protocol_versions) + .unwrap() + .with_root_certificates(root_store) + .with_no_client_auth(); + + // Build a ureq agent with the rustls config. + let agent1 = ureq::builder().tls_config(Arc::new(tls_config)).build(); + + let response1 = agent1.get("https://httpbin.org/get").call().unwrap(); + assert!(response1.status() == 200); + + //////////////////////////////////////////////////////////// + + // Narrow the accepted TLS versions for native-tls + // See native-tls documentation for more configuration options. + let tls_connector = native_tls::TlsConnector::builder() + .min_protocol_version(Some(Protocol::Tlsv12)) + .max_protocol_version(Some(Protocol::Tlsv12)) + .build() + .unwrap(); + + // Build a ureq agent with the native-tls config. + let agent2 = ureq::builder() + .tls_connector(Arc::new(tls_connector)) + .build(); + + let response2 = agent2.get("https://httpbin.org/get").call().unwrap(); + assert!(response2.status() == 200); +}