Skip to content

Commit

Permalink
Provide example of more in-depth TLS config
Browse files Browse the repository at this point in the history
Close #480
  • Loading branch information
algesten committed Feb 10, 2022
1 parent 4f3ea15 commit b4ed76c
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
67 changes: 67 additions & 0 deletions examples/tls_config.rs
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit b4ed76c

Please sign in to comment.