Analyzing Network Packets with Scapy
Overview
Scapy is a Python packet manipulation library that enables crafting, sending, sniffing, and dissecting network packets at granular protocol layers. This skill covers using Scapy for security-relevant tasks including TCP/UDP/ICMP packet crafting, pcap file analysis, protocol field extraction, SYN scan implementation, DNS query analysis, and detecting anomalous traffic patterns such as unusually fragmented packets or malformed headers.
When to Use
Trigger phrases:
"analyzing network packets with scapy"
"Craft, send, sniff, and dissect network packets using Scapy for protocol analysi"
When investigating security incidents that require analyzing network packets with scapy
When building detection rules or threat hunting queries for this domain
When SOC analysts need structured procedures for this analysis type
When validating security monitoring coverage for related attack techniques
Prerequisites
- Python 3.8+ with
scapy library installed (pip install scapy)
- Root/administrator privileges for raw socket operations (sniffing, sending)
- Npcap (Windows) or libpcap (Linux) for packet capture
- Authorization to perform packet operations on target network
Steps
# Example: IOC detection
import re
IOC_PATTERNS = {
"ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
"domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",
"hash_md5": r"\b[a-f0-9]{32}\b",
"hash_sha256": r"\b[a-f0-9]{64}\b",
}
def extract_iocs(text: str) -> dict:
return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}
- Read and parse pcap/pcapng files with
rdpcap() for offline analysis
- Extract protocol layers (IP, TCP, UDP, DNS, HTTP) and field values
- Compute traffic statistics: top talkers, protocol distribution, port frequency
- Detect SYN flood patterns by analyzing TCP flag ratios
- Identify DNS exfiltration indicators via query length and entropy analysis
- Craft custom probe packets for authorized network testing
- Export findings as structured JSON report
Expected Output
JSON report containing packet statistics, protocol distribution, top source/destination IPs, detected anomalies (SYN floods, DNS tunneling indicators, fragmentation attacks), and per-flow summaries.
When NOT to Use
- You need to perform the attack, not analyze it (use performing-* skills)
- Task is about detection, not analysis (use detecting-* skills)
- You need to implement controls (use implementing-* skills)
- Task is about threat hunting, not post-incident analysis (use hunting-* skills)
- You don't have access to the artifacts/logs to analyze
- Task requires real-time monitoring (use SOC tools)
Red Flags
- Performing actions without explicit written authorization from the asset owner
- Testing against production systems without a defined scope and rules of engagement
- Capturing traffic on networks without authorization or privacy considerations
- Leaving packet captures containing sensitive data unencrypted on disk
- Deploying inline blocking rules without testing for false positives first
Process
- Scope — Define research questions, identify data sources, set time boundaries
- Gather — Collect data from primary sources, APIs, and public records
- Synthesize — Analyze findings, identify patterns, produce actionable report
Verification
- All steps executed successfully against a test environment before production use
- Output documented with screenshots or logs demonstrating expected behavior
- Captures verified as complete with no dropped packets
- Detection rules tested against known-benign traffic for false positive rate
- Alert thresholds validated and tuned to reduce noise
Anti-Rationalization Table
| Rationalization |
Reality |
| "We are too small to be targeted" |
Automated attacks target everyone. Size does not matter. |
| "Security slows us down" |
A breach slows you down 100x more. Build security in from the start. |
| "We will fix it after launch" |
Vulnerabilities in production are exploited within hours. Fix before deploy. |
1---2name: analyzing-network-packets-with-scapy3description: Use when craft, send, sniff, and dissect network packets using Scapy for protocol analysis, network reconnaissance, and traffic anomaly detection in authorized security testing. Use when working with analyzing network packets with scapy.4license: Apache-2.05---678# Analyzing Network Packets with Scapy910## Overview1112Scapy is a Python packet manipulation library that enables crafting, sending, sniffing, and dissecting network packets at granular protocol layers. This skill covers using Scapy for security-relevant tasks including TCP/UDP/ICMP packet crafting, pcap file analysis, protocol field extraction, SYN scan implementation, DNS query analysis, and detecting anomalous traffic patterns such as unusually fragmented packets or malformed headers.131415## When to Use16**Trigger phrases:**17- "analyzing network packets with scapy"18- "Craft, send, sniff, and dissect network packets using Scapy for protocol analysi"192021- When investigating security incidents that require analyzing network packets with scapy22- When building detection rules or threat hunting queries for this domain23- When SOC analysts need structured procedures for this analysis type24- When validating security monitoring coverage for related attack techniques2526## Prerequisites2728- Python 3.8+ with `scapy` library installed (`pip install scapy`)29- Root/administrator privileges for raw socket operations (sniffing, sending)30- Npcap (Windows) or libpcap (Linux) for packet capture31- Authorization to perform packet operations on target network3233## Steps3435```python36# Example: IOC detection37import re3839IOC_PATTERNS = {40 "ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",41 "domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",42 "hash_md5": r"\b[a-f0-9]{32}\b",43 "hash_sha256": r"\b[a-f0-9]{64}\b",44}4546def extract_iocs(text: str) -> dict:47 return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}48```49501. Read and parse pcap/pcapng files with `rdpcap()` for offline analysis512. Extract protocol layers (IP, TCP, UDP, DNS, HTTP) and field values523. Compute traffic statistics: top talkers, protocol distribution, port frequency534. Detect SYN flood patterns by analyzing TCP flag ratios545. Identify DNS exfiltration indicators via query length and entropy analysis556. Craft custom probe packets for authorized network testing567. Export findings as structured JSON report5758## Expected Output5960JSON report containing packet statistics, protocol distribution, top source/destination IPs, detected anomalies (SYN floods, DNS tunneling indicators, fragmentation attacks), and per-flow summaries.61## When NOT to Use6263- You need to perform the attack, not analyze it (use performing-* skills)64- Task is about detection, not analysis (use detecting-* skills)65- You need to implement controls (use implementing-* skills)66- Task is about threat hunting, not post-incident analysis (use hunting-* skills)67- You don't have access to the artifacts/logs to analyze68- Task requires real-time monitoring (use SOC tools)697071## Red Flags7273- Performing actions without explicit written authorization from the asset owner74- Testing against production systems without a defined scope and rules of engagement75- Capturing traffic on networks without authorization or privacy considerations76- Leaving packet captures containing sensitive data unencrypted on disk77- Deploying inline blocking rules without testing for false positives first7879## Process80811. **Scope** — Define research questions, identify data sources, set time boundaries821. **Gather** — Collect data from primary sources, APIs, and public records831. **Synthesize** — Analyze findings, identify patterns, produce actionable report8485## Verification8687- All steps executed successfully against a test environment before production use88- Output documented with screenshots or logs demonstrating expected behavior89- Captures verified as complete with no dropped packets90- Detection rules tested against known-benign traffic for false positive rate91- Alert thresholds validated and tuned to reduce noise9293## Anti-Rationalization Table9495| Rationalization | Reality |96|---|---|97| "We are too small to be targeted" | Automated attacks target everyone. Size does not matter. |98| "Security slows us down" | A breach slows you down 100x more. Build security in from the start. |99| "We will fix it after launch" | Vulnerabilities in production are exploited within hours. Fix before deploy. |