Notes
Layers
A packet in Scapy is layers stacked with the slash operator. Here is an IP layer addressed to the local machine, with a TCP layer on top aimed at port eight thousand and eighty, and the SYN flag set. That is the first packet of a handshake, written by hand. Summary prints it in one line. The raw packet is forty bytes: twenty of IP header and twenty of TCP. Every field you did not set got a sensible default, and you can read any of them.
from scapy.all import IP, TCP, raw
p = IP(dst="127.0.0.1") / TCP(
dport=8080, flags="S")
p.summary()
# IP / TCP 127.0.0.1:ftp_data >
# 127.0.0.1:http_alt S
len(raw(p)) # 40 bytes
p[IP].ttl # 64
p[TCP].sport # 20 (the default) Any field
Show prints every field of every layer, and ls lists the fields a layer supports. You can change any of them: the time to live, the flags, the window size, and you can add a payload on top. Scapy recalculates lengths and checksums when the packet is sent. This is what makes it a teaching tool. Every field in the TCP and IP diagrams from Part two is now something you can set and watch the effect of.
p.show() # every field ls(TCP) # fields of a layer p[IP].ttl = 5 p[TCP].flags = "SA" # SYN + ACK p[TCP].window = 1024 p = p / b"hello" # add a payload # checksums and lengths are # recalculated when it is sent
Send and receive
Now send one. The function s r one sends a packet and returns the first reply. We sent a single SYN to port nine on the local machine, where nothing listens. The reply came back with the flags R A, reset and acknowledge. That is the closed port answer from the Nmap episode, seen directly. An open port would answer S A, and a filtered one would return nothing before the timeout. Sending raw packets needs root, because you are bypassing the operating system's own networking.
from scapy.all import sr1
r = sr1(IP(dst="127.0.0.1") /
TCP(dport=9, flags="S"),
timeout=2, verbose=0)
r.summary()
# IP / TCP 127.0.0.1:discard >
# 127.0.0.1:ftp_data RA
r[TCP].flags # RA
# RA = RST + ACK: port closed Other protocols
The same pattern works for any protocol Scapy knows, and it knows hundreds. An ICMP layer on top of IP is a ping, and the reply comes back as an echo reply. Stack UDP and a DNS layer with a question record and you have built a DNS query by hand. You can see how small these protocols really are, and why forging a DNS answer was possible in the DNS episode: an answer is just another short packet with a matching question.
from scapy.all import ICMP, UDP, DNS
from scapy.all import DNSQR
sr1(IP(dst="127.0.0.1")/ICMP(),
timeout=2).summary()
# IP / ICMP ... echo-reply 0
q = IP(dst="10.10.10.53")/UDP(dport=53)/\
DNS(rd=1, qd=DNSQR(qname="shop.example"))
q.summary()
# IP / UDP / DNS Qry b'shop.example.' Sniff
Scapy captures as well as sends. Sniff takes an interface, a filter written in the same language tcpdump uses, and a function to call for each packet. Inside that function a packet is a Python object, so you can test for a layer and read fields directly. That turns packet capture into something you can program: count SYN packets per source, flag a DNS name longer than fifty characters, or record every new destination a machine contacts.
from scapy.all import sniff
def show(pkt):
if pkt.haslayer("TCP"):
print(pkt["IP"].src,
pkt["TCP"].dport,
pkt["TCP"].flags)
sniff(iface="lo", count=20,
filter="tcp port 8080",
prn=show) Capture files
Scapy reads and writes the same capture files as Wireshark and tcpdump. We wrote our two hand-built packets to a file and read them back: two packets, and the second one's DNS question is the name we set. In practice you go the other way. Someone hands you a capture from an incident, and a ten-line script loops over a million packets and pulls out exactly the field you need, which no amount of clicking in a graphical tool will do as fast.
from scapy.all import rdpcap, wrpcap
wrpcap("t.pcap", [p, q])
pkts = rdpcap("t.pcap")
len(pkts) # 2
pkts[1][DNSQR].qname
# b'shop.example.'
# loop over a real capture and
# pull out exactly what you need Defensive uses
What do defenders do with this? They generate exactly the traffic a control is supposed to catch. Send the packet your firewall rule should drop, and confirm nothing comes back. Produce the traffic your intrusion detection rule should alert on, and confirm it fires. Reproduce a strange packet seen in an incident to understand it. Check how your own device copes with malformed input. A control that has never been tested with real traffic is a hope, not a control.
- test a firewall rule: send the packet it should drop, check that nothing comes back
- test an IDS rule: generate the traffic it should alert on reproduce an odd packet from an incident
- check how a device handles malformed input (your own)
- analyse captures in bulk
The sharp edges
Scapy does exactly what you tell it, including things that harm networks. It will happily forge a source address or send packets in a tight loop. So this is a lab-only tool: an isolated network, your own machines, and no spoofing or flooding of anything else, ever. Two practical notes. Your operating system may reset connections it did not open itself, which confuses hand-built handshakes. And Scapy is slow; it is for precision, not volume.
- Scapy does what you say: it will forge source addresses and flood if asked
- so: lab network only, isolated
- never spoof or flood outside your own lab
- your OS may send a RST to replies it did not expect
- for volume, real tools are faster; Scapy is for precision
Common mistakes
Mistakes. Running experiments outside an isolated lab. Forgetting that sending needs root. No timeout, so the script waits forever for a reply that will never come. Sniffing or sending on the wrong interface. Using Scapy for large scans, where it is far too slow. Loading a huge capture file into memory in one go, when a streaming reader exists. And assuming the packet on the wire is what you intended, without capturing it to check.
- running it outside an isolated lab
- forgetting root, then wondering why nothing sends
- no timeout on sr1
- the wrong interface
- using it for large scans
- reading a huge pcap fully into memory (use PcapReader)
- trusting a packet you built without capturing it
Say it like this
In the interview: Scapy is a Python library for building, sending, sniffing and parsing packets at any layer, with every header field under your control. I use it to test firewall and intrusion detection rules by generating exactly the traffic they should handle, to script the analysis of capture files, and to understand protocols by building their packets by hand. It is a precision tool for a lab, not something to scan with at scale.
- "A Python library to build, send, sniff and parse packets
- at any layer. I use it to test firewall and IDS rules
- with exact traffic, to script
- analysis of pcap files, and to learn protocols. It is for precision in a lab, not for scanning at scale."