Cleanup & Covering Tracks

Proper cleanup ensures client systems are returned to their original state. This is a professional requirement, not evasion - document everything and remove all artifacts.

Danger

CRITICAL: Cleanup is mandatory for legitimate penetration testing. Leaving backdoors creates liability and security risks. Track every change during the engagement to ensure complete remediation.
flowchart LR A[Engagement Log] --> B[Identify Artifacts] B --> C[Remove Persistence] C --> D[Delete Files] D --> E[Clear Evidence] E --> F[Verify Cleanup] F --> G[Client Handoff] style A fill:#00ff00,stroke:#000,color:#000 style G fill:#a855f7,stroke:#000,color:#000

Cleanup Checklist

text
# Pre-Cleanup Verification Checklist
□ Review engagement log for all changes made
□ Identify all systems accessed
□ List all persistence mechanisms installed
□ Document all files uploaded/created
□ Note all accounts created/modified
□ Record all firewall/ACL changes
□ List all scheduled tasks/cron jobs created
□ Identify all services installed

# Post-Cleanup Verification
□ Verify all artifacts removed
□ Confirm persistence mechanisms disabled
□ Validate original configurations restored
□ Test that backdoors are inaccessible
□ Generate cleanup report for client

Windows Cleanup

Remove Registry Persistence

powershell
# Run Keys
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "MaliciousEntry" /f
reg delete "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "MaliciousEntry" /f

# PowerShell
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "MaliciousEntry"

# Verify removal
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run"

Remove Scheduled Tasks

powershell
# List tasks (find pentest tasks)
schtasks /query /fo LIST

# Delete specific task
schtasks /delete /tn "TaskName" /f

# PowerShell
Unregister-ScheduledTask -TaskName "TaskName" -Confirm:$false

# Verify
Get-ScheduledTask | Where-Object {$_.TaskName -like "*suspicious*"}

Remove Services

powershell
# Stop and delete service
sc stop "ServiceName"
sc delete "ServiceName"

# PowerShell
Stop-Service -Name "ServiceName" -Force
Remove-Service -Name "ServiceName"

# Verify
Get-Service | Where-Object {$_.Name -like "*pentest*"}

Remove WMI Persistence

powershell
# List WMI subscriptions
Get-WMIObject -Namespace root\Subscription -Class __EventFilter
Get-WMIObject -Namespace root\Subscription -Class __EventConsumer
Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding

# Remove specific subscription
Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='MaliciousFilter'" | Remove-WMIObject
Get-WMIObject -Namespace root\Subscription -Class CommandLineEventConsumer -Filter "Name='MaliciousConsumer'" | Remove-WMIObject
Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding | Where-Object {$_.Filter -like "*MaliciousFilter*"} | Remove-WMIObject

Delete Files & Tools

powershell
# Remove uploaded tools
Remove-Item -Path "C:\Users\Public\payload.exe" -Force
Remove-Item -Path "C:\Windows\Temp\mimikatz.exe" -Force
Remove-Item -Path "C:\Temp\*" -Recurse -Force

# Remove from startup folder
Remove-Item -Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\malicious.lnk" -Force

# Secure delete (overwrite before deletion)
cipher /w:C:\Temp

# Find and remove tools
Get-ChildItem -Path C:\ -Recurse -Include "mimikatz*","rubeus*","beacon*" -ErrorAction SilentlyContinue | Remove-Item -Force

Remove Created Users

powershell
# Local users
net user pentestuser /delete

# PowerShell
Remove-LocalUser -Name "pentestuser"

# Domain users (requires DA)
Remove-ADUser -Identity "pentestuser" -Confirm:$false

# Verify
Get-LocalUser
Get-ADUser -Filter {Name -like "*pentest*"}

Linux Cleanup

Remove SSH Keys

bash
# Remove added SSH keys
# First identify your key (compare with engagement notes)
cat /root/.ssh/authorized_keys
cat /home/*/.ssh/authorized_keys

# Remove specific key
sed -i '/pentest-key-comment/d' /root/.ssh/authorized_keys

# Or remove all and restore from backup
# (coordinate with client)

Remove Cron Jobs

bash
# List and remove crontab entries
crontab -l
crontab -e  # Remove malicious entries

# Remove from cron directories
rm /etc/cron.daily/pentest-script
rm /etc/cron.d/malicious

# Check /etc/crontab
grep -v "malicious" /etc/crontab > /tmp/crontab.clean
mv /tmp/crontab.clean /etc/crontab

Remove Systemd Services

bash
# Stop and disable service
systemctl stop pentest-service
systemctl disable pentest-service

# Remove service file
rm /etc/systemd/system/pentest-service.service

# Reload daemon
systemctl daemon-reload

# Verify
systemctl list-units --type=service | grep pentest

Remove Backdoor Users

bash
# Remove user
userdel -r pentestuser

# If user has processes running
pkill -u pentestuser
userdel -rf pentestuser

# Verify
grep pentest /etc/passwd
grep pentest /etc/shadow

Remove Files & Tools

bash
# Remove uploaded tools
rm -rf /tmp/linpeas.sh
rm -rf /dev/shm/beacon
rm -rf /var/tmp/tools/

# Find and remove
find / -name "linpeas*" -o -name "pspy*" -o -name "beacon*" 2>/dev/null | xargs rm -f

# Secure delete
shred -vfz -n 5 /tmp/sensitive_file

Remove LD_PRELOAD Backdoors

bash
# Check for LD_PRELOAD hijacking
cat /etc/ld.so.preload
ls -la /etc/ld.so.preload

# Remove malicious entries
vim /etc/ld.so.preload  # Remove malicious .so paths

# Remove the malicious library
rm /usr/local/lib/evil.so

# Refresh library cache
ldconfig

Active Directory Cleanup

Reset Compromised Credentials

Warning

Coordinate password resets with the client. Forced resets can cause service outages. Document which accounts were compromised for client notification.
powershell
# Document compromised accounts for client
# DO NOT reset without client coordination

# If authorized, reset krbtgt (invalidates Golden Tickets)
# Must be done TWICE with replication time between
# Reset 1
Set-ADAccountPassword -Identity krbtgt -Reset -NewPassword (ConvertTo-SecureString "NewPassword1!" -AsPlainText -Force)
# Wait for replication (varies by environment)
# Reset 2
Set-ADAccountPassword -Identity krbtgt -Reset -NewPassword (ConvertTo-SecureString "NewPassword2!" -AsPlainText -Force)

# Note: Client should perform these resets

Remove ACL Modifications

powershell
# Remove DCSync rights added during engagement
Import-Module ActiveDirectory
$Domain = Get-ADDomain
$DomainDN = $Domain.DistinguishedName
$UserSID = (Get-ADUser pentestuser).SID

$ACL = Get-Acl "AD:\$DomainDN"
# Find and remove the ACE we added
$ACL.Access | Where-Object {$_.IdentityReference -match "pentestuser"} | ForEach-Object {
    $ACL.RemoveAccessRule($_)
}
Set-Acl "AD:\$DomainDN" $ACL

# Remove AdminSDHolder modifications
$AdminSDHolder = "AD:\CN=AdminSDHolder,CN=System,$DomainDN"
$ACL = Get-Acl $AdminSDHolder
$ACL.Access | Where-Object {$_.IdentityReference -match "pentestuser"} | ForEach-Object {
    $ACL.RemoveAccessRule($_)
}
Set-Acl $AdminSDHolder $ACL

Revoke Delegation

powershell
# Remove RBCD configurations
Import-Module PowerView
Set-ADComputer -Identity "TargetComputer" -Clear 'msDS-AllowedToActOnBehalfOfOtherIdentity'

# Remove created computer accounts
Remove-ADComputer -Identity "EVILPC$" -Confirm:$false

Log Management

Information

For authorized testing, discuss log handling with the client. They may want logs preserved for training. Never clear logs without explicit authorization.

Windows Event Logs (Reference Only)

powershell
# VIEW logs to document your activity (for reporting)
# DO NOT clear without client authorization

# View Security logs
Get-WinEvent -LogName Security -MaxEvents 100 | Where-Object {$_.TimeCreated -gt (Get-Date).AddHours(-24)}

# Export specific timeframe for client
wevtutil epl Security C:\engagement_logs\security.evtx /q:"*[System[TimeCreated[@SystemTime>='2024-01-15T00:00:00' and @SystemTime<='2024-01-16T00:00:00']]]"

# Key Event IDs to document:
# 4624 - Logon
# 4625 - Failed logon  
# 4672 - Special privileges
# 4688 - Process creation
# 4698/4699 - Scheduled task created/deleted

Linux Logs (Reference Only)

bash
# VIEW logs to document activity (for reporting)

# Auth logs
cat /var/log/auth.log | grep "pentest_period"
cat /var/log/secure | grep "pentest_period"

# Command history - document but leave for client
cat ~/.bash_history

# Key log files:
# /var/log/auth.log - Authentication
# /var/log/syslog - System events
# /var/log/apache2/access.log - Web access
# ~/.bash_history - Command history

Cleanup Documentation

markdown
# Cleanup Report Template

## Engagement Cleanup Summary
**Date:** [Date]
**Tester:** [Name]
**Client:** [Client Name]

## Systems Accessed
| Hostname | IP Address | Access Level | Duration |
|----------|------------|--------------|----------|
| DC01 | 10.10.10.1 | Domain Admin | 48 hours |
| WEB01 | 10.10.10.20 | Local Admin | 24 hours |

## Artifacts Removed
| Type | Location | Status |
|------|----------|--------|
| Scheduled Task | DC01: "WindowsUpdate" | ✅ Removed |
| Registry Key | WEB01: HKCU\Run\Update | ✅ Removed |
| Uploaded File | DC01: C:\Temp\mimikatz.exe | ✅ Deleted |
| User Account | corp.local\pentestadmin | ✅ Deleted |

## Credentials Compromised (For Client Remediation)
| Account | Hash Type | Recommendation |
|---------|-----------|----------------|
| Administrator | NTLM | Reset password |
| svc_sql | NTLM | Reset password |
| krbtgt | NTLM | Double reset required |

## Verification Steps Completed
□ All persistence mechanisms removed
□ All uploaded tools deleted
□ Created accounts removed
□ Registry modifications reverted
□ Client notified of compromised accounts

## Notes
[Any additional information for client]

Client Handoff

text
# Items to provide client:
1. Cleanup report with all actions taken
2. List of compromised credentials requiring reset
3. Timeline of access for log correlation
4. Recommendations for detection improvements
5. Confirmation that all artifacts removed

# Schedule handoff meeting to:
- Walk through cleanup report
- Answer questions about persistence locations
- Provide recommendations for monitoring
- Confirm client's verification steps