TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Project: Packet Analysis Utility with Scapy

Project: Packet Analysis Utility with Scapy

Wireshark is the right tool for looking at one capture by hand. When the question is the same for a hundred captures ("does any of them contain cleartext credentials?", "which hosts changed their MAC address?", "which names failed to resolve?"), you want a small script that reads pcap files and prints findings. Writing your own dissector for every protocol would be a mistake, though: protocol parsing is exactly where tools get confused and exploited (Binary Formats with struct). This project uses an existing, maintained library, Scapy, to do the parsing, and keeps its own code to the analysis.

The session runs in your sandbox, which has no network: the tool only reads the lab captures in $SAMPLES/pcap (synthetic traffic of the lab network 10.10.0.0/24, generated for this track and also used in Networking for Security).

Definitions

  • pcap: the classic capture file format: a global header, then one record per packet with a timestamp and the raw bytes. rdpcap() reads one into a list of packets; PcapReader streams large files.
  • Layer access in Scapy: pkt.haslayer(TCP), pkt[IP].src, pkt[TCP].dport, pkt[Raw].load (the payload bytes), pkt[DNS].qd.qname.
  • Flow: packets sharing the 5-tuple (protocol, source address and port, destination address and port); a conversation is both directions of a flow.
  • Finding (as before): rule, evidence, where.

The analyser

The script makes four passes over the captures, each a small function: flow summary, HTTP requests with a cleartext-credential check, DNS answers, and an ARP watch that remembers which MAC address claimed each IP address. Credentials found in traffic are redacted in the output: a report must not spread the secret it warns about.

bash · try it yourself
cat > pcapscan.py <<'PY'
import re, sys
from collections import Counter, defaultdict
from scapy.all import rdpcap, IP, TCP, UDP, Raw, DNS, DNSRR, ARP

def flows(pkts):
    c = Counter()
    for p in pkts:
        if p.haslayer(IP) and (p.haslayer(TCP) or p.haslayer(UDP)):
            l4 = p[TCP] if p.haslayer(TCP) else p[UDP]
            key = (p[IP].proto, *sorted([(p[IP].src, l4.sport), (p[IP].dst, l4.dport)]))
            c[key] += len(p)
    for (proto, a, b), size in sorted(c.items()):
        print(f"  {'tcp' if proto == 6 else 'udp'} {a[0]}:{a[1]} <-> {b[0]}:{b[1]}  {size} bytes")

SECRET = re.compile(rb"(password|passwd|pwd|pass)=([^&\s]*)", re.I)

def http(pkts):
    for p in pkts:
        if p.haslayer(TCP) and p.haslayer(Raw) and p[TCP].dport == 80:
            data = bytes(p[Raw].load)
            line = data.split(b"\r\n", 1)[0].decode("ascii", "backslashreplace")
            print(f"  {p[IP].src} -> {p[IP].dst}: {line}")
            body = data.split(b"\r\n\r\n", 1)[-1]
            for m in SECRET.finditer(body):
                print(f"  FINDING cleartext-credential field={m[1].decode()} value=<redacted, {len(m[2])} chars>")

def dns(pkts):
    rcodes = {0: "NOERROR", 3: "NXDOMAIN"}
    for p in pkts:
        if p.haslayer(DNS) and p[DNS].qr == 1:
            d = p[DNS]
            name = d.qd.qname.decode().rstrip(".")
            answers = [d.an[i].rdata for i in range(d.ancount)] if d.ancount else []
            print(f"  id=0x{d.id:04x} {name} {rcodes.get(d.rcode, d.rcode)} {answers}")

def arp(pkts):
    seen = {}
    for p in pkts:
        if p.haslayer(ARP) and p[ARP].op == 2:          # is-at (reply)
            ip, mac = p[ARP].psrc, p[ARP].hwsrc
            if ip in seen and seen[ip] != mac:
                print(f"  FINDING arp-mac-change {ip}: {seen[ip]} -> {mac} at t+{float(p.time - pkts[0].time):.1f}s")
            seen.setdefault(ip, mac)
    print(f"  bindings: {seen}")

for name, fn in [("http.pcap", flows), ("http.pcap", http), ("dns.pcap", dns), ("arp.pcap", arp)]:
    pkts = rdpcap(f"{sys.argv[1]}/{name}")
    print(f"== {fn.__name__} ({name}, {len(pkts)} packets)")
    fn(pkts)
PY
python3 pcapscan.py "$SAMPLES/pcap" 2>&1 | grep -v '^WARNING'
== flows (http.pcap, 20 packets)
  tcp 10.10.0.10:80 <-> 10.10.0.5:50412  760 bytes
  tcp 10.10.0.10:80 <-> 10.10.0.5:50414  835 bytes
== http (http.pcap, 20 packets)
  10.10.0.5 -> 10.10.0.10: GET / HTTP/1.1
  10.10.0.5 -> 10.10.0.10: POST /login HTTP/1.1
  FINDING cleartext-credential field=password value=<redacted, 12 chars>
== dns (dns.pcap, 4 packets)
  id=0x1a2b www.lab.test NOERROR ['10.10.0.10']
  id=0x1a2c nope.lab.test NXDOMAIN []
== arp (arp.pcap, 3 packets)
  FINDING arp-mac-change 10.10.0.1: 02:00:00:0a:0a:01 -> 02:00:00:0a:0a:66 at t+5.0s
  bindings: {'10.10.0.1': '02:00:00:0a:0a:01'}

Four small passes, four kinds of finding:

  • The flow summary shows two TCP conversations between the same client and the web server, one per HTTP request.
  • The HTTP pass prints both request lines and flags the login form: a password field sent over plain HTTP, its value replaced by its length. The fix is TLS (HTTP in Cleartext versus HTTPS), and the finding is the evidence for it.
  • The DNS pass lists one successful answer and one NXDOMAIN. Many NXDOMAINs for random-looking names from one client is a classic sign of malware searching for its servers (a domain-generation algorithm); a single one is usually a typo.
  • The ARP pass remembers that 10.10.0.1 was at 02:00:00:0a:0a:01 and reports the unsolicited reply five seconds later claiming the same address from a different MAC: the signature of ARP spoofing (ARP Spoofing: Mechanism, Detection and Fix).

Cross-checking with tshark

A tool you wrote should agree with a tool everyone trusts. tshark reads the same files with Wireshark's dissectors:

bash · try it yourself
tshark -r "$SAMPLES/pcap/http.pcap" -Y http.request -T fields -e ip.src -e http.request.method -e http.request.uri
tshark -r "$SAMPLES/pcap/dns.pcap" -Y 'dns.flags.response == 1' -T fields -e dns.id -e dns.qry.name -e dns.flags.rcode -e dns.a
tshark -r "$SAMPLES/pcap/arp.pcap" -Y 'arp.opcode == 2' -T fields -e frame.time_relative -e arp.src.proto_ipv4 -e arp.src.hw_mac
10.10.0.5	GET	/
10.10.0.5	POST	/login
0x1a2b	www.lab.test	0	10.10.0.10
0x1a2c	nope.lab.test	3
0.000400000	10.10.0.1	02:00:00:0a:0a:01
5.000000000	10.10.0.1	02:00:00:0a:0a:66

The values match the script's output field for field (tshark prints the DNS response code as a number: 0 is NOERROR, 3 is NXDOMAIN). Differential checks like this catch parsing mistakes in your own code before they reach a report.

How the analysis itself can fail (detection)

  • Truncated packets (a capture with a small snap length) lose payloads: Scapy then has no Raw layer and the credential check silently finds nothing. Print the snap length and the count of packets without payload.
  • TCP reassembly: a request split across two segments, or sent out of order, is not one Raw load. Scapy's sessions or tshark's reassembly handle it; per-packet regexes don't.
  • Non-standard ports: HTTP on 8080 is missed by dport == 80. Detect protocols by content (b"HTTP/1.") where it matters.
  • Huge captures: rdpcap loads everything into memory; use PcapReader to stream.

How to keep it safe and useful (prevention)

  1. Parse with maintained libraries, keep them updated, and run the analyser as an unprivileged user on copies of captures: dissectors have had memory-safety bugs (Wireshark publishes advisories every few months).
  2. Redact secrets in findings, store captures encrypted, and delete them when the case closes: a capture of a login page is a credential store.
  3. Make each pass a function with a test on a small synthetic capture (Scapy writes one with wrpcap; give every packet a fixed .time so the test is reproducible).
  4. Read-only by design: the tool never sends packets. Scapy can send; this tool doesn't import send or sr.

Pitfalls

  • Scapy prints warnings to stderr at import on systems without some interfaces; filter them, don't disable error output entirely.
  • len(pkt) is the length on the wire as captured, including the Ethernet header.
  • Time: pkt.time is the number of seconds since 1970 from the capture's clock (in Scapy 2.5 a Decimal-like EDecimal; convert with float()); compare relative times within one capture, and treat captures from different sensors with care.

Practice

1. Extend the HTTP pass to print the Host header of each request.

Search the header block: m = re.search(rb"^Host: *([^\r\n]+)", data, re.M | re.I) and print m[1].decode() when it matches. Report a missing Host header as a finding: HTTP/1.1 requires it, so its absence points to a hand-made client.

2. How would you turn the DNS pass into a "many NXDOMAIN" detector?

Count NXDOMAIN responses per client (the destination address of the response) in a time window, as in the log analyser, and alert above a threshold, optionally adding the entropy of the queried labels as a second signal for generated names.

3. Why does the ARP pass use seen.setdefault(ip, mac) instead of seen[ip] = mac?

So the first binding is kept as the reference: every later reply with a different MAC is reported against the original. With seen[ip] = mac an attacker's repeated replies would become the "known" binding and a later legitimate reply would look like the change.

Test yourself

Why does the project use Scapy instead of a hand-written parser for Ethernet, IP, TCP and DNS?

  1. Scapy is faster
  2. Protocol parsing is error-prone and a maintained library is safer; the tool's own code stays in the analysis
  3. Hand-written parsers can't read pcap
  4. Scapy needs no Python

What does the credential finding print for the password value?

  1. The password
  2. Its SHA-256
  3. <redacted> with its length
  4. Nothing; it is skipped

Which observation in arp.pcap indicates ARP spoofing?

  1. A who-has request
  2. An unsolicited reply claiming 10.10.0.1 from a different MAC address than the first reply
  3. A DNS NXDOMAIN
  4. A TCP FIN

Why compare the script's output with tshark?

  1. tshark is required by law
  2. A differential check catches parsing mistakes in your own tool
  3. tshark is faster
  4. To capture live traffic