rping/src/libs/icmp.rs

248 lines
10 KiB
XML

// use crate::libs::args::Config;
// use core::time::Duration;
// use rand::{
// Rng,
// thread_rng,
// distributions::Alphanumeric,
// };
// use std::time::Instant;
// use std::{
// io::{self},
// net,
// net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs},
// };
// use std::os::{
// unix::io::AsRawFd,
// 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(config : crate::libs::args::Config) -> Result<(),()>{
// 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(
// config.ping_type,
// config.identifier,
// config.sequence,
// config.payload,
// config.payload_size
// );
// let buffer = [0xd8 ,0xcb ,0x8a ,0xc1 ,0x1b ,0xac ,0x54 ,0xaf ,0x97 ,0x4d ,0x13 ,0xbf ,0x08 ,0x00 ,0x45 ,0x00
// ,0x00 ,0x54 ,0x68 ,0xc4 ,0x40 ,0x00 ,0x40 ,0x01 ,0x4e ,0x84 ,0xc0 ,0xa8 ,0x01 ,0x03 ,0xc0 ,0xa8
// ,0x01 ,0x0d ,0x08 ,0x00 ,0xbe ,0x7a ,0x00 ,0x04 ,0x00 ,0x01 ,0x90 ,0x19 ,0x95 ,0x63 ,0x00 ,0x00
// ,0x00 ,0x00 ,0x47 ,0x30 ,0x0e ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x10 ,0x11 ,0x12 ,0x13 ,0x14 ,0x15
// ,0x16 ,0x17 ,0x18 ,0x19 ,0x1a ,0x1b ,0x1c ,0x1d ,0x1e ,0x1f ,0x20 ,0x21 ,0x22 ,0x23 ,0x24 ,0x25
// ,0x26 ,0x27 ,0x28 ,0x29 ,0x2a ,0x2b ,0x2c ,0x2d ,0x2e ,0x2f ,0x30 ,0x31 ,0x32 ,0x33 ,0x34 ,0x35
// ,0x36 ,0x37];
// // Send the ping request to the specified destination IP address.
// print_send_pre_message(checksum, &buffer.to_vec());
// socket_final.connect(&addr.socket2_addr).expect("Couldn't connect the socket to remote host");
// // Starting the timer
// let now = Instant::now();
// let result = socket_final.send_to(&buffer, &addr.socket2_addr);
// // let result = socket_arc.send_to_with_flags(&buffer, dest_addr, 0);
// match result {
// 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::new();
// // buf.reserve(config.payload_size); // Make that buffer arbitrary large;
// use std::mem::MaybeUninit;
// let mut buf = Vec::<std::mem::MaybeUninit<u8>>::new();
// let mut buff = MaybeUninit::<Vec<u8>>::uninit();
// buf.reserve(config.payload_size);
// // unsafe { make_uninit_vec(v.as_mut_ptr(),config.payload_size); }
// // let mut buf : socket2::MaybeUninitSlice = socket2::MaybeUninitSlice::from(buf);
// let timeout = std::time::Duration::from_secs(1);
// socket_final.set_nonblocking(false);
// let bytes_recv=socket_final.recv(&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");
// // 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.expect(""), elapsed);
// Ok(())
// }
// // fn make_uninit_vec(out: *mut Vec<i32>, size:usize) {
// // }
// fn create_addresses(dest_ip: &String) -> SocketAddresses{
// // SOURCE IP ADDRESS
// let localhost = Ipv4Addr::UNSPECIFIED;
// let socket1_addr = SocketAddr::new(IpAddr::V4(localhost), 80);
// let socket2_addr = socket1_addr.into();
// 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 {
// let socket2_ipv4_socket = socket2::Socket::new(
// socket2::Domain::IPV4,
// socket2::Type::RAW,
// 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
// ));
// socket2_ipv4_socket
// }
// fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> socket2::Socket {
// // 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"));
// socket2::Socket::from(std_ipv4_socket)
// //Arc::new(std_ipv4_socket)
// }
// fn create_socket_raw(config: &Config, _socket2_ipv4_socket: &mut socket2::Socket) -> 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)
// 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.
// 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)
// }
// pub fn calculate_checksum(buf : &Vec<u8>) -> 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<u8>){
// 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<std::mem::MaybeUninit<u8>>, bytes_recv:usize, elapsed:Duration){
// // Parse the response from the destination.
// // unsafe {buf.assume_init()};
// println!("Received {} bytes in {:?} {:?}",bytes_recv, elapsed, buf);
// // 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<u8>,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);
// }
// }