From 54d035a78bde6db37698afef43600f268ef0f9ed Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 10 Dec 2022 00:55:55 +0100 Subject: [PATCH] Added all the first refactor, will now use pnet and or build_packet --- libc.rs | 64 ++++++++++ src/libs.rs | 7 ++ src/libs/args.rs | 45 +++++++ src/libs/icmp.rs | 190 ++++++++++++++++++++++++++++++ src/libs/socket.rs | 0 src/main.rs | 288 ++++++++++++--------------------------------- 6 files changed, 384 insertions(+), 210 deletions(-) create mode 100644 libc.rs create mode 100644 src/libs.rs create mode 100644 src/libs/args.rs create mode 100644 src/libs/icmp.rs create mode 100644 src/libs/socket.rs diff --git a/libc.rs b/libc.rs new file mode 100644 index 0000000..c00a65b --- /dev/null +++ b/libc.rs @@ -0,0 +1,64 @@ +extern crate libc; + +use std::net::Ipv4Addr; +use std::mem; +use std::slice; + +use libc::{c_int, c_void, sockaddr_in, in_addr, htons, inet_pton}; + +const IHL_MASK: u8 = 0x0F; // The mask for the IHL field +const IHL_SHIFT: u8 = 4; // The number of bits to shift the IHL value + +fn main() { + // Create the raw socket + let socket_fd = unsafe { + socket(AF_INET, SOCK_RAW, libc::IPPROTO_RAW) + }; + + if socket_fd < 0 { + // Handle the error + } else { + // Construct the packet + let mut packet: [u8; 40] = [0; 40]; // 40 bytes for a header with IHL=10 + + // Set the IHL field + let ihl = 10; + packet[0] |= (ihl << IHL_SHIFT) & IHL_MASK; + + // Set the other fields in the header as needed... + + // Create the sockaddr_in structure to specify the destination + let mut addr: sockaddr_in = mem::zeroed(); + addr.sin_family = AF_INET as u16; + addr.sin_port = htons(0); // Set the port to 0 + + // Set the destination IP address + let ip_str = "192.0.2.1"; + let ip = Ipv4Addr::from_str(ip_str).unwrap(); + let in_addr = in_addr { s_addr: u32::from(ip) }; + inet_pton(AF_INET, &in_addr as *const in_addr as *const c_void, &mut addr.sin_addr as *mut sockaddr_in as *mut c_void); + + // Send the packet + let send_result = unsafe { + libc::sendto( + socket_fd, + 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::() as u32, + ) +}; + +if send_result < 0 { + // Handle the error +} else { + // The packet was sent successfully +} diff --git a/src/libs.rs b/src/libs.rs new file mode 100644 index 0000000..bac686e --- /dev/null +++ b/src/libs.rs @@ -0,0 +1,7 @@ +mod icmp; +mod args; + +pub use icmp::{ + generate_ping_request +}; +pub use args::parse_all_arguments; \ No newline at end of file diff --git a/src/libs/args.rs b/src/libs/args.rs new file mode 100644 index 0000000..4f34b24 --- /dev/null +++ b/src/libs/args.rs @@ -0,0 +1,45 @@ +use std::env; + +pub fn parse_all_arguments() -> (String,u8,u16,u16,Vec, usize){ + // Load all inline arguments and change them in place + let args: Vec = env::args().collect(); + let mut ping_type : u8 = 0x08; + let mut identifier : u16 = 0x4242; + let mut sequence : u16 = 0x4242; + let mut payload = Vec::::new(); + let mut payload_size : usize = 64; + + if args.len() == 1 { + exit_with_help(); + } + // let dest_ip=args[1].parse::().unwrap(); + let 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::().unwrap(); + } else if arg == "--identifier" || arg == "-i" { + identifier = args[i + 2].parse::().unwrap(); + } else if arg == "--sequence" || arg == "-q" { + sequence = args[i + 2].parse::().unwrap(); + } else if arg == "--payload" || arg == "-p" { + payload = args[i + 2].as_bytes().to_vec(); + } else if arg == "--size" || arg == "-s" { + payload_size = args[i + 2].parse::().unwrap(); + } + } + (dest_addr,ping_type,identifier,sequence,payload,payload_size) +} + +fn exit_with_help() { + eprintln!("Usage: cargo run --dest + [--type/-t ] The type of ping request 8 for IPv4 128 for IPv6 (8b) + [--code/-c ] The mandatory 0 code (8b) + [--identifier/-i ] The Header identifier (16b) + [--sequence/-q ] The Sequence number (16b) + [--payload/-p ] The Payload, generated randomly if not given (any) + [--size/-s ] The Payload size (any) but smaller than ???\ + "); + std::process::exit(1); +} \ No newline at end of file diff --git a/src/libs/icmp.rs b/src/libs/icmp.rs new file mode 100644 index 0000000..172eccd --- /dev/null +++ b/src/libs/icmp.rs @@ -0,0 +1,190 @@ +use core::time::Duration; +use rand::{ + Rng, + thread_rng, + distributions::Alphanumeric, +}; +use std::time::Instant; + +use std::{ + sync::Arc, + io::{self}, + net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs}, +}; +use std::os::{ + unix::io::AsRawFd, + unix::io::FromRawFd +}; + +//use env_logger::Env; +pub fn generate_ping_request(dest_addr: String,ping_type:u8,identifier:u16,sequence:u16,payload:Vec, payload_size:usize) -> 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 (buffer, checksum) = create_buffer(ping_type,identifier, sequence, payload, 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_arc.send_to_with_flags(&buffer, dest_addr, 0); + + match result { + Ok(bytes) => print_send_post_messages(bytes, 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 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) { + Ok(res) => res, + Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { + println!(" [ERROR] No response from destination"); + println!(" [ERROR] {:?}", err); + std::process::exit(0); + } + Err(err) => panic!(" [ERROR] Error receiving data: {}", err), + }; + let elapsed = now.elapsed(); + + print_recv_post_message(&buf, bytes_recv, elapsed); + Ok(()) +} +fn create_addresses(dest_ip: String) -> (SocketAddr, socket2::SockAddr, SocketAddr){ + // 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 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) +} + +fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::SockAddr) -> socket2::Socket { + let socket2_ipv4_socket = socket2::Socket::new( + socket2::Domain::IPV4, + socket2::Type::DGRAM, + Some(socket2::Protocol::ICMPV4), + ).unwrap(); + + // BIND TO LOCAL ADDRESS + socket2_ipv4_socket + .bind(&socket2_ip_address) + .expect(&format!( + "Failed binding to Ipv4 address {:?}", + &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*/ { + // 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) +} + + + +fn create_buffer(ping_type: u8, identifier: u16, sequence: u16, mut payload: Vec, payload_size : usize) -> (Vec,u16){ + // Create the ping request message. + let mut buf = vec![0u8; payload_size]; + let header = [ + ping_type, 0x00, // Type and Code=0 fields + 0x00, 0x00, // Checksum (filled in later) + 0x00, 0x00, 0x00, 0x00, // Identifier and Sequence Number fields + ]; + buf[..header.len()].copy_from_slice(&header); + + // Add the data to the ping request message. + let header = [ + (identifier >> 8) as u8, (identifier & 0xff) as u8, + (sequence >> 8) as u8, (sequence & 0xff) as u8, + ]; + + if payload.len() == 0{ + generate_payload(&mut payload, payload_size); + } + buf[header.len()..(header.len() + header.len())].copy_from_slice(&header); + buf[header.len() + header.len()..(header.len() + header.len()+payload.len())].copy_from_slice(&payload); + + // Calculate the checksum of the ping request message. + let checksum = calculate_checksum(&buf); + buf[2] = (checksum >> 8) as u8; + buf[3] = (checksum & 0xff) as u8; + (buf, checksum) +} + +fn calculate_checksum(buf : &Vec) -> u16 { + let checksum = { + let mut sum = 0; + for i in 0..(buf.len() / 2) { + sum += (buf[2 * i+1 ] as usize) << 8 | buf[2 * i] as usize; + } + if buf.len()%2==1 { sum += buf[buf.len()-1] as usize; } + while sum>>16!=0 { sum = (sum & 0xffff) + (sum >> 16) } + !(sum as u16) + }; + checksum +} + +fn print_send_pre_message(_checksum:u16, buffer:&Vec){ + println!("[SENDING ICMP DATA]\n"); + println!(" TY C0 CHECK ID SQ PAYLOAD----------> "); + println!("{}",rhexdump::hexdump(&buffer)); +} + +fn print_send_post_messages(bytes:usize, dest_addr:std::net::SocketAddr, checksum:u16){ + println!(" > Checksum [{:02x} {:02x}] - {} bytes sent to {}", (checksum&0xff00)>>8, (checksum)&0xff, bytes, dest_addr); +} + +fn print_recv_post_message(buf: &Vec, bytes_recv:usize, elapsed:Duration){ + // Parse the response from the destination. + let icmp_type = buf[0]; + let icmp_code = buf[1]; + let icmp_checksum = ((buf[2] as u16) << 8) | (buf[3] as u16); + let icmp_id = ((buf[4] as u16) << 8) | (buf[5] as u16); + let icmp_seq = ((buf[6] as u16) << 8) | (buf[7] as u16); + //let data = &buf[8..bytes_recv]; + + // Print the parsed response. + println!("\n[RECEIVING ICMP DATA] \n"); + println!(" TY C0 CHECK ID SQ PAYLOAD----------> "); + // println!("CHECKSUM: {:02x} {:02x}", (icmp_checksum&0xff00)>>8, (icmp_checksum)&0xff); + println!("{}",rhexdump::hexdump(&buf)); + println!(" > Checksum [{:02x} {:02x}] - \ + {} bytes recv over the socket in {:.2} milliseconds", + (icmp_checksum)>>8, (icmp_checksum)&0xff, + bytes_recv, (elapsed.as_micros() as f64)/1000. + ); + println!(" > icmp_type = {:width$} icmp_code = {:width$}", icmp_type, icmp_code, width=2); + println!(" > icmp_id = {:width$} icmp_seq = {:width$}", icmp_id, icmp_seq, width=2); + println!(); +} + +fn generate_payload(payload: &mut Vec,size:usize){ + // Generate a payload of size lenght + let mut rng = thread_rng(); + for _ in 0..(size-10){ + payload.push(rng.sample(Alphanumeric) as u8); + } +} \ No newline at end of file diff --git a/src/libs/socket.rs b/src/libs/socket.rs new file mode 100644 index 0000000..e69de29 diff --git a/src/main.rs b/src/main.rs index 858a546..33ba97e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,221 +1,89 @@ - //use dns_lookup::lookup_host; - use core::time::Duration; -use rand::{ - Rng, - thread_rng, - distributions::Alphanumeric, -}; -use std::time::Instant; +// Import libs -use std::{ - sync::Arc, - env, - io::{self}, - net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs}, -}; -use std::os::{ - unix::io::AsRawFd, - unix::io::FromRawFd -}; -//use env_logger::Env; + +//use dns_lookup::lookup_host; + +mod libs; +// mod test; fn main() { - //env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); + // env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); // Parse the command line arguments. - let (dest_addr,ping_request,data,payload, payload_size) = parse_all_arguments(); - - 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 (buffer, checksum) = create_buffer(ping_request,data,payload, 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 buffer2 = vec![0; 64]; - let result = socket_arc.send_to(&buffer, dest_addr); - match result { - Ok(bytes) => print_send_post_messages(bytes, dest_addr), - Err(err) => println!(" [ERROR] Failed to send data over the socket: {}", err) + 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); + match res { + Ok(()) => (), + Err(()) => eprintln!("Program exited with errors") } - - // Wait for a response from the destination. - let mut buf = vec![0; 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) { - Ok(res) => res, - Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { - println!(" [ERROR] No response from destination"); - println!(" [ERROR] {:?}", err); - std::process::exit(0); - } - Err(err) => panic!(" [ERROR] Error receiving data: {}", err), - }; - let elapsed = now.elapsed(); - - print_recv_post_message(&buf, bytes_recv, elapsed); } +// 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)); +// } -fn parse_all_arguments() -> (String,u16,u16,Vec, usize){ - // Load all inline arguments and change them in place - let args: Vec = env::args().collect(); - let mut ping_request : u16 = 0x0800; - let mut data : u16 = 0x0000; - let mut payload = Vec::::new(); - let mut payload_size : usize = 64; +// } - if args.len() == 1 { - exit_with_help(); - } - // let dest_ip=args[1].parse::().unwrap(); - let dest_addr= args[1].clone(); - for (i,arg) in args[1..].iter().enumerate(){ - if arg == "--help" || arg == "-h" { - exit_with_help(); - } else if arg == "--request" || arg == "-r" { - ping_request = args[i + 2].parse::().unwrap(); - } else if arg == "--data" || arg == "-d" { - data = args[i + 2].parse::().unwrap(); - } else if arg == "--payload" || arg == "-p" { - payload = args[i + 2].as_bytes().to_vec(); - } else if arg == "--size" || arg == "-s" { - payload_size = args[i + 2].parse::().unwrap(); - } - } - (dest_addr,ping_request, data, payload, payload_size) -} - -fn create_addresses(dest_ip: String) -> (SocketAddr, socket2::SockAddr, SocketAddr){ - // 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 dest_addr = (dest_ip,0).to_socket_addrs().unwrap().next().unwrap();//SocketAddr::new(IpAddr::V4(dest_ip), 0); - // let dest_addr = "dandaedre.com".to_socket_addrs().unwrap(); - (socket_ip_address, socket2_ip_address, dest_addr) -} - -fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::SockAddr) -> socket2::Socket { - let socket2_ipv4_socket = socket2::Socket::new( - socket2::Domain::IPV4, - socket2::Type::DGRAM, - Some(socket2::Protocol::ICMPV4), - ).unwrap(); - - // BIND TO LOCAL ADDRESS - socket2_ipv4_socket - .bind(&socket2_ip_address) - .expect(&format!( - "Failed binding to Ipv4 address {:?}", - &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) -> Arc { - // 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")); - - Arc::new(std_ipv4_socket) -} - -fn exit_with_help() { - eprintln!("Usage: cargo run --dest [--request/-r ] [--data/-d ] [--payload/-p ]"); - std::process::exit(1); -} - -fn create_buffer(ping_request: u16, data: u16, mut payload: Vec, payload_size : usize) -> (Vec,u16){ - // Create the ping request message. - let mut buf = vec![0u8; payload_size]; - let ping_request = [ - (ping_request >> 8) as u8, (ping_request & 0xff) as u8, // Type and Code fields - 0x00, 0x00, // Checksum (filled in later) - 0x00, 0x00, 0x00, 0x00, // Identifier and Sequence Number fields - ]; - buf[..ping_request.len()].copy_from_slice(&ping_request); - - // Add the data to the ping request message. - let data = [ - (data >> 8) as u8, (data & 0xff) as u8, - ]; - - if payload.len() == 0{ - generate_payload(&mut payload); - } - buf[ping_request.len()..(ping_request.len() + data.len())].copy_from_slice(&data); - buf[ping_request.len() + data.len()..(ping_request.len() + data.len()+payload.len())].copy_from_slice(&payload); - - // Calculate the checksum of the ping request message. - let checksum = calculate_checksum(&buf); - buf[2] = (checksum >> 8) as u8; - buf[3] = (checksum & 0xff) as u8; - (buf, checksum) -} - -fn calculate_checksum(buf : &Vec) -> u16 { - let checksum = { - let mut sum = 0; - for i in 0..(buf.len() / 2) { - sum += (buf[2 * i+1 ] as usize) << 8 | buf[2 * i] as usize; - } - if buf.len()%2==1 { sum += buf[buf.len()-1] as usize; } - while sum>>16!=0 { sum = (sum & 0xffff) + (sum >> 16) } - !(sum as u16) - }; - checksum -} - -fn print_send_pre_message(checksum:u16, buffer:&Vec){ - println!("[SENDING ICMP DATA]\n"); - println!("CHECKSUM: {:02x} {:02x}", (checksum&0xff00)>>8, (checksum)&0xff); - println!("{}",rhexdump::hexdump(&buffer)); -} - -fn print_send_post_messages(bytes:usize, dest_addr:std::net::SocketAddr){ - println!(" > {} bytes sent to {}", bytes, dest_addr); -} - -fn print_recv_post_message(buf: &Vec, bytes_recv:usize, elapsed:Duration){ - // Parse the response from the destination. - let icmp_type = buf[0]; - let icmp_code = buf[1]; - let icmp_checksum = ((buf[2] as u16) << 8) | (buf[3] as u16); - let icmp_id = ((buf[4] as u16) << 8) | (buf[5] as u16); - let icmp_seq = ((buf[6] as u16) << 8) | (buf[7] as u16); - //let data = &buf[8..bytes_recv]; - - // Print the parsed response. - println!("\n[ANALYSIS] \n"); - println!("CHECKSUM: {:02x} {:02x}", (icmp_checksum&0xff00)>>8, (icmp_checksum)&0xff); - println!("{}",rhexdump::hexdump(&buf)); - println!(" > {} bytes recv over the socket in {:.2} milliseconds", bytes_recv, (elapsed.as_micros() as f64)/1000.); - println!(" > icmp_type = {:width$} icmp_code = {:width$}", icmp_type, icmp_code, width=2); - println!(" > icmp_id = {:width$} icmp_seq = {:width$}", icmp_id, icmp_seq, width=2); - println!(); -} - -fn generate_payload(payload: &mut Vec/*,size:usize*/){ - // Generate a payload of size lenght - let mut rng = thread_rng(); - for _ in 0..54{ - payload.push(rng.sample(Alphanumeric) as u8); - } -} +// // Calculate the IPv4 header checksum +// fn calculate_checksum(header: &Ipv4Header) -> u16 { +// // TODO: Implement the checksum calculation +// } \ No newline at end of file