Monday, July 18, 2011

Sqlmap Introduction – SQL Injection Walkthrough


In prior posts, we've discussed performing reconnaissance work on targets. We've talked about using FOCA, Maltego and other tools (including some that simply query how the Internet works) and how to gather information from targets about them.


Starting today, we're going to discuss the practical application of some more technical tools. Tools that will provide for us information on targets that will help us determine what our attack vector is going to be for that target.

In this particular write up, we're going to explore the specifics of finding a web application and determining if it's vulnerable through SQL injection. Once we determine that it is, indeed, vulnerable, we're going to use an automated tool called “sqlmap” to help us gather data from the database. I think it's important to also discuss how to manually get to the same point, but that's for another blog post. We'll follow up and show you manual SQL injection in our next post.

So you can follow along at home, let's talk a little about what I've got set up in my lab and where to get the software I'm using.

Setting Up The Lab – Vulnerable Web Application
Now, in order to test a web application for vulnerabilities, you're going to need to deploy a vulnerable web application.

Come back to this blog when you've written up a nice PHP/mysql web application that is chock full of vulnerabilities for us to exploit. Go on, I'll wait.

What's that? You don't feel like writing your own web application just so you can test it later? Fine.

Lucky for us, there are plenty of folks who have done just that so that we don't have to. The Internet has dozens of bootable Linux distributions out in the world that provide for us, the security researcher, the hacker, call-us-what-you-will, an environment that contains vulnerable applications. All we need to do is grab one, boot it up and start testing away.

For my lab, I settled on “Damn Vulnerable Web Application”, which you can find more info on at their web site (http://www.dvwa.co.uk/) and you can download an ISO file of the bootable web app here: (http://www.dvwa.co.uk/DVWA-1.0.7.iso).

You can either burn that ISO file to CD and boot up a physical host or you can create a Virtual Machine in either VMWare Player or VirtualBox and have it boot up that way. In either virtual machine software, you can create a machine with a handful of RAM (say 512 or 1GB) and no hard disk. And then define it to use the ISO file you downloaded for boot. Then you've got a Virtual Machine that's booting a CD/DVD (LiveCD).

Once you've got that set up and running, make sure you know what IP address the machine is (so you know what target you're supposed to be hitting) and then it's to start scanning!


Scanning the Target with NMAP
Here's the thing when it comes to NMAP: there are a bunch of great tutorials already out there that will go over with you all the different flags and how they affect NMAP's behavior.

The best online resource regarding NMAP may, indeed, be the http://www.insecure.org web site—home to NMAP. This is where you go to download it. It's

However, the best TUTORIAL on the net, regarding NMAP is located here, .at networkuptime.com. It goes into real depth with you about how each type of scan manipulates the three way handshake that TCP negotiates and how that manipulation reports ports differently.

You do remember the three way handshake, no? No? Really?

OK, here's the short version:

When the Transmission Control Protocol (TCP) establishes a connection between two networked items (servers, workstations, printers, routers, etc), the client of the connection (the system, server or workstation initiating the connection) must first send a TCP packet with the SYN flag set. This, per the specification, tells the server (the receiving end of the connection) that a client's trying to attempt a connection.

The Server then sends a TCP packet back to the client with the SYN and ACK flags set. This means the server is ACKnowledging the client's SYN packet.

Lastly, the client sends an ACK packet back ACKnowledging the server's SYN/ACK packet.

Usually, this handshake looks like this:



In order to determine which ports are open, NMAP can use different iterations of this three way handshake.

For instance, our best bet, as hackers, is to be as quiet as possible. So, we're going to use NMAP's SYN scan (-sS flags) in order to break the three way handshake at the SYN.

Why would we do this? Because if we break the three way handshake in the middle, most systems won't log the packets. Therefore, our network traffic won't be in their logs and there will be less evidence of our penetration to erase later on.

NMAP also has another flag we're going to invoke to remain as quiet as possible on our target network: “-f”. This fragments our packets up so it's harder for firewalls and IDS's to identify us as a scan.

And one last thing we're going to do to be as quiet as possible is we're NOT going to scan every single port on the host. We're going to limit our port scan to ports 80 and port 443. This way, we don't look like abnormal traffic too much.

My DVWA Virtual Machine is set up with an IP Address of 192.168.50.160, so we're going to scan it with NMAP using the following flags:

nmap -f -sS -v -oA dvwa -A -p 80,443 192.168.50.160
(Edited for the sake of brevity, this post is long enough :) )
PORT    STATE SERVICE  VERSION
80/tcp  open  http     Apache httpd 2.2.14 ((Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1)
443/tcp open  ssl/http Apache httpd 2.2.14 ((Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1)
...
From this scan, we know that both ports are answering, they are both running Apache httpd 2.2.14, and that Apache's running PHP, version 5.3.1.

So, we know we're absolutely, positively dealing with a web server. And that web server is running PHP. And if it's running PHP, there's a damn good chance it's also running mysql. A quick google search tells us that port 3306 is the default mysql port. Let's take a look at port 3306 (knowing full well, that they are probably filtering that port, to be more secure).

nmap -f -sS -v -A -p3306 192.168.50.160
...
PORT STATE SERVICE VERSION
3306/tcp open mysql MySQL (unauthorized)

Yep, it's confirmed. They are running mysql.

Now, let's browse to this web application and take a look at what it's serving.

Checking Out the Web Application

So, I brought up a web browser and attempted to log in. The distro is called “Damn Vulnerable Web App” with good cause: the admin password is “password”. I logged in with admin/password and found a menu on the left that has various lessons that we'll take a look at later.

For now, we want to focus on the “SQL Injection” lesson. Clicking on the “SQL Injection” button brings up the following web page.

Just messing around, I decided to put a “1” into the User ID box. Why not? What other number would user id's start with? I got the following result:


Entering other numbers (2-5), we find that there are 5 users in the application. But let's focus on the first entry, Number “1”.

The URL of the web page, when a successful Number “1” is entered is the following: “http://192.168.50.160/vulnerabilities/sqli/?id=1&Submit=Submit#”

We'll use this URL when using sqlmap to start to determine if this web page is truly vulnerable or not.

In our next post, we'll go into how to manually abuse this URL and manipulate the SQL queries behind it. For now, we're going to fire up sqlmap in our BackTrack distribution and run it against the URL.

Getting the Latest SQLMAP

So, the version of sqlmap that is included in the BackTrack 5 distribution is version 0.9. Personally, I've not had a whole lot of success with version 0.9. I've come across known vulnerable web apps that version 0.9 simply doesn't show as vulnerable but the dev version that you can download from the sqlmap web site has always been very reliable for me. So, create yourself a seperate directory and download sqlmap from their svn repository. Always check their web site to ensure the 'svn' command you invoke is the correct one for the latest. Right now, their site says, run the following command to download the latest version:

$ svn checkout https://svn.sqlmap.org/sqlmap/trunk/sqlmap sqlmap-dev

At this point, you'll have a sqlmap-dev directory, which when you enter, will contain several files and directories, but will specifically contain sqlmap.py. This is the command we'll invoke to probe the application.

Setting the Web Application Security Level

The first step in using sqlmap to probe the web application is to make sure you use the same cookie that you would if you were using the web application through a web browser. Why? Because we want to make sure certain things about our session remain the same when using sqlmap. One thing we want to remain the same is the fact that Damn Vulnerable Web Application has three levels of security: high (kinda secure), medium (little less secure), and low (about as secure as using wet gauze to keep out a rabid dog).

So, here's our plan: we're going to log into DVWA, set our security setting to “low”, then log out. You'll find DVWA's security settings when you click the “DVWA Security” button. Select “low” and then log out of the application.



Grabbing the Cookie

We're going to capture the cookie using another web tool, WebScarab, a web proxy. Proxies sit between two network nodes and assist in capturing and processing packets.

You can find WebScarab here ( https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project ). Download it and run it (java -jar ./webscarab.jar). By default, WebScarab runs on port 8008. Configure your web browser to use a proxy at localhost:8008. This way, we'll be able to log into DVWA through WebScarab.

In your web browser, log into DVWA (admin / password) and navigate your way to some page (the SQL Injection page is fine). In WebScarab, you'll find the index page for DVWA in the “Summary” tab. It'll look something like this:



NOTE: you need to find the page that shows the “Set-Cookie” checkmark is checked.

Once you do that, navigate your way to the “Session ID Analysis” tab of WebScarab and choose the dropdown labeled “Previous Requests”. Find the login page (“login.php”) and select it.



About midway down the page, you'll see the “Request” part of the page. And under the “Request” part of the page, you'll see the “Cookie” section. Highlight and copy the actual “Cookie” data. We'll need that when we use sqlmap in a minute.

For my example, my cookie data was “PHPSESSID=lu4bqq7h7bali86bs6hadfscd6; security=low”. Look a little familiar? The security level of the app is part of the cookie.

Probing the Web Application with SQLMAP

OK – we've got all the puzzle pieces together (finally). We know the url we're going to probe. We know the cookie data we're going to use. We are ready to use sqlmap. We can piece together our sqlmap command from all the pieces we have gathered.

Make your way into the directory that you've downloaded sqlmap into and put together the following command:

./sqlmap.py -u “http://192.168.50.160/vulnerabilities/sqli/?id=1&Submit=Submit#” --cookie=”PHPSESSID=lu4bqq7h7bali86bs6hadfscd6; security=low” --dbs

NOTE: I added the –string flag and added “Surname” to it but this is strictly optional. We're using the “--dbs” flag to list out the databases the application server hosts. You're command should look similar to this:



Hit enter and you'll start to see output like the following:



Success! Sqlmap gave us the listing of the databases: cdcol, dvwa, information_schema, mysql, phpmyadmin, test

Now, let's select one of the databases we got back (dvwa looks like a legitimate database for our web app) and let's see what tables are in it.

We do that by using the “-D <database” flag and the “--tables” flag together. Your command should look something like this:


You'll get back something that looks like this:


Success!! The DVWA database has two tables: “guestbook” and “users”. Let's take a closer look at the “users” table and inspect what columns it has.

We're going to add the “-T <table>” and the “--columns” flags in order to enumerate those columns. It'll look something like this:


Hopefully, you'll see some results that look like this:


Now that we know that there are columns in the “users” table that we can look at, we're going to simply use the “--dump” flag to dump those columns.

Our command should look something like this:


And let's see what the results are:


Success!! We got a list of user id's and password hashes!

What can we do with this? Well, for one thing, we can run those hashes through onlinehashcrack.com and see if they are as complex as they should be.




Newsflash: They aren't.

With these credentials, we can probably manipulate the application further.

Conclusion

Congratulations! You've walked through your first probing of a SQL Injection-vulnerable web page using sqlmap.

Next time, we're going to go more in-depth into SQL queries in legitimate application usage and how SQL Injections work by manipulating those queries.

14 comments:

  1. c'mon, sqlmap sucks, can't detect shit.

    ReplyDelete
  2. Why are you trying to detect shit?

    ReplyDelete
  3. 2 null, :D lol. U not read RTFM 100%

    ReplyDelete
  4. Hello writer I found you post very interesting I have followed up the examples
    But I got stuck
    ./sqlmap.py -u “http://192.168.50.160/vulnerabilities/sqli/?id=1&Submit=Submit#” --cookie=”PHPSESSID=lu4bqq7h7bali86bs6hadfscd6; security=low” --dbs

    now I hve install sqlmap-dev on my BT 5 R1 32bit, I use Mac Os and run a parallel on my mac Os . I run mamp as my virtual server, I hve install websecarab and use it to intercept the connection which I got the PHPSESSID . then I fire up cd /pentest/web/scanners/sqlmap/sqlmap-dev
    and run ./sqlmap put in the following ./sqlmap.py -u “http://192.168.50.160/vulnerabilities/sqli/?id=1&Submit=Submit#” --cookie=”PHPSESSID=lu4bqq7h7bali86bs6hadfscd6; security=low” –dbs it keep telling failed to connect.
    I have taken a risk uploading the script online in one of my domain to test it online it keep showing me same thing please what can I do ?

    ReplyDelete
    Replies
    1. dude why are u trying to use the same cookie that the blog used :|
      ur cookie will be set when u visit the web app through ur browser . that's what he used web scarab for....he retrieved the cookie that the web site assigned him. If u use mozilla firefox as browser, it has add-ons that allow u to read all the packets sent and recieved by the browser , that includes the cookies set in them

      Delete
  5. you can see cookie by javascript injection by typing the code in browser's url bar -
    javascript:alert(document.cookie);

    ReplyDelete
  6. It didn't work when the security was set to high. Any reason ?

    ReplyDelete
  7. OMG, bactrack 5 is cool! is that linux???

    ReplyDelete
  8. having the same problem as jboy unfortunately

    ReplyDelete
  9. solved it by using --random-agent after cookie

    ReplyDelete
  10. Backtrack 5 isn't call "Revolution" for nothing! Yes it is Linux, a modified Ubuntu 10.04, Linux kernel 2.6 if memory serves.

    ReplyDelete
  11. I have a big question, i wish you will understand :
    I am wondering if is it possible through sqlmap to download some hidden content of the vulnerable site, because i have some great pdf and jpeg to check :
    I am into this : -u "thesite" -D "thedatabase" -T "thetables" -C "thecolumn" --dump
    and i have a lot of thing, so how to directly download it or get acces to ?

    Thanks a lot

    ReplyDelete
  12. No Sqlmap is there to copy the sql database pdf and jpg are nothing to do with SQL <WorldVideosBuzz
    Yes backtrack is linux
    jboy < try http://127.0.0.1 at the beggining if its hosted on your localhost
    @null sqlmap is the dog bollocks

    ReplyDelete