1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

chore: upgrade to rustls v0.23

This commit is contained in:
Rob Ede
2024-05-25 05:36:36 +01:00
parent d066747672
commit f36601babb
16 changed files with 263 additions and 199 deletions

View File

@ -7,11 +7,11 @@ edition.workspace = true
[dependencies]
acme-rfc8555 = "0.1"
actix-files.workspace = true
actix-web = { workspace = true, features = ["rustls"] }
actix-web = { workspace = true, features = ["rustls-0_23"] }
color-eyre = "0.6"
env_logger.workspace = true
eyre = "0.6"
log.workspace = true
rustls = "0.21"
rustls-pemfile = "1"
rustls.workspace = true
rustls-pemfile.workspace = true
tokio = { workspace = true, features = ["fs"] }

View File

@ -4,6 +4,7 @@ use acme::{create_p256_key, Certificate, Directory, DirectoryUrl};
use actix_files::Files;
use actix_web::{rt, web, App, HttpRequest, HttpServer, Responder};
use eyre::eyre;
use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};
use tokio::fs;
const CHALLENGE_DIR: &str = "./acme-challenges";
@ -112,7 +113,7 @@ pub async fn gen_tls_cert(user_domain: &str, contact_email: &str) -> eyre::Resul
// certificate is either issued or rejected. Again we poll
// for the status change.
let ord_cert = ord_csr
.finalize(signing_key, Duration::from_millis(5000))
.finalize(signing_key, Duration::from_secs(5))
.await?;
// Now download the certificate. Also stores the cert in
@ -139,6 +140,10 @@ async fn main() -> eyre::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
color_eyre::install()?;
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
// Load keys
// ==============================================
// = IMPORTANT: =
@ -157,7 +162,7 @@ async fn main() -> eyre::Result<()> {
// Start HTTP server!
let srv = HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_rustls_021(("0.0.0.0", 443), rustls_config)?
.bind_rustls_0_23(("0.0.0.0", 443), rustls_config)?
.run();
let srv_handle = srv.handle();
@ -177,19 +182,16 @@ async fn main() -> eyre::Result<()> {
fn load_rustls_config(cert: Certificate) -> eyre::Result<rustls::ServerConfig> {
// init server config builder with safe defaults
let config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth();
let config = rustls::ServerConfig::builder().with_no_client_auth();
// convert ACME-obtained private key
let private_key = rustls::PrivateKey(cert.private_key_der()?.to_owned());
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.private_key_der()?));
// convert ACME-obtained certificate chain
let cert_chain =
rustls_pemfile::certs(&mut std::io::BufReader::new(cert.certificate().as_bytes()))?
.into_iter()
.map(rustls::Certificate)
.collect();
rustls_pemfile::certs(&mut std::io::BufReader::new(cert.certificate().as_bytes()))
.collect::<Result<Vec<_>, _>>()
.unwrap();
Ok(config.with_single_cert(cert_chain, private_key)?)
}

View File

@ -5,10 +5,10 @@ edition = "2021"
[dependencies]
actix-web.workspace = true
awc = { workspace = true, features = ["rustls-0_21"] }
awc = { workspace = true, features = ["rustls-0_23"] }
env_logger.workspace = true
log.workspace = true
mime = "0.3"
rustls.workspace = true
webpki-roots = "0.25"
webpki-roots = "0.26"

View File

@ -2,7 +2,7 @@ use std::{sync::Arc, time::Instant};
use actix_web::{get, middleware, web::Data, App, HttpResponse, HttpServer};
use awc::{http::header, Client, Connector};
use rustls::{ClientConfig, OwnedTrustAnchor, RootCertStore};
use rustls::{ClientConfig, RootCertStore};
const MAP_URL: &str =
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg";
@ -49,7 +49,7 @@ async fn main() -> std::io::Result<()> {
// Wikipedia requires a User-Agent header to make requests
.add_default_header((header::USER_AGENT, "awc-example/1.0"))
// a "connector" wraps the stream into an encrypted connection
.connector(Connector::new().rustls_021(Arc::clone(&client_tls_config)))
.connector(Connector::new().rustls_0_23(Arc::clone(&client_tls_config)))
.finish();
App::new()
@ -65,17 +65,13 @@ async fn main() -> std::io::Result<()> {
/// Create simple rustls client config from root certificates.
fn rustls_config() -> ClientConfig {
let mut root_store = RootCertStore::empty();
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
let root_store = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.to_owned());
rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_store)
.with_no_client_auth()
}

View File

@ -4,7 +4,7 @@ version = "1.0.0"
edition = "2021"
[dependencies]
actix-web = { workspace = true, features = ["rustls-0_21"] }
actix-web = { workspace = true, features = ["rustls-0_23"] }
actix-files.workspace = true
color-eyre.workspace = true
env_logger.workspace = true
@ -13,6 +13,6 @@ futures-util.workspace = true
log.workspace = true
notify = "6"
rustls.workspace = true
rustls-pemfile = "1"
rustls-pemfile.workspace = true
tokio = { workspace = true, features = ["time", "rt", "macros"] }
parking_lot = "0.12"

View File

@ -5,7 +5,7 @@ use actix_web::{
};
use log::debug;
use notify::{Event, RecursiveMode, Watcher as _};
use rustls::{Certificate, PrivateKey, ServerConfig};
use rustls::{pki_types::PrivateKeyDer, ServerConfig};
use rustls_pemfile::{certs, pkcs8_private_keys};
use tokio::sync::mpsc;
@ -65,7 +65,7 @@ async fn main() -> eyre::Result<()> {
.wrap(middleware::Logger::default())
})
.workers(2)
.bind_rustls_021("127.0.0.1:8443", config)?
.bind_rustls_0_23("127.0.0.1:8443", config)?
.run();
// server handle to send signals
@ -100,21 +100,23 @@ async fn main() -> eyre::Result<()> {
}
fn load_rustls_config() -> eyre::Result<rustls::ServerConfig> {
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
// init server config builder with safe defaults
let config = ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth();
let config = ServerConfig::builder().with_no_client_auth();
// load TLS key/cert files
let cert_file = &mut BufReader::new(File::open("cert.pem")?);
let key_file = &mut BufReader::new(File::open("key.pem")?);
// convert files to key/cert objects
let cert_chain = certs(cert_file)?.into_iter().map(Certificate).collect();
let mut keys: Vec<PrivateKey> = pkcs8_private_keys(key_file)?
.into_iter()
.map(PrivateKey)
.collect();
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
let mut keys = pkcs8_private_keys(key_file)
.map(|key| key.map(PrivateKeyDer::Pkcs8))
.collect::<Result<Vec<_>, _>>()
.unwrap();
// exit if no keys could be parsed
if keys.is_empty() {

View File

@ -4,9 +4,9 @@ version = "1.0.0"
edition = "2021"
[dependencies]
actix-tls = { workspace = true, features = ["rustls-0_21"] }
actix-web = { workspace = true, features = ["rustls-0_21"] }
actix-tls = { workspace = true, features = ["rustls-0_23"] }
actix-web = { workspace = true, features = ["rustls-0_23"] }
env_logger.workspace = true
log.workspace = true
rustls.workspace = true
rustls-pemfile = "1"
rustls-pemfile.workspace = true

View File

@ -3,13 +3,15 @@
use std::{any::Any, fs::File, io::BufReader, net::SocketAddr, sync::Arc};
use actix_tls::accept::rustls_0_21::{reexports::ServerConfig, TlsStream};
use actix_tls::accept::rustls_0_23::TlsStream;
use actix_web::{
dev::Extensions, rt::net::TcpStream, web, App, HttpRequest, HttpResponse, HttpServer, Responder,
};
use log::info;
use rustls::{
server::AllowAnyAnonymousOrAuthenticatedClient, Certificate, PrivateKey, RootCertStore,
pki_types::{CertificateDer, PrivateKeyDer},
server::WebPkiClientVerifier,
RootCertStore, ServerConfig,
};
use rustls_pemfile::{certs, pkcs8_private_keys};
@ -27,7 +29,7 @@ struct ConnectionInfo {
async fn route_whoami(req: HttpRequest) -> impl Responder {
let conn_info = req.conn_data::<ConnectionInfo>().unwrap();
let client_cert = req.conn_data::<Certificate>();
let client_cert = req.conn_data::<CertificateDer<'static>>();
if let Some(cert) = client_cert {
HttpResponse::Ok().body(format!("{:?}\n\n{:?}", &conn_info, &cert))
@ -71,36 +73,35 @@ fn get_client_cert(connection: &dyn Any, data: &mut Extensions) {
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
let mut cert_store = RootCertStore::empty();
// import CA cert
let ca_cert = &mut BufReader::new(File::open(CA_CERT)?);
let ca_cert = Certificate(certs(ca_cert).unwrap()[0].clone());
let ca_cert = certs(ca_cert).collect::<Result<Vec<_>, _>>().unwrap();
cert_store
.add(&ca_cert)
.expect("root CA not added to store");
for cert in ca_cert {
cert_store.add(cert).expect("root CA not added to store");
}
// set up client authentication requirements
let client_auth = AllowAnyAnonymousOrAuthenticatedClient::new(cert_store);
let config = ServerConfig::builder()
.with_safe_defaults()
.with_client_cert_verifier(Arc::new(client_auth));
let client_auth = WebPkiClientVerifier::builder(Arc::new(cert_store))
.build()
.unwrap();
let config = ServerConfig::builder().with_client_cert_verifier(client_auth);
// import server cert and key
let cert_file = &mut BufReader::new(File::open(SERVER_CERT)?);
let key_file = &mut BufReader::new(File::open(SERVER_KEY)?);
let cert_chain = certs(cert_file)
.unwrap()
.into_iter()
.map(Certificate)
.collect();
let mut keys: Vec<PrivateKey> = pkcs8_private_keys(key_file)
.unwrap()
.into_iter()
.map(PrivateKey)
.collect();
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
let mut keys = pkcs8_private_keys(key_file)
.map(|key| key.map(PrivateKeyDer::Pkcs8))
.collect::<Result<Vec<_>, _>>()
.unwrap();
let config = config.with_single_cert(cert_chain, keys.remove(0)).unwrap();
log::info!("starting HTTP server at http://localhost:8080 and https://localhost:8443");
@ -108,7 +109,7 @@ async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().default_service(web::to(route_whoami)))
.on_connect(get_client_cert)
.bind(("localhost", 8080))?
.bind_rustls_021(("localhost", 8443), config)?
.bind_rustls_0_23(("localhost", 8443), config)?
.workers(1)
.run()
.await

View File

@ -3,15 +3,11 @@ name = "rustls-example"
version = "1.0.0"
edition = "2021"
[[bin]]
name = "rustls-server"
path = "src/main.rs"
[dependencies]
actix-web = { workspace = true, features = ["rustls-0_21"] }
actix-web = { workspace = true, features = ["rustls-0_23"] }
actix-files.workspace = true
env_logger.workspace = true
log.workspace = true
rustls.workspace = true
rustls-pemfile = "1"
rustls-pemfile.workspace = true

View File

@ -5,7 +5,7 @@ use actix_web::{
http::header::ContentType, middleware, web, App, HttpRequest, HttpResponse, HttpServer,
};
use log::debug;
use rustls::{Certificate, PrivateKey, ServerConfig};
use rustls::{pki_types::PrivateKeyDer, ServerConfig};
use rustls_pemfile::{certs, pkcs8_private_keys};
/// simple handle
@ -36,32 +36,29 @@ async fn main() -> std::io::Result<()> {
.service(web::redirect("/", "/index.html"))
.service(Files::new("/static", "static"))
})
.bind_rustls_021("127.0.0.1:8443", config)?
.bind_rustls_0_23("127.0.0.1:8443", config)?
.run()
.await
}
fn load_rustls_config() -> rustls::ServerConfig {
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
// init server config builder with safe defaults
let config = ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth();
let config = ServerConfig::builder().with_no_client_auth();
// load TLS key/cert files
let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap());
let key_file = &mut BufReader::new(File::open("key.pem").unwrap());
// convert files to key/cert objects
let cert_chain = certs(cert_file)
.unwrap()
.into_iter()
.map(Certificate)
.collect();
let mut keys: Vec<PrivateKey> = pkcs8_private_keys(key_file)
.unwrap()
.into_iter()
.map(PrivateKey)
.collect();
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
let mut keys = pkcs8_private_keys(key_file)
.map(|key| key.map(PrivateKeyDer::Pkcs8))
.collect::<Result<Vec<_>, _>>()
.unwrap();
// exit if no keys could be parsed
if keys.is_empty() {