mcpField
A
analyzing-command-and-control-communication

analyzing-command-and-control-communication

github.com/mukul975セキュリティ35.2k530 回インストール8 週間前に更新
リポジトリ

analyzing-command-and-control-communication について

マルウェア分析者やインシデント対応担当者向けのセキュリティ分析スキルです。既知または疑わしい C2 通信の解析、インフラの追跡、検知ルールの作成を支援します。

主な機能

  1. 01C2 プロトコルと通信経路の特定
  2. 02ビーコン間隔と通信パターンの分析
  3. 03メッセージ構造のリバースエンジニアリング
  4. 04既知の C2 フレームワークの特徴照合
  5. 05C2 インフラとフェイルオーバーの把握
  6. 06ネットワーク検知ルールの作成

活用シーン

  1. 01マルウェアの PCAP 通信を分析
  2. 02特定の C2 フレームワーク向け検知シグネチャの作成
  3. 03プライマリーサーバー、代替ドメイン、中継先の追跡

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill analyzing-command-and-control-communication

インストール後、Claude Code で/analyzing-command-and-control-communicationを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

LICENSE
references/
api-reference.md
scripts/
agent.py

詳細

コマンド&コントロール通信の分析

使用する場面

  • マルウェアサンプルのリバースエンジニアリングで、プロトコル分析が必要なネットワーク通信が見つかった場合
  • 特定の C2 フレームワーク(Cobalt Strike、Metasploit、Sliver)向けに、ネットワークレベルの検知シグネチャを作成する場合
  • プライマリーサーバー、フォールバックドメイン、デッドドロップを含む C2 インフラストラクチャをマッピングする場合
  • 暗号化またはエンコードされた C2 トラフィックを分析し、コマンドセットとデータ形式を把握する場合
  • C2 インフラストラクチャのパターンとツールに基づき、マルウェアを脅威アクターに帰属させる場合

一般的なネットワーク異常検知には使用しないでください。マルウェア分析から既知または疑いのある C2 プロトコルを把握することに特化しています。

前提条件

  • マルウェアのネットワークトラフィックをキャプチャした PCAP(サンドボックス、ネットワークタップ、または全パケットキャプチャから取得)
  • パケットレベルの分析用の Wireshark/tshark
  • マルウェアバイナリ内の C2 コードを理解するためのリバースエンジニアリングツール(Ghidra、dnSpy)
  • プロトコル分析とリプレイ用の scapy、dpkt、requests を備えた Python 3.8+
  • C2 インフラストラクチャの相関分析用の脅威インテリジェンスデータベース(VirusTotal、Shodan、Censys)
  • TLS ベースの C2 識別用の JA3/JA3S フィンガープリントデータベース

ワークフロー

ステップ 1:C2 チャネルを特定する

C2 通信に使用されているプロトコルとトランスポートを特定します。

C2 Communication Channels:
━━━━━━━━━━━━━━━━━━━━━━━━━
HTTP/HTTPS:     Most common; uses standard web traffic to blend in
                Indicators: Regular POST/GET requests, specific URI patterns, custom headers

DNS:            Tunneling data through DNS queries and responses
                Indicators: High-volume TXT queries, long subdomain names, high entropy

Custom TCP/UDP: Proprietary binary protocol on non-standard port
                Indicators: Non-HTTP traffic on high ports, unknown protocol

ICMP:           Data encoded in ICMP echo/reply payloads
                Indicators: ICMP packets with large or non-standard payloads

WebSocket:      Persistent bidirectional connection for real-time C2
                Indicators: WebSocket upgrade followed by binary frames

Cloud Services: Using legitimate APIs (Telegram, Discord, Slack, GitHub)
                Indicators: API calls to cloud services from unexpected processes

Email:          SMTP/IMAP for C2 commands and data exfiltration
                Indicators: Automated email operations from non-email processes
ステップ 2:ビーコンパターンを分析する

定期的な通信パターンを明らかにします。

from scapy.all import rdpcap, IP, TCP
from collections import defaultdict
import statistics
import json

packets = rdpcap("c2_traffic.pcap")

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

# Analyze each destination for beaconing
for dst, times in sorted(connections.items()):
    if len(times) < 3:
        continue

    intervals = [times[i+1] - times[i] for i in range(len(times)-1)]
    avg_interval = statistics.mean(intervals)
    stdev = statistics.stdev(intervals) if len(intervals) > 1 else 0
    jitter_pct = (stdev / avg_interval * 100) if avg_interval > 0 else 0
    duration = times[-1] - times[0]

    beacon_data = {
        "destination": dst,
        "connections": len(times),
        "duration_seconds": round(duration, 1),
        "avg_interval_seconds": round(avg_interval, 1),
        "stdev_seconds": round(stdev, 1),
        "jitter_percent": round(jitter_pct, 1),
        "is_beacon": 5 < avg_interval < 7200 and jitter_pct < 25,
    }

    if beacon_data["is_beacon"]:
        print(f"[!] BEACON DETECTED: {dst}")
        print(f"    Interval: {avg_interval:.0f}s +/- {stdev:.0f}s ({jitter_pct:.0f}% jitter)")
        print(f"    Sessions: {len(times)} over {duration:.0f}s")
ステップ 3:C2 プロトコルの構造をデコードする

キャプチャしたトラフィックからメッセージ形式をリバースエンジニアリングします。

# HTTP-based C2 protocol analysis
import dpkt
import base64

with open("c2_traffic.pcap", "rb") as f:
    pcap = dpkt.pcap.Reader(f)

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    if not isinstance(eth.data, dpkt.ip.IP):
        continue
    ip = eth.data
    if not isinstance(ip.data, dpkt.tcp.TCP):
        continue
    tcp = ip.data

    if tcp.dport == 80 or tcp.dport == 443:
        if len(tcp.data) > 0:
            try:
                http = dpkt.http.Request(tcp.data)
                print(f"\n--- C2 REQUEST ---")
                print(f"Method: {http.method}")
                print(f"URI: {http.uri}")
                print(f"Headers: {dict(http.headers)}")
                if http.body:
                    print(f"Body ({len(http.body)} bytes):")
                    # Try Base64 decode
                    try:
                        decoded = base64.b64decode(http.body)
                        print(f"  Decoded: {decoded[:200]}")
                    except:
                        print(f"  Raw: {http.body[:200]}")
            except:
                pass
ステップ 4:C2 フレームワークを特定する

観測されたパターンを既知の C2 フレームワークと照合します。

Known C2 Framework Signatures:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Cobalt Strike:
  - Default URIs: /pixel, /submit.php, /___utm.gif, /ca, /dpixel
  - Malleable C2 profiles customize all traffic characteristics
  - JA3: varies by profile, catalog at ja3er.com
  - Watermark in beacon config (unique per license)
  - Config extraction: use CobaltStrikeParser or 1768.py

Metasploit/Meterpreter:
  - Default staging URI patterns: random 4-char checksum
  - Reverse HTTP(S) handler patterns
  - Meterpreter TLV (Type-Length-Value) protocol structure

Sliver:
  - mTLS, HTTP, DNS, WireGuard transport options
  - Protobuf-encoded messages
  - Unique implant ID in communication

Covenant:
  - .NET-based C2 framework
  - HTTP with customizable profiles
  - Task-based command execution

PoshC2:
  - PowerShell/C# based
  - HTTP with encrypted payloads
  - Cookie-based session management
# Extract Cobalt Strike beacon configuration from PCAP or sample
python3 << 'PYEOF'
# Using CobaltStrikeParser (pip install cobalt-strike-parser)
from cobalt_strike_parser import BeaconConfig

try:
    config = BeaconConfig.from_file("suspect.exe")
    print("Cobalt Strike Beacon Configuration:")
    for key, value in config.items():
        print(f"  {key}: {value}")
except Exception as e:
    print(f"Not a Cobalt Strike beacon or parse error: {e}")
PYEOF
ステップ 5:C2 インフラストラクチャをマッピングする

C2 インフラストラクチャ全体とフェイルオーバーの仕組みを記録します。

# Infrastructure mapping
import requests
import json

c2_indicators = {
    "primary_c2": "185.220.101.42",
    "domains": ["update.malicious.com", "backup.evil.net"],
    "ports": [443, 8443],
    "failover_dns": ["ns1.malicious-dns.com"],
}

# Enrich with Shodan
def shodan_lookup(ip, api_key):
    resp = requests.get(f"https://api.shodan.io/shodan/host/{ip}?key={api_key}")
    if resp.status_code == 200:
        data = resp.json()
        return {
            "ip": ip,
            "ports": data.get("ports", []),
            "os": data.get("os"),
            "org": data.get("org"),
            "asn": data.get("asn"),
            "country": data.get("country_code"),
            "hostnames": data.get("hostnames", []),
            "last_update": data.get("last_update"),
        }
    return None

# Enrich with passive DNS
def pdns_lookup(domain):
    # Using VirusTotal passive DNS
    resp = requests.get(
        f"https://www.virustotal.com/api/v3/domains/{domain}/resolutions",
        headers={"x-apikey": VT_API_KEY}
    )
    if resp.status_code == 200:
        data = resp.json()
        resolutions = []
        for r in data.get("data", []):
            resolutions.append({
                "ip": r["attributes"]["ip_address"],
                "date": r["attributes"]["date"],
            })
        return resolutions
    return []
ステップ 6:ネットワーク検知シグネチャを作成する

分析した C2 の特徴に基づいて検知ルールを作成します。

# Suricata rules for the analyzed C2
cat << 'EOF' > c2_detection.rules
# HTTP beacon pattern
alert http $HOME_NET any -> $EXTERNAL_NET any (
    msg:"MALWARE MalwareX C2 HTTP Beacon";
    flow:established,to_server;
    http.method; content:"POST";
    http.uri; content:"/gate.php"; startswith;
    http.header; content:"User-Agent: Mozilla/5.0 (compatible; MSIE 10.0)";
    threshold:type threshold, track by_src, count 5, seconds 600;
    sid:9000010; rev:1;
)

# JA3 fingerprint match
alert tls $HOME_NET any -> $EXTERNAL_NET any (
    msg:"MALWARE MalwareX TLS JA3 Fingerprint";
    ja3.hash; content:"a0e9f5d64349fb13191bc781f81f42e1";
    sid:9000011; rev:1;
)

# DNS beacon detection (high-entropy subdomain)
alert dns $HOME_NET any -> any any (
    msg:"MALWARE Suspected DNS C2 Tunneling";
    dns.query; pcre:"/^[a-z0-9]{20,}\./";
    threshold:type threshold, track by_src, count 10, seconds 60;
    sid:9000012; rev:1;
)

# Certificate-based detection
alert tls $HOME_NET any -> $EXTERNAL_NET any (
    msg:"MALWARE MalwareX Self-Signed C2 Certificate";
    tls.cert_subject; content:"CN=update.malicious.com";
    sid:9000013; rev:1;
)
EOF

重要な概念

用語定義
ビーコン通信マルウェアから C2 サーバーへの定期的なチェックイン通信です。パターン検知を避けるため、間隔にジッターが加えられることがよくあります。
ジッタービーコン間隔に加えるランダム化です(例:60 秒 +/- 15%)。タイミングパターンの予測を困難にし、検知されにくくします。
Malleable C2オペレーターが C2 トラフィックのあらゆる要素(URI、ヘッダー、エンコード)をカスタマイズし、正規のサービスを装える Cobalt Strike の機能です。
デッドドロップマルウェアが取得する C2 コマンドを投稿する中継地点(ペーストサイト、クラウドストレージ、ソーシャルメディア)です。
ドメインフロンティングTLS の SNI では信頼された CDN ドメインを使用しながら、別のバックエンドにルーティングする手法です。C2 トラフィックが正規のサービスに向かっているように見せかけます。
ファストフラックスC2 ドメインの DNS レコードを急速に変更し、多数の IP に分散させて、テイクダウンの取り組みに対抗する手法です。
C2 フレームワークC2 サーバー、インプラント生成ツール、オペレーターインターフェースを提供するソフトウェアツールキットです(Cobalt Strike、Metasploit、Sliver、Covenant)。

ツールとシステム

  • Wireshark:パケットレベルで詳細な C2 プロトコル分析を行うパケットアナライザー
  • RITA(Real Intelligence Threat Analytics):ビーコン検知と DNS トンネリングのために Zeek ログを分析するオープンソースツール
  • CobaltStrikeParser:サンプルやメモリダンプから Cobalt Strike ビーコンの設定を抽出するツール
  • JA3/JA3S:TLS 実装の特性から C2 フレームワークを識別する TLS フィンガープリンティング手法
  • Shodan/Censys:C2 インフラストラクチャのマッピングと関連サーバーの特定に使うインターネットスキャンプラットフォーム

よくあるシナリオ

シナリオ:カスタムC2プロトコルのリバースエンジニアリング

コンテキスト:マルウェアのサンプルが、TCPポート8443を使って未知のバイナリプロトコルでC2サーバーと通信しています。コマンドセットを把握し、検知シグネチャを作成するには、プロトコルをデコードする必要があります。

アプローチ:

  1. TCPポート8443の通信をPCAPでフィルタリングし、TCPストリームを抽出します
  2. 最初の数回のやり取りを分析し、ハンドシェイク/認証の仕組みを特定します
  3. メッセージ構造(長さプレフィックス、型フィールド、ペイロードのエンコーディング)を特定します
  4. Ghidraでマルウェアの送受信関数の逆アセンブル結果と照合します
  5. コマンドディスパッチャーを特定し、各コマンドコードの機能を記録します
  6. 継続的なトラフィック分析のため、Pythonでプロトコルデコーダーを作成します
  7. プロトコルのハンドシェイクまたは固定ヘッダーバイト列に一致するSuricataルールを作成します

注意点:

  • プロトコルが固定的だと思い込まないこと。一部のC2フレームワークでは、ハンドシェイク中に暗号化方式がネゴシエートされます
  • すべてのコマンドタイプを確認できるだけのトラフィックを取得できていないこと(まれにしか実行されないコマンドもあります)
  • プライマリチャネルが失敗した際に有効になる、フォールバックC2チャネル(DNS、ICMP)を見落とすこと
  • 暗号化されたペイロードデータとプロトコルのフレーミング構造を混同すること

出力形式

C2 COMMUNICATION ANALYSIS REPORT
===================================
Sample:           malware.exe (SHA-256: e3b0c44...)
C2 Framework:     Cobalt Strike 4.9

BEACON CONFIGURATION
C2 Server:        hxxps://185.220.101[.]42/updates
Beacon Type:      HTTPS (reverse)
Sleep:            60 seconds
Jitter:           15%
User-Agent:       Mozilla/5.0 (Windows NT 10.0; Win64; x64)
URI (GET):        /dpixel
URI (POST):       /submit.php
Watermark:        1234567890

PROTOCOL ANALYSIS
Transport:        HTTPS (TLS 1.2)
JA3 Hash:         a0e9f5d64349fb13191bc781f81f42e1
Certificate:      CN=Microsoft Update (self-signed)
Encoding:         Base64 with XOR key 0x69
Command Format:   [4B length][4B command_id][payload]

COMMAND SET
0x01 - Sleep          Change beacon interval
0x02 - Shell          Execute cmd.exe command
0x03 - Download       Transfer file from C2
0x04 - Upload         Exfiltrate file to C2
0x05 - Inject         Process injection
0x06 - Keylog         Start keylogger
0x07 - Screenshot     Capture screen

INFRASTRUCTURE
Primary:          185.220.101[.]42 (AS12345, Hosting Co, NL)
Failover:         91.215.85[.]17 (AS67890, VPS Provider, RU)
DNS:              update.malicious[.]com -> 185.220.101[.]42
Registrar:        NameCheap
Registration:     2025-09-01

DETECTION SIGNATURES
SID 9000010:      HTTP beacon pattern
SID 9000011:      JA3 TLS fingerprint
SID 9000013:      C2 certificate match

コメント