New configuration method. Version 0.6.0. Examples updated to new configuration method. Configuration files removed.

This commit is contained in:
PinkP4nther 2021-10-09 22:05:03 -07:00
commit 61217ed351
8 changed files with 91 additions and 160 deletions

View file

@ -23,7 +23,7 @@
//! ```
//! ## Example (basic.rs)
//! ```
//! use sslrelay::{self, ConfigType, RelayConfig, HandlerCallbacks, CallbackRet, TCPDataType};
//! use sslrelay::{self, RelayConfig, HandlerCallbacks, CallbackRet, TCPDataType, TLSConfig};
//!
//! // Handler object
//! #[derive(Clone)] // Must have Clone trait implemented.
@ -63,29 +63,36 @@
//! // Create new SSLRelay object
//! let mut relay = sslrelay::SSLRelay::new(
//! Handler,
//! ConfigType::Conf(RelayConfig {
//! RelayConfig {
//! downstream_data_type: TCPDataType::TLS,
//! upstream_data_type: TCPDataType::TLS,
//! bind_host: "0.0.0.0".to_string(),
//! bind_port: "443".to_string(),
//! remote_host: "remote.com".to_string(),
//! remote_port: "443".to_string(),
//! ssl_private_key_path: Some("./remote.com.key".to_string()),
//! ssl_cert_path: Some("./remote.com.crt".to_string()),
//! })
//! tls_config: TLSConfig::FILE{
//! certificate_path: "./tls.crt".to_string(),
//! private_key_path: "./tls.key".to_string(),
//! },
//! }
//! );
//!
//! // Start listening
//! relay.start();
//! }
//! ```
use openssl::ssl::{
SslVerifyMode,
SslConnector,
SslAcceptor,
SslStream,
SslFiletype,
SslMethod
use openssl::{
x509::X509,
pkey::PKey,
ssl::{
SslVerifyMode,
SslConnector,
SslAcceptor,
SslStream,
SslFiletype,
SslMethod,
}
};
use std::net::{
@ -104,8 +111,6 @@ use std::{
};
use std::{
env,
fs,
path::Path,
time::Duration,
};
@ -122,8 +127,6 @@ use std::sync::mpsc::{
Sender
};
use toml::Value as TValue;
mod data;
mod tcp;
mod relay;
@ -154,16 +157,15 @@ pub enum TCPDataType {
RAW,
}
/// The relay configuration type.
/// Env: Uses the SSLRELAY_CONFIG environmental variable for the path to the config file.
/// Path: Specifies the path to the config file.
/// Conf: For passing an instance of the object instead of using a config file.
/// Default: Uses ./relay_config.toml config file.
pub enum ConfigType<T> {
Env,
Path(T),
Conf(RelayConfig),
Default,
/// TLSConfig is used to specify TLS options.
/// FILE is for specifying a path to a certificate and private key.
/// DATA is for passing the certificate and private key bytes directly.
/// NONE is for when you are not using TLS on the listening/downstream side of the relay.
#[derive(Clone)]
pub enum TLSConfig {
FILE {certificate_path: String, private_key_path: String},
DATA {certificate: Vec<u8>, private_key: Vec<u8>},
NONE,
}
/// Relay Config structure for passing into the SSLRelay::new() config parameter.
@ -175,8 +177,7 @@ pub struct RelayConfig {
pub bind_port: String,
pub remote_host: String,
pub remote_port: String,
pub ssl_private_key_path: Option<String>,
pub ssl_cert_path: Option<String>,
pub tls_config: TLSConfig,
}
/// CallbackRet for blocking callback functions

View file

@ -5,28 +5,27 @@ use crate::{
HandlerCallbacks,
InnerHandlers,
TCPDataType,
ConfigType,
TcpListener,
thread,
FullDuplexTcp,
DataStreamType,
RelayConfig,
env,
TValue,
fs,
Arc,
SslAcceptor,
Path,
SslMethod,
SslFiletype,
TLSConfig,
PKey,
X509,
};
impl<H: HandlerCallbacks + std::marker::Sync + std::marker::Send + Clone + 'static> SSLRelay<H> {
/// Creates new SSLRelay instance.
pub fn new(handlers: H, config: ConfigType<String>) -> Self {
pub fn new(handlers: H, config: RelayConfig) -> Self {
SSLRelay {
config: Self::load_relay_config(config),
config,
handlers: Some(InnerHandlers{cb: handlers}),
}
}
@ -35,13 +34,15 @@ impl<H: HandlerCallbacks + std::marker::Sync + std::marker::Send + Clone + 'stat
let rhost = self.config.remote_host.clone();
let rport = self.config.remote_port.clone();
let listener = TcpListener::bind(format!("{}:{}", self.config.bind_host.clone(), self.config.bind_port.clone())).unwrap();
let upstream_data_stream_type = self.config.upstream_data_type;
let listener = TcpListener::bind(format!("{}:{}", self.config.bind_host.clone(), self.config.bind_port.clone())).unwrap();
match self.config.downstream_data_type {
TCPDataType::TLS => {
let acceptor = self.setup_ssl_config(self.config.ssl_private_key_path.clone(), self.config.ssl_cert_path.clone());
let acceptor = self.setup_ssl_config(self.config.tls_config.clone());
for stream in listener.incoming() {
@ -61,7 +62,7 @@ impl<H: HandlerCallbacks + std::marker::Sync + std::marker::Send + Clone + 'stat
// FULL DUPLEX OBJECT CREATION HERE
match FullDuplexTcp::new(DataStreamType::TLS(stream), upstream_data_stream_type, r_host, r_port, handler_clone) {
Ok(mut fdtcp) => fdtcp.handle(),
Err(_ec) => {}
Err(_ec) => {println!("[SSLRelay Error] Failed to handle TCP(TLS) connection: {}", _ec)}
}
},
Err(e) => {
@ -93,9 +94,8 @@ impl<H: HandlerCallbacks + std::marker::Sync + std::marker::Send + Clone + 'stat
// FULL DUPLEX OBJECT CREATION HERE
match FullDuplexTcp::new(DataStreamType::RAW(stream), upstream_data_stream_type, r_host, r_port, handler_clone) {
Ok(mut fdtcp) => fdtcp.handle(),
Err(_ec) => {},
Err(_ec) => println!("[SSLRelay Error] Failed to handle TCP connection: {}", _ec),
}
});
},
Err(e) => {println!("[Error] Tcp Connection Failed: {}", e)}
@ -105,103 +105,33 @@ impl<H: HandlerCallbacks + std::marker::Sync + std::marker::Send + Clone + 'stat
}
}
fn load_relay_config(config: ConfigType<String>) -> RelayConfig {
let mut resolved_path = String::from("./relay_config.toml");
match config {
ConfigType::Path(path) => {
resolved_path = path.clone();
},
ConfigType::Env => {
resolved_path = match env::var("SSLRELAY_CONFIG") {
Ok(p) => p.clone(),
Err(_e) => {
println!("[-] Environmental variable SSLRELAY_CONFIG does not exist.");
std::process::exit(-1);
}
};
},
ConfigType::Conf(conf) => {
return conf;
}
ConfigType::Default => {}
}
let bytes = fs::read(resolved_path).unwrap();
let config_file = String::from_utf8_lossy(&bytes);
let config_parsed = config_file.parse::<TValue>().unwrap();
let bind_host = config_parsed["bind_host"].to_string().replace("\"", "");
let bind_port = config_parsed["bind_port"].to_string().replace("\"", "");
let ssl_private_key_path = config_parsed["ssl_private_key_path"].to_string().replace("\"", "");
let ssl_cert_path = config_parsed["ssl_cert_path"].to_string().replace("\"", "");
let remote_host = config_parsed["remote_host"].to_string().replace("\"", "");
let remote_port = config_parsed["remote_port"].to_string().replace("\"", "");
let upstream_tls_conf = config_parsed["upstream_data_type"].to_string().replace("\"", "").to_lowercase();
let downstream_tls_conf = config_parsed["downstream_data_type"].to_string().replace("\"", "").to_lowercase();
let upstream_data_type: TCPDataType;
let downstream_data_type: TCPDataType;
if upstream_tls_conf == "tls" {
upstream_data_type = TCPDataType::TLS;
} else if upstream_tls_conf == "raw" {
upstream_data_type = TCPDataType::RAW;
} else {
panic!("[SSLRelay Error] Unrecognized TCPDataType for upstream_data_type. Data type received was not 'tcp' or 'tls'!");
// Create error handling for load_relay_config()
}
if downstream_tls_conf == "tls" {
downstream_data_type = TCPDataType::TLS;
} else if downstream_tls_conf == "raw" {
downstream_data_type = TCPDataType::RAW;
} else {
panic!("[SSLRelay Error] Unrecognized TCPDataType for downstream_data_type. Data type received was not 'tcp' or 'tls'!");
// Create error handling for load_relay_config()
}
let mut ssl_pk_path = None;
let mut ssl_c_path = None;
if !ssl_private_key_path.is_empty() {
ssl_pk_path = Some(ssl_private_key_path.clone());
}
if !ssl_cert_path.is_empty() {
ssl_c_path = Some(ssl_cert_path.clone());
}
RelayConfig {
upstream_data_type,
downstream_data_type,
bind_host: bind_host.clone(),
bind_port: bind_port.clone(),
ssl_private_key_path: ssl_pk_path,
ssl_cert_path: ssl_c_path,
remote_host: remote_host.clone(),
remote_port: remote_port.clone(),
}
}
fn setup_ssl_config(&self, priv_key: Option<String>, cert: Option<String>) -> Arc<SslAcceptor> {
fn setup_ssl_config(&self, tls_config: TLSConfig) -> Arc<SslAcceptor> {
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
let private_key = priv_key.expect("[SSLRelay Error] No private key file specified!");
let certificate = cert.expect("[SSLRelay Error] No certificate file specified!");
if !Path::new(&private_key).exists() {
panic!("[-] [{}] does not exist!", private_key);
}
acceptor.set_private_key_file(private_key, SslFiletype::PEM).unwrap();
match tls_config {
TLSConfig::FILE{certificate_path, private_key_path} => {
if !Path::new(&certificate).exists() {
panic!("[-] [{}] does not exist!", certificate);
if !Path::new(&private_key_path).exists() {
panic!("[-] [{}] does not exist!", private_key_path);
}
if !Path::new(&certificate_path).exists() {
panic!("[-] [{}] does not exist!", certificate_path);
}
acceptor.set_private_key_file(private_key_path, SslFiletype::PEM).unwrap();
acceptor.set_certificate_chain_file(certificate_path).unwrap();
acceptor.check_private_key().unwrap();
},
TLSConfig::DATA{certificate, private_key} => {
let x_509_certificate = X509::from_pem(certificate.as_slice()).unwrap();
let private_key = PKey::private_key_from_pem(private_key.as_slice()).unwrap();
acceptor.set_certificate(x_509_certificate.as_ref()).unwrap();
acceptor.set_private_key(private_key.as_ref()).unwrap();
},
TLSConfig::NONE => {
panic!("[SSLRelay Error] Specified NONE for TLSConfig and downstream_data_type as TLS.");
}
}
acceptor.set_certificate_chain_file(certificate).unwrap();
acceptor.check_private_key().unwrap();
Arc::new(acceptor.build())
}
}// SSLRelay