Optimize root certificate management on client side

This commit is contained in:
2022-08-31 11:21:23 +02:00
parent 723ed5e390
commit 1b95b10553
8 changed files with 64 additions and 44 deletions

View File

@ -0,0 +1,40 @@
use clap::Parser;
static mut ROOT_CERT: Option<Vec<u8>> = None;
/// TCP relay client
#[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)]
pub struct ClientConfig {
/// Access token
#[clap(short, long)]
pub token: String,
/// Relay server
#[clap(short, long, default_value = "http://127.0.0.1:8000")]
pub relay_url: String,
/// Listen address
#[clap(short, long, default_value = "127.0.0.1")]
pub listen_address: String,
/// Optional root certificate to use for server authentication
#[clap(short = 'c', long)]
pub root_certificate: Option<String>,
}
impl ClientConfig {
/// Load root certificate
pub fn get_root_certificate(&self) -> Option<Vec<u8>> {
self.root_certificate.as_ref()?;
if unsafe { ROOT_CERT.is_none() } {
log::info!("Loading root certificate from disk");
let cert = self.root_certificate.as_ref().map(|c| std::fs::read(c)
.expect("Failed to read root certificate!"));
unsafe { ROOT_CERT = cert }
}
unsafe { ROOT_CERT.clone() }
}
}

View File

@ -1 +1,2 @@
pub mod client_config;
pub mod relay_client;

View File

@ -6,38 +6,18 @@ use futures::future::join_all;
use reqwest::Certificate;
use base::RemoteConfig;
use tcp_relay_client::client_config::ClientConfig;
use tcp_relay_client::relay_client::relay_client;
/// TCP relay client
#[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)]
pub struct Args {
/// Access token
#[clap(short, long)]
pub token: String,
/// Relay server
#[clap(short, long, default_value = "http://127.0.0.1:8000")]
pub relay_url: String,
/// Listen address
#[clap(short, long, default_value = "127.0.0.1")]
pub listen_address: String,
/// Optional root certificate to use for server authentication
#[clap(short = 'c', long)]
pub root_certificate: Option<String>,
}
async fn get_server_config(config: &Args, root_cert: &Option<Vec<u8>>) -> Result<RemoteConfig, Box<dyn Error>> {
async fn get_server_config(config: &ClientConfig) -> Result<RemoteConfig, Box<dyn Error>> {
let url = format!("{}/config", config.relay_url);
log::info!("Retrieving configuration on {}", url);
let mut client = reqwest::Client::builder();
// Specify root certificate, if any was specified in the command line
if let Some(cert) = root_cert {
client = client.add_root_certificate(Certificate::from_pem(cert)?);
if let Some(cert) = config.get_root_certificate() {
client = client.add_root_certificate(Certificate::from_pem(&cert)?);
}
let client = client.build().expect("Failed to build reqwest client");
@ -55,17 +35,14 @@ async fn get_server_config(config: &Args, root_cert: &Option<Vec<u8>>) -> Result
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Box<dyn Error>> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let args: Args = Args::parse();
let args: ClientConfig = ClientConfig::parse();
let args = Arc::new(args);
let root_cert = args.root_certificate.as_ref().map(|c| std::fs::read(c)
.expect("Failed to read root certificate!"));
// Get server relay configuration (fetch the list of port to forward)
let conf = get_server_config(&args, &root_cert).await?;
let conf = get_server_config(&args).await?;
// Start to listen port
let mut handles = vec![];
@ -77,7 +54,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
args.relay_url, port.id, urlencoding::encode(&args.token))
.replace("http", "ws"),
listen_address,
root_cert.clone(),
args.clone(),
));
handles.push(h);
}

View File

@ -8,7 +8,9 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::Message;
pub async fn relay_client(ws_url: String, listen_address: String, root_cert: Option<Vec<u8>>) {
use crate::client_config::ClientConfig;
pub async fn relay_client(ws_url: String, listen_address: String, config: Arc<ClientConfig>) {
log::info!("Start to listen on {}", listen_address);
let listener = match TcpListener::bind(&listen_address).await {
Ok(l) => l,
@ -22,7 +24,7 @@ pub async fn relay_client(ws_url: String, listen_address: String, root_cert: Opt
let (socket, _) = listener.accept().await
.expect("Failed to accept new connection!");
tokio::spawn(relay_connection(ws_url.clone(), socket, root_cert.clone()));
tokio::spawn(relay_connection(ws_url.clone(), socket, config.clone()));
}
}
@ -30,14 +32,14 @@ pub async fn relay_client(ws_url: String, listen_address: String, root_cert: Opt
///
/// WS read => TCP write
/// TCP read => WS write
async fn relay_connection(ws_url: String, socket: TcpStream, root_cert: Option<Vec<u8>>) {
async fn relay_connection(ws_url: String, socket: TcpStream, conf: Arc<ClientConfig>) {
log::debug!("Connecting to {}...", ws_url);
let ws_stream = if ws_url.starts_with("wss") {
let config = rustls::ClientConfig::builder()
.with_safe_defaults();
let config = match root_cert {
let config = match conf.get_root_certificate() {
None => config.with_native_roots(),
Some(cert) => {
log::debug!("Using custom root certificates");