Network Packet Analysis with Scapy

Loading

Introduction to Scapy

Scapy is a powerful Python library used for network packet analysis, sniffing, crafting, and manipulation. It allows security professionals, network engineers, and researchers to analyze network traffic, build custom packets, and perform penetration testing.

Installing Scapy

Install Scapy using pip:

pip install scapy

For Linux users, run:

sudo apt-get install scapy

1. Capturing Network Packets (Sniffing)

You can sniff packets to analyze network activity.

from scapy.all import sniff

# Function to process captured packets
def packet_callback(packet):
print(packet.summary()) # Print packet details

# Sniff 10 packets from the network
sniff(prn=packet_callback, count=10)

sniff() → Captures packets
prn=packet_callback → Calls a function to process each packet
count=10 → Captures only 10 packets

Capturing Packets on a Specific Interface

sniff(iface="eth0", count=5, prn=lambda x: x.summary())

iface="eth0" → Captures packets on Ethernet (eth0), can be changed to wlan0 for WiFi.


2. Filtering Packets (Capturing Specific Traffic)

Scapy allows you to filter packets based on protocol, IP, or port.

Sniff Only HTTP or TCP Packets

sniff(filter="tcp", count=5, prn=lambda x: x.summary())

✔ Uses BPF (Berkeley Packet Filter) syntax.
✔ Examples:

  • "icmp" → Capture only ping (ICMP) packets
  • "port 80" → Capture only HTTP traffic

3. Analyzing Packet Structure

Captured packets contain multiple layers like Ethernet, IP, TCP, etc.

packet = sniff(count=1)[0]  # Capture one packet
packet.show() # Display full packet details

packet.show() → Prints detailed packet layers and fields.


4. Extracting Information from Packets

You can extract source & destination IP, ports, and protocols.

def process_packet(packet):
if packet.haslayer("IP"): # Check if packet has an IP layer
print(f"Source IP: {packet['IP'].src} → Destination IP: {packet['IP'].dst}")
if packet.haslayer("TCP"):
print(f"Source Port: {packet['TCP'].sport} → Destination Port: {packet['TCP'].dport}")

sniff(count=5, prn=process_packet)

✔ Extracts IP addresses and TCP port numbers.
packet['IP'].src → Source IP
packet['TCP'].sport → Source Port


5. Sending Custom Packets

You can craft and send packets using Scapy.

Sending a Custom ICMP Ping

from scapy.all import IP, ICMP, send

# Create a Ping (ICMP) packet
packet = IP(dst="192.168.1.1") / ICMP()
send(packet)

Sends a ping (ICMP request) to a target.
IP(dst="192.168.1.1") → Target IP.

Sending a TCP SYN Packet (Port Scanning)

from scapy.all import IP, TCP, send

packet = IP(dst="192.168.1.1") / TCP(dport=80, flags="S")
send(packet)

Initiates a SYN scan to check if port 80 is open.
✔ Useful for penetration testing.


6. Performing Network Scanning

Scapy can be used to scan live hosts on a network.

from scapy.all import ARP, Ether, srp

target_ip = "192.168.1.1/24" # Scan entire subnet
packet = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=target_ip)

result, _ = srp(packet, timeout=2, verbose=False)

for sent, received in result:
print(f"IP: {received.psrc} - MAC: {received.hwsrc}")

ARP scanning for live hosts.
192.168.1.1/24 → Scans an entire subnet.
✔ Returns IP & MAC addresses of devices.


7. Extracting HTTP Traffic (MITM Attack Simulation)

Scapy can capture HTTP requests.

from scapy.all import sniff, Raw
from scapy.layers.http import HTTPRequest # Import HTTP layer

def process_packet(packet):
if packet.haslayer(HTTPRequest): # Check if it's an HTTP request
print(f"URL: {packet[HTTPRequest].Host.decode()}{packet[HTTPRequest].Path.decode()}")
if packet.haslayer(Raw):
print(f"Data: {packet[Raw].load.decode(errors='ignore')}")

sniff(filter="tcp port 80", prn=process_packet, store=False)

✔ Captures HTTP requests & extracts URLs and form data.
✔ Only works on unencrypted HTTP traffic (port 80).


8. Detecting Network Attacks (Intrusion Detection)

Scapy can detect suspicious traffic, such as excessive ping requests (DDoS attack).

from scapy.all import sniff

packet_counts = {}

def detect_attack(packet):
if packet.haslayer("IP"):
src_ip = packet["IP"].src
packet_counts[src_ip] = packet_counts.get(src_ip, 0) + 1
if packet_counts[src_ip] > 50: # Threshold for attack
print(f"Potential attack detected from: {src_ip}")

sniff(prn=detect_attack, store=False)

✔ If an IP sends >50 packets in a short time, it’s flagged as an attack.
✔ Useful for detecting DDoS & port scanning.


9. Writing Captured Packets to a File (PCAP Format)

To save packets for later analysis:

from scapy.all import sniff, wrpcap

packets = sniff(count=100) # Capture 100 packets
wrpcap("captured_traffic.pcap", packets) # Save to PCAP file

✔ Saves network traffic for Wireshark analysis.

Reading a PCAP File

from scapy.all import rdpcap

packets = rdpcap("captured_traffic.pcap")
for packet in packets:
print(packet.summary())

✔ Reads and analyzes previously saved packets.


10. Automating Packet Analysis (Real-time Monitoring)

Run Scapy continuously to monitor suspicious network activity.

def monitor_traffic(packet):
if packet.haslayer("IP") and packet["IP"].dst == "192.168.1.100":
print(f"Alert! Traffic to suspicious IP: {packet.summary()}")

sniff(prn=monitor_traffic, store=False)

✔ Alerts when traffic is sent to a specific IP.

Leave a Reply

Your email address will not be published. Required fields are marked *