mcpField
D
deobfuscating-javascript-malware

deobfuscating-javascript-malware

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

deobfuscating-javascript-malware について

セキュリティ分析者向けの JavaScript マルウェア解析スキルです。隔離環境での安全な抽出、段階的な難読化解除、ペイロード調査を扱います。

主な機能

  1. 01スクリプトの安全な抽出と確認
  2. 02一般的な難読化手法の特定
  3. 03解析妨害トラップの除去
  4. 04文字列の段階的なデコード
  5. 05eval チェーンの安全な解決
  6. 06ペイロード指標の抽出

活用シーン

  1. 01フィッシングページの難読化スクリプト調査
  2. 02EC サイトに埋め込まれたスキマーの分析
  3. 03スクリプトを含む悪意あるメール添付の調査

インストール

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

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill deobfuscating-javascript-malware

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

同梱ファイル

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

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

詳細

JavaScript マルウェアの難読化解除

使用する状況

  • 認証情報を窃取したりリダイレクトしたりする難読化された JavaScript を含むフィッシングページを調査する場合
  • EC サイトに埋め込まれたウェブスキマー(Magecart 型)を分析する場合
  • 第 2 段階のマルウェアをダウンロードして実行する JavaScript ドロッパーの難読化を解除する場合
  • 難読化されたスクリプトを埋め込んだ HTML ファイルを含む、悪意のあるメール添付ファイルを調査する場合
  • エクスプロイトの配布を隠すために JavaScript を高度に難読化する、ブラウザーエクスプロイトキットを分析する場合

難読化された JavaScript が単なる本番コードの圧縮である場合は、使用しないでください。代わりに、一般的なコード整形ツールを使用してください。

前提条件

  • 制御された環境で JavaScript を実行およびデバッグするための Node.js 18 以降
  • コード整形用の jsbeautifier ライブラリを含む Python 3.8 以降
  • 隔離されたブラウザーで制御された実行を行うためのブラウザーデベロッパーツール(Chrome DevTools)
  • エンコード/デコード処理用の CyberChef(https://gchq.github.io/CyberChef/)
  • JavaScript の自動難読化解除に使用する de4js または JStillery
  • 本番システムや機密データにアクセスできない、隔離された分析用 VM

ワークフロー

ステップ 1:難読化されたスクリプトを安全に抽出して調査する

実行せずに悪意のある JavaScript を分離します。

# Extract JavaScript from HTML file
python3 << 'PYEOF'
from html.parser import HTMLParser

class ScriptExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_script = False
        self.scripts = []
        self.current = ""

    def handle_starttag(self, tag, attrs):
        if tag == "script":
            self.in_script = True
            self.current = ""

    def handle_endtag(self, tag):
        if tag == "script":
            self.in_script = False
            if self.current.strip():
                self.scripts.append(self.current)

    def handle_data(self, data):
        if self.in_script:
            self.current += data

with open("malicious_page.html") as f:
    parser = ScriptExtractor()
    parser.feed(f.read())

for i, script in enumerate(parser.scripts):
    with open(f"script_{i}.js", "w") as f:
        f.write(script)
    print(f"Extracted script_{i}.js ({len(script)} bytes)")
PYEOF

# Beautify the extracted JavaScript
npx js-beautify script_0.js -o script_0_pretty.js
ステップ 2:難読化手法を特定する

使用されている難読化手法を分類します。

Common JavaScript Obfuscation Techniques:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
String Encoding:
  - Hex encoding:          "\x68\x65\x6c\x6c\x6f" -> "hello"
  - Unicode escapes:       "\u0068\u0065\u006c\u006c\u006f" -> "hello"
  - Base64:                atob("aGVsbG8=") -> "hello"
  - charCodeAt/fromCharCode: String.fromCharCode(104,101,108,108,111)
  - Array-based lookup:    var _0x1234 = ["hello","world"]; _0x1234[0]

Eval Chains:
  - eval(atob("..."))
  - eval(unescape("..."))
  - new Function("return " + decoded)()
  - document.write("<script>" + decoded + "</script>")
  - setTimeout(decoded, 0)

Control Flow:
  - Switch-case dispatcher with shuffled case order
  - Opaque predicates (always-true/false conditions)
  - Dead code insertion
  - Variable name mangling (_0x4a3b, _0xab12)

Anti-Analysis:
  - Debugger traps: setInterval(function(){debugger;}, 100)
  - Console detection: overriding console.log
  - Timing checks: performance.now() deltas
  - DevTools detection: window.outerWidth - window.innerWidth > 100
ステップ 3:解析妨害の保護機能を取り除く

デバッグ対策および解析対策のトラップを無効化します。

// Remove debugger traps before analysis
// Replace in the obfuscated script:

// Before:
setInterval(function() { debugger; }, 100);

// After (neutralized):
setInterval(function() { /* debugger removed */ }, 100);

// Neutralize DevTools detection
// Before:
if (window.outerWidth - window.innerWidth > 160) { window.location = "about:blank"; }

// After:
if (false) { window.location = "about:blank"; }

// Neutralize timing checks
// Override performance.now to return consistent values
const originalNow = performance.now;
performance.now = function() { return 0; };
ステップ 4:文字列の難読化レイヤーをデコードする

エンコードされた文字列を段階的にデコードします。

# Python script to decode common JS obfuscation patterns
import re
import base64
import urllib.parse

def decode_hex_strings(code):
    """Replace \\xNN sequences with ASCII characters"""
    def hex_replace(match):
        hex_str = match.group(0)
        try:
            return bytes.fromhex(hex_str.replace("\\x", "")).decode("ascii")
        except:
            return hex_str
    return re.sub(r'(?:\\x[0-9a-fA-F]{2})+', hex_replace, code)

def decode_unicode_escapes(code):
    """Replace \\uNNNN sequences with characters"""
    def unicode_replace(match):
        return chr(int(match.group(1), 16))
    return re.sub(r'\\u([0-9a-fA-F]{4})', unicode_replace, code)

def decode_charcode_arrays(code):
    """Resolve String.fromCharCode calls"""
    def charcode_replace(match):
        codes = [int(c.strip()) for c in match.group(1).split(",")]
        return '"' + "".join(chr(c) for c in codes) + '"'
    return re.sub(r'String\.fromCharCode\(([0-9,\s]+)\)', charcode_replace, code)

def decode_base64_strings(code):
    """Resolve atob() calls with static strings"""
    def atob_replace(match):
        try:
            decoded = base64.b64decode(match.group(1)).decode("utf-8")
            return f'"{decoded}"'
        except:
            return match.group(0)
    return re.sub(r'atob\(["\']([A-Za-z0-9+/=]+)["\']\)', atob_replace, code)

# Apply all decoders
with open("script_0.js") as f:
    code = f.read()

code = decode_hex_strings(code)
code = decode_unicode_escapes(code)
code = decode_charcode_arrays(code)
code = decode_base64_strings(code)

with open("script_0_decoded.js", "w") as f:
    f.write(code)
print("Decoded strings written to script_0_decoded.js")
ステップ 5:eval チェーンを安全に解決する

実行せずに eval/Function コンストラクターのチェーンを展開します。

// Node.js script to safely resolve eval chains
// Run in isolated environment: node --experimental-vm-modules deobfuscate.js

const vm = require('vm');

// Create sandboxed context with logging
const sandbox = {
    eval: function(code) {
        console.log("=== EVAL INTERCEPTED ===");
        console.log(code.substring(0, 500));
        console.log("========================");
        return code; // Return the code instead of executing it
    },
    document: {
        write: function(html) {
            console.log("=== DOCUMENT.WRITE INTERCEPTED ===");
            console.log(html.substring(0, 500));
        },
        getElementById: function() { return { innerHTML: "" }; }
    },
    window: { location: { href: "" } },
    atob: function(s) { return Buffer.from(s, 'base64').toString(); },
    unescape: unescape,
    setTimeout: function(fn) { if (typeof fn === 'string') console.log("TIMEOUT CODE:", fn); },
    console: console,
    String: String,
    Array: Array,
    parseInt: parseInt,
    RegExp: RegExp,
};

const context = vm.createContext(sandbox);

// Load and execute the obfuscated script in sandbox
const fs = require('fs');
const code = fs.readFileSync('script_0.js', 'utf8');

try {
    vm.runInContext(code, context, { timeout: 5000 });
} catch(e) {
    console.log("Execution error (expected):", e.message);
}
ステップ 6:難読化を解除したペイロードを分析する

明らかになった悪意のあるロジックを調査します。

Deobfuscated Malware Categories and IOC Extraction:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Credential Harvester:
  - Form action URLs (exfiltration endpoints)
  - XMLHttpRequest/fetch destinations
  - Targeted input field names (username, password, cc_number)

Web Skimmer (Magecart):
  - Payment form overlay injection
  - Card data exfiltration URLs
  - Keylogger event listeners (onkeypress, oninput)

Redirect Script:
  - Destination URLs in location.href assignments
  - Conditional redirects based on user-agent or referrer
  - Cloaking logic (show benign content to bots)

Exploit Kit Landing:
  - Browser/plugin version checks
  - Exploit payload URLs
  - Shellcode embedded as arrays or encoded strings

主要な概念

用語定義
Eval チェーンeval()、Function()、または document.write() の呼び出しを入れ子にしたもので、それぞれが難読化の 1 レイヤーをデコードしてから次へ渡します
文字列配列のローテーションすべての文字列をシャッフルした配列に格納し、計算したインデックスで参照して文字列リテラルを隠す難読化手法です
デッドコードの挿入実行されない機能しないコードブロックを追加して解析を複雑化し、パターンマッチングを混乱させます
不透明述語結果があらかじめ決まっているものの、静的に判断するのが難しい条件式です。制御フローを隠すために使用されます
デバッグ対策debugger 文やタイミングチェックなど、ブラウザーの DevTools やデバッガーの使用を検出して阻止する JavaScript の手法です
ウェブスキマー決済フォームからカード情報を窃取するため、EC サイトに埋め込まれた悪意のある JavaScript です(Magecart 攻撃)

ツールとシステム

  • CyberChef:多層の難読化を解く際に役立つ、エンコード/デコード変換用の GCHQ のウェブベースツールです
  • de4js:一般的な難読化ツール(obfuscator.io、JScrambler)に対応した、オンラインの JavaScript 難読化解除ツールです
  • Node.js VM Module:傍受した API を使って難読化コードを安全に評価するための、サンドボックス化された JavaScript 実行環境です
  • Chrome DevTools:ブレークポイントとコンソールを使って JavaScript の実行をステップ実行するための、ブラウザーデベロッパーツールです
  • JSDetox:実行エミュレーションと難読化解除機能を備えた、JavaScript マルウェア分析ツールです

よくあるシナリオ

シナリオ:Magecart のウェブスキマーの難読化解除

背景:侵害された EC サイトのチェックアウトページに、難読化された JavaScript が挿入されています。データ流出先のエンドポイントを特定し、盗まれた顧客データを判断するために、スクリプトの難読化を解除する必要があります。

手順:

  1. ページソースから挿入されたスクリプトを抽出します(正規の JS ファイルに追加されているか、外部ドメインから読み込まれていることがよくあります)
  2. コードを整形し、難読化手法を特定します(通常は文字列配列+ローテーション+16 進エンコードです)
  3. Python デコーダースクリプトを使用して、文字列のエンコード層(16 進数 → Unicode → base64)をデコードします
  4. 配列定義とローテーション関数を評価し、文字列配列を解決します
  5. フォームの対象を指定するロジックを特定します(支払いフォームのフィールドに対する querySelector)
  6. XMLHttpRequest または fetch の呼び出しから、流出先 URL を抽出します
  7. インシデント対応のため、盗まれたデータのフィールドと流出先エンドポイントを記録します

注意点:

  • 接続中のシステムで難読化されたスクリプトを実行すること(解析中にスクリプトが外部へ通信する可能性があります)
  • ブラウザーの DevTools を使用する前にアンチデバッグのトラップを削除しないこと(デバッガーの無限ループが発生します)
  • 外部 URL から動的に読み込まれる追加の難読化レイヤーを見落とすこと
  • 追加のスクリプトが含まれている可能性のある、base64 エンコードされたインライン画像やデータ URI を見落とすこと

出力形式

JAVASCRIPT MALWARE DEOBFUSCATION REPORT
=========================================
Source:           checkout.js (injected into example-shop.com)
Obfuscation:      obfuscator.io (string array + rotation + hex encoding)
Layers Removed:   3

OBFUSCATION TECHNIQUES IDENTIFIED
[1] String array with 247 entries, rotated by 0x1a3
[2] Hex-encoded string references (\x68\x65\x6c\x6c\x6f)
[3] Base64-wrapped eval chain (2 layers)
[4] Anti-debugging: setInterval debugger trap

DEOBFUSCATED FUNCTIONALITY
Type:             Magecart Payment Card Skimmer
Target Forms:     input[name*="card"], input[name*="cc_"]
Data Captured:    Card number, expiration, CVV, cardholder name
Exfil Method:     POST via XMLHttpRequest
Exfil URL:        hxxps://analytics-cdn[.]com/collect
Exfil Format:     JSON { "cn": card_number, "exp": expiry, "cv": cvv }
Trigger:          Form submit event on checkout page

EXTRACTED IOCs
Domains:          analytics-cdn[.]com
IPs:              185.220.101[.]42
URLs:             hxxps://analytics-cdn[.]com/collect
                  hxxps://analytics-cdn[.]com/gate.js

コメント