Refactored again
This commit is contained in:
parent
54d035a78b
commit
2e0cab46f7
|
|
@ -6,7 +6,7 @@ edition = "2021"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
socket2 = "0.4"
|
||||
socket2 = { version = "0.4.7", features = ["all"] }
|
||||
env_logger = "0.10"
|
||||
rhexdump = "0.1.1"
|
||||
rand = "0.8.5"
|
||||
|
|
|
|||
20
libc.rs
20
libc.rs
|
|
@ -45,16 +45,16 @@ fn main() {
|
|||
packet.as_ptr() as *const c_void,
|
||||
packet.len() as u64,
|
||||
0,
|
||||
// Send the packet
|
||||
let send_result = unsafe {
|
||||
libc::sendto(
|
||||
socket_fd,
|
||||
packet.as_ptr() as *const c_void,
|
||||
packet.len() as u64,
|
||||
0,
|
||||
&addr as *const sockaddr_in as *const libc::sockaddr,
|
||||
mem::size_of::<sockaddr_in>() as u32,
|
||||
)
|
||||
// Send the packet
|
||||
let send_result = unsafe {
|
||||
libc::sendto(
|
||||
socket_fd,
|
||||
packet.as_ptr() as *const c_void,
|
||||
packet.len() as u64,
|
||||
0,
|
||||
&addr as *const sockaddr_in as *const libc::sockaddr,
|
||||
mem::size_of::<sockaddr_in>() as u32,
|
||||
)
|
||||
};
|
||||
|
||||
if send_result < 0 {
|
||||
|
|
|
|||
|
|
@ -1,35 +1,51 @@
|
|||
use std::env;
|
||||
|
||||
pub fn parse_all_arguments() -> (String,u8,u16,u16,Vec<u8>, usize){
|
||||
// Load all inline arguments and change them in place
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let mut ping_type : u8 = 0x08;
|
||||
let mut identifier : u16 = 0x4242;
|
||||
let mut sequence : u16 = 0x4242;
|
||||
let mut payload = Vec::<u8>::new();
|
||||
let mut payload_size : usize = 64;
|
||||
pub struct Config{
|
||||
pub dest_addr : String,
|
||||
pub ping_type : u8,
|
||||
pub identifier : u16,
|
||||
pub sequence : u16,
|
||||
pub payload : Vec<u8>,
|
||||
pub payload_size : usize,
|
||||
pub raw_packet : bool,
|
||||
}
|
||||
|
||||
pub fn parse_all_arguments() -> Config {
|
||||
// Load all inline arguments and create a config structure
|
||||
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let mut config = Config {
|
||||
dest_addr : String::new(),
|
||||
ping_type : 0x08,
|
||||
identifier : 0x4242,
|
||||
sequence : 0x4242,
|
||||
payload: Vec::<u8>::new(),
|
||||
payload_size : 64,
|
||||
raw_packet: false,
|
||||
};
|
||||
if args.len() == 1 {
|
||||
exit_with_help();
|
||||
}
|
||||
// let dest_ip=args[1].parse::<Ipv4Addr>().unwrap();
|
||||
let dest_addr= args[1].clone();
|
||||
|
||||
config.dest_addr= args[1].clone();
|
||||
for (i,arg) in args[1..].iter().enumerate(){
|
||||
if arg == "--help" || arg == "-h" {
|
||||
exit_with_help();
|
||||
} else if arg == "--type" || arg == "-t" {
|
||||
ping_type = args[i + 2].parse::<u8>().unwrap();
|
||||
config.ping_type = args[i + 2].parse::<u8>().unwrap();
|
||||
} else if arg == "--identifier" || arg == "-i" {
|
||||
identifier = args[i + 2].parse::<u16>().unwrap();
|
||||
config.identifier = args[i + 2].parse::<u16>().unwrap();
|
||||
} else if arg == "--sequence" || arg == "-q" {
|
||||
sequence = args[i + 2].parse::<u16>().unwrap();
|
||||
config.sequence = args[i + 2].parse::<u16>().unwrap();
|
||||
} else if arg == "--payload" || arg == "-p" {
|
||||
payload = args[i + 2].as_bytes().to_vec();
|
||||
config.payload = args[i + 2].as_bytes().to_vec();
|
||||
} else if arg == "--size" || arg == "-s" {
|
||||
payload_size = args[i + 2].parse::<usize>().unwrap();
|
||||
config.payload_size = args[i + 2].parse::<usize>().unwrap();
|
||||
} else if arg =="--raw" {
|
||||
config.raw_packet=true; // This enable raw packets but requires root privilege
|
||||
}
|
||||
}
|
||||
(dest_addr,ping_type,identifier,sequence,payload,payload_size)
|
||||
config
|
||||
}
|
||||
|
||||
fn exit_with_help() {
|
||||
|
|
@ -39,7 +55,8 @@ fn exit_with_help() {
|
|||
[--identifier/-i <id>] The Header identifier (16b)
|
||||
[--sequence/-q <seq>] The Sequence number (16b)
|
||||
[--payload/-p <text>] The Payload, generated randomly if not given (any)
|
||||
[--size/-s <size>] The Payload size (any) but smaller than ???\
|
||||
[--size/-s <size>] The Payload size (any) but smaller than ???
|
||||
[--raw] Enable raw packet, require root privileges
|
||||
");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
use crate::libs::args::Config;
|
||||
use core::time::Duration;
|
||||
use rand::{
|
||||
Rng,
|
||||
|
|
@ -7,8 +8,8 @@ use rand::{
|
|||
use std::time::Instant;
|
||||
|
||||
use std::{
|
||||
sync::Arc,
|
||||
io::{self},
|
||||
net,
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs},
|
||||
};
|
||||
use std::os::{
|
||||
|
|
@ -16,35 +17,50 @@ use std::os::{
|
|||
unix::io::FromRawFd
|
||||
};
|
||||
|
||||
|
||||
struct SocketAddresses{
|
||||
socket1_addr: net::SocketAddr,
|
||||
socket2_addr: socket2::SockAddr,
|
||||
dest_addr: net::SocketAddr,
|
||||
}
|
||||
//use env_logger::Env;
|
||||
pub fn generate_ping_request(dest_addr: String,ping_type:u8,identifier:u16,sequence:u16,payload:Vec<u8>, payload_size:usize) -> Result<(),()>{
|
||||
pub fn generate_ping_request(config : crate::libs::args::Config) -> Result<(),()>{
|
||||
|
||||
let (socket_ip_address, socket2_ip_address, dest_addr) = create_addresses(dest_addr);
|
||||
let mut socket2_ipv4_socket=create_sockets(socket_ip_address, socket2_ip_address);
|
||||
let socket_arc = create_socket_arc(&mut socket2_ipv4_socket);
|
||||
let addr = create_addresses(&config.dest_addr);
|
||||
let mut socket2_ipv4_socket=create_sockets(addr.socket1_addr, addr.socket2_addr);
|
||||
let socket_final = match config.raw_packet{
|
||||
true => create_socket_raw(&config, &mut socket2_ipv4_socket),
|
||||
false => create_socket_udp(&mut socket2_ipv4_socket),
|
||||
};
|
||||
|
||||
let (buffer, checksum) = create_buffer(ping_type,identifier, sequence, payload, payload_size);
|
||||
let (buffer, checksum) = create_buffer(
|
||||
config.ping_type,
|
||||
config.identifier,
|
||||
config.sequence,
|
||||
config.payload,
|
||||
config.payload_size
|
||||
);
|
||||
|
||||
// Send the ping request to the specified destination IP address.
|
||||
print_send_pre_message(checksum, &buffer);
|
||||
|
||||
// Starting the timer
|
||||
let now = Instant::now();
|
||||
let result = socket_arc.send_to(&buffer, dest_addr);
|
||||
let result = socket_final.send_to(&buffer, addr.dest_addr);
|
||||
// let result = socket_arc.send_to_with_flags(&buffer, dest_addr, 0);
|
||||
|
||||
match result {
|
||||
Ok(bytes) => print_send_post_messages(bytes, dest_addr, checksum),
|
||||
Ok(bytes) => print_send_post_messages(bytes, addr.dest_addr, checksum),
|
||||
Err(err) => println!(" [ERROR] Failed to send data over the socket: {}", err)
|
||||
}
|
||||
|
||||
// Wait for a response from the destination.
|
||||
let mut buf = vec![0; payload_size]; // Make that buffer arbitrary large
|
||||
let mut buf = vec![0; config.payload_size]; // Make that buffer arbitrary large
|
||||
let timeout = std::time::Duration::from_secs(1);
|
||||
|
||||
|
||||
socket_arc.set_read_timeout(Some(timeout)).unwrap();
|
||||
let (bytes_recv, _src_addr) = match socket_arc.recv_from(&mut buf) {
|
||||
socket_final.set_read_timeout(Some(timeout)).unwrap();
|
||||
let (bytes_recv, _src_addr) = match socket_final.recv_from(&mut buf) {
|
||||
Ok(res) => res,
|
||||
Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => {
|
||||
println!(" [ERROR] No response from destination");
|
||||
|
|
@ -58,14 +74,15 @@ pub fn generate_ping_request(dest_addr: String,ping_type:u8,identifier:u16,seque
|
|||
print_recv_post_message(&buf, bytes_recv, elapsed);
|
||||
Ok(())
|
||||
}
|
||||
fn create_addresses(dest_ip: String) -> (SocketAddr, socket2::SockAddr, SocketAddr){
|
||||
|
||||
fn create_addresses(dest_ip: &String) -> SocketAddresses{
|
||||
// SOURCE IP ADDRESS
|
||||
let localhost = Ipv4Addr::UNSPECIFIED;
|
||||
let socket_ip_address = SocketAddr::new(IpAddr::V4(localhost), 80);
|
||||
let socket2_ip_address = socket_ip_address.into();
|
||||
let socket1_addr = SocketAddr::new(IpAddr::V4(localhost), 80);
|
||||
let socket2_addr = socket1_addr.into();
|
||||
|
||||
let dest_addr = (dest_ip,0).to_socket_addrs().unwrap().next().unwrap();//SocketAddr::new(IpAddr::V4(dest_ip), 0);
|
||||
(socket_ip_address, socket2_ip_address, dest_addr)
|
||||
let dest_addr = ((*dest_ip).clone(),0).to_socket_addrs().unwrap().next().unwrap();
|
||||
SocketAddresses {socket1_addr, socket2_addr, dest_addr}
|
||||
}
|
||||
|
||||
fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::SockAddr) -> socket2::Socket {
|
||||
|
|
@ -83,27 +100,44 @@ fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::Sock
|
|||
&socket_ip_address
|
||||
));
|
||||
|
||||
// Set the socket to be non-blocking.
|
||||
// socket.set_nonblocking(true).unwrap();
|
||||
|
||||
// Set the Time-To-Live (TTL) value for the socket.
|
||||
// socket.set_ttl(64).unwrap();
|
||||
|
||||
socket2_ipv4_socket
|
||||
}
|
||||
|
||||
fn create_socket_arc(socket2_ipv4_socket: &mut socket2::Socket) -> std::net::UdpSocket/*Arc<std::net::UdpSocket>*/ {
|
||||
fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> std::net::UdpSocket/*socket2::Socket,std::net::UdpSocketArc<std::net::UdpSocket>*/ {
|
||||
// CREATE STD SOCKET FROM SOCKET2 SOCKET
|
||||
let raw_ipv4_socket = socket2_ipv4_socket.as_raw_fd();
|
||||
let std_ipv4_socket = unsafe { std::net::UdpSocket::from_raw_fd(raw_ipv4_socket) };
|
||||
|
||||
std_ipv4_socket
|
||||
.set_read_timeout(Some(Duration::from_millis(100)))
|
||||
.expect(&format!("Failed to set read timeout"));
|
||||
std_ipv4_socket
|
||||
// Arc::new(std_ipv4_socket)
|
||||
*Box::new(std_ipv4_socket)
|
||||
//Arc::new(std_ipv4_socket)
|
||||
}
|
||||
|
||||
|
||||
fn create_socket_raw(config: &Config, _socket2_ipv4_socket: &mut socket2::Socket) -> std::net::UdpSocket /*socket2::Socket*/{
|
||||
let socket = match socket2::Socket::new_raw(
|
||||
socket2::Domain::IPV4,
|
||||
socket2::Type::RAW,
|
||||
Some(socket2::Protocol::ICMPV4)
|
||||
){
|
||||
Err(error) => match error.kind() {
|
||||
std::io::ErrorKind::PermissionDenied => {
|
||||
println!("[ERROR] Raw socket require root privilege on your OS");
|
||||
std::process::exit(1);
|
||||
},
|
||||
_ => panic!("Couldn't create raw socket {:?} ",error)
|
||||
},
|
||||
Ok(res) => res,
|
||||
};
|
||||
if config.raw_packet { match socket.set_header_included(true){
|
||||
Err(e) => panic!("Can't setup a raw packet via Socket2 options {}",e),
|
||||
_ => (),}};
|
||||
socket.set_read_timeout(Some(Duration::from_millis(100)))
|
||||
.expect(&format!("Failed to set read timeout"));
|
||||
//Into::<std::net::UdpSocket>::into(socket);
|
||||
std::net::UdpSocket::from(socket)
|
||||
}
|
||||
|
||||
fn create_buffer(ping_type: u8, identifier: u16, sequence: u16, mut payload: Vec<u8>, payload_size : usize) -> (Vec<u8>,u16){
|
||||
// Create the ping request message.
|
||||
|
|
|
|||
81
src/main.rs
81
src/main.rs
|
|
@ -1,89 +1,12 @@
|
|||
// Import libs
|
||||
|
||||
|
||||
//use dns_lookup::lookup_host;
|
||||
|
||||
mod libs;
|
||||
// mod test;
|
||||
|
||||
fn main() {
|
||||
// env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
|
||||
|
||||
// Parse the command line arguments.
|
||||
let (dest_addr,ping_type,identifier,sequence,payload, payload_size) = libs::parse_all_arguments();
|
||||
let res = libs::generate_ping_request(dest_addr,ping_type,identifier,sequence,payload, payload_size);
|
||||
let res = libs::generate_ping_request(libs::parse_all_arguments());
|
||||
match res {
|
||||
Ok(()) => (),
|
||||
Err(()) => eprintln!("Program exited with errors")
|
||||
}
|
||||
|
||||
}
|
||||
// use std::net::{Ipv4Addr, UdpSocket};
|
||||
|
||||
// // Define the IPv4 header structure
|
||||
// #[repr(C)]
|
||||
// struct Ipv4Header {
|
||||
// version: u8,
|
||||
// ihl: u8,
|
||||
// dscp: u8,
|
||||
// ecn: u8,
|
||||
// total_length: u16,
|
||||
// identification: u16,
|
||||
// flags: u8,
|
||||
// fragment_offset: u16,
|
||||
// ttl: u8,
|
||||
// protocol: u8,
|
||||
// checksum: u16,
|
||||
// source: Ipv4Addr,
|
||||
// destination: Ipv4Addr,
|
||||
// }
|
||||
|
||||
// fn main() {
|
||||
// // Create the socket
|
||||
// let socket = UdpSocket::bind("0.0.0.0:0").expect("Failed to bind socket");
|
||||
|
||||
// // Set the source and destination IP addresses
|
||||
// let src_ip = Ipv4Addr::new(0, 0, 0, 0);
|
||||
// let dst_ip = Ipv4Addr::new(8, 8, 8, 8);
|
||||
|
||||
// // Fill in the IPv4 header fields
|
||||
// let mut header = Ipv4Header {
|
||||
// version: 4,
|
||||
// ihl: 5,
|
||||
// dscp: 0,
|
||||
// ecn: 0,
|
||||
// total_length: 0, // This will be calculated later
|
||||
// identification: 0,
|
||||
// flags: 0,
|
||||
// fragment_offset: 0,
|
||||
// ttl: 64,
|
||||
// protocol: 17, // UDP
|
||||
// checksum: 0, // This will be calculated later
|
||||
// source: src_ip,
|
||||
// destination: dst_ip,
|
||||
// };
|
||||
|
||||
// // Create the data to send
|
||||
// const DATA: &[u8; 11] = b"hello world";
|
||||
|
||||
// // Calculate the total length and checksum fields
|
||||
// header.total_length = (header.ihl as usize * 4 + DATA.len()) as u16;
|
||||
// header.checksum = 0;//calculate_checksum(&header);
|
||||
|
||||
// // Create a buffer that contains the header and data
|
||||
// let mut buf = [0u8; 20 + DATA.len()];
|
||||
// let header_bytes = unsafe { std::slice::from_raw_parts(&header as *const _ as *const u8, 20) };
|
||||
// buf[..20].copy_from_slice(header_bytes);
|
||||
// buf[20..].copy_from_slice(DATA);
|
||||
|
||||
// // Send the buffer
|
||||
// let _result = socket.send_to(&buf, (dst_ip, 80));
|
||||
// }
|
||||
|
||||
|
||||
// }
|
||||
|
||||
// // Calculate the IPv4 header checksum
|
||||
// fn calculate_checksum(header: &Ipv4Header) -> u16 {
|
||||
// // TODO: Implement the checksum calculation
|
||||
// }
|
||||
}
|
||||
Loading…
Reference in New Issue