--- name: c2-protocol-analysis description: > Reverse engineer and analyze command-and-control (C2) communication protocols used by malware. Covers HTTP/S beaconing analysis (including Cobalt Strike malleable profiles), DNS-based C2 tunneling, custom binary protocols, domain fronting detection, JA3/JA3S TLS fingerprinting, DGA reverse engineering, and protocol emulation for dynamic analysis. Use when you need to understand how malware communicates with its infrastructure or when building network-level detections. --- # C2 Protocol Analysis Reverse engineer command-and-control communication to understand how malware receives commands, exfiltrates data, and maintains persistence through network channels. ## Prerequisites - **Python 3.10+**: `scapy`, `dpkt`, `pyshark`, `dns.resolver` - **Tools**: Wireshark/tshark, mitmproxy, fakeDNS, INetSim - **Optional**: JA3 library, `dnstwist`, `dgad` (DGA detector) - **Environment**: Isolated network with traffic capture capability ## Step-by-Step Instructions ### Step 1: Capture and Identify C2 Traffic Isolate the malware's network communications from background noise. **Capture with tshark:** ```bash # Capture all traffic from the analysis VM tshark -i eth0 -w capture.pcap -f "host 10.0.0.100" # Filter for likely C2 traffic (exclude common benign) tshark -r capture.pcap -Y "!(dns.qry.name contains \"microsoft\" or dns.qry.name contains \"windowsupdate\")" -w filtered.pcap ``` **Run the analyzer for initial assessment:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode identify --output c2_assessment.json ``` **Identify beaconing patterns:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode beacon --output beacon_analysis.json ``` Beaconing indicators: | Pattern | Description | Tool | |---------|-------------|------| | Regular intervals | Fixed sleep timer (e.g., every 60s) | Statistical analysis | | Jittered intervals | Randomized ±% around base interval | Distribution analysis | | Consistent payload size | Same request/response sizes | Packet length histogram | | Unusual hours | Traffic during off-hours only | Time-of-day analysis | ### Step 2: Analyze HTTP/S C2 Communication Most modern malware uses HTTP/S for C2 to blend with legitimate traffic. **Extract HTTP metadata:** ```bash tshark -r capture.pcap -Y "http.request" -T fields \ -e frame.time -e ip.dst -e http.host -e http.request.uri \ -e http.user_agent -e http.content_type -e http.request.method ``` **Detect Cobalt Strike malleable profiles:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode cobalt-strike --output cs_analysis.json ``` Key HTTP C2 indicators: - **URI patterns**: `/api/v1/`, `/updates/check`, `/pixel.gif`, `/submit.php` - **Custom headers**: Non-standard headers for data encoding (X-Request-ID with encoded data) - **Cookie abuse**: Session cookies carrying encoded commands/responses - **POST body encoding**: Base64, XOR, custom encoding in POST data - **User-Agent anomalies**: Static UA strings, outdated browsers, non-browser UAs **Cobalt Strike indicators:** ```bash # Check for default Cobalt Strike patterns tshark -r capture.pcap -Y "http.request.uri matches \"/[a-zA-Z0-9]{4}$\"" -T fields -e http.request.uri # Check for checksum8 URI pattern (CS default) python3 -c " import sys uri = sys.argv[1] checksum = sum(ord(c) for c in uri.lstrip('/')) % 256 print(f'URI: {uri}, Checksum: {checksum}') print('Matches CS beacon: ' + str(checksum == 92)) print('Matches CS stager: ' + str(checksum == 93)) " "/aB3d" ``` ### Step 3: Analyze DNS-Based C2 DNS tunneling encodes data in DNS queries and responses. **Detect DNS tunneling:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode dns-tunnel --output dns_analysis.json ``` **Manual DNS analysis:** ```bash # Extract all DNS queries tshark -r capture.pcap -Y "dns.qry.name" -T fields -e dns.qry.name -e dns.qry.type | sort | uniq -c | sort -rn # Look for high-entropy subdomains (tunneling indicator) tshark -r capture.pcap -Y "dns.qry.name" -T fields -e dns.qry.name | \ awk -F. '{print length($1), $0}' | sort -rn | head -20 # Check for TXT record abuse tshark -r capture.pcap -Y "dns.qry.type == 16" -T fields -e dns.qry.name -e dns.txt ``` **DNS tunneling indicators:** | Indicator | Threshold | Meaning | |-----------|-----------|---------| | Subdomain length | > 30 chars | Data encoded in subdomain | | Query frequency | > 100/min to same domain | Active data transfer | | TXT record responses | Large TXT responses | Data exfiltration channel | | Unique subdomain ratio | > 90% unique | Each query carries different data | | Entropy of subdomains | > 3.5 bits/char | Encoded/encrypted data | ### Step 4: Reverse Engineer Custom Binary Protocols Some malware uses custom TCP/UDP protocols for C2. **Extract TCP stream data:** ```bash # Follow a specific TCP stream tshark -r capture.pcap -Y "tcp.stream eq 0" -T fields -e data.data > stream_hex.txt # Convert to binary for analysis python3 -c " import sys with open('stream_hex.txt') as f: for line in f: sys.stdout.buffer.write(bytes.fromhex(line.strip())) " > stream_raw.bin ``` **Analyze protocol structure:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode protocol --stream 0 --output protocol_analysis.json ``` **Common custom protocol elements:** - **Magic bytes**: Fixed header bytes identifying the protocol (e.g., `\xDE\xAD`) - **Length field**: Packet size (2-4 bytes, big/little endian) - **Command ID**: Operation type (1-2 bytes) - **Session/bot ID**: Unique identifier for the infected host - **Encryption layer**: XOR, RC4, AES wrapping the payload - **Checksum/CRC**: Integrity validation ### Step 5: Detect Domain Fronting and CDN Abuse Identify C2 traffic hiding behind legitimate CDN infrastructure. **Check for domain fronting:** ```bash # Compare TLS SNI with HTTP Host header tshark -r capture.pcap -Y "ssl.handshake.extensions_server_name && http.host" \ -T fields -e ssl.handshake.extensions_server_name -e http.host | \ awk '$1 != $2 {print "FRONTING: SNI=" $1 " Host=" $2}' ``` **CDN abuse indicators:** - TLS SNI points to legitimate CDN domain (e.g., `cdn.example.com`) - HTTP Host header points to attacker-controlled domain - Traffic to cloud provider IPs (AWS CloudFront, Azure CDN, Fastly) - Unusual paths on legitimate-looking domains ### Step 6: TLS Fingerprinting with JA3/JA3S Identify malware by its TLS client/server fingerprints. **Extract JA3 hashes:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode ja3 --output ja3_fingerprints.json ``` **Manual JA3 extraction:** ```bash # Use tshark with JA3 fields (requires Wireshark 3.x+) tshark -r capture.pcap -Y "tls.handshake.type == 1" \ -T fields -e ip.src -e ip.dst -e tls.handshake.ja3 ``` **Compare against known malware JA3 databases:** - Cobalt Strike default: `72a589da586844d7f0818ce684948eea` - Metasploit Meterpreter: `5d65ea3ab1d764ef1d24e6e6f4a1c141` - Compare with https://ja3er.com/ and abuse.ch JA3 feeds ### Step 7: Reverse Engineer DGA (Domain Generation Algorithm) Extract and predict domains generated by DGA-based malware. **Identify DGA behavior:** ```bash python3 scripts/c2_analyzer.py --pcap capture.pcap --mode dga --output dga_analysis.json ``` **DGA indicators in DNS traffic:** ```bash # High NXDomain ratio indicates DGA probing tshark -r capture.pcap -Y "dns.flags.rcode == 3" -T fields -e dns.qry.name | \ awk -F. '{print $NF}' | sort | uniq -c | sort -rn # Look for algorithmically generated patterns tshark -r capture.pcap -Y "dns.flags.rcode == 3" -T fields -e dns.qry.name | head -50 ``` **Reverse engineering the DGA:** 1. Identify the seed (date, hardcoded value, system info) 2. Extract the algorithm from the binary (string manipulation, math operations) 3. Determine the TLD selection logic 4. Generate the full domain list for sinkholing ### Step 8: Build Protocol Emulator for Dynamic Analysis Create a fake C2 server to interact with the malware. **Set up INetSim for generic emulation:** ```bash # Start INetSim to emulate common services inetsim --data-dir /var/lib/inetsim --log-dir /var/log/inetsim ``` **Build custom C2 emulator:** ```bash python3 scripts/c2_analyzer.py --mode emulate \ --protocol-spec protocol_analysis.json \ --listen-port 443 \ --output interaction_log.json ``` **Protocol emulation tips:** - Start with a passive listener to capture initial beacon - Replay recorded responses to keep malware active - Gradually modify responses to trigger different behaviors - Log all interactions for behavioral analysis ## Output Format ```json { "c2_channels": [ { "protocol": "HTTPS", "host": "updates.example.com", "port": 443, "uri_pattern": "/api/v1/check", "method": "POST", "beacon_interval_seconds": 60, "jitter_percentage": 15, "encoding": "base64 in cookie", "framework": "Cobalt Strike", "ja3_hash": "72a589da586844d7f0818ce684948eea" } ], "dns_tunneling": { "detected": false, "domain": null }, "dga": { "detected": true, "seed_type": "date-based", "tlds": [".com", ".net", ".org"], "daily_domain_count": 500, "sample_domains": ["xkj3mf9a.com", "pq7bnw2e.net"] }, "domain_fronting": { "detected": false }, "iocs": { "c2_domains": ["updates.example.com"], "c2_ips": ["198.51.100.50"], "ja3_hashes": ["72a589da586844d7f0818ce684948eea"], "uri_patterns": ["/api/v1/*"] }, "mitre_attack": ["T1071.001", "T1568.002", "T1573.001", "T1008"] } ``` ## Tips - Capture traffic for at least 24 hours to identify all beaconing patterns and sleep cycles - Use mitmproxy with custom certificates to decrypt HTTPS C2 traffic in your analysis VM - Many C2 frameworks have default configurations — check for known fingerprints first - DGA malware may only resolve one domain per day; adjust your analysis timeline accordingly - Domain fronting detection requires comparing TLS SNI with HTTP Host headers - Some malware uses multiple C2 channels as fallbacks — map all of them - JA3 hashes can change with minor TLS configuration changes; use them as one signal among many - When emulating C2, start with minimal responses and increase complexity gradually