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

@ -1,6 +1,6 @@
[package]
name = "sslrelay"
version = "0.5.0"
version = "0.6.0"
authors = ["PinkP4nther <pinkp4nther@protonmail.com> @Pink_P4nther"]
edition = "2018"
description = "A TCP relay library for relaying/modifying/spoofing TCP traffic by implementing callback code."
@ -11,6 +11,3 @@ license = "Apache-2.0"
[dependencies.openssl]
version = "0.10.36"
[dependencies.toml]
version = "0.5.8"

View file

@ -30,3 +30,5 @@ A TCP relay library that can handle raw TCP and SSL/TLS connections. You can rea
> 10/07/2021 | **v0.4.3** | Blocking callbacks now pass self as a mutable reference. This can allow the developer to create structures that can be accessed every stream write. (ONLY in the BLOCKING callback). The self object is refreshed per TCP connection. Separate TCP connections can not touch eachothers data.
>
> 10/08/2021 | **v0.4.4** | Added ability to set TLS certificate and certificate private key to nothing. When passing RelayConfig to the relay object use the 'None' variant of Option<T> enum. In a config file put the cert path and key path as an empty 'String' to specify 'None'.
>
> 10/09/2021 | **v0.6.0** | Gone away with 'ConfigType<T>'! No more specifying config files unless the developer implements it themself. A new config enum 'TLSConfig' has been introduced. This has 3 variants FILE(Specify the cert and pk file paths), DATA(Pass the cert(PEM) data and the pk(PEM) data as bytes), NONE(This is when you are not using TLS on the listening/downstream side of the relay).

View file

@ -1,4 +1,4 @@
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.
@ -38,17 +38,20 @@ fn main() {
// 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();
}

View file

@ -1,8 +0,0 @@
bind_host = "0.0.0.0"
bind_port = "443"
ssl_private_key_path = "./remote.com.key"
ssl_cert_path = "./remote.com.crt"
remote_host = "remote.com"
remote_port = "443"
downstream_data_type = "tls"
upstream_data_type = "tls"

View file

@ -1,4 +1,4 @@
use sslrelay::{self, ConfigType, HandlerCallbacks, CallbackRet};
use sslrelay::{self, TLSConfig, TCPDataType, RelayConfig, HandlerCallbacks, CallbackRet};
// Handler object
#[derive(Clone)] // Must have Clone trait implemented.
@ -38,7 +38,21 @@ impl HandlerCallbacks for Handler {
fn main() {
// Create new SSLRelay object
let mut relay = sslrelay::SSLRelay::new(Handler, ConfigType::Default);
let mut relay = sslrelay::SSLRelay::new(
Handler,
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(),
tls_config: TLSConfig::FILE{
certificate_path: "./tls.crt".to_string(),
private_key_path: "./tls.key".to_string(),
},
}
);
// Start listening
relay.start();

View file

@ -1,8 +0,0 @@
bind_host = "0.0.0.0"
bind_port = "443"
ssl_private_key_path = "./ssl.key"
ssl_cert_path = "./ssl.crt"
remote_host = "remote.com"
remote_port = "443"
downstream_data_type = "tls"
upstream_data_type = "tls"

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::{
use openssl::{
x509::X509,
pkey::PKey,
ssl::{
SslVerifyMode,
SslConnector,
SslAcceptor,
SslStream,
SslFiletype,
SslMethod
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!");
match tls_config {
TLSConfig::FILE{certificate_path, private_key_path} => {
if !Path::new(&private_key).exists() {
panic!("[-] [{}] does not exist!", private_key);
if !Path::new(&private_key_path).exists() {
panic!("[-] [{}] does not exist!", private_key_path);
}
acceptor.set_private_key_file(private_key, SslFiletype::PEM).unwrap();
if !Path::new(&certificate).exists() {
panic!("[-] [{}] does not exist!", certificate);
if !Path::new(&certificate_path).exists() {
panic!("[-] [{}] does not exist!", certificate_path);
}
acceptor.set_certificate_chain_file(certificate).unwrap();
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.");
}
}
Arc::new(acceptor.build())
}
}// SSLRelay