mcpField
A
analyzing-email-headers-for-phishing-investigation

analyzing-email-headers-for-phishing-investigation

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

analyzing-email-headers-for-phishing-investigation について

不審なメールを調査するセキュリティ担当者向けの手順ガイドです。メールの送信元追跡、送信者の真正性確認、認証レコードの検証、本文や添付ファイルの調査を扱います。

主な機能

  1. 01ヘッダーと配送経路の解析
  2. 02SPF、DKIM、DMARC の検証
  3. 03送信ドメインと基盤の確認
  4. 04リンクと添付ファイルの抽出・調査
  5. 05メール分析レポートの作成

活用シーン

  1. 01フィッシング疑いメールの送信元調査
  2. 02送信者の確認となりすまし検出
  3. 03リンクをクリックした後のインシデント対応
  4. 04不審なリンクや添付ファイルの検査

インストール

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

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill analyzing-email-headers-for-phishing-investigation

インストール後、Claude Code で/analyzing-email-headers-for-phishing-investigationを入力して読み込まれたか確認します。

同梱ファイル

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

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

詳細

フィッシング調査のためのメールヘッダー分析

使用する場面

  • フィッシングの疑いがあるメールを調査し、本当の送信元を特定するとき
  • 送信者の正当性を確認し、メールのなりすましを検出するとき
  • ユーザーがフィッシングリンクをクリックした際のインシデント対応時
  • 不審なメールの配信経路や中継サーバーを追跡するとき
  • SPF、DKIM、DMARCの整合性を検証し、偽造を特定するとき

前提条件

  • 不審なメッセージの未加工のメールヘッダー(EMLまたはMSG形式)
  • SMTPプロトコルとメールヘッダーフィールドに関する知識
  • SPF/DKIM/DMARC検証用のDNS照会ツール(dig、nslookup)へのアクセス
  • メールヘッダー分析ツール(MHA、emailheaders.netの概念)
  • 自動分析用のメール解析ライブラリを備えたPython
  • IP/ドメインのレピュテーションを調べる脅威インテリジェンスプラットフォームへのアクセス

ワークフロー

ステップ 1:未加工のメールヘッダーを抽出する
# Export from Outlook: Open email > File > Properties > Internet Headers
# Export from Gmail: Open email > Three dots > Show original
# Export from Thunderbird: View > Message Source

# If working with EML file from forensic image
cp /mnt/evidence/Users/suspect/AppData/Local/Microsoft/Outlook/phishing_email.eml \
   /cases/case-2024-001/email/

# If working with PST file, extract individual messages
pip install pypff
python3 << 'PYEOF'
import pypff

pst = pypff.file()
pst.open("/cases/case-2024-001/email/outlook.pst")
root = pst.get_root_folder()

def extract_messages(folder, path=""):
    for i in range(folder.get_number_of_sub_messages()):
        msg = folder.get_sub_message(i)
        headers = msg.get_transport_headers()
        subject = msg.get_subject()
        if headers:
            filename = f"/cases/case-2024-001/email/msg_{i}_{subject[:30]}.txt"
            with open(filename, 'w') as f:
                f.write(headers)
    for i in range(folder.get_number_of_sub_folders()):
        extract_messages(folder.get_sub_folder(i))

extract_messages(root)
PYEOF
ステップ 2:メールヘッダーの連鎖を解析する
# Parse headers using Python email library
python3 << 'PYEOF'
import email
from email import policy

with open('/cases/case-2024-001/email/phishing_email.eml', 'r') as f:
    msg = email.message_from_file(f, policy=policy.default)

print("=== KEY HEADER FIELDS ===")
print(f"From:          {msg['From']}")
print(f"To:            {msg['To']}")
print(f"Subject:       {msg['Subject']}")
print(f"Date:          {msg['Date']}")
print(f"Message-ID:    {msg['Message-ID']}")
print(f"Reply-To:      {msg['Reply-To']}")
print(f"Return-Path:   {msg['Return-Path']}")
print(f"X-Mailer:      {msg['X-Mailer']}")
print(f"X-Originating-IP: {msg['X-Originating-IP']}")

print("\n=== RECEIVED HEADERS (bottom-up = chronological) ===")
received_headers = msg.get_all('Received')
if received_headers:
    for i, header in enumerate(reversed(received_headers)):
        print(f"\nHop {i+1}: {header.strip()}")

print("\n=== AUTHENTICATION RESULTS ===")
auth_results = msg.get_all('Authentication-Results')
if auth_results:
    for result in auth_results:
        print(result)

print(f"\nARC-Authentication-Results: {msg.get('ARC-Authentication-Results', 'Not present')}")
print(f"Received-SPF: {msg.get('Received-SPF', 'Not present')}")
print(f"DKIM-Signature: {msg.get('DKIM-Signature', 'Not present')}")
PYEOF
ステップ 3:SPF、DKIM、DMARCレコードを検証する
# Extract the envelope sender domain
SENDER_DOMAIN="example-corp.com"

# Check SPF record
dig TXT $SENDER_DOMAIN +short | grep "v=spf1"
# Example: "v=spf1 include:_spf.google.com include:sendgrid.net ~all"

# Check DKIM record (selector from DKIM-Signature header, e.g., "s=selector1")
DKIM_SELECTOR="selector1"
dig TXT ${DKIM_SELECTOR}._domainkey.${SENDER_DOMAIN} +short

# Check DMARC record
dig TXT _dmarc.${SENDER_DOMAIN} +short
# Example: "v=DMARC1; p=reject; rua=mailto:[email protected]; pct=100"

# Verify the sending IP against SPF
# Extract IP from first Received header
SENDING_IP="203.0.113.45"

# Manual SPF check using python
python3 << 'PYEOF'
import spf  # pip install pyspf

result, explanation = spf.check2(
    i='203.0.113.45',
    s='[email protected]',
    h='mail.example-corp.com'
)
print(f"SPF Result: {result}")
print(f"Explanation: {explanation}")
# Results: pass, fail, softfail, neutral, none, temperror, permerror
PYEOF

# Check if sending IP is in known malicious IP lists
# Query AbuseIPDB or VirusTotal
curl -s "https://api.abuseipdb.com/api/v2/check?ipAddress=${SENDING_IP}" \
   -H "Key: YOUR_API_KEY" -H "Accept: application/json" | python3 -m json.tool
ステップ 4:送信者のドメインとインフラストラクチャを分析する
# WHOIS lookup on sender domain
whois $SENDER_DOMAIN | grep -iE '(registrar|creation|expiration|registrant|nameserver)'

# Check domain age (recently registered domains are suspicious)
# DNS record investigation
dig A $SENDER_DOMAIN +short
dig MX $SENDER_DOMAIN +short
dig NS $SENDER_DOMAIN +short

# Reverse DNS on sending IP
dig -x $SENDING_IP +short

# Check for lookalike/typosquatting domains
# Compare with legitimate domain using visual similarity
python3 << 'PYEOF'
import Levenshtein  # pip install python-Levenshtein

legitimate = "microsoft.com"
suspicious = "micr0soft.com"

distance = Levenshtein.distance(legitimate, suspicious)
ratio = Levenshtein.ratio(legitimate, suspicious)
print(f"Edit distance: {distance}")
print(f"Similarity ratio: {ratio:.2%}")
if ratio > 0.8:
    print("WARNING: Likely typosquatting/lookalike domain!")
PYEOF

# Check domain reputation on VirusTotal
curl -s "https://www.virustotal.com/api/v3/domains/${SENDER_DOMAIN}" \
   -H "x-apikey: YOUR_VT_API_KEY" | python3 -m json.tool

# Check if the Reply-To differs from From (common phishing indicator)
python3 -c "
import email
with open('/cases/case-2024-001/email/phishing_email.eml') as f:
    msg = email.message_from_file(f)
from_addr = email.utils.parseaddr(msg['From'])[1]
reply_to = email.utils.parseaddr(msg.get('Reply-To', msg['From']))[1]
if from_addr != reply_to:
    print(f'WARNING: From ({from_addr}) != Reply-To ({reply_to})')
else:
    print('From and Reply-To match')
"
ステップ 5:メール本文と添付ファイルを調べる
# Extract URLs from email body
python3 << 'PYEOF'
import email
import re
from email import policy

with open('/cases/case-2024-001/email/phishing_email.eml', 'r') as f:
    msg = email.message_from_file(f, policy=policy.default)

body = msg.get_body(preferencelist=('html', 'plain'))
if body:
    content = body.get_content()
    urls = re.findall(r'https?://[^\s<>"\']+', content)
    print("=== URLs FOUND IN EMAIL BODY ===")
    for url in set(urls):
        print(f"  {url}")

    # Check for URL obfuscation (display text != href)
    href_pattern = re.findall(r'<a[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)</a>', content, re.DOTALL)
    print("\n=== HYPERLINK ANALYSIS ===")
    for href, text in href_pattern:
        display_url = re.findall(r'https?://[^\s<]+', text)
        if display_url and display_url[0] != href:
            print(f"  MISMATCH: Display='{display_url[0]}' -> Actual='{href}'")

# Extract and hash attachments
print("\n=== ATTACHMENTS ===")
for part in msg.walk():
    if part.get_content_disposition() == 'attachment':
        filename = part.get_filename()
        content = part.get_payload(decode=True)
        import hashlib
        sha256 = hashlib.sha256(content).hexdigest()
        print(f"  File: {filename}, Size: {len(content)}, SHA-256: {sha256}")
        with open(f'/cases/case-2024-001/email/attachments/{filename}', 'wb') as af:
            af.write(content)
PYEOF

# Submit attachment hashes to VirusTotal
# Submit URLs to URLhaus or PhishTank for reputation check

主な概念

概念説明
SPF(Sender Policy Framework)ドメインで認可されたメールサーバーを指定するDNSレコード
DKIM(DomainKeys Identified Mail)メールコンテンツの完全性を検証する暗号署名
DMARC送信者認証のためにSPFとDKIMを組み合わせたポリシーフレームワーク
Receivedヘッダー配信経路上の各ホップを示す、サーバーが追加したヘッダー(下から上へ読みます)
Return-Pathバウンスメッセージに使用されるエンベロープ送信者アドレス。Fromとは異なる場合があります
Message-ID送信元のメールサーバーが割り当てる一意の識別子
X-Originating-IP元の送信者のIPアドレス(一部のメールサービスが追加)
ヘッダーの偽造攻撃者はFrom、Reply-Toなどのヘッダーを偽造できますが、Receivedの連鎖は偽造できません

ツールとシステム

ツール用途
MXToolboxオンラインのメールヘッダー分析ツールおよびDNS照会ツール
dig/nslookupSPF、DKIM、DMARC検証用のDNSレコード照会
pyspfSPFレコード検証用Pythonライブラリ
dkimpyDKIM署名検証用Pythonライブラリ
PhishToolフィッシングメールに特化した分析プラットフォーム
VirusTotalURLとファイルのレピュテーション確認サービス
AbuseIPDBIPアドレスのレピュテーションデータベース
whoisドメイン登録情報の照会

よくあるシナリオ

シナリオ 1:CEO詐欺/ビジネスメール詐欺 メールはCEOからのように見えますが、Reply-ToはGmailアドレスを指しています。送信元IPが偽装されたドメインで認可されていないためSPFに失敗し、DKIMはなく、Fromのドメインはよく似たドメインです(ceo-company.comとcompany.com)。

シナリオ 2:認証情報を盗み取るフィッシング メール内のリンクには「login.microsoft.com」と表示されていますが、hrefはよく似たドメインを指しています。添付ファイルは、認証情報を外部に送信するJavaScriptを含む偽のログインページを埋め込んだHTMLファイルです。送信ドメインは3日前に登録されています。

シナリオ 3:添付ファイルによるマルウェア配信 マクロを含むOffice文書が添付されたメールです。送信者のドメインはSPFに合格していますが、アカウントは侵害されています。DKIM署名は有効です(正規のインフラストラクチャから送信)。添付ファイルのSHA-256は、VirusTotal上の既知のマルウェアと一致します。

シナリオ 4:正規サービスを利用したスピアフィッシング 攻撃者は正規のメールマーケティングサービスを利用してフィッシングメールを送信します。サービスが認可されているためSPFとDKIMには合格します。フィッシング要素はインフラストラクチャではなくコンテンツにあるため、ヘッダー認証の確認ではなくURLとコンテンツの分析が必要です。

出力形式

Email Header Analysis Report:
  Subject:     "Urgent: Invoice Payment Required"
  From:        [email protected] (SPOOFED)
  Reply-To:    [email protected] (MISMATCH)
  Return-Path: <[email protected]>
  Date:        2024-01-15 09:23:45 UTC

  Delivery Path (4 hops):
    Hop 1: mail-server.xyz [203.0.113.45] -> relay1.isp.com
    Hop 2: relay1.isp.com -> mx.target-company.com
    Hop 3: mx.target-company.com -> internal-filter.target.com
    Hop 4: internal-filter.target.com -> mailbox

  Authentication:
    SPF:    FAIL (203.0.113.45 not authorized for examp1e-corp.com)
    DKIM:   NONE (no signature present)
    DMARC:  FAIL (p=none, no enforcement)

  Indicators of Phishing:
    - Lookalike domain (examp1e-corp.com vs example-corp.com, 96% similar)
    - From/Reply-To mismatch
    - Domain registered 2 days before email sent
    - URL in body points to credential harvesting page
    - Attachment: invoice.xlsm (SHA-256: a3f2...) - Known malware on VT

  Risk Level: HIGH

コメント