0% found this document useful (0 votes)
7 views19 pages

SQL Injection

SQL Injection (SQLi) is a critical web security vulnerability that allows attackers to manipulate database queries through unvalidated user inputs, potentially leading to data theft, unauthorized access, and system control. The document outlines four main types of SQLi, their causes, impacts, and both attacker and victim perspectives, as well as detection and prevention strategies. It emphasizes the importance of secure coding practices and input validation to mitigate SQLi risks.

Uploaded by

hackietackie07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

SQL Injection

SQL Injection (SQLi) is a critical web security vulnerability that allows attackers to manipulate database queries through unvalidated user inputs, potentially leading to data theft, unauthorized access, and system control. The document outlines four main types of SQLi, their causes, impacts, and both attacker and victim perspectives, as well as detection and prevention strategies. It emphasizes the importance of secure coding practices and input validation to mitigate SQLi risks.

Uploaded by

hackietackie07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SUBMITTED BY-

BARANI S -1058

JAYAPRAKASH R – 1064

SHAIK MOHAMMED AKRAM – 1082

SHEGUFTA NASRIN MAZUMDER– 1083

THIKKA VEERA NAGENDRA - 1089

SQL INJECTION
-A Deep Dive into One of the Web’s
Most Dangerous Threat
What is SQL Injection (SQLi)?
SQL Injection (SQLi) is a type of web security vulnerability that allows an
attacker to interfere with the queries that an application makes to its database.
It usually happens when user inputs are improperly validated or not sanitized,
allowing malicious SQL statements to be executed by the backend database.

By injecting arbitrary SQL code, attackers can read sensitive data, modify or
delete data, execute administrative operations, and in some cases, gain
complete access to the server hosting the database.

4 Main Types of SQL Injection


1. Error-Based SQL Injection

• Description: This technique relies on error messages thrown by the database server to
gather information about the database structure.

• How it works: The attacker injects malformed SQL syntax to force the database to
return an error.

• Example:

' OR 1=1; --

• Use: Helps in database fingerprinting and schema enumeration.

2. Union-Based SQL Injection

• Description: This method uses the UNION SQL operator to combine the results of two
queries into a single result, allowing data from other tables to be retrieved.

• How it works: An attacker appends a UNION SELECT clause with matching column
counts.

• Example:

' UNION SELECT username, password FROM users; --

• Use: Extracts data from other database tables.

3. Boolean-Based (Blind) SQL Injection

• Description: Used when the application does not return error messages. The attacker
sends a query that returns either true or false and observes changes in the web
application’s behaviour.

• How it works: The attacker injects logical conditions.

• Example:

' AND 1=1; -- (returns true)


pg. 1
' AND 1=2; -- (returns false)
• Use: Used for data extraction when error messages are hidden.
4. Time-Based (Blind) SQL Injection

• Description: Relies on making the database wait for a specified amount of time before
responding. If a delay is observed, it indicates a successful injection.

• How it works: Uses commands like SLEEP() or WAITFOR DELAY.

• Example:

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

• Use: Helps when there is no visible output but allows observing response time.

Causes of SQL Injection


• Improper Input Validation: Failure to validate and sanitize user inputs.

• Dynamic SQL Queries: Directly concatenating user input into SQL


queries.

• Lack of Use of Prepared Statements.

• Inadequate Access Control: Giving unnecessary privileges to database


users.

• Outdated Systems: Older systems with known vulnerabilities.

Advantages (from Attacker’s Perspective)


• Data Theft: Access confidential data like emails, passwords, credit card numbers.

• Authentication Bypass: Log in as admin without knowing credentials.

• Database Control: Modify, delete, or insert malicious records.

• Network Footprinting: Understand the structure of the application and backend.

Disadvantages (from Victim’s Perspective)


• Data Breach: Confidential information is exposed.

• Reputation Damage: Loss of customer trust and market value.

• Legal Consequences: Violations of data protection laws (e.g., GDPR).

• System Downtime: May disrupt operations and availability.

• Financial Loss: Recovery, fines, and customer compensation.

pg. 2
Impact and Risks of SQL Injection
• Confidentiality Violation: Exposing private or business-critical data.

• Integrity Loss: Alteration of data.

• Authentication Bypass: Unauthorized access to systems.

• Privilege Escalation: Gaining higher-level access.

• Complete System Takeover: In extreme cases, remote code execution.

Real-World Examples
• Yahoo (2012): Over 450,000 email addresses and passwords leaked.

• Heartland Payment Systems: 130M credit cards compromised.

• Sony Pictures (2011): Massive data breach via SQLi.

Detection Strategies
• Code Review: Manual or automated review of SQL query construction.

• Vulnerability Scanners: Tools like Acunetix, SQLmap, Burp Suite.

• Web Application Firewalls (WAF): Can detect and block suspicious requests.

• Log Monitoring: Unusual or malicious query patterns in server/database logs.

• Behavioral Analysis: Track patterns like sudden large data exports.

Prevention Strategies
1. Use Prepared Statements (Parameterized Queries)

• Prevents direct injection by separating SQL logic from data input.

2. Input Validation and Sanitization

• Validate and sanitize all user inputs (e.g., whitelisting).

3. Use ORM Tools

• ORM frameworks like Sequelize, Hibernate help abstract database


interactions.

4. Least Privilege Principle

• Restrict database access based on roles and responsibilities.

5. Error Handling

• Do not expose database errors to end users.

pg. 3
6. Use Stored Procedures

• Encapsulate queries in the database layer with strict inputs.

7. Security Patching

• Regularly update database systems and application frameworks.

Conclusion
S QL Injection is one of the oldest yet most dangerous vulnerabilities in web applications. Its ease of exploitation and
severe consequences make it critical to address early in the software development lifecycle. By implementing secure
coding practices, validating inputs, using prepared statements, and performing regular security audits, organizations can
significantly reduce the risk of SQL Injection attacks. Prevention is not only about defending systems but also about
safeguarding user trust and business reputation.
pg. 4
PRACTICAL EXAMPLES OF THE 4
TYPES OF SQL INJECTION
1. UNION based SQLi

LAB OBJECTIVE: This lab contains a SQL injection vulnerability in the product category filter. The results from the
query are returned in the application's response, so you can use a UNION attack to retrieve data from other
tables. To construct such an attack, you need to combine some of the techniques you learned in previous labs.

The database contains a different table called users, with columns called username and password.

To solve the lab, perform a SQL injection UNION attack that retrieves all usernames and passwords, and use the
information to log in as the administrator user.

METHODOLOGY
Step 1: First, we determine that the number of columns is at least 2, as the injection below doesn’t produce an
error: category=Gifts' ORDER BY 2—

Step 2: We have multiple categories on the site, and when I clicked on the ‘Accessories’ category, I noticed that the
URL contains a category parameter with a specific value. This indicates that the application uses this parameter to
dynamically retrieve data, likely from a database, which could be vulnerable to SQL injection if input validation is
insufficient.

pg. 5
Step 3: The category parameter accepts arbitrary input tray and reflects it in the response, indicating that the
backend might be using it directly in queries. This makes it vulnerable to SQL injection testing.
Data was intercepted and sent to the repeater.

Step 4: Used ' UNION SELECT username, password FROM users-- and it returned 200 OK - this was mentioned in
the lab instructions, but in real-world scenarios, it's also a common default table. So make sure to try it.

Used the credentials to log in to the application and we were able to access the account as an admin.

OUTPUT:

pg. 6
2. ERROR based SQLi

Lab Objective:

Exploit a SQL injection vulnerability via the Tracking Id cookie to exfiltrate the administrator
password and gain access to their account. This mimics a common scenario where cookies,
often overlooked, are vulnerable due to a lack of proper sanitization and validation

Step 1: Intercept the Request

Action: Use Burp’s built-in browser and open the lab site. Go to Proxy > HTTP history and
locate the GET request containing the TrackingId cookie

pg. 7
Professional Tip: If nothing shows up, make sure intercept is enabled and reload the page
manually. Look specifically for any request that includes cookies sent to the server.

Step 2: Test for Injection Point Payload:


TrackingId=xyz'

Observation: Server returns a verbose SQL error: unclosed string

Step 3: Fix the Syntax with SQL Comment


Payload:TrackingId=xyz'—

Expected Result: No error. The query is


syntactically valid again.

pg. 8
Step 4: Inject a SELECT Statement Payload:
TrackingId=xyz' AND CAST((SELECT 1) AS int)--s

Response: Error — AND the condition must return a boolean.


Lesson: SQL needs logical expressions in conditions like something, like 1 = CAST(...), to
return TRUE or FALSE and avoid an [Link]. Just using C

Step 5: Try Data Extraction Payload:


TrackingId=xyz' AND 1=CAST((SELECT username FROM users) AS int)--

Issue: Query is too long and gets cut off. The error message we receive — Unterminated string
literal started at position 95... — shows that the injected comment (--) didn’t reach the SQL
parser. That means the payload was too long and got truncated before the comment could
neutralize the rest of the query. As a result, the application’s SQL the cookie size is limited.

Step 6: Limit to One Row Payload:


TrackingId=' AND 1=CAST((SELECT username FROM users LIMIT 1) AS int)--

Why It Works: SQL tried to convert the string “administrator” to an integer and failed, and the

pg. 9
error revealed the actual value.
Advanced Tip: Want to get more rows? Use LIMIT 1 OFFSET n to iterate and extract data one row at
a time.
Final Step: Use the leaked credentials to log in and complete the lab. Final Step: Use the
leaked credentials to log in and complete the [Link] Step: Use the leaked credentials to
log in and complete the lab.

Result: The error leaks the admin password.

3. TIME based SQLi

LAB Objective:

This lab challenges us to exploit a blind SQL injection vulnerability using time delays. In this context, ‘blind’ means the
application does not return visible output or errors from the database.

There is no output shown to the user, no error messages, and no UI clues. The goal is to extract the administrator
password by observing time-based responses using pg _ sleep().The vulnerability lies in a cookie parameter (Tracking
Id) that is passed un sanitized to a SQL query

Step 1:

① Confirm the Injection Point with Time-Based SQLi Payload:


pg. 10
Tracking Id= x';SELECT CASE WHEN (1=1) THEN pg_sleep(10) ELSE pg_sleep(0) END-TrackingId=x';SELECT CASE WHEN
(1=1) THEN pg_sleep(10) ELSE pg_sleep(0) END—

STEP 2:

Ⓒ Validate the Existence of the Admin User Payload:


TrackingId=x'; SELECT CASE WHEN (username='administrator') THEN pg_sleep(10) ELSE pg_sleep(0) END FROM users--
TrackingId=x'; SELECT CASE WHEN (username='administrator') THEN pg_sleep(10) ELSE pg_sleep(0) END FROM
users--
• We’re now filtering by username='administrator'. If this condition is true for any row, the server will sleep.

• Check the Burp response timing in the Repeater tab. If the delay is under 1 second, it likely means the
condition was false.

• Use the ‘Response received’ or ‘Response time’ column in Burp Intruder to identify difference.

• We confirmed that an administrator user exists.

STEP 3:

Discover the Password LengthNow we’ll guess the length using LENGTH(). Payloads (increment n):
TrackingId= x'; SELECT CASE WHEN (username='administrator' AND LENGTH(password)>1) THEN pg_sleep(10) ELSE
pg_sleep(0) END FROM users- TrackingId= x'; SELECT CASE WHEN (username='administrator' AND
LENGTH(password)>1) THEN pg_sleep(10) ELSE pg_sleep(0) END FROM users--
pg. 11
• Repeat with >2, >3, etc., until the delay stops. When the delay no longer occurs, it means the condition became
false — that is, the guessed length is no longer greater than the actual length, which helps us identify the exact
password length.

• When the delay stops, you’ve reached the exact length. For this lab, it stops after >20, meaning the length
is exactly 20.
• Password length = 20

STEP 4:

Extract Password Character-by-Character

Time to extract each character using SUBSTRING (), but instead of testing one payload at a time, we’ll use
Burp Intruder with Cluster Bomb — ideal for when we want to test position and character in parallel.

Intruder Setup:
Attack type: Cluster Bomb

Payload Position 1 (position offset): values 1 through 20 (for each character index in the password).

pg. 12
Payload Position 2 (character guess): a-z, 0-9
Threading: Resource Pool → Set Max concurrent requests to 1 (for accurate timing).

Why Cluster Bomb:

This attack iterates through every combination of position + character, and helps automate what would otherwise be
20 manual rounds of guessing. It’s slower but very systematic.
How to Detect the Match:
Sort results by the Response Time or Response Received column. The correct combination will
take ~10 seconds to respond

Once the correct character is found for each position, assemble the full password in order. Then
proceed to the login step to complete the lab.

pg. 13
Log In and Solve Visit /login
Enter administrator and the password you’ve discovered.

RESULT:
This information can be used to plan further attack to identify potential vulnerabilities in the
database.

4. BOOLEAN based SQLi

[Link] the target :

2. checking for Boolean based vulnerabilities :

pg. 14
3. Bannering :

pg. 15
4. Fetching all the databases :

5. Dumping all the tables from the database :

pg. 16
6. Dumping the sensitive data (exploiting the database) :

SUMMARY
SQL Injection (SQLi) is like a hacker’s secret backdoor into a website’s database. It’s a powerful web security
vulnerability where attackers sneak malicious SQL code into input fields—like login forms or search bars—to trick the
system into revealing or manipulating sensitive data. Think of it as whispering a secret command into a system that wasn’t
supposed to listen.

With SQLi, attackers can bypass authentication, access private user information, tamper with records, or even
take control of the entire database. It’s been behind some of the most notorious data breaches in history. The
scary part? Sometimes all it takes is a single quote (') in the right place to break the system wide open.
But the good news is: with proper coding practices, input validation, and the use of prepared statements, SQLi
can be completely prevented. It’s a classic example of how a small oversight in code can open the door to big
consequences—and why cybersecurity is never just an afterthought.

pg. 17
pg. 18

You might also like