1
0
mirror of https://github.com/actix/examples synced 2024-11-28 08:22:39 +01:00
examples/security/rustls-client-cert/src/main.rs

120 lines
3.7 KiB
Rust
Raw Normal View History

2020-10-30 05:22:24 +01:00
//! This example shows how to use `actix_web::HttpServer::on_connect` to access client certificates
//! pass them to a handler through request-local data.
use std::{any::Any, env, fs::File, io::BufReader, net::SocketAddr};
2022-01-29 17:51:49 +01:00
use actix_tls::accept::rustls::reexports::ServerConfig;
use actix_tls::accept::rustls::TlsStream;
2020-10-30 05:22:24 +01:00
use actix_web::{
dev::Extensions, rt::net::TcpStream, web, App, HttpResponse, HttpServer, Responder,
};
use log::info;
use rustls::{
2022-01-29 17:51:49 +01:00
server::AllowAnyAnonymousOrAuthenticatedClient, Certificate, PrivateKey,
RootCertStore,
2020-10-30 05:22:24 +01:00
};
2022-01-29 17:51:49 +01:00
use rustls_pemfile::{certs, pkcs8_private_keys};
2020-10-30 05:22:24 +01:00
const CA_CERT: &str = "certs/rootCA.pem";
const SERVER_CERT: &str = "certs/server-cert.pem";
const SERVER_KEY: &str = "certs/server-key.pem";
#[derive(Debug, Clone)]
struct ConnectionInfo {
bind: SocketAddr,
peer: SocketAddr,
ttl: Option<u32>,
}
async fn route_whoami(
conn_info: web::ReqData<ConnectionInfo>,
client_cert: Option<web::ReqData<Certificate>>,
) -> impl Responder {
if let Some(cert) = client_cert {
HttpResponse::Ok().body(format!("{:?}\n\n{:?}", &conn_info, &cert))
} else {
HttpResponse::Unauthorized().body("No client certificate provided.")
}
}
fn get_client_cert(connection: &dyn Any, data: &mut Extensions) {
if let Some(tls_socket) = connection.downcast_ref::<TlsStream<TcpStream>>() {
info!("TLS on_connect");
let (socket, tls_session) = tls_socket.get_ref();
data.insert(ConnectionInfo {
bind: socket.local_addr().unwrap(),
peer: socket.peer_addr().unwrap(),
ttl: socket.ttl().ok(),
});
2022-01-29 17:51:49 +01:00
if let Some(certs) = tls_session.peer_certificates() {
2020-10-30 05:22:24 +01:00
info!("client certificate found");
// insert a `rustls::Certificate` into request data
2022-01-29 17:51:49 +01:00
data.insert(certs.last().unwrap().clone());
2020-10-30 05:22:24 +01:00
}
} else if let Some(socket) = connection.downcast_ref::<TcpStream>() {
info!("plaintext on_connect");
data.insert(ConnectionInfo {
bind: socket.local_addr().unwrap(),
peer: socket.peer_addr().unwrap(),
ttl: socket.ttl().ok(),
});
} else {
unreachable!("socket should be TLS or plaintext");
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "info");
}
env_logger::init();
let mut cert_store = RootCertStore::empty();
// import CA cert
let ca_cert = &mut BufReader::new(File::open(CA_CERT)?);
2022-01-29 17:51:49 +01:00
let ca_cert = Certificate(certs(ca_cert).unwrap()[0].clone());
2020-10-30 05:22:24 +01:00
cert_store
2022-01-29 17:51:49 +01:00
.add(&ca_cert)
2020-10-30 05:22:24 +01:00
.expect("root CA not added to store");
// set up client authentication requirements
let client_auth = AllowAnyAnonymousOrAuthenticatedClient::new(cert_store);
2022-01-29 17:51:49 +01:00
let config = ServerConfig::builder()
.with_safe_defaults()
.with_client_cert_verifier(client_auth);
2020-10-30 05:22:24 +01:00
// 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)?);
2022-01-29 17:51:49 +01:00
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 config = config.with_single_cert(cert_chain, keys.remove(0)).unwrap();
2020-10-30 05:22:24 +01:00
// start server
HttpServer::new(|| App::new().default_service(web::to(route_whoami)))
.on_connect(get_client_cert)
.bind(("localhost", 8080))?
.bind_rustls(("localhost", 8443), config)?
.workers(1)
.run()
.await
}