Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/3 replay against different server #18

Merged
merged 8 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions config/config.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
address = "127.0.0.1:8080"
config_dir = "/etc/ruroco/"
ip = "<ip-address>" # public IP address of your server where this service runs on
address = "127.0.0.1:8080" # address where this service runs on
config_dir = "/etc/ruroco/" # directory where pem files are
socket_user = "ruroco" # user of socket, facilitating communication between server and commander
socket_group = "ruroco" # user group of socket, facilitating communication between server and commander

[commands]
[commands] # commands which are possible to execute
31 changes: 25 additions & 6 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

use std::fmt::{Debug, Display};
use std::fs;
use std::net::UdpSocket;
use std::net::{SocketAddr, UdpSocket};
use std::path::PathBuf;

use openssl::pkey::Private;
use openssl::rsa::Rsa;
use openssl::version::version;

use std::net::ToSocketAddrs;

use crate::common::{info, PADDING_SIZE, RSA_PADDING};
use crate::data::ServerData;

Expand All @@ -25,16 +27,28 @@ pub fn send(
command: String,
deadline: u16,
strict: bool,
ip: Option<String>,
source_ip: Option<String>,
now: u128,
) -> Result<(), String> {
info(format!(
"Connecting to udp://{address}, loading PEM from {pem_path:?}, using {} ...",
version()
));

let destination_ips = address
.to_socket_addrs()
.map_err(|err| format!("Could not resolve hostname for {address}: {err}"))?
.filter(|a| a.is_ipv4())
.collect::<Vec<SocketAddr>>();

let destination_ip = match destination_ips.first() {
Some(a) => a.ip().to_string(),
None => return Err(format!("Could not find any IPv4 address for {address}")),
};

let rsa = get_rsa_private(&pem_path)?;
let data_to_encrypt = get_data_to_encrypt(&command, &rsa, deadline, strict, ip, now)?;
let data_to_encrypt =
get_data_to_encrypt(&command, &rsa, deadline, strict, source_ip, destination_ip, now)?;
let encrypted_data = encrypt_data(&data_to_encrypt, &rsa)?;

// create UDP socket and send the encrypted data to the specified address
Expand Down Expand Up @@ -95,10 +109,13 @@ fn get_data_to_encrypt(
rsa: &Rsa<Private>,
deadline: u16,
strict: bool,
ip: Option<String>,
source_ip: Option<String>,
destination_ip: String,
now_ns: u128,
) -> Result<Vec<u8>, String> {
let data_to_encrypt = ServerData::create(command, deadline, strict, ip, now_ns).serialize()?;
let data_to_encrypt =
ServerData::create(command, deadline, strict, source_ip, destination_ip, now_ns)
.serialize()?;
let data_to_encrypt_len = data_to_encrypt.len();
let rsa_size = rsa.size() as usize;
if data_to_encrypt_len + PADDING_SIZE > rsa_size {
Expand Down Expand Up @@ -147,20 +164,22 @@ mod tests {
5,
false,
Some(String::from("192.168.178.123")),
String::from("192.168.178.124"),
1725821510 * 1_000_000_000,
)
.serialize()
.unwrap();
let server_data_str = String::from_utf8_lossy(&server_data).to_string();

assert_eq!(server_data_str, "c=\"some_kind_of_long_but_not_really_that_long_command\"\nd=\"1725821515000000000\"\ns=0\ni=\"192.168.178.123\"");
assert_eq!(server_data_str, "c=\"some_kind_of_long_but_not_really_that_long_command\"\nd=\"1725821515000000000\"\ns=0\ni=\"192.168.178.123\"\nh=\"192.168.178.124\"");
assert_eq!(
ServerData::deserialize(&server_data).unwrap(),
ServerData {
c: String::from("some_kind_of_long_but_not_really_that_long_command"),
d: 1725821515000000000,
s: 0,
i: Some(String::from("192.168.178.123")),
h: String::from("192.168.178.124")
}
);
}
Expand Down
5 changes: 4 additions & 1 deletion src/config_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub struct CliServer {
#[derive(Debug, Deserialize, PartialEq)]
pub struct ConfigServer {
pub commands: HashMap<String, String>,
pub ip: String,
#[serde(default = "default_address")]
pub address: String,
#[serde(default = "default_config_path")]
Expand All @@ -39,6 +40,7 @@ impl Default for ConfigServer {
fn default() -> ConfigServer {
ConfigServer {
commands: HashMap::new(),
ip: String::from("127.0.0.1"),
address: String::from(""),
socket_user: String::from(""),
socket_group: String::from(""),
Expand Down Expand Up @@ -74,9 +76,10 @@ mod tests {
#[test]
fn test_create_deserialize() {
assert_eq!(
ConfigServer::deserialize("[commands]").unwrap(),
ConfigServer::deserialize("ip = \"127.0.0.1\"\n[commands]").unwrap(),
ConfigServer {
commands: HashMap::new(),
ip: String::from("127.0.0.1"),
address: default_address(),
config_dir: default_config_path(),
socket_user: default_socket_user(),
Expand Down
17 changes: 12 additions & 5 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,26 @@ pub struct ServerData {
pub c: String, // command name
#[serde(serialize_with = "serialize", deserialize_with = "deserialize")]
pub d: u128, // deadline in ns
pub s: u8, // strict - 0 == false, 1 == true
pub i: Option<String>, // ip address
pub s: u8, // strict -> 0 == false, 1 == true
pub i: Option<String>, // source ip address
pub h: String, // host ip address
}

impl ServerData {
pub fn create(
command: &str,
deadline: u16,
strict: bool,
ip: Option<String>,
source_ip: Option<String>,
destination_ip: String,
now_ns: u128,
) -> ServerData {
ServerData {
c: command.to_string(),
d: now_ns + (u128::from(deadline) * 1_000_000_000),
s: if strict { 1 } else { 0 },
i: ip,
i: source_ip,
h: destination_ip,
}
}

Expand All @@ -61,10 +64,14 @@ impl ServerData {
self.s == 1
}

pub fn ip(&self) -> Option<String> {
pub fn source_ip(&self) -> Option<String> {
self.i.clone()
}

pub fn destination_ip(&self) -> String {
self.h.clone()
}

pub fn deadline(&self) -> u128 {
self.d
}
Expand Down
76 changes: 51 additions & 25 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use openssl::rsa::Rsa;
use openssl::version::version;
use std::fs::ReadDir;
use std::io::Write;
use std::net::{SocketAddr, UdpSocket};
use std::net::{IpAddr, SocketAddr, UdpSocket};
use std::os::fd::{FromRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
Expand All @@ -20,6 +20,7 @@ pub struct Server {
rsa: Rsa<Public>,
socket: UdpSocket,
address: String,
ip: String,
encrypted_data: Vec<u8>,
decrypted_data: Vec<u8>,
socket_path: PathBuf,
Expand Down Expand Up @@ -50,6 +51,17 @@ impl Server {
let address = config.address;
let config_dir = resolve_path(&config.config_dir);

let ip_addr = config.ip.parse::<IpAddr>().map_err(|e| {
format!("Could not parse configured host IP address {}: {e}", config.ip)
})?;

if !ip_addr.is_ipv4() {
return Err(format!(
"Only IPv4 Addresses are currently supported, got IP config {}",
ip_addr
));
}

let pem_path = Self::get_pem_path(&config_dir)?;
info(format!(
"Creating server, loading public PEM from {pem_path:?}, using {} ...",
Expand All @@ -61,42 +73,47 @@ impl Server {
let rsa = Rsa::public_key_from_pem(&pem_data)
.map_err(|e| format!("Could not load public key from {pem_path:?}: {e}"))?;

let socket = Self::create_udp_socket(&address)?;

let rsa_size = rsa.size() as usize;
let decrypted_data = vec![0; rsa_size];
let encrypted_data = vec![0; rsa_size];

Ok(Server {
rsa,
address,
ip: ip_addr.to_string(),
socket,
decrypted_data,
encrypted_data,
socket_path: get_socket_path(&config_dir),
blocklist: Blocklist::create(&config_dir),
})
}

fn create_udp_socket(address: &str) -> Result<UdpSocket, String> {
let pid = std::process::id().to_string();
let socket = match env::var("LISTEN_PID") {
match env::var("LISTEN_PID") {
Ok(listen_pid) if listen_pid == pid => {
info(String::from(
"env var LISTEN_PID was set to our PID, creating socket from raw fd ...",
));
let fd: RawFd = 3;
unsafe { UdpSocket::from_raw_fd(fd) }
Ok(unsafe { UdpSocket::from_raw_fd(fd) })
}
Ok(_) => {
info(format!(
"env var LISTEN_PID was set, but not to our PID, binding to {address}"
));
UdpSocket::bind(&address)
.map_err(|e| format!("Could not UdpSocket bind {address:?}: {e}"))?
UdpSocket::bind(address)
.map_err(|e| format!("Could not UdpSocket bind {address:?}: {e}"))
}
Err(_) => {
info(format!("env var LISTEN_PID was not set, binding to {address}"));
UdpSocket::bind(&address)
.map_err(|e| format!("Could not UdpSocket bind {address:?}: {e}"))?
UdpSocket::bind(address)
.map_err(|e| format!("Could not UdpSocket bind {address:?}: {e}"))
}
};

let rsa_size = rsa.size() as usize;
let decrypted_data = vec![0; rsa_size];
let encrypted_data = vec![0; rsa_size];

Ok(Server {
rsa,
address,
socket,
decrypted_data,
encrypted_data,
socket_path: get_socket_path(&config_dir),
blocklist: Blocklist::create(&config_dir),
})
}
}

fn get_pem_path(config_dir: &PathBuf) -> Result<PathBuf, String> {
Expand Down Expand Up @@ -180,17 +197,26 @@ impl Server {
Ok((now_ns, data)) if now_ns > data.deadline() => {
error(format!("Invalid deadline - now {now_ns} is after {}", data.deadline()))
}
Ok((_, data)) if self.ip != data.destination_ip() => error(format!(
"Invalid host IP - expected {}, actual {}",
self.ip,
data.destination_ip()
)),
Ok((_, data)) if self.blocklist.is_blocked(data.deadline()) => {
error(format!("Invalid deadline - {} is on blocklist", data.deadline()))
}
Ok((_, data))
if data.is_strict() && data.ip().is_some_and(|ip_sent| ip_sent != ip_src) =>
if data.is_strict()
&& data.source_ip().is_some_and(|ip_sent| ip_sent != ip_src) =>
{
error(format!("Invalid IP - expected {:?}, actual {ip_src}", data.ip()))
error(format!(
"Invalid source IP - expected {:?}, actual {ip_src}",
data.source_ip()
))
}
Ok((now_ns, data)) => {
let command_name = String::from(&data.c);
let ip = data.ip().unwrap_or(ip_src);
let ip = data.source_ip().unwrap_or(ip_src);
info(format!("Valid data - trying {command_name} with {ip}"));

self.send_command(CommanderData { command_name, ip });
Expand Down
8 changes: 4 additions & 4 deletions tests/client_send_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ mod tests {

assert_eq!(
result.unwrap_err().to_string(),
format!("Could not connect/send data to \"{address}\": invalid port value")
format!("Could not resolve hostname for {address}: invalid port value")
);
}

Expand Down Expand Up @@ -117,7 +117,7 @@ mod tests {
assert_eq!(
result.unwrap_err().to_string(),
format!(
"Could not connect/send data to \"{address}\": \
"Could not resolve hostname for {address}: \
failed to lookup address information: Name or service not known"
)
);
Expand Down Expand Up @@ -148,8 +148,8 @@ mod tests {
assert_eq!(
result.unwrap_err().to_string(),
String::from(
"Too much data, must be at most 117 bytes, but was 118 bytes. \
Reduce command name length or create a bigger RSA key size."
"Too much data, must be at most 117 bytes, but was 132 bytes. \
Reduce command name length or create a bigger RSA key size."
)
);
}
Expand Down
1 change: 1 addition & 0 deletions tests/commander_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ mod tests {
Commander::create_from_path(path),
Ok(Commander::create(ConfigServer {
address: String::from("127.0.0.1:8080"),
ip: String::from("127.0.0.1"),
config_dir: PathBuf::from("tests/conf_dir"),
socket_user: String::from("ruroco"),
socket_group: String::from("ruroco"),
Expand Down
2 changes: 1 addition & 1 deletion tests/files/config.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
address = "127.0.0.1:8080"
ip = "127.0.0.1"
config_dir = "tests/conf_dir"

[commands]
Expand Down
2 changes: 1 addition & 1 deletion tests/files/config_end_to_end.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
address = "127.0.0.1:8080"
ip = "127.0.0.1"
config_dir = "/etc/ruroco/"

[commands]
Expand Down
Loading