Refactored most of the code

This commit is contained in:
Dandaedre 2022-12-12 03:11:40 +01:00
parent 4564af6d77
commit 0ed323b536
7 changed files with 221 additions and 524 deletions

View File

@ -1,14 +1,16 @@
mod icmp;
mod args;
mod ipv4;
mod rp_icmp;
mod rp_args;
mod rp_ipv4;
pub use icmp::{
pub use rp_icmp::{
create_icmp_packet,
// generate_ping_request,
// calculate_checksum
};
pub use args::parse_all_arguments;
pub use ipv4::{
pub use rp_args::parse_all_arguments;
pub use rp_ipv4::{
create_ethernet_packet,
create_interface,
send_packet,
recv_packet,
};

View File

@ -1,248 +0,0 @@
// 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);
// }
// }

View File

@ -1,152 +0,0 @@
// Create an Ipv4 connection and have it ready to send IPv4 packets
use crate::libs::args::Config;
// use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
use pnet::packet::ipv4;
use pnet::packet::icmp;
use pnet::packet::Packet;
// use pnet_datalink::{
// self,
// MacAddr
// };
use pnet_transport::{
icmp_packet_iter,
transport_channel,
// TransportChannelType::Layer4,
// TransportProtocol::Ipv4,
TransportChannelType::Layer3,
TransportReceiver,
TransportSender,
};
use pnet::packet::ip::{
IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
};
use std::net::{IpAddr, Ipv4Addr};
use pnet::packet::icmp::{
echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
};
// Takes a config structure and generate a wrapper Packet, note that it will need to be filled with a payload
pub fn create_ethernet_packet<'a>(config: &'a Config) -> ipv4::MutableIpv4Packet<'a>{
let (mut tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
// let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) { // Non Raw
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("An error occurred when creating transport channel: {}", e),
};
// The total length is dependent on the packed sent
let size_tot: u16 = (config.ihl*4 + config.packet_size).into(); //84; // ihl*4+packet_size
let binding = vec![0; size_tot as usize];
let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::owned(binding).unwrap();
// let mut binding = [/*0x44 ,0xd4 ,0x53 ,0x93 ,0x8a ,0x90 ,0x54 ,0xaf ,0x97 ,0x4d ,0x13 ,0xbf ,0x08 ,0x00 ,*/
// 0x45 ,0x00,
// 0x00 ,0x54 ,0xcd ,0xdf ,0x40 ,0x00 ,0x40 ,0x01 ,0xe9 ,0x74 ,0xc0 ,0xa8 ,0x01 ,0x03 ,0xc0 ,0xa8,
// 0x01 ,0x01 ,0x08 ,0x00 ,0xba ,0x4c ,0x00 ,0x02 ,0x00 ,0x02 ,0xed ,0x04 ,0x95 ,0x63 ,0x00 ,0x00,
// 0x00 ,0x00 ,0xf6 ,0x73 ,0x06 ,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];
// let rethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).unwrap();
// IPv4
ethernet_packet.set_total_length(size_tot);
ethernet_packet.set_version(config.ipv4_version);
ethernet_packet.set_header_length(config.ihl);
ethernet_packet.set_dscp(config.dcsp);
ethernet_packet.set_ecn(config.ecn);
ethernet_packet.set_ttl(config.ttl);
ethernet_packet.set_identification(config.identification);
ethernet_packet.set_flags(config.flags);
ethernet_packet.set_fragment_offset(config.offset);
ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Icmp);//pnet_packet::ip::IpNextHeaderProtocol(6));
// Get the IP address of the interface
// let ip_addr = interface.ips.into_iter().next().unwrap();
//config.src_addr.parse
ethernet_packet.set_source(config.src_addr.parse::<Ipv4Addr>().expect("Couldn't parse source address"));
ethernet_packet.set_destination(config.dest_addr.parse::<Ipv4Addr>().expect("Couldn't parse destination address"));
ethernet_packet.set_checksum(ipv4::checksum(&ethernet_packet.to_immutable()));
// Send the Ethernet frame using the `ethernet::EthernetPacket::send` function
// println!("{:?} {:?}",rethernet_packet.packet(), rethernet_packet);
// assert_eq!(rethernet_packet.packet(),[69, 0, 0, 84, 205, 223, 64, 0, 64, 1, 233, 116, 192, 168, 1, 3, 192, 168, 1, 1, 8, 0, 186, 76, 0, 2, 0, 2, 237, 4, 149, 99, 0, 0, 0, 0, 246, 115, 6, 0, 0, 0, 0, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]);
// let res = tx.send_to(rethernet_packet, std::net::IpAddr::V4("192.168.1.1".parse::<Ipv4Addr>().expect("Couldn't parse source address")));
// println!("{:?}",res);
ethernet_packet
}
// Create a transmiter/receiver interface with the send_to, recv methods
pub fn create_interface(config: &Config) -> (TransportSender,TransportReceiver) {
// Get the default network interface // Should allow for selection
// let interfaces = pnet_datalink::interfaces();
// let interface = interfaces.into_iter().next().unwrap();
let (tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
// let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) { // Non Raw
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("An error occurred when creating transport channel: {}", e),
};
(tx,rx)
}
pub fn send_packet(packet: ipv4::Ipv4Packet, mut interface: TransportSender, dst: Ipv4Addr) -> Result<usize,std::io::Error>{
let res = interface.send_to(packet, std::net::IpAddr::V4(dst));
println!("{:?}",res);
res
}
fn main() {
// Get the default network interface
// let interfaces = pnet_datalink::interfaces();
// let interface = interfaces.into_iter().next().unwrap();
// let (mut tx, mut rx) = match transport_channel(1500, Layer3(IpNextHeaderProtocols::Udp)) {
let (mut tx, mut rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
// let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("An error occurred when creating transport channel: {}", e),
};
let mut recv = icmp_packet_iter(&mut rx);
// Create a new mutable ICMP packet
// let mut binding = [4;64];
// let mut packet = icmp::MutableIcmpPacket::new(&mut binding).expect("Couldn't create packet");
// let mut packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).expect("Couldn't create packet");
// // Set the ICMP packet type and code to the appropriate values for a ping request
// packet.set_icmp_type(icmp::IcmpTypes::EchoRequest);
// packet.set_icmp_code(pnet::packet::icmp::IcmpCode(0xaa));
// // let frozen = binding.clone();
// packet.set_checksum(pnet_packet::icmp::checksum(&packet.to_immutable()));
// // Get a `Packet` object representing the ping request packet
// let ping_request_packet = packet.packet();
// let IDENT_NUM: u16 = 111;
// Create a new mutable Ethernet packet containaing the ICMP packet
// let res = tx.send_to(ethernet_packet, std::net::IpAddr::V4(dst));
// println!("{:?}",res);
// match recv.next() {
// Ok((pkt, addr)) => {
// let pong = EchoReplyPacket::new(pkt.packet()).unwrap();
// if pong.get_icmp_type() == IcmpTypes::EchoReply
// && pong.get_identifier() == IDENT_NUM
// && pong.get_sequence_number() == 1
// {
// ()
// } else {
// ()
// }
// }
// Err(e) => eprintln!("Error: {} ", e),
// }
}

View File

@ -66,6 +66,13 @@ pub fn parse_all_arguments() -> Config {
config.raw_packet=true; // This enable raw packets but requires root privilege
}
}
//Sanitize inputs and show it
if config.payload.len()!=0{
println!("Corrected payload size, went from {} to {} according to given input",config.payload_size,config.payload.len()/4);
config.payload_size=config.payload.len()/4;
}
config
}

110
src/libs/rp_icmp.rs Normal file
View File

@ -0,0 +1,110 @@
use crate::libs::rp_args::Config;
// use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
// use pnet::packet::ipv4;
use pnet::packet::icmp;
// use pnet::packet::Packet;
// use pnet_datalink::{
// self,
// // MacAddr
// };
// use pnet_transport::{
// icmp_packet_iter, transport_channel, TransportChannelType::Layer4, TransportProtocol::Ipv4,
// TransportChannelType::Layer3
// };
// use pnet::packet::ip::{
// IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
// };
// use std::net::{IpAddr, Ipv4Addr};
// use pnet::packet::icmp::{
// echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
// };
use rand::{
thread_rng,
distributions::Alphanumeric,
Rng,
};
pub fn create_icmp_packet(config: &Config) -> icmp::MutableIcmpPacket{
// Create a new mutable ICMP packet
let mut binding = vec![0u8;config.packet_size as usize];
// Loading a custom Id, because I didn't want to split it into two functions
binding[4]=(config.identifier >> 8) as u8;
binding[5]=(config.identifier&0xff) as u8;
// Loading a custom Seq Number, because I didn't wat to split it into two
binding[6]=(config.sequence>>8) as u8;
binding[7]=(config.sequence&0xff) as u8;
let mut packet = icmp::MutableIcmpPacket::owned(binding).expect("Couldn't create packet");
// Set the ICMP packet type and code to the appropriate values for a ping request
packet.set_icmp_type(icmp::IcmpTypes::EchoRequest);
packet.set_icmp_code(pnet::packet::icmp::IcmpCode(0));
if config.payload.len()==0{
// let payload=vec![4u8;(config.packet_size-4).into()]; // For a fixed payload
let mut payload=Vec::<u8>::new();
// Loading a custom Id, because I didn't want to split it into two functions
payload.push((config.identifier >> 8) as u8);
payload.push((config.identifier&0xff) as u8);
// Loading a custom Seq Number, because I didn't wat to split it into two
payload.push((config.sequence>>8) as u8);
payload.push((config.sequence&0xff) as u8);
generate_payload(&mut payload, (config.packet_size).into());
packet.set_payload(&payload);
}
packet.set_checksum(pnet_packet::icmp::checksum(&packet.to_immutable()));
packet
}
// 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-8){
payload.push(rng.sample(Alphanumeric) as u8);
}
}

84
src/libs/rp_ipv4.rs Normal file
View File

@ -0,0 +1,84 @@
// Create an Ipv4 connection and have it ready to send IPv4 packets
use crate::libs::rp_args::Config;
// use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
use pnet::packet::ipv4;
// use pnet::packet::icmp;
use pnet::packet::Packet;
// use pnet_datalink::{
// self,
// MacAddr
// };
use pnet_transport::{
icmp_packet_iter,
transport_channel,
// TransportChannelType::Layer4,
// TransportProtocol::Ipv4,
TransportChannelType::Layer3,
TransportReceiver,
TransportSender,
};
// use pnet::packet::ip::{
// IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
// };
use std::net::{
// IpAddr,
Ipv4Addr
};
use pnet::packet::icmp::{
echo_reply::EchoReplyPacket,
// echo_request::MutableEchoRequestPacket, IcmpTypes,
};
// Takes a config structure and generate a wrapper Packet, note that it will need to be filled with a payload
pub fn create_ethernet_packet<'a>(config: &'a Config) -> ipv4::MutableIpv4Packet<'a>{
// The total length is dependent on the packed sent
let size_tot: u16 = (config.ihl*4 + config.packet_size).into(); //84; // ihl*4+packet_size
let binding = vec![0; size_tot as usize];
let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::owned(binding).unwrap();
// IPv4
ethernet_packet.set_total_length(size_tot);
ethernet_packet.set_version(config.ipv4_version);
ethernet_packet.set_header_length(config.ihl);
ethernet_packet.set_dscp(config.dcsp);
ethernet_packet.set_ecn(config.ecn);
ethernet_packet.set_ttl(config.ttl);
ethernet_packet.set_identification(config.identification);
ethernet_packet.set_flags(config.flags);
ethernet_packet.set_fragment_offset(config.offset);
ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Icmp);//pnet_packet::ip::IpNextHeaderProtocol(6));
ethernet_packet.set_source(config.src_addr.parse::<Ipv4Addr>().expect("Couldn't parse source address"));
ethernet_packet.set_destination(config.dest_addr.parse::<Ipv4Addr>().expect("Couldn't parse destination address"));
ethernet_packet.set_checksum(ipv4::checksum(&ethernet_packet.to_immutable()));
ethernet_packet
}
// Create a transmiter/receiver interface with the send_to, recv methods
pub fn create_interface(_config: &Config) -> (TransportSender,TransportReceiver) {
let (tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("An error occurred when creating transport channel: {}", e),
};
(tx,rx)
}
pub fn send_packet(packet: ipv4::Ipv4Packet, mut interface: TransportSender, dst: Ipv4Addr) -> Result<usize,std::io::Error>{
let res = interface.send_to(packet, std::net::IpAddr::V4(dst));
println!("{:?}",res);
res
}
pub fn recv_packet(mut interface: TransportReceiver){
let mut recv = icmp_packet_iter(&mut interface);
match recv.next() {
Ok((pkt, addr)) => {
let packet = EchoReplyPacket::new(pkt.packet()).unwrap();
println!("{:?}:{}",packet,addr);
}
Err(e) => eprintln!("Error: {} ", e),
}
}

View File

@ -3,131 +3,25 @@ use std::net::{
// IpAddr,
Ipv4Addr
};
// mod test;
use pnet::packet::Packet;
fn main() {
// Parse the command line arguments.
let config = libs::parse_all_arguments();
let packet = libs::create_ethernet_packet(&config);
let (rx, _tx) = libs::create_interface(&config);
let res = libs::send_packet(packet.to_immutable(),rx,config.dest_addr.parse::<Ipv4Addr>().expect("Couldn't parse the IpAddr"));
let mut packet = libs::create_ethernet_packet(&config);
packet.set_payload(libs::create_icmp_packet(&config).packet());
let (tx, rx) = libs::create_interface(&config);
let res = libs::send_packet(packet.to_immutable(),tx,config.dest_addr.parse::<Ipv4Addr>().expect("Couldn't parse the IpAddr"));
match res {
Ok(s) => println!("{:?}", s),
Err(e) => eprintln!("Program exited with errors {:?}",e)
}
libs::recv_packet(rx);
}
// use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
// use pnet::packet::ipv4;
// use pnet::packet::icmp;
// use pnet::packet::Packet;
// use pnet_datalink::{
// self,
// MacAddr
// };
// use pnet_transport::{
// icmp_packet_iter, transport_channel, TransportChannelType::Layer4, TransportProtocol::Ipv4,
// TransportChannelType::Layer3
// };
// use pnet::packet::ip::{
// IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
// };
// use std::net::{IpAddr, Ipv4Addr};
// use pnet::packet::icmp::{
// echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
// };
// fn main (){
// // Get the default network interface
// // let interfaces = pnet_datalink::interfaces();
// // let interface = interfaces.into_iter().next().unwrap();
// // let (mut tx, mut rx) = match transport_channel(1500, Layer3(IpNextHeaderProtocols::Udp)) {
// let (mut tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
// // let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) {
// Ok((tx, rx)) => (tx, rx),
// Err(e) => panic!("An error occurred when creating transport channel: {}", e),
// };
// // Get the IP address of the interface
// // let ip_addr = interface.ips.into_iter().next().unwrap();
// // Calculate the checksum of the ping request packet
// // let checksum = icmp::checksum(&[0; 0]);
// // let mut recv = icmp_packet_iter(&mut rx);
// // Create a new mutable ICMP packet
// // let mut binding = [4;64];
// // let mut packet = icmp::MutableIcmpPacket::new(&mut binding).expect("Couldn't create packet");
// // let mut packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).expect("Couldn't create packet");
// // // Set the ICMP packet type and code to the appropriate values for a ping request
// // packet.set_icmp_type(icmp::IcmpTypes::EchoRequest);
// // packet.set_icmp_code(pnet::packet::icmp::IcmpCode(0xaa));
// // // let frozen = binding.clone();
// // packet.set_checksum(pnet_packet::icmp::checksum(&packet.to_immutable()));
// // // Get a `Packet` object representing the ping request packet
// // let ping_request_packet = packet.packet();
// // let IDENT_NUM: u16 = 111;
// // Create a new mutable Ethernet packet containaing the ICMP packet
// let mut binding = [0; 84];
// // let mut binding = [/*0x44 ,0xd4 ,0x53 ,0x93 ,0x8a ,0x90 ,0x54 ,0xaf ,0x97 ,0x4d ,0x13 ,0xbf ,0x08 ,0x00 ,*/
// // 0x45 ,0x00,
// // 0x00 ,0x54 ,0xcd ,0xdf ,0x40 ,0x00 ,0x40 ,0x01 ,0xe9 ,0x74 ,0xc0 ,0xa8 ,0x01 ,0x03 ,0xc0 ,0xa8,
// // 0x01 ,0x01 ,0x08 ,0x00 ,0xba ,0x4c ,0x00 ,0x02 ,0x00 ,0x02 ,0xed ,0x04 ,0x95 ,0x63 ,0x00 ,0x00,
// // 0x00 ,0x00 ,0xf6 ,0x73 ,0x06 ,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];
// let size: u16 = binding.len().try_into().unwrap();
// let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).unwrap();
// // IPv4
// ethernet_packet.set_total_length(size);
// ethernet_packet.set_version(4);
// ethernet_packet.set_header_length(5);
// ethernet_packet.set_dscp(0);
// ethernet_packet.set_ecn(0);
// ethernet_packet.set_ttl(64);
// ethernet_packet.set_identification(52703);
// ethernet_packet.set_flags(2);
// ethernet_packet.set_fragment_offset(0);
// ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Icmp);//pnet_packet::ip::IpNextHeaderProtocol(6));
// ethernet_packet.set_source("192.168.1.3".parse::<Ipv4Addr>().expect("Couldn't set destination"));
// ethernet_packet.set_destination("192.168.1.1".parse::<Ipv4Addr>().expect("Couldn't set destination"));
// ethernet_packet.set_checksum(pnet::packet::ipv4::checksum(&ethernet_packet.to_immutable()));
// // Set the EtherType to indicate that the payload is an IP packet
// // ethernet_packet.set_ethertype(pnet::packet::ethernet::EtherType(0x0000));
// // Set the payload of the Ethernet packet to the ping request packet
// // ethernet_packet.set_payload(ping_request_packet);
// // Get an `EthernetPacket` object from the mutable Ethernet packet
// // let ethernet_frame = ethernet_packet.packet();
// // assert_eq!([69, 0, 0, 84, 205, 223, 64, 0, 64, 1, 233, 116, 192, 168, 1, 3, 192, 168, 1, 1, 8, 0, 186, 76, 0, 2, 0, 2, 237, 4, 149, 99, 0, 0, 0, 0, 246, 115, 6, 0, 0, 0, 0, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55],ethernet_packet.packet());
// // Send the Ethernet frame using the `ethernet::EthernetPacket::send` function
// let dst = "192.168.1.1".parse::<Ipv4Addr>().expect("");
// println!("{:?} {:?}",ethernet_packet.packet(), ethernet_packet);
// let res = tx.send_to(ethernet_packet, std::net::IpAddr::V4(dst));
// println!("{:?}",res);
// // match recv.next() {
// // Ok((pkt, addr)) => {
// // let pong = EchoReplyPacket::new(pkt.packet()).unwrap();
// // if pong.get_icmp_type() == IcmpTypes::EchoReply
// // && pong.get_identifier() == IDENT_NUM
// // && pong.get_sequence_number() == 1
// // {
// // ()
// // } else {
// // ()
// // }
// // }
// // Err(e) => eprintln!("Error: {} ", e),
// // }
// }