Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.63 KB | None | 0 0
  1. use std::io;
  2. use std::collections::HashMap;
  3. ust std::net::Ipv4Addr;
  4.  
  5. mod tcp
  6. ;
  7. struct Quad {
  8.     src: (Ipv4Addr, u16),
  9.     dst: (Ipv4Addr, u16)
  10. }
  11.  
  12. fn main() -> io::Result<()> {
  13.     let mut connections: HashMap<Quad, tcp::State> = Default::default();
  14.  
  15.   let nic = tun_tap::Iface::new("tun0", tun_tap::Mode::Tun)?;
  16.   let mut buf = [0u8; 1504];
  17.   loop {
  18.       let nbytes = nic.recv(&mut buf[..])?;
  19.       let eth_flags = u16::from_be_bytes([buf[0], buf[1]]);
  20.       let eth_protocol = u16::from_be_bytes([buf[2], buf[3]]);
  21.       if eth_protocol != 0x0800 {
  22.         println!("Got non-ipv4 protocol");
  23.         continue; // ethernet protocol is not ipv4
  24.       }
  25.  
  26.       match etherparse::Ipv4HeaderSlice::from_slice(&buf[4..nbytes]) {
  27.         Ok(ip_header) => {
  28.               let src = ip_header.source_addr();
  29.               let dst = ip_header.destination_addr();
  30.  
  31.               if ip_header.protocol() != 0x06 { // Protocol has to be TCP
  32.                 continue;
  33.               }
  34.  
  35.               match etherparse::TcpHeaderSlice::from_slice(&buf[4+ip_header.slice().len()..]) {
  36.                 Ok(tcp_header) => {
  37.                     let data_i = 4 + ip_header.slice().len() + tcp_header.slice().len();
  38.                     connections.entry(Quad {
  39.                         src: (src, p.source_port()),
  40.                         dst: (dst, p.destination_port()),
  41.                     }).or_default().on_packet(ip_header, tcp_header, &buf[data_i..]);
  42.                     // (srcip, srcport, dstip, dstport)
  43.                       eprintln!("{} -> {} - {} bytes of TCP to port {}",    src, dst,   tcp_header.slice().len(), tcp_header.destination_port());
  44.                 },
  45.                 Err(e) => {
  46.                     eprintln!("Ignoring TCP packet {:?}", e);
  47.                 }
  48.               }
  49.         },
  50.         Err(e) => {
  51.             eprintln!("Ignoring weird packet {:?}", e);
  52.         }
  53.       }
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement