Marcio Cunha

How to simulate malicious traffic in Linux with Scapy rules

Learn how to craft custom network packets in Linux using Scapy to test the effectiveness of corporate firewalls and detect traffic anomalies.

Marcio Cunha•4 min
Also available in:PortuguêsEspañol
Summary
  • Scapy acts as a flexible Python framework for low-level network packet manipulation and crafting.
  • Controlled packet injection validates whether packet filtering rules and firewalls block real threats accurately.
  • Proper use of Linux raw sockets requires superuser privileges to intercept and inject frames directly.
  • Anomaly analysis requires understanding custom TCP/IP headers and modified flags for inspection bypass.
  • Systematic attack simulation prevents operational surprises by exposing security gaps before real incidents.

Why test firewalls with simulated traffic?

In enterprise network engineering, relying solely on theory and default firewall rules is a quiet invitation to security gaps. When we configure defense systems, we assume they block unwanted access, but we rarely validate this premise in practice. This is precisely where controlled traffic injection comes in, allowing you to fire tailored forged packets to test the behavior of security devices. Before investing in complex tools, infrastructure validation shares similarities with advanced diagnostic techniques, such as how to track corrupted network packets in Linux with eBPF to isolate transport layer anomalies.

In practice, this means creating custom network packets—altering source IP addresses, ports, and control flags—to check whether the intrusion detection system (IDS) or firewall actually drops suspicious traffic. If a rule was written to block malformed packets and the traffic passes unnoticed, you discovered a flaw before a real attacker did. This process turns defensive security into a proactive exercise, simulating real-world scenarios within an isolated lab or staging environment.

The power of Scapy in packet manipulation

Scapy is a library written in Python that allows you to create, decode, send, and capture network packets with just a few lines of code. Unlike traditional load testing tools that only trigger HTTP requests or generic pings, Scapy operates at the link and network layers, allowing you to sculpt every single byte of the IP, TCP, or UDP header. In practice, it works like a digital building block set, where you snap OSI layers together according to your exact testing needs.

To start using Scapy on Linux systems, you will typically need administrative privileges, since direct manipulation of raw sockets requires root access to inject data directly into the network interface. If you notice bottlenecks or slowdowns during heavy load testing with intensive scripts, it is worth checking overall hardware health using practical guides on how to spot CPU and memory bottlenecks on Linux servers, ensuring your testing system itself is not the limiting factor.

Creating and sending custom packets in Python

Let us get practical by building a simple Scapy script to generate a TCP packet with a modified flag, simulating a stealthy port scan. The code below assembles a customized network and transport layer structure and sends it through the default Linux interface. Before executing network scripts in enterprise environments, isolating traffic is crucial to avoid production outages, a concept similar to what we cover when we simulate packet loss and latency in local tests.

The following code snippet demonstrates crafting and sending an isolated TCP SYN packet:

from scapy.all import IP, TCP, send

def send_test_packet(destination_ip):
    # Create the IP packet pointing to the destination
    ip_layer = IP(dst=destination_ip)
    # Create the TCP packet on port 80 with SYN flag enabled
    tcp_layer = TCP(dport=80, flags='S')
    # Combine layers and send the packet over the network
    packet = ip_layer / tcp_layer
    send(packet, verbose=False)
    print('Custom packet successfully sent to ' + destination_ip)

# Example function call in a safe environment
send_test_packet('192.168.1.100')

This code builds a SYN-type packet—the classic initial handshake of a TCP connection—and dispatches it without establishing an actual connection. When the firewall or monitoring system intercepts this isolated traffic, it should log the event or drop the packet according to current security policies. Testing minor variations in these flags helps map exactly which attack signatures your sensors can see.

Validating firewall rules and detecting anomalies

After firing the custom packets, the next critical step is checking firewall logs, iptables, or the detection system to confirm if the security policy worked as expected. If the packet passed without leaving a trace, your filtering rules need urgent adjustments. Controlled injection is meant precisely to close these windows of invisibility, ensuring anomalous traffic is immediately cataloged and blocked.

Beyond perimeter firewalls, anomaly analysis in corporate traffic helps identify atypical behaviors generated by infected machines on the internal network trying to communicate with external command and control servers. Continuously monitoring network behavior prevents lateral threats from roaming freely across internal company segments. With a consistent testing routine using Scapy, your team shifts from a strictly reactive role to a truly resilient security engineering posture.

Final considerations on traffic testing

Injecting controlled malicious traffic with Scapy is an essential technique for network engineers and security professionals who want to move past theory and empirically validate their defenses. By crafting tailored packets in Linux, you expose hidden vulnerabilities in firewalls, intrusion prevention systems, and routing policies before a real incident occurs. Always remember to execute these tests strictly within authorized and controlled environments, turning technical experimentation into a solid pillar for protecting corporate infrastructure.