You are on page 1of 17

Study Notes Jan 15th,2021

Muhammad Rohmanur Rizqi


A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Refernsi
1. HackerOne’s https://www.youtube.com/watch?v=bIB3Hi6KeZU
2. Studdard & Pinto’s Web Application Handbook 2nd Edition
3. Kontra Free Web Training
https://application.security/free-application-security-training/owas-top-10-sql-injecti
on
4. Portswigger’s Lab https://portswigger.net/web-security/sql-injection
5. SQLi Cheat Sheet https://portswigger.net/web-security/sql-injection/cheat-sheet
6. Portswigger’s Lab for SQLi Union Attacks
https://portswigger.net/web-security/sql-injection/union-attacks

Shotouts
1. Truly inspiring personas: Anggi Rifa Pradana, Satrya Mahardika, Andhika Sudarman
2. Partner of my KamApp Final Exam, Shafira Dinda Ramadhini
3. The “Merintis Bersama” team, Dendi Risman, Achmad Husein, Antonoius A, Emmanuele
S.
4. Stok Fredrick, TomNomNom, Farah Hawa, and all bug bounty communities that I can
never mention one by one (for obvious reasons)

Content (Click to go to the desired part!)


1. Theory 5. Lab #1 8. Fingerprinting
2. Impact 6. Exploiting Other 9. Exploiting UNION (Labs)
3. Examples Statements
4. Basic Vulnerability 7. Finding SQLi Vuln

Theory

SQL Injection should not be an alien term if you’ve been hangin out with computer stuff for a
while since it is one of the ‘main course’ which many hackers use to exploit a vulnerable
website. As we all know, SQL database is one of the most common data store (beside
XML-based repositories and LDAP directories), therefore, an attack that involves the use of it
should have something to do with database. Essentially, an SQL Injection attack is conducted
through injecting an SQL querry into a user-supplied input value. Simple as that!

Impacts

SQL Injection can enable an anonymous attacker to read and modify all data stoed within the
database, and even take full control of the server on which the database is running.

Examples

Well, SQL Injection itself has a lot of varieties involving various vulnerabilities, attack
methods, and techniques which depends on the situation that the attacker may faces.
However, some varieties are more common than others, namely:
1. Retrieve Hidden Data, you can modify an SQL Query to return presumably desired
additional results!
2. Subverting Application Logic, change a query to interfere with the business logic of the
application.
3. UNION Attacks, retrieve data from different database tables.

1
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

4. Database Examination, extract information about the version and structure of the
database.
5. Blind SQLi, well.... since it’s blind, an attacker will not be able to see any returned value
in the application’s response from the attack.

Well, to be able to easily digest about this attack, let’s observe the explanation and study
cases in the followings subparts.

Basic Vulnerability

Let’s imagine about the following scenario, Shafira is hired by a book retailer to create a web
application which enables users to search their products by author, title, publisher, etc.
Since it’s now digital, the catalog is no longer printed out as book but is stored within a
database which requires SQL queries to retrieve any detail about any book based on key
words supplied by users.
The web application has a user search input like the following image

From the backend side, that search button performs the following querry:

SELECT author,title,year FROM booksCatalog WHERE publisher = ‘[input by


user]’ and published=1

where, if the user use ‘Gramedia’ as keyword, the querry will be something like this:

SELECT author,title,year FROM booksCatalog WHERE publisher = ‘Gramedia’


and published=1

That querry will perform a database checking to every row within the booksCatalog table
and extract each records where the value of publisher column is Gramedia and the value
of published is 1. Seems pretty cool right? I guess so.
But let’s think about the other scenario.
A user wants to find a book which was published by a publisher called Arba’in Nawawi ,
therefore, the code will look like the following snippet

SELECT author,title,year FROM booksCatalog WHERE publisher = ‘Arba’in


Nawawi’ and published=1

Let’s toss a coin and guess what can be the result of it. Voila! It returns an error message as
the following

Incorrect syntax near ‘in Nawawi’.


Server : Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark before the character string ‘

YooHoo! What did I do wrong? Well, if you notice in the first scenario, the string Gramedia is
located within the quotation mark ‘...’ . However, the Arba’in Nawawi has another ‘ in
its name which will confuse the SQL Querry and makes them just takes the ‘Arba’, leaving
the ‘in Nawawi alone.... sad:( But that’s the reality.

This shitty situation can be escalated by even a kindergarten toddler who learned about SQL
Injection for a week by using the keyword

2
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Gramedia’ OR 1=1--

Where the the ‘ behind Gramedia is used to close the mark in the backend-side SQL, and the
querry OR 1=1 is used to return every records in the table. While the -- is used to comment
out the rest of the querry. Therefore, it will look like this:

SELECT author,title,year FROM booksCatalog WHERE publisher = ‘Gramedia’


OR 1=1--’ and published=1

Ding Dong! the web application will give the user every records (every book, written by every
author, published in any year) that is stored within the database. That’s Radical, isn’t it?!

Lab Practice #1

Lab : https://portswigger.net/web-security/sql-injection/lab-retrieve-hidden-data

The lab points us to a web that looks like a gift shop.

Let’s try to randomly click on every link and see what’s happening

And if we use burpsuite, something interesting happens in the Gift method where if we click
the category (All, Corporate Gift, Food&Drink, etc.), the GET request will look something
like this

3
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Hmmmm.... Let’s check the other link...

Hmmm.... Interesting!
So what if we forward the captured frame to the repeater and modify the GET request into
something like this...

Exactly! Whatever happens in the backend, I believe it should be something like

SELECT * FROM xxx WHERE category=’Gifts’ ,

therefore, if we modify the GET request into something like in the picture, the querry will
be:

SELECT * FROM xxx WHERE category=’Gifts’ OR 1=1--’

Let’s send that request and see what’s gonna happen

4
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Voila! We did it! We solve the lab.

Exploiting Other Statements

So, is that it? We only can inject through SELECT statement? HELL NO! Other statements can
be our target of injection as well.

Click on the desired part


1. SELECT 3. UPDATE
2. INSERT 4. DELETE

1. SELECT

as we all know, the SELECT statement is used to retrieve/show information from the
database. We already knew how to exploit this one from the previous part, so let’s not waste
our time.

2. INSERT

INSERT is used to create a new row of data within a table. Usually, this is employed in an
‘Add new...’ function of an application such as create new user, add user, add info, etc.

Username : shafiradr
Email : shafibot@mail.com
password : password12345

Let’s imagine that Shafira’s website has an ‘Add user’ function that performs the following
querry:
INSERT INTO userBaru (username, password, email, ID, privilege) VALUES
(‘shafiradr’,’password12345’,’shafibot@mail.com’, 0015, 1)--

5
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Where privilege value 1 is assumed as normal user while privilege value 0 is assumed as
root/admin user.
A vulnerable website can be exploited by attacker through modification of INSERT statement,
for example, the attacker may supply the following data

INSERT INTO users (username, password, email, ID, privilege) VALUES


(‘foo’,’bar’,’baz@mail.com’, 9909,0 )--

Which will give the attacker an account with administrator privilege. What can be worst than
having a bad guy as the principal of the room?

3. UPDATE

Obvious isn’t it? If the previous statement is used to add something, this UPDATE statement is
used to update something.... no rocket science here.
Let’s just jump to the scenario. Suppose that Shafira, somehow wants to do some evil-doing
stuff, so she knows that the web application she built has SQL vulnerabilities. Well, what
motivates her to do this because the book store owner was being an ass by refusing to give
her a complete collection of marvel comics as a reward. So she wants to escalate her
privilege as an admin to delete marvel comic from the catalog. “If I can’t have this, no one
can!” she said.
She log in to the account using the following input

Username : ‘ UPDATE users SET password=’’ WHERE user=’admin’--


Password : ‘ --

At this point, you should already know what’s gonna happen right?
Then, Shafira can just log in using admin as username and blank password and Voila! Marvel
Comic is gone from the catalog.

4. DELETE

Nothing can be more obvious than this, exploiting DELETE statements will cause loss of data.
What can be more evil than burning all assets of your victim? It works the same way with
other statements.

Discovering SQLi In The Wild!

Alright, let say, Shafira is not only good at developing build application but also good at bug
hunting. She’s exploring the cyberspace, visiting many websites, to obtain bugs within each
website she visited. But the question is, How on earth can she discover that a website has
SQLi Vuln? Let’s answer that question.

Ways to find SQLi Vuln (click on the desired part!)


1. Injecting String Data 3. Injecting Querry Structure
2. Injecting Numeric Data

Injecting String Data

Well, you’ve seen in many examples above right? If a website has a user-supplied data such
as username, name, email input, etc., the string is encapsulated within quotation marks
(‘...’). So in order to find out whether an input field for string is vulnerable or not, try to
break out of that quotation marks through the following step
a) Submit a single quotation mark and observer whether there’s a visible error or not.

6
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

b) If you see an error, submit two single quetation marks altogether and observe
whetere there’s an anomaly or not.
c) If an anomaly is visible, then the web app is probably vulnerable. To further verify
the vulnerability, try to input some benign input that’s concatenated with another
input (each version of SQL has different concatenator) such as the following
examples:
Oracle : ‘||’FOO
MS-SQL : ‘+’FOO
MySQL : ‘ ‘FOO (there’s a space in between)

Injecting Numeric Data

Usually numeric data is noticable in the url of a web app, if you see the url looks something
like:

https://shafiraworld.net/archive?page=2

or something like

https://shafishop.com/catalog?id=2

or anything similar to the examples above,whenever you intercept the request packet, you’ll
probably see that the web is requesting a numeriv data either id of a page, or number of a
page, etc. So if you find that in the wild, what should you do?
Suppose that you are visiting https://shafiraworld.net/archive?page=2 and you
know that the page id to a particular page is 2, try to modify it using some mathematical
expression that has the value of 2 like 1+1, 3-1, or 7-5 :

https://shafiraworld.net/archive?page=1+1

And if that still returns the same page, it’s a good sign that the site is SQLi Vulnerable. To
firther verify the vulnerability, try to modify the input using another method such as using
the SQLI value that if it’s being operated with other numeric value will return the value of 2.

https://shafiraworld.net/archive?page=67-ASCII(‘A’)
(the value of A in ASCII is 65, but this example may not work if the quotation marks is being
filtered/sanitized)

https://shafiraworld.net/archive?page=51-ASCII(1)

And if those still return the same page with the page id of 2, Voila! You just discover an SQLi
Vuln in the wild.

*)Notes:
You may need to encode mathematical operators and some characters using url encoding.
& = used to join name/value pairs, encoded with %26
= = used to join name/value pairs, encoded with %3d
+ = used for addition, encoded with %2b.
(space) = space is a space. Encoded with + or %20
Semicolon (;) = used to terminate a function, separate cookie fields, etc. Encoded with %3b.

Injecting into the Querry Structure

This case is different from the two cases mentioned above because the user-supplied data is
being inserted into the structure of the SQL querry itself rather than an iyem of daya within
the querry. Therefore an injection should involves a valid SQL syntax and no escaping is
required to break out of any data context.

7
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

The most common point for injection within SQL querry structure is ORDER BY clause whose
keyword takes a column name or number and order the result according to the values within
the column. Common example is like the following snippet:

SELECT author, title, year FROM books WHERE publisher=’Gramedia’ ORDER


BY title ASC

You can see that in the, the result of any record whose publisher is ‘Gramedia’ will be
ordered Ascendingly by the ORDER BY clause based on its title.
In this case, It will be difficult to conduct an SQLi if we don’t know the name of a valid
column or table. Therefore, some steps are required to successfully conduct SQLi into the
Querry Structure:
a) Take note of any parameter that appears to control the order or field types within
the result returned by application
b) Try to input ORDER BY 1, ORDER BY 2, and so on with increasing value of the
number. If you see some difference, it’s a good sign of SQLi vuln. However, if the
number supplied is greater than the actual number of columns within the result set,
it will fail.
c) When you supply number 1 and it causes a set of results with a column containing 1
in every row, the input is probably being inserted into the name of a column
returned by the querry. For instance:
SELECT 1,title,year FROM books WHERE publisher=’Gramedia’

Fingerprinting

“If you know your enemy and you know yourself, you’ll win any battle” said Sun Tzu within
his book, The Art of War. That’s why fingerprinting is very useful to understand the type of
back-end database that we’re dealing with. Why tho? Well because each type of database
has different way to treat some characters/expressions. Let me remind you about the
concatenation. Let’s take a look at how each type of database concate strings ‘Sha’ and
‘fira’ into ‘Shafira’
Oracle : ‘sha’||’fira’
MS-SQL : ‘sha’+’fira’
MySQL : ‘sha’ ‘fira’ (space in between)

By trying each why of concatenation, at least we know what type of database we’re dealing
with. If the user-supplied data is a numeric data, we can try the following input:
Oracle : BITAND(1,1)-BITAND(1,1)
MS-SQL : @@PACK_RECEIVED-@@PACK_RECEIVED
MySQL : CONNECTION_ID()-CONNECTION_ID()

Those input evaluates to 0 on the specified type of database and will return an error
messages if it’s being supplied to a wrong type of database.

There’s a trivia in MySQL database because it handles certain types of inline comment that
begins with an exclamation point followed by the version of the database:

/*!32302 and 1=0*/

The above statement will causes the WHERE clause of a SELECT statement to be FALSE if
MySQL version in use is greater than or equal to MySQL 3.23.02.

8
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Exploiting the UNION!

(click on the desired subpart of this part!)


1. Determine the number of column 5. Retrieve Interesting Data
2. Lab #2 Column 6. Lab #4 Retrieve Data
3. Finding column with a useful data type 7. Retrieve Multiple Values
4. Lab #3 Find Useful Data 8. Lab #5 Retrieve Multiple Values

Let’s do a quick review of what UNION statement can do.

That search button right there performs the following querry:

SELECT author,title,year FROM booksCatalog WHERE publisher = ‘[input by


user]’ and published=1

Let say, Joko, a malicious Taruna, enters the following keyword

Gramedia’ UNION SELECT username,password,uid FROM users--

Therefore, behind the curtain, the following querry is being performed

SELECT author,title,year FROM booksCatalog WHERE publisher = ‘Gramedia’


UNION SELECT username, password,uid FROM users--’ and published=1

Well, you should be able to guess what’s the output right?


Author Title Year
Bernawan Ikshan How to Conquer Any Living 2020
Girls
Melandy Andriawan A Secret Way to Efficient 2017
Diet
admin r00t 0
ShafiraDR developer 1

You notice what’s dangerous?

Well, a powerful weapon usually comes in handy. So there are couple things that need to be
understood about this UNION exploit:
a) to combine the results of two querries using UNION, those result sets MUST have the
same structure (contain the same number of columns which have the same or
compatible data types, appearing in the same order.
b) To inject the second querry that will return interesting results, the attacker needs
to know the name of the database table that he wants to target and the name of
columns relevant to it.
Therefore to successfully launch this attack, you usually need to figure out some stuff such
as:
● How many columns are being returned from the original querry?
● Which columns returned from the original querry are of a suitable data type to hold the
results from the injected querry?
We will work our way to obtain the answer of those questions, yooHoo!

9
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Determining the Number of Column

At the previous part, we learned about the ORDER BY clause, ight? that’s one of the two
methods that are gonna be explained on how to acquire the number of column.
1. Using the ORDER BY clause incremently, therefore, you’re gonna know how many
column are there, you can just simply try this:
‘ ORDER BY 1--
‘ ORDER BY 2--
‘ ORDER BY 3--
‘ ORDER BY 4--
etc.
Whenever it returns you the following error:

The ORDER BY position number 5 is out of range of the number of items in


the select list.

Voila! That tells you if your target has only 4 columns. Easy peasy?
2. Using the same concept in another way by inputting the following querry
‘ UNION SELECT NULL--
‘ UNION SELECT NULL, NULL--
‘ UNION SELECT NULL, NULL, NULL--
‘ UNION SELECT NULL, NULL, NULL, NULL--
etc.
Again, whenever it returns you an error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have
an equal number of expressions in their target lists.

BOOM! That also tells you that the number of column is how many null that works for you.

*)Notes : NULL is used because it is convertible to every commonly used data type. In the
ORACLE database, you need FROM keyword which can be set as DUAL (a built in table),
therefore it should look like : ‘ UNION SELECT NULL, NULL FROM DUAL--

Lab #2 - How many columns are there?

Lab :
https://portswigger.net/web-security/sql-injection/union-attacks/lab-determine-number-o
f-columns

10
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

The lab pointed us to some shop site. We,ll see what happens with the request in burpsuite.

I clicked on one of the categories and here’s what I got.

Alrighty, seems like that’s our attack surface. So what are we waiting for? I forwarded it to
the Repeater and I’ll craft the GET request

I tried that one but failed.

So I tried to just add the querry behind a benign category. Accessories’ ORDER BY 3--
which was encoded as Accessories%27+ORDER+BY+3%2d%2d

Voila! It works!
As easy as that, therefore I know that whatever table used to sort categories out has 3
columns. (Cause I tried 4 and 5 and they didn’t work!)

11
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Finding Column with Useful Data Types

So we already knew how many columns are there. The next step is to determine which
column contains useful data types? Cause we don;t wanna end up retrieving data that filled
with gibberish no-so-useful data right?
You can do that by modifying your ‘null’ value into a data type. In this case, we’re gonna use
‘a’ character to test whether that ‘null’ has a suitable data type or not.
The querry will look like this (suppose that we only has 3 columns in the target)

‘ UNION SELECT ‘a’,NULL,NULL--


‘ UNION SELECT NULL,’a’,NULL--
‘ UNION SELECT NULL,NULL,’a’--

If the data type of a ‘null’ place is not compatible with ‘a’ (as a string data), then it will
return the following error messge:

Conversion failed when converting the varchar value ‘a’ to data type int.

But if it doesm’t return anything. Wink wink! It’s compatible.

Lab # Which Column is Useful?

Lab:
https://portswigger.net/web-security/sql-injection/union-attacks/lab-find-column-containi
ng-text

Alrighty, back to our lovely shop site, and straight to burpsuite

Since it wants us to retrieve a string ‘Tuhkhd’, were gonna try it from the last column and see
what happens.

Pets’ UNION SELECT NULL,NULL,’Tuhkhd’-- encoded into


Pets%27+UNION+SELECT+NULL%2cNULL%2c%27Tuhkhd%27%2d%2d

12
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Doesn’t work! Let’s try the first column maybe?

Still no work! Alrighty last try! the middle one

Voila! It works!. So the value ‘Tuhkhd’ is compatible with the data type of the second column.
Got it!

Retrieve Interesting Data

Alrighty! Now we know more about which column is useful or not. But we don’t need some
string like ‘Tuhkhd’. I mean..... seriously WHAT THE F IS DATTTT?! So we want something
more delicious like username, password, credit card number, etc. How can we got it?
There’s a way! And one of the most common way is that you can dump data using a built-in
table like information.schemas table, but in order to keep this as short as possible, let’s say
that there is a table called users and has three columns. What you need to do in a situation
like that?
Easy Peasy!
Just input the following querry
‘ UNION SELECT username,password,NULL FROM users--
‘ UNION SELECT username,NULL,password FROM users--

13
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

‘ UNION SELECT NULL,username,password FROM users--


(try which one works for you)

As easy as that.

Lab #4 Interesting Data huh?

Lab:
https://portswigger.net/web-security/sql-injection/union-attacks/lab-retrieve-data-from-o
ther-tables
So the lab tells us that The database contains a different table called users, with columns
called username and password. Alrighty, let’s kick some ass!

Well.... we’re back to this lovely shopping site. But hey, you notice on the top right corner?
There is a Login button. Let’s just do it fast, where is our almighty burpsuite. We capture the
request packet and forward it to the repeater

Alright, let’s send it and see what we’re gonna get.

14
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Boom! I feel like a pro altho it’s just a lab environment. Look at that! It’s a username and
password for the admin. Let’s hit the login page and input ‘em as our credentials.

1 2 3 Surprise surprise!

Boom! We solve it. Job’s done, sir!

15
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

Retrieve Multiple Values in a Single Column!

Well, the previous example shows us that the web returns two columns, the username and
password. But what if it only returns a single column?
Ofcourse we can still do the magic using the concatenator.
Alright, suppose our target is an Oracle database whose concatenator is ||, the magic is
gonna look something like this:

‘ UNION SELECT username || ‘~’ || password FROM users--

therefore, between username and password is only separated by ‘~’ character.


Alright, let’s wrap this study session up and see how does it work?

Lab #5 Whoa Multiple Values!

Lab:
https://portswigger.net/web-security/sql-injection/union-attacks/lab-retrieve-multiple-val
ues-in-single-column

So the lab tells us that The database contains a different table called users, with columns
called username and password. Alrighty, let’s kick another ass!

Straight to burpsuite and repeater!

I modify the request into


Accessories’ UNION SELECT username || ‘~’ || password FROM users--
which is encoded into something like in the picture

fail tho, well, let see if use a null column before the username

16
Study Notes Jan 15th,2021
Muhammad Rohmanur Rizqi
A Journey to Bug Bounty
OWASP : SQL Injection Part 1

And see what we’re gonna get.

Boom it works! Let’s scroll down the response to see if we get the admin’s credentials.

We do got it and.... 1 2 3 surprise surprise!!!

Voila! We solve the lab!

17

You might also like