Kinda working, A lot of undocumented stuff to figure out

This commit is contained in:
Dandaedre 2022-12-11 16:56:04 +01:00
parent 2e0cab46f7
commit edfa28d947
5 changed files with 335 additions and 52 deletions

View File

@ -10,6 +10,12 @@ socket2 = { version = "0.4.7", features = ["all"] }
env_logger = "0.10"
rhexdump = "0.1.1"
rand = "0.8.5"
pnet = "0.31.0"
pnet_datalink = "0.31.0"
pnet_transport = "0.31.0"
pnet_packet = "0.31.0"
libc = "0.2.138"
#dns-lookup = "1.0.8"
[profile.release]

View File

@ -2,6 +2,7 @@ mod icmp;
mod args;
pub use icmp::{
generate_ping_request
generate_ping_request,
calculate_checksum
};
pub use args::parse_all_arguments;

View File

@ -57,6 +57,7 @@ fn exit_with_help() {
[--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
[--hex] Read value as hex (no spaces)
");
std::process::exit(1);
}

View File

@ -27,7 +27,7 @@ struct SocketAddresses{
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 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),
@ -40,13 +40,21 @@ pub fn generate_ping_request(config : crate::libs::args::Config) -> Result<(),()
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);
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.dest_addr);
let result = socket_final.send_to(&buffer, &addr.socket2_addr);
// let result = socket_arc.send_to_with_flags(&buffer, dest_addr, 0);
match result {
@ -55,26 +63,38 @@ pub fn generate_ping_request(config : crate::libs::args::Config) -> Result<(),()
}
// Wait for a response from the destination.
let mut buf = vec![0; config.payload_size]; // Make that buffer arbitrary large
// 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),
};
// 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);
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;
@ -85,10 +105,10 @@ fn create_addresses(dest_ip: &String) -> SocketAddresses{
SocketAddresses {socket1_addr, socket2_addr, dest_addr}
}
fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::SockAddr) -> socket2::Socket {
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,
socket2::Type::RAW,
Some(socket2::Protocol::ICMPV4),
).unwrap();
@ -103,7 +123,7 @@ fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address:socket2::Sock
socket2_ipv4_socket
}
fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> std::net::UdpSocket/*socket2::Socket,std::net::UdpSocketArc<std::net::UdpSocket>*/ {
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) };
@ -111,11 +131,11 @@ fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> std::net::Udp
std_ipv4_socket
.set_read_timeout(Some(Duration::from_millis(100)))
.expect(&format!("Failed to set read timeout"));
*Box::new(std_ipv4_socket)
socket2::Socket::from(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*/{
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,
@ -133,10 +153,12 @@ fn create_socket_raw(config: &Config, _socket2_ipv4_socket: &mut socket2::Socket
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)
//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){
@ -168,7 +190,7 @@ fn create_buffer(ping_type: u8, identifier: u16, sequence: u16, mut payload: Vec
(buf, checksum)
}
fn calculate_checksum(buf : &Vec<u8>) -> u16 {
pub fn calculate_checksum(buf : &Vec<u8>) -> u16 {
let checksum = {
let mut sum = 0;
for i in 0..(buf.len() / 2) {
@ -191,28 +213,30 @@ fn print_send_post_messages(bytes:usize, dest_addr:std::net::SocketAddr, checksu
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){
fn print_recv_post_message(buf: &Vec<std::mem::MaybeUninit<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];
// 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!();
// // 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){

View File

@ -2,11 +2,262 @@
mod libs;
// mod test;
// fn main() {
// // Parse the command line arguments.
// let res = libs::generate_ping_request(libs::parse_all_arguments());
// match res {
// Ok(()) => (),
// Err(()) => eprintln!("Program exited with errors")
// }
// }
// use pnet::packet::icmp::{
// echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
// };
// use pnet::packet::ip::IpNextHeaderProtocols::Icmp;
// use pnet::packet::Packet;
// use pnet_transport::{
// icmp_packet_iter, transport_channel, TransportChannelType::Layer4, TransportProtocol::Ipv4,
// };
// use pnet::util::checksum;
// use std::net::{IpAddr, Ipv4Addr};
// use std::sync::atomic::{AtomicBool, Ordering};
// use std::sync::{Arc, Mutex};
// use std::time::{Duration, Instant};
// /// The ping function of this program
// pub fn main() {
// // Create a channel to send ping packets
// 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),
// };
// // Typical ICMP packet size
// let mut payload = [0u8; 64];
// let input = Arc::new("192.168.1.3");
// // Iterate through received ping packets
// let dst = input.parse::<Ipv4Addr>().expect("");
// let mut recv = icmp_packet_iter(&mut rx);
// // Random identifier
// const IDENT_NUM: u16 = 111;
// const TTL: u8 = 64;
// let counter = Arc::new(Mutex::new(0));
// let packet_loss = Arc::new(Mutex::new(0));
// let time: Arc<Mutex<Vec<f64>>> = Arc::new(Mutex::new(Vec::new()));
// let stop = Arc::new(AtomicBool::from(false));
// // Mimicking the `ping` utility in unix
// println!(
// "PING {}: {}({}) data bytes",
// // See if input is a domain name or IP address, and output accordingly
// if input.to_string() == dst.to_string() {
// dst.to_string()
// } else {
// format!("{} ({})", input, dst)
// },
// payload.len(),
// payload.len() - 8
// );
// let mut ping = MutableEchoRequestPacket::new(&mut payload).unwrap();
// ping.set_icmp_type(IcmpTypes::EchoRequest);
// ping.set_payload(b"hello");
// ping.set_identifier(IDENT_NUM);
// ping.set_sequence_number(*counter.lock().unwrap());
// ping.set_checksum(checksum(ping.packet(), 1));
// let curr_time = Instant::now();
// tx.set_ttl(TTL).unwrap();
// tx.send_to(ping, std::net::IpAddr::V4(dst)).expect("");
// 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() == *counter.lock().unwrap()
// {
// let elapsed = curr_time.elapsed();
// *counter.lock().unwrap() += 1;
// time.lock()
// .unwrap()
// .push(elapsed.as_micros() as f64 / 1000 as f64);
// println!(
// "{} bytes from {}: icmp_seq={} ttl={} time={:.1} ms",
// payload.len() - 8,
// // Same as above
// if input.to_string() == addr.to_string() {
// addr.to_string()
// } else {
// format!("{} ({})", input, addr)
// },
// counter.lock().unwrap(),
// TTL,
// elapsed.as_micros() as f64 / 1000 as f64
// );
// } else {
// *packet_loss.lock().unwrap() += 1;
// }
// }
// Err(e) => eprintln!("Error: {} ", e),
// }
// }
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() {
// Parse the command line arguments.
let res = libs::generate_ping_request(libs::parse_all_arguments());
match res {
Ok(()) => (),
Err(()) => eprintln!("Program exited with errors")
}
}
// 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, 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");
// // 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 = [3; 64+32];
let mut ethernet_packet = MutableEthernetPacket::new(&mut binding).unwrap();
// ethernet_packet.set_icmp_type();
// Set the destination and source MAC addresses
ethernet_packet.set_destination(interface.mac.unwrap().clone());
ethernet_packet.set_source(interface.mac.unwrap());
// 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();
// 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.payload());
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),
}
}
// use std::io;
// use std::os::unix::io::AsRawFd;
// use libc::{AF_PACKET, SOCK_RAW, socket, sockaddr, sendto};
// fn main() -> io::Result<()> {
// // Create a new raw socket
// let socket = unsafe {
// socket(
// AF_PACKET,
// SOCK_RAW,
// libc::ETH_P_ALL
// )
// };
// if socket < 0 {
// println!("Couldn't build socket");
// return Err(io::Error::last_os_error());
// }
// // Set the write timeout to None
// // (not possible with the libc crate, so we have to use blocking I/O)
// // Create a byte array containing the data to be sent
// let data = [1, 2, 3, 4, 5];
// // Call the send_to method, specifying the destination MAC address
// let num_bytes = unsafe {
// sendto(
// socket,
// data.as_ptr() as *const libc::c_void,
// data.len() as libc::size_t,
// 0,
// &sockaddr {
// sa_family: AF_PACKET as u16,
// sa_data: [
// libc::ETH_P_ALL as i8,
// 0,
// 0,
// 0,
// 6,
// 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 1],
// } as *const sockaddr,
// std::mem::size_of::<sockaddr>() as libc::socklen_t
// )
// };
// if num_bytes < 0 {
// println!("No bytes were sent");
// return Err(io::Error::last_os_error());
// }
// println!("Successfully wrote {} bytes to the socket at layer 2.", num_bytes);
// Ok(())
// }