Crafting Dummy Packets with Scapy Using Python

Discover how to create custom dummy packets using Python's Scapy library to simulate network traffic, test firewall rules, and monitor latency. This tutorial covers practical examples for TCP, ICMP, and UDP packets, with real-world applications in network performance monitoring.
  · 8 min read · Updated nov 2024 · Ethical Hacking · Packet Manipulation Using Scapy

Turn your code into any language with our Code Converter. It's the ultimate tool for multi-language programming. Start converting now!

Introduction

Creating dummy packets in Python using Scapy is a powerful technique that enables network and cybersecurity professionals to simulate network traffic, test firewall rules, understand packet structures, or even simulate network attacks for ethical hacking purposes. Scapy, a Python library for packet manipulation, allows users to construct, decode, send, capture, and analyze network packets. 

In this tutorial, we’ll start with the basics: why you might need to create dummy packets, how Scapy can help you, and some examples to get you started. We’ll end with a practical scenario that demonstrates how these dummy packets can be useful in the real world.

Requirements:

For this demonstration, I’ll be making use of my Kali Linux as a virtual machine and Python3. I’ll also use Metasploitable briefly for testing at the end. We cover how to install and use Metasploitable here.

Why Craft Dummy Packets?

  1. Testing Firewalls and IDS/IPS Systems: Dummy packets allow you to test how well firewalls and intrusion detection/prevention systems handle different types of network traffic.
  2. Understanding Network Protocols: Dummy packets give a hands-on approach to understanding packet structures of different network protocols, which is essential for cybersecurity professionals.
  3. Penetration Testing: Dummy packets can simulate certain types of network attacks in a controlled environment, helping testers validate network defenses.

Before we begin, ensure that you have Scapy installed:

$ pip install scapy

Creating Simple Packets with Scapy

Scapy allows you to create various layers of network packets. Let's start by crafting a simple IP packet and adding layers as we go.

from scapy.all import IP, TCP, send

# Step 1: Creating a simple IP packet
packet = IP(dst="192.168.1.1")  # Setting the destination IP
print(packet.show())  # Display packet details

Result:

Adding a TCP Layer

After crafting an IP layer, you can add additional layers, such as TCP, UDP, or ICMP. Here’s an example where we add a TCP layer to simulate a connection attempt to a specific port:

# Step 2: Adding a TCP layer to the IP packet
packet = IP(dst="192.168.1.1") / TCP(dport=80, sport=12345, flags="S")
print(packet.show())

Here, we set:

  • dport as the destination port (port 80 for HTTP).
  • sport as the source port (chosen arbitrarily).
  • flags as "S" for SYN, which starts the TCP handshake.

Result:

Sending the Packet

Now that we’ve created a packet, let’s send it to the network. Please make sure to run it as root. As the root user is privileged to send a packet:

# Step 3: Sending the packet
send(packet)

The send() function transmits the packet over the network. This command sends the crafted packet with IP and TCP headers to the specified destination.

Result:

Crafting Custom Dummy Packets for Testing Purposes

Let’s dive into a few practical examples that demonstrate various packet customizations.

Example 1: ICMP Ping Packet

An ICMP packet, commonly used in ping operations, is useful for checking if a machine is reachable:

from scapy.all import ICMP

# Creating an ICMP Echo request packet
icmp_packet = IP(dst="192.168.1.1") / ICMP()
send(icmp_packet)

This sends an ICMP echo request to the target IP, similar to a ping command:

Example 2: UDP Packet

A UDP packet is useful for testing UDP services and understanding how firewalls handle UDP traffic:

from scapy.all import UDP

# Creating a UDP packet
udp_packet = IP(dst="192.168.1.1") / UDP(dport=53, sport=12345)
send(udp_packet)

In this case, dport is set to 53, the port used by DNS, as an example of a common UDP service:

Example 3: Testing Firewall Rules

Let’s say you’re testing firewall rules that should block all traffic to port 80 but allow traffic to port 53. Using dummy packets, you can verify that these rules are working as intended by crafting and sending packets with Scapy.

Step-by-Step:

  1. Create a packet targeting port 80 (should be blocked).
       blocked_packet = IP(dst="192.168.1.1") / TCP(dport=80, flags="S")
       send(blocked_packet)
  2. Create a packet targeting port 53 (should be allowed).
       allowed_packet = IP(dst="192.168.1.1") / UDP(dport=53)
       send(allowed_packet)
  3. Analyze responses: By observing network logs or using packet-capturing tools (like Wireshark), you can determine if your firewall rules are working correctly. If the packet to port 80 is dropped and the packet to port 53 is allowed, the firewall configuration is working as intended.

Just with these examples we can see how easy it is to use Scapy for packet crafting.

Real-World Application

In large-scale deployments, such as cloud applications or content delivery networks (CDNs), it's crucial to monitor and test network latency and reliability across various servers or regions. Crafting dummy packets with Scapy can help simulate network traffic to measure response times and determine if specific servers are experiencing delays or packet loss.

Latency and Packet Loss Monitoring Across Servers

Scenario

Imagine a company with a globally distributed network that serves a popular web application. To ensure optimal performance, the company needs to continuously monitor network latency between its servers to detect any performance issues in specific regions. By crafting and sending periodic dummy packets, network engineers can measure response times and detect if certain routes are slower than others or experiencing packet loss.

Implementation

  1. Define a List of Server IPs:  Collect the IP addresses of each server to which you want to send dummy packets. This will allow for a distributed latency test.
       server_ips = ["192.168.27.1", "192.168.17.129", "192.168.3.1"]
    The first IP is of my host machine. The second is of my Metasploitable machine and the third is a dummy IP address for testing purposes. Please run this code as a root user.
  2. Create and Send ICMP Packets (Ping) to Each Server:
    Using ICMP packets (similar to a ping), we can test latency to each server.
     from scapy.all import IP, ICMP, sr1
     import time
    
       def check_latency(ip):
           packet = IP(dst=ip) / ICMP()
           start_time = time.time()
           response = sr1(packet, timeout=2, verbose=0)
           end_time = time.time()
           
           if response:
               latency = (end_time - start_time) * 1000  # Convert to milliseconds
               print(f"[+] Latency to {ip}: {latency:.2f} ms")
           else:
               print(f"[-] No response from {ip} (possible packet loss)")
    
       for server_ip in server_ips:
           check_latency(server_ip)
    Result:

  3. Schedule Periodic Checks:
    By running this script at regular intervals (e.g., every 10 minutes), you can collect latency data over time. This is particularly useful for identifying intermittent issues.
  4. Analyze Results and Set Alerts:
    Based on the latency measurements, you can set thresholds for acceptable response times. For example, if latency to any server exceeds 100 ms consistently, you may want to trigger an alert. Additionally, if no response is received, it might indicate packet loss or connectivity issues to that server.

Practical Benefits

  • Identify Network Bottlenecks: Regularly measuring latency can help locate network congestion or underperforming routes.
  • Monitor Server Health: Absence of responses (packet loss) can signal downtime or network isolation issues with specific servers.
  • Enhance User Experience: By identifying slow paths or unresponsive servers, network engineers can take proactive steps to reroute traffic, ensuring that users always connect to the fastest available server.

Conclusion

Using Scapy to craft dummy packets for testing is advantageous because it provides flexibility. You can customize packets to test specific network protocols (TCP, ICMP, UDP), simulate different types of traffic, and even set custom IP headers for advanced testing, such as emulating different geographic origins or network configurations.

Related Tutorials

We have lots of tutorials that use Scapy to build different tools. You can check them here.

I hope you enjoyed this one!

Finished reading? Keep the learning going with our AI-powered Code Explainer. Try it now!

View Full Code Generate Python Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!