Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views143 pages

06 - SQL Injection

The document provides an introduction to SQL Injection attacks, detailing their types, history, and potential impacts on database security. It covers various SQL injection techniques, including In-Band, Blind, and Out-of-Band SQL injections, and explains the importance of understanding relational and NoSQL databases. Additionally, it outlines the prerequisites for learning about SQL injection and the objectives of the course, emphasizing the need for proper input validation in web applications.

Uploaded by

moath.dibian2020
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)
17 views143 pages

06 - SQL Injection

The document provides an introduction to SQL Injection attacks, detailing their types, history, and potential impacts on database security. It covers various SQL injection techniques, including In-Band, Blind, and Out-of-Band SQL injections, and explains the importance of understanding relational and NoSQL databases. Additionally, it outlines the prerequisites for learning about SQL injection and the objectives of the course, emphasizing the need for proper input validation in web applications.

Uploaded by

moath.dibian2020
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
You are on page 1/ 143

SQL Injection Attacks

Course Introduction
Alexis Ahmed
Senior Penetration Tester @HackerSploit
Offensive Security Instructor @INE

[email protected]
@HackerSploit
@AlexisAhmed
+ Introduction To SQL Injection.
Course + Types of SQL Injection Vulnerabilities.
Topic + Introduction to Databases, DBMS, Relational
Databases and NoSQL Databases.
Overview
+ SQL Fundamentals.
+ Hunting for SQL Injection Vulnerabilities.
+ Identifying & Exploiting In-Band SQL Injection
Vulnerabilities (Error-Based SQLi & UNION-Based
SQLi).
+ Identifying & Exploiting Blind SQL Injection
Vulnerabilities (Time-Based SQLi & Boolean-
Based SQLi).
+ Identifying & Exploiting SQLi vulnerabilities with
automated tools like SQLMap.
+ Pentesting NoSQL Databases.
+ Basic familiarity with
HTTP/HTTPS.
+ Basic familiarity with
Linux. Prerequisites
+ Basic familiarity with
OWASP ZAP/Burp
Suite.
Learning + You will have a solid understanding of what a SQL injection
vulnerabilities are, what causes them and their potential impact.
Objectives: + You will have an understanding of how Relational Databases and
NoSQL databases work and how they differ from one another.
+ You will have an understanding of the three different
categories/Types of SQL Injection vulnerabilities and their
respective subtypes.
+ You will be able to understand and write basic SQL queries.
+ You will be able to identify and exploit In-Band SQL Injection
vulnerabilities (Error-Based SQLi & UNION-Based SQLi).
+ You will be able to identify and exploit Blind SQL Injection
vulnerabilities (Time-Based SQLi & Boolean-Based SQLi).
+ You will be able to automate the identification and exploitation of
SQLi vulnerabilities with tools like SQLMap.
+ You will be able to identify and exploit vulnerabilities in NoSQL
databases.
Let’s Get Started!
Introduction To SQL Injection
Introduction to SQL Injection
● SQL injection (SQLi) is a web application injection vulnerability that
occurs when an attacker injects malicious SQL statements into an
application's input fields.
● This occurs when a web application does not properly validate user
input, allowing an attacker to inject SQL code/queries that can
manipulate the database or gain access to sensitive information.
● For example, suppose a website has a login form that accepts a
username and password. If the website does not properly validate the
user's input, an attacker could enter a malicious SQL statement into the
username field that would allow them to bypass the login process and
gain access to the website's database.
Introduction to SQL Injection
● SQL injection attacks can have serious consequences, including the theft
of sensitive data, unauthorized access to sensitive systems, and even full
system compromise.
● Complex web applications generally use a database for storing data,
user credentials or statistics.
● Content Management Systems (CMSs), as well as simple web pages,
can connect to relational databases such as MySQL, MSSQL, SQL Server,
Oracle, PostgreSQL, and others.
● To interact with databases, entities such as systems operators,
programmers, applications and web applications use the Structured
Query Language (SQL).
History of SQL Injection Attacks

● The term "SQL injection" was coined by Jeff Forristal, also known as
"Rain Forest Puppy", in a paper he presented at the DefCon 8 conference
in 2000.
● Forristal was one of the first security researchers to publicly document
the SQL injection vulnerability and explain how it could be exploited to
gain unauthorized access to databases and sensitive information.
● SQL injection attacks have been around since the early days of web
applications and database-driven websites.
History of SQL Injection Attacks
● SQL injection attacks have been around since the early days of web
applications and database-driven websites. Here's a brief history of
notable SQL injection attacks:
○ In 1998, an attacker known as "Rain Forest Puppy" used SQL injection to gain access to
a U.S. Department of Energy computer network.
○ In 2000, the first publicized SQL injection attack occurred when a hacker used SQL
injection to steal credit card data from the website of e-tailer CD Universe.
○ In 2002, a group of Russian hackers known as "The Helldiggers" used SQL injection to
gain access to the database of the United Nations, resulting in the theft of sensitive
information.
○ In 2012, the LinkedIn data breach occurred, in which attackers used SQL injection to
steal 6.5 million user passwords.
○ In 2015, the Ashley Madison data breach occurred, in which attackers used SQL
injection to steal sensitive user data from the infidelity dating site.
SQL Injection Impact
● Confidentiality - Since SQL databases generally hold sensitive data, loss
of confidentiality is a frequent problem with SQL Injection vulnerabilities.
● Integrity - Just as it may be possible to read sensitive information, it is
also possible to make changes or even delete this information with a
SQL Injection attack.
● Authentication - If poor SQL commands are used to check user names
and passwords, it may be possible to connect to a system as another
user with no previous knowledge of the password.
● Availability - SQL injection attacks can affect the availability of a web
application and database and could take the website down due to
loss/damage of data.
SQL Injection Consequences
● Sensitive data exposure/data breaches - SQL injection attacks can result
in unauthorized access to sensitive data stored in a database. Attackers
may be able to view or steal confidential information, such as customer
data, financial information, and intellectual property.
● Data manipulation - Attackers may be able to modify or delete data
stored in a database, potentially causing data loss or corruption.
● Code execution - If a database user has administrative privileges, an
attacker can gain access to the target system using malicious code.
● Business disruption - Successful SQL injection attacks can lead to
business disruption, as organizations work to restore services and
prevent further attacks.
Demo: SQL Injection Risks
Anatomy of an SQL Injection Attack
Anatomy of an SQL injection Attack
Web Application

1 Specially crafted Web Server


Attacker HTTP request
Database
2 SQL Query

Internet
3 Data

4 HTTP response
with data
Authenticated Connection
Types of SQL Injection Vulnerabilities
SQL Injection Types & Subtypes
SQL Injection

In-Band SQLi Blind SQLi Out-of-Band SQLi

Error Based SQLi Union Based SQLi Boolean Based SQLi Time Based SQLi
In-Band SQL Injection
● In-band SQL injection is the most common type of SQL injection attack. It
occurs when an attacker uses the same communication channel to send
the attack and receive the results.
● In other words, the attacker injects malicious SQL code into the web
application and receives the results of the attack through the same
channel used to submit the code.
● In-band SQL injection attacks are dangerous because they can be used
to steal sensitive information, modify or delete data, or take over the
entire web application or even the entire server.
In-Band SQL Injection
During an in-band SQLi attack the penetration tester
finds a way to ask the the web application for desired
information.

Web Application
1

Attacker Web Server


List user
accounts Database
SQL Query
Internet

User accounts:
2 admin, john, mike
In-Band SQL Injection Subtypes
● In-band SQL injection can be further divided into two
subtypes/exploitation techniques:
○ Error-based SQL injection: In error-based SQL injection, the attacker injects
SQL code that causes the web application to generate an error message. The
error message can contain valuable information about the database schema
or the contents of the database itself, which the attacker can use to further
exploit the vulnerability.
○ Union-based SQL injection: In union-based SQL injection, the attacker uses
the UNION operator to combine the results of two or more SQL queries into
a single result set. By manipulating the injected SQL code, the attacker can
extract data from the database that they are not authorized to access.
Error Based SQL Injection
During an Error-Based SQL injection attack, the
penetration tester tries to force the DBMS to output an
error message and then uses that information to
perform data exfiltration.
Web Application
1

Attacker Web Server


SQLi Payload
Database
SQL Query
Internet

2 ERROR MESSAGE
Blind SQL Injection
● Blind SQL Injection is a type of SQL Injection attack where an attacker
can exploit a vulnerability in a web application that does not directly
reveal information about the database or the results of the injected SQL
query.
● In this type of attack, the attacker injects malicious SQL code into the
application's input field, but the application does not return any useful
information or error messages to the attacker in the response.
● The attacker typically uses various techniques to infer information about
the database, such as time delays or Boolean logic.
● The attacker may inject SQL code that causes the application to delay for
a specified amount of time, depending on the result of a query.
Blind SQL Injection Subtypes
● Blind SQL injection can be further divided into two subtypes/exploitation
techniques:
○ Boolean-based SQL Injection: In this type of attack, the attacker exploits the
application's response to boolean conditions to infer information about the
database. The attacker sends a malicious SQL query to the application and
evaluates the response based on whether the query executed successfully or
failed.
○ Time-based Blind Injection: In this type of attack, the attacker exploits the
application's response time to infer information about the database. The
attacker sends a malicious SQL query to the application and measures the
time it takes for the application to respond.
Blind SQL Injection (Boolean-based)
An attacker might send a query that asks whether a particular username
exists in the database, and the application's response will either be true
or false. By asking a series of questions and analyzing the responses, the
attacker can slowly build up a picture of the database schema and
contents. Web Application
1

Attacker Does the user Web Server


“john” exist? Database
SQL Query
Internet

2 TRUE/FALS
E
Out-of-Band SQL Injection
● Out-of-band SQL Injection is the least common type of SQL injection
attack. It involves an attacker exploiting a vulnerability in a web
application to extract data from a database using a different channel,
other than the web application itself.
● Unlike in-band SQL Injection, where the attacker can observe the result
of the injected SQL query in the application's response, out-of-band SQL
Injection does not require the attacker to receive any response from the
application.
● The attacker can use various techniques to extract data from the
database, such as sending HTTP requests to an external server
controlled by the attacker or using DNS queries to extract data.
Out-of-Band SQL Injection
An Out-Of-Band attack is classified by having two different communication
channels, one to launch the attack and the other to gather the results. For example,
the attack channel could be a web request, and the data gathering channel could
be monitoring HTTP/DNS requests made to a service you control.
Web Application
1
Attacker Web Server
SQLi Payload
Database
SQL Query
Internet

Response sent back via


alternate communication
2 channel
Introduction To Databases & DBMS
Introduction to Databases
● A database is a collection of data that is organized in a way that makes it
easy to manage, access, and update.
● In computing, a database is typically managed by a Database
Management System (DBMS) that provides a set of tools and interfaces
to interact with the data.
● Databases are used in a variety of applications, including business
applications, websites, and mobile apps, to store and manage large
amounts of structured or unstructured data. Some examples of data that
can be stored in a database include customer information, financial
records, product inventory, and employee records.
Database Management Systems (DBMS)
● DBMS stands for "Database Management System". It is a software
system that enables users to create, store, organize, manage, and
retrieve data from a database.
● DBMS provides an interface between the user and the database,
allowing users to interact with the database without having to
understand the underlying technical details of data storage, retrieval,
and management.
● DBMS provides various functionalities such as creating, deleting,
modifying, and querying the data stored in the database. It also manages
security, concurrency control, backup, recovery, and other important
aspects of data management.
Database Management Systems (DBMS)
● The following are examples of popular DBMS (Database Management
Systems):
○ MySQL - A free, open-source relational database management system that
is widely used for web applications.
○ PostgreSQL - Another popular open-source relational database
management system that is known for its advanced features and reliability.
○ Oracle Database - A commercial relational database management system
developed by Oracle Corporation that is widely used in enterprise
applications.
○ Microsoft SQL Server - A commercial relational database management
system developed.
Types of Databases
● Relational Databases - A database that organizes data into one or more
tables or relations, where each table represents an entity or a concept,
and the columns of the table represent the attributes of that entity or
concept.
● NoSQL Databases - A type of database that does not use the traditional
tabular relations used in relational databases. Instead, NoSQL databases
use a variety of data models to store and access data.
● Object-oriented Databases - A database that stores data as objects
rather than in tables, allowing for more complex data structures and
relationships.
SQL Databases
● SQL databases are relational databases that store data in tables with
rows and columns, and use SQL (Structured Query Language) as their
standard language for managing data.
● They enforce strict data integrity rules and support transactions to
ensure data consistency.
● SQL databases are widely used in applications that require complex data
queries and the ability to handle large amounts of structured data. Some
examples of SQL databases include MySQL, Oracle, Microsoft SQL
Server, and PostgreSQL.
Relational Databases vs NoSQL
Databases
Relational Databases
● A relational database is a type of database that organizes data into one
or more tables or relations, where each table represents an entity or a
concept, and the columns of the table represent the attributes of that
entity or concept.
● The relations between the tables are established by the use of keys,
which link the records in one table to the records in another table.
● Relational databases use a structured query language (SQL) to manage
the data.
● SQL is a standardized language used to create, manipulate, and query
relational databases.
RDBMS
● RDBMS stands for Relational Database Management System.
● It is a software system that enables the creation, management, and
administration of relational databases.
● RDBMSs are designed to store, organize, and retrieve large amounts of
structured data efficiently.
● RDBMSs provide a set of features and functionalities that allow users to
create database schemas, define relationships between tables, insert,
update, and retrieve data, and perform complex queries using SQL.
● They also handle aspects like data security, transaction management,
and concurrency control to ensure data integrity and consistency.
RDBMS
● Some popular examples of RDBMSs include:
○ Oracle Database: Developed by Oracle Corporation, it is one of the most
widely used enterprise-level RDBMSs known for its scalability, reliability,
and comprehensive feature set.
○ MySQL: An open-source RDBMS that is known for its ease of use, high
performance, and wide adoption. MySQL is commonly used in web
applications and is backed by Oracle Corporation.
○ Microsoft SQL Server: A popular RDBMS developed by Microsoft. It offers a
range of editions for different workloads and has strong integration with
other Microsoft products.
○ PostgreSQL: An open-source RDBMS known for its robustness, scalability,
and adherence to SQL standards. PostgreSQL offers advanced features and
is highly extensible.
How Relational Databases Work
● Tables: The basic building blocks of a relational database are tables, also
known as relations. A table consists of rows (also called records or
tuples) and columns (also known as attributes). Each row represents a
unique record or instance of an entity, and each column represents a
specific attribute or characteristic of that entity.
● Keys: Keys are used to uniquely identify records within a table and
establish relationships between tables. The primary key is a column or
set of columns that uniquely identifies each row in a table. It ensures the
integrity and uniqueness of the data. Foreign keys are columns in one
table that reference the primary key of another table, establishing
relationships between the tables.
How Relational Databases Work
● Relationships: Relationships define how tables are connected or
associated with each other. Common types of relationships include one-
to-one, one-to-many, and many-to-many. These relationships are
established using primary and foreign keys, allowing data to be linked
and retrieved across multiple tables.
● Structured Query Language (SQL): Relational databases are typically
accessed and manipulated using the Structured Query Language (SQL).
SQL provides a standardized language for querying, inserting, updating,
and deleting data from relational databases. It allows users to perform
operations such as retrieving specific records, filtering data based on
conditions, joining tables to combine data, and aggregating data using
functions.
How Relational Databases Work

Student Courses

Student ID Course ID

1 1

Students 1 2 Courses

ID Name 2 2 ID Name

1 Mike 3 1 1 XSS

2 John 2 Java

3 Mary 3 PHP
NoSQL Databases
● NoSQL (Not Only SQL) databases are a type of database management
system that differ from traditional relational databases (RDBMS) in terms
of data model, scalability, and flexibility.
● NoSQL databases are designed to handle large volumes of unstructured,
semi-structured, and rapidly changing data.
● NoSQL databases are commonly used in modern web applications, big
data analytics, real-time streaming, content management systems, and
other scenarios where the flexibility, scalability, and performance
advantages they offer are valuable.
NoSQL Databases
● There are several popular NoSQL databases available, each with its own
strengths and use cases. Here are some examples of well-known
NoSQL databases:
○ MongoDB: MongoDB is a document database that stores data in flexible,
JSON-like documents. It provides scalability, high performance, and rich
query capabilities. MongoDB is widely used in web applications, content
management systems, and real-time analytics.
○ Redis: Redis is an in-memory data store that supports various data
structures, including strings, hashes, lists, sets, and sorted sets. It is known
for its exceptional performance and low latency. Redis is often used for
caching, real-time analytics, session management, and pub/sub messaging.
Introduction To SQL
Introduction to SQL
● Complex web applications generally use a database for storing data,
user credentials or statistics. CMSs, as well as simple personal web
pages, can connect to databases such as MySQL, SQL Server, Oracle,
PostgreSQL, and others.
● In order to interact with databases, applications and web applications
use the Structured Query Language (SQL).
● SQL is a powerful interpreted language used to extract and manipulate
data from a database. Web applications embed SQL commands, also
known as queries, in their server-side code.
Database Connectors
● The server-side code usually takes care of
establishing and maintaining the connection to
the database through the use of connectors.
● Database connectors, also known as database
drivers or database connectors, are software
components or libraries that provide an interface
to connect and interact with specific databases
from an application or programming language.
● They enable applications to communicate with
the database, execute queries, retrieve and
modify data, and handle database transactions.
Introduction to SQL
● Before learning how to perform a SQL Injection attack, we have to know
the following:

○ SQL statement syntax


○ How to perform a query
○ How to combine the results of two queries with the UNION
operator
○ How comments work
Important SQL Commands

Command Function

SELECT Read data from the database based on specific search criteria.

UNION Used to combine the results of two or more SELECT statements.

INSERT Insert a new record into the database/table.

UPDATE Update existing data/record based on specified criteria.

DELETE Delete existing data/record based on specified criteria.

Order By Used to sort the result-set in ascending or descending order.

Limit By Used to retrieve records from one or more tables.


SQL Special Characters
Command Function

‘ or “ Character string indicators.

/*...*/ Multi-line comment.

+ Addition or concatenation.

# or - - (Hyphen hyphen) Single-line comment.

|| (Double pipe) Concatenation

% Wildcard attribute indicator

@variable Local variable.

@@variable Global variable.

waitfor delay ‘00:00:10’ Time delay.


SELECT Statement Syntax
In order to better understand SQLi, you need to know the basic syntax of a
SELECT statement:

> SELECT <columns list> FROM <table> WHERE <condition>;


SELECT Statement Example
A typical SELECT SQL statement/query looks like the following:

> SELECT name, description FROM products WHERE id=9;

The SQL code snippet above queries the database, asking for the name and
the description attributes of a record in the products table. In this
example, the selected record has an id of 9.
UNION Statement Syntax
The following is an example of an SQL statement that uses the UNION
command:

> <SELECT statement> UNION <other SELECT statement>;


UNION Statement Example
A typical UNION SQL statement/query looks like the following:

> SELECT name, description FROM products WHERE id=9 UNION SELECT
price FROM products WHERE id=9;

The SQL code snippet above queries the database, asking for the name and
the description attributes of a record in the products table in addition to
querying the database for the price attribute of the record with an id
equal to 9.
SQL Comments
There are two strings you can use to comment a line in SQL:
● # (the hash symbol)
● -- (two dashes followed by a space)

> SELECT field FROM table; # this is a comment


> SELECT field FROM table; -- this is another comment
How Web Apps Utilize SQL Queries
The following code contains a PHP example of a connection to a MySQL
database and the execution of a SQL query.

$dbhostname='1.2.3.4';
$dbuser='username';
$dbpassword='password';
$dbname='database';

$connection = mysqli_connect($dbhostname, $dbuser, $dbpassword, $dbname);


$query = "SELECT Name, Description FROM Products WHERE ID='3' UNION SELECT Username,
Password FROM Accounts;";

$results = mysqli_query($connection, $query);


display_results($results);
How Web Apps Utilize SQL Queries
The previous example shows a static query example inside a PHP page:

● $connection is an object referencing the connection to the database.


● The $query variable contains the SQL query.
● mysqli_query() is a function which submits the query to the
database.
● Finally, the custom display_results() function renders the data.
How Web Apps Utilize SQL Queries
Anatomy of a database interaction in PHP. This example uses a MySQL
database.

$dbhostname='1.2.3.4'; Configuration
$dbuser='username';
$dbpassword='password';
$dbname='database';
Connection

$connection = mysqli_connect($dbhostname, $dbuser, $dbpassword, $dbname);


$query = "SELECT Name, Description FROM Products WHERE ID='3' UNION SELECT
Username, Password FROM Accounts;";
Query
definition $results = mysqli_query($connection, $query);
display_results($results);
Submit
Usage
Vulnerable Dynamic Queries
Most of the times queries are not static; they are indeed dynamically built by
using user' inputs. Here you can find a vulnerable dynamic query example:

$id = $_GET['id'];

$connection = mysqli_connect($dbhostname, $dbuser, $dbpassword, $dbname);


$query = "SELECT Name, Description FROM Products WHERE ID='$id';";

$results = mysqli_query($connection, $query);


display_results($results);
Vulnerable Dynamic Queries
● The previous example shows some code which uses user-supplied input
to build a query (the id parameter of the GET request). The code then
submits the query to the database.

● This behavior is very dangerous because a malicious user can exploit the
query construction to take control of the database interaction.

Let’s see how!


Vulnerable Dynamic Queries
The dynamic query:

SELECT Name, Description FROM Products WHERE ID='$id';

Expects $id values such as:


+ 1 - SELECT Name, Description FROM Products WHERE
ID='1';
+ Example - SELECT Name, Description FROM Products WHERE
ID='Example';
+ Itid3 - SELECT Name, Description FROM Products WHERE
ID='Itid3';
Vulnerable Dynamic Queries
But, what if an attacker crafts an $id value which can actually change the
query? Something like:

' OR 'a'='a

Then the query becomes:

SELECT Name, Description FROM Products WHERE ID='' OR 'a'='a';


Vulnerable Dynamic Queries
● This tells the database to select the items by checking two conditions:
○ The id must be empty (id='')
○ OR an always true condition ('a'='a’)

● While the first condition is not met, the SQL engine will consider the
second condition of the OR. This second condition is crafted as an
always true condition.
● In other words, this tells the database to select all the items in the
Products table!
SQL Fundamentals
Demo: SQL Fundamentals
Hunting For SQL Injection Vulnerabilities
Finding SQL Injection Vulnerabilities
● In order to exploit a SQL injection vulnerability, you first have to identify
an injection point within the web application, after which, you can craft a
SQL query/payload that can be injected in an injectable parameter.
● The most straightforward way to find SQL injection vulnerabilities within
a web application is to probe its inputs with special characters that are
known to cause the SQL query to be syntactically invalid therefore
forcing the web application to return an error.

Note: Not all the inputs in a web application interact with the database. It
is therefore recommended to perform reconnaissance on the web
application and categorize the different input parameters.
Common Injectable Fields
● SQL injection vulnerabilities can exist in various input fields within an
application. Here are some common examples of injectable fields where
SQL injection vulnerabilities can be found:
○ Login forms: The username and password fields in a login form are common
targets for SQL injection attacks. If the application does not properly validate
or sanitize the input, an attacker may be able to manipulate the SQL query
used for authentication.
○ Search boxes: Input fields used for searching within an application are
potential targets for SQL injection. If the search query is directly incorporated
into a SQL statement without proper validation, an attacker can inject
malicious SQL code to manipulate the query and potentially access
unauthorized data.
Common Injectable Fields
○ URL parameters: Web applications often use URL parameters to pass data
between pages. If the application uses these parameters directly in
constructing SQL queries without proper validation and sanitization, it can be
susceptible to SQL injection attacks.
○ Form fields: Any input fields in forms, such as registration forms, contact
forms, or comment fields, can be vulnerable to SQL injection if the input is
not properly validated and sanitized before being used in SQL queries.
○ Hidden fields: Hidden fields in HTML forms can also be susceptible to SQL
injection attacks if the data from these fields is directly incorporated into SQL
queries without proper validation.
○ Cookies: In some cases, cookies containing user data or session information
may be used in SQL queries. If the application does not validate or sanitize
the cookie data properly, it can lead to SQL injection vulnerabilities.
Finding SQL Injection Vulnerabilities
Identifying SQL injection vulnerabilities typically involves a combination of
manual testing and automated scanning. Here are some methods to help
identify SQL injection vulnerabilities:

Manual Testing
● Manual testing with malicious input: Try injecting SQL statements or
special characters into input fields such as login forms, search boxes, or
URL parameters. Look for unexpected behavior, error messages, or any
indications that the input is being interpreted as SQL code.
● Error-based testing: Submitting intentionally malformed input to trigger
SQL errors can reveal underlying database errors or SQL statements
being executed.
Finding SQL Injection Vulnerabilities
● Union-based testing: Injecting UNION SELECT statements into input
fields can help determine if the application is vulnerable to SQL injection
by retrieving data from other tables or databases.
● Boolean-based testing: Manipulating the application's response based
on Boolean conditions can help determine if the application is
vulnerable. For example, injecting ' OR '1'='1 in a login form to bypass
authentication.
● Time-based testing: Injecting time-delayed SQL queries can reveal if the
application is vulnerable to time-based blind SQL injection by observing
delays in the server response.
Finding SQL Injection Vulnerabilities
● Input validation and sanitization: Review the application's code and
check if proper input validation and sanitization techniques are
implemented. Look for instances where user input is directly
concatenated into SQL queries without proper sanitization or prepared
statements.

Automated Testing
● Automated vulnerability scanners: Utilize automated tools such as
SQLMap, OWASP ZAP, or Burp Suite to scan for SQL injection
vulnerabilities. These tools can help automate the process of identifying
and exploiting SQL injection vulnerabilities in web applications.
SQL Injection Testing
● Testing an application input for SQL injection will typically involve trying
to inject:

○ String terminators: ' and "


○ SQL commands: SELECT, UNION, and other SQL commands
○ SQL comments: # or --

● It is also important to consider whether the injectable parameter/input is


string based or integer based.

Note: Always test one injection at a time! Otherwise, you will not be able
to identify which injection vector/payload is successful.
Integer Based Injection
● Integer based parameter injection - In some cases, SQL queries will
treat the injectable parameter as an integer depending on the data type.

URL — http://site.com/user.php?id=1

SQL Query – SELECT * FROM Users WHERE id = FUZZ;

In such cases, it is recommended to utilize SQL queries that use logical


operators (boolean) operations to test for injection.
Integer Based Injection Payloads

AND 1 - True
AND 0 - False
AND true - True
And false - false
1-false - Returns 1 if vulnerable
1-true - Returns 0 if vulnerable
1*56 - Returns 56 if vulnerable
1*56 - Returns 1 if not vulnerable
String Based Injection
● String based parameter injection - In some cases, the SQL queries will
treat the injectable parameter as a string.

URL — http://site.com/user.php?id=alexis

SQL Query – SELECT * FROM Users WHERE name = ‘FUZZ’;

In such cases, it is recommended to utilize special SQL characters like the


single quote to delimit string literals.
‘ - False
‘’ - True
“ - False
“” - True
Exploiting The Single Quote (‘)

● SQL injection vulnerabilities often arise when user-supplied input is not


properly validated, sanitized, or handled within the application code.
● One common technique used in SQL injection attacks is exploiting the
single quote character (').
● In SQL, the single quote is used to delimit string literals. When user
input is directly incorporated into an SQL query without proper handling,
an attacker can inject a single quote character as part of the input, which
can disrupt the intended query structure and allow for the injection of
malicious SQL code.
Exploiting The Single Quote (‘)
● For example, consider a login form where the username and password
inputs are concatenated into an SQL query without proper validation:
SELECT * FROM users WHERE username = '<username>' AND password =
'<password>'

If the application does not handle the single quote character in the input
correctly, an attacker can inject a single quote to terminate the string literal
and add their malicious SQL code. Here's an example of an attack payload:

' OR '1'='1'; --
Exploiting The Single Quote (‘)
● The modified query would become:

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


password = '<password>'

● In this example, the single quote ' is injected before the payload ' OR
'1'='1'; --. The purpose of the injected single quote is to close the string
literal that encompasses the username input field.
● Then, the attacker's injected SQL code ' OR '1'='1'; -- causes the
condition '1'='1' to evaluate to true, effectively bypassing the
authentication mechanism.
Database Fingerprinting
● Every DBMS/RDBMS responds to incorrect/erroneous SQL queries with
different error messages.

A typical error from MS-SQL will look like this:

Incorrect syntax near [query snippet]

While a typical MySQL error looks more like this:

You have an error in your SQL syntax. Check the manual that corresponds
to your MySQL server version for the right syntax to use near [query
snippet]
Common SQLi Payloads
' ‘ or ‘1’=‘1 --
-- or #
'' ‘ or (‘1’=‘1’ -–
' OR '1
` Admin’ –-
' OR 1 -- -
`` Admin’ #
" OR "" = "
, ‘ having 1=1 -–
" OR 1 = 1 -- -
" ‘ or b=b -–
' OR '' = '
"" ‘ or 1=1#
'='
/ ‘ or 2 > 1 -–
'LIKE'
// ‘ or test=test-–
'=0--+
\ ‘) or ‘1’=‘1 -–
OR 1=1
\\ ‘ or 10-5=5 -–
' OR 'x'='x
; ‘ or sqltest=sql+test-–
' AND id IS NULL; --
' or " ‘’ or a=a –
Admin’--
Database Specific SQLi Payloads

--MySQL, MSSQL, Oracle,


PostgreSQL, SQLite
' OR '1'='1’ –
' OR '1'='1' /*

--MySQL
' OR '1'='1’ #

--Access (using null characters)


' OR '1'='1' %00
' OR '1'='1' %16
OWASP Testing Checklist - SQLi
https://github.com/tanprathan/OWASP-Testing-Checklist
SQLi Resources
● The following is a list of useful, open source repositories, tools and
documentation that will provide you with information and payloads that
can be used to test for different types and subtypes of SQLi
vulnerabilities:

Cheat Sheets
● https://github.com/payloadbox/sql-injection-payload-list
● https://portswigger.net/web-security/sql-injection/cheat-sheet
OWASP
● OWASP WSTG: https://owasp.org/www-project-web-security-
testing-guide/
Finding SQL Injection Vulnerabilities
Manually
Demo: Finding SQL Injection
Vulnerabilities Manually
Finding SQL Injection Vulnerabilities With
OWASP ZAP
Demo: Finding SQL Injection
Vulnerabilities With OWASP ZAP
Exploiting Error-Based SQL Injection
Vulnerabilities
SQL Injection Types & Subtypes
SQL Injection

In-Band SQLi Blind SQLi Out-of-Band SQLi

Error Based SQLi Union Based SQLi Boolean Based SQLi Time Based SQLi
In-Band SQL Injection
● In-band SQL injection is the most common type of SQL injection attack. It
occurs when an attacker uses the same communication channel to send
the attack and receive the results.
● In other words, the attacker injects malicious SQL code into the web
application and receives the results of the attack through the same
channel used to submit the code.
● In-band SQL injection attacks are dangerous because they can be used
to steal sensitive information, modify or delete data, or take over the
entire web application or even the entire server.
In-Band SQL Injection
During an in-band SQLi attack the penetration tester
finds a way to ask the the web application for desired
information.

Web Application
1

Attacker Web Server


List user
accounts Database
SQL Query
Internet

User accounts:
2 admin, john, mike
Error-Based SQL Injection
● Error-based SQL injection is a technique used by attackers to exploit SQL
injection vulnerabilities in web applications.
● It relies on intentionally causing database errors and using the error
messages returned by the database to extract information or gain
unauthorized access to the application's database.
● The error message can contain valuable information about the database
schema or the contents of the database itself, which the attacker can use
to further exploit the vulnerability.
● Identifying error-based SQL injection vulnerabilities involves testing the
web application to determine if it is susceptible to this type of attack.
Error-Based SQL Injection Methodology
● Identify a vulnerable parameter: Find a parameter in the web application
that is vulnerable to SQL injection, typically through user input fields,
URL parameters, or form inputs.
● Inject malicious SQL code: Craft a payload that includes SQL statements
designed to trigger a database error. This can involve appending invalid
SQL syntax or manipulating existing queries.
● Observe error messages: Submit the payload to the vulnerable
parameter and observe the error message returned by the database. The
error message can provide valuable information about the structure and
content of the database.
Error-Based SQL Injection Methodology
● Extract data: Modify the payload to extract specific information from the
database by leveraging the error messages. This can include retrieving
usernames, passwords, or other sensitive data stored in the database.
● Exploit the vulnerability: Exploit the information gathered through error-
based SQL injection to further exploit the application, gain unauthorized
access, or perform other malicious actions.
Error Based SQL Injection
During an Error-Based SQL injection attack, the
penetration tester tries to force the DBMS to output an
error message and then uses that information to
perform data exfiltration.
Web Application
1

Attacker Web Server


SQLi Payload
Database
SQL Query
Internet

2 ERROR MESSAGE
Demo: Exploiting Error-Based SQL
Injection Vulnerabilities
Exploiting Union-Based SQL Injection
Vulnerabilities
SQL Injection Types & Subtypes
SQL Injection

In-Band SQLi Blind SQLi Out-of-Band SQLi

Error Based SQLi Union Based SQLi Boolean Based SQLi Time Based SQLi
Union-Based SQL Injection
● Union-based SQL injection is a type of SQL injection attack that exploits
the ability to use the UNION operator in SQL queries.
● It occurs when an application fails to properly validate or sanitize user
input and allows an attacker to inject malicious SQL code into the query.
● The UNION operator is used in SQL to combine the results of two or
more SELECT statements into a single result set.
● It requires that the number of columns and their data types match in the
SELECT statements being combined.
● In a union-based SQL injection attack, the attacker injects additional
SELECT statements through the vulnerable input to retrieve data from
other database tables or to extract sensitive information.
Union-Based SQL Injection
Here's an example to illustrate the concept. Consider the following
vulnerable code snippet:
SELECT id, name FROM users WHERE id = '<user_input>'

An attacker can exploit this vulnerability by injecting a UNION-based attack


payload into the <user_input> parameter. They could inject a statement like:

' UNION SELECT credit_card_number, 'hack' FROM credit_cards --

The injected payload modifies the original query to retrieve the credit card
numbers along with a custom value ('hack') from the credit_cards table. The
double dash at the end is used to comment out the remaining part of the
original query.
Union-Based SQL Injection
If the application is vulnerable to union-based SQL injection, the modified
query would become:

SELECT id, name FROM users WHERE id = '' UNION SELECT


credit_card_number, 'hack' FROM credit_cards --

The database would then execute this modified query, and the result would
include the credit card numbers alongside the original user data. The attacker
can subsequently extract this sensitive information.
Union-Based SQL Injection Methodology
● Identify user inputs: Determine the inputs on the application that are
used in database queries. These inputs can include URL parameters,
form fields, cookies, or any other user-controllable data.
● Test inputs for vulnerability: Inject a simple payload, such as a single
quote (') or a double quote ("). If the application produces an error or
exhibits unexpected behavior, it might indicate a potential SQL injection
vulnerability.
● Identify vulnerable injection points: Manipulate the injected payload to
check if the application responds differently based on the injected data.
You can try injecting various payloads like UNION SELECT statements or
boolean conditions (e.g., ' OR '1'='1) to see if the application behaves
differently based on the response.
Union-Based SQL Injection Methodology
● Confirm the presence of a vulnerability: Once you have identified a
potential injection point, you need to confirm if it is vulnerable to Union-
based SQL injection. To do this, you can inject a UNION SELECT
statement and observe the application's response. If the response
includes additional columns or unexpected data, it is likely vulnerable to
Union-based SQL injection.
● Enumerate the database: Exploit the Union-based SQL injection
vulnerability to enumerate the database structure. Inject UNION SELECT
statements with appropriate column names and table names to retrieve
information about the database schema, tables, and columns. You can
use techniques like ORDER BY or LIMIT clauses to retrieve specific
information.
Demo: Exploiting Union-Based SQL
Injection Vulnerabilities
Introduction To Boolean-Based SQL
Injection Vulnerabilities
SQL Injection Types & Subtypes
SQL Injection

In-Band SQLi Blind SQLi Out-of-Band SQLi

Error Based SQLi Union Based SQLi Boolean Based SQLi Time Based SQLi
Blind SQL Injection
● Blind SQL Injection is a type of SQL Injection attack where an attacker
can exploit a vulnerability in a web application that does not directly
reveal information about the database or the results of the injected SQL
query.
● In this type of attack, the attacker injects malicious SQL code into the
application's input field, but the application does not return any useful
information or error messages to the attacker in the response.
● The attacker typically uses various techniques to infer information about
the database, such as time delays or Boolean logic.
● The attacker may inject SQL code that causes the application to delay for
a specified amount of time, depending on the result of a query.
Blind SQL Injection Subtypes
● Blind SQL injection can be further divided into two subtypes/exploitation
techniques:
○ Boolean-based SQL Injection: In this type of attack, the attacker exploits the
application's response to boolean conditions to infer information about the
database. The attacker sends a malicious SQL query to the application and
evaluates the response based on whether the query executed successfully or
failed.
○ Time-based Blind Injection: In this type of attack, the attacker exploits the
application's response time to infer information about the database. The
attacker sends a malicious SQL query to the application and measures the
time it takes for the application to respond.
Boolean-Based SQL Injection
● Boolean-based SQL injection is a technique used to exploit SQL injection
vulnerabilities in web applications when the application does not directly
reveal the results of the injected SQL queries.
● In this type of attack, the attacker uses boolean-based conditional
statements to infer information indirectly.
● Blind SQL injection attacks typically occur when the application does not
display database errors or query results on the web page.
● Instead, the attacker can manipulate the application's behavior by
injecting boolean conditions into the SQL queries and observing the
resulting behavior or response from the application.
Blind SQL Injection (Boolean-based)
An attacker might send a query that asks whether a particular username
exists in the database, and the application's response will either be true
or false. By asking a series of questions and analyzing the responses, the
attacker can slowly build up a picture of the database schema and
contents. Web Application
1

Attacker Does the user Web Server


“john” exist? Database
SQL Query
Internet

2 TRUE/FALS
E
Boolean-Based SQL Injection
Here's an example to illustrate the concept. Let's say there is a vulnerable
login page that uses the following SQL query to check the credentials
provided by the user:

SELECT * FROM users WHERE username = '<username>' AND password =


'<password>'

An attacker can attempt a boolean-based SQL injection attack by


manipulating the username parameter. For instance, if the attacker enters the
following username:

' OR '1'='1
Boolean-Based SQL Injection
The resulting SQL query executed by the application would become:

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


'<password>'

● In this case, the injected portion ' OR '1'='1 always evaluates to true,
effectively bypassing the original password check.
● The attacker can then potentially gain unauthorized access or perform
other malicious actions.
● To extract information from the database, an attacker can use a
technique called "blind" boolean-based SQL injection.
Boolean-Based SQL Injection

● In blind attacks, the attacker doesn't directly see the query results but
uses conditional statements to infer information indirectly.
● For example, the attacker might craft an injection like ' OR
LENGTH(database()) > 5--, which tests whether the length of the
database name is greater than 5 characters.
● By observing the application's response, such as a page displaying
specific content or a delay in the response, the attacker can gradually
extract information about the database structure.
Boolean-Based SQL Injection Methodology
● Identify potential injection points: Analyze the application's functionality
and identify input points where user-supplied data is used in SQL
queries. Look for parameters in URLs, form fields, cookies, or any other
user-controllable input.
● Analyze the application's behavior: Submit various inputs and observe
the application's response. Look for indications of blind vulnerabilities,
such as different response times, error messages, or changes in the
application's behavior without directly displaying query results.
● Craft test payloads: Create payloads that inject boolean conditions into
the input fields identified in step 1. Use techniques like appending ' OR
<condition> -- to the input to check if the condition affects the
query's logic.
Boolean-Based SQL Injection Methodology
● Observe application response: Submit the crafted payloads and analyze
the application's response. Look for differences in behavior that may
indicate whether the injected condition is evaluated as true or false.
● Perform binary search: If you detect a difference in behavior but cannot
directly extract data, perform a binary search-like approach. Inject
conditions that split the possible range in half, testing each half at a time
to narrow down the potential values or lengths of data in the database.
● Extract information gradually: Once you have identified a blind boolean-
based vulnerability, continue crafting payloads to extract information
from the database. Guess the length of strings, characters, or check for
the existence of specific data using boolean conditions.
Demo: Bypassing Authentication
With Boolean-Based SQL Injection
Exploiting Boolean-Based SQL
Injection Vulnerabilities
Demo: Exploiting Boolean-Based SQL
Injection Vulnerabilities
Exploiting Time-Based SQL Injection
Vulnerabilities
SQL Injection Types & Subtypes
SQL Injection

In-Band SQLi Blind SQLi Out-of-Band SQLi

Error Based SQLi Union Based SQLi Boolean Based SQLi Time Based SQLi
Time-Based SQL Injection
● Time-based SQL injection is a technique used to exploit vulnerabilities in
a web application's database layer by manipulating the SQL queries to
introduce delays.
● This type of attack relies on the ability to inject malicious SQL code that
causes the application to pause or delay its response, revealing
information about the database structure or data.
● The basic idea behind time-based SQL injection is to inject SQL
statements that force the application to wait for a certain period of time
before responding. The attacker can then infer information about the
database by measuring the delay in the application's response.
Time-Based SQL Injection
Here's an example of a time-based SQL injection attack:
Assume we have a vulnerable login form where a user provides their
username and password, and the application performs a SQL query to
validate the credentials:
SELECT * FROM users WHERE username = '[username]' AND password =
'[password]';

An attacker can exploit this vulnerability by injecting malicious SQL code that
introduces a delay. For example, the attacker might provide the following
input as the username:

' OR SLEEP(5) -- '


Time-Based SQL Injection
The injected SQL code ' OR SLEEP(5) -- ' modifies the original query
to:
SELECT * FROM users WHERE username = '' OR SLEEP(5) -- ' AND
password = '[password]';

● In this case, the SLEEP(5) function is causing the database to pause


execution for 5 seconds before responding.
● If the application takes noticeably longer to respond, it indicates that the
injected query is causing a delay.
● The attacker can then infer that the injection point is vulnerable to time-
based SQL injection.
Demo: Exploiting Time-Based SQL
Injection Vulnerabilities
NoSQL Fundamentals
Introduction to NoSQL
● NoSQL databases, also known as "Not Only SQL" databases, are a class
of database management systems that provide a non-relational
approach for storing and retrieving data.
● Unlike traditional relational databases, which organize data into tables
with predefined schemas, NoSQL databases offer more flexible data
models that can handle unstructured, semi-structured, and rapidly
evolving data.
● NoSQL databases emerged as a response to the need for scalability,
performance, and agility in handling modern data types and workloads.
Types of NoSQL Databases
● Key-Value Stores: These databases store data as a collection of key-
value pairs. The value can be any type of data, such as text, JSON, or
binary objects. Examples include Redis, Riak, and Amazon DynamoDB.
● Document Databases: Document databases store and retrieve data in
JSON-like documents. Documents can vary in structure, and the
database provides features for querying and indexing based on the
document's content. MongoDB and Couchbase Server are popular
document databases.
● Columnar Databases: Columnar databases organize data into columns
rather than rows, making them efficient for analytical workloads and
handling large volumes of data. Apache Cassandra and Apache HBase
are examples of columnar databases.
NoSQL vs SQL Databases
FEATURE SQL NoSQL

Type Relational Non-Relational

Data Storage Tables with fixed rows and columns. ● Unstructured.


Model ● Stored in JSON files.
● Key-value pairs; tables with rows and dynamic
columns.

Schema Static/Rigid Dynamic/Flexible

Scalability Vertical Horizontal

Language Structured Query Language (SQL) Un-structured Query Language

Schema Rigid/static Schema bound to relationship Non-rigid Schema

Query Complexity Supports complex queries Doesn’t support complex queries


NoSQL vs SQL Databases
Popular NoSQL Databases
● MongoDB: MongoDB is a document database that stores data in flexible,
JSON-like documents. It provides high scalability, automatic sharding,
and a powerful query language.
● Cassandra: Apache Cassandra is a distributed columnar database
designed to handle large amounts of data across multiple commodity
servers. It offers high availability, fault tolerance, and linear scalability.
● Redis: Redis is an in-memory key-value store that can be used as a
database, cache, or message broker. It supports a wide range of data
structures and provides high performance and low latency.
NoSQL Database Query Language
● NoSQL databases typically have their own query languages or interfaces
for data retrieval and manipulation. Here are some examples of query
languages used in popular NoSQL databases:
○ MongoDB: MongoDB uses a query language called the MongoDB Query
Language (MQL). It provides a rich set of operators and functions for
querying and manipulating documents in the database.
○ Redis: Redis is primarily an in-memory data structure store and does not
have a traditional query language. It provides a set of commands that
operate on different data structures like strings, lists, sets, and hashes. Redis
commands are typically used to perform operations such as reading and
writing data, data manipulation, and data expiration.
Demo: MongoDB Basics
MongoDB NoSQL Injection
NoSQL Injection
● NoSQL Injection is a security vulnerability that occurs in applications that
utilize NoSQL databases.
● It is a type of attack that involves an attacker manipulating a NoSQL
database query by injecting malicious input, leading to unauthorized
access, data leakage, or unintended operations.
● In traditional SQL Injection attacks, attackers exploit vulnerabilities by
inserting malicious SQL code into input fields that are concatenated with
database queries.
● Similarly, in NoSQL Injection, attackers exploit weaknesses in the
application's handling of user-supplied input to manipulate NoSQL
database queries.
NoSQL Injection Example
● Let's assume we have a web application that uses MongoDB as its
NoSQL database backend.
● The application has a login functionality where users provide their
username and password.
● The application performs a query to check if the provided credentials are
valid:

var username = getRequestParameter("username"); // User-supplied


input
var password = getRequestParameter("password"); // User-supplied
input
NoSQL Injection Example
// MongoDB query
var query = {
username: username,
password: password
};

// Perform query to check if credentials are valid


var result = db.users.findOne(query);

if (result) {
// Login successful
} else {
// Login failed
}
NoSQL Injection Example
● In this example, the application constructs a MongoDB query using user-
supplied values for the username and password fields. If an attacker
intentionally provides a specially crafted value, they could potentially
exploit a NoSQL injection vulnerability.
● For instance, an attacker might enter the following value as the
username parameter:

username: { $gt: "" }


NoSQL Injection Example

● In a normal scenario, the query would search for a user with the exact
username provided.
● However, in this case, the attacker is using the $gt operator (greater
than) with an empty string as the value.
● This can manipulate the query's logic, causing it to retrieve a user record
that the attacker should not have access to.
● The attacker could potentially bypass the login mechanism and gain
unauthorized access.
NoSQL Injection Payloads
Payload Use case/Function

username[$ne]=1$password[$ne]=1 Not equals to (Auth Bypass)

username[$regex]=^adm$password[$ne]=1 Checks a regular expression (Auth Bypass)

username[$regex]=.{25}&pass[$ne]=1 Checks regex to find the length of a value

username[$eq]=admin&password[$ne]=1 Equals to.

username[$ne]=admin&pass[$gt]=s Greater than.

You can learn more about NoSQL Injection and find additional payloads here:
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%
20Injection
Demo: MongoDB NoSQL
Injection
SQL Injection Attacks
Course Conclusion
Learning + You will have a solid understanding of what a SQL injection
vulnerabilities are, what causes them and their potential impact.
Objectives: + You will have an understanding of how Relational Databases and
NoSQL databases work and how they differ from one another.
+ You will have an understanding of the three different
categories/Types of SQL Injection vulnerabilities and their
respective subtypes.
+ You will be able to understand and write basic SQL queries.
+ You will be able to identify and exploit In-Band SQL Injection
vulnerabilities (Error-Based SQLi & UNION-Based SQLi).
+ You will be able to identify and exploit Blind SQL Injection
vulnerabilities (Time-Based SQLi & Boolean-Based SQLi).
+ You will be able to automate the identification and exploitation of
SQLi vulnerabilities with tools like SQLMap.
+ You will be able to identify and exploit vulnerabilities in NoSQL
databases.
Thank You!

You might also like