Remove redundant code

This commit is contained in:
Pierre HUBERT 2022-08-31 15:00:41 +02:00
parent 3cbbd72a14
commit c063cdcef6
10 changed files with 78 additions and 76 deletions

4
Cargo.lock generated
View File

@ -315,6 +315,8 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
name = "base" name = "base"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"rustls",
"rustls-pemfile",
"serde", "serde",
] ]
@ -1574,7 +1576,6 @@ dependencies = [
"log", "log",
"reqwest", "reqwest",
"rustls", "rustls",
"rustls-pemfile",
"tokio", "tokio",
"tokio-tungstenite", "tokio-tungstenite",
"urlencoding", "urlencoding",
@ -1594,7 +1595,6 @@ dependencies = [
"futures", "futures",
"log", "log",
"rustls", "rustls",
"rustls-pemfile",
"serde", "serde",
"tokio", "tokio",
"webpki", "webpki",

View File

@ -4,4 +4,6 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
serde = { version = "1.0.144", features = ["derive"] } serde = { version = "1.0.144", features = ["derive"] }
rustls-pemfile = "1.0.1"
rustls = "0.20.6"

37
base/src/cert_utils.rs Normal file
View File

@ -0,0 +1,37 @@
use std::error::Error;
use std::io::{Cursor, ErrorKind};
use rustls::{Certificate, PrivateKey};
use rustls_pemfile::{read_one, Item};
/// Parse PEM certificates bytes into a [`rustls::Certificate`] structure
pub fn parse_pem_certificates(certs: &[u8]) -> Result<Vec<Certificate>, Box<dyn Error>> {
Ok(rustls_pemfile::certs(&mut Cursor::new(certs))?
.into_iter()
.map(Certificate)
.collect())
}
/// Parse PEM private key bytes into a [`rustls::PrivateKey`] structure
pub fn parse_pem_private_key(privkey: &[u8]) -> Result<PrivateKey, Box<dyn Error>> {
let key = match read_one(&mut Cursor::new(privkey))? {
None => {
Err(std::io::Error::new(
ErrorKind::Other,
"Failed to extract private key!",
))?;
unreachable!()
}
Some(Item::PKCS8Key(key)) => key,
Some(Item::RSAKey(key)) => key,
_ => {
Err(std::io::Error::new(
ErrorKind::Other,
"Unsupported private key type!",
))?;
unreachable!();
}
};
Ok(PrivateKey(key))
}

View File

@ -1,7 +1,4 @@
#[derive(serde::Serialize, serde::Deserialize, Copy, Clone, Debug)] pub mod cert_utils;
pub struct RelayedPort { mod structs;
pub id: usize,
pub port: u16,
}
pub type RemoteConfig = Vec<RelayedPort>; pub use structs::{RelayedPort, RemoteConfig};

7
base/src/structs.rs Normal file
View File

@ -0,0 +1,7 @@
#[derive(serde::Serialize, serde::Deserialize, Copy, Clone, Debug)]
pub struct RelayedPort {
pub id: usize,
pub port: u16,
}
pub type RemoteConfig = Vec<RelayedPort>;

View File

@ -15,5 +15,4 @@ tokio-tungstenite = { version = "0.17.2", features = ["__rustls-tls", "rustls-tl
urlencoding = "2.1.0" urlencoding = "2.1.0"
rustls = { version = "0.20.6" } rustls = { version = "0.20.6" }
hyper-rustls = { version = "0.23.0", features = ["rustls-native-certs"] } hyper-rustls = { version = "0.23.0", features = ["rustls-native-certs"] }
rustls-pemfile = { version = "1.0.1" }
bytes = "1.2.1" bytes = "1.2.1"

View File

@ -1,14 +1,14 @@
use std::io::Cursor;
use std::sync::Arc; use std::sync::Arc;
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};
use hyper_rustls::ConfigBuilderExt; use hyper_rustls::ConfigBuilderExt;
use rustls::{Certificate, PrivateKey, RootCertStore}; use rustls::RootCertStore;
use rustls_pemfile::{read_one, Item};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream}; use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::Message;
use base::cert_utils;
use crate::client_config::ClientConfig; use crate::client_config::ClientConfig;
pub async fn relay_client(ws_url: String, listen_address: String, config: Arc<ClientConfig>) { pub async fn relay_client(ws_url: String, listen_address: String, config: Arc<ClientConfig>) {
@ -46,11 +46,10 @@ async fn relay_connection(ws_url: String, socket: TcpStream, conf: Arc<ClientCon
Some(cert) => { Some(cert) => {
log::debug!("Using custom root certificates"); log::debug!("Using custom root certificates");
let mut store = RootCertStore::empty(); let mut store = RootCertStore::empty();
rustls_pemfile::certs(&mut Cursor::new(cert)) cert_utils::parse_pem_certificates(&cert)
.expect("Failed to parse root certificates!") .unwrap()
.into_iter() .iter()
.map(Certificate) .for_each(|c| store.add(c).expect("Failed to add certificate to chain!"));
.for_each(|c| store.add(&c).expect("Failed to add certificate to chain!"));
config.with_root_certificates(store) config.with_root_certificates(store)
} }
@ -59,29 +58,14 @@ async fn relay_connection(ws_url: String, socket: TcpStream, conf: Arc<ClientCon
let config = match conf.get_client_keypair() { let config = match conf.get_client_keypair() {
None => config.with_no_client_auth(), None => config.with_no_client_auth(),
Some((certs, key)) => { Some((certs, key)) => {
let certs = rustls_pemfile::certs(&mut Cursor::new(certs)) let certs = cert_utils::parse_pem_certificates(certs)
.expect("Failed to parse client certificates!") .expect("Failed to parse client certificate!");
.into_iter()
.map(Certificate)
.collect::<Vec<_>>();
let key = match read_one(&mut Cursor::new(key)) let key = cert_utils::parse_pem_private_key(key)
.expect("Failed to read client private key!") .expect("Failed to parse client auth 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 config
.with_single_cert(certs, PrivateKey(key)) .with_single_cert(certs, key)
.expect("Failed to set client certificate!") .expect("Failed to set client certificate!")
} }
}; };

View File

@ -16,5 +16,4 @@ serde = { version = "1.0.144", features = ["derive"] }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
futures = "0.3.24" futures = "0.3.24"
rustls = "0.20.6" rustls = "0.20.6"
rustls-pemfile = "1.0.1"
webpki = "0.22.0" webpki = "0.22.0"

View File

@ -1,14 +1,10 @@
use std::fs::File;
use std::io::BufReader;
use std::sync::Arc; use std::sync::Arc;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use clap::Parser; use clap::Parser;
use rustls::{Certificate, PrivateKey};
use rustls_pemfile::{certs, read_one, Item};
use base::RelayedPort; use base::{cert_utils, RelayedPort};
use tcp_relay_server::relay_ws::relay_ws; use tcp_relay_server::relay_ws::relay_ws;
use tcp_relay_server::server_config::ServerConfig; use tcp_relay_server::server_config::ServerConfig;
use tcp_relay_server::tls_cert_client_verifier::CustomCertClientVerifier; use tcp_relay_server::tls_cert_client_verifier::CustomCertClientVerifier;
@ -80,29 +76,16 @@ async fn main() -> std::io::Result<()> {
// Load TLS configuration, if any // Load TLS configuration, if any
let tls_config = if let (Some(cert), Some(key)) = (&args.tls_cert, &args.tls_key) { let tls_config = if let (Some(cert), Some(key)) = (&args.tls_cert, &args.tls_key) {
// Load TLS certificate & private key // Load TLS certificate & private key
let cert_file = &mut BufReader::new(File::open(cert).unwrap()); let cert_file = std::fs::read(cert).expect("Failed to read certificate file");
let key_file = &mut BufReader::new(File::open(key).unwrap()); let key_file = std::fs::read(key).expect("Failed to read server private key");
// Get certificates chain // Get certificates chain
let cert_chain = certs(cert_file) let cert_chain =
.unwrap() cert_utils::parse_pem_certificates(&cert_file).expect("Failed to extract certificates");
.into_iter()
.map(Certificate)
.collect();
// Get private key // Get private key
let key = match read_one(key_file).expect("Failed to read private key!") { let key =
None => { cert_utils::parse_pem_private_key(&key_file).expect("Failed to extract private key!");
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!();
}
};
let config = rustls::ServerConfig::builder().with_safe_defaults(); let config = rustls::ServerConfig::builder().with_safe_defaults();
@ -113,7 +96,7 @@ async fn main() -> std::io::Result<()> {
}; };
let config = config let config = config
.with_single_cert(cert_chain, PrivateKey(key)) .with_single_cert(cert_chain, key)
.expect("Failed to load TLS certificate!"); .expect("Failed to load TLS certificate!");
Some(config) Some(config)

View File

@ -1,11 +1,10 @@
use std::fs::File;
use std::io::BufReader;
use std::sync::Arc; use std::sync::Arc;
use std::time::SystemTime; use std::time::SystemTime;
use rustls::server::{AllowAnyAuthenticatedClient, ClientCertVerified, ClientCertVerifier}; use rustls::server::{AllowAnyAuthenticatedClient, ClientCertVerified, ClientCertVerifier};
use rustls::{Certificate, DistinguishedNames, Error, RootCertStore}; use rustls::{Certificate, DistinguishedNames, Error, RootCertStore};
use rustls_pemfile::certs;
use base::cert_utils::parse_pem_certificates;
use crate::server_config::ServerConfig; use crate::server_config::ServerConfig;
@ -19,16 +18,11 @@ impl CustomCertClientVerifier {
.tls_client_auth_root_cert .tls_client_auth_root_cert
.as_deref() .as_deref()
.expect("No root certificates for client authentication provided!"); .expect("No root certificates for client authentication provided!");
let cert_file = &mut BufReader::new( let cert_file = std::fs::read(cert_path)
File::open(cert_path) .expect("Failed to read root certificates for client authentication!");
.expect("Failed to read root certificates for client authentication!"),
);
let root_certs = certs(cert_file) let root_certs = parse_pem_certificates(&cert_file)
.unwrap() .expect("Failed to read root certificates for server authentication!");
.into_iter()
.map(Certificate)
.collect::<Vec<_>>();
if root_certs.is_empty() { if root_certs.is_empty() {
log::error!("No certificates found for client authentication!"); log::error!("No certificates found for client authentication!");