Scapy — Made Easy
Scapy is a packet manipulation tool for computer networks, originally written in Python by Philippe Biondi. It can forge or decode packets, send them on the wire, capture them, and match requests and replies. It can also handle tasks like scanning, tracerouting, probing, unit tests, attacks, and network discovery — Wikipedia
Now that the introduction is done, let's dig in. Please make sure that you have python3 and scapy installed.
1. Capturing packets and writing to a PCAP file
from scapy.all import *sniffed_packets = sniff(timeout = 60,iface="<your interface>")
wrpcap("temp.pcap",test)for packet in sniffed_packets:
print(packet.show())
Since the timeout is specified as 60, this program would capture packets on the interface specified for 60 seconds. Make sure that you have ‘sudo’ permission when running this program as the function sniff would mostly require admin rights.
sudo python3 <filename.py>
2. Reading from a PCAP file
from scapy.all import *data= "<file-name.pcap>"
packets=rdpcap(data)for packet in packets:
print(packet.show())
This would print out all the details of each individual packet in the pcap file you have specified.
3. Grabbing payload information
from scapy.all import *
data= "<file-name.pcap>"
packets=rdpcap(data)
for packet in packets:
try:
print(packet[TCP].payload)
except:
pass
Here I’m using try and except because there could be packets other than TCP which might cause an error that will just be avoided here. You can grab source IP, destination IP, all the necessary information from the variable ‘packet’.
4. Matching payload and regular expressions
from scapy.all import *sniffed_packets = sniff(timeout = 60,iface="<your interface>")
count=0for packet in sniffed_packets:
try:
str_payload= re.escape((str(bytes(packet[TCP].payload))))
signature = re.search(r"\\\\...\\\\...\\\\x00\\\\x00\\\\x06\\\\x01", str_payload)
if signature is not None:
print(packet[IP].src)
print(packet[IP].dst)
except:
pass
This would go through each packet and identifies the packet with the specified signature. Then would print the source and destination IP address of the packet(should have ‘sudo’ rights to run this program).