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

Part5 SW SEC SQL Injection

Uploaded by

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

Part5 SW SEC SQL Injection

Uploaded by

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

SOFTWARE

SECURITY
SQL INJECTION
Outline
• Introduction
• What is the impact of a successful SQL injection attack?
• SQL injection examples
1. Retrieving hidden data
2. Subverting application logic
3. Retrieving data from other database tables
4. Examining the database
5. Blind SQL injection vulnerabilities
• How to detect SQL injection vulnerabilities
• SQL injection in different parts of the query
• Types of SQL injection attacks
• How to prevent SQL injection
Introduction
• SQL injection is a web security vulnerability that allows an attacker to interfere with the
queries that an application makes to its database.
• This vulnerability allows attackers to view data that they are not normally able to
retrieve.
• This might include data belonging to other users, or any other data that the application itself is
able to access.
• In many cases, an attacker can modify or delete this data so that this can cause persistent
changes to the application's content or behavior.

• In some situations, an attacker can exploit an SQL injection attack to perform a DoS
attack.
What is the impact of a successful SQL injection attack?

• A successful SQL injection attack can result in unauthorized access to sensitive


data, such as passwords, credit card details, or personal user information.
• Many high-profile data breaches in recent years have been the result of SQL
injection attacks, leading to reputational damage and regulatory fines.
• In some cases, an attacker can obtain a persistent backdoor into an
organization’s systems so that can lead to a long-term compromise that can go
unnoticed for an extended period.
SQL injection examples
• There are a wide variety of SQL injection vulnerabilities, attacks, and techniques, which
arise in different situations. Some common SQL injection examples include:
1. Retrieving hidden data, where you can modify an SQL query to return additional results.
2. Subverting application logic, where you can change a query to interfere with the
application's logic.
3. UNION attacks, where you can retrieve data from different database tables.
4. Examining the database, where you can extract information about the version and
structure of the database.
5. Blind SQL injection, where the results of a query you control are not returned in the
application's responses.
1. Retrieving hidden data
• Consider a shopping application that displays products in different categories. When the user
clicks on the Gifts category, their browser requests the URL:
https://insecure-website.com/products?category=Gifts
• This causes the application to make an SQL query to retrieve details of the relevant products from
the database:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
• This SQL query asks the database to return: all details (*) from the products table where the
category is Gifts and released is 1.
1. Retrieving hidden data

SELECT * FROM products WHERE category = 'Gifts' AND released = 1


• The restriction released = 1 is being used to hide products that are not released. For
unreleased products, presumably released = 0.
• The application doesn't implement any defenses against SQL injection attacks, so an
attacker can construct an attack like:
https://insecure-website.com/products?category=Gifts'--
• This results in the SQL query:

SELECT * FROM products WHERE category = 'Gifts'--' AND released = 1


1. Retrieving hidden data
• The key thing here is that the double-dash sequence -- is a comment indicator in SQL, and means that the
rest of the query is interpreted as a comment. This effectively removes the remainder of the query, so it no
longer includes AND released = 1. This means that all products are displayed, including unreleased products.
• Going further, an attacker can cause the application to display all the products in any category, including
categories that they don't know about:
https://insecure-website.com/products?category=Gifts'+OR+1=1--
• This results in the SQL query:

SELECT * FROM products WHERE category = 'Gifts' OR 1=1--' AND released = 1


• The modified query will return all items where either the category is Gifts, or 1 is equal to 1. Since 1=1 is
always true, the query will return all items.
1. Retrieving hidden data – further example
• Consider a simple website with a search feature that allows users to find products by entering
keywords. The website uses an SQL query to fetch products from the database based on the user input.
Here's an example of a vulnerable SQL query:
SELECT * FROM products WHERE name = ‘keyword’; This is a vulnerable code.
• Here, the SQL query searches for products based on the user-supplied ‘keyword’.
• The ‘name’ field is vulnerable to SQL injection because the input is not properly sanitized or validated.
• An attacker can exploit this vulnerability by inputting crafted SQL code into the search box to manipulate
the query’s behavior.
• Suppose, there is a hidden product category called 'Special', and the website does not display these
products to regular users.
1. Retrieving hidden data – further example

• An attacker enters the following input into the search box:

' OR category = 'Special’ --


• The manipulated query becomes:

SELECT * FROM products WHERE name = '' OR category = 'Special' -- ';


• The SQL query now retrieves all products where the category is 'Special’ regardless of
the original keyword entered by the user, so that the hidden data is exposed.

•The single quote ' closes the original SQL string.


•OR category = 'Special' is the injected SQL code.
•-- is used to comment out the rest of the query.
2. Subverting application logic
• Consider an application that lets users log in with a username and password.
• If a user submits the username wiener and the password bluecheese, the application checks the
credentials by performing the following SQL query:
SELECT * FROM users WHERE username = 'wiener' AND password = 'bluecheese'
• If the query returns the details of a user, then the login is successful. Otherwise, it is rejected.
• Here, an attacker can log in as any user without a password simply by using the SQL comment
sequence -- to remove the password check from the WHERE clause of the query. For example,
submitting the username administrator'-- and a blank password results in the following query:
SELECT * FROM users WHERE username = 'administrator'--' AND password = ''
• This query returns the user whose username is administrator and successfully logs the attacker
in as that user.
2. Subverting application logic – another example

• Imagine a banking website where users can transfer money between accounts. The website
uses an SQL query to process these transactions. Here's an example of a vulnerable SQL query:
UPDATE accounts SET balance = balance - amount WHERE account_id = 'source_account_id'; Vulnerabl
UPDATE accounts SET balance = balance + amount WHERE account_id = 'destination_account_id’; e codes

• Here, when a user initiates a transfer, the website executes two SQL queries.
• 1st query subtracts amount from the source account (balance - amount)
• 2nd query adds the amount to the destination account (balance + amount).

• Both queries are vulnerable to SQL injection because they include user-supplied data without
proper validation.
• An attacker can exploit this vulnerability to manipulate the logic of the transaction and
perform unauthorized transfers.
2. Subverting application logic – another example

• An attacker wants to transfer money from account A to account B, but they also want to
keep a copy of the transferred amount in account C.
• The attacker enters the following input into the amount field during the transfer:
100; UPDATE accounts SET balance = balance + 100 WHERE account_id = 'C' --
2. Subverting application logic – another example

• The manipulated queries become:


SQL query UPDATE accounts SET balance = balance - 100 WHERE account_id = 'A';
1
SQL query UPDATE accounts SET balance = balance + 100 WHERE account_id = 'B'; UPDATE accounts SET balance = balance
2 + 100 WHERE account_id = 'C' -- ‘;

• The SQL injection has now:


• Subtracted 100 from account A as expected.
• Added 100 to account B as expected.
• Added 100 to account C, that would create a fake transaction to account C.
•The ; semicolon is used to separate multiple SQL statements in a single query.
•The injected SQL code after the semicolon will update account C by adding 100
3. Retrieving data from other database tables
• In cases where the results of an SQL query are returned within the application’s responses, an attacker
can leverage an SQL injection vulnerability to retrieve data from other tables within the database.
• This is done using the UNION keyword, which lets the attacker execute an additional SELECT query and
append the results to the original query.
• For example, if an application executes the following query containing the user input “Gifts”:

SELECT name, description FROM products WHERE category = ‘Gifts’


• then an attacker can submit the input:

' UNION SELECT username, password FROM users--


• This will cause the application to return all usernames and passwords along with the names and
descriptions of products.
4. Examining the database
• Following initial identification of an SQL injection vulnerability, it is generally useful to obtain
some information about the database itself. This information can often ease the way for further
exploitation.
• You can query the version details for the database. The way that this is done depends on the
database type, so you can infer the database type from whichever technique works. For example,
on Oracle you can execute:
SELECT * FROM v$version
• You can also determine what database tables exist, and which columns they contain. For
example, on most databases you can execute the following query to list the tables:
SELECT * FROM information_schema.tables
5. Blind SQL injection vulnerabilities
• Many instances of SQL injection are blind vulnerabilities.

• Blind vulnerabilities can still be exploited to access unauthorized data,


but the techniques involved are generally more complicated and
difficult to perform.
5. Blind SQL injection
• Blind SQL Injection is a type of SQL injection attack where the application
is vulnerable to SQL injection but does not directly give the results of the
injected SQL query.
• The attacker can’t see (The attacker is blind.) the data directly but can infer
information based on the application’s behavior.
• There are two main types: Boolean-based and Time-based.
5. Blind SQL Injection; timing-based attacks

• One common technique in Blind SQL Injection attacks is to use timing-based


attacks, where the attacker crafts SQL injection payloads that cause the
application to respond differently based on the injected condition.
• For example, an attacker might inject a payload like
OR IF(condition, SLEEP(5), 0)
into an input field that is vulnerable to SQL injection.
If the injected condition is true, the application will pause for 5 seconds before
responding.
5. Blind SQL Injection; timing-based attacks –
Attacks’ scenarios
• If application takes 5 seconds longer to respond after the injected payload, it
indicates that the injected condition is true.
• This means the attacker has successfully guessed a part of the query that caused a
delay in the application’s response.

• The SLEEP(5) function is a common function used in SQL injection attacks for
timing-based attacks.
• It causes the database to pause execution for a specified number of seconds.
5. Blind SQL Injection; timing-based attacks –
Attacks’ scenarios
AN EXAMPLE
• Let’s say an attacker wants to extract the password from a database using Blind SQL
Injection. They may inject a payload like:

SELECT password FROM users WHERE username='admin' AND IF(condition, SLEEP(5), 0)

• If the condition in the IF statement is true, it will execute SLEEP(5); application will cause the
database to pause for 5 seconds.
• If the condition is false, application will respond immediately by returning 0.
• By observing response time, attacker can confirm whether the injected condition is true or false.
5. Blind SQL Injection; timing-based attacks –
Attacks’ scenarios
AN EXAMPLE
• Let’s say an attacker wants to extract the password from a database using Blind
SQL Injection. They may inject a payload like:
• If the injected condition is true, SQL query will become:
SELECT password FROM users WHERE username='admin' AND IF(true, SLEEP(5), 0)

• Once condition is true,  database will pause for 5 seconds.  This delay is
utilized to verify a guessed password.
How to detect SQL injection vulnerabilities
• The majority of SQL injection vulnerabilities can be found quickly and reliably using Burp
Suite's web vulnerability scanner.
• SQL injection can be detected manually by using a systematic set of tests against every entry
point in the application. This involves:
• Submitting the single quote character and looking for errors or other anomalies.
• Submitting some SQL-specific syntax that evaluates to the base (original) value of the entry point,
and to a different value, and looking for systematic differences in the resulting application
responses.
• Submitting Boolean conditions such as OR 1=1 and OR 1=2, and looking for differences in the
application's responses.
• Submitting payloads designed to trigger time delays when executed within an SQL query, and
looking for differences in the time taken to respond.
GitHub - payloadbox/sql
-injection-payload-list: 🎯 SQL Injection Payload Lis
t
SQL injection in different parts of the query

• Most SQL injection vulnerabilities arise within the WHERE clause of a SELECT query.
• This type of SQL injection is generally well-understood by experienced testers.

• But SQL injection vulnerabilities can in principle occur at any location within the
query, and within different query types. The most common other locations where
SQL injection arises are:
• In UPDATE statements, within the updated values or the WHERE clause.
• In INSERT statements, within the inserted values.
• In SELECT statements, within the table or column name.
• In SELECT statements, within the ORDER BY clause.
Types of SQL injection attacks

• The impact of SQL injection attacks may vary from gathering of sensitive data to
manipulating database information, and from executing system-level commands to
denial of service of the application.
• SQL injection attacks do not have to return data directly to the user to be useful.
• “Blind” attacks (for example, that creates a database user, but otherwise return no data) can
still be very useful to an attacker.
• In addition, attackers are known to use timing or other performance indicators,
and even error messages to deduce the success or results of an attack.
Types of SQL injection attacks

• Researchers generally divide injection attacks into three categories:


• First Order Attack
• The attacker can enter a malicious string and cause the modified code to be
executed immediately.
• Second Order Attack
• The attacker injects into persistent storage (such as a table row) which is deemed
as a trusted source. An attack is subsequently executed by another activity.
• Lateral Injection
• The attacker can manipulate the implicit function To_Char() by changing
the values of the environment variables, NLS_Date_Format or
NLS_Numeric_Characters.
How to prevent SQL injection
• The following code is vulnerable to SQL injection because the user input is concatenated directly
into the query:
Vulnerable String query = "SELECT * FROM products WHERE category = '"+ input + “’”;
code Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
• If input contains malicious SQL code, it will be directly inserted into the query.

• Using parameterized queries, also known as prepared statements, is a method to prevent SQL
injection attacks.
• This code can be easily rewritten in a way that prevents the user input from interfering with the
query structure:
PreparedStatement statement = connection.prepareStatement("SELECT * FROM products WHERE category
Secure
code = ?");
statement.setString(1, input);
ResultSet resultSet = statement.executeQuery();
How to prevent SQL injection
PreparedStatement statement = connection.prepareStatement("SELECT * FROM products WHERE category = ?");
Secure statement.setString(1, input);
code ResultSet resultSet = statement.executeQuery();

 The SQL query is pre-compiled with placeholders (?)

 user input is set as a parameter using setString.


 The input is treated as data and not as part of SQL query. This prevents SQL injection because
database knows that input is not a part of SQL command to be executed.

OR ‘1’=‘1’
• In this condition, the condition ‘1’=‘1’ will always evaluate to true. If this condition is within SQL
query, it will effectively bypass any authentication check.
How to prevent SQL injection
1. Use Parameterized Queries
• Instead of dynamically constructing SQL queries by concatenating strings, use parameterized
queries or prepared statements provided by your database framework. This way, user input is
treated as data rather than executable code.

2. Input Validation
• Validate and sanitize all user input before using it in SQL queries. Ensure that input adheres to
expected formats and doesn't contain unexpected characters or SQL keywords.

3. Least Privilege Principle


• Ensure that database users have the least privilege necessary to perform their tasks. Avoid using
administrative or superuser accounts for routine operations.

4. Avoid Dynamic SQL


• Minimize the use of dynamic SQL, especially for constructing complex queries based on user input.
If dynamic SQL is unavoidable, use parameterized queries or carefully validate and sanitize input.
How to prevent SQL injection
5. Escaping Special Characters
 If you can't use parameterized queries, escape special characters in user input before including
them in SQL queries. This prevents those characters from being interpreted as part of the SQL
syntax.
6. Database Hardening
 Implement database security measures such as firewalls, intrusion detection systems, and
regular security updates to protect against SQL injection attacks at the database level.
7. Educate Developers
 Train developers on secure coding practices and the risks associated with SQL injection.
Encourage them to follow secure coding guidelines and perform regular code reviews to
identify and mitigate vulnerabilities.
How to Prevent SQL Injection
in PHP
• Step 1: Validate input
• If possible, validate the data supplied by the user  Step 5: Execute your query
against a whitelist:  After you pass the parameters, you may
if (is_numeric($id) == true) { ... } execute your query. For example:
• Step 2: Prepare a query $sth->execute();
• Create your query using parameter names preceded  Step 6: Fetch the result
with colons as placeholders:  After you execute the query, you may
$q = "SELECT username FROM users WHERE id = :id"; fetch its result to use further on. For
example:
• Step 3: Create the prepared statement
• Create the prepared SQL statement: $result = $sth->fetchColumn();
$sth = $dbh->prepare($q);  Step 7: Validate your application
• Step 4: Bind the parameters (Step 2) to the prepared statement (Step  To make sure that your application is
3) secure, use tool and run a website
vulnerability scan for your website.
• Bind your parameters to the query. For example, to
bind the value of ID, use:

$sth->bindParam(':id', $id);

You might also like