SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · PYTHON · 40 OF 229

Scapy Tutorial: Craft and Sniff Packets in Python

Scapy lets you build any packet layer by layer in Python, send it, and read the reply: stacking IP, TCP, UDP, ICMP and DNS with the slash operator, sending one SYN and seeing the RST-ACK come back from a closed port, sniffing with a filter, reading and writing capture files, and using it to test firewalls and detection rules in your own lab.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Layers stacked with /
  • set any field
  • sr1 sends and reads the reply
  • sniff with filters
  • read and write pcap
  • lab only

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.

build a SYN packet
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.

inspect and change
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.

one SYN, one answer (as root)
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.

ping and a DNS 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.

capture in Python
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.

work with pcap files
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.

Defensive uses
  • 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.

Use with care
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is Scapy?

A Python library for crafting, sending, capturing and dissecting network packets. Packets are built by stacking protocol layers with the / operator, and every header field can be read or set, which makes it useful for testing, analysis and learning protocols.

Q2How do you build and send a TCP SYN packet with Scapy?

Stack the layers: IP(dst=host)/TCP(dport=port, flags="S"), then send it and wait for a reply with sr1(packet, timeout=2). The reply’s TCP flags show the port state: SA for open, RA for closed, and no reply for filtered.

Q3Why does sending packets with Scapy require root privileges?

Scapy writes raw packets directly to the network interface, bypassing the operating system’s TCP/IP stack. Raw sockets and packet capture are privileged operations, so they need root or the equivalent capabilities.

Q4What do the TCP flags SA and RA in a reply mean?

SA is SYN plus ACK, the second step of the handshake, meaning a service is listening. RA is RST plus ACK, meaning the host is reachable but the port is closed. No reply within the timeout suggests a firewall dropped the probe.

Q5How do you capture packets with Scapy?

With sniff(), giving an interface, an optional BPF filter such as "tcp port 443", a count or timeout, and a callback (prn) that receives each packet as an object whose layers and fields can be inspected in Python.

Q6How would you analyse a large pcap file with Scapy?

Iterate with PcapReader rather than rdpcap so packets are streamed instead of loaded into memory, test each packet for the layers of interest and extract the needed fields, for example counting DNS query names or SYN packets per source.

Q7How do defenders use Scapy?

To generate precise test traffic that verifies firewall rules and IDS signatures, to reproduce unusual packets seen in incidents, to test how their own devices handle malformed input, and to automate extraction of data from capture files.

Q8What are the limitations and risks of Scapy?

It is slow compared with dedicated scanners, the host OS may interfere with hand-built connections by sending resets, and it will forge or flood if told to, so it must only be used on isolated lab networks and systems you are authorised to test.