Client can authenticate using TLS certificate

This commit is contained in:
2022-08-31 14:35:52 +02:00
parent 27b52dfcb7
commit cd0f6fea94
5 changed files with 118 additions and 17 deletions

View File

@@ -3,7 +3,8 @@ use std::sync::Arc;
use futures::{SinkExt, StreamExt};
use hyper_rustls::ConfigBuilderExt;
use rustls::{Certificate, RootCertStore};
use rustls::{Certificate, PrivateKey, RootCertStore};
use rustls_pemfile::{Item, read_one};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::Message;
@@ -54,7 +55,33 @@ async fn relay_connection(ws_url: String, socket: TcpStream, conf: Arc<ClientCon
}
};
let config = config.with_no_client_auth();
let config = match conf.get_client_keypair() {
None => config.with_no_client_auth(),
Some((certs, key)) => {
let certs = rustls_pemfile::certs(&mut Cursor::new(certs))
.expect("Failed to parse client certificates!")
.into_iter()
.map(Certificate)
.collect::<Vec<_>>();
let key = match read_one(&mut Cursor::new(key))
.expect("Failed to read client private key!") {
None => {
log::error!("Failed to extract private key!");
panic!();
}
Some(Item::PKCS8Key(key)) => key,
Some(Item::RSAKey(key)) => key,
_ => {
log::error!("Unsupported private key type!");
panic!();
}
};
config.with_single_cert(certs, PrivateKey(key))
.expect("Failed to set client certificate!")
}
};
let connector = tokio_tungstenite::Connector::Rustls(Arc::new(config));
let (ws_stream, _) = tokio_tungstenite::connect_async_tls_with_config(