Compare commits
8 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
f83a8303dd | |
|
|
4fe25e4080 | |
|
|
0ed323b536 | |
|
|
4564af6d77 | |
|
|
e23791d4bb | |
|
|
1f9715b649 | |
|
|
89af0844ad | |
|
|
edfa28d947 |
|
|
@ -14,3 +14,5 @@ Cargo.lock
|
|||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
pkts.txt
|
||||
original.rs
|
||||
|
|
@ -6,11 +6,14 @@ edition = "2021"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
socket2 = { version = "0.4.7", features = ["all"] }
|
||||
env_logger = "0.10"
|
||||
rhexdump = "0.1.1"
|
||||
hex = " 0.4.3"
|
||||
argh = "0.1.9"
|
||||
rand = "0.8.5"
|
||||
#dns-lookup = "1.0.8"
|
||||
pnet = "0.31.0"
|
||||
pnet_datalink = "0.31.0"
|
||||
pnet_transport = "0.31.0"
|
||||
pnet_packet = "0.31.0"
|
||||
|
||||
[profile.release]
|
||||
strip = true # Automatically strip symbols from the binary.
|
||||
|
|
|
|||
22
src/libs.rs
22
src/libs.rs
|
|
@ -1,7 +1,19 @@
|
|||
mod icmp;
|
||||
mod args;
|
||||
mod rp_icmp;
|
||||
mod rp_args;
|
||||
mod rp_ipv4;
|
||||
|
||||
pub use icmp::{
|
||||
generate_ping_request
|
||||
pub use rp_icmp::{
|
||||
create_icmp_packet,
|
||||
// generate_ping_request,
|
||||
// calculate_checksum
|
||||
};
|
||||
pub use args::parse_all_arguments;
|
||||
pub use rp_args::{
|
||||
parse_all_arguments,
|
||||
get_payload_from_str,
|
||||
};
|
||||
pub use rp_ipv4::{
|
||||
create_ethernet_packet,
|
||||
create_interface,
|
||||
send_packet,
|
||||
recv_packet,
|
||||
};
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
use std::env;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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" {
|
||||
config.ping_type = args[i + 2].parse::<u8>().unwrap();
|
||||
} else if arg == "--identifier" || arg == "-i" {
|
||||
config.identifier = args[i + 2].parse::<u16>().unwrap();
|
||||
} else if arg == "--sequence" || arg == "-q" {
|
||||
config.sequence = args[i + 2].parse::<u16>().unwrap();
|
||||
} else if arg == "--payload" || arg == "-p" {
|
||||
config.payload = args[i + 2].as_bytes().to_vec();
|
||||
} else if arg == "--size" || arg == "-s" {
|
||||
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
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
fn exit_with_help() {
|
||||
eprintln!("Usage: cargo run --dest <destination IP address>
|
||||
[--type/-t <ping type>] The type of ping request 8 for IPv4 128 for IPv6 (8b)
|
||||
[--code/-c <code=0>] The mandatory 0 code (8b)
|
||||
[--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 ???
|
||||
[--raw] Enable raw packet, require root privileges
|
||||
");
|
||||
std::process::exit(1);
|
||||
}
|
||||
224
src/libs/icmp.rs
224
src/libs/icmp.rs
|
|
@ -1,224 +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
|
||||
);
|
||||
|
||||
// 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_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, 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; config.payload_size]; // Make that buffer arbitrary large
|
||||
let timeout = std::time::Duration::from_secs(1);
|
||||
|
||||
|
||||
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, elapsed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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::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
|
||||
));
|
||||
|
||||
socket2_ipv4_socket
|
||||
}
|
||||
|
||||
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"));
|
||||
*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.
|
||||
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<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<u8>, 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<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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
// use std::env;
|
||||
use argh::FromArgs;
|
||||
use hex;
|
||||
|
||||
#[derive(FromArgs)]
|
||||
/// rping, sending very custom icmp requests
|
||||
pub struct Config{
|
||||
/// the destination address for the request
|
||||
#[argh(positional)]
|
||||
pub dest_addr : String,
|
||||
|
||||
/// the source address for the request
|
||||
#[argh(option, default = "String::from(\"0.0.0.0\")")]
|
||||
pub src_addr : String,
|
||||
|
||||
/// the type of ping request
|
||||
#[argh(option, default = "8")]
|
||||
pub ping_type : u8,
|
||||
|
||||
/// the ping identifier u16 number
|
||||
#[argh(option, default = "0x4242")]
|
||||
pub identifier : u16,
|
||||
|
||||
/// the ping sequence u16 number
|
||||
#[argh(option, default = "0x0001")]
|
||||
pub sequence : u16,
|
||||
|
||||
/// the actual ping payload,
|
||||
#[argh(option, default = "String::new()")]
|
||||
pub payload : String,
|
||||
|
||||
/// the total icmp payload size
|
||||
#[argh(option, default = "64")]
|
||||
pub payload_size : usize,
|
||||
|
||||
/// force the usage of a raw packet
|
||||
#[argh(option, default = "false")]
|
||||
pub raw_packet : bool,
|
||||
|
||||
/// the packet size (excluding header)
|
||||
#[argh(option, default = "64")]
|
||||
pub packet_size : u8,
|
||||
|
||||
/// the ip version used (4 or 6)
|
||||
#[argh(option, default = "4")]
|
||||
pub ipv4_version : u8,
|
||||
|
||||
/// inter header length (must be >=5)
|
||||
#[argh(option, default = "5")]
|
||||
pub ihl : u8,
|
||||
|
||||
/// differentiated service code points
|
||||
#[argh(option, default = "0")]
|
||||
pub dcsp : u8,
|
||||
|
||||
/// explicit congestion notification
|
||||
#[argh(option, default = "0")]
|
||||
pub ecn : u8,
|
||||
|
||||
/// time to live
|
||||
#[argh(option, default = "64")]
|
||||
pub ttl: u8,
|
||||
|
||||
/// identification (lacking documentation)
|
||||
#[argh(option, default = "52703")]
|
||||
pub identification : u16,
|
||||
|
||||
/// flags : 2 don't fragment, 4 more fragments
|
||||
#[argh(option, default = "2")]
|
||||
pub flags : u8,
|
||||
|
||||
/// the fragment offset (if fragmented)
|
||||
#[argh(option, default = "0")]
|
||||
pub offset : u16,
|
||||
|
||||
}
|
||||
|
||||
|
||||
pub fn get_payload_from_str(inputp: &str) -> Vec<u8> {
|
||||
// If you start your payload by 0x all following will be parsed as hex (ignoring spaces)
|
||||
let mut payload = Vec::<u8>::new();
|
||||
payload.resize(0,4); // The identifier and sequence are in the payload for dumb reasons
|
||||
|
||||
if inputp.len()<2 {
|
||||
return payload
|
||||
}
|
||||
|
||||
if &inputp[..2]=="0x"{
|
||||
let nopx = inputp.trim_start_matches("0x");
|
||||
hex::decode_to_slice(nopx,&mut payload[4..]).expect("Couldn't parse the payload");
|
||||
} else {
|
||||
payload = inputp.as_bytes().to_vec();
|
||||
}
|
||||
payload
|
||||
}
|
||||
pub fn sanitize_config(config: &mut Config){
|
||||
// Expected behaviour is as follows:
|
||||
// If you specify a payload, it will increase the payload length and total length as needed
|
||||
// If you have length set longer than your payloads zeroes will be added as needed
|
||||
|
||||
// if config.payload.len()<=4{
|
||||
// config.payload.resize(config.payload_size+4,0); // Resize payload to match the size given
|
||||
// }
|
||||
// if config.packet_size
|
||||
// if config.payload.len()>=2{
|
||||
// if &config.payload[..2]=="0x"{
|
||||
// let nopx = config.payload.trim_start_matches("0x");
|
||||
// hex::decode_to_slice(nopx,&mut payload).expect("Couldn't parse the payload");
|
||||
// } else {
|
||||
// payload = config.payload.as_bytes().to_vec();
|
||||
// }
|
||||
// }
|
||||
// if config.packet_size < (config.payload.len()-4) as u8{
|
||||
// config.packet_size = (config.payload.len()-4) as u8;
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
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 = argh::from_env();
|
||||
|
||||
|
||||
//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
|
||||
mut_config
|
||||
}
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
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<'a>(config: &Config, icmp_payload: &Vec<u8>) -> icmp::MutableIcmpPacket<'a>{
|
||||
// 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));
|
||||
|
||||
packet.set_payload(&icmp_payload);
|
||||
// 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);
|
||||
// } else {
|
||||
// packet.set_payload(&config.payload.as_bytes());
|
||||
// }
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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(ðernet_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),
|
||||
}
|
||||
}
|
||||
25
src/main.rs
25
src/main.rs
|
|
@ -1,12 +1,25 @@
|
|||
// Import libs
|
||||
mod libs;
|
||||
// mod test;
|
||||
use std::net::{
|
||||
// IpAddr,
|
||||
Ipv4Addr
|
||||
};
|
||||
|
||||
use pnet::packet::Packet;
|
||||
|
||||
fn main() {
|
||||
// Parse the command line arguments.
|
||||
let res = libs::generate_ping_request(libs::parse_all_arguments());
|
||||
|
||||
let mut config = libs::parse_all_arguments();
|
||||
// let icmp_payload = libs::get_payload_from_config(&mut config);
|
||||
let mut packet = libs::create_ethernet_packet(&config);
|
||||
let payload = libs::create_icmp_packet(&config, &libs::get_payload_from_str(&config.payload));
|
||||
packet.set_payload(payload.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"));
|
||||
libs::recv_packet(rx);
|
||||
|
||||
match res {
|
||||
Ok(()) => (),
|
||||
Err(()) => eprintln!("Program exited with errors")
|
||||
Ok(s) => println!("{:?}", s),
|
||||
Err(e) => eprintln!("Program exited with errors {:?}",e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue