mcpField
P
performing-malware-triage-with-yara

performing-malware-triage-with-yara

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

performing-malware-triage-with-yara について

マルウェア分析者向けの YARA トリアージスキルです。既存ルールによるスキャン、検出ルールの作成、誤検知の確認を扱い、未知の挙動は特定できない点も説明します。

主な機能

  1. 01ルールセットによるサンプルスキャン
  2. 02文字列・バイトパターンルールの作成
  3. 03PE モジュールによる構造検出
  4. 04Python による一括スキャンの自動化
  5. 05誤検知の検証と性能調整

活用シーン

  1. 01既知マルウェアの一括分類
  2. 02新しいマルウェアファミリーの検出ルール作成
  3. 03ファイル共有やメモリダンプでの脅威探索
  4. 04サンプルトリアージの自動化パイプライン構築

インストール

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

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill performing-malware-triage-with-yara

インストール後、Claude Code で/performing-malware-triage-with-yaraを入力して読み込まれたか確認します。

同梱ファイル

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

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

詳細

YARA を使用したマルウェアのトリアージ

使用する場面

  • 既知のファミリーのシグネチャと照合し、大量のマルウェアサンプルを迅速に分類する
  • 新たに分析したマルウェアファミリーの固有のバイトパターンに基づいて検知ルールを作成する
  • ファイル共有、エンドポイント、メモリダンプをスキャンし、特定の脅威の痕跡を探す
  • 手動分析の前にサンプルを分類する自動トリアージパイプラインを構築する
  • YARA スキャンを使用して、企業内で既知の脅威の亜種をハンティングする

唯一の分析手法としては使用しないでください。 YARA によるトリアージでは既知のパターンを特定できますが、新たなマルウェアや未知のマルウェアの振る舞いは明らかになりません。

前提条件

  • YARA 4.x がインストールされていること(apt install yara または pip install yara-python)
  • YARA ルールのリポジトリ(YARA-Rules、awesome-yara、Malpedia のルール、Florian Roth's signature-base)
  • スクリプトによるスキャン用の Python 3.8+ と yara-python
  • バッチスキャン用にディレクトリ構造で整理されたサンプルコレクション
  • ルール作成に必要な PE ファイル形式、16 進数パターン、正規表現の知識

ワークフロー

ステップ 1:既存のルールセットでサンプルをスキャンする

コミュニティおよび商用の YARA ルールを適用して、サンプルを分類します。

# Scan a single file
yara -s malware_rules.yar suspect.exe

# Scan a directory of samples
yara -r malware_rules.yar /path/to/samples/

# Scan with multiple rule files
yara -r rules/apt_rules.yar rules/ransomware_rules.yar rules/trojan_rules.yar suspect.exe

# Scan with timeout (prevent hanging on large files)
yara -t 30 malware_rules.yar suspect.exe

# Scan and show matching strings
yara -s -r malware_rules.yar suspect.exe

# Scan with compiled rules (faster for repeated scans)
yarac malware_rules.yar compiled_rules.yarc
yara compiled_rules.yarc suspect.exe
# Download community rule sets
git clone https://github.com/Yara-Rules/rules.git yara-community-rules
git clone https://github.com/Neo23x0/signature-base.git signature-base

# Scan with signature-base
yara -r signature-base/yara/*.yar suspect.exe
ステップ 2:固有の文字列パターンのルールを作成する

マルウェア分析中に抽出した文字列に基づいて YARA ルールを作成します。

rule MalwareX_Strings {
    meta:
        description = "Detects MalwareX based on unique strings"
        author = "analyst"
        date = "2025-09-15"
        reference = "Internal Analysis Report #1547"
        hash = "e3b0c44298fc1c149afbf4c8996fb924"
        tlp = "WHITE"

    strings:
        // C2 URL pattern
        $url1 = "/gate.php?id=" ascii
        $url2 = "/panel/connect.php" ascii

        // Unique mutex name
        $mutex = "Global\\CryptLocker_2025" ascii wide

        // User-Agent string
        $ua = "Mozilla/5.0 (compatible; MSIE 10.0)" ascii

        // Registry persistence path
        $reg = "Software\\Microsoft\\Windows\\CurrentVersion\\Run\\WindowsUpdate" ascii

        // Campaign identifier
        $campaign = "campaign_2025_q3" ascii

    condition:
        uint16(0) == 0x5A4D and      // PE file (MZ header)
        filesize < 500KB and          // Size constraint
        ($url1 or $url2) and          // At least one C2 URL
        ($mutex or $campaign) and     // Campaign identifier
        $ua                           // Specific User-Agent
}
ステップ 3:バイトパターンのルールを作成する

特定のコードシーケンスに一致するルールを作成します。

rule MalwareX_Decryptor {
    meta:
        description = "Detects MalwareX XOR decryption routine"
        author = "analyst"
        date = "2025-09-15"

    strings:
        // XOR decryption loop (x86 assembly)
        // mov al, [esi+ecx]
        // xor al, [edi+ecx]
        // mov [esi+ecx], al
        // inc ecx
        // cmp ecx, edx
        // jl loop
        $xor_loop = { 8A 04 0E 32 04 0F 88 04 0E 41 3B CA 7C F3 }

        // RC4 KSA initialization (256-byte loop)
        $rc4_ksa = { 33 C0 88 04 ?8 40 3D 00 01 00 00 7? }

        // Embedded RSA public key marker
        $rsa_key = { 06 02 00 00 00 A4 00 00 52 53 41 31 }  // PUBLICKEYBLOB

    condition:
        uint16(0) == 0x5A4D and
        ($xor_loop or $rc4_ksa) and
        $rsa_key
}
ステップ 4:PE モジュールを使用したルールを作成する

YARA の PE モジュールを活用して、構造に基づく検知を行います。

import "pe"
import "hash"
import "math"

rule MalwareX_PE_Characteristics {
    meta:
        description = "Detects MalwareX by PE structure and imports"
        author = "analyst"

    condition:
        pe.is_pe and

        // Compiled within specific timeframe
        pe.timestamp > 1693526400 and   // After 2023-09-01
        pe.timestamp < 1727740800 and   // Before 2024-10-01

        // Specific import hash
        pe.imphash() == "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" or

        // Suspicious import combination
        (
            pe.imports("kernel32.dll", "VirtualAllocEx") and
            pe.imports("kernel32.dll", "WriteProcessMemory") and
            pe.imports("kernel32.dll", "CreateRemoteThread") and
            pe.imports("wininet.dll", "InternetOpenA")
        ) or

        // High entropy .text section (packed)
        (
            for any section in pe.sections : (
                section.name == ".text" and
                math.entropy(section.raw_data_offset, section.raw_data_size) > 7.0
            )
        )
}

rule MalwareX_Rich_Header {
    meta:
        description = "Detects MalwareX by Rich header hash"

    condition:
        pe.is_pe and
        hash.md5(pe.rich_signature.clear_data) == "abc123def456abc123def456abc123de"
}
ステップ 5:Python でバッチトリアージを行う

サンプルコレクションのスキャンを自動化します。

import yara
import os
import json
import hashlib
from datetime import datetime

# Compile all rule files
rule_files = {
    "apt": "rules/apt_rules.yar",
    "ransomware": "rules/ransomware_rules.yar",
    "trojan": "rules/trojan_rules.yar",
    "custom": "rules/custom_rules.yar",
}
rules = yara.compile(filepaths=rule_files)

# Scan sample directory
results = []
sample_dir = "/path/to/samples"

for filename in os.listdir(sample_dir):
    filepath = os.path.join(sample_dir, filename)
    if not os.path.isfile(filepath):
        continue

    with open(filepath, "rb") as f:
        data = f.read()
        sha256 = hashlib.sha256(data).hexdigest()

    matches = rules.match(filepath)

    result = {
        "filename": filename,
        "sha256": sha256,
        "size": len(data),
        "matches": [],
        "classification": "UNKNOWN",
    }

    for match in matches:
        result["matches"].append({
            "rule": match.rule,
            "namespace": match.namespace,
            "tags": match.tags,
            "strings": [(hex(s[0]), s[1], s[2].decode("utf-8", errors="replace")[:100])
                       for s in match.strings] if match.strings else []
        })

    if result["matches"]:
        result["classification"] = result["matches"][0]["namespace"].upper()

    results.append(result)

# Summary
classified = sum(1 for r in results if r["classification"] != "UNKNOWN")
print(f"Scanned: {len(results)} samples")
print(f"Classified: {classified} ({classified/len(results)*100:.1f}%)")
print(f"Unknown: {len(results)-classified}")

# Export results
with open("triage_results.json", "w") as f:
    json.dump(results, f, indent=2)
ステップ 6:ルールを検証して最適化する

誤検知とパフォーマンスについてルールをテストします。

# Test rule syntax
yara -C custom_rules.yar

# Scan known-clean directory to check false positives
yara -r custom_rules.yar /path/to/clean_files/ > false_positives.txt
wc -l false_positives.txt

# Benchmark rule performance
time yara -r custom_rules.yar /path/to/large_sample_collection/

# Profile individual rule performance
yara -p custom_rules.yar suspect.exe

主要な概念

用語定義
YARA ルール特定のファイルやマルウェアファミリーを特定する文字列、バイトシーケンス、条件を定義したパターンマッチングルール
条件文字列の一致、ファイルのプロパティ、モジュール関数を組み合わせ、ルールが一致するかどうかを判定するブール式
16 進数文字列マシンコードやバイナリデータに一致させるための、任意のワイルドカード(??)やジャンプ([N-M])を含むバイトパターン
PE モジュール構造に基づくマッチング用に、PE ファイルのプロパティ(インポート、セクション、タイムスタンプ、リソース)へのアクセスを提供する YARA モジュール
ImphashPE ファイルのインポートテーブルの MD5 ハッシュ。同じファミリーのサンプルは、多くの場合、同じインポートハッシュを共有します
Rich Headerコンパイラー/リンカーのメタデータを含む、文書化されていない PE 構造。マルウェアのビルド環境内で一貫しています
YARA-C繰り返し使用するルールを事前コンパイルすることで、より高速なスキャンを可能にするコンパイル済み YARA ルール形式

ツールとシステム

  • YARA:テキスト、16 進数、構造パターンに基づいてマルウェアを特定、分類するパターンマッチングエンジン
  • yara-python:スクリプトによるスキャン、ルールのコンパイル、分析パイプラインとの統合を可能にする YARA 用 Python バインディング
  • yarGen:固有の文字列とオペコードを特定し、マルウェアサンプルからルールを作成する YARA ルール自動生成ツール
  • YARA-Rules(GitHub):マルウェアファミリー、エクスプロイト、不審な痕跡を網羅した、コミュニティ管理の YARA ルールリポジトリ
  • Malpedia YARA:Malpedia マルウェア百科事典が厳選した、高品質でファミリー固有の YARA ルール

よくあるシナリオ

シナリオ:新しいマルウェアファミリーの検出ルールの作成

コンテキスト:新しいマルウェアサンプルのリバースエンジニアリングにより、固有の文字列、バイトパターン、PE の特性が特定されました。組織全体でのハンティングと継続的な検出のために、YARA ルールが必要です。

アプローチ:

  1. アンパックしたバイナリから固有の文字列を抽出します(C2 URL、ミューテックス名、レジストリパス)
  2. 暗号化ルーチンまたは C2 プロトコルから固有のバイト列を特定します(Ghidra の解析を使用)
  3. PE の特性を記録します(imphash、Rich ヘッダーハッシュ、セクション名、コンパイル時刻の範囲)
  4. 文字列、バイトパターン、PE モジュールの条件を組み合わせた YARA ルールを記述します
  5. 既知のマルウェアサンプルに対してテストし、真陽性の検出を確認します
  6. クリーンなファイルコーパス(Windows のシステムファイル、一般的なアプリケーション)に対してテストし、誤検知がゼロであることを確認します
  7. 組織のスキャンインフラストラクチャと脅威インテリジェンスプラットフォームに導入します

注意点:

  • ルールを単一のサンプルに特化しすぎると、わずかな変更が加えられた亜種を検出できなくなります
  • ルールが汎用的すぎると、正規のソフトウェアにも一致し、誤検知が発生します
  • 一般的なライブラリやフレームワーク(OpenSSL の文字列など)に現れる文字列を使用しないでください
  • 導入前に、十分に大規模なクリーンなコーパスでテストしてください

出力形式

YARA TRIAGE RESULTS
=====================
Scan Date:        2025-09-15
Rule Sets:        apt_rules (847 rules), ransomware_rules (312 rules),
                  trojan_rules (1,204 rules), custom_rules (45 rules)
Samples Scanned:  2,500
Processing Time:  47 seconds

CLASSIFICATION SUMMARY
APT:              12 samples (0.5%)
Ransomware:       187 samples (7.5%)
Trojan:           423 samples (16.9%)
Unknown:          1,878 samples (75.1%)

TOP MATCHING RULES
Rule                         Matches  Family
MalwareX_C2_Beacon           45       MalwareX
LockBit3_Ransom_Note         38       LockBit 3.0
Emotet_Epoch5_Loader         32       Emotet
CobaltStrike_Beacon_Config   28       Cobalt Strike
QakBot_DLL_Loader            25       QakBot

SAMPLE DETAIL
File:    suspect.exe
SHA-256: e3b0c44298fc1c149afbf4c8996fb924...
Matches:
  [1] MalwareX_Strings (custom)
      - $url1 at 0x4A20: "/gate.php?id="
      - $mutex at 0x5100: "Global\\CryptLocker_2025"
  [2] MalwareX_Decryptor (custom)
      - $xor_loop at 0x401200: { 8A 04 0E 32 04 0F ... }
  [3] MalwareX_PE_Characteristics (custom)
      - PE import combination matched
Classification: MALWAREX (HIGH CONFIDENCE)

コメント