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 Scapy4 for protocol analysis, network reconnaissance, and traffic anomaly detection in5 authorized security testing. Use when working with analyzing network packets with6 scapy.7domain: cybersecurity8subdomain: network-security9tags:10- scapy11- packet-analysis12- network-forensics13- protocol-dissection14- pcap15- traffic-analysis16version: '1.0'17author: oyi7718license: Apache-2.019nist_csf:20- PR.IR-0121- DE.CM-0122- ID.AM-0323- PR.DS-0224category: cybersecurity25metadata:26 source: https://skillmd.com/skills/oyi77/analyzing-network-packets-with-scapy27---282930# Analyzing Network Packets with Scapy3132## Overview3334Scapy 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.353637## When to Use38**Trigger phrases:**39- "analyzing network packets with scapy"40- "Craft, send, sniff, and dissect network packets using Scapy for protocol analysi"414243- When investigating security incidents that require analyzing network packets with scapy44- When building detection rules or threat hunting queries for this domain45- When SOC analysts need structured procedures for this analysis type46- When validating security monitoring coverage for related attack techniques4748## Prerequisites4950- Python 3.8+ with `scapy` library installed (`pip install scapy`)51- Root/administrator privileges for raw socket operations (sniffing, sending)52- Npcap (Windows) or libpcap (Linux) for packet capture53- Authorization to perform packet operations on target network5455## Steps5657```python58# Example: IOC detection59import re6061IOC_PATTERNS = {62 "ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",63 "domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",64 "hash_md5": r"\b[a-f0-9]{32}\b",65 "hash_sha256": r"\b[a-f0-9]{64}\b",66}6768def extract_iocs(text: str) -> dict:69 return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}70```71721. Read and parse pcap/pcapng files with `rdpcap()` for offline analysis732. Extract protocol layers (IP, TCP, UDP, DNS, HTTP) and field values743. Compute traffic statistics: top talkers, protocol distribution, port frequency754. Detect SYN flood patterns by analyzing TCP flag ratios765. Identify DNS exfiltration indicators via query length and entropy analysis776. Craft custom probe packets for authorized network testing787. Export findings as structured JSON report7980## Expected Output8182JSON report containing packet statistics, protocol distribution, top source/destination IPs, detected anomalies (SYN floods, DNS tunneling indicators, fragmentation attacks), and per-flow summaries.83## When NOT to Use8485- You need to perform the attack, not analyze it (use performing-* skills)86- Task is about detection, not analysis (use detecting-* skills)87- You need to implement controls (use implementing-* skills)88- Task is about threat hunting, not post-incident analysis (use hunting-* skills)89- You don't have access to the artifacts/logs to analyze90- Task requires real-time monitoring (use SOC tools)919293## Red Flags9495- Performing actions without explicit written authorization from the asset owner96- Testing against production systems without a defined scope and rules of engagement97- Capturing traffic on networks without authorization or privacy considerations98- Leaving packet captures containing sensitive data unencrypted on disk99- Deploying inline blocking rules without testing for false positives first100101## Process1021031. **Scope** — Define research questions, identify data sources, set time boundaries1041. **Gather** — Collect data from primary sources, APIs, and public records1051. **Synthesize** — Analyze findings, identify patterns, produce actionable report106107## Verification108109- All steps executed successfully against a test environment before production use110- Output documented with screenshots or logs demonstrating expected behavior111- Captures verified as complete with no dropped packets112- Detection rules tested against known-benign traffic for false positive rate113- Alert thresholds validated and tuned to reduce noise114115## Anti-Rationalization Table116117| Rationalization | Reality |118|---|---|119| "We are too small to be targeted" | Automated attacks target everyone. Size does not matter. |120| "Security slows us down" | A breach slows you down 100x more. Build security in from the start. |121| "We will fix it after launch" | Vulnerabilities in production are exploited within hours. Fix before deploy. |