somefixed to P2P communication

This commit is contained in:
PoliEcho 2025-07-31 13:40:48 +02:00
parent dc55e4e1f6
commit a87899c402
7 changed files with 130 additions and 60 deletions

View File

@ -38,6 +38,10 @@ struct Cli {
)]
password: Option<String>,
#[arg(short = 'i', long = "interface-name")]
#[arg(help = "select tun interface name Default: pea0")]
if_name: Option<String>,
#[arg(short = 'v', long = "verbose")]
verbose: bool,
@ -76,7 +80,10 @@ fn main() -> std::io::Result<()> {
#[allow(non_snake_case)] // i think this is valid snake case but rustc doesnt think so
let server_SocketAddr: core::net::SocketAddr = format!("{}:{}", cli.registrar, server_port)
.parse()
.unwrap();
.expect(&format!(
"{}:{} is invalid sock addr",
cli.registrar, server_port
));
// query here
let public_sock_addr_raw: String =
@ -85,8 +92,8 @@ fn main() -> std::io::Result<()> {
Err(e) => return Err(ServerErrorResponses::into_io_error(e)),
};
let mut salt: [u8; SALT_AND_IV_SIZE] = [0u8; SALT_AND_IV_SIZE];
let mut iv: [u8; SALT_AND_IV_SIZE] = [0u8; SALT_AND_IV_SIZE];
let mut salt: [u8; BLOCK_SIZE] = [0u8; BLOCK_SIZE];
let mut iv: [u8; BLOCK_SIZE] = [0u8; BLOCK_SIZE];
let (mut public_sock_addr, encryption_key) = match cli.password {
Some(ref p) => {
let mut rng = rand::rng();
@ -246,7 +253,7 @@ fn main() -> std::io::Result<()> {
}
let tun_iface = Arc::new(
match tun::create_tun_interface(virtual_network.read().unwrap().private_ip) {
match tun::create_tun_interface(virtual_network.read().unwrap().private_ip, cli.if_name) {
Ok(t) => t,
Err(e) => {
eprintln!(
@ -263,23 +270,31 @@ fn main() -> std::io::Result<()> {
#[cfg(not(feature = "no-timeout"))]
socket.set_read_timeout(None)?;
smol::block_on(async {
smol::spawn(tun::read_tun_iface(
tun_iface.clone(),
socket.clone(),
virtual_network.clone(),
))
.detach();
{let tun_iface_clone = tun_iface.clone();
let socket_clone = socket.clone();
let virtual_network_clone = virtual_network.clone();
std::thread::spawn(move || {
tun::read_tun_iface(
tun_iface_clone,
socket_clone,
virtual_network_clone,
)
});} // just let me have my thread
smol::block_on(async {
loop {
buf.fill(0);
match socket.recv_from(&mut buf) {
Ok((data_lenght, src)) => {
#[cfg(debug_assertions)]
eprintln!("recived method 0x{:02x} spawning handler", buf[0]);
smol::spawn(net::handle_incoming_connection(
buf,
src,
virtual_network.clone(),
tun_iface.clone(),
socket.clone(),
data_lenght,
))
.detach();

View File

@ -9,6 +9,7 @@ use super::types;
use crate::net_utils;
use crate::types::Peer;
use colored::Colorize;
use libc::socket;
use pea_2_pea::*;
use rand::{RngCore, rng};
@ -143,7 +144,7 @@ pub fn register_request(
socket: &UdpSocket,
network: &types::Network,
public_sock_addr: &Box<[u8]>,
iv: &[u8; SALT_AND_IV_SIZE as usize],
iv: &[u8; BLOCK_SIZE as usize],
) -> Result<usize, ServerErrorResponses> {
#[cfg(debug_assertions)]
println!("REGISTER method");
@ -180,10 +181,10 @@ pub fn register_request(
.copy_from_slice(network.net_id.as_bytes()); // store network id
send_buf[RegisterRequestDataPositions::IV as usize
..RegisterRequestDataPositions::IV as usize + SALT_AND_IV_SIZE as usize]
..RegisterRequestDataPositions::IV as usize + BLOCK_SIZE as usize]
.copy_from_slice(iv); // copy iv ad salt do the request
send_buf[RegisterRequestDataPositions::SALT as usize
..RegisterRequestDataPositions::SALT as usize + SALT_AND_IV_SIZE as usize]
..RegisterRequestDataPositions::SALT as usize + BLOCK_SIZE as usize]
.copy_from_slice(&network.salt);
send_buf[RegisterRequestDataPositions::SOCKADDR_LEN as usize] = public_sock_addr.len() as u8;
@ -242,8 +243,8 @@ pub fn get_request(
let mut num_of_clients: u8 = buf[GetResponseDataPositions::NUM_OF_CLIENTS as usize];
let salt: [u8; SALT_AND_IV_SIZE as usize] = buf[GetResponseDataPositions::SALT as usize
..GetResponseDataPositions::SALT as usize + SALT_AND_IV_SIZE as usize]
let salt: [u8; BLOCK_SIZE as usize] = buf[GetResponseDataPositions::SALT as usize
..GetResponseDataPositions::SALT as usize + BLOCK_SIZE as usize]
.try_into()
.unwrap();
@ -264,13 +265,13 @@ pub fn get_request(
while num_of_clients != 0 {
let sock_addr_len: u8 = buf[GetResponseDataPositions::CLIENTS as usize + offset];
let mut iv: [u8; SALT_AND_IV_SIZE as usize] = [0; SALT_AND_IV_SIZE as usize];
let mut iv: [u8; BLOCK_SIZE as usize] = [0; BLOCK_SIZE as usize];
let sock_addr_raw: Box<[u8]> =
buf[GetResponseDataPositions::CLIENTS as usize + 1 + offset + SALT_AND_IV_SIZE as usize
buf[GetResponseDataPositions::CLIENTS as usize + 1 + offset + BLOCK_SIZE as usize
..GetResponseDataPositions::CLIENTS as usize
+ 1
+ offset
+ SALT_AND_IV_SIZE as usize
+ BLOCK_SIZE as usize
+ sock_addr_len as usize]
.to_vec()
.into_boxed_slice();
@ -283,7 +284,7 @@ pub fn get_request(
..GetResponseDataPositions::CLIENTS as usize
+ 1
+ offset
+ SALT_AND_IV_SIZE as usize],
+ BLOCK_SIZE as usize],
);
#[cfg(debug_assertions)]
eprintln!(
@ -339,7 +340,7 @@ pub fn get_request(
peers.push(types::Peer::new(peer, None));
break;
}
offset += SALT_AND_IV_SIZE as usize + sock_addr_len as usize + 1 /*for size byte */;
offset += BLOCK_SIZE as usize + sock_addr_len as usize + 1 /*for size byte */;
num_of_clients -= 1;
}
@ -358,14 +359,14 @@ pub fn send_heartbeat(
socket: &UdpSocket,
network: &types::Network,
my_public_sock_addr: &Box<[u8]>,
iv: &[u8; SALT_AND_IV_SIZE as usize],
iv: &[u8; BLOCK_SIZE as usize],
) -> Result<usize, ServerErrorResponses> {
#[cfg(debug_assertions)]
println!("HEARTBEAT method");
let mut send_buf: Box<[u8]> = vec![
0u8;
HeartBeatRequestDataPositions::IV as usize
+ SALT_AND_IV_SIZE as usize
+ BLOCK_SIZE as usize
+ my_public_sock_addr.len()
+ network.net_id.len()
]
@ -377,7 +378,7 @@ pub fn send_heartbeat(
my_public_sock_addr.len() as u8;
send_buf[HeartBeatRequestDataPositions::IV as usize
..HeartBeatRequestDataPositions::IV as usize + SALT_AND_IV_SIZE as usize]
..HeartBeatRequestDataPositions::IV as usize + BLOCK_SIZE as usize]
.copy_from_slice(iv);
send_buf[HeartBeatRequestDataPositions::DATA as usize
@ -424,8 +425,8 @@ pub fn P2P_query(
STANDARD_RETRY_MAX,
)?;
let iv: [u8; SALT_AND_IV_SIZE] = buf[P2PStandardDataPositions::IV as usize
..P2PStandardDataPositions::IV as usize + SALT_AND_IV_SIZE]
let iv: [u8; BLOCK_SIZE] = buf[P2PStandardDataPositions::IV as usize
..P2PStandardDataPositions::IV as usize + BLOCK_SIZE]
.try_into()
.expect("this should never happen");
@ -474,7 +475,7 @@ pub fn P2P_hello(
let private_ip_str = private_ip.to_string();
let (private_ip_final, iv) = if network.read().unwrap().encrypted {
let mut rng = rng();
let mut iv: [u8; SALT_AND_IV_SIZE] = [0u8; SALT_AND_IV_SIZE];
let mut iv: [u8; BLOCK_SIZE] = [0u8; BLOCK_SIZE];
rng.fill_bytes(&mut iv);
(
shared::crypto::encrypt(
@ -489,7 +490,7 @@ pub fn P2P_hello(
} else {
(
private_ip_str.as_bytes().to_vec().into_boxed_slice(),
[0u8; SALT_AND_IV_SIZE],
[0u8; BLOCK_SIZE],
)
};
@ -498,7 +499,7 @@ pub fn P2P_hello(
send_buf[0] = P2PMethods::PEER_HELLO as u8;
send_buf[P2PStandardDataPositions::IV as usize
..P2PStandardDataPositions::IV as usize + SALT_AND_IV_SIZE]
..P2PStandardDataPositions::IV as usize + BLOCK_SIZE]
.copy_from_slice(&iv);
send_buf[P2PStandardDataPositions::DATA as usize..].copy_from_slice(&private_ip_final);
@ -514,9 +515,13 @@ pub async fn handle_incoming_connection(
src: SocketAddr,
network: Arc<RwLock<types::Network>>,
tun_iface: Arc<tappers::Tun>,
socket: Arc<std::net::UdpSocket>,
data_lenght: usize,
) {
#[cfg(debug_assertions)]
eprintln!("recived method 0x{:02x}", buf[0]);
match buf[0] {
x if x == P2PMethods::PACKET as u8 => {
#[cfg(debug_assertions)]
println!("PACKET from difernt peer receved");
@ -525,7 +530,7 @@ pub async fn handle_incoming_connection(
match shared::crypto::decrypt(
&network.read().unwrap().key,
&buf[P2PStandardDataPositions::IV as usize
..P2PStandardDataPositions::IV as usize + SALT_AND_IV_SIZE],
..P2PStandardDataPositions::IV as usize + BLOCK_SIZE],
&buf[P2PStandardDataPositions::DATA as usize..data_lenght as usize-1 /*compensate for size and index diference*/],
) {
Ok(data) => match tun_iface.send(&data) {
@ -549,6 +554,36 @@ pub async fn handle_incoming_connection(
};
}
}
x if x == P2PMethods::PEER_QUERY as u8 => {
let encrypted = network.read().unwrap().encrypted;
let private_ip = network.read().unwrap().private_ip;
let private_ip_str = private_ip.to_string();
let mut send_buf: Box<[u8]> = if encrypted {
vec![0; P2PStandardDataPositions::DATA as usize + 1 + (private_ip_str.len() + (BLOCK_SIZE - (private_ip_str.len() % BLOCK_SIZE)))].into() // calculate lenght of data with block alligment
} else {
vec![0; P2PStandardDataPositions::DATA as usize + 1 + private_ip_str.len()].into()
};
send_buf[0] = P2PMethods::PEER_QUERY as u8;
let mut iv = [0u8; BLOCK_SIZE];
if encrypted {
let mut rng = rng();
rng.fill_bytes(&mut iv);
send_buf[P2PStandardDataPositions::DATA as usize..P2PStandardDataPositions::DATA as usize + (private_ip_str.len() + (BLOCK_SIZE - (private_ip_str.len() % BLOCK_SIZE)))].copy_from_slice(shared::crypto::encrypt(&network.read().unwrap().key, &iv, private_ip_str.as_bytes()).unwrap().as_slice());
} else {
send_buf[P2PStandardDataPositions::DATA as usize..P2PStandardDataPositions::DATA as usize + private_ip_str.len()].copy_from_slice(private_ip_str.as_bytes());
}
match socket.send_to(&send_buf, &src) {
Ok(s) => {
#[cfg(debug_assertions)]
eprintln!("send {} bytes", s);
}
Err(e) => {
eprintln!("Error sending data: {}", e);
}
}
},
x if x == P2PMethods::PEER_HELLO as u8 => {
println!("{} peer hello receved from: {}", "[LOG]".blue(), src);
@ -563,7 +598,7 @@ pub async fn handle_incoming_connection(
match std::net::Ipv4Addr::from_str(
match std::str::from_utf8(if encrypted {
match shared::crypto::decrypt(&key, &buf[P2PStandardDataPositions::IV as usize
..P2PStandardDataPositions::IV as usize + SALT_AND_IV_SIZE], &buf[P2PStandardDataPositions::DATA as usize..data_lenght as usize-1 /*compensate for size and index diference*/]) {
..P2PStandardDataPositions::IV as usize + BLOCK_SIZE], &buf[P2PStandardDataPositions::DATA as usize..data_lenght as usize-1 /*compensate for size and index diference*/]) {
Ok(data) => {tmp_data = data; &tmp_data},
Err(e) => {
eprintln!(
@ -601,6 +636,15 @@ pub async fn handle_incoming_connection(
),
));
}
match socket.send_to(&[P2PMethods::PEER_HELLO as u8], &src) {
Ok(s) => {
#[cfg(debug_assertions)]
eprintln!("send {} bytes", s);
}
Err(e) => {
eprintln!("Error sending data: {}", e);
}
}
}
x if x == P2PMethods::PEER_GOODBYE as u8 => {
println!("{} peer goodbye receved from: {}", "[LOG]".blue(), src);
@ -610,10 +654,10 @@ pub async fn handle_incoming_connection(
let key = network_lock.key;
let encrypted: bool = network_lock.encrypted;
let mut data_tmp: Vec<u8> = Vec::with_capacity(SALT_AND_IV_SIZE); // block size
let mut data_tmp: Vec<u8> = Vec::with_capacity(BLOCK_SIZE); // block size
network_lock.peers.retain(|peer| !{peer.private_ip == match std::net::Ipv4Addr::from_str(match std::str::from_utf8( if encrypted {
match shared::crypto::decrypt(&key, &buf[P2PStandardDataPositions::IV as usize..P2PStandardDataPositions::IV as usize + SALT_AND_IV_SIZE], &buf[P2PStandardDataPositions::DATA as usize..data_lenght as usize-1 /*compensate for size and index diference*/]) {
match shared::crypto::decrypt(&key, &buf[P2PStandardDataPositions::IV as usize..P2PStandardDataPositions::IV as usize + BLOCK_SIZE], &buf[P2PStandardDataPositions::DATA as usize..data_lenght as usize-1 /*compensate for size and index diference*/]) {
Ok(data) => {data_tmp = data;
&data_tmp},
Err(e) => {eprintln!("{} error parsing ip, Error: {}", "[ERROR]".red(), e); return false;},
@ -625,6 +669,15 @@ pub async fn handle_incoming_connection(
Ok(ip) => ip,
Err(e) => {eprintln!("{} error parsing ip, Error: {}", "[ERROR]".red(), e); return false;},
} && peer.sock_addr == src});
match socket.send_to(&[P2PMethods::PEER_GOODBYE as u8], &src) {
Ok(s) => {
#[cfg(debug_assertions)]
eprintln!("send {} bytes", s);
}
Err(e) => {
eprintln!("Error sending data: {}", e);
}
}
}
_ => {

View File

@ -8,8 +8,11 @@ use crate::types::Network;
pub fn create_tun_interface(
private_ip: std::net::Ipv4Addr,
if_name: Option<String>,
) -> Result<tappers::Tun, std::io::Error> {
let mut tun_iface: tappers::Tun = tappers::Tun::new_named(tappers::Interface::new("pea0")?)?;
let mut tun_iface: tappers::Tun = tappers::Tun::new_named(tappers::Interface::new(
if_name.unwrap_or("pea0".to_owned()),
)?)?;
let mut addr_req = tappers::AddAddressV4::new(private_ip);
addr_req.set_netmask(24);
let mut broadcast_addr_oct = private_ip.octets();
@ -20,7 +23,6 @@ pub fn create_tun_interface(
return Ok(tun_iface);
}
pub async fn read_tun_iface(
tun_iface: Arc<tappers::Tun>,
socket: Arc<std::net::UdpSocket>,
@ -59,7 +61,7 @@ pub async fn handle_ip_packet(
);
let mut rng = rand::rng();
let mut iv: [u8; SALT_AND_IV_SIZE] = [0u8; SALT_AND_IV_SIZE];
let mut iv: [u8; BLOCK_SIZE] = [0u8; BLOCK_SIZE];
rng.fill_bytes(&mut iv);
let mut encrypted_data =

View File

@ -27,7 +27,7 @@ pub struct Network {
#[readonly]
pub net_id: String,
#[readonly]
pub salt: [u8; SALT_AND_IV_SIZE as usize],
pub salt: [u8; BLOCK_SIZE as usize],
pub peers: Vec<Peer>,
pub private_ip: std::net::Ipv4Addr,
}
@ -37,7 +37,7 @@ impl Network {
encrypted: bool,
key: [u8; 32],
net_id: String,
salt: [u8; SALT_AND_IV_SIZE as usize],
salt: [u8; BLOCK_SIZE as usize],
peers: Vec<Peer>,
) -> Self {
Network {
@ -54,13 +54,13 @@ impl Network {
#[readonly::make]
pub struct EncryptablePulicSockAddr {
#[readonly]
pub iv: [u8; SALT_AND_IV_SIZE],
pub iv: [u8; BLOCK_SIZE],
#[readonly]
pub sock_addr: Box<[u8]>,
}
impl EncryptablePulicSockAddr {
pub fn new(iv: [u8; SALT_AND_IV_SIZE], sock_addr: Box<[u8]>) -> Self {
pub fn new(iv: [u8; BLOCK_SIZE], sock_addr: Box<[u8]>) -> Self {
EncryptablePulicSockAddr { iv, sock_addr }
}
}

View File

@ -5,7 +5,7 @@ pub const UDP_BUFFER_SIZE: usize = 65527;
pub const IP_BUFFER_SIZE: usize = 65535;
pub const DEFAULT_TIMEOUT: u64 = 30;
pub const VERSION: &str = "v0.1";
pub const SALT_AND_IV_SIZE: usize = 16;
pub const BLOCK_SIZE: usize = 16;
pub const STANDARD_RETRY_MAX: usize = 10;
pub const DEST_IN_IPV4_OFFSET: usize = 16;
@ -82,8 +82,8 @@ pub enum RegisterRequestDataPositions {
ID_LEN = 2,
SOCKADDR_LEN = 3,
SALT = 4,
IV = (SALT_AND_IV_SIZE as usize + RegisterRequestDataPositions::SALT as usize) as usize,
DATA = (SALT_AND_IV_SIZE as usize + RegisterRequestDataPositions::IV as usize) as usize, // after this there will be id and sockaddr in string or encrypted form after
IV = (BLOCK_SIZE as usize + RegisterRequestDataPositions::SALT as usize) as usize,
DATA = (BLOCK_SIZE as usize + RegisterRequestDataPositions::IV as usize) as usize, // after this there will be id and sockaddr in string or encrypted form after
}
#[allow(non_camel_case_types)]
@ -99,7 +99,7 @@ pub enum GetResponseDataPositions {
NUM_OF_CLIENTS = 2,
SALT = 3,
CLIENTS =
(SALT_AND_IV_SIZE as usize + RegisterRequestDataPositions::SALT as usize) - 1 as usize,
(BLOCK_SIZE as usize + RegisterRequestDataPositions::SALT as usize) - 1 as usize,
// after this there will be blocks of this sturcture: one byte size of sockaddr than there will be IV that is SALT_AND_IV_SIZE long and after that there will be sockaddr this repeats until the end of packet
}
@ -109,7 +109,7 @@ pub enum HeartBeatRequestDataPositions {
ID_LEN = 1,
SOCKADDR_LEN = 2,
IV = 3,
DATA = (HeartBeatRequestDataPositions::IV as usize + SALT_AND_IV_SIZE as usize) as usize, // first ID than sockaddr
DATA = (HeartBeatRequestDataPositions::IV as usize + BLOCK_SIZE as usize) as usize, // first ID than sockaddr
}
#[allow(non_camel_case_types)]
@ -124,7 +124,7 @@ pub enum P2PMethods {
pub enum P2PStandardDataPositions {
// sould apply to all P2P Methods
IV = 1,
DATA = P2PStandardDataPositions::IV as usize + SALT_AND_IV_SIZE,
DATA = P2PStandardDataPositions::IV as usize + BLOCK_SIZE,
}
pub mod shared;

View File

@ -77,7 +77,7 @@ pub async fn handle_request(
.cloned();
let mut send_vec: Vec<u8> = Vec::with_capacity(
1/*initial status byte */ +
GetResponseDataPositions::SALT as usize + /*2 times one for SALT and other for first IV*/ 2*SALT_AND_IV_SIZE as usize + 20, /*magic number guess for how long is encrypted residencial ipv4 with port long */
GetResponseDataPositions::SALT as usize + /*2 times one for SALT and other for first IV*/ 2*BLOCK_SIZE as usize + 20, /*magic number guess for how long is encrypted residencial ipv4 with port long */
); // use vector to handle many clients
send_vec.push(ServerMethods::GET as u8); // this means success
@ -191,21 +191,21 @@ pub async fn handle_request(
None => {}
}
let salt: Option<[u8; SALT_AND_IV_SIZE as usize]>;
let iv: Option<[u8; SALT_AND_IV_SIZE as usize]>;
let salt: Option<[u8; BLOCK_SIZE as usize]>;
let iv: Option<[u8; BLOCK_SIZE as usize]>;
if encrypted {
salt = Some(
buf[(RegisterRequestDataPositions::SALT as usize)
..(RegisterRequestDataPositions::SALT as usize)
+ (SALT_AND_IV_SIZE as usize)]
+ (BLOCK_SIZE as usize)]
.try_into()
.expect("this should never happen"),
);
iv = Some(
buf[(RegisterRequestDataPositions::IV as usize)
..(RegisterRequestDataPositions::IV as usize)
+ (SALT_AND_IV_SIZE as usize)]
+ (BLOCK_SIZE as usize)]
.try_into()
.expect("this should never happen"),
)
@ -297,9 +297,9 @@ pub async fn handle_request(
}
};
let iv: [u8; SALT_AND_IV_SIZE as usize] =
let iv: [u8; BLOCK_SIZE as usize] =
buf[HeartBeatRequestDataPositions::IV as usize
..HeartBeatRequestDataPositions::IV as usize + SALT_AND_IV_SIZE as usize]
..HeartBeatRequestDataPositions::IV as usize + BLOCK_SIZE as usize]
.try_into()
.unwrap();

View File

@ -8,11 +8,11 @@ pub struct Client {
pub client_sock_addr: Vec<u8>,
pub last_heart_beat: i64,
#[readonly]
pub iv: [u8; SALT_AND_IV_SIZE as usize],
pub iv: [u8; BLOCK_SIZE as usize],
}
impl Client {
pub fn new(client_addr: Vec<u8>, heart_beat: i64, iv: [u8; SALT_AND_IV_SIZE as usize]) -> Self {
pub fn new(client_addr: Vec<u8>, heart_beat: i64, iv: [u8; BLOCK_SIZE as usize]) -> Self {
Client {
client_sock_addr: client_addr,
last_heart_beat: heart_beat,
@ -32,7 +32,7 @@ pub struct Registration {
#[readonly]
pub encrypted: bool,
#[readonly]
pub salt: [u8; SALT_AND_IV_SIZE as usize],
pub salt: [u8; BLOCK_SIZE as usize],
}
impl Registration {
@ -41,19 +41,19 @@ impl Registration {
client_addr: Vec<u8>,
encrypted: bool,
heart_beat: i64,
salt: Option<[u8; SALT_AND_IV_SIZE as usize]>,
iv: Option<[u8; SALT_AND_IV_SIZE as usize]>,
salt: Option<[u8; BLOCK_SIZE as usize]>,
iv: Option<[u8; BLOCK_SIZE as usize]>,
) -> Self {
Registration {
net_id,
clients: vec![Client::new(
client_addr,
heart_beat,
iv.unwrap_or([0; SALT_AND_IV_SIZE as usize]),
iv.unwrap_or([0; BLOCK_SIZE as usize]),
)],
encrypted,
last_heart_beat: heart_beat,
salt: salt.unwrap_or([0; SALT_AND_IV_SIZE as usize]),
salt: salt.unwrap_or([0; BLOCK_SIZE as usize]),
}
}
}