analyzing-network-traffic-of-malware

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Analyzing Network Traffic of Malware

恶意软件网络流量分析

When to Use

适用场景

  • Sandbox execution has captured a PCAP file and the network behavior needs detailed analysis
  • Identifying the C2 protocol structure for writing network detection signatures
  • Determining what data the malware exfiltrates and to which external infrastructure
  • Analyzing DNS tunneling, domain generation algorithms (DGA), or fast-flux behavior
  • Creating Suricata/Snort signatures based on observed malware network patterns
Do not use for host-based analysis of malware behavior; use Cuckoo sandbox reports or Volatility memory analysis for process-level activity.
  • 沙箱执行已捕获PCAP文件,需要对网络行为进行详细分析
  • 识别C2协议结构,用于编写网络检测特征规则
  • 确定恶意软件泄露的数据内容及其传输到的外部基础设施
  • 分析DNS隧道、域名生成算法(DGA)或快速通量(fast-flux)行为
  • 根据观察到的恶意软件网络模式创建Suricata/Snort特征规则
请勿用于恶意软件行为的主机端分析;进程级活动请使用Cuckoo沙箱报告或Volatility内存分析。

Prerequisites

前置条件

  • Wireshark 4.x installed for interactive PCAP analysis
  • tshark (Wireshark CLI) for scripted packet extraction
  • Zeek installed for automated metadata generation from PCAPs
  • Suricata with ET Open/ET Pro rulesets for signature matching
  • NetworkMiner for file extraction and credential detection from PCAPs
  • Python 3.8+ with
    scapy
    and
    dpkt
    for programmatic packet analysis
  • 安装Wireshark 4.x用于交互式PCAP分析
  • 安装tshark(Wireshark命令行工具)用于脚本化数据包提取
  • 安装Zeek用于从PCAP自动生成元数据
  • 配置有ET Open/ET Pro规则集的Suricata用于特征匹配
  • 安装NetworkMiner用于从PCAP提取文件和检测凭证
  • 安装Python 3.8+及
    scapy
    dpkt
    库用于程序化数据包分析

Workflow

工作流程

Step 1: Initial PCAP Overview

步骤1:PCAP文件初步概览

Get a high-level understanding of the network traffic:
bash
undefined
获取网络流量的高层级信息:
bash
undefined

Capture statistics

Capture statistics

capinfos malware.pcap
capinfos malware.pcap

Protocol hierarchy

Protocol hierarchy

tshark -r malware.pcap -q -z io,phs
tshark -r malware.pcap -q -z io,phs

Endpoint statistics (top talkers)

Endpoint statistics (top talkers)

tshark -r malware.pcap -q -z endpoints,ip
tshark -r malware.pcap -q -z endpoints,ip

Conversation statistics

Conversation statistics

tshark -r malware.pcap -q -z conv,tcp
tshark -r malware.pcap -q -z conv,tcp

DNS query summary

DNS query summary

tshark -r malware.pcap -q -z dns,tree
undefined
tshark -r malware.pcap -q -z dns,tree
undefined

Step 2: Analyze DNS Activity

步骤2:分析DNS活动

Examine DNS queries for DGA, tunneling, or C2 domain resolution:
bash
undefined
检查DNS查询是否存在DGA、隧道或C2域名解析行为:
bash
undefined

Extract all DNS queries

Extract all DNS queries

tshark -r malware.pcap -T fields -e frame.time -e dns.qry.name -e dns.a
-Y "dns.flags.response == 1" | sort
tshark -r malware.pcap -T fields -e frame.time -e dns.qry.name -e dns.a
-Y "dns.flags.response == 1" | sort

Detect DGA patterns (high entropy domain names)

Detect DGA patterns (high entropy domain names)

python3 << 'PYEOF' import math from collections import Counter
def entropy(s): p = [n/len(s) for n in Counter(s).values()] return -sum(pi * math.log2(pi) for pi in p if pi > 0)
python3 << 'PYEOF' import math from collections import Counter
def entropy(s): p = [n/len(s) for n in Counter(s).values()] return -sum(pi * math.log2(pi) for pi in p if pi > 0)

Parse DNS queries from tshark output

Parse DNS queries from tshark output

import subprocess result = subprocess.run( ["tshark", "-r", "malware.pcap", "-T", "fields", "-e", "dns.qry.name", "-Y", "dns.flags.response == 0"], capture_output=True, text=True )
domains = set(result.stdout.strip().split('\n')) print("Suspicious DNS queries (high entropy):") for domain in domains: if domain: subdomain = domain.split('.')[0] ent = entropy(subdomain) if ent > 3.5 and len(subdomain) > 10: print(f" {domain} (entropy: {ent:.2f})") PYEOF
import subprocess result = subprocess.run( ["tshark", "-r", "malware.pcap", "-T", "fields", "-e", "dns.qry.name", "-Y", "dns.flags.response == 0"], capture_output=True, text=True )
domains = set(result.stdout.strip().split('\n')) print("Suspicious DNS queries (high entropy):") for domain in domains: if domain: subdomain = domain.split('.')[0] ent = entropy(subdomain) if ent > 3.5 and len(subdomain) > 10: print(f" {domain} (entropy: {ent:.2f})") PYEOF

Detect DNS tunneling (large TXT responses)

Detect DNS tunneling (large TXT responses)

tshark -r malware.pcap -T fields -e dns.qry.name -e dns.txt
-Y "dns.resp.type == 16 and dns.resp.len > 100"
undefined
tshark -r malware.pcap -T fields -e dns.qry.name -e dns.txt
-Y "dns.resp.type == 16 and dns.resp.len > 100"
undefined

Step 3: Analyze HTTP/HTTPS C2 Communication

步骤3:分析HTTP/HTTPS C2通信

Examine web-based command-and-control traffic:
bash
undefined
检查基于Web的命令与控制流量:
bash
undefined

Extract HTTP requests

Extract HTTP requests

tshark -r malware.pcap -T fields
-e frame.time -e ip.src -e ip.dst -e http.host
-e http.request.method -e http.request.uri -e http.user_agent
-Y "http.request"
tshark -r malware.pcap -T fields
-e frame.time -e ip.src -e ip.dst -e http.host
-e http.request.method -e http.request.uri -e http.user_agent
-Y "http.request"

Extract HTTP response bodies (potential payload downloads)

Extract HTTP response bodies (potential payload downloads)

tshark -r malware.pcap -T fields
-e http.host -e http.request.uri -e http.content_type -e tcp.len
-Y "http.response and tcp.len > 1000"
tshark -r malware.pcap -T fields
-e http.host -e http.request.uri -e http.content_type -e tcp.len
-Y "http.response and tcp.len > 1000"

Extract POST data (potential exfiltration)

Extract POST data (potential exfiltration)

tshark -r malware.pcap -T fields
-e http.host -e http.request.uri -e http.file_data
-Y "http.request.method == POST"
tshark -r malware.pcap -T fields
-e http.host -e http.request.uri -e http.file_data
-Y "http.request.method == POST"

TLS analysis (SNI, JA3 fingerprints)

TLS analysis (SNI, JA3 fingerprints)

tshark -r malware.pcap -T fields
-e tls.handshake.extensions_server_name
-e tls.handshake.ja3
-Y "tls.handshake.type == 1"
tshark -r malware.pcap -T fields
-e tls.handshake.extensions_server_name
-e tls.handshake.ja3
-Y "tls.handshake.type == 1"

Extract TLS certificate details

Extract TLS certificate details

tshark -r malware.pcap -T fields
-e x509ce.dNSName -e x509af.serialNumber
-e x509sat.utf8String
-Y "tls.handshake.type == 11"
tshark -r malware.pcap -T fields
-e x509ce.dNSName -e x509af.serialNumber
-e x509sat.utf8String
-Y "tls.handshake.type == 11"

Export HTTP objects (downloaded files)

Export HTTP objects (downloaded files)

tshark -r malware.pcap --export-objects http,exported_files/
undefined
tshark -r malware.pcap --export-objects http,exported_files/
undefined

Step 4: Detect Beaconing Patterns

步骤4:检测信标行为模式

Identify regular periodic communication indicating C2 beaconing:
python
undefined
识别表明C2信标的定期通信:
python
undefined

Beacon detection from PCAP

Beacon detection from PCAP

from scapy.all import rdpcap, IP, TCP from collections import defaultdict import statistics
packets = rdpcap("malware.pcap")
from scapy.all import rdpcap, IP, TCP from collections import defaultdict import statistics
packets = rdpcap("malware.pcap")

Group connections by destination IP:port

Group connections by destination IP:port

connections = defaultdict(list) for pkt in packets: if IP in pkt and TCP in pkt: if pkt[TCP].flags & 0x02: # SYN flag dst = f"{pkt[IP].dst}:{pkt[TCP].dport}" connections[dst].append(float(pkt.time))
connections = defaultdict(list) for pkt in packets: if IP in pkt and TCP in pkt: if pkt[TCP].flags & 0x02: # SYN flag dst = f"{pkt[IP].dst}:{pkt[TCP].dport}" connections[dst].append(float(pkt.time))

Analyze timing intervals for beaconing

Analyze timing intervals for beaconing

print("Beacon Analysis:") for dst, times in connections.items(): if len(times) >= 5: intervals = [times[i+1] - times[i] for i in range(len(times)-1)] avg = statistics.mean(intervals) stdev = statistics.stdev(intervals) if len(intervals) > 1 else 0 jitter = (stdev / avg * 100) if avg > 0 else 0
    if 10 < avg < 3600 and jitter < 30:  # Regular interval with < 30% jitter
        print(f"  [!] {dst}: {len(times)} connections")
        print(f"      Interval: {avg:.1f}s ± {stdev:.1f}s (jitter: {jitter:.1f}%)")
        print(f"      Pattern: LIKELY BEACONING")
undefined
print("Beacon Analysis:") for dst, times in connections.items(): if len(times) >= 5: intervals = [times[i+1] - times[i] for i in range(len(times)-1)] avg = statistics.mean(intervals) stdev = statistics.stdev(intervals) if len(intervals) > 1 else 0 jitter = (stdev / avg * 100) if avg > 0 else 0
    if 10 < avg < 3600 and jitter < 30:  # Regular interval with < 30% jitter
        print(f"  [!] {dst}: {len(times)} connections")
        print(f"      Interval: {avg:.1f}s ± {stdev:.1f}s (jitter: {jitter:.1f}%)")
        print(f"      Pattern: LIKELY BEACONING")
undefined

Step 5: Generate Network Detection Signatures

步骤5:生成网络检测特征规则

Create Suricata/Snort rules from observed traffic patterns:
bash
undefined
根据观察到的流量模式创建Suricata/Snort规则:
bash
undefined

Run Suricata against the PCAP for existing signature matches

Run Suricata against the PCAP for existing signature matches

suricata -r malware.pcap -l suricata_output/ -c /etc/suricata/suricata.yaml
suricata -r malware.pcap -l suricata_output/ -c /etc/suricata/suricata.yaml

Review alerts

Review alerts

cat suricata_output/fast.log
cat suricata_output/fast.log

Create custom Suricata rule from observed patterns

Create custom Suricata rule from observed patterns

cat << 'EOF' > custom_malware.rules
cat << 'EOF' > custom_malware.rules

C2 beacon detection based on observed URI pattern

C2 beacon detection based on observed URI pattern

alert http $HOME_NET any -> $EXTERNAL_NET any ( msg:"MALWARE MalwareX C2 Beacon"; flow:established,to_server; http.method; content:"POST"; http.uri; content:"/gate.php?id="; http.user_agent; content:"Mozilla/5.0 (compatible; MSIE 10.0)"; sid:9000001; rev:1; )
alert http $HOME_NET any -> $EXTERNAL_NET any ( msg:"MALWARE MalwareX C2 Beacon"; flow:established,to_server; http.method; content:"POST"; http.uri; content:"/gate.php?id="; http.user_agent; content:"Mozilla/5.0 (compatible; MSIE 10.0)"; sid:9000001; rev:1; )

DNS query for known C2 domain

DNS query for known C2 domain

alert dns $HOME_NET any -> any any ( msg:"MALWARE MalwareX C2 DNS Query"; dns.query; content:"update.malicious.com"; sid:9000002; rev:1; )
alert dns $HOME_NET any -> any any ( msg:"MALWARE MalwareX C2 DNS Query"; dns.query; content:"update.malicious.com"; sid:9000002; rev:1; )

JA3 hash match for malware TLS client

JA3 hash match for malware TLS client

alert tls $HOME_NET any -> $EXTERNAL_NET any ( msg:"MALWARE MalwareX JA3 Match"; ja3.hash; content:"a0e9f5d64349fb13191bc781f81f42e1"; sid:9000003; rev:1; ) EOF
undefined
alert tls $HOME_NET any -> $EXTERNAL_NET any ( msg:"MALWARE MalwareX JA3 Match"; ja3.hash; content:"a0e9f5d64349fb13191bc781f81f42e1"; sid:9000003; rev:1; ) EOF
undefined

Step 6: Extract Files and Artifacts from Traffic

步骤6:从流量中提取文件和工件

Recover transferred files and embedded data:
bash
undefined
恢复传输的文件和嵌入数据:
bash
undefined

Extract files using Zeek

Extract files using Zeek

zeek -r malware.pcap /opt/zeek/share/zeek/policy/frameworks/files/extract-all-files.zeek ls extract_files/
zeek -r malware.pcap /opt/zeek/share/zeek/policy/frameworks/files/extract-all-files.zeek ls extract_files/

Extract files using NetworkMiner (GUI)

Extract files using NetworkMiner (GUI)

Or use tshark for specific protocol exports

Or use tshark for specific protocol exports

tshark -r malware.pcap --export-objects http,http_objects/ tshark -r malware.pcap --export-objects smb,smb_objects/ tshark -r malware.pcap --export-objects tftp,tftp_objects/
tshark -r malware.pcap --export-objects http,http_objects/ tshark -r malware.pcap --export-objects smb,smb_objects/ tshark -r malware.pcap --export-objects tftp,tftp_objects/

Hash all extracted files

Hash all extracted files

sha256sum http_objects/* smb_objects/* 2>/dev/null
sha256sum http_objects/* smb_objects/* 2>/dev/null

Generate Zeek logs for comprehensive metadata

Generate Zeek logs for comprehensive metadata

zeek -r malware.pcap
zeek -r malware.pcap

Output: conn.log, dns.log, http.log, ssl.log, files.log, etc.

Output: conn.log, dns.log, http.log, ssl.log, files.log, etc.

undefined
undefined

Key Concepts

核心概念

TermDefinition
BeaconingRegular periodic connections from malware to C2 server, identifiable by consistent time intervals and packet sizes
JA3/JA3STLS fingerprinting method creating a hash from ClientHello/ServerHello parameters to uniquely identify malware TLS implementations
DGA (Domain Generation Algorithm)Algorithm generating pseudo-random domain names that malware queries to locate C2 servers, evading static domain blocklists
DNS TunnelingEncoding data in DNS queries and responses to establish a C2 channel or exfiltrate data through DNS infrastructure
Fast FluxDNS technique rapidly rotating IP addresses for a domain to avoid takedown and distribute C2 across many compromised hosts
SNI (Server Name Indication)TLS extension revealing the hostname the client is connecting to; visible even in encrypted HTTPS connections
Network SignatureSuricata/Snort rule matching specific patterns in network traffic (headers, payloads, timing) to detect malicious communications
术语定义
Beaconing恶意软件与C2服务器之间的定期连接,可通过一致的时间间隔和数据包大小识别
JA3/JA3STLS指纹识别方法,通过ClientHello/ServerHello参数生成哈希值,用于唯一识别恶意软件的TLS实现
DGA (Domain Generation Algorithm)生成伪随机域名的算法,恶意软件通过查询这些域名定位C2服务器,规避静态域名黑名单
DNS Tunneling在DNS查询和响应中编码数据,通过DNS基础设施建立C2通道或泄露数据
Fast Flux一种DNS技术,快速轮换域名对应的IP地址,避免被封禁并将C2分布到多个受 compromise 的主机
SNI (Server Name Indication)TLS扩展,可显示客户端连接的主机名;即使在加密HTTPS连接中也可见
Network SignatureSuricata/Snort规则,匹配网络流量中的特定模式(头部、载荷、时序)以检测恶意通信

Tools & Systems

工具与系统

  • Wireshark: Open-source packet analyzer for deep interactive inspection of network traffic at the protocol level
  • Zeek: Network analysis framework generating structured metadata logs (conn, dns, http, ssl) from live or captured traffic
  • Suricata: High-performance network IDS/IPS for signature-based detection with Lua scripting for custom detection logic
  • NetworkMiner: Network forensic analysis tool for extracting files, images, and credentials from PCAP files
  • Scapy: Python packet manipulation library for programmatic packet analysis, beacon detection, and protocol decoding
  • Wireshark: 开源数据包分析器,用于在协议层对网络流量进行深度交互式检查
  • Zeek: 网络分析框架,从实时或捕获的流量生成结构化元数据日志(conn、dns、http、ssl等)
  • Suricata: 高性能网络IDS/IPS,支持基于特征的检测,可通过Lua脚本实现自定义检测逻辑
  • NetworkMiner: 网络取证分析工具,用于从PCAP文件中提取文件、图像和凭证
  • Scapy: Python数据包操作库,用于程序化数据包分析、信标检测和协议解码

Common Scenarios

常见场景

Scenario: Decoding a Custom Binary C2 Protocol

场景:解码自定义二进制C2协议

Context: Malware communicates with its C2 server using a custom binary protocol over TCP port 8443. Standard HTTP analysis yields no results. The protocol structure needs to be reverse engineered from the PCAP.
Approach:
  1. Filter the PCAP for TCP port 8443 conversations and follow the TCP stream
  2. Identify the message framing (length prefix, delimiter, fixed-size headers)
  3. Compare multiple messages to identify static header fields vs variable data fields
  4. Cross-reference with reverse engineering findings from Ghidra (if the binary was analyzed)
  5. Write a Wireshark dissector or Scapy parser for the custom protocol
  6. Create Suricata rules matching the static header bytes for network detection
  7. Document the full protocol specification for threat intelligence sharing
Pitfalls:
  • Analyzing only the first few packets; some C2 protocols change behavior after initial handshake
  • Not decrypting TLS traffic when the sandbox has MITM capabilities
  • Confusing legitimate CDN or cloud traffic with C2 (validate destination IPs)
  • Missing C2 traffic that uses DNS or ICMP instead of TCP/UDP
背景: 恶意软件通过TCP 8443端口使用自定义二进制协议与C2服务器通信。标准HTTP分析无法得到有效结果,需要从PCAP中逆向工程协议结构。
方法:
  1. 在PCAP中过滤TCP 8443端口的会话并跟踪TCP流
  2. 识别消息帧格式(长度前缀、分隔符、固定大小头部)
  3. 对比多条消息,识别静态头部字段与可变数据字段
  4. 与Ghidra逆向工程结果交叉验证(如果已分析二进制文件)
  5. 为自定义协议编写Wireshark dissector或Scapy解析器
  6. 创建匹配静态头部字节的Suricata规则用于网络检测
  7. 记录完整的协议规范用于威胁情报共享
注意事项:
  • 仅分析前几个数据包;部分C2协议在初始握手后会改变行为
  • 当沙箱具备MITM能力时未解密TLS流量
  • 将合法CDN或云流量误认为C2(需验证目标IP)
  • 遗漏使用DNS或ICMP而非TCP/UDP的C2流量

Output Format

输出格式

MALWARE NETWORK TRAFFIC ANALYSIS
===================================
PCAP File:        malware_sandbox.pcap
Duration:         300 seconds
Total Packets:    12,847
Total Bytes:      4.2 MB

DNS ACTIVITY
Total Queries:    47
DGA Detected:     Yes (23 high-entropy queries to .com TLD)
Tunneling:        No
Resolved C2:      update.malicious[.]com -> 185.220.101[.]42

C2 COMMUNICATION
Protocol:         HTTPS (TLS 1.2)
Server:           185.220.101[.]42:443
SNI:              update.malicious[.]com
JA3 Hash:         a0e9f5d64349fb13191bc781f81f42e1
Beacon Interval:  60.2s ± 6.8s (11.3% jitter)
Total Sessions:   237
Data Sent:        147 MB
Data Received:    2.3 MB
Certificate:      CN=update.malicious[.]com (self-signed, expired)

PAYLOAD DOWNLOADS
GET /payload.dll from compromised-site[.]com
  Size: 98,304 bytes
  SHA-256: abc123def456...
  Content-Type: application/octet-stream

EXFILTRATION
Method:           HTTPS POST to /gate.php
Content-Type:     application/octet-stream
Average Size:     15,432 bytes per request
Total Volume:     147 MB over 4 hours

SURICATA ALERTS
[1:2028401] ET MALWARE Generic C2 Beacon Pattern
[1:2028500] ET POLICY Self-Signed Certificate

GENERATED SIGNATURES
SID 9000001: MalwareX HTTP beacon pattern
SID 9000002: MalwareX DNS C2 domain
SID 9000003: MalwareX JA3 TLS fingerprint
MALWARE NETWORK TRAFFIC ANALYSIS
===================================
PCAP File:        malware_sandbox.pcap
Duration:         300 seconds
Total Packets:    12,847
Total Bytes:      4.2 MB

DNS ACTIVITY
Total Queries:    47
DGA Detected:     Yes (23 high-entropy queries to .com TLD)
Tunneling:        No
Resolved C2:      update.malicious[.]com -> 185.220.101[.]42

C2 COMMUNICATION
Protocol:         HTTPS (TLS 1.2)
Server:           185.220.101[.]42:443
SNI:              update.malicious[.]com
JA3 Hash:         a0e9f5d64349fb13191bc781f81f42e1
Beacon Interval:  60.2s ± 6.8s (11.3% jitter)
Total Sessions:   237
Data Sent:        147 MB
Data Received:    2.3 MB
Certificate:      CN=update.malicious[.]com (self-signed, expired)

PAYLOAD DOWNLOADS
GET /payload.dll from compromised-site[.]com
  Size: 98,304 bytes
  SHA-256: abc123def456...
  Content-Type: application/octet-stream

EXFILTRATION
Method:           HTTPS POST to /gate.php
Content-Type:     application/octet-stream
Average Size:     15,432 bytes per request
Total Volume:     147 MB over 4 hours

SURICATA ALERTS
[1:2028401] ET MALWARE Generic C2 Beacon Pattern
[1:2028500] ET POLICY Self-Signed Certificate

GENERATED SIGNATURES
SID 9000001: MalwareX HTTP beacon pattern
SID 9000002: MalwareX DNS C2 domain
SID 9000003: MalwareX JA3 TLS fingerprint