TL;DR
- 目的:Use Scapy to craft, send, sniff, and dissect TCP/UDP/ICMP/DNS packets, analyze pcap files, implement SYN scans, and detect anomalous traffic…
- 适用:辅助/通用
- 输入:PCAP 文件路径 + 分析目标(协议分布/IOC 提取)
- 输出:资产清单/子域/端口表
- 红线:仅限授权范围内;扫描限速
-c 10 -rl 10;所有动作记 oplog - 关联:上游:003-src-session-start → 下游:179-performing-network-traffic-analysis-with-tshark, 180-performing-network-traffic-analysis-with-zeek, 175-analyzing-security-logs-with-splunk
Analyzing Network Packets with Scapy
Quick Start
# Scapy 嗅探示例
from scapy.all import sniff, IP, TCP
packets = sniff(filter="tcp", count=10)
packets.summary()
# 读 pcap
from scapy.all import rdpcap
pkts = rdpcap("capture.pcap")
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
- 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
scapylibrary 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
Workflow
- 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
Output Format
JSON report containing packet statistics, protocol distribution, top source/destination IPs, detected anomalies (SYN floods, DNS tunneling indicators, fragmentation attacks), and per-flow summaries.
Advanced Techniques
Custom Protocol Detection
from scapy.all import *
# 检测 Heartbleed 攻击
def detect_heartbleed(pcap_file):
pkts = rdpcap(pcap_file)
for pkt in pkts:
if pkt.haslayer(TCP) and pkt[TCP].dport == 443:
if len(pkt[TCP].payload) > 100: # 异常大 payload
print(f"Heartbleed suspect: {pkt[IP].src}")
PCAP Anomaly Detection
# 检测端口扫描
pkts = rdpcap("capture.pcap")
syn_packets = [p for p in pkts if p.haslayer(TCP) and p[TCP].flags == 'S']
scan_threshold = 20
if len(syn_packets) > scan_threshold:
print("Possible port scan detected!")