DevNotes

Concise, Handy and Elegant Notes for Developers

0%

Capture Network Packet

Tcpdump is a very useful tool to capture network packets.
e.g. to capture TCP packet from interface lo0 via port 9999

1
sudo tcpdump -i lo0 port 9999 -XX -v

Here demostrate sending some UDP packets, using tcpdump to capture them and using Tcpreplay to playback.

  1. Send some UDP packets via port 9999
  2. Listen UDP packets from port 9999
  3. Capture UDP packet using Tcpdump, save captured packets into a file
  4. Playback captured packets
  5. Listen UDP packets to verify

Let’s have more fun! Assuming we have captured some UDP packets using the command below:

1
sudo tcpdump -i en0 udp port 3333 -XX -v -w li.pcap

Then we use tcprewrite command to reverse the source and destination.

And if we double check the modified .pcap file, it shows as we want.

I also wrote a shell script to rewrite the network package automatically.

#!/bin/bash
usage()
{
printf "\n"
printf "Usage: $0 [-h] [-f]\n";
printf " -h : Display this help.\n";
printf " -f : INPUT FILE name.\n";
printf " -i : Destination IP address.\n";
printf " -m : Destination MAC address.\n";
printf "\n"
printf "Example:\n"
printf "$0 -f filename.pcap -i 192.168.0.16 -m 68:01:A7:B2:13:0A\n"
exit 0
}
if [ $# -eq 0 ]
then
echo "No arguments supplied"
usage
exit 1
fi
while getopts ':f:i:m:h' option
do
case "${option}"
in
f) FILE=${OPTARG};;
i) DST_IP=${OPTARG};;
m) DST_MAC=${OPTARG};;
h) usage;;
\?)echo "Invalid option: -$OPTARG" >&2
usage
exit 1
;;
:) echo "Option $OPTARG requires an argument." >&2
usage
exit 1
;;
esac
done
[ -z "$FILE" ] && echo "INPUT FILE should not be empty!" && usage && exit 1
[ -z "$DST_IP" ] && echo "DEST IP should not be empty!" && usage && exit 1
[ -z "$DST_MAC" ] && echo "DEST MAC not be empty!" && usage && exit 1
unameOut="$(uname -s)"
case "${unameOut}" in
Linux*) SRC_MAC=$(ifconfig | grep -Eo 'HWaddr ([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | awk '{print $2}');;
Darwin*) SRC_MAC=$(ifconfig en0 | grep -Eo '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}');;
esac
SRC_IP=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1')
tcprewrite --infile=$FILE --outfile=temp1.pcap --dstipmap=0.0.0.0/0:$DST_IP --enet-dmac=$DST_MAC
tcprewrite --infile=temp1.pcap --outfile=temp2.pcap --srcipmap=0.0.0.0/0:$SRC_IP --enet-smac=$SRC_MAC
tcprewrite --infile=temp2.pcap --outfile=final.pcap --fixcsum
rm temp1.pcap temp2.pcap
echo "New file is generated!"
echo "Now run the command below to replay the data."
echo "sudo tcpreplay --intf1=en0 final.pcap"
echo "Interface(intf1) could be eth0, eth1 or en0 or others, run ifconfig command to check what you have on you machine."

References: